code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def create_s3app(self):
"""Create S3 infra for s3 applications"""
utils.banner("Creating S3 App Infrastructure")
primary_region = self.configs['pipeline']['primary_region']
s3obj = s3.S3Apps(app=self.app,
env=self.env,
region=self.regio... | Create S3 infra for s3 applications |
def items(cls):
"""
:return: List of tuples consisting of every enum value in the form [('NAME', value), ...]
:rtype: list
"""
items = [(value.name, key) for key, value in cls.values.items()]
return sorted(items, key=lambda x: x[1]) | :return: List of tuples consisting of every enum value in the form [('NAME', value), ...]
:rtype: list |
def bulk_copy(self, ids):
"""Bulk copy a set of users.
:param ids: Int list of user IDs.
:return: :class:`users.User <users.User>` list
"""
schema = UserSchema()
return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema) | Bulk copy a set of users.
:param ids: Int list of user IDs.
:return: :class:`users.User <users.User>` list |
def _build_voronoi_polygons(df):
"""
Given a GeoDataFrame of point geometries and pre-computed plot extrema, build Voronoi simplexes for the given
points in the given space and returns them.
Voronoi simplexes which are located on the edges of the graph may extend into infinity in some direction. In
... | Given a GeoDataFrame of point geometries and pre-computed plot extrema, build Voronoi simplexes for the given
points in the given space and returns them.
Voronoi simplexes which are located on the edges of the graph may extend into infinity in some direction. In
other words, the set of points nearest the g... |
def chunkprocess(func):
"""take a function that taks an iterable as the first argument.
return a wrapper that will break an iterable into chunks using
chunkiter and run each chunk in function, yielding the value of each
function call as an iterator.
"""
@functools.wraps(func)
def wrapper(it... | take a function that taks an iterable as the first argument.
return a wrapper that will break an iterable into chunks using
chunkiter and run each chunk in function, yielding the value of each
function call as an iterator. |
def _fill_row_borders(self):
"""Add the first and last rows to the data by extrapolation.
"""
lines = len(self.hrow_indices)
chunk_size = self.chunk_size or lines
factor = len(self.hrow_indices) / len(self.row_indices)
tmp_data = []
for num in range(len(self.tie_... | Add the first and last rows to the data by extrapolation. |
def create(ctx, name, integration_type, location, non_interactive, quiet, dry_run):
"""Create scaffolding for a new integration."""
repo_choice = ctx.obj['repo_choice']
root = resolve_path(location) if location else get_root()
path_sep = os.path.sep
integration_dir = os.path.join(root, normalize_pa... | Create scaffolding for a new integration. |
def bare(self):
"Make a Features object with no metadata; points to the same features."
if not self.meta:
return self
elif self.stacked:
return Features(self.stacked_features, self.n_pts, copy=False)
else:
return Features(self.features, copy=False) | Make a Features object with no metadata; points to the same features. |
def mask(self, pattern):
"""A drawing operator that paints the current source
using the alpha channel of :obj:`pattern` as a mask.
(Opaque areas of :obj:`pattern` are painted with the source,
transparent areas are not painted.)
:param pattern: A :class:`Pattern` object.
... | A drawing operator that paints the current source
using the alpha channel of :obj:`pattern` as a mask.
(Opaque areas of :obj:`pattern` are painted with the source,
transparent areas are not painted.)
:param pattern: A :class:`Pattern` object. |
def check(text):
"""Check the text."""
err = "misc.annotations"
msg = u"Annotation left in text."
annotations = [
"FIXME",
"FIX ME",
"TODO",
"todo",
"ERASE THIS",
"FIX THIS",
]
return existence_check(
text, annotations, err, msg, ignore_c... | Check the text. |
def qs_add(self, *args, **kwargs):
'''Add value to QuerySet MultiDict'''
query = self.query.copy()
if args:
mdict = MultiDict(args[0])
for k, v in mdict.items():
query.add(k, v)
for k, v in kwargs.items():
query.add(k, v)
return... | Add value to QuerySet MultiDict |
def _validate_validator(self, validator, field, value):
""" {'oneof': [
{'type': 'callable'},
{'type': 'list',
'schema': {'oneof': [{'type': 'callable'},
{'type': 'string'}]}},
{'type': 'string'}
... | {'oneof': [
{'type': 'callable'},
{'type': 'list',
'schema': {'oneof': [{'type': 'callable'},
{'type': 'string'}]}},
{'type': 'string'}
]} |
def client_args_for_bank(bank_info, ofx_version):
"""
Return the client arguments to use for a particular Institution, as found
from ofxhome. This provides us with an extension point to override or
augment ofxhome data for specific institutions, such as those that
require specific User-Agent headers... | Return the client arguments to use for a particular Institution, as found
from ofxhome. This provides us with an extension point to override or
augment ofxhome data for specific institutions, such as those that
require specific User-Agent headers (or no User-Agent header).
:param bank_info: OFXHome ban... |
def get_builder_openshift_url(self):
""" url of OpenShift where builder will connect """
key = "builder_openshift_url"
url = self._get_deprecated(key, self.conf_section, key)
if url is None:
logger.warning("%r not found, falling back to get_openshift_base_uri()", key)
... | url of OpenShift where builder will connect |
def standard_FPR(reference_patterns, estimated_patterns, tol=1e-5):
"""Standard F1 Score, Precision and Recall.
This metric checks if the prototype patterns of the reference match
possible translated patterns in the prototype patterns of the estimations.
Since the sizes of these prototypes must be equa... | Standard F1 Score, Precision and Recall.
This metric checks if the prototype patterns of the reference match
possible translated patterns in the prototype patterns of the estimations.
Since the sizes of these prototypes must be equal, this metric is quite
restictive and it tends to be 0 in most of 2013... |
def process_data(self, file_info):
"""expects FileInfo"""
if self._exceeds_max_file_size(file_info):
self.log.info("File '%s' has a size in bytes (%d) greater than the configured limit. Will be ignored.",
file_info.path, file_info.size)
self.fire(events.... | expects FileInfo |
async def open(self) -> 'NodePool':
"""
Explicit entry. Opens pool as configured, for later closure via close().
For use when keeping pool open across multiple calls.
Raise any IndyError causing failure to create ledger configuration.
:return: current object
"""
... | Explicit entry. Opens pool as configured, for later closure via close().
For use when keeping pool open across multiple calls.
Raise any IndyError causing failure to create ledger configuration.
:return: current object |
def url(self) -> str:
"""
Returns the URL that will open this project results file in the browser
:return:
"""
return 'file://{path}?id={id}'.format(
path=os.path.join(self.results_path, 'project.html'),
id=self.uuid
) | Returns the URL that will open this project results file in the browser
:return: |
def main(configpath = None, startup = None, daemon = False, pidfile = None, fork = None):
"""
The most simple way to start the VLCP framework
:param configpath: path of a configuration file to be loaded
:param startup: startup modules list. If None, `server.startup` in the configuration files
... | The most simple way to start the VLCP framework
:param configpath: path of a configuration file to be loaded
:param startup: startup modules list. If None, `server.startup` in the configuration files
is used; if `server.startup` is not configured, any module defined or imported
... |
def _expand_libs_in_libs(specs):
"""
Expands specs.libs.depends.libs to include any indirectly required libs
"""
for lib_name, lib_spec in specs['libs'].iteritems():
if 'depends' in lib_spec and 'libs' in lib_spec['depends']:
lib_spec['depends']['libs'] = _get_dependent('libs', lib_n... | Expands specs.libs.depends.libs to include any indirectly required libs |
def bind(self, sock):
"""Wrap and return the given socket."""
if self.context is None:
self.context = self.get_context()
conn = SSLConnection(self.context, sock)
self._environ = self.get_environ()
return conn | Wrap and return the given socket. |
def flatten(self):
"""
Get a flattened list of the items in the collection.
:rtype: Collection
"""
def _flatten(d):
if isinstance(d, dict):
for v in d.values():
for nested_v in _flatten(v):
yield nested_v
... | Get a flattened list of the items in the collection.
:rtype: Collection |
def show_type(cls, result):
"""
:param TryHaskell.Result result: Parse result of JSON data.
:rtype: str|unicode
"""
if result.ok:
return ' :: '.join([result.expr, result.type])
return result.value | :param TryHaskell.Result result: Parse result of JSON data.
:rtype: str|unicode |
def generalize(self,
sr,
geometries,
maxDeviation,
deviationUnit):
"""
The generalize operation is performed on a geometry service resource.
The generalize operation simplifies the input geometries using the
Do... | The generalize operation is performed on a geometry service resource.
The generalize operation simplifies the input geometries using the
Douglas-Peucker algorithm with a specified maximum deviation distance.
The output geometries will contain a subset of the original input vertices.
... |
def CreateChatWith(self, *Usernames):
"""Creates a chat with one or more users.
:Parameters:
Usernames : str
One or more Skypenames of the users.
:return: A chat object
:rtype: `Chat`
:see: `Chat.AddMembers`
"""
return Chat(self, chop(self... | Creates a chat with one or more users.
:Parameters:
Usernames : str
One or more Skypenames of the users.
:return: A chat object
:rtype: `Chat`
:see: `Chat.AddMembers` |
def enable_node(self, service_name, node_name):
"""
Enables a given node name for the given service name via the
"enable server" HAProxy command.
"""
logger.info("Enabling server %s/%s", service_name, node_name)
return self.send_command(
"enable server %s/%s" ... | Enables a given node name for the given service name via the
"enable server" HAProxy command. |
def verify_notification(data):
"""
Function to verify notification came from a trusted source
Returns True if verfied, False if not verified
"""
pemfile = grab_keyfile(data['SigningCertURL'])
cert = crypto.load_certificate(crypto.FILETYPE_PEM, pemfile)
signature = base64.decodestring(six.b(... | Function to verify notification came from a trusted source
Returns True if verfied, False if not verified |
def get_characteristic_from_uuid(self, uuid):
"""Given a characteristic UUID, return a :class:`Characteristic` object
containing information about that characteristic
Args:
uuid (str): a string containing the hex-encoded UUID
Returns:
None if an error occurs, ot... | Given a characteristic UUID, return a :class:`Characteristic` object
containing information about that characteristic
Args:
uuid (str): a string containing the hex-encoded UUID
Returns:
None if an error occurs, otherwise a :class:`Characteristic` object |
def plot_reaction_scheme(df, temperature, pressure, potential, pH, e_lim=None):
"""Returns a matplotlib object with the plotted reaction path.
Parameters
----------
df : Pandas DataFrame generated by reaction_network
temperature : numeric
temperature in K
pressure : numeric
press... | Returns a matplotlib object with the plotted reaction path.
Parameters
----------
df : Pandas DataFrame generated by reaction_network
temperature : numeric
temperature in K
pressure : numeric
pressure in mbar
pH : PH in bulk solution
potential : Electric potential vs. SHE in ... |
def create_calc_dh_dv(estimator):
"""
Return the function that can be used in the various gradient and hessian
calculations to calculate the derivative of the transformation with respect
to the index.
Parameters
----------
estimator : an instance of the estimation.LogitTypeEstimator class.
... | Return the function that can be used in the various gradient and hessian
calculations to calculate the derivative of the transformation with respect
to the index.
Parameters
----------
estimator : an instance of the estimation.LogitTypeEstimator class.
Should contain a `design` attribute th... |
def get_product_version(path: typing.Union[str, Path]) -> VersionInfo:
"""
Get version info from executable
Args:
path: path to the executable
Returns: VersionInfo
"""
path = Path(path).absolute()
pe_info = pefile.PE(str(path))
try:
for file_info in pe_info.FileInfo: ... | Get version info from executable
Args:
path: path to the executable
Returns: VersionInfo |
def indicator_associations(self, params=None):
"""
Gets the indicator association from a Indicator/Group/Victim
Yields: Indicator Association
"""
if not self.can_update():
self._tcex.handle_error(910, [self.type])
if params is None:
params = ... | Gets the indicator association from a Indicator/Group/Victim
Yields: Indicator Association |
def get_celery_app(name=None, **kwargs): # nocv
# pylint: disable=import-error
'''
Function to return celery-app. Works only if celery installed.
:param name: Application name
:param kwargs: overrided env-settings
:return: Celery-app object
'''
from celery import Celery
prepare_envi... | Function to return celery-app. Works only if celery installed.
:param name: Application name
:param kwargs: overrided env-settings
:return: Celery-app object |
def to_dict(self):
"""
Returns:
dict: ConciseCV represented as a dictionary.
"""
param = {
"n_folds": self._n_folds,
"n_rows": self._n_rows,
"use_stored_folds": self._use_stored_folds
}
if self._concise_global_model is None... | Returns:
dict: ConciseCV represented as a dictionary. |
def get_wildcard(self):
"""Return the wildcard bits notation of the netmask."""
return _convert(self._ip, notation=NM_WILDCARD,
inotation=IP_DOT, _check=False, _isnm=self._isnm) | Return the wildcard bits notation of the netmask. |
def dump(self, fh, value, context=None):
"""Attempt to transform and write a string-based foreign value to the given file-like object.
Returns the length written.
"""
value = self.dumps(value)
fh.write(value)
return len(value) | Attempt to transform and write a string-based foreign value to the given file-like object.
Returns the length written. |
def GetCoinAssets(self):
"""
Get asset ids of all coins present in the wallet.
Returns:
list: of UInt256 asset id's.
"""
assets = set()
for coin in self.GetCoins():
assets.add(coin.Output.AssetId)
return list(assets) | Get asset ids of all coins present in the wallet.
Returns:
list: of UInt256 asset id's. |
def nonver_name(self):
"""Return the non versioned name"""
nv = self.as_version(None)
if not nv:
import re
nv = re.sub(r'-[^-]+$', '', self.name)
return nv | Return the non versioned name |
def deprecatedMessage(msg, key=None, printStack=False):
'''
deprecatedMessage - Print a deprecated messsage (unless they are toggled off). Will print a message only once (based on "key")
@param msg <str> - Deprecated message to possibly print
@param key <anything> - A key that is specific to this message.
... | deprecatedMessage - Print a deprecated messsage (unless they are toggled off). Will print a message only once (based on "key")
@param msg <str> - Deprecated message to possibly print
@param key <anything> - A key that is specific to this message.
If None is provided (default), one will be generated from the... |
def _get_updated_environment(self, env_dict=None):
"""Returns globals environment with 'magic' variable
Parameters
----------
env_dict: Dict, defaults to {'S': self}
\tDict that maps global variable name to value
"""
if env_dict is None:
env_dict = ... | Returns globals environment with 'magic' variable
Parameters
----------
env_dict: Dict, defaults to {'S': self}
\tDict that maps global variable name to value |
def print_menuconfig(kconf):
"""
Prints all menu entries for the configuration.
"""
# Print the expanded mainmenu text at the top. This is the same as
# kconf.top_node.prompt[0], but with variable references expanded.
print("\n======== {} ========\n".format(kconf.mainmenu_text))
print_menuc... | Prints all menu entries for the configuration. |
def get_low_battery_warning_level(self):
"""
Looks through all power supplies in POWER_SUPPLY_PATH.
If there is an AC adapter online returns POWER_TYPE_AC returns LOW_BATTERY_WARNING_NONE.
Otherwise determines total percentage and time remaining across all attached batteries.
"""... | Looks through all power supplies in POWER_SUPPLY_PATH.
If there is an AC adapter online returns POWER_TYPE_AC returns LOW_BATTERY_WARNING_NONE.
Otherwise determines total percentage and time remaining across all attached batteries. |
def get_async_response(response_id):
"""
Get the response from the async table
"""
response = DYNAMODB_CLIENT.get_item(
TableName=ASYNC_RESPONSE_TABLE,
Key={'id': {'S': str(response_id)}}
)
if 'Item' not in response:
return None
return {
'status': response['I... | Get the response from the async table |
def _get_force_constants_disps(force_constants,
supercell,
dataset,
symmetry,
atom_list=None):
"""Calculate force constants Phi = -F / d
Force constants are obtained by one of the followi... | Calculate force constants Phi = -F / d
Force constants are obtained by one of the following algorithm.
Parameters
----------
force_constants: ndarray
Force constants
shape=(len(atom_list),n_satom,3,3)
dtype=double
supercell: Supercell
Supercell
dataset: dict
... |
def make_position_choices(self):
"""Create choices for available positions
"""
choices = []
for pos in self.get_available_positions():
choices.append({
"ResultValue": pos,
"ResultText": pos,
})
return choices | Create choices for available positions |
def formatFunctionNode(node,path,stack):
'''Add some helpful attributes to node.'''
#node.name is already defined by AST module
node.weight = calcFnWeight(node)
node.path = path
node.pclass = getCurrentClass(stack)
return node | Add some helpful attributes to node. |
def _empty_except_predicates(xast, node, context):
'''Check if a node is empty (no child nodes or attributes) except
for any predicates defined in the specified xpath.
:param xast: parsed xpath (xpath abstract syntax tree) from
:mod:`eulxml.xpath`
:param node: lxml element to check
:param context:... | Check if a node is empty (no child nodes or attributes) except
for any predicates defined in the specified xpath.
:param xast: parsed xpath (xpath abstract syntax tree) from
:mod:`eulxml.xpath`
:param node: lxml element to check
:param context: any context required for the xpath (e.g.,
namespace ... |
def worker_collectionfinish(self, node, ids):
"""worker has finished test collection.
This adds the collection for this node to the scheduler. If
the scheduler indicates collection is finished (i.e. all
initial nodes have submitted their collections), then tells the
scheduler t... | worker has finished test collection.
This adds the collection for this node to the scheduler. If
the scheduler indicates collection is finished (i.e. all
initial nodes have submitted their collections), then tells the
scheduler to schedule the collected items. When initiating
... |
def delete_token():
'''
Delete current token, file & CouchDB admin user
'''
username = get_admin()[0]
admins = get_couchdb_admins()
# Delete current admin if exist
if username in admins:
print 'I delete {} CouchDB user'.format(username)
delete_couchdb_admin(username)
... | Delete current token, file & CouchDB admin user |
def command(
self,
mark_success=False,
ignore_all_deps=False,
ignore_depends_on_past=False,
ignore_task_deps=False,
ignore_ti_state=False,
local=False,
pickle_id=None,
raw=False,
job_id=None,
... | Returns a command that can be executed anywhere where airflow is
installed. This command is part of the message sent to executors by
the orchestrator. |
def configure(self, options, config):
"""Configure the plugin and system, based on selected options.
attr and eval_attr may each be lists.
self.attribs will be a list of lists of tuples. In that list, each
list is a group of attributes, all of which must match for the rule to
m... | Configure the plugin and system, based on selected options.
attr and eval_attr may each be lists.
self.attribs will be a list of lists of tuples. In that list, each
list is a group of attributes, all of which must match for the rule to
match. |
def read_reaction(self, root):
folder_name = os.path.basename(root)
self.reaction, self.sites = ase_tools.get_reaction_from_folder(
folder_name) # reaction dict
self.stdout.write(
'----------- REACTION: {} --> {} --------------\n'
.format('+'.join(self.rea... | Create empty dictionaries |
def contains_vasp_input(dir_name):
"""
Checks if a directory contains valid VASP input.
Args:
dir_name:
Directory name to check.
Returns:
True if directory contains all four VASP input files (INCAR, POSCAR,
KPOINTS and POTCAR).
"""
for f in ["INCAR", "POSCAR... | Checks if a directory contains valid VASP input.
Args:
dir_name:
Directory name to check.
Returns:
True if directory contains all four VASP input files (INCAR, POSCAR,
KPOINTS and POTCAR). |
def update_feature_flag(self, state, name, user_email=None, check_feature_exists=None, set_at_application_level_also=None):
"""UpdateFeatureFlag.
[Preview API] Change the state of an individual feature flag for a name
:param :class:`<FeatureFlagPatch> <azure.devops.v5_0.feature_availability.mode... | UpdateFeatureFlag.
[Preview API] Change the state of an individual feature flag for a name
:param :class:`<FeatureFlagPatch> <azure.devops.v5_0.feature_availability.models.FeatureFlagPatch>` state: State that should be set
:param str name: The name of the feature to change
:param str use... |
def vcsmode_vcs_mode(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
vcsmode = ET.SubElement(config, "vcsmode", xmlns="urn:brocade.com:mgmt:brocade-vcs")
vcs_mode = ET.SubElement(vcsmode, "vcs-mode")
vcs_mode.text = kwargs.pop('vcs_mode')
... | Auto Generated Code |
def trim_docstring(docstring):
"""Uniformly trims leading/trailing whitespace from docstrings.
Based on http://www.python.org/peps/pep-0257.html#handling-docstring-indentation
"""
if not docstring or not docstring.strip():
return ""
# Convert tabs to spaces and split into lines
lines = ... | Uniformly trims leading/trailing whitespace from docstrings.
Based on http://www.python.org/peps/pep-0257.html#handling-docstring-indentation |
def wait_for_ajax_calls_to_complete(self, timeout=5):
"""
Waits until there are no active or pending ajax requests.
Raises TimeoutException should silence not be had.
:param timeout: time to wait for silence (default: 5 seconds)
:return: None
"""
from selenium.w... | Waits until there are no active or pending ajax requests.
Raises TimeoutException should silence not be had.
:param timeout: time to wait for silence (default: 5 seconds)
:return: None |
def apply_gravity(repulsion, nodes, gravity, scaling_ratio):
"""
Iterate through the nodes or edges and apply the gravity directly to the node objects.
"""
for i in range(0, len(nodes)):
repulsion.apply_gravitation(nodes[i], gravity / scaling_ratio) | Iterate through the nodes or edges and apply the gravity directly to the node objects. |
def run_process(path: Union[Path, str], target: Callable, *,
args: Tuple=(),
kwargs: Dict[str, Any]=None,
callback: Callable[[Set[Tuple[Change, str]]], None]=None,
watcher_cls: Type[AllWatcher]=PythonWatcher,
debounce=400,
m... | Run a function in a subprocess using multiprocessing.Process, restart it whenever files change in path. |
def average_loss(lc):
"""
Given a loss curve array with `poe` and `loss` fields,
computes the average loss on a period of time.
:note: As the loss curve is supposed to be piecewise linear as it
is a result of a linear interpolation, we compute an exact
integral by using the trapei... | Given a loss curve array with `poe` and `loss` fields,
computes the average loss on a period of time.
:note: As the loss curve is supposed to be piecewise linear as it
is a result of a linear interpolation, we compute an exact
integral by using the trapeizodal rule with the width given by... |
def past_active_subjunctive(self):
"""
Weak verbs
I
>>> verb = WeakOldNorseVerb()
>>> verb.set_canonic_forms(["kalla", "kallaði", "kallaðinn"])
>>> verb.past_active_subjunctive()
['kallaða', 'kallaðir', 'kallaði', 'kallaðim', 'kallaðið', 'kallaði']
II
... | Weak verbs
I
>>> verb = WeakOldNorseVerb()
>>> verb.set_canonic_forms(["kalla", "kallaði", "kallaðinn"])
>>> verb.past_active_subjunctive()
['kallaða', 'kallaðir', 'kallaði', 'kallaðim', 'kallaðið', 'kallaði']
II
>>> verb = WeakOldNorseVerb()
>>> verb.set... |
def parse_args():
"""
Parse commandline arguments.
"""
def exclusive_group(group, name, default, help):
destname = name.replace('-', '_')
subgroup = group.add_mutually_exclusive_group(required=False)
subgroup.add_argument(f'--{name}', dest=f'{destname}',
... | Parse commandline arguments. |
def make_regression(func, n_samples=100, n_features=1, bias=0.0, noise=0.0,
random_state=None):
"""
Make dataset for a regression problem.
Examples
--------
>>> f = lambda x: 0.5*x + np.sin(2*x)
>>> X, y = make_regression(f, bias=.5, noise=1., random_state=1)
>>> X.shape... | Make dataset for a regression problem.
Examples
--------
>>> f = lambda x: 0.5*x + np.sin(2*x)
>>> X, y = make_regression(f, bias=.5, noise=1., random_state=1)
>>> X.shape
(100, 1)
>>> y.shape
(100,)
>>> X[:5].round(2)
array([[ 1.62],
[-0.61],
[-0.53],
... |
def hessian(self, x, y, kappa_ext, ra_0=0, dec_0=0):
"""
Hessian matrix
:param x: x-coordinate
:param y: y-coordinate
:param kappa_ext: external convergence
:return: second order derivatives f_xx, f_yy, f_xy
"""
gamma1 = 0
gamma2 = 0
kappa... | Hessian matrix
:param x: x-coordinate
:param y: y-coordinate
:param kappa_ext: external convergence
:return: second order derivatives f_xx, f_yy, f_xy |
def find_file(name, directory):
"""Searches up from a directory looking for a file"""
path_bits = directory.split(os.sep)
for i in range(0, len(path_bits) - 1):
check_path = path_bits[0:len(path_bits) - i]
check_file = "%s%s%s" % (os.sep.join(check_path), os.sep, name)
if os.path.exi... | Searches up from a directory looking for a file |
def removeSheet(self, vs):
'Remove all traces of sheets named vs.name from the cmdlog.'
self.rows = [r for r in self.rows if r.sheet != vs.name]
status('removed "%s" from cmdlog' % vs.name) | Remove all traces of sheets named vs.name from the cmdlog. |
def calculate_cycles(self):
"""
Calculate performance model cycles from cache stats.
calculate_cache_access() needs to have been execute before.
"""
element_size = self.kernel.datatypes_size[self.kernel.datatype]
elements_per_cacheline = float(self.machine['cacheline siz... | Calculate performance model cycles from cache stats.
calculate_cache_access() needs to have been execute before. |
def extract_diff_sla_from_config_file(obj, options_file):
"""
Helper function to parse diff config file, which contains SLA rules for diff comparisons
"""
rule_strings = {}
config_obj = ConfigParser.ConfigParser()
config_obj.optionxform = str
config_obj.read(options_file)
for section in config_obj.secti... | Helper function to parse diff config file, which contains SLA rules for diff comparisons |
def rename(name, new_name):
'''
Change the username for a named user
CLI Example:
.. code-block:: bash
salt '*' user.rename name new_name
'''
current_info = info(name)
if not current_info:
raise CommandExecutionError('User \'{0}\' does not exist'.format(name))
new_info... | Change the username for a named user
CLI Example:
.. code-block:: bash
salt '*' user.rename name new_name |
def create_args(args, root):
"""
Encapsulates a set of custom command line arguments in key=value
or key.namespace=value form into a chain of Namespace objects,
where each next level is an attribute of the Namespace object on the
current level
Parameters
----------
args : list
A... | Encapsulates a set of custom command line arguments in key=value
or key.namespace=value form into a chain of Namespace objects,
where each next level is an attribute of the Namespace object on the
current level
Parameters
----------
args : list
A list of strings representing arguments i... |
def add_toolbars_to_menu(self, menu_title, actions):
"""Add toolbars to a menu."""
# Six is the position of the view menu in menus list
# that you can find in plugins/editor.py setup_other_windows.
view_menu = self.menus[6]
if actions == self.toolbars and view_menu:
... | Add toolbars to a menu. |
def set_burnstages_upgrade_massive(self):
'''
Outputs burnign stages as done in burningstages_upgrade (nugridse)
'''
burn_info=[]
burn_mini=[]
for i in range(len(self.runs_H5_surf)):
sefiles=se(self.runs_H5_out[i])
burn_info.append(sefiles.burnstage_upgrade())
... | Outputs burnign stages as done in burningstages_upgrade (nugridse) |
def as_matrix(self, columns=None):
"""
Convert the frame to its Numpy-array representation.
.. deprecated:: 0.23.0
Use :meth:`DataFrame.values` instead.
Parameters
----------
columns : list, optional, default:None
If None, return all columns, oth... | Convert the frame to its Numpy-array representation.
.. deprecated:: 0.23.0
Use :meth:`DataFrame.values` instead.
Parameters
----------
columns : list, optional, default:None
If None, return all columns, otherwise, returns specified columns.
Returns
... |
def confd_state_webui_listen_tcp_ip(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
webui = ET.SubElement(confd_state, "webui")
listen = ET.SubEle... | Auto Generated Code |
def _build_message_body(self, body_size):
"""Build the Message body from the inbound queue.
:rtype: str
"""
body = bytes()
while len(body) < body_size:
if not self._inbound:
self.check_for_errors()
sleep(IDLE_WAIT)
cont... | Build the Message body from the inbound queue.
:rtype: str |
def format(self, clip=0, grand=None):
'''Return format dict.
'''
if self.number > 1: # avg., plural
a, p = int(self.total / self.number), 's'
else:
a, p = self.total, ''
o = self.objref
if self.weak: # weakref'd
o = o()
t = _S... | Return format dict. |
def get_connection(self, command_name, *keys, **options):
"""
Get a connection, blocking for ``self.timeout`` until a connection
is available from the pool.
If the connection returned is ``None`` then creates a new connection.
Because we use a last-in first-out queue, the existi... | Get a connection, blocking for ``self.timeout`` until a connection
is available from the pool.
If the connection returned is ``None`` then creates a new connection.
Because we use a last-in first-out queue, the existing connections
(having been returned to the pool after the initial ``N... |
def add_wikipage(self, slug, content, **attrs):
"""
Add a Wiki page to the project and returns a :class:`WikiPage` object.
:param name: name of the :class:`WikiPage`
:param attrs: optional attributes for :class:`WikiPage`
"""
return WikiPages(self.requester).create(
... | Add a Wiki page to the project and returns a :class:`WikiPage` object.
:param name: name of the :class:`WikiPage`
:param attrs: optional attributes for :class:`WikiPage` |
def calculate_new_length(gene_split, gene_results, hit):
''' Function for calcualting new length if the gene is split on several
contigs
'''
# Looping over splitted hits and calculate new length
first = 1
for split in gene_split[hit['sbjct_header']]:
new_start = int(gene_results[split]['sbjct_st... | Function for calcualting new length if the gene is split on several
contigs |
def run(self):
"""Keep running this thread until it's stopped"""
while not self._finished.isSet():
self._func(self._reference)
self._finished.wait(self._func._interval / 1000.0) | Keep running this thread until it's stopped |
def build_parser(self, options=None, permissive=False, **override_kwargs):
"""Construct an argparser from supplied options.
:keyword override_kwargs: keyword arguments to override when calling
parser constructor.
:keyword permissive: when true, build a parser that does not validate
... | Construct an argparser from supplied options.
:keyword override_kwargs: keyword arguments to override when calling
parser constructor.
:keyword permissive: when true, build a parser that does not validate
required arguments. |
def endElement(self, name, value, connection):
"""Overwritten to also add the NextRecordName and
NextRecordType to the base object"""
if name == 'NextRecordName':
self.next_record_name = value
elif name == 'NextRecordType':
self.next_record_type = value
el... | Overwritten to also add the NextRecordName and
NextRecordType to the base object |
def get_userid_from_botid(self, botid):
'''Perform a lookup of bots.info to resolve a botid to a userid
Args:
botid (string): Slack botid to lookup.
Returns:
string: userid value
'''
botinfo = self.slack_client.api_call('bots.info', bot=botid)
if ... | Perform a lookup of bots.info to resolve a botid to a userid
Args:
botid (string): Slack botid to lookup.
Returns:
string: userid value |
def getArgNames(function):
'''
Returns a list of strings naming all of the arguments for the passed function.
Parameters
----------
function : function
A function whose argument names are wanted.
Returns
-------
argNames : [string]
The names of the arguments of function... | Returns a list of strings naming all of the arguments for the passed function.
Parameters
----------
function : function
A function whose argument names are wanted.
Returns
-------
argNames : [string]
The names of the arguments of function. |
def _get_result_paths(self, data):
""" Set the result paths
"""
result = {}
# OTU map (mandatory output)
result['OtuMap'] = ResultPath(Path=self.Parameters['-O'].Value,
IsWritten=True)
# SumaClust will not produce any output file i... | Set the result paths |
def new_worker_redirected_log_file(self, worker_id):
"""Create new logging files for workers to redirect its output."""
worker_stdout_file, worker_stderr_file = (self.new_log_files(
"worker-" + ray.utils.binary_to_hex(worker_id), True))
return worker_stdout_file, worker_stderr_file | Create new logging files for workers to redirect its output. |
def upload_object(self, object_name, file_obj):
"""
Upload an object to this bucket.
:param str object_name: The target name of the object.
:param file file_obj: The file (or file-like object) to upload.
:param str content_type: The content type associated to this object.
... | Upload an object to this bucket.
:param str object_name: The target name of the object.
:param file file_obj: The file (or file-like object) to upload.
:param str content_type: The content type associated to this object.
This is mainly useful when accessing an o... |
def _compute_cell_extents_grid(bounding_rect=(0.03, 0.03, 0.97, 0.97),
num_rows=2, num_cols=6,
axis_pad=0.01):
"""
Produces array of num_rows*num_cols elements each containing the rectangular extents of
the corresponding cell ... | Produces array of num_rows*num_cols elements each containing the rectangular extents of
the corresponding cell the grid, whose position is within bounding_rect. |
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the SignatureVerify request payload to a
stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usuall... | Write the data encoding the SignatureVerify request payload to a
stream.
Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumer... |
def padded_grid_stack_from_mask_sub_grid_size_and_psf_shape(cls, mask, sub_grid_size, psf_shape):
"""Setup a grid-stack of masked grid_stack from a mask, sub-grid size and psf-shape.
Parameters
-----------
mask : Mask
The mask whose masked pixels the grid-stack are setup us... | Setup a grid-stack of masked grid_stack from a mask, sub-grid size and psf-shape.
Parameters
-----------
mask : Mask
The mask whose masked pixels the grid-stack are setup using.
sub_grid_size : int
The size of a sub-pixels sub-grid (sub_grid_size x sub_grid_size... |
def run_update_cat(_):
'''
Update the catagery.
'''
recs = MPost2Catalog.query_all().objects()
for rec in recs:
if rec.tag_kind != 'z':
print('-' * 40)
print(rec.uid)
print(rec.tag_id)
print(rec.par_id)
MPost2Catalog.update_field(r... | Update the catagery. |
def match_regex_list(patterns, string):
"""Perform a regex match of a string against a list of patterns.
Returns true if the string matches at least one pattern in the
list."""
for p in patterns:
if re.findall(p, string):
return True
return False | Perform a regex match of a string against a list of patterns.
Returns true if the string matches at least one pattern in the
list. |
def _is_valid_relpath(
relpath,
maxdepth=None):
'''
Performs basic sanity checks on a relative path.
Requires POSIX-compatible paths (i.e. the kind obtained through
cp.list_master or other such calls).
Ensures that the path does not contain directory transversal, and
that it do... | Performs basic sanity checks on a relative path.
Requires POSIX-compatible paths (i.e. the kind obtained through
cp.list_master or other such calls).
Ensures that the path does not contain directory transversal, and
that it does not exceed a stated maximum depth (if specified). |
def system_drop_keyspace(self, keyspace):
"""
drops a keyspace and any column families that are part of it. returns the new schema id.
Parameters:
- keyspace
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_system_drop_keyspace(keyspace)
return d | drops a keyspace and any column families that are part of it. returns the new schema id.
Parameters:
- keyspace |
def delete(self, key, cas=0):
"""
Delete a key/value from server. If key does not exist, it returns True.
:param key: Key's name to be deleted
:param cas: CAS of the key
:return: True in case o success and False in case of failure.
"""
returns = []
for se... | Delete a key/value from server. If key does not exist, it returns True.
:param key: Key's name to be deleted
:param cas: CAS of the key
:return: True in case o success and False in case of failure. |
def get_entity_by_query(self, uuid=None, path=None, metadata=None):
'''Retrieve entity by query param which can be either uuid/path/metadata.
Args:
uuid (str): The UUID of the requested entity.
path (str): The path of the requested entity.
metadata (dict): A dictiona... | Retrieve entity by query param which can be either uuid/path/metadata.
Args:
uuid (str): The UUID of the requested entity.
path (str): The path of the requested entity.
metadata (dict): A dictionary of one metadata {key: value} of the
requested entitity.
... |
def get_value(self, name):
"""Get the value of a variable"""
value = self.shellwidget.get_value(name)
# Reset temporal variable where value is saved to
# save memory
self.shellwidget._kernel_value = None
return value | Get the value of a variable |
def delete(ctx, schema, uuid, object_filter, yes):
"""Delete stored objects (CAUTION!)"""
database = ctx.obj['db']
if schema is None:
log('No schema given. Read the help', lvl=warn)
return
model = database.objectmodels[schema]
if uuid:
count = model.count({'uuid': uuid})
... | Delete stored objects (CAUTION!) |
def write_graph(self, outfile, manifest):
"""Write the graph to a gpickle file. Before doing so, serialize and
include all nodes in their corresponding graph entries.
"""
out_graph = _updated_graph(self.graph, manifest)
nx.write_gpickle(out_graph, outfile) | Write the graph to a gpickle file. Before doing so, serialize and
include all nodes in their corresponding graph entries. |
def write_headers(self, fp, headers, mute=None):
"""
Convenience function to output headers in a formatted fashion
to a file-like fp, optionally muting any headers in the mute
list.
"""
if headers:
if not mute:
mute = []
fmt = '%%-%... | Convenience function to output headers in a formatted fashion
to a file-like fp, optionally muting any headers in the mute
list. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.