text
stringlengths
78
104k
score
float64
0
0.18
def flatten(listish): """Flatten an arbitrarily-nested list of strings and lists. Works for any subclass of basestring and any type of iterable. """ for elem in listish: if (isinstance(elem, collections.Iterable) and not isinstance(elem, basestring)): for subelem in ...
0.002494
def main(): '''Calculate the distance of an object in inches using a HCSR04 sensor and a Raspberry Pi''' trig_pin = 17 echo_pin = 27 # Default values # unit = 'metric' # temperature = 20 # round_to = 1 # Create a distance reading with the hcsr04 sensor module # and overide ...
0.001202
def bss_eval(reference_sources, estimated_sources, window=2 * 44100, hop=1.5 * 44100, compute_permutation=False, filters_len=512, framewise_filters=False, bsseval_sources_version=False ): """BSS_EVAL version 4. Measurement of the sep...
0.000215
def configuration_check(config): """Perform a sanity check on configuration. First it performs a sanity check against settings for daemon and then against settings for each service check. Arguments: config (obj): A configparser object which holds our configuration. Returns: None i...
0.000581
def send_email(sender, pw, to, subject, content, files=None, service='163'): """send email, recommended use 163 mailbox service, as it is tested. :param sender: str email address of sender :param pw: str password for sender :param to: str email addressee :param subject: str ...
0.001431
def __register_services(api_name_version_map, api_config_registry): """Register & return a list of each URL and class that handles that URL. This finds every service class in api_name_version_map, registers it with the given ApiConfigRegistry, builds the URL for that class, and adds the URL and its fac...
0.00315
def logp_plus_loglike(self): ''' The summed log-probability of all stochastic variables that depend on self.stochastics, and self.stochastics. ''' sum = logp_of_set(self.markov_blanket) if self.verbose > 2: print_('\t' + self._id + ' Current...
0.005128
def refresh_session(self): """ Re-authenticate using the refresh token if available. Otherwise log in using the username and password if it was used to authenticate initially. :return: The authentication response or `None` if not available """ if not self._refre...
0.002928
def trainable_gamma(shape, min_concentration=1e-3, min_scale=1e-5, name=None): """Learnable Gamma via concentration and scale parameterization.""" with tf.compat.v1.variable_scope(None, default_name="trainable_gamma"): unconstrained_concentration = tf.compat.v1.get_variable( "unconstrained_concentration...
0.003356
def delete_file(self, record, field, return_format='json', event=None): """ Delete a file from REDCap Notes ----- There is no undo button to this. Parameters ---------- record : str record ID field : str field name ...
0.001978
def add_child_sensor(self, child_id, child_type, description=''): """Create and add a child sensor.""" if child_id in self.children: _LOGGER.warning( 'child_id %s already exists in children of node %s, ' 'cannot add child', child_id, self.sensor_id) ...
0.004435
def launch(exec_, args): """ Launches application. """ if not exec_: raise RuntimeError( 'Mayalauncher could not find a maya executable, please specify' 'a path in the config file (-e) or add the {} directory location' 'to your PATH system environment....
0.001754
def pop_object(self, element): ''' Pop the object element if the object contains an higher TLP then allowed. ''' redacted_text = "Redacted. Object contained TLP value higher than allowed." element['id'] = '' element['url'] = '' element['type'] = '' eleme...
0.004813
def get_conf_path(filename=None): """Return absolute path for configuration file with specified filename.""" conf_dir = osp.join(get_home_dir(), '.condamanager') if not osp.isdir(conf_dir): os.mkdir(conf_dir) if filename is None: return conf_dir else: return osp.j...
0.002915
def from_prev_calc(cls, prev_calc_dir, copy_chgcar=True, nbands_factor=1.2, standardize=False, sym_prec=0.1, international_monoclinic=True, reciprocal_density=100, small_gap_multiply=None, **kwargs): """ Generate a set of Vasp input fi...
0.001663
def verify_password(self, password, password_hash): """Verify plaintext ``password`` against ``hashed password``. Args: password(str): Plaintext password that the user types in. password_hash(str): Password hash generated by a previous call to ``hash_password()``. Return...
0.008017
def run(self, n_iterations=1, min_n_workers=1, iteration_kwargs = {},): """ run n_iterations of SuccessiveHalving Parameters ---------- n_iterations: int number of iterations to be performed in this run min_n_workers: int minimum number of workers before starting the run """ self.wait_for_worke...
0.041137
def handle(self, *app_labels, **options): """ Serializes objects from the database. Works much like Django's ``manage.py dumpdata``, except that it allows you to limit and sort the apps that you're pulling in, as well as automatically follow the dependency graph to pull in relat...
0.003214
def setColumn(self, header, values): """ Set the values of a column. Args: header: The header of the column to be set. values: The values to set. """ if any(isinstance(value, basestring) for value in values): values = list(map(str, values)) ...
0.00315
def _VmB (VmKey): """Parse /proc/<pid>/status file for given key. @return: requested number value of status entry @rtype: float """ if os.name != 'posix': # not supported return 0.0 global _proc_status, _scale # get pseudo file /proc/<pid>/status try: t = open(_p...
0.002869
def worklogs(self, issue): """Get a list of worklog Resources from the server for an issue. :param issue: ID or key of the issue to get worklogs from :rtype: List[Worklog] """ r_json = self._get_json('issue/' + str(issue) + '/worklog') worklogs = [Worklog(self._options, ...
0.004545
def create_experiment( run_config, hparams, model_name, problem_name, data_dir, train_steps, eval_steps, min_eval_frequency=2000, eval_throttle_seconds=600, schedule="train_and_evaluate", export=False, decode_hparams=None, use_tfdbg=False, use_dbgprofile=False, ...
0.009313
def getError(self, device=DEFAULT_DEVICE_ID, message=True): """ Get the error message or value stored in the Qik 2s9v1 hardware. :Keywords: device : `int` The device is the integer number of the hardware devices ID and is only used with the Pololu Protocol. Def...
0.002762
def root(self): """ Property to return the root of this node. Returns: Package: this node's root package. """ node = self while node.package is not None: node = node.package return node
0.007519
def serialize(self, q): """ Serialize a Q object into a (possibly nested) dict. """ children = [] for child in q.children: if isinstance(child, Q): children.append(self.serialize(child)) else: children.append(child) ...
0.004866
def get_kind(self): """Get function type It returns one of 'function', 'method', 'staticmethod' or 'classmethod' strs. """ scope = self.parent.get_scope() if isinstance(self.parent, PyClass): for decorator in self.decorators: pyname = rope.ba...
0.00311
def resnik_sim(go_id1, go_id2, godag, termcounts): ''' Computes Resnik's similarity measure. ''' goterm1 = godag[go_id1] goterm2 = godag[go_id2] if goterm1.namespace == goterm2.namespace: msca_goid = deepest_common_ancestor([go_id1, go_id2], godag) return get_info_content(msc...
0.00295
def get_jobs(deployment_name, token_manager=None, app_url=defaults.APP_URL): """ return list of currently running jobs """ headers = token_manager.get_access_token_headers() data_urls = get_data_urls(deployment_name, app_url=app_url, ...
0.002068
def _to_brightness(self, brightness): """ Step to a given brightness. :param brightness: Get to this brightness. """ self._to_value(self._brightness, brightness, self.command_set.brightness_steps, self._dimmer, self._brighter)
0.006557
def readline(self): """ Get the next line from the input buffer. """ self.line_number += 1 if self.line_number > len(self.lines): return '' return self.lines[self.line_number - 1]
0.008368
def toString(val, join_char='\n'): """ Turn a string or array value into a string. """ if type(val) in (list, tuple): return join_char.join(val) return val
0.009662
def regex_group(ctx, text, pattern, group_num): """ Tries to match the text with the given pattern and returns the value of matching group """ text = conversions.to_string(text, ctx) pattern = conversions.to_string(pattern, ctx) group_num = conversions.to_integer(group_num, ctx) expression ...
0.004695
def update(self, name=None, description=None, image_url=None, office_mode=None, share=None, **kwargs): """Update the details of the group. :param str name: group name (140 characters maximum) :param str description: short description (255 characters maximum) :param str im...
0.004762
def discover(self, transaction): """ Render a GET request to the .well-know/core link. :param transaction: the transaction :return: the transaction """ transaction.response.code = defines.Codes.CONTENT.number payload = "" for i in self._parent.root.dump()...
0.005089
def read_metadata(self, file_path): # type: (str) ->str """ Get version out of a .ini file (or .cfg) :return: """ config = configparser.ConfigParser() config.read(file_path) try: return unicode(config["metadata"]["version"]) except KeyError: ...
0.005882
def rot3(theta): """ Args: theta (float): Angle in radians Return: Rotation matrix of angle theta around the Z-axis """ return np.array([ [np.cos(theta), np.sin(theta), 0], [-np.sin(theta), np.cos(theta), 0], [0, 0, 1] ])
0.003509
def find_version(include_dev_version=True, root='%(pwd)s', version_file='%(root)s/version.txt', version_module_paths=(), git_args=None, vcs_args=None, decrement_dev_version=None, strip_prefix='v', Popen=subprocess.Popen, open=open): """Find an appr...
0.000658
def convert_dedent(self): """Convert a dedent into an indent""" # Dedent means go back to last indentation if self.indent_amounts: self.indent_amounts.pop() # Change the token tokenum = INDENT # Get last indent amount last_indent = 0 if self....
0.003344
def unstage_signature(vcs, signature): """Remove `signature` from the list of staged signatures Args: vcs (easyci.vcs.base.Vcs) signature (basestring) Raises: NotStagedError """ evidence_path = _get_staged_history_path(vcs) staged = get_staged_signatures(vcs) if sig...
0.002024
async def fetch_token(self): """Fetch new session token from api.""" url = '{}/login'.format(API_URL) payload = 'email={}&password={}'.format(self._email, self._password) reg = await self.api_post(url, None, payload) if reg is None: _LOGGER.error('Unable to authentic...
0.003322
def find_fixtures(fixtures_base_dir: str) -> Iterable[Tuple[str, str]]: """ Finds all of the (fixture_path, fixture_key) pairs for a given path under the JSON test fixtures directory. """ all_fixture_paths = find_fixture_files(fixtures_base_dir) for fixture_path in sorted(all_fixture_paths): ...
0.001953
def to_dataframe(self): """Build a dataframe from the effect collection""" # list of properties to extract from Variant objects if they're # not None variant_properties = [ "contig", "start", "ref", "alt", "is_snv", ...
0.002606
def filter_correlation(self, x_analyte, y_analyte, window=15, r_threshold=0.9, p_threshold=0.05, filt=True, recalc=False): """ Calculate correlation filter. Parameters ---------- x_analyte, y_analyte : str The names of the x and y analytes ...
0.003165
def create_vault_ec2_certificate_configuration(self, cert_name, aws_public_cert, mount_point='aws-ec2'): """POST /auth/<mount_point>/config/certificate/<cert_name> :param cert_name: :type cert_name: :param aws_public_cert: :type aws_public_cert: :param mount_point: ...
0.006504
def open(self, mode='a', **kwargs): """ Open the file in the specified mode Parameters ---------- mode : {'a', 'w', 'r', 'r+'}, default 'a' See HDFStore docstring or tables.open_file for info about modes """ tables = _tables() if self._mode !...
0.000733
def has_no_error( state, incorrect_msg="Have a look at the console: your code contains an error. Fix it and try again!", ): """Check whether the submission did not generate a runtime error. If all SCTs for an exercise pass, before marking the submission as correct pythonwhat will automatically check wh...
0.005155
def delete_vpnservice(self, vpnservice): ''' Deletes the specified VPN service ''' vpnservice_id = self._find_vpnservice_id(vpnservice) ret = self.network_conn.delete_vpnservice(vpnservice_id) return ret if ret else True
0.007463
def _resolve_global_entity(project_or_job_id, folderpath, entity_name, describe=True, visibility="either"): """ :param project_or_job_id: The project ID to which the entity belongs (then the entity is an existing data object), or the job ID to which th...
0.001682
def _process_pod_rate(self, metric_name, metric, scraper_config): """ Takes a simple metric about a pod, reports it as a rate. If several series are found for a given pod, values are summed before submission. """ if metric.type not in METRIC_TYPES: self.log.error("Met...
0.006889
def get_by_number(self, number: int) -> Optional[DataObjectReplica]: """ Gets the data object replica in this collection with the given number. Will return `None` if such replica does not exist. :param number: the number of the data object replica to get :return: the data object ...
0.009434
def RgbToGreyscale(r, g, b): '''Convert the color from RGB to its greyscale equivalent Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (r, g, b) tuple in the ...
0.001901
def ctxtReadMemory(self, buffer, size, URL, encoding, options): """parse an XML in-memory document and build a tree. This reuses the existing @ctxt parser context """ ret = libxml2mod.xmlCtxtReadMemory(self._o, buffer, size, URL, encoding, options) if ret is None:raise treeError('xmlC...
0.012563
def files(self, filters=None): """ A generator that produces a sequence of paths to files in the project that matches the specified filters. :param filters: the regular expressions to use when finding files in the project. If not specified, all files are returned...
0.003035
def translate(obj, vec, **kwargs): """ Translates curves, surface or volumes by the input vector. Keyword Arguments: * ``inplace``: if False, operation applied to a copy of the object. *Default: False* :param obj: input geometry :type obj: abstract.SplineGeometry or multi.AbstractContainer ...
0.002634
def semi_dual_obj_grad(alpha, a, b, C, regul): """ Compute objective value and gradient of semi-dual objective. Parameters ---------- alpha: array, shape = len(a) Current iterate of semi-dual potentials. a: array, shape = len(a) b: array, shape = len(b) Input histograms (sho...
0.001068
def remove_subsegment(self, subsegment): """ Remove input subsegment from child subsegemnts and decrement parent segment total subsegments count. :param Subsegment: subsegment to remove. """ super(Subsegment, self).remove_subsegment(subsegment) self.parent_segmen...
0.005714
def send_message_event(self, room_id, event_type, content, txn_id=None, timestamp=None): """Perform PUT /rooms/$room_id/send/$event_type Args: room_id (str): The room ID to send the message event in. event_type (str): The event type to send. ...
0.004695
def get_json(self, link): """ Returns specified link instance as JSON. :param link: the link instance. :rtype: JSON. """ return json.dumps({ 'id': link.id, 'title': link.title, 'url': link.get_absolute_url(), ...
0.008368
def is_duplicated(self, item): """Check whether the item has been in the cache If the item has not been seen before, then hash it and put it into the cache, otherwise indicates the item is duplicated. When the cache size exceeds capacity, discard the earliest items in the cache. ...
0.001899
def analyse_topology(self,topology, cutoff=3.5): """ In case user wants to analyse only a single topology file, this process will determine the residues that should be plotted and find the ligand atoms closest to these residues. """ self.define_residues_for_plotting_topology(cut...
0.013514
def addOptions(parser, config=Config()): """ Adds toil options to a parser object, either optparse or argparse. """ # Wrapper function that allows toil to be used with both the optparse and # argparse option parsing modules addLoggingOptions(parser) # This adds the logging stuff. if isinsta...
0.005013
def search_query(self, **kwargs): """ Query the Yelp Search API. documentation: https://www.yelp.com/developers/documentation/v3/business_search required parameters: * one of either: * location - text specifying a location to ...
0.009459
def gen_binder_url(fpath, binder_conf, gallery_conf): """Generate a Binder URL according to the configuration in conf.py. Parameters ---------- fpath: str The path to the `.py` file for which a Binder badge will be generated. binder_conf: dict or None The Binder configuration dictio...
0.000615
def recognize_using_websocket(self, audio, content_type, recognize_callback, model=None, language_customization_id=None, ...
0.00833
def reshape_array(data_header, array): """Extract the appropriate array shape from the header. Can handle taking a data header and either bytes containing data or a StructureData instance, which will have binary data as well as some additional information. Parameters ---------- array : :class:...
0.005882
def categories(self): """List[:class:`CategoryChannel`]: A list of categories that belongs to this guild. This is sorted by the position and are in UI order from top to bottom. """ r = [ch for ch in self._channels.values() if isinstance(ch, CategoryChannel)] r.sort(key=lambda c:...
0.011204
def flatten_dir_tree(self, tree): """ Convert a file tree back into a flat dict """ result = {} def helper(tree, leading_path = ''): dirs = tree['dirs']; files = tree['files'] for name, file_info in files.iteritems(): file_info['path'] = leading_path + ...
0.018797
def _check_dataframe(dv=None, between=None, within=None, subject=None, effects=None, data=None): """Check dataframe""" # Check that data is a dataframe if not isinstance(data, pd.DataFrame): raise ValueError('Data must be a pandas dataframe.') # Check that both dv and data a...
0.000587
def itervalues(self, index=None): ''' Iterate through values in the ``index`` (defaults to all indices except the first index). When ``index is None``, yielded values depend on the length of indices (``N``): * if N <= 1: return * if N == 2: yield values in the 2...
0.003656
def is_key(sarg): """Check if `sarg` is a key (eg. -foo, --foo) or a negative number (eg. -33). """ if not sarg.startswith("-"): return False if sarg.startswith("--"): return True return not sarg.lstrip("-").isnumeric()
0.007843
def namespace_absent(name, **kwargs): ''' Ensures that the named namespace is absent. name The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} namespace = __salt__['kubernetes.show_namespace'](name, **kwarg...
0.000719
def message(blockers): """Create a sequence of key messages based on what is blocking.""" if not blockers: encoding = getattr(sys.stdout, 'encoding', '') if encoding: encoding = encoding.lower() if encoding == 'utf-8': # party hat flair = "\U0001F389 ...
0.001546
def event_filter_for_payments( event: architecture.Event, token_network_identifier: TokenNetworkID = None, partner_address: Address = None, ) -> bool: """Filters out non payment history related events - If no other args are given, all payment related events match - If a token networ...
0.003642
def setHeight(self, vehID, height): """setHeight(string, double) -> None Sets the height in m for this vehicle. """ self._connection._sendDoubleCmd( tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_HEIGHT, vehID, height)
0.007937
def find_config_file(self): """ Find where our config file is if there is any If the value for the config file is a default and it doesn't exist then it is silently ignored. If however, the value isn't a default and it doesn't exist, an error is raised "...
0.005202
def _check_and_install_ruby(ret, ruby, default=False, user=None): ''' Verify that ruby is installed, install if unavailable ''' ret = _ruby_installed(ret, ruby, user=user) if not ret['result']: if __salt__['rbenv.install_ruby'](ruby, runas=user): ret['result'] = True ...
0.001515
def _report_connection_status(self, status): """ Report a change in the connection status to any listeners """ for listener in self._connection_listeners: try: self.logger.debug("[%s:%s] connection listener: %x (%s)", self.fn or self.host, se...
0.002882
def start(self, job): """ Start spark and hdfs master containers :param job: The underlying job. """ if self.hostname is None: self.hostname = subprocess.check_output(["hostname", "-f",])[:-1] _log.info("Started Spark master container.") self.sparkC...
0.009189
def column(table_name, column_name=None, cache=False, cache_scope=_CS_FOREVER): """ Decorates functions that return a Series. Decorator version of `add_column`. Series index must match the named table. Column name defaults to name of function. The function's argument names and keyword argument val...
0.001171
def render_generator(self, context, result): """Attempt to serve generator responses through stream encoding. This allows for direct use of cinje template functions, which are generators, as returned views. """ context.response.encoding = 'utf8' context.response.app_iter = ( (i.encode('utf8') if isinst...
0.03304
def get_index_by_alias(self, alias): """Get index name for given alias. If there is no alias assume it's an index. :param alias: alias name """ try: info = self.es.indices.get_alias(name=alias) return next(iter(info.keys())) except elasticsearch....
0.005405
def _get_entity_ids(field_name, attrs): """Find the IDs for a one to many relationship. The server may return JSON data in the following forms for a :class:`nailgun.entity_fields.OneToManyField`:: 'user': [{'id': 1, …}, {'id': 42, …}] 'users': [{'id': 1, …}, {'id': 42, …}] 'user_id...
0.000788
def line(self, x1, y1, x2, y2, color="black", width=1): """ Draws a line between 2 points :param int x1: The x position of the starting point. :param int y1: The y position of the starting point. :param int x2: The x position of the end poin...
0.008816
def count_objects_by_tags(self, metric, scraper_config): """ Count objects by whitelisted tags and submit counts as gauges. """ config = self.object_count_params[metric.name] metric_name = "{}.{}".format(scraper_config['namespace'], config['metric_name']) object_counter = Counter() ...
0.006868
def find_conda(): """ Try to find conda on the system """ USER_HOME = os.path.expanduser('~') CONDA_HOME = os.environ.get('CONDA_HOME', '') PROGRAMDATA = os.environ.get('PROGRAMDATA', '') # Search common install paths and sys path search_paths = [ # Windows join(PROGRAMDATA, 'mi...
0.000991
def post(self, request, bot_id, format=None): """ Add a new hook --- serializer: HookSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request """ return super(Hoo...
0.005525
def _skip_frame(self): """Skip one frame""" self._get_line() num_atoms = int(self._get_line()) if self.num_atoms is not None and self.num_atoms != num_atoms: raise ValueError("The number of atoms must be the same over the entire file.") for i in range(num_atoms+1): ...
0.008671
def tags(): "Get a set of tags for the current git repo." result = [t.decode('ascii') for t in subprocess.check_output([ 'git', 'tag' ]).split(b"\n")] assert len(set(result)) == len(result) return set(result)
0.004237
def forum_topic_delete(self, topic_id): """Delete a topic (Login Requires) (Moderator+) (UNTESTED). Parameters: topic_id (int): Where topic_id is the topic id. """ return self._get('forum_topics/{0}.json'.format(topic_id), method='DELETE', auth=True)
0.00625
def inbreeding_coefficient(g, fill=np.nan): """Calculate the inbreeding coefficient for each variant. Parameters ---------- g : array_like, int, shape (n_variants, n_samples, ploidy) Genotype array. fill : float, optional Use this value for variants where the expected heterozygosit...
0.000651
def mime_type(self): """ :return: String describing the mime type of this file (based on the filename) :note: Defaults to 'text/plain' in case the actual file type is unknown. """ guesses = None if self.path: guesses = guess_type(self.path) return guesses and ...
0.011236
def moving_average(array, n=3): """ Calculates the moving average of an array. Parameters ---------- array : array The array to have the moving average taken of n : int The number of points of moving average to take Returns ------- MovingAverageArray : array ...
0.004175
def reboot(self, uuid): """ Reboot a kvm domain by uuid :param uuid: uuid of the kvm container (same as the used in create) :return: """ args = { 'uuid': uuid, } self._domain_action_chk.check(args) self._client.sync('kvm.reboot', args)
0.00625
def wsgi_extend(self, controller): """ Extends a controller by registering another controller as an extension of it. All actions defined on the extension controller have routes generated for them (only if none already exist) and are made actions of this controller; all e...
0.001524
def get_full_path(self, offset: int = None): """ :return: Returns the full path that will join all fields according to the following format if no offset if provided: 'destination_directory'/'symbol_class'/'raw_file_name_without_extension'_'stroke_thickness'.'extension', e.g.: data/images...
0.004371
def unassign_log_entry_from_log(self, log_entry_id, log_id): """Removes a ``LogEntry`` from a ``Log``. arg: log_entry_id (osid.id.Id): the ``Id`` of the ``LogEntry`` arg: log_id (osid.id.Id): the ``Id`` of the ``Log`` raise: NotFound - ``log_entry_id`` or ``log_id...
0.00188
def retrieve_content(self): """Retrieve the content of a resource.""" path = self._construct_path_to_source_content() res = self._http.get(path) self._populated_fields['content'] = res['content'] return res['content']
0.007782
def _bootstrap_yum( root, pkg_confs='/etc/yum*', pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Bootstrap an image using the yum tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /...
0.002671
def parse_config(config_file=None): ''' Returns a dict of poudriere main configuration definitions CLI Example: .. code-block:: bash salt '*' poudriere.parse_config ''' if config_file is None: config_file = _config_file() ret = {} if _check_config_exists(config_file): ...
0.001653
def _fast_memory_load_bytes(self, addr, length): """ Perform a fast memory loading of some data. :param int addr: Address to read from. :param int length: Size of the string to load. :return: A string or None if the address does not exist. :rtype: bytes ...
0.004283