text
stringlengths
78
104k
score
float64
0
0.18
def update(self, *, name=None, show_headers=None, show_totals=None, style=None): """ Updates this table :param str name: the name of the table :param bool show_headers: whether or not to show the headers :param bool show_totals: whether or not to show the totals :param st...
0.003239
def degree_histogram(G, t=None): """Return a list of the frequency of each degree value. Parameters ---------- G : Graph opject DyNetx graph object t : snapshot id (default=None) snapshot id Returns ------- hist : list ...
0.001493
def main(fw_name, args=None, items=None): """ Reusable entry point. Arguments are parsed via the argparse-subcommands configured via each Command class found in globals(). Stop exceptions are propagated to callers. The name of the framework will be used in logging and similar. """ ...
0.000776
def path_filter(extensions, exclude_paths=None): """ Returns a function that returns True if a filepath is acceptable. @param extensions An array of strings. Specifies what file extensions should be accepted by the filter. If None, we default to the U...
0.000532
def types(subtag): """ Get the types of a subtag string (excludes redundant and grandfathered). :param str subtag: subtag. :return: list of types. The return list can be empty. """ if subtag in index: types = index[subtag] return [type for type i...
0.009501
def a(self, text, count=1): """ Return the appropriate indefinite article followed by text. The indefinite article is either 'a' or 'an'. If count is not one, then return count followed by text instead of 'a' or 'an'. Whitespace at the start and end is preserved. ...
0.00289
def send(self, request): """ Send a request to the server and wait for its response. Args: request (Request): Reference to a request object that is sent to the server. Returns: Response: The response from the server to the request. """ self._connection.c...
0.004932
def find_subgraphs_by_preds(xmrs, preds, connected=None): """ Yield subgraphs matching a list of predicates. Predicates may match multiple EPs/nodes in the *xmrs*, meaning that more than one subgraph is possible. Also, predicates in *preds* match in number, so if a predicate appears twice in *preds...
0.000736
def create_pipe_workers(configfile, directory): """ Creates the workers based on the given configfile to provide named pipes in the directory. """ type_map = {'service': ServiceSearch, 'host': HostSearch, 'range': RangeSearch, 'user': UserSearch} config = configpa...
0.002024
def iter_equivalent_nodes(self, node: BaseEntity) -> Iterable[BaseEntity]: """Iterate over nodes that are equivalent to the given node, including the original.""" yield node yield from self._equivalent_node_iterator_helper(node, {node})
0.011538
def run(self, port=5000, background=False): """ Runs this application with builtin server for testing. This is only for test usage, do not use in production stage. :param port: Port number :param background: Flag to run in background :type port: int :type background: boo...
0.00369
def yeardec2datetime(atime: float) -> datetime.datetime: """ Convert atime (a float) to DT.datetime This is the inverse of datetime2yeardec. assert dt2t(t2dt(atime)) == atime http://stackoverflow.com/questions/19305991/convert-fractional-years-to-a-real-date-in-python Authored by "unutbu" http:...
0.000959
def patch_data(data, L=100, try_diag=True, verbose=False): '''Patch ``data`` (for example Markov chain output) into parts of length ``L``. Return a Gaussian mixture where each component gets the empirical mean and covariance of one patch. :param data: Matrix-like array; the points to be patche...
0.003151
def cmd_reverse_lookup(command_name): '''returns 0 if key not found''' for key, value in miss_cmds.items(): if (value.upper() == command_name.upper()): return key return 0
0.004926
def execute(self, context): """Execute the python dataflow job.""" bucket_helper = GoogleCloudBucketHelper( self.gcp_conn_id, self.delegate_to) self.py_file = bucket_helper.google_cloud_to_local(self.py_file) hook = DataFlowHook(gcp_conn_id=self.gcp_conn_id, ...
0.003128
def _default(self, key, default=None): """ Lookup value of *key* themeable If *key* not in themeable or value is None, return the *default* value. """ try: value = self.theme.themeables.property(key) except KeyError: value = None ...
0.005464
async def create(source_id: str, name: str, schema_id: str, payment_handle: int): """ Creates a new CredentialDef object that is written to the ledger :param source_id: Institution's unique ID for the credential definition :param name: Name of credential definition :param schema...
0.003827
def run_marionette_script(script, chrome=False, async=False, host='localhost', port=2828): """Create a Marionette instance and run the provided script""" m = DeviceHelper.getMarionette(host, port) m.start_session() if chrome: m.set_context(marionette.Marionette.CONTEXT_CHROME) if not async: ...
0.008696
def wipe(ctx): """Drop the mongo database given.""" LOG.info("Running scout wipe") db_name = ctx.obj['mongodb'] LOG.info("Dropping database %s", db_name) try: ctx.obj['client'].drop_database(db_name) except Exception as err: LOG.warning(err) ctx.abort() LOG.info("Drop...
0.002941
def getFeatures(self, referenceName=None, start=None, end=None, startIndex=None, maxResults=None, featureTypes=None, parentId=None, name=None, geneSymbol=None): """ method passed to runSearchRequest to fulfill the request :param str ref...
0.003743
def split_type(self, typename): """ Given a potentially complex type, split it into its base type and specializers """ name = self._canonicalize_type(typename) if '(' not in name: return name, False, [] base, sub = name.split('(') if len(sub) == 0 or...
0.00708
def validate(self, metadata, path, value): """ Validate this requirement. """ if isinstance(value, Requirement): # if the RHS is still a Requirement object, it was not set if metadata.testing and self.mock_value is not None: value = self.mock_valu...
0.005208
def _connectionLost(self, reason): """Called when the protocol connection is lost - Log the disconnection. - Mark any outstanding requests as unsent so they will be sent when a new connection is made. - If closing the broker client, mark completion of that process. :p...
0.002466
def num_pending_tasks(self): """ Return how many tasks are PENDING + RUNNING. O(1). """ return len(self._status_tasks[PENDING]) + len(self._status_tasks[RUNNING])
0.015464
def main(argv=None): """ Entry point :param argv: Script arguments (None for sys.argv) :return: An exit code or None """ # Parse arguments parser = argparse.ArgumentParser( prog="pelix.shell.console", parents=[make_common_parser()], description="Pelix Shell Console",...
0.000898
def filter_facet_queryset(self, queryset): """ Given a search queryset, filter it with whichever facet filter backends in use. """ for backend in list(self.facet_filter_backends): queryset = backend().filter_queryset(self.request, queryset, self) if self.load...
0.005089
def _patch(self, uri, data): """ Simple PATCH operation for a given path. The body is expected to list operations to perform to update the data. Operations include: - add - remove - replace - move - copy - test ...
0.003916
def create_release_vcs(path, vcs_name=None): """Return a new release VCS that can release from this source path.""" from rez.plugin_managers import plugin_manager vcs_types = get_release_vcs_types() if vcs_name: if vcs_name not in vcs_types: raise ReleaseVCSError("Unknown version con...
0.001558
def _get_child_relation(self, child_pid): """Retrieve the relation between this node and a child PID.""" return PIDRelation.query.filter_by( parent=self._resolved_pid, child=child_pid, relation_type=self.relation_type.id).one()
0.007168
def on_success(self, retval, task_id, args, kwargs): """on_success http://docs.celeryproject.org/en/latest/reference/celery.app.task.html :param retval: return value :param task_id: celery task id :param args: arguments passed into task :param kwargs: keyword arguments ...
0.003215
def __replace_verbs(sentence, counts): """Lets find and replace all instances of #VERB :param _sentence: :param counts: """ if sentence is not None: while sentence.find('#VERB') != -1: sentence = sentence.replace('#VERB', str(__get_verb(counts)), 1) if sentence.find...
0.002347
def _match_line(self, city_name, lines): """ The lookup is case insensitive and returns the first matching line, stripped. :param city_name: str :param lines: list of str :return: str """ for line in lines: toponym = line.split(',')[0] ...
0.004762
def _publish_stats(self, counter_prefix, stats): """Given a stats dictionary from _get_stats_from_socket, publish the individual values. """ for stat_name, stat_value in flatten_dictionary( stats, prefix=counter_prefix, ): self.publish_gauge(st...
0.005882
def iter_links(self, file, encoding=None, context=False): '''Return the links. This function is a convenience function for calling :meth:`iter_text` and returning only the links. ''' if context: return [item for item in self.iter_text(file, encoding) if item[1]] ...
0.007282
def pixel(self, func:PixelFunc, *args, **kwargs)->'Image': "Equivalent to `image.px = func(image.px)`." self.px = func(self.px, *args, **kwargs) return self
0.022222
def hellinger(Ks, dim, required, clamp=True, to_self=False): r''' Estimate the Hellinger distance between distributions, based on kNN distances: \sqrt{1 - \int \sqrt{p q}} Always enforces 0 <= H, to be able to sqrt; if clamp, also enforces H <= 1. Returns a vector: one element for each K. ...
0.002075
def dataset_search(self, dataset_returning_query): """ Run a dataset query against Citrination. :param dataset_returning_query: :class:`DatasetReturningQuery` to execute. :type dataset_returning_query: :class:`DatasetReturningQuery` :return: Dataset search result object with the...
0.005146
def get_description(self, lang='en'): """ Retrieve the description in a certain language :param lang: The Wikidata language the description should be retrieved for :return: Returns the description string """ if self.fast_run: return list(self.fast_run_containe...
0.008117
async def delete(self, turn_context: TurnContext) -> None: """ Delete any state currently stored in this state scope. :param turn_context: The context object for this turn. :return: None """ if turn_context == None: raise TypeError('BotState.delete():...
0.014679
def map(self, func): """ :param func: :type func: (K, T) -> U :rtype: TList[U] Usage: >>> sorted(TDict(k1=1, k2=2, k3=3).map(lambda k, v: v*2)) [2, 4, 6] """ return TList([func(k, v) for k, v in self.items()])
0.006873
def remove(path): ''' Runs os.remove(path) and suppresses the OSError if the file doesn't exist ''' try: os.remove(path) except OSError as exc: if exc.errno != errno.ENOENT: raise
0.004405
def is_in_intervall(value, min_value, max_value, name='variable'): """ Raise an exception if value is not in an interval. Parameters ---------- value : orderable min_value : orderable max_value : orderable name : str Name of the variable to print in exception. """ if not...
0.002101
def get_logger(): """ Instantiate a logger. """ root = logging.getLogger() root.setLevel(logging.WARNING) ch = logging.StreamHandler(sys.stderr) ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(message)s') ch.setFormatter(formatter) root.addHandler(ch) return root
0.003135
def _decorator(store_name, store_values): """ Return a class decorator that: 1) Defines a new class method, `wait_for_js` 2) Defines a new class list variable, `store_name` and adds `store_values` to the list. """ def decorator(clz): # pylint: disable=missing-docstring # Add a...
0.002717
def get_wallets(self, fetch=False): """Return this Applications's wallets object, populating it if fetch is True.""" return Wallets( self.resource.wallets, self.client, populate=fetch, application=self)
0.012605
def write_directory(self, directory: str) -> bool: """Write a BEL namespace for identifiers, names, name hash, and mappings to the given directory.""" current_md5_hash = self.get_namespace_hash() md5_hash_path = os.path.join(directory, f'{self.module_name}.belns.md5') if not os.path.exi...
0.005922
def commit(self): """Send buffered requests and refresh all indexes.""" self.send_buffered_operations() retry_until_ok(self.elastic.indices.refresh, index="")
0.010989
def __calculate_perimeter_scoring(): """Return a 512 element vector which gives the perimeter given surrounding pts """ # # This is the array from the paper - a 256 - element array leaving out # the center point. The first value is the index, the second, the perimeter # prashker = np.ar...
0.18441
def draw(self, milliseconds): """Draws all of the objects in our world.""" cam = Ragnarok.get_world().Camera camPos = cam.get_world_pos() self.__sort_draw() self.clear_backbuffer() for obj in self.__draw_objects: #Check to see if the object is visible to the c...
0.006623
def clear(self): """ Clear the cache, setting it to its initial state. """ self.name.clear() self.path.clear() self.generated = False
0.01105
def _endLineupsNode(self, name, content): """Process the end of a node under xtvd/lineups""" if name == 'map': if not self._error: self._importer.new_mapping(self._lineupId, self._stationId, self._channel, self._channelMinor, ...
0.01087
def mark_flags_as_mutual_exclusive(flag_names, required=False, flag_values=_flagvalues.FLAGS): """Ensures that only one flag among flag_names is not None. Important note: This validator checks if flag values are None, and it does not distinguish between default and explicit val...
0.005119
def iter_referents(self): """ Generates target sets that are compatible with the current beliefstate. """ tlow, thigh = self['targetset_arity'].get_tuple() clow, chigh = self['contrast_arity'].get_tuple() referents = list(self.iter_singleton_referents()) t = len(referents) ...
0.013378
def delete_all_hosting_devices(self, context, force_delete=False): """Deletes all hosting devices.""" for item in self._get_collection_query( context, hd_models.HostingDeviceTemplate): self.delete_all_hosting_devices_by_template( context, template=item, force_...
0.005882
def press(self, key_code): """ Sends a 'down' event for the specified scan code """ if key_code >= 128: # Media key ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( 14, # type (0, 0), # loc...
0.008691
def area(poly): """Area of a polygon poly""" if len(poly) < 3: # not a plane - no area return 0 total = [0, 0, 0] num = len(poly) for i in range(num): vi1 = poly[i] vi2 = poly[(i+1) % num] prod = np.cross(vi1, vi2) total[0] += prod[0] total[1] += prod[...
0.003781
def untokenize(tokens): """ Converts the output of tokenize.generate_tokens back into a human-readable string (that doesn't contain oddly-placed whitespace everywhere). .. note:: Unlike :meth:`tokenize.untokenize`, this function requires the 3rd and 4th items in each token tuple (thoug...
0.001147
def move_to_destination(source, destination, job_name, sagemaker_session): """move source to destination. Can handle uploading to S3 Args: source (str): root directory to move destination (str): file:// or s3:// URI that source will be moved to. job_name (str): SageMaker job name. ...
0.002933
def init_run_context(self, raw=False): """ Sets the log context. """ self.raw = raw self._set_context(self)
0.013605
def del_from_groups(self, username, groups): """Delete user from groups""" # it follows the same logic than add_to_groups # but with MOD_DELETE ldap_client = self._bind() tmp = self._get_user(self._byte_p2(username), ALL_ATTRS) if tmp is None: raise UserDoesnt...
0.001289
def GetMacAddresses(self): """MAC addresses from all interfaces.""" result = set() for interface in self.interfaces: if (interface.mac_address and interface.mac_address != b"\x00" * len(interface.mac_address)): result.add(Text(interface.mac_address.human_readable_address)) return...
0.008955
def map_peaks_to_image(peaks, r=4, vox_dims=(2, 2, 2), dims=(91, 109, 91), header=None): """ Take a set of discrete foci (i.e., 2-D array of xyz coordinates) and generate a corresponding image, convolving each focus with a hard sphere of radius r.""" data = np.zeros(dims) for ...
0.001996
def expected_cost(numobj): """Gets the expected cost category of a short number (however, nothing is implied about its validity). If the country calling code is unique to a region, this method behaves exactly the same as expected_cost_for_region. However, if the country calling code is shared by mul...
0.001738
def qry_helper(flag_id, qry_string, param_str, flag_filt=False, filt_st=""): """Dynamically add syntaxtical elements to query. This functions adds syntactical elements to the query string, and report title, based on the types and number of items added thus far. Args: flag_filt (bool): at least...
0.000983
def alias_resolving(self): """ Alias definitions with resolved values as defined on this engine. Aliases can be used in rules to simplify multiple object creation :: fw = Engine('myfirewall') for alias in fw.alias_resolving(): print(alias, alias.r...
0.002538
def create_routertype(self, context, routertype): """Creates a router type. Also binds it to the specified hosting device template. """ LOG.debug("create_routertype() called. Contents %s", routertype) rt = routertype['routertype'] with context.session.begin(subtransactio...
0.00191
def filter_params(target): """Decorator which filters params to remove non-oauth_* parameters Assumes the decorated method takes a params dict or list of tuples as its first argument. """ def wrapper(params, *args, **kwargs): params = filter_oauth_params(params) return target(params...
0.002532
def watsonsV(Dir1, Dir2): """ calculates Watson's V statistic for two sets of directions """ counter, NumSims = 0, 500 # # first calculate the fisher means and cartesian coordinates of each set of Directions # pars_1 = fisher_mean(Dir1) pars_2 = fisher_mean(Dir2) # # get V statistic for these # ...
0.001604
def all_substrings(s): ''' yields all substrings of a string ''' join = ''.join for i in range(1, len(s) + 1): for sub in window(s, i): yield join(sub)
0.005464
def main(): # noqa """Attempt to fully destroy AWS Resources for a Spinnaker Application.""" logging.basicConfig(format=LOGGING_FORMAT) parser = argparse.ArgumentParser(description=main.__doc__) add_debug(parser) add_app(parser) args = parser.parse_args() if args.debug == logging.DEBUG: ...
0.000652
def get_remote_data(data, settings, mode, more_excluded_names=None): """ Return globals according to filter described in *settings*: * data: data to be filtered (dictionary) * settings: variable explorer settings (dictionary) * mode (string): 'editable' or 'picklable' * more_excl...
0.000925
def gettarinfo(self, name=None, arcname=None, fileobj=None): """Create a TarInfo object for either the file `name' or the file object `fileobj' (using os.fstat on its file descriptor). You can modify some of the TarInfo's attributes before you add it using addfile(). If given, `...
0.000577
def GetDefaultContract(self): """ Get the default contract. Returns: contract (Contract): if Successful, a contract of type neo.SmartContract.Contract, otherwise an Exception. Raises: Exception: if no default contract is found. Note: Prints ...
0.006932
def Popen(self, cmd, **kwargs): """ Remote Popen :param cmd: command to remotely execute :param kwargs: extra arguments to Popen (see subprocess.Popen) :return: handle to subprocess """ masked_cmd = ' '.join(self.cmd_mask_password(cmd)) self.log.info("Exe...
0.003704
def from_pty(cls, stdout, true_color=False, ansi_colors_only=None, term=None): """ Create an Output class from a pseudo terminal. (This will take the dimensions by reading the pseudo terminal attributes.) """ assert stdout.isatty() def get_size(): rows...
0.00565
def _parse_args(): """Parse and return command line arguments.""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=_CliFormatter) parser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose output.') fb_group = parser.ad...
0.000731
def managed(name, roles=None, profiles=None, authorizations=None): ''' Manage RBAC properties for user name : string username roles : list list of roles for user profiles : list list of profiles for user authorizations : list list of authorizations for user ...
0.00319
def header(self, name, value): """ Store all message headers, optionally clean them up. This simply stores all message headers so we can send them to DSPAM. Additionally, headers that have the same prefix as the ones we're about to add are deleted. """ self.mess...
0.002999
def get_modules(folder): """Find all valid modules in the given folder which must be in in the same directory as this loader.py module. A valid module has a .py extension, and is importable. @return: all loaded valid modules @rtype: iterator of module """ if is_frozen(): # find modul...
0.003575
def Close(self): """Flushes the flow and all its requests to the data_store.""" self._CheckLeaseAndFlush() super(FlowBase, self).Close() # Writing the messages queued in the queue_manager of the runner always has # to be the last thing that happens or we will have a race condition. self.FlushMes...
0.003058
def centralManager_didDisconnectPeripheral_error_(self, manager, peripheral, error): """Called when a device is disconnected.""" logger.debug('centralManager_didDisconnectPeripheral called') # Get the device and remove it from the device list, then fire its # disconnected event. ...
0.005484
def _trj_store_trajectory(self, traj, only_init=False, store_data=pypetconstants.STORE_DATA, max_depth=None): """ Stores a trajectory to an hdf5 file Stores all groups, parameters and results """ if not only_init: self._logger.info('Start stori...
0.006674
def trending(limit=DEFAULT_SEARCH_LIMIT, api_key=GIPHY_PUBLIC_KEY, strict=False, rating=None): """ Shorthand for creating a Giphy api wrapper with the given api key and then calling the trending method. Note that this will return a generator """ return Giphy(api_key=api_key, strict=...
0.002681
def authorization_code_grant_flow(credentials, storage_filename): """Get an access token through Authorization Code Grant. Parameters credentials (dict) All your app credentials and information imported from the configuration file. storage_filename (str) File...
0.000556
def visit_FunctionDeclaration(self, node): """Visitor for `FunctionDeclaration` AST node.""" for parameter in node.parameters: try: var_name = parameter.variable.identifier.name var_is_mutable = parameter.variable.is_mutable except AttributeError: ...
0.004573
def session_token(self): """Return OAuth session token.""" session_token = None if self.user_id is not None: session_token = token_getter(self.remote) if session_token: token = RemoteToken.get( self.user_id, self.remote.consumer_key, ...
0.004878
def _get_token( request=None, allowed_auth_schemes=('OAuth', 'Bearer'), allowed_query_keys=('bearer_token', 'access_token')): """Get the auth token for this request. Auth token may be specified in either the Authorization header or as a query param (either access_token or bearer_token). We'll check in ...
0.008869
def delete(args): """ cdstarcat delete OID Delete an object specified by OID from CDSTAR. """ with _catalog(args) as cat: n = len(cat) cat.delete(args.args[0]) args.log.info('{0} objects deleted'.format(n - len(cat))) return n - len(cat)
0.003448
def list_volume_attachment(self, **kwargs): """ list or watch objects of kind VolumeAttachment This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_volume_attachment(async_req=True) ...
0.001978
def _print_bar(self): '''Print a progress bar.''' self._print('[') for position in range(self._bar_width): position_fraction = position / (self._bar_width - 1) position_bytes = position_fraction * self.max_value if position_bytes < (self.continue_value or 0)...
0.005474
def print_list(cls, l, output='table'): """ prints a list :param l: the list :param output: the output, default is a table :return: """ def dict_from_list(l): """ returns a dict from a list for printing :param l: the list ...
0.005085
def connection_service_name(service, *args): ''' the name of a service that manages the connection between services ''' # if the service is a string if isinstance(service, str): return service return normalize_string(type(service).__name__)
0.003774
def punct(self, text): """Push punctuation onto the token queue.""" cls = self.PUNCTUATION[text] self.push_token(cls(text, self.lineno, self.offset))
0.011561
def create_basic_op_node(op_name, node, kwargs): """Helper function to create a basic operator node that doesn't contain op specific attrs""" name, input_nodes, _ = get_inputs(node, kwargs) node = onnx.helper.make_node( op_name, input_nodes, [name], name=name ) r...
0.003012
def etree_replace_namespace(etree_obj, ns_str): """In-place change the namespace of elements in an ElementTree. Args: etree_obj: ElementTree ns_str : str The namespace to set. E.g.: ``http://ns.dataone.org/service/types/v1``. """ def _replace_recursive(el, n): el.tag = re...
0.001704
def encode(cls, value): """ take a valid unicode string and turn it into utf-8 bytes :param value: unicode, str :return: bytes """ coerced = unicode(value) if coerced == value: return coerced.encode(cls._encoding) raise InvalidValue('not text...
0.006211
def find_next_comma(self, node, sub): """Find comma after sub andd add NodeWithPosition in node""" position = (sub.last_line, sub.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first))
0.006431
def submit_completion(self, user, course_key, block_key, completion): """ Update the completion value for the specified record. Parameters: * user (django.contrib.auth.models.User): The user for whom the completion is being submitted. * course_key (opaque_k...
0.001828
def getobject_use_prevfield(idf, idfobject, fieldname): """field=object_name, prev_field=object_type. Return the object""" if not fieldname.endswith("Name"): return None # test if prevfieldname ends with "Object_Type" fdnames = idfobject.fieldnames ifieldname = fdnames.index(fieldname) p...
0.0016
def _compile_mothur_script(self): """Returns a Mothur batch script as a string""" fasta = self._input_filename required_params = ["reference", "taxonomy"] for p in required_params: if self.Parameters[p].Value is None: raise ValueError("Must provide value for ...
0.003484