code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _ParseFSMState(self, template):
"""Extracts State and associated Rules from body of template file.
After the Value definitions the remainder of the template is
state definitions. The routine is expected to be called iteratively
until no more states remain - indicated by returning None.
The rou... | Extracts State and associated Rules from body of template file.
After the Value definitions the remainder of the template is
state definitions. The routine is expected to be called iteratively
until no more states remain - indicated by returning None.
The routine checks that the state names are a well... |
def keygen(get_keyring=get_keyring):
"""Generate a public/private key pair."""
WheelKeys, keyring = get_keyring()
ed25519ll = signatures.get_ed25519ll()
wk = WheelKeys().load()
keypair = ed25519ll.crypto_sign_keypair()
vk = native(urlsafe_b64encode(keypair.vk))
sk = native(urlsafe_b64enco... | Generate a public/private key pair. |
def apply(self, data):
""" Applies calibration solution to data array. Assumes structure of (nint, nbl, nch, npol).
"""
# flag bad ants
if self.flagants:
badants = self.calc_flag()
else:
badants = n.array([[]])
# apply gain correction
if ... | Applies calibration solution to data array. Assumes structure of (nint, nbl, nch, npol). |
def linear_regression(self):
""" Linear Regression.
This function runs linear regression and stores the,
1. Model
2. Model name
3. Mean score of cross validation
4. Metrics
"""
model = LinearRegression()
scores = []
kfold = KFold(n_sp... | Linear Regression.
This function runs linear regression and stores the,
1. Model
2. Model name
3. Mean score of cross validation
4. Metrics |
def autosolve(equation):
"""
Automatically solve an easy maths problem.
:type equation: string
:param equation: The equation to calculate.
>>> autosolve("300 + 600")
900
"""
try:
# Try to set a variable to an integer
num1 = int(equation.split(" ")[0])
except Value... | Automatically solve an easy maths problem.
:type equation: string
:param equation: The equation to calculate.
>>> autosolve("300 + 600")
900 |
def draw_math(str, x, y, alpha=1.0):
""" Uses mimetex to generate a GIF-image from the LaTeX equation.
"""
try: from web import _ctx
except: pass
str = re.sub("</{0,1}math>", "", str.strip())
img = mimetex.gif(str)
w, h = _ctx.imagesize(img)
_ctx.image(img, x, y, alpha=alp... | Uses mimetex to generate a GIF-image from the LaTeX equation. |
def row(self, content='', align='left'):
"""
A row of the menu, which comprises the left and right verticals plus the given content.
Returns:
str: A row of this menu component with the specified content.
"""
return u"{lm}{vert}{cont}{vert}".format(lm=' ' * self.margi... | A row of the menu, which comprises the left and right verticals plus the given content.
Returns:
str: A row of this menu component with the specified content. |
def pending(self):
'''
600 废单 未委托成功
200 委托成功,完全交易
203 委托成功,未完全成功
300 委托队列 待成交
400 已撤单
500 服务器撤单/每日结算
订单生成(100) -- 废单(600)
订单生成(100) -- 进入待成交队列(300) -- 完全成交(200) -- 每日结算(500)-- 死亡
订单生成(100) -- 进入待成交队列(300) -- 部分成交(203) -- 未成交(300) -- 每日结算(... | 600 废单 未委托成功
200 委托成功,完全交易
203 委托成功,未完全成功
300 委托队列 待成交
400 已撤单
500 服务器撤单/每日结算
订单生成(100) -- 废单(600)
订单生成(100) -- 进入待成交队列(300) -- 完全成交(200) -- 每日结算(500)-- 死亡
订单生成(100) -- 进入待成交队列(300) -- 部分成交(203) -- 未成交(300) -- 每日结算(500) -- 死亡
订单生成(100) -- 进入待成交队列... |
def prompt(youtube_list):
'''
Prompts for song number from list of songs
'''
option = int(input('\nEnter song number > '))
try:
song_url = list(youtube_list.values())[option - 1]
song_title = list(youtube_list.keys())[option - 1]
except IndexError:
log.log_error('Invalid... | Prompts for song number from list of songs |
def case_study_social_link_facebook(value):
"""
Confirms that the social media url is pointed at the correct domain.
Args:
value (string): The url to check.
Raises:
django.forms.ValidationError
"""
parsed = parse.urlparse(value.lower())
if not parsed.netloc.endswith('face... | Confirms that the social media url is pointed at the correct domain.
Args:
value (string): The url to check.
Raises:
django.forms.ValidationError |
def _set_bd_ip_igmp(self, v, load=False):
"""
Setter method for bd_ip_igmp, mapped from YANG variable /bridge_domain/ip/bd_ip_igmp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bd_ip_igmp is considered as a private
method. Backends looking to populate t... | Setter method for bd_ip_igmp, mapped from YANG variable /bridge_domain/ip/bd_ip_igmp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bd_ip_igmp is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set... |
def lsf(self, astr_path=""):
"""
List only the "files" in the astr_path.
:param astr_path: path to list
:return: "files" in astr_path, empty list if no files
"""
d_files = self.ls(astr_path, nodes=False, data=True)
l_files = d_files.ke... | List only the "files" in the astr_path.
:param astr_path: path to list
:return: "files" in astr_path, empty list if no files |
def init_distributed(cuda):
"""
Initializes distributed backend.
:param cuda: (bool) if True initializes nccl backend, if False initializes
gloo backend
"""
world_size = int(os.environ.get('WORLD_SIZE', 1))
distributed = (world_size > 1)
if distributed:
backend = 'nccl' if c... | Initializes distributed backend.
:param cuda: (bool) if True initializes nccl backend, if False initializes
gloo backend |
def load_python_bindings(python_input):
"""
Custom key bindings.
"""
bindings = KeyBindings()
sidebar_visible = Condition(lambda: python_input.show_sidebar)
handle = bindings.add
@handle('c-l')
def _(event):
"""
Clear whole screen and render again -- also when the sideb... | Custom key bindings. |
def getLinearityFunction(expTimes, imgs, mxIntensity=65535, min_ascent=0.001,
):
'''
returns offset, ascent
of image(expTime) = offset + ascent*expTime
'''
# TODO: calculate [min_ascent] from noise function
# instead of having it as variable
ascent, offset... | returns offset, ascent
of image(expTime) = offset + ascent*expTime |
def compare_vals(cls, sort=True):
"""Return this class's attribute values (those not stating with '_'),
but only for attributes with `compare` set to `True`.
Returns
-------
_compare_vals : list of objects
List of values of internal attributes to use when comparing
... | Return this class's attribute values (those not stating with '_'),
but only for attributes with `compare` set to `True`.
Returns
-------
_compare_vals : list of objects
List of values of internal attributes to use when comparing
`CatDict` objects. Order sorted by... |
def check_migrations_applied(migrate):
"""
A built-in check to see if all migrations have been applied correctly.
It's automatically added to the list of Dockerflow checks if a
`flask_migrate.Migrate <https://flask-migrate.readthedocs.io/>`_ object
is passed to the :class:`~dockerflow.flask.app.Doc... | A built-in check to see if all migrations have been applied correctly.
It's automatically added to the list of Dockerflow checks if a
`flask_migrate.Migrate <https://flask-migrate.readthedocs.io/>`_ object
is passed to the :class:`~dockerflow.flask.app.Dockerflow` class during
instantiation, e.g.::
... |
def _convert_input(self, *args, **kwargs):
""" Takes variable inputs
:param args: (dict, Nomenclate), any number of dictionary inputs or Nomenclates to be converted to dicts
:param kwargs: str, any number of kwargs that represent token:value pairs
:return: dict, combined dictionary of a... | Takes variable inputs
:param args: (dict, Nomenclate), any number of dictionary inputs or Nomenclates to be converted to dicts
:param kwargs: str, any number of kwargs that represent token:value pairs
:return: dict, combined dictionary of all inputs |
def join(self):
'''Waits until all there are no processes enqueued.'''
while True:
with self._processes_lock:
if not self._processes and self._processing_semaphore.locked():
return True
gevent.sleep(0.1) | Waits until all there are no processes enqueued. |
def all(self, workflow_id):
"""
Get information about subscribers who were removed from an Automation
workflow.
:param workflow_id: The unique id for the Automation workflow.
:type workflow_id: :py:class:`str`
"""
self.workflow_id = workflow_id
return sel... | Get information about subscribers who were removed from an Automation
workflow.
:param workflow_id: The unique id for the Automation workflow.
:type workflow_id: :py:class:`str` |
def plot_probability_alive_matrix(
model,
max_frequency=None,
max_recency=None,
title="Probability Customer is Alive,\nby Frequency and Recency of a Customer",
xlabel="Customer's Historical Frequency",
ylabel="Customer's Recency",
**kwargs
):
"""
Plot probability alive matrix as heat... | Plot probability alive matrix as heatmap.
Plot a figure of the probability a customer is alive based on their
frequency and recency.
Parameters
----------
model: lifetimes model
A fitted lifetimes model.
max_frequency: int, optional
The maximum frequency to plot. Default is max... |
def python_object_name(item, module=True):
"""takes a python object and returns its import path.
:param item: the source object
:param module: bool - defaults to ``True`` - whether the object name should be prefixed by its module name.
"""
if not isinstance(item, type):
return python_object_... | takes a python object and returns its import path.
:param item: the source object
:param module: bool - defaults to ``True`` - whether the object name should be prefixed by its module name. |
def start(self, interval, now=True):
"""Start running pre-set function every interval seconds.
"""
if interval < 0:
raise ValueError('interval must be >= 0')
if self._running:
self.stop()
self._running = True
self._interval = interval
if ... | Start running pre-set function every interval seconds. |
def read(self, file):
"""Reads the captions file."""
content = self._read_content(file)
self._validate(content)
self._parse(content)
return self | Reads the captions file. |
def color(self, x, y, paint_method):
"""
:param paint_method: 'point' or 'replace' or 'floodfill' or
'filltoborder' or 'reset'
:type paint_method: str or pgmagick.PaintMethod
"""
paint_method = _convert_paintmethod(paint_method)
color = pgmagi... | :param paint_method: 'point' or 'replace' or 'floodfill' or
'filltoborder' or 'reset'
:type paint_method: str or pgmagick.PaintMethod |
def get_dev_alarms(devId, auth=auth.creds, url=auth.url):
"""
function takes the devId of a specific device and issues a RESTFUL call to get the current alarms for the target
device.
:param devId: int or str value of the target device
:return:list of dictionaries containing the alarms for this devic... | function takes the devId of a specific device and issues a RESTFUL call to get the current alarms for the target
device.
:param devId: int or str value of the target device
:return:list of dictionaries containing the alarms for this device |
def _handle_message(self, tags, source, command, target, msg):
"""Construct the correct events and handle them
:param tags: the tags of the message
:type tags: :class:`list` of :class:`message.Tag`
:param source: the sender of the message
:type source: :class:`str`
:para... | Construct the correct events and handle them
:param tags: the tags of the message
:type tags: :class:`list` of :class:`message.Tag`
:param source: the sender of the message
:type source: :class:`str`
:param command: the event type
:type command: :class:`str`
:par... |
def LoadFromString(yaml_doc, product_yaml_key, required_client_values,
optional_product_values):
"""Loads the data necessary for instantiating a client from file storage.
In addition to the required_client_values argument, the yaml file must supply
the keys used to create OAuth2 credentials. I... | Loads the data necessary for instantiating a client from file storage.
In addition to the required_client_values argument, the yaml file must supply
the keys used to create OAuth2 credentials. It may also optionally set proxy
configurations.
Args:
yaml_doc: the yaml document whose keys should be used.
... |
def product_status(request, form):
''' Summarises the inventory status of the given items, grouping by
invoice status. '''
products = form.cleaned_data["product"]
categories = form.cleaned_data["category"]
items = commerce.ProductItem.objects.filter(
Q(product__in=products) | Q(product__ca... | Summarises the inventory status of the given items, grouping by
invoice status. |
def _freeze(self) -> OrderedDict:
"""
Evaluate all of the column values and return the result
:return: column/value tuples
"""
return OrderedDict(**{k: getattr(self, k, None) for k in super().__getattribute__("_columns")}) | Evaluate all of the column values and return the result
:return: column/value tuples |
def _create_get_request(self, resource, billomat_id='', command=None, params=None):
"""
Creates a get request and return the response data
"""
if not params:
params = {}
if not command:
command = ''
else:
command = '/' + command
... | Creates a get request and return the response data |
def get_user_settings_module(project_root: str):
"""Return project-specific user settings module, if it exists.
:param project_root: Absolute path to project root directory.
A project settings file is a file named `YSETTINGS_FILE` found at the top
level of the project root dir.
Return `None` if p... | Return project-specific user settings module, if it exists.
:param project_root: Absolute path to project root directory.
A project settings file is a file named `YSETTINGS_FILE` found at the top
level of the project root dir.
Return `None` if project root dir is not specified,
or if no such file... |
def memwarp_multi(src_ds_list, res='first', extent='intersection', t_srs='first', r='cubic', verbose=True, dst_ndv=0):
"""Helper function for memwarp of multiple input GDAL Datasets
"""
return warp_multi(src_ds_list, res, extent, t_srs, r, warptype=memwarp, verbose=verbose, dst_ndv=dst_ndv) | Helper function for memwarp of multiple input GDAL Datasets |
def parse_full(self, element):
r"""Parse xml element include the node attributes.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
.. versionadded:: 1.2.1
"""
values = collections.defaultdict(dict)
for child in element:
... | r"""Parse xml element include the node attributes.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
.. versionadded:: 1.2.1 |
def indexableText(self, include_properties=True):
"""Words found in the various texts of the document.
:param include_properties: Adds words from properties
:return: Space separated words of the document.
"""
text = set()
for extractor in self._text_extractors:
... | Words found in the various texts of the document.
:param include_properties: Adds words from properties
:return: Space separated words of the document. |
def log_very_verbose(self, message):
"""
Logs a message only when logging level is very verbose.
:param str|list[str] message: The message.
"""
if self.get_verbosity() >= Output.VERBOSITY_VERY_VERBOSE:
self.writeln(message) | Logs a message only when logging level is very verbose.
:param str|list[str] message: The message. |
def progress_bar(iteration,
total,
prefix=None,
suffix=None,
decs=1,
length=100):
"""Creates a console progress bar.
This should be called in a loop to create a progress bar.
See `StackOverflow <http://stackoverflow.com/q... | Creates a console progress bar.
This should be called in a loop to create a progress bar.
See `StackOverflow <http://stackoverflow.com/questions/3173320/>`__.
Args:
iteration (int): current iteration
total (int): total iterations
prefix (str): prefix string
suffix (str): suffix st... |
def _get_model_without_dependencies(self, models_dict):
'''
Helper function to find the next model that should be created
'''
next_model = None
if not models_dict:
return next_model
for model, dependencies in six.iteritems(models_dict):
if depende... | Helper function to find the next model that should be created |
def _checkCanIndex(self):
'''
_checkCanIndex - Check if we CAN index (if all fields are indexable).
Also checks the right-most field for "hashIndex" - if it needs to hash we will hash.
'''
# NOTE: We can't just check the right-most field. For types like pickle that don't support indexing, they don't
# ... | _checkCanIndex - Check if we CAN index (if all fields are indexable).
Also checks the right-most field for "hashIndex" - if it needs to hash we will hash. |
def validate_metadata_sign(xml, cert=None, fingerprint=None, fingerprintalg='sha1', validatecert=False, debug=False):
"""
Validates a signature of a EntityDescriptor.
:param xml: The element we should validate
:type: string | Document
:param cert: The pubic cert
:type: ... | Validates a signature of a EntityDescriptor.
:param xml: The element we should validate
:type: string | Document
:param cert: The pubic cert
:type: string
:param fingerprint: The fingerprint of the public cert
:type: string
:param fingerprintalg: The algorithm... |
def scheduled(self, offset=0, count=25):
'''Return all the currently-scheduled jobs'''
return self.client('jobs', 'scheduled', self.name, offset, count) | Return all the currently-scheduled jobs |
def _get_type_name(type_):
# type: (type) -> str
"""Return a displayable name for the type.
Args:
type_: A class object.
Returns:
A string value describing the class name that can be used in a natural
language sentence.
"""
name = repr(type_)
if name.startswith("<")... | Return a displayable name for the type.
Args:
type_: A class object.
Returns:
A string value describing the class name that can be used in a natural
language sentence. |
def serialize(self) -> str:
"""
Dump current object to a JSON-compatible dictionary.
:return: dict representation of current DIDDoc
"""
return {
'@context': DIDDoc.CONTEXT,
'id': canon_ref(self.did, self.did),
'publicKey': [pubkey.to_dict() f... | Dump current object to a JSON-compatible dictionary.
:return: dict representation of current DIDDoc |
def evaluate(self, x, y, flux, x_0, y_0):
"""
Evaluate the `GriddedPSFModel` for the input parameters.
"""
# NOTE: this is needed because the PSF photometry routines input
# length-1 values instead of scalars. TODO: fix the photometry
# routines.
if not np.issca... | Evaluate the `GriddedPSFModel` for the input parameters. |
def GoZero(self, speed):
' Go to Zero position '
self.ReleaseSW()
spi.SPI_write_byte(self.CS, 0x82 | (self.Dir & 1)) # Go to Zero
spi.SPI_write_byte(self.CS, 0x00)
spi.SPI_write_byte(self.CS, speed)
while self.IsBusy():
pass
time.sleep(0.3)
... | Go to Zero position |
def add(self, entry):
"""Add an ENTRY to the CArchive.
ENTRY must have:
entry[0] is name (under which it will be saved).
entry[1] is fullpathname of the file.
entry[2] is a flag for it's storage format (0==uncompressed,
1==compressed)
... | Add an ENTRY to the CArchive.
ENTRY must have:
entry[0] is name (under which it will be saved).
entry[1] is fullpathname of the file.
entry[2] is a flag for it's storage format (0==uncompressed,
1==compressed)
entry[3] is the entry's type code... |
def verify_reg_list(self, obj, object_type):
"""Verify a list of registers."""
# We expect the object to be a bitlist or an idlist, we don't care.
# We will iterate it and ensure everything in it is declared as a bit,
# and throw if not.
for children in obj.children:
... | Verify a list of registers. |
def replace_traceback_format_tb():
"""
Replaces these functions from the traceback module by our own:
- traceback.format_tb
- traceback.StackSummary.format
- traceback.StackSummary.extract
Note that this kind of monkey patching might not be safe under all circumstances
and is not officiall... | Replaces these functions from the traceback module by our own:
- traceback.format_tb
- traceback.StackSummary.format
- traceback.StackSummary.extract
Note that this kind of monkey patching might not be safe under all circumstances
and is not officially supported by Python. |
def get_all(self, start=0, count=-1, filter='', query='', sort='', view='', fields='', uri=None, scope_uris=''):
"""
Gets all items according with the given arguments.
Args:
start:
The first item to return, using 0-based indexing.
If not specified, th... | Gets all items according with the given arguments.
Args:
start:
The first item to return, using 0-based indexing.
If not specified, the default is 0 - start with the first available item.
count:
The number of resources to return. A count o... |
def interpolate_intervals(intervals, labels, time_points, fill_value=None):
"""Assign labels to a set of points in time given a set of intervals.
Time points that do not lie within an interval are mapped to `fill_value`.
Parameters
----------
intervals : np.ndarray, shape=(n, 2)
An array o... | Assign labels to a set of points in time given a set of intervals.
Time points that do not lie within an interval are mapped to `fill_value`.
Parameters
----------
intervals : np.ndarray, shape=(n, 2)
An array of time intervals, as returned by
:func:`mir_eval.io.load_intervals()`.
... |
def write(self, session, directory, name, maskMap):
"""
Write from database to file.
*session* = SQLAlchemy session object\n
*directory* = to which directory will the files be written (e.g.: '/example/path')\n
*name* = name of file that will be written (e.g.: 'my_project.ext')\n... | Write from database to file.
*session* = SQLAlchemy session object\n
*directory* = to which directory will the files be written (e.g.: '/example/path')\n
*name* = name of file that will be written (e.g.: 'my_project.ext')\n |
def get_description(self):
"""Get description (as dictionary)"""
message = self._get_description_message()
data = self._parse_description(message)
return data | Get description (as dictionary) |
def sort_by_successors(l, succsOf):
""" Sorts a list, such that if l[b] in succsOf(l[a]) then a < b """
rlut = dict()
nret = 0
todo = list()
for i in l:
rlut[i] = set()
for i in l:
for j in succsOf(i):
rlut[j].add(i)
for i in l:
if len(rlut[i]) == 0:
... | Sorts a list, such that if l[b] in succsOf(l[a]) then a < b |
def delta_e_cie1994(color1, color2, K_L=1, K_C=1, K_H=1, K_1=0.045, K_2=0.015):
"""
Calculates the Delta E (CIE1994) of two colors.
K_l:
0.045 graphic arts
0.048 textiles
K_2:
0.015 graphic arts
0.014 textiles
K_L:
1 default
2 textiles
"""
color1_vector =... | Calculates the Delta E (CIE1994) of two colors.
K_l:
0.045 graphic arts
0.048 textiles
K_2:
0.015 graphic arts
0.014 textiles
K_L:
1 default
2 textiles |
def PredictivePmf(self, xs, name=''):
"""Makes a predictive distribution.
xs: values to go into the Pmf
Returns: Pmf that maps from x to the mean prevalence of x
"""
alpha0 = self.params.sum()
ps = self.params / alpha0
return MakePmfFromItems(zip(xs, ps), name=n... | Makes a predictive distribution.
xs: values to go into the Pmf
Returns: Pmf that maps from x to the mean prevalence of x |
def get(self, name, default=None, cache=False):
"""
Get a pane by name, possibly from the cache. Return None if not found.
"""
if cache == True:
for pane in self.cache:
if pane.name == name:
return pane
return default
fo... | Get a pane by name, possibly from the cache. Return None if not found. |
def list_groups(self, scope_ids=None, recurse=None, deleted=None, properties=None):
"""ListGroups.
:param str scope_ids:
:param bool recurse:
:param bool deleted:
:param str properties:
:rtype: [Identity]
"""
query_parameters = {}
if scope_ids is n... | ListGroups.
:param str scope_ids:
:param bool recurse:
:param bool deleted:
:param str properties:
:rtype: [Identity] |
def get_object(self, mpath, path=None, accept="*/*"):
"""GetObject
https://apidocs.joyent.com/manta/api.html#GetObject
@param mpath {str} Required. A manta path, e.g. '/trent/stor/myobj'.
@param path {str} Optional. If given, the retrieved object will be
written to the given... | GetObject
https://apidocs.joyent.com/manta/api.html#GetObject
@param mpath {str} Required. A manta path, e.g. '/trent/stor/myobj'.
@param path {str} Optional. If given, the retrieved object will be
written to the given file path instead of the content being
returned.
... |
def load_environment(global_conf, app_conf):
"""Configure the Pylons environment via the ``pylons.config``
object
"""
# Pylons paths
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
paths = dict(root=root,
controllers=os.path.join(root, 'controllers'),
... | Configure the Pylons environment via the ``pylons.config``
object |
def iter_items(cls, repo, common_path=None, remote=None):
"""Iterate remote references, and if given, constrain them to the given remote"""
common_path = common_path or cls._common_path_default
if remote is not None:
common_path = join_path(common_path, str(remote))
# END han... | Iterate remote references, and if given, constrain them to the given remote |
def profileit(path=None):
"""cProfile decorator to profile a function
:param path: output file path
:type path: str
:return: Function
"""
def inner(func):
@wraps(func)
def wrapper(*args, **kwargs):
prof = cProfile.Profile()
retval = prof.runcall(func, *a... | cProfile decorator to profile a function
:param path: output file path
:type path: str
:return: Function |
def corpus_importer(self, corpus, n_val=1, bos='_START_', eos='_END_'):
r"""Fill in self.ngcorpus from a Corpus argument.
Parameters
----------
corpus :Corpus
The Corpus from which to initialize the n-gram corpus
n_val : int
Maximum n value for n-grams
... | r"""Fill in self.ngcorpus from a Corpus argument.
Parameters
----------
corpus :Corpus
The Corpus from which to initialize the n-gram corpus
n_val : int
Maximum n value for n-grams
bos : str
String to insert as an indicator of beginning of sen... |
def without_global_scope(self, scope):
"""
Remove a registered global scope.
:param scope: The scope to remove
:type scope: Scope or str
:rtype: Builder
"""
if isinstance(scope, basestring):
del self._scopes[scope]
return self
k... | Remove a registered global scope.
:param scope: The scope to remove
:type scope: Scope or str
:rtype: Builder |
def remove(self, first, count):
"""
Remove a range of count consecutive ids starting at id first
from all the ranges in the set.
"""
# Avoid trivialities
if first < 0 or count < 1:
return
new_range = []
last = first + count - 1
for r ... | Remove a range of count consecutive ids starting at id first
from all the ranges in the set. |
def _bfs_path_states(self, graph, start):
"""
Find state access strings (DFA shortest paths for every state)
using BFS
Args:
graph (DFA): The DFA states
start (int): The DFA initial state
Return:
list: A list of all the DFA shortest paths for e... | Find state access strings (DFA shortest paths for every state)
using BFS
Args:
graph (DFA): The DFA states
start (int): The DFA initial state
Return:
list: A list of all the DFA shortest paths for every state |
def render_obs(self, obs):
"""Render a frame given an observation."""
start_time = time.time()
self._obs = obs
self.check_valid_queued_action()
self._update_camera(point.Point.build(
self._obs.observation.raw_data.player.camera))
for surf in self._surfaces:
# Render that surface.
... | Render a frame given an observation. |
def deployment_state(self, deployment_state):
"""
Sets the deployment_state of this CampaignDeviceMetadata.
The state of the update campaign on the device
:param deployment_state: The deployment_state of this CampaignDeviceMetadata.
:type: str
"""
allowed_values ... | Sets the deployment_state of this CampaignDeviceMetadata.
The state of the update campaign on the device
:param deployment_state: The deployment_state of this CampaignDeviceMetadata.
:type: str |
def set(self, opts, popsize=None, ccovfac=1, verbose=True):
"""Compute strategy parameters as a function
of dimension and population size """
alpha_cc = 1.0 # cc-correction for mueff, was zero before
def conedf(df, mu, N):
"""used for computing separable learning rate"""
... | Compute strategy parameters as a function
of dimension and population size |
def file_do(self, filename):
"""Execute a file on the device using 'do'"""
log.info('Executing '+filename)
res = self.__exchange('dofile("'+filename+'")')
log.info(res)
return res | Execute a file on the device using 'do |
def build_batch(cls, size, **kwargs):
"""Build a batch of instances of the given class, with overriden attrs.
Args:
size (int): the number of instances to build
Returns:
object list: the built instances
"""
return [cls.build(**kwargs) for _ in range(size... | Build a batch of instances of the given class, with overriden attrs.
Args:
size (int): the number of instances to build
Returns:
object list: the built instances |
def _retrieve_userinfo(self, access_token=None):
"""
Requests extra user information from the Provider's UserInfo and
returns the result.
:returns: The contents of the UserInfo endpoint.
:rtype: dict
"""
if 'userinfo_uri' not in self.client_secrets:
l... | Requests extra user information from the Provider's UserInfo and
returns the result.
:returns: The contents of the UserInfo endpoint.
:rtype: dict |
def get_default_bus():
"""Return the default bus number based on the device platform. For a
Raspberry Pi either bus 0 or 1 (based on the Pi revision) will be returned.
For a Beaglebone Black the first user accessible bus, 1, will be returned.
"""
plat = Platform.platform_detect()
if plat == Pla... | Return the default bus number based on the device platform. For a
Raspberry Pi either bus 0 or 1 (based on the Pi revision) will be returned.
For a Beaglebone Black the first user accessible bus, 1, will be returned. |
def get_application(name):
"""Fetch an :class:`Application` associated with ``name`` if available.
This function may return an :ref:`asynchronous component <coroutine>`.
The application name is set during initialisation. Check the
:attr:`Configurator.name` attribute for more information.
"""
ac... | Fetch an :class:`Application` associated with ``name`` if available.
This function may return an :ref:`asynchronous component <coroutine>`.
The application name is set during initialisation. Check the
:attr:`Configurator.name` attribute for more information. |
def close(self, child):
"""
Close a child position - alias for rebalance(0, child). This will also
flatten (close out all) the child's children.
Args:
* child (str): Child, specified by name.
"""
c = self.children[child]
# flatten if children not None... | Close a child position - alias for rebalance(0, child). This will also
flatten (close out all) the child's children.
Args:
* child (str): Child, specified by name. |
def ScheduleSystemCronFlows(names=None, token=None):
"""Schedule all the SystemCronFlows found."""
if data_store.RelationalDBEnabled():
return cronjobs.ScheduleSystemCronJobs(names=names)
errors = []
for name in config.CONFIG["Cron.disabled_system_jobs"]:
try:
cls = registry.AFF4FlowRegistry.Flo... | Schedule all the SystemCronFlows found. |
def save(self, vpk_output_path):
"""
Saves the VPK at the given path
"""
with fopen(vpk_output_path, 'wb') as f:
# write VPK1 header
f.write(struct.pack("3I", self.signature,
self.version,
... | Saves the VPK at the given path |
def _save_fastq_space(items):
"""Potentially save fastq space prior to merging, since alignments done.
"""
to_cleanup = {}
for data in (utils.to_single_data(x) for x in items):
for fname in data.get("files", []):
if os.path.realpath(fname).startswith(dd.get_work_dir(data)):
... | Potentially save fastq space prior to merging, since alignments done. |
def _caveat_v1_to_dict(c):
''' Return a caveat as a dictionary for export as the JSON
macaroon v1 format.
'''
serialized = {}
if len(c.caveat_id) > 0:
serialized['cid'] = c.caveat_id
if c.verification_key_id:
serialized['vid'] = utils.raw_urlsafe_b64encode(
c.verifica... | Return a caveat as a dictionary for export as the JSON
macaroon v1 format. |
def get_cache_context(self):
'''
Retrieve a context cache from disk
'''
with salt.utils.files.fopen(self.cache_path, 'rb') as cache:
return salt.utils.data.decode(self.serial.load(cache)) | Retrieve a context cache from disk |
def run(self):
"""
Let the pipe flow
:return:
"""
assert len(self.elements) >= 2, "In order flow, pipe needs 2 or more elements"
in_pipe = self.elements[0]
other_pipes = self.elements[1:-1]
out_pipe = self.elements[-1]
self.make_assertions(in_pipe... | Let the pipe flow
:return: |
def replace(self, **k):
"""Note returns a new Date obj"""
if self.date != 'infinity':
return Date(self.date.replace(**k))
else:
return Date('infinity') | Note returns a new Date obj |
def has_title(self):
"""Read/write boolean, specifying whether this chart has a title.
Assigning |True| causes a title to be added if not already present.
Assigning |False| removes any existing title along with its text and
settings.
"""
title = self._chartSpace.chart.ti... | Read/write boolean, specifying whether this chart has a title.
Assigning |True| causes a title to be added if not already present.
Assigning |False| removes any existing title along with its text and
settings. |
def is_port_default(self):
'''Return whether the URL is using the default port.'''
if self.scheme in RELATIVE_SCHEME_DEFAULT_PORTS:
return RELATIVE_SCHEME_DEFAULT_PORTS[self.scheme] == self.port | Return whether the URL is using the default port. |
def gettext(self, message):
"""Contacts the GP service instance to find the translated value for
the provided message key.
If translated value is not available, and a fallback has been set,
the fallback will be used. If there is no fallback, the source language
value is re... | Contacts the GP service instance to find the translated value for
the provided message key.
If translated value is not available, and a fallback has been set,
the fallback will be used. If there is no fallback, the source language
value is returned. And if the message key is not fo... |
def project_and_to2dim_ordered_indices(self, pps, plane_center='mean'):
"""
Projects each points in the point list pps on plane and returns the indices that would sort the
list of projected points in anticlockwise order
:param pps: List of points to project on plane
:return: List... | Projects each points in the point list pps on plane and returns the indices that would sort the
list of projected points in anticlockwise order
:param pps: List of points to project on plane
:return: List of indices that would sort the list of projected points |
def trace(self, trace_obj):
"""
Trace given trace_obj (usuall a Message instance) recursively.
:param trace_obj:
:return: a string with properly formatted tracing information
"""
tracer = self
tracer.writeln(u'%s = ' % trace_obj.__class__.__name__)
tracer.... | Trace given trace_obj (usuall a Message instance) recursively.
:param trace_obj:
:return: a string with properly formatted tracing information |
def delete(self, guid):
"""
Delete guid
"""
return self.client.delete(self.url, params={'guid': guid}) | Delete guid |
def install_required(f):
""" Return an exception if the namespace is not already installed """
@wraps(f)
def wrapped(self, *args, **kwargs):
if self.directory.new:
raise SprinterException("Namespace %s is not yet installed!" % self.namespace)
return f(self, *args, **kwargs)
... | Return an exception if the namespace is not already installed |
def _parseHeaderValue(self, header_value):
"""
Parse out a complex header value (such as Content-Type, with a value
like "text/html; charset=utf-8") into a main value and a dictionary of
extra information (in this case, 'text/html' and {'charset': 'utf8'}).
"""
values = h... | Parse out a complex header value (such as Content-Type, with a value
like "text/html; charset=utf-8") into a main value and a dictionary of
extra information (in this case, 'text/html' and {'charset': 'utf8'}). |
def expire(self, name, time):
"""
Allow the key to expire after ``time`` seconds.
:param name: str the name of the redis key
:param time: time expressed in seconds.
:return: Future()
"""
with self.pipe as pipe:
return pipe.expire(self.redis_key(na... | Allow the key to expire after ``time`` seconds.
:param name: str the name of the redis key
:param time: time expressed in seconds.
:return: Future() |
def _hide_tick_lines_and_labels(axis):
"""
Set visible property of ticklines and ticklabels of an axis to False
"""
for item in axis.get_ticklines() + axis.get_ticklabels():
item.set_visible(False) | Set visible property of ticklines and ticklabels of an axis to False |
def confirm_registration(request, key, template="locksmith/confirmed.html"):
'''
API key confirmation
visiting this URL marks a Key as ready for use
'''
context = {'LOCKSMITH_BASE_TEMPLATE': settings.LOCKSMITH_BASE_TEMPLATE}
try:
context['key'] = key_obj = Key.objects.get(key=ke... | API key confirmation
visiting this URL marks a Key as ready for use |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'name') and self.name is not None:
_dict['name'] = self.name
if hasattr(self, 'out_of_vocabulary_words'
) and self.out_of_vocabulary_words is not None:
... | Return a json dictionary representing this model. |
def beta_r(self, r, kwargs):
"""
returns the anisotorpy parameter at a given radius
:param r:
:return:
"""
if self._type == 'const':
return self.const_beta(kwargs)
elif self._type == 'r_ani':
return self.beta_r_ani(r, kwargs)
else:
... | returns the anisotorpy parameter at a given radius
:param r:
:return: |
def run_on_all_sites(self, cmd, *args, **kwargs):
"""
Like run(), but re-runs the command for each site in the current role.
"""
r = self.local_renderer
for _site, _data in iter_sites():
r.env.SITE = _site
with self.settings(warn_only=True):
... | Like run(), but re-runs the command for each site in the current role. |
def isexec(path):
'''
Check if given path points to an executable file.
:param path: file path
:type path: str
:return: True if executable, False otherwise
:rtype: bool
'''
return os.path.isfile(path) and os.access(path, os.X_OK) | Check if given path points to an executable file.
:param path: file path
:type path: str
:return: True if executable, False otherwise
:rtype: bool |
def extend_safe(target, source):
"""
Extends source list to target list only if elements doesn't exists in target list.
:param target:
:type target: list
:param source:
:type source: list
"""
for elt in source:
if elt not in target:
target.append(elt) | Extends source list to target list only if elements doesn't exists in target list.
:param target:
:type target: list
:param source:
:type source: list |
def compute_offset_sad(dem1, dem2, pad=(9,9), plot=False):
"""Compute subpixel horizontal offset between input rasters using sum of absolute differences (SAD) method
"""
#This defines the search window size
#Use half-pixel stride?
#Note: stride is not properly implemented
#stride = 1
#ref =... | Compute subpixel horizontal offset between input rasters using sum of absolute differences (SAD) method |
def get_usage(self, loadbalancer=None, start=None, end=None):
"""
Return the load balancer usage records for this account. If 'loadbalancer'
is None, records for all load balancers are returned. You may optionally
include a start datetime or an end datetime, or both, which will limit
... | Return the load balancer usage records for this account. If 'loadbalancer'
is None, records for all load balancers are returned. You may optionally
include a start datetime or an end datetime, or both, which will limit
the records to those on or after the start time, and those before or on the
... |
def from_stream(cls, reader: ReaderAdapter):
"""
Read and decode MQTT message fixed header from stream
:return: FixedHeader instance
"""
@asyncio.coroutine
def decode_remaining_length():
"""
Decode message length according to MQTT specifications
... | Read and decode MQTT message fixed header from stream
:return: FixedHeader instance |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.