text
stringlengths
78
104k
score
float64
0
0.18
def get_files(file_tokens, cwd=None): """ Given a list of parser file tokens, return a list of input objects for them. """ if not file_tokens: return [] token = file_tokens.pop() try: filename = token.filename except AttributeError: filename = '' if cwd: ...
0.002146
def gaussApprox(self,xy,**kwargs): """ NAME: gaussApprox PURPOSE: return the mean and variance of a Gaussian approximation to the stream DF at a given phase-space point in Galactocentric rectangular coordinates (distribution is over missing directions) INPUT: ...
0.022102
def skip_whitespace(self): """Consume input until a non-whitespace character is encountered. The non-whitespace character is then ungotten, and the number of whitespace characters consumed is returned. If the tokenizer is in multiline mode, then newlines are whitespace. @rtype...
0.003311
def b6_evalue_filter(handle, e_value, *args, **kwargs): """Yields lines from handle with E-value less than or equal to e_value Args: handle (file): B6/M8 file handle, can be any iterator so long as it it returns subsequent "lines" of a B6/M8 entry e_value (float): max E-value to re...
0.001053
def _format_property_values(self, previous, current): """ Format WMI Object's RAW data based on the previous sample. Do not override the original WMI Object ! """ formatted_wmi_object = CaseInsensitiveDict() for property_name, property_raw_value in iteritems(current): ...
0.003974
def scan(self, table_name, index_name=None, consistent_read=None, projection_expression=None, filter_expression=None, expression_attribute_names=None, expression_attribute_values=None, segment=None, tota...
0.004518
def make_error_response(self, cond): """Create error response for the a "get" or "set" iq stanza. :Parameters: - `cond`: error condition name, as defined in XMPP specification. :return: new `Iq` object with the same "id" as self, "from" and "to" attributes swapped, type...
0.012393
def _remove_magic(self, data): '''Verify and remove magic''' if not self.magic: return data magic_size = len(self.magic) magic = data[:magic_size] if magic != self.magic: raise Exception('Invalid magic') data = data[magic_size:] return d...
0.006192
def update(self, w, offset=0): """Compute gradient and Hessian matrix with respect to `w`.""" time = self.time x = self.x exp_xw = numpy.exp(offset + numpy.dot(x, w)) n_samples, n_features = x.shape gradient = numpy.zeros((1, n_features), dtype=float) hessian = n...
0.00194
def directory(cls, prefix=None): """ Path that should be used for caching. Different for all subclasses. """ prefix = prefix or utility.read_config().directory name = cls.__name__.lower() directory = os.path.expanduser(os.path.join(prefix, name)) utility.ensure_di...
0.00551
def delete_namespace(self, name): """ Delete namespace with specific name :param name: str, namespace to delete :return: None """ self.core_api.delete_namespace(name, client.V1DeleteOptions()) logger.info("Deleting namespace: %s", name)
0.006826
def _init_map(self): """stub""" super(MultiLanguageDragAndDropQuestionFormRecord, self)._init_map() self.my_osid_object_form._my_map['droppables'] = \ self._droppables_metadata['default_object_values'][0] self.my_osid_object_form._my_map['targets'] = \ self._targe...
0.003337
def update( self, filepath, cache=False, remove=False, bumpversion=None, prerelease=None, dependencies=None, metadata=None, message=None): ''' Enter a new version to a DataArchive Paramet...
0.000662
def build(self, builder): """Build XML by appending to builder""" params = dict(OID=self.oid, Name=self.name) if self.unit_dictionary_name: params["mdsol:UnitDictionaryName"] = self.unit_dictionary_name for suffix in ["A", "B", "C", "K"]: val = getattr(self, "c...
0.00303
def summary(self): """ :rtype: twilio.rest.insights.v1.summary.CallSummaryList """ if self._summary is None: self._summary = CallSummaryList(self) return self._summary
0.009132
def dtype(self, byte_order='='): ''' Return the numpy dtype of the in-memory representation of the data. (If there are no list properties, and the PLY format is binary, then this also accurately describes the on-disk representation of the element.) ''' return _n...
0.004762
def main(): """The main entry point.""" if sys.version_info < (2, 7): sys.exit('crispy requires at least Python 2.7') elif sys.version_info[0] == 3 and sys.version_info < (3, 4): sys.exit('crispy requires at least Python 3.4') kwargs = dict( name='crispy', version=get_ve...
0.000362
def evaluate(self, verbose=True, passes=None): """Summary Returns: TYPE: Description """ if self.is_pivot: index, pivot, columns = LazyOpResult( self.expr, self.weld_type, 0 ).evaluate(verbose=verbose, p...
0.00173
def copy(self): """Create a new copy of selfe. does not do a deep copy for payload :return: copied range :rtype: GenomicRange """ return type(self)(self.chr, self.start+self._start_offset, self.end, self.payload, ...
0.003003
def connect(polylines, max_dist=10): """ connect polylines that are close and have a similar orientation o---o <-> o---o ==> o----o--o----o TODO: max_dist as function of cell size """ ll = len(polylines) remove = [] for n in range(ll - 1, -1, -1): c = polylines[n] if ...
0.000743
def _load_response(response): ''' Load the response from json data, return the dictionary or raw text ''' try: data = salt.utils.json.loads(response.text) except ValueError: data = response.text ret = {'code': response.status_code, 'content': data} return ret
0.003268
def _quote(self, value, multiline=True): """ Return a safely quoted version of a value. Raise a ConfigObjError if the value cannot be safely quoted. If multiline is ``True`` (default) then use triple quotes if necessary. * Don't quote values that don't need it. ...
0.003145
def close(self): """Flush the buffer and finalize the file. When this returns the new file is available for reading. """ if not self.closed: self.closed = True self._flush(finish=True) self._buffer = None
0.016736
def visit_Expr(self, node: ast.Expr) -> Optional[ast.Expr]: """Eliminate no-op constant expressions which are in the tree as standalone statements.""" if isinstance( node.value, ( ast.Constant, # type: ignore ast.Name, ast....
0.004415
def translate_z(self, d): """Translate mesh for z-direction :param float d: Amount to translate """ mat = numpy.array([ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, d, 1] ]) self.vectors = self.vectors.dot(mat) ...
0.006042
def seed(cache_dir=CACHE_DIR, product=DEFAULT_PRODUCT, bounds=None, max_download_tiles=9, **kwargs): """Seed the DEM to given bounds. :param cache_dir: Root of the DEM cache folder. :param product: DEM product choice. :param bounds: Output bounds in 'left bottom right top' order. :param max_downloa...
0.003568
def simple_moving_average(data, period): """ Simple Moving Average. Formula: SUM(data / N) """ catch_errors.check_for_period_error(data, period) # Mean of Empty Slice RuntimeWarning doesn't affect output so it is # supressed with warnings.catch_warnings(): warnings.simplefil...
0.00396
def hpss(y, **kwargs): '''Decompose an audio time series into harmonic and percussive components. This function automates the STFT->HPSS->ISTFT pipeline, and ensures that the output waveforms have equal length to the input waveform `y`. Parameters ---------- y : np.ndarray [shape=(n,)] ...
0.000628
def Magic(self): #self.view.setFixedSize(self.width(), self.width()) self.WholeData = [] self.x_scale = self.width_plot / self.width_load self.y_scale = self.height_plot / self.height_load self.z_scale = self.depth_plot / self.depth_load # print(self.x_scale,' and ...
0.007513
def write_desc(self) -> None: """ Writes a description of the model to the exp_dir. """ path = os.path.join(self.exp_dir, "model_description.txt") with open(path, "w") as desc_f: for key, val in self.__dict__.items(): print("%s=%s" % (key, val), file=desc_f) ...
0.015902
def format_output(instances, flag): """return formatted string for instance""" out = [] line_format = '{0}\t{1}\t{2}\t{3}\t{4}' name_len = _get_max_name_len(instances) + 3 if flag: line_format = '{0:<' + str(name_len) + '}{1:<16}{2:<21}{3:<16}{4:<16}' for i in instances: tag_nam...
0.003992
def pyprf_sim(strPrior, strStmApr, lgcNoise=False, lgcRtnNrl=True, lstRat=None, lgcTest=False): """ Simulate pRF response given pRF parameters and stimulus apertures. Parameters ---------- strPrior : str Absolute file path of config file used for pRF fitting. strStmApr : s...
0.000129
def add_attribute(self, attribute, value): """ Add an attribute to the current instance :param str attribute: Attribute name :type value: Union[datetime,bool,str] :param value: Attribute value """ class_name = self.__class__.__name__ if class_name.startsw...
0.004747
def remove_object(collision_object): """Remove the collision object from the Manager""" global collidable_objects if isinstance(collision_object, CollidableObj): # print "Collision object of type ", type(collision_object), " removed from the collision manager." try: ...
0.008389
def _get_qe(self, key, obj): """Instantiate a query engine, or retrieve a cached one. """ if key in self._cached: return self._cached[key] qe = create_query_engine(obj, self._class) self._cached[key] = qe return qe
0.007299
def send_vdp_query_msg(self, mode, mgrid, typeid, typeid_ver, vsiid_frmt, vsiid, filter_frmt, gid, mac, vlan, oui_id, oui_data): """Constructs and Sends the VDP Query Message. Please refer http://www.ieee802.org/1/pages/802.1bg.html VDP Sect...
0.002154
def _value__get(self): """ Get/set the value (which is the contents of this element) """ content = self.text or '' if self.tag.startswith("{%s}" % XHTML_NAMESPACE): serialisation_method = 'xml' else: serialisation_method = 'html' for el in ...
0.003745
def future_add_done_callback( # noqa: F811 future: "Union[futures.Future[_T], Future[_T]]", callback: Callable[..., None] ) -> None: """Arrange to call ``callback`` when ``future`` is complete. ``callback`` is invoked with one argument, the ``future``. If ``future`` is already done, ``callback`` is i...
0.003448
def _format_options_usage(options): """ Format the Options-part of the usage text. Parameters ---------- options : list[sacred.commandline_options.CommandLineOption] A list of all supported commandline options. Returns ------- str Text formatted as a des...
0.000911
def add_usable_app(name, app): 'Add app to local registry by name' name = slugify(name) global usable_apps # pylint: disable=global-statement usable_apps[name] = app return name
0.010152
def CheckTaskReadyForMerge(self, task): """Checks if a task is ready for merging with this session storage. If the task is ready to be merged, this method also sets the task's storage file size. Args: task (Task): task. Returns: bool: True if the task is ready to be merged. Raise...
0.005092
def place_objects(self): """Places objects randomly until no collisions or max iterations hit.""" pos_arr, quat_arr = self.initializer.sample() for k, obj_name in enumerate(self.objects): self.objects[obj_name].set("pos", array_to_string(pos_arr[k])) self.objects[obj_name...
0.008264
def create(cls, jar): """Creates an actual M2Coordinate from the given M2Coordinate-like object (eg a JarDependency). :API: public :param JarDependency jar: the input coordinate. :return: A new M2Coordinate, unless the input is already an M2Coordinate in which case it just returns the input unch...
0.00998
def update(self, value): """Update the mean and variance estimates. Args: value: Batch or single value tensor. Returns: Summary tensor. """ with tf.name_scope(self._name + '/update'): if value.shape.ndims == self._mean.shape.ndims: # Add a batch dimension if necessary. ...
0.005917
def get_or_create(self, login): """ Get the qid of the item by its external id or create if doesn't exist :param login: WDLogin item :return: tuple of (qid, list of warnings (strings), success (True if success, returns the Exception otherwise)) """ if self.p: ...
0.005906
def load_file(self, currency_file): """To be subclassed if alternate methods of loading data. """ if currency_file.startswith(('http://', 'https://')): content = urlopen(currency_file).read() else: with open(currency_file, 'rb') as f: content = f.r...
0.003953
def cmd_alias(args): '''alias commands''' usage = "usage: alias <add|remove|list>" if len(args) < 1 or args[0] == "list": if len(args) >= 2: wildcard = args[1].upper() else: wildcard = '*' for a in sorted(mpstate.aliases.keys()): if fnmatch.fnmatch...
0.00117
def url(self): ''' Executes the methods to send request, process the response and then publishes the url. ''' self.get_response() url = self.process_response() if url: logging.info('Your paste has been published at %s' %(url)) return url ...
0.006652
def all_conditional_solidity_variables_read(self, include_loop=True): """ Return the Soldiity variables directly used in a condtion Use of the IR to filter index access Assumption: the solidity vars are used directly in the conditional node It won't work if the v...
0.005151
def read1(self, size=-1): """Read up to *size* bytes. This function reads from the buffer only once. It is useful in case you need to read a large input, and want to do so efficiently. If *size* is big enough, then this method will return the chunks passed into the memory buffer...
0.003361
def matchBytes(self, bytes): """Look for a sequence of bytes at the start of a string. If the bytes are found return True and advance the position to the byte after the match. Otherwise return False and leave the position alone""" p = self.position data = self[p:p + len(bytes)] ...
0.004684
def ingest(self, text, log_message=None): """ Ingest a new object into Fedora. Returns the pid of the new object on success. Calls :meth:`ApiFacade.ingest`. :param text: full text content of the object to be ingested :param log_message: optional log message :rtype: stri...
0.003891
def setup_args(parser, config_files=[], ignore_unknown=False): """Parses arguments.""" global args arglist = sys.argv[1:] # Load arguments from config files for config_file in filter(os.path.isfile, config_files): arglist.insert(0, "@" + config_file) args, unknown = parser.parse_known_...
0.001458
def list_pubs(self, buf): """SSH v2 public keys are serialized and returned.""" assert not buf.read() keys = self.conn.parse_public_keys() code = util.pack('B', msg_code('SSH2_AGENT_IDENTITIES_ANSWER')) num = util.pack('L', len(keys)) log.debug('available keys: %s', [k['n...
0.003604
def remove(self): ''' Remove this environment ''' self.run_hook('preremove') utils.rmtree(self.path) self.run_hook('postremove')
0.011364
def evaluate_call_args(self, calculator): """Interpreting this literal as a function call, return a 2-tuple of ``(args, kwargs)``. """ args = [] kwargs = OrderedDict() # Sass kwargs preserve order for var_node, value_node in self.argpairs: value = value_node....
0.002262
def remove_non_magic_cols(self): """ Remove all non-MagIC columns from all tables. """ for table_name in self.tables: table = self.tables[table_name] table.remove_non_magic_cols_from_table()
0.00813
def insertIndividual(self, individual): """ Inserts the specified individual into this repository. """ try: models.Individual.create( id=individual.getId(), datasetId=individual.getParentContainer().getId(), name=individual.getL...
0.002361
def local_targets(self): """Iterator over the targets defined in this build file.""" for node in self.node: if (node.repo, node.path) == (self.target.repo, self.target.path): yield node
0.008734
def armor(data, versioned=True): """ Returns a string in ASCII Armor format, for the given binary data. The output of this is compatiple with pgcrypto's armor/dearmor functions. """ template = '-----BEGIN PGP MESSAGE-----\n%(headers)s%(body)s\n=%(crc)s\n-----END PGP MESSAGE-----' body = base64.b...
0.005755
def main(api_key, token): """List out the boards for our client""" trello_client = TrelloClient( api_key=api_key, token=token, ) print('Boards') print('-----') print('Name: Id') for board in trello_client.list_boards(): print('{board.name}: {board.id}'.format(board=bo...
0.003077
def prefix(expof10): ''' Args: expof10 : Exponent of a power of 10 associated with a SI unit character. Returns: str : One of the characters in "yzafpnum kMGTPEZY". ''' prefix_levels = (len(SI_PREFIX_UNITS) - 1) // 2 si_level = expof10 // 3 if abs(si_level) > ...
0.002188
def handle_time(msg): """Process an internal time request message.""" return msg.copy(ack=0, payload=calendar.timegm(time.localtime()))
0.006993
def best_buy_1(self): """量大收紅 """ result = self.data.capacity[-1] > self.data.capacity[-2] and \ self.data.price[-1] > self.data.open[-1] return result
0.015
def _vcf_info(start, end, mate_id, info=None): """Return breakend information line with mate and imprecise location. """ out = "SVTYPE=BND;MATEID={mate};IMPRECISE;CIPOS=0,{size}".format( mate=mate_id, size=end-start) if info is not None: extra_info = ";".join("{0}={1}".format(k, v) for k...
0.004914
def start(cls, ev=None): """ Start the query to aleph by ISSN. """ ViewController.log_view.add("Beginning AlephReader request..") ViewController.issnbox_error.reset() issn = ViewController.issn.strip() # make sure, that `issn` was filled if not issn: ...
0.002372
def extract_rzip (archive, compression, cmd, verbosity, interactive, outdir): """Extract an RZIP archive.""" cmdlist = [cmd, '-d', '-k'] if verbosity > 1: cmdlist.append('-v') outfile = util.get_single_outfile(outdir, archive) cmdlist.extend(["-o", outfile, archive]) return cmdlist
0.006369
def Parse(self, stat, file_object, knowledge_base): """Parse the History file.""" _, _ = stat, knowledge_base # TODO(user): Convert this to use the far more intelligent plaso parser. ff = Firefox3History(file_object) for timestamp, unused_entry_type, url, title in ff.Parse(): yield rdf_webhist...
0.00369
def find_covalent_bonds(ampal, max_range=2.2, threshold=1.1, tag=True): """Finds all covalent bonds in the AMPAL object. Parameters ---------- ampal : AMPAL Object Any AMPAL object with a `get_atoms` method. max_range : float, optional Used to define the sector size, so interactions...
0.005483
def turn_on(self, time): """(Helper) Turn on an output""" self._elk.send(cn_encode(self._index, time))
0.016949
def build(self): """Generate a TermDocMatrix from data in parameters. Returns ---------- term_doc_matrix : TermDocMatrix The object that this factory class builds. """ if self._category_text_iter is None: raise CategoryTextIterNotSetError() ...
0.00246
def show(self): """Publish HTML.""" IPython.display.display(IPython.display.HTML(self.as_html()))
0.017699
def _getSerialTimeout(self, device): """ Get the serial timeout stored on the hardware device. Caution, more that one value returned from the Qik can have the same actual timeout value according the the formula below. I have verified this as an idiosyncrasy of the Qik itself. Th...
0.002041
def subgraph(self, nodes): """ Return the subgraph consisting of the given nodes and edges between thses nodes. Parameters ---------- nodes : array_like(int, ndim=1) Array of node indices. Returns ------- DiGraph A DiGraph ...
0.00295
def hmac_hex_key(self, hmac_hex_key): """ Sets the hmac_hex_key of this CfsslAuthCredentials. The key that is used to compute the HMAC of the request using the HMAC-SHA-256 algorithm. Must contain an even number of hexadecimal characters. :param hmac_hex_key: The hmac_hex_key of this C...
0.00843
def start(self): ''' Startup the kafka consumer. ''' log.debug('Creating the consumer using the bootstrap servers: %s and the group ID: %s', self.bootstrap_servers, self.group_id) try: self.consumer = kafka.KafkaConsumer(bootstrap_s...
0.005935
def homogenize(series_dict): """ Conform a set of SparseSeries (with NaN fill_value) to a common SparseIndex corresponding to the locations where they all have data Parameters ---------- series_dict : dict or DataFrame Notes ----- Using the dumbest algorithm I could think of. Shoul...
0.000892
def summary(self, campaign_id=None): """ Returns the campaign summary """ resource_cls = CampaignSummary single_resource = False if not campaign_id: resource_cls = CampaignSummaries single_resource = True return super(API, self).get( resource...
0.004357
def RandomNormalInitializer(stddev=1e-2): """An initializer function for random normal coefficients.""" def init(shape, rng): return (stddev * backend.random.normal(rng, shape)).astype('float32') return init
0.018433
def _parse(self, root, line, idx): """ :param root: Tree node. :param line: String to parse. :param idx: Global counter of characters parsed. :return: (list of parsed graphemes, incremented character count) """ # Base (or degenerate..) case. if len(line) =...
0.002086
def recognize(mol): """ Detect cycle basis, biconnected and isolated components (DFS). This will add following attribute to the molecule instance object. mol.ring: Cycle basis mol.scaffold: biconnected components mol.isolated: isolated components other than the largest one To find minimum set ...
0.000429
def ksum(p, K=2): """From T. Ogita, S.M. Rump, and S. Oishi. Accurate Sum and Dot Product, SIAM J. Sci. Comput., 26(6), 1955–1988 (34 pages). <https://doi.org/10.1137/030601818>. Algorithm 4.8. Summation as in K-fold precision by (K−1)-fold error-free vector transformation. """ # D...
0.002309
def add_postfix(file_path, postfix): # type: (AnyStr, AnyStr) -> AnyStr """Add postfix for a full file path. Examples: >>> FileClass.add_postfix('/home/zhulj/dem.tif', 'filled') '/home/zhulj/dem_filled.tif' >>> FileClass.add_postfix('dem.tif', 'filled') ...
0.004128
def check(self, src_tgt, actual_deps): """Check for missing deps. See docstring for _compute_missing_deps for details. """ if self._check_missing_direct_deps or self._check_unnecessary_deps: missing_file_deps, missing_direct_tgt_deps = \ self._compute_missing_deps(src_tgt, actual_deps) ...
0.010797
def refitPrefixes(self): """ Refit namespace qualification by replacing prefixes with explicit namespaces. Also purges prefix mapping table. @return: self @rtype: L{Element} """ for c in self.children: c.refitPrefixes() if self.prefix is not No...
0.003868
def allhexlify(data): """Hexlify given data into a string representation with hex values for all chars Input like 'ab\x04ce' becomes '\x61\x62\x04\x63\x65' """ hx = binascii.hexlify(data) return b''.join([b'\\x' + o for o in re.findall(b'..', hx)])
0.006944
def on_pause(self): """Sync the database with the current state of the game.""" self.engine.commit() self.strings.save() self.funcs.save() self.config.write()
0.010101
def _get_cythonized_result(self, how, grouper, aggregate=False, cython_dtype=None, needs_values=False, needs_mask=False, needs_ngroups=False, result_is_index=False, pre_processing=None, post_proce...
0.001588
def fix_code(code, directory): """Formats Python code to conform to the PEP 8 style guide. """ if not black: raise Fault("black not installed", code=400) try: if parse_version(black.__version__) < parse_version("19.0"): reformatted_source = black.format_file_contents( ...
0.002577
def _set_dag_run_state(dag_id, execution_date, state, session=None): """ Helper method that set dag run state in the DB. :param dag_id: dag_id of target dag run :param execution_date: the execution date from which to start looking :param state: target state :param session: database session "...
0.001536
def _parse_line(cls, line): """ Helper method for parsing package line with or without SOS report information. Args: line (str): package line with or without SOS report information Returns: dict: dictionary containing 'name', 'version', 'release' and 'arch' keys...
0.00609
def view(self, repo): """ View repository information """ status = "{0}disabled{1}".format(self.meta.color["RED"], self.meta.color["ENDC"]) self.form["Status:"] = status self.form["Default:"] = "no" if repo in self.meta.def...
0.00151
def checkPrediction2(self, patternNZs, output=None, confidence=None, details=False): """ This function will replace checkPrediction. This function produces goodness-of-match scores for a set of input patterns, by checking for their presense in the current and predicted output of ...
0.00875
def has_na(eqdata): """ Return false if `eqdata` contains no missing values. Parameters ---------- eqdata : DataFrame or ndarray Data to check for missing values (NaN, None) Returns ---------- answer : bool False iff `eqdata` contains no missing values. """ if i...
0.002141
def start(self): """ Start the node on the cloud using the given instance properties. This method is non-blocking: as soon as the node id is returned from the cloud provider, it will return. The `is_alive`:meth: and `update_ips`:meth: methods should be used to further gather det...
0.003161
def add(self, child, name=None, coordinates=None): """ Adds child to the :Placeable:, storing it's :name: and :coordinates: This method is used to add :Well:s to the :Container:, add :Slot:s to :Deck:, etc """ if not name: name = str(child) if name i...
0.002933
def _add_defaults_python(self): """getting python files""" if self.distribution.has_pure_modules(): build_py = self.get_finalized_command('build_py') self.filelist.extend(build_py.get_source_files()) # This functionality is incompatible with include_package_data, and ...
0.002451
def _get_jsmap_name(self, url): """return 'name' of the map in .js format""" ret = urlopen(url) return ret.read().decode('utf-8').split('=')[0].replace(" ", "")
0.015544
def error(self, table_name, key, error_message, error_stack=None): """ Log an error message. The job reservation is replaced with an error entry. if an error occurs, leave an entry describing the problem :param table_name: `database`.`table_name` :param key: the dict of the job'...
0.003673
def clear(self): """Remove all sources from this configuration.""" super(LazyConfig, self).clear() self._lazy_suffix = [] self._lazy_prefix = []
0.011364