text
stringlengths
78
104k
score
float64
0
0.18
def get_stats_action(cachespec, interval): """Action for getting bcache statistics for a given cachespec. Cachespec can either be a device name, eg. 'sdb', which will retrieve cache stats for the given device, or 'global', which will retrieve stats for all cachesets """ if cachespec == 'global':...
0.001848
def register_patch(self, name, path): """ Registers given patch. :param name: Patch name. :type name: unicode :param path: Patch path. :type path: unicode :return: Method success. :rtype: bool """ patch = foundations.strings.get_splitext_...
0.003604
def total_size(self): """ Determine the size (in bytes) of this node. If an array, returns size of the entire array """ if self.inst.is_array: # Total size of arrays is technically supposed to be: # self.inst.array_stride * (self.inst.n_elements-1) + sel...
0.004608
def do_title(s): """Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase. """ return ''.join( [item[0].upper() + item[1:].lower() for item in _word_beginning_split_re.split(soft_unicode(s)) if item])
0.003175
def from_node(cls, work): """Initialize an instance from a :class:`Work` instance.""" new = super().from_node(work) # Will put all files found in outdir in GridFs # Warning: assuming binary files. d = {os.path.basename(f): f for f in work.outdir.list_filepaths()} new.reg...
0.00551
def GetParserAndPluginNames(cls, parser_filter_expression=None): """Retrieves the parser and parser plugin names. Args: parser_filter_expression (Optional[str]): parser filter expression, where None represents all parsers and plugins. Returns: list[str]: parser and parser plugin name...
0.006536
def dropEvent( self, event ): """ Handles the drop event. :param event | <QDropEvent> """ tags = nativestring(event.mimeData().text()) # handle an internal move if event.source() == self: curr_item = self.selectedItems()[0...
0.017319
def replace(self, scaling_group, name, cooldown, min_entities, max_entities, metadata=None): """ Replace an existing ScalingGroup configuration. All of the attributes must be specified. If you wish to delete any of the optional attributes, pass them in as None. """ ...
0.006696
def to_tensor(X, device, accept_sparse=False): """Turn input data to torch tensor. Parameters ---------- X : input data Handles the cases: * PackedSequence * numpy array * torch Tensor * scipy sparse CSR matrix * list or tuple of one of the former *...
0.000585
def run_action(self, feature, action, run_if_error=False, raise_exception=True): """ Run an action, and log it's output in case of errors """ if len(self._error_dict[feature]) > 0 and not run_if_error: return error = None instance = self...
0.004573
def parse_cluster(self, global_params, region, cluster): """ Parse a single EMR cluster :param global_params: Parameters shared for all regions :param region: Name of the AWS region :param cluster: EMR cluster """ cluste...
0.009926
def get_resource_allocation(self): """Get the :py:class:`ResourceAllocation` element tance. Returns: ResourceAllocation: Resource allocation used to access information about the resource where this PE is running. .. versionadded:: 1.9 """ if hasattr(self, 'resourceA...
0.009009
def make_sine_surface(dims=DEFAULT_DIMS, offset=0.5, scale=1.0): """Makes a surface from the 3D sine function. Args: dims (pair): the dimensions of the surface to create offset (float): an offset applied to the function scale (float): a scale applied to the sine frequency Returns: ...
0.002075
def dumps(obj, decimals=16): """ Dump a GeoJSON-like `dict` to a WKT string. """ try: geom_type = obj['type'] exporter = _dumps_registry.get(geom_type) if exporter is None: _unsupported_geom_type(geom_type) # Check for empty cases if geom_type == 'Ge...
0.000649
def new_run(self): """Creates a new RunData object and increments pointers""" self.current_run += 1 self.runs.append(RunData(self.current_run + 1))
0.011696
def g(self, id): """ If the given id is known, the numerical representation is returned, otherwise a new running number is assigned to the id and returned""" if id not in self._m: if self.orig_ids: self._m[id] = id if self.warn: ...
0.004511
def convert(self, destination_units): """Convert units. Parameters ---------- destination_units : string (optional) Units to convert into. """ if not wt_units.is_valid_conversion(self.units, destination_units): kind = wt_units.kind(self.units) ...
0.004115
def get_values(self, obj): """get label and shape for classes. The label contains all attributes and methods """ label = obj.title if obj.shape == "interface": label = "«interface»\\n%s" % label if not self.config.only_classnames: label = r"%s|%s\...
0.004054
def _getExperimentDescriptionSchema(): """ Returns the experiment description schema. This implementation loads it in from file experimentDescriptionSchema.json. Parameters: -------------------------------------------------------------------------- Returns: returns a dict representing the experiment des...
0.011194
def produce_characteristic_explorer(corpus, category, category_name=None, not_category_name=None, not_categories=None, characteristic_scorer...
0.002607
def bounds(self): """Gets the bounds of a tile represented as the most west and south point and the most east and north point""" google_x, google_y = self.google pixel_x_west, pixel_y_north = google_x * TILE_SIZE, google_y * TILE_SIZE pixel_x_east, pixel_y_south = (google_x + 1) * TILE_S...
0.011986
def valid_file(cls, filename): """ Check if the provided file is a valid file for this plugin. :arg filename: the path to the file to check. """ return not os.path.isdir(filename) \ and os.path.basename(filename).startswith('Session ') \ and filename.endswith('....
0.006154
def norm(x, mu, sigma=1.0): """ Scipy norm function """ return stats.norm(loc=mu, scale=sigma).pdf(x)
0.009174
def _compile(self, p): """ Recursively compiles the regexs in the pattern (p). """ if self._is_value_filter(p) and p[0] == '=~': try: p[2] = re.compile(p[2]) except: # Python doesn't document exactly what exceptions re.compile throws ...
0.007561
def spawn_isolated_child(self): """ Fork or launch a new child off the target context. :returns: mitogen.core.Context of the new child. """ return self.get_chain(use_fork=True).call( ansible_mitogen.target.spawn_isolated_child )
0.006645
def _chown(self, path, uid, gid): """Change the *owner* of a resource. """ if uid is None or gid is None: info = self.getinfo(path, namespaces=('access',)) uid = uid or info.get('access', 'uid') gid = gid or info.get('access', 'gid') self._sftp.chown(p...
0.005988
def stream_download(self, chunk_size: Optional[int] = None, callback: Optional[Callable] = None) -> AsyncIterator[bytes]: """Generator for streaming request body data. """ chunk_size = chunk_size or CONTENT_CHUNK_SIZE async def async_gen(resp): while True: chu...
0.007952
def current_custom_claims(): """ This method returns any custom claims in the current jwt """ jwt_data = get_jwt_data_from_app_context() return {k: v for (k, v) in jwt_data.items() if k not in RESERVED_CLAIMS}
0.004367
def make_qs(n, m=None): """Make sympy symbols q0, q1, ... Args: n(int), m(int, optional): If specified both n and m, returns [qn, q(n+1), ..., qm], Only n is specified, returns[q0, q1, ..., qn]. Return: tuple(Symbol): Tuple of sympy symbols. """ try: ...
0.002584
def zeroize(): ''' Resets the device to default factory settings CLI Example: .. code-block:: bash salt 'device_name' junos.zeroize ''' conn = __proxy__['junos.conn']() ret = {} ret['out'] = True try: conn.cli('request system zeroize') ret['message'] = 'Com...
0.001984
def opener(ip_address, port, delay=1): """ Wait a little and then open a web browser page for the control panel. """ global WEBPAGE_OPENED if WEBPAGE_OPENED: return WEBPAGE_OPENED = True raw_opener(ip_address, port, delay)
0.003876
def no_param_shortcut(parser, token): """ Shortcut to transmogrify thumbnail """ bits = smart_split(token.contents) tagname = bits.next() try: imageurl = bits.next() except StopIteration: raise template.TemplateSyntaxError("%r tag requires at least the image url" % tagname) ...
0.00542
def wait(fs, timeout=-1, return_when=ALL_COMPLETED): """Wait for the futures in the given sequence to complete. Using this function may prevent a worker from executing. :param fs: The sequence of Futures to wait upon. :param timeout: The maximum number of seconds to wait. If negative or not spe...
0.000721
def distributions_route(self, request): """Given a tag and single run, return an array of compressed histograms.""" tag = request.args.get('tag') run = request.args.get('run') try: (body, mime_type) = self.distributions_impl(tag, run) code = 200 except ValueError as e: (body, mime_...
0.011547
def setColor(self, poiID, color): """setColor(string, (integer, integer, integer, integer)) -> None Sets the rgba color of the poi. """ self._connection._beginMessage( tc.CMD_SET_POI_VARIABLE, tc.VAR_COLOR, poiID, 1 + 1 + 1 + 1 + 1) self._connection._string += struct...
0.004338
def on_decks(self, *args): """Inform the cards of their deck and their index within the deck; extend the ``_hint_offsets`` properties as needed; and trigger a layout. """ if None in ( self.canvas, self.decks, self.deck_x_hint_offse...
0.001364
def recurring(self, offset=0, count=25): '''Return all the recurring jobs''' return self.client('jobs', 'recurring', self.name, offset, count)
0.012658
def read(url, **args): """Loads an object from a data URI.""" info, data = url.path.split(',') info = data_re.search(info).groupdict() mediatype = info.setdefault('mediatype', 'text/plain;charset=US-ASCII') if ';' in mediatype: mimetype, params = mediatype.split(';', 1) params = [p.s...
0.001623
def selection(self): """ Selection property. :return: None if no font is selected and font family name if one is selected. :rtype: None or str """ selection = self.listbox.curselection() if len(selection) is 0: return None retu...
0.010753
def readedf(filename): """Read an ESRF data file (measured at beamlines ID01 or ID02) Inputs ------ filename: string the input file name Output ------ the imported EDF structure in a dict. The scattering pattern is under key 'data'. Notes ----- Only datatype ``Floa...
0.001287
def get_users_by_tag(self, tag_id, next_open_id=""): """ 获取标签下粉丝列表 :param tag_id: 标签 ID :param next_open_id: 第一个拉取用户的 OPENID,默认从头开始拉取 :return: 返回的 JSON 数据包 """ return self.post( url="https://api.weixin.qq.com/cgi-bin/user/tag/get", data={ ...
0.004762
def focusInEvent(self, event): """ When this widget loses focus, try to emit the record changed event signal. """ self._changedRecord = -1 super(XOrbRecordBox, self).focusInEvent(event)
0.008368
def _count_citations(aux_file): ''' Counts the citations in an aux-file. @return: defaultdict(int) - {citation_name: number, ...} ''' counter = defaultdict(int) with open(aux_file) as fobj: content = fobj.read() for match in CITE_PATTERN.finditer(content): name = match.grou...
0.002674
def insert_graph(cur, nodelist, edgelist, encoded_data=None): """Insert a graph into the cache. A graph is stored by number of nodes, number of edges and a json-encoded list of edges. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a ...
0.00049
def _run_server(self): """ 启动 HTTP Server """ try: if __conf__.DEBUG: self._webapp.listen(self._port) else: server = HTTPServer(self._webapp) server.bind(self._port) server.start(0) ...
0.007109
def _update_targets(vesseldicts, environment_dict): """ <Purpose> Connects to the nodes in the vesseldicts and adds them to the list of valid targets. <Arguments> vesseldicts: A list of vesseldicts obtained through SeattleClearinghouseClient calls. <Side Effects> All valid targ...
0.013445
def mavlink_packet(self, m): '''handle mavlink packets''' if m.get_type() == 'GLOBAL_POSITION_INT': if self.settings.target_system == 0 or self.settings.target_system == m.get_srcSystem(): self.packets_mytarget += 1 else: self.packets_othertarget +...
0.009288
def get_ht_mcs(mcs): """http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/util.c?id=v3.17#n591. Positional arguments: mcs -- bytearray. Returns: Dict. """ answers = dict() max_rx_supp_data_rate = (mcs[10] & ((mcs[11] & 0x3) << 8)) tx_mcs_set_defined = not not (mcs[12] &...
0.001854
def _mine_delete(self, load): ''' Allow the minion to delete a specific function from its own mine :param dict load: A payload received from a minion :rtype: bool :return: Boolean indicating whether or not the given function was deleted from the mine ''' load = ...
0.006237
def forum_post_update(self, topic_id, body): """Update a specific forum post (Requries login)(Moderator+)(UNTESTED). Parameters: post_id (int): Forum topic id. body (str): Post content. """ params = {'forum_post[body]': body} return self._get('forum_posts...
0.004926
def _call(ins): """ Calls a function XXXX (or address XXXX) 2nd parameter contains size of the returning result if any, and will be pushed onto the stack. """ output = [] output.append('call %s' % str(ins.quad[1])) try: val = int(ins.quad[2]) if val == 1: output....
0.001555
def getMeta(self, uri): """Return meta information about an action. Cache the result as specified by the server""" action = urlparse(uri).path mediaKey = self.cacheKey + '_meta_' + action mediaKey = mediaKey.replace(' ', '__') meta = cache.get(mediaKey, None) # Nothin...
0.005825
def fromEpoch(cls, epoch_time): ''' a method for constructing a labDT object from epoch timestamp :param epoch_time: number with epoch timestamp info :return: labDT object ''' # validate input title = 'Epoch time input for labDT.fromEpoch' if not isinstan...
0.003319
def _variant_levels(level, variant): """ Gets the level for the variant. :param int level: the current variant level :param int variant: the value for this level if variant :returns: a level for the object and one for the function :rtype: int * int """ r...
0.007299
def removeLogbook(self, menu=None): '''Remove logbook menu set.''' if self.logMenuCount > 1 and menu is not None: menu.removeMenu() self.logMenus.remove(menu) self.logMenuCount -= 1
0.008584
def create(vm_): ''' Create a single VM from a data dict ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'azu...
0.001057
def handle_challenge(self,data): """ Executed when the server requests additional authentication """ # Send challenge response self.send_message(AUTHENTICATE( signature = self.password, extra = {} ))
0.025455
def _call(self, method, params): """Call a method. :param method: method to call :param params: dict with the HTTP parameters needed to call the given method :raises ConduitError: when an error is returned by the server """ url = self.URL % {'base': self.bas...
0.001932
def db_exec_literal(self, sql: str) -> int: """Executes SQL without modification. Returns rowcount.""" self.ensure_db_open() cursor = self.db.cursor() debug_sql(sql) try: cursor.execute(sql) return cursor.rowcount except: # nopep8 log....
0.005222
def create_account(self, email, password=None, attrs={}): """ :param email: Full email with domain eg: login@domain.com :param password: Password for local auth :param attrs: a dictionary of attributes to set ({key:value,...}) :returns: the created zobjects.Account ...
0.003236
def sample_multinomial(N, p, size=None): r""" Draws fixed number of samples N from different multinomial distributions (with the same number dice sides). :param int N: How many samples to draw from each distribution. :param np.ndarray p: Probabilities specifying each distribution. Sum along...
0.001342
def add(self, entries=None, force=False, allow_address_duplication=False): """ Add instances of HostsEntry to the instance of Hosts. :param entries: A list of instances of HostsEntry :param force: Remove matching before adding :param allow_address_duplication: Allow using multipl...
0.001287
def _compute_missing_rates(self, currency): """Fill missing rates of a currency. This is done by linear interpolation of the two closest available rates. :param str currency: The currency to fill missing rates for. """ rates = self._rates[currency] # tmp will store the...
0.003984
def maintained_selection(): """Maintain selection during context Example: >>> with maintained_selection(): ... # Modify selection ... node.setSelected(on=False, clear_all_selected=True) >>> # Selection restored """ previous_selection = hou.selectedNodes() t...
0.001761
def append_cluster(self, cluster, data = None, marker = '.', markersize = None, color = None): """! @brief Appends cluster for visualization. @param[in] cluster (list): cluster that may consist of indexes of objects from the data or object itself. @param[in] data (list): If defines...
0.013274
def redirect_from_callback(self): '''Redirect to the callback URL after a successful authentication.''' state = toolkit.request.params.get('state') came_from = get_came_from(state) toolkit.response.status = 302 toolkit.response.location = came_from
0.006944
def write_comment(self, comment): """ Write a comment into the header """ self._FITS.write_comment(self._ext+1, str(comment))
0.012739
def addNewRole(self, txn): """ Adds a new client or steward to this node based on transaction type. """ # If the client authenticator is a simple authenticator then add verkey. # For a custom authenticator, handle appropriately. # NOTE: The following code should not be u...
0.002564
def merge(assembled_gtfs, ref_file, gtf_file, num_cores, data): """ run cuffmerge on a set of assembled GTF files """ assembled_file = tempfile.NamedTemporaryFile(delete=False).name with open(assembled_file, "w") as temp_handle: for assembled in assembled_gtfs: temp_handle.write(...
0.000702
def get_release_data(self, package_name: str, version: str) -> Tuple[str, str, str]: """ Returns ``(package_name, version, manifest_uri)`` associated with the given package name and version, *if* they are published to the currently set registry. * Parameters: * ``name``: Mus...
0.007485
def write_result(self, data): """Write the results received to the database :param dict data: the data to save in database :return: None """ data['custom_timers'] = ujson.dumps(data['custom_timers']) self.results.append(data) if len(self.results) >= 150: # 150 r...
0.003831
def start_connect(self): """Tries to connect to the Heron Server ``loop()`` method needs to be called after this. """ Log.debug("In start_connect() of %s" % self._get_classname()) # TODO: specify buffer size, exception handling self.create_socket(socket.AF_INET, socket.SOCK_STREAM) # when ...
0.002433
def get_param(self, param, default=None): """ Get a parameter in config (handle default value) :param param: name of the parameter to recover :type param: string :param default: the default value, raises an exception if param is not in configuration and default i...
0.002821
def _set_emails( self, emails, global_substitutions=None, is_multiple=False, p=0): """Adds emails to the Personalization object :param emails: An Email or list of Email objects :type emails: Email, list(Email) :param global_substitutions: A dict of substitutions for all reci...
0.000796
def upgrade(): """Upgrade database.""" op.create_table( 'oauthclient_remoteaccount', sa.Column('id', sa.Integer(), nullable=False), sa.Column('user_id', sa.Integer(), nullable=False), sa.Column('client_id', sa.String(length=255), nullable=False), sa.Column( 'e...
0.000587
def find_level_aliases(): """ Find log level names which are aliases of each other. :returns: A dictionary that maps aliases to their canonical name. .. note:: Canonical names are chosen to be the alias with the longest string length so that e.g. ``WARN`` is an alias for ``WARNING`` ...
0.000978
def get_product(config): """Get the /product/<product> resource from LTD Keeper. """ product_url = config['keeper_url'] + '/products/{p}'.format( p=config['ltd_product']) r = requests.get(product_url) if r.status_code != 200: raise RuntimeError(r.json()) product_info = r.json() ...
0.002924
def is_condition_met(self, hand, win_tile, melds, is_tsumo): """ Three closed pon sets, the other sets need not to be closed :param hand: list of hand's sets :param win_tile: 136 tiles format :param melds: list Meld objects :param is_tsumo: :return: true|false ...
0.003074
def tags(self): '''Return a list of all tags that have this semantic tag, sorted by name. :rtype: list of ckan.model.tag.Tag objects ''' q = meta.Session.query(_tag.Tag) q = q.join(TagSemanticTag) q = q.filter_by(tag_id=self.id) # q = q.filter_by(state='active') q = q.order_by(_tag.Tag.name) tags = q...
0.035294
def clone(cls, srcpath, destpath): """Copy a main repository to a new location.""" try: os.makedirs(destpath) except OSError as e: if not e.errno == errno.EEXIST: raise cmd = [SVNADMIN, 'dump', '--quiet', '.'] dump = subprocess.Popen( ...
0.00274
def walk(self, node, *listeners:RDLListener): """ Initiates the walker to traverse the current ``node`` and its children. Calls the corresponding callback for each of the ``listeners`` provided in the order that they are listed. Parameters ---------- node : :clas...
0.007277
def omim_terms(case_obj): """Extract all OMIM phenotypes available for the case Args: case_obj(dict): a scout case object Returns: disorders(list): a list of OMIM disorder objects """ LOG.info("Collecting OMIM disorders for case {}".format(case_obj.get('display_name'))) disorders...
0.007899
def filter_pem(data): '''Processes the bytes for PEM certificates. Returns: ``set`` containing each certificate ''' assert isinstance(data, bytes), 'Expect bytes. Got {}.'.format(type(data)) certs = set() new_list = [] in_pem_block = False for line in re.split(br'[\r\n]+', data...
0.001117
def comments(self): # pylint: disable=E0202 """Return forest of comments, with top-level comments as tree roots. May contain instances of MoreComment objects. To easily replace these objects with Comment objects, use the replace_more_comments method then fetch this attribute. Use comme...
0.002933
def trace_error(function_index=2): """ This will return the line number and line text of the last error :param function_index: int to tell what frame to look from :return: int, str of the line number and line text """ info = function_info(function_index) traces = traceback.format_stack(limit...
0.003231
def new_model(self, info): """ Handles the new Graph action. """ if info.initialized: retval = confirm(parent = info.ui.control, message = "Replace existing graph?", title = "New Graph", default = YES)...
0.031008
def sort_descendants(self, attr="name"): """ This function sort the branches of a given tree by considerening node names. After the tree is sorted, nodes are labeled using ascendent numbers. This can be used to ensure that nodes in a tree with the same node names are always ...
0.004065
def bend(mapping, source, context=None): """ The main bending function. mapping: the map of benders source: a dict to be bent returns a new dict according to the provided map. """ context = {} if context is None else context transport = Transport(source, context) return _bend(mappi...
0.002994
def compile_instance_masks(cls): """ Compiles instance masks into a master mask that is usable by the IO expander. Also determines whether or not the pump should be on. Method is generalized to support multiple IO expanders for possible future expansi...
0.003676
def connect_to_endpoints_blocking(self, *endpoints: ConnectionConfig, timeout: int=30) -> None: """ Connect to the given endpoints and block until the connection to every endpoint is established. Raises a ``TimeoutError`` if connections do not become available within ``timeout`` seconds ...
0.012478
def save_repo_cache(i): """ Input: {} Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } """ r=save_json_to_file({'json_file':work['dir_cache_repo_uoa'],...
0.026769
def weights(self, other): """ Compute weights, given a scale or time-frequency representation :param other: A time-frequency representation, or a scale :return: a numpy array of weights """ try: return self._wdata(other) except AttributeError: ...
0.004854
def LOS_get_sample(D, u, dL, DL=None, dLMode='abs', method='sum', Test=True): """ Return the sampled line, with the specified method 'linspace': return the N+1 edges, including the first and last point 'sum' : return the N middle of the segments 'simps': return the N+1 egdes, where N has to be even (sc...
0.018792
def setUserPasswdCredentials(self, username, password): """Set username and password in ``disk.0.os.credentials``.""" self.setCredentialValues(username=username, password=password)
0.010152
def values(self, desc = None): '''numpy asarray does not copy data''' if self._ts: res = asarray(self._ts) if desc == True: return reversed(res) else: return res else: return ndarray([0,0])
0.019868
def evaluate(self, dataset, metric='auto', batch_size=None, verbose=True): """ Evaluate the model by making predictions of target values and comparing these to actual values. Parameters ---------- dataset : SFrame Dataset of new observations. Must inc...
0.00496
def send_mail(recipient_list, subject, body, html=False, from_address=None): """ :param recipient_list: List of recipients i.e. ['testing@fig14.com', 'Stephen Brown <steve@fig14.com>'] :param subject: The subject :param body: The email body :param html: Is this a html email? Defaults to False :p...
0.004193
def remove_repo(self, repo, team): """Remove ``repo`` from ``team``. :param str repo: (required), form: 'user/repo' :param str team: (required) :returns: bool """ for t in self.iter_teams(): if team == t.name: return t.remove_repo(repo) ...
0.005988
def train(self, x, drop=False, na_rm=False): """ Train discrete range """ self.range = scale_discrete.train(x, self.range, drop, na_rm=na_rm)
0.011561
def send_data(self, endpoint=None, **kwargs): """Sends data to the API. This call is similar to ``fetch``, but **sends** data to the API instead of retrieving it. Returned data will appear in the ``items`` key of the resulting dictionary. Sending data **requires** tha...
0.003873