code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def pull_image(self, image_name, stream=None): stream_writer = stream or StreamWriter(sys.stderr) try: result_itr = self.docker_client.api.pull(image_name, stream=True, decode=True) except docker.errors.APIError as ex: LOG.debug("Failed to download image with name %s", im...
Ask Docker to pull the container image with given name. Parameters ---------- image_name str Name of the image stream samcli.lib.utils.stream_writer.StreamWriter Optional stream writer to output to. Defaults to stderr Raises ------ Docker...
def getall(self): vrfs_re = re.compile(r'(?<=^vrf definition\s)(\w+)', re.M) response = dict() for vrf in vrfs_re.findall(self.config): response[vrf] = self.get(vrf) return response
Returns a dict object of all VRFs in the running-config Returns: A dict object of VRF attributes
def artboards(src_path): pages = list_artboards(src_path) artboards = [] for page in pages: artboards.extend(page.artboards) return artboards
Return artboards as a flat list
def getHourTable(date, pos): table = hourTable(date, pos) return HourTable(table, date)
Returns an HourTable object.
def get_query_str(query: Type[QueryDict], max_length: int = 1024) -> str: query_dict = query.copy() query_dict.pop('password', None) query_dict.pop(settings.AXES_PASSWORD_FORM_FIELD, None) query_str = '\n'.join( f'{key}={value}' for key, value in query_dict.items() ) retu...
Turns a query dictionary into an easy-to-read list of key-value pairs. If a field is called either ``'password'`` or ``settings.AXES_PASSWORD_FORM_FIELD`` it will be excluded. The length of the output is limited to max_length to avoid a DoS attack via excessively large payloads.
def append_var_uint32(self, value): if not 0 <= value <= wire_format.UINT32_MAX: raise errors.EncodeError('Value out of range: %d' % value) self.append_var_uint64(value)
Appends an unsigned 32-bit integer to the internal buffer, encoded as a varint.
def getTimeSinceLastVsync(self): fn = self.function_table.getTimeSinceLastVsync pfSecondsSinceLastVsync = c_float() pulFrameCounter = c_uint64() result = fn(byref(pfSecondsSinceLastVsync), byref(pulFrameCounter)) return result, pfSecondsSinceLastVsync.value, pulFrameCounter.value
Returns the number of elapsed seconds since the last recorded vsync event. This will come from a vsync timer event in the timer if possible or from the application-reported time if that is not available. If no vsync times are available the function will return zero for vsync time and frame...
def capture_packet(self): data = self.socket.recv(self._buffer_size) for h in self.capture_handlers: h['reads'] += 1 h['data_read'] += len(data) d = data if 'pre_write_transforms' in h: for data_transform in h['pre_write_transforms']: ...
Write packet data to the logger's log file.
def getAllNodeUids(self): ret = { self.uid } ret.update(self.getAllChildNodeUids()) return ret
getAllNodeUids - Returns all the unique internal IDs from getAllChildNodeUids, but also includes this tag's uid @return set<uuid.UUID> A set of uuid objects
def is_main_variation(self) -> bool: if not self.parent: return True return not self.parent.variations or self.parent.variations[0] == self
Checks if this node is the first variation from the point of view of its parent. The root node is also in the main variation.
def _read_until(infile=sys.stdin, maxchars=20, end=RS): chars = [] read = infile.read if not isinstance(end, tuple): end = (end,) while maxchars: char = read(1) if char in end: break chars.append(char) maxchars -= 1 return ''.join(chars)
Read a terminal response of up to a few characters from stdin.
def remove_callback(self, callback, msg_type=None): if msg_type is None: msg_type = self._callbacks.keys() cb_keys = self._to_iter(msg_type) if cb_keys is not None: for msg_type_ in cb_keys: try: self._callbacks[msg_type_].remove(callba...
Remove per message type of global callback. Parameters ---------- callback : fn Callback function msg_type : int | iterable Message type to remove callback from. Default `None` means global callback. Iterable type removes the callback from all the message t...
def stonith_create(stonith_id, stonith_device_type, stonith_device_options=None, cibfile=None): return item_create(item='stonith', item_id=stonith_id, item_type=stonith_device_type, extra_args=stonith_device_options, cibfile...
Create a stonith resource via pcs command stonith_id name for the stonith resource stonith_device_type name of the stonith agent fence_eps, fence_xvm f.e. stonith_device_options additional options for creating the stonith resource cibfile use cibfile instead of the live ...
def v1_tag_associate(request, tags, tag): tag = tag.decode('utf-8').strip() assoc = dict(json.loads(request.body.read()), **{'tag': tag}) tags.add(assoc)
Associate an HTML element with a tag. The association should be a JSON serialized object on the request body. Here is an example association that should make the object's structure clear: .. code-block:: python { "url": "http://example.com/abc/xyz?foo=bar", "text": "Th...
def getedges(fname, iddfile): data, commdct, _idd_index = readidf.readdatacommdct(fname, iddfile=iddfile) edges = makeairplantloop(data, commdct) return edges
return the edges of the idf file fname
def gff3_to_recarray(path, attributes=None, region=None, score_fill=-1, phase_fill=-1, attributes_fill='.', tabix='tabix', dtype=None): recs = list(iter_gff3(path, attributes=attributes, region=region, score_fill=score_fill, phase_fill=phase_fill, ...
Load data from a GFF3 into a NumPy recarray. Parameters ---------- path : string Path to input file. attributes : list of strings, optional List of columns to extract from the "attributes" field. region : string, optional Genome region to extract. If given, file must be posi...
def update_workspace_attributes(namespace, workspace, attrs): headers = _fiss_agent_header({"Content-type": "application/json"}) uri = "{0}workspaces/{1}/{2}/updateAttributes".format(fcconfig.root_url, namespace, workspace) body = json.dumps(attrs) ...
Update or remove workspace attributes. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name attrs (list(dict)): List of update operations for workspace attributes. Use the helper dictionary construction functions to create these: ...
def depth(sequence, func=max, _depth=0): if isinstance(sequence, dict): sequence = list(sequence.values()) depth_list = [depth(item, func=func, _depth=_depth + 1) for item in sequence if (isinstance(item, dict) or util_type.is_listlike(item))] if len(depth_list) > 0: return...
Find the nesting depth of a nested sequence
def from_str(cls, string): return cls([Literal.from_str(lit) for lit in string.split('+')])
Creates a clause from a given string. Parameters ---------- string: str A string of the form `a+!b` which translates to `a AND NOT b`. Returns ------- caspo.core.clause.Clause Created object instance
def get_automatic_parser(exim_id, infile): adapter = getExim(exim_id) if IInstrumentAutoImportInterface.providedBy(adapter): return adapter.get_automatic_parser(infile) parser_func = filter(lambda i: i[0] == exim_id, PARSERS) parser_func = parser_func and parser_func[0][1] or None if not par...
Returns the parser to be used by default for the instrument id interface and results file passed in.
def iter_issues(self, milestone=None, state=None, assignee=None, mentioned=None, labels=None, sort=None, direction=None, since=None, number=...
Iterate over issues on this repo based upon parameters passed. .. versionchanged:: 0.9.0 The ``state`` parameter now accepts 'all' in addition to 'open' and 'closed'. :param int milestone: (optional), 'none', or '*' :param str state: (optional), accepted values: ('all'...
def change_directory(self, directory): self._process.write(('cd %s\n' % directory).encode()) if sys.platform == 'win32': self._process.write((os.path.splitdrive(directory)[0] + '\r\n').encode()) self.clear() else: self._process.write(b'\x0C')
Changes the current directory. Change is made by running a "cd" command followed by a "clear" command. :param directory: :return:
def _sync_enter(self): if hasattr(self, 'loop'): loop = self.loop else: loop = self._client.loop if loop.is_running(): raise RuntimeError( 'You must use "async with" if the event loop ' 'is running (i.e. you are inside an "async def")' ) return loo...
Helps to cut boilerplate on async context managers that offer synchronous variants.
def max_or(a, b, c, d, w): m = (1 << (w - 1)) while m != 0: if (b & d & m) != 0: temp = (b - m) | (m - 1) if temp >= a: b = temp break temp = (d - m) | (m - 1) if temp >= c: ...
Upper bound of result of ORing 2-intervals. :param a: Lower bound of first interval :param b: Upper bound of first interval :param c: Lower bound of second interval :param d: Upper bound of second interval :param w: bit width :return: Upper bound of ORing 2-intervals
def netmask(mask): if not isinstance(mask, string_types): return False octets = mask.split('.') if not len(octets) == 4: return False return ipv4_addr(mask) and octets == sorted(octets, reverse=True)
Returns True if the value passed is a valid netmask, otherwise return False
def complain(error): if callable(error): if DEVELOP: raise error() elif DEVELOP: raise error else: logger.warn_err(error)
Raises in develop; warns in release.
def generate_config(directory): default_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "config.yml") target_config_path = os.path.abspath(os.path.join(directory, 'config.yml')) shutil.copy(default_config, target_config_path) six.print_("Config file has been generated in", target_conf...
Generate default config file
def is_in(self, search_list, pair): index = -1 for nr, i in enumerate(search_list): if(np.all(i == pair)): return nr return index
If pair is in search_list, return the index. Otherwise return -1
def tabFileNameChanged(self, tab): if tab == self.currentTab: if tab.fileName: self.setWindowTitle("") if globalSettings.windowTitleFullPath: self.setWindowTitle(tab.fileName + '[*]') self.setWindowFilePath(tab.fileName) self.tabWidget.setTabText(self.ind, tab.getBaseName()) self.tabWidget...
Perform all UI state changes that need to be done when the filename of the current tab has changed.
def get_subkey(self,name): subkey = Key(name,self) try: hkey = subkey.hkey except WindowsError: raise AttributeError("subkey '%s' does not exist" % (name,)) return subkey
Retreive the subkey with the specified name. If the named subkey is not found, AttributeError is raised; this is for consistency with the attribute-based access notation.
def setColor(self, color): if color == 'blue': self.color = 'blue' self.colorCode = self.colors['blue'] self.colorCodeDark = self.colors['dblue'] elif color == 'red': self.color = 'red' self.colorCode = self.colors['red'] self.color...
Sets Card's color and escape code.
def flatten_spec(spec, prefix,joiner=" :: "): if any(filter(operator.methodcaller("startswith","Test"),spec.keys())): flat_spec = {} for (k,v) in spec.items(): flat_spec.update(flatten_spec(v,prefix + joiner + k[5:])) return flat_spec else: return {"Test "+prefix: spec}
Flatten a canonical specification with nesting into one without nesting. When building unique names, concatenate the given prefix to the local test name without the "Test " tag.
def All(*validators): @wraps(All) def built(value): for validator in validators: value = validator(value) return value return built
Combines all the given validator callables into one, running all the validators in sequence on the given value.
def parse_partial(self, text): if not isinstance(text, str): raise TypeError( 'Can only parsing string but got {!r}'.format(text)) res = self(text, 0) if res.status: return (res.value, text[res.index:]) else: raise ParseError(res.expect...
Parse the longest possible prefix of a given string. Return a tuple of the result value and the rest of the string. If failed, raise a ParseError.
def FundamentalType(self, _type): log.debug('HERE in FundamentalType for %s %s', _type, _type.name) if _type.name in ["None", "c_long_double_t", "c_uint128", "c_int128"]: self.enable_fundamental_type_wrappers() return _type.name return "ctypes.%s" % (_type.name)
Returns the proper ctypes class name for a fundamental type 1) activates generation of appropriate headers for ## int128_t ## c_long_double_t 2) return appropriate name for type
def execute_with_retries(retryable_function, retryable_errors, logger, human_readable_action_name='Action', nonretryable_errors=None): max_retries = 10 attempt = 0 if not nonretryable_errors: nonretry...
This attempts to execute "retryable_function" with exponential backoff on delay time. 10 retries adds up to about 34 minutes total delay before the last attempt. "human_readable_action_name" is an option input to customize retry message.
def getPageImageList(self, pno): if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") if self.isPDF: return self._getPageInfo(pno, 2) return []
Retrieve a list of images used on a page.
def chgroups(name, groups, append=False): if isinstance(groups, six.string_types): groups = groups.split(',') ugrps = set(list_groups(name)) if ugrps == set(groups): return True if append: groups.update(ugrps) cmd = ['usermod', '-G', ','.join(groups), name] return __salt_...
Change the groups to which a user belongs name Username to modify groups List of groups to set for the user. Can be passed as a comma-separated list or a Python list. append : False Set to ``True`` to append these groups to the user's existing list of groups. Other...
def get_cache_key(content, **kwargs): cache_key = '' for key in sorted(kwargs.keys()): cache_key = '{cache_key}.{key}:{value}'.format( cache_key=cache_key, key=key, value=kwargs[key], ) cache_key = '{content}{cache_key}'.format( content=content, ...
generate cache key
def sync_remote_to_local(force="no"): assert "local_wp_dir" in env, "Missing local_wp_dir in env" if force != "yes": message = "This will replace your local database with your "\ "remote, are you sure [y/n]" answer = prompt(message, "y") if answer != "y": logger.i...
Replace your remote db with your local Example: sync_remote_to_local:force=yes
def _hmm_command(self, input_pipe, pairs_to_run): r element = pairs_to_run.pop() hmmsearch_cmd = self._individual_hmm_command(element[0][0], element[0][1], element[1]) while len(pa...
r"""INTERNAL method for getting cmdline for running a batch of HMMs. Parameters ---------- input_pipe: as hmmsearch pairs_to_run: list list with 2 members: (1) list of hmm and output file, (2) number of CPUs to use when searching Returns ------- ...
def _download_metadata_archive(self): with tempfile.NamedTemporaryFile(delete=False) as metadata_archive: shutil.copyfileobj(urlopen(self.catalog_source), metadata_archive) yield metadata_archive.name remove(metadata_archive.name)
Makes a remote call to the Project Gutenberg servers and downloads the entire Project Gutenberg meta-data catalog. The catalog describes the texts on Project Gutenberg in RDF. The function returns a file-pointer to the catalog.
def identify_degenerate_nests(nest_spec): degenerate_positions = [] for pos, key in enumerate(nest_spec): if len(nest_spec[key]) == 1: degenerate_positions.append(pos) return degenerate_positions
Identify the nests within nest_spec that are degenerate, i.e. those nests with only a single alternative within the nest. Parameters ---------- nest_spec : OrderedDict. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives b...
def _initialize(self): self._graph = tf.Graph() with self._graph.as_default(): self._input_node = tf.placeholder(tf.float32, (self._batch_size, self._im_height, self._im_width, self._num_channels)) weights = self.build_alexnet_weights() self._output_tensor = self.buil...
Open from caffe weights
def bind_path_fallback(self, name, folder): if not len(name) or name[0] != '/' or name[-1] != '/': raise ValueError( "name must start and end with '/': {0}".format(name)) self._folder_masks.append((name, folder))
Adds a fallback for a given folder relative to `base_path`.
def toggle_sequential_download(self, infohash_list): data = self._process_infohash_list(infohash_list) return self._post('command/toggleSequentialDownload', data=data)
Toggle sequential download in supplied torrents. :param infohash_list: Single or list() of infohashes.
def get_knowledge_category_id(self): if not bool(self._my_map['knowledgeCategoryId']): raise errors.IllegalState('this Objective has no knowledge_category') else: return Id(self._my_map['knowledgeCategoryId'])
Gets the grade ``Id`` associated with the knowledge dimension. return: (osid.id.Id) - the grade ``Id`` raise: IllegalState - ``has_knowledge_category()`` is ``false`` *compliance: mandatory -- This method must be implemented.*
async def cleanup(self, app): self.conn.close() if self.pubsub_conn: self.pubsub_reader.cancel() self.pubsub_conn.close() await asyncio.sleep(0)
Close self connections.
def _reverse_indexer(self): categories = self.categories r, counts = libalgos.groupsort_indexer(self.codes.astype('int64'), categories.size) counts = counts.cumsum() result = (r[start:end] for start, end in zip(counts, counts[1:])) r...
Compute the inverse of a categorical, returning a dict of categories -> indexers. *This is an internal function* Returns ------- dict of categories -> indexers Example ------- In [1]: c = pd.Categorical(list('aabca')) In [2]: c Out[2]: ...
def acquire(self, signal=True): if not self.needs_lock: return with self.synclock: while not self.lock.acquire(False): self.synclock.wait() if signal: self.acquired_event(self) self.synclock.notify_all()
Locks the account. Method has no effect if the constructor argument `needs_lock` wsa set to False. :type signal: bool :param signal: Whether to emit the acquired_event signal.
def _get_split_tasks(args, split_fn, file_key, outfile_i=-1): split_args = [] combine_map = {} finished_map = collections.OrderedDict() extras = [] for data in args: out_final, out_parts = split_fn(data) for parts in out_parts: split_args.append([utils.deepish_copy(data)]...
Split up input files and arguments, returning arguments for parallel processing. outfile_i specifies the location of the output file in the arguments to the processing function. Defaults to the last item in the list.
def find_inherited_key_completions(rootpath, root_env): tup = inflate_context_tuple(rootpath, root_env) if isinstance(tup, runtime.CompositeTuple): keys = set(k for t in tup.tuples[:-1] for k in t.keys()) return {n: get_completion(tup, n) for n in keys} return {}
Return completion keys from INHERITED tuples. Easiest way to get those is to evaluate the tuple, check if it is a CompositeTuple, then enumerate the keys that are NOT in the rightmost tuple.
def getitem_in(obj, name): for part in name.split('.'): obj = obj[part] return obj
Finds a key in @obj via a period-delimited string @name. @obj: (#dict) @name: (#str) |.|-separated keys to search @obj in .. obj = {'foo': {'bar': {'baz': True}}} getitem_in(obj, 'foo.bar.baz') .. |True|
def share(self, auth, resource, options={}, defer=False): return self._call('share', auth, [resource, options], defer)
Generates a share code for the given resource. Args: auth: <cik> resource: The identifier of the resource. options: Dictonary of options.
def check_version(ctx, param, value): if ctx.resilient_parsing: return if not value and ctx.invoked_subcommand != 'run': ctx.call_on_close(_check_version)
Check for latest version of renku on PyPI.
def list_roles(): for role in lib.get_roles(): margin_left = lib.get_margin(len(role['fullname'])) print("{0}{1}{2}".format( role['fullname'], margin_left, role.get('description', '(no description)')))
Show a list of all available roles
def remove(self): from fs.errors import ResourceNotFoundError try: self._fs.remove(self.file_name) except ResourceNotFoundError: pass
Removes file from filesystem.
def fundamental_frequency(s,FS): s = s - mean(s) f, fs = plotfft(s, FS, doplot=False) fs = fs[1:int(len(fs) / 2)] f = f[1:int(len(f) / 2)] cond = find(f > 0.5)[0] bp = bigPeaks(fs[cond:], 0) if bp==[]: f0=0 else: bp = bp + cond f0 = f[min(bp)] return f0
Compute fundamental frequency along the specified axes. Parameters ---------- s: ndarray input from which fundamental frequency is computed. FS: int sampling frequency Returns ------- f0: int its integer multiple best explain the content of the signal spectrum.
def get_ip(request, real_ip_only=False, right_most_proxy=False): best_matched_ip = None warnings.warn('get_ip is deprecated and will be removed in 3.0.', DeprecationWarning) for key in defs.IPWARE_META_PRECEDENCE_ORDER: value = request.META.get(key, request.META.get(key.replace('_', '-'), '')).strip...
Returns client's best-matched ip-address, or None @deprecated - Do not edit
def search_by_release(self, release_id, limit=0, order_by=None, sort_order=None, filter=None): url = "%s/release/series?release_id=%d" % (self.root_url, release_id) info = self.__get_search_results(url, limit, order_by, sort_order, filter) if info is None: raise ValueError('No series...
Search for series that belongs to a release id. Returns information about matching series in a DataFrame. Parameters ---------- release_id : int release id, e.g., 151 limit : int, optional limit the number of results to this value. If limit is 0, it means fetchin...
def __set_values(self, values): array = tuple(tuple(self._clean_value(col) for col in row) for row in values) self._get_target().setDataArray(array)
Sets values in this cell range from an iterable of iterables.
def __prepare_namespaces(self): self.namespaces = dict( text="urn:text", draw="urn:draw", table="urn:table", office="urn:office", xlink="urn:xlink", svg="urn:svg", manifest="urn:manifest", ) for tree_root in self...
create proper namespaces for our document
def _write_sample_config(run_folder, ldetails): out_file = os.path.join(run_folder, "%s.yaml" % os.path.basename(run_folder)) with open(out_file, "w") as out_handle: fc_name, fc_date = flowcell.parse_dirname(run_folder) out = {"details": sorted([_prepare_sample(x, run_folder) for x in ldetails],...
Generate a bcbio-nextgen YAML configuration file for processing a sample.
def negotiate_encoding (self): try: features = self.url_connection.sendcmd("FEAT") except ftplib.error_perm as msg: log.debug(LOG_CHECK, "Ignoring error when getting FTP features: %s" % msg) pass else: log.debug(LOG_CHECK, "FTP features %s", featur...
Check if server can handle UTF-8 encoded filenames. See also RFC 2640.
def open_external_file(self, fname): fname = encoding.to_unicode_from_fs(fname) if osp.isfile(fname): self.open_file(fname, external=True) elif osp.isfile(osp.join(CWD, fname)): self.open_file(osp.join(CWD, fname), external=True)
Open external files that can be handled either by the Editor or the variable explorer inside Spyder.
def clear_cycle_mrkrs(self, test=False): if not test: msgBox = QMessageBox(QMessageBox.Question, 'Clear Cycle Markers', 'Are you sure you want to remove all cycle ' 'markers for this rater?') msgBox.setStandardButtons(QMes...
Remove all cycle markers.
def parameters_to_datetime(self, p): dt = p[self._param_name] return datetime(dt.year, dt.month, dt.day)
Given a dictionary of parameters, will extract the ranged task parameter value
def _cp_embeds_into(cp1, cp2): if cp1 is None or cp2 is None: return False cp1 = as_complex_pattern(cp1) cp2 = as_complex_pattern(cp2) if len(cp2.monomer_patterns) == 1: mp2 = cp2.monomer_patterns[0] for mp1 in cp1.monomer_patterns: if _mp_embeds_into(mp1, mp2): ...
Check that any state in ComplexPattern2 is matched in ComplexPattern1.
def cleanup(self): for instance in self.context: del(instance) for plugin in self.plugins: del(plugin)
Forcefully delete objects from memory In an ideal world, this shouldn't be necessary. Garbage collection guarantees that anything without reference is automatically removed. However, because this application is designed to be run multiple times from the same interpreter process...
def main(filename): font_family = 'arial' font = Font(font_family, bold=True) if not font: raise RuntimeError('No font found for %r' % font_family) with Document('output.pdf') as document: with document.Page() as ctx: with Image(filename) as embed: ctx.box = e...
Creates a PDF by embedding the first page from the given image and writes some text to it. @param[in] filename The source filename of the image to embed.
def zlines(f = None, sep = "\0", osep = None, size = 8192): if f is None: f = sys.stdin if osep is None: osep = sep buf = "" while True: chars = f.read(size) if not chars: break buf += chars; lines = buf.split(sep); buf = lines.pop() for line in lines: yield line + osep if buf: yield buf
File iterator that uses alternative line terminators.
def get_order(self, order_id): if order_id in self.blotter.orders: return self.blotter.orders[order_id].to_api_obj()
Lookup an order based on the order id returned from one of the order functions. Parameters ---------- order_id : str The unique identifier for the order. Returns ------- order : Order The order object.
def get_primary_domain(self): try: domain = self.domains.get(is_primary=True) return domain except get_tenant_domain_model().DoesNotExist: return None
Returns the primary domain of the tenant
def shift_select(self, first_element, last_element): self.click(first_element) self.shift_click(last_element)
Clicks a web element and shift clicks another web element. :param first_element: WebElement instance :param last_element: WebElement instance :return: None
def get_anchor_contents(markup): soup = BeautifulSoup(markup, 'lxml') return ['%s' % link.contents[0] for link in soup.find_all('a')]
Given HTML markup, return a list of href inner html for each anchor tag.
def _get_dispatches(filter_kwargs): dispatches = Dispatch.objects.prefetch_related('message').filter( **filter_kwargs ).order_by('-message__time_created') return list(dispatches)
Simplified version. Not distributed friendly.
def get_value_prob(self, attr_name, value): if attr_name not in self._attr_value_count_totals: return n = self._attr_value_counts[attr_name][value] d = self._attr_value_count_totals[attr_name] return n/float(d)
Returns the value probability of the given attribute at this node.
def add(self, filename): basename = os.path.basename(filename) match = self.regexp.search(basename) if match: self.by_episode[int(match.group('ep'))].add(filename)
Try to add a file.
def create(self, re='brunel-py-ex-*.gdf', index=True): self.cursor.execute('CREATE TABLE IF NOT EXISTS spikes (neuron INT UNSIGNED, time REAL)') tic = now() for f in glob.glob(re): print(f) while True: try: for data in self._blockread(f...
Create db from list of gdf file glob Parameters ---------- re : str File glob to load. index : bool Create index on neurons for speed. Returns ------- None See also -------- ...
def _get_price(self, package): for price in package['prices']: if not price.get('locationGroupId'): return price['id'] raise SoftLayer.SoftLayerError("Could not find valid price")
Returns valid price for ordering a dedicated host.
def get_ancestors(self): node = self ancestor_list = [] while node.parent is not None: ancestor_list.append(node.parent) node = node.parent return ancestor_list
Returns a list of ancestors of the node. Ordered from the earliest. :return: node's ancestors, ordered from most recent :rtype: list(FenwickNode)
def use_comparative_hierarchy_view(self): self._hierarchy_view = COMPARATIVE for session in self._get_provider_sessions(): try: session.use_comparative_hierarchy_view() except AttributeError: pass
Pass through to provider HierarchyLookupSession.use_comparative_hierarchy_view
def fill_main_goids(go2obj, goids): for goid in goids: goobj = go2obj[goid] if goid != goobj.id and goobj.id not in go2obj: go2obj[goobj.id] = goobj
Ensure main GO IDs are included in go2obj.
def remove_bucket(self, bucket_name): is_valid_bucket_name(bucket_name) self._url_open('DELETE', bucket_name=bucket_name) self._delete_bucket_region(bucket_name)
Remove a bucket. :param bucket_name: Bucket to remove
def annotation_path(cls, project, incident, annotation): return google.api_core.path_template.expand( "projects/{project}/incidents/{incident}/annotations/{annotation}", project=project, incident=incident, annotation=annotation, )
Return a fully-qualified annotation string.
def getlines(self, bufnr=None): buf = self._vim.buffers[bufnr] if bufnr else self._vim.current.buffer return buf[:]
Get all lines of a buffer as a list. Args: bufnr (Optional[int]): A Vim buffer number, current if ``None``. Returns: List[str]
def get_time_now(self): import datetime import getpass username = getpass.getuser() timenow = str(datetime.datetime.now()) timenow = timenow.split('.')[0] msg = '<div class="date">Created on ' + timenow msg += " by " + username +'</div>' return msg
Returns a time stamp
def update_firewall_policy(self, firewall_policy, body=None): return self.put(self.firewall_policy_path % (firewall_policy), body=body)
Updates a firewall policy.
def release(): sh("paver bdist_egg") print print "~" * 78 print "TESTING SOURCE BUILD" sh( "{ cd dist/ && unzip -q %s-%s.zip && cd %s-%s/" " && /usr/bin/python setup.py sdist >/dev/null" " && if { unzip -ql ../%s-%s.zip; unzip -ql dist/%s-%s.zip; }" " | cut -...
Check release before upload to PyPI.
def get_journal_abstracts(self, refresh=True): return [abstract for abstract in self.get_abstracts(refresh=refresh) if abstract.aggregationType == 'Journal']
Return a list of ScopusAbstract objects using ScopusSearch, but only if belonging to a Journal.
def filter_queryset(self, request, queryset, view): self.ordering_param = view.SORT ordering = self.get_ordering(request, queryset, view) if ordering: return queryset.order_by(*ordering) return queryset
Filter the queryset, applying the ordering. The `ordering_param` can be overwritten here. In DRF, the ordering_param is 'ordering', but we support changing it to allow the viewset to control the parameter.
def list(self,params=None, headers=None): path = '/creditor_bank_accounts' response = self._perform_request('GET', path, params, headers, retry_failures=True) return self._resource_for(response)
List creditor bank accounts. Returns a [cursor-paginated](#api-usage-cursor-pagination) list of your creditor bank accounts. Args: params (dict, optional): Query string parameters. Returns: CreditorBankAccount
def generic_visit(self, node): super(RangeValues, self).generic_visit(node) return self.add(node, UNKNOWN_RANGE)
Other nodes are not known and range value neither.
def get_addresses_from_input_file(input_file_name): mode = 'r' if sys.version_info[0] < 3: mode = 'rb' with io.open(input_file_name, mode) as input_file: reader = csv.reader(input_file, delimiter=',', quotechar='"') addresses = list(map(tuple, reader)) if len(addresses) == 0:...
Read addresses from input file into list of tuples. This only supports address and zipcode headers
def get_system_properties(server=None): properties = {} data = _api_get('system-properties', server) if any(data['extraProperties']['systemProperties']): for element in data['extraProperties']['systemProperties']: properties[element['name']] = element['value'] return properties ...
Get system properties
def multiget(self, pairs, **params): if self._multiget_pool: params['pool'] = self._multiget_pool return riak.client.multi.multiget(self, pairs, **params)
Fetches many keys in parallel via threads. :param pairs: list of bucket_type/bucket/key tuple triples :type pairs: list :param params: additional request flags, e.g. r, pr :type params: dict :rtype: list of :class:`RiakObjects <riak.riak_object.RiakObject>`, :class:`...
def bundle(self, ref, capture_exceptions=False): from ..orm.exc import NotFoundError if isinstance(ref, Dataset): ds = ref else: try: ds = self._db.dataset(ref) except NotFoundError: ds = None if not ds: try:...
Return a bundle build on a dataset, with the given vid or id reference
async def get_wallets(self, *args, **kwargs): logging.debug("\n [+] -- Get wallets debugging.") if kwargs.get("message"): kwargs = json.loads(kwargs.get("message")) logging.debug(kwargs) uid = kwargs.get("uid",0) address = kwargs.get("address") coinid = kwargs.get("coinid") try: coinid = coinid.repl...
Get users wallets by uid Accepts: - uid [integer] (users id) Returns a list: - [ { "address": [string], "uid": [integer], "amount_active": [integer], "amount_frozen": [integer] }, ]
def get_extra_kwargs(self): extra_kwargs = getattr(self.Meta, 'extra_kwargs', {}) read_only_fields = getattr(self.Meta, 'read_only_fields', None) if read_only_fields is not None: for field_name in read_only_fields: kwargs = extra_kwargs.get(field_name, {}) ...
Return a dictionary mapping field names to a dictionary of additional keyword arguments.
def update(self, scopes=[], add_scopes=[], rm_scopes=[], note='', note_url=''): success = False json = None if scopes: d = {'scopes': scopes} json = self._json(self._post(self._api, data=d), 200) if add_scopes: d = {'add_scopes': add_sco...
Update this authorization. :param list scopes: (optional), replaces the authorization scopes with these :param list add_scopes: (optional), scopes to be added :param list rm_scopes: (optional), scopes to be removed :param str note: (optional), new note about authorization ...