code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def serialise_to_nrml(self, filename, use_defaults=False):
'''
Writes the source model to a nrml source model file given by the
filename
:param str filename:
Path to output file
:param bool use_defaults:
Boolean to indicate whether to use default values ... | Writes the source model to a nrml source model file given by the
filename
:param str filename:
Path to output file
:param bool use_defaults:
Boolean to indicate whether to use default values (True) or not.
If set to False, ValueErrors will be raised when an ... |
def one_step(self, current_state, previous_kernel_results):
"""Runs one iteration of the Transformed Kernel.
Args:
current_state: `Tensor` or Python `list` of `Tensor`s
representing the current state(s) of the Markov chain(s),
_after_ application of `bijector.forward`. The first `r`
... | Runs one iteration of the Transformed Kernel.
Args:
current_state: `Tensor` or Python `list` of `Tensor`s
representing the current state(s) of the Markov chain(s),
_after_ application of `bijector.forward`. The first `r`
dimensions index independent chains,
`r = tf.rank(target... |
def centre_of_atoms(atoms, mass_weighted=True):
""" Returns centre point of any list of atoms.
Parameters
----------
atoms : list
List of AMPAL atom objects.
mass_weighted : bool, optional
If True returns centre of mass, otherwise just geometric centre of points.
Returns
--... | Returns centre point of any list of atoms.
Parameters
----------
atoms : list
List of AMPAL atom objects.
mass_weighted : bool, optional
If True returns centre of mass, otherwise just geometric centre of points.
Returns
-------
centre_of_mass : numpy.array
3D coordi... |
def _contextualise(self):
'''Determine contextual idents (cidents)'''
# loop through hierarchy identifying unique lineages
# TODO: gain other contextual information, not just ident
deja_vues = []
for rank in reversed(self.taxonomy):
# return named clades -- '' are ign... | Determine contextual idents (cidents) |
def merge(self, evaluation_context: 'EvaluationContext') -> None:
"""
Merges the provided evaluation context to the current evaluation context.
:param evaluation_context: Evaluation context to merge.
"""
self.global_context.merge(evaluation_context.global_context)
self.lo... | Merges the provided evaluation context to the current evaluation context.
:param evaluation_context: Evaluation context to merge. |
def parse(self, inputstring, parser, preargs, postargs):
"""Use the parser to parse the inputstring with appropriate setup and teardown."""
self.reset()
pre_procd = None
with logger.gather_parsing_stats():
try:
pre_procd = self.pre(inputstring, **preargs)
... | Use the parser to parse the inputstring with appropriate setup and teardown. |
def fill_wildcards(self, field=None, value=0):
"""Update wildcards attribute.
This method update a wildcards considering the attributes of the
current instance.
Args:
field (str): Name of the updated field.
value (GenericType): New value used in the field.
... | Update wildcards attribute.
This method update a wildcards considering the attributes of the
current instance.
Args:
field (str): Name of the updated field.
value (GenericType): New value used in the field. |
def num2bytes(value, size):
"""Convert an unsigned integer to MSB-first bytes with specified size."""
res = []
for _ in range(size):
res.append(value & 0xFF)
value = value >> 8
assert value == 0
return bytes(bytearray(list(reversed(res)))) | Convert an unsigned integer to MSB-first bytes with specified size. |
def token(self):
"""JSON-serializable representation of the current Stream state.
Use :func:`Engine.stream(YourModel, token) <bloop.engine.Engine.stream>` to create an identical stream,
or :func:`stream.move_to(token) <bloop.stream.Stream.move_to>` to move an existing stream to this position.
... | JSON-serializable representation of the current Stream state.
Use :func:`Engine.stream(YourModel, token) <bloop.engine.Engine.stream>` to create an identical stream,
or :func:`stream.move_to(token) <bloop.stream.Stream.move_to>` to move an existing stream to this position.
:returns: Stream sta... |
def pkg_by_name(self, name):
"""
Return a single package that matches name.
"""
pkgmatches = self.all_pkgs_by_name(name)
if (len(pkgmatches) != 0):
return self.all_pkgs_by_name(name)[-1]
else:
return None | Return a single package that matches name. |
def is_method(func):
"""Detects if the given callable is a method. In context of pytypes this
function is more reliable than plain inspect.ismethod, e.g. it automatically
bypasses wrappers from typechecked and override decorators.
"""
func0 = _actualfunc(func)
argNames = getargnames(getargspecs(... | Detects if the given callable is a method. In context of pytypes this
function is more reliable than plain inspect.ismethod, e.g. it automatically
bypasses wrappers from typechecked and override decorators. |
def mr(items, targets, **kwargs):
"""Max-Rest
Complexity O(n^2)
"""
bins = [(target, []) for target in targets]
skip = []
for item in items:
capacities = [target - sum(content) for target, content in bins]
weighted = weight(capacities, **kwargs)
(target, content), capa... | Max-Rest
Complexity O(n^2) |
def make_zip(folder_path, output_filename):
"""将目录中除zip之外的文件打包成zip文件(包括子文件夹)
空文件夹不会被打包
example
----------------
make_zip('results','zips//招标信息结果_2017-05-09.zip')
"""
cwd = os.getcwd()
# 获取需要打包的文件列表
file_lists = []
for root, dirs, files in os.walk(folder_path):
for file ... | 将目录中除zip之外的文件打包成zip文件(包括子文件夹)
空文件夹不会被打包
example
----------------
make_zip('results','zips//招标信息结果_2017-05-09.zip') |
def _hasExplicitOid(store, table):
"""
Does the given table have an explicit oid column?
"""
return any(info[1] == 'oid' for info
in store.querySchemaSQL(
'PRAGMA *DATABASE*.table_info({})'.format(table))) | Does the given table have an explicit oid column? |
def shorrocks_index(A):
r"""
Implements Shorrocks mobility index
Parameters
-----------
A : array_like(float)
Square matrix with transition probabilities (mobility matrix) of
dimension m
Returns
--------
Shorrocks index: float
The Shorrocks mobility index calcul... | r"""
Implements Shorrocks mobility index
Parameters
-----------
A : array_like(float)
Square matrix with transition probabilities (mobility matrix) of
dimension m
Returns
--------
Shorrocks index: float
The Shorrocks mobility index calculated as
.. math::
... |
def reverse_geocode(self, lat, lng, **kwargs):
"""
Given a latitude & longitude, return an address for that point from OpenCage's Geocoder.
:param lat: Latitude
:param lng: Longitude
:return: Results from OpenCageData
:rtype: dict
:raises RateLimitExceededError: ... | Given a latitude & longitude, return an address for that point from OpenCage's Geocoder.
:param lat: Latitude
:param lng: Longitude
:return: Results from OpenCageData
:rtype: dict
:raises RateLimitExceededError: if you have exceeded the number of queries you can make. Exception ... |
def validate_full_name(self, full_name, timeout=-1):
"""
Verifies if a fullName is already in use.
Args:
full_name:
The fullName to be verified.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort t... | Verifies if a fullName is already in use.
Args:
full_name:
The fullName to be verified.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in
OneView, just stops waiting for its compl... |
def getPluginDescriptor(self, dir):
"""
Detects the .uplugin descriptor file for the Unreal plugin in the specified directory
"""
for plugin in glob.glob(os.path.join(dir, '*.uplugin')):
return os.path.realpath(plugin)
# No plugin detected
raise UnrealManagerException('could not detect an Unreal plugi... | Detects the .uplugin descriptor file for the Unreal plugin in the specified directory |
def _CalculateAttributeStorageTypes(self):
"""Build a mapping between column names and types."""
self.attribute_types = {}
for attribute in itervalues(aff4.Attribute.PREDICATES):
self.attribute_types[attribute.predicate] = (
attribute.attribute_type.data_store_type) | Build a mapping between column names and types. |
def last(symbols=None, token='', version=''):
'''Last provides trade data for executions on IEX. It is a near real time, intraday API that provides IEX last sale price, size and time.
Last is ideal for developers that need a lightweight stock quote.
https://iexcloud.io/docs/api/#last
Args:
sym... | Last provides trade data for executions on IEX. It is a near real time, intraday API that provides IEX last sale price, size and time.
Last is ideal for developers that need a lightweight stock quote.
https://iexcloud.io/docs/api/#last
Args:
symbol (string); Ticker to request
token (string... |
def search_registered_query_deleted_for_facet(self, facet, **kwargs): # noqa: E501
"""Lists the values of a specific facet over the customer's deleted derived metric definitions # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronou... | Lists the values of a specific facet over the customer's deleted derived metric definitions # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.search_registered_query_del... |
def setup_variables(self):
"""
Set up variables.
"""
if self.input_tensor:
if type(self.input_tensor) == int:
x = dim_to_var(self.input_tensor, name="x")
else:
x = self.input_tensor
else:
x = T.matrix('x')
... | Set up variables. |
def summary(self, alpha=0.05, start=0, batches=100, chain=None, roundto=3):
"""
Generate a pretty-printed summary of the node.
:Parameters:
alpha : float
The alpha level for generating posterior intervals. Defaults to
0.05.
start : int
The starting... | Generate a pretty-printed summary of the node.
:Parameters:
alpha : float
The alpha level for generating posterior intervals. Defaults to
0.05.
start : int
The starting index from which to summarize (each) chain. Defaults
to zero.
batches : int
... |
def dimension_size(x, axis):
"""Returns the size of a specific dimension."""
# Since tf.gather isn't "constant-in, constant-out", we must first check the
# static shape or fallback to dynamic shape.
s = tf.compat.dimension_value(
tensorshape_util.with_rank_at_least(x.shape, np.abs(axis))[axis])
if s is ... | Returns the size of a specific dimension. |
def make_variant(cls, converters, re_opts=None, compiled=False, strict=True):
"""
Creates a type converter for a number of type converter alternatives.
The first matching type converter is used.
REQUIRES: type_converter.pattern attribute
:param converters: List of type converte... | Creates a type converter for a number of type converter alternatives.
The first matching type converter is used.
REQUIRES: type_converter.pattern attribute
:param converters: List of type converters as alternatives.
:param re_opts: Regular expression options zu use (=default_re_opts).... |
def call_each_reversed(funcs: list, *args, **kwargs):
'''
call each func from reversed func list.
return the last func value or None if func list is empty.
'''
ret = None
for func in reversed(funcs):
ret = func(*args, **kwargs)
return ret | call each func from reversed func list.
return the last func value or None if func list is empty. |
def diff_flux_threshold(self, skydir, fn, ts_thresh, min_counts):
"""Compute the differential flux threshold for a point source at
position ``skydir`` with spectral parameterization ``fn``.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
Sky coordinate... | Compute the differential flux threshold for a point source at
position ``skydir`` with spectral parameterization ``fn``.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
Sky coordinates at which the sensitivity will be evaluated.
fn : `~fermipy.spectru... |
def _create_resource(resource, name=None, tags=None, region=None, key=None,
keyid=None, profile=None, **kwargs):
'''
Create a VPC resource. Returns the resource id if created, or False
if not created.
'''
try:
try:
conn = _get_conn(region=region, key=key, ke... | Create a VPC resource. Returns the resource id if created, or False
if not created. |
def show_lbaas_member(self, lbaas_member, lbaas_pool, **_params):
"""Fetches information of a certain lbaas_member."""
return self.get(self.lbaas_member_path % (lbaas_pool, lbaas_member),
params=_params) | Fetches information of a certain lbaas_member. |
def py_to_weld_type(self, obj):
"""Summary
Args:
obj (TYPE): Description
Returns:
TYPE: Description
Raises:
Exception: Description
"""
if isinstance(obj, np.ndarray):
dtype = str(obj.dtype)
if dtype == 'int16'... | Summary
Args:
obj (TYPE): Description
Returns:
TYPE: Description
Raises:
Exception: Description |
def get_context_data(self, **kwargs):
"""Includes the Gauge slugs and data in the context."""
data = super(GaugesView, self).get_context_data(**kwargs)
data.update({'gauges': get_r().gauge_slugs()})
return data | Includes the Gauge slugs and data in the context. |
def prepare(self, query, custom_payload=None, keyspace=None):
"""
Prepares a query string, returning a :class:`~cassandra.query.PreparedStatement`
instance which can be used as follows::
>>> session = cluster.connect("mykeyspace")
>>> query = "INSERT INTO users (id, name... | Prepares a query string, returning a :class:`~cassandra.query.PreparedStatement`
instance which can be used as follows::
>>> session = cluster.connect("mykeyspace")
>>> query = "INSERT INTO users (id, name, age) VALUES (?, ?, ?)"
>>> prepared = session.prepare(query)
... |
def rpc_connect(self):
"""Connect to a coin daemon's JSON RPC interface.
Returns:
bool: True if successfully connected, False otherwise.
"""
if self.coin in COINS:
rpc_url = COINS[self.coin]["rpc-url"] + ":"
if self.testnet:
rpc_url += ... | Connect to a coin daemon's JSON RPC interface.
Returns:
bool: True if successfully connected, False otherwise. |
def ctype_class(self):
"""Summary
Returns:
TYPE: Description
"""
def vec_factory(elemType):
"""Summary
Args:
elemType (TYPE): Description
Returns:
TYPE: Description
"""
class Vec(St... | Summary
Returns:
TYPE: Description |
async def findArtifactFromTask(self, *args, **kwargs):
"""
Get Artifact From Indexed Task
Find a task by index path and redirect to the artifact on the most recent
run with the given `name`.
Note that multiple calls to this endpoint may return artifacts from differen tasks
... | Get Artifact From Indexed Task
Find a task by index path and redirect to the artifact on the most recent
run with the given `name`.
Note that multiple calls to this endpoint may return artifacts from differen tasks
if a new task is inserted into the index between calls. Avoid using thi... |
def raise_db_exception(self):
""" Raises exception from last server message
This function will skip messages: The statement has been terminated
"""
if not self.messages:
raise tds_base.Error("Request failed, server didn't send error message")
msg = None
while... | Raises exception from last server message
This function will skip messages: The statement has been terminated |
def destroy(self):
"""
Destroy the record
"""
return self.get_data(
"domains/%s/records/%s" % (self.domain, self.id),
type=DELETE,
) | Destroy the record |
def fragment(self, fragment_size, mask=False):
"""
Fragment the frame into a chain of fragment frames:
- An initial frame with non-zero opcode
- Zero or more frames with opcode = 0 and final = False
- A final frame with opcode = 0 and final = True
The first and last fram... | Fragment the frame into a chain of fragment frames:
- An initial frame with non-zero opcode
- Zero or more frames with opcode = 0 and final = False
- A final frame with opcode = 0 and final = True
The first and last frame may be the same frame, having a non-zero
opcode and final... |
def _module_info_from_proto_safe(module_info_def, import_scope=None):
"""Deserializes the `module_info_def` proto without raising exceptions.
Args:
module_info_def: An instance of `module_pb2.SonnetModule`.
import_scope: Optional `string`. Name scope to use.
Returns:
An instance of `ModuleInfo`.
"... | Deserializes the `module_info_def` proto without raising exceptions.
Args:
module_info_def: An instance of `module_pb2.SonnetModule`.
import_scope: Optional `string`. Name scope to use.
Returns:
An instance of `ModuleInfo`. |
def isSameHVal(a: Value, b: Value) -> bool:
"""
:return: True if two Value instances are same
:note: not just equal
"""
return a is b or (isinstance(a, Value)
and isinstance(b, Value)
and a.val == b.val
and a.vldMask == b.vldMask) | :return: True if two Value instances are same
:note: not just equal |
def path(self, which=None):
"""Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
smart_class_parameters
/api/environments/:environment_id/smart_class_parameters
Otherwise, call ``super``.
"""
if... | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
smart_class_parameters
/api/environments/:environment_id/smart_class_parameters
Otherwise, call ``super``. |
def ec2_credentials_get(user_id=None, name=None, access=None,
profile=None, **connection_args):
'''
Return ec2_credentials for a user (keystone ec2-credentials-get)
CLI Examples:
.. code-block:: bash
salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e6708... | Return ec2_credentials for a user (keystone ec2-credentials-get)
CLI Examples:
.. code-block:: bash
salt '*' keystone.ec2_credentials_get c965f79c4f864eaaa9c3b41904e67082 access=722787eb540849158668370
salt '*' keystone.ec2_credentials_get user_id=c965f79c4f864eaaa9c3b41904e67082 access=72278... |
def connect(self, hostname, port=SSH_PORT, username=None, password=None, pkey=None,
key_filename=None, timeout=None, allow_agent=True, look_for_keys=True,
compress=False, sock=None):
"""
Connect to an SSH server and authenticate to it. The server's host key
is ch... | Connect to an SSH server and authenticate to it. The server's host key
is checked against the system host keys (see `load_system_host_keys`)
and any local host keys (`load_host_keys`). If the server's hostname
is not found in either set of host keys, the missing host key policy
is used... |
def write(self, data):
"""
Write ``data`` to the file.
:type data: bytes
:param data: the data to be written to the file
:rtype: int
:return: the number of bytes written
"""
_complain_ifclosed(self.closed)
if self.__encoding:
self.f.wr... | Write ``data`` to the file.
:type data: bytes
:param data: the data to be written to the file
:rtype: int
:return: the number of bytes written |
def teardown(self):
"""Restores all doubled objects to their original state."""
for proxy in self._proxies.values():
proxy.restore_original_object()
for patch in self._patches.values():
patch.restore_original_object() | Restores all doubled objects to their original state. |
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = dat... | The target function to call that will create the parallel thread/process |
def _readXputMaps(self, mapCards, directory, session, spatial=False, spatialReferenceID=4236, replaceParamFile=None):
"""
GSSHA Project Read Map Files from File Method
"""
if self.mapType in self.MAP_TYPES_SUPPORTED:
for card in self.projectCards:
if (card.nam... | GSSHA Project Read Map Files from File Method |
def version_diff(version1, version2):
"""Return string representing the diff between package versions.
We're interested in whether this is a major, minor, patch or 'other'
update. This method will compare the two versions and return None if
they are the same, else it will return a string value indicati... | Return string representing the diff between package versions.
We're interested in whether this is a major, minor, patch or 'other'
update. This method will compare the two versions and return None if
they are the same, else it will return a string value indicating the
type of diff - 'major', 'minor', '... |
def doTransaction(conn, start=True, startSQL='START TRANSACTION'):
'''
wrap a connection in a transaction. starts a transaction, yields the conn, and then if an exception occurs, calls rollback(). otherwise calls commit().
start: if True, executes 'START TRANSACTION' sql before yielding conn. Useful for ... | wrap a connection in a transaction. starts a transaction, yields the conn, and then if an exception occurs, calls rollback(). otherwise calls commit().
start: if True, executes 'START TRANSACTION' sql before yielding conn. Useful for connections that are autocommit by default.
startSQL: override if 'START TR... |
def _initializes_minimum_needs_fields():
"""Initialize minimum needs fields.
Minimum needs definitions are taken from currently used profile.
"""
needs_profile = NeedsProfile()
needs_profile.load()
fields = []
needs_parameters = needs_profile.get_needs_parameters()
for need_parameter ... | Initialize minimum needs fields.
Minimum needs definitions are taken from currently used profile. |
def verify_type_product(self, satellite):
"""Gets satellite id """
if satellite == 'L5':
id_satellite = '3119'
stations = ['GLC', 'ASA', 'KIR', 'MOR', 'KHC', 'PAC', 'KIS', 'CHM', 'LGS', 'MGR', 'COA', 'MPS']
elif satellite == 'L7':
id_satellite = '3373'
... | Gets satellite id |
def from_master_secret(cls, seed, network="bitcoin_testnet"):
"""Generate a new PrivateKey from a secret key.
:param seed: The key to use to generate this wallet. It may be a long
string. Do not use a phrase from a book or song, as that will
be guessed and is not secure. My advi... | Generate a new PrivateKey from a secret key.
:param seed: The key to use to generate this wallet. It may be a long
string. Do not use a phrase from a book or song, as that will
be guessed and is not secure. My advice is to not supply this
argument and let me generate a new r... |
def cumulant(self, n, k, error=False):
r"""
Calculate `c_n\{k\}`,
the `k`-particle cumulant for `n`\ th-order anisotropy.
:param int n: Anisotropy order.
:param int k: Correlation order.
:param bool error:
Whether to calculate statistical error (for `c_n\{2\... | r"""
Calculate `c_n\{k\}`,
the `k`-particle cumulant for `n`\ th-order anisotropy.
:param int n: Anisotropy order.
:param int k: Correlation order.
:param bool error:
Whether to calculate statistical error (for `c_n\{2\}` only).
If true, return a tuple `... |
def get_brokers(self):
"""
Parses the KAKFA_URL and returns a list of hostname:port pairs in the format
that kafka-python expects.
"""
return ['{}:{}'.format(parsedUrl.hostname, parsedUrl.port) for parsedUrl in
[urlparse(url) for url in self.kafka_url.split(',')]] | Parses the KAKFA_URL and returns a list of hostname:port pairs in the format
that kafka-python expects. |
def get_by_provider_display_name(self, provider_display_name):
"""
Gets a SAN Manager by provider display name.
Args:
provider_display_name: Name of the Provider Display Name
Returns:
dict: SAN Manager.
"""
san_managers = self._client.get_all()
... | Gets a SAN Manager by provider display name.
Args:
provider_display_name: Name of the Provider Display Name
Returns:
dict: SAN Manager. |
def extract(self, progress = True, recurse = True, tex_only = False,
extract_manifest = False, path = None, **kwargs):
if path is None:
path = self.folder_out
if tex_only:
kwargs['use_cache'] = False
utils.mkdir_silent(path)
utime(path, (self.time, sel... | to_extract = (f for f in self.tree.all_files if not(tex_only and not isinstance(f, ImageFile) and not isinstance(f, ImageCanvas)))
p = Pool()
args = zip(to_extract, itertools.cycle((path,)), itertools.cycle((kwargs,)))
to_recurse = []
for f in tqdm(p.imap_unordered(_extract, args)):
... |
def multilabel_accuracy_matchk(predictions,
labels,
k,
weights_fn=common_layers.weights_nonzero):
"""Used to evaluate the VQA accuracy.
Let n be the times that predictions appear in labels, then final score
is min(n/k, 1... | Used to evaluate the VQA accuracy.
Let n be the times that predictions appear in labels, then final score
is min(n/k, 1).
Refer to https://arxiv.org/pdf/1505.00468.pdf.
Args:
predictions: A tensor with shape [batch_size, 1, 1, 1, vocab_size].
labels: A tensor with shape [batch_size, length, 1, 1].
... |
def load_texture(self, file_path):
"""Generate our sprite's surface by loading the specified image from disk.
Note that this automatically centers the origin."""
self.image = pygame.image.load(file_path)
self.apply_texture(self.image) | Generate our sprite's surface by loading the specified image from disk.
Note that this automatically centers the origin. |
def src_new(converter_type, channels):
"""Initialise a new sample rate converter.
Parameters
----------
converter_type : int
Converter to be used.
channels : int
Number of channels.
Returns
-------
state
An anonymous pointer to the internal state of the converte... | Initialise a new sample rate converter.
Parameters
----------
converter_type : int
Converter to be used.
channels : int
Number of channels.
Returns
-------
state
An anonymous pointer to the internal state of the converter.
error : int
Error code. |
def set_perspective(self, fov, aspect, near, far):
"""Set the perspective
Parameters
----------
fov : float
Field of view.
aspect : float
Aspect ratio.
near : float
Near location.
far : float
Far location.
"... | Set the perspective
Parameters
----------
fov : float
Field of view.
aspect : float
Aspect ratio.
near : float
Near location.
far : float
Far location. |
def parse_args(kwargs, defaults=None):
"""Apply command line arguments or show help.
Use this in conjunction with the fire library to quickly build
command line interfaces for your scripts.
This function returns another function that must be called with
the estimator (e.g. ``NeuralNet``) to apply ... | Apply command line arguments or show help.
Use this in conjunction with the fire library to quickly build
command line interfaces for your scripts.
This function returns another function that must be called with
the estimator (e.g. ``NeuralNet``) to apply the parsed command
line arguments. If the ... |
def __marshal_matches(matched):
"""Convert matches to JSON format.
:param matched: a list of matched identities
:returns json_matches: a list of matches in JSON format
"""
json_matches = []
for m in matched:
identities = [i.uuid for i in m]
if l... | Convert matches to JSON format.
:param matched: a list of matched identities
:returns json_matches: a list of matches in JSON format |
def add_resource_url(self, url, mimetype, placement=None):
"""
Add a resource by URL needed by this Fragment.
Other helpers, such as :func:`add_css_url` or
:func:`add_javascript_url` are more convenent for those common types of
resource.
`url`: the URL to the resource.
... | Add a resource by URL needed by this Fragment.
Other helpers, such as :func:`add_css_url` or
:func:`add_javascript_url` are more convenent for those common types of
resource.
`url`: the URL to the resource.
Other parameters are as defined for :func:`add_resource`. |
def _get_credentials(username=None, password=None, dbhost=None):
"""Obtain user credentials by arguments or asking the user"""
# Database salt
system_config = dbhost.objectmodels['systemconfig'].find_one({
'active': True
})
try:
salt = system_config.salt.encode('ascii')
except ... | Obtain user credentials by arguments or asking the user |
def publish(self, **kwargs):
"""
Publishes the global workflow, so all users can find it and use it on the platform.
The current user must be a developer of the workflow.
"""
if self._dxid is not None:
return dxpy.api.global_workflow_publish(self._dxid, **kwargs)
... | Publishes the global workflow, so all users can find it and use it on the platform.
The current user must be a developer of the workflow. |
def getPartitionId(self, i):
"""
Gets the partition id given an index.
:param i: index of partition
:returns: the partition id associated with pattern i. Returns None if no id
is associated with it.
"""
if (i < 0) or (i >= self._numPatterns):
raise RuntimeError("index out of bound... | Gets the partition id given an index.
:param i: index of partition
:returns: the partition id associated with pattern i. Returns None if no id
is associated with it. |
def _convert_to_style(cls, style_dict, num_format_str=None):
"""
converts a style_dict to an xlwt style object
Parameters
----------
style_dict : style dictionary to convert
num_format_str : optional number format string
"""
import xlwt
if style_d... | converts a style_dict to an xlwt style object
Parameters
----------
style_dict : style dictionary to convert
num_format_str : optional number format string |
def _find_matching_instance(cache_key):
"""Find a running TensorBoard instance compatible with the cache key.
Returns:
A `TensorBoardInfo` object, or `None` if none matches the cache key.
"""
infos = get_all()
candidates = [info for info in infos if info.cache_key == cache_key]
for candidate in sorted(... | Find a running TensorBoard instance compatible with the cache key.
Returns:
A `TensorBoardInfo` object, or `None` if none matches the cache key. |
def get_attrtext(value):
"""attrtext = 1*(any non-ATTRIBUTE_ENDS character)
We allow any non-ATTRIBUTE_ENDS in attrtext, but add defects to the
token's defects list if we find non-attrtext characters. We also register
defects for *any* non-printables even though the RFC doesn't exclude all of
them... | attrtext = 1*(any non-ATTRIBUTE_ENDS character)
We allow any non-ATTRIBUTE_ENDS in attrtext, but add defects to the
token's defects list if we find non-attrtext characters. We also register
defects for *any* non-printables even though the RFC doesn't exclude all of
them, because we follow the spirit o... |
def processSquarePayment(request):
'''
This view handles the charging of approved Square Checkout payments.
All Checkout payments must either be associated with a pre-existing Invoice
or a registration, or they must have an amount and type passed in the post data
(such as gift certificate payment r... | This view handles the charging of approved Square Checkout payments.
All Checkout payments must either be associated with a pre-existing Invoice
or a registration, or they must have an amount and type passed in the post data
(such as gift certificate payment requests). |
def _set_cached_value(self, xblock, value):
"""Store a value in the xblock's cache, creating the cache if necessary."""
# pylint: disable=protected-access
if not hasattr(xblock, '_field_data_cache'):
xblock._field_data_cache = {}
xblock._field_data_cache[self.name] = value | Store a value in the xblock's cache, creating the cache if necessary. |
def get_data(self, datasource, callback):
"""
Сохранение медиафайла
:param task:
:param media_metadata:
:param file_suffix:
:param callback:
:return:
"""
task = self.__app.worker.current_task
media_metadata = datasource.connector_type_prese... | Сохранение медиафайла
:param task:
:param media_metadata:
:param file_suffix:
:param callback:
:return: |
def get_area_slices(data_area, area_to_cover):
"""Compute the slice to read from an *area* based on an *area_to_cover*."""
if data_area.proj_dict['proj'] != 'geos':
raise NotImplementedError('Only geos supported')
# Intersection only required for two different projections
if area_to_cover.proj... | Compute the slice to read from an *area* based on an *area_to_cover*. |
def add_pooling_with_padding_types(builder, name, height, width, stride_height, stride_width,
layer_type, padding_type, input_name, output_name,
padding_top = 0, padding_bottom = 0, padding_left = 0, padding_right = 0,
same_padding_asymmetry_mode = 'BOTTOM_RIGHT_HEAVY',
exclude_pad_a... | Add a pooling layer to the model.
This is our own implementation of add_pooling since current CoreML's version (0.5.0) of builder
doesn't provide support for padding types apart from valid. This support will be added in the
next release of coremltools. When that happens, this can be removed.
Par... |
def DiffArrayObjects(self, oldObj, newObj, isElementLinks=False):
"""Method which deligates the diffing of arrays based on the type"""
if oldObj == newObj:
return True
if not oldObj or not newObj:
return False
if len(oldObj) != len(newObj):
__Log__.debug('DiffArrayObje... | Method which deligates the diffing of arrays based on the type |
def sandbox_status(self, vm_name=None):
'''
Returns the status of the sandbox mode.
Possible values are:
- on
- off
- unknown
- not installed
'''
vagrant_sandbox_output = self._run_sandbox_command(['status', vm_name])
return self._parse_va... | Returns the status of the sandbox mode.
Possible values are:
- on
- off
- unknown
- not installed |
def get_actor(self, aid, check_monitor=True):
'''Given an actor unique id return the actor proxy.
'''
aid = actor_identity(aid)
return self._concurrency.get_actor(self, aid,
check_monitor=check_monitor) | Given an actor unique id return the actor proxy. |
def _copy_static_assets(self, output_dir):
"""Copy assets for the report to `output_dir`.
:param output_dir: directory to output assets to
:type output_dir: `str`
"""
base_directory = 'assets/{}'.format(self._report_name)
for asset in resource_listdir(self._package_name... | Copy assets for the report to `output_dir`.
:param output_dir: directory to output assets to
:type output_dir: `str` |
def parse_response(cls, response, **kwargs):
"""Parse the server response for this put file command
This will parse xml of the following form::
<put_file />
or with an error::
<put_file>
<error ... />
</put_file>
:param response: T... | Parse the server response for this put file command
This will parse xml of the following form::
<put_file />
or with an error::
<put_file>
<error ... />
</put_file>
:param response: The XML root of the response for a put file command
... |
def make_redirect_url(self, path_info, query_args=None, domain_part=None):
"""Creates a redirect URL.
:internal:
"""
suffix = ""
if query_args:
suffix = "?" + self.encode_query_args(query_args)
return str(
"%s://%s/%s%s"
% (
... | Creates a redirect URL.
:internal: |
def delete_service_settings_on_service_delete(sender, instance, **kwargs):
""" Delete not shared service settings without services """
service = instance
try:
service_settings = service.settings
except ServiceSettings.DoesNotExist:
# If this handler works together with delete_service_set... | Delete not shared service settings without services |
def run(align_bams, items, ref_file, assoc_files, region=None, out_file=None):
"""Run tumor only pisces calling
Handles bgzipping output file and fixing VCF sample naming to match BAM sample.
"""
paired = vcfutils.get_paired_bams(align_bams, items)
assert paired and not paired.normal_bam, ("Pisces ... | Run tumor only pisces calling
Handles bgzipping output file and fixing VCF sample naming to match BAM sample. |
def indicators_from_tag(self, indicator, tag_name, filters=None, params=None):
"""
Args:
indicator:
tag_name:
filters:
params:
Return:
"""
params = params or {}
for t in sel... | Args:
indicator:
tag_name:
filters:
params:
Return: |
def read(self, entity=None, attrs=None, ignore=None, params=None):
"""Fetch as many attributes as possible for this entity.
Do not read the ``facts``, ``organization`` or ``type`` attributes.
For more information, see `Bugzilla #1202917
<https://bugzilla.redhat.com/show_bug.cgi?id=12029... | Fetch as many attributes as possible for this entity.
Do not read the ``facts``, ``organization`` or ``type`` attributes.
For more information, see `Bugzilla #1202917
<https://bugzilla.redhat.com/show_bug.cgi?id=1202917>`_. |
def event_text(self, event):
"""Returns a textual explanation of a given event object
:param event: an PSrvEvent struct object
:returns: the error string
"""
logger.debug("error text for %s" % hex(event.EvtCode))
len_ = 1024
text_type = ctypes.c_char * len_
... | Returns a textual explanation of a given event object
:param event: an PSrvEvent struct object
:returns: the error string |
def join(self, network):
"""
Join a zerotier network
:param network: network id to join
:return:
"""
args = {'network': network}
self._network_chk.check(args)
response = self._client.raw('zerotier.join', args)
result = response.get()
if r... | Join a zerotier network
:param network: network id to join
:return: |
def phase_identification_parameter(V, dP_dT, dP_dV, d2P_dV2, d2P_dVdT):
r'''Calculate the Phase Identification Parameter developed in [1]_ for
the accurate and efficient determination of whether a fluid is a liquid or
a gas based on the results of an equation of state. For supercritical
conditions, thi... | r'''Calculate the Phase Identification Parameter developed in [1]_ for
the accurate and efficient determination of whether a fluid is a liquid or
a gas based on the results of an equation of state. For supercritical
conditions, this provides a good method for choosing which property
correlations to us... |
def replace(self, key, initial_value, new_value):
"""Atomically replace the value of a key with a new value.
This compares the current value of a key, then replaces it with a new
value if it is equal to a specified value. This operation takes place
in a transaction.
:param key:... | Atomically replace the value of a key with a new value.
This compares the current value of a key, then replaces it with a new
value if it is equal to a specified value. This operation takes place
in a transaction.
:param key: key in etcd to replace
:param initial_value: old val... |
def make_features(context, frmat='table', str_maximal=False):
"""Return a new feature system from context string in the given format.
Args:
context (str): Formal context table as plain-text string.
frmat: Format of the context string (``'table'``, ``'cxt'``, ``'csv'``).
str_maximal (boo... | Return a new feature system from context string in the given format.
Args:
context (str): Formal context table as plain-text string.
frmat: Format of the context string (``'table'``, ``'cxt'``, ``'csv'``).
str_maximal (bool):
Example:
>>> make_features('''
... |+ma... |
def lifecycle_lock(self):
"""An identity-keyed inter-process lock for safeguarding lifecycle and other operations."""
safe_mkdir(self._metadata_base_dir)
return OwnerPrintingInterProcessFileLock(
# N.B. This lock can't key into the actual named metadata dir (e.g. `.pids/pantsd/lock`
# via `Proce... | An identity-keyed inter-process lock for safeguarding lifecycle and other operations. |
def _get_hold(line, pattern=__HOLD_PATTERN, full=True):
'''
Resolve a package name from a line containing the hold expression. If the
regex is not matched, None is returned.
yum ==> 2:vim-enhanced-7.4.629-5.el6.*
dnf ==> vim-enhanced-2:7.4.827-1.fc22.*
'''
if full:
if _yum() == 'dnf... | Resolve a package name from a line containing the hold expression. If the
regex is not matched, None is returned.
yum ==> 2:vim-enhanced-7.4.629-5.el6.*
dnf ==> vim-enhanced-2:7.4.827-1.fc22.* |
def post(self):
"""POST item to Model
---
post:
requestBody:
description: Model schema
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/{{self.__class__.__name__}}.post'
... | POST item to Model
---
post:
requestBody:
description: Model schema
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/{{self.__class__.__name__}}.post'
responses:
... |
def receive_request(self, transaction):
"""
checks the cache for a response to the request
:param transaction:
:return:
"""
transaction.cached_element = self.cache.search_response(transaction.request)
if transaction.cached_element is None:
transactio... | checks the cache for a response to the request
:param transaction:
:return: |
def aggregate_raw_batches(self, pipeline, **kwargs):
"""Perform an aggregation and retrieve batches of raw BSON.
Similar to the :meth:`aggregate` method but returns each batch as bytes.
This example demonstrates how to work with raw batches, but in practice
raw batches should be passed... | Perform an aggregation and retrieve batches of raw BSON.
Similar to the :meth:`aggregate` method but returns each batch as bytes.
This example demonstrates how to work with raw batches, but in practice
raw batches should be passed to an external library that can decode
BSON into anothe... |
def step(self, observation, **extra_feed):
"""
Compute next action(s) given the observation(s)
Parameters:
----------
observation observation data (either single or a batch)
**extra_feed additional data such as state or mask (names of the arguments should match ... | Compute next action(s) given the observation(s)
Parameters:
----------
observation observation data (either single or a batch)
**extra_feed additional data such as state or mask (names of the arguments should match the ones in constructor, see __init__)
Returns:
... |
def update(self, **kwargs):
"""When setting useProxyServer to enable we need to supply
proxyServerPool value as well
"""
if 'useProxyServer' in kwargs and kwargs['useProxyServer'] == 'enabled':
if 'proxyServerPool' not in kwargs:
error = 'Missing proxySer... | When setting useProxyServer to enable we need to supply
proxyServerPool value as well |
def request(self, method, path, contents, headers, decode_json=False,
stream=False, query=None, cdn=False):
"""
See :py:func:`swiftly.client.client.Client.request`
"""
if query:
path += '?' + '&'.join(
('%s=%s' % (quote(k), quote(v)) if v else ... | See :py:func:`swiftly.client.client.Client.request` |
def unique_string(length=UUID_LENGTH):
'''Generate a unique string'''
# We need a string at least as long as length
string = str(uuid4()) * int(math.ceil(length / float(UUID_LENGTH)))
return string[:length] if length else string | Generate a unique string |
def add_entity_errors(
self,
property_name,
direct_errors=None,
schema_errors=None
):
"""
Attach nested entity errors
Accepts a list errors coming from validators attached directly,
or a dict of errors produced by a nested schema.
:param prope... | Attach nested entity errors
Accepts a list errors coming from validators attached directly,
or a dict of errors produced by a nested schema.
:param property_name: str, property name
:param direct_errors: list, errors from validators attached directly
:param schema_errors: dict, ... |
def parameters(self):
"""
Get the dictionary of parameters (either ra,dec or l,b)
:return: dictionary of parameters
"""
if self._coord_type == 'galactic':
return collections.OrderedDict((('l', self.l), ('b', self.b)))
else:
return collections.... | Get the dictionary of parameters (either ra,dec or l,b)
:return: dictionary of parameters |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.