text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def report_progress(stream=None):
"""Report progress from any currently installed reporters.
Args:
stream: The text stream (default: sys.stderr) to which
progress will be reported.
"""
if stream is None:
stream = sys.stderr
for reporter in _reporters:
reporter(st... | 0.003077 |
def get_post_reference_section_keyword_patterns():
"""Return a list of compiled regex patterns used to search for various
keywords that can often be found after, and therefore suggest the end of,
a reference section in a full-text document.
@return: (list) of compiled regex patterns.
"""
... | 0.009942 |
def format(self, text, width=78, indent=4):
"""Apply textwrap to a given text string"""
return textwrap.fill(
text,
width=width,
initial_indent=' ' * indent,
subsequent_indent=' ' * indent,
) | 0.007605 |
def manage_schedule(self, tag, data):
'''
Refresh the functions and returners.
'''
func = data.get('func', None)
name = data.get('name', None)
schedule = data.get('schedule', None)
where = data.get('where', None)
persist = data.get('persist', None)
... | 0.001386 |
def _plain_auth_stage2(self, _unused):
"""Do the second stage (<iq type='set'/>) of legacy "plain"
authentication.
[client only]"""
iq=Iq(stanza_type="set")
q=iq.new_query("jabber:iq:auth")
q.newTextChild(None,"username",to_utf8(self.my_jid.node))
q.newTextChild(... | 0.022181 |
def parse_manifest(manifest):
"""
return a list of dicts containing an rpm name, version and release
eg: [{'name': 'httpd', 'version': 1.3.39, 'release': 1}]
"""
regex = re.compile('(.*)-(.*)')
manifest = os.path.expanduser(manifest)
if not os.path.exists(manifest):
raise JuicerMani... | 0.005114 |
def generateVectors():
"""Convert the known ra/decs of the channel corners
into unit vectors. This code creates the conents of the
function loadOriginVectors() (below)
"""
ra_deg = 290.66666667
dec_deg = +44.5
#rollAngle_deg = 33.0
rollAngle_deg = +123.
boresight = r.vecFromRaDec(ra... | 0.014043 |
def iter_xCharts(self):
"""
Generate each xChart child element in document.
"""
plot_tags = (
qn('c:area3DChart'), qn('c:areaChart'), qn('c:bar3DChart'),
qn('c:barChart'), qn('c:bubbleChart'), qn('c:doughnutChart'),
qn('c:line3DChart'), qn('c:lineChart... | 0.00299 |
def set_branding(self, asset_ids):
"""Sets the branding.
arg: asset_ids (osid.id.Id[]): the new assets
raise: InvalidArgument - ``asset_ids`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``asset_ids`` is ``null``
*complia... | 0.002725 |
def put_contacts(self, uid, **kwargs):
"""
Assign contacts to the specified list.
:Example:
client.lists.put_contacts(uid=1901010, contacts="1723812,1239912")
:param int uid: The unique id of the List. Required.
:param str contacts: Contact ID(s), separated by com... | 0.00339 |
def estimate_noise_std(img, average=True):
"""Estimate standard deviation of noise in ``img``.
The algorithm, given in [Immerkaer1996], estimates the noise in an image.
Parameters
----------
img : array-like
Array to estimate noise in.
average : bool
If ``True``, return the mea... | 0.000625 |
def parse(self, resource=None):
""" Parse a list of directories ans
:param resource: List of folders
"""
if resource is None:
resource = self.__resources__
self.inventory = self.dispatcher.collection
try:
self._parse(resource)
except MyC... | 0.003683 |
def process(self, frames, eod, spec_range=120.0):
""" Returns a tuple containing the spectral centroid and
the spectrum (dB scales) of the input audio frames.
FFT window sizes are adatable to the input frame size."""
samples = frames[:, 0]
nsamples = len(frames[:, 0])
if... | 0.000945 |
def check_subprocess(self):
"""
Make sure the process didn't exit with an error and run the checks.
:rtype: bool
:return: the actual check status
:raise ProcessExitedWithError: when the main process exits with
an error
"""
exit_code = self.process.pol... | 0.003058 |
def get_file_search(self, query):
"""Performs advanced search on samples, matching certain binary/
metadata/detection criteria.
Possible queries: file size, file type, first or last submission to
VT, number of positives, bynary content, etc.
Args:
query: di... | 0.003686 |
def _get_initial_step(parameters, lower_bounds, upper_bounds, max_step_sizes):
"""Get an initial step size to use for every parameter.
This chooses the step sizes based on the maximum step size and the lower and upper bounds.
Args:
parameters (ndarray): The parameters at which to evaluate the grad... | 0.005922 |
def datastream_etag(request, pid, dsid, repo=None,
as_of_date=None, **kwargs):
'''Method suitable for use as an etag function with
:class:`django.views.decorators.http.condition`. Takes the same
arguments as :meth:`~eulfedora.views.raw_datastream`.
'''
# if a range is requested and it is not fo... | 0.003517 |
def normalize_to_unit_range(values):
"""Bring a 1D NumPy array with at least two values in `values` to a linearly normalized range of [0, 1]."""
if not isinstance(values, np.ndarray) or values.ndim != 1:
raise ValueError('`values` must be a 1D NumPy array')
if len(values) < 2:
raise ValueEr... | 0.003478 |
def _retrieve(self):
"""
Return the current content of the inactive-db.json file.
"""
if PyFunceble.CONFIGURATION["inactive_database"]:
# The database subsystem is activated.
# We get, format and initiate the historical database file.
self._reformat_... | 0.003565 |
def _widening_points(self, function_address):
"""
Return the ordered widening points for a specific function.
:param int function_address: Address of the querying function.
:return: A list of sorted merge points (addresses).
:rtype: list
"""
# we are entering a ... | 0.006301 |
def get_plaintext_citations(file):
"""
Parse a plaintext file to get a clean list of plaintext citations. The \
file should have one citation per line.
:param file: Either the path to the plaintext file or the content of a \
plaintext file.
:returns: A list of cleaned plaintext... | 0.001511 |
def array_values(expr):
"""Given an expression expr denoting a list of values, array_values(expr)
returns a list of values for that expression."""
if isinstance(expr, Array):
return expr.get_elems(all_subs(expr._bounds))
elif isinstance(expr, list):
vals = [array_values(x) for x in e... | 0.005195 |
async def requirements(client: Client, search: str) -> dict:
"""
GET list of requirements for a given UID/Public key
:param client: Client to connect to the api
:param search: UID or public key
:return:
"""
return await client.get(MODULE + '/requirements/%s' % search, schema=REQUIREMENTS_SC... | 0.006154 |
def get_version_status(
package_descriptors, targets, repos_data,
strip_version=False, strip_os_code_name=False):
"""
For each package and target check if it is affected by a sync.
This is the case when the package version in the testing repo is different
from the version in the main re... | 0.000503 |
def add_completions(
replace_list: list, belstr: str, replace_span: Span, completion_text: str
) -> List[Mapping[str, Any]]:
"""Create completions to return given replacement list
Args:
replace_list: list of completion replacement values
belstr: BEL String
replace_span: start, stop ... | 0.004371 |
def switch(self, gen_mode:bool=None):
"Switch the model, if `gen_mode` is provided, in the desired mode."
self.gen_mode = (not self.gen_mode) if gen_mode is None else gen_mode
self.opt.opt = self.opt_gen.opt if self.gen_mode else self.opt_critic.opt
self._set_trainable()
self.mod... | 0.015831 |
def __get_favorites(self, favorite_type, start=0, max_items=100):
""" Helper method for `get_favorite_radio_*` methods.
Args:
favorite_type (str): Specify either `RADIO_STATIONS` or
`RADIO_SHOWS`.
start (int): Which number to start the retrieval from. Used for
... | 0.00097 |
def makeAggShkDstn(self):
'''
Creates the attributes TranShkAggDstn, PermShkAggDstn, and AggShkDstn.
Draws on attributes TranShkAggStd, PermShkAddStd, TranShkAggCount, PermShkAggCount.
Parameters
----------
None
Returns
-------
None
'''
... | 0.014827 |
def is_persistent(arg):
'''
is_persistent(x) yields True if x is a persistent object and False if not.
Note that this persistence can only be checked by the pimms library, so immutable/persistent
structures not known to pimms or defined in terms of pimms's immutables library cannot be
evaluated cor... | 0.013462 |
def qos_map_dscp_cos_mark_to(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos")
map = ET.SubElement(qos, "map")
dscp_cos = ET.SubElement(map, "dscp-cos")
dscp_cos_m... | 0.003802 |
def _get_subword_units(token, gram):
"""Return subword-units presentation, given a word/token.
"""
if token == '</s>': # special token for padding purpose.
return [token]
t = '#' + token + '#'
return [t[i:i + gram] for i in range(0, len(t) - gram + 1)] | 0.003559 |
def resize_droplet(self, droplet_id, size):
"""
This method allows you to resize a specific droplet to a different size.
This will affect the number of processors and memory allocated to the droplet.
Required parameters:
droplet_id:
Integer, this is the id o... | 0.002633 |
def get(self):
"""Return the bars."""
frac, whole = modf(self.size * self.percent / 100.0)
ret = curses_bars[8] * int(whole)
if frac > 0:
ret += curses_bars[int(frac * 8)]
whole += 1
ret += self.__empty_char * int(self.size - whole)
if self.__with_... | 0.004988 |
def _validate(self, val):
"""
Checks that the list is of the right length and has the right contents.
Otherwise, an exception is raised.
"""
if self.allow_None and val is None:
return
if not isinstance(val, list):
raise ValueError("List '%s' must ... | 0.015539 |
def kill(self):
"""Kill the current process."""
# safety measure in case the current process has been killed in
# meantime and the kernel reused its PID
if not self.is_running():
name = self._platform_impl._process_name
raise NoSuchProcess(self.pid, name)
... | 0.004464 |
def reflect_table_data(table, mapping=None, engine_name='default'):
"""
Write table to Model dict
"""
table = reflect_table(table, engine_name)
mapping = mapping or {}
from uliweb.utils.sorteddict import SortedDict
field_type_map = {'VARCHAR':'str', 'VARCHAR2':'str', 'INTEGER':'int', 'FLOA... | 0.005675 |
def _insert(self, name, value, timestamp, intervals, **kwargs):
'''
Insert the new value.
'''
# TODO: confirm that this is in fact using the indices correctly.
for interval,config in self._intervals.items():
timestamps = self._normalize_timestamps(timestamp, intervals, config)
for tstamp... | 0.009756 |
def confirmation(self, *args, **kwargs):
"""Upstream packet, send to current terminal."""
if not self.current_terminal:
raise RuntimeError("no active terminal")
if not isinstance(self.current_terminal, Client):
raise RuntimeError("current terminal not a client")
... | 0.005391 |
def from_dicts(cls, ds: List[dict],
force_snake_case: bool=True, force_cast: bool=False, restrict: bool=True) -> TList[T]:
"""From list of dict to list of instance
:param ds: List of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 i... | 0.009813 |
def _dspace(
irez,
d2201, d2211, d3210, d3222, d4410,
d4422, d5220, d5232, d5421, d5433,
dedt, del1, del2, del3, didt,
dmdt, dnodt, domdt, argpo, argpdot,
t, tc, gsto, xfact, xlamo,
no,
atime, em, argpm, inclm, xli,
... | 0.038865 |
def chk_associations(self, fout_err="gaf.err"):
"""Check that fields are legal in GAF"""
obj = GafData("2.1")
return obj.chk(self.associations, fout_err) | 0.011299 |
def date_to_solr(d):
""" converts DD-MM-YYYY to YYYY-MM-DDT00:00:00Z"""
return "{y}-{m}-{day}T00:00:00Z".format(day=d[:2], m=d[3:5], y=d[6:]) if d else d | 0.012422 |
def from_config(cls, gitlab_id=None, config_files=None):
"""Create a Gitlab connection from configuration files.
Args:
gitlab_id (str): ID of the configuration section.
config_files list[str]: List of paths to configuration files.
Returns:
(gitlab.Gitlab): A... | 0.002014 |
def ask_for_board_id(self):
"""Factored out in case interface isn't keyboard"""
board_id = raw_input("paste in board id or url: ").strip()
m = re.search(r"(?:https?://)?(?:trello.com)?/?b?/?([a-zA-Z]{8})/(?:.*)", board_id)
if m:
board_id = m.group(1)
return board_id | 0.009434 |
def make_full_path(basedir, outkey, origname):
"""Make a full file path by combining tokens
Parameters
-----------
basedir : str
The top level output area
outkey : str
The key for the particular instance of the analysis
origname : str
Template for the output file name... | 0.004367 |
def get_fullpath(self, fullname=None, relative_to=None):
"""
Return the original full path if full path is specified, otherwise
search in the case file path
"""
# if is an empty path
if not fullname:
return fullname
isabs = os.path.isabs(fullname)
... | 0.003356 |
def userBrowser(self, request, tag):
"""
Render a TDB of local users.
"""
f = LocalUserBrowserFragment(self.browser)
f.docFactory = webtheme.getLoader(f.fragmentName)
f.setFragmentParent(self)
return f | 0.007782 |
def cree_local_DB(scheme):
"""Create emmpt DB according to the given scheme : dict { table : [ (column_name, column_type), .. ]}
Usefull at installation of application (and for developement)
"""
conn = LocalConnexion()
req = ""
for table, fields in scheme.items():
req += f"DROP TABLE IF ... | 0.00471 |
def get_classification_node(self, project, structure_group, path=None, depth=None):
"""GetClassificationNode.
Gets the classification node for a given node path.
:param str project: Project ID or project name
:param TreeStructureGroup structure_group: Structure group of the classificatio... | 0.005902 |
def erase_key_value(self):
"""
Erase key-value represented fields.
:rtype: Column
:Example:
>>> new_ds = df.erase_key_value('f1 f2')
"""
field_name = self.name
new_df = copy_df(self)
new_df._perform_operation(op.FieldKVConfigOperation({field_nam... | 0.008523 |
def _build_fluent_table(self):
'''Builds the fluent table for each RDDL pvariable.'''
self.fluent_table = collections.OrderedDict()
for name, size in zip(self.domain.non_fluent_ordering, self.non_fluent_size):
non_fluent = self.domain.non_fluents[name]
self.fluent_table[... | 0.006466 |
def main(reactor, argv=sys.argv[1:], env=os.environ,
acme_url=LETSENCRYPT_DIRECTORY.asText()):
"""
A tool to automatically request, renew and distribute Let's Encrypt
certificates for apps running on Marathon and served by marathon-lb.
"""
parser = argparse.ArgumentParser(
descripti... | 0.000184 |
def plot_counts(df, theme):
""" plot the counts of a given theme from a created database over time"""
dates, counts = df['date-observation'], df[theme + "_count"]
fig, ax = plt.subplots()
ax.set_ylabel("{} pixel counts".format(" ".join(theme.split("_"))))
ax.set_xlabel("observation date")
ax.plo... | 0.002632 |
def validate_axiscolor(value):
"""Validate a dictionary containing axiscolor definitions
Parameters
----------
value: dict
see :attr:`psyplot.plotter.baseplotter.axiscolor`
Returns
-------
dict
Raises
------
ValueError"""
validate = try_and_error(validate_none, val... | 0.002692 |
def build_chunk(oscillators):
"""
Build an audio chunk and progress the oscillator states.
Args:
oscillators (list): A list of oscillator.Oscillator objects
to build chunks from
Returns:
str: a string of audio sample bytes ready to be written to a wave file
"""
step... | 0.000586 |
def split(self, frac):
"""
Split the DataFrame into two DataFrames with certain ratio.
:param frac: Split ratio
:type frac: float
:return: two split DataFrame objects
:rtype: list[DataFrame]
"""
from .. import preprocess
split_obj = getattr(prepr... | 0.005102 |
def sanity_check_ir_blocks_from_frontend(ir_blocks, query_metadata_table):
"""Assert that IR blocks originating from the frontend do not have nonsensical structure.
Args:
ir_blocks: list of BasicBlocks representing the IR to sanity-check
Raises:
AssertionError, if the IR has unexpected str... | 0.004045 |
def show_queue():
'''
Show contents of the mail queue
CLI Example:
.. code-block:: bash
salt '*' postfix.show_queue
'''
cmd = 'mailq'
out = __salt__['cmd.run'](cmd).splitlines()
queue = []
queue_pattern = re.compile(r"(?P<queue_id>^[A-Z0-9]+)\s+(?P<size>\d+)\s(?P<timesta... | 0.00256 |
def clean(tf_matrix,
tf_matrix_gene_names,
target_gene_name):
"""
:param tf_matrix: numpy array. The full transcription factor matrix.
:param tf_matrix_gene_names: the full list of transcription factor names, corresponding to the tf_matrix columns.
:param target_gene_name: the target... | 0.006917 |
def create_action(self):
"""Create actions associated with Annotations."""
actions = {}
act = QAction('New Annotations', self)
act.triggered.connect(self.new_annot)
actions['new_annot'] = act
act = QAction('Load Annotations', self)
act.triggered.connect(self.loa... | 0.002837 |
def connect_all_networks(self, action, container_name, **kwargs):
"""
Connects a container to all of its configured networks. Assuming that this is typically used after container
creation, where teh first endpoint is already defined, this skips the first configuration. Pass ``skip_first``
... | 0.007203 |
def convert_vocab(vocab_file):
"""GluonNLP specific code to convert the original vocabulary to nlp.vocab.BERTVocab."""
original_vocab = load_vocab(vocab_file)
token_to_idx = dict(original_vocab)
num_tokens = len(token_to_idx)
idx_to_token = [None] * len(original_vocab)
for word in original_vocab... | 0.001731 |
def cells(self):
"""The number of cells in the MOC.
This gives the total number of cells at all orders,
with cells from every order counted equally.
>>> m = MOC(0, (1, 2))
>>> m.cells
2
"""
n = 0
for (order, cells) in self:
n += len... | 0.005797 |
def call_set_attr(node: Node, key: str, value):
"""Calls node setter"""
node.set_attr(key, value) | 0.009524 |
def PackageVariable(key, help, default, searchfunc=None):
# NB: searchfunc is currently undocumented and unsupported
"""
The input parameters describe a 'package list' option, thus they
are returned with the correct converter and validator appended. The
result is usable for input to opts.Add() .
... | 0.00639 |
def create_upload(self, project_id, path_data, hash_data, remote_filename=None, storage_provider_id=None):
"""
Create a chunked upload id to pass to create_file_chunk_url to create upload urls.
:param project_id: str: uuid of the project
:param path_data: PathData: holds file system data... | 0.009646 |
def _set_instance(self, v, load=False):
"""
Setter method for instance, mapped from YANG variable /protocol/spanning_tree/mstp/instance (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_instance is considered as a private
method. Backends looking to populate thi... | 0.004041 |
def absent(name, user=None, config=None):
'''
Verifies that the specified host is not known by the given user
name
The host name
Note that only single host names are supported. If foo.example.com
and bar.example.com are the same machine and you need to exclude both,
you wil... | 0.001535 |
def compare_vm_configs(new_config, current_config):
'''
Compares virtual machine current and new configuration, the current is the
one which is deployed now, and the new is the target config. Returns the
differences between the objects in a dictionary, the keys are the
configuration parameter keys a... | 0.000259 |
def get(self, *args, **kwargs):
"""Get a relationship details"""
self.before_get(args, kwargs)
relationship_field, model_relationship_field, related_type_, related_id_field = self._get_relationship_data()
obj, data = self._data_layer.get_relationship(model_relationship_field,
... | 0.003795 |
def to_json(self, is_admin=False):
"""Returns a dict representation of the object
Args:
is_admin (`bool`): If true, include information about the account that should be avaiable only to admins
Returns:
`dict`
"""
if is_admin:
return {
... | 0.004324 |
def partition(self, id_):
"""Get a partition by the id number.
Arguments:
id_ -- a partition id value
Returns:
A partitions.Partition object
Throws:
a Sqlalchemy exception if the partition either does not exist or
is not unique
... | 0.001712 |
def check(self, radl):
"""Check the features in this application."""
SIMPLE_FEATURES = {
"name": (str, lambda x, _: bool(x.value)),
"path": (str, lambda x, _: bool(x.value)),
"version": (str, is_version),
"preinstalled": (str, ["YES", "NO"])
}
... | 0.005495 |
def remove_entity(self, entity, second=False):
'''
Removes entity from world and kills entity
'''
if entity in self._entities:
if second:
for group in self._groups.keys():
if entity in self._groups[group]:
self.dereg... | 0.003899 |
def compose_later(self, *things):
"""
register list of things for composition using compose()
compose_later takes a list of fsts.
The last element specifies the base module as string
things are composed directly after the base module
is imported by application code
... | 0.004491 |
def get_broks_from_satellites(self): # pragma: no cover - not used!
"""Get broks from my all internal satellite links
The arbiter get the broks from ALL the known satellites
:return: None
"""
for satellites in [self.conf.brokers, self.conf.schedulers,
... | 0.004608 |
def get_for_file( fp, hash_mode="md5" ):
r"""
Returns a hash string for the given file path.
:param fp: Path to the file.
:param hash_mode: Can be either one of 'md5', 'sha1', 'sha256' or 'sha512'.
Defines the algorithm used to generate the resulting h... | 0.009785 |
def build_GTK_KDE(self):
"""Build the Key Data Encapsulation for GTK
KeyID: 0
Ref: 802.11i p81
"""
return b''.join([
b'\xdd', # Type KDE
chb(len(self.gtk_full) + 6),
b'\x00\x0f\xac', # OUI
b'\x01', # GTK KDE
b'\x00\x0... | 0.005141 |
def guesstype(timestr):
"""Tries to guess whether a string represents a time or a time delta and
returns the appropriate object.
:param timestr (required)
The string to be analyzed
"""
timestr_full = " {} ".format(timestr)
if timestr_full.find(" in ") != -1 or timestr_full.find(" ago ")... | 0.001761 |
def _bool_encode(self, d):
"""
Converts bool values to lowercase strings
"""
for k, v in d.items():
if isinstance(v, bool):
d[k] = str(v).lower()
return d | 0.016667 |
def advertise(
self,
routers=None,
name=None,
timeout=None,
router_file=None,
jitter=None,
):
"""Make a service available on the Hyperbahn routing mesh.
This will make contact with a Hyperbahn host from a list of known
Hyperbahn routers. Addit... | 0.002322 |
def select_event(
event = None,
selection = "ejets"
):
"""
Select a HEP event.
"""
if selection == "ejets":
# Require single lepton.
# Require >= 4 jets.
if \
0 < len(event.el_pt) < 2 and \
len(event.jet_pt) >= 4 and \
len(event... | 0.020151 |
def command(epilog=None, help=None, width=140, **attrs):
"""Same as `@click.command()`, but with common settings (ie: "-h" for help, epilog, slightly larger help display)"""
if epilog is None:
epilog = _get_caller_doc()
attrs = settings(epilog=epilog, help=help, width=width, **attrs)
return clic... | 0.005917 |
def list_statistics(self, begin_date, end_date, shop_id=-1):
"""
Wi-Fi数据统计
详情请参考
http://mp.weixin.qq.com/wiki/8/dfa2b756b66fca5d9b1211bc18812698.html
:param begin_date: 起始日期时间,最长时间跨度为30天
:param end_date: 结束日期时间戳,最长时间跨度为30天
:param shop_id: 可选,门店 ID,按门店ID搜索,-1为总统计... | 0.002326 |
def diversity_coef_sign(W, ci):
'''
The Shannon-entropy based diversity coefficient measures the diversity
of intermodular connections of individual nodes and ranges from 0 to 1.
Parameters
----------
W : NxN np.ndarray
undirected connection matrix with positive and negative weights
... | 0.001544 |
def register_custom_adapter(cls, target_class, adapter):
"""
:type target_class: type
:type adapter: JsonAdapter|type
:rtype: None
"""
class_name = target_class.__name__
if adapter.can_serialize():
cls._custom_serializers[class_name] = adapter
... | 0.004843 |
def ftypes(self):
"""
Return the ftypes (indication of sparse/dense and dtype) in DataFrame.
This returns a Series with the data type of each column.
The result's index is the original DataFrame's columns. Columns
with mixed types are stored with the ``object`` dtype. See
... | 0.001439 |
def reqfile(filepath):
"""Turns a text file into a list (one element per line)"""
result = []
import re
url_re = re.compile(".+:.+#egg=(.+)")
with open(filepath, "r") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continu... | 0.002114 |
def status_favourite(self, id):
"""
Favourite a status.
Returns a `toot dict`_ with the favourited status.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/favourite'.format(str(id))
return self.__api_request('POST', url) | 0.006969 |
def min_conn_k(traj_exp):
'''
Function returns the minimum number of connections, k, that are required to form a fully connected graph based gene expression data
:param traj_exp: ndarray representing gene expression
:return k: int of the minimum number of connections needed for a minimally connected gra... | 0.027753 |
def first_container_with_errors(self, errors):
"""
Returns the first container with errors, otherwise returns None.
"""
for tab in self.fields:
errors_here = any(error in tab for error in errors)
if errors_here:
return tab
return None | 0.006369 |
def initialize_all_switch_interfaces(self, interfaces,
switch_ip=None, replay=True):
"""Configure Nexus interface and get port channel number.
Called during switch replay or just init if no replay
is configured. For latter case, only configured interfac... | 0.002076 |
def signature_split(signatures: bytes, pos: int) -> Tuple[int, int, int]:
"""
:param signatures: signatures in form of {bytes32 r}{bytes32 s}{uint8 v}
:param pos: position of the signature
:return: Tuple with v, r, s
"""
signature_pos = 65 * pos
v = signatures[64 + signature_pos]
r = int... | 0.004124 |
def mtf_unitransformer_base():
"""Hyperparameters for single-stack Transformer."""
hparams = mtf_transformer2_base()
hparams.add_hparam("autoregressive", True)
# HYPERPARAMETERS FOR THE SINGLE LAYER STACK
hparams.add_hparam("layers", ["self_att", "drd"] * 6)
# number of heads in multihead attention
hparam... | 0.022663 |
def __verify_minion(self, id_, token):
'''
Take a minion id and a string signed with the minion private key
The string needs to verify as 'salt' with the minion public key
:param str id_: A minion ID
:param str token: A string signed with the minion private key
:rtype: ... | 0.002091 |
def register(linter):
'''
Register the transformation functions.
'''
try:
MANAGER.register_transform(nodes.Class, rootlogger_transform)
except AttributeError:
MANAGER.register_transform(nodes.ClassDef, rootlogger_transform) | 0.003861 |
def iter_package_families(paths=None):
"""Iterate over package families, in no particular order.
Note that multiple package families with the same name can be returned.
Unlike packages, families later in the searchpath are not hidden by earlier
families.
Args:
paths (list of str, optional)... | 0.00149 |
def getFlags (self, ifname):
"""Get the flags for an interface"""
try:
result = self._ioctl(self.SIOCGIFFLAGS, self._getifreq(ifname))
except IOError as msg:
log.warn(LOG_CHECK,
"error getting flags for interface %r: %s", ifname, msg)
return 0... | 0.008333 |
def _forward_iterator(self):
"Returns a forward iterator over the trie"
path = [(self, 0, Bits())]
while path:
node, idx, prefix = path.pop()
if idx==0 and node.value is not None and not node.prune_value:
yield (self._unpickle_key(prefix), self._unpickle_v... | 0.008696 |
def predict(self, Xnew, full_cov=False, Y_metadata=None, kern=None,
likelihood=None, include_likelihood=True):
"""
Predict the function(s) at the new point(s) Xnew. This includes the
likelihood variance added to the predicted underlying function
(usually referred to as f)... | 0.00112 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.