text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def add_package(self, package_item):
"""
Adds a package to the ship request.
@type package_item: WSDL object, type of RequestedPackageLineItem
WSDL object.
@keyword package_item: A RequestedPackageLineItem, created by
calling create_wsdl_object_of_type('... | 0.005634 |
def get_for_update(self, connection_name='DEFAULT', **kwargs):
"""
http://docs.sqlalchemy.org/en/latest/orm/query.html?highlight=update#sqlalchemy.orm.query.Query.with_for_update # noqa
"""
if not kwargs:
raise InvalidQueryError(
"Can not execute a query wit... | 0.003268 |
def create(name, host):
'''Create a new virtual folder.
\b
NAME: Name of a virtual folder.
HOST: Name of a virtual folder host in which the virtual folder will be created.
'''
with Session() as session:
try:
result = session.VFolder.create(name, host)
print('Virt... | 0.004396 |
def is_possible_temp(temp: str) -> bool:
"""
Returns True if all characters are digits or 'M' (for minus)
"""
for char in temp:
if not (char.isdigit() or char == 'M'):
return False
return True | 0.00431 |
def initialize_wind_turbine_cluster(example_farm, example_farm_2):
r"""
Initializes a :class:`~.wind_turbine_cluster.WindTurbineCluster` object.
Function shows how to initialize a WindTurbineCluster object. In this case
the cluster only contains two wind farms.
Parameters
----------
exampl... | 0.001232 |
def find_plugin(self, name):
"""Find a plugin named name"""
suffix = ".py"
if not self.class_name:
suffix = ""
for i in self._get_paths():
path = os.path.join(i, "%s%s" % (name, suffix))
if os.path.exists(path):
return path
retu... | 0.006116 |
def listTasks(self, opts={}, queryOpts={}):
"""
Get information about all Koji tasks.
Calls "listTasks" XML-RPC.
:param dict opts: Eg. {'state': [task_states.OPEN]}
:param dict queryOpts: Eg. {'order' : 'priority,create_time'}
:returns: deferred that when fired returns ... | 0.003003 |
def fit_texture(layer):
"""Fits a layer into a texture by scaling each axis to (0, 1).
Does not preserve aspect ratio (TODO: make this an option).
Args:
layer (layer): the layer to scale
Returns:
texture: A texture.
"""
x, y = layer
x = (x - np.nanmin(x)) / (np.nanmax(x) -... | 0.002445 |
def stats(self, **attrs):
""" Method for `Data Stream Stats <https://m2x.att.com/developer/documentation/v2/device#Data-Stream-Stats>`_ endpoint.
:param attrs: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
:return: The API response, see M2... | 0.009158 |
def _get_message(
self, target_message, indices, pending, timeout, condition):
"""
Gets the next desired message under the desired condition.
Args:
target_message (`object`):
The target message for which we want to find another
response th... | 0.000885 |
def parse_mpi(s):
"""See https://tools.ietf.org/html/rfc4880#section-3.2 for details."""
bits = s.readfmt('>H')
blob = bytearray(s.read(int((bits + 7) // 8)))
return sum(v << (8 * i) for i, v in enumerate(reversed(blob))) | 0.004219 |
def mean(name, add, match):
'''
Accept a numeric value from the matched events and store a running average
of the values in the given register. If the specified value is not numeric
it will be skipped
USAGE:
.. code-block:: yaml
foo:
reg.mean:
- add: data_field
... | 0.001684 |
def from_iso(cls, iso):
"""Retrieve the first datacenter id associated to an ISO."""
result = cls.list({'sort_by': 'id ASC'})
dc_isos = {}
for dc in result:
if dc['iso'] not in dc_isos:
dc_isos[dc['iso']] = dc['id']
return dc_isos.get(iso) | 0.006494 |
def set_iam_policy(self, policy, client=None):
"""Update the IAM policy for the bucket.
See
https://cloud.google.com/storage/docs/json_api/v1/buckets/setIamPolicy
If :attr:`user_project` is set, bills the API request to that project.
:type policy: :class:`google.api_core.iam.P... | 0.001456 |
def confd_state_snmp_version_v3(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
snmp = ET.SubElement(confd_state, "snmp")
version = ET.SubElement(... | 0.006397 |
def create_proxy_model(self, model):
"""Create a sort filter proxy model for the given model
:param model: the model to wrap in a proxy
:type model: :class:`QtGui.QAbstractItemModel`
:returns: a new proxy model that can be used for sorting and filtering
:rtype: :class:`QtGui.QAb... | 0.00381 |
def transform(self, maps):
"""This function transforms from chirp distance to luminosity distance,
given the chirp mass.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
>>> import numpy as np
... | 0.005093 |
def create(self, name, *args, **kwargs):
"""
Need to wrap the default call to handle exceptions.
"""
try:
return super(ImageMemberManager, self).create(name, *args, **kwargs)
except Exception as e:
if e.http_status == 403:
raise exc.Unshara... | 0.007426 |
def _expand_parameters(circuits, run_config):
"""Verifies that there is a single common set of parameters shared between
all circuits and all parameter binds in the run_config. Returns an expanded
list of circuits (if parameterized) with all parameters bound, and a copy of
the run_config with parameter_... | 0.00397 |
def assign_reads_to_otus(original_fasta,
filtered_fasta,
output_filepath=None,
log_name="assign_reads_to_otus.log",
perc_id_blast=0.97,
global_alignment=True,
HALT_EXEC=F... | 0.000523 |
def gallery_section(images, title):
"""Create detail section with gallery.
Args:
title (str): Title to be displayed for detail section.
images: stream of marv image files
Returns
One detail section.
"""
# pull all images
imgs = []
while True:
img = yield mar... | 0.001534 |
def find_if(pred, iterable, default=None):
"""
Returns a reference to the first element in the ``iterable`` range for
which ``pred`` returns ``True``. If no such element is found, the
function returns ``default``.
>>> find_if(lambda x: x == 3, [1, 2, 3, 4])
3
:param pred: a predica... | 0.001587 |
def solvers(config_file, profile, solver_def, list_solvers):
"""Get solver details.
Unless solver name/id specified, fetch and display details for
all online solvers available on the configured endpoint.
"""
with Client.from_config(
config_file=config_file, profile=profile, solver=solv... | 0.002843 |
def solve_spectral(prob, *args, **kwargs):
"""Solve the spectral relaxation with lambda = 1.
"""
# TODO: do this efficiently without SDP lifting
# lifted variables and semidefinite constraint
X = cvx.Semidef(prob.n + 1)
W = prob.f0.homogeneous_form()
rel_obj = cvx.Minimize(cvx.sum_entries... | 0.001982 |
def create(self, resource, uri=None, timeout=-1, custom_headers=None, default_values={}):
"""
Makes a POST request to create a resource when a request body is required.
Args:
resource:
OneView resource dictionary.
uri:
Can be either the re... | 0.00472 |
def from_raw(self, rval: RawObject, jptr: JSONPointer = "") -> ObjectValue:
"""Override the superclass method."""
if not isinstance(rval, dict):
raise RawTypeError(jptr, "object")
res = ObjectValue()
for qn in rval:
if qn.startswith("@"):
if qn != ... | 0.002291 |
def meanFracdet(map_fracdet, lon_population, lat_population, radius_population):
"""
Compute the mean fracdet within circular aperture (radius specified in decimal degrees)
lon, lat, and radius are taken to be arrays of the same length
"""
nside_fracdet = healpy.npix2nside(len(map_fracdet))
map... | 0.009991 |
def enforce_versioning(force=False):
"""Install versioning on the db."""
connect_str, repo_url = get_version_data()
LOG.warning("Your database uses an unversioned benchbuild schema.")
if not force and not ui.ask(
"Should I enforce version control on your schema?"):
LOG.error("User de... | 0.001901 |
def guess_mime_file_text (file_prog, filename):
"""Determine MIME type of filename with file(1)."""
cmd = [file_prog, "--brief", filename]
try:
output = backtick(cmd).strip()
except OSError:
# ignore errors, as file(1) is only a fallback
return None
# match output against kno... | 0.004115 |
def act(self):
"""
Power on action
"""
g = get_root(self).globals
g.clog.debug('Power on pressed')
if execCommand(g, 'online'):
g.clog.info('ESO server online')
g.cpars['eso_server_online'] = True
if not isPoweredOn(g):
... | 0.001637 |
def confirmdir(self, target_directory):
"""Test that the target is actually a directory, raising OSError
if not.
Args:
target_directory: Path to the target directory within the fake
filesystem.
Returns:
The FakeDirectory object corresponding to t... | 0.002328 |
def find(dag_id=None, run_id=None, execution_date=None,
state=None, external_trigger=None, no_backfills=False,
session=None):
"""
Returns a set of dag runs for the given search criteria.
:param dag_id: the dag_id to find dag runs for
:type dag_id: int, list
... | 0.002173 |
def get_values(abf,key="freq",continuous=False):
"""returns Xs, Ys (the key), and sweep #s for every AP found."""
Xs,Ys,Ss=[],[],[]
for sweep in range(abf.sweeps):
for AP in cm.matrixToDicts(abf.APs):
if not AP["sweep"]==sweep:
continue
Ys.append(AP[key])
... | 0.020992 |
def p_declare_list(p):
'''declare_list : STRING EQUALS static_scalar
| declare_list COMMA STRING EQUALS static_scalar'''
if len(p) == 4:
p[0] = [ast.Directive(p[1], p[3], lineno=p.lineno(1))]
else:
p[0] = p[1] + [ast.Directive(p[3], p[5], lineno=p.lineno(2))] | 0.003257 |
def _port_scan(self, port):
"""Scan the port structure (dict) and update the status key."""
if int(port['port']) == 0:
return self._port_scan_icmp(port)
else:
return self._port_scan_tcp(port) | 0.008368 |
def click_window(self, window, button):
"""
Send a click for a specific mouse button at the current mouse location.
:param window:
The window you want to send the event to or CURRENTWINDOW
:param button:
The mouse button. Generally, 1 is left, 2 is middle, 3 is
... | 0.004535 |
def flatten(arys, returns_shapes=True, hstack=np.hstack, ravel=np.ravel,
shape=np.shape):
"""
Flatten a potentially recursive list of multidimensional objects.
.. note::
Not to be confused with `np.ndarray.flatten()` (a more befitting
might be `chain` or `stack` or maybe somethin... | 0.000308 |
def splitList(self, elements, chunksnum):
""" Splits a list to a n lists with chunksnum number of elements
each one.
For a list [3,4,5,6,7,8,9] with chunksunum 4, the method
will return the following list of groups:
[[3,4,5,6],[7,8,9]]
"""
if len(e... | 0.004983 |
def path_is_remote(path, s3=True):
"""
Determine whether file path is remote or local.
Parameters
----------
path : path to file
Returns
-------
is_remote : bool
"""
prefixes = ("http://", "https://", "/vsicurl/")
if s3:
prefixes += ("s3://", "/vsis3/")
return p... | 0.002907 |
def align_times(times, frames):
"""Aligns the times to the closest frame times (e.g. beats).
Parameters
----------
times: np.ndarray
Times in seconds to be aligned.
frames: np.ndarray
Frame times in seconds.
Returns
-------
aligned_times: np.ndarray
Aligned time... | 0.002 |
def process_pc_pathsfromto(source_genes, target_genes, neighbor_limit=1,
database_filter=None):
"""Returns a BiopaxProcessor for a PathwayCommons paths-from-to query.
The paths-from-to query finds the paths from a set of source genes to
a set of target genes.
http://www.path... | 0.001852 |
def add_mutations_and_flush(self, table, muts):
"""
Add mutations to a table without the need to create and manage a batch writer.
"""
if not isinstance(muts, list) and not isinstance(muts, tuple):
muts = [muts]
cells = {}
for mut in muts:
cells.se... | 0.007109 |
def transform(self, X, y=None):
"""
Apply transforms, and transform with the final estimator
This also works where final estimator is ``None``: all prior
transformations are applied.
Parameters
----------
X : iterable
Data to transform. Must fulfill i... | 0.002212 |
def _list_records_in_zone(self, zone, rdtype=None, name=None, content=None):
"""
Iterates over all records of the zone and returns a list of records filtered
by record type, name and content. The list is empty if no records found.
"""
records = []
rrsets = zone.iterate_rd... | 0.005315 |
def uni_to(self, target, *args, **kwargs):
"""Unified to."""
logging.debug(_('target: %s, args: %s, kwargs: %s'),
target, args, kwargs)
return getattr(self, self.func_dict[target])(*args, **kwargs) | 0.00823 |
async def get_events(
self, device_ids, group_ids=None, from_time=None, to_time=None, event_types=None
):
"""Get the local installed version."""
if to_time is None:
to_time = datetime.utcnow()
if from_time is None:
from_time = to_time - timedelta(seconds=EVENT... | 0.003857 |
def activate_components_ui(self):
"""
Activates user selected Components.
:return: Method success.
:rtype: bool
:note: May require user interaction.
"""
selected_components = self.get_selected_components()
self.__engine.start_processing("Activating Com... | 0.007739 |
def ser_iuwt_recomposition(in1, scale_adjust, smoothed_array):
"""
This function calls the a trous algorithm code to recompose the input into a single array. This is the
implementation of the isotropic undecimated wavelet transform recomposition for a single CPU core.
INPUTS:
in1 (no de... | 0.010131 |
def _func(self, volume, params):
"""
Pourier-Tarantola equation from PRB 70, 224107
"""
e0, b0, b1, v0 = tuple(params)
eta = (volume / v0) ** (1. / 3.)
squiggle = -3.*np.log(eta)
return e0 + b0 * v0 * squiggle ** 2 / 6. * (3. + squiggle * (b1 - 2)) | 0.006579 |
def download_tasks_number(self):
"""获取离线任务总数
:return: int
"""
ret = self.list_download_tasks().content
foo = json.loads(ret)
return foo['total'] | 0.010363 |
def module_imports_on_top_of_file(
logical_line, indent_level, checker_state, noqa):
r"""Place imports at the top of the file.
Always put imports at the top of the file, just after any module comments
and docstrings, and before module globals and constants.
Okay: import os
Okay: # this is ... | 0.000485 |
def branch_exists(self, branch):
"""Returns true or false depending on if a branch exists"""
try:
git(self.gitdir, self.gitwd, "rev-parse", branch)
except sh.ErrorReturnCode:
return False
return True | 0.007843 |
def get_value(self, ColumnName, RunNo):
"""
Retreives the value of the collumn named ColumnName associated
with a particular run number.
Parameters
----------
ColumnName : string
The name of the desired org-mode table's collumn
RunNo : int
... | 0.007508 |
def _create_sequences(self, func, iterable, chunksize, collector=None):
"""
Create the WorkUnit objects to process and pushes them on the
work queue. Each work unit is meant to process a slice of
iterable of size chunksize. If collector is specified, then
the ApplyResult objects ... | 0.001566 |
def setup_users_page(self, ):
"""Create and set the model on the users page
:returns: None
:rtype: None
:raises: None
"""
self.users_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)
log.debug("Loading users for users page.")
roo... | 0.00561 |
async def apply(self, sender: str, recipient: str, mailbox: str,
append_msg: AppendMessage) \
-> Tuple[Optional[str], AppendMessage]:
"""Run the filter and return the mailbox where it should be appended,
or None to discard, and the message to be appended, which is usually... | 0.004292 |
def runserver(project_name):
'''
Runs a python cgi server in a subprocess.
'''
DIR = os.listdir(project_name)
if 'settings.py' not in DIR:
raise NotImplementedError('No file called: settings.py found in %s'%project_name)
CGI_BIN_FOLDER = os.path.join(project_name, 'cgi', 'cgi-bin')
CGI_FOLDER = os.path.join(... | 0.030801 |
def insert_before(self, value: Union[RawValue, Value],
raw: bool = False) -> "ArrayEntry":
"""Insert a new entry before the receiver.
Args:
value: The value of the new entry.
raw: Flag to be set if `value` is raw.
Returns:
An instance n... | 0.005245 |
def str_slice(arr, start=None, stop=None, step=None):
"""
Slice substrings from each element in the Series or Index.
Parameters
----------
start : int, optional
Start position for slice operation.
stop : int, optional
Stop position for slice operation.
step : int, optional
... | 0.001365 |
def sudo(self, password=None):
"""
Enter sudo mode
"""
if self.username == 'root':
raise ValueError('Already root user')
password = self.validate_password(password)
stdin, stdout, stderr = self.exec_command('sudo su')
stdin.write("%s\n" % password)
... | 0.004706 |
def _sanitize_entity(self, entity):
"""
Make given entity 'sane' for further use.
"""
aliases = {
"current_state": "state",
"is_flapping": "flapping",
"scheduled_downtime_depth": "in_downtime",
"has_been_checked": "checked",
"sh... | 0.00175 |
def write_meta(self):
"""ucds, descriptions and units are written as attributes in the hdf5 file, instead of a seperate file as
the default :func:`Dataset.write_meta`.
"""
with h5py.File(self.filename, "r+") as h5file_output:
h5table_root = h5file_output[self.h5table_root_n... | 0.003665 |
def do_cli(ctx, template, semantic_version):
"""Publish the application based on command line inputs."""
try:
template_data = get_template_data(template)
except ValueError as ex:
click.secho("Publish Failed", fg='red')
raise UserException(str(ex))
# Override SemanticVersion in t... | 0.005387 |
def kill(self):
"""
Send a SIGKILL to all worker processes
"""
for sock in self.workers:
os.kill(sock.pid, signal.SIGKILL)
return 'WorkerPool %s killed' % self.ctrl_url | 0.009091 |
def save(self, *args, **kwargs):
"""
**uid**: :code:`division_cycle_ballotmeasure:{number}`
"""
self.uid = '{}_{}_ballotmeasure:{}'.format(
self.division.uid,
self.election_day.uid,
self.number
)
super(BallotMeasure, self).save(*args, *... | 0.006098 |
def read(self, entity=None, attrs=None, ignore=None, params=None):
"""Ignore ``organization`` field as it's never returned by the server
and is only added to entity to be able to use organization path
dependent helpers.
"""
if ignore is None:
ignore = set()
ig... | 0.004751 |
def get_levels(dict_, n=0, levels=None):
r"""
DEPCIRATE
Args:
dict_ (dict_): a dictionary
n (int): (default = 0)
levels (None): (default = None)
CommandLine:
python -m utool.util_graph --test-get_levels --show
python3 -m utool.util_graph --test-get_levels --sho... | 0.000668 |
def leading_whitespace(self, line): # type: (str) -> str
"""
For preserving indents
:param line:
:return:
"""
string = ""
for char in line:
if char in " \t":
string += char
continue
else:
ret... | 0.005682 |
def connection_made(self, transport):
"""Method run when the UDP broadcast server is started
"""
#print('started')
self.transport = transport
sock = self.transport.get_extra_info("socket")
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(... | 0.007407 |
def thumbs_up_songs(self, *, library=True, store=True):
"""Get a listing of 'Thumbs Up' store songs.
Parameters:
library (bool, Optional): Include 'Thumbs Up' songs from library.
Default: True
generated (bool, Optional): Include 'Thumbs Up' songs from store.
Default: True
Returns:
list: Dicts o... | 0.032836 |
async def new_job(self, message: BackendNewJob):
"""
Handles a new job: starts the grading container
"""
self._logger.info("Received request for jobid %s", message.job_id)
future_results = asyncio.Future()
out = await self._loop.run_in_executor(None, lambda: self.__new_jo... | 0.008606 |
def create(self, request, *args, **kwargs):
"""Create a resource."""
self.define_contributor(request)
try:
return super().create(request, *args, **kwargs)
except IntegrityError as ex:
return Response({'error': str(ex)}, status=status.HTTP_409_CONFLICT) | 0.009677 |
def update_object(self, url, container, container_object, object_headers,
container_headers):
"""Update an existing object in a swift container.
This method will place new headers on an existing object or container.
:param url:
:param container:
:param con... | 0.004208 |
def store_config(config, suffix = None):
'''
Store configuration
args:
config (list[dict]): configurations for each project
'''
home = os.path.expanduser('~')
if suffix is not None:
config_path = os.path.join(home, '.transfer', suffix)
else:
config_path = os.path.joi... | 0.010309 |
def set_ids(self, set_image_id, image_id, set_parent_id, parent_id):
"""Changes the UUID and parent UUID for a hard disk medium.
in set_image_id of type bool
Select whether a new image UUID is set or not.
in image_id of type str
New UUID for the image. If an empty strin... | 0.006072 |
def fill_triangular(x, upper=False, name=None):
r"""Creates a (batch of) triangular matrix from a vector of inputs.
Created matrix can be lower- or upper-triangular. (It is more efficient to
create the matrix as upper or lower, rather than transpose.)
Triangular matrix elements are filled in a clockwise spira... | 0.003679 |
def prepare_gold(ctx, annotations, gout):
"""Prepare bc-evaluate gold file from annotations supplied by CHEMDNER."""
click.echo('chemdataextractor.chemdner.prepare_gold')
for line in annotations:
pmid, ta, start, end, text, category = line.strip().split('\t')
gout.write('%s\t%s:%s:%s\n' % (p... | 0.002933 |
def steam64_from_url(url, http_timeout=30):
"""
Takes a Steam Community url and returns steam64 or None
.. note::
Each call makes a http request to ``steamcommunity.com``
.. note::
For a reliable resolving of vanity urls use ``ISteamUser.ResolveVanityURL`` web api
:param url: stea... | 0.00365 |
def agitate(self):
"""Agitate this particle so that it is likely to go to a new position.
Every time agitate is called, the particle is jiggled an even greater
amount.
Parameters:
--------------------------------------------------------------
retval: None
"""
for (varName,... | 0.004975 |
def changelist(self):
"""Which :class:`.Changelist` is this revision in"""
if self._changelist:
return self._changelist
if self._p4dict['change'] == 'default':
return Default(connection=self._connection)
else:
return Changelist(str(self._p4dict['chang... | 0.005831 |
def _RunActions(self, rule, client_id):
"""Run all the actions specified in the rule.
Args:
rule: Rule which actions are to be executed.
client_id: Id of a client where rule's actions are to be executed.
Returns:
Number of actions started.
"""
actions_count = 0
for action in... | 0.0062 |
def list_create(self, title):
"""
Create a new list with the given `title`.
Returns the `list dict`_ of the created list.
"""
params = self.__generate_params(locals())
return self.__api_request('POST', '/api/v1/lists', params) | 0.010601 |
def pack_value(self, val):
"""Convert 8-byte string into 16-byte list"""
if isinstance(val, bytes):
val = list(iterbytes(val))
slen = len(val)
if self.pad:
pad = b'\0\0' * (slen % 2)
else:
pad = b''
return struct.pack('>' + 'H' * sle... | 0.00578 |
def exchange(_context, component, backend, base, name=''):
"""Handle exchange subdirectives."""
_context.action(
discriminator=('currency', 'exchange', component),
callable=_register_exchange,
args=(name, component, backend, base)
) | 0.006849 |
def etag(self, etag):
"""
Set the ETag of the resource.
:param etag: the ETag
"""
if not isinstance(etag, bytes):
etag = bytes(etag, "utf-8")
self._etag.append(etag) | 0.00885 |
def bucket_policy_to_dict(policy):
"""Produce a dictionary of read, write permissions for an existing bucket policy document"""
import json
if not isinstance(policy, dict):
policy = json.loads(policy)
statements = {s['Sid']: s for s in policy['Statement']}
d = {}
for rw in ('Read', '... | 0.003382 |
def _get_all_forecast_from_api(api_result: dict) -> OrderedDict:
"""Converts results fråm API to SmhiForeCast list"""
# Total time in hours since last forecast
total_hours_last_forecast = 1.0
# Last forecast time
last_time = None
# Need the ordered dict to get
# the days in order ... | 0.000311 |
def zmax(self, return_times=False, func=np.mean,
interp_kwargs=None, minimize_kwargs=None,
approximate=False):
"""
Estimate the maximum ``z`` height of the orbit by identifying local
maxima in the absolute value of the ``z`` position and interpolating
between ti... | 0.002418 |
def alignment(job, ids, input_args, sample):
"""
Runs BWA and then Bamsort on the supplied fastqs for this sample
Input1: Toil Job instance
Input2: jobstore id dictionary
Input3: Input arguments dictionary
Input4: Sample tuple -- contains uuid and urls for the sample
"""
uuid, urls = sa... | 0.003423 |
def ip_addresses(self):
"""
Access the ip_addresses
:returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressList
:rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressList
"""
if self._ip_addresses is None:
... | 0.00703 |
def convert_using_api(from_currency, to_currency):
""" convert from from_currency to to_currency by requesting API """
convert_str = from_currency + '_' + to_currency
options = {'compact': 'ultra', 'q': convert_str}
api_url = 'https://free.currencyconverterapi.com/api/v5/convert'
result = requests.get(api_url, par... | 0.019074 |
def joint_prop(self, properties, pic_path, num_iid, session, id=None, position=None):
'''taobao.item.joint.propimg 商品关联属性图
- 关联一张商品属性图片到num_iid指定的商品中
- 传入的num_iid所对应的商品必须属于当前会话的用户
- 图片的属性必须要是颜色的属性,这个在前台显示的时候需要和sku进行关联的
- 商品图片关联在卖家身份和图片来源上的限制,卖家要是B卖家或订购了多图服务才能关联图片,并且图片... | 0.015171 |
def trim_docstring(docstring):
"""Taken from http://www.python.org/dev/peps/pep-0257/"""
if not docstring:
return ''
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().splitlines()
# Determine minimum indentatio... | 0.001038 |
def _handleEsc(self):
""" Handler for CTRL+Z keypresses """
if self._typingSms:
self.serial.write(self.ESC_CHARACTER)
self._typingSms = False
self.inputBuffer = []
self.cursorPos = 0 | 0.00813 |
def coordinates(x0, y0, distance, angle):
""" Returns the location of a point by rotating around origin (x0,y0).
"""
return (x0 + cos(radians(angle)) * distance,
y0 + sin(radians(angle)) * distance) | 0.004425 |
def _get_cpu_info_from_sysinfo_v1():
'''
Returns the CPU info gathered from sysinfo.
Returns {} if sysinfo is not found.
'''
try:
# Just return {} if there is no sysinfo
if not DataSource.has_sysinfo():
return {}
# If sysinfo fails return {}
returncode, output = DataSource.sysinfo_cpu()
if output == ... | 0.045061 |
def circles_pycairo(width, height, color):
""" Implementation of circle border with PyCairo. """
cairo_color = color / rgb(255, 255, 255)
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
ctx = cairo.Context(surface)
# draw a circle in the center
ctx.new_path()
ctx.set_sour... | 0.002028 |
def flux_balance(model, reaction, tfba, solver):
"""Run flux balance analysis on the given model.
Yields the reaction id and flux value for each reaction in the model.
This is a convenience function for sertting up and running the
FluxBalanceProblem. If the FBA is solved for more than one parameter
... | 0.00095 |
def load(self, json_file):
"""
Build a cart from a json file
"""
cart_file = os.path.join(CART_LOCATION, json_file)
try:
cart_body = juicer.utils.read_json_document(cart_file)
except IOError as e:
juicer.utils.Log.log_error('an error occured while ... | 0.005333 |
def _find_recursive_dependencies(sql, values, code, resolved_vars, resolving_vars=None):
""" Recursive helper method for expanding variables including transitive dependencies.
Placeholders in SQL are represented as $<name>. If '$' must appear within
the SQL statement literally, then it can be escaped as '$... | 0.011322 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.