text
stringlengths
78
104k
score
float64
0
0.18
def _parse_dependencies(string): """ This function actually parses the dependencies are sorts them into the buildable and given dependencies """ contents = _get_contents_between(string, '(', ')') unsorted_dependencies = contents.split(',') _check_parameters(unsorted_dependencies, ('?',)) ...
0.001462
def _pressModifiers(self, modifiers, pressed=True, globally=False): """Press given modifiers (provided in list form). Parameters: modifiers list, global or app specific Optional: keypressed state (default is True (down)) Returns: Unsigned int representing flags to set """ ...
0.002625
def build_parameters_error(cls, errors=None): """Utility method to build a HTTP 400 Parameter Error response""" errors = [errors] if not isinstance(errors, list) else errors return cls(Status.PARAMETERS_ERROR, errors)
0.008299
def slamdunkTcPerUTRPosPlot (self): """ Generate the tc per UTR pos plots """ pconfig_nontc = { 'id': 'slamdunk_slamdunk_nontcperutrpos_plot', 'title': 'Slamdunk: Non-T>C mutations over 3\' UTR ends', 'ylab': 'Percent mismatches %', 'xlab': 'Position in t...
0.013333
def impad(img, shape, pad_val=0): """Pad an image to a certain shape. Args: img (ndarray): Image to be padded. shape (tuple): Expected padding shape. pad_val (number or sequence): Values to be filled in padding areas. Returns: ndarray: The padded image. """ if not i...
0.001385
def _add_instruction(self, instruction, value): """ :param instruction: instruction name to be added :param value: instruction value """ if (instruction == 'LABEL' or instruction == 'ENV') and len(value) == 2: new_line = instruction + ' ' + '='.join(map(quote, value))...
0.00487
def longest_common_substring_similarity(s1, s2, norm='dice', min_len=2): """ longest_common_substring_similarity(s1, s2, norm='dice', min_len=2) An implementation of the longest common substring similarity algorithm described in Christen, Peter (2012). Parameters ---------- s1 : label, pan...
0.000153
def print_commandless_help(self): """ print_commandless_help """ doc_help = self.m_doc.strip().split("\n") if len(doc_help) > 0: print("\033[33m--\033[0m") print("\033[34m" + doc_help[0] + "\033[0m") asp = "author :" doc_help_rest...
0.002169
def get_mimetype(path): """ Guesses the mime type of a file. If mime type cannot be detected, plain text is assumed. :param path: path of the file :return: the corresponding mime type. """ filename = os.path.split(path)[1] mimetype = mimetypes.guess_type(...
0.004149
def write_file(filename, contents): """Create a file with the specified name and write 'contents' (a sequence of strings without line terminators) to it. """ contents = "\n".join(contents) # assuming the contents has been vetted for utf-8 encoding contents = contents.encode("utf-8") with o...
0.002451
def save_image(figure, filename): """Save an image to the docs images directory. Args: filename (str): The name of the file (not containing directory info). """ path = os.path.join(IMAGES_DIR, filename) figure.savefig(path, bbox_inches="tight") plt.close(figure)
0.003257
def print_file_results(file_result): """Print the results of validating a file. Args: file_result: A FileValidationResults instance. """ print_results_header(file_result.filepath, file_result.is_valid) for object_result in file_result.object_results: if object_result.warnings: ...
0.00189
def get_installed_extensions(self, contribution_ids=None, include_disabled_apps=None, asset_types=None): """GetInstalledExtensions. [Preview API] :param [str] contribution_ids: :param bool include_disabled_apps: :param [str] asset_types: :rtype: [InstalledExtension] ...
0.006255
def raster_weights(self, **kwargs): """ Compute neighbor weights for GeoRaster. See help(gr.raster_weights) for options Usage: geo.raster_weights(rook=True) """ if self.weights is None: self.weights = raster_weights(self.raster, **kwargs) pass
0.00625
def one_or_more( schema: dict, unique_items: bool = True, min: int = 1, max: int = None ) -> dict: """ Helper function to construct a schema that validates items matching `schema` or an array containing items matching `schema`. :param schema: The schema to use :param unique_items: Flag if array...
0.001359
def save_jsonf(data: Union[list, dict], fpath: str, encoding: str, indent=None) -> str: """ :param data: list | dict data :param fpath: write path :param encoding: encoding :param indent: :rtype: written path """ with codecs.open(fpath, mode='w', encoding=encoding) as f: f.write(...
0.005479
def connect(src, *destinations, exclude: set=None, fit=False): """ Connect src (signals/interfaces/values) to all destinations :param exclude: interfaces on any level on src or destinations which should be excluded from connection process :param fit: auto fit source width to destination width ...
0.003699
def parse_cookies(self, req: Request, name: str, field: Field) -> typing.Any: """Pull a value from the cookiejar.""" return core.get_value(req.cookies, name, field)
0.011111
def close(self): """shut down the pool's workers this method sets the :attr:`closing` attribute, lines up the :attr:`closed` attribute to be set once any queued data has been processed, and raises a PoolClosed() exception in any coroutines still blocked on :meth:`get`. "...
0.004246
def __search_email_by_subject(self, subject, match_recipient): "Get a list of message numbers" if match_recipient is None: _, data = self._mail.uid('search', None, '(HEADER SUBJECT "{subject}")' ...
0.00495
def copy(self): ''' copy - Create a copy of this IRField. Each subclass should implement this, as you'll need to pass in the args to constructor. @return <IRField (or subclass)> - Another IRField that has all the same values as this one. ''' return self.__class__(name=self.name, valueType=self.valueT...
0.031414
def _decoderFromString(cfg): """ Return a decoder function. If cfg is a string such as 'latin-1' or u'latin-1', then we return a new lambda, s.decode(). If cfg is already a lambda or function, then we return that. """ if isinstance(cfg, (bytes, str)): ...
0.005263
def split(self, point=None): """ Split this read into two halves. Original sequence is left unaltered. The name of the resultant reads will have '.1' and '.2' appended to the name from the original read. :param point: the point (index, starting from 0) at which to split this read...
0.002683
def add_includes(self, includes): # type: (_BaseSourcePaths, list) -> None """Add a list of includes :param _BaseSourcePaths self: this :param list includes: list of includes """ if not isinstance(includes, list): if isinstance(includes, tuple): ...
0.002863
def installedApp(self): """identify the propery application to launch, given the configuration""" try: return self._installedApp except: # raises if not yet defined self._installedApp = runConfigs.get() # application/install/platform management return self._installedAp...
0.028037
def build_error_handler_for_flask_restplus(*tasks): """ Provides a generic error function that packages a flask_buzz exception so that it can be handled by the flask-restplus error handler:: @api.errorhandler(SFBDError) def do_it(error): return SFBDError....
0.00163
def _parse_makefile(filename, vars=None): """Parse a Makefile-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ # Regexes needed for parsing Makefile (and similar syntaxes...
0.001511
def counter(self, key, delta=1, initial=None, ttl=0): """Increment or decrement the numeric value of an item. This method instructs the server to treat the item stored under the given key as a numeric counter. Counter operations require that the stored value exists as a string ...
0.000877
def app_start_up_time(self, package: str) -> str: '''Get the time it took to launch your application.''' output, _ = self._execute( '-s', self.device_sn, 'shell', 'am', 'start', '-W', package) return re.findall('TotalTime: \d+', output)[0]
0.010909
def simple_name_generator(obj): """ Simple name_generator designed for HoloViews objects. Objects are labeled with {group}-{label} for each nested object, based on a depth-first search. Adjacent objects with identical representations yield only a single copy of the representation, to avoid lon...
0.006859
def discover(source): "Given a JavaScript file, find the sourceMappingURL line" source = source.splitlines() # Source maps are only going to exist at either the top or bottom of the document. # Technically, there isn't anything indicating *where* it should exist, so we # are generous and assume it's...
0.005675
def get_instance(self, payload): """ Build an instance of VerificationCheckInstance :param dict payload: Payload response from the API :returns: twilio.rest.preview.acc_security.service.verification_check.VerificationCheckInstance :rtype: twilio.rest.preview.acc_security.servic...
0.010246
def createStatus(self, repo_user, repo_name, sha, state, target_url=None, description=None, context=None): """ :param sha: Full sha to create the status for. :param state: one of the following 'pending', 'success', 'error' or 'failure'. :para...
0.004278
def _read_tags(self): """ Fill in the _tags dict from the tags file. Args: None Returns: True Todo: Figure what could go wrong and at least acknowledge the the fact that Murphy was an optimist. """ tags = self._co...
0.002677
def create_community(self, token, name, **kwargs): """ Create a new community or update an existing one using the uuid. :param token: A valid token for the user in question. :type token: string :param name: The community name. :type name: string :param descriptio...
0.001453
def copy(self): """ :rtype: Return a copy of the hypercube """ return HyperCube( dimensions=self.dimensions(copy=False), arrays=self.arrays(), properties=self.properties())
0.008929
def searchsorted(self, value, side='left', sorter=None): """ Find indices where elements should be inserted to maintain order. Find the indices into a sorted array `self` such that, if the corresponding elements in `value` were inserted before the indices, the order of `self` wo...
0.001234
def gen_decode(iterable): "A generator for de-unsynchronizing a byte iterable." sync = False for b in iterable: if sync and b & 0xE0: warn("Invalid unsynched data", Warning) if not (sync and b == 0x00): yield b sync = (b == 0xFF...
0.006231
def _parse_pages_binding(details): """ Parse number of pages and binding of the book. Args: details (obj): HTMLElement containing slice of the page with details. Returns: (pages, binding): Tuple with two string or two None. """ pages = _get_td_or_none( details, ...
0.001481
def unserialize(self, msg_list, content=True, copy=True): """Unserialize a msg_list to a nested message dict. This is roughly the inverse of serialize. The serialize/unserialize methods work with full message lists, whereas pack/unpack work with the individual message parts in the messa...
0.002775
def present(name, save=False, **kwargs): ''' Ensure beacon is configured with the included beacon data. Args: name (str): The name of the beacon ensure is configured. save (bool): ``True`` updates the beacons.conf. Default is ``False``. ...
0.001483
def set_vm_status(self, boot_on_next_reset): """Set the Virtual Media drive status. :param boot_on_next_reset: boolean value :raises: SushyError, on an error from iLO. """ data = { "Oem": { "Hpe": { "BootOnNextServerReset": boot_on...
0.00463
def get_file_type_map(): """Map file types (extensions) to strategy types.""" file_type_map = {} for strategy_type in get_strategy_types(): for ext in strategy_type.file_types: if ext in file_type_map: raise KeyError( 'File type {ext} already registere...
0.004357
def apply(db, op): """ Apply operation in db """ dbname = op['ns'].split('.')[0] or "admin" opts = bson.CodecOptions(uuid_representation=bson.binary.STANDARD) db[dbname].command("applyOps", [op], codec_options=opts)
0.004184
def get_not_unique_values(array): '''Returns the values that appear at least twice in array. Parameters ---------- array : array like Returns ------- numpy.array ''' s = np.sort(array, axis=None) s = s[s[1:] == s[:-1]] return np.unique(s)
0.003521
def _convert_response_to_error(self, response): """Subclasses may override this method in order to influence how errors are parsed from the response. Parameters: response(Response): The response object. Returns: object or None: Any object for which a max retry count...
0.001639
def onset_precision_recall_f1(ref_intervals, est_intervals, onset_tolerance=0.05, strict=False, beta=1.0): """Compute the Precision, Recall and F-measure of note onsets: an estimated onset is considered correct if it is within +-50ms of a reference onset. Note that this metric ...
0.000386
def wrap(self, value): """Wrap numpy.ndarray as Value """ attrib = getattr(value, 'attrib', {}) S, NS = divmod(time.time(), 1.0) value = numpy.asarray(value) # loses any special/augmented attributes dims = list(value.shape) dims.reverse() # inner-most sent as lef...
0.00869
def call_api(self, table, column, value, **kwargs): """Exposed method to connect and query the EPA's API.""" try: output_format = kwargs.pop('output_format') except KeyError: output_format = self.output_format url_list = [self.base_url, table, column, ...
0.003328
def get_slac_default_args(job_time=1500): """ Create a batch job interface object. Parameters ---------- job_time : int Expected max length of the job, in seconds. This is used to select the batch queue and set the job_check_sleep parameter that sets how often we check ...
0.00135
def indicator_body(indicators): """Generate the appropriate dictionary content for POST of an File indicator Args: indicators (list): A list of one or more hash value(s). """ hash_patterns = { 'md5': re.compile(r'^([a-fA-F\d]{32})$'), 'sha1': re.compi...
0.003559
def rotate_clip(data_np, theta_deg, rotctr_x=None, rotctr_y=None, out=None, use_opencl=True, logger=None): """ Rotate numpy array `data_np` by `theta_deg` around rotation center (rotctr_x, rotctr_y). If the rotation center is omitted it defaults to the center of the array. No adjus...
0.000826
def _solve_implicit_banded(current, banded_matrix): """Uses a banded solver for matrix inversion of a tridiagonal matrix. Converts the complete listed tridiagonal matrix *(nxn)* into a three row matrix *(3xn)* and calls :py:func:`scipy.linalg.solve_banded()`. :param array current: the curren...
0.002985
def _get_migration_files(self, path): """ Get all of the migration files in a given path. :type path: str :rtype: list """ files = glob.glob(os.path.join(path, "[0-9]*_*.py")) if not files: return [] files = list(map(lambda f: os.path.basen...
0.007371
def clear_symbols(self, index): """Clears all symbols begining with the index to the end of table""" try: del self.table[index:] except Exception: self.error() self.table_len = len(self.table)
0.007874
def read(self, size=None): """Read data from the file. """ if size is None: size = self.size - self.position else: size = min(size, self.size - self.position) buf = b"" while size > 0: while True: data, start, stop, off...
0.002188
def validate_root_vertex_directives(root_ast): """Validate the directives that appear at the root vertex field.""" directives_present_at_root = set() for directive_obj in root_ast.directives: directive_name = directive_obj.name.value if is_filter_with_outer_scope_vertex_field_operator(direc...
0.005747
def lb2pix(nside, l, b, nest=True): """ Converts Galactic (l, b) to HEALPix pixel index. Args: nside (:obj:`int`): The HEALPix :obj:`nside` parameter. l (:obj:`float`, or array of :obj:`float`): Galactic longitude, in degrees. b (:obj:`float`, or array of :obj:`float`): Galactic lat...
0.005576
def verify(self): """Checks all parameters for invalidating conditions :returns: str -- message if error, 0 otherwise """ for row in range(self.nrows()): result = self.verify_row(row) if result != 0: return result return 0
0.006601
def next_tokens_in_sequence(observed, current): """ Given the observed list of tokens, and the current list, finds out what should be next next emitted word """ idx = 0 for word in current: if observed[idx:].count(word) != 0: found_pos = observed.index(word, idx) idx ...
0.002119
def branches(self): """Get basic block branches. """ branches = [] if self._taken_branch: branches += [(self._taken_branch, 'taken')] if self._not_taken_branch: branches += [(self._not_taken_branch, 'not-taken')] if self._direct_branch: ...
0.005076
def percent_pareto_recharges(recharges, percentage=0.8): """ Percentage of recharges that account for 80% of total recharged amount. """ amounts = sorted([r.amount for r in recharges], reverse=True) total_sum = sum(amounts) partial_sum = 0 for count, a in enumerate(amounts): partial...
0.002283
def xyz_with_ports(self): """Return all particle coordinates in this compound including ports. Returns ------- pos : np.ndarray, shape=(n, 3), dtype=float Array with the positions of all particles and ports. """ if not self.children: pos = self._...
0.00335
def extract_thermodynamic_quantities(self,temperature_array): """ Calculates the thermodynamic quantities of your system at each point in time. Calculated Quantities: self.Q (heat),self.W (work), self.Delta_E_kin, self.Delta_E_pot self.Delta_E (change of Hamiltonian), Parame...
0.009986
def record(self): # type: () -> bytes ''' Generate a string representing the Rock Ridge Extension Selector record. Parameters: None. Returns: String containing the Rock Ridge record. ''' if not self._initialized: raise pycdlibexcepti...
0.012371
def connection_lost(self, exception): """Called when the connection is lost or closed. The argument is either an exception object or None. The latter means a regular EOF is received, or the connection was aborted or closed by this side of the connection. """ if exception...
0.004577
def record_timing(self, duration, *path): """Record a timing. This method records a timing to the application's namespace followed by a calculated path. Each element of `path` is converted to a string and normalized before joining the elements by periods. The normalization pro...
0.003431
def localize(self): """ Check if this module was saved as a resource. If it was, return a new module descriptor that points to a local copy of that resource. Should only be called on a worker node. On the leader, this method returns this resource, i.e. self. :rtype: toil.resourc...
0.005357
def add_statement(self, statement_obj): """ Adds a statement object to the layer @type statement_obj: L{Cstatement} @param statement_obj: the statement object """ if statement_obj.get_id() in self.idx: raise ValueError("Statement with id {} already exists!" ...
0.004107
def create(self, request, *args, **kwargs): """HACK: couldn't get POST to the list endpoint without messing up POST for the other list_routes so I'm doing this. Maybe something to do with the router? """ return self.list(request, *args, **kwargs)
0.006993
def status(self, additional=[]): """ Returns status information for device. This returns only a subset of possible properties. """ self.manager.refresh_client() fields = ['batteryLevel', 'deviceDisplayName', 'deviceStatus', 'name'] fields += additional properties...
0.004587
def create_guest(self, capacity_id, test, guest_object): """Turns an empty Reserve Capacity into a real Virtual Guest :param int capacity_id: ID of the RESERVED_CAPACITY_GROUP to create this guest into :param bool test: True will use verifyOrder, False will use placeOrder :param diction...
0.004828
def _enumerator(opener, entry_cls, format_code=None, filter_code=None): """Return an archive enumerator from a user-defined source, using a user- defined entry type. """ archive_res = _archive_read_new() try: r = _set_read_context(archive_res, format_code, filter_code) opener(archi...
0.001282
def updateAccuracy(self, *accuracy): """ Updates current accuracy flag """ for acc in accuracy: if not isinstance(acc, int): acc = self._ACCURACY_REVERSE_MAPPING[acc] self.accuracy |= acc
0.007722
def _tensor_product(self, other, reverse=False): """Return the tensor product channel. Args: other (QuantumChannel): a quantum channel. reverse (bool): If False return self ⊗ other, if True return if True return (other ⊗ self) [Default: False ...
0.001522
def init_defaults(self): """ Sets the default values for this instance """ self.sql = '' self.tables = [] self.joins = [] self._where = Where() self.groups = [] self.sorters = [] self._limit = None self.table_prefix = '' sel...
0.003846
def _AcceptRPC(self): """Reads RPC request from stdin and processes it, writing result to stdout. Returns: True as long as execution is to be continued, False otherwise. Raises: RpcException: if no function was specified in the RPC or no such API function exists. """ request =...
0.007062
def check_html_warnings(html, parser=None): """Check html warnings :param html: str: raw html text :param parser: bs4.BeautifulSoup: html parser :raise VkPageWarningsError: in case of found warnings """ if parser is None: parser = bs4.BeautifulSoup(html, 'html.parser') # Check warn...
0.001969
def get_first_category(app_uid): ''' Get the first, as the uniqe category of post. ''' recs = MPost2Catalog.query_by_entity_uid(app_uid).objects() if recs.count() > 0: return recs.get() return None
0.007752
def from_text(text): """Convert text into a DNS rdata type value. @param text: the text @type text: string @raises dns.rdatatype.UnknownRdatatype: the type is unknown @raises ValueError: the rdata type value is not >= 0 and <= 65535 @rtype: int""" value = _by_text.get(text.upper()) if v...
0.003295
def addDeviceNames(self, remote): """ If XML-API (http://www.homematic-inside.de/software/addons/item/xmlapi) is installed on CCU this function will add names to CCU devices """ LOG.debug("RPCFunctions.addDeviceNames") # First try to get names from metadata when nur credentials are set ...
0.003389
def find_ref_centers(mds): """Finds the center of the three reference clusters. :param mds: the ``mds`` information about each samples. :type mds: numpy.recarray :returns: a tuple with a :py:class:`numpy.array` containing the centers of the three reference population cluster as first el...
0.000796
def get_available_fields(self, obj): """ Get a list of all available fields for an object. :param obj: The name of the Salesforce object that we are getting a description of. :type obj: str :return: the names of the fields. :rtype: list of str """ self.ge...
0.006637
def load(cls, fp, **kwargs): """wrapper for :py:func:`json.load`""" json_obj = json.load(fp, **kwargs) return parse(cls, json_obj)
0.007042
def chat(self): """ Access the Chat Twilio Domain :returns: Chat Twilio Domain :rtype: twilio.rest.chat.Chat """ if self._chat is None: from twilio.rest.chat import Chat self._chat = Chat(self) return self._chat
0.006849
def encodeLength(value): ''' Encodes value into a multibyte sequence defined by MQTT protocol. Used to encode packet length fields. ''' encoded = bytearray() while True: digit = value % 128 value //= 128 if value > 0: digit |= 128 encoded.append(digit)...
0.002632
def T(self, T): """ Set the temperature of the package to the specified value, and recalculate it's enthalpy. :param T: Temperature. [°C] """ self._T = T self._H = self._calculate_H(T)
0.008264
def drawPolyline(self, points): """Draw several connected line segments. """ for i, p in enumerate(points): if i == 0: if not (self.lastPoint == Point(p)): self.draw_cont += "%g %g m\n" % JM_TUPLE(Point(p) * self.ipctm) self.las...
0.005556
def set_client_certificate(self, certificate): '''Sets client certificate for the request. ''' _certificate = BSTR(certificate) _WinHttpRequest._SetClientCertificate(self, _certificate)
0.009569
def exception_message(): """Create a message with details on the exception.""" exc_type, exc_value, exc_tb = exc_info = sys.exc_info() return {'exception': {'type': exc_type, 'value': exc_value, 'traceback': exc_tb}, 'traceback': traceback.form...
0.002907
def to_polygon(self): """ Generate a polygon from the line string points. Returns ------- imgaug.augmentables.polys.Polygon Polygon with the same corner points as the line string. Note that the polygon might be invalid, e.g. contain less than 3 ...
0.004367
def build(self): '''Builds Depoyed Classifier ''' if self._clf is None: raise NeedToTrainExceptionBeforeDeployingException() return DeployedClassifier(self._category, self._term_doc_matrix._category_idx_store, self._term_doc_matrix._term_idx_store, ...
0.034759
def get_all_security_groups(self, groupnames=None, group_ids=None, filters=None): """ Get all security groups associated with your account in a region. :type groupnames: list :param groupnames: A list of the names of security groups to retrieve. ...
0.001807
def _create_index_files(root_dir, force_no_processing=False): """ Crawl the root directory downwards, generating an index HTML file in each directory on the way down. @param {String} root_dir - The top level directory to crawl down from. In normal usage, this will be '.'. @param {Boolean=Fal...
0.001389
def dict_to_etree(source, root_tag=None): """ Recursively load dict/list representation of an XML tree into an etree representation. Args: source -- A dictionary representing an XML document where identical children tags are countained in a list. Keyword args: ...
0.003571
def get_balance(): """ Get the latest balance(s) for a single User. Currently no search parameters are supported. All balances returned. --- responses: '200': description: the User's balance(s) schema: items: $ref: '#/definitions/Balance' type: a...
0.001185
def disasm_app(_parser, cmd, args): # pragma: no cover """ Disassemble code from commandline or stdin. """ parser = argparse.ArgumentParser( prog=_parser.prog, description=_parser.description, ) parser.add_argument('code', help='the code to disassemble, read from stdin if omitt...
0.002755
def clean(self): """ Cleans the data and throws ValidationError on failure """ errors = {} cleaned = {} for name, validator in self.validate_schema.items(): val = getattr(self, name, None) try: cleaned[name] = validator.to_python(val) ...
0.004073
def enhance(self): """ Function enhance Enhance the object with new item or enhanced items """ self.update({'os_default_templates': SubDict(self.api, self.objName, self.payloadObj, self.key, SubItemOsDefaultTe...
0.003745
def VAR_DECL(self, cursor): """Handles Variable declaration.""" # get the name name = self.get_unique_name(cursor) log.debug('VAR_DECL: name: %s', name) # Check for a previous declaration in the register if self.is_registered(name): return self.get_registered(...
0.002265