code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_list_filter(self, request):
"""
Adds versionable custom filtering ability to changelist
"""
list_filter = super(VersionedAdmin, self).get_list_filter(request)
return list(list_filter) + [('version_start_date', DateTimeFilter),
IsCurrent... | Adds versionable custom filtering ability to changelist |
def intersect(self, r):
"""Restrict self to common area with rectangle r."""
if not len(r) == 4:
raise ValueError("bad sequ. length")
self.x0, self.y0, self.x1, self.y1 = TOOLS._intersect_rect(self, r)
return self | Restrict self to common area with rectangle r. |
def split_title(title, width, title_fs):
"""Split a string for a specified width and font size"""
titles = []
if not title:
return titles
size = reverse_text_len(width, title_fs * 1.1)
title_lines = title.split("\n")
for title_line in title_lines:
while len(title_line) > size:
... | Split a string for a specified width and font size |
def enable_servicegroup_host_notifications(self, servicegroup):
"""Enable host notifications for a servicegroup
Format of the line that triggers function call::
ENABLE_SERVICEGROUP_HOST_NOTIFICATIONS;<servicegroup_name>
:param servicegroup: servicegroup to enable
:type serviceg... | Enable host notifications for a servicegroup
Format of the line that triggers function call::
ENABLE_SERVICEGROUP_HOST_NOTIFICATIONS;<servicegroup_name>
:param servicegroup: servicegroup to enable
:type servicegroup: alignak.objects.servicegroup.Servicegroup
:return: None |
def uncheck_all(self, name):
"""Remove the *checked*-attribute of all input elements with
a *name*-attribute given by ``name``.
"""
for option in self.form.find_all("input", {"name": name}):
if "checked" in option.attrs:
del option.attrs["checked"] | Remove the *checked*-attribute of all input elements with
a *name*-attribute given by ``name``. |
def get_command_invocation(self, **kwargs):
"""
https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetCommandInvocation.html
"""
command_id = kwargs.get('CommandId')
instance_id = kwargs.get('InstanceId')
plugin_name = kwargs.get('PluginName', None)
... | https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetCommandInvocation.html |
def compile_and_exec_form( # pylint: disable= too-many-arguments
form: ReaderForm,
ctx: CompilerContext,
module: types.ModuleType,
wrapped_fn_name: str = _DEFAULT_FN,
collect_bytecode: Optional[BytecodeCollector] = None,
) -> Any:
"""Compile and execute the given form. This function will be mos... | Compile and execute the given form. This function will be most useful
for the REPL and testing purposes. Returns the result of the executed expression.
Callers may override the wrapped function name, which is used by the
REPL to evaluate the result of an expression and print it back out. |
def hint_for_accuracy(self, accuracy="normal"):
"""
Returns a :class:`Hint` object with the suggested value of ecut [Ha] and
pawecutdg [Ha] for the given accuracy.
ecut and pawecutdg are set to zero if no hint is available.
Args:
accuracy: ["low", "normal", "high"]
... | Returns a :class:`Hint` object with the suggested value of ecut [Ha] and
pawecutdg [Ha] for the given accuracy.
ecut and pawecutdg are set to zero if no hint is available.
Args:
accuracy: ["low", "normal", "high"] |
def distance_to(self, p: Union["Unit", Point2, Point3], bot: "BotAI" = None) -> Union[int, float]:
""" Using the 2d distance between self and p. To calculate the 3d distance,
use unit.position3d.distance_to(p) """
if bot and isinstance(p, Unit):
index = bot.distances_tag_dict
... | Using the 2d distance between self and p. To calculate the 3d distance,
use unit.position3d.distance_to(p) |
def write_csv(filename, data, delimiter=CSV_DELIMITER):
""" Write image data to CSV file
:param filename: name of CSV file to write data to
:type filename: str
:param data: image data to write to CSV file
:type data: numpy array
:param delimiter: delimiter used in CSV file. Default is ``;``
... | Write image data to CSV file
:param filename: name of CSV file to write data to
:type filename: str
:param data: image data to write to CSV file
:type data: numpy array
:param delimiter: delimiter used in CSV file. Default is ``;``
:type delimiter: str |
def compressed(self):
""" Derive compressed public key """
order = ecdsa.SECP256k1.generator.order()
p = ecdsa.VerifyingKey.from_string(
compat_bytes(self), curve=ecdsa.SECP256k1).pubkey.point
x_str = ecdsa.util.number_to_string(p.x(), order)
# y_str = ecdsa.util.numb... | Derive compressed public key |
def update(self, volume_id, **kwargs):
"""
update an export
"""
# These arguments are allowed
self.allowed('update', kwargs,
['status', 'instance_id',
'mountpoint', 'ip', 'initiator', 'session_ip',
'session_initiato... | update an export |
def cp_cmd(argv):
"""Duplicate the named virtualenv to make a new one."""
parser = argparse.ArgumentParser()
parser.add_argument('source')
parser.add_argument('target', nargs='?')
parser.add_argument('-d', '--dont-activate', action='store_false',
default=True, dest='activate'... | Duplicate the named virtualenv to make a new one. |
def details_handler(args):
"""usage: {program} details <anchor-id> [<path>]
Get the details of a single anchor.
"""
repo = _open_repo(args)
_, anchor = _get_anchor(repo, args['<anchor-id>'])
print("""path: {file_path}
encoding: {encoding}
[before]
{before}
--------------
[topic]
{topic}
---... | usage: {program} details <anchor-id> [<path>]
Get the details of a single anchor. |
def _create_inverse_maps(self):
'''Create the inverse mappings (UniParc -> SEQRES -> ATOM -> Rosetta).'''
# We have already determined that the inverse maps are well-defined (the normal maps are injective). The inverse maps will be partial maps in general.
self.atom_to_rosetta_sequence_maps = ... | Create the inverse mappings (UniParc -> SEQRES -> ATOM -> Rosetta). |
def server_show(endpoint_id, server_id):
"""
Executor for `globus endpoint server show`
"""
client = get_client()
server_doc = client.get_endpoint_server(endpoint_id, server_id)
if not server_doc["uri"]: # GCP endpoint server
fields = (("ID", "id"),)
text_epilog = dedent(
... | Executor for `globus endpoint server show` |
def makeAggShkDstn(self):
'''
Creates the attributes TranShkAggDstn, PermShkAggDstn, and AggShkDstn.
Draws on attributes TranShkAggStd, PermShkAddStd, TranShkAggCount, PermShkAggCount.
This version accounts for the Markov macroeconomic state.
Parameters
----------
... | Creates the attributes TranShkAggDstn, PermShkAggDstn, and AggShkDstn.
Draws on attributes TranShkAggStd, PermShkAddStd, TranShkAggCount, PermShkAggCount.
This version accounts for the Markov macroeconomic state.
Parameters
----------
None
Returns
-------
... |
def reply(self, text):
"""Replys a text message
Args:
text(str): message content
Returns:
RTMMessage
"""
data = {'text': text, 'vchannel_id': self['vchannel_id']}
if self.is_p2p():
data['type'] = RTMMessageType.P2PMessage
... | Replys a text message
Args:
text(str): message content
Returns:
RTMMessage |
async def getTriggerToken(self, *args, **kwargs):
"""
Get a trigger token
Retrieve a unique secret token for triggering the specified hook. This
token can be deactivated with `resetTriggerToken`.
This method gives output: ``v1/trigger-token-response.json#``
This method... | Get a trigger token
Retrieve a unique secret token for triggering the specified hook. This
token can be deactivated with `resetTriggerToken`.
This method gives output: ``v1/trigger-token-response.json#``
This method is ``stable`` |
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the DerivationParameters struct and decode it
into its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a... | Read the data encoding the DerivationParameters struct and decode it
into its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
object.
kmip_version (K... |
def name(self, *args):
'''
get/set the descriptive name text of this object.
'''
if len(args):
self.__name = args[0]
else:
return self.__name | get/set the descriptive name text of this object. |
def get_whitelisted_statements(self, addr):
"""
:returns: True if all statements are whitelisted
"""
if addr in self._run_statement_whitelist:
if self._run_statement_whitelist[addr] is True:
return None # This is the default value used to say
... | :returns: True if all statements are whitelisted |
def matchPrefix(text):
"""
This is silver bullet, cornerstone and magic wand of speed of this algorithm
it filters patterns using manually selected rules. Yes, yes, it's "dirty" code and it could be beautified in
many ways but this library intended to be fast, not beautiful. Without matching is x1.3 slo... | This is silver bullet, cornerstone and magic wand of speed of this algorithm
it filters patterns using manually selected rules. Yes, yes, it's "dirty" code and it could be beautified in
many ways but this library intended to be fast, not beautiful. Without matching is x1.3 slower so let it be.
:param text: ... |
def open_external_file(self, fname):
"""
Open external files that can be handled either by the Editor or the
variable explorer inside Spyder.
"""
fname = encoding.to_unicode_from_fs(fname)
if osp.isfile(fname):
self.open_file(fname, external=True)
... | Open external files that can be handled either by the Editor or the
variable explorer inside Spyder. |
def _init_metadata(self, **kwargs):
"""Initialize form metadata"""
osid_objects.OsidSourceableForm._init_metadata(self)
osid_objects.OsidObjectForm._init_metadata(self, **kwargs)
self._copyright_registration_default = self._mdata['copyright_registration']['default_string_values'][0]
... | Initialize form metadata |
def write(self, address, value, force=False):
"""
Write a value at address.
:param address: The address at which to write
:type address: int or long or Expression
:param value: Bytes to write
:type value: str or list
:param force: Whether to ignore permissions
... | Write a value at address.
:param address: The address at which to write
:type address: int or long or Expression
:param value: Bytes to write
:type value: str or list
:param force: Whether to ignore permissions |
def file_saved_in_other_editorstack(self, original_filename, filename):
"""
File was just saved in another editorstack, let's synchronize!
This avoids file being automatically reloaded.
The original filename is passed instead of an index in case the tabs
on the editor stac... | File was just saved in another editorstack, let's synchronize!
This avoids file being automatically reloaded.
The original filename is passed instead of an index in case the tabs
on the editor stacks were moved and are now in a different order - see
issue 5703.
Filename is... |
def _handle_stranded_msgs(self, eid, uuid):
"""Handle messages known to be on an engine when the engine unregisters.
It is possible that this will fire prematurely - that is, an engine will
go down after completing a result, and the client will be notified
that the result failed and lat... | Handle messages known to be on an engine when the engine unregisters.
It is possible that this will fire prematurely - that is, an engine will
go down after completing a result, and the client will be notified
that the result failed and later receive the actual result. |
def logevents(self):
"""Iterator yielding all logevents from groups dictionary."""
for key in self.groups:
for logevent in self.groups[key]:
yield logevent | Iterator yielding all logevents from groups dictionary. |
def profile_fields(user):
"""
Returns profile fields as a dict for the given user. Used in the
profile view template when the ``ACCOUNTS_PROFILE_VIEWS_ENABLED``
setting is set to ``True``, and also in the account approval emails
sent to administrators when the ``ACCOUNTS_APPROVAL_REQUIRED``
sett... | Returns profile fields as a dict for the given user. Used in the
profile view template when the ``ACCOUNTS_PROFILE_VIEWS_ENABLED``
setting is set to ``True``, and also in the account approval emails
sent to administrators when the ``ACCOUNTS_APPROVAL_REQUIRED``
setting is set to ``True``. |
def pre(cond):
"""
Add a precondition check to the annotated method. The condition
is passed the arguments from the annotated method. It does not
need to accept all of the methods parameters. The condition
is inspected to figure out which parameters to pass.
"""
cond_args, cond_varargs, ... | Add a precondition check to the annotated method. The condition
is passed the arguments from the annotated method. It does not
need to accept all of the methods parameters. The condition
is inspected to figure out which parameters to pass. |
def read_with_mac(self, *blocks):
"""Read a number of data blocks with integrity check.
This method accepts a variable number of integer arguments as
the block numbers to read. The blocks are read with service
code 0x000B (NDEF). Along with the requested block data the
tag retur... | Read a number of data blocks with integrity check.
This method accepts a variable number of integer arguments as
the block numbers to read. The blocks are read with service
code 0x000B (NDEF). Along with the requested block data the
tag returns a message authentication code that is veri... |
def write_vaultlocker_conf(context, priority=100):
"""Write vaultlocker configuration to disk and install alternative
:param context: Dict of data from vault-kv relation
:ptype: context: dict
:param priority: Priority of alternative configuration
:ptype: priority: int"""
charm_vl_path = "/var/l... | Write vaultlocker configuration to disk and install alternative
:param context: Dict of data from vault-kv relation
:ptype: context: dict
:param priority: Priority of alternative configuration
:ptype: priority: int |
def get_counters(counter_list):
'''
Get the values for the passes list of counters
Args:
counter_list (list):
A list of counters to lookup
Returns:
dict: A dictionary of counters and their values
'''
if not isinstance(counter_list, list):
raise CommandExecut... | Get the values for the passes list of counters
Args:
counter_list (list):
A list of counters to lookup
Returns:
dict: A dictionary of counters and their values |
def locateChild(self, ctx, segments):
"""
Look up a shared item for the role viewing this SharingIndex and return a
L{PublicAthenaLivePage} containing that shared item's fragment to the
user.
These semantics are UNSTABLE. This method is adequate for simple uses,
but it ... | Look up a shared item for the role viewing this SharingIndex and return a
L{PublicAthenaLivePage} containing that shared item's fragment to the
user.
These semantics are UNSTABLE. This method is adequate for simple uses,
but it should be expanded in the future to be more consistent wit... |
def rel_humid_from_db_enth(db_temp, enthalpy, b_press=101325):
"""Relative Humidity (%) at db_temp (C), enthalpy (kJ/kg)
and Pressure b_press (Pa).
"""
assert enthalpy >= 0, 'enthalpy must be' \
'greater than 0. Got {}'.format(str(enthalpy))
hr = (enthalpy - (1.006 * db_temp)) / ((1.84 * db_... | Relative Humidity (%) at db_temp (C), enthalpy (kJ/kg)
and Pressure b_press (Pa). |
def unmount(self, force=None, auth_no_user_interaction=None):
"""Unmount filesystem."""
return self._M.Filesystem.Unmount(
'(a{sv})',
filter_opt({
'force': ('b', force),
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
... | Unmount filesystem. |
def sample(ctx, element, timestamp, repeat, delay):
"""Sample the value of a vehicle data element
This command allows for the current value of a vehicle data element
to be sampled:
\b
$ wva vehicle sample VehicleSpeed
168.15329
Optionally, the value may be samples multiple times:
\b
$ wva vehicle sa... | Sample the value of a vehicle data element
This command allows for the current value of a vehicle data element
to be sampled:
\b
$ wva vehicle sample VehicleSpeed
168.15329
Optionally, the value may be samples multiple times:
\b
$ wva vehicle sample VehicleSpeed --repeat 10 --delay 1 --timestamp
148... |
def delete(self, id):
'''Delete a single item with the given ID'''
if not self._item_path:
raise AttributeError('delete is not available for %s' % self._item_name)
target = self._item_path % id
self._redmine.delete(target)
return None | Delete a single item with the given ID |
def pop(self, instance):
'''Remove ``instance`` from the :class:`SessionModel`. Instance
could be a :class:`Model` or an id.
:parameter instance: a :class:`Model` or an ``id``.
:rtype: the :class:`Model` removed from session or ``None`` if
it was not in the session.
'''
if isinstance(instan... | Remove ``instance`` from the :class:`SessionModel`. Instance
could be a :class:`Model` or an id.
:parameter instance: a :class:`Model` or an ``id``.
:rtype: the :class:`Model` removed from session or ``None`` if
it was not in the session. |
def _input_as_dict(self, data):
"""Takes dictionary that sets input and output files.
Valid keys for the dictionary are specified in the subclasses. File
paths must be absolute.
"""
# clear self._input; ready to receive new input and output files
self._input = {}
... | Takes dictionary that sets input and output files.
Valid keys for the dictionary are specified in the subclasses. File
paths must be absolute. |
def reassembly(self, info):
"""Reassembly procedure.
Positional arguments:
* info -- Info, info dict of packets to be reassembled
"""
BUFID = info.bufid # Buffer Identifier
DSN = info.dsn # Data Sequence Number
ACK = info.ack # Acknowledgement Num... | Reassembly procedure.
Positional arguments:
* info -- Info, info dict of packets to be reassembled |
def projection_pp(site, normal, dist_to_plane, reference):
'''
This method finds the projection of the site onto the plane containing
the slipped area, defined as the Pp(i.e. 'perpendicular projection of
site location onto the fault plane' Spudich et al. (2013) - page 88)
given a site.
:param s... | This method finds the projection of the site onto the plane containing
the slipped area, defined as the Pp(i.e. 'perpendicular projection of
site location onto the fault plane' Spudich et al. (2013) - page 88)
given a site.
:param site:
Location of the site, [lon, lat, dep]
:param normal:
... |
def load(filepath=None, filecontent=None):
""" Read the json file located at `filepath`
If `filecontent` is specified, its content will be json decoded
and loaded instead.
Usage:
config.load(filepath=None, filecontent=None):
Provide either a filepath or a json string
"""
conf =... | Read the json file located at `filepath`
If `filecontent` is specified, its content will be json decoded
and loaded instead.
Usage:
config.load(filepath=None, filecontent=None):
Provide either a filepath or a json string |
def load_configs(self):
"""Load the AMP configuration files."""
if self.config is None:
return False
# Display a warning (deprecated) message if the monitor section exist
if "monitor" in self.config.sections():
logger.warning("A deprecated [monitor] section exist... | Load the AMP configuration files. |
def param_list(self):
"""
paramlist : var, paramlist
paramlist : var
paramlist :
"""
params = []
while self.cur_token.type == TokenTypes.VAR:
params.append(Var(self.cur_token))
self.eat(TokenTypes.VAR)
if self.cur_token.type ... | paramlist : var, paramlist
paramlist : var
paramlist : |
def extract_element(self, vector, idx, name=''):
"""
Returns the value at position idx.
"""
instr = instructions.ExtractElement(self.block, vector, idx, name=name)
self._insert(instr)
return instr | Returns the value at position idx. |
def _bounding_ellipsoids(points, ell, pointvol=0., vol_dec=0.5,
vol_check=2.):
"""
Internal method used to compute a set of bounding ellipsoids when a
bounding ellipsoid for the entire set has already been calculated.
Parameters
----------
points : `~numpy.ndarray` with... | Internal method used to compute a set of bounding ellipsoids when a
bounding ellipsoid for the entire set has already been calculated.
Parameters
----------
points : `~numpy.ndarray` with shape (npoints, ndim)
A set of coordinates.
ell : Ellipsoid
The bounding ellipsoid containing ... |
def list_datastore_full(kwargs=None, call=None, datastore=None):
'''
Returns a dictionary with basic information for the given datastore
CLI Example:
.. code-block:: bash
salt-cloud -f list_datastore_full my-vmware-config datastore=datastore-name
'''
if call != 'function':
rai... | Returns a dictionary with basic information for the given datastore
CLI Example:
.. code-block:: bash
salt-cloud -f list_datastore_full my-vmware-config datastore=datastore-name |
def render(self, screen):
"""Renders the MenuElement"""
self.rect.render(screen)
super(MenuElement, self).render(screen) | Renders the MenuElement |
def get_for(self, query_type, value):
"""
Create a query and run it for the given arg if it doesn't exist, and
return the tweets for the query.
"""
from yacms.twitter.models import Query
lookup = {"type": query_type, "value": value}
query, created = Query.objects.... | Create a query and run it for the given arg if it doesn't exist, and
return the tweets for the query. |
def _visible_layers_count(self):
"""Calculate the number of visible layers in the legend.
.. versionadded: 3.1
:returns: Count of layers that are actually visible.
:rtype: int
"""
treeroot = QgsProject.instance().layerTreeRoot()
return len([lyr for lyr in treero... | Calculate the number of visible layers in the legend.
.. versionadded: 3.1
:returns: Count of layers that are actually visible.
:rtype: int |
def _valid_file(self, base, name):
"""Return whether a file can be searched."""
valid = False
fullpath = os.path.join(base, name)
if self.file_check is not None and self.compare_file(fullpath[self._base_len:] if self.file_pathname else name):
valid = True
if valid an... | Return whether a file can be searched. |
def save(self, txt_fst_filename):
"""
Save the machine in the openFST format in the file denoted by
txt_fst_filename.
Args:
txt_fst_filename (str): The name of the file
Returns:
None
"""
txt_fst = open(txt_fst_filename, 'w+')
states... | Save the machine in the openFST format in the file denoted by
txt_fst_filename.
Args:
txt_fst_filename (str): The name of the file
Returns:
None |
def add_distinguished_name_list(list_name):
'''
Add a list of policy distinguished names.
list_name(str): The name of the specific policy distinguished name list to add.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_distinguished_name_list MyDistinguishedList
'''
... | Add a list of policy distinguished names.
list_name(str): The name of the specific policy distinguished name list to add.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_distinguished_name_list MyDistinguishedList |
def getSearchUrl(self, album, artist):
""" See CoverSource.getSearchUrl. """
# build request url
params = collections.OrderedDict()
params["gbv"] = "2"
params["q"] = "\"%s\" \"%s\" front cover" % (artist, album)
if abs(self.target_size - 500) < 300:
params["tbs"] = "isz:m"
elif self.ta... | See CoverSource.getSearchUrl. |
def dataframe(df, **kwargs):
"""Print table with data from the given pandas DataFrame
Parameters
----------
df : DataFrame
A pandas DataFrame with the table to print
"""
table(df.values, list(df.columns), **kwargs) | Print table with data from the given pandas DataFrame
Parameters
----------
df : DataFrame
A pandas DataFrame with the table to print |
def _find_prefix_path(self, basedir, prefix):
"""Similar to _find_prefix_paths() but only returns the first match"""
ret = ""
for ret in self._find_prefix_paths(basedir, prefix):
break
if not ret:
raise IOError("Could not find prefix {} in path {}".format(prefix,... | Similar to _find_prefix_paths() but only returns the first match |
def get_gates(self, x):
"""Return the bucket id of the given tensor.
Args:
x (tf.Tensor): float32 of shape [length, depth]
Returns:
tf.Tensor: One-hot vector int64 of shape [heads, length, nb_buckets]
containing the id of the bucket
"""
# The balance loss don't propagate to th... | Return the bucket id of the given tensor.
Args:
x (tf.Tensor): float32 of shape [length, depth]
Returns:
tf.Tensor: One-hot vector int64 of shape [heads, length, nb_buckets]
containing the id of the bucket |
def print_downloads(self):
"""Print file fields to standard output."""
for path, ann in self.annotation.items():
if path.startswith('output') and ann['type'] == 'basic:file:':
print("{}: {}".format(path, ann['value']['file'])) | Print file fields to standard output. |
def _forward_step(self, Y, T_X, Var_X, Var_dX, rho_e, sigma2_e, weight):
""" forward step for HMM, assuming both the hidden state and noise
have 1-step dependence on the previous value.
"""
# We currently only implement diagonal form
# of covariance matrix for Var_X, Var_dX a... | forward step for HMM, assuming both the hidden state and noise
have 1-step dependence on the previous value. |
def remove_tag(self, key, value=None):
"""
Remove a tag from this object. Removing a tag involves a round-trip
to the EC2 service.
:type key: str
:param key: The key or name of the tag being stored.
:type value: str
:param value: An optional value that can be s... | Remove a tag from this object. Removing a tag involves a round-trip
to the EC2 service.
:type key: str
:param key: The key or name of the tag being stored.
:type value: str
:param value: An optional value that can be stored with the tag.
If a value is pro... |
def ts_stats_significance(ts, ts_stat_func, null_ts_func, B=1000, permute_fast=False):
""" Compute the statistical significance of a test statistic at each point
of the time series.
"""
stats_ts = ts_stat_func(ts)
if permute_fast:
# Permute it in 1 shot
null_ts = map(np.random.p... | Compute the statistical significance of a test statistic at each point
of the time series. |
def upload(ctx, release, rebuild):
""" Uploads distribuition files to pypi or pypitest. """
dist_path = Path(DIST_PATH)
if rebuild is False:
if not dist_path.exists() or not list(dist_path.glob('*')):
print("No distribution files found. Please run 'build' command first")
retu... | Uploads distribuition files to pypi or pypitest. |
def _handle_stop_workflow(self, request):
""" The handler for the stop_workflow request.
The stop_workflow request adds all running dags to the list of dags
that should be stopped and prevents new dags from being started. The dags will
then stop queueing new tasks, which will terminate ... | The handler for the stop_workflow request.
The stop_workflow request adds all running dags to the list of dags
that should be stopped and prevents new dags from being started. The dags will
then stop queueing new tasks, which will terminate the dags and in turn the
workflow.
Ar... |
async def _auth_cram_md5(self, username, password):
"""
Performs an authentication attemps using the CRAM-MD5 mechanism.
Protocol:
1. Send 'AUTH CRAM-MD5' to server ;
2. If the server replies with a 334 return code, we can go on:
1) The challenge (sent ... | Performs an authentication attemps using the CRAM-MD5 mechanism.
Protocol:
1. Send 'AUTH CRAM-MD5' to server ;
2. If the server replies with a 334 return code, we can go on:
1) The challenge (sent by the server) is base64-decoded ;
2) The decoded challe... |
def summarize(self):
"""Return some diagnostic summary statistics about this Markov model
"""
doc = '''Markov state model
------------------
Lag time : {lag_time}
Reversible type : {reversible_type}
Ergodic cutoff : {ergodic_cutoff}
Prior counts : {prior_counts}
Number of states... | Return some diagnostic summary statistics about this Markov model |
def token(cls: Type[CSVType], time: int) -> CSVType:
"""
Return CSV instance from time
:param time: Timestamp
:return:
"""
csv = cls()
csv.time = str(time)
return csv | Return CSV instance from time
:param time: Timestamp
:return: |
def get_response(self, action, params, path='/', parent=None,
verb='GET', list_marker='Set'):
"""
Utility method to handle calls to IAM and parsing of responses.
"""
if not parent:
parent = self
response = self.make_request(action, params, path, v... | Utility method to handle calls to IAM and parsing of responses. |
def _create_chain_entry(user_id, task_id, task_class, args, kwargs, callbacks, parent=None):
"""
Create and update status records for a new :py:class:`UserTaskMixin` in a Celery chain.
"""
LOGGER.debug(task_class)
if issubclass(task_class.__class__, UserTaskMixin):
arguments_dict = task_clas... | Create and update status records for a new :py:class:`UserTaskMixin` in a Celery chain. |
def print_res(data):
""" Print translate result in a better format
Args:
data(str): result
"""
print('===================================')
main_part = data['data']
print(main_part['word_name'])
symbols = main_part['symbols'][0]
print("美式音标:[" + symbols['ph_am'] + "]")
print(... | Print translate result in a better format
Args:
data(str): result |
def make_feature_bed(gtf, feature, out=None):
"""
Make a bed file with the start and stop coordinates for all of a particular
feature in Gencode. Valid features are the features present in the third
column of the Gencode GTF file.
Parameters
----------
gtf : str
Filename of the Genc... | Make a bed file with the start and stop coordinates for all of a particular
feature in Gencode. Valid features are the features present in the third
column of the Gencode GTF file.
Parameters
----------
gtf : str
Filename of the Gencode gtf file.
feature : str
Feature from thir... |
def namedb_get_history_rows( cur, history_id, offset=None, count=None, reverse=False ):
"""
Get the history for a name or namespace from the history table.
Use offset/count if given.
"""
ret = []
if not reverse:
select_query = "SELECT * FROM history WHERE history_id = ? ORDER BY block_id... | Get the history for a name or namespace from the history table.
Use offset/count if given. |
def thaw(vault_client, src_file, opt):
"""Given the combination of a Secretfile and the output of
a freeze operation, will restore secrets to usable locations"""
if not os.path.exists(src_file):
raise aomi.exceptions.AomiFile("%s does not exist" % src_file)
tmp_dir = ensure_tmpdir()
zip_fil... | Given the combination of a Secretfile and the output of
a freeze operation, will restore secrets to usable locations |
def process_update(self, update: types.Update):
"""
Parse Update object
:param update:
:return:
"""
yield 'update_id', update.update_id
if update.message:
yield 'update_type', 'message'
yield from self.process_message(update.message)
... | Parse Update object
:param update:
:return: |
def ed25519_public_key_from_string(string):
"""Create an ed25519 public key from ``string``, which is a seed.
Args:
string (str): the string to use as a seed.
Returns:
Ed25519PublicKey: the public key
"""
try:
return Ed25519PublicKey.from_public_bytes(
base64.b... | Create an ed25519 public key from ``string``, which is a seed.
Args:
string (str): the string to use as a seed.
Returns:
Ed25519PublicKey: the public key |
def distance_to_contact(D, alpha=1):
"""Compute contact matrix from input distance matrix. Distance values of
zeroes are given the largest contact count otherwise inferred non-zero
distance values.
"""
if callable(alpha):
distance_function = alpha
else:
try:
a = np.f... | Compute contact matrix from input distance matrix. Distance values of
zeroes are given the largest contact count otherwise inferred non-zero
distance values. |
def _read_para_host_id(self, code, cbit, clen, *, desc, length, version):
"""Read HIP HOST_ID parameter.
Structure of HIP HOST_ID parameter [RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1... | Read HIP HOST_ID parameter.
Structure of HIP HOST_ID parameter [RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
... |
def calculate_bin_edges(centers):
"""Calculate the edges of wavelength bins given the centers.
The algorithm calculates bin edges as the midpoints between bin centers
and treats the first and last bins as symmetric about their centers.
Parameters
----------
centers : array-like or `~astropy.un... | Calculate the edges of wavelength bins given the centers.
The algorithm calculates bin edges as the midpoints between bin centers
and treats the first and last bins as symmetric about their centers.
Parameters
----------
centers : array-like or `~astropy.units.quantity.Quantity`
Sequence o... |
def _find_row_label_positions(self, match_value_or_fct, levels=None):
"""Check the original DataFrame's row labels to find the locations of rows. And return the adjusted
row indexing within region (offset if including index)"""
allmatches = find_locations(self.df.index, match_value_or_fct, level... | Check the original DataFrame's row labels to find the locations of rows. And return the adjusted
row indexing within region (offset if including index) |
def execute_query(cmd, client, application, analytics_query, start_time=None, end_time=None, offset='1h', resource_group_name=None):
"""Executes a query against the provided Application Insights application."""
from .vendored_sdks.applicationinsights.models import QueryBody
targets = get_query_targets(cmd.c... | Executes a query against the provided Application Insights application. |
def percolating_continua(target, phi_crit, tau,
volume_fraction='pore.volume_fraction',
bulk_property='pore.intrinsic_conductivity'):
r'''
Calculates the effective property of a continua using percolation theory
Parameters
----------
target : OpenPN... | r'''
Calculates the effective property of a continua using percolation theory
Parameters
----------
target : OpenPNM Object
The object for which these values are being calculated. This
controls the length of the calculated array, and also provides
access to other necessary ther... |
def button_with_image(size='medium', icon=None, text=None, title=None, button=False,
name=None, target=False, disabled=False, extra_css=None, modal=None,
data_target='#modal', viewname=None, next=None, extra_href=False, href=False,
fancyajax=False, vie... | Output a button using Bingo's button html.
@param size: The size that refers to the icon css class.
@param icon: A css class that refers to an icon - for example 'send_mail'
@param text: Text to display on the button
@param title: Title parameter for the button or if button=False the data-tip for a... |
def GetCalendarFieldValuesTuple(self):
"""Return the tuple of calendar.txt values or None if this ServicePeriod
should not be in calendar.txt ."""
if self.start_date and self.end_date:
return [getattr(self, fn) for fn in self._FIELD_NAMES] | Return the tuple of calendar.txt values or None if this ServicePeriod
should not be in calendar.txt . |
def _get_version(addon_dir, manifest, odoo_version_override=None,
git_post_version=True):
""" Get addon version information from an addon directory """
version = manifest.get('version')
if not version:
warn("No version in manifest in %s" % addon_dir)
version = '0.0.0'
if... | Get addon version information from an addon directory |
def _error(self, message, start, end=None):
"""Raise a nice error, with the token highlighted."""
raise errors.EfilterParseError(
source=self.source, start=start, end=end, message=message) | Raise a nice error, with the token highlighted. |
def build(self, pre=None, shortest=False):
"""Build the String instance
:param list pre: The prerequisites list (optional, default=None)
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated.
"""
if pre is None:... | Build the String instance
:param list pre: The prerequisites list (optional, default=None)
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated. |
def do_mv(self, subcmd, opts, message, folder):
"""${cmd_name}: move the specified message to the specified folder
${cmd_usage}
"""
client = MdClient(self.maildir, filesystem=self.filesystem)
client.move(message, folder) | ${cmd_name}: move the specified message to the specified folder
${cmd_usage} |
def major_axes(ell):
"""
Gets major axes of ellipsoids
"""
_ = ell[:-1,:-1]
U,s,V = N.linalg.svd(_)
scalar = -(ell.sum()-_.sum())
return N.sqrt(s*scalar)*V | Gets major axes of ellipsoids |
def _sort_lines(self):
"""Haproxy writes its logs after having gathered all information
related to each specific connection. A simple request can be
really quick but others can be really slow, thus even if one connection
is logged later, it could have been accepted before others that are... | Haproxy writes its logs after having gathered all information
related to each specific connection. A simple request can be
really quick but others can be really slow, thus even if one connection
is logged later, it could have been accepted before others that are
already processed and log... |
def enable_windows_virtual_terminal_sequences():
"""
Sets the appropriate flags to enable virtual terminal sequences in a Windows command prompt.
Reference: https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
"""
try:
from ctypes import windll, byref
... | Sets the appropriate flags to enable virtual terminal sequences in a Windows command prompt.
Reference: https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences |
def bsp_traverse_level_order(
node: tcod.bsp.BSP,
callback: Callable[[tcod.bsp.BSP, Any], None],
userData: Any = 0,
) -> None:
"""Traverse this nodes hierarchy with a callback.
.. deprecated:: 2.0
Use :any:`BSP.level_order` instead.
"""
_bsp_traverse(node.level_order(), callback, use... | Traverse this nodes hierarchy with a callback.
.. deprecated:: 2.0
Use :any:`BSP.level_order` instead. |
def _flush_signature(key, return_type):
# type: (FunctionKey, InternalType) -> None
"""Store signature for a function.
Assume that argument types have been stored previously to
'collected_args'. As the 'return_type' argument provides the return
type, we now have a complete signature.
As a side... | Store signature for a function.
Assume that argument types have been stored previously to
'collected_args'. As the 'return_type' argument provides the return
type, we now have a complete signature.
As a side effect, removes the argument types for the function from
'collected_args'. |
def get_header_description(filedata):
"""Get description from metadata file and remove any empty lines at end."""
python_version = sys.version_info.major
if python_version == 3:
filedata = Parser().parsestr(filedata)
else:
filedata = Parser().parsestr(filedata.encode("UTF-8", "replace"))... | Get description from metadata file and remove any empty lines at end. |
def paste_to_selection(self, selection, data, freq=None):
"""Pastes data into grid selection"""
(bb_top, bb_left), (bb_bottom, bb_right) = \
selection.get_grid_bbox(self.grid.code_array.shape)
adjusted_data = self.selection_paste_data_gen(selection, data)
self.paste_to_curre... | Pastes data into grid selection |
def train(self, *args, **kwargs):
'''Train the network until the trainer converges.
All arguments are passed to :func:`itertrain`.
Returns
-------
training : dict
A dictionary of monitor values computed using the training dataset,
at the conclusion of tr... | Train the network until the trainer converges.
All arguments are passed to :func:`itertrain`.
Returns
-------
training : dict
A dictionary of monitor values computed using the training dataset,
at the conclusion of training. This dictionary will at least contain... |
def error(msg, details=None):
'''Display an error message with optional details'''
msg = '{0} {1}'.format(red(KO), white(safe_unicode(msg)))
msg = safe_unicode(msg)
if details:
msg = b'\n'.join((msg, safe_unicode(details)))
echo(format_multiline(msg)) | Display an error message with optional details |
def dict_mirror(d,**kwargs):
'''
d = {1:'a',2:'a',3:'b'}
'''
md = {}
if('sort_func' in kwargs):
sort_func = kwargs['sort_func']
else:
sort_func = sorted
vl = list(d.values())
uvl = elel.uniqualize(vl)
for v in uvl:
kl = _keys_via_value_nonrecur(d,v)
... | d = {1:'a',2:'a',3:'b'} |
def load_hpo(adapter, disease_lines, hpo_disease_lines=None, hpo_lines=None, hpo_gene_lines=None):
"""Load the hpo terms and hpo diseases into database
Args:
adapter(MongoAdapter)
disease_lines(iterable(str)): These are the omim genemap2 information
hpo_lines(iterable(str))
... | Load the hpo terms and hpo diseases into database
Args:
adapter(MongoAdapter)
disease_lines(iterable(str)): These are the omim genemap2 information
hpo_lines(iterable(str))
disease_lines(iterable(str))
hpo_gene_lines(iterable(str)) |
def patch(args):
"""
%prog patch reference.fasta reads.fasta
Run PBJelly with reference and reads.
"""
from jcvi.formats.base import write_file
from jcvi.formats.fasta import format
p = OptionParser(patch.__doc__)
p.add_option("--cleanfasta", default=False, action="store_true",
... | %prog patch reference.fasta reads.fasta
Run PBJelly with reference and reads. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.