text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def nearest_overlap(self, overlap, bins):
"""Return nearest overlap/crop factor based on number of bins"""
bins_overlap = overlap * bins
if bins_overlap % 2 != 0:
bins_overlap = math.ceil(bins_overlap / 2) * 2
overlap = bins_overlap / bins
logger.warning('numb... | 0.006356 |
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
... | 0.000461 |
def get_users(profile='pagerduty', subdomain=None, api_key=None):
'''
List users belonging to this account
CLI Example:
salt myminion pagerduty.get_users
'''
return _list_items(
'users',
'id',
profile=profile,
subdomain=subdomain,
api_key=api_key,
... | 0.003086 |
def _set_auto_cost(self, v, load=False):
"""
Setter method for auto_cost, mapped from YANG variable /rbridge_id/router/ospf/auto_cost (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_auto_cost is considered as a private
method. Backends looking to populate... | 0.00602 |
def _inherit_data(self):
"""
Inherits the data from the parent.
"""
LOG.debug("'%s' inheriting data from '%s'" % (self.get_name(),
self.parent.get_name()),
extra=dict(data=self.parent.data))
self.set_data(**s... | 0.005952 |
def create(input_width, input_height, input_channels=1):
""" Vel factory function """
def instantiate(**_):
return DoubleNatureCnn(input_width=input_width, input_height=input_height, input_channels=input_channels)
return ModelFactory.generic(instantiate) | 0.007273 |
def to_weld_type(weld_type, dim):
"""Summary
Args:
weld_type (TYPE): Description
dim (TYPE): Description
Returns:
TYPE: Description
"""
for i in xrange(dim):
weld_type = WeldVec(weld_type)
return weld_type | 0.003802 |
def kraken_request(self, method, endpoint, **kwargs):
"""Make a request to one of the kraken api endpoints.
Headers are automatically set to accept :data:`TWITCH_HEADER_ACCEPT`.
Also the client id from :data:`CLIENT_ID` will be set.
The url will be constructed of :data:`TWITCH_KRAKENURL... | 0.002752 |
def source_files(self):
"""This rule's source files."""
if 'srcs' in self.params and self.params['srcs'] is not None:
return util.flatten(self.params['srcs']) | 0.010753 |
def dannots2dalignbed2dannotsagg(cfg):
"""
Aggregate annotations per query
step#8
:param cfg: configuration dict
"""
datatmpd=cfg['datatmpd']
daannotp=f'{datatmpd}/08_dannot.tsv'
cfg['daannotp']=daannotp
dannotsaggp=cfg['dannotsaggp']
logging.info(basename(daannotp))
if... | 0.023318 |
def abort (aggregate):
"""Helper function to ensure a clean shutdown."""
while True:
try:
aggregate.abort()
aggregate.finish()
aggregate.end_log_output(interrupt=True)
break
except KeyboardInterrupt:
log.warn(LOG_CHECK, _("user abort; f... | 0.004843 |
def set_deployment_run_id(self):
"""Sets the deployment run ID from deployment properties
:return: None
"""
log = logging.getLogger(self.cls_logger + '.set_deployment_run_id')
deployment_run_id_val = self.get_value('cons3rt.deploymentRun.id')
if not deployment_run_id_val... | 0.005051 |
def policy_exists(vhost, name, runas=None):
'''
Return whether the policy exists based on rabbitmqctl list_policies.
Reference: http://www.rabbitmq.com/ha.html
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.policy_exists / HA
'''
if runas is None and not salt.utils.platform.... | 0.002079 |
def convolve(input, weights, mask=None, slow=False):
"""2 dimensional convolution.
This is a Python implementation of what will be written in Fortran.
Borders are handled with reflection.
Masking is supported in the following way:
* Masked points are skipped.
* Parts of the input whic... | 0.000456 |
def __get_wbfmt_format_txt(self, data_nt):
"""Return format for text cell from namedtuple field, 'format_txt'."""
format_txt_val = getattr(data_nt, "format_txt")
if format_txt_val == 1:
return self.fmtname2wbfmtobj.get("very light grey")
if format_txt_val == 2:
re... | 0.004751 |
def _push_property_schema(self, prop):
"""Construct a sub-schema from a property of the current schema."""
schema = Schema(self._schema.properties[prop])
self._push_schema(schema, ".properties." + prop) | 0.00885 |
def wrap(s, width=80):
"""
Formats the text input with newlines given the user specified width for
each line.
Parameters
----------
s : str
width : int
Returns
-------
text : str
Notes
-----
.. versionadded:: 1.1
"""
return '\n'.join(textwrap.wrap(str(s... | 0.002976 |
def nvmlDeviceGetUtilizationRates(handle):
r"""
/**
* Retrieves the current utilization rates for the device's major subsystems.
*
* For Fermi &tm; or newer fully supported devices.
*
* See \ref nvmlUtilization_t for details on available utilization rates.
*
* \note During dri... | 0.006892 |
def get_disk_usage(path):
"""Return disk usage associated with path."""
st = os.statvfs(path)
free = (st.f_bavail * st.f_frsize)
total = (st.f_blocks * st.f_frsize)
used = (st.f_blocks - st.f_bfree) * st.f_frsize
percent = usage_percent(used, total, _round=1)
# NB: the percentage is -5% than... | 0.002075 |
def _easteregg(app=None):
"""Like the name says. But who knows how it works?"""
def bzzzzzzz(gyver):
import base64
import zlib
return zlib.decompress(base64.b64decode(gyver)).decode("ascii")
gyver = u"\n".join(
[
x + (77 - len(x)) * u" "
for x in b... | 0.000261 |
def name_from_type(type_):
# type: (InternalType) -> str
"""
Helper function to get PEP-484 compatible string representation of our internal types.
"""
if isinstance(type_, (DictType, ListType, TupleType, SetType, IteratorType)):
return repr(type_)
else:
if type_.__name__ != 'Non... | 0.004242 |
def get_float(self, key, default=UndefinedKey):
"""Return float representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: float
:return: float value
... | 0.004622 |
def parse_stream(cls, iterable):
"""
Parse a stream of messages into a stream of L{Task} instances.
:param iterable: An iterable of serialized Eliot message dictionaries.
:return: An iterable of parsed L{Task} instances. Remaining
incomplete L{Task} will be returned when th... | 0.0032 |
def remove_update_callback(self, group, name=None, cb=None):
"""Remove the supplied callback for a group or a group.name"""
if not cb:
return
if not name:
if group in self.group_update_callbacks:
self.group_update_callbacks[group].remove_callback(cb)
... | 0.003899 |
def MOVQ(cpu, dest, src):
"""
Move quadword.
Copies a quadword from the source operand (second operand) to the destination operand (first operand).
The source and destination operands can be MMX(TM) technology registers, XMM registers, or 64-bit memory
locations. This instructio... | 0.005732 |
def _get_section(self, path_):
"""Auto-creates section structure
Last element in path_ is considered to be the "filename" (item name)
Returns: (configobj.Session object, converted path)
"""
if isinstance(path_, str):
path_ = path_.strip().split("/")
... | 0.003026 |
def command_runner(shell_command, force_rerun_flag, outfile_checker, cwd=None, silent=False):
"""Run a shell command with subprocess, with additional options to check if output file exists and printing stdout.
Args:
shell_command (str): Command as it would be formatted in the command-line (ie. "program... | 0.00555 |
def __exchange(self, output, timeout=None):
"""Write output to the port and wait for response"""
self.__writeln(output)
self._port.flush()
return self.__expect(timeout=timeout or self._timeout) | 0.008889 |
def histogram(a, bins=10, range=None):
"""Compute the histogram of the input data.
Parameters
----------
a : NDArray
Input data. The histogram is computed over the flattened array.
bins : int or sequence of scalars
If bins is an int, it defines the number of equal-width bins in the
... | 0.003234 |
def worktree_prune(cwd,
dry_run=False,
verbose=True,
expire=None,
opts='',
git_opts='',
user=None,
password=None,
ignore_retcode=False,
output_encodi... | 0.000256 |
async def copy_from_table(self, table_name, *, output,
columns=None, schema_name=None, timeout=None,
format=None, oids=None, delimiter=None,
null=None, header=None, quote=None,
escape=None, force_quot... | 0.002291 |
def Herning_Zipperer(zs, mus, MWs):
r'''Calculates viscosity of a gas mixture according to
mixing rules in [1]_.
.. math::
TODO
Parameters
----------
zs : float
Mole fractions of components
mus : float
Gas viscosities of all components, [Pa*S]
MWs : float
... | 0.001645 |
def _get_salt_params():
'''
Try to get all sort of parameters for Server Density server info.
NOTE: Missing publicDNS and publicIPs parameters. There might be way of
getting them with salt-cloud.
'''
all_stats = __salt__['status.all_status']()
all_grains = __salt__['grains.items']()
par... | 0.00349 |
def send(self, payload):
"""
Send a payload to exchange to containing command and payload to the queue specified in config.
:param command: str: name of the command we want run by WorkQueueProcessor
:param payload: str: string data that will be put into the exchange's message body
... | 0.010582 |
def setup(gandi):
""" Initialize Gandi CLI configuration.
Create global configuration directory with API credentials
"""
intro = """Welcome to GandiCLI, let's configure a few things before we \
start.
"""
outro = """
Setup completed. You can now:
* use 'gandi' to see all command.
* use 'gandi vm c... | 0.001957 |
def tsp_gurobi(edges):
"""
Modeled using GUROBI python example.
"""
from gurobipy import Model, GRB, quicksum
edges = populate_edge_weights(edges)
incoming, outgoing, nodes = node_to_edge(edges)
idx = dict((n, i) for i, n in enumerate(nodes))
nedges = len(edges)
n = len(nodes)
... | 0.000324 |
def config_cred(config, providers):
"""Read credentials from configfile."""
expected = ['aws', 'azure', 'gcp', 'alicloud']
cred = {}
to_remove = []
for item in providers:
if any(item.startswith(itemb) for itemb in expected):
try:
cred[item] = dict(list(config[item... | 0.001387 |
def _find_channel_index(data_format):
"""Returns the index of the channel dimension.
Args:
data_format: A string of characters corresponding to Tensor dimensionality.
Returns:
channel_index: An integer indicating the channel dimension.
Raises:
ValueError: If no channel dimension was found.
"""
... | 0.00998 |
def _setDefaults(input_dict={}):
""" Define full set of default values for unit-testing this module.[OBSOLETE]"""
paramDict = {
'input':'*flt.fits',
'output':None,
'mdriztab':None,
'refimage':None,
'runfile':None,
'workinplace':False,
'updatewcs':True,
... | 0.033443 |
def maximum_deck_area(self, water_plane_coef=0.88):
"""
Return the maximum deck area of the ship
:param water_plane_coef: optional water plane coefficient
:return: Area of the deck
"""
AD = self.beam * self.length * water_plane_coef
return AD | 0.006689 |
def generate_hcard(template=None, **kwargs):
"""Generate a hCard document.
Template specific key-value pairs need to be passed as ``kwargs``, see classes.
:arg template: Ready template to fill with args, for example "diaspora" (optional)
:returns: HTML document (str)
"""
if template == "diaspo... | 0.006881 |
def approve(self, asset, sender: Account, b58_recv_address: str, amount: int, payer: Account, gas_limit: int,
gas_price: int) -> str:
"""
This is an interface used to send an approve transaction
which allow receiver to spend a amount of ONT or ONG asset in sender's account.
... | 0.006391 |
def data(self, as_cells=False):
""" Reads the worksheet and returns an indexed dictionary of the
row objects.
For example:
>>>print sheet.data()
{'Miss Piggy': {'Color': 'Pink', 'Performer': 'Frank Oz'}, 'Kermit': {'Color': 'Green', 'Performer': 'Jim Henson'}} ... | 0.003778 |
def variables(self):
'''return a list of available variables'''
return sorted(list(self.mapping.vars.keys()),
key = lambda v : self.mapping.vars[v].index) | 0.026042 |
def get_app_token(self, scope):
"""Gets the app auth token"""
app_token = self.__get_app_token(scope)
if app_token:
return app_token
if self.__cache is not None:
token = self.__cache.get(self.__app_token_cache_key(scope))
if token:
r... | 0.004329 |
def with_category(category: str) -> Callable:
"""A decorator to apply a category to a command function."""
def cat_decorator(func):
categorize(func, category)
return func
return cat_decorator | 0.004566 |
def path(self, which=None):
"""Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
import
/templates/import
export
/templates/export
"""
if which:
return '{0}/{1}'.format(
... | 0.004619 |
async def post(self, cmd, data=None, timeout=None, **args):
"""Perform DAAP POST command with optional data."""
def _post_request():
headers = copy(_DMAP_HEADERS)
headers['Content-Type'] = 'application/x-www-form-urlencoded'
return self.http.post_data(
... | 0.003824 |
def lithospheric_stress(step, trench, ridge, time):
"""calculate stress in the lithosphere"""
timestep = step.isnap
base_lith = step.geom.rcmb + 1 - 0.105
stressfld = step.fields['sII'][0, :, :, 0]
stressfld = np.ma.masked_where(step.geom.r_mesh[0] < base_lith, stressfld)
# stress integration ... | 0.000257 |
def convert_to_match_query(ir_blocks):
"""Convert the list of IR blocks into a MatchQuery object, for easier manipulation."""
output_block = ir_blocks[-1]
if not isinstance(output_block, ConstructResult):
raise AssertionError(u'Expected last IR block to be ConstructResult, found: '
... | 0.005678 |
def confd_state_webui_listen_tcp_ip(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
webui = ET.SubElement(confd_state, "webui")
listen = ET.SubEle... | 0.005474 |
def get_doc_type_mappings(self, doc_type):
"""Converts all doc_types' fields to .kibana"""
doc_fields_arr = []
found_score = False
for (key, val) in iteritems(doc_type):
# self.pr_dbg("\t\tfield: %s" % key)
# self.pr_dbg("\tval: %s" % val)
add_it = Fal... | 0.001117 |
def get(self, fields=[]):
'''taobao.shopcats.list.get 获取前台展示的店铺类目
此API获取淘宝面向买家的浏览导航类目 跟后台卖家商品管理的类目有差异'''
request = TOPRequest('taobao.shopcats.list.get')
if not fields:
shopCat = ShopCat()
fields = shopCat.fields
request['fields'] = fields
... | 0.007792 |
async def _receive_packet(self, pkt):
"""Handle incoming packets from the server."""
packet_name = packet.packet_names[pkt.packet_type] \
if pkt.packet_type < len(packet.packet_names) else 'UNKNOWN'
self.logger.info(
'Received packet %s data %s', packet_name,
... | 0.002571 |
def as_raw(self):
"""
Return a representation of this object that can be used with mongoengine Document.objects(__raw__=x)
Example:
>>> stream_id = StreamId(name='test', meta_data=((u'house', u'1'), (u'resident', u'1')))
>>> stream_id.as_raw()
{'stream_id.meta_data': [(u... | 0.009434 |
def reinforce(self, **kwargs):
"""
Reinforces the grid and calculates grid expansion costs.
See :meth:`edisgo.flex_opt.reinforce_grid` for more information.
"""
results = reinforce_grid(
self, max_while_iterations=kwargs.get(
'max_while_iterations', ... | 0.00292 |
def find_typed_function(pytype, prefix, suffix, module=lal):
"""Returns the lal method for the correct type
Parameters
----------
pytype : `type`, `numpy.dtype`
the python type, or dtype, to map
prefix : `str`
the function name prefix (before the type tag)
suffix : `str`
... | 0.001337 |
def usufyToJsonExport(d, fPath):
"""
Workaround to export to a json file.
Args:
-----
d: Data to export.
fPath: File path for the output file.
"""
oldData = []
try:
with open (fPath) as iF:
oldText = iF.read()
if oldText != "":
... | 0.009074 |
def validate_attribute(attr, name, expected_type=None, required=False):
'''Validates that an attribute meets expectations.
This function will check if the given attribute value matches a necessary
type and/or is not None, an empty string, an empty list, etc. It will raise
suitable exceptions on validat... | 0.000894 |
def require_authentication(self, realm, environ):
"""Return True if this realm requires authentication (grant anonymous access otherwise)."""
realm_entry = self._get_realm_entry(realm)
if realm_entry is None:
_logger.error(
'Missing configuration simple_dc.user_mappin... | 0.006682 |
def make_stats(data, perfile, fsamplehits, fbarhits, fmisses, fdbars):
"""
Write stats and stores to Assembly object.
"""
## out file
outhandle = os.path.join(data.dirs.fastqs, 's1_demultiplex_stats.txt')
outfile = open(outhandle, 'w')
## write the header for file stats -------------------... | 0.01069 |
def esc_split(text, delimiter=" ", maxsplit=-1, escape="\\", *, ignore_empty=False):
"""Escape-aware text splitting:
Split text on on a delimiter, recognizing escaped delimiters."""
is_escaped = False
split_count = 0
yval = []
for char in text:
if is_escaped:
is_escaped = False
yval.append... | 0.024272 |
def stem(u, v, dfs_data):
"""The stem of Bu(v) is the edge uv in Bu(v)."""
#return dfs_data['graph'].get_first_edge_id_by_node_ids(u, v)
uv_edges = dfs_data['graph'].get_edge_ids_by_node_ids(u, v)
buv_edges = B(u, v, dfs_data)
for edge_id in uv_edges:
if edge_id in buv_edges:
ret... | 0.005764 |
def modify_object(self, modification, obj):
"""
Modify an object that supports pymatgen's as_dict() and from_dict API.
Args:
modification (dict): Modification must be {action_keyword :
settings}. E.g., {'_set': {'Hello':'Universe', 'Bye': 'World'}}
obj (o... | 0.004435 |
def parse(cls, data: bytes) -> 'MessageContent':
"""Parse the bytestring into message content.
Args:
data: The bytestring to parse.
"""
lines = cls._find_lines(data)
view = memoryview(data)
return cls._parse(data, view, lines) | 0.006944 |
def cas(self, key, value, cas, time=0, compress_level=-1):
"""
Set a value for a key on server if its CAS value matches cas.
:param key: Key's name
:type key: six.string_types
:param value: A value to be stored on server.
:type value: object
:param cas: The CAS v... | 0.00227 |
def build_synchronize_decorator():
"""Returns a decorator which prevents concurrent calls to functions.
Usage:
synchronized = build_synchronize_decorator()
@synchronized
def read_value():
...
@synchronized
def write_value(x):
...
Returns:
make_threadsafe (fct): The decorato... | 0.009631 |
async def status_by_coordinates(
self, latitude: float, longitude: float) -> dict:
"""Get symptom data for the location nearest to the user's lat/lon."""
return await self.nearest_by_coordinates(latitude, longitude) | 0.00823 |
def delay_job(self, job, delayed_until):
"""
Add the job to the delayed list (zset) of the queue.
"""
timestamp = datetime_to_score(delayed_until)
self.delayed.zadd(timestamp, job.ident) | 0.00885 |
def _focus_tab(self, tab_idx):
"""Change tab focus"""
for i in range(self.tab_widget.count()):
self.tab_widget.setTabEnabled(i, False)
self.tab_widget.setTabEnabled(tab_idx, True)
self.tab_widget.setCurrentIndex(tab_idx) | 0.007435 |
def _asdict(self):
"""Create a dictionary snapshot of the current config values."""
# Start with any default values we have, and override with loaded values,
# and then override with flag values.
retval = {key: self._declarations[key].default_value for
key in self._declarations if self._de... | 0.003044 |
def align_orthologous_genes_pairwise(self, gapopen=10, gapextend=0.5):
"""For each gene in the base strain, run a pairwise alignment for all orthologous gene sequences to it."""
for ref_gene in tqdm(self.reference_gempro.genes):
if len(ref_gene.protein.sequences) > 1:
alignme... | 0.008646 |
def _make_standalone_handler(preamble):
"""Class factory used so that preamble can be passed to :py:class:`_StandaloneHandler`
without use of static members"""
class _StandaloneHandler(BaseHTTPRequestHandler, object):
"""HTTP Handler for standalone mode"""
def do_GET(self):
sel... | 0.002829 |
def _direct_set(self, key, value):
'''
_direct_set - INTERNAL USE ONLY!!!!
Directly sets a value on the underlying dict, without running through the setitem logic
'''
dict.__setitem__(self, key, value)
return value | 0.01087 |
def cookiestring(self):
"""Cookie string"""
return '; '.join('%s=%s' % (k, v) for k, v in self.cookies.items()) | 0.015748 |
def selections(self):
"Yields (column, lookup, value) tuples"
for key, value in self.pairs:
if '__' in key:
column, lookup = key.rsplit('__', 1)
else:
column = key
lookup = 'exact'
yield column, lookup, value | 0.006494 |
def detect_fold_level(self, prev_block, block):
"""
Perfoms fold level detection for current block (take previous block
into account).
:param prev_block: previous block, None if `block` is the first block.
:param block: block to analyse.
:return: block fold level
... | 0.001833 |
def stretch(image, mask=None):
'''Normalize an image to make the minimum zero and maximum one
image - pixel data to be normalized
mask - optional mask of relevant pixels. None = don't mask
returns the stretched image
'''
image = np.array(image, float)
if np.product(image.shape) == 0:
... | 0.000847 |
def update_claim(self, queue, claim, ttl=None, grace=None):
"""
Updates the specified claim with either a new TTL or grace period, or
both.
"""
return queue.update_claim(claim, ttl=ttl, grace=grace) | 0.008403 |
def _convert_string_to_native(value):
"""Convert a string to its native python type"""
result = None
try:
result = ast.literal_eval(str(value))
except (SyntaxError, ValueError):
# Likely a string
result = value.split(',')
return result | 0.003571 |
def margin(self, axis):
"""Return marginal value of the current slice scaled means.
This value is the the same what you would get from a single variable
(constituting a 2D cube/slice), when the "non-missing" filter of the
opposite variable would be applied. This behavior is consistent w... | 0.0018 |
async def _drain_writer(self, timeout: NumType = None) -> None:
"""
Wraps writer.drain() with error handling.
"""
if self._stream_writer is None:
raise SMTPServerDisconnected("Client not connected")
# Wrapping drain in a task makes mypy happy
drain_task = asy... | 0.003125 |
def index(self, value):
"""
Gets the index in the list for a value
"""
if self.__modified_data__ is not None:
return self.__modified_data__.index(value)
return self.__original_data__.index(value) | 0.008097 |
def pull(self, path, use_sudo=False, user=None, force=False):
"""
Fetch changes from the default remote repository and merge them.
:param path: Path of the working copy directory. This directory must exist
and be a Git working copy with a default remote to pull from.
... | 0.005801 |
def discard_plugin_preset(self):
"""
Discard the current active preset. Will release any active plugins that could have come from the old preset.
"""
if self.has_plugin_preset:
for name, plugin in list(self._active_plugins.items()):
if id(plugin) in self._prov... | 0.006452 |
def _write_results(self, db_count, output_path):
'''Write the table to the output_path directory
db_count: dict
Contains samples as entries. The value for each sample is another
dictionary with HMM as the key, and number of hits as values:
{"sample_1":{H... | 0.00818 |
def _get_uploaded_file(session, file_info, fragment_count=0):
"""
:param session: locked session (with self._session_resource as >> session <<)
:param file_info: contains file information to save or query
:param fragment_count: amount of fragments associated to the file
:return: ... | 0.005222 |
def eval_entropy(x):
"""Evaluate the entropy of the input variable.
:param x: input variable 1D
:return: entropy of x
"""
hx = 0.
sx = sorted(x)
for i, j in zip(sx[:-1], sx[1:]):
delta = j-i
if bool(delta):
hx += np.log(np.abs(delta))
hx = hx / (len(x) - 1) +... | 0.002809 |
def get(self, statediag, dfaaccepted):
"""
# - Remove all the POP (type - 2) transitions to state 0,non DFA accepted
# for symbol @closing
# - Generate the accepted transitions
- Replace DFA accepted States with a push - pop symbol and two extra states
Args:
s... | 0.002819 |
def value_to_db(self, value):
""" Returns field's single value prepared for saving into a database. """
assert isinstance(value, str)
array = value.split("-")
length = len(array) - 3
assert length >= 0
assert array[0] == 'S'
array = array[1:2] + [length, 0, 0,... | 0.006742 |
def build(target_python, requirements):
"""
Builds an APK given a target Python and a set of requirements.
"""
if not requirements:
return
testapp = 'setup_testapp_python2.py'
android_sdk_home = os.environ['ANDROID_SDK_HOME']
android_ndk_home = os.environ['ANDROID_NDK_HOME']
if t... | 0.00221 |
def compare_response_code(url, code):
'''
Compare the response code of url param with code param and returns boolean
@param url -> string e.g. http://127.0.0.1/index
@param content_type -> int e.g. 404, 500, 400 ..etc
'''
try:
response = urllib2.urlopen(url)
except HTTPError as... | 0.011765 |
def _query_ned_and_add_results_to_database(
self,
batchCount):
""" query ned and add results to database
**Key Arguments:**
- ``batchCount`` - the index number of the batch sent to NED
.. todo ::
- update key arguments values and definitions wit... | 0.002283 |
def get_output_from_pipe(self, input_file):
"""Executes an external command and get its output. The command
receives its input_file from the stdin through a pipe
:param input_file: input file
:return: output of command
"""
args = shlex.split(self.cmd)
p =... | 0.006073 |
def update_nexusport_binding(port_id, new_vlan_id):
"""Updates nexusport binding."""
if not new_vlan_id:
LOG.warning("update_nexusport_binding called with no vlan")
return
LOG.debug("update_nexusport_binding called")
session = bc.get_writer_session()
binding = _lookup_one_nexus_bindi... | 0.002193 |
def set_column(self, X, column, value):
"""Sets a column on the matrix X with the given value.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
column: `int` or `str`.
value: `np.ndarray` with shape (1,)
Returns:
`np.ndarray` or `pandas.DataFrame`... | 0.003976 |
async def _body_callback(self, h11_connection):
'''
A callback func to be supplied if the user wants to do something
directly with the response body's stream.
'''
# pylint: disable=not-callable
while True:
next_event = await self._recv_event(h11_connection)
... | 0.004246 |
def autoscale(bp, optimal=6):
"""
>>> autoscale(150000000)
20000000
>>> autoscale(97352632)
10000000
"""
slen = str(bp)
tlen = slen[0:2] if len(slen) > 1 else slen[0]
precision = len(slen) - 2 # how many zeros we need to pad?
bp_len_scaled = int(tlen) # scale bp_len to range (0... | 0.001739 |
def open(self, fnames=None):
"""Open files with the appropriate application"""
if fnames is None:
fnames = self.get_selected_filenames()
for fname in fnames:
if osp.isfile(fname) and encoding.is_text_file(fname):
self.parent_widget.sig_open_file.emit... | 0.005038 |
def backend(self, client=None):
'''The :class:`stdnet.BackendDatServer` for this instance.
It can be ``None``.
'''
session = self.session
if session:
return session.model(self).backend | 0.008197 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.