text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def to_netcdf(self, filename, compress=True):
"""Write InferenceData to file using netcdf4.
Parameters
----------
filename : str
Location to write to
compress : bool
Whether to compress result. Note this saves disk space, but may make
saving a... | 0.004292 |
def check_lazy_load_afdeling(f):
'''
Decorator function to lazy load a :class:`Afdeling`.
'''
def wrapper(self):
afdeling = self
if (getattr(afdeling, '_%s' % f.__name__, None) is None):
log.debug('Lazy loading Afdeling %d', afdeling.id)
afdeling.check_gateway()
... | 0.001618 |
def from_line(
cls, name, comes_from=None, isolated=False, options=None,
wheel_cache=None):
"""Creates an InstallRequirement from a name, which might be a
requirement, directory containing 'setup.py', filename, or URL.
"""
from pip.index import Link
if is... | 0.000678 |
def unmarkCollapsed( self ):
"""
Unmarks this splitter as being in a collapsed state, clearing any \
collapsed information.
"""
if ( not self.isCollapsed() ):
return
self._collapsed = False
self._storedSizes = None
if ( ... | 0.032415 |
def get_article_status(self, url=None, article_id=None):
"""
Send a HEAD request to the `parser` endpoint to the parser API to
get the articles status.
Returned is a `requests.Response` object. The id and status for the
article can be extracted from the `X-Article-Id` and `X-Art... | 0.002181 |
def get_fixtures(self, competition=None, team=None, timeFrame=None, matchday=None, season=None, venue=None, league=None):
""" This method gets a set of fixtures. There are several possibilities to load them. The following three main resources are available:
* competitions
* teams
... | 0.006176 |
def _makeNestedTempDir(top, seed, levels=2):
"""
Gets a temporary directory in the hierarchy of directories under a given
top directory.
This exists to avoid placing too many temporary directories under a single
top in a flat structure, which can slow down metadata updates such as
deletes on th... | 0.000728 |
def _make_df(rows):
"""Internal Method to make and clean the dataframe in preparation for sending to Parquet"""
# Make DataFrame
df = pd.DataFrame(rows).set_index('ts')
# TimeDelta Support: https://issues.apache.org/jira/browse/ARROW-835
for column in df.columns:
if(df[column].dtype == 'ti... | 0.004255 |
def driver_from_file(input_file):
"""
Guess driver from file extension.
Returns
-------
driver : string
driver name
"""
file_ext = os.path.splitext(input_file)[1].split(".")[1]
if file_ext not in _file_ext_to_driver():
raise MapcheteDriverError(
"no driver co... | 0.001608 |
def initFilter(input, filterInfo = None):
""" Initializes internal filter variables for further processing.
Returns a tuple (function to call,parameters for the filter call)
The filterInfo is a dict. Here is an example structure:
{fieldName: {'min': x,
'max': y,
'type': 'cat... | 0.013719 |
def convert_snapshot(self, shift, instruction):
"""Return converted `Snapshot`.
Args:
shift(int): Offset time.
instruction (Snapshot): snapshot instruction.
Returns:
dict: Dictionary of required parameters.
"""
command_dict = {
'na... | 0.003861 |
def fix_config(self, options):
"""
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
"""
opt = "annotation"
... | 0.005355 |
def order_percent(id_or_ins, percent, price=None, style=None):
"""
发送一个花费价值等于目前投资组合(市场价值和目前现金的总和)一定百分比现金的买/卖单,正数代表买,负数代表卖。股票的股数总是会被调整成对应的一手的股票数的倍数(1手是100股)。百分比是一个小数,并且小于或等于1(<=100%),0.5表示的是50%.需要注意,如果资金不足,该API将不会创建发送订单。
需要注意:
发送买单时,percent 代表的是期望买入股票消耗的金额(包含税费)占投资组合总权益的比例。
发送卖单时,percent 代表的是期望卖出的股票... | 0.00339 |
def sumexp_stable(data):
"""Compute the sum of exponents for a list of samples
Parameters
----------
data : array, shape=[features, samples]
A data array containing samples.
Returns
-------
result_sum : array, shape=[samples,]
The sum of exponents for each sample divided... | 0.001 |
def get_partial_word_under_cursor(self):
"""
Returns the document partial word under cursor ( From word start to cursor position ).
:return: Partial word under cursor.
:rtype: QString
"""
if not re.match(r"^\w+$", foundations.strings.to_string(self.get_previous_characte... | 0.007366 |
def get_token(username, length=20, timeout=20):
"""
Obtain an access token that can be passed to a websocket client.
"""
redis = get_redis_client()
token = get_random_string(length)
token_key = 'token:{}'.format(token)
redis.set(token_key, username)
redis.expire(token_key, timeout)
r... | 0.003021 |
def output(self, args):
'''
Print the output message.
'''
print("SensuPlugin: {}".format(' '.join(str(a) for a in args))) | 0.013072 |
def asyncPipeItembuilder(context=None, _INPUT=None, conf=None, **kwargs):
"""A source that asynchronously builds an item. Loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : asyncPipe like object (twisted Deferred iterable of items)
conf : {
'attrs': [
... | 0.001068 |
def from_series(cls, series):
"""Convert a pandas.Series into an xarray.DataArray.
If the series's index is a MultiIndex, it will be expanded into a
tensor product of one-dimensional coordinates (filling in missing
values with NaN). Thus this operation should be the inverse of the
... | 0.003802 |
def get_file_to_stream(self, stream, share_name, directory_name, file_name, **kwargs):
"""
Download a file from Azure File Share.
:param stream: A filehandle to store the file to.
:type stream: file-like object
:param share_name: Name of the share.
:type share_name: str
... | 0.003881 |
def to_OrderedDict(self, include_null=True):
"""
Convert to OrderedDict.
"""
if include_null:
return OrderedDict(self.items())
else:
items = list()
for c in self.__table__._columns:
try:
items.append((c.name,... | 0.004545 |
def restore(self):
"""Reimplemented OneColumnTree method"""
if self.current_editor is not None:
self.collapseAll()
editor_id = self.editor_ids[self.current_editor]
self.root_item_selected(self.editor_items[editor_id]) | 0.007299 |
def match_paren(self, tokens, item):
"""Matches a paren."""
match, = tokens
return self.match(match, item) | 0.015385 |
def send_password_reset_notice(user):
"""Sends the password reset notice email for the specified user.
:param user: The user to send the notice to
"""
if config_value('SEND_PASSWORD_RESET_NOTICE_EMAIL'):
_security.send_mail(config_value('EMAIL_SUBJECT_PASSWORD_NOTICE'),
... | 0.002762 |
def set_parent(self, new_site):
"""
Set self.site as either an empty string, or with a new Site.
"""
if new_site:
if not isinstance(new_site, Site):
raise Exception
self.site = new_site
self.propagate_data()
return new_site | 0.006515 |
def enable_branching_model(self, project, repository):
"""
Enable branching model by setting it with default configuration
:param project:
:param repository:
:return:
"""
default_model_data = {'development': {'refId': None, 'useDefault': True},
... | 0.002078 |
def assign_from_user(self, partitions):
"""Manually assign a list of TopicPartitions to this consumer.
This interface does not allow for incremental assignment and will
replace the previous assignment (if there was one).
Manual topic assignment through this method does not use the cons... | 0.001451 |
def load(self, dump_fn='', prep_only=0, force_upload=0, from_local=0, name=None, site=None, dest_dir=None, force_host=None):
"""
Restores a database snapshot onto the target database server.
If prep_only=1, commands for preparing the load will be generated,
but not the command to finall... | 0.006138 |
def groups_pools_getGroups():
"""Get a list of groups the auth'd user can post photos to."""
method = 'flickr.groups.pools.getGroups'
data = _doget(method, auth=True)
groups = []
if isinstance(data.rsp.groups.group, list):
for group in data.rsp.groups.group:
groups.append(Group(g... | 0.003676 |
def get_medium(self, agent_type, index=0):
'''Returns the medium class for the
given agent_type. Optional index tells which one to give.'''
mediums = list(x for x in self.agency._agents
if x.get_descriptor().type_name == agent_type)
try:
return mediums[... | 0.003448 |
def hist2d(x, y, bins=10, labels=None, aspect="auto", plot=True, fig=None, ax=None, interpolation='none', cbar=True, **kwargs):
"""
Creates a 2-D histogram of data *x*, *y* with *bins*, *labels* = :code:`[title, xlabel, ylabel]`, aspect ration *aspect*. Attempts to use axis *ax* first, then the current axis of ... | 0.007942 |
def set_is_immediate(self, value):
"""
Setter for 'is_immediate' field.
:param value - a new value of 'is_immediate' field. Must be a boolean type.
"""
if value is None:
self.__is_immediate = value
elif not isinstance(value, bool):
raise TypeError(... | 0.007335 |
def rcfile(appname, section=None, args={}, strip_dashes=True):
"""Read environment variables and config files and return them merged with
predefined list of arguments.
Parameters
----------
appname: str
Application name, used for config files and environment variable
names.
sec... | 0.00104 |
def filter(self, base_collection):
'''Yields subset of base_collection/generator based on filters.'''
for item in base_collection:
excluded = []
for (name, exclude) in self._filters:
if exclude(item):
excluded.append(name)
if exclud... | 0.004301 |
def stack_outputs(self, name):
"""
Given a name, describes CloudFront stacks and returns dict of the stack Outputs
, else returns an empty dict.
"""
try:
stack = self.cf_client.describe_stacks(StackName=name)['Stacks'][0]
return {x['OutputKey']: x['OutputV... | 0.00716 |
def save_function(self, obj, name=None):
""" Registered with the dispatch to handle all function types.
Determines what kind of function obj is (e.g. lambda, defined at
interactive prompt, etc) and handles the pickling appropriately.
"""
write = self.write
if name is None:
name = obj.__na... | 0.01506 |
def profile(func):
"""
Simple profile decorator, monitors method execution time
"""
@inlineCallbacks
def callme(*args, **kwargs):
start = time.time()
ret = yield func(*args, **kwargs)
time_to_execute = time.time() - start
log.msg('%s executed in %.3f seconds' % (func.... | 0.005128 |
def speed_difference(points):
""" Computes the speed difference between each adjacent point
Args:
points (:obj:`Point`)
Returns:
:obj:`list` of int: Indexes of changepoints
"""
data = [0]
for before, after in pairwise(points):
data.append(before.vel - after.vel)
retu... | 0.003058 |
def list_mapping(html_cleaned):
"""将预处理后的网页文档映射成列表和字典,并提取虚假标题
Keyword arguments:
html_cleaned -- 预处理后的网页源代码,字符串类型
Return:
unit_raw -- 网页文本行
init_dict -- 字典的key是索引,value是网页文本行,并按照网页文本行长度降序排序
fake_title -- 虚假标题,即网页源代码<title>中的文本... | 0.002141 |
def new_linsolver(name,prop):
"""
Creates a linear solver.
Parameters
----------
name : string
prop : string
Returns
-------
solver : :class:`LinSolver <optalg.lin_solver.LinSolver>`
"""
if name == 'mumps':
return LinSolverMUMPS(prop)
elif name == 'supe... | 0.010432 |
def other_dependancies(server, environment):
"""
Installs things that need to be in place before installing the main package
"""
print(' ** Other Dependancides, based on server', server, '**')
server = server.lower()
# Pillow is not on TestPyPI
if server is "local":
pass
elif se... | 0.00365 |
def build_parameters(request, meta, orgaMode, currentOrga):
"""Return the list of get, post and file parameters to send"""
postParameters = {}
getParameters = {}
files = {}
def update_parameters(data):
tmp_getParameters, tmp_postParameters, tmp_files = data
getParameters.update(tm... | 0.00149 |
def dashed(requestContext, seriesList, dashLength=5):
"""
Takes one metric or a wildcard seriesList, followed by a float F.
Draw the selected metrics with a dotted line with segments of length F
If omitted, the default length of the segments is 5.0
Example::
&target=dashed(server01.instan... | 0.001942 |
def _process_response(response: requests.Response, expected: list = []) -> dict:
"""
Processes an API response. Raises an exception when appropriate.
The exception that will be raised is MoneyBird.APIError. This exception is subclassed so implementing programs
can easily react appropria... | 0.003733 |
def get_previous_thumbprint(self, components=None):
"""
Returns a dictionary representing the previous configuration state.
Thumbprint is of the form:
{
component_name1: {key: value},
component_name2: {key: value},
...
}
... | 0.002047 |
def RechazarCTG(self, carta_porte, ctg, motivo):
"El Destino puede rechazar el CTG a través de la siguiente operatoria"
response = self.client.rechazarCTG(request=dict(
auth={
'token': self.Token, 'sign': self.Sign,
'cuitRep... | 0.002278 |
def cross_entropy_calc(TOP, P, POP):
"""
Calculate cross entropy.
:param TOP: test outcome positive
:type TOP : dict
:param P: condition positive
:type P : dict
:param POP: population
:type POP : dict
:return: cross entropy as float
"""
try:
result = 0
for i ... | 0.001481 |
def GetAccounts(self):
"""Return the client accounts associated with the user's manager account.
Returns:
list List of ManagedCustomer data objects.
"""
selector = {
'fields': ['CustomerId', 'CanManageClients']
}
accounts = self.client.GetService('ManagedCustomerService').get(sel... | 0.002793 |
def synchronizeReplica(self,
replicaID,
transportType="esriTransportTypeUrl",
replicaServerGen=None,
returnIdsForAdds=False,
edits=None,
returnAttachmentDatab... | 0.019716 |
def pop(self, strip=False):
"""Current content popped, useful for testing"""
r = self.contents()
self.clear()
if r and strip:
r = r.strip()
return r | 0.01 |
def load_corpus(self, path, config):
'''Load a dialogue corpus; eventually, support pickles and potentially other formats'''
# use the default dataset if no path is provided
# TODO -- change this to use a pre-saved dataset
if path == '':
path = self.default_path_to_corpus
... | 0.007874 |
def _find_feed_language(self):
"""Find feed language based specified feed_info.txt or agency.txt.
"""
self.feed_language = (
read_first_available_value(
os.path.join(self.src_dir, 'feed_info.txt'), 'feed_lang') or
read_first_available_value(
... | 0.00346 |
def flat_data(self):
"""
Function to pass our modified values to the original ones
"""
def flat_field(value):
"""
Flat item
"""
try:
value.flat_data()
return value
except AttributeError:
... | 0.006515 |
def is_on_tag(self) -> bool:
"""
:return: True if latest commit is tagged
:rtype: bool
"""
if self.get_current_tag():
LOGGER.debug('latest commit is tagged')
return True
LOGGER.debug('latest commit is NOT tagged')
return False | 0.006515 |
def wnunid(a, b):
"""
Place the union of two double precision windows into a third window.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnunid_c.html
:param a: Input window A.
:type a: spiceypy.utils.support_types.SpiceCell
:param b: Input window B.
:type b: spiceypy.utils.sup... | 0.004292 |
def camel_case(string):
"""
Converts a string to camel case. For example::
camel_case('one_two_three') -> 'oneTwoThree'
"""
if not string:
return string
parts = snake_case(string).split('_')
rv = ''
while parts:
part = parts.pop(0)
rv += part or '_'
i... | 0.002532 |
def combine_images(imgs, register=True):
"""Combine similar images into one to reduce the noise
Parameters
----------
imgs: list of 2d array
Series of images
register: Boolean, default False
True if the images should be register before combination
Returns
-------
im: 2d... | 0.001418 |
def initialize_state(self):
""" Call this to initialize the state of the UI after everything has been connected. """
if self.__hardware_source:
self.__profile_changed_event_listener = self.__hardware_source.profile_changed_event.listen(self.__update_profile_index)
self.__frame_pa... | 0.006463 |
def get_port_channel_detail_output_lacp_partner_oper_key(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_channel_detail = ET.Element("get_port_channel_detail")
config = get_port_channel_detail
output = ET.SubElement(get_port_channel_deta... | 0.003339 |
def return_period_from_string(arg):
"""
Takes a string such as "days=1,seconds=30" and strips the quotes
and returns a dictionary with the key/value pairs
"""
period = {}
if arg[0] == '"' and arg[-1] == '"':
opt = arg[1:-1] # remove quotes
else:
opt = arg
for o in opt... | 0.002364 |
def pprint(to_be_printed):
"""nicely formated print"""
try:
import pprint as pp
# generate an instance PrettyPrinter
# pp.PrettyPrinter().pprint(to_be_printed)
pp.pprint(to_be_printed)
except ImportError:
if isinstance(to_be_printed, dict):
print('{')
... | 0.001406 |
def move_distance(self, distance_x_m, distance_y_m, distance_z_m,
velocity=VELOCITY):
"""
Move in a straight line.
positive X is forward
positive Y is left
positive Z is up
:param distance_x_m: The distance to travel along the X-axis (meters)
... | 0.002791 |
def callable_name(func: Callable) -> str:
"""Return the qualified name (e.g. package.module.func) for the given callable."""
if func.__module__ == 'builtins':
return func.__name__
else:
return '{}.{}'.format(func.__module__, func.__qualname__) | 0.00738 |
def make_sloppy_codec(encoding):
"""
Take a codec name, and return a 'sloppy' version of that codec that can
encode and decode the unassigned bytes in that encoding.
Single-byte encodings in the standard library are defined using some
boilerplate classes surrounding the functions that do the actual... | 0.000341 |
def backspace_changed(self, settings, key, user_data):
"""If the gconf var compat_backspace be changed, this method
will be called and will change the binding configuration in
all terminals open.
"""
for i in self.guake.notebook_manager.iter_terminals():
i.set_backspa... | 0.007937 |
def _validate_compute_chunk_params(self,
graph,
dates,
sids,
initial_workspace):
"""
Verify that the values passed to compute_chunk are well-formed.... | 0.001572 |
def create_enrollment_term(self, account_id, enrollment_term_end_at=None, enrollment_term_name=None, enrollment_term_sis_term_id=None, enrollment_term_start_at=None):
"""
Create enrollment term.
Create a new enrollment term for the specified account.
"""
path = {}
... | 0.002836 |
def _get_rule_definition(self, rule):
"""Generates the source code for a rule."""
fmt = """def {rule_fxn_name}(self, text):
{indent}\"\"\"{rule_source}\"\"\"
{indent}self._attempting(text)
{indent}return {rule_definition}(text){transform}
"""
fmt = self._clea... | 0.005085 |
def from_bytes(SaplingTx, byte_string):
'''
byte-like -> SaplingTx
'''
header = byte_string[0:4]
group_id = byte_string[4:8]
if header != b'\x04\x00\x00\x80' or group_id != b'\x85\x20\x2f\x89':
raise ValueError(
'Bad header or group ID. Expect... | 0.000587 |
def translate_alias(self, alias, namespace=None, target_namespaces=None, translate_ncbi_namespace=None):
"""given an alias and optional namespace, return a list of all other
aliases for same sequence
"""
if translate_ncbi_namespace is None:
translate_ncbi_namespace = self.t... | 0.007062 |
def replace(self, target):
"""
Rename this path to the given path, clobbering the existing
destination if it exists.
"""
if sys.version_info < (3, 3):
raise NotImplementedError("replace() is only available "
"with Python 3.3 and l... | 0.004662 |
def loaded_modules(self):
'''The list of loaded module profile dictionaries.'''
with self._mutex:
if not self._loaded_modules:
self._loaded_modules = []
for mp in self._obj.get_loaded_modules():
self._loaded_modules.append(utils.nvlist_to_d... | 0.008 |
def _proc_no_rot_sym(self):
"""
Handles molecules with no rotational symmetry. Only possible point
groups are C1, Cs and Ci.
"""
self.sch_symbol = "C1"
if self.is_valid_op(PointGroupAnalyzer.inversion_op):
self.sch_symbol = "Ci"
self.symmops.append... | 0.003503 |
def mf_aBl(self):
"""
These are the expected log likelihoods (node potentials)
as seen from the discrete states.
"""
mf_aBl = self._mf_aBl = np.zeros((self.T, self.num_states))
ids, dds, eds = self.init_dynamics_distns, self.dynamics_distns, \
self.emission_di... | 0.006579 |
def run_display_profile(self, program_main):
"""Print profile name with programMain.
Args:
program_main (str): The executable name.
"""
install_json = self.profile.get('install_json')
output = 'Profile: '
output += '{}{}{}{} '.format(
c.Style.BRI... | 0.003319 |
def virtual_memory():
'''
.. versionadded:: 2014.7.0
Return a dict that describes statistics about system memory usage.
.. note::
This function is only available in psutil version 0.6.0 and above.
CLI Example:
.. code-block:: bash
salt '*' ps.virtual_memory
'''
if p... | 0.001927 |
def get_likes(self, offset=0, limit=50):
""" Get user's likes. """
response = self.client.get(
self.client.USER_LIKES % (self.name, offset, limit))
return self._parse_response(response, strack) | 0.008734 |
def array2bytes(arr, bytes_type=bytes):
"""Wraps NumPy's save function to return bytes.
We use :func:`numpy.save` rather than :meth:`numpy.ndarray.tobytes` because
it encodes endianness and order.
Args:
arr (:obj:`numpy.ndarray`):
Array to be saved.
bytes_type (class, opti... | 0.001302 |
def entries(self, query=None):
"""Fetches all Entries from the Space (up to the set limit, can be modified in `query`).
API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/entries/entries-collection/get-all-entries-of-a-space
:param query: (opt... | 0.00313 |
def create_hook(self, auth, repo_name, hook_type, config, events=None, organization=None, active=False):
"""
Creates a new hook, and returns the created hook.
:param auth.Authentication auth: authentication object, must be admin-level
:param str repo_name: the name of the repo for which... | 0.005671 |
def compute_consistency_score(returns_test, preds):
"""
Compute Bayesian consistency score.
Parameters
----------
returns_test : pd.Series
Observed cumulative returns.
preds : numpy.array
Multiple (simulated) cumulative returns.
Returns
-------
Consistency score
... | 0.001037 |
def add_source(self, source):
"""Connect the source to all existing other nodes."""
nodes = [n for n in self.nodes() if not isinstance(n, Source)]
source.connect(whom=nodes) | 0.010152 |
def get_dates_file(path):
""" parse dates file of dates and probability of choosing"""
with open(path) as f:
dates = f.readlines()
return [(convert_time_string(date_string.split(" ")[0]), float(date_string.split(" ")[1]))
for date_string in dates] | 0.007168 |
def _split_dimension(text):
"""
Returns the number and unit from the given piece of text as a pair.
>>> _split_dimension('1pt')
(1, 'pt')
>>> _split_dimension('1 pt')
(1, 'pt')
>>> _split_dimension('1 \tpt')
(1, 'pt')
>>> _split_dimension('1 \tpt ')
(1, 'pt')
>>> _split_d... | 0.001245 |
def _get_valid_indices(shape, ix0, ix1, iy0, iy1):
"""Give array shape and desired indices, return indices that are
correctly bounded by the shape."""
ymax, xmax = shape
if ix0 < 0:
ix0 = 0
if ix1 > xmax:
ix1 = xmax
if iy0 < 0:
iy0 = 0
if iy1 > ymax:
iy1 = ym... | 0.001972 |
def list_tables(self):
'''
Load existing tables and their descriptions.
:return:
'''
if not self._tables:
for table_name in os.listdir(self.db_path):
self._tables[table_name] = self._load_table(table_name)
return self._tables.keys() | 0.006452 |
def dropAssayFromStudy(assayNum, studyNum, pathToISATABFile):
"""
This function removes an Assay from a study in an ISA file
Typically, you should use the exploreISA function to check the contents
of the ISA file and retrieve the assay and study numbers you are interested in!
:param assayNum: The As... | 0.005917 |
def elements_to_kwargs(elements, fix_texture, image):
"""
Given an elements data structure, extract the keyword
arguments that a Trimesh object constructor will expect.
Parameters
------------
elements: OrderedDict object, with fields and data loaded
Returns
-----------
kwargs: dic... | 0.000216 |
def confd_state_ha_node_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
ha = ET.SubElement(confd_state, "ha")
node_id = ET.SubElement(ha, "node... | 0.006508 |
def search_for_devices_by_serial_number(self, sn):
"""
Returns a list of device objects that match the serial number
in param 'sn'.
This will match partial serial numbers.
"""
import re
sn_search = re.compile(sn)
matches = []
for dev... | 0.002591 |
def file_is_attached(self, url):
'''return true if at least one book has
file with the given url as attachment
'''
body = self._get_search_field('_attachments.url', url)
return self.es.count(index=self.index_name, body=body)['count'] > 0 | 0.007143 |
def makenex(assembly, names, longname, partitions):
""" PRINT NEXUS """
## make nexus output
data = iter(open(os.path.join(assembly.dirs.outfiles, assembly.name+".phy" ), 'r' ))
nexout = open(os.path.join(assembly.dirs.outfiles, assembly.name+".nex" ), 'wb' )
ntax, nchar = data.next().strip().spli... | 0.012056 |
def clean(self, py_value):
"""
Cleans the value before storing it.
:param: py_value : <str>
:return: <str>
"""
try:
from webhelpers.text import strip_tags
return strip_tags(py_value)
except ImportError:
warnings.warn('U... | 0.007353 |
def options_request(
self,
alias,
uri,
headers=None,
allow_redirects=None,
timeout=None):
""" Send an OPTIONS request on the session object found using the
given `alias`
``alias`` that will be used to identify the Session o... | 0.004264 |
def create_account_user(self, account_id, body, **kwargs): # noqa: E501
"""Create a new user. # noqa: E501
An endpoint for creating or inviting a new user to the account. In case of invitation email address is used only, other attributes are set in the 2nd step. **Example usage:** `curl -X POST htt... | 0.001378 |
def run(self):
"""
Start queueing the chain to the worker cluster
:return: the chain's group id
"""
self.group = async_chain(chain=self.chain[:], group=self.group, cached=self.cached, sync=self.sync,
broker=self.broker)
self.started = True... | 0.008671 |
def remove_sensor(self, sensor):
"""Remove a sensor from the device.
Also deregisters all clients observing the sensor.
Parameters
----------
sensor : Sensor object or name string
The sensor to remove from the device server.
"""
if isinstance(sensor... | 0.002642 |
def make_serviceitem_servicedll(servicedll, condition='contains', negate=False, preserve_case=False):
"""
Create a node for ServiceItem/serviceDLL
:return: A IndicatorItem represented as an Element node
"""
document = 'ServiceItem'
search = 'ServiceItem/serviceDLL'
content_type = 'strin... | 0.009025 |
def _parse_type_rule(ctype, typespec):
"""
Parse a content type rule. Unlike the other rules, content type
rules are more complex, since both selected content type and API
version must be expressed by one rule. The rule is split on
whitespace, then the components beginning with "type:" and
"ve... | 0.000541 |
def require(self, *requirements):
"""Ensure that distributions matching `requirements` are activated
`requirements` must be a string or a (possibly-nested) sequence
thereof, specifying the distributions and versions required. The
return value is a sequence of the distributions that nee... | 0.00314 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.