code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def _hunters_watching(self, piece): <NEW_LINE> <INDENT> hunters = () <NEW_LINE> for ememyClass in (self ._get_peiceTypes_in_board(get_opposing_team_char(piece))): <NEW_LINE> <INDENT> for move in ememyClass.baseMoves: <NEW_LINE> <INDENT> r = piece.row+move[0] <NEW_LINE> c = piece.column+move[1] <NEW_LINE> dbprint(r, c) ... | Checks the enemy pieces looking at the given piece. | 625941e6cc0a2c11143dd2d5 |
def prompt_new_network(): <NEW_LINE> <INDENT> questions = [ { 'type': 'input', 'name': 'name', 'message': 'Network name' }, { 'type': 'input', 'name': 'ip', 'message': 'Network IP' } ] <NEW_LINE> answers = inquirer.prompt(questions, style=aergo_style) <NEW_LINE> return answers | Prompt user to input a new network's information:
- Name
- IP/url | 625941e630bbd722463cc20b |
def run_command(args=None): <NEW_LINE> <INDENT> cli_cmd = CLICommand() <NEW_LINE> cli_cmd.parse(args) <NEW_LINE> cli_cmd.run() <NEW_LINE> cli_cmd.pretty_print() | Runs a command with the provided arguments
:param args: arguments to execute the operation (including operation to be performed) | 625941e64f6381625f114e7f |
def close(self): <NEW_LINE> <INDENT> if isinstance(self.vectorContainer, dict): <NEW_LINE> <INDENT> for key in self.vectorContainer: <NEW_LINE> <INDENT> vector = self.vectorContainer[key] <NEW_LINE> vector.cleanup() <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(self.vectorContainer, Vector): <NEW_LINE> <INDENT> self.vec... | Closes all datasets and removes temporary files. | 625941e6ff9c53063f47c634 |
def dropout_forward(x, dropout_param): <NEW_LINE> <INDENT> p, mode = dropout_param['p'], dropout_param['mode'] <NEW_LINE> if 'seed' in dropout_param: <NEW_LINE> <INDENT> np.random.seed(dropout_param['seed']) <NEW_LINE> <DEDENT> mask = None <NEW_LINE> out = None <NEW_LINE> if mode == 'train': <NEW_LINE> <INDENT> mask = ... | Performs the forward pass for (inverted) dropout.
Inputs:
- x: Input data, of any shape
- dropout_param: A dictionary with the following keys:
- p: Dropout parameter. We keep each neuron output with probability p.
- mode: 'test' or 'train'. If the mode is train, then perform dropout;
if the mode is test, then ... | 625941e6a05bb46b383ecc60 |
@scopes.add_arg_scope <NEW_LINE> def conv2d(inputs, num_filters_out, kernel_size, stride=1, padding='SAME', activation=tf.nn.relu, stddev=0.01, bias=0.0, weight_decay=0, batch_norm_params=None, is_training=True, trainable=True, restore=True, weights_initializer = tf.truncated_normal_initializer, scope=None, reuse=None,... | Adds a 2D convolution followed by an optional batch_norm layer.
conv2d creates a variable called 'weights', representing the convolutional
kernel, that is convolved with the input. If `batch_norm_params` is None, a
second variable called 'biases' is added to the result of the convolution
operation.
Args:
inputs: a ... | 625941e6090684286d50f12e |
def loadGenomicSegmentMeta(pathname): <NEW_LINE> <INDENT> genomicMetadata = None <NEW_LINE> try: <NEW_LINE> <INDENT> genomicMetadata = GenomicSegmentMetadata(pathname) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print >> sys.stderr, sys.exc_info()[1] <NEW_LINE> okay = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <IND... | Load the genomic segment metadata. Return a vaildation flag | 625941e638b623060ff0b230 |
def test_attribute_fast_deltas(self): <NEW_LINE> <INDENT> self.assertFormatAttribute('fast_deltas', (True, False)) | Test the format.fast_deltas attribute. | 625941e6293b9510aa2c36d4 |
def sys_mount_device(device, mount_point, filesystem='xfs'): <NEW_LINE> <INDENT> if util_mount_is_mounted(device): <NEW_LINE> <INDENT> abort('Device ({0}) is already mounted'.format(device)) <NEW_LINE> <DEDENT> util_mount_validate_vars(device, mount_point, filesystem) <NEW_LINE> sudo('mount -t {0} {1} {2}'.format(files... | Mount a device - Ex: (cmd:<device>,<mountpoint>,[filesystem]) | 625941e61d351010ab855f5e |
def _combine_constraints(cubename, constraint): <NEW_LINE> <INDENT> if cubename is None: <NEW_LINE> <INDENT> combined_constraint = constraint <NEW_LINE> <DEDENT> elif constraint is None: <NEW_LINE> <INDENT> combined_constraint = cubename <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> combined_constraint = iris.Constr... | combines the cubename constraint and any other specified constraint | 625941e69b70327d1c4e121a |
def before_worker_start(func): <NEW_LINE> <INDENT> _func_only(func) <NEW_LINE> worker_methods_db.register_before_start(func) <NEW_LINE> return func | Register function to be executed just before worker start | 625941e6e64d504609d74c83 |
def run(self): <NEW_LINE> <INDENT> raise NotImplementedError(self.run) | Base method that connects or binds a socket to self._endpoint.
Sub classes must override this method. | 625941e65510c4643540f81c |
def merge_Sort(self, the_list): <NEW_LINE> <INDENT> if len(the_list) > 1: <NEW_LINE> <INDENT> first_half = the_list[ : len(the_list) // 2] <NEW_LINE> second_half = the_list[len(the_list) // 2 :] <NEW_LINE> self.merge_Sort(first_half) <NEW_LINE> self.merge_Sort(second_half) <NEW_LINE> self.merge_Them(first_half, second... | Break up the lists on each iteration and pass them to the merge function | 625941e66aa9bd52df0371ea |
def handle(self, cmd): <NEW_LINE> <INDENT> cmd = self.sanitize(cmd) <NEW_LINE> print("handling:", repr(cmd)) <NEW_LINE> if re.match(self.ELM_AT, cmd): <NEW_LINE> <INDENT> if re.match(self.ELM_ECHO, cmd): <NEW_LINE> <INDENT> self.echo = (cmd[3] == '1') <NEW_LINE> print("set ECHO %s" % self.echo) <NEW_LINE> return self.E... | handles all commands | 625941e6d99f1b3c44c679ca |
@app.route('/access-token', methods=['DELETE']) <NEW_LINE> def revoke_token(): <NEW_LINE> <INDENT> auth.require_authorization() <NEW_LINE> auth.current_device.delete() <NEW_LINE> database.commit() <NEW_LINE> return Response(status=204) | Revoke the current access token. | 625941e6dc8b845886cb5979 |
def SetFunctor(self, *args): <NEW_LINE> <INDENT> return _itkNaryMaximumImageFilterPython.itkNaryMaximumImageFilterIUS2IUS2_Superclass_SetFunctor(self, *args) | SetFunctor(self, itk::Functor::Maximum1<(unsigned short,unsigned short)> functor) | 625941e6dc8b845886cb597a |
def _setResultTrackFormat(self): <NEW_LINE> <INDENT> self._resultTrackFormat = self._tracks[0].trackFormat | Create the correct TrackFormat for the output track.
:return: | 625941e63317a56b8693a091 |
@module <NEW_LINE> @RGFunctionFactory('Y') <NEW_LINE> def mY(stack): <NEW_LINE> <INDENT> stack.append(1/math.e) | e**(-1) | 625941e6f548e778e58cd9c2 |
def test_decision_function(self): <NEW_LINE> <INDENT> dataset = MNIST(which_set='train') <NEW_LINE> X = dataset.X[0:20, :] <NEW_LINE> y = dataset.y[0:20] <NEW_LINE> for i in xrange(10): <NEW_LINE> <INDENT> assert (y == i).sum() > 0 <NEW_LINE> <DEDENT> model = DenseMulticlassSVM(kernel='poly', C=1.0).fit(X, y) <NEW_LINE... | Test DenseMulticlassSVM.decision_function. | 625941e69c8ee82313fbbbb9 |
def start(service): <NEW_LINE> <INDENT> sudo('service %(service)s start' % locals()) | Start a service.
::
import fabtools
# Start service if it is not running
if not fabtools.service.is_running('foo'):
fabtools.service.start('foo') | 625941e6507cdc57c6307128 |
def __init__(self, sprite_image, width, height, score): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.image = pygame.image.load(sprite_image).convert() <NEW_LINE> self.image = pygame.transform.scale(self.image, (width, height)) <NEW_LINE> self.image.set_colorkey(WHITE) <NEW_LINE> self.rect = self.image.get_rec... | Constructor. Pass in the color of the block,
and its x and y position. | 625941e6cc40096d61595d92 |
def plot_noisy_overlay(plist, fdir): <NEW_LINE> <INDENT> params = {'axes.labelsize': 14, 'text.fontsize': 14, 'legend.fontsize': 10, 'font.family': 'serif', 'text.usetex': True } <NEW_LINE> pylab.rcParams.update(params) <NEW_LINE> fig = pylab.figure() <NEW_LINE> ax = fig.gca() <NEW_LINE> ax.set_title('Overlay of DFA pl... | Create plot with objects from plist.
plist : list of tuples, (dfa array, noise level) | 625941e6462c4b4f79d1db12 |
def parse_params(self, trail, chain, *params): <NEW_LINE> <INDENT> so, s = (len(chain)-1, len(trail)-1) if chain else (0, 0,) <NEW_LINE> params = list(params) <NEW_LINE> for i, param in enumerate(params): <NEW_LINE> <INDENT> if isinstance(param, int) and param >= 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> para... | Process params with {so} and {s} patterns, if defined.
Allowed values:
(0, 10, 10, 10,) - direct integer values,
({s}, {s}+10, {so}+1, {so}+10,) - expressions (see below)
Values should contains only digits, [+-] signs and {s}, {so}
patterns (no space allowed), which are selected (deepest chain n... | 625941e626068e7796caf128 |
def check_feature_geometry(feat, geom, max_error=0.0001): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> f_geom = feat.GetGeometryRef() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> f_geom = feat <NEW_LINE> <DEDENT> if geom is not None and isinstance(geom, type('a')): <NEW_LINE> <INDENT> geom = ogr.CreateGeometryFromWk... | Returns 0 in case of success | 625941e6099cdd3c635f109c |
def GetPointer(self): <NEW_LINE> <INDENT> return _itkMultiplyByConstantImageFilterPython.itkMultiplyByConstantImageFilterIUL3DIUL3_Superclass_GetPointer(self) | GetPointer(self) -> itkMultiplyByConstantImageFilterIUL3DIUL3_Superclass | 625941e64428ac0f6e5bac39 |
def numCols(self): <NEW_LINE> <INDENT> return self._java_matrix_wrapper.call("numCols") | Get or compute the number of cols.
>>> rows = sc.parallelize([[1, 2, 3], [4, 5, 6],
... [7, 8, 9], [10, 11, 12]])
>>> mat = RowMatrix(rows)
>>> print(mat.numCols())
3
>>> mat = RowMatrix(rows, 7, 6)
>>> print(mat.numCols())
6 | 625941e67cff6e4e81117dc9 |
def letterCombinations(self, digits): <NEW_LINE> <INDENT> if not digits: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> result = [] <NEW_LINE> self.recurse(digits, result, "", 0) <NEW_LINE> return result | :type digits: str
:rtype: List[str] | 625941e6b57a9660fec33ccd |
def reset_rib_in(self): <NEW_LINE> <INDENT> self._init_rib_table() | clear _adj_rib_in table when bgp peer establish
:return: | 625941e6293b9510aa2c36d5 |
def get_template_path(): <NEW_LINE> <INDENT> return os.path.abspath(os.path.join(os.path.dirname(__file__), 'jupytemplate', 'template.ipynb')) | Get absolute path of template notebook.
:return: the path if the template notebook | 625941e610dbd63aa1bd2fe5 |
def renameColumn(self): <NEW_LINE> <INDENT> col = self.table.currentcol <NEW_LINE> df = self.model.df <NEW_LINE> name = df.columns[col] <NEW_LINE> new = simpledialog.askstring("New column name?", "Enter new name:", initialvalue=name) <NEW_LINE> if new !=None: <NEW_LINE> <INDENT> if new == '': <NEW_LINE> <INDENT> messag... | Rename column | 625941e6f9cc0f698b140a3b |
def __init__(self, augment=None, **kwargs): <NEW_LINE> <INDENT> self.augment = augment if augment is not None else Constant.DATA_AUGMENTATION <NEW_LINE> self.resize_shape = [] <NEW_LINE> super().__init__(**kwargs) | Initialize the instance.
The classifier will be loaded from the files in 'path' if parameter 'resume' is True.
Otherwise it would create a new one.
Args:
verbose: A boolean of whether the search process will be printed to stdout.
path: A string. The path to a directory, where the intermediate results are saved.... | 625941e6ec188e330fd5abda |
def checkLengthsAndTypes(self): <NEW_LINE> <INDENT> gm = ["Alignment.checkLengthsAndTypes()"] <NEW_LINE> if self.fName: <NEW_LINE> <INDENT> gm.append("fName = %s" % self.fName) <NEW_LINE> <DEDENT> if len(self.sequences) > 1: <NEW_LINE> <INDENT> len0 = len(self.sequences[0].sequence) <NEW_LINE> type0 = self.sequences[0]... | Last checks after reading an Alignment.
Make sure the sequence lengths and dataType are all the same.
Set self.length, self.dataType, self.symbols, self.dim, and self.equates | 625941e6711fe17d825427a5 |
def _get_expr_string(self): <NEW_LINE> <INDENT> return "Function(...)" | Get the string representing this expression, name excluded. | 625941e6be8e80087fb21080 |
def _insured_loss_curve_on_kvs(self, column, row, insured_loss_curve, asset): <NEW_LINE> <INDENT> key_ic = kvs.tokens.insured_loss_curve_key( self.job_ctxt.job_id, row, column, asset.asset_ref) <NEW_LINE> kvs.get_client().set(key_ic, insured_loss_curve.to_json()) | Put the insured loss curve on kvs. | 625941e676e4537e8c351ab9 |
def create_admin_employee(self, data={}): <NEW_LINE> <INDENT> if not data: <NEW_LINE> <INDENT> data = self._real_admin <NEW_LINE> <DEDENT> response = self.client.post( '/auth/admin/employees', data=json.dumps(self._real_admin), content_type='application/json' ) <NEW_LINE> return response | this is a helper method to keep
creating the user for the test
methods that need to post then
run a test. | 625941e6460517430c3945bd |
def events(self, start_date=None, end_date=None): <NEW_LINE> <INDENT> if start_date is not None and end_date is not None: <NEW_LINE> <INDENT> for date, value in daily_sticky_events(self._events): <NEW_LINE> <INDENT> if start_date is not None and date < start_date: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if end... | Return a generator to iterate over all daily events.
The generator iterates over the events in the order they were added. If
dates are missing in between two successive events, this function fills
in the missing dates with the value on the latest known date. | 625941e696565a6dacc8fb0d |
def get_ai_move(self): <NEW_LINE> <INDENT> return randrange(9) | Get the AI's next move | 625941e607d97122c4178cd8 |
def writeResultsToFile(OutputString, folderpath): <NEW_LINE> <INDENT> today=datetime.datetime.today() <NEW_LINE> outfilename=str(today.year) + '-' + str(today.month) + '-' + str(today.day) + '-' + str(today.hour) + ':' + str(today.minute) + '.org' <NEW_LINE> with open(folderpath + '/' + ... | generate automated string describing summary of results to org file
:param OutputString: String containing content formatted for org-markdown
:param folderpath: Path to output org file | 625941e6cad5886f8bd2741c |
def test_layout_and_styling(self): <NEW_LINE> <INDENT> self.browser.get(self.server_url) <NEW_LINE> self.browser.set_window_size(1024, 768) <NEW_LINE> inputbox = self.get_item_input_box() <NEW_LINE> self.assertAlmostEqual( inputbox.location['x'] + inputbox.size['width']/2, 512, delta=3 ) <NEW_LINE> inputbox.send_keys('... | docstring for test_layout_and_styling | 625941e67c178a314d6ef8aa |
def getRow_math(rowIndex): <NEW_LINE> <INDENT> rowItems = [1] <NEW_LINE> if rowIndex == 0: <NEW_LINE> <INDENT> return rowItems <NEW_LINE> <DEDENT> for i in range(1, rowIndex): <NEW_LINE> <INDENT> item = rowItems[i-1] * (rowIndex - i + 1) / i <NEW_LINE> rowItems.append(int(item)) <NEW_LINE> <DEDENT> rowItems.append(1) <... | 利用线性递推
时间复杂度:O(n)
空间复杂度:O(n)
:param rowIndex:
:return: | 625941e692d797404e3045cf |
def missingNumber(self, nums): <NEW_LINE> <INDENT> num_set = set(nums) <NEW_LINE> n = len(nums) + 1 <NEW_LINE> for number in range(n): <NEW_LINE> <INDENT> if number not in num_set: <NEW_LINE> <INDENT> return number | solution: https://leetcode.com/problems/missing-number/solution/
:type nums: List[int]
:rtype: int | 625941e663d6d428bbe44934 |
def loadFile(self, path): <NEW_LINE> <INDENT> sourcePath = path <NEW_LINE> if not sourcePath.endswith(CadenceData.EXTENSION): <NEW_LINE> <INDENT> sourcePath += CadenceData.EXTENSION <NEW_LINE> <DEDENT> if not os.path.exists(sourcePath): <NEW_LINE> <INDENT> sourcePath = os.path.join(CadenceData.ROOT_DATA_PATH, path) <NE... | Same as the load method, except the data is loaded from the file specified by path,
relative to Cadence's root data folder.
@@@param path:string
Relative path to the Cadence data file to open.
@@@return bool
True if the load was successful, False otherwise. | 625941e6baa26c4b54cb155f |
def set_label_attributes(self, scale, rescale=True, horiz_align="center", vert_align="middle", i=0): <NEW_LINE> <INDENT> self._extend_labels_array(i) <NEW_LINE> self._scale[i] = scale <NEW_LINE> self._rescale[i] = rescale <NEW_LINE> self._horiz_align[i] = horiz_align <NEW_LINE> self._vert_align[i] = vert_align | Set the various label attributes | 625941e615fb5d323cde0f59 |
def import_list(self,lst): <NEW_LINE> <INDENT> for x in lst: <NEW_LINE> <INDENT> self.add(x) | Add all the elements of the list 'lst' to DATA
Make sure this does not modify the input list 'lst' | 625941e6566aa707497f49a6 |
def adding_score(self, player_score): <NEW_LINE> <INDENT> self.point += player_score | adds the player scores . | 625941e63c8af77a43ae3be9 |
def on_save(self): <NEW_LINE> <INDENT> G = Network() <NEW_LINE> print(self.routers) <NEW_LINE> print(self.switches) <NEW_LINE> print(self.hosts) <NEW_LINE> print(self.hosts) <NEW_LINE> network_core.dictionary_to_nodes(self.routers, G) <NEW_LINE> network_core.dictionary_to_nodes(self.switches, G) <NEW_LINE> network_core... | Method called when the user presses the save button in the editor configuration. It applies the changes in the temporary network and updates the network graph of the canvas.
Parameters:
- self: current instance of the class; | 625941e6e1aae11d1e74a0ff |
@cliutils.arg( '--wrap', dest='wrap', metavar='<integer>', default=64, help=_('Wrap PKI tokens to a specified length, or 0 to disable.')) <NEW_LINE> def do_credentials(cs, _args): <NEW_LINE> <INDENT> if isinstance(cs.client, client.SessionClient): <NEW_LINE> <INDENT> auth = cs.client.auth <NEW_LINE> sc = auth.get_acces... | Show user credentials returned from auth. | 625941e650812a4eaa59c761 |
def transform_raw_sst(data_path, raw_fn, new_fn): <NEW_LINE> <INDENT> fout_x_name = os.path.join(data_path, new_fn + '.sentences.txt') <NEW_LINE> fout_x = open(fout_x_name, 'w', encoding='utf-8') <NEW_LINE> fout_y_name = os.path.join(data_path, new_fn + '.labels.txt') <NEW_LINE> fout_y = open(fout_y_name, 'w', encoding... | Transforms the raw data format to a new format.
| 625941e626238365f5f0f2b8 |
def clean_traffic_log(): <NEW_LINE> <INDENT> dt = pendulum.now().subtract(days=7).date() <NEW_LINE> query = TrafficLog.objects.filter(log_date__lt=dt) <NEW_LINE> count, res = query.delete() <NEW_LINE> print("Time: {} traffic record removed!:{}".format(timezone.now(), count)) | 清空七天前的所有流量记录 | 625941e68a349b6b435e85b6 |
def test___init__(self, fix_optimization_object): <NEW_LINE> <INDENT> algorithm_obj_1 = AlgorithmObject( optimization_object=fix_optimization_object ) <NEW_LINE> assert algorithm_obj_1.optimization_object == fix_optimization_object <NEW_LINE> assert not algorithm_obj_1.verbose <NEW_LINE> with pytest.raises(AttributeErr... | Test __init__() constructor function. | 625941e6d7e4931a7ee9e363 |
def _get_stacked(self, files, labeled, input_shape=None, output_shape=None): <NEW_LINE> <INDENT> assert(len(files) > 1) <NEW_LINE> imgs = np.array([self.loader._get_image(f, input_shape, source='auto') for f in files[:self.stack_size]]) <NEW_LINE> if imgs.shape[-1] == 1: <NEW_LINE> <INDENT> imgs = np.moveaxis(np.array(... | Get the image data for a number of files, with the label for the last one. The files need to
come from the same sequence, else the data will be meaningless.
Args:
files: Any number of files that the loader can make sense of
labeled: Set to True to return a label for the sequence, else a image will be returned... | 625941e607f4c71912b118c8 |
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <... | Returns the model properties as a dict | 625941e696565a6dacc8fb0e |
def __str__(self): <NEW_LINE> <INDENT> stri = "" <NEW_LINE> if self.perimeter == 0: <NEW_LINE> <INDENT> return stri <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for i in range(self.__height): <NEW_LINE> <INDENT> for j in range(self.__width): <NEW_LINE> <INDENT> stri = stri + str(self.print_symbol) <NEW_LINE> <DEDENT> ... | repr method.
Args:
None
Retuns:
Rectangle printed with the print_symbol. | 625941e6fb3f5b602dac3adb |
def process_directive(): <NEW_LINE> <INDENT> global ignoreline, num_ignored_hits <NEW_LINE> if never_ignore: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> hitfound = 0 <NEW_LINE> for i in range(len(hitlist) - 1, -1, -1): <NEW_LINE> <INDENT> if hitlist[i].filename == filename and hitlist[i].line == linenumber: <NEW_LIN... | Given a directive, process it. | 625941e62c8b7c6e89b35c01 |
def read_from_obj(filename): <NEW_LINE> <INDENT> vertices = [] <NEW_LINE> triangles = [] <NEW_LINE> with open(filename, 'rb') as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> line = line.decode('UTF-8').strip() <NEW_LINE> try: <NEW_LINE> <INDENT> vals = line.split() <NEW_LINE> if vals[0] == 'v': <NEW_LINE> ... | Read the mesh from an obj file.
Args:
filename: Path to the OBJ file.
Returns:
vertices: Vertices of the object as an array..
triangles: Triangles of the object as an array.. | 625941e630dc7b7665901da6 |
def get_pca_projection(ss, spikes_per_channel, n_features, neighbors): <NEW_LINE> <INDENT> window_size, _, n_channels = ss.shape <NEW_LINE> rot = np.zeros((window_size, n_features, n_channels)) <NEW_LINE> ss_all = np.sum(ss, 2) <NEW_LINE> w, v = np.linalg.eig(ss_all) <NEW_LINE> rot_all = v[:, np.argsort(w)[window_size:... | Get PCA projection matrix per channel
Parameters
----------
ss: matrix
SS matrix as returned from get_pca_suff_stat
spikes_per_channel: array
Number of spikes per channel
n_features: int
Number of features
neighbors: matrix
Neighbors matrix | 625941e6851cf427c661a94f |
def value(): <NEW_LINE> <INDENT> return (3 + random() * 2) * choice([1, -1]) | Randomly generate value between (-5,-3) or (3,5). | 625941e68e05c05ec3eea7bc |
def register(self, obj: object = None, *, name: str = None, freeze: bool = False) -> Optional[object]: <NEW_LINE> <INDENT> if obj is None: <NEW_LINE> <INDENT> def deco(func_or_class: object) -> object: <NEW_LINE> <INDENT> nonlocal name, freeze <NEW_LINE> if name is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> nam... | Register the given object under the the name `obj.__name__`.
Can be used as either a decorator or not. See docstring of this class for usage. | 625941e657b8e32f524838e2 |
def __init__(self, path, exts, subsample=None, tokenize=None, lower=False, cached_path=None, skip_cache=False, **kwargs): <NEW_LINE> <INDENT> cache_name = os.path.join(cached_path, os.path.basename(path), str(subsample)) <NEW_LINE> if os.path.exists(cache_name) and not skip_cache: <NEW_LINE> <INDENT> logger.info(f'Load... | Create a TranslationDataset given paths and fields.
Arguments:
path: Common prefix of paths to the data files for both languages.
exts: A tuple containing the extension to path for each language.
fields$: fields for handling all columns
Remaining keyword arguments: Passed to the constructor of Dataset. | 625941e6d6c5a10208144492 |
def swd_scan(self, start, end, volts): <NEW_LINE> <INDENT> return self.driver.device_swd_scan(start, end, volts) | Returns SWD IDCODE scan result in dictionary format.
Args:
start (int): First pin (channel number) to start the scan
stop (int): Last pin (channel number) to stop the scan
volts (str): Target voltage out
Return:
list: The list of dict containing SWD ID and pin info
Raises:
Nothing | 625941e630c21e258bdfa8e6 |
def input_processor(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description="Produces a plot of a computed potential energy surface.") <NEW_LINE> parser.add_argument('-i', '--input', type=str, default='input.dat', help="Name of the input file to be read in") <NEW_LINE> args = parser.parse_args() <NEW_LINE> ... | Checks command line input from user. Prints error messages if needed. Causes program to exit. | 625941e6d8ef3951e3243982 |
def test_icon_png(self): <NEW_LINE> <INDENT> path = ':/plugins/QgisCgiServer/icon.png' <NEW_LINE> icon = QIcon(path) <NEW_LINE> self.assertFalse(icon.isNull()) | Test we can click OK. | 625941e68c3a873295158804 |
def decorate(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def wrap(*args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return func(*args, **kwargs) <NEW_LINE> <DEDENT> except TestBaseException: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> except exceptions as details: <NEW_LINE> <INDENT> raise TestFai... | Decorator | 625941e64a966d76dd551457 |
def test_circular_scatter_num_point(): <NEW_LINE> <INDENT> area = [0, 1000, 0, 1000] <NEW_LINE> size = 1000 <NEW_LINE> x, y = gridder.circular_scatter(area, size, random=False) <NEW_LINE> assert x.size == size and y.size == size <NEW_LINE> x, y = gridder.circular_scatter(area, size, random=True) <NEW_LINE> assert x.siz... | gridder.circular_scatter returns a specified ``n`` number of points. | 625941e663b5f9789fde752a |
def set_Email(self, value): <NEW_LINE> <INDENT> super(ShowUserIdentityInputSet, self)._set_input('Email', value) | Set the value of the Email input for this Choreo. ((required, string) The email address you use to login to your Zendesk account.) | 625941e630bbd722463cc20c |
def __init__(self, bay_group=None, baynum=None, blocks=None, chassis=None, devname=None, firmware=None, handle=None, interface_type=None, lnum=None, locnstr=None, logical_block_length=None, media_type=None, model=None, pending_actions=None, physical_block_length=None, present=None, purpose=None, purpose_description=Non... | NodeDrivesNodeDrive - a model defined in Swagger | 625941e60fa83653e46573fc |
def _filter(self, resolution, cutoff, outputRows, inputIndex, outputIndex): <NEW_LINE> <INDENT> sampleRate = 1 <NEW_LINE> power = resolution <NEW_LINE> while power > 0: <NEW_LINE> <INDENT> sampleRate *= 10 <NEW_LINE> power = power - 1 <NEW_LINE> <DEDENT> nyquist = 0.5 * sampleRate <NEW_LINE> b, a = signal.butter(4, cut... | Apply a high pass filter to outputRows[].val[inputIndex],
putting the result in outputRows[].val[outputIndex]. | 625941e6e5267d203edce0db |
def get_elasticache(): <NEW_LINE> <INDENT> elastic_cache = boto3.client('elasticache') <NEW_LINE> ec_cluster = elastic_cache.describe_cache_clusters() <NEW_LINE> for cluster in ec_cluster['CacheClusters']: <NEW_LINE> <INDENT> for s_group in cluster['SecurityGroups']: <NEW_LINE> <INDENT> s_id = s_group['SecurityGroupId'... | Collect Elasticache and used SGs | 625941e6377c676e912725eb |
def get_edge_content(self, vertex, edge_label): <NEW_LINE> <INDENT> return self.__adjacencies__[vertex][edge_label] | Returns:
The content of the edge of label 'edge_label' linked to 'vertex' | 625941e699cbb53fe6793029 |
def get_changes(old, new, prefix='cdda-jenkins-b'): <NEW_LINE> <INDENT> r = requests.get('https://api.github.com/repos/CleverRaven/Cataclysm-DDA/compare/{}{}...{}{}'.format(prefix, old, prefix, new)) <NEW_LINE> rjson = r.json() <NEW_LINE> try: <NEW_LINE> <INDENT> commits = rjson['commits'] <NEW_LINE> <DEDENT> except: <... | Get changes between @old and @new commits/branches | 625941e6283ffb24f3c55d41 |
def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, PaginatedEncodingsCollection): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict() | Returns true if both objects are not equal | 625941e61d351010ab855f5f |
def unzip(filename, directory_to_extract_to): <NEW_LINE> <INDENT> zip_ref = zipfile.ZipFile(filename, 'r') <NEW_LINE> zip_ref.extractall(directory_to_extract_to) <NEW_LINE> zip_ref.close() | Unzips |filename| to |directory_to_extract_to|.
| 625941e66aa9bd52df0371eb |
def __init__(self, parent=None, name=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.parent = parent <NEW_LINE> if self.parent is not None: <NEW_LINE> <INDENT> self._logger = self.parent.logger.getChild(name) | Store the parent and gets a child of the parent.
:param _LogInstance parent:
A parent logger or None.
:param str name:
A name for the logger or None. | 625941e6be383301e01b58c1 |
def main(): <NEW_LINE> <INDENT> solver_prototxt_filename = 'iris_solver.prototxt' <NEW_LINE> train_test_prototxt_filename = 'iris_train_test.prototxt' <NEW_LINE> deploy_prototxt_filename = 'iris_deploy.prototxt' <NEW_LINE> deploy_prototxt_filename = 'iris_deploy.prototxt' <NEW_LINE> deploy_prototxt_batch2_filename =... | This is the main function | 625941e629b78933be1e5aeb |
def send(self, scanner, message): <NEW_LINE> <INDENT> data = scanner + message <NEW_LINE> self.logger.debug( "Send to the scanner (%r) the message : %r", scanner, message) <NEW_LINE> self.serial.write(data) | Send to the scanner the current message by the Serial connection
with scanner base
:param scanner: numero du scanner
:param message: message a envoyer | 625941e62c8b7c6e89b35c02 |
def Create(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') | Creates an SQL Server user in the specified cluster.
| 625941e6097d151d1a22329c |
def do_maketitle(self, node): <NEW_LINE> <INDENT> metadata = node.ownerDocument.userdata <NEW_LINE> displayTitle = 'Page Title' <NEW_LINE> if 'title' in metadata: <NEW_LINE> <INDENT> displayTitle = self._stripNode(metadata['title']) <NEW_LINE> <DEDENT> displayAuthor = [] <NEW_LINE> if 'author' in metadata: <NEW_LINE> <... | Page title | 625941e6d18da76e23532920 |
def _submit_order_with_instructions(self, symbol, qty, side, type, time_in_force, limit_price=None, stop_price=None, client_order_id=None, extended_hours=None, order_class=None, take_profit=None, stop_loss=None): <NEW_LINE> <INDENT> params = { 'symbol': symbol, 'qty': qty, 'side': side, 'type'... | This is slightly modified version of the original submit_order
method of alpaca_trade_api used when we need to add order instructions. | 625941e699cbb53fe679302a |
def home(self, wait=True): <NEW_LINE> <INDENT> for axis in self.axes: <NEW_LINE> <INDENT> axis.home(wait=False) <NEW_LINE> <DEDENT> if wait: <NEW_LINE> <INDENT> self.wait_until_idle() <NEW_LINE> <DEDENT> self.initialized = True | Returns the axes to their home position.
Args:
wait (bool): Wait until the axes are idle, default set to True. | 625941e685dfad0860c3b2a0 |
def draw(self): <NEW_LINE> <INDENT> if self.isvisible: <NEW_LINE> <INDENT> self.game.graphics.draw(self.tex, self.pos) | Draw powerup. | 625941e6d53ae8145f87a6ac |
def on_signal(self, event: Event): <NEW_LINE> <INDENT> if not isinstance(event, SignalEvent): return <NEW_LINE> order_type = LimitOrderEvent if event.order_type.upper() == 'LMT' else MarketOrderEvent <NEW_LINE> for n, (asset, quantity) in enumerate(event.order_quantity): <NEW_LINE> <INDENT> if self.inst_exec... | Put signal events into events queue
Args:
event: signal events | 625941e64428ac0f6e5bac3a |
def snapshot_brain_montage(fig, montage, hide_sensors=True): <NEW_LINE> <INDENT> mlab = _import_mlab() <NEW_LINE> from ..channels import Montage, DigMontage <NEW_LINE> from .. import Info <NEW_LINE> if isinstance(montage, (Montage, DigMontage)): <NEW_LINE> <INDENT> chs = montage.dig_ch_pos <NEW_LINE> ch_names, xyz = zi... | Take a snapshot of a Mayavi Scene and project channels onto 2d coords.
Note that this will take the raw values for 3d coordinates of each channel,
without applying any transforms. If brain images are flipped up/dn upon
using `imshow`, check your matplotlib backend as this behavior changes.
Parameters
----------
fig :... | 625941e673bcbd0ca4b2c4ba |
def _calculate_lrc_string(inputstring): <NEW_LINE> <INDENT> _check_string(inputstring, description="input LRC string") <NEW_LINE> register = 0 <NEW_LINE> for character in inputstring: <NEW_LINE> <INDENT> register += ord(character) <NEW_LINE> <DEDENT> lrc = ((register ^ 0xFF) + 1) & 0xFF <NEW_LINE> return _num_to_onebyt... | Calculate LRC for Modbus.
Args:
inputstring (str): An arbitrary-length message (without the beginning
colon and terminating CRLF). It should already be decoded from hex-string.
Returns:
A one-byte LRC bytestring (not encoded to hex-string)
Algorithm from the document 'MODBUS over serial line specificatio... | 625941e666656f66f7cbc5f1 |
def send(self, protocol, command, payload, message_id=None): <NEW_LINE> <INDENT> message = {'protocol': protocol, 'command': command, 'payload': payload, 'id': message_id or str(uuid.uuid4())} <NEW_LINE> print("--OUT--") <NEW_LINE> import pprint <NEW_LINE> pprint.pprint(message) <NEW_LINE> try: <NEW_LINE> <INDENT> self... | Send a message to UI/client | 625941e65e10d32532c5f36a |
def print_aln_list_info(alns, sort=True): <NEW_LINE> <INDENT> if not alns: return "no alignments!" <NEW_LINE> aln_data = [('-' if a.not_primary_alignment else '+', '1' if a.pe_which=='first' else '2', aln_read_coverage_fraction(a, True), a.optional_field('NM'), a.iv.chrom, a.iv.start, a.iv.end) for a in alns] <NEW_L... | Return string of useful information about a list of alignments, optionally sorted. | 625941e6627d3e7fe0d69296 |
def check_folder_exists(self, folder_path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.ftp.stat(folder_path) <NEW_LINE> return True <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> return False | check if the folder exists on remote machine
:param folder_path: path on the remote machine
:return: True/False | 625941e6cc0a2c11143dd2d6 |
def on_message_received(self, msg): <NEW_LINE> <INDENT> self.received_msg = msg <NEW_LINE> self.msg_received_event.set() | Actions
Args:
msg(str): Message | 625941e6e8904600ed9f2378 |
def __init__(self, iri: IRI): <NEW_LINE> <INDENT> self._is_nothing = iri.is_nothing() <NEW_LINE> self._is_thing = iri.is_thing() <NEW_LINE> self._iri = iri | Gets an instance of OWLClass that has the specified IRI.
Args:
iri: The IRI. | 625941e645492302aab5e70c |
def get_freeCount(self): <NEW_LINE> <INDENT> url_params = {'a': self.__APP_ID, 't': int(time.time())} <NEW_LINE> res = requests.get(url=self.__Url, params=url_params) <NEW_LINE> if res.status_code == 200: <NEW_LINE> <INDENT> result = res.json() <NEW_LINE> if result['errCode'] == 0: <NEW_LINE> <INDENT> self.label.config... | 获取今日的免费次数 | 625941e663d6d428bbe44935 |
def solve_constraint_generic(problem, enqueue_condition=None) : <NEW_LINE> <INDENT> agenda = [problem] <NEW_LINE> num_extensions = 0 <NEW_LINE> while agenda: <NEW_LINE> <INDENT> prob = agenda.pop(0) <NEW_LINE> num_extensions +=1 <NEW_LINE> if has_empty_domains(prob): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if ... | Solves the problem, calling propagate with the specified enqueue
condition (a function). If enqueue_condition is None, uses DFS only.
Same return type as solve_constraint_dfs. | 625941e64e4d5625662d4816 |
def verify_md5(j): <NEW_LINE> <INDENT> data = {} <NEW_LINE> data['date'] = j.get('date') <NEW_LINE> data['uid'] = j.get('uid') <NEW_LINE> data['name'] = j.get('name') <NEW_LINE> data_json = json.dumps(data) <NEW_LINE> data_json_md5 = hashlib.md5(data_json).hexdigest() <NEW_LINE> if data_json_md5 == j.get('md5checksum')... | Verify md5 checksum of submitted data.
Builds data dict to run md5 against
data is converted to json object before md5 checksum is run
md5 checksum match returns data dict | 625941e67c178a314d6ef8ab |
def problem_lia(): <NEW_LINE> <INDENT> from solutions.lia import lia <NEW_LINE> f = readfile('rosalind_lia.txt') <NEW_LINE> with f: <NEW_LINE> <INDENT> k, n = [int(i) for i in f.next().split()] <NEW_LINE> lineoutput(lia(k, n)) | http://rosalind.info/problems/lia/ | 625941e6aad79263cf390e8c |
def __init__(self, anchor, id, lineSize, time, direction=None, filters=None): <NEW_LINE> <INDENT> self.anchor = anchor <NEW_LINE> self.direction = direction <NEW_LINE> self.filters = filters <NEW_LINE> self.id = id <NEW_LINE> self.lineSize = lineSize <NEW_LINE> self.time = time | :param anchor: 查询anchor,基于该值偏移进行上下文检索
:param direction: (Optional) 搜索方向,默认both,可取值:up,down,both
:param filters: (Optional) 指定返回字段,只对系统日志生效,不填默认按照产品线配置返回字段,Name支持:key,Values填入返回字段
:param id: 日志记录ID
:param lineSize: 查看上下文行数大小,最大支持200
:param time: 查询日志时返回的时间戳 | 625941e697e22403b379d3e0 |
def register_addressable_alias(self, alias, addressable_type): <NEW_LINE> <INDENT> if alias in self._addressable_alias_map: <NEW_LINE> <INDENT> logger.info('Addressable alias {alias} has already been registered. Overwriting!' .format(alias=alias)) <NEW_LINE> <DEDENT> self._addressable_alias_map[alias] = addressable_ty... | Registers a general Addressable type under the given alias.
Addressables are the general mechanism for capturing the name and value of objects instantiated
in BUILD files. Most notably, TargetAddressable is a subclass of Addressable, and
`register_target_alias` delegates to this method after noting the alias mapping ... | 625941e67cff6e4e81117dca |
def _HandleGetSessions(self, first_command): <NEW_LINE> <INDENT> command_response_pairs = collections.defaultdict(dict) <NEW_LINE> command_response_pairs[first_command.session_id] = ( {"command": first_command}) <NEW_LINE> while True: <NEW_LINE> <INDENT> next_entry = self._parser.GetNext() <NEW_LINE> if not next_entry:... | Special case handler for the GetSessions command.
Since it is dispatched to each session thread, GetSessions doesn't guarantee
command-response-command-response ordering in the log. This happens with
getSessions, which is broadcast to and logged by each of the active sessions
in the ChromeDriver instance. This simply ... | 625941e6cc0a2c11143dd2d7 |
def locateChild(self, ctx, segments): <NEW_LINE> <INDENT> store = _storeFromUsername( self.loginSystem.store, segments[0].decode('utf-8')) <NEW_LINE> if store is None: <NEW_LINE> <INDENT> return rend.NotFound <NEW_LINE> <DEDENT> return (SharingIndex(store, self.webViewer), segments[1:]) | Retrieve a L{SharingIndex} for a particular user, or rend.NotFound. | 625941e6d10714528d60012c |
def test_openlog(infopl): <NEW_LINE> <INDENT> with WorkflowMock(['script', 'workflow:openlog']) as c: <NEW_LINE> <INDENT> wf = Workflow() <NEW_LINE> wf.args <NEW_LINE> assert c.cmd == ['open', wf.logfile] <NEW_LINE> wf.reset() | Magic: open logfile | 625941e6956e5f7376d712b1 |
def remove_dir(dir): <NEW_LINE> <INDENT> if os.path.exists(dir): <NEW_LINE> <INDENT> shutil.rmtree(dir) | remove directory
:param dir:
:return: | 625941e64527f215b584c897 |
def query_without_transaction( conversion: Conversion, caller: str, sql: str ) -> DBAccessQueryResult: <NEW_LINE> <INDENT> client, cursor, error = None, None, None <NEW_LINE> try: <NEW_LINE> <INDENT> connection_details = { 'port': conversion.target_con_string['port'], 'host': conversion.target_con_string['host'], 'user... | Sends given query to the target PostgreSQL database without wrapping it with transaction. | 625941e6ff9c53063f47c636 |
def main(): <NEW_LINE> <INDENT> if os.environ.get("NO_POSTINSTALL"): <NEW_LINE> <INDENT> print("Skipping postinstall script.") <NEW_LINE> return <NEW_LINE> <DEDENT> print("Running KBase app tests.") <NEW_LINE> token, kbase_endpoint = load_config() <NEW_LINE> env = dict(os.environ) <NEW_LINE> env["KB_AUTH_TOKEN"] = toke... | Run KBase tests, collect static assets and start server. | 625941e6e64d504609d74c85 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.