text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def primary_avatar(user, size=AVATAR_DEFAULT_SIZE):
"""
This tag tries to get the default avatar for a user without doing any db
requests. It achieve this by linking to a special view that will do all the
work for us. If that special view is then cached by a CDN for instance,
we will avoid many db ... | 0.011858 |
def apply_trans_rot(ampal, translation, angle, axis, point, radians=False):
"""Applies a translation and rotation to an AMPAL object."""
if not numpy.isclose(angle, 0.0):
ampal.rotate(angle=angle, axis=axis, point=point, radians=radians)
ampal.translate(vector=translation)
return | 0.003289 |
def ximshow_unrectified(self, slitlet2d):
"""Display unrectified image with spectrails and frontiers.
Parameters
----------
slitlet2d : numpy array
Array containing the unrectified slitlet image.
"""
title = "Slitlet#" + str(self.islitlet)
ax = xims... | 0.001947 |
def gen_toy(f, nsample, bound, accuracy=10000, quiet=True, **kwd):
"""
generate ntoy
:param f:
:param nsample:
:param ntoy:
:param bound:
:param accuracy:
:param quiet:
:param kwd: the rest of keyword argument will be passed to f
:return: numpy.ndarray
"""
# based on inve... | 0.001762 |
def returner(load):
'''
Return data to couchbase bucket
'''
cb_ = _get_connection()
hn_key = '{0}/{1}'.format(load['jid'], load['id'])
try:
ret_doc = {'return': load['return'],
'full_ret': salt.utils.json.dumps(load)}
cb_.add(hn_key,
ret_doc,
... | 0.006601 |
def get_language_tabs(self):
"""
Determine the language tabs to show.
"""
current_language = self.get_current_language()
if self.object:
available_languages = list(self.object.get_available_languages())
else:
available_languages = []
retur... | 0.007653 |
def login(self, user, password, exe_path, comm_password=None, **kwargs):
"""
:param user: 用户名
:param password: 密码
:param exe_path: 客户端路径, 类似
:param comm_password:
:param kwargs:
:return:
"""
if comm_password is None:
raise Val... | 0.001375 |
def _get_variants(data):
"""Retrieve variants from CWL and standard inputs for organizing variants.
"""
active_vs = []
if "variants" in data:
variants = data["variants"]
# CWL based list of variants
if isinstance(variants, dict) and "samples" in variants:
variants = v... | 0.000835 |
def rinse_rpnexp(self, rpnexp, rpndict):
""" replace valid keyword of rpnexp from rpndict
e.g. rpnexp = 'b a /', rpndict = {'b': 10}
then after rinsing, rpnexp = '10 a /'
return rinsed rpnexp
"""
for wd in rpnexp.split():
if wd in rpndict:
... | 0.005917 |
def add(self, name='', type='', agent='', scanner='', location='', language='en', *args, **kwargs):
""" Simplified add for the most common options.
Parameters:
name (str): Name of the library
agent (str): Example com.plexapp.agents.imdb
type (str): mo... | 0.007863 |
def get_vasp_kpoint_file_sym(structure):
"""
get a kpoint file ready to be ran in VASP along the symmetry lines of the
Brillouin Zone
"""
output = run_aconvasp_command(["aconvasp", "--kpath"], structure)
if "ERROR" in output[1]:
raise AconvaspError(output[1])
started = False
kpoi... | 0.00303 |
def bambus(args):
"""
%prog bambus bambus.bed bambus.mates total.fasta
Insert unplaced scaffolds based on mates.
"""
from jcvi.utils.iter import pairwise
from jcvi.formats.bed import BedLine
from jcvi.formats.posmap import MatesFile
p = OptionParser(bambus.__doc__)
p.add_option("--... | 0.000968 |
def include_file(filename):
"""Load another yaml file (no recursion)."""
if os.path.isfile(filename):
with open(filename) as handle:
return safe_load(handle)
raise RuntimeError("Include file %s doesn't exist!" % filename) | 0.007326 |
def pyramid(
input_raster,
output_dir,
pyramid_type=None,
output_format=None,
resampling_method=None,
scale_method=None,
zoom=None,
bounds=None,
overwrite=False,
debug=False
):
"""Create tile pyramid out of input raster."""
bounds = bounds if bounds else None
options ... | 0.001661 |
def process_full_data(fname, rhomin, mass1, mass2, lo_mchirp, hi_mchirp):
"""Read the zero-lag and time-lag triggers identified by templates in
a specified range of chirp mass.
Parameters
----------
hdfile:
File that stores all the triggers
rhomin: float
... | 0.001725 |
def unpack(cls, msg, client, server, request_id):
"""Parse message and return an `OpMsg`.
Takes the client message as bytes, the client and server socket objects,
and the client request id.
"""
payload_document = OrderedDict()
flags, = _UNPACK_UINT(msg[:4])
pos =... | 0.001856 |
def save(self, indexes, parent_id):
"""
Save the selected section. This will save the selected section
as well as its direct child pages obtained through the ?child_of
query parameter. The ?descendant_of query parameter is probably
better suited because it all pages under that p... | 0.002222 |
def _get_application_settings(self, application_id, settings_key, error_message):
"""Legacy behaviour"""
if not application_id:
value = SETTINGS.get(settings_key, empty)
if value is empty:
raise ImproperlyConfigured(error_message)
return value
else:
msg = (
"LegacySettings does not support ap... | 0.032468 |
def diff_mtime_map(map1, map2):
'''
Is there a change to the mtime map? return a boolean
'''
# check if the mtimes are the same
if sorted(map1) != sorted(map2):
return True
# map1 and map2 are guaranteed to have same keys,
# so compare mtimes
for filename, mtime in six.iteritems... | 0.002208 |
def Kdiag(self, X, target):
"""Compute the diagonal of the covariance matrix for X."""
self._K_diag_computations(X)
target+= self.variance*self._K_diag_dvar | 0.016667 |
def POST(self, **kwargs):
r'''
Easily generate keys for a minion and auto-accept the new key
Accepts all the same parameters as the :py:func:`key.gen_accept
<salt.wheel.key.gen_accept>`.
.. note:: A note about ``curl``
Avoid using the ``-i`` flag or HTTP headers will... | 0.001206 |
def to_sql(self, instring, schema, use_bag_semantics=False):
"""
Translate a relational algebra string into a SQL string.
:param instring: a relational algebra string to translate
:param schema: a mapping of relation names to their attributes
:param use_bag_semantics: flag for u... | 0.005566 |
def get_row_generator(self, ref, cache=None):
"""Return a row generator for a reference"""
from inspect import isgenerator
from rowgenerators import get_generator
g = get_generator(ref)
if not g:
raise GenerateError("Cant figure out how to generate rows from {} ref... | 0.007813 |
def extension_supported(request, extension_name):
"""This method will determine if Cinder supports a given extension name."""
for extension in list_extensions(request):
if extension.name == extension_name:
return True
return False | 0.003817 |
def find_output_with_tag(self, tag):
"""
Find all files who have tag in self.tags
"""
# Enforce upper case
tag = tag.upper()
return FileList([i for i in self if tag in i.tags]) | 0.008929 |
def decode_to_shape(inputs, shape, scope):
"""Encode the given tensor to given image shape."""
with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
x = inputs
x = tfl.flatten(x)
x = tfl.dense(x, shape[2], activation=None, name="dec_dense")
x = tf.expand_dims(x, axis=1)
return x | 0.009967 |
def listBlockParents(self, **kwargs):
"""
API to list block parents.
:param block_name: name of block who's parents needs to be found (Required)
:type block_name: str
:returns: List of dictionaries containing following keys (block_name)
:rtype: list of dicts
... | 0.007273 |
def wait(hotkey=None, suppress=False, trigger_on_release=False):
"""
Blocks the program execution until the given hotkey is pressed or,
if given no parameters, blocks forever.
"""
if hotkey:
lock = _Event()
remove = add_hotkey(hotkey, lambda: lock.set(), suppress=suppress, trigger_on... | 0.004376 |
def run(cmd, stdout=None, stderr=None, **kwargs):
"""
A blocking wrapper around subprocess.Popen(), but with a simpler interface
for the stdout/stderr arguments:
stdout=False / stderr=False
stdout/stderr will be redirected to /dev/null (or discarded in some
other suitable manner)
st... | 0.000326 |
def remove_objects(code, count=1):
""" This function replaces objects with OBJECTS_LVALS, returns new code, replacement dict and count.
count arg is the number that should be added to the LVAL of the first replaced object
"""
replacements = {} #replacement dict
br = bracket_split(code, ['{}', '... | 0.00493 |
def asset(self):
""" Returns the asset as instance of :class:`.asset.Asset`
"""
if not self["asset"]:
self["asset"] = self.asset_class(
self["symbol"], blockchain_instance=self.blockchain
)
return self["asset"] | 0.007092 |
def get_public_key(self):
"""
Parse the scriptSig and extract the public key.
Raises ValueError if this is a multisig-controlled subdomain.
"""
res = self.get_public_key_info()
if 'error' in res:
raise ValueError(res['error'])
if res['type'] != 'singl... | 0.004914 |
def is_pattern_valid(pattern):
"""Returns True if pattern is valid.
:param pattern: Normalized pattern.
is_pattern_valid() assumes pattern to be normalized.
see: globbing.normalize_pattern
"""
result = True
translator = Globster.pattern_info[Globster.identify(pat... | 0.006734 |
def _mysqld_process_checkpoint():
'''this helper method checks if
mysql server is available in the sys
if not fires up one
'''
try:
subprocess.check_output("pgrep mysqld", shell=True)
except Exception:
logger.warning(
'Your mysql server is offline, fake2db will try to... | 0.001689 |
def get_aligned_abi_inputs(abi, args):
"""
Takes a function ABI (``abi``) and a sequence or mapping of args (``args``).
Returns a list of type strings for the function's inputs and a list of
arguments which have been aligned to the layout of those types. The args
contained in ``args`` may contain n... | 0.003672 |
def parse_file( self, filename ):
"""parse a C source file, and add its blocks to the processor's list"""
self.reset()
self.filename = filename
fileinput.close()
self.format = None
self.lineno = 0
self.lines = []
for line in fileinput.input( filename ... | 0.015487 |
def wrap_rankboost(job, rsem_files, merged_mhc_calls, transgene_out, univ_options,
rankboost_options):
"""
A wrapper for boost_ranks.
:param dict rsem_files: Dict of results from rsem
:param dict merged_mhc_calls: Dict of results from merging mhc peptide binding predictions
:para... | 0.005405 |
def get_motor_offsets(SERVO_OUTPUT_RAW, ofs, motor_ofs):
'''calculate magnetic field strength from raw magnetometer'''
import mavutil
self = mavutil.mavfile_global
m = SERVO_OUTPUT_RAW
motor_pwm = m.servo1_raw + m.servo2_raw + m.servo3_raw + m.servo4_raw
motor_pwm *= 0.25
rc3_min = self.par... | 0.002681 |
def stop_instance(self):
"""Stop the instance for this Streaming Analytics service.
Returns:
dict: JSON response for the instance stop operation.
"""
stop_url = self._get_url('stop_path')
res = self.rest_client.session.put(stop_url, json={})
_handle_http_erro... | 0.005666 |
def BL(self, params):
"""
BL label
Branch to the label, storing the next instruction in the Link Register
"""
label = self.get_one_parameter(self.ONE_PARAMETER, params)
self.check_arguments(label_exists=(label,))
# TODO check if label is within +- 16 MB
... | 0.005445 |
def generate_network(nl_model,
handler,
seed=1234,
always_include_props=False,
include_connections=True,
include_inputs=True,
base_dir=None):
"""
Generate the network model as describ... | 0.011326 |
def take_profit(self, accountID, **kwargs):
"""
Shortcut to create a Take Profit Order in an Account
Args:
accountID : The ID of the Account
kwargs : The arguments to create a TakeProfitOrderRequest
Returns:
v20.response.Response containing the resul... | 0.004115 |
def value(self):
"""
Returns :data:`True` if the host returned a single ping, and
:data:`False` otherwise.
"""
# XXX This is doing a DNS lookup every time it's queried; should we
# call gethostbyname in the constructor and ping that instead (good
# for consistency... | 0.002766 |
def tile_bbox(self, tile_indices):
"""
Returns the WGS84 bbox of the specified tile
"""
(z, x, y) = tile_indices
topleft = (x * self.tilesize, (y + 1) * self.tilesize)
bottomright = ((x + 1) * self.tilesize, y * self.tilesize)
nw = self.unproject_pixels(topleft, z... | 0.005063 |
def definitiondir(self, filetype, **kwargs):
"""Returns definition subdirectory in :envvar:`PLATELIST_DIR` of the form: ``NNNNXX``.
Parameters
----------
filetype : str
File type parameter.
designid : int or str
Design ID number. Will be converted to int... | 0.004823 |
def _get_cairo_bmp(self, mdc, key, rect, is_selected, view_frozen):
"""Returns a wx.Bitmap of cell key in size rect"""
bmp = wx.EmptyBitmap(rect.width, rect.height)
mdc.SelectObject(bmp)
mdc.SetBackgroundMode(wx.SOLID)
mdc.SetBackground(wx.WHITE_BRUSH)
mdc.Clear()
... | 0.001623 |
def _read_para_transaction_id(self, code, cbit, clen, *, desc, length, version):
"""Read HIP TRANSACTION_ID parameter.
Structure of HIP TRANSACTION_ID parameter [RFC 6078]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 ... | 0.002514 |
def runCLI():
"""
The starting point for the execution of the Scrapple command line tool.
runCLI uses the docstring as the usage description for the scrapple command. \
The class for the required command is selected by a dynamic dispatch, and the \
command is executed through the execute_command() ... | 0.005006 |
def _zc_decode(self, msg):
"""ZC: Zone Change."""
status = _status_decode(int(msg[7:8], 16))
return {'zone_number': int(msg[4:7])-1, 'zone_status': status} | 0.011173 |
def fromfits(infile, hdu = 0, verbose = True):
"""
Factory function that reads a FITS file and returns a f2nimage object.
Use hdu to specify which HDU you want (primary = 0)
"""
pixelarray, hdr = ft.getdata(infile, hdu, header=True)
pixelarray = np.asarray(pixelarray).transpose()
#print... | 0.01958 |
def relpath(self):
"""
Determine the relative path to this repository
Returns:
str: relative path to this repository
"""
here = os.path.abspath(os.path.curdir)
relpath = os.path.relpath(self.fpath, here)
return relpath | 0.006969 |
def _check_lr(name, optimizer, lr):
"""Return one learning rate for each param group."""
n = len(optimizer.param_groups)
if not isinstance(lr, (list, tuple)):
return lr * np.ones(n)
if len(lr) != n:
raise ValueError("{} lr values were passed for {} but there are "
... | 0.002558 |
def _update_servers(self):
"""Sync our Servers from TopologyDescription.server_descriptions.
Hold the lock while calling this.
"""
for address, sd in self._description.server_descriptions().items():
if address not in self._servers:
monitor = self._settings.mo... | 0.001531 |
def get_altimeter(wxdata: [str], units: Units, version: str = 'NA') -> ([str], Number): # type: ignore # noqa
"""
Returns the report list and the removed altimeter item
Version is 'NA' (North American / default) or 'IN' (International)
"""
if not wxdata:
return wxdata, None
altimeter ... | 0.000552 |
def do_execute(self, options, args):
"""Implementation of 'coverage run'."""
# Set the first path element properly.
old_path0 = sys.path[0]
# Run the script.
self.coverage.start()
code_ran = True
try:
try:
if options.module:
... | 0.002304 |
def stop(self):
'''Set everything back to normal and collect our data'''
for key, value in self._configs.items():
self._client.config_set(key, value)
logs = self._client.execute_command('slowlog', 'get', 100000)
current = {
'name': None, 'accumulated': defaultdict... | 0.001285 |
def checkout(request, user_id=None):
''' Runs the checkout process for the current cart.
If the query string contains ``fix_errors=true``, Registrasion will attempt
to fix errors preventing the system from checking out, including by
cancelling expired discounts and vouchers, and removing any unavailabl... | 0.000649 |
def create_namespace(self, body, **kwargs): # noqa: E501
"""create_namespace # noqa: E501
create a Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespac... | 0.001445 |
def delete(self):
"""Remove this resource (recursive)."""
self._check_write_access()
filepath = self._getFilePath()
commands.remove(self.provider.ui, self.provider.repo, filepath, force=True) | 0.013453 |
def _get_pseudo_key(self, row):
"""
Returns the pseudo key in a row.
:param dict row: The row.
:rtype: tuple
"""
ret = list()
for key in self._pseudo_key:
ret.append(row[key])
return tuple(ret) | 0.007353 |
def concat_chunks(data, ipyclient):
"""
Concatenate chunks. If multiple chunk files match to the same sample name
but with different barcodes (i.e., they are technical replicates) then this
will assign all the files to the same sample name file.
"""
## collate files progress bar
start = ti... | 0.005638 |
def information_coefficient(total1,total2,intersect):
'''a simple jacaard (information coefficient) to compare two lists of overlaps/diffs
'''
total = total1 + total2
return 2.0*len(intersect) / total | 0.018519 |
def get_members(pkg_name, module_filter = None, member_filter = None):
"""
返回包中所有符合条件的模块成员。
参数:
pkg_name 包名称
module_filter 模块名过滤器 def (module_name)
member_filter 成员过滤器 def member_filter(module_member_object)
"""
modules = get_modules(p... | 0.011236 |
def get_document_unit(self):
"""Get the unit of the SVG surface.
If the surface passed as an argument is not a SVG surface, the function
sets the error status to ``STATUS_SURFACE_TYPE_MISMATCH`` and
returns :ref:`SVG_UNIT_USER`.
:return: The SVG unit of the SVG surface.
... | 0.003929 |
def set_decode_area(codec, image, start_x=0, start_y=0, end_x=0, end_y=0):
"""Wraps openjp2 library function opj_set_decode area.
Sets the given area to be decoded. This function should be called right
after read_header and before any tile header reading.
Parameters
----------
codec : CODEC_T... | 0.000679 |
def thread_stopped(self):
""" :meth:`.WThreadTask._polling_iteration` implementation
"""
if self.__current_task is not None:
task = self.__task_chain[self.__current_task]
task.stop()
self.__current_task = None | 0.035714 |
def _insert_dummy_zmat(self, exception, inplace=False):
"""Works INPLACE"""
def insert_row(df, pos, key):
if pos < len(df):
middle = df.iloc[pos:(pos + 1)]
middle.index = [key]
start, end = df.iloc[:pos], df.iloc[pos:]
return pd... | 0.00095 |
def graph(ctx, path, metrics, output, x_axis, changes):
"""
Graph a specific metric for a given file, if a path is given, all files within path will be graphed.
Some common examples:
Graph all .py files within src/ for the raw.loc metric
$ wily graph src/ raw.loc
Graph test.py against ra... | 0.002203 |
def _get_names(self, collector):
"""Get names of timeseries the collector produces."""
desc_func = None
# If there's a describe function, use it.
try:
desc_func = collector.describe
except AttributeError:
pass
# Otherwise, if auto describe is enabl... | 0.002026 |
def sign(self, pkt, key):
"""
Sign an IPsec (ESP or AH) packet with this algo.
@param pkt: a packet that contains a valid encrypted ESP or AH layer
@param key: the authentication key, a byte string
@return: the signed packet
"""
if not self.mac:
... | 0.002841 |
def send(self, wifs, txouts, change_address=None, lock_time=0, fee=10000):
"""TODO add doc string"""
# FIXME test!!
rawtx = self.create_tx(txouts=txouts, lock_time=lock_time)
rawtx = self.add_inputs(rawtx, wifs, change_address=change_address,
fee=fee)
... | 0.005714 |
def convert_time(obj):
"""Returns a TIME column as a time object:
>>> time_or_None('15:06:17')
datetime.time(15, 6, 17)
Illegal values are returned as None:
>>> time_or_None('-25:06:17') is None
True
>>> time_or_None('random crap') is None
True
Note that MySQL always ... | 0.001599 |
def endpoint_access(self, method):
"""
Determine access level needed for endpoint
:param method: The request verb
:return: String representing access type.
"""
if method == 'OPTIONS':
# The CORS pre-flight checks should not require authentication
r... | 0.005146 |
def write_template(fn, lang="python"):
"""
Write language-specific script template to file.
Arguments:
- fn(``string``) path to save the template to
- lang('python', 'bash') which programming language
"""
with open(fn, "wb") as fh:
if lang == "python":
fh.wri... | 0.005025 |
def update_user_lock(repository_path, session_token):
""" Write or clear the user lock file """ # NOTE ALWAYS use within lock access callback
# While the user lock file should ALWAYS be written only within a lock_access
# callback, it is sometimes read asynchronously. Because of this updates to
# the f... | 0.013569 |
def clean_str(string):
"""Tokenization/string cleaning for all datasets except for SST.
Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py
"""
string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string)
string = re.sub(r"\'s", " \'s", string)
string = re.sub(r"\'v... | 0.002457 |
def status(self):
"""
The current status of the event (started, finished or pending).
"""
myNow = timezone.localtime(timezone=self.tz)
fromDt = getAwareDatetime(self.except_date, self.time_from, self.tz)
daysDelta = dt.timedelta(days=self.num_days - 1)
toDt = getA... | 0.006024 |
def new_line(self, tokens, line_end, line_start):
"""a new line has been encountered, process it if necessary"""
if _last_token_on_line_is(tokens, line_end, ";"):
self.add_message("unnecessary-semicolon", line=tokens.start_line(line_end))
line_num = tokens.start_line(line_start)
... | 0.005906 |
def get_client(self, email=None, password=None, **__):
"""Get the google data client."""
if self.client is not None:
return self.client
return Auth(email, password) | 0.01 |
def zrevrank(self, name, value):
"""
Returns the ranking in reverse order for the member
:param name: str the name of the redis key
:param member: str
"""
with self.pipe as pipe:
return pipe.zrevrank(self.redis_key(name),
... | 0.005714 |
def prior_rev(C, alpha=-1.0):
r"""Prior counts for sampling of reversible transition
matrices.
Prior is defined as
b_ij= alpha if i<=j
b_ij=0 else
The reversible prior adds -1 to the upper triagular part of
the given count matrix. This prior respects the fact that
for a revers... | 0.001242 |
def render_children(self, block, view_name=None, context=None):
"""Render a block's children, returning a list of results.
Each child of `block` will be rendered, just as :func:`render_child` does.
Returns a list of values, each as provided by :func:`render`.
"""
results = []
... | 0.005682 |
def get_default_values(self):
"""
Overridding to make updating the defaults after instantiation of
the option parser possible, update_defaults() does the dirty work.
"""
if not self.process_default_values:
# Old, pre-Optik 1.5 behaviour.
return optparse.Va... | 0.002774 |
def no_witness(self):
'''
Tx -> bytes
'''
tx = bytes()
tx += self.version
tx += VarInt(len(self.tx_ins)).to_bytes()
for tx_in in self.tx_ins:
tx += tx_in.to_bytes()
tx += VarInt(len(self.tx_outs)).to_bytes()
for tx_out in self.tx_outs:
... | 0.00489 |
def _right_align(p_str):
"""
Returns p_str with content after <TAB> character aligned right.
Right alignment is done using proper number of spaces calculated from
'line_width' attribute.
"""
to_fill = _columns() - len(escape_ansi(p_str))
if to_fill > 0:
p_str = re.sub('\t', ' '*to_... | 0.002494 |
def create_WCSname(wcsname):
""" Verify that a valid WCSNAME has been provided, and if not, create a
default WCSNAME based on current date.
"""
if util.is_blank(wcsname):
ptime = fileutil.getDate()
wcsname = "User_"+ptime
return wcsname | 0.00361 |
def next(self):
'''
Return the next iteration by popping `chunk_size` from the left and
appending `chunk_size` to the right if there's info on the file left
to be read.
'''
if self.__buffered is None:
# Use floor division to force multiplier to an integer
... | 0.002073 |
async def get_storage_list(self) -> List[Storage]:
"""Return information about connected storage devices."""
return [
Storage.make(**x)
for x in await self.services["system"]["getStorageList"]({})
] | 0.00813 |
def from_fptr(cls, label, type_, fptr):
"""Return ``FSEntry`` object."""
return FSEntry(
label=label,
type=type_,
path=fptr.path,
use=fptr.use,
file_uuid=fptr.file_uuid,
derived_from=fptr.derived_from,
checksum=fptr.chec... | 0.005277 |
def convert(self, value, param, ctx): # pylint: disable=inconsistent-return-statements
"""Validate memory argument. Returns the memory value in megabytes."""
matches = MEMORY_RE.match(value.lower())
if matches is None:
self.fail('%s is not a valid value for memory amount' % value, p... | 0.00591 |
def _get_digest(self, info):
"""
Get a digest from a dictionary by looking at keys of the form
'algo_digest'.
Returns a 2-tuple (algo, digest) if found, else None. Currently
looks only for SHA256, then MD5.
"""
result = None
for algo in ('sha256', 'md5'):... | 0.004237 |
def ncbi_blast(self, db="nr", megablast=True, sequence=None):
"""
perform an NCBI blast against the sequence of this feature
"""
import requests
requests.defaults.max_retries = 4
assert sequence in (None, "cds", "mrna")
seq = self.sequence() if sequence is None el... | 0.007042 |
def create_devices(self, thing_names, config_file, region=None,
cert_dir=None, append=False, account_id=None,
policy_name='ggd-discovery-policy', profile_name=None):
"""
Using the `thing_names` values, creates Things in AWS IoT, attaches and
download... | 0.001593 |
def get_root_path(self, language):
"""
Get root path to pass to the LSP servers.
This can be the current project path or the output of
getcwd_or_home (except for Python, see below).
"""
path = None
# Get path of the current project
if self.main and self.... | 0.001821 |
def get_cache_key(datatable_class, view=None, user=None, **kwargs):
"""
Returns a cache key unique to the current table, and (if available) the request user.
The ``view`` argument should be the class reference itself, since it is easily obtainable
in contexts where the instance is not available.
""... | 0.002457 |
def create_geotiff(name, Array, driver, ndv, xsize, ysize, geot, projection, datatype, band=1):
'''
Creates new geotiff from array
'''
if isinstance(datatype, np.int) == False:
if datatype.startswith('gdal.GDT_') == False:
datatype = eval('gdal.GDT_'+datatype)
newfilename = name+... | 0.00527 |
def on_close(self):
""" Called by the server when the App have to be terminated
"""
self._stop_update_flag = True
for ws in self.websockets:
ws.close() | 0.010256 |
def plot(parameterized, fignum=None, ax=None, colors=None, figsize=(12, 6)):
"""
Plot latent space X in 1D:
- if fig is given, create input_dim subplots in fig and plot in these
- if ax is given plot input_dim 1D latent space plots of X into each `axis`
- if neither fig nor ax is given ... | 0.003254 |
def skip_while(self, predicate):
'''Omit elements from the start for which a predicate is True.
Note: This method uses deferred execution.
Args:
predicate: A single argument predicate function.
Returns:
A Queryable over the sequence of elements beginning with t... | 0.003297 |
def remove_binaries(package_dir=False):
"""Remove all binaries for the current platform
Parameters
----------
package_dir: bool
If True, remove all binaries from the `resources`
directory of the qpsphere package. If False,
remove all binaries from the user's cache directory.
... | 0.001739 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.