text
stringlengths
78
104k
score
float64
0
0.18
def _generate(self): u"""overrided in each modules.""" self._data['key'] = self.key self._data['value'] = self.value self._data['host'] = self.host self._data['clock'] = self.clock
0.00905
def apply_smoothing(self, smooth_fwhm): """Set self._smooth_fwhm and then smooths the data. See boyle.nifti.smooth.smooth_imgs. Returns ------- the smoothed data deepcopied. """ if smooth_fwhm <= 0: return old_smooth_fwhm = self._smooth_fw...
0.004739
def parse_cfg(self): """ parses the given config file for experiments. """ self.cfgparser = ConfigParser() if not self.cfgparser.read(self.options.config): raise SystemExit('config file %s not found.'%self.options.config) # Change the current working directory to be relativ...
0.01046
def _set_parent_port_detail(self, v, load=False): """ Setter method for parent_port_detail, mapped from YANG variable /ptp_state/parent_port_detail (container) If this variable is read-only (config: false) in the source YANG file, then _set_parent_port_detail is considered as a private method. Backe...
0.005426
def _setup_logging(cls, args): '''Set up the root logger if needed. The root logger is set the appropriate level so the file and WARC logs work correctly. ''' assert ( logging.CRITICAL > logging.ERROR > logging.WARNING > logging.IN...
0.002177
def _check_action_feasibility(self): """ Check that for every state, reward is finite for some action, and for the case sa_pair is True, that for every state, there is some action available. """ # Check that for every state, reward is finite for some action R_max...
0.001729
def df_from_groups(groups, columns=None): """Create DataFrame of GroupBy object with columns for each product(grouped_value, column_label)""" if columns is None: columns = list(groups.get_group(groups.indices.keys()[0]).columns) df = pd.DataFrame() for col, group_label in product(columns, groups...
0.004228
def scope(self, key, *tags, default=None): """Only apply tags and default for top-level key, effectively scoping the tags.""" scope = self._scopes[key] tags = self._ensure_exclamation(tags) default = default if not default or default.startswith("!") else "!" + default if scope: ...
0.008114
def auth(alias=None, url=None, cfg="~/.xnat_auth"): ''' Read connection details from an xnat_auth XML file Example: >>> import yaxil >>> auth = yaxil.auth('xnatastic') >>> auth.url, auth.username, auth.password ('https://www.xnatastic.org/', 'username', '********') :par...
0.001381
def check_local_install(ctx, version, ext, server="local"): """ Upload and install works? Uploads a distribution to PyPI, and then tests to see if I can download and install it. Returns: str: string summazing operation """ here = Path(ctx.releaser.here).resolve() dist_dir = her...
0.00083
def relative_field(field, parent): """ RETURN field PATH WITH RESPECT TO parent """ if parent==".": return field field_path = split_field(field) parent_path = split_field(parent) common = 0 for f, p in _builtin_zip(field_path, parent_path): if f != p: break ...
0.003704
def new_cells(self, name=None, formula=None): """Create a cells in the space. Args: name: If omitted, the model is named automatically ``CellsN``, where ``N`` is an available number. func: The function to define the formula of the cells. Returns: ...
0.004505
def _fix_dynamic_class_lookup(cls, pstfx): """Fix name lookup problem that prevents pickling of dynamically defined classes. Parameters ---------- cls : class Dynamically generated class to which fix is to be applied pstfx : string Postfix that can be used to identify dynamically ge...
0.001094
def _matches_contigs(in_file, contigs, checked_file): """Check if the contigs in the input file match the defined contigs in the reference genome. """ tocheck_contigs = 2 if utils.file_exists(checked_file): with open(checked_file) as in_handle: return in_handle.read().strip() == "mat...
0.002217
def user_create(name, passwd, database=None, user=None, password=None, host=None, port=None): ''' Create a cluster admin or a database user. If a database is specified: it will create database user. If a dat...
0.002009
def find(self, item_id=None): "Recursively find a menu item by its id (useful for event handlers)" for it in self: found = it.find(item_id) if found: return found
0.008969
def consume(self, kind): """Consume one token and verify it is of the expected kind.""" next_token = self.stream.move() assert next_token.kind == kind
0.011494
def fileopenbox(msg=None, title=None, default='*', filetypes=None, multiple=False): """ A dialog to get a file name. **About the "default" argument** The "default" argument specifies a filepath that (normally) contains one or more wildcards. fileopenbox will display only files that match the d...
0.004063
def compute_utility(self, board, move, player): "If X wins with this move, return 1; if O return -1; else return 0." if (self.k_in_row(board, move, player, (0, 1)) or self.k_in_row(board, move, player, (1, 0)) or self.k_in_row(board, move, player, (1, -1)) or self.k_i...
0.006865
def safeArgs(args): """Iterate over valid, finite values in an iterable. Skip any items that are None, NaN, or infinite. """ return (arg for arg in args if arg is not None and not math.isnan(arg) and not math.isinf(arg))
0.004016
def u_distance_correlation_sqr(x, y, **kwargs): """ u_distance_correlation_sqr(x, y, *, exponent=1) Computes the bias-corrected estimator for the squared distance correlation between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond...
0.000532
def execute(self, timeSeries): """Creates a new TimeSeries containing the smoothed and forcasted values. :return: TimeSeries object containing the smoothed TimeSeries, including the forecasted values. :rtype: TimeSeries :note: The first normalized value is chosen a...
0.004314
def set_objective(self, measured_metabolites): ''' Updates objective function for given measured metabolites. :param dict measured_metabolites: dict in which keys are metabolite names and values are float numbers represent fold changes in metabolites. ''' self.clea...
0.006925
def pop(self, name: str, default: Any=_sentinel) -> Any: """Pop, get and remove the named attribute of this instance.""" if default is _sentinel: return self.__dict__.pop(name) else: return self.__dict__.pop(name, default)
0.014815
def p_scalar__doublequote(self, p): """ scalar : DOUBLEQUOTE_START SCALAR DOUBLEQUOTE_END """ scalar = re.sub('\n\s+', ' ', str(p[2])) p[0] = Str(scalar.replace('\\"', '"'))
0.013953
def smart_email_send(self, smart_email_id, to, consent_to_track, cc=None, bcc=None, attachments=None, data=None, add_recipients_to_list=None): """Sends the smart email.""" validate_consent_to_track(consent_to_track) body = { "To": to, "CC": cc, "BCC": bcc, ...
0.004498
def manage(self): """ Manage the task to handle restarts, reconfiguration, etc. Returns True to request a shorter period before the next call, False if nothing special is needed. """ log = self._params.get('log', self._discard) if self._stopping: log.debu...
0.004024
def setup(self, reason, grr_server_url, grr_username, grr_password, approvers=None, verify=True): """Initializes a GRR hunt result collector. Args: reason: justification for GRR access. grr_server_url: GRR server URL. grr_username: GRR username. grr_password: GRR password. ...
0.003525
def get_result(self, indices_or_msg_ids=None, block=None): """Retrieve a result by msg_id or history index, wrapped in an AsyncResult object. If the client already has the results, no request to the Hub will be made. This is a convenient way to construct AsyncResult objects, which are wrappers...
0.005319
def activate(self): """ Activate the scene. """ response = self.api_interface.set_device_state(self, None) self._update_state_from_response(response)
0.010309
def copy_previous_results(self): """Use the latest valid results_dir as the starting contents of the current results_dir. Should be called after the cache is checked, since previous_results are not useful if there is a cached artifact. """ # TODO(mateo): This should probably be managed by the task,...
0.01056
def on_add_cols(self, event): """ Show simple dialog that allows user to add a new column name """ col_labels = self.grid.col_labels dia = pw.ChooseOne(self, yes="Add single columns", no="Add groups") result1 = dia.ShowModal() if result1 == wx.ID_CANCEL: ...
0.001982
def _fx_mapping(raw_rates): ''' Map raw output to clearer labels ''' return {pair[0].lower(): { 'timeStamp': pair[1], 'bid': float(pair[2] + pair[3]), 'ask': float(pair[4] + pair[5]), 'high': float(pair[6]), 'low': float(pair[7]) } for pair in map(lambda x: x.split(',...
0.002985
def put_mapping(self, doc_type=None, mapping=None, indices=None, ignore_conflicts=None): """ Register specific mapping definition for a specific type against one or more indices. (See :ref:`es-guide-reference-api-admin-indices-put-mapping`) """ if not isinstance(mapping, dict): ...
0.004274
def kill(self, typ=TaskExit, value=None, tb=None): """Terminates the current task by raising an exception into it. Whatever that task might be doing; be it waiting for I/O or another primitive, it sees an exception as soon as it yields control. By default, this exception is TaskExit, bu...
0.002584
def can_vote_on_poll(self, request): """Based on jmbo.models.can_vote.""" # can't vote if liking is closed if self.votes_closed: return False, 'closed' # can't vote if liking is disabled if not self.votes_enabled: return False, 'disabled' # anon...
0.002395
def _update_sid_to_last_existing_pid_map(pid): """Set chain head PID to the last existing object in the chain to which ``pid`` belongs. If SID has been set for chain, it resolves to chain head PID. Intended to be called in MNStorage.delete() and other chain manipulation. Preconditions: - ``pid`` m...
0.003086
def conference_hangup(self, call_params): """REST Conference Hangup helper """ path = '/' + self.api_version + '/ConferenceHangup/' method = 'POST' return self.request(path, method, call_params)
0.008547
def apns_fetch_inactive_ids(): """ Queries the APNS server for id's that are no longer active since the last fetch """ with closing(_apns_create_socket_to_feedback()) as socket: inactive_ids = [] for _, registration_id in _apns_receive_feedback(socket): inactive_ids.appe...
0.002525
async def delay(self, duration_s: int): """ Pause and sleep """ self.pause() await asyncio.sleep(duration_s) self.resume()
0.012346
def raise_for_execution_errors(nb, output_path): """Assigned parameters into the appropriate place in the input notebook Parameters ---------- nb : NotebookNode Executable notebook object output_path : str Path to write executed notebook """ error = None for cell in nb.cel...
0.002216
def set(self, indexes, values=None): """ Given indexes will set a sub-set of the Series to the values provided. This method will direct to the below methods based on what types are passed in for the indexes. If the indexes contains values not in the Series then new rows or columns will...
0.011096
def value(self): """Set a calculated value for this Expression. Used when writing formulas using XlsxWriter to give cells an initial value when the sheet is loaded without being calculated. """ try: if isinstance(self.__value, Expression): return self....
0.004796
def xy_reading_order(e1, e2): """ A comparator to sort bboxes from left to right, top to bottom """ b1 = e1.bbox b2 = e2.bbox if round(b1[x0]) == round(b2[x0]): return float_cmp(b1[y0], b2[y0]) return float_cmp(b1[x0], b2[x0])
0.003817
def monthly_cooling_design_days_100(self): """A list of 12 objects representing monthly 10.0% cooling design days.""" if self.monthly_found is False or self._monthly_db_100 == [] \ or self._monthly_wb_100 == []: return [] else: db_conds = [DryBulbC...
0.005417
def build_image(self, conf, pushing=False): """Build this image""" with conf.make_context() as context: try: stream = BuildProgressStream(conf.harpoon.silent_build) with self.remove_replaced_images(conf) as info: cached = NormalBuilder().bu...
0.004521
def setTableType( self, tableType ): """ Sets the table type for this record box to the inputed table type. :param tableType | <orb.Table> """ self._tableType = tableType if tableType: self._tableTypeName = tableType.schema(...
0.018373
def encode(self, word, max_length=5, zero_pad=True): """Return the Roger Root code for a word. Parameters ---------- word : str The word to transform max_length : int The maximum length (default 5) of the code to return zero_pad : bool ...
0.00229
def make_request_parser(model_or_inst, excludes=None, only=None, for_populate=False): """Pass a `model class` or `model instance` to this function, then, it will generate a `RequestParser` that extract user request data from `request.json` according to the model class's definition. Parameter `exclude...
0.005128
def id_lookup(paper_id, idtype): """Take an ID of type PMID, PMCID, or DOI and lookup the other IDs. If the DOI is not found in Pubmed, try to obtain the DOI by doing a reverse-lookup of the DOI in CrossRef using article metadata. Parameters ---------- paper_id : str ID of the article....
0.000442
def _get_path_infomation(self): """Get useful infomation from the device path.""" long_identifier = self._device_path.split('/')[4] protocol, remainder = long_identifier.split('-', 1) identifier, _, device_type = remainder.rsplit('-', 2) return (protocol, identifier, device_type)
0.00625
def accepts_port(self, port): """ Query whether this Router will accept the given port. """ if self.rejected_ports is None and self.accepted_ports is None: raise RuntimeError("policy hasn't been set yet") if self.rejected_ports: for x in self.rejected_po...
0.00381
def child(self, **kwargs): '''set childSelector.''' return AutomatorDeviceObject( self.device, self.selector.clone().child(**kwargs) )
0.010989
def install_python(python, runas=None): ''' Install a python implementation. python The version of python to install, should match one of the versions listed by pyenv.list CLI Example: .. code-block:: bash salt '*' pyenv.install_python 2.0.0-p0 ''' python = re.sub...
0.001025
def get_orders(self, address, chain_name='NEO', contract_version='V2', pair=None, from_epoch_time=None, order_status=None, before_id=None, limit=50): """ Function to fetch the order history of the given address. Execution of this function is as follows:: get_order...
0.004023
def addfile(self, tarinfo, fileobj=None): """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be ...
0.001967
def safe_zip(*args): """like zip but with these properties: - returns a list, rather than an iterator. This is the old Python2 zip behavior. - a guarantee that all arguments are the same length. (normal zip silently drops entries to make them the same length) """ length = len(args[0]) if not all(len(arg) ...
0.012295
def get_properties_by_type(self, type, recursive=True, parent_path=""): """ Returns a sorted list of fields that match the type. :param type the type of the field "string","integer" or a list of types :param recursive recurse to sub object :returns a sorted list of fields the ma...
0.003826
def get(cls, uni_char): """Return the general category code (as Unicode string) for the given Unicode character""" uni_char = unicod(uni_char) # Force to Unicode return unicod(unicodedata.category(uni_char))
0.012931
def supports(cls, template_file=None): """ :return: Whether the engine can process given template file or not. """ if anytemplate.compat.IS_PYTHON_3: cls._priority = 99 return False # Always as it's not ported to python 3. return super(Engine, cls).suppo...
0.005682
def store_in_internal_db(args, hsm, modhex_id, public_id, kh, aead): """ Store record (AEAD) in YubiHSM internal DB """ if args.verbose: print " %i bytes (%s) -> internal db..." % \ (len(aead.data), shorten_aead(aead)), try: hsm.db_store_yubikey(public_id.decode('hex'), kh, ae...
0.003049
def quote(cls, value): """Quote the value for the cookie. This can be any object supported by :attr:`serialization_method`. :param value: the value to quote. """ if cls.serialization_method is not None: value = cls.serialization_method.dumps(value) if cls.qu...
0.004684
def add_and_get(self, delta): ''' Atomically adds `delta` to the current value. :param delta: The delta to add. ''' with self._lock.exclusive: self._value += delta return self._value
0.008097
def num_throats(self, labels='all', mode='union'): r""" Return the number of throats of the specified labels Parameters ---------- labels : list of strings, optional The throat labels that should be included in the count. If not supplied, all throats are ...
0.001212
def valid_id(opts, id_): ''' Returns if the passed id is valid ''' try: if any(x in id_ for x in ('/', '\\', str('\0'))): return False return bool(clean_path(opts['pki_dir'], id_)) except (AttributeError, KeyError, TypeError, UnicodeDecodeError): return False
0.003175
def update(self, friendly_name): """ Update the FunctionInstance :param unicode friendly_name: The friendly_name :returns: Updated FunctionInstance :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance """ data = values.of({'FriendlyName': friendly...
0.003165
def _checker(keywords): """Generate a checker which tests a given value not starts with keywords.""" def _(v): """Check a given value matches to keywords.""" for k in keywords: if k in v: return False return True return _
0.007018
def set_basic_selection(self, selection, value, fields=None): """Modify data for an item or region of the array. Parameters ---------- selection : tuple An integer index or slice or tuple of int/slice specifying the requested region for each dimension of the arra...
0.003246
def arc(self, x, y, radius, start_angle, end_angle): """draw arc going counter-clockwise from start_angle to end_angle""" self._add_instruction("arc", x, y, radius, start_angle, end_angle)
0.009804
def create_course_completion(self, user_id, payload): # pylint: disable=unused-argument """ Send a completion status payload to the Degreed Completion Status endpoint Args: user_id: Unused. payload: JSON encoded object (serialized from DegreedLearnerDataTransmissionAudi...
0.005747
def execute(self): """ Stops the cluster if it's running. """ cluster_name = self.params.cluster creator = make_creator(self.params.config, storage_path=self.params.storage) try: cluster = creator.load_cluster(cluster_name) ...
0.002347
def acquire(self): """ Locks the account. Returns True on success, False if the account is thread-local and must not be locked. """ if self.host: self.parent.send(('acquire-account-for-host', self.host)) elif self.account_hash: self.parent.send(('a...
0.002587
def to_array(self): """ Serializes this GameHighScore to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(GameHighScore, self).to_array() array['position'] = int(self.position) # type int array['user'] = sel...
0.004717
def crud_mutation_name(action, model): """ This function returns the name of a mutation that performs the specified crud action on the given model service """ model_string = get_model_string(model) # make sure the mutation name is correctly camelcases model_string = model_string[0].u...
0.004717
def delete(self): """ delete() executes the query by delegating to delete_by_query() """ es = connections.get_connection(self._using) return AttrDict( es.delete_by_query( index=self._index, body=self.to_dict(), **self....
0.005698
def extract_from_zip(path, candidates): """ Given a zip archive and a function to detect the presence of a given filename, unzip the archive into a temporary directory and return the full path of the file. Raise an IOError if the file cannot be found within the archive. :param path: pathname of...
0.001661
def previous(self): """ Returns new CharacterDataWrapper TODO: Don't lower offset below 0 """ self.params['offset'] = str(int(self.params['offset']) - int(self.params['limit'])) return self.marvel.get_characters(self.marvel, (), **self.params)
0.010309
def add_function_attribute(self, attr): """Only works on function value Parameters ----------- attr : str attribute name """ if not self.is_function: raise ValueError('expected function value, got %s' % (self._kind,)) attrname = str(attr) ...
0.003419
def _infer_stmts(stmts, context, frame=None): """Return an iterator on statements inferred by each statement in *stmts*.""" inferred = False if context is not None: name = context.lookupname context = context.clone() else: name = None context = contextmod.InferenceContext...
0.001938
def tracer_config(__init__, app, args, kwargs): """ Wraps the Tornado web application initialization so that the TornadoTracing instance is created around an OpenTracing-compatible tracer. """ __init__(*args, **kwargs) tracing = app.settings.get('opentracing_tracing') tracer_callable = app....
0.000696
def clear_trace_filter_cache(): ''' Clear the trace filter cache. Call this after reloading. ''' global should_trace_hook try: # Need to temporarily disable a hook because otherwise # _filename_to_ignored_lines.clear() will never complete. old_hook = should_trace_hook ...
0.00198
def get_property(self, key): """Expect Django Conf property""" _key = DJANGO_CONF[key] return getattr(self, _key, CONF_SPEC[_key])
0.012987
def opt(self, *, exception=None, record=False, lazy=False, ansi=False, raw=False, depth=0): r"""Parametrize a logging call to slightly change generated log message. Parameters ---------- exception : |bool|, |tuple| or |Exception|, optional If it does not evaluate as ``False`...
0.005861
def get_historical_output(self, assessment, options): """ To get output of a historical Assessment :param assessment: string :param options: dict """ responseFormat=None if options and 'format' in options and options['format'] is not None: responseForm...
0.007156
def warsaw_up_to_warsaw(C, parameters=None, sectors=None): """Translate from the 'Warsaw up' basis to the Warsaw basis. Parameters used: - `Vus`, `Vub`, `Vcb`, `gamma`: elements of the unitary CKM matrix (defined as the mismatch between left-handed quark mass matrix diagonalization matrices). ...
0.001083
def insert_picture(self, image_file): """ Return a |PlaceholderPicture| object depicting the image in *image_file*, which may be either a path (string) or a file-like object. The image is cropped to fill the entire space of the placeholder. A |PlaceholderPicture| object has all t...
0.002853
def visit_Cond(self, node): ''' generic expression splitting algorithm. Should work for ifexp and if using W(rap) and U(n)W(rap) to manage difference between expr and stmt The idea is to split a BinOp in three expressions: 1. a (possibly empty) non-static expr 2....
0.000776
def acs2d(input, exec_path='', time_stamps=False, verbose=False, quiet=False, exe_args=None): r""" Run the acs2d.e executable as from the shell. Output is automatically named based on input suffix: +--------------------+----------------+------------------------------+ | INPUT ...
0.000342
def replace(self, text, pattern=None): """Replace selected text by *text* If *pattern* is not None, replacing selected text using regular expression text substitution""" cursor = self.textCursor() cursor.beginEditBlock() if pattern is not None: seltxt =...
0.003241
def DeregisterHelper(cls, helper_class): """Deregisters a helper class. The helper classes are identified based on their lower case name. Args: helper_class (type): class object of the argument helper. Raises: KeyError: if helper class is not set for the corresponding name. """ he...
0.00367
def spa_tmplt(**kwds): """ Generate a minimal TaylorF2 approximant with optimations for the sin/cos """ # Pull out the input arguments f_lower = kwds['f_lower'] delta_f = kwds['delta_f'] distance = kwds['distance'] mass1 = kwds['mass1'] mass2 = kwds['mass2'] s1z = kwds['spin1z'] ...
0.002093
def connect_async(self, connection_id, connection_string, callback): """Asynchronously connect to a device Args: connection_id (int): A unique identifier that will refer to this connection connection_string (string): A DeviceAdapter specific string that can be used to connect to...
0.009642
def _call(self, vf, out): """Implement ``self(vf, out)``.""" if self.domain.field == ComplexNumbers(): vf[0].multiply(self._vecfield[0].conj(), out=out) else: vf[0].multiply(self._vecfield[0], out=out) if self.is_weighted: out *= self.weights[0] ...
0.002635
def parse_text(self, formatted_text): """ Retursn a list of operations (draw, cup, ed,...). Each operation consist of a command and its associated data. :param formatted_text: text to parse with the default char format to apply. :return: list of Operation """ as...
0.002008
def _install_directory_structure_file(cls): """ Download the latest version of `dir_structure_production.json`. """ # We initiate the link to the public suffix configuration. # It is not hard coded because this method is called only if we # are sure that the configuratio...
0.004591
def show(self, m_a): """ Display (with a pretty print) this object :param m_a: :class:`MethodAnalysis` object """ bytecode.PrettyShow(m_a, m_a.basic_blocks.gets(), self.notes) bytecode.PrettyShowEx(m_a.exceptions.gets())
0.00722
def parse_string_factory( alg, sep, splitter, input_transform, component_transform, final_transform ): """ Create a function that will split and format a *str* into a tuple. Parameters ---------- alg : ns enum Indicate how to format and split the *str*. sep : str The string ...
0.000364
def connect(self): """connect to the database **Return:** - ``dbConn`` -- the database connection See the class docstring for usage """ self.log.debug('starting the ``get`` method') dbSettings = self.dbSettings port = False if "tunnel" in d...
0.001715
def _MaybePurgeOrphanedData(self, event): """Maybe purge orphaned data due to a TensorFlow crash. When TensorFlow crashes at step T+O and restarts at step T, any events written after step T are now "orphaned" and will be at best misleading if they are included in TensorBoard. This logic attempts t...
0.01417
def _render_our_module_flags(self, module, output_lines, prefix=''): """Returns a help string for a given module.""" flags = self._get_flags_defined_by_module(module) if flags: self._render_module_flags(module, flags, output_lines, prefix)
0.007782