text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def extract_file_name(content_dispo):
"""Extract file name from the input request body"""
# print type(content_dispo)
# print repr(content_dispo)
# convertion of escape string (str type) from server
# to unicode object
content_dispo = content_dispo.decode('unicode-escape').strip('"')
file_na... | 0.001876 |
def _discard_config(self):
"""Set candidate_cfg to current running-config. Erase the merge_cfg file."""
discard_candidate = "copy running-config {}".format(
self._gen_full_path(self.candidate_cfg)
)
discard_merge = "copy null: {}".format(self._gen_full_path(self.merge_cfg))
... | 0.009259 |
def get_owner_and_repo(repourl):
"""
Takes a git repository URL from Bitbucket and tries to determine the owner and repository name
:param repourl: Bitbucket git repo in the form of
git@bitbucket.com:OWNER/REPONAME.git
https://bitbucket.com/OWNER/REPONAME.... | 0.004269 |
def split(self, decode=True):
"""
Für das Bit-Alignment (neu Ausrichten von Hex, ASCII-View)
:rtype: list of array.array
"""
start = 0
result = []
message = self.decoded_bits if decode else self.plain_bits
bit_alignments = set()
if self.align_labe... | 0.004412 |
def _getspnam(name, root=None):
'''
Alternative implementation for getspnam, that use only /etc/shadow
'''
root = '/' if not root else root
passwd = os.path.join(root, 'etc/shadow')
with salt.utils.files.fopen(passwd) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_... | 0.001575 |
def get_assessment_part_item_design_session_for_bank(self, bank_id, proxy):
"""Gets the ``OsidSession`` associated with the assessment part item design service for the given bank.
arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank``
return: (osid.assessment.authoring.AssessmentPartItemDesig... | 0.004691 |
def as_task(self, logger=None, **fields):
"""
Start a new L{eliot.Action} of this type as a task (i.e. top-level
action) with the given start fields.
See L{ActionType.__call__} for example of usage.
@param logger: A L{eliot.ILogger} provider to which the action's
me... | 0.003436 |
def sign(self, hash160_lookup, tx_in_idx_set=None, hash_type=None, **kwargs):
"""
Sign a standard transaction.
hash160_lookup:
A dictionary (or another object with .get) where keys are hash160 and
values are tuples (secret exponent, public_pair, is_compressed) or None
... | 0.003946 |
def from_text_file(file_path):
"""Load MonsoonData objects from a text file generated by
MonsoonData.save_to_text_file.
Args:
file_path: The full path of the file load from, including the file
name.
Returns:
A list of MonsoonData objects.
... | 0.003356 |
def create(self, name, regexes, tag_ids, logs=None):
"""
Create a hook
:param name: The hook's name (should be the same as the tag)
:type name: str
:param regexes: The list of regular expressions that Logentries expects.
Ex: `['user_agent = /curl\/[\d.]*/']` Would m... | 0.003965 |
def check_accesspoints(sess):
"""
check the status of all connected access points
"""
ap_names = walk_data(sess, name_ap_oid, helper)[0]
ap_operationals = walk_data(sess, operational_ap_oid, helper)[0]
ap_availabilitys = walk_data(sess, availability_ap_oid, helper)[0]
... | 0.009751 |
def _catch_errors(self, json_response):
""" Changed: removed check on number of elements:
- totalResultsCount not sytematically returned (e.g in hierarchy)
- done in base.py
"""
status = json_response.get('status')
if status:
message = status.get('mess... | 0.002894 |
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
"""
Orographic Gage File Read from File Method
"""
# Set file extension property
self.fileExtension = extension
# Open file and parse into HmetRecords
... | 0.002 |
def _get_namespace2go2term(go2terms):
"""Group GO IDs by namespace."""
namespace2go2term = cx.defaultdict(dict)
for goid, goterm in go2terms.items():
namespace2go2term[goterm.namespace][goid] = goterm
return namespace2go2term | 0.007435 |
def do_upgrade(self):
"""Implement your upgrades here."""
sql = text('delete from upgrade where upgrade = :upgrade')
for upgrade in self.legacy_upgrades:
db.engine.execute(sql, upgrade=upgrade) | 0.008734 |
def get_angle(v1, v2, units="degrees"):
"""
Calculates the angle between two vectors.
Args:
v1: Vector 1
v2: Vector 2
units: "degrees" or "radians". Defaults to "degrees".
Returns:
Angle between them in degrees.
"""
d = np.dot(v1, v2) / np.linalg.norm(v1) / np.l... | 0.001733 |
def finite_diff(f, axis, dx=1.0, method='forward', out=None, **kwargs):
"""Calculate the partial derivative of ``f`` along a given ``axis``.
In the interior of the domain of f, the partial derivative is computed
using first-order accurate forward or backward difference or
second-order accurate central ... | 0.000084 |
def remove(self, msg, callback):
"""Remove a callback from the callback list.
msg: Message template
callback: Callback method to remove.
If callback is None, all callbacks for the message template are
removed.
"""
if callback is None:
self._dict.pop(... | 0.002628 |
def fuzzy_date_parser(self, text):
"""Thin wrapper around ``parsedatetime`` and ``dateutil`` modules.
Since there's no upstream suppport for multiple locales, this wrapper
exists.
:param str text: Text to parse.
:returns: A parsed date/time object. Raises exception on failure.
... | 0.002105 |
def add(self, child):
"""
Adds a typed child object to the component.
@param child: Child object to be added.
"""
if isinstance(child, Component):
self.add_child(child)
else:
raise ModelError('Unsupported child element') | 0.006803 |
def derive_identity_rmf(name, rmf):
"""Create an "identity" RMF that does not mix energies.
*name*
The name of the RMF object to be created; passed to Sherpa.
*rmf*
An existing RMF object on which to base this one.
Returns:
A new RMF1D object that has a response matrix that is as clos... | 0.002031 |
def best_unique_genomes(self, n):
"""Returns the most n fit genomes, with no duplication."""
best_unique = {}
for g in self.most_fit_genomes:
best_unique[g.key] = g
best_unique_list = list(best_unique.values())
def key(genome):
return genome.fitness
... | 0.005236 |
def tomof(self, maxline=MAX_MOF_LINE):
"""
Return a MOF string with the declaration of this CIM qualifier type.
The returned MOF string conforms to the ``qualifierDeclaration``
ABNF rule defined in :term:`DSP0004`.
Qualifier flavors are included in the returned MOF string only ... | 0.000735 |
def put(self, key, value, cache=None, options={}):
"""Query the server to set the key specified to the value specified in
the specified cache.
Keyword arguments:
key -- the name of the key to be set. Required.
value -- the value to set key to. Must be a string or JSON
... | 0.003858 |
def remove_diskgroup(cache_disk_id, data_accessibility=True,
service_instance=None):
'''
Remove the diskgroup with the specified cache disk.
cache_disk_id
The canonical name of the cache disk.
data_accessibility
Specifies whether to ensure data accessibility. Defau... | 0.001554 |
def receive(sources, timeout=None):
"""Get all outstanding signals from sources.
A source can be either (1) an object ID returned by the task (we want
to receive signals from), or (2) an actor handle.
When invoked by the same entity E (where E can be an actor, task or
driver), for each source S in... | 0.000256 |
def GetValueByPath(self, path_segments):
"""Retrieves a plist value by path.
Args:
path_segments (list[str]): path segment strings relative to the root
of the plist.
Returns:
object: The value of the key specified by the path or None.
"""
key = self.root_key
for path_segm... | 0.012363 |
def round(self, x):
"""Round the given value.
@param x: to round
@type x: numeric
"""
fraction, scaled_x, scale = self._get_fraction(x)
if fraction < self.minimum_stochastic_distance or 1-fraction <self.minimum_stochastic_distance:
result = round(x... | 0.010972 |
def delegate(attribute_name, method_names):
"""Pass the call to the attribute called attribute_name for every method listed in method_names."""
# hack for python 2.7 as nonlocal is not available
info = {
'attribute': attribute_name,
'methods': method_names
}
def decorator(cls):
... | 0.004267 |
def design(n, spacing, shift, fI, fC=False, r=None, r_def=(1, 1, 2), reim=None,
cvar='amp', error=0.01, name=None, full_output=False, finish=False,
save=True, path='filters', verb=2, plot=1):
r"""Digital linear filter (DLF) design
This routine can be used to design digital linear filters ... | 0.000124 |
def get_imports(self, volume=None, state=None, offset=None, limit=None):
"""
Fetches imports for this project.
:param volume: Optional volume identifier.
:param state: Optional state.
:param offset: Pagination offset.
:param limit: Pagination limit.
:return: Colle... | 0.004032 |
def _handle_commit_error(self, failure, retry_delay, attempt):
""" Retry the commit request, depending on failure type
Depending on the type of the failure, we retry the commit request
with the latest processed offset, or callback/errback self._commit_ds
"""
# Check if we are st... | 0.000956 |
def pendulum():
"""Configuration for the pendulum classic control task."""
locals().update(default())
# Environment
env = 'Pendulum-v0'
max_length = 200
steps = 1e6 # 1M
# Optimization
batch_size = 20
chunk_length = 50
return locals() | 0.043137 |
def relaxng(cls, includechildren=True,extraattribs = None, extraelements=None, origclass = None):
"""Returns a RelaxNG definition for this element (as an XML element (lxml.etree) rather than a string)"""
E = ElementMaker(namespace="http://relaxng.org/ns/structure/1.0",nsmap={None:'http://relaxng.org/ns/... | 0.027536 |
def load_external_data_for_model(model, base_dir): # type: (ModelProto, Text) -> None
"""
Loads external tensors into model
@params
model: ModelProto to load external data to
base_dir: directory that contains external data
"""
for tensor in _get_all_tensors(model):
if uses_external... | 0.005076 |
def make(cls, vol):
""" Convert uuid to Volume, if necessary. """
if isinstance(vol, cls):
return vol
elif vol is None:
return None
else:
return cls(vol, None) | 0.008811 |
def clean(self, value):
"""Cleans and returns the given value, or raises a ParameterNotValidError exception"""
if isinstance(value, numpy.ndarray):
return value
elif isinstance(value, (list, tuple)):
return numpy.array(value)
raise ParameterNotValidError | 0.009615 |
def change_logger_levels(logger=None, level=logging.DEBUG):
"""
Go through the logger and handlers and update their levels to the
one specified.
:param logger: logging name or object to modify, defaults to root logger
:param level: logging level to set at (10=Debug, 20=Info, 30=Warn, 40=Error)
... | 0.003945 |
def _convert_oauth2_credentials(credentials):
"""Converts to :class:`google.oauth2.credentials.Credentials`.
Args:
credentials (Union[oauth2client.client.OAuth2Credentials,
oauth2client.client.GoogleCredentials]): The credentials to
convert.
Returns:
google.oauth2.c... | 0.001284 |
def standardize_polygons_str(data_str):
"""Given a POLYGON string, standardize the coordinates to a 1x1 grid.
Input : data_str (taken from above)
Output: tuple of polygon objects
"""
# find all of the polygons in the letter (for instance an A
# needs to be constructed from 2 polygons)
path_s... | 0.005484 |
def run(self):
"""print .new configuration files
"""
self.find_new()
for n in self.news:
print("{0}".format(n))
print("")
self.msg.template(78)
print("| Installed {0} new configuration files:".format(
len(self.news)))
self.msg.templ... | 0.005714 |
def list_images(self):
"""
Return the list of available images for this node type
:returns: Array of hash
"""
try:
return list_images(self._NODE_TYPE)
except OSError as e:
raise aiohttp.web.HTTPConflict(text="Can not list images {}".format(e)) | 0.009464 |
def tile_x_size(self, zoom):
"""
Width of a tile in SRID units at zoom level.
- zoom: zoom level
"""
warnings.warn(DeprecationWarning("tile_x_size is deprecated"))
validate_zoom(zoom)
return round(self.x_size / self.matrix_width(zoom), ROUND) | 0.006689 |
def share(self, group_id, group_access, expires_at=None, **kwargs):
"""Share the project with a group.
Args:
group_id (int): ID of the group.
group_access (int): Access level for the group.
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
... | 0.002762 |
def check_ranges(cls, ranges, length):
"""Removes errored ranges"""
result = []
for start, end in ranges:
if isinstance(start, int) or isinstance(end, int):
if isinstance(start, int) and not (0 <= start < length):
continue
elif isin... | 0.010695 |
def plot_obsseries(self, **kwargs: Any) -> None:
"""Plot the |IOSequence.series| of the |Obs| sequence object.
See method |Node.plot_allseries| for further information.
"""
self.__plot_series([self.sequences.obs], kwargs) | 0.007874 |
def set_trace(host=None, port=None, patch_stdstreams=False):
"""
Opens a remote PDB on first available port.
"""
if host is None:
host = os.environ.get('REMOTE_PDB_HOST', '127.0.0.1')
if port is None:
port = int(os.environ.get('REMOTE_PDB_PORT', '0'))
rdb = RemotePdb(host=host, p... | 0.002427 |
def _populate_trie(self, values: List[str]) -> CharTrie:
"""Takes a list and inserts its elements into a new trie and returns it"""
if self._default_tokenizer:
return reduce(self._populate_trie_reducer, iter(values), CharTrie())
return reduce(self._populate_trie_reducer_regex, iter(v... | 0.014749 |
def pan_delta(self, dx_px, dy_px):
"""
This causes the scene to appear to translate right and up
(i.e., what really happens is the camera is translated left and down).
This is also called "panning" in some software packages.
Passing in negative delta values causes the opposite mo... | 0.002301 |
def irange(self, minimum=None, maximum=None, inclusive=(True, True),
reverse=False):
"""
Create an iterator of values between `minimum` and `maximum`.
`inclusive` is a pair of booleans that indicates whether the minimum
and maximum ought to be included in the range, respe... | 0.002997 |
def _draw(self, txt, final=False):
"""Print the rendered string to the stdout."""
if not self._file_mode:
# If the user presses Ctrl+C this ensures we still start writing from the beginning of the line
sys.stdout.write("\r")
sys.stdout.write(txt)
if final and not ... | 0.005825 |
def get_zone_info(cls, area_str, match_type='EXACT', result_type='LIST'):
"""
输入包含省份、城市、地区信息的内容,返回地区编号;
:param:
* area_str: (string) 要查询的区域,省份、城市、地区信息,比如 北京市
* match_type: (string) 查询匹配模式,默认值 'EXACT',表示精确匹配,可选 'FUZZY',表示模糊查询
* result_type: (string) 返回结果数量类型,默... | 0.003357 |
def check_for_partition(self, schema, table, partition):
"""
Checks whether a partition exists
:param schema: Name of hive schema (database) @table belongs to
:type schema: str
:param table: Name of hive table @partition belongs to
:type schema: str
:partition: E... | 0.002317 |
def str_2_obj(obj_str, tg_type=None):
"""Converts a string into an object according to the given tango type
:param obj_str: the string to be converted
:type obj_str: :py:obj:`str`
:param tg_type: tango type
:type tg_type: :class:`tango.CmdArgType`
:return: an ... | 0.001258 |
def get_package_counts(package_descriptors, targets, repos_data):
"""
Get the number of packages per target and repository.
:return: a dict indexed by targets containing
a list of integer values (one for each repo)
"""
counts = {}
for target in targets:
counts[target] = [0] * len(... | 0.001414 |
def _get_project(msg, key='project'):
''' Return the project as `foo` or `user/foo` if the project is a
fork.
'''
project = msg[key]['name']
ns = msg[key].get('namespace')
if ns:
project = '/'.join([ns, project])
if msg[key]['parent']:
user = msg[key]['user']['name']
... | 0.002618 |
def _extract_packages(self):
"""
Extract a package in a new directory.
"""
if not hasattr(self, "retrieved_packages_unpacked"):
self.retrieved_packages_unpacked = [self.package_name]
for path in self.retrieved_packages_unpacked:
package_name = basename(pat... | 0.002131 |
def v_magnitude(v):
"""
Simple vector helper function returning the length of a vector.
``v`` may be any vector, with any number of dimensions
"""
return math.sqrt(sum(v[i]*v[i] for i in range(len(v)))) | 0.008811 |
def get_breadcrumbs(url, request=None):
"""
Given a url returns a list of breadcrumbs, which are each a
tuple of (name, url).
"""
from wave.reverse import preserve_builtin_query_params
from wave.settings import api_settings
from wave.views import APIView
view_name_func = api_settings.VI... | 0.000984 |
def fetch_ticker(self) -> Ticker:
"""Fetch the market ticker."""
return self._fetch('ticker', self.market.code)(self._ticker)() | 0.013986 |
def get_hosting_device_driver(self, context, id):
"""Returns device driver for hosting device template with <id>."""
if id is None:
return
try:
return self._hosting_device_drivers[id]
except KeyError:
try:
template = self._get_hosting_d... | 0.002725 |
def list_records(self, file_const=None):
"""Iterate through the file records"""
for r in self._dataset.files:
if file_const and r.minor_type != file_const:
continue
yield self.instance_from_name(r.path) | 0.007752 |
async def release(data):
"""
Release a session
:param data: Information obtained from a POST request.
The content type is application/json.
The correct packet form should be as follows:
{
'token': UUID token from current session start
'command': 'release'
}
"""
global se... | 0.00161 |
def bottleneck_layer(inputs,
hparams,
name="discrete_bottleneck"):
"""Computes latents given inputs (typically, compressed targets)."""
[
latents_dense,
latents_discrete,
extra_loss,
embed_fn,
_,
] = hparams.bottleneck(inputs=inputs,
... | 0.00774 |
def from_hertz(self, hertz, standard_pitch=440):
"""Set the Note name and pitch, calculated from the hertz value.
The standard_pitch argument can be used to set the pitch of A-4,
from which the rest is calculated.
"""
value = ((log((float(hertz) * 1024) / standard_pitch, 2) +
... | 0.006098 |
def ShowWindow(handle: int, cmdShow: int) -> bool:
"""
ShowWindow from Win32.
handle: int, the handle of a native window.
cmdShow: int, a value in clas `SW`.
Return bool, True if succeed otherwise False.
"""
return ctypes.windll.user32.ShowWindow(ctypes.c_void_p(handle), cmdShow) | 0.003247 |
def PushAttributeContainer(self, serialized_data):
"""Pushes a serialized attribute container onto the list.
Args:
serialized_data (bytes): serialized attribute container data.
"""
self._list.append(serialized_data)
self.data_size += len(serialized_data)
self.next_sequence_number += 1 | 0.003165 |
def get_dataset(self, dataset):
"""
Checks to see if the dataset is present. If not, it downloads and unzips it.
"""
# If the dataset is present, no need to download anything.
success = True
dataset_path = self.base_dataset_path + dataset
if not isdir(dataset_path... | 0.004115 |
def unicode_is_ascii(u_string):
"""Determine if unicode string only contains ASCII characters.
:param str u_string: unicode string to check. Must be unicode
and not Python 2 `str`.
:rtype: bool
"""
assert isinstance(u_string, str)
try:
u_string.encode('ascii')
return Tru... | 0.002681 |
def get_extra_path(name):
"""
:param name: name in format helper.path_name
sip.default_sip_dir
"""
# Paths are cached in path_cache
helper_name, _, key = name.partition(".")
helper = path_helpers.get(helper_name)
if not helper:
raise ValueError("Helper '{0}' not found.".format(h... | 0.003263 |
def run_once(self):
'''comsume queues and feed tasks to fetcher, once'''
self._update_projects()
self._check_task_done()
self._check_request()
while self._check_cronjob():
pass
self._check_select()
self._check_delete()
self._try_dump_cnt() | 0.006329 |
def create_volume(DryRun=None, Size=None, SnapshotId=None, AvailabilityZone=None, VolumeType=None, Iops=None, Encrypted=None, KmsKeyId=None, TagSpecifications=None):
"""
Creates an EBS volume that can be attached to an instance in the same Availability Zone. The volume is created in the regional endpoint that y... | 0.005098 |
def check_args(args):
"""Checks the arguments and options."""
# Checking that only VCF can have a - (stdout) as output
if args.output_format not in _streamable_format and args.output == "-":
logger.error("{} format cannot be streamed to standard output"
"".format(args.output_for... | 0.001553 |
def get_release_definitions(self, project, search_text=None, expand=None, artifact_type=None, artifact_source_id=None, top=None, continuation_token=None, query_order=None, path=None, is_exact_name_match=None, tag_filter=None, property_filters=None, definition_id_filter=None, is_deleted=None, search_text_contains_folder... | 0.005495 |
def get_parent_dir(name):
"""Get the parent directory of a filename."""
parent_dir = os.path.dirname(os.path.dirname(name))
if parent_dir:
return parent_dir
return os.path.abspath('.') | 0.004808 |
def finditem(self, item, threshold=None):
"""Return most similar item to the provided one, or None if
nothing exceeds the threshold.
>>> from ngram import NGram
>>> n = NGram([(0, "Spam"), (1, "Ham"), (2, "Eggsy"), (3, "Egggsy")],
... key=lambda x:x[1].lower())
>>> n... | 0.003257 |
def failed(self, reason=None):
"""失败订单(未成功创建入broker)
Arguments:
reason {str} -- 失败原因
"""
# 订单创建失败(如废单/场外废单/价格高于涨停价/价格低于跌停价/通讯失败)
self._status = ORDER_STATUS.FAILED
self.reason = str(reason) | 0.008 |
def handle_delete_user(self, req):
"""Handles the DELETE v2/<account>/<user> call for deleting a user from an
account.
Can only be called by an account .admin.
:param req: The swob.Request to process.
:returns: swob.Response, 2xx on success.
"""
# Validate path ... | 0.001505 |
def class_get_trait_help(cls, trait, inst=None):
"""Get the help string for a single trait.
If `inst` is given, it's current trait values will be used in place of
the class default.
"""
assert inst is None or isinstance(inst, cls)
lines = []
header = "--%... | 0.004102 |
def _minutes_to_exclude(self):
"""
Calculate the minutes which should be excluded when a window
occurs on days which had an early close, i.e. days where the close
based on the regular period of minutes per day and the market close
do not match.
Returns
-------
... | 0.001942 |
def error(self):
"""Returns the error for this barrier and all work items, if any."""
# Copy the error from any failed item to be the error for the whole
# barrier. The first error seen "wins". Also handles the case where
# the WorkItems passed into the barrier have already completed and... | 0.004057 |
def set_subservice(self, obj):
"""Add a sub-service object.
:param obj: stackinabox.services.StackInABoxService instance
:raises: RouteAlreadyRegisteredError if the route is already registered
:returns: n/a
"""
# ensure there is not already a sub-service
if self.... | 0.001771 |
def angle(array_of_xyzs):
"""
Calculates angle between three coordinate points (I could not find a package
that does this but if one exists that would probably be better). Used for Angle constraints.
"""
ab = array_of_xyzs[0] - array_of_xyzs[1]
cb = array_of_xyzs[2] - array_of_xyzs[1]
retur... | 0.01573 |
def key(self, att=None):
"""Returns the Redis key where the values are stored."""
if att is not None:
return self._key[self.id][att]
else:
return self._key[self.id] | 0.009434 |
def flip_strand(self):
"""Flips the strand of the alleles."""
self.reference = complement_alleles(self.reference)
self.coded = complement_alleles(self.coded)
self.variant.complement_alleles() | 0.008969 |
def _atexit__register(self, func, *targs, **kwargs):
"""
Intercept :func:`atexit.register` calls, diverting any to
:func:`shutil.rmtree` into a private list.
"""
if func == shutil.rmtree:
self.deferred.append((func, targs, kwargs))
return
self.ori... | 0.00554 |
def do_escape_nl(self, arg):
"""
Escape newlines in any responses
"""
if arg.lower() == 'off':
self.escape_nl = False
else:
self.escape_nl = True | 0.009569 |
def load(cls, query_name):
"""Load a pre-made query.
These queries are distributed with lsstprojectmeta. See
:file:`lsstrojectmeta/data/githubv4/README.rst` inside the
package repository for details on available queries.
Parameters
----------
query_name : `str`
... | 0.002336 |
def call_hook(message,
attachment=None,
color='good',
short=False,
identifier=None,
channel=None,
username=None,
icon_emoji=None):
'''
Send message to Slack incoming webhook.
:param message: The topic of m... | 0.000431 |
def _do_scale(image, size):
"""Rescale the image by scaling the smaller spatial dimension to `size`."""
shape = tf.cast(tf.shape(image), tf.float32)
w_greater = tf.greater(shape[0], shape[1])
shape = tf.cond(w_greater,
lambda: tf.cast([shape[0] / shape[1] * size, size], tf.int32),
... | 0.018141 |
def as_field_error(node, secid):
""" convert a fieldExceptions element to a FieldError or FieldError array """
assert node.Name == 'fieldExceptions'
if node.IsArray:
return [XmlHelper.as_field_error(node.GetValue(_), secid) for _ in range(node.NumValues)]
else:
fl... | 0.005675 |
def plot_predict(self, h=5, past_values=20, intervals=True, **kwargs):
""" Makes forecast with the estimated model
Parameters
----------
h : int (default : 5)
How many steps ahead would you like to forecast?
past_values : int (default : 20)
How man... | 0.009057 |
def convert(self, blob, size=500):
"""Size is the maximum horizontal size."""
file_list = []
with make_temp_file(blob) as in_fn, make_temp_file() as out_fn:
try:
subprocess.check_call(["pdftoppm", "-jpeg", in_fn, out_fn])
file_list = sorted(glob.glob(f... | 0.002301 |
def walk_nodes(self, node, original):
"""
Iterate over the nodes recursively yielding the templatetag 'sass_src'
"""
try:
# try with django-compressor<2.1
nodelist = self.parser.get_nodelist(node, original=original)
except TypeError:
nodelist =... | 0.004666 |
def _kafka_success(self, item, spider, response):
'''
Callback for successful send
'''
item['success'] = True
item = self._clean_item(item)
item['spiderid'] = spider.name
self.logger.info("Sent page to Kafka", item) | 0.00738 |
def as_coeff_unit(self):
"""Factor the coefficient multiplying a unit
For units that are multiplied by a constant dimensionless
coefficient, returns a tuple containing the coefficient and
a new unit object for the unmultiplied unit.
Example
-------
>>> import u... | 0.00271 |
def subsystem(s):
"""Validate a |Subsystem|.
Checks its state and cut.
"""
node_states(s.state)
cut(s.cut, s.cut_indices)
if config.VALIDATE_SUBSYSTEM_STATES:
state_reachable(s)
return True | 0.004425 |
def getBitmap(self):
""" Captures screen area of this region, at least the part that is on the screen
Returns image as numpy array
"""
return PlatformManager.getBitmapFromRect(self.x, self.y, self.w, self.h) | 0.016667 |
def get_missing_required_annotations(self) -> List[str]:
"""Return missing required annotations."""
return [
required_annotation
for required_annotation in self.required_annotations
if required_annotation not in self.annotations
] | 0.006897 |
def new_result(self, job):
"""
function to register finished runs
Every time a run has finished, this function should be called
to register it with the result logger. If overwritten, make
sure to call this method from the base class to ensure proper
logging.
Parameters:
-----------
job_id: ... | 0.032918 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.