code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def includeme(config):
"""
Add pyramid_htmlmin n your pyramid include list.
"""
log.info('Loading htmlmin pyramid plugin')
for key, val in config.registry.settings.items():
if key.startswith('htmlmin.'):
log.debug('Setup %s = %s' % (key, val))
htmlmin_opts[key[8:]] = ... | Add pyramid_htmlmin n your pyramid include list. |
def delete_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg
'''
return _delete_resource(name, name_param='Ca... | Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg |
def Right(self, n = 1, dl = 0):
"""右方向键n次
"""
self.Delay(dl)
self.keyboard.tap_key(self.keyboard.right_key, n) | 右方向键n次 |
def flush(self):
"""
Flush the compressor. This will emit the remaining output data, but
will not destroy the compressor. It can be used, for example, to ensure
that given chunks of content will decompress immediately.
"""
chunks = []
chunks.append(self._compress(... | Flush the compressor. This will emit the remaining output data, but
will not destroy the compressor. It can be used, for example, to ensure
that given chunks of content will decompress immediately. |
def sphlat(r, colat, lons):
"""
Convert from spherical coordinates to latitudinal coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sphlat_c.html
:param r: Distance of the point from the origin.
:type r: float
:param colat: Angle of the point from positive z axis (radians).
... | Convert from spherical coordinates to latitudinal coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sphlat_c.html
:param r: Distance of the point from the origin.
:type r: float
:param colat: Angle of the point from positive z axis (radians).
:type colat: float
:param lons: ... |
def _create_storage(storage_service, trajectory=None, **kwargs):
"""Creates a service from a constructor and checks which kwargs are not used"""
kwargs_copy = kwargs.copy()
kwargs_copy['trajectory'] = trajectory
matching_kwargs = get_matching_kwargs(storage_service, kwargs_copy)
storage_service = st... | Creates a service from a constructor and checks which kwargs are not used |
def lmean (inlist):
"""
Returns the arithematic mean of the values in the passed list.
Assumes a '1D' list, but will function on the 1st dim of an array(!).
Usage: lmean(inlist)
"""
sum = 0
for item in inlist:
sum = sum + item
return sum/float(len(inlist)) | Returns the arithematic mean of the values in the passed list.
Assumes a '1D' list, but will function on the 1st dim of an array(!).
Usage: lmean(inlist) |
def node_link_graph(data, directed=False, attrs=_attrs):
"""Return graph from node-link data format.
Parameters
----------
data : dict
node-link formatted graph data
directed : bool
If True, and direction not specified in data, return a directed graph.
attrs : dict
A d... | Return graph from node-link data format.
Parameters
----------
data : dict
node-link formatted graph data
directed : bool
If True, and direction not specified in data, return a directed graph.
attrs : dict
A dictionary that contains three keys 'id', 'source', 'target'.
... |
def add_missing_row(
df: pd.DataFrame,
id_cols: List[str],
reference_col: str,
complete_index: Union[Dict[str, str], List[str]] = None,
method: str = None,
cols_to_keep: List[str] = None
) -> pd.DataFrame:
"""
Add missing row to a df base on a reference column
---
### Parameter... | Add missing row to a df base on a reference column
---
### Parameters
*mandatory :*
- `id_cols` (*list of str*): names of the columns used to create each group
- `reference_col` (*str*): name of the column used to identify missing rows
*optional :*
- `complete_index` (*list* or *dict*): ... |
def watch(self, *keys):
"""
Put the pipeline into immediate execution mode.
Does not actually watch any keys.
"""
if self.explicit_transaction:
raise RedisError("Cannot issue a WATCH after a MULTI")
self.watching = True
for key in keys:
sel... | Put the pipeline into immediate execution mode.
Does not actually watch any keys. |
def _parse_options(self, argv, location):
"""Parse the options part of an argument list.
IN:
lsArgs <list str>:
List of arguments. Will be altered.
location <str>:
A user friendly string describing where this data came from.
"""
observ... | Parse the options part of an argument list.
IN:
lsArgs <list str>:
List of arguments. Will be altered.
location <str>:
A user friendly string describing where this data came from. |
def expand_effect_repertoire(self, new_purview=None):
"""See |Subsystem.expand_repertoire()|."""
return self.subsystem.expand_effect_repertoire(
self.effect.repertoire, new_purview) | See |Subsystem.expand_repertoire()|. |
def eval_model(model, test, add_eval_metrics={}):
"""Evaluate model's performance on the test-set.
# Arguments
model: Keras model
test: test-dataset. Tuple of inputs `x` and target `y` - `(x, y)`.
add_eval_metrics: Additional evaluation metrics to use. Can be a dictionary or a list of f... | Evaluate model's performance on the test-set.
# Arguments
model: Keras model
test: test-dataset. Tuple of inputs `x` and target `y` - `(x, y)`.
add_eval_metrics: Additional evaluation metrics to use. Can be a dictionary or a list of functions
accepting arguments: `y_true`, `y_predicted`... |
def _gaussian(x, amp, loc, std):
'''This is a simple gaussian.
Parameters
----------
x : np.array
The items at which the Gaussian is evaluated.
amp : float
The amplitude of the Gaussian.
loc : float
The central value of the Gaussian.
std : float
The stand... | This is a simple gaussian.
Parameters
----------
x : np.array
The items at which the Gaussian is evaluated.
amp : float
The amplitude of the Gaussian.
loc : float
The central value of the Gaussian.
std : float
The standard deviation of the Gaussian.
Retu... |
def remove_stream_handlers(logger=None):
"""
Remove only stream handlers from the specified logger
:param logger: logging name or object to modify, defaults to root logger
"""
if not isinstance(logger, logging.Logger):
logger = logging.getLogger(logger)
new_handlers = []
for handle... | Remove only stream handlers from the specified logger
:param logger: logging name or object to modify, defaults to root logger |
def aggregate_detail(slug_list, with_data_table=False):
"""Template Tag to display multiple metrics.
* ``slug_list`` -- A list of slugs to display
* ``with_data_table`` -- if True, prints the raw data in a table.
"""
r = get_r()
metrics_data = []
granularities = r._granularities()
# X... | Template Tag to display multiple metrics.
* ``slug_list`` -- A list of slugs to display
* ``with_data_table`` -- if True, prints the raw data in a table. |
def find_last_true(sorted_list, true_criterion):
"""
Suppose we have a list of item [item1, item2, ..., itemN].
:type array: list
:param array: an iterable object that support inex
:param x: a comparable value
If we do a mapping::
>>> def true_criterion(item):
... return ... | Suppose we have a list of item [item1, item2, ..., itemN].
:type array: list
:param array: an iterable object that support inex
:param x: a comparable value
If we do a mapping::
>>> def true_criterion(item):
... return item <= 6
>>> [true_criterion(item) for item in sorte... |
def goto(reference_beats,
estimated_beats,
goto_threshold=0.35,
goto_mu=0.2,
goto_sigma=0.2):
"""Calculate Goto's score, a binary 1 or 0 depending on some specific
heuristic criteria
Examples
--------
>>> reference_beats = mir_eval.io.load_events('reference.txt')... | Calculate Goto's score, a binary 1 or 0 depending on some specific
heuristic criteria
Examples
--------
>>> reference_beats = mir_eval.io.load_events('reference.txt')
>>> reference_beats = mir_eval.beat.trim_beats(reference_beats)
>>> estimated_beats = mir_eval.io.load_events('estimated.txt')
... |
def h2i(self, pkt, seconds):
"""Convert the number of seconds since 1-Jan-70 UTC to the packed
representation."""
if seconds is None:
seconds = 0
tmp_short = (seconds >> 32) & 0xFFFF
tmp_int = seconds & 0xFFFFFFFF
return struct.pack("!HI", tmp_short, tmp... | Convert the number of seconds since 1-Jan-70 UTC to the packed
representation. |
def minimize(self, time, variables, **kwargs):
"""
Performs an optimization step.
Args:
time: Time tensor.
variables: List of variables to optimize.
**kwargs: Additional optimizer-specific arguments. The following arguments are used
by some op... | Performs an optimization step.
Args:
time: Time tensor.
variables: List of variables to optimize.
**kwargs: Additional optimizer-specific arguments. The following arguments are used
by some optimizers:
- arguments: Dict of arguments for callables,... |
def backup(self, backup_name, folder_key=None, folder_name=None):
"""Copies the google spreadsheet to the backup_name and folder specified.
Args:
backup_name (str): The name of the backup document to create.
folder_key (Optional) (str): The key of a folder that the n... | Copies the google spreadsheet to the backup_name and folder specified.
Args:
backup_name (str): The name of the backup document to create.
folder_key (Optional) (str): The key of a folder that the new copy will
be moved to.
folder_name (Opti... |
def _database_create(self, engine, database):
"""Create a new database and return a new url representing
a connection to the new database
"""
logger.info('Creating database "%s" in "%s"', database, engine)
database_operation(engine, 'create', database)
url = copy(engine.u... | Create a new database and return a new url representing
a connection to the new database |
def get_job(self, job_id):
"""GetJob
https://apidocs.joyent.com/manta/api.html#GetJob
with the added sugar that it will retrieve the archived job if it has
been archived, per:
https://apidocs.joyent.com/manta/jobs-reference.html#job-completion-and-archival
"""
... | GetJob
https://apidocs.joyent.com/manta/api.html#GetJob
with the added sugar that it will retrieve the archived job if it has
been archived, per:
https://apidocs.joyent.com/manta/jobs-reference.html#job-completion-and-archival |
def get_device_by_name(self, device_name):
"""Search the list of connected devices by name.
device_name param is the string name of the device
"""
# Find the device for the vera device name we are interested in
found_device = None
for device in self.get_devices():
... | Search the list of connected devices by name.
device_name param is the string name of the device |
def add_stock(self, product_id, sku_info, quantity):
"""
增加库存
:param product_id: 商品ID
:param sku_info: sku信息,格式"id1:vid1;id2:vid2",如商品为统一规格,则此处赋值为空字符串即可
:param quantity: 增加的库存数量
:return: 返回的 JSON 数据包
"""
return self._post(
'merchant/stock/add'... | 增加库存
:param product_id: 商品ID
:param sku_info: sku信息,格式"id1:vid1;id2:vid2",如商品为统一规格,则此处赋值为空字符串即可
:param quantity: 增加的库存数量
:return: 返回的 JSON 数据包 |
def calc_tc_v1(self):
"""Adjust the measured air temperature to the altitude of the
individual zones.
Required control parameters:
|NmbZones|
|TCAlt|
|ZoneZ|
|ZRelT|
Required input sequence:
|hland_inputs.T|
Calculated flux sequences:
|TC|
Basic equation:
... | Adjust the measured air temperature to the altitude of the
individual zones.
Required control parameters:
|NmbZones|
|TCAlt|
|ZoneZ|
|ZRelT|
Required input sequence:
|hland_inputs.T|
Calculated flux sequences:
|TC|
Basic equation:
:math:`TC = T - TCAlt \... |
def _send_consumer_aware_request(self, group, payloads, encoder_fn, decoder_fn):
"""
Send a list of requests to the consumer coordinator for the group
specified using the supplied encode/decode functions. As the payloads
that use consumer-aware requests do not contain the group (e.g.
... | Send a list of requests to the consumer coordinator for the group
specified using the supplied encode/decode functions. As the payloads
that use consumer-aware requests do not contain the group (e.g.
OffsetFetchRequest), all payloads must be for a single group.
Arguments:
group... |
def _process_execute_error(self, msg):
""" Process a reply for an execution request that resulted in an error.
"""
content = msg['content']
# If a SystemExit is passed along, this means exit() was called - also
# all the ipython %exit magic syntax of '-k' to be used to keep
... | Process a reply for an execution request that resulted in an error. |
def _fit_stage(self, i, X, y, y_pred, sample_weight, sample_mask,
random_state, scale, X_idx_sorted, X_csc=None, X_csr=None):
"""Fit another stage of ``n_classes_`` trees to the boosting model. """
assert sample_mask.dtype == numpy.bool
loss = self.loss_
# whether to... | Fit another stage of ``n_classes_`` trees to the boosting model. |
def server(self):
"""Creates and returns a ServerConnection object."""
conn = self.connection_class(self)
with self.mutex:
self.connections.append(conn)
return conn | Creates and returns a ServerConnection object. |
def _goto(self, pose, duration, wait, accurate):
""" Goes to a given cartesian pose.
:param matrix pose: homogeneous matrix representing the target position
:param float duration: move duration
:param bool wait: whether to wait for the end of the move
:param bool... | Goes to a given cartesian pose.
:param matrix pose: homogeneous matrix representing the target position
:param float duration: move duration
:param bool wait: whether to wait for the end of the move
:param bool accurate: trade-off between accurate solution and computatio... |
def obfn_g0var(self):
"""Variable to be evaluated in computing
:meth:`.ADMMTwoBlockCnstrnt.obfn_g0`, depending on the ``AuxVarObj``
option value.
"""
return self.var_y0() if self.opt['AuxVarObj'] else \
self.cnst_A0(None, self.Xf) - self.cnst_c0() | Variable to be evaluated in computing
:meth:`.ADMMTwoBlockCnstrnt.obfn_g0`, depending on the ``AuxVarObj``
option value. |
def post_cleanup(self):
"""\
remove any divs that looks like non-content,
clusters of links, or paras with no gusto
"""
targetNode = self.article.top_node
node = self.add_siblings(targetNode)
for e in self.parser.getChildren(node):
e_tag = self.parser.... | \
remove any divs that looks like non-content,
clusters of links, or paras with no gusto |
def _truncate_to_field(model, field_name, value):
"""
Shorten data to fit in the specified model field.
If the data were too big for the field, it would cause a failure to
insert, so we shorten it, truncating in the middle (because
valuable information often shows up at the end.
"""
field =... | Shorten data to fit in the specified model field.
If the data were too big for the field, it would cause a failure to
insert, so we shorten it, truncating in the middle (because
valuable information often shows up at the end. |
def list(self, service_rec=None, host_rec=None, hostfilter=None):
"""
List a specific service or all services
:param service_rec: t_services.id
:param host_rec: t_hosts.id
:param hostfilter: Valid hostfilter or None
:return: [(svc.t_services.id, svc.t_services.f_hosts_id... | List a specific service or all services
:param service_rec: t_services.id
:param host_rec: t_hosts.id
:param hostfilter: Valid hostfilter or None
:return: [(svc.t_services.id, svc.t_services.f_hosts_id, svc.t_hosts.f_ipaddr,
svc.t_hosts.f_hostname, svc.t_services.f_proto,
... |
def _get_headers(self):
"""Get all the headers we're going to need:
1. Authorization
2. Content-Type
3. User-agent
Note that the User-agent string contains the library name, the
libary version, and the python version. This will help us track
what people are usin... | Get all the headers we're going to need:
1. Authorization
2. Content-Type
3. User-agent
Note that the User-agent string contains the library name, the
libary version, and the python version. This will help us track
what people are using, and where we should concentrate ... |
def _set_mldVlan(self, v, load=False):
"""
Setter method for mldVlan, mapped from YANG variable /interface_vlan/interface/vlan/ipv6/mldVlan (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mldVlan is considered as a private
method. Backends looking to popu... | Setter method for mldVlan, mapped from YANG variable /interface_vlan/interface/vlan/ipv6/mldVlan (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mldVlan is considered as a private
method. Backends looking to populate this variable should
do so via calling thi... |
def collection(data, bins=10, *args, **kwargs):
"""Create histogram collection with shared binnning."""
from physt.histogram_collection import HistogramCollection
if hasattr(data, "columns"):
data = {column: data[column] for column in data.columns}
return HistogramCollection.multi_h1(data, bins,... | Create histogram collection with shared binnning. |
def exec_func_src3(func, globals_, sentinal=None, verbose=False,
start=None, stop=None):
"""
execs a func and returns requested local vars.
Does not modify globals unless update=True (or in IPython)
SeeAlso:
ut.execstr_funckw
"""
import utool as ut
sourcecode = u... | execs a func and returns requested local vars.
Does not modify globals unless update=True (or in IPython)
SeeAlso:
ut.execstr_funckw |
def next_conkey(self, conkey):
"""Return the next <conkey><n> based on conkey as a
string. Example, if 'startcond3' and 'startcond5' exist, this
will return 'startcond6' if 'startcond5' value is not None,
else startcond5 is returned.
It is assumed conkey is a valid condition key... | Return the next <conkey><n> based on conkey as a
string. Example, if 'startcond3' and 'startcond5' exist, this
will return 'startcond6' if 'startcond5' value is not None,
else startcond5 is returned.
It is assumed conkey is a valid condition key.
.. warning::
Under c... |
def make_measurement(name,
channels,
lumi=1.0, lumi_rel_error=0.1,
output_prefix='./histfactory',
POI=None,
const_params=None,
verbose=False):
"""
Create a Measurement from a list of Cha... | Create a Measurement from a list of Channels |
def set_value(self, control, value=None):
"""Set a value on the controller
If percent is True all controls will accept a value between -1.0 and 1.0
If not then:
Triggers are 0 to 255
Axis are -32768 to 32767
Control List:
AxisLx , Left Stick X-Axis
AxisLy ... | Set a value on the controller
If percent is True all controls will accept a value between -1.0 and 1.0
If not then:
Triggers are 0 to 255
Axis are -32768 to 32767
Control List:
AxisLx , Left Stick X-Axis
AxisLy , Left Stick Y-Axis
AxisRx ,... |
def geom_find_group(g, atwts, pr_ax, mom, tt, \
nmax=_DEF.SYMM_MATCH_NMAX, \
tol=_DEF.SYMM_MATCH_TOL, \
dig=_DEF.SYMM_ATWT_ROUND_DIGITS,
avmax=_DEF.SYMM_AVG_MAX):
""" [Find all(?) proper rotation axes (n > 1) and reflection planes.]
.. todo:: Complete geom_find_axes docstring IN... | [Find all(?) proper rotation axes (n > 1) and reflection planes.]
.. todo:: Complete geom_find_axes docstring INCLUDING NEW HEADER LINE
DEPENDS on principal axes and moments being sorted such that:
I_A <= I_B <= I_C
Logic flow developed using:
1) http://symmetry.otterbein.edu/common/image... |
def fragment_fromstring(html, create_parent=False, base_url=None,
parser=None, **kw):
"""
Parses a single HTML element; it is an error if there is more than
one element, or if anything but whitespace precedes or follows the
element.
If ``create_parent`` is true (or is a tag ... | Parses a single HTML element; it is an error if there is more than
one element, or if anything but whitespace precedes or follows the
element.
If ``create_parent`` is true (or is a tag name) then a parent node
will be created to encapsulate the HTML in a single element. In this
case, leading or tr... |
def finalize(self):
"""finalize for StatisticsConsumer"""
super(StatisticsConsumer, self).finalize()
# run statistics on timewave slice w at grid point g
# self.result = [(g, self.statistics(w)) for g, w in zip(self.grid, self.result)]
# self.result = zip(self.grid, (self.statist... | finalize for StatisticsConsumer |
def _reverse_rounding_method(method):
"""
Reverse meaning of ``method`` between positive and negative.
"""
if method is RoundingMethods.ROUND_UP:
return RoundingMethods.ROUND_DOWN
if method is RoundingMethods.ROUND_DOWN:
return RoundingMethods.ROUND_UP
... | Reverse meaning of ``method`` between positive and negative. |
def preserve_shape(func):
"""Preserve shape of the image."""
@wraps(func)
def wrapped_function(img, *args, **kwargs):
shape = img.shape
result = func(img, *args, **kwargs)
result = result.reshape(shape)
return result
return wrapped_function | Preserve shape of the image. |
def _function_add_node(self, cfg_node, function_addr):
"""
Adds node to function manager, converting address to CodeNode if
possible
:param CFGNode cfg_node: A CFGNode instance.
:param int function_addr: Address of the current function.
:return: None
"""
... | Adds node to function manager, converting address to CodeNode if
possible
:param CFGNode cfg_node: A CFGNode instance.
:param int function_addr: Address of the current function.
:return: None |
def move(self, key, folder):
"""Move the specified key to folder.
folder must be an MdFolder instance. MdFolders can be obtained
through the 'folders' method call.
"""
# Basically this is a sophisticated __delitem__
# We need the path so we can make it in the new folder
... | Move the specified key to folder.
folder must be an MdFolder instance. MdFolders can be obtained
through the 'folders' method call. |
def root_mean_square(X):
''' root mean square for each variable in the segmented time series '''
segment_width = X.shape[1]
return np.sqrt(np.sum(X * X, axis=1) / segment_width) | root mean square for each variable in the segmented time series |
def add_url_rule(
self,
path: str,
endpoint: Optional[str]=None,
view_func: Optional[Callable]=None,
methods: Optional[Iterable[str]]=None,
defaults: Optional[dict]=None,
host: Optional[str]=None,
subdomain: Optional[str]=No... | Add a route/url rule to the application.
This is designed to be used on the application directly. An
example usage,
.. code-block:: python
def route():
...
app.add_url_rule('/', route)
Arguments:
path: The path to route on, should ... |
def send_text(self, text):
"""Send a plain text message to the room."""
return self.client.api.send_message(self.room_id, text) | Send a plain text message to the room. |
def uniform_discr_frompartition(partition, dtype=None, impl='numpy', **kwargs):
"""Return a uniformly discretized L^p function space.
Parameters
----------
partition : `RectPartition`
Uniform partition to be used for discretization.
It defines the domain and the functions and the grid f... | Return a uniformly discretized L^p function space.
Parameters
----------
partition : `RectPartition`
Uniform partition to be used for discretization.
It defines the domain and the functions and the grid for
discretization.
dtype : optional
Data type for the discretized s... |
def _determine_rotated_logfile(self):
"""
We suspect the logfile has been rotated, so try to guess what the
rotated filename is, and return it.
"""
rotated_filename = self._check_rotated_filename_candidates()
if rotated_filename and exists(rotated_filename):
i... | We suspect the logfile has been rotated, so try to guess what the
rotated filename is, and return it. |
def fieldAlphaHistogram(
self, name, q='*:*', fq=None, nbins=10, includequeries=True
):
"""Generates a histogram of values from a string field. Output is:
[[low, high, count, query], ... ] Bin edges is determined by equal division
of the fields
"""
oldpersist = s... | Generates a histogram of values from a string field. Output is:
[[low, high, count, query], ... ] Bin edges is determined by equal division
of the fields |
def get_managed_policy_document(policy_arn, policy_metadata=None, client=None, **kwargs):
"""Retrieve the currently active (i.e. 'default') policy version document for a policy.
:param policy_arn:
:param policy_metadata: This is a previously fetch managed policy response from boto/cloudaux.
... | Retrieve the currently active (i.e. 'default') policy version document for a policy.
:param policy_arn:
:param policy_metadata: This is a previously fetch managed policy response from boto/cloudaux.
This is used to prevent unnecessary API calls to get the initial policy default vers... |
def unit_overlap(evaluated_model, reference_model):
"""
Computes unit overlap of two text documents. Documents
has to be represented as TF models of non-empty document.
:returns float:
0 <= overlap <= 1, where 0 means no match and 1 means
exactly the same.
"""
if not (isinstance... | Computes unit overlap of two text documents. Documents
has to be represented as TF models of non-empty document.
:returns float:
0 <= overlap <= 1, where 0 means no match and 1 means
exactly the same. |
def register_model(cls, model):
"""
Register a model class according to its remote name
Args:
model: the model to register
"""
rest_name = model.rest_name
resource_name = model.resource_name
if rest_name not in cls._model_rest_name_regis... | Register a model class according to its remote name
Args:
model: the model to register |
def write_dltime (self, url_data):
"""Write url_data.dltime."""
self.writeln(u"<tr><td>"+self.part("dltime")+u"</td><td>"+
(_("%.3f seconds") % url_data.dltime)+
u"</td></tr>") | Write url_data.dltime. |
def knob_end(self):
""" Coordinates of the end of the knob residue (atom in side-chain furthest from CB atom.
Returns CA coordinates for GLY.
"""
side_chain_atoms = self.knob_residue.side_chain
if not side_chain_atoms:
return self.knob_residue['CA']
distances ... | Coordinates of the end of the knob residue (atom in side-chain furthest from CB atom.
Returns CA coordinates for GLY. |
def directional_hamming_distance(reference_intervals, estimated_intervals):
"""Compute the directional hamming distance between reference and
estimated intervals as defined by [#harte2010towards]_ and used for MIREX
'OverSeg', 'UnderSeg' and 'MeanSeg' measures.
Examples
--------
>>> (ref_interv... | Compute the directional hamming distance between reference and
estimated intervals as defined by [#harte2010towards]_ and used for MIREX
'OverSeg', 'UnderSeg' and 'MeanSeg' measures.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')
>>> (... |
def _fix_repo_url(repo_url):
"""Add empty credentials to a repo URL if not set, but only for HTTP/HTTPS.
This is to make git not hang while trying to read the username and
password from standard input."""
parsed = urlparse.urlparse(repo_url)
if parsed.scheme not in ('http', 'https'):
... | Add empty credentials to a repo URL if not set, but only for HTTP/HTTPS.
This is to make git not hang while trying to read the username and
password from standard input. |
def get_rendition_size(self, spec, output_scale, crop):
"""
Wrapper to determine the overall rendition size and cropping box
Returns tuple of (size,box)
"""
if crop:
# Use the cropping rectangle size
_, _, width, height = crop
else:
#... | Wrapper to determine the overall rendition size and cropping box
Returns tuple of (size,box) |
def _check_operators(self):
"""Check Operators
This method checks if the input operators have a "cost" method
Raises
------
ValueError
For invalid operators type
ValueError
For operators without "cost" method
"""
if not isinstan... | Check Operators
This method checks if the input operators have a "cost" method
Raises
------
ValueError
For invalid operators type
ValueError
For operators without "cost" method |
def decode(data):
'''
str -> bytes
'''
if riemann.network.CASHADDR_PREFIX is None:
raise ValueError('Network {} does not support cashaddresses.'
.format(riemann.get_current_network_name()))
if data.find(riemann.network.CASHADDR_PREFIX) != 0:
raise ValueError(... | str -> bytes |
def _make_fake_message(self, user_id, page_id, payload):
"""
Creates a fake message for the given user_id. It contains a postback
with the given payload.
"""
event = {
'sender': {
'id': user_id,
},
'recipient': {
... | Creates a fake message for the given user_id. It contains a postback
with the given payload. |
def _main(self):
"""
process
"""
probes = self.config.get('probes', None)
if not probes:
raise ValueError('no probes specified')
for probe_config in self.config['probes']:
probe = plugin.get_probe(probe_config, self.plugin_context)
# F... | process |
def validate_rc():
""" Before we execute any actions, let's validate our .vacationrc. """
transactions = rc.read()
if not transactions:
print('Your .vacationrc file is empty! Set days and rate.')
return False
transactions = sort(unique(transactions))
return validate_setup(transaction... | Before we execute any actions, let's validate our .vacationrc. |
def parse(data):
"""
Parse the given ChangeLog data into a list of Hashes.
@param [String] data File data from the ChangeLog.md
@return [Array<Hash>] Parsed data, e.g. [{ 'version' => ..., 'url' => ..., 'date' => ..., 'content' => ...}, ...]
"""
sections = re.compile("^## .+$", re.MULTILINE).s... | Parse the given ChangeLog data into a list of Hashes.
@param [String] data File data from the ChangeLog.md
@return [Array<Hash>] Parsed data, e.g. [{ 'version' => ..., 'url' => ..., 'date' => ..., 'content' => ...}, ...] |
def get_file_str(path, saltenv='base'):
'''
Download a file from a URL to the Minion cache directory and return the
contents of that file
Returns ``False`` if Salt was unable to cache a file from a URL.
CLI Example:
.. code-block:: bash
salt '*' cp.get_file_str salt://my/file
'''... | Download a file from a URL to the Minion cache directory and return the
contents of that file
Returns ``False`` if Salt was unable to cache a file from a URL.
CLI Example:
.. code-block:: bash
salt '*' cp.get_file_str salt://my/file |
def to_wire(self, file, compress=None, origin=None, **kw):
"""Convert the RRset to wire format."""
return super(RRset, self).to_wire(self.name, file, compress, origin,
self.deleting, **kw) | Convert the RRset to wire format. |
def set_lacp_fallback(self, name, mode=None):
"""Configures the Port-Channel lacp_fallback
Args:
name(str): The Port-Channel interface name
mode(str): The Port-Channel LACP fallback setting
Valid values are 'disabled', 'static', 'individual':
* ... | Configures the Port-Channel lacp_fallback
Args:
name(str): The Port-Channel interface name
mode(str): The Port-Channel LACP fallback setting
Valid values are 'disabled', 'static', 'individual':
* static - Fallback to static LAG mode
* i... |
def vote_choice_address(self) -> List[str]:
'''calculate the addresses on which the vote is casted.'''
if self.vote_id is None:
raise Exception("vote_id is required")
addresses = []
vote_init_txid = unhexlify(self.vote_id)
for choice in self.choices:
vo... | calculate the addresses on which the vote is casted. |
def _get_elements(complex_type, root):
"""Get attribute elements
"""
found_elements = []
element = findall(root, '{%s}complexType' % XS_NAMESPACE,
attribute_name='name', attribute_value=complex_type)[0]
found_elements = findall(element, '{%s}element' % XS_NAMESPACE)
retu... | Get attribute elements |
def on_menu_exit(self, event):
"""
Exit the GUI
"""
# also delete appropriate copy file
try:
self.help_window.Destroy()
except:
pass
if '-i' in sys.argv:
self.Destroy()
try:
sys.exit() # can raise TypeError i... | Exit the GUI |
def convert_op(self, op):
"""
Converts NeuroML arithmetic/logical operators to python equivalents.
@param op: NeuroML operator
@type op: string
@return: Python operator
@rtype: string
"""
if op == '.gt.':
return '>'
elif op == '.ge.... | Converts NeuroML arithmetic/logical operators to python equivalents.
@param op: NeuroML operator
@type op: string
@return: Python operator
@rtype: string |
def get_rendered_fields(self, ctx=None):
'''
:param ctx: rendering context in which the method was called
:return: ordered list of the fields that will be rendered
'''
if ctx is None:
ctx = RenderContext()
ctx.push(self)
current = self._fields[self._fi... | :param ctx: rendering context in which the method was called
:return: ordered list of the fields that will be rendered |
def _get_shaperecords(self, num_fill_bits,
num_line_bits, shape_number):
"""Return an array of SHAPERECORDS."""
shape_records = []
bc = BitConsumer(self._src)
while True:
type_flag = bc.u_get(1)
if type_flag:
# edge recor... | Return an array of SHAPERECORDS. |
def get_scale_fac(fig, fiducial_width=8, fiducial_height=7):
"""Gets a factor to scale fonts by for the given figure. The scale
factor is relative to a figure with dimensions
(`fiducial_width`, `fiducial_height`).
"""
width, height = fig.get_size_inches()
return (width*height/(fiducial_width*fid... | Gets a factor to scale fonts by for the given figure. The scale
factor is relative to a figure with dimensions
(`fiducial_width`, `fiducial_height`). |
def fetch(version='bayestar2017'):
"""
Downloads the specified version of the Bayestar dust map.
Args:
version (Optional[:obj:`str`]): The map version to download. Valid versions are
:obj:`'bayestar2017'` (Green, Schlafly, Finkbeiner et al. 2018) and
:obj:`'bayestar2015'` (G... | Downloads the specified version of the Bayestar dust map.
Args:
version (Optional[:obj:`str`]): The map version to download. Valid versions are
:obj:`'bayestar2017'` (Green, Schlafly, Finkbeiner et al. 2018) and
:obj:`'bayestar2015'` (Green, Schlafly, Finkbeiner et al. 2015). Defaul... |
def timeinfo(self):
"""Time series data of the time step.
Set to None if no time series data is available for this time step.
"""
if self.istep not in self.sdat.tseries.index:
return None
return self.sdat.tseries.loc[self.istep] | Time series data of the time step.
Set to None if no time series data is available for this time step. |
def latitude(self, latitude):
"""Setter for latiutde."""
if not (-90 <= latitude <= 90):
raise ValueError('latitude was {}, but has to be in [-90, 90]'
.format(latitude))
self._latitude = latitude | Setter for latiutde. |
def resource_to_url(resource, request=None, quote=False):
"""
Converts the given resource to a URL.
:param request: Request object (required for the host name part of the
URL). If this is not given, the current request is used.
:param bool quote: If set, the URL returned will be quoted.
"""
... | Converts the given resource to a URL.
:param request: Request object (required for the host name part of the
URL). If this is not given, the current request is used.
:param bool quote: If set, the URL returned will be quoted. |
def spades(args):
"""
%prog spades folder
Run automated SPADES.
"""
from jcvi.formats.fastq import readlen
p = OptionParser(spades.__doc__)
opts, args = p.parse_args(args)
if len(args) == 0:
sys.exit(not p.print_help())
folder, = args
for p, pf in iter_project(folder)... | %prog spades folder
Run automated SPADES. |
def _fetch(self, params, required, defaults):
"""Make the NVP request and store the response."""
defaults.update(params)
pp_params = self._check_and_update_params(required, defaults)
pp_string = self.signature + urlencode(pp_params)
response = self._request(pp_string)
res... | Make the NVP request and store the response. |
def _check_response(response, expected):
"""
Checks if the expected response code matches the actual response code.
If they're not equal, raises the appropriate exception
Args:
response: (int) Actual status code
expected: (int) Expected status code
"""
... | Checks if the expected response code matches the actual response code.
If they're not equal, raises the appropriate exception
Args:
response: (int) Actual status code
expected: (int) Expected status code |
def class_in_progress(stack=None):
"""True if currently inside a class definition, else False."""
if stack is None:
stack = inspect.stack()
for frame in stack:
statement_list = frame[4]
if statement_list is None:
continue
if statement_list[0].strip().startswith('c... | True if currently inside a class definition, else False. |
async def delete(self, request, resource=None, **kwargs):
"""Delete a resource."""
if resource is None:
raise RESTNotFound(reason='Resource not found')
self.collection.remove(resource) | Delete a resource. |
def data_files(self):
"""Returns a python list of all (sharded) data subset files.
Returns:
python list of all (sharded) data set files.
Raises:
ValueError: if there are not data_files matching the subset.
"""
tf_record_pattern = os.path.join(FLAGS.data_dir, '%s-*' % self.subset)
da... | Returns a python list of all (sharded) data subset files.
Returns:
python list of all (sharded) data set files.
Raises:
ValueError: if there are not data_files matching the subset. |
def populate(self):
"""Populates a new cache.
"""
if self.exists:
raise CacheAlreadyExistsException('location: %s' % self.cache_uri)
self._populate_setup()
with closing(self.graph):
with self._download_metadata_archive() as metadata_archive:
... | Populates a new cache. |
def time_col_turbulent(EnergyDis, ConcAl, ConcClay, coag, material,
DiamTarget, DIM_FRACTAL):
"""Calculate single collision time for turbulent flow mediated collisions.
Calculated as a function of floc size.
"""
return((1/6) * (6/np.pi)**(1/9) * EnergyDis**(-1/3) * DiamTarget**(2... | Calculate single collision time for turbulent flow mediated collisions.
Calculated as a function of floc size. |
def registerFilter(self, column, patterns, is_regex=False,
ignore_case=False):
"""Register filter on a column of table.
@param column: The column name.
@param patterns: A single pattern or a list of patterns used for
matching ... | Register filter on a column of table.
@param column: The column name.
@param patterns: A single pattern or a list of patterns used for
matching column values.
@param is_regex: The patterns will be treated as regex if True, the
... |
def derenzo_sources(space, min_pt=None, max_pt=None):
"""Create the PET/SPECT Derenzo sources phantom.
The Derenzo phantom contains a series of circles of decreasing size.
In 3d the phantom is simply the 2d phantom extended in the z direction as
cylinders.
Parameters
----------
space : `D... | Create the PET/SPECT Derenzo sources phantom.
The Derenzo phantom contains a series of circles of decreasing size.
In 3d the phantom is simply the 2d phantom extended in the z direction as
cylinders.
Parameters
----------
space : `DiscreteLp`
Space in which the phantom should be creat... |
def add_ones(a):
"""Adds a column of 1s at the end of the array"""
arr = N.ones((a.shape[0],a.shape[1]+1))
arr[:,:-1] = a
return arr | Adds a column of 1s at the end of the array |
def call_pre_hook(awsclient, cloudformation):
"""Invoke the pre_hook BEFORE the config is read.
:param awsclient:
:param cloudformation:
"""
# TODO: this is deprecated!! move this to glomex_config_reader
# no config available
if not hasattr(cloudformation, 'pre_hook'):
# hook is not... | Invoke the pre_hook BEFORE the config is read.
:param awsclient:
:param cloudformation: |
def get_daemon_stats(self, details=False):
"""Send a HTTP request to the satellite (GET /get_daemon_stats)
:return: Daemon statistics
:rtype: dict
"""
logger.debug("Get daemon statistics for %s, %s %s", self.name, self.alive, self.reachable)
return self.con.get('stats%s'... | Send a HTTP request to the satellite (GET /get_daemon_stats)
:return: Daemon statistics
:rtype: dict |
def list_items(path_to_directory, pattern, wanted):
"""All items in the given path which match the given glob and are wanted"""
if not path_to_directory:
return set()
needed = make_needed(pattern, path_to_directory, wanted)
return [os.path.join(path_to_directory, name)
for name in _n... | All items in the given path which match the given glob and are wanted |
def get_sidecar(fname, allowedfileformats='default'):
"""
Loads sidecar or creates one
"""
if allowedfileformats == 'default':
allowedfileformats = ['.tsv', '.nii.gz']
for f in allowedfileformats:
fname = fname.split(f)[0]
fname += '.json'
if os.path.exists(fname):
wi... | Loads sidecar or creates one |
def increase(self, infile):
'''Increase: 任意の箇所のバイト列と それより大きなサイズの任意のバイト列と入れ換える
'''
gf = infile[31:]
index = gf.index(random.choice(gf))
index_len = len(gf[index])
large_size_index = random.choice([gf.index(g) for g in gf if len(g) > index_len])
gf[index], gf[large_... | Increase: 任意の箇所のバイト列と それより大きなサイズの任意のバイト列と入れ換える |
def getReferenceSetByName(self, name):
"""
Returns the reference set with the specified name.
"""
if name not in self._referenceSetNameMap:
raise exceptions.ReferenceSetNameNotFoundException(name)
return self._referenceSetNameMap[name] | Returns the reference set with the specified name. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.