code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def remove_files(filename):
# type: (AnyStr) -> None
"""
Delete all files with same root as fileName,
i.e. regardless of suffix, such as ESRI shapefile
"""
pattern = os.path.splitext(filename)[0] + '.*'
for f in glob.iglob(pattern):
os.remove(f) | Delete all files with same root as fileName,
i.e. regardless of suffix, such as ESRI shapefile |
def named_objs(objlist, namesdict=None):
"""
Given a list of objects, returns a dictionary mapping from
string name for the object to the object itself. Accepts
an optional name,obj dictionary, which will override any other
name if that item is present in the dictionary.
"""
objs = OrderedDi... | Given a list of objects, returns a dictionary mapping from
string name for the object to the object itself. Accepts
an optional name,obj dictionary, which will override any other
name if that item is present in the dictionary. |
def connectPeer(self, peer):
"""Establish a SIGMA connection to the given peer.
@param peer: a Q2QAddress of a peer which has a file that I want
@return: a Deferred which fires a SigmaProtocol.
"""
return self.conns.connectCached(endpoint.Q2QEndpoint(self.svc,
... | Establish a SIGMA connection to the given peer.
@param peer: a Q2QAddress of a peer which has a file that I want
@return: a Deferred which fires a SigmaProtocol. |
def do_patch(endpoint, body, access_token):
'''Do an HTTP PATCH request and return JSON.
Args:
endpoint (str): Azure Resource Manager management endpoint.
body (str): JSON body of information to patch.
access_token (str): A valid Azure authentication token.
Returns:
HTTP re... | Do an HTTP PATCH request and return JSON.
Args:
endpoint (str): Azure Resource Manager management endpoint.
body (str): JSON body of information to patch.
access_token (str): A valid Azure authentication token.
Returns:
HTTP response. JSON body. |
def add_translation(sender):
"""
Adds the actions to a class.
"""
# 1. Execute _save_translations when saving an object
signals.post_save.connect(_save_translations, sender=sender)
# 2. Adds get_fieldtranslations to class. Remember that this method get all the translations.
sender.add_to_class("get_fieldtranslat... | Adds the actions to a class. |
def generate_random_person(self, n):
# type: (int) -> Iterable[Tuple[str, str, str, str]]
"""
Generator that yields details on a person with plausible name, sex and age.
:yields: Generated data for one person
tuple - (id: int, name: str('First Last'), birthdate: str('DD/MM/Y... | Generator that yields details on a person with plausible name, sex and age.
:yields: Generated data for one person
tuple - (id: int, name: str('First Last'), birthdate: str('DD/MM/YYYY'), sex: str('M' | 'F') ) |
def execute_after_scenario_steps(self, context):
"""
actions after each scenario
:param context: It’s a clever place where you and behave can store information to share around, automatically managed by behave.
"""
if not self.feature_error and not self.scenario_error:
... | actions after each scenario
:param context: It’s a clever place where you and behave can store information to share around, automatically managed by behave. |
def get_context_override(self, request):
"""
Override the request object with an emulated user.
"""
context_override = super(EmulateUserModelMixin, self).get_context_override(request)
try:
if request.user.is_staff:
user = self.UserModel.objects.get(pk=... | Override the request object with an emulated user. |
def search_users(self, username_keyword, limit=10):
"""
Searches for users whose username matches ``username_keyword``, and returns
a list of matched users.
:param str username_keyword: keyword to search with
:param int limit: maximum number of returned users
:return: a ... | Searches for users whose username matches ``username_keyword``, and returns
a list of matched users.
:param str username_keyword: keyword to search with
:param int limit: maximum number of returned users
:return: a list of matched users
:rtype: List[GogsUser]
:raises Net... |
def get(self, word, default=nil):
"""
Retrieves output value associated with word.
If there is no word returns default value,
and if default is not given rises KeyError.
"""
node = self.__get_node(word)
output = nil
if node:
output = node.output
if output is nil:
if default is nil:
raise ... | Retrieves output value associated with word.
If there is no word returns default value,
and if default is not given rises KeyError. |
def list(self, limit=None, marker=None, name=None, visibility=None,
member_status=None, owner=None, tag=None, status=None,
size_min=None, size_max=None, sort_key=None, sort_dir=None,
return_raw=False):
"""
Returns a list of resource objects. Pagination is supported th... | Returns a list of resource objects. Pagination is supported through the
optional 'marker' and 'limit' parameters. Filtering the returned value
is possible by specifying values for any of the other parameters. |
def _promote_and_split(s):
"""
E:F:.O:M:.t.- => E:.-F:.O:M:.-t.-‘
E:F:.M:M:.l.- => E:.-F:.M:M:.-l.-‘
"""
subst, attr, mode = s
subst0, subst1, _mode = subst
assert isinstance(_mode, NullScript)
return m(m(m(subst0)) ,m(m(subst1), attr) ,m(mode)) | E:F:.O:M:.t.- => E:.-F:.O:M:.-t.-‘
E:F:.M:M:.l.- => E:.-F:.M:M:.-l.-‘ |
def _run_with_kvm(self, qemu_path, options):
"""
Check if we could run qemu with KVM
:param qemu_path: Path to qemu
:param options: String of qemu user options
:returns: Boolean True if we need to enable KVM
"""
if sys.platform.startswith("linux") and self.manag... | Check if we could run qemu with KVM
:param qemu_path: Path to qemu
:param options: String of qemu user options
:returns: Boolean True if we need to enable KVM |
def w3_tx(self):
"""
:return: Web3 contract tx prepared for `call`, `transact` or `buildTransaction`
"""
safe_contract = get_safe_contract(self.w3, address=self.safe_address)
return safe_contract.functions.execTransaction(
self.to,
self.value,
... | :return: Web3 contract tx prepared for `call`, `transact` or `buildTransaction` |
def is_descendant_of_bank(self, id_, bank_id):
"""Tests if an ``Id`` is a descendant of a bank.
arg: id (osid.id.Id): an ``Id``
arg: bank_id (osid.id.Id): the ``Id`` of a bank
return: (boolean) - ``true`` if the ``id`` is a descendant of
the ``bank_id,`` ``false``... | Tests if an ``Id`` is a descendant of a bank.
arg: id (osid.id.Id): an ``Id``
arg: bank_id (osid.id.Id): the ``Id`` of a bank
return: (boolean) - ``true`` if the ``id`` is a descendant of
the ``bank_id,`` ``false`` otherwise
raise: NotFound - ``bank_id`` not foun... |
def _fetch_data(self):
"""Converts inputspec to files"""
if (self.inputs.surface_target == "fsnative" or
self.inputs.volume_target != "MNI152NLin2009cAsym"):
# subject space is not support yet
raise NotImplementedError
annotation_files = sorted(glob(os.pa... | Converts inputspec to files |
def search_individuals(self, dataset_id, name=None):
"""
Returns an iterator over the Individuals fulfilling the specified
conditions.
:param str dataset_id: The dataset to search within.
:param str name: Only Individuals matching the specified name will
be returned.... | Returns an iterator over the Individuals fulfilling the specified
conditions.
:param str dataset_id: The dataset to search within.
:param str name: Only Individuals matching the specified name will
be returned.
:return: An iterator over the :class:`ga4gh.protocol.Biosample`
... |
def _normalize_purge_unknown(mapping, schema):
""" {'type': 'boolean'} """
for field in tuple(mapping):
if field not in schema:
del mapping[field]
return mapping | {'type': 'boolean'} |
def crates(self, from_page=1):
"""Get crates in alphabetical order"""
path = urijoin(CRATES_API_URL, CATEGORY_CRATES)
raw_crates = self.__fetch_items(path, from_page)
return raw_crates | Get crates in alphabetical order |
def _configure_detail_level(cls, detail_level):
"""
Validate the `detail_level` parameter and return it.
This accepts a string or integer for `detail_level`.
"""
# process detail_level
if isinstance(detail_level, six.string_types):
if detail_level not in LOG_... | Validate the `detail_level` parameter and return it.
This accepts a string or integer for `detail_level`. |
def build_news(ctx, draft=False, yes=False):
""" Build towncrier newsfragments.
"""
report.info(ctx, "docs.build-news", "building changelog from news fragments")
build_command = f"towncrier --version {ctx.metadata['version']}"
if draft:
report.warn(
ctx,
"docs.build-... | Build towncrier newsfragments. |
def process_results(self):
"""
function that is called when a stage is completed and
needs to be analyzed befor further computations.
The code here implements the original SH algorithms by
advancing the k-best (lowest loss) configurations at the current
budget. k is defined by the num_configs list (see __i... | function that is called when a stage is completed and
needs to be analyzed befor further computations.
The code here implements the original SH algorithms by
advancing the k-best (lowest loss) configurations at the current
budget. k is defined by the num_configs list (see __init__)
and the current stage valu... |
def mtf_image_transformer_tiny_spatial1d():
"""Small single parameters."""
hparams = mtf_image_transformer_tiny()
hparams.num_decoder_layers = 6
hparams.filter_size = 128
hparams.block_height = 8
hparams.block_width = 8
hparams.attention_type = "local1d_spatial"
hparams.mesh_shape = ""
hparams.layout ... | Small single parameters. |
def get_volumes(container_map, config, default_volume_paths, include_named):
"""
Generates volume paths for the ``volumes`` argument during container creation.
:param container_map: Container map.
:type container_map: dockermap.map.config.main.ContainerMap
:param config: Container configuration.
... | Generates volume paths for the ``volumes`` argument during container creation.
:param container_map: Container map.
:type container_map: dockermap.map.config.main.ContainerMap
:param config: Container configuration.
:type config: dockermap.map.config.container.ContainerConfiguration
:param default_... |
def run(self, context=None, options=None):
"""
Run axe against the current page.
:param context: which page part(s) to analyze and/or what to exclude.
:param options: dictionary of aXe options.
"""
template = (
"var callback = arguments[arguments.length - 1];... | Run axe against the current page.
:param context: which page part(s) to analyze and/or what to exclude.
:param options: dictionary of aXe options. |
def extract_scopes(self, request):
"""
Extract scopes from a request object.
"""
payload = self.extract_payload(request)
if not payload:
return None
scopes_attribute = self.config.scopes_name()
return payload.get(scopes_attribute, None) | Extract scopes from a request object. |
def cast_to_list(position):
"""Cast the positional argument at given position into a list if not already a list."""
@wrapt.decorator
def wrapper(function, instance, args, kwargs):
if not isinstance(args[position], list):
args = list(args)
args[position] = [args[position]]
args = tuple(args)
return fun... | Cast the positional argument at given position into a list if not already a list. |
def find_link(self, target_node):
"""
Find the link that points to ``target_node`` if it exists.
If no link in ``self`` points to ``target_node``, return None
Args:
target_node (Node): The node to look for in ``self.link_list``
Returns:
Link: An existin... | Find the link that points to ``target_node`` if it exists.
If no link in ``self`` points to ``target_node``, return None
Args:
target_node (Node): The node to look for in ``self.link_list``
Returns:
Link: An existing link pointing to ``target_node`` if found
... |
def get_job_definition(self, identifier):
"""
Get job defintiion by name or ARN
:param identifier: Name or ARN
:type identifier: str
:return: Job definition or None
:rtype: JobDefinition or None
"""
env = self.get_job_definition_by_arn(identifier)
... | Get job defintiion by name or ARN
:param identifier: Name or ARN
:type identifier: str
:return: Job definition or None
:rtype: JobDefinition or None |
def get_all_instance_profiles(path_prefix='/', region=None, key=None,
keyid=None, profile=None):
'''
Get and return all IAM instance profiles, starting at the optional path.
.. versionadded:: 2016.11.0
CLI Example:
salt-call boto_iam.get_all_instance_profiles
... | Get and return all IAM instance profiles, starting at the optional path.
.. versionadded:: 2016.11.0
CLI Example:
salt-call boto_iam.get_all_instance_profiles |
def connection(self) -> Iterator[amqp.Connection]:
"""Returns a new connection as a context manager."""
TCP_USER_TIMEOUT = 18 # constant is available on Python 3.6+.
socket_settings = {TCP_USER_TIMEOUT: self.config.TCP_USER_TIMEOUT}
if sys.platform.startswith('darwin'):
del... | Returns a new connection as a context manager. |
def get_connection(connection='', engine_name=None, connection_type='long', **args):
"""
Creating an NamedEngine or just return existed engine instance
if '://' include in connection parameter, it'll create new engine object
otherwise return existed engine isntance
"""
engine_name = engine_name... | Creating an NamedEngine or just return existed engine instance
if '://' include in connection parameter, it'll create new engine object
otherwise return existed engine isntance |
def categorical_partition_data(data):
"""Convenience method for creating weights from categorical data.
Args:
data (list-like): The data from which to construct the estimate.
Returns:
A new partition object::
{
"partition": (list) The categorical values present... | Convenience method for creating weights from categorical data.
Args:
data (list-like): The data from which to construct the estimate.
Returns:
A new partition object::
{
"partition": (list) The categorical values present in the data
"weights": (list... |
def find_one_and_replace(self, filter, replacement,
projection=None, sort=None, upsert=False,
return_document=ReturnDocument.BEFORE, **kwargs):
"""Finds a single document and replaces it, returning either the
original or the replaced document.
... | Finds a single document and replaces it, returning either the
original or the replaced document.
The :meth:`find_one_and_replace` method differs from
:meth:`find_one_and_update` by replacing the document matched by
*filter*, rather than modifying the existing document.
>>> fo... |
def smart_scrubf(df,col_name,error_rate = 0):
""" Scrubs from the front of an 'object' column in a DataFrame
until the scrub would semantically alter the contents of the column. If only a
subset of the elements in the column are scrubbed, then a boolean array indicating which
elements have been scrubbe... | Scrubs from the front of an 'object' column in a DataFrame
until the scrub would semantically alter the contents of the column. If only a
subset of the elements in the column are scrubbed, then a boolean array indicating which
elements have been scrubbed is appended to the dataframe. Returns the string tha... |
def log_url (self, url_data):
"""
Store url check info into the database.
"""
self.writeln(u"insert into %(table)s(urlname,"
"parentname,baseref,valid,result,warning,info,url,line,col,"
"name,checktime,dltime,size,cached,level,modified) values ("
... | Store url check info into the database. |
def graftm_package_is_protein(graftm_package):
'''Return true if this package is an Amino Acid alignment package, otherwise
False i.e. it is a nucleotide package. In general it is best to use
'is_protein_package' instead.
'''
found = None
with open(graftm_package.alignme... | Return true if this package is an Amino Acid alignment package, otherwise
False i.e. it is a nucleotide package. In general it is best to use
'is_protein_package' instead. |
def parse(self, line):
"""Parse a line, return a Message.
Parameters
----------
line : str
The line to parse (should not contain the terminating newline
or carriage return).
Returns
-------
msg : Message object
The resulting M... | Parse a line, return a Message.
Parameters
----------
line : str
The line to parse (should not contain the terminating newline
or carriage return).
Returns
-------
msg : Message object
The resulting Message. |
def _create_record(self, rtype, name, content):
"""Create record. If it already exists, do nothing."""
if not self._list_records(rtype, name, content):
self._update_records([{}], {
'type': rtype,
'hostname': self._relative_name(name),
'destinat... | Create record. If it already exists, do nothing. |
def get_group_details(self, group):
""" Get the group details. """
result = {}
try:
lgroup = self._get_group(group.name)
lgroup = preload(lgroup, database=self._database)
except ObjectDoesNotExist:
return result
for i, j in lgroup.items():
... | Get the group details. |
def lock_time(logfile):
'''work out gps lock times for a log file'''
print("Processing log %s" % filename)
mlog = mavutil.mavlink_connection(filename)
locked = False
start_time = 0.0
total_time = 0.0
t = None
m = mlog.recv_match(type=['GPS_RAW_INT','GPS_RAW'], condition=args.condition)
... | work out gps lock times for a log file |
def get_service_types(self):
"""
Get all service types supported by this cluster.
@return: A list of service types (strings)
"""
resp = self._get_resource_root().get(self._path() + '/serviceTypes')
return resp[ApiList.LIST_KEY] | Get all service types supported by this cluster.
@return: A list of service types (strings) |
def cmd(send, msg, args):
"""Slap somebody.
Syntax: {command} <nick> [for <reason>]
"""
implements = ['the golden gate bridge', 'a large trout', 'a clue-by-four', 'a fresh haddock', 'moon', 'an Itanium', 'fwilson', 'a wombat']
methods = ['around a bit', 'upside the head']
if not msg:
c... | Slap somebody.
Syntax: {command} <nick> [for <reason>] |
def split_bin_edges(edges, npts=2):
"""Subdivide an array of bins by splitting each bin into ``npts``
subintervals.
Parameters
----------
edges : `~numpy.ndarray`
Bin edge array.
npts : int
Number of intervals into which each bin will be subdivided.
Returns
-------
... | Subdivide an array of bins by splitting each bin into ``npts``
subintervals.
Parameters
----------
edges : `~numpy.ndarray`
Bin edge array.
npts : int
Number of intervals into which each bin will be subdivided.
Returns
-------
edges : `~numpy.ndarray`
Subdivide... |
def getkeys(table):
"""
customize by commenting out unwanted keys
"""
keys = []
if table == "ER_expedition":
pass
if table == "ER_citations":
keys.append("er_citation_name")
keys.append("long_authors")
keys.append("year")
keys.append("title")
keys.... | customize by commenting out unwanted keys |
def save(self, obj):
""" Subclass the save method, to hash ndarray subclass, rather
than pickling them. Off course, this is a total abuse of
the Pickler class.
"""
if isinstance(obj, self.np.ndarray) and not obj.dtype.hasobject:
# Compute a hash of the object
... | Subclass the save method, to hash ndarray subclass, rather
than pickling them. Off course, this is a total abuse of
the Pickler class. |
def sync_repo(self, repo_name=None, envs=[], query='/repositories/'):
"""
Sync repository in specified environments
"""
juicer.utils.Log.log_debug(
"Sync Repo %s In: %s" % (repo_name, ",".join(envs)))
data = {
'override_config': {
'verify_... | Sync repository in specified environments |
def save_plot(self, filename, img_format="eps", ylim=None, units="thz"):
"""
Save matplotlib plot to a file.
Args:
filename: Filename to write to.
img_format: Image format to use. Defaults to EPS.
ylim: Specifies the y-axis limits.
units: units fo... | Save matplotlib plot to a file.
Args:
filename: Filename to write to.
img_format: Image format to use. Defaults to EPS.
ylim: Specifies the y-axis limits.
units: units for the frequencies. Accepted values thz, ev, mev, ha, cm-1, cm^-1. |
def set_tlsext_use_srtp(self, profiles):
"""
Enable support for negotiating SRTP keying material.
:param bytes profiles: A colon delimited list of protection profile
names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
:return: None
"""
if not is... | Enable support for negotiating SRTP keying material.
:param bytes profiles: A colon delimited list of protection profile
names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
:return: None |
def _index_action(self, payload):
"""Bulk index action.
:param payload: Decoded message body.
:returns: Dictionary defining an Elasticsearch bulk 'index' action.
"""
record = Record.get_record(payload['id'])
index, doc_type = self.record_to_index(record)
return ... | Bulk index action.
:param payload: Decoded message body.
:returns: Dictionary defining an Elasticsearch bulk 'index' action. |
def findFile(input):
"""Search a directory for full filename with optional path."""
# If no input name is provided, default to returning 'no'(FALSE)
if not input:
return no
# We use 'osfn' here to insure that any IRAF variables are
# expanded out before splitting out the path...
_fdir,... | Search a directory for full filename with optional path. |
def breakdown_tt2000(tt2000, to_np=None): # @NoSelf
"""
Breaks down the epoch(s) into UTC components.
For CDF_EPOCH:
they are 7 date/time components: year, month, day,
hour, minute, second, and millisecond
For CDF_EPOCH16:
they are 10 dat... | Breaks down the epoch(s) into UTC components.
For CDF_EPOCH:
they are 7 date/time components: year, month, day,
hour, minute, second, and millisecond
For CDF_EPOCH16:
they are 10 date/time components: year, month, day,
hour, minute, second... |
def diy(expression_data,
regressor_type,
regressor_kwargs,
gene_names=None,
tf_names='all',
client_or_address='local',
early_stop_window_length=EARLY_STOP_WINDOW_LENGTH,
limit=None,
seed=None,
verbose=False):
"""
:param expression_data: one... | :param expression_data: one of:
* a pandas DataFrame (rows=observations, columns=genes)
* a dense 2D numpy.ndarray
* a sparse scipy.sparse.csc_matrix
:param regressor_type: string. One of: 'RF', 'GBM', 'ET'. Case insensitive.
:param regressor_kwargs: a dictionary of key-value pa... |
def set_coords(self, value):
"""Set all the images contained in the animation to the specified value."""
self.__coords = value
for image in self.images:
image.coords = value | Set all the images contained in the animation to the specified value. |
def _parse_qual(self, data):
"""Parse qual attribute of the old HEPData format
example qual:
*qual: RE : P P --> Z0 Z0 X
:param data: data to be parsed
:type data: str
"""
list = []
headers = data.split(':')
name = headers[0].strip()
nam... | Parse qual attribute of the old HEPData format
example qual:
*qual: RE : P P --> Z0 Z0 X
:param data: data to be parsed
:type data: str |
def get_rank_based_enrichment(
self,
ranked_genes: List[str],
pval_thresh: float = 0.05,
X_frac: float = 0.25,
X_min: int = 5,
L: int = None,
adjust_pval_thresh: bool = True,
escore_pval_thresh: float = None,
exa... | Test for gene set enrichment at the top of a ranked list of genes.
This function uses the XL-mHG test to identify enriched gene sets.
This function also calculates XL-mHG E-scores for the enriched gene
sets, using ``escore_pval_thresh`` as the p-value threshold "psi".
Parameters
... |
async def create_rev_reg(self, rr_id: str, rr_size: int = None) -> None:
"""
Create revocation registry artifacts and new tails file (with association to
corresponding revocation registry identifier via symbolic link name)
for input revocation registry identifier. Symbolic link presence ... | Create revocation registry artifacts and new tails file (with association to
corresponding revocation registry identifier via symbolic link name)
for input revocation registry identifier. Symbolic link presence signals completion.
If revocation registry builder operates in a process external to ... |
def search(self, search, **kwargs):
"""
Search for Repository Configurations based on internal or external url, ignoring the protocol and \".git\" suffix. The matching is done using LIKE.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP reque... | Search for Repository Configurations based on internal or external url, ignoring the protocol and \".git\" suffix. The matching is done using LIKE.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be in... |
def convert_str_to_datetime(df, *, column: str, format: str):
"""
Convert string column into datetime column
---
### Parameters
*mandatory :*
- `column` (*str*): name of the column to format
- `format` (*str*): current format of the values (see [available formats](
https://docs.python... | Convert string column into datetime column
---
### Parameters
*mandatory :*
- `column` (*str*): name of the column to format
- `format` (*str*): current format of the values (see [available formats](
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior)) |
def _RegisterProcess(self, process):
"""Registers a process with the engine.
Args:
process (MultiProcessBaseProcess): process.
Raises:
KeyError: if the process is already registered with the engine.
ValueError: if the process is missing.
"""
if process is None:
raise ValueE... | Registers a process with the engine.
Args:
process (MultiProcessBaseProcess): process.
Raises:
KeyError: if the process is already registered with the engine.
ValueError: if the process is missing. |
def from_plane(cls, plane):
"""
:param plane: cadquery plane instance to base coordinate system on
:type plane: :class:`cadquery.Plane`
:return: duplicate of the given plane, in this class
:rtype: :class:`CoordSystem`
usage example:
.. doctest::
>>>... | :param plane: cadquery plane instance to base coordinate system on
:type plane: :class:`cadquery.Plane`
:return: duplicate of the given plane, in this class
:rtype: :class:`CoordSystem`
usage example:
.. doctest::
>>> import cadquery
>>> from cqparts.ut... |
def check_rollout(edits_service, package_name, days):
"""Check if package_name has a release on staged rollout for too long"""
edit = edits_service.insert(body={}, packageName=package_name).execute()
response = edits_service.tracks().get(editId=edit['id'], track='production', packageName=package_name).execu... | Check if package_name has a release on staged rollout for too long |
def _require_host_parameter(args, to):
"""
Make sure, that user specified --host argument.
"""
if not args.host:
sys.stderr.write("--host is required parameter to --%s\n" % to)
sys.exit(1) | Make sure, that user specified --host argument. |
def addup_fluxes(self):
"""Add up the sum of the fluxes calculated so far.
>>> from hydpy.models.test_v1 import *
>>> parameterstep()
>>> fluxes.fastaccess._q_sum = 1.0
>>> fluxes.q(2.0)
>>> model.addup_fluxes()
>>> fluxes.fastaccess._q_sum
3.0
""... | Add up the sum of the fluxes calculated so far.
>>> from hydpy.models.test_v1 import *
>>> parameterstep()
>>> fluxes.fastaccess._q_sum = 1.0
>>> fluxes.q(2.0)
>>> model.addup_fluxes()
>>> fluxes.fastaccess._q_sum
3.0 |
def gen_nf_quick_check(output, ascii_props=False, append=False, prefix=""):
"""Generate quick check properties."""
categories = []
nf = {}
all_chars = ALL_ASCII if ascii_props else ALL_CHARS
file_name = os.path.join(HOME, 'unicodedata', UNIVERSION, 'DerivedNormalizationProps.txt')
with codecs.o... | Generate quick check properties. |
def _get_changes(cls, diff_dict):
'''
Returns a list of string message with the differences in a diff dict.
Each inner difference is tabulated two space deeper
'''
changes_strings = []
for p in sorted(diff_dict.keys()):
if sorted(diff_dict[p].keys()) == ['new... | Returns a list of string message with the differences in a diff dict.
Each inner difference is tabulated two space deeper |
def _check_load_parameters(self, **kwargs):
"""Override method for one in resource.py to check partition
The partition cannot be included as a parameter to load a guest.
Raise an exception if a consumer gives the partition parameter.
:raises: DisallowedReadParameter
"""
... | Override method for one in resource.py to check partition
The partition cannot be included as a parameter to load a guest.
Raise an exception if a consumer gives the partition parameter.
:raises: DisallowedReadParameter |
def key_rule(self, regex, verifier):
"""Add a rule with a pattern that should apply to all keys.
Any key not explicitly listed in an add_required or add_optional rule
must match ONE OF the rules given in a call to key_rule().
So these rules are all OR'ed together.
In this case ... | Add a rule with a pattern that should apply to all keys.
Any key not explicitly listed in an add_required or add_optional rule
must match ONE OF the rules given in a call to key_rule().
So these rules are all OR'ed together.
In this case you should pass a raw string specifying a regex ... |
def get_word_before_cursor(self, WORD=False):
"""
Give the word before the cursor.
If we have whitespace before the cursor this returns an empty string.
"""
if self.text_before_cursor[-1:].isspace():
return ''
else:
return self.text_before_cursor[s... | Give the word before the cursor.
If we have whitespace before the cursor this returns an empty string. |
def _container_start_handler_factory(ion_type, before_yield=lambda c, ctx: None):
"""Generates handlers for tokens that begin with container start characters.
Args:
ion_type (IonType): The type of this container.
before_yield (Optional[callable]): Called at initialization. Accepts the first cha... | Generates handlers for tokens that begin with container start characters.
Args:
ion_type (IonType): The type of this container.
before_yield (Optional[callable]): Called at initialization. Accepts the first character's ordinal and the
current context; performs any necessary initializati... |
def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \
-> Generator[Any, None, None]:
"""
Generate the first value in each row.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
the first value of each row
"""
return... | Generate the first value in each row.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
the first value of each row |
def create_values(self, value_names):
"""Read original values from the settings or the defaults.
Parameters
----------
value_names : list of str
list of value names to read
Returns
-------
dict
dictionary with the value names as keys
... | Read original values from the settings or the defaults.
Parameters
----------
value_names : list of str
list of value names to read
Returns
-------
dict
dictionary with the value names as keys |
def update_clock(self, dt):
"""This method is called by the ClockApp whenever the timer fires
to update the clock. `dt` is a timezone-aware datetime object.
"""
dt = dt.astimezone(self.tzinfo)
fmt = "%H:%M"
if self.show_seconds:
fmt = "%H:%M:%S"
self... | This method is called by the ClockApp whenever the timer fires
to update the clock. `dt` is a timezone-aware datetime object. |
def _elements_to_dict(data, position, obj_end, opts, subdocument=None):
"""Decode a BSON document."""
if type(opts.document_class) == tuple:
result = opts.document_class[0](**opts.document_class[1]) if not subdocument else dict()
else:
result = opts.document_class() if not subdocument else d... | Decode a BSON document. |
def shutdown(self, hub=True, targets='all', block=False):
"""Shutdown the executor, including all workers and controllers.
The interface documentation for IPP is `here <http://ipyparallel.readthedocs.io/en/latest/api/ipyparallel.html#ipyparallel.Client.shutdown>`_
Kwargs:
- hub (Bo... | Shutdown the executor, including all workers and controllers.
The interface documentation for IPP is `here <http://ipyparallel.readthedocs.io/en/latest/api/ipyparallel.html#ipyparallel.Client.shutdown>`_
Kwargs:
- hub (Bool): Whether the hub should be shutdown, Default:True,
- ... |
def connection(self):
"""
Get a connection to the database or raise an exception
"""
connection = self._get_connection()
if connection:
return connection
else:
message = "GTF database needs to be created"
if self.install_string:
... | Get a connection to the database or raise an exception |
def commit(*args):
"""Commit changes to the fragments repository, limited to FILENAME(s) if specified."""
parser = argparse.ArgumentParser(prog="%s %s" % (__package__, commit.__name__), description=commit.__doc__)
parser.add_argument('FILENAME', help="file(s) to commit", nargs="*", default=['.'])
args =... | Commit changes to the fragments repository, limited to FILENAME(s) if specified. |
def receive(self, path, diffTo, diffFrom):
""" Receive a btrfs diff. """
diff = self.toObj.diff(diffTo, diffFrom)
self._open(self.butterStore.receive(diff, [path, ])) | Receive a btrfs diff. |
def handle(self, *args, **options):
"""Handle the management command."""
if mon is None:
sys.stderr.write(MISSING)
else:
mon.run(**options) | Handle the management command. |
def home(request):
"""Try to connect to database, and list available examples."""
try:
DBSession.query(User).first()
except DBAPIError:
return Response(
conn_err_msg,
content_type="text/plain",
status_int=500,
)
return {"project": "pyramid_tut... | Try to connect to database, and list available examples. |
def _parse_quniform(self, param_value):
'''parse type of quniform parameter and return a list'''
if param_value[2] < 2:
raise RuntimeError("The number of values sampled (q) should be at least 2")
low, high, count = param_value[0], param_value[1], param_value[2]
interval = (hi... | parse type of quniform parameter and return a list |
def ellipse(n=1000, adaptive=False):
"""
Get a parameterized set of vectors defining
ellipse for a major and minor axis length.
Resulting vector bundle has major axes
along axes given.
"""
u = N.linspace(0,2*N.pi,n)
# Get a bundle of vectors defining
# a full rotation around the unit... | Get a parameterized set of vectors defining
ellipse for a major and minor axis length.
Resulting vector bundle has major axes
along axes given. |
def _store_post(self, stored_entry, entry=None):
""" This method formats entry returned by _get_data() and puts to DB
create textDesc, title, and MIME """
# stored_entry.content_type = utils.get_source_setting(ds.type, 'type')
if stored_entry.published is None:
stored_... | This method formats entry returned by _get_data() and puts to DB
create textDesc, title, and MIME |
def _empty_notification(self):
""" empty and return list of message notification
"""
sess = cherrypy.session
username = sess.get(SESSION_KEY, None)
if username in self.notifications:
ret = self.notifications[username]
else:
ret = []
self.no... | empty and return list of message notification |
def _load_neighbors_from_external_source(self) -> None:
"""
Loads the neighbors of the node from the igraph `Graph` instance that is
wrapped by the graph that has this node.
"""
graph: SpotifyArtistGraph = self._graph
items: List[NameExternalIDPair] = graph.client.similar... | Loads the neighbors of the node from the igraph `Graph` instance that is
wrapped by the graph that has this node. |
def cut(self, start=0, end=-1, index=False):
"""
The method cuts the time series to reduce its length.
:param start: int or float, optional, New start point
:param end: int or float, optional, New end point
:param index: bool, optional, if False then start and end are considered ... | The method cuts the time series to reduce its length.
:param start: int or float, optional, New start point
:param end: int or float, optional, New end point
:param index: bool, optional, if False then start and end are considered values in time. |
def update(self, muted=values.unset, hold=values.unset, hold_url=values.unset,
hold_method=values.unset, announce_url=values.unset,
announce_method=values.unset, wait_url=values.unset,
wait_method=values.unset, beep_on_exit=values.unset,
end_conference_on_exit... | Update the ParticipantInstance
:param bool muted: Whether the participant should be muted
:param bool hold: Whether the participant should be on hold
:param unicode hold_url: The URL we call using the `hold_method` for music that plays when the participant is on hold
:param unicode hol... |
def _entropy(self):
"""Shannon entropy in nats."""
if any(self._dist_fn_args):
raise ValueError(
'Can only compute entropy when all distributions are independent.')
return sum(joint_distribution_lib.maybe_check_wont_broadcast(
(d().entropy() for d in self._dist_fn_wrapped),
s... | Shannon entropy in nats. |
def most_seen_creators_by_works(work_kind=None, role_name=None, num=10):
"""
Returns a QuerySet of the Creators that are associated with the most Works.
"""
return Creator.objects.by_works(kind=work_kind, role_name=role_name)[:num] | Returns a QuerySet of the Creators that are associated with the most Works. |
def maps_get_default_rules_output_rules_timebase(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_default_rules = ET.Element("maps_get_default_rules")
config = maps_get_default_rules
output = ET.SubElement(maps_get_default_rules, "output"... | Auto Generated Code |
def get_turbine_data_from_oedb(turbine_type, fetch_curve, overwrite=False):
r"""
Fetches data for one wind turbine type from the OpenEnergy Database (oedb).
If turbine data exists in local repository it is loaded from this file. The
file is created when turbine data was loaded from oedb in
:py:func... | r"""
Fetches data for one wind turbine type from the OpenEnergy Database (oedb).
If turbine data exists in local repository it is loaded from this file. The
file is created when turbine data was loaded from oedb in
:py:func:`~.load_turbine_data_from_oedb`. Use this function with
`overwrite=True` to... |
def is_writable(path):
"""Check if path has write access"""
try:
testfile = tempfile.TemporaryFile(dir=path)
testfile.close()
except OSError as e:
if e.errno == errno.EACCES: # 13
return False
return True | Check if path has write access |
def add(A, b, offset=0):
"""
Add b to the view of A in place (!).
Returns modified A.
Broadcasting is allowed, thus b can be scalar.
if offset is not zero, make sure b is of right shape!
:param ndarray A: 2 dimensional array
:param ndarray-like b: either one dimensional or scalar
:para... | Add b to the view of A in place (!).
Returns modified A.
Broadcasting is allowed, thus b can be scalar.
if offset is not zero, make sure b is of right shape!
:param ndarray A: 2 dimensional array
:param ndarray-like b: either one dimensional or scalar
:param int offset: same as in view.
:r... |
def cmd(command):
"""Send IPMI 'command' via ipmitool"""
env()
ipmi = cij.env_to_dict(PREFIX, EXPORTED + REQUIRED)
command = "ipmitool -U %s -P %s -H %s -p %s %s" % (
ipmi["USER"], ipmi["PASS"], ipmi["HOST"], ipmi["PORT"], command)
cij.info("ipmi.command: %s" % command)
return cij.ut... | Send IPMI 'command' via ipmitool |
def _apply_data_mask(self, data):
"""
Apply pre-defined masks to the data.
"""
data = self._format_data(data)
masked_data, pixels_affected = [], 0
data_mask = self._configuration.get("masks", {}).get("data", [])
for spectrum in data:
masked_spectrum ... | Apply pre-defined masks to the data. |
def token_distance(t1, t2, initial_match_penalization):
"""Calculates the edit distance between two tokens."""
if isinstance(t1, NameInitial) or isinstance(t2, NameInitial):
if t1.token == t2.token:
return 0
if t1 == t2:
return initial_match_penalization
return 1.... | Calculates the edit distance between two tokens. |
def _parse(self, stream):
"""Parse a JSON BUILD file.
Args:
builddata: dictionary of buildfile data
reponame: name of the repo that it came from
path: directory path within the repo
"""
builddata = json.load(stream)
log.debug('This is a JSON build f... | Parse a JSON BUILD file.
Args:
builddata: dictionary of buildfile data
reponame: name of the repo that it came from
path: directory path within the repo |
def _parse_tile_url(tile_url):
""" Extracts tile name, data and AWS index from tile URL
:param tile_url: Location of tile at AWS
:type: tile_url: str
:return: Tuple in a form (tile_name, date, aws_index)
:rtype: (str, str, int)
"""
props = tile_url.rsplit('/', 7)... | Extracts tile name, data and AWS index from tile URL
:param tile_url: Location of tile at AWS
:type: tile_url: str
:return: Tuple in a form (tile_name, date, aws_index)
:rtype: (str, str, int) |
def apply(
self, value, locale, currency=None, currency_digits=True,
decimal_quantization=True):
"""Renders into a string a number following the defined pattern.
Forced decimal quantization is active by default so we'll produce a
number string that is strictly following C... | Renders into a string a number following the defined pattern.
Forced decimal quantization is active by default so we'll produce a
number string that is strictly following CLDR pattern definitions. |
def name(self):
"""str: name of the file entry, which does not include the full path."""
if self._name is None:
location = getattr(self.path_spec, 'location', None)
if location is not None:
self._name = self._file_system.BasenamePath(location)
else:
volume_index = apfs_helper.A... | str: name of the file entry, which does not include the full path. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.