text
stringlengths
78
104k
score
float64
0
0.18
def get_params(self): """Gets current parameters. Returns ------- (arg_params, aux_params) A pair of dictionaries each mapping parameter names to NDArray values. This is a merged dictionary of all the parameters in the modules. """ assert self.bin...
0.005
def get_regular_expressions(taxonomy_name, rebuild=False, no_cache=False): """Return a list of patterns compiled from the RDF/SKOS ontology. Uses cache if it exists and if the taxonomy hasn't changed. """ # Translate the ontology name into a local path. Check if the name # relates to an existing on...
0.000347
def parse(text): """Parse the given text into metadata and strip it for a Markdown parser. :param text: text to be parsed """ rv = {} m = META.match(text) while m: key = m.group(1) value = m.group(2) value = INDENTATION.sub('\n', value.strip()) rv[key] = value ...
0.002463
def template(self, name): """ Set an active template to use with our Postman. This changes the call signature of send. Arguments: - `name`: str Return: None Exceptions: None """ self.plain, self.html = self._find_tpls(name) if not self.p...
0.003711
async def SetTools(self, agent_tools): ''' agent_tools : typing.Sequence[~EntityVersion] Returns -> typing.Sequence[~ErrorResult] ''' # map input types to rpc msg _params = dict() msg = dict(type='Upgrader', request='SetTools', ...
0.004264
def choice(choices=[], message='Pick something.', default=None, title=''): """ Present the user with a list of choices. return the choice that he selects. return None if he cancels the selection selection. :ref:`screenshots<choice>` :param choices: a list of the choices to be displayed :pa...
0.003436
def raise_(tp, value=None, tb=None): """ A function that matches the Python 2.x ``raise`` statement. This allows re-raising exceptions with the cls value and traceback on Python 2 and 3. """ if value is not None and isinstance(tp, Exception): raise TypeError("instance exception may not h...
0.001976
def exception_handler(exc, context): """ Returns the response that should be used for any given exception. By default we handle the REST framework `APIException`, and also Django's built-in `Http404` and `PermissionDenied` exceptions. Any unhandled exceptions may return `None`, which will cause a ...
0.000743
def validate(self, value): """ Accepts: str, unicode, bool Returns: bool """ if isinstance(value, bool): return value if isinstance(value, (str, unicode)): if value.lower() == "true": value = True elif value.lower() == "...
0.003241
def load_from_file(filename): """ Load a list of filenames from an external text file. """ if os.path.isdir(filename): logger.error("Err: File '%s' is a directory", filename) return None if not os.path.isfile(filename): logger.error("Err: File '%s' does not exist", filename) ...
0.001582
def fix_pin(self, line): """ Fix dependency by removing post-releases from versions and loosing constraints on internal packages. Drop packages from ignore set Also populate packages set """ dep = Dependency(line) if dep.valid: if dep.package ...
0.00148
def summarize_mutation_io(name, type, required=False): """ This function returns the standard summary for mutations inputs and outputs """ return dict( name=name, type=type, required=required )
0.004016
def setRequest(self, endPointReference, action): '''Call For Request ''' self._action = action self.header_pyobjs = None pyobjs = [] namespaceURI = self.wsAddressURI addressTo = self._addressTo messageID = self._messageID = "uuid:%s" %time.time() ...
0.011306
def secondYAxis(requestContext, seriesList): """ Graph the series on the secondary Y axis. """ for series in seriesList: series.options['secondYAxis'] = True series.name = 'secondYAxis(%s)' % series.name return seriesList
0.003891
def create_query_future(self, key): """ Create and return a :class:`asyncio.Future` for the given `hash_` function and `node` URL. The future is referenced internally and used by any calls to :meth:`lookup` which are made while the future is pending. The future is removed from th...
0.002999
def start(self, timeout=None): """ Startup of the node. :param join: optionally wait for the process to end (default : True) :return: None """ assert super(PyrosBase, self).start(timeout=timeout) # Because we currently use this to setup connection return ...
0.006079
def rewire_inputs(data_list): """Rewire inputs of provided data objects. Input parameter is a list of original and copied data object model instances: ``[{'original': original, 'copy': copy}]``. This function finds which objects reference other objects (in the list) on the input and replaces origin...
0.004847
def _extract_clublog_header(self, cty_xml_filename): """ Extract the header of the Clublog XML File """ cty_header = {} try: with open(cty_xml_filename, "r") as cty: raw_header = cty.readline() cty_date = re.search("date='.+'", raw_heade...
0.004775
def guess_depth(packages): """ Guess the optimal depth to use for the given list of arguments. Args: packages (list of str): list of packages. Returns: int: guessed depth to use. """ if len(packages) == 1: return packages[0].count('.') + 2 return min(p.count('.') fo...
0.002941
def events(self, since=None, until=None, filters=None, decode=None): """ Get real-time events from the server. Similar to the ``docker events`` command. Args: since (UTC datetime or int): Get events from this point until (UTC datetime or int): Get events until th...
0.001089
def variance_inflation_factor(regressors, hasconst=False): """Calculate variance inflation factor (VIF) for each all `regressors`. A wrapper/modification of statsmodels: statsmodels.stats.outliers_influence.variance_inflation_factor One recommendation is that if VIF is greater than 5, then the e...
0.00045
def decompose(self): """Recursively destroys the contents of this tree.""" self.extract() if len(self.contents) == 0: return current = self.contents[0] while current is not None: next = current.next if isinstance(current, Tag): ...
0.00361
def get_interface(self, component): """ Gets given Component interface. Usage:: >>> manager = Manager() >>> manager.register_component("tests_component_a.rc") True >>> manager.get_interface("core.tests_component_a") <tests_component_a...
0.003195
def delete(self, fnames=None): """Delete files""" if fnames is None: fnames = self.get_selected_filenames() multiple = len(fnames) > 1 yes_to_all = None for fname in fnames: if fname == self.proxymodel.path_list[0]: self.sig_delete_...
0.00363
def _validate_profile(self, bag): """ Validate against OCRD BagIt profile (bag-info fields, algos etc) """ if not self.profile_validator.validate(bag): raise Exception(str(self.profile_validator.report))
0.008097
def wait_init(self): """ Block until init_done flag is set or until init_wait_timeout happens. :return: value of init_done """ init_done = self.init_done.wait(timeout=self.init_wait_timeout) if not init_done: if hasattr(self, "peek"): app = se...
0.005128
def wrap(self, values): """Pack an iterable of dict into a Value >>> T=NTTable([('A', 'ai'), ('B', 'as')]) >>> V = T.wrap([ {'A':42, 'B':'one'}, {'A':43, 'B':'two'}, ]) """ if isinstance(values, Value): return values cols = dic...
0.003463
def make_DID(name_type, address, index): """ Standard way of making a DID. name_type is "name" or "subdomain" """ if name_type not in ['name', 'subdomain']: raise ValueError("Require 'name' or 'subdomain' for name_type") if name_type == 'name': address = virtualchain.address_ree...
0.001297
def read(database, table, key): """Does a single read operation.""" with database.snapshot() as snapshot: result = snapshot.execute_sql('SELECT u.* FROM %s u WHERE u.id="%s"' % (table, key)) for row in result: key = row[0] for i in range(...
0.002762
def main(argv=None): """Validate text parsed with FSM or validate an FSM via command line.""" if argv is None: argv = sys.argv try: opts, args = getopt.getopt(argv[1:], 'h', ['help']) except getopt.error as msg: raise Usage(msg) for opt, _ in opts: if opt in ('-h', '--help'): print(__...
0.018651
def weave( target, advices, pointcut=None, ctx=None, depth=1, public=False, pointcut_application=None, ttl=None ): """Weave advices on target with input pointcut. :param callable target: target from where checking pointcut and weaving advices. :param advices: advices to weave on tar...
0.000342
def transition_issue(self, issue, transition, fields=None, comment=None, worklog=None, **fieldargs): """Perform a transition on an issue. Each keyword argument (other than the predefined ones) is treated as a field name and the argument's value is treated as the intended value for that field --...
0.002874
def feature_names(self): """Get feature names (column labels). Returns ------- feature_names : list or None """ if self._feature_names is None: self._feature_names = ['f{0}'.format(i) for i in range(self.num_col())] return self._feature_names
0.009646
def main(argv): """Train on examples and export the updated model weights.""" tf_records = argv[1:] logging.info("Training on %s records: %s to %s", len(tf_records), tf_records[0], tf_records[-1]) with utils.logged_timer("Training"): train(*tf_records) if FLAGS.export_path: ...
0.001855
def with_name(self, name): """Sets the name scope for future operations.""" self._head = self._head.with_name(name) return self
0.007194
def add_retout_site(self, node): """ Add a custom retout site. Retout (returning to outside of the function) sites are very rare. It mostly occurs during CFG recovery when we incorrectly identify the beginning of a function in the first iteration, and then correctly identify that ...
0.008326
def get_help_data(filepath): """ Get the json data from a help file Args: filepath (str): The file path for the help file Returns: data: The json data from a help file """ try: with open(filepath, 'r') as file: return _json.load(file, object_pairs_hook=Orde...
0.002151
def extract_lightcurve( log, spectrumFiles, userExplosionDay, extendLightCurveTail, obsmode): """ *Extract the requested lightcurve from list of spectrum files* **Key Arguments:** - ``log`` -- logger - ``spectrumFiles`` -- list of the spectrum files ...
0.003044
def _set_interface_vlan_ospf_conf(self, v, load=False): """ Setter method for interface_vlan_ospf_conf, mapped from YANG variable /routing_system/interface/ve/ip/interface_vlan_ospf_conf (container) If this variable is read-only (config: false) in the source YANG file, then _set_interface_vlan_ospf_conf...
0.005914
def post(param_map, url=URL): """Posts a `param_map` created with `config` to the FlashAir config.cgi entrypoint""" prepped_request = _prep_post(url=url, **param_map) return cgi.send(prepped_request)
0.004651
def with_headers(self, headers): """Create a new request with added headers Parameters ---------- headers: Mapping the headers to add """ return self.replace(headers=_merge_maps(self.headers, headers))
0.007634
def normalize(data): """ Function to normalize data to have mean 0 and unity standard deviation (also called z-transform) Parameters ---------- data : numpy.ndarray Returns ------- numpy.ndarray z-transform of input array """ data = data.astyp...
0.018135
def put_tagging(Bucket, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Given a valid config, update the tags for a bucket. Returns {updated: true} if tags were updated and returns {updated: False} if tags were not updated. CLI Example: .. code-block:: bash ...
0.003115
def true_events(network, previous_state, current_state, next_state, indices=None, major_complex=None): """Return all mechanisms that have true causes and true effects within the complex. Args: network (Network): The network to analyze. previous_state (tuple[int]): The state ...
0.000852
def get_authinfo(request): """Get authentication info from the encrypted message.""" if (("files_iv" not in request.session) or ("files_text" not in request.session) or ("files_key" not in request.COOKIES)): return False """ Decrypt the password given the SERVER-side IV, SERVER-side ...
0.003593
def path_helper(self, operations, view, **kwargs): """Path helper that allows passing a bottle view function.""" operations.update(yaml_utils.load_operations_from_docstring(view.__doc__)) app = kwargs.get('app', _default_app) route = self._route_for_view(app, view) return self.bo...
0.008523
def relabel_map(label_image, mapping, key=lambda x, y: x[y]): r""" Relabel an image using the supplied mapping. The ``mapping`` can be any kind of subscriptable object. The respective region id is used to access the new value from the ``mapping``. The ``key`` keyword parameter can be used to su...
0.010023
def _set_subject_alt(self, name, values): """ Replaces all existing asn1crypto.x509.GeneralName objects of the choice represented by the name parameter with the values :param name: A unicode string of the choice name of the x509.GeneralName object :param values: ...
0.001765
def applyEdits(self, addFeatures=[], updateFeatures=[], deleteFeatures=None, gdbVersion=None, rollbackOnFailure=True): """ This operation adds, updates, and deletes features to the associated fea...
0.004557
def logical_not_expr(self): """ logical_not_expr: 'not' logical_not_expr | comparison """ if self.token.nature == Nature.NOT: token = self.token self._process(Nature.NOT) return UnaryOperation(op=token, right=self.logical_not_ex...
0.005319
def make_video_cache(self, days=None): """Save videos on _cache_videos to avoid dups.""" if days is None: days = self._min_days_vdo_cache self._cached_videos = self.videos(days)
0.00939
def unknown_command(self, args): '''handle mode switch by mode name as command''' mode_mapping = self.master.mode_mapping() mode = args[0].upper() if mode in mode_mapping: self.master.set_mode(mode_mapping[mode]) return True return False
0.006645
def shutdown_notebook(request, username): """Stop any running notebook for a user.""" manager = get_notebook_manager(request) if manager.is_running(username): manager.stop_notebook(username)
0.004739
def weekofyear(self, first_day_of_week=SATURDAY): """weekofyear(first_day_of_week=SATURDAY) :param first_day_of_week: One of the :py:data:`khayyam.SATURDAY`, :py:data:`khayyam.SUNDAY`, :py:data:`khayyam.MONDAY`, :py:data:`khayyam.TUESDAY`,...
0.002395
def discard(self, element, multiplicity=None): """Removes the `element` from the multiset. If multiplicity is ``None``, all occurrences of the element are removed: >>> ms = Multiset('aab') >>> ms.discard('a') 2 >>> sorted(ms) ['b'] Otherwise, the multip...
0.002214
def append(self, item): """ Appends the *item* to the end of the `Sequence`. :param item: any :class:`Structure`, :class:`Sequence`, :class:`Array` or :class:`Field` instance. """ if not is_any(item): raise MemberTypeError(self, item, member=len(self)) se...
0.005865
def write_pad_codewords(buff, version, capacity, length): """\ Writes the pad codewords iff the data does not fill the capacity of the symbol. :param buff: The byte buffer. :param int version: The (Micro) QR Code version. :param int capacity: The total capacity of the symbol (incl. error correc...
0.002364
def encryptPassword(self, login, passwd): """Encrypt credentials using the google publickey, with the RSA algorithm""" # structure of the binary key: # # *-------------------------------------------------------* # | modulus_length | modulus | exponent_length | exponent |...
0.001322
def _set_master(self, v, load=False): """ Setter method for master, mapped from YANG variable /ntp/master (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_master is considered as a private method. Backends looking to populate this variable should do so vi...
0.004225
def _departmentsVoc(self): """Vocabulary of available departments """ query = { "portal_type": "Department", "is_active": True } results = api.search(query, "bika_setup_catalog") items = map(lambda dept: (api.get_uid(dept), api.get_title(dept)), ...
0.002288
def human_filesize(i): """ 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc). """ bytes = float(i) if bytes < 1024: return u"%d Byte%s" % (bytes, bytes != 1 and u"s" or u"") if bytes < 1024 * 1024: return u"%.1f KB" % (bytes / 1024) if bytes < 1024 * 1024 * 1024...
0.002336
def parse_negation_operation(operation: str) -> Tuple[bool, str]: """Parse the negation modifier in an operation.""" _operation = operation.strip() if not _operation: raise QueryParserException('Operation is not valid: {}'.format(operation)) negation = False if _operation[0] == '~': ...
0.004854
def retry(exception_to_check, tries=5, delay=5, multiplier=2): '''Tries to call the wrapped function again, after an incremental delay :param exception_to_check: Exception(s) to check for, before retrying. :type exception_to_check: Exception :param tries: Number of time to retry before failling. :t...
0.000679
def get_cropping_offset(crop, epsilon): """ Calculates the cropping offset for the cropped image. This only calculates the offset for one dimension (X or Y). This should be called twice to get the offsets for the X and Y dimensions. :param str crop: A percentage cropping value for the plane. This i...
0.002139
def first_run(self, known_block_number): """ Blocking call to update the local state, if necessary. """ assert self.callbacks, 'callbacks not set' latest_block = self.chain.get_block(block_identifier='latest') log.debug( 'Alarm task first run', known_block_number...
0.00299
def actnorm_scale(name, x, logscale_factor=3., reverse=False, init=False): """Per-channel scaling of x.""" x_shape = common_layers.shape_list(x) with tf.variable_scope(name, reuse=tf.AUTO_REUSE): # Variance initialization logic. assert len(x_shape) == 2 or len(x_shape) == 4 if len(x_shape) == 2: ...
0.011797
def _get_struct_format(self, size): """ Get's the format specified for use in struct. This is only designed for 1, 2, 4, or 8 byte values and will throw an exception if it is anything else. :param size: The size as an int :return: The struct format specifier for the size...
0.00267
def _connect_attempt(self, mode='default_reset', esp32r0_delay=False): """ A single connection attempt, with esp32r0 workaround options """ # esp32r0_delay is a workaround for bugs with the most common auto reset # circuit and Windows, if the EN pin on the dev board does not have # enoug...
0.001226
def sample_given_context(self, c, c_dims): ''' Sample the region with max progress among regions that have the same context c: context value on c_dims dimensions c_dims: w.r.t sensory space dimensions ''' index = self.discrete_progress.sample_given_context(c, c_di...
0.011062
def get_options(self, gradebook_id): """Get options for gradebook. Get options dictionary for a gradebook. Options include gradebook attributes. Args: gradebook_id (str): unique identifier for gradebook, i.e. ``2314`` Returns: An example return value ...
0.000832
def command(db, channel, command, *args): """ Utility function to issue a command to all Turnstile instances. :param db: The database handle. :param channel: The control channel all Turnstile instances are listening on. :param command: The command, as plain text. Currently, onl...
0.001247
def from_dict(document): """Create attribute definition form Json-like object represenation. Parameters ---------- document : dict Json-like object represenation Returns ------- AttributeDefinition """ if 'default' in document: ...
0.003226
def __calculate_centers(self): """! @brief Calculate center using membership of each cluster. @return (list) Updated clusters as list of clusters. Each cluster contains indexes of objects from data. @return (numpy.array) Updated centers. """ dimension = self._...
0.006163
def prune_dupes(self): """Remove all but the last entry for a given resource URI. Returns the number of entries removed. Also removes all entries for a given URI where the first entry is a create and the last entry is a delete. """ n = 0 pruned1 = [] seen...
0.001963
async def volume(gc: GroupControl, volume): """Adjust volume [-100, 100]""" click.echo("Setting volume to %s" % volume) click.echo(await gc.set_group_volume(volume))
0.00565
def _insert_or_update(self, resourcetype, source, mode='insert', hhclass='Service'): """ Insert or update a record in the repository """ keywords = [] if self.filter is not None: catalog = Catalog.objects.get(id=int(self.filter.split()[-1])) try: ...
0.002952
def query(self, req, timeout=None, metadata=None, credentials=None): """Runs query operation.""" return self.stub.Query(req, timeout=timeout, metadata=metadata, credentials=credentials)
0.008621
def _digest_auth_in_stage2(self, username, _unused, stanza): """Handle the second stage (<iq type='set'/>) of legacy "digest" authentication. [server only]""" digest=stanza.xpath_eval("a:query/a:digest",{"a":"jabber:iq:auth"}) if digest: digest=digest[0].getContent()...
0.01626
def streamitem_to_key_data(si): ''' extract the parts of a StreamItem that go into a kvlayer key, convert StreamItem to blob for storage. return (kvlayer key tuple), data blob ''' key = key_for_stream_item(si) data = streamcorpus.serialize(si) errors, data = streamcorpus.compress_and_en...
0.002618
def logfile(targetfile="ros.log"): """ Set the file for Quilt to log to targetfile: Change the file to log to. """ log = logging.getLogger(__name__) log.basicConfig(filename=str(targetfile))
0.004587
def rnumlistwithreplacement(howmany, max, min=0): """Returns a list of howmany integers with a maximum value = max. The minimum value defaults to zero.""" if checkquota() < 1: raise Exception("Your www.random.org quota has already run out.") requestparam = build_request_parameterWR(howmany, min,...
0.001802
def normprob(d, snrs, inds=None, version=2): """ Uses observed SNR distribution to calculate normal probability SNR Uses state dict to calculate number of trials. snrs is list of all snrs in distribution. version used to toggle for tests. version 2 is fastest and returns zeros for filtered snr values. ...
0.006244
def relation_get(attribute=None, unit=None, rid=None): """Attempt to use leader-get if supported in the current version of Juju, otherwise falls back on relation-get. Note that we only attempt to use leader-get if the provided rid is a peer relation id or no relation id is provided (in which case we as...
0.001587
def _get_account_policy(name): ''' Get the entire accountPolicy and return it as a dictionary. For use by this module only :param str name: The user name :return: a dictionary containing all values for the accountPolicy :rtype: dict :raises: CommandExecutionError on user not found or any ...
0.000956
def repr_setattr(self, class_data): """Create code like this:: person = Person(name='Jack', person_id=1) self.name____Jack = person self.person_id____1 = person person = Person(name='Paul', person_id=2) sel...
0.006687
def _http_request(url, method='GET', headers=None, data=None): ''' Make the HTTP request and return the body as python object. ''' req = requests.request(method, url, headers=headers, ...
0.002845
def escape_regex_special_chars(api_path): """ Turns the non prametrized path components into strings subtable for using as a regex pattern. This primarily involves escaping special characters so that the actual character is matched in the regex. """ def substitute(string, replacements): ...
0.002151
def sa(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): """Compute the Spectral Angle (SA). .. image:: /pictures/SA.png **Range:** -π/2 ≤ SA < π/2, closer to 0 is better. **Notes:** The spectral angle metric measures the angle between t...
0.004771
def bfd(self, **kwargs): """Configure BFD for BGP globally. Args: rbridge_id (str): Rbridge to configure. (1, 225, etc) tx (str): BFD transmit interval in milliseconds (300, 500, etc) rx (str): BFD receive interval in milliseconds (300, 500, etc) multipl...
0.000907
def from_spec(spec, kwargs): """ Creates an agent from a specification dict. """ agent = util.get_object( obj=spec, predefined_objects=tensorforce.agents.agents, kwargs=kwargs ) assert isinstance(agent, Agent) return agent
0.006369
def channels_rename(self, room_id, name, **kwargs): """Changes the name of the channel.""" return self.__call_api_post('channels.rename', roomId=room_id, name=name, kwargs=kwargs)
0.015385
def add_semantic_data(self, path_as_list, value, key): """ Adds a semantic data entry. :param list path_as_list: The path in the vividict to enter the value :param value: The value of the new entry. :param key: The key of the new entry. :return: """ assert isinst...
0.004246
def add_elasticache_node(self, node, cluster, region): ''' Adds an ElastiCache node to the inventory and index, as long as it is addressable ''' # Only want available nodes unless all_elasticache_nodes is True if not self.all_elasticache_nodes and node['CacheNodeStatus'] != 'available':...
0.003119
def get_setup_attribute(attribute, setup_path): """ Runs the project's setup.py script in a process with an arg that will print out the value for a particular attribute such as author or version, and returns the value. """ args = ["python", setup_path, "--%s" % attribute] return Popen(args, ...
0.002681
def check_task_status_and_id(task_json): """ Read status of import json and parse :param task_json: status json to parse :return: (stillRunning, imageId) """ if task_json.get('ImportImageTasks') is not None: task = task_json['ImportImageTasks'][0] else...
0.003714
def create_component(self, name, description=None): """ Create a sub component in the business component. :param name: The new component's name. :param description: The new component's description. :returns: The created component. """ new_comp = Component(name,...
0.00432
def pull_byte(self, stack_pointer): """ pulled a byte from stack """ addr = stack_pointer.value byte = self.memory.read_byte(addr) # log.info( # log.error( # "%x|\tpull $%x from %s stack at $%x\t|%s", # self.last_op_address, byte, stack_pointer.name, addr, # ...
0.004008
def deepcopy(x, memo=None, _nil=[]): """Deep copy operation on arbitrary Python objects. See the module's __doc__ string for more info. """ if memo is None: memo = {} d = id(x) y = memo.get(d, _nil) if y is not _nil: return y cls = type(x) copier = _deepcopy_disp...
0.002026
def choice(self, queues, connection): """ Chooses a random queue for messages to specified connection. @param queues: A C{dict} mapping queue name to queues (sets of frames) to which specified connection is subscribed. @type queues: C{dict} of C{str} to C{set} ...
0.008596
def create_geometry(self, input_geometry, upper_depth, lower_depth): ''' If geometry is defined as a numpy array then create instance of nhlib.geo.point.Point class, otherwise if already instance of class accept class :param input_geometry: Input geometry (point) as ...
0.001881