text
stringlengths
78
104k
score
float64
0
0.18
def ready(self): """ Assumes postgres now talks to pg_ctl, but might not yet be listening or connections from psql. Test that psql is able to connect, as it occasionally takes 5-10 seconds for postgresql to start listening. """ cmd = self._psql_cmd() for i in ran...
0.00361
def console_host(self, new_host): """ If allow remote connection we need to bind console host to 0.0.0.0 """ server_config = Config.instance().get_section_config("Server") remote_console_connections = server_config.getboolean("allow_remote_console") if remote_console_conn...
0.006085
def run_all(self, delay_seconds=0): """ Run all jobs regardless if they are scheduled to run or not. A delay of `delay` seconds is added between each job. This helps distribute system load generated by the jobs more evenly over time. :param delay_seconds: A delay added ...
0.003442
def clear_text(self, label): """stub""" if label not in self.my_osid_object_form._my_map['texts']: raise NotFound() del self.my_osid_object_form._my_map['texts'][label]
0.009804
def _get_device_grain(name, proxy=None): ''' Retrieves device-specific grains. ''' device = _retrieve_device_cache(proxy=proxy) return device.get(name.upper())
0.005587
def create_project(self, key, name, description=""): """ Create project :param key: :param name: :param description: :return: """ url = 'rest/api/1.0/projects' data = {"key": key, "name": name, "description": descrip...
0.005222
def list(self, name, platform='', genre=''): """ The name argument is required for this method as per the API server specification. This method also provides the platform and genre optional arguments as filters. """ data_list = self.db.get_data(self.list_path, name=name, ...
0.003802
def sort_seq_records(self, seq_records): """Checks that SeqExpandedRecords are sorted by gene_code and then by voucher code. The dashes in taxon names need to be converted to underscores so the dataset will be accepted by Biopython to do format conversions. """ for seq_record i...
0.002324
def _really_parse_entity(self): """Actually parse an HTML entity and ensure that it is valid.""" self._emit(tokens.HTMLEntityStart()) self._head += 1 this = self._read(strict=True) if this == "#": numeric = True self._emit(tokens.HTMLEntityNumeric()) ...
0.001378
def checkUserAccess(self): """ Checks if the current user has granted access to this worksheet. Returns False if the user has no access, otherwise returns True """ # Deny access to foreign analysts allowed = True pm = getToolByName(self, "portal_membership") m...
0.002475
def convert_units(self, from_units, to_units): ''' Convert the mesh from one set of units to another. These calls are equivalent: - mesh.convert_units(from_units='cm', to_units='m') - mesh.scale(.01) ''' from blmath import units factor = units.factor( ...
0.004405
def run_command_under_r_root(self, cmd, catched=True): """ subprocess run on here """ RPATH = self.path with self.cd(newdir=RPATH): if catched: process = sp.run(cmd, stdout=sp.PIPE, stderr=sp.PIPE) else: process = sp.run(cmd...
0.005747
def _resolveambig(subseq): """ Randomly resolves iupac hetero codes. This is a shortcut for now, we could instead use the phased alleles in RAD loci. """ N = [] for col in subseq: rand = np.random.binomial(1, 0.5) N.append([_AMBIGS[i][rand] for i in col]) return np.array(N)
0.00627
def setup(self, name_filters=['*.py', '*.pyw'], show_all=False, single_click_to_open=False): """Setup tree widget""" self.setup_view() self.set_name_filters(name_filters) self.show_all = show_all self.single_click_to_open = single_click_to_open ...
0.009132
def for_object(self, instance, flag=''): """ Filter to a specific instance. """ check(instance) content_type = ContentType.objects.get_for_model(instance).pk queryset = self.filter(content_type=content_type, object_id=instance.pk) if flag: queryset = q...
0.00813
def set_focus(self, focus_stage=None, samples=None, subset=None): """ Set the 'focus' attribute of the data file. The 'focus' attribute of the object points towards data from a particular stage of analysis. It is used to identify the 'working stage' of the data. Processing funct...
0.002454
def start(self): """Gets the rtm ws_host and user information Returns: None if request failed, else a dict containing "user"(User) and "ws_host" """ resp = self.post('start') if resp.is_fail(): return None if 'result' not in resp.data...
0.004098
def _sample(self, n_samples): """ Sample Generate samples for posterior distribution using Gauss-Newton proposal parameters Inputs : n_samples : number of samples to generate Hidden Outputs : chain : chain of samples n_samples : ...
0.013446
def create_site(sitename): """Create a new site directory and init Yass""" sitepath = os.path.join(CWD, sitename) if os.path.isdir(sitepath): print("Site directory '%s' exists already!" % sitename) else: print("Creating site: %s..." % sitename) os.makedirs(sitepath) copy_...
0.00189
def _move_agent(self, agent, direction, wrap_allowed=True): """ moves agent 'agent' in 'direction' """ x,y = agent.coords['x'], agent.coords['y'] print('moving agent ', agent.name, 'to x,y=', direction, 'wrap_allowed = ', wrap_allowed) agent.coords['x'] = x + direction[0]...
0.010959
def delete(self): """ Delete the table. Returns: True if the Table no longer exists; False otherwise. """ try: self._api.table_delete(self._name_parts) except google.datalab.utils.RequestException: # TODO(gram): May want to check the error reasons here and if it is not # bec...
0.013483
def _handle_shutdown_reply(self, msg): """ Handle shutdown signal, only if from other console. """ self.log.debug("shutdown: %s", msg.get('content', '')) if not self._hidden and not self._is_from_this_session(msg): if self._local_kernel: if not msg['content'][...
0.010718
def getStatus(rh): """ Get the power (logon/off) status of a virtual machine. Input: Request Handle with the following properties: function - 'POWERVM' subfunction - 'STATUS' userid - userid of the virtual machine Output: Request Handle updated with ...
0.002941
def items( self ): """ Returns all the rollout items for this widget. :return [<XRolloutItem>, ..] """ layout = self.widget().layout() return [layout.itemAt(i).widget() for i in range(layout.count()-1)]
0.019011
def format_op_row(ipFile, totLines, totWords, uniqueWords): """ Format the output row with stats """ txt = os.path.basename(ipFile).ljust(36) + ' ' txt += str(totLines).rjust(7) + ' ' txt += str(totWords).rjust(7) + ' ' txt += str(len(uniqueWords)).rjust(7) + ' ' return txt
0.003268
def getAvailableMethods(self): """ Returns the methods available for this analysis. If the service has the getInstrumentEntryOfResults(), returns the methods available from the instruments capable to perform the service, as well as the methods set manually for the ...
0.002
def get_query(query_id, session, retry_count=5): """attemps to get the query and retry if it cannot""" query = None attempt = 0 while not query and attempt < retry_count: try: query = session.query(Query).filter_by(id=query_id).one() except Exception: attempt += 1...
0.001344
def add_years(dateobj, nb_years): """return `dateobj` + `nb_years` If landing date doesn't exist (e.g. february, 30th), return the last day of the landing month. >>> add_years(date(2018, 1, 1), 1) datetime.date(2019, 1, 1) >>> add_years(date(2018, 1, 1), -1) datetime.date(2017, 1, 1) >...
0.001618
def monitor(name, callback): ''' monitors actions on the specified container, callback is a function to be called on ''' global _monitor if not exists(name): raise ContainerNotExists("The container (%s) does not exist!" % name) if _monitor: if _monitor.is_monitored...
0.006757
def normalize_signature(func): """Decorator. Combine args and kwargs. Unpack single item tuples.""" @wraps(func) def wrapper(*args, **kwargs): if kwargs: args = args, kwargs if len(args) is 1: args = args[0] return func(args) return wrapper
0.003236
def reverse_func(apps, schema_editor): """ manage migrate backup_app 0003_auto_20160127_2002 """ print("\n") remove_count = 0 BackupRun = apps.get_model("backup_app", "BackupRun") backup_runs = BackupRun.objects.all() for backup_run in backup_runs: # Use the origin BackupRun mode...
0.002541
def export_as_string(self): """ Returns a string of CQL queries that can be used to recreate this table along with all indexes on it. The returned string is formatted to be human readable. """ if self._exc_info: import traceback ret = "/*\nWarning...
0.005387
def task_done(self, **kw): """ Marks a pending task as done, optionally specifying a completion date with the 'end' argument. """ def validate(task): if not Status.is_pending(task['status']): raise ValueError("Task is not pending.") return sel...
0.005333
def binaryRecordsStream(self, directory, recordLength): """ Create an input stream that monitors a Hadoop-compatible file system for new files and reads them as flat binary files with records of fixed length. Files must be written to the monitored directory by "moving" them from ...
0.005917
def parse_values_from_lines(self,lines,iskeyword=False): """ cast the string lines for a pest control file into actual inputs Parameters ---------- lines : list strings from pest control file """ if iskeyword: extra = {} for line in ...
0.011292
def scan_list(self, start_time=None, end_time=None, **kwargs): """List scans stored in Security Center in a given time range. Time is given in UNIX timestamps, assumed to be UTC. If a `datetime` is passed it is converted. If `end_time` is not specified it is NOW. If `start_time` is not ...
0.001544
def get_default(self, node): """ If not explicitly set, check if onwrite sets the equivalent """ if node.inst.properties.get("onwrite", None) == rdltypes.OnWriteType.woclr: return True else: return self.default
0.010949
def ddel_tasks(provider, user_ids=None, job_ids=None, task_ids=None, labels=None, create_time_min=None, create_time_max=None): """Kill jobs or job tasks. This function separates ddel logic from flag parsing and user output. U...
0.005578
def fastrcnn_2fc_head(feature): """ Args: feature (any shape): Returns: 2D head feature """ dim = cfg.FPN.FRCNN_FC_HEAD_DIM init = tf.variance_scaling_initializer() hidden = FullyConnected('fc6', feature, dim, kernel_initializer=init, activation=tf.nn.relu) hidden = Full...
0.007212
def next(self) -> Future: """Returns a `.Future` that will yield the next available result. Note that this `.Future` will not be the same object as any of the inputs. """ self._running_future = Future() if self._finished: self._return_result(self._finished.p...
0.005464
def getc(self, block=True): """Return one character from the input queue""" if not block: if not len(self.cookedq): return '' while not len(self.cookedq): time.sleep(0.05) self.IQUEUELOCK.acquire() ret = self.cookedq[0] self.cookedq...
0.005102
def require(self, value): """ Setter for **self.__require** attribute. :param value: Attribute value. :type value: tuple or list """ if value is not None: assert type(value) in (tuple, list), "'{0}' attribute: '{1}' type is not 'tuple' or 'list'!".format( ...
0.007853
def load(self, d3mds): """Load X, y and context from D3MDS.""" X, y = d3mds.get_data() resource_columns = d3mds.get_related_resources(self.data_modality) for resource_column in resource_columns: X = self.load_resources(X, resource_column, d3mds) context = self.get_c...
0.005038
def available_files(self): """ The filenames of the available configuration files (a list of strings). The value of :attr:`available_files` is computed the first time its needed by searching for available configuration files that match :attr:`filename_patterns` using :func:`~glo...
0.002941
def _write(self, session, openFile, replaceParamFile): """ Replace Param File Write to File Method """ # Retrieve TargetParameter objects targets = self.targetParameters # Write lines openFile.write('%s\n' % self.numParameters) for target in targets: ...
0.007538
def diff_info(data): """ >>> diff_info([5,5,10,10,5,5,10,10]) (0, 15) >>> diff_info([5,10,10,5,5,10,10,5]) (15, 0) """ def get_diff(l): diff = 0 for no1, no2 in iter_steps(l, steps=2): diff += abs(no1 - no2) return diff data1 = data[2:] diff1 = ge...
0.004878
def model_deleted(sender, instance, using, **kwargs): """ Automatically triggers "deleted" actions. """ opts = get_opts(instance) model = '.'.join([opts.app_label, opts.object_name]) distill_model_event(instance, model, 'deleted')
0.009804
def configured_logger(self, name=None): """Configured logger. """ log_handlers = self.log_handlers # logname if not name: # base name is always pulsar basename = 'pulsar' # the namespace name for this config name = self.name ...
0.001594
def handler_for_name(fq_name): """Resolves and instantiates handler by fully qualified name. First resolves the name using for_name call. Then if it resolves to a class, instantiates a class, if it resolves to a method - instantiates the class and binds method to the instance. Args: fq_name: fully quali...
0.007926
def connect(self, db_uri, debug=False): """Configure connection to a SQL database. Args: db_uri (str): path/URI to the database to connect to debug (Optional[bool]): whether to output logging information """ kwargs = {'echo': debug, 'convert_unicode': True} ...
0.001878
def _parse_node(graph, text, condition_node_params, leaf_node_params): """parse dumped node""" match = _NODEPAT.match(text) if match is not None: node = match.group(1) graph.node(node, label=match.group(2), **condition_node_params) return node match = _LEAFPAT.match(text) if ...
0.001931
def delete_item(self, table_name, key, expected=None, return_values=None, object_hook=None): """ Delete an item and all of it's attributes by primary key. You can perform a conditional delete by specifying an expected rule. :type table_nam...
0.004438
def btc_is_multisig_segwit(privkey_info): """ Does the given private key info represent a multisig bundle? For Bitcoin, this is true for multisig p2sh (not p2sh-p2wsh) """ try: jsonschema.validate(privkey_info, PRIVKEY_MULTISIG_SCHEMA) if len(privkey_info['private_keys']) == 1: ...
0.002232
def use(wcspkg, raise_err=True): """Choose WCS package.""" global coord_types, wcs_configured, WCS if wcspkg not in common.custom_wcs: # Try to dynamically load WCS modname = 'wcs_%s' % (wcspkg) path = os.path.join(wcs_home, '%s.py' % (modname)) try: my_import(mo...
0.001658
def do_batch(value, linecount, fill_with=None): """ A filter that batches items. It works pretty much like `slice` just the other way round. It returns a list of lists with the given number of items. If you provide a second parameter this is used to fill up missing items. See this example: .. s...
0.001157
def create_or_update_vmextension(call=None, kwargs=None): # pylint: disable=unused-argument ''' .. versionadded:: 2019.2.0 Create or update a VM extension object "inside" of a VM object. required kwargs: .. code-block:: yaml extension_name: myvmextension virtual_machine_name: m...
0.001957
def _get_policies(self, resource_properties): """ Returns a list of policies from the resource properties. This method knows how to interpret and handle polymorphic nature of the policies property. Policies can be one of the following: * Managed policy name: string ...
0.004324
def alias_absent(name, index): ''' Ensure that the index alias is absent. name Name of the index alias to remove index Name of the index for the alias ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} try: alias = __salt__['elasticsearch.alias_...
0.007018
def get_gender(self, name, country=None): """Returns best gender for the given name and country pair""" if not self.case_sensitive: name = name.lower() if name not in self.names: return self.unknown_value elif not country: def counter(country_values):...
0.004499
def _is_mandatory_method_param(self, node): """Check if astroid.Name corresponds to first attribute variable name Name is `self` for method, `cls` for classmethod and `mcs` for metaclass. """ return ( self._first_attrs and isinstance(node, astroid.Name) ...
0.008086
def modifie_many(self, dic: dict): """Convenience function which calls modifie on each element of dic""" for i, v in dic.items(): self.modifie(i, v)
0.011364
def keys_with_value(dictionary, value): "Returns a subset of keys from the dict with the value supplied." subset = [key for key in dictionary if dictionary[key] == value] return subset
0.009524
def _anime_add(self, data): """ Adds an anime to a user's list. :param data: A :class:`Pymoe.Mal.Objects.Anime` object with the anime data :raises: SyntaxError on invalid data type :raises: ServerError on failure to add :rtype: Bool :return: True on success ...
0.006397
def get_adcm(self): """ Absolute deviation around class median (ADCM). Calculates the absolute deviations of each observation about its class median as a measure of fit for the classification method. Returns sum of ADCM over all classes """ adcm = 0 for ...
0.00361
def voxel_count(dset,p=None,positive_only=False,mask=None,ROI=None): ''' returns the number of non-zero voxels :p: threshold the dataset at the given *p*-value, then count :positive_only: only count positive values :mask: count within the given mask :ROI: only use the...
0.015634
def defaults(self): """ Reset the chart options and style to defaults """ self.chart_style = {} self.chart_opts = {} self.style("color", "#30A2DA") self.width(900) self.height(250)
0.05102
def update(self, turret_data): """Update a given turret :param dict turret_data: the data of the turret to update """ if turret_data.get('uuid') not in self.turrets: return False turret = self.turrets[turret_data.get('uuid')] turret.update(**turret_data) ...
0.005525
def get_queryset(self): """Replicates Django CBV `get_queryset()` method, but for MongoEngine. """ if hasattr(self, "queryset") and self.queryset: return self.queryset self.set_mongonaut_base() self.set_mongoadmin() self.document = getattr(self.models, self.d...
0.003911
def add_dependency (self, targets, sources): """Adds a dependency from 'targets' to 'sources' Both 'targets' and 'sources' can be either list of target names, or a single target name. """ if isinstance (targets, str): targets = [targets] if isinstance (source...
0.010811
def getMetadata(self, remote, address, key): """Get metadata of device""" if self._server is not None: # pylint: disable=E1121 return self._server.getAllMetadata(remote, address, key)
0.008969
def dedupe(contains_dupes, threshold=70, scorer=fuzz.token_set_ratio): """This convenience function takes a list of strings containing duplicates and uses fuzzy matching to identify and remove duplicates. Specifically, it uses the process.extract to identify duplicates that score greater than a user defined...
0.004681
def seek(self, offset, whence=Seek.set): # type: (int, SupportsInt) -> int """Change stream position. Change the stream position to the given byte offset. The offset is interpreted relative to the position indicated by ``whence``. Arguments: offset (int): th...
0.001528
def get_notify_observers_kwargs(self): """ Return the mapping between the metrics call and the iterated variables. Return ---------- notify_observers_kwargs: dict, the mapping between the iterated variables. """ return {'x_new': self._linear.adj_op(sel...
0.005195
def get_vulnerability_functions_04(node, fname): """ :param node: a vulnerabilityModel node :param fname: path to the vulnerability file :returns: a dictionary imt, vf_id -> vulnerability function """ logging.warning('Please upgrade %s to NRML 0.5', fname) # NB: the I...
0.000514
def allow_blank(self, form, name): """ Allow blank determines if the form might be completely empty. If it's empty it will result in a None as the saved value for the ForeignKey. """ if self.blank is not None: return self.blank model = form._meta.model ...
0.004878
def extract_angular(fileobj, keywords, comment_tags, options): """Extract messages from angular template (HTML) files. It extract messages from angular template (HTML) files that use angular-gettext translate directive as per https://angular-gettext.rocketeer.be/ :param fileobj: the file-like obje...
0.001056
def cmd_reload(args): '''reload graphs''' mestate.console.writeln('Reloading graphs', fg='blue') load_graphs() setup_menus() mestate.console.write("Loaded %u graphs\n" % len(mestate.graphs))
0.004762
def extract_dynamic_part(uri): """ Extract dynamic url part from :uri: string. :param uri: URI string that may contain dynamic part. """ for part in uri.split('/'): part = part.strip() if part.startswith('{') and part.endswith('}'): return clean_dynamic_uri(part)
0.003247
def _EccZmaxRperiRap(self,*args,**kwargs): """ NAME: EccZmaxRperiRap (_EccZmaxRperiRap) PURPOSE: evaluate the eccentricity, maximum height above the plane, peri- and apocenter for a spherical potential INPUT: Either: a) R,vR,vT,z,vz[,phi]: ...
0.022862
def get_item_project(self, eitem): """ Get the project name related to the eitem :param eitem: enriched item for which to find the project :return: a dictionary with the project data """ eitem_project = {} project = self.find_item_project(eitem) if projec...
0.002907
def benchmark(store, n=10000): """ Increments an integer count n times. """ x = UpdatableItem(store=store, count=0) for _ in xrange(n): x.count += 1
0.005682
def poke_native(getstate): """ Serializer factory for types which state can be natively serialized. Arguments: getstate (callable): takes an object and returns the object's state to be passed to `pokeNative`. Returns: callable: serializer (`poke` routine). """ de...
0.002146
def manifold(self, transformer): """ Creates the manifold estimator if a string value is passed in, validates other objects passed in. """ if not is_estimator(transformer): if transformer not in self.ALGORITHMS: raise YellowbrickValueError( ...
0.002783
def plot4_nolog(self, num): """ Plots the abundances of H-1, He-4, C-12 and O-16. """ self.plot_prof_2(num,'H-1',0.,5.) self.plot_prof_2(num,'He-4',0.,5.) self.plot_prof_2(num,'C-12',0.,5.) self.plot_prof_2(num,'O-16',0.,5.) pyl.legend(loc=3)
0.045307
def Upload(self, fd, sign_fn=None): """Uploads data from a given stream and signs them with a given key.""" if not sign_fn: raise ValueError("sign_fn can't be empty. " "See DefaultUploadSigner as a possible option.") args = binary_management_pb2.ApiUploadGrrBinaryArgs( ...
0.013514
def geo(*params): """ 根据经纬度后去地址 :param params: 经纬度 :return: 地址字符串 """ api = 'http://www.gpsspg.com/apis/maps/geo/' headers = { 'Accept':'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01', 'Accept-Encoding':'gzip, deflate',...
0.008554
def _graph(self): """"Return a graph containing the dependencies of this expression Structure is: [<string expression>, <function name if callable>, <function object if callable>, [subgraph/dependencies, ....]] """ expression = self.expression def walk(node): ...
0.002402
def get_cartesian(r, theta): """ Given a radius and theta, return the cartesian (x, y) coordinates. """ x = r*np.sin(theta) y = r*np.cos(theta) return x, y
0.005556
def reserve(cls, queues, res, worker=None, timeout=10): """Reserve a job on one of the queues. This marks this job so that other workers will not pick it up. """ if isinstance(queues, string_types): queues = [queues] queue, payload = res.pop(queues, timeout=timeout) ...
0.005115
def detect_encoding(string): """ Tries to detect the encoding of the passed string. Defaults to UTF-8. """ assert isinstance(string, bytes) try: detected = chardet.detect(string) if detected: return detected.get('encoding') or 'utf-8' except Exception as e: ...
0.00289
def update_expiry(self, commit=True): """Update token's expiration datetime on every auth action.""" self.expires = update_expiry(self.created) if commit: self.save()
0.009901
def _create_tag_posts_table(self): """ Creates the table to store association info between blog posts and tags. :return: """ with self._engine.begin() as conn: tag_posts_table_name = self._table_name("tag_posts") if not conn.dialect.has_table(conn,...
0.001214
def use_comparative_asset_view(self): """Pass through to provider AssetLookupSession.use_comparative_asset_view""" self._object_views['asset'] = COMPARATIVE # self._get_provider_session('asset_lookup_session') # To make sure the session is tracked for session in self._get_provider_sessio...
0.008869
def get_metadata_value(self, key: str) -> typing.Any: """Get the metadata value for the given key. There are a set of predefined keys that, when used, will be type checked and be interoperable with other applications. Please consult reference documentation for valid keys. If using a cu...
0.007398
def prj_created_data(project, role): """Return the data for created :param project: the project that holds the data :type project: :class:`jukeboxcore.djadapter.models.Project` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the created :rtype: depending on...
0.002273
def pipe(cmd, *arguments, **kwargs): """ Pipe many commands:: >>> noop = pipe(['gzip'], ['gzip'], ['zcat'], ['zcat']) >>> _ = noop.stdin.write('foo'.encode()) # Ignore output in Python 3 >>> noop.stdin.close() >>> print(noop.stdout.read().decode()) foo Returns a Su...
0.001862
def edit_message_live_location(self, *args, **kwargs): """See :func:`edit_message_live_location`""" return edit_message_live_location(*args, **self._merge_overrides(**kwargs)).run()
0.015228
def parse_nestings(string, only_curl=False): r""" References: http://stackoverflow.com/questions/4801403/pyparsing-nested-mutiple-opener-clo CommandLine: python -m utool.util_gridsearch parse_nestings:1 --show Example: >>> # DISABLE_DOCTEST >>> from utool.util_gridsearc...
0.001864
def redirect(self, redirect_error, auth): """Redirect the connection to an alternative endpoint. :param redirect: The Link DETACH redirect details. :type redirect: ~uamqp.errors.LinkRedirect :param auth: Authentication credentials to the redirected endpoint. :type auth: ~uamqp.au...
0.002616
def prerequisite_check(): """ Check prerequisites of the framework, including Python version, installation of modules, etc. Returns: Optional[str]: If the check is not passed, return error message regarding failed test case. None is returned otherwise. """ # Check Python v...
0.004902