code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def construct_publish_comands(additional_steps=None, nightly=False):
'''Get the shell commands we'll use to actually build and publish a package to PyPI.'''
publish_commands = (
['rm -rf dist']
+ (additional_steps if additional_steps else [])
+ [
'python setup.py sdist bdist_... | Get the shell commands we'll use to actually build and publish a package to PyPI. |
def set_xticks(self, row, column, ticks):
"""Manually specify the x-axis tick values.
:param row,column: specify the subplot.
:param ticks: list of tick values.
"""
subplot = self.get_subplot_at(row, column)
subplot.set_xticks(ticks) | Manually specify the x-axis tick values.
:param row,column: specify the subplot.
:param ticks: list of tick values. |
def _import_LOV(
baseuri="http://lov.okfn.org/dataset/lov/api/v2/vocabulary/list",
keyword=""):
"""
2016-03-02: import from json list
"""
printDebug("----------\nReading source... <%s>" % baseuri)
query = requests.get(baseuri, params={})
all_options = query.json()
... | 2016-03-02: import from json list |
def print_plugins(folders, exit_code=0):
"""Print available plugins and exit."""
modules = plugins.get_plugin_modules(folders)
pluginclasses = sorted(plugins.get_plugin_classes(modules), key=lambda x: x.__name__)
for pluginclass in pluginclasses:
print(pluginclass.__name__)
doc = strfor... | Print available plugins and exit. |
def getXmlText (parent, tag):
"""Return XML content of given tag in parent element."""
elem = parent.getElementsByTagName(tag)[0]
# Yes, the DOM standard is awful.
rc = []
for node in elem.childNodes:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return ''.join(rc) | Return XML content of given tag in parent element. |
def sg_layer_func(func):
r"""Decorates a function `func` as a sg_layer function.
Args:
func: function to decorate
"""
@wraps(func)
def wrapper(tensor, **kwargs):
r"""Manages arguments of `tf.sg_opt`.
Args:
tensor: A `tensor` (automatically passed by decorator).
... | r"""Decorates a function `func` as a sg_layer function.
Args:
func: function to decorate |
def _create_affine(x_axis, y_axis, z_axis, image_pos, voxel_sizes):
"""
Function to generate the affine matrix for a dicom series
This method was based on (http://nipy.org/nibabel/dicom/dicom_orientation.html)
:param sorted_dicoms: list with sorted dicom files
"""
# Create affine matrix (http:... | Function to generate the affine matrix for a dicom series
This method was based on (http://nipy.org/nibabel/dicom/dicom_orientation.html)
:param sorted_dicoms: list with sorted dicom files |
def get_waveset(model):
"""Get optimal wavelengths for sampling a given model.
Parameters
----------
model : `~astropy.modeling.Model`
Model.
Returns
-------
waveset : array-like or `None`
Optimal wavelengths. `None` if undefined.
Raises
------
synphot.exceptio... | Get optimal wavelengths for sampling a given model.
Parameters
----------
model : `~astropy.modeling.Model`
Model.
Returns
-------
waveset : array-like or `None`
Optimal wavelengths. `None` if undefined.
Raises
------
synphot.exceptions.SynphotError
Invalid... |
def show_all(self):
"""Show entire demo on screen, block by block"""
fname = self.title
title = self.title
nblocks = self.nblocks
silent = self._silent
marquee = self.marquee
for index,block in enumerate(self.src_blocks_colored):
if silent[index]:
... | Show entire demo on screen, block by block |
def _get_batches(self, mapping, batch_size=10000):
"""Get data from the local db"""
action = mapping.get("action", "insert")
fields = mapping.get("fields", {}).copy()
static = mapping.get("static", {})
lookups = mapping.get("lookups", {})
record_type = mapping.get("record... | Get data from the local db |
def create_aaaa_record(self, name, values, ttl=60, weight=None, region=None,
set_identifier=None):
"""
Creates an AAAA record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings... | Creates an AAAA record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:keyword int weight: *For weighted record sets ... |
def order(self, mechanism, purview):
"""Order the mechanism and purview in time.
If the direction is ``CAUSE``, then the purview is at |t-1| and the
mechanism is at time |t|. If the direction is ``EFFECT``, then the
mechanism is at time |t| and the purview is at |t+1|.
"""
... | Order the mechanism and purview in time.
If the direction is ``CAUSE``, then the purview is at |t-1| and the
mechanism is at time |t|. If the direction is ``EFFECT``, then the
mechanism is at time |t| and the purview is at |t+1|. |
def _make_query(self, ID: str, methodname: str, returnable: bool, *args: Any, **kwargs: Any):
"""将调用请求的ID,方法名,参数包装为请求数据.
Parameters:
ID (str): - 任务ID
methodname (str): - 要调用的方法名
returnable (bool): - 是否要求返回结果
args (Any): - 要调用的方法的位置参数
kwargs (A... | 将调用请求的ID,方法名,参数包装为请求数据.
Parameters:
ID (str): - 任务ID
methodname (str): - 要调用的方法名
returnable (bool): - 是否要求返回结果
args (Any): - 要调用的方法的位置参数
kwargs (Any): - 要调用的方法的关键字参数
Return:
(Dict[str, Any]) : - 请求的python字典形式 |
def _make_cmap(colors, position=None, bit=False):
'''
_make_cmap takes a list of tuples which contain RGB values. The RGB
values may either be in 8-bit [0 to 255] (in which bit must be set to
True when called) or arithmetic [0 to 1] (default). _make_cmap returns
a cmap with equally spaced colors.
... | _make_cmap takes a list of tuples which contain RGB values. The RGB
values may either be in 8-bit [0 to 255] (in which bit must be set to
True when called) or arithmetic [0 to 1] (default). _make_cmap returns
a cmap with equally spaced colors.
Arrange your tuples so that the first color is the lowest va... |
def argmax(iterable, key=None, both=False):
"""
>>> argmax([4,2,-5])
0
>>> argmax([4,2,-5], key=abs)
2
>>> argmax([4,2,-5], key=abs, both=True)
(2, 5)
"""
if key is not None:
it = imap(key, iterable)
else:
it = iter(iterable)
score, argmax = reduce(max, izip(i... | >>> argmax([4,2,-5])
0
>>> argmax([4,2,-5], key=abs)
2
>>> argmax([4,2,-5], key=abs, both=True)
(2, 5) |
def rekey(self,
uuid=None,
offset=None,
template_attribute=None,
credential=None):
"""
Check object usage according to specific constraints.
Args:
uuid (string): The unique identifier of a managed cryptographic
... | Check object usage according to specific constraints.
Args:
uuid (string): The unique identifier of a managed cryptographic
object that should be checked. Optional, defaults to None.
offset (int): An integer specifying, in seconds, the difference
between ... |
def for_all_targets(self, module, func, filter_func=None):
"""Call func once for all of the targets of this module."""
for target in self.targets(module):
if filter_func is None or filter_func(target):
func(target) | Call func once for all of the targets of this module. |
def process_tile(tile_x, tile_y, tile_size, pix, draw, image):
"""Process a tile whose top left corner is at the given x and y
coordinates.
"""
logging.debug('Processing tile (%d, %d)', tile_x, tile_y)
# Calculate average color for each "triangle" in the given tile
n, e, s, w = triangle_colors(... | Process a tile whose top left corner is at the given x and y
coordinates. |
def byteswap(data, word_size=4):
""" Swap the byte-ordering in a packet with N=4 bytes per word
"""
return reduce(lambda x,y: x+''.join(reversed(y)), chunks(data, word_size), '') | Swap the byte-ordering in a packet with N=4 bytes per word |
def opendocs(where='index', how='default'):
'''
Rebuild documentation and opens it in your browser.
Use the first argument to specify how it should be opened:
`d` or `default`: Open in new tab or new window, using the default
method of your browser.
`t` or `tab`: Open documentatio... | Rebuild documentation and opens it in your browser.
Use the first argument to specify how it should be opened:
`d` or `default`: Open in new tab or new window, using the default
method of your browser.
`t` or `tab`: Open documentation in new tab.
`n`, `w` or `window`: Open docume... |
def setup_queue(self):
"""Declare the queue
When completed, the on_queue_declareok method will be invoked by pika.
"""
logger.debug("Declaring queue %s" % self._queue)
self._channel.queue_declare(self.on_queue_declareok, self._queue, durable=True) | Declare the queue
When completed, the on_queue_declareok method will be invoked by pika. |
def create_rectangular_prism(origin, size):
'''
Return a Mesh which is an axis-aligned rectangular prism. One vertex is
`origin`; the diametrically opposite vertex is `origin + size`.
size: 3x1 array.
'''
from lace.topology import quads_to_tris
lower_base_plane = np.array([
# Lowe... | Return a Mesh which is an axis-aligned rectangular prism. One vertex is
`origin`; the diametrically opposite vertex is `origin + size`.
size: 3x1 array. |
def optimal_t(self, t_max=100, plot=False, ax=None):
"""Find the optimal value of t
Selects the optimal value of t based on the knee point of the
Von Neumann Entropy of the diffusion operator.
Parameters
----------
t_max : int, default: 100
Maximum value of ... | Find the optimal value of t
Selects the optimal value of t based on the knee point of the
Von Neumann Entropy of the diffusion operator.
Parameters
----------
t_max : int, default: 100
Maximum value of t to test
plot : boolean, default: False
If... |
async def open(self) -> 'Issuer':
"""
Explicit entry. Perform ancestor opening operations,
then synchronize revocation registry to tails tree content.
:return: current object
"""
LOGGER.debug('Issuer.open >>>')
await super().open()
for path_rr_id in Tai... | Explicit entry. Perform ancestor opening operations,
then synchronize revocation registry to tails tree content.
:return: current object |
def db_scan_block( block_id, op_list, db_state=None ):
"""
(required by virtualchain state engine)
Given the block ID and the list of virtualchain operations in the block,
do block-level preprocessing:
* find the state-creation operations we will accept
* make sure there are no collisions.
... | (required by virtualchain state engine)
Given the block ID and the list of virtualchain operations in the block,
do block-level preprocessing:
* find the state-creation operations we will accept
* make sure there are no collisions.
This modifies op_list, but returns nothing.
This aborts on run... |
def parse_port_pin(name_str):
"""Parses a string and returns a (port-num, pin-num) tuple."""
if len(name_str) < 3:
raise ValueError("Expecting pin name to be at least 3 charcters.")
if name_str[0] != 'P':
raise ValueError("Expecting pin name to start with P")
if name_str[1] < 'A' or name... | Parses a string and returns a (port-num, pin-num) tuple. |
def parse_file(filename):
"""
Convenience method to parse a generic volumetric data file in the vasp
like format. Used by subclasses for parsing file.
Args:
filename (str): Path of file to parse
Returns:
(poscar, data)
"""
poscar_read = F... | Convenience method to parse a generic volumetric data file in the vasp
like format. Used by subclasses for parsing file.
Args:
filename (str): Path of file to parse
Returns:
(poscar, data) |
def recarraydifference(X,Y):
"""
Records of a numpy recarray (or ndarray with structured dtype)
that do not appear in another.
Fast routine for determining which records in numpy array `X`
do not appear in numpy recarray `Y`.
Record array version of func:`tabular.fast.arraydifference`.
**... | Records of a numpy recarray (or ndarray with structured dtype)
that do not appear in another.
Fast routine for determining which records in numpy array `X`
do not appear in numpy recarray `Y`.
Record array version of func:`tabular.fast.arraydifference`.
**Parameters**
**X** : numpy ... |
def feed_line(self, line):
"""Feeds one line of input into the reader machine. This method is
a generator that yields all top-level S-expressions that have been
recognized on this line (including multi-line expressions whose last
character is on this line).
"""
self.line... | Feeds one line of input into the reader machine. This method is
a generator that yields all top-level S-expressions that have been
recognized on this line (including multi-line expressions whose last
character is on this line). |
def set_html(self, html, url = None):
""" Sets custom HTML in our Webkit session and allows to specify a fake URL.
Scripts and CSS is dynamically fetched as if the HTML had been loaded from
the given URL. """
if url:
self.conn.issue_command('SetHtml', html, url)
else:
self.conn.issue_com... | Sets custom HTML in our Webkit session and allows to specify a fake URL.
Scripts and CSS is dynamically fetched as if the HTML had been loaded from
the given URL. |
def root(reference_labels, estimated_labels):
"""Compare chords according to roots.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')
>>> (est_intervals,
... est_labels) = mir_eval.io.load_labeled_intervals('est.lab')
>>> est_interva... | Compare chords according to roots.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')
>>> (est_intervals,
... est_labels) = mir_eval.io.load_labeled_intervals('est.lab')
>>> est_intervals, est_labels = mir_eval.util.adjust_intervals(
... |
def get_kwargs(self, form, name):
"""
Return the keyword arguments that are used to instantiate the formset.
"""
kwargs = {
'prefix': self.get_prefix(form, name),
'initial': self.get_initial(form, name),
}
kwargs.update(self.default_kwargs)
... | Return the keyword arguments that are used to instantiate the formset. |
def read(fname):
"""
utility function to read and return file contents
"""
fpath = os.path.join(os.path.dirname(__file__), fname)
with codecs.open(fpath, 'r', 'utf8') as fhandle:
return fhandle.read().strip() | utility function to read and return file contents |
def decrement(self, key, value=1):
"""
Decrement the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The decrement value
:type value: int
:rtype: int or bool
"""
return self._memcache.decr(self._prefix + key... | Decrement the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The decrement value
:type value: int
:rtype: int or bool |
def _align_with_substrings(self, chains_to_skip = set()):
'''Simple substring-based matching'''
for c in self.representative_chains:
# Skip specified chains
if c not in chains_to_skip:
#colortext.pcyan(c)
#colortext.warning(self.fasta[c])
... | Simple substring-based matching |
async def create_vm(self, *, preset_name, image, flavor, security_groups=None,
userdata=None, key_name=None, availability_zone=None,
subnet=None):
"""
Dummy create_vm func.
"""
info = {
'id': next(self._id_it),
'name... | Dummy create_vm func. |
def toString(self):
""" Returns date as string. """
slist = self.toList()
sign = '' if slist[0] == '+' else '-'
string = '/'.join(['%02d' % v for v in slist[1:]])
return sign + string | Returns date as string. |
def entry_modification_time(self):
"""dfdatetime.Filetime: entry modification time or None if not set."""
timestamp = self._fsntfs_attribute.get_entry_modification_time_as_integer()
return dfdatetime_filetime.Filetime(timestamp=timestamp) | dfdatetime.Filetime: entry modification time or None if not set. |
def create_container_service(access_token, subscription_id, resource_group, service_name, \
agent_count, agent_vm_size, agent_dns, master_dns, admin_user, location, public_key=None,\
master_count=3, orchestrator='DCOS', app_id=None, app_secret=None, admin_password=None, \
ostype='Linux'):
'''Create a ne... | Create a new container service - include app_id and app_secret if using Kubernetes.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
service_name (str): Name of container serv... |
def is_course_complete(last_update):
"""
Determine is the course is likely to have been terminated or not.
We return True if the timestamp given by last_update is 30 days or older
than today's date. Otherwise, we return True.
The intended use case for this is to detect if a given courses has not
... | Determine is the course is likely to have been terminated or not.
We return True if the timestamp given by last_update is 30 days or older
than today's date. Otherwise, we return True.
The intended use case for this is to detect if a given courses has not
seen any update in the last 30 days or more. ... |
def get_public_key(key, passphrase=None, asObj=False):
'''
Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
... | Returns a string containing the public key in PEM format.
key:
A path or PEM encoded string containing a CSR, Certificate or
Private Key from which a public key can be retrieved.
CLI Example:
.. code-block:: bash
salt '*' x509.get_public_key /etc/pki/mycert.cer |
def get_cached_source_variable(self, source_id, variable, default=None):
""" Get the cached value of a source variable. If the variable is not
cached return the default value. """
source_id = int(source_id)
try:
return self._retrieve_cached_source_variable(
... | Get the cached value of a source variable. If the variable is not
cached return the default value. |
def remove_slug(path):
"""
Return the remainin part of the path
>>> remove_slug('/test/some/function/')
test/some
"""
if path.endswith('/'):
path = path[:-1]
if path.startswith('/'):
path = path[1:]
if "/" not in path or not path:
return None
parts = ... | Return the remainin part of the path
>>> remove_slug('/test/some/function/')
test/some |
def persistent_timer(func):
"""
Times the execution of a function. If the process is stopped and restarted then timing is continued using saved
files.
Parameters
----------
func
Some function to be timed
Returns
-------
timed_function
The same function with a timer ... | Times the execution of a function. If the process is stopped and restarted then timing is continued using saved
files.
Parameters
----------
func
Some function to be timed
Returns
-------
timed_function
The same function with a timer attached. |
def start(self):
"""Initiate server connection."""
yield from self._do_connect()
_LOGGER.info('connected to snapserver on %s:%s', self._host, self._port)
status = yield from self.status()
self.synchronize(status)
self._on_server_connect() | Initiate server connection. |
def close(self):
"""Close the tough connection.
You are allowed to close a tough connection by default
and it will not complain if you close it more than once.
You can disallow closing connections by setting
the closeable parameter to something false. In this case,
clo... | Close the tough connection.
You are allowed to close a tough connection by default
and it will not complain if you close it more than once.
You can disallow closing connections by setting
the closeable parameter to something false. In this case,
closing tough connections will ... |
def load_or_create(cls, filename=None, no_input=False, create_new=False, **kwargs):
"""
Load system from a dump, if dump file exists, or create a new system if it does not exist.
"""
parser = argparse.ArgumentParser()
parser.add_argument('--no_input', action='store_true')
... | Load system from a dump, if dump file exists, or create a new system if it does not exist. |
def add_view_permissions(sender, verbosity, **kwargs):
"""
This post_syncdb/post_migrate hooks takes care of adding a view permission too all our
content types.
"""
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
for content_type ... | This post_syncdb/post_migrate hooks takes care of adding a view permission too all our
content types. |
def required_arguments(func):
"""Return all arguments of a function that do not have a default value."""
defaults = default_values_of(func)
args = arguments_of(func)
if defaults:
args = args[:-len(defaults)]
return args | Return all arguments of a function that do not have a default value. |
def _read_buffer(self, data_in):
"""Process the socket buffer, and direct the data to the appropriate
channel.
:rtype: bytes
"""
while data_in:
data_in, channel_id, frame_in = self._handle_amqp_frame(data_in)
if frame_in is None:
break
... | Process the socket buffer, and direct the data to the appropriate
channel.
:rtype: bytes |
def create_negotiate_message(self, domain_name=None, workstation=None):
"""
Create an NTLM NEGOTIATE_MESSAGE
:param domain_name: The domain name of the user account we are authenticating with, default is None
:param worksation: The workstation we are using to authenticate with, default ... | Create an NTLM NEGOTIATE_MESSAGE
:param domain_name: The domain name of the user account we are authenticating with, default is None
:param worksation: The workstation we are using to authenticate with, default is None
:return: A base64 encoded string of the NEGOTIATE_MESSAGE |
def iscomplex(polynomial):
"""Returns whether the polynomial has complex coefficients
:param polynomial: Polynomial of noncommutive variables.
:type polynomial: :class:`sympy.core.expr.Expr`.
:returns: bool -- whether there is a complex coefficient.
"""
if isinstance(polynomial, (int, float)):... | Returns whether the polynomial has complex coefficients
:param polynomial: Polynomial of noncommutive variables.
:type polynomial: :class:`sympy.core.expr.Expr`.
:returns: bool -- whether there is a complex coefficient. |
def download(self, id, attid): # pylint: disable=invalid-name,redefined-builtin
"""Download a device's attachment.
:param id: Device ID as an int.
:param attid: Attachment ID as an int.
:rtype: tuple `(io.BytesIO, 'filename')`
"""
resp = self.service.get_id(self._base(id... | Download a device's attachment.
:param id: Device ID as an int.
:param attid: Attachment ID as an int.
:rtype: tuple `(io.BytesIO, 'filename')` |
def log(self, metrics_dict):
"""Print calculated metrics and optionally write to file (json/tb)"""
if self.writer:
self.write_to_file(metrics_dict)
if self.verbose:
self.print_to_screen(metrics_dict)
self.reset() | Print calculated metrics and optionally write to file (json/tb) |
def index_model(index_name, adapter):
''' Indel all objects given a model'''
model = adapter.model
log.info('Indexing {0} objects'.format(model.__name__))
qs = model.objects
if hasattr(model.objects, 'visible'):
qs = qs.visible()
if adapter.exclude_fields:
qs = qs.exclude(*adapte... | Indel all objects given a model |
def conf(self):
"""Generate the Sphinx `conf.py` configuration file
Returns:
(str): the contents of the `conf.py` file.
"""
return self.env.get_template('conf.py.j2').render(
metadata=self.metadata,
package=self.package) | Generate the Sphinx `conf.py` configuration file
Returns:
(str): the contents of the `conf.py` file. |
def grid(self, dimensions=None, **kwargs):
"""Group by supplied dimension(s) and lay out groups in grid
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a GridSpace.
Args:
dimensions: Dimension/str or list
Dimension or list of dim... | Group by supplied dimension(s) and lay out groups in grid
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a GridSpace.
Args:
dimensions: Dimension/str or list
Dimension or list of dimensions to group by
Returns:
Grid... |
def computeRawAnomalyScore(activeColumns, prevPredictedColumns):
"""Computes the raw anomaly score.
The raw anomaly score is the fraction of active columns not predicted.
:param activeColumns: array of active column indices
:param prevPredictedColumns: array of columns indices predicted in prev step
:return... | Computes the raw anomaly score.
The raw anomaly score is the fraction of active columns not predicted.
:param activeColumns: array of active column indices
:param prevPredictedColumns: array of columns indices predicted in prev step
:returns: anomaly score 0..1 (float) |
def write(models, out=None, base=None, logger=logging):
'''
models - one or more input Versa models from which output is generated.
'''
assert out is not None #Output stream required
if not isinstance(models, list): models = [models]
for m in models:
for link in m.match():
s,... | models - one or more input Versa models from which output is generated. |
def build_inside(input_method, input_args=None, substitutions=None):
"""
use requested input plugin to load configuration and then initiate build
"""
def process_keyvals(keyvals):
""" ["key=val", "x=y"] -> {"key": "val", "x": "y"} """
keyvals = keyvals or []
processed_keyvals = {... | use requested input plugin to load configuration and then initiate build |
def start_system(components, bind_to, hooks={}):
"""Start all components on component map."""
deps = build_deps_graph(components)
started_components = start_components(components, deps, None)
run_hooks(hooks, started_components)
if type(bind_to) is str:
master = started_components[bind_to]... | Start all components on component map. |
def make_predictor(regressor=LassoLarsIC(fit_intercept=False),
Selector=GridSearchCV, fourier_degree=(2, 25),
selector_processes=1,
use_baart=False, scoring='r2', scoring_cv=3,
**kwargs):
"""make_predictor(regressor=LassoLarsIC(fit_intercep... | make_predictor(regressor=LassoLarsIC(fit_intercept=False), Selector=GridSearchCV, fourier_degree=(2, 25), selector_processes=1, use_baart=False, scoring='r2', scoring_cv=3, **kwargs)
Makes a predictor object for use in :func:`get_lightcurve`.
**Parameters**
regressor : object with "fit" and "transform" m... |
def rlmb_long_stochastic_discrete_100steps():
"""Long setting with stochastic discrete model, changed ppo steps."""
hparams = rlmb_long_stochastic_discrete()
hparams.ppo_epoch_length = 100
hparams.simulated_rollout_length = 100
hparams.simulated_batch_size = 8
return hparams | Long setting with stochastic discrete model, changed ppo steps. |
def _process_genes(self, limit=None):
"""
This method processes the KEGG gene IDs.
The label for the gene is pulled as
the first symbol in the list of gene symbols;
the rest are added as synonyms.
The long-form of the gene name is added as a definition.
This is ha... | This method processes the KEGG gene IDs.
The label for the gene is pulled as
the first symbol in the list of gene symbols;
the rest are added as synonyms.
The long-form of the gene name is added as a definition.
This is hardcoded to just processes human genes.
Triples cr... |
def tear_down(self):
""" Called when controller is destroyed. """
super(ReceiverController, self).tear_down()
self.status = None
self.launch_failure = None
self.app_to_launch = None
self.app_launch_event.clear()
self._status_listeners[:] = [] | Called when controller is destroyed. |
def namelist_handle(tokens):
"""Process inline nonlocal and global statements."""
if len(tokens) == 1:
return tokens[0]
elif len(tokens) == 2:
return tokens[0] + "\n" + tokens[0] + " = " + tokens[1]
else:
raise CoconutInternalException("invalid in-line nonlocal / global tokens", ... | Process inline nonlocal and global statements. |
def parse_rules(data, chain):
"""
Parse the rules for the specified chain.
"""
rules = []
for line in data.splitlines(True):
m = re_rule.match(line)
if m and m.group(3) == chain:
rule = parse_rule(m.group(4))
rule.packets = int(m.group(1))
rule.byt... | Parse the rules for the specified chain. |
def execd_module_paths(execd_dir=None):
"""Generate a list of full paths to modules within execd_dir."""
if not execd_dir:
execd_dir = default_execd_dir()
if not os.path.exists(execd_dir):
return
for subpath in os.listdir(execd_dir):
module = os.path.join(execd_dir, subpath)
... | Generate a list of full paths to modules within execd_dir. |
def _render_expression(self, check):
"""Turn a mongodb-style search dict into an SQL query."""
expressions = []
args = []
skeys = set(check.keys())
skeys.difference_update(set(self._keys))
skeys.difference_update(set(['buffers', 'result_buffers']))
if skeys:
... | Turn a mongodb-style search dict into an SQL query. |
def _validate(config):
""" Config validation
Raises:
KeyError on missing mandatory key
SyntaxError on invalid key
ValueError on invalid value for key
:param config: {dict} config to validate
:return: None
"""
for mandatory_key in _mandatory_keys:
i... | Config validation
Raises:
KeyError on missing mandatory key
SyntaxError on invalid key
ValueError on invalid value for key
:param config: {dict} config to validate
:return: None |
def check_has_docstring(self, api):
'''An API class must have a docstring.'''
if not api.__doc__:
msg = 'The Api class "{}" lacks a docstring.'
return [msg.format(api.__name__)] | An API class must have a docstring. |
def _get_nailgun_client(self, jvm_options, classpath, stdout, stderr, stdin):
"""This (somewhat unfortunately) is the main entrypoint to this class via the Runner. It handles
creation of the running nailgun server as well as creation of the client."""
classpath = self._nailgun_classpath + classpath
n... | This (somewhat unfortunately) is the main entrypoint to this class via the Runner. It handles
creation of the running nailgun server as well as creation of the client. |
def to_dict(self):
"""
Return a dict that can be serialised to JSON and sent to UpCloud's API.
"""
return dict(
(attr, getattr(self, attr))
for attr in self.ATTRIBUTES
if hasattr(self, attr)
) | Return a dict that can be serialised to JSON and sent to UpCloud's API. |
async def _handle_container_timeout(self, container_id, timeout):
"""
Check timeout with docker stats
:param container_id:
:param timeout: in seconds (cpu time)
"""
try:
docker_stats = await self._docker_interface.get_stats(container_id)
source = A... | Check timeout with docker stats
:param container_id:
:param timeout: in seconds (cpu time) |
def next_permutation(tab):
"""find the next permutation of tab in the lexicographical order
:param tab: table with n elements from an ordered set
:modifies: table to next permutation
:returns: False if permutation is already lexicographical maximal
:complexity: O(n)
"""
n = len(tab)
piv... | find the next permutation of tab in the lexicographical order
:param tab: table with n elements from an ordered set
:modifies: table to next permutation
:returns: False if permutation is already lexicographical maximal
:complexity: O(n) |
def _filter_commands(ctx, commands=None):
"""Return list of used commands."""
lookup = getattr(ctx.command, 'commands', {})
if not lookup and isinstance(ctx.command, click.MultiCommand):
lookup = _get_lazyload_commands(ctx.command)
if commands is None:
return sorted(lookup.values(), key... | Return list of used commands. |
def set_scene_velocity(self, scene_id, velocity):
"""reconfigure a scene by scene ID"""
if not scene_id in self.state.scenes: # does that scene_id exist?
err_msg = "Requested to set velocity on scene {sceneNum}, which does not exist".format(sceneNum=scene_id)
logging.info(err_msg... | reconfigure a scene by scene ID |
def _has_local_storage(self, pod=None):
"""
Determines if a K8sPod has any local storage susceptible to be lost.
:param pod: The K8sPod we're interested in.
:return: a boolean.
"""
for vol in pod.volumes:
if vol.emptyDir is not None:
return ... | Determines if a K8sPod has any local storage susceptible to be lost.
:param pod: The K8sPod we're interested in.
:return: a boolean. |
def parse_route_name_and_version(route_repr):
"""
Parse a route representation string and return the route name and version number.
:param route_repr: Route representation string.
:return: A tuple containing route name and version number.
"""
if ':' in route_repr:
route_name, version =... | Parse a route representation string and return the route name and version number.
:param route_repr: Route representation string.
:return: A tuple containing route name and version number. |
def _execute_hooks(self, element):
"""
Executes finalize hooks
"""
if self.hooks and self.finalize_hooks:
self.param.warning(
"Supply either hooks or finalize_hooks not both, "
"using hooks and ignoring finalize_hooks.")
hooks = self.ho... | Executes finalize hooks |
def append(self, other, ignore_index=False):
"""Append rows of `other` to the end of this frame, returning a new object.
Wrapper around the :meth:`pandas.DataFrame.append` method.
Args:
other (Cartesian):
ignore_index (sequence, bool, int): If it is a boolean, it
... | Append rows of `other` to the end of this frame, returning a new object.
Wrapper around the :meth:`pandas.DataFrame.append` method.
Args:
other (Cartesian):
ignore_index (sequence, bool, int): If it is a boolean, it
behaves like in the description of
... |
def _filter_nodes(superclass, all_nodes=_all_nodes):
"""Filter out AST nodes that are subclasses of ``superclass``."""
node_names = (node.__name__ for node in all_nodes
if issubclass(node, superclass))
return frozenset(node_names) | Filter out AST nodes that are subclasses of ``superclass``. |
def find_side(ls, side):
"""
Given a shapely LineString which is assumed to be rectangular, return the
line corresponding to a given side of the rectangle.
"""
minx, miny, maxx, maxy = ls.bounds
points = {'left': [(minx, miny), (minx, maxy)],
'right': [(maxx, miny), (maxx, max... | Given a shapely LineString which is assumed to be rectangular, return the
line corresponding to a given side of the rectangle. |
def _run_init_queries(self):
'''
Initialization queries
'''
for obj in (Package, PackageCfgFile, PayloadFile, IgnoredDir, AllowedDir):
self._db.create_table_from_object(obj()) | Initialization queries |
def occurrence_halved_fingerprint(
word, n_bits=16, most_common=MOST_COMMON_LETTERS_CG
):
"""Return the occurrence halved fingerprint.
This is a wrapper for :py:meth:`OccurrenceHalved.fingerprint`.
Parameters
----------
word : str
The word to fingerprint
n_bits : int
Number... | Return the occurrence halved fingerprint.
This is a wrapper for :py:meth:`OccurrenceHalved.fingerprint`.
Parameters
----------
word : str
The word to fingerprint
n_bits : int
Number of bits in the fingerprint returned
most_common : list
The most common tokens in the tar... |
def power_corr(r=None, n=None, power=None, alpha=0.05, tail='two-sided'):
"""
Evaluate power, sample size, correlation coefficient or
significance level of a correlation test.
Parameters
----------
r : float
Correlation coefficient.
n : int
Number of observations (sample siz... | Evaluate power, sample size, correlation coefficient or
significance level of a correlation test.
Parameters
----------
r : float
Correlation coefficient.
n : int
Number of observations (sample size).
power : float
Test power (= 1 - type II error).
alpha : float
... |
def declareLegacyItem(typeName, schemaVersion, attributes, dummyBases=()):
"""
Generate a dummy subclass of Item that will have the given attributes,
and the base Item methods, but no methods of its own. This is for use
with upgrading.
@param typeName: a string, the Axiom TypeName to have attribut... | Generate a dummy subclass of Item that will have the given attributes,
and the base Item methods, but no methods of its own. This is for use
with upgrading.
@param typeName: a string, the Axiom TypeName to have attributes for.
@param schemaVersion: an int, the (old) version of the schema this is a pro... |
def get_rc_creds():
"""
Reads ~/.rightscalerc and returns API endpoint and refresh token.
Always returns a tuple of strings even if the file is empty - in which
case, returns ``('', '')``.
"""
config = get_config()
try:
return (
config.get(CFG_SECTION_OAUTH, CFG_OPTI... | Reads ~/.rightscalerc and returns API endpoint and refresh token.
Always returns a tuple of strings even if the file is empty - in which
case, returns ``('', '')``. |
def get_bucket_region(self, bucket) -> str:
"""
Get region associated with a specified bucket name.
:param bucket: the bucket to be checked.
:return: region, Note that underlying AWS API returns None for default US-East-1,
I'm replacing that with us-east-1.
"""
re... | Get region associated with a specified bucket name.
:param bucket: the bucket to be checked.
:return: region, Note that underlying AWS API returns None for default US-East-1,
I'm replacing that with us-east-1. |
def convert_attrs_to_uppercase(obj: Any, attrs: Iterable[str]) -> None:
"""
Converts the specified attributes of an object to upper case, modifying
the object in place.
"""
for a in attrs:
value = getattr(obj, a)
if value is None:
continue
setattr(obj, a, value.up... | Converts the specified attributes of an object to upper case, modifying
the object in place. |
def calc_qdga2_v1(self):
"""Perform the runoff concentration calculation for "fast" direct runoff.
The working equation is the analytical solution of the linear storage
equation under the assumption of constant change in inflow during
the simulation time step.
Required derived parameter:
|KD... | Perform the runoff concentration calculation for "fast" direct runoff.
The working equation is the analytical solution of the linear storage
equation under the assumption of constant change in inflow during
the simulation time step.
Required derived parameter:
|KD2|
Required state sequence:... |
def walk(p, mode='all', **kw):
"""Wrapper for `os.walk`, yielding `Path` objects.
:param p: root of the directory tree to walk.
:param mode: 'all|dirs|files', defaulting to 'all'.
:param kw: Keyword arguments are passed to `os.walk`.
:return: Generator for the requested Path objects.
"""
fo... | Wrapper for `os.walk`, yielding `Path` objects.
:param p: root of the directory tree to walk.
:param mode: 'all|dirs|files', defaulting to 'all'.
:param kw: Keyword arguments are passed to `os.walk`.
:return: Generator for the requested Path objects. |
def _get_wms_wcs_url_parameters(request, date):
""" Returns parameters common dictionary for WMS and WCS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition dat... | Returns parameters common dictionary for WMS and WCS request.
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcRequest or GeopediaRequest
:param date: acquisition date or None
:type date: datetime.datetime or None
... |
async def on_raw_731(self, message):
""" Someone we are monitoring got offline. """
for nick in message.params[1].split(','):
self._destroy_user(nick, monitor_override=True)
await self.on_user_offline(nickname) | Someone we are monitoring got offline. |
def tree(node, formatter=None, prefix=None, postfix=None, _depth=1):
"""Print a tree.
Sometimes it's useful to print datastructures as a tree. This function prints
out a pretty tree with root `node`. A tree is represented as a :class:`dict`,
whose keys are node names and values are :class:`dict` objects for su... | Print a tree.
Sometimes it's useful to print datastructures as a tree. This function prints
out a pretty tree with root `node`. A tree is represented as a :class:`dict`,
whose keys are node names and values are :class:`dict` objects for sub-trees
and :class:`None` for terminals.
:param dict node: The root o... |
def input_yn(conf_mess):
"""Print Confirmation Message and Get Y/N response from user."""
ui_erase_ln()
ui_print(conf_mess)
with term.cbreak():
input_flush()
val = input_by_key()
return bool(val.lower() == 'y') | Print Confirmation Message and Get Y/N response from user. |
def getParameters(self, postalAddress):
"""
Return a C{list} of one L{LiveForm} parameter for editing a
L{PostalAddress}.
@type postalAddress: L{PostalAddress} or C{NoneType}
@param postalAddress: If not C{None}, an existing contact item from
which to get the postal... | Return a C{list} of one L{LiveForm} parameter for editing a
L{PostalAddress}.
@type postalAddress: L{PostalAddress} or C{NoneType}
@param postalAddress: If not C{None}, an existing contact item from
which to get the postal address default value.
@rtype: C{list}
@re... |
def _nonmatch_class_pos(self):
"""Return the position of the non-match class."""
# TODO: add notfitted warnings
if self.kernel.classes_.shape[0] != 2:
raise ValueError("Number of classes is {}, expected 2.".format(
self.kernel.classes_.shape[0]))
# # get the ... | Return the position of the non-match class. |
def maybe_convert_values(self,
identifier: Identifier,
data: Dict[str, Any],
) -> Dict[str, Any]:
"""
Takes a dictionary of raw values for a specific identifier, as parsed
from the YAML file, and depending upo... | Takes a dictionary of raw values for a specific identifier, as parsed
from the YAML file, and depending upon the type of db column the data
is meant for, decides what to do with the value (eg leave it alone,
convert a string to a date/time instance, or convert identifiers to
model instan... |
def toxml(self):
"""
Exports this object into a LEMS XML object
"""
return '<Property name="{0}"'.format(self.name) +\
(' dimension="{0}"'.format(self.dimension) if self.dimension else 'none') +\
(' defaultValue = "{0}"'.format(self.default_value) if self.default_val... | Exports this object into a LEMS XML object |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.