text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def is_unstructured(self):
"""A boolean for each array whether it is unstructured or not"""
return [
arr.psy.decoder.is_unstructured(arr)
if not isinstance(arr, ArrayList) else
arr.is_unstructured
for arr in self] | 0.00722 |
def get_url(url_base, tenant_id, user, password, type, region):
"""It get the url for a concrete service
:param url_base: keystone url
:param tenand_id: the id of the tenant
:param user: the user
:param paassword: the password
:param type: the type of service
:param region: the region
""... | 0.001756 |
def deny(ip,
port=None,
proto='tcp',
direction='in',
port_origin='d',
ip_origin='d',
ttl=None,
comment=''):
'''
Add an rule to csf denied hosts
See :func:`_access_rule`.
1- Deny an IP:
CLI Example:
.. code-block:: bash
salt '*' cs... | 0.018072 |
def pages(site_id):
"""Pages already crawled."""
start = int(flask.request.args.get("start", 0))
end = int(flask.request.args.get("end", start + 90))
reql = rr.table("pages").between(
[site_id, 1, r.minval], [site_id, r.maxval, r.maxval],
index="least_hops").order_by(index="least... | 0.002188 |
def proxify_elt(elt, bases=None, _dict=None, public=False):
"""Proxify input elt.
:param elt: elt to proxify.
:param bases: elt class base classes. If None, use elt type.
:param dict _dict: specific elt class content to use.
:param bool public: if True (default False), proxify only public members
... | 0.000294 |
def build(self):
"""Builds the barcode pattern from 'self.upc'
:return: The pattern as string
:rtype: String
"""
code = _upc.EDGE[:]
for i, number in enumerate(self.upc[0:6]):
code += _upc.CODES['L'][int(number)]
code += _upc.MIDDLE
for num... | 0.004556 |
def _locate_java(self, s):
'''If JAVA_HOME is in the environ, return $JAVA_HOME/bin/s. Otherwise,
return s.
'''
if 'JAVA_HOME' in self.buildozer.environ:
return join(self.buildozer.environ['JAVA_HOME'], 'bin', s)
else:
return s | 0.006873 |
def find_single_file_project(self): # type: () -> List[str]
"""
Take first non-setup.py python file. What a mess.
:return:
"""
# TODO: use package_dirs
packaged_dirs = ""
try:
# Right now only returns 1st.
packaged_dirs = self.extract_pack... | 0.002414 |
def get_state_all(self):
"""Returns all device states"""
state_dict = {}
for device in self.get_device_names().keys():
state_dict[device] = self.get_state(device)
return state_dict | 0.008929 |
def validate_multiindex(self, obj):
"""validate that we can store the multi-index; reset and return the
new object
"""
levels = [l if l is not None else "level_{0}".format(i)
for i, l in enumerate(obj.index.names)]
try:
return obj.reset_index(), leve... | 0.004167 |
def make_vertical_bar(percentage, width=1):
"""
Draws a vertical bar made of unicode characters.
:param value: A value between 0 and 100
:param width: How many characters wide the bar should be.
:returns: Bar as a String
"""
bar = ' _▁▂▃▄▅▆▇█'
percentage //= 10
percentage = int(perc... | 0.001996 |
def removed(name,
user=None,
env=None):
'''
Verify that given package is not installed.
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
try:
installed_pkgs = __salt__['cabal.list'](
user=user, installed=True, env=env)
except (C... | 0.001771 |
def get_orm_columns(cls: Type) -> List[Column]:
"""
Gets :class:`Column` objects from an SQLAlchemy ORM class.
Does not provide their attribute names.
"""
mapper = inspect(cls) # type: Mapper
# ... returns InstanceState if called with an ORM object
# http://docs.sqlalchemy.org/en/latest... | 0.001603 |
def _apply_hard_disk(unit_number, key, operation, disk_label=None, size=None,
unit='GB', controller_key=None, thin_provision=None,
eagerly_scrub=None, datastore=None, filename=None):
'''
Returns a vim.vm.device.VirtualDeviceSpec object specifying to add/edit
a virtu... | 0.000373 |
def emit(self, event, *args, **kwargs):
"""Send out an event and call it's associated functions
:param event: Name of the event to trigger
"""
for func in self._registered_events[event].values():
func(*args, **kwargs) | 0.007634 |
def run_commands(commands, # type: List[Union[str, List[str], Dict[str, Union[str, List[str]]]]]
directory, # type: str
env=None # type: Optional[Dict[str, Union[str, int]]]
): # noqa
# type: (...) -> None
"""Run list of commands."""
if env is None:
... | 0.001665 |
def symbolic_rotation_matrix(phi, theta, symbolic_psi):
"""Retourne une matrice de rotation où psi est symbolique"""
return sympy.Matrix(Rz_matrix(phi)) * sympy.Matrix(Rx_matrix(theta)) * symbolic_Rz_matrix(symbolic_psi) | 0.008772 |
def main():
'''Entry point'''
if len(sys.argv) == 1:
print("Usage: tyler [filename]")
sys.exit(0)
filename = sys.argv[1]
if not os.path.isfile(filename):
print("Specified file does not exists")
sys.exit(8)
my_tyler = Tyler(filename=filename)
while True:
... | 0.001953 |
def cublasDgemm(handle, transa, transb, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc):
"""
Matrix-matrix product for real general matrix.
"""
status = _libcublas.cublasDgemm_v2(handle,
_CUBLAS_OP[transa],
_CUBLAS_OP[transb],... | 0.004762 |
def put(self, key, value):
'''Stores the object `value` named by `key`self.
DirectoryTreeDatastore stores a directory entry.
'''
super(DirectoryTreeDatastore, self).put(key, value)
str_key = str(key)
# ignore root
if str_key == '/':
return
# retrieve directory, to add entry
... | 0.007018 |
def get_goa_gene_sets(go_annotations):
"""Generate a list of gene sets from a collection of GO annotations.
Each gene set corresponds to all genes annotated with a certain GO term.
"""
go_term_genes = OrderedDict()
term_ids = {}
for ann in go_annotations:
term_ids[ann.go_term.id] = ann.... | 0.002105 |
def _get_proto():
'''
Checks configuration to see whether the user has SSL turned on. Default is:
.. code-block:: yaml
use_ssl: True
'''
use_ssl = config.get_cloud_config_value(
'use_ssl',
get_configured_provider(),
__opts__,
search_global=False,
def... | 0.0025 |
def wrap_code(code: str, args: str = '') -> ast.Module:
"""
Compiles Python code into an async function or generator,
and automatically adds return if the function body is a single evaluation.
Also adds inline import expression support.
"""
if sys.version_info >= (3, 7):
user_code = imp... | 0.001943 |
def background_noise(self):
"""
Gaussian sigma of noise level per pixel (in counts per second)
:return: sqrt(variance) of background noise level
"""
if self._background_noise is None:
return data_util.bkg_noise(self.read_noise, self._exposure_time, self.sky_brightnes... | 0.008584 |
def read_cifar10(filename_queue):
"""Reads and parses examples from CIFAR10 data files.
Recommendation: if you want N-way read parallelism, call this function
N times. This will give you N independent Readers reading different
files & positions within those files, which will give better mixing of
examples.
... | 0.01219 |
def _get_notmuch_thread(self, tid):
"""returns :class:`notmuch.database.Thread` with given id"""
query = self.query('thread:' + tid)
try:
return next(query.search_threads())
except StopIteration:
errmsg = 'no thread with id %s exists!' % tid
raise None... | 0.00578 |
def to_ranges(lst):
"""
Convert a list of numbers to a list of ranges::
>>> numbers = [1,2,3,5,6]
>>> list(to_ranges(numbers))
[(1, 3), (5, 6)]
"""
for a, b in itertools.groupby(enumerate(lst), lambda t: t[1] - t[0]):
b = list(b)
yield b[0][1], b[-1][1] | 0.003344 |
def inspect_node_neighborhood(nlinks, msinds, node_msindex):
"""
Get information about one node in graph
:param nlinks: neighboorhood edges
:param msinds: indexes in 3d image
:param node_msindex: int, multiscale index of selected voxel
:return: node_neighboor_edges_and_weights, node_neighboor_s... | 0.001852 |
def deep(symbol=None, token='', version=''):
'''DEEP is used to receive real-time depth of book quotations direct from IEX.
The depth of book quotations received via DEEP provide an aggregated size of resting displayed orders at a price and side,
and do not indicate the size or number of individual orders a... | 0.005994 |
def compatibility_rank(self, supported):
"""Rank the wheel against the supported tags. Smaller ranks are more
compatible!
:param supported: A list of compatibility tags that the current
Python implemenation can run.
"""
preferences = []
for tag in self.compat... | 0.003333 |
def get_profile_for_user(user):
"""
Returns site-specific profile for this user. Raises
``ProfileNotConfigured`` if ``settings.ACCOUNTS_PROFILE_MODEL`` is not
set, and ``ImproperlyConfigured`` if the corresponding model can't
be found.
"""
if not hasattr(user, '_yacms_profile'):
# Ra... | 0.001312 |
def meantsubpool(d, data_read):
""" Wrapper for mean visibility subtraction in time.
Doesn't work when called from pipeline using multiprocessing pool.
"""
logger.info('Subtracting mean visibility in time...')
data_read = numpyview(data_read_mem, 'complex64', datashape(d))
tsubpart = partial(rt... | 0.005181 |
def _handle_pagerange(pagerange):
"""
Yields start and end pages from DfR pagerange field.
Parameters
----------
pagerange : str or unicode
DfR-style pagerange, e.g. "pp. 435-444".
Returns
-------
start : str
Start page.
end : str
End page.
"""
try:... | 0.007843 |
def calc_run(request):
"""
Run a calculation.
:param request:
a `django.http.HttpRequest` object.
If the request has the attribute `hazard_job_id`, the results of the
specified hazard calculations will be re-used as input by the risk
calculation.
The request also nee... | 0.000571 |
def __button_action(self, data=None):
"""Button action event"""
if any(not x for x in (self._ename.value, self._p1.value, self._p2.value, self._file.value)):
print("Missing one of the required fields (event name, player names, file name)")
return
self.__p1chars = []
... | 0.002425 |
def _unbytes(bytestr):
"""
Returns a bytestring from the human-friendly string returned by `_bytes`.
>>> _unbytes('123456')
'\x12\x34\x56'
"""
return ''.join(chr(int(bytestr[k:k + 2], 16))
for k in range(0, len(bytestr), 2)) | 0.003731 |
def reset_default_props(**kwargs):
"""Reset properties to initial cycle point"""
global _DEFAULT_PROPS
pcycle = plt.rcParams['axes.prop_cycle']
_DEFAULT_PROPS = {
'color': itertools.cycle(_get_standard_colors(**kwargs))
if len(kwargs) > 0 else itertools.cycle([x['color'] for x in pcycle]... | 0.002212 |
def show_instances(server, cim_class):
"""
Display the instances of the CIM_Class defined by cim_class. If the
namespace is None, use the interop namespace. Search all namespaces for
instances except for CIM_RegisteredProfile
"""
if cim_class == 'CIM_RegisteredProfile':
for inst in serve... | 0.001079 |
def calculate_correlations(tetra_z):
"""Returns dataframe of Pearson correlation coefficients.
- tetra_z - dictionary of Z-scores, keyed by sequence ID
Calculates Pearson correlation coefficient from Z scores for each
tetranucleotide. This is done longhand here, which is fast enough,
but for robus... | 0.001271 |
def canonical_circulation(elements: T, key: Optional[Callable[[T], bool]] = None) -> T:
"""Get get a canonical representation of the ordered collection by finding its minimum circulation with the
given sort key
"""
return min(get_circulations(elements), key=key) | 0.010791 |
def read(self, file, nbytes):
"""Read nbytes characters from file while running Tk mainloop"""
if not capable.OF_GRAPHICS:
raise RuntimeError("Cannot run this command without graphics")
if isinstance(file, int):
fd = file
else:
# Otherwise, assume we h... | 0.006984 |
def bind_unix_socket(path):
""" Returns a unix file socket bound on (path). """
assert path
bindsocket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
os.unlink(path)
except OSError:
if os.path.exists(path):
raise
try:
bindsocket.bind(path)
excep... | 0.001996 |
def evdev_device(self):
"""
Return our corresponding evdev device object
"""
devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()]
for device in devices:
if device.name == self.evdev_device_name:
return device
raise Exception("%s: ... | 0.007752 |
def approle_token(vault_client, role_id, secret_id):
"""Returns a vault token based on the role and seret id"""
resp = vault_client.auth_approle(role_id, secret_id)
if 'auth' in resp and 'client_token' in resp['auth']:
return resp['auth']['client_token']
else:
raise aomi.exceptions.AomiC... | 0.002865 |
def determineFrom(cls, challenge, password):
"""
Create a nonce and use it, along with the given challenge and password,
to generate the parameters for a response.
@return: A C{dict} suitable to be used as the keyword arguments when
calling this command.
"""
... | 0.004367 |
def is_readable(value, **kwargs):
"""Indicate whether ``value`` is a readable file.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the readability of a file *before* attempting to read it
exposes your code to a bug called
`TOCTOU ... | 0.003253 |
def attach(self, container_id=None, sudo=False):
'''attach to a container instance based on container_id
Parameters
==========
container_id: the container_id to delete
sudo: whether to issue the command with sudo (or not)
a container started with sudo will belong to the roo... | 0.00111 |
def metadata(self, file_path, params=None):
"""
:params:
title: string
keywords: array
extra_metadata: array
temporal_coverage: coverage object
spatial_coverage: coverage object
:return:
file metadata object (200 ... | 0.008395 |
def send(self, fail_silently=False):
"""
Sends the sms message
"""
if not self.to:
# Don't bother creating the connection if there's nobody to send to
return 0
res = self.get_connection(fail_silently).send_messages([self])
sms_post_send.send(sender... | 0.007481 |
def collect_yarn_application_diagnostics(self, *application_ids):
"""
DEPRECATED: use create_yarn_application_diagnostics_bundle on the Yarn service. Deprecated since v10.
Collects the Diagnostics data for Yarn applications.
@param application_ids: An array of strings containing the ids of the
... | 0.008741 |
def pOparapar(self,Opar,apar,tdisrupt=None):
"""
NAME:
pOparapar
PURPOSE:
return the probability of a given parallel (frequency,angle) offset pair
INPUT:
Opar - parallel frequency offset (array) (can be Quantity)
apar - parallel angle off... | 0.021944 |
def weakref_proxy(obj):
"""returns either a weakref.proxy for the object, or if object is already a proxy,
returns itself."""
if type(obj) in weakref.ProxyTypes:
return obj
else:
return weakref.proxy(obj) | 0.008475 |
def determine_version(self, request, *args, **kwargs):
"""
If versioning is being used, then determine any API version for the
incoming request. Returns a two-tuple of (version, versioning_scheme)
"""
if self.versioning_class is None:
return (None, None)
schem... | 0.004728 |
def append_vobject(self, vtodo, project=None):
"""Add a task from vObject to Taskwarrior
vtodo -- the iCalendar to add
project -- the project to add (see get_filesnames() as well)
"""
if project:
project = basename(project)
return self.to_task(vtodo.vtodo, pro... | 0.006154 |
def repopulateWinowMenu(self, actionGroup):
""" Clear the window menu and fills it with the actions of the actionGroup
"""
for action in self.windowMenu.actions():
self.windowMenu.removeAction(action)
for action in actionGroup.actions():
self.windowMenu.addAction... | 0.009146 |
def ListChildren(self, limit=None, age=NEWEST_TIME):
"""Yields RDFURNs of all the children of this object.
Args:
limit: Total number of items we will attempt to retrieve.
age: The age of the items to retrieve. Should be one of ALL_TIMES,
NEWEST_TIME or a range in microseconds.
Yields:
... | 0.007599 |
def argsort(*args, **kwargs):
"""
like np.argsort but for lists
Args:
*args: multiple lists to sort by
**kwargs:
reverse (bool): sort order is descending if True else acscending
CommandLine:
python -m utool.util_list argsort
Example:
>>> # DISABLE_DOCTE... | 0.001274 |
def _load_site_scons_dir(topdir, site_dir_name=None):
"""Load the site_scons dir under topdir.
Prepends site_scons to sys.path, imports site_scons/site_init.py,
and prepends site_scons/site_tools to default toolpath."""
if site_dir_name:
err_if_not_found = True # user specified: err if mis... | 0.001481 |
def query_recent(num=8, **kwargs):
'''
query recent posts.
'''
order_by_create = kwargs.get('order_by_create', False)
kind = kwargs.get('kind', None)
if order_by_create:
if kind:
recent_recs = TabPost.select().where(
(TabPos... | 0.001698 |
def _evolve(self, state, qargs=None):
"""Evolve a quantum state by the operator.
Args:
state (QuantumState): The input statevector or density matrix.
qargs (list): a list of QuantumState subsystem positions to apply
the operator on.
Returns:
... | 0.001768 |
def find_triangles(self):
"""
Finds all the triangles present in the given model
Examples
--------
>>> from pgmpy.models import MarkovModel
>>> from pgmpy.factors.discrete import DiscreteFactor
>>> from pgmpy.inference import Mplp
>>> mm = MarkovModel()
... | 0.003425 |
def new_crew_member(self, program, role, fullname, givenname, surname):
"""Callback run for each new crew member entry. 'fullname' is a
derived full-name, based on the presence of 'givenname' and/or
'surname'.
"""
if self.__v_crew_member:
# [Crew: EP000036710112, Ac... | 0.007335 |
def detectOperaMobile(self):
"""Return detection of an Opera browser for a mobile device
Detects Opera Mobile or Opera Mini.
"""
return UAgentInfo.engineOpera in self.__userAgent \
and (UAgentInfo.mini in self.__userAgent
or UAgentInfo.mobi in self.__userAgen... | 0.009317 |
def extinction_query(lon, lat,
coordtype='equatorial',
sizedeg=5.0,
forcefetch=False,
cachedir='~/.astrobase/dust-cache',
verbose=True,
timeout=10.0,
jitter=5.0):
'''Thi... | 0.003946 |
def predict(self, quadruplets):
"""Predicts the ordering between sample distances in input quadruplets.
For each quadruplet, returns 1 if the quadruplet is in the right order (
first pair is more similar than second pair), and -1 if not.
Parameters
----------
quadruplets : array-like, shape=(n... | 0.000965 |
def _update_limits_from_api(self):
"""
Call the service's API action to retrieve limit/quota information, and
update AwsLimit objects in ``self.limits`` with this information.
"""
logger.debug('Setting DirectoryService limits from API')
self.connect()
resp = self.... | 0.002558 |
def add(x1, x2, output_shape=None, name=None):
"""Binary addition with broadcsting.
Args:
x1: a Tensor
x2: a Tensor
output_shape: an optional Shape
name: an optional string
Returns:
a Tensor
"""
output_shape = convert_to_shape(output_shape)
if not isinstance(x2, Tensor):
return Scal... | 0.008432 |
def extreme_temperature_range(tasmax, tasmin, freq='YS'):
r"""Extreme intra-period temperature range.
The maximum of max temperature (TXx) minus the minimum of min temperature (TNn) for the given time period.
Parameters
----------
tasmax : xarray.DataArray
Maximum daily temperature values [℃... | 0.00381 |
def parse_headers(self, http_code):
""" Parse http-code (like 'Header-X: foo\r\nHeader-Y: bar\r\n') and retrieve (save) HTTP-headers
:param http_code: code to parse
:return: None
"""
if self.__ro_flag:
raise RuntimeError('Read-only object changing attempt')
self.__headers = WHTTPHeaders.import_headers(h... | 0.030395 |
def gateways_info():
"""Returns gateways data.
"""
data = netifaces.gateways()
results = {'default': {}}
with suppress(KeyError):
results['ipv4'] = data[netifaces.AF_INET]
results['default']['ipv4'] = data['default'][netifaces.AF_INET]
with suppress(KeyError):
results['i... | 0.002247 |
def rpccall(pvname, request=None, rtype=None):
"""Decorator marks a client proxy method.
:param str pvname: The PV name, which will be formated using the 'format' argument of the proxy class constructor.
:param request: A pvRequest string or :py:class:`p4p.Value` passed to eg. :py:meth:`p4p.client.thread.C... | 0.004785 |
def _task_idle_ticks(seconds_per_cycle):
""" 计算下次周期的沉睡时间 """
t = time_ticks()
while True:
t += seconds_per_cycle
yield max(t - time_ticks(), 0) | 0.011628 |
def wsgi_middleware(self, app, cors=False):
"""WSGI middlewares that wraps the given ``app`` and serves
actual image files. ::
fs_store = HttpExposedFileSystemStore('userimages', 'images/')
app = fs_store.wsgi_middleware(app)
:param app: the wsgi app to wrap
:ty... | 0.004211 |
def dset_copy(dset,to_dir):
'''robust way to copy a dataset (including AFNI briks)'''
if nl.is_afni(dset):
dset_strip = re.sub(r'\.(HEAD|BRIK)?(\.(gz|bz))?','',dset)
for dset_file in [dset_strip + '.HEAD'] + glob.glob(dset_strip + '.BRIK*'):
if os.path.exists(dset_file):
... | 0.019784 |
def _traverse_repos(self, callback, repo_name=None):
'''
Traverse through all repo files and apply the functionality provided in
the callback to them
'''
repo_files = []
if os.path.exists(self.opts['spm_repos_config']):
repo_files.append(self.opts['spm_repos_c... | 0.003481 |
def notify_update_image(self, x, y, width, height, image):
"""Informs about an update and provides 32bpp bitmap.
in x of type int
in y of type int
in width of type int
in height of type int
in image of type str
Array with 32BPP image data.
"""
... | 0.004132 |
def get_deploy_data(self):
'''
Gets any default data attached to the current deploy, if any.
'''
if self.state and self.state.deploy_data:
return self.state.deploy_data
return {} | 0.008621 |
def trim_sample(data):
"""Trim from a sample with the provided trimming method.
Support methods: read_through.
"""
data = utils.to_single_data(data)
trim_reads = dd.get_trim_reads(data)
# this block is to maintain legacy configuration files
if not trim_reads:
logger.info("Skipping tr... | 0.001543 |
def std_check_in(dataset, name, allowed_vals):
"""
Returns 0 if attr not present, 1 if present but not in correct value, 2 if good
"""
if not hasattr(dataset, name):
return 0
ret_val = 1
if getattr(dataset, name) in allowed_vals:
ret_val += 1
return ret_val | 0.006601 |
def _generate_G_points(self, kpoint):
"""
Helper function to generate G-points based on nbmax.
This function iterates over possible G-point values and determines
if the energy is less than G_{cut}. Valid values are appended to
the output array. This function should not be called... | 0.002412 |
def spatial_clip(catalog, corners, mindepth=None, maxdepth=None):
"""
Clip the catalog to a spatial box, can be irregular.
Can only be irregular in 2D, depth must be between bounds.
:type catalog: :class:`obspy.core.catalog.Catalog`
:param catalog: Catalog to clip.
:type corners: :class:`matpl... | 0.000655 |
def organization_tags(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/tags#show-tags"
api_path = "/api/v2/organizations/{id}/tags.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | 0.007663 |
def envs(backend=None, sources=False):
'''
Return the available fileserver environments. If no backend is provided,
then the environments for all configured backends will be returned.
backend
Narrow fileserver backends to a subset of the enabled ones.
.. versionchanged:: 2015.5.0
... | 0.000859 |
def main():
"""
Main function.
"""
msg = ''
try:
songs = parse_argv()
if not songs:
msg = 'No songs specified'
except ValueError as error:
msg = str(error)
if msg:
logger.error('%s: Error: %s', sys.argv[0], msg)
return 1
logger.debug('... | 0.002165 |
def no_duplicates_sections2d(sections2d, prt=None):
"""Check for duplicate header GO IDs in the 2-D sections variable."""
no_dups = True
ctr = cx.Counter()
for _, hdrgos in sections2d:
for goid in hdrgos:
ctr[goid] += 1
for goid, cnt in ctr.most_common():
if cnt == 1:
... | 0.004065 |
def set_harddisk_sleep(minutes):
'''
Set the amount of idle time until the harddisk sleeps. Pass "Never" of "Off"
to never sleep.
:param minutes: Can be an integer between 1 and 180 or "Never" or "Off"
:ptype: int, str
:return: True if successful, False if not
:rtype: bool
CLI Example... | 0.002849 |
def launch_satellite(cli):
"""Deploys a new satellite app over any existing app"""
cli.info("Launching skypipe satellite:")
finish = wait_for(" Pushing to dotCloud")
# destroy any existing satellite
destroy_satellite(cli)
# create new satellite app
url = '/applications'
try:
... | 0.007173 |
def attach(self, id, filename, url):
"""Add an attachmemt to record from url
:param id: ID of record
:param filename: File name of attachment
:param url: Public url to download file from.
"""
Attachment = self.client.model('ir.attachment')
return Attachment.add_a... | 0.004902 |
def create(model_config, epochs, optimizer, model, source, storage, scheduler=None, callbacks=None, max_grad_norm=None):
""" Vel factory function """
return SimpleTrainCommand(
epochs=epochs,
model_config=model_config,
model_factory=model,
optimizer_factory=optimizer,
sch... | 0.00431 |
def is_url(name):
"""Returns true if the name looks like a URL"""
if ':' not in name:
return False
scheme = name.split(':', 1)[0].lower()
return scheme in ['http', 'https', 'file', 'ftp'] + vcs.all_schemes | 0.004367 |
def validate_configuration(self):
""" Runs :meth:`arca.DockerBackend.validate_configuration` and checks extra:
* ``box`` format
* ``provider`` format
* ``use_registry_name`` is set and ``registry_pull_only`` is not enabled.
"""
super().validate_configuration()
i... | 0.005981 |
def set_variable(self, name, expression_or_value, write=True):
"""Set the variable to an expression or value defined by expression_or_value.
Example
>>> df.set_variable("a", 2.)
>>> df.set_variable("b", "a**2")
>>> df.get_variable("b")
'a**2'
>>> df.evaluate_var... | 0.005505 |
def subscribe(self, feedUrl):
"""
Adds a feed to the top-level subscription list
Ubscribing seems idempotent, you can subscribe multiple times
without error
returns True or throws HTTPError
"""
response = self.httpPost(
ReaderUrl.SUBSCRIPTION_EDIT_UR... | 0.005837 |
async def enable(self, reason=None):
"""Resumes normal operation
Parameters:
reason (str): Reason of enabling
Returns:
bool: ``True`` on success
"""
params = {"enable": False, "reason": reason}
response = await self._api.put("/v1/agent/maintenance... | 0.005333 |
def from_abinit_ixc(cls, ixc):
"""Build the object from Abinit ixc (integer)"""
ixc = int(ixc)
if ixc >= 0:
return cls(**cls.abinitixc_to_libxc[ixc])
else:
# libxc notation employed in Abinit: a six-digit number in the form XXXCCC or CCCXXX
#ixc = str(... | 0.010014 |
def filter_(input_, filename='<internal>', state='INITIAL'):
""" Filter the input string thought the preprocessor.
result is appended to OUTPUT global str
"""
global CURRENT_DIR
prev_dir = CURRENT_DIR
CURRENT_FILE.append(filename)
CURRENT_DIR = os.path.dirname(CURRENT_FILE[-1])
LEXER.in... | 0.002088 |
def keywords(self) -> Set[str]:
"""A set of all keywords of all handled devices.
In addition to attribute access via device names, |Nodes| and
|Elements| objects allow for attribute access via keywords,
allowing for an efficient search of certain groups of devices.
Let us use th... | 0.000868 |
def load_transport(self, url):
'''
For remote communication. Sets the communication dispatcher of the host
at the address and port specified.
The scheme must be http if using a XMLRPC dispatcher.
amqp for RabbitMQ communications.
This methos is internal. Automatically c... | 0.002049 |
def structureChunk(keywords, resultDict, lines):
"""
Parse Weir and Culvert Structures Method
"""
chunks = pt.chunk(keywords, lines)
# Parse chunks associated with each key
for key, chunkList in iteritems(chunks):
# Parse each chunk in the chunk list
for chunk in chunkList:
... | 0.001742 |
def _login(self):
"""
Login using username / password and get the first auth token
"""
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json"
}
url = self.api_base_url + "account/directlogin"
data = ... | 0.001942 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.