text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def havespace(self, scriptname, scriptsize):
"""Ask for available space.
See MANAGESIEVE specifications, section 2.5
:param scriptname: script's name
:param scriptsize: script's size
:rtype: boolean
"""
code, data = self.__send_command(
"HAVESPACE", ... | 0.00464 |
def report(self, morfs, outfile=None):
"""Generate a Cobertura-compatible XML report for `morfs`.
`morfs` is a list of modules or filenames.
`outfile` is a file object to write the XML to.
"""
# Initial setup.
outfile = outfile or sys.stdout
# Create the DOM t... | 0.000759 |
def _get(self, url, params=None):
"""Used by every other method, it makes a GET request with the given params.
Args:
url (str): relative path of a specific service (account_info, ...).
params (:obj:`dict`, optional): contains parameters to be sent in the GET request.
Re... | 0.00627 |
def get_item_hrefs(result_collection):
"""
Given a result_collection (returned by a previous API call that
returns a collection, like get_bundle_list() or search()), return a
list of item hrefs.
'result_collection' a JSON object returned by a previous API
call.
Returns a list, which may be... | 0.001466 |
def _GetCompressedStreamTypes(self, mediator, path_spec):
"""Determines if a data stream contains a compressed stream such as: gzip.
Args:
mediator (ParserMediator): mediates the interactions between
parsers and other components, such as storage and abort signals.
path_spec (dfvfs.PathSpe... | 0.005285 |
def parse_sidebar(self, media_page):
"""Parses the DOM and returns media attributes in the sidebar.
:type media_page: :class:`bs4.BeautifulSoup`
:param media_page: MAL media page's DOM
:rtype: dict
:return: media attributes.
:raises: InvalidMediaError, MalformedMediaPageError
"""
med... | 0.016507 |
def set_mag_offsets_send(self, target_system, target_component, mag_ofs_x, mag_ofs_y, mag_ofs_z, force_mavlink1=False):
'''
Deprecated. Use MAV_CMD_PREFLIGHT_SET_SENSOR_OFFSETS instead. Set the
magnetometer offsets
target_system : System ID (u... | 0.006234 |
def index_exists(self):
"""Check to see if index exists."""
headers = {'Content-Type': 'application/json', 'DB-Method': 'GET'}
url = '/v2/exchange/db/{}/{}/_search'.format(self.domain, self.data_type)
r = self.tcex.session.post(url, headers=headers)
if not r.ok:
self.... | 0.009132 |
def make_slash_number(self):
"""
Charset lines have \2 or \3 depending on type of partitioning and codon
positions requested for our dataset.
:return:
"""
if self.partitioning == 'by codon position' and self.codon_positions == '1st-2nd':
return '\\2'
... | 0.008214 |
def download(self,
files=None,
formats=None,
glob_pattern=None,
dry_run=None,
verbose=None,
silent=None,
ignore_existing=None,
checksum=None,
destdir=None,
... | 0.004313 |
def namedb_get_account_history(cur, address, offset=None, count=None):
"""
Get the history of an account's tokens
"""
sql = 'SELECT * FROM accounts WHERE address = ? ORDER BY block_id DESC, vtxindex DESC'
args = (address,)
if count is not None:
sql += ' LIMIT ?'
args += (count,)... | 0.003396 |
def crossJoin(self, other):
"""Returns the cartesian product with another :class:`DataFrame`.
:param other: Right side of the cartesian product.
>>> df.select("age", "name").collect()
[Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')]
>>> df2.select("name", "height").collect(... | 0.006702 |
def bank_account_query(self, number, date, account_type, bank_id):
"""Bank account statement request"""
return self.authenticated_query(
self._bareq(number, date, account_type, bank_id)
) | 0.008969 |
def analyze_beam_spot(scan_base, combine_n_readouts=1000, chunk_size=10000000, plot_occupancy_hists=False, output_pdf=None, output_file=None):
''' Determines the mean x and y beam spot position as a function of time. Therefore the data of a fixed number of read outs are combined ('combine_n_readouts'). The occupanc... | 0.004399 |
def create_session(docker_image=None,
docker_rm=None,
echo=False,
loglevel='WARNING',
nocolor=False,
session_type='bash',
vagrant_session_name=None,
vagrant_image='ubuntu/xenial64',
... | 0.024151 |
def get_room_member_profile(self, room_id, user_id, timeout=None):
"""Call get room member profile API.
https://devdocs.line.me/en/#get-group-room-member-profile
Gets the user profile of a member of a room that
the bot is in. This can be the user ID of a user who has
not added ... | 0.002863 |
def get_property_names(self, is_allprop):
"""Return list of supported property names in Clark Notation.
Note that 'allprop', despite its name, which remains for
backward-compatibility, does not return every property, but only dead
properties and the live properties defined in RFC4918.
... | 0.001 |
def calculate_bbh(blast_results_1, blast_results_2, r_name=None, g_name=None, outdir=''):
"""Calculate the best bidirectional BLAST hits (BBH) and save a dataframe of results.
Args:
blast_results_1 (str): BLAST results for reference vs. other genome
blast_results_2 (str): BLAST results for othe... | 0.003465 |
def fetch_by_client_id(self, client_id):
"""
Retrieve a client by its identifier.
:param client_id: Identifier of a client app.
:return: An instance of :class:`oauth2.Client`.
:raises: ClientNotFoundError
"""
if client_id not in self.clients:
raise C... | 0.005291 |
def hgetall(self, name):
"""
Returns all the fields and values in the Hash.
:param name: str the name of the redis key
:return: Future()
"""
with self.pipe as pipe:
f = Future()
res = pipe.hgetall(self.redis_key(name))
def cb():
... | 0.00295 |
def _parse_seq_body(line):
"""
Ex:
{()YVPFARKYRPKFFREVIGQEAPVRILKALNcknpskgepcgereiDRGVFPDVRA-LKLLDQASVYGE()}*
MENINNI{()----------FKLILVGDGKFFSSSGEIIFNIWDTKFGGLRDGYYRLTYKNEDDM()}*
Or:
{(HY)ELPWVEKYR...
The sequence fragments in parentheses represent N- or C-terminal flanking
regions... | 0.002317 |
def pick_and_display_buffer(self, i):
"""
pick i-th buffer from list and display it
:param i: int
:return: None
"""
if len(self.buffers) == 1:
# we don't need to display anything
# listing is already displayed
return
else:
... | 0.00404 |
def transform(odtfile, debug=False, parsable=False, outputdir=None):
""" Given an ODT file this returns a tuple containing
the cnxml, a dictionary of filename -> data, and a list of errors """
# Store mapping of images extracted from the ODT file (and their bits)
images = {}
# Log of Errors and ... | 0.008795 |
def create_request_with_query(self, kind, query, size="thumb", fmt="json"):
"""api/data.[fmt], api/images/[size].[fmt] api/files.[fmt]
kind = ['data', 'images', 'files']
"""
if kind == "data" or kind == "files":
url = "{}/{}.{}".format(base_url, kind, fmt)
elif kin... | 0.004082 |
def join (self, timeout=None):
"""Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all... | 0.003024 |
def SRU_Compute_CPU(activation_type, d, bidirectional=False, scale_x=1):
"""CPU version of the core SRU computation.
Has the same interface as SRU_Compute_GPU() but is a regular Python function
instead of a torch.autograd.Function because we don't implement backward()
explicitly.
"""
def sru_c... | 0.002671 |
def _log(self, message, stream, color=None, newline=False):
'''
Logs the message to the sys.stdout or sys.stderr stream.
When color is defined and the TERM environemnt variable contains the
string "color", then the output will be colored.
'''
if color and self.color_ter... | 0.003096 |
def CO_ratio(self,ifig,ixaxis):
"""
plot surface C/O ratio in Figure ifig with x-axis quantity ixaxis
Parameters
----------
ifig : integer
Figure number in which to plot
ixaxis : string
what quantity is to be on the x-axis, either 'time' or 'model... | 0.015513 |
def send_msg_async(self, *, message_type, user_id=None, group_id=None, discuss_id=None, message, auto_escape=False):
"""
发送消息 (异步版本)
------------
:param str message_type: 消息类型,支持 `private`、`group`、`discuss`,分别对应私聊、群组、讨论组
:param int user_id: 对方 QQ 号(消息类型为 `private` 时需要)
... | 0.007084 |
def get_datetime(self, timestamp: str, unix=True):
"""Converts a %Y%m%dT%H%M%S.%fZ to a UNIX timestamp
or a datetime.datetime object
Parameters
---------
timestamp: str
A timstamp in the %Y%m%dT%H%M%S.%fZ format, usually returned by the API
in the ``creat... | 0.005698 |
def search(self, keyword, children=None, arg=None):
"""Return list of receiver's substmts with `keyword`.
"""
if children is None:
children = self.substmts
return [ ch for ch in children
if (ch.keyword == keyword and
(arg is None or ch.ar... | 0.009063 |
def create_from_item(self, languages, item, fields, trans_instance=None):
"""
Creates tasks from a model instance "item" (master)
Used in the api call
:param languages:
:param item:
:param fields:
:param trans_instance: determines if we are in bulk mode or not.
... | 0.00227 |
def result(filetype="PNG",saveas=None, host=cytoscape_host,port=cytoscape_port):
"""
Checks the current network.
Note: works only on localhost
:param filetype: file type, default="PNG"
:param saveas: /path/to/non/tmp/file.prefix
:param host: cytoscape host address, default=cytoscape_h... | 0.030172 |
def _slug_strip(self, value):
"""
Clean up a slug by removing slug separator characters that occur at
the beginning or end of a slug.
If an alternate separator is used, it will also replace any instances
of the default '-' separator with the new separator.
"""
re... | 0.004057 |
def ensure_data_exists(self, request, data, error_message=None):
"""
Ensure that the wrapped API client's response brings us valid data. If not, raise an error and log it.
"""
if not data:
error_message = (
error_message or "Unable to fetch API response from e... | 0.008658 |
def add_data_to_df(self, data: np.array):
"""Build Pandas Dataframe in memory"""
col_names = ['high_p', 'low_p', 'open_p', 'close_p', 'volume', 'oi']
data = np.array(data).reshape(-1, len(col_names) + 1)
df = pd.DataFrame(data=data[:, 1:], index=data[:, 0],
co... | 0.00235 |
def FDMT_params(f_min, f_max, maxDT, inttime):
"""
Summarize DM grid and other parameters.
"""
maxDM = inttime*maxDT/(4.1488e-3 * (1/f_min**2 - 1/f_max**2))
logger.info('Freqs from {0}-{1}, MaxDT {2}, Int time {3} => maxDM {4}'.format(f_min, f_max, maxDT, inttime, maxDM)) | 0.006826 |
def parse_args():
"""Parse arguments."""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description='Diagnose script for checking the current system.')
choices = ['python', 'pip', 'mxnet', 'os', 'hardware', 'network']
for choice in choices:
... | 0.003542 |
def create(args):
"""Create records.
Argument:
args: arguments object
"""
# for PUT HTTP method
action = True
if ((args.__dict__.get('domain') and args.__dict__.get('name')
and args.__dict__.get('rtype') and args.__dict__.get('content'))):
# for create sub-command
... | 0.000936 |
def clear_descendants(self, source, clear_source=True):
"""Clear values and nodes calculated from `source`."""
removed = self.cellgraph.clear_descendants(source, clear_source)
for node in removed:
del node[OBJ].data[node[KEY]] | 0.007634 |
def tuplify(*args):
"""
Convert args to a tuple, unless there's one arg and it's a
function, then acts a decorator.
"""
if (len(args) == 1) and callable(args[0]):
func = args[0]
@wraps(func)
def _inner(*args, **kwargs):
return tuple(func(*args, **kwargs))
... | 0.002695 |
def to_pascal(arr, is_dp=False):
"""Force data with units either hPa or Pa to be in Pa."""
threshold = 400 if is_dp else 1200
if np.max(np.abs(arr)) < threshold:
warn_msg = "Conversion applied: hPa -> Pa to array: {}".format(arr)
logging.debug(warn_msg)
return arr*100.
return arr | 0.003125 |
def _match_cubes(ccube_clean, ccube_dirty,
bexpcube_clean, bexpcube_dirty,
hpx_order):
""" Match the HEALPIX scheme and order of all the input cubes
return a dictionary of cubes with the same HEALPIX scheme and order
"""
if hpx_order == ccube_cl... | 0.00443 |
def op_get_consensus_fields( op_name ):
"""
Get the set of consensus-generating fields for an operation.
"""
global SERIALIZE_FIELDS
if op_name not in SERIALIZE_FIELDS.keys():
raise Exception("No such operation '%s'" % op_name )
fields = SERIALIZE_FIELDS[op_name][:]
return fiel... | 0.015528 |
def carmichael() -> Iterator[int]:
"""Composite numbers n such that a^(n-1) == 1 (mod n) for every a coprime
to n.
https://oeis.org/A002997
"""
for m in composite():
for a in range(2, m):
if pow(a, m, m) != a:
break
else:
yield m | 0.003279 |
async def unformat(self):
"""Unformat this block device."""
self._data = await self._handler.unformat(
system_id=self.node.system_id, id=self.id) | 0.011561 |
def apply_uncertainty(self, value, source):
"""
Apply this branchset's uncertainty with value ``value`` to source
``source``, if it passes :meth:`filters <filter_source>`.
This method is not called for uncertainties of types "gmpeModel"
and "sourceModel".
:param value:
... | 0.001807 |
def parse_value(value, allowed_types, name='value'):
"""Parse a value into one of a number of types.
This function is used to coerce untyped HTTP parameter strings into an
appropriate type. It tries to coerce the value into each of the allowed
types, and uses the first that evaluates properly.
Bec... | 0.000363 |
def playMovie(self):
"""Play button handler."""
if self.state == self.READY:
# Create a new thread to listen for RTP packets
print "Playing Movie"
threading.Thread(target=self.listenRtp).start()
self.playEvent = threading.Event()
self.playEvent.clear()
self.sendRtspRequest(se... | 0.021341 |
def get_doc(logger=None, plugin=None, reporthook=None):
"""
Return URL to documentation. Attempt download if does not exist.
Parameters
----------
logger : obj or `None`
Ginga logger.
plugin : obj or `None`
Plugin object. If given, URL points to plugin doc directly.
If ... | 0.000565 |
def get_package(self):
"""Get the URL or sandbox to release.
"""
directory = self.directory
develop = self.develop
scmtype = self.scmtype
self.scm = self.scms.get_scm(scmtype, directory)
if self.scm.is_valid_url(directory):
directory = self.urlparser... | 0.004246 |
def can_approve(self, user, **data):
"""
Only org admins can approve joining an organisation
:param user: a User
:param data: data that the user wants to update
"""
is_org_admin = user.is_org_admin(self.organisation_id)
is_reseller_preverifying = user.is_reseller... | 0.007109 |
def format_h4(s, format="text", indents=0):
"""
Encloses string in format text
Args, Returns: see format_h1()
"""
_CHAR = "^"
if format.startswith("text"):
return format_underline(s, _CHAR, indents)
elif format.startswith("markdown"):
return ["#### {}".format(s)]... | 0.002481 |
def make_row_dict(row):
"""
Takes in a DataFrame row (Series),
and return a dictionary with the row's index as key,
and the row's values as values.
{col1_name: col1_value, col2_name: col2_value}
"""
ind = row[row.notnull()].index
values = row[row.notnull()].values
# to transformation... | 0.002564 |
def parse_requirements(fname='requirements.txt'):
"""
Parse the package dependencies listed in a requirements file but strips
specific versioning information.
TODO:
perhaps use https://github.com/davidfischer/requirements-parser instead
CommandLine:
python -c "import setup; print(s... | 0.000441 |
def get_single_hdd_only_candidate_model(
data,
minimum_non_zero_hdd,
minimum_total_hdd,
beta_hdd_maximum_p_value,
weights_col,
balance_point,
):
""" Return a single candidate hdd-only model for a particular balance
point.
Parameters
----------
data : :any:`pandas.DataFrame`
... | 0.000564 |
def turn_to_angle(self, speed, angle_target_degrees, brake=True, block=True):
"""
Rotate in place to `angle_target_degrees` at `speed`
"""
assert self.odometry_thread_id, "odometry_start() must be called to track robot coordinates"
# Make both target and current angles positive ... | 0.004778 |
def check_trigger(self, date_tuple, utc_offset=0):
"""
Returns boolean indicating if the trigger is active at the given time.
The date tuple should be in the local time. Unless periodicities are
used, utc_offset does not need to be specified. If periodicities are
used, specifical... | 0.000409 |
def validate_version(err, value, source):
'Tests a manifest version number'
field_name = '<em:version>' if source == 'install.rdf' else 'version'
err.metadata['version'] = value
# May not be longer than 32 characters
if len(value) > 32:
err.error(
('metadata_helpers', '_test_... | 0.001873 |
def address(self, street, city=None, state=None, zipcode=None, **kwargs):
'''Geocode an address.'''
fields = {
'street': street,
'city': city,
'state': state,
'zip': zipcode,
}
return self._fetch('address', fields, **kwargs) | 0.006557 |
def dvc_walk(
top,
topdown=True,
onerror=None,
followlinks=False,
ignore_file_handler=None,
):
"""
Proxy for `os.walk` directory tree generator.
Utilizes DvcIgnoreFilter functionality.
"""
ignore_filter = None
if topdown:
from dvc.ignore import DvcIgnoreFilter
... | 0.001508 |
def _find_observable_paths(extra_files=None):
"""Finds all paths that should be observed."""
rv = set(
os.path.dirname(os.path.abspath(x)) if os.path.isfile(x) else os.path.abspath(x)
for x in sys.path
)
for filename in extra_files or ():
rv.add(os.path.dirname(os.path.abspath(f... | 0.003497 |
def CmdVersion(self):
"""Obtain the version of the device and test transport format.
Obtains the version of the device and determines whether to use ISO
7816-4 or the U2f variant. This function should be called at least once
before CmdAuthenticate or CmdRegister to make sure the object is using the
... | 0.002976 |
def priority(self,priority):
"""Set the priority for all threads in this group.
If setting priority fails on any thread, the priority of all threads
is restored to its previous value.
"""
with self.__lock:
old_priorities = {}
try:
for thre... | 0.005115 |
def parse_keys_and_ranges(i_str, keyfunc, rangefunc):
'''Parse the :class:`from_kvlayer` input string.
This accepts two formats. In the textual format, it accepts any
number of stream IDs in timestamp-docid format, separated by ``,``
or ``;``, and processes those as individual stream IDs. In the
... | 0.000519 |
def send_http_request_with_body_parameters(context, method):
"""
Parameters:
+-------------+--------------+
| param_name | param_value |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |
... | 0.002004 |
def _group_by(data, criteria):
"""
Group objects in data using a function or a key
"""
if isinstance(criteria, str):
criteria_str = criteria
def criteria(x):
return x[criteria_str]
res = defaultdict(list)
for element in data:
key = criteria(element)
... | 0.002755 |
def remove_child_catalog(self, catalog_id, child_id):
"""Removes a child from a catalog.
arg: catalog_id (osid.id.Id): the ``Id`` of a catalog
arg: child_id (osid.id.Id): the ``Id`` of the new child
raise: NotFound - ``catalog_id`` is not a parent of
``child_id``
... | 0.004124 |
def annotate_metadata_action(repo):
"""
Update metadata with the action history
"""
package = repo.package
print("Including history of actions")
with cd(repo.rootdir):
filename = ".dgit/log.json"
if os.path.exists(filename):
history = open(... | 0.019337 |
def saveAsTextFiles(self, prefix, suffix=None):
"""
Save each RDD in this DStream as at text file, using string
representation of elements.
"""
def saveAsTextFile(t, rdd):
path = rddToFileName(prefix, suffix, t)
try:
rdd.saveAsTextFile(path... | 0.003317 |
def kill(self, dwExitCode = 0):
"""
Terminates the execution of the process.
@raise WindowsError: On error an exception is raised.
"""
hProcess = self.get_handle(win32.PROCESS_TERMINATE)
win32.TerminateProcess(hProcess, dwExitCode) | 0.014286 |
def get_file_results(self):
"""Print the result and return the overall count for this file."""
self._deferred_print.sort()
for line_number, offset, code, text, doc in self._deferred_print:
print(self._fmt % {
'path': self.filename,
'row': self.line_off... | 0.001676 |
def on_item_changed(self, item, new_value, row, column):
"""Event for the item change.
Args:
emitter (TableWidget): The emitter of the event.
item (TableItem): The TableItem instance.
new_value (str): New text content.
row (int): row index.
co... | 0.004963 |
def _process_mgi_note_vocevidence_view(self, limit):
"""
Here we fetch the free text descriptions of the phenotype associations.
Triples:
<annot_id> dc:description "description text"
:param limit:
:return:
"""
line_counter = 0
if self.test_mode:
... | 0.001914 |
def check_log_stream_exists(awsclient, log_group_name, log_stream_name):
"""Check
:param log_group_name: log group name
:param log_stream_name: log stream name
:return: True / False
"""
lg = describe_log_group(awsclient, log_group_name)
if lg and lg['logGroupName'] == log_group_name:
... | 0.003992 |
def xyY_to_XYZ(cobj, *args, **kwargs):
"""
Convert from xyY to XYZ.
"""
# avoid division by zero
if cobj.xyy_y == 0.0:
xyz_x = 0.0
xyz_y = 0.0
xyz_z = 0.0
else:
xyz_x = (cobj.xyy_x * cobj.xyy_Y) / cobj.xyy_y
xyz_y = cobj.xyy_Y
xyz_z = ((1.0 - cobj.... | 0.00431 |
def get_fresh(self, columns=None):
"""
Execute the query as a fresh "select" statement
:param columns: The columns to get
:type columns: list
:return: The result
:rtype: list
"""
if not columns:
columns = ['*']
if not self.columns:
... | 0.004695 |
def construct_blastn_cmdline(
fname1, fname2, outdir, blastn_exe=pyani_config.BLASTN_DEFAULT
):
"""Returns a single blastn command.
- filename - input filename
- blastn_exe - path to BLASTN executable
"""
fstem1 = os.path.splitext(os.path.split(fname1)[-1])[0]
fstem2 = os.path.splitext(os.p... | 0.001218 |
def script(self, sql_script, split_algo='sql_split', prep_statements=True, dump_fails=True):
"""Wrapper method providing access to the SQLScript class's methods and properties."""
return Execute(sql_script, split_algo, prep_statements, dump_fails, self) | 0.018587 |
def _open_config_files(self, command_line_args):
"""Tries to parse config file path(s) from within command_line_args.
Returns a list of opened config files, including files specified on the
commandline as well as any default_config_files specified in the
constructor that are present on d... | 0.001718 |
def lineReceived(self, line):
"""
A line was received.
"""
if line.startswith(b"#"): # ignore it
return
if line.startswith(b"OK"):
# if no command issued, then just 'ready'
if self._ready:
self._dq.pop(0).callback(self._currentR... | 0.004243 |
def _make_serverproxy_handler(name, command, environment, timeout, absolute_url, port):
"""
Create a SuperviseAndProxyHandler subclass with given parameters
"""
# FIXME: Set 'name' properly
class _Proxy(SuperviseAndProxyHandler):
def __init__(self, *args, **kwargs):
super().__ini... | 0.002833 |
def to_seconds(string):
"""
Converts a human readable time string into seconds.
Accepts:
- 's': seconds
- 'm': minutes
- 'h': hours
- 'd': days
Examples:
>>> to_seconds('1m30s')
90
>>> to_seconds('5m')
300
>>> to_seconds('1h')
3600
>>> to_seconds('1h30m')
... | 0.00221 |
def _ConvertHeaderToId(header):
"""Convert a Content-ID header value to an id.
Presumes the Content-ID header conforms to the format that
_ConvertIdToHeader() returns.
Args:
header: A string indicating the Content-ID header value.
Returns:
The extracted id ... | 0.002436 |
def p_constant_declaration(p):
'constant_declaration : STRING EQUALS static_scalar'
p[0] = ast.ConstantDeclaration(p[1], p[3], lineno=p.lineno(1)) | 0.006494 |
def run_in_pod(self, namespace="default"):
"""
run image inside Kubernetes Pod
:param namespace: str, name of namespace where pod will be created
:return: Pod instance
"""
core_api = get_core_api()
image_data = self.get_metadata()
pod = Pod.create(image... | 0.006002 |
def relative_path(sub_directory='', function_index=1):
"""
This will return the file relative to this python script
:param subd_irectory: str of the relative path
:param function_index: int of the number of function calls to go back
:return: str of the full path
"""
frm = ... | 0.002706 |
def threadsafe_call(self, fn, *args, **kwargs):
"""Wrapper around `AsyncSession.threadsafe_call`."""
def handler():
try:
fn(*args, **kwargs)
except Exception:
warn("error caught while excecuting async callback\n%s\n",
format_ex... | 0.004098 |
def get_unpacked_response_body(self, requestId, mimetype="application/unknown"):
'''
Return a unpacked, decoded resposne body from Network_getResponseBody()
'''
content = self.Network_getResponseBody(requestId)
assert 'result' in content
result = content['result']
assert 'base64Encoded' in result
asse... | 0.034003 |
def send(tag, data=None):
'''
Send an event with the given tag and data.
This is useful for sending events directly to the master from the shell
with salt-run. It is also quite useful for sending events in orchestration
states where the ``fire_event`` requisite isn't sufficient because it does
... | 0.000497 |
def cancel(self, job_ids):
''' Cancels the jobs specified by a list of job ids
Args:
job_ids : [<job_id> ...]
Returns :
[True/False...] : If the cancel operation fails the entire list will be False.
'''
job_id_list = ' '.join(job_ids)
retcode, stdout, s... | 0.00731 |
def total_memory(self, image='ubuntu'):
'''Get the available ram fo the docker machine in Kb'''
try:
ret = subprocess.check_output(
f'''docker run -t {image} cat /proc/meminfo | grep MemTotal''',
shell=True,
stdin=subprocess.DEVNULL)
... | 0.005535 |
def init_module(remote_credences=None,local_path=None):
"""Connnexion informations : remote_credences for remote acces OR local_path for local access"""
if remote_credences is not None:
RemoteConnexion.HOST = remote_credences["DB"]["host"]
RemoteConnexion.USER = remote_credences["DB"]["user"]
... | 0.004859 |
def save_model(self, request, obj, form, change):
"""
sends the email and does not save it
"""
email = message.EmailMessage(
subject=obj.subject,
body=obj.body,
from_email=obj.from_email,
to=[t.strip() for t in obj.to_emails.split(',')],
... | 0.004228 |
def create_embedded_class(self, method):
"""
Build the estimator class.
Returns
-------
:return : string
The built class as string.
"""
temp_class = self.temp('embedded.class')
return temp_class.format(class_name=self.class_name,
... | 0.004494 |
def _get_zeropoint(expnum, ccd, prefix=None, version='p'):
"""
Retrieve the zeropoint stored in the tags associated with this image.
@param expnum: Exposure number
@param ccd: ccd of the exposure
@param prefix: possible prefix (such as 'fk')
@param version: which version: p, s, or o ?
@retur... | 0.00354 |
def safe_call(self, kwargs, args=None):
"""
Call the underlying function safely, given a set of keyword
arguments. If successful, the function return value (likely
None) will be returned. If the underlying function raises an
exception, the return value will be the exception mes... | 0.001812 |
def get_device_info(self, bigip):
'''Get device information about a specific BigIP device.
:param bigip: bigip object --- device to inspect
:returns: bigip object
'''
coll = bigip.tm.cm.devices.get_collection()
device = [device for device in coll if device.selfDevice ==... | 0.005195 |
def _getTransformation(self):
"""_getTransformation(self) -> PyObject *"""
CheckParent(self)
val = _fitz.Page__getTransformation(self)
val = Matrix(val)
return val | 0.009756 |
def answers(self, other):
"""In CCP, the payload of a DTO packet is dependent on the cmd field
of a corresponding CRO packet. Two packets correspond, if there
ctr field is equal. If answers detect the corresponding CRO, it will
interpret the payload of a DTO with the correct class. In CC... | 0.001919 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.