text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def randomize_molecule_low(molecule, manipulations):
"""Return a randomized copy of the molecule, without the nonbond check."""
manipulations = copy.copy(manipulations)
shuffle(manipulations)
coordinates = molecule.coordinates.copy()
for manipulation in manipulations:
manipulation.apply(coo... | 0.002604 |
def sheet_to_table(worksheet):
"""Transforma una hoja de libro de Excel en una lista de diccionarios.
Args:
worksheet (Workbook.worksheet): Hoja de cálculo de un archivo XLSX
según los lee `openpyxl`
Returns:
list_of_dicts: Lista de diccionarios, con tantos elementos como
... | 0.000651 |
def uppercase_chars(string: any) -> str:
"""Return all (and only) the uppercase chars in the given string."""
return ''.join([c if c.isupper() else '' for c in str(string)]) | 0.010582 |
def get_arp_output_arp_entry_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_arp = ET.Element("get_arp")
config = get_arp
output = ET.SubElement(get_arp, "output")
arp_entry = ET.SubElement(output, "arp-entry")
... | 0.003086 |
def create_extras(cls: Type[T],
extras: Dict[str, Any]) -> Dict[str, Any]:
"""
Given a dictionary of extra arguments, returns a dictionary of
kwargs that actually are a part of the signature of the cls.from_params
(or cls) method.
"""
subextras: Dict[str, Any] = {}
if hasat... | 0.005634 |
def create_ppo_optimizer(self, probs, old_probs, value, entropy, beta, epsilon, lr, max_step):
"""
Creates training-specific Tensorflow ops for PPO models.
:param probs: Current policy probabilities
:param old_probs: Past policy probabilities
:param value: Current value estimate
... | 0.007413 |
def _draw_arrow(
self, x1, y1, x2, y2, Dx, Dy, label="", width=1.0, arrow_curvature=1.0, color="grey",
patchA=None, patchB=None, shrinkA=0, shrinkB=0, arrow_label_size=None):
"""
Draws a slightly curved arrow from (x1,y1) to (x2,y2).
Will allow the given patches at start end end.... | 0.003127 |
def build_train(make_obs_ph, q_func, num_actions, optimizer, grad_norm_clipping=None, gamma=1.0,
double_q=True, scope="deepq", reuse=None, param_noise=False, param_noise_filter_func=None):
"""Creates the train function:
Parameters
----------
make_obs_ph: str -> tf.placeholder or TfInput
a f... | 0.004132 |
def datetime(anon, obj, field, val):
"""
Returns a random datetime
"""
return anon.faker.datetime(field=field) | 0.007937 |
def post_op(self, id: str, path_data: Union[dict, None], post_data: Any) -> dict:
"""Modifies the ESI by looking up an operation id.
Args:
path: raw ESI URL path
path_data: data to format the path with (can be None)
post_data: data to send to ESI
Returns:
... | 0.006637 |
def generate_source_catalog(image, **kwargs):
""" Build source catalogs for each chip using photutils.
The catalog returned by this function includes sources found in all chips
of the input image with the positions translated to the coordinate frame
defined by the reference WCS `refwcs`. The sources w... | 0.001304 |
def consume(self, state):
"""
consume new producer state
"""
self.state.append(self.func(state))
return self.state | 0.012987 |
def result(self, timeout=None):
"""Gets the result of the task.
Arguments:
timeout: Maximum seconds to wait for a result before raising a
TimeoutError. If set to None, this will wait forever. If the
queue doesn't store results and timeout is None, this call w... | 0.002427 |
def authorize_redirect(self, callback_uri=None, extra_params=None):
"""Redirects the user to obtain OAuth authorization for this service.
Twitter and FriendFeed both require that you register a Callback
URL with your application. You should call this method to log the
user in, and then ... | 0.003712 |
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'... | 0.00225 |
def slackpkg_update(self):
"""This replace slackpkg ChangeLog.txt file with new
from Slackware official mirrors after update distribution.
"""
NEW_ChangeLog_txt = URL(mirrors("ChangeLog.txt", "")).reading()
if os.path.isfile(self.meta.slackpkg_lib_path + "ChangeLog.txt.old"):
... | 0.00243 |
def _sample_item(self, **kwargs):
"""Sample an item from the pool according to the instrumental
distribution
"""
t = self.t_
# Update instrumental distribution
self._calc_inst_pmf()
if self.record_inst_hist:
inst_pmf = self._inst_pmf[:,t]
els... | 0.00846 |
def upload(self, local_path, remote_url):
"""Copy a local file to an S3 location."""
bucket, key = _parse_url(remote_url)
with open(local_path, 'rb') as fp:
return self.call("PutObject", bucket=bucket, key=key, body=fp) | 0.007813 |
def GetParentFileEntry(self):
"""Retrieves the parent file entry.
Returns:
OSFileEntry: parent file entry or None if not available.
"""
location = getattr(self.path_spec, 'location', None)
if location is None:
return None
parent_location = self._file_system.DirnamePath(location)
... | 0.006678 |
def user_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/users#create-user"
api_path = "/api/v2/users.json"
return self.call(api_path, method="POST", data=data, **kwargs) | 0.00885 |
def TNE_metric(bpmn_graph):
"""
Returns the value of the TNE metric (Total Number of Events of the Model)
for the BPMNDiagramGraph instance.
:param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model.
"""
events_counts = get_events_counts(bpmn_graph)
return sum(
[c... | 0.00271 |
def get_clients_per_page(self, per_page=1000, page=1, params=None):
"""
Get clients per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
retu... | 0.007264 |
def val_where(cond, tval, fval):
"""Like tf.where but works on namedtuples."""
if isinstance(tval, tf.Tensor):
return tf.where(cond, tval, fval)
elif isinstance(tval, tuple):
cls = type(tval)
return cls(*(val_where(cond, t, f) for t, f in zip(tval, fval)))
else:
raise Exception(TypeError) | 0.015974 |
def fit(self, X, design, nuisance=None, scan_onsets=None, coords=None,
inten=None):
"""Compute the Bayesian RSA
Parameters
----------
X: numpy array, shape=[time_points, voxels]
If you have multiple scans of the same participants that you
want to anal... | 0.000258 |
def _get_traceback_no_io():
"""
Return a version of L{traceback} that doesn't do I/O.
"""
try:
module = load_module(str("_traceback_no_io"), traceback)
except NotImplementedError:
# Can't fix the I/O problem, oh well:
return traceback
class FakeLineCache(object):
... | 0.001748 |
def byPromissor(self, ID):
""" Returns all directions to a promissor. """
res = []
for direction in self.table:
if ID in direction[1]:
res.append(direction)
return res | 0.008811 |
def run(self):
'''Run until there are no events to be processed.'''
# We left-append rather than emit (right-append) because some message
# may have been already queued for execution before the director runs.
global_event_queue.appendleft((INITIATE, self, (), {}))
while global_ev... | 0.005115 |
def delete(self, key):
'''Removes the object named by `key` in `service`.
Args:
key: Key naming the object to remove.
'''
key = self._service_key(key)
self._service_ops['delete'](key) | 0.004762 |
def off_command_control(self, val_id):
"""
Parameters
----------
val_id : str
Returns
-------
requests.Response
"""
data = "control,controlId=0|" + val_id
return self._basic_post(url='commandControlPublic', data=data) | 0.006711 |
def _get_rs_id(variant, rs_map, variant_type):
"""
Given a variant dict, return unambiguous RS ID
TODO
Some sequence alterations appear to have mappings to dbsnp's notation
for example,
reference allele: TTTTTTTTTTTTTT
variant allele: TTTTTTTTTTTTTTT
Is ... | 0.002208 |
def attributes(self):
"""Return sync attributes."""
attr = {
'name': self.name,
'id': self.sync_id,
'network_id': self.network_id,
'serial': self.serial,
'status': self.status,
'region': self.region,
'region_id': self.re... | 0.005587 |
def randomMails(self, count=1):
"""
Return random e-mails.
:rtype: list
:returns: list of random e-mails
"""
self.check_count(count)
random_nicks = self.rn.random_nicks(count=count)
random_domains = sample(self.dmails, count)
return [
... | 0.004193 |
def do_keyframes_overlap(self):
"""Checks for keyframs timing overlap.
Returns the name of the first keyframs that overlapped."""
skl = self.sorted_key_list()
for i in range(len(skl)-1):
this_time = self.dct[skl[i]]['__abs_time__']
next_time = self.dct[skl[i+1]][... | 0.003914 |
def includeme(config):
"""
:type config: :class:`pyramid.config.Configurator`
"""
settings = config.registry.settings
swagger_versions = get_swagger_versions(settings)
# for rendering /swagger.yaml
config.add_renderer(
'yaml', 'pyramid_swagger.api.YamlRendererFactory',
)
# ... | 0.001306 |
def _get_cygwin_path(self, windows_path):
"""
Convert windows path to cygpath
"""
conv_cmd = [os.path.join(self._cygwin_bin_location, "cygpath.exe"),
"-u", windows_path]
process = Popen(conv_cmd,
stdout=PIPE, stderr=PIPE, shell=False)
... | 0.004357 |
def get_user(self, name):
"""Get the user for the given name
:param name: The username
:type name: :class:`str`
:returns: the user instance
:rtype: :class:`models.User`
:raises: None
"""
r = self.kraken_request('GET', 'user/' + name)
return models... | 0.005848 |
def del_downtime(self, downtime_id):
"""
Delete a downtime in this object
:param downtime_id: id of the downtime to delete
:type downtime_id: int
:return: None
"""
if downtime_id in self.downtimes:
self.downtimes[downtime_id].can_be_deleted = True
... | 0.005556 |
def update_keys(self):
"""Updates the Google API key with the text value"""
from ...main import add_api_key
add_api_key("reddit_api_user_agent", self.reddit_api_user_agent.get())
add_api_key("reddit_api_client_id", self.reddit_api_client_id.get())
add_api_key("reddit_api_client_s... | 0.008242 |
def has_comment(src):
"""Indicate whether an input line has (i.e. ends in, or is) a comment.
This uses tokenize, so it can distinguish comments from # inside strings.
Parameters
----------
src : string
A single line input string.
Returns
-------
Boolean: True if sour... | 0.006861 |
def derive(self, srcfile=None, request=None, outfile=None):
"""Do sequence of manipulations for IIIF to derive output image.
Named argments:
srcfile -- source image file
request -- IIIFRequest object with parsed parameters
outfile -- output image file. If set the the output file... | 0.001066 |
async def start(self, *args, **kwargs):
"""|coro|
A shorthand coroutine for :meth:`login` + :meth:`connect`.
"""
bot = kwargs.pop('bot', True)
reconnect = kwargs.pop('reconnect', True)
await self.login(*args, bot=bot)
await self.connect(reconnect=reconnect) | 0.006349 |
def map_keys_deep(f, dct):
"""
Implementation of map that recurses. This tests the same keys at every level of dict and in lists
:param f: 2-ary function expecting a key and value and returns a modified key
:param dct: Dict for deep processing
:return: Modified dct with matching props mapped
"""... | 0.008043 |
def repo_groups(self, project_key, repo_key, limit=99999, filter_str=None):
"""
Get repository Groups
:param project_key:
:param repo_key:
:param limit: OPTIONAL: The limit of the number of groups to return, this may be restricted by
fixed system limit... | 0.006165 |
def rest_put(url, data, timeout):
'''Call rest put method'''
try:
response = requests.put(url, headers={'Accept': 'application/json', 'Content-Type': 'application/json'},\
data=data, timeout=timeout)
return response
except Exception as e:
print('Get ex... | 0.009852 |
def to_sections(idl_parsed):
"""
Iterates through elements in idl_parsed list and returns a list of section dicts.
Currently elements of type "comment", "enum", "struct", and "interface" are processed.
:Parameters:
idl_parsed
Barrister parsed IDL
"""
sections = []
for entity i... | 0.004115 |
def rlmb_ppo_quick():
"""Base setting but quicker with only 2 epochs."""
hparams = rlmb_ppo_base()
hparams.epochs = 2
hparams.model_train_steps = 25000
hparams.ppo_epochs_num = 700
hparams.ppo_epoch_length = 50
return hparams | 0.033473 |
def histogram(data):
"""Returns a histogram of your data.
:param data: The data to histogram
:type data: list[object]
:return: The histogram
:rtype: dict[object, int]
"""
ret = {}
for datum in data:
if datum in ret:
ret[datum] += 1
else:
ret[datum... | 0.002941 |
def get_kvlayer_stream_ids_by_doc_id(client, doc_id):
'''Retrieve stream ids from :mod:`kvlayer`.
Namely, it returns an iterator over all stream ids with the given
docid. The docid should be an md5 hash of the document's abs_url.
:param client: kvlayer client object
:type client: :class:`kvlayer.A... | 0.001339 |
def internal_get_next_statement_targets(dbg, seq, thread_id, frame_id):
''' gets the valid line numbers for use with set next statement '''
try:
frame = dbg.find_frame(thread_id, frame_id)
if frame is not None:
code = frame.f_code
xml = "<xml>"
if hasattr(code... | 0.003613 |
def subscribe(self, code_list, subtype_list, is_first_push=True):
"""
订阅注册需要的实时信息,指定股票和订阅的数据类型即可
注意:len(code_list) * 订阅的K线类型的数量 <= 100
:param code_list: 需要订阅的股票代码列表
:param subtype_list: 需要订阅的数据类型列表,参见SubType
:param is_first_push: 订阅成功后是否马上推送一次数据
:return: (ret, e... | 0.002653 |
def _insert_base_path(self):
"""If the "base" path is set in the paths section of the config, insert
it into the python path.
"""
if config.BASE in self.paths:
sys.path.insert(0, self.paths[config.BASE]) | 0.008065 |
def copyFile(src, dest):
"""Copies a source file to a destination whose path may not yet exist.
Keyword arguments:
src -- Source path to a file (string)
dest -- Path for destination file (also a string)
"""
#Src Exists?
try:
if os.path.isfile(src):
dpath, dfile = os.path... | 0.003344 |
def _read(self, fp, fpname):
"""A direct copy of the py2.4 version of the super class's _read method
to assure it uses ordered dicts. Had to change one line to make it work.
Future versions have this fixed, but in fact its quite embarrassing for the
guys not to have done it right in the... | 0.00192 |
def GetUsers(alias=None):
"""Gets all of users assigned to a given account.
https://t3n.zendesk.com/entries/22427662-GetUsers
:param alias: short code for a particular account. If none will use account's default alias
"""
if alias is None: alias = clc.v1.Account.GetAlias()
r = clc.v1.API.Call('post','... | 0.040964 |
def link_to_storage(self, sensor_log):
"""Attach this DataStreamer to an underlying SensorLog.
Calling this method is required if you want to use this DataStreamer
to generate reports from the underlying data in the SensorLog.
You can call it multiple times and it will unlink itself fr... | 0.003891 |
def establish_connection(self):
"""Establish connection to the AMQP broker."""
conninfo = self.connection
if not conninfo.hostname:
raise KeyError("Missing hostname for AMQP connection.")
if conninfo.userid is None:
raise KeyError("Missing user id for AMQP connect... | 0.002454 |
def _cleanup(self) -> None:
"""Cleanup unused transports."""
if self._cleanup_handle:
self._cleanup_handle.cancel()
now = self._loop.time()
timeout = self._keepalive_timeout
if self._conns:
connections = {}
deadline = now - timeout
... | 0.001658 |
def ways_in_bbox(lat_min, lng_min, lat_max, lng_max, network_type,
timeout=180, memory=None,
max_query_area_size=50*1000*50*1000,
custom_osm_filter=None):
"""
Get DataFrames of OSM data in a bounding box.
Parameters
----------
lat_min : float
... | 0.000501 |
def _orbList(obj1, obj2, aspList):
""" Returns a list with the orb and angular
distances from obj1 to obj2, considering a
list of possible aspects.
"""
sep = angle.closestdistance(obj1.lon, obj2.lon)
absSep = abs(sep)
return [
{
'type': asp,
'orb': abs(a... | 0.007519 |
def identifier(self):
"""Get the identifier for this node.
Extended keys can be identified by the Hash160 (RIPEMD160 after SHA256)
of the public key's `key`. This corresponds exactly to the data used in
traditional Bitcoin addresses. It is not advised to represent this data
in b... | 0.003263 |
def create_session(self, session_request, protocol):
"""CreateSession.
[Preview API] Creates a session, a wrapper around a feed that can store additional metadata on the packages published to it.
:param :class:`<SessionRequest> <azure.devops.v5_0.provenance.models.SessionRequest>` session_reques... | 0.006284 |
def neg_loglikelihood(y, mean, scale, shape, skewness):
""" Negative loglikelihood function for this distribution
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Cauchy distribution
... | 0.002721 |
def train(sess, loss, x_train, y_train,
init_all=False, evaluate=None, feed=None, args=None,
rng=None, var_list=None, fprop_args=None, optimizer=None,
devices=None, x_batch_preprocessor=None, use_ema=False,
ema_decay=.998, run_canary=None,
loss_threshold=1e5, dataset_tr... | 0.008006 |
def get_tx_fee(tx_hex, config_path=None, bitcoind_opts=None, bitcoind_client=None):
"""
Get the tx fee for a tx
Return the fee on success
Return None on error
"""
tx_fee_per_byte = get_tx_fee_per_byte(config_path=config_path, bitcoind_opts=bitcoind_opts, bitcoind_client=bitcoind_client)
if t... | 0.007194 |
def select_page(self, limit, offset=0, **kwargs):
"""
:type limit: int
:param limit: The max row number for each page
:type offset: int
:param offset: The starting position of the page
:return:
"""
start = offset
while True:
result = se... | 0.003781 |
def invoke(self):
"""
Call the external handler to be invoked.
"""
# flush to ensure external process can see flags as they currently
# are, and write flags (flush releases lock)
unitdata.kv().flush()
subprocess.check_call([self._filepath, '--invoke', self._test_o... | 0.008746 |
def partial(self, fn, *user_args, **user_kwargs):
"""Return function with closure to lazily inject annotated callable.
Repeat calls to the resulting function will reuse injections from the
first call.
Positional arguments are provided in this order:
1. positional arguments pro... | 0.002646 |
def chip_as_adjacency_list(device: 'cirq.google.XmonDevice',
) -> Dict[GridQubit, List[GridQubit]]:
"""Gives adjacency list representation of a chip.
The adjacency list is constructed in order of above, left_of, below and
right_of consecutively.
Args:
device: Chip to... | 0.002717 |
def range(self, low, high, with_scores=False, desc=False, reverse=False):
"""
Return a range of items between ``low`` and ``high``. By
default scores will not be included, but this can be controlled
via the ``with_scores`` parameter.
:param low: Lower bound.
:param high:... | 0.002551 |
def get_all_conversion_chains(self, from_type: Type[Any] = JOKER, to_type: Type[Any] = JOKER) \
-> Tuple[List[Converter], List[Converter], List[Converter]]:
"""
Utility method to find matching converters or conversion chains.
:param from_type: a required type of input object, or JOK... | 0.006773 |
def _init_command(self, action, flags=None):
''' a wrapper to the base init_command, ensuring that "oci" is added
to each command
Parameters
==========
action: the main action to perform (e.g., build)
flags: one or more additional flags (e.g, volumes)... | 0.005164 |
def _clear_temp_dir():
""" Clear the temporary directory.
"""
tempdir = get_tempdir()
for fname in os.listdir(tempdir):
try:
os.remove( os.path.join(tempdir, fname) )
except Exception:
pass | 0.012245 |
def get_proficiencies_for_objective_and_resource(self, objective_id, resource_id):
"""Gets a ``ProficiencyList`` relating to the given objective and resource ````.
arg: objective_id (osid.id.Id): an objective ``Id``
arg: resource_id (osid.id.Id): a resource ``Id``
return: (osid.le... | 0.003709 |
def __callbackWrapper(self, transfer_p):
"""
Makes it possible for user-provided callback to alter transfer when
fired (ie, mark transfer as not submitted upon call).
"""
self.__submitted = False
self.__after_completion(self)
callback = self.__callback
if ... | 0.004773 |
def parse_list_header(value):
"""Parse lists as described by RFC 2068 Section 2.
In particular, parse comma-separated lists where the elements of
the list may include quoted-strings. A quoted-string could
contain a comma. A non-quoted string could have quotes in the
middle. Quotes are removed au... | 0.000992 |
def seek(self, position):
"""Seek to the specified position (byte offset) in the S3 key.
:param int position: The byte offset from the beginning of the key.
"""
self._position = position
range_string = make_range_string(self._position)
logger.debug('content_length: %r ra... | 0.00498 |
def nvmlDeviceGetSupportedEventTypes(handle):
r"""
/**
* Returns information about events supported on device
*
* For Fermi &tm; or newer fully supported devices.
*
* Events are not supported on Windows. So this function returns an empty mask in \a eventTypes on Windows.
*
* @... | 0.005212 |
def add_connection_score(self, node):
"""
Return a numeric value that determines this node's score for adding
a new connection. A negative value indicates that no connections
should be made to this node for at least that number of seconds.
A value of -inf indicates no connections... | 0.001912 |
def on_exchange_declareok(self, unused_frame):
"""
Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC
command.
:param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame
"""
self._logger.debug('Exchange declared')
self.setup_queue(s... | 0.009063 |
def post_message(self, message, duration=None, pause=True, style="info"):
""" Post a message on the screen with Messenger.
Arguments:
message: The message to display.
duration: The time until the message vanishes. (Default: 2.55s)
pause: If True, the p... | 0.002137 |
def piecewise(target, throat_endpoints='throat.endpoints',
throat_centroid='throat.centroid'):
r"""
Calculate throat length from end points and optionally a centroid
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the... | 0.000577 |
def _insert_update(self, index: int, length: int) -> None:
"""Update self._type_to_spans according to the added length."""
ss, se = self._span
for spans in self._type_to_spans.values():
for span in spans:
if index < span[1] or span[1] == index == se:
... | 0.003861 |
def _parse_line(line=''):
'''
Used by conf() to break config lines into
name/value pairs
'''
parts = line.split()
key = parts.pop(0)
value = ' '.join(parts)
return key, value | 0.004854 |
def build(tagname_or_element, ns_uri=None, adapter=None):
"""
Return a :class:`~xml4h.builder.Builder` that represents an element in
a new or existing XML DOM and provides "chainable" methods focussed
specifically on adding XML content.
:param tagname_or_element: a string name for the root node of ... | 0.000665 |
def report(self, start=0, end=None):
"""
This will return a list of call reports which have the endpoint
with arguments and a representation of the data
:param start: int of the index to start at
:param end: int of the index to end at
:return: list of str
"""
... | 0.005263 |
def setupcfg_requirements(self):
"""Generate requirements from setup.cfg as
('Requires-Dist', 'requirement; qualifier') tuples. From a metadata
section in setup.cfg:
[metadata]
provides-extra = extra1
extra2
requires-dist = requirement; qualifier
... | 0.00265 |
def get_audits():
"""Get OS hardening access audits.
:returns: dictionary of audits
"""
audits = []
settings = utils.get_settings('os')
# Remove write permissions from $PATH folders for all regular users.
# This prevents changing system-wide commands from normal users.
path_folders = ... | 0.000894 |
def setup(path_config="~/.config/scalar/config.yaml", configuration_name=None):
"""
Load a configuration from a default or specified configuration file, accessing a default or
specified configuration name.
"""
global config
global client
global token
global room
# config file
pat... | 0.008416 |
def deploy(self, id_networkv4):
"""Deploy network in equipments and set column 'active = 1' in tables redeipv4
:param id_networkv4: ID for NetworkIPv4
:return: Equipments configuration output
"""
data = dict()
uri = 'api/networkv4/%s/equipments/' % id_networkv4
... | 0.007958 |
def implementation(self, for_type=None, for_types=None):
"""Return a decorator that will register the implementation.
Example:
@multimethod
def add(x, y):
pass
@add.implementation(for_type=int)
def add(x, y):
return x + y
... | 0.003017 |
def __get_query_agg_terms(cls, field, agg_id=None):
"""
Create a es_dsl aggregation object based on a term.
:param field: field to be used to aggregate
:return: a tuple with the aggregation id and es_dsl aggregation object. Ex:
{
"terms": {
... | 0.004734 |
def hist_calls_with_dims(**dims):
"""Decorator to check the distribution of return values of a
function with dimensions.
"""
def hist_wrapper(fn):
@functools.wraps(fn)
def fn_wrapper(*args, **kwargs):
_histogram = histogram(
"%s_calls" % pyformance.registry.ge... | 0.00188 |
def get_arr(self):
"""
Get the heatmap's array within the value range originally provided in ``__init__()``.
The HeatmapsOnImage object saves heatmaps internally in the value range ``(min=0.0, max=1.0)``.
This function converts the internal representation to ``(min=min_value, max=max_va... | 0.005703 |
def is_out_of_range(brain_or_object, result=_marker):
"""Checks if the result for the analysis passed in is out of range and/or
out of shoulders range.
min max
warn min max warn
·········|----... | 0.000506 |
def _to_graph(self, contexts):
"""This is an iterator that returns each edge of our graph
with its two nodes"""
prev = None
for context in contexts:
if prev is None:
prev = context
continue
yield prev[0], context[1], context[0]
... | 0.005952 |
def loop_iteration(self, timeout = 60):
"""A loop iteration - check any scheduled events
and I/O available and run the handlers.
"""
if self.check_events():
return 0
next_timeout, sources_handled = self._call_timeout_handlers()
if self._quit:
retur... | 0.005742 |
def scale_image(self, in_fname, out_fname, max_width, max_height):
"""Scales an image with the same aspect ratio centered in an
image with a given max_width and max_height
if in_fname == out_fname the image can only be scaled down
"""
# local import to avoid testing depende... | 0.001612 |
def validate_account_user_email(self, account_id, user_id, **kwargs): # noqa: E501
"""Validate the user email. # noqa: E501
An endpoint for validating the user email. **Example usage:** `curl -X POST https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/users/{user-id}/validate-email -H 'Auth... | 0.001553 |
def update_agent(self, agent_id, **kwargs):
"""Updates an agent"""
url = 'agents/%s' % agent_id
agent = self._api._put(url, data=json.dumps(kwargs))
return Agent(**agent) | 0.009901 |
def parse_header(filename):
'''Returns a list of :attr:`VariableSpec`, :attr:`FunctionSpec`,
:attr:`StructSpec`, :attr:`EnumSpec`, :attr:`EnumMemberSpec`, and
:attr:`TypeDef` instances representing the c header file.
'''
with open(filename, 'rb') as fh:
content = '\n'.join(fh.read().sp... | 0.000534 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.