code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _sum(data):
"""_sum(data [, start]) -> value
Return a high-precision sum of the given numeric data. If optional
argument ``start`` is given, it is added to the total. If ``data`` is
empty, ``start`` (defaulting to 0) is returned.
Examples
--------
>>> _sum([3, 2.25, 4.5, -0.5, 1.0], 0.75... | _sum(data [, start]) -> value
Return a high-precision sum of the given numeric data. If optional
argument ``start`` is given, it is added to the total. If ``data`` is
empty, ``start`` (defaulting to 0) is returned.
Examples
--------
>>> _sum([3, 2.25, 4.5, -0.5, 1.0], 0.75)
11.0
Some sou... |
def lrem(self, key, value, count=0):
"""Emulate lrem."""
value = self._encode(value)
redis_list = self._get_list(key, 'LREM')
removed_count = 0
if self._encode(key) in self.redis:
if count == 0:
# Remove all ocurrences
while redis_list.... | Emulate lrem. |
def _map_arguments(self, args):
"""Map from the top-level arguments to the arguments provided to
the indiviudal links """
config_yaml = args['config']
config_dict = load_yaml(config_yaml)
data = config_dict.get('data')
comp = config_dict.get('comp')
dry_run = ar... | Map from the top-level arguments to the arguments provided to
the indiviudal links |
def start(self):
""" Initialize websockets, say hello, and start listening for events
"""
self.connect()
if not self.isAlive():
super(WAMPClient,self).start()
self.hello()
return self | Initialize websockets, say hello, and start listening for events |
def import_trade(self, trade):
"""
trade是一个可迭代的list/generator
"""
for item in trade:
self.make_deal(item.code, item.datetime, item.amount,
item.towards, item.price.item.order_model, item.amount_model) | trade是一个可迭代的list/generator |
def init_app(self, app,
entry_point_group='invenio_workflows.workflows',
**kwargs):
"""Flask application initialization."""
app.config.setdefault(
"WORKFLOWS_OBJECT_CLASS",
"invenio_workflows.api.WorkflowObject"
)
state = _Workflo... | Flask application initialization. |
def qualified_name_import(cls):
"""Full name of a class, including the module. Like qualified_class_name, but when you already have a class """
parts = qualified_name(cls).split('.')
return "from {} import {}".format('.'.join(parts[:-1]), parts[-1]) | Full name of a class, including the module. Like qualified_class_name, but when you already have a class |
def db_import(self, urls=None, force_download=False):
"""Updates the CTD database
1. downloads all files from CTD
2. drops all tables in database
3. creates all tables in database
4. import all data from CTD files
:param iter[str] urls: An iterable of UR... | Updates the CTD database
1. downloads all files from CTD
2. drops all tables in database
3. creates all tables in database
4. import all data from CTD files
:param iter[str] urls: An iterable of URL strings
:param bool force_download: force method to dow... |
def count_mismatches_before_variant(reference_prefix, cdna_prefix):
"""
Computes the number of mismatching nucleotides between two cDNA sequences before a variant
locus.
Parameters
----------
reference_prefix : str
cDNA sequence of a reference transcript before a variant locus
cdna... | Computes the number of mismatching nucleotides between two cDNA sequences before a variant
locus.
Parameters
----------
reference_prefix : str
cDNA sequence of a reference transcript before a variant locus
cdna_prefix : str
cDNA sequence detected from RNAseq before a variant locus |
def _find(expr, sub, start=0, end=None):
"""
Return lowest indexes in each strings in the sequence or scalar
where the substring is fully contained between [start:end]. Return -1 on failure.
Equivalent to standard str.find().
:param expr:
:param sub: substring being searched
:param start: l... | Return lowest indexes in each strings in the sequence or scalar
where the substring is fully contained between [start:end]. Return -1 on failure.
Equivalent to standard str.find().
:param expr:
:param sub: substring being searched
:param start: left edge index
:param end: right edge index
:... |
def groupuninstall(group, options=None):
"""
Remove an existing software group.
Extra *options* may be passed to ``yum`` if necessary.
"""
manager = MANAGER
if options is None:
options = []
elif isinstance(options, str):
options = [options]
options = " ".join(options)
... | Remove an existing software group.
Extra *options* may be passed to ``yum`` if necessary. |
def is_function_or_method(obj):
"""Check if an object is a function or method.
Args:
obj: The Python object in question.
Returns:
True if the object is an function or method.
"""
return inspect.isfunction(obj) or inspect.ismethod(obj) or is_cython(obj) | Check if an object is a function or method.
Args:
obj: The Python object in question.
Returns:
True if the object is an function or method. |
def is_interesting(entry):
"""Is this entry interesting?
``entry`` is an XML node representing one entry of the svn status
XML output. It looks like this::
<entry path="unchanged.txt">
<wc-status item="normal" revision="1" props="none">
<commit revisi... | Is this entry interesting?
``entry`` is an XML node representing one entry of the svn status
XML output. It looks like this::
<entry path="unchanged.txt">
<wc-status item="normal" revision="1" props="none">
<commit revision="1">
<author>mg</... |
def _configure_manager(self):
"""
Creates a manager to handle the instances, and another
to handle flavors.
"""
self._manager = CloudDNSManager(self, resource_class=CloudDNSDomain,
response_key="domains", plural_response_key="domains",
uri_base="do... | Creates a manager to handle the instances, and another
to handle flavors. |
def load_model_from_link(name, **overrides):
"""Load a model from a shortcut link, or directory in spaCy data path."""
path = get_data_path() / name / "__init__.py"
try:
cls = import_file(name, path)
except AttributeError:
raise IOError(Errors.E051.format(name=name))
return cls.load(... | Load a model from a shortcut link, or directory in spaCy data path. |
def _get_mechanism(self, rup, coeffs):
"""
Compute fifth term of equation (1) on p. 1200:
``b6 * H``
"""
is_strike_slip = self.get_fault_type_dummy_variables(rup)
return coeffs['b6']*is_strike_slip | Compute fifth term of equation (1) on p. 1200:
``b6 * H`` |
def logout_all(self,
command='exit',
note=None,
echo=None,
timeout=shutit_global.shutit_global_object.default_timeout,
nonewline=False,
loglevel=logging.DEBUG):
"""Logs the user out of all pexpect sessions within this Shut... | Logs the user out of all pexpect sessions within this ShutIt object.
@param command: Command to run to log out (default=exit)
@param note: See send() |
def compute_score(self):
"""Calculate the overall test score using the configuration."""
# LOGGER.info("Begin scoring")
cases = self.get_configured_tests() | set(self.result.cases)
scores = DataFrame({"score": 0.0, "max": 1.0},
index=sorted(cases))
self... | Calculate the overall test score using the configuration. |
def get_coverage(config: CoverageConfig) -> 'Coverage':
"""
Returns a Coverage instance.
:param config: Coverage configuration.
:return: Instance of Coverage.
"""
if config.type == C.COVERAGE_COUNT or config.type == C.COVERAGE_FERTILITY:
utils.check_condition(config.num_hidden == 1, "Co... | Returns a Coverage instance.
:param config: Coverage configuration.
:return: Instance of Coverage. |
def parse(self):
"""Parse the metadata.rb into a dict."""
data = utils.ruby_lines(self.readlines())
data = [tuple(j.strip() for j in line.split(None, 1))
for line in data]
depends = {}
for line in data:
if not len(line) == 2:
continue
... | Parse the metadata.rb into a dict. |
def replace_suffixes_1(self, word):
"""
Find the longest suffix among the ones specified
and perform the required action.
"""
length = len(word)
if word.endswith("sses"):
return word[:-2]
elif word.endswith("ied") or word.endswith("ies"):
... | Find the longest suffix among the ones specified
and perform the required action. |
def is_contradictory(self, other):
"""
Can these two strings coexist ?
"""
other = StringCell.coerce(other)
if self.value is None or other.value is None:
# None = empty, and won't contradict anything
return False
def sequence_in(s1, s2):
... | Can these two strings coexist ? |
def combine_proximals(*factory_list):
r"""Combine proximal operators into a diagonal product space operator.
This assumes the functional to be separable across variables in order to
make use of the separable sum property of proximal operators.
Parameters
----------
factory_list : sequence of c... | r"""Combine proximal operators into a diagonal product space operator.
This assumes the functional to be separable across variables in order to
make use of the separable sum property of proximal operators.
Parameters
----------
factory_list : sequence of callables
Proximal operator factori... |
def lookup_facade(name, version):
"""
Given a facade name and version, attempt to pull that facade out
of the correct client<version>.py file.
"""
for _version in range(int(version), 0, -1):
try:
facade = getattr(CLIENTS[str(_version)], name)
return facade
ex... | Given a facade name and version, attempt to pull that facade out
of the correct client<version>.py file. |
def get_ref_bedtool(ref_file, config, chrom=None):
"""Retrieve a pybedtool BedTool object with reference sizes from input reference.
"""
broad_runner = broad.runner_from_path("picard", config)
ref_dict = broad_runner.run_fn("picard_index_ref", ref_file)
ref_lines = []
with pysam.Samfile(ref_dict... | Retrieve a pybedtool BedTool object with reference sizes from input reference. |
def get_wrap_size_limit(self, output_size, conf_req=True, qop_req=C.GSS_C_QOP_DEFAULT):
"""
Calculates the maximum size of message that can be fed to :meth:`wrap` so that the size of
the resulting wrapped token (message plus wrapping overhead) is no more than a given
maximum output size.... | Calculates the maximum size of message that can be fed to :meth:`wrap` so that the size of
the resulting wrapped token (message plus wrapping overhead) is no more than a given
maximum output size.
:param output_size: The maximum output size (in bytes) of a wrapped token
:type output_siz... |
def get_index_nested(x, i):
"""
Description:
Returns the first index of the array (vector) x containing the value i.
Parameters:
x: one-dimensional array
i: search value
"""
for ind in range(len(x)):
if i == x[ind]:
return ind
return -1 | Description:
Returns the first index of the array (vector) x containing the value i.
Parameters:
x: one-dimensional array
i: search value |
def Wow64EnableWow64FsRedirection(Wow64FsEnableRedirection):
"""
This function may not work reliably when there are nested calls. Therefore,
this function has been replaced by the L{Wow64DisableWow64FsRedirection}
and L{Wow64RevertWow64FsRedirection} functions.
@see: U{http://msdn.microsoft.com/en-... | This function may not work reliably when there are nested calls. Therefore,
this function has been replaced by the L{Wow64DisableWow64FsRedirection}
and L{Wow64RevertWow64FsRedirection} functions.
@see: U{http://msdn.microsoft.com/en-us/library/windows/desktop/aa365744(v=vs.85).aspx} |
def input(self, _in, out, **kwargs):
"""Process individual translation file."""
language_code = _re_language_code.search(_in.read()).group(
'language_code'
)
_in.seek(0) # move at the begining after matching the language
catalog = read_po(_in)
out.write('gett... | Process individual translation file. |
def create_index_tuple(group_ids):
"""An helper function to create index tuples for fast lookup in HDF5Pump"""
max_group_id = np.max(group_ids)
start_idx_arr = np.full(max_group_id + 1, 0)
n_items_arr = np.full(max_group_id + 1, 0)
current_group_id = group_ids[0]
current_idx = 0
item_count... | An helper function to create index tuples for fast lookup in HDF5Pump |
def make_present_participles(verbs):
"""Make the list of verbs into present participles
E.g.:
empower -> empowering
drive -> driving
"""
res = []
for verb in verbs:
parts = verb.split()
if parts[0].endswith("e"):
parts[0] = parts[0][:-1] + "ing"
... | Make the list of verbs into present participles
E.g.:
empower -> empowering
drive -> driving |
def swipe_left(self, width: int = 1080, length: int = 1920) -> None:
'''Swipe left.'''
self.swipe(0.8*width, 0.5*length, 0.2*width, 0.5*length) | Swipe left. |
def get_printoptions():
"""Return the current print options.
Returns
-------
dict
Dictionary of current print options with keys
- short : bool
- xml : bool
- codestream : bool
For a full description of these options, see `set_printoptions`.
See also
... | Return the current print options.
Returns
-------
dict
Dictionary of current print options with keys
- short : bool
- xml : bool
- codestream : bool
For a full description of these options, see `set_printoptions`.
See also
--------
set_printoptio... |
def drop_zero_priors(self):
'''
Returns
-------
PriorFactory
'''
self.term_doc_mat = self.term_doc_mat.remove_terms(
self.priors[self.priors == 0].index
)
self._reindex_priors()
return self | Returns
-------
PriorFactory |
def handle_stats(name, obj):
"""
Stats object handler.
:param name: Unused String
:param obj: GitPython Stats
:return: Dictionary of attributes.
"""
return {'total_deletions': obj.total['deletions'],
'total_insertions': obj.total['insertions'],
'total_lines': obj.tota... | Stats object handler.
:param name: Unused String
:param obj: GitPython Stats
:return: Dictionary of attributes. |
def draw_peaks_inverted(self, x, peaks, line_color):
"""Draw 2 inverted peaks at x"""
y1 = self.image_height * 0.5 - peaks[0] * (self.image_height - 4) * 0.5
y2 = self.image_height * 0.5 - peaks[1] * (self.image_height - 4) * 0.5
if self.previous_y and x < self.image_width - 1:
... | Draw 2 inverted peaks at x |
def load_from_db(cls, callback_etat=print, out=None):
"""Launch data fetching then load data received.
The method _load_remote_db should be overridden.
If out is given, datas are set in it, instead of returning a new base object.
"""
dic = cls._load_remote_db(callback_etat)
... | Launch data fetching then load data received.
The method _load_remote_db should be overridden.
If out is given, datas are set in it, instead of returning a new base object. |
def public_pair_to_sec(public_pair, compressed=True):
"""Convert a public pair (a pair of bignums corresponding to a public key) to the
gross internal sec binary format used by OpenSSL."""
x_str = to_bytes_32(public_pair[0])
if compressed:
return int2byte((2 + (public_pair[1] & 1))) + x_str
... | Convert a public pair (a pair of bignums corresponding to a public key) to the
gross internal sec binary format used by OpenSSL. |
def put(self, key, value):
"""
>>> c = LRUCache()
>>> c.put(1, 'one')
>>> c.get(1)
'one'
>>> c.size()
1
>>> c.put(2, 'two')
>>> c.put(3, 'three')
>>> c.put(4, 'four')
>>> c.put(5, 'five')
>>> c.get(5)
'five'
... | >>> c = LRUCache()
>>> c.put(1, 'one')
>>> c.get(1)
'one'
>>> c.size()
1
>>> c.put(2, 'two')
>>> c.put(3, 'three')
>>> c.put(4, 'four')
>>> c.put(5, 'five')
>>> c.get(5)
'five'
>>> c.size()
5 |
def unpackexe(exefile, destdir):
"""Unpack the given exefile into destdir, using 7z"""
nullfd = open(os.devnull, "w")
exefile = cygpath(os.path.abspath(exefile))
try:
check_call([SEVENZIP, 'x', exefile], cwd=destdir,
stdout=nullfd, preexec_fn=_noumask)
except Exception:
... | Unpack the given exefile into destdir, using 7z |
def j2(x):
""" A fast j2 defined in terms of other special functions """
to_return = 2./(x+1e-15)*j1(x) - j0(x)
to_return[x==0] = 0
return to_return | A fast j2 defined in terms of other special functions |
def find_service_by_id(self, service_id):
"""
Get service for a given service_id.
:param service_id: Service id, str
:return: Service
"""
service_id_key = 'serviceDefinitionId'
service_id = str(service_id)
for service in self._services:
if ser... | Get service for a given service_id.
:param service_id: Service id, str
:return: Service |
def _write(self, cmd, *datas):
"""Helper function to simplify writing."""
cmd = Command(write=cmd)
cmd.write(self._transport, self._protocol, *datas) | Helper function to simplify writing. |
def instance_query_movie_ids(self) -> List[str]:
"""Demonstrates showing tabular hinting of tab completion information"""
completions_with_desc = []
# Sort the movie id strings with a natural sort since they contain numbers
for movie_id in utils.natural_sort(self.MOVIE_DATABASE_IDS):
... | Demonstrates showing tabular hinting of tab completion information |
def do_execute(self):
"""
The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str
"""
for s in self.resolve_option("strings"):
self._output.append(Token(s))
return None | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str |
def ReadPostingLists(self,
keywords,
start_time=FIRST_TIMESTAMP,
end_time=LAST_TIMESTAMP,
last_seen_map=None):
"""Finds all objects associated with any of the keywords.
Args:
keywords: A collection of keywords tha... | Finds all objects associated with any of the keywords.
Args:
keywords: A collection of keywords that we are interested in.
start_time: Only considers keywords added at or after this point in time.
end_time: Only considers keywords at or before this point in time.
last_seen_map: If present, ... |
def FinalizeTaskStorage(self, task):
"""Finalizes a processed task storage.
Moves the task storage file from its temporary directory to the processed
directory.
Args:
task (Task): task.
Raises:
IOError: if the storage type is not supported or
if the storage file cannot be re... | Finalizes a processed task storage.
Moves the task storage file from its temporary directory to the processed
directory.
Args:
task (Task): task.
Raises:
IOError: if the storage type is not supported or
if the storage file cannot be renamed.
OSError: if the storage type is... |
def get_group_name_nonetrick(self, group_name = None):
""" In all getter function in case of single payment group, group_name can be None """
groups = self.m["groups"]
if (len(groups) == 0):
raise Exception("Cannot find any groups in metadata")
if (not group_name):
... | In all getter function in case of single payment group, group_name can be None |
def _gcs_list(args, _):
""" List the buckets or the contents of a bucket.
This command is a bit different in that we allow wildchars in the bucket name and will list
the buckets that match.
"""
target = args['objects']
project = args['project']
if target is None:
return _gcs_list_buckets(project, '*'... | List the buckets or the contents of a bucket.
This command is a bit different in that we allow wildchars in the bucket name and will list
the buckets that match. |
def vector_poly_data(orig, vec):
""" Creates a vtkPolyData object composed of vectors """
# shape, dimention checking
if not isinstance(orig, np.ndarray):
orig = np.asarray(orig)
if not isinstance(vec, np.ndarray):
vec = np.asarray(vec)
if orig.ndim != 2:
orig = orig.resha... | Creates a vtkPolyData object composed of vectors |
def same_log10_order_of_magnitude(x, delta=0.1):
"""
Return true if range is approximately in same order of magnitude
For example these sequences are in the same order of magnitude:
- [1, 8, 5] # [1, 10)
- [35, 20, 80] # [10 100)
- [232, 730] # [100, 1000)
Parameters
... | Return true if range is approximately in same order of magnitude
For example these sequences are in the same order of magnitude:
- [1, 8, 5] # [1, 10)
- [35, 20, 80] # [10 100)
- [232, 730] # [100, 1000)
Parameters
----------
x : array-like
Values in base 10. ... |
def parse_network_osm_query(data):
"""
Convert OSM query data to DataFrames of ways and way-nodes.
Parameters
----------
data : dict
Result of an OSM query.
Returns
-------
nodes, ways, waynodes : pandas.DataFrame
"""
if len(data['elements']) == 0:
raise Runtim... | Convert OSM query data to DataFrames of ways and way-nodes.
Parameters
----------
data : dict
Result of an OSM query.
Returns
-------
nodes, ways, waynodes : pandas.DataFrame |
def help(self, *args):
"""Get help for a remote interface method.
Examples
--------
help('ginga', `method`)
name of the method for which you want help
help('channel', `chname`, `method`)
name of the method in the channel for which you want help
... | Get help for a remote interface method.
Examples
--------
help('ginga', `method`)
name of the method for which you want help
help('channel', `chname`, `method`)
name of the method in the channel for which you want help
Returns
-------
he... |
def last(iterable, default=_marker):
"""Return the last item of *iterable*, or *default* if *iterable* is
empty.
>>> last([0, 1, 2, 3])
3
>>> last([], 'some default')
'some default'
If *default* is not provided and there are no items in the iterable,
raise ``ValueError`... | Return the last item of *iterable*, or *default* if *iterable* is
empty.
>>> last([0, 1, 2, 3])
3
>>> last([], 'some default')
'some default'
If *default* is not provided and there are no items in the iterable,
raise ``ValueError``. |
def from_bytes_list(cls, function_descriptor_list):
"""Create a FunctionDescriptor instance from list of bytes.
This function is used to create the function descriptor from
backend data.
Args:
cls: Current class which is required argument for classmethod.
functi... | Create a FunctionDescriptor instance from list of bytes.
This function is used to create the function descriptor from
backend data.
Args:
cls: Current class which is required argument for classmethod.
function_descriptor_list: list of bytes to represent the
... |
def reset(cls, newObjs):
'''
reset - Remove all stored data associated with this model (i.e. all objects of this type),
and then save all the provided objects in #newObjs , all in one atomic transaction.
Use this method to move from one complete set of objects to another, where any querying applications
... | reset - Remove all stored data associated with this model (i.e. all objects of this type),
and then save all the provided objects in #newObjs , all in one atomic transaction.
Use this method to move from one complete set of objects to another, where any querying applications
will only see the complete before... |
def make_wsgi_app(registry=REGISTRY):
"""Create a WSGI app which serves the metrics from a registry."""
def prometheus_app(environ, start_response):
params = parse_qs(environ.get('QUERY_STRING', ''))
r = registry
encoder, content_type = choose_encoder(environ.get('HTTP_ACCEPT'))
... | Create a WSGI app which serves the metrics from a registry. |
def maskMatch(self, mask):
"""
Determine whether this sequence matches the given mask.
:param mask: string to match against. Ns in the mask are considered to
match anything in the sequence -- all other chars must
match exactly.
:return: True if the mask match... | Determine whether this sequence matches the given mask.
:param mask: string to match against. Ns in the mask are considered to
match anything in the sequence -- all other chars must
match exactly.
:return: True if the mask matches at all places, otherwise false |
def initialize(self, emt_id, emt_pass):
"""Manual initialization of the interface attributes.
This is useful when the interface must be declare but initialized later
on with parsed configuration values.
Args:
emt_id (str): ID given by the server upon registration
... | Manual initialization of the interface attributes.
This is useful when the interface must be declare but initialized later
on with parsed configuration values.
Args:
emt_id (str): ID given by the server upon registration
emt_pass (str): Token given by the server upon re... |
def estimate(self, observations, weights):
"""
Maximum likelihood estimation of output model given the observations and weights
Parameters
----------
observations : [ ndarray(T_k) ] with K elements
A list of K observation trajectories, each having length T_k
... | Maximum likelihood estimation of output model given the observations and weights
Parameters
----------
observations : [ ndarray(T_k) ] with K elements
A list of K observation trajectories, each having length T_k
weights : [ ndarray(T_k, N) ] with K elements
A li... |
def add_dirrecord(self, rec):
# type: (Union[dr.DirectoryRecord, udfmod.UDFFileEntry]) -> None
'''
A method to set the Directory Record associated with this Boot Catalog.
Parameters:
rec - The DirectoryRecord object to associate with this Boot Catalog.
Returns:
... | A method to set the Directory Record associated with this Boot Catalog.
Parameters:
rec - The DirectoryRecord object to associate with this Boot Catalog.
Returns:
Nothing. |
def p_matcharglist(p):
'''
matcharglist : matcharg
| matcharglist COMMA matcharg
'''
if len(p) == 2:
p[0] = [p[1]]
else:
p[0] = p[1]
p[0].append(p[3]) | matcharglist : matcharg
| matcharglist COMMA matcharg |
def check_string(value, min_length=None, max_length=None, pattern=None):
"""
verify that a string has a particular size and conforms
to a particular alphabet
>>> check_string(1)
False
>>> check_string(None)
False
>>> check_string(True)
False
>>> check_string({})
False
>>... | verify that a string has a particular size and conforms
to a particular alphabet
>>> check_string(1)
False
>>> check_string(None)
False
>>> check_string(True)
False
>>> check_string({})
False
>>> check_string([])
False
>>> check_string((1,2))
False
>>> check_stri... |
def list_pools(**kwargs):
'''
List all storage pools.
:param connection: libvirt connection URI, overriding defaults
:param username: username to connect with, overriding defaults
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
CLI Example:
.... | List all storage pools.
:param connection: libvirt connection URI, overriding defaults
:param username: username to connect with, overriding defaults
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' ... |
def get_extra_info(self, name, default=None):
"""
Called by the client protocol to return optional transport
information. Information requests not recognized by the
``FramerProtocol`` are passed on to the underlying transport.
The values of ``name`` recognized directly by
... | Called by the client protocol to return optional transport
information. Information requests not recognized by the
``FramerProtocol`` are passed on to the underlying transport.
The values of ``name`` recognized directly by
``FramerProtocol`` are:
=============== =============... |
def timestamp(self):
"Return POSIX timestamp as float"
if self._tzinfo is None:
return _time.mktime((self.year, self.month, self.day,
self.hour, self.minute, self.second,
-1, -1, -1)) + self.microsecond / 1e6
else:
... | Return POSIX timestamp as float |
def add_filter(self, name, query, color=None, item_order=None):
"""Create a new filter.
.. warning:: Requires Todoist premium.
:param name: The name of the filter.
:param query: The query to search for.
:param color: The color of the filter.
:param item_order: The filte... | Create a new filter.
.. warning:: Requires Todoist premium.
:param name: The name of the filter.
:param query: The query to search for.
:param color: The color of the filter.
:param item_order: The filter's order in the filter list.
:return: The newly created filter.
... |
def export(self, name, columns, points):
"""Write the points in Riemann."""
for i in range(len(columns)):
if not isinstance(points[i], Number):
continue
else:
data = {'host': self.hostname, 'service': name + " " + columns[i], 'metric': points[i]}
... | Write the points in Riemann. |
def askyesno(title=None, message=None, **options):
"""Original doc: Ask a question; return true if the answer is yes"""
return psidialogs.ask_yes_no(title=title, message=message) | Original doc: Ask a question; return true if the answer is yes |
def discover(email, credentials):
"""
Performs the autodiscover dance and returns the primary SMTP address of the account and a Protocol on success. The
autodiscover and EWS server might not be the same, so we use a different Protocol to do the autodiscover request,
and return a hopefully-cached Protoco... | Performs the autodiscover dance and returns the primary SMTP address of the account and a Protocol on success. The
autodiscover and EWS server might not be the same, so we use a different Protocol to do the autodiscover request,
and return a hopefully-cached Protocol to the callee. |
def alloc(self):
"""
Allocate an ID value and return it.
Raises:
ValueError: Out of capacity in ID pool.
"""
if not self._free:
self._expand()
id = self._free.pop()
self._used.add(id)
return id | Allocate an ID value and return it.
Raises:
ValueError: Out of capacity in ID pool. |
def _validate(self):
"""Validate the JPEG 2000 outermost superbox. These checks must be
done at a file level.
"""
# A JP2 file must contain certain boxes. The 2nd box must be a file
# type box.
if not isinstance(self.box[1], FileTypeBox):
msg = "{filename} d... | Validate the JPEG 2000 outermost superbox. These checks must be
done at a file level. |
def get_asset_lookup_session(self):
"""Gets the ``OsidSession`` associated with the asset lookup service.
return: (osid.repository.AssetLookupSession) - the new
``AssetLookupSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports... | Gets the ``OsidSession`` associated with the asset lookup service.
return: (osid.repository.AssetLookupSession) - the new
``AssetLookupSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_asset_lookup()`` is ``false``
*complia... |
def aggregate(self, search):
"""
Add aggregations representing the facets selected, including potential
filters.
"""
for f, facet in iteritems(self.facets):
agg = facet.get_aggregation()
agg_filter = MatchAll()
for field, filter in iteritems(se... | Add aggregations representing the facets selected, including potential
filters. |
def bbox2wktpolygon(bbox):
"""
Return OGC WKT Polygon of a simple bbox list of strings
"""
minx = float(bbox[0])
miny = float(bbox[1])
maxx = float(bbox[2])
maxy = float(bbox[3])
return 'POLYGON((%.2f %.2f, %.2f %.2f, %.2f %.2f, %.2f %.2f, %.2f %.2f))' \
% (minx, miny, minx, max... | Return OGC WKT Polygon of a simple bbox list of strings |
def on(message):
'''Decorator that register a class method as callback for a message.'''
def decorator(function):
try:
function._callback_messages.append(message)
except AttributeError:
function._callback_messages = [message]
return function
return decorator | Decorator that register a class method as callback for a message. |
def list_logtail_config(self, project_name, offset=0, size=100):
""" list logtail config name in a project
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type offset: int
:param offset: the o... | list logtail config name in a project
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type offset: int
:param offset: the offset of all config names
:type size: int
:param size: the... |
def lv_unpack(txt):
"""
Deserializes a string of the length:value format
:param txt: The input string
:return: a list og values
"""
txt = txt.strip()
res = []
while txt:
l, v = txt.split(':', 1)
res.append(v[:int(l)])
txt = v[int(l):]
return res | Deserializes a string of the length:value format
:param txt: The input string
:return: a list og values |
def conditional_entropy(X, Y, base=2):
"""Calculates the conditional entropy, H(X|Y), in the given base
Parameters
----------
X: array-like (# samples)
An array of values for which to compute the conditional entropy
Y: array-like (# samples)
An array of values for which to compute t... | Calculates the conditional entropy, H(X|Y), in the given base
Parameters
----------
X: array-like (# samples)
An array of values for which to compute the conditional entropy
Y: array-like (# samples)
An array of values for which to compute the conditional entropy
base: integer (defa... |
def get_mobilenet(multiplier, pretrained=False, ctx=cpu(),
root=os.path.join(base.data_dir(), 'models'), **kwargs):
r"""MobileNet model from the
`"MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications"
<https://arxiv.org/abs/1704.04861>`_ paper.
Parameters... | r"""MobileNet model from the
`"MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications"
<https://arxiv.org/abs/1704.04861>`_ paper.
Parameters
----------
multiplier : float
The width multiplier for controling the model size. Only multipliers that are no
le... |
def parse_date(self, item, field_name, source_name):
"""
Converts the date in the format: Thu 03.
As only the day is provided, tries to find the best match
based on the current date, considering that dates are on
the past.
"""
# Get the current date
now =... | Converts the date in the format: Thu 03.
As only the day is provided, tries to find the best match
based on the current date, considering that dates are on
the past. |
def _ws_on_open(self, ws: websocket.WebSocketApp):
"""Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection
... | Callback for sending the initial authentication data
This "payload" contains the required data to authenticate this websocket
client as a suitable bot connection to the Discord websocket.
Args:
ws: websocket connection |
def _write_model_stats(self, iteration:int)->None:
"Writes gradient statistics to Tensorboard."
# We don't want to write stats when model is not iterated on and hence has zeroed out gradients
gen_mode = self.learn.gan_trainer.gen_mode
if gen_mode and not self.gen_stats_updated: self._wri... | Writes gradient statistics to Tensorboard. |
def get_last(self, table=None):
"""Just the last entry."""
if table is None: table = self.main_table
query = 'SELECT * FROM "%s" ORDER BY ROWID DESC LIMIT 1;' % table
return self.own_cursor.execute(query).fetchone() | Just the last entry. |
def sort_segment_points(Aps, Bps):
"""Takes two line segments and sorts all their points,
so that they form a continuous path
Args:
Aps: Array of tracktotrip.Point
Bps: Array of tracktotrip.Point
Returns:
Array with points ordered
"""
mid = []
j = 0
mid.append(Ap... | Takes two line segments and sorts all their points,
so that they form a continuous path
Args:
Aps: Array of tracktotrip.Point
Bps: Array of tracktotrip.Point
Returns:
Array with points ordered |
def query_statements(self, query):
"""Query the LRS for statements with specified parameters
:param query: Dictionary of query parameters and their values
:type query: dict
:return: LRS Response object with the returned StatementsResult object as content
:rtype: :class:`tincan.l... | Query the LRS for statements with specified parameters
:param query: Dictionary of query parameters and their values
:type query: dict
:return: LRS Response object with the returned StatementsResult object as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
.. note::
... |
def check_state(self):
"""Tracks differences in the device state."""
if self.dpad:
x_state, y_state = self.handle_dpad()
else:
x_state, y_state = self.handle_abs()
# pylint: disable=no-member
new_state = set((
x_state,
y_state,
... | Tracks differences in the device state. |
def text(self):
"""Linearize the bib source according to the rules of the unified style.
Book:
author. year. booktitle. (series, volume.) address: publisher.
Article:
author. year. title. journal volume(issue). pages.
Incollection:
author. year. title. In edito... | Linearize the bib source according to the rules of the unified style.
Book:
author. year. booktitle. (series, volume.) address: publisher.
Article:
author. year. title. journal volume(issue). pages.
Incollection:
author. year. title. In editor (ed.), booktitle, pages. ... |
def register_method(self, func):
"""
Register a function to be available as RPC method.
The given function will be inspected to find external_name, protocol and entry_point values set by the decorator
@rpc_method.
:param func: A function previously decorated using @rpc_method
... | Register a function to be available as RPC method.
The given function will be inspected to find external_name, protocol and entry_point values set by the decorator
@rpc_method.
:param func: A function previously decorated using @rpc_method
:return: The name of registered method |
def dump_code_line(disassembly_line, bShowAddress = True,
bShowDump = True,
bLowercase = True,
dwDumpWidth = None,
... | Dump a single line of code. To dump a block of code use L{dump_code}.
@type disassembly_line: tuple( int, int, str, str )
@param disassembly_line: Single item of the list returned by
L{Process.disassemble} or L{Thread.disassemble_around_pc}.
@type bShowAddress: bool
@para... |
def handle_startendtag(self, tag, attrs):
"""Function called for empty tags (e.g. <br />)"""
if tag.lower() in self.allowed_tag_whitelist:
self.result += '<' + tag
for (attr, value) in attrs:
if attr.lower() in self.allowed_attribute_whitelist:
... | Function called for empty tags (e.g. <br />) |
def setRecord(self, record):
"""
Sets the record instance linked with this widget.
:param record | <orb.Table>
"""
self._record = record
if record is not None:
self.loadValues(record.recordValues(autoInflate=True))
else:
... | Sets the record instance linked with this widget.
:param record | <orb.Table> |
def layer_width(layer):
'''get layer width.
'''
if is_layer(layer, "Dense"):
return layer.units
if is_layer(layer, "Conv"):
return layer.filters
raise TypeError("The layer should be either Dense or Conv layer.") | get layer width. |
def update(self):
"""Update processes stats using the input method."""
# Init new stats
stats = self.get_init_value()
if self.input_method == 'local':
# Update stats using the standard system lib
# Note: Update is done in the processcount plugin
# Jus... | Update processes stats using the input method. |
def get_cli_version():
"""
获取终端命令版本号,若存在VERSION文件则使用其中的版本号,
否则使用 :meth:`.get_setup_version`
:return: 终端命令版本号
:rtype: str
"""
directory = os.path.dirname(os.path.abspath(__file__))
version_path = os.path.join(directory, 'VERSION')
if os.path.exists(version_path):
with open(ve... | 获取终端命令版本号,若存在VERSION文件则使用其中的版本号,
否则使用 :meth:`.get_setup_version`
:return: 终端命令版本号
:rtype: str |
def describe(lcdict, returndesc=False, offsetwith=None):
'''This describes the light curve object and columns present.
Parameters
----------
lcdict : dict
The input lcdict to parse for column and metadata info.
returndesc : bool
If True, returns the description string as an str in... | This describes the light curve object and columns present.
Parameters
----------
lcdict : dict
The input lcdict to parse for column and metadata info.
returndesc : bool
If True, returns the description string as an str instead of just
printing it to stdout.
offsetwith : s... |
def add_version(self, project, version, egg):
"""
Adds a new project egg to the Scrapyd service. First class, maps to
Scrapyd's add version endpoint.
"""
url = self._build_url(constants.ADD_VERSION_ENDPOINT)
data = {
'project': project,
'version': ... | Adds a new project egg to the Scrapyd service. First class, maps to
Scrapyd's add version endpoint. |
def dot_product_attention(q,
k,
v,
bias,
dropout_rate=0.0,
image_shapes=None,
name=None,
make_image_summary=True,
... | Dot-product attention.
Args:
q: Tensor with shape [..., length_q, depth_k].
k: Tensor with shape [..., length_kv, depth_k]. Leading dimensions must
match with q.
v: Tensor with shape [..., length_kv, depth_v] Leading dimensions must
match with q.
bias: bias Tensor (see attention_bias())
... |
def exp_and_normalise(lw):
"""Exponentiate, then normalise (so that sum equals one).
Arguments
---------
lw: ndarray
log weights.
Returns
-------
W: ndarray of the same shape as lw
W = exp(lw) / sum(exp(lw))
Note
----
uses the log_sum_exp trick to avoid overflo... | Exponentiate, then normalise (so that sum equals one).
Arguments
---------
lw: ndarray
log weights.
Returns
-------
W: ndarray of the same shape as lw
W = exp(lw) / sum(exp(lw))
Note
----
uses the log_sum_exp trick to avoid overflow (i.e. subtract the max
befo... |
def run(self, scenario=None, only=None, **kwargs):
"""
Run MAGICC and parse the output.
As a reminder, putting ``out_parameters=1`` will cause MAGICC to write out its
parameters into ``out/PARAMETERS.OUT`` and they will then be read into
``output.metadata["parameters"]`` where `... | Run MAGICC and parse the output.
As a reminder, putting ``out_parameters=1`` will cause MAGICC to write out its
parameters into ``out/PARAMETERS.OUT`` and they will then be read into
``output.metadata["parameters"]`` where ``output`` is the returned object.
Parameters
---------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.