code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def resize(self, logical_size):
"""Starts resizing this medium. This means that the nominal size of the
medium is set to the new value. Both increasing and decreasing the
size is possible, and there are no safety checks, since VirtualBox
does not make any assumptions about the medium con... | Starts resizing this medium. This means that the nominal size of the
medium is set to the new value. Both increasing and decreasing the
size is possible, and there are no safety checks, since VirtualBox
does not make any assumptions about the medium contents.
Resizing usually ne... |
def format_t_into_dhms_format(timestamp):
""" Convert an amount of second into day, hour, min and sec
:param timestamp: seconds
:type timestamp: int
:return: 'Ad Bh Cm Ds'
:rtype: str
>>> format_t_into_dhms_format(456189)
'5d 6h 43m 9s'
>>> format_t_into_dhms_format(3600)
'0d 1h 0... | Convert an amount of second into day, hour, min and sec
:param timestamp: seconds
:type timestamp: int
:return: 'Ad Bh Cm Ds'
:rtype: str
>>> format_t_into_dhms_format(456189)
'5d 6h 43m 9s'
>>> format_t_into_dhms_format(3600)
'0d 1h 0m 0s' |
def configure_ckan(m):
"""Load groups and organizations, from a file in Metatab format"""
from ckanapi import RemoteCKAN
try:
doc = MetapackDoc(m.mt_file, cache=m.cache)
except (IOError, MetatabError) as e:
err("Failed to open metatab '{}': {}".format(m.mt_file, e))
c = RemoteCKAN(... | Load groups and organizations, from a file in Metatab format |
def call_builder_init(cls, kb_app, sphinx_app: Sphinx):
""" On builder init event, commit registry and do callbacks """
# Find and commit docs project plugins
conf_dir = sphinx_app.confdir
plugins_dir = sphinx_app.config.kaybee_settings.plugins_dir
full_plugins_dir = os.path.joi... | On builder init event, commit registry and do callbacks |
def add_sample(self, name, labels, value, timestamp=None, exemplar=None):
"""Add a sample to the metric.
Internal-only, do not use."""
self.samples.append(Sample(name, labels, value, timestamp, exemplar)) | Add a sample to the metric.
Internal-only, do not use. |
def load_yamlf(fpath, encoding):
"""
:param unicode fpath:
:param unicode encoding:
:rtype: dict | list
"""
with codecs.open(fpath, encoding=encoding) as f:
return yaml.safe_load(f) | :param unicode fpath:
:param unicode encoding:
:rtype: dict | list |
def assert_hasattr(attr: str, msg: str, tp: BaseException = SpotifyException) -> Callable:
"""decorator to assert an object has an attribute when run."""
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
def decorated(self, *args, **kwargs):
if not hasattr(self, attr)... | decorator to assert an object has an attribute when run. |
def temporary_file_path(root_dir=None, cleanup=True, suffix='', permissions=None):
"""
A with-context that creates a temporary file and returns its path.
:API: public
You may specify the following keyword args:
:param str root_dir: The parent directory to create the temporary file.
:param bool c... | A with-context that creates a temporary file and returns its path.
:API: public
You may specify the following keyword args:
:param str root_dir: The parent directory to create the temporary file.
:param bool cleanup: Whether or not to clean up the temporary file. |
def set_pwm(self, channel, on, off):
"""Sets a single PWM channel."""
self.i2c.write8(LED0_ON_L+4*channel, on & 0xFF)
self.i2c.write8(LED0_ON_H+4*channel, on >> 8)
self.i2c.write8(LED0_OFF_L+4*channel, off & 0xFF)
self.i2c.write8(LED0_OFF_H+4*channel, off >> 8) | Sets a single PWM channel. |
def isRecord(self, db=None):
"""
Returns whether or not this database table record exists
in the database.
:return <bool>
"""
if db is not None:
same_db = db == self.context().db
if db is None or same_db:
col = self.schema().idColumn(... | Returns whether or not this database table record exists
in the database.
:return <bool> |
def conjugate_quat(quat):
"""Negate the vector part of the quaternion."""
return Quat(-quat.x, -quat.y, -quat.z, quat.w) | Negate the vector part of the quaternion. |
def _cleanlogs(silent=False, log_location="log"):
"""
Cleans up Mbed-test default log directory.
:param silent: Defaults to False
:param log_location: Location of log files, defaults to "log"
:return: Nothing
"""
try:
print("cleaning up Icetea log directory.")
shutil.rmtree(... | Cleans up Mbed-test default log directory.
:param silent: Defaults to False
:param log_location: Location of log files, defaults to "log"
:return: Nothing |
def clone(self):
# TODO: check docstring
"""Returns a deep copy of self
Function clones:
* allocation
* nodes
Returns
-------
type
Deep copy of self
"""
new_node = self.__class__(self._name, self._dem... | Returns a deep copy of self
Function clones:
* allocation
* nodes
Returns
-------
type
Deep copy of self |
def mapPriority(levelno):
"""Map logging levels to journald priorities.
Since Python log level numbers are "sparse", we have
to map numbers in between the standard levels too.
"""
if levelno <= _logging.DEBUG:
return LOG_DEBUG
elif levelno <= _logging.INFO:
... | Map logging levels to journald priorities.
Since Python log level numbers are "sparse", we have
to map numbers in between the standard levels too. |
def lorentz_deriv((x, y, z), t0, sigma=10., beta=8./3, rho=28.0):
"""Compute the time-derivative of a Lorentz system."""
return [sigma * (y - x), x * (rho - z) - y, x * y - beta * z] | Compute the time-derivative of a Lorentz system. |
def gaus_pdf(x, mean, std):
'''Gaussian distribution's probability density function.
See, e.g. `Wikipedia <https://en.wikipedia.org/wiki/Normal_distribution>`_.
:param x: point in x-axis
:type x: float or numpy.ndarray
:param float mean: mean or expectation
:param float str: standard deviation... | Gaussian distribution's probability density function.
See, e.g. `Wikipedia <https://en.wikipedia.org/wiki/Normal_distribution>`_.
:param x: point in x-axis
:type x: float or numpy.ndarray
:param float mean: mean or expectation
:param float str: standard deviation
:returns: pdf(s) in point **x*... |
async def shutdown(self, force = False, connmark = -1):
'''
Can call without delegate
'''
if connmark is None:
connmark = self.connmark
self.scheduler.emergesend(ConnectionControlEvent(self, ConnectionControlEvent.SHUTDOWN, force, connmark)) | Can call without delegate |
def report(self, min_confidence=0, sort_by_size=False,
make_whitelist=False):
"""
Print ordered list of Item objects to stdout.
"""
for item in self.get_unused_code(
min_confidence=min_confidence, sort_by_size=sort_by_size):
print(item.get_white... | Print ordered list of Item objects to stdout. |
def load(self, path=None, format=None, schema=None, **options):
"""Loads a data stream from a data source and returns it as a :class`DataFrame`.
.. note:: Evolving.
:param path: optional string for file-system backed data sources.
:param format: optional string for format of the data s... | Loads a data stream from a data source and returns it as a :class`DataFrame`.
.. note:: Evolving.
:param path: optional string for file-system backed data sources.
:param format: optional string for format of the data source. Default to 'parquet'.
:param schema: optional :class:`pyspar... |
def messageid_match(self, messageid):
"""Add match for log entries with specified `messageid`.
`messageid` can be string of hexadicimal digits or a UUID
instance. Standard message IDs can be found in systemd.id128.
Equivalent to add_match(MESSAGE_ID=`messageid`).
"""
if... | Add match for log entries with specified `messageid`.
`messageid` can be string of hexadicimal digits or a UUID
instance. Standard message IDs can be found in systemd.id128.
Equivalent to add_match(MESSAGE_ID=`messageid`). |
def _svd(cls, matrix, num_concepts=5):
"""
Perform singular value decomposition for dimensionality reduction of the input matrix.
"""
u, s, v = svds(matrix, k=num_concepts)
return u, s, v | Perform singular value decomposition for dimensionality reduction of the input matrix. |
def _drawContents(self, currentRti=None):
""" Draws the attributes of the currentRTI
"""
table = self.table
table.setUpdatesEnabled(False)
try:
table.clearContents()
verticalHeader = table.verticalHeader()
verticalHeader.setSectionResizeMode(Qt... | Draws the attributes of the currentRTI |
def disk_clone(hypervisor, identifier, storage_pool, configuration, image, logger):
"""Disk image cloning.
Given an original disk image it clones it into a new one, the clone will be created within the storage pool.
The following values are set into the disk XML configuration:
* name
* target... | Disk image cloning.
Given an original disk image it clones it into a new one, the clone will be created within the storage pool.
The following values are set into the disk XML configuration:
* name
* target/path
* target/permission/label
* backingStore/path if copy on write is enabled |
def _set_instance_proxies(self):
"""
Set the proxies to any of the following:
Proxy List - a list of proxies to choose randomly from for each request. Read from file.
TOR - a dict of socks5 and the TOR service default 9050 that will be used
Else, No proxies - an empty dict will b... | Set the proxies to any of the following:
Proxy List - a list of proxies to choose randomly from for each request. Read from file.
TOR - a dict of socks5 and the TOR service default 9050 that will be used
Else, No proxies - an empty dict will be used. |
def oauth_client_create(self, name, redirect_uri, **kwargs):
"""
Make a new OAuth Client and return it
"""
params = {
"label": name,
"redirect_uri": redirect_uri,
}
params.update(kwargs)
result = self.client.post('/account/oauth-clients', ... | Make a new OAuth Client and return it |
def t_ATOM(self, t):
r'[a-zA-Z_][a-zA-Z_0-9]*'
t.type = LDLfLexer.reserved.get(t.value, 'ATOM') # Check for reserved words
return t | r'[a-zA-Z_][a-zA-Z_0-9]* |
async def _process_auth_form(self, html: str) -> (str, str):
"""
Parsing data from authorization page and filling the form and submitting the form
:param html: html page
:return: url and html from redirected page
"""
# Parse page
p = AuthPageParser()
p.f... | Parsing data from authorization page and filling the form and submitting the form
:param html: html page
:return: url and html from redirected page |
def getMonitorById(self, monitorId):
"""
Returns monitor status and alltimeuptimeratio for a MonitorId.
"""
url = self.baseUrl
url += "getMonitors?apiKey=%s&monitors=%s" % (self.apiKey, monitorId)
url += "&noJsonCallback=1&format=json"
success, response = self.req... | Returns monitor status and alltimeuptimeratio for a MonitorId. |
def add_version_tracking(self, info_id, version, date, command_line=''):
"""
Add a line with information about which software that was run and when
to the header.
Arguments:
info_id (str): The id of the info line
version (str): The version of the softwar... | Add a line with information about which software that was run and when
to the header.
Arguments:
info_id (str): The id of the info line
version (str): The version of the software used
date (str): Date when software was run
command_line (str): The... |
def _validate_doc_refs_helper(self, env, doc, loc, type_context=None):
"""
Validates that all the documentation references in a docstring are
formatted properly, have valid values, and make references to valid
symbols.
Args:
env (dict): The environment of defined sym... | Validates that all the documentation references in a docstring are
formatted properly, have valid values, and make references to valid
symbols.
Args:
env (dict): The environment of defined symbols.
doc (str): The docstring to validate.
lineno (int): The line ... |
def raise_api_exceptions(function, *args, **kwargs):
"""Raise client side exception(s) when present in the API response.
Returned data is not modified.
"""
try:
return_value = function(*args, **kwargs)
except errors.HTTPException as exc:
if exc._raw.status_code != 400: # pylint: d... | Raise client side exception(s) when present in the API response.
Returned data is not modified. |
def _list_records(self, rtype=None, name=None, content=None):
"""
list all records
:param str rtype: type of record
:param str name: name of record
:param mixed content: value of record
:return list: list of found records
:raises Exception: on error
"""
... | list all records
:param str rtype: type of record
:param str name: name of record
:param mixed content: value of record
:return list: list of found records
:raises Exception: on error |
def get_fault(fault_id=None):
"""Retrieve a randomly-generated error message as a unicode string.
:param fault_id:
Allows you to optionally specify an integer representing the fault_id
from the database table. This allows you to retrieve a specific fault
each time, albeit... | Retrieve a randomly-generated error message as a unicode string.
:param fault_id:
Allows you to optionally specify an integer representing the fault_id
from the database table. This allows you to retrieve a specific fault
each time, albeit with different keywords. |
def start_site(name):
'''
Start a Web Site in IIS.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the website to start.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.start_site name='My Test Site'... | Start a Web Site in IIS.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the website to start.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.start_site name='My Test Site' |
def records(self):
""" Returns a list of records in SORT_KEY order """
return [self._records[i] for i in range(len(self._records))] | Returns a list of records in SORT_KEY order |
def groups_set_description(self, room_id, description, **kwargs):
"""Sets the description for the private group."""
return self.__call_api_post('groups.setDescription', roomId=room_id, description=description, kwargs=kwargs) | Sets the description for the private group. |
def tree(self):
"""
:rtype: cmdtree.tree.CmdTree
"""
from cmdtree.tree import CmdTree
if self._tree is None:
self._tree = CmdTree()
return self._tree | :rtype: cmdtree.tree.CmdTree |
def name(cls):
"""The URL name of this object, unique across all instances of this model"""
if cls.__name_length__ is None:
column_type = UnicodeText()
else:
column_type = Unicode(cls.__name_length__)
if cls.__name_blank_allowed__:
return Column(column... | The URL name of this object, unique across all instances of this model |
def coordination_geometry_symmetry_measures_sepplane_optim(self, coordination_geometry,
points_perfect=None,
nb_set=None, optimization=None):
"""
Returns the symmetry measures of... | Returns the symmetry measures of a given coordination_geometry for a set of permutations depending on
the permutation setup. Depending on the parameters of the LocalGeometryFinder and on the coordination
geometry, different methods are called.
:param coordination_geometry: Coordination geometry... |
def decrypt_var(source, passphrase=None):
"""Attempts to decrypt a variable"""
cmd = [gnupg_bin(), "--decrypt", gnupg_home(), gnupg_verbose(),
passphrase_file(passphrase)]
return stderr_with_input(flatten(cmd), source) | Attempts to decrypt a variable |
def attach(self, name, data=None, maintype=None, subtype=None,
inline=False, filename=None, filename_charset='', filename_language='',
encoding=None):
"""Attach a file to this message.
:param name: Path to the file to attach if data is None, or the name
of the file if the ``data`` argument is given
:pa... | Attach a file to this message.
:param name: Path to the file to attach if data is None, or the name
of the file if the ``data`` argument is given
:param data: Contents of the file to attach, or None if the data is to
be read from the file pointed to by the ``name`` argument
:type data: bytes or a fil... |
def element_should_exist(self, json_string, expr):
"""
Check the existence of one or more elements, matching [ http://jsonselect.org/ | JSONSelect] expression.
*DEPRECATED* JSON Select query language is outdated and not supported any more.
Use other keywords of this library to query JSO... | Check the existence of one or more elements, matching [ http://jsonselect.org/ | JSONSelect] expression.
*DEPRECATED* JSON Select query language is outdated and not supported any more.
Use other keywords of this library to query JSON.
*Args:*\n
_json_string_ - JSON string;\n
_e... |
def gregorian_to_julian(day):
"""Convert a datetime.date object to its corresponding Julian day.
:param day: The datetime.date to convert to a Julian day
:returns: A Julian day, as an integer
"""
before_march = 1 if day.month < MARCH else 0
#
# Number of months since March
#
month_... | Convert a datetime.date object to its corresponding Julian day.
:param day: The datetime.date to convert to a Julian day
:returns: A Julian day, as an integer |
def map_ontologies():
"""Run ontology mapping on a list of INDRA Statements."""
if request.method == 'OPTIONS':
return {}
response = request.body.read().decode('utf-8')
body = json.loads(response)
stmts_json = body.get('statements')
stmts = stmts_from_json(stmts_json)
om = OntologyMa... | Run ontology mapping on a list of INDRA Statements. |
def api_call(endpoint, args, payload):
"""
Generic function to call the RO API
"""
headers = {'content-type': 'application/json; ; charset=utf-8'}
url = 'https://{}/{}'.format(args['--server'], endpoint)
attempt = 0
resp = None
while True:
try:
attempt += 1
... | Generic function to call the RO API |
def copyModel(mdl):
'''
copyModel - Copy this model, and return that copy.
The copied model will have all the same data, but will have a fresh instance of the FIELDS array and all members,
and the INDEXED_FIELDS array.
This is useful for converting, like changing field types or whatever, wh... | copyModel - Copy this model, and return that copy.
The copied model will have all the same data, but will have a fresh instance of the FIELDS array and all members,
and the INDEXED_FIELDS array.
This is useful for converting, like changing field types or whatever, where you can load from one mod... |
def raw(self, drop_collections = False):
"""
Produces the extractor object's data as it is stored internally.
:param bool drop_collections: Defaults to False. Indicates whether columns with lists/dicts/sets will be dropped.
:return: pandas.DataFrame
"""
base_df = self._... | Produces the extractor object's data as it is stored internally.
:param bool drop_collections: Defaults to False. Indicates whether columns with lists/dicts/sets will be dropped.
:return: pandas.DataFrame |
def _set_bang_to_py_ast(ctx: GeneratorContext, node: SetBang) -> GeneratedPyAST:
"""Return a Python AST Node for a `set!` expression."""
assert node.op == NodeOp.SET_BANG
val_temp_name = genname("set_bang_val")
val_ast = gen_py_ast(ctx, node.val)
target = node.target
assert isinstance(
... | Return a Python AST Node for a `set!` expression. |
def list_streams(self):
"""
Returns the existing streams.
Streams are returned in lexicographical order.
:rtype: ~collections.Iterable[.Stream]
"""
# Server does not do pagination on listings of this resource.
# Return an iterator anyway for similarity with othe... | Returns the existing streams.
Streams are returned in lexicographical order.
:rtype: ~collections.Iterable[.Stream] |
def stop(self):
"""
Force the next() method to return while in another thread.
The return value of next() will be None.
"""
with self.condition:
self.running = False
self.condition.notify_all() | Force the next() method to return while in another thread.
The return value of next() will be None. |
def to_dict(self, include_meta=False):
"""
Returns the result as a dictionary, provide the include_meta flag to als show information like index and doctype.
"""
result = super(JackalDoc, self).to_dict(include_meta=include_meta)
if include_meta:
source = result.pop... | Returns the result as a dictionary, provide the include_meta flag to als show information like index and doctype. |
def wait(self):
""" Wait for all running containers to stop.
"""
try:
SpawningProxy(self.containers, abort_on_error=True).wait()
except Exception:
# If a single container failed, stop its peers and re-raise the
# exception
self.stop()
... | Wait for all running containers to stop. |
async def process_activity(self, logic: Callable):
"""
Begins listening to console input.
:param logic:
:return:
"""
while True:
msg = input()
if msg is None:
pass
else:
self._next_id += 1
... | Begins listening to console input.
:param logic:
:return: |
def create_log2fc_bigwigs(matrix, outdir, args):
# type: (pd.DataFrame, str, Namespace) -> None
"""Create bigwigs from matrix."""
call("mkdir -p {}".format(outdir), shell=True)
genome_size_dict = args.chromosome_sizes
outpaths = []
for bed_file in matrix[args.treatment]:
outpath = join... | Create bigwigs from matrix. |
def ellipticity2phi_q(e1, e2):
"""
:param e1:
:param e2:
:return:
"""
phi = np.arctan2(e2, e1)/2
c = np.sqrt(e1**2+e2**2)
if c > 0.999:
c = 0.999
q = (1-c)/(1+c)
return phi, q | :param e1:
:param e2:
:return: |
def add_event(self,
source,
reference,
event_title,
event_type,
method='',
description='',
bucket_list=[],
campaign='',
confidence='',
date=... | Adds an event. If the event name already exists, it will return that
event instead.
Args:
source: Source of the information
reference: A reference where more information can be found
event_title: The title of the event
event_type: The type of event. See y... |
def add(self, text, checked=False, sort=None):
"""Add a new sub item to the list. This item must already be attached to a list.
Args:
text (str): The text.
checked (bool): Whether this item is checked.
sort (int): Item id for sorting.
"""
if self.pare... | Add a new sub item to the list. This item must already be attached to a list.
Args:
text (str): The text.
checked (bool): Whether this item is checked.
sort (int): Item id for sorting. |
def find(self, name, resolved=True):
"""
Get the definition object for the schema object by name.
@param name: The name of a schema object.
@type name: basestring
@param resolved: A flag indicating that the fully resolved type
should be returned.
@type resolve... | Get the definition object for the schema object by name.
@param name: The name of a schema object.
@type name: basestring
@param resolved: A flag indicating that the fully resolved type
should be returned.
@type resolved: boolean
@return: The found schema I{type}
... |
async def get_json(
self, force: bool=False, silent: bool=False, cache: bool=True,
) -> Any:
"""Parses the body data as JSON and returns it.
Arguments:
force: Force JSON parsing even if the mimetype is not JSON.
silent: Do not trigger error handling if parsing fails,... | Parses the body data as JSON and returns it.
Arguments:
force: Force JSON parsing even if the mimetype is not JSON.
silent: Do not trigger error handling if parsing fails, without
this the :meth:`on_json_loading_failed` will be called on
error.
... |
def _call(self, x):
"""Return ``self(x)``."""
result = 0
for i in range(0, self.domain.size - 1):
result += (self.scale * (x[i + 1] - x[i] ** 2) ** 2 +
(x[i] - 1) ** 2)
return result | Return ``self(x)``. |
def spatial_firing_rate(self,label_x='x',label_y='y',bins=None,resolution=1.0,geometry=None,weight_function=None,normalize_time=True,normalize_n=False,start_units_with_0=True):
"""
`bins` can be either a number of bins (has to be int) or a list of edges.
`bins` can be a tuple (fo... | `bins` can be either a number of bins (has to be int) or a list of edges.
`bins` can be a tuple (for x and y respectively).
imshow(s.spatial_firing_rate(weight_function=lambda x: (x[:,1]>0.5)*(x[:,1]<0.6))) |
def _gather_buffer_space():
'''
Gather some system data and then calculate
buffer space.
Result is in bytes.
'''
if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
# Oh good, we have psutil. This will be quick.
total_mem = psutil.virtual_memory().total
else:
# Avoid... | Gather some system data and then calculate
buffer space.
Result is in bytes. |
def parse(self):
"""Parse the configuration.
If one of `BASE_ERROR_SELECTION_OPTIONS` was selected, overrides all
error codes to check and disregards any error code related
configurations from the configuration files.
"""
self._options, self._arguments = self._parse_arg... | Parse the configuration.
If one of `BASE_ERROR_SELECTION_OPTIONS` was selected, overrides all
error codes to check and disregards any error code related
configurations from the configuration files. |
def rename(self, req, parent, name, newparent, newname):
"""Rename a file
Valid replies:
reply_err
"""
self.reply_err(req, errno.EROFS) | Rename a file
Valid replies:
reply_err |
def add_prefix(prefix, s):
"Add `prefix` to all unprefixed names in `s`"
# tokenize the XPath expression
toks = xpath_lexer.scan(s)
# add default prefix to unprefixed names
toks2 = [_add_prefix(prefix, tok) for tok in toks]
# build a string of the patched expression
ls = [x.value for x in to... | Add `prefix` to all unprefixed names in `s` |
def write_file(path, data, format=True):
"""
Write JSON data to file.
Arguments:
path (str): Destination.
data (dict or list): JSON serializable data.
format (bool, optional): Pretty-print JSON data.
"""
if format:
fs.write_file(path, format_json(data))
else:
... | Write JSON data to file.
Arguments:
path (str): Destination.
data (dict or list): JSON serializable data.
format (bool, optional): Pretty-print JSON data. |
def pip_cmd(env, cmd, ignore_activated=False, **kwargs):
r"""Run pip command in given or activated virtual environment.
:param env: Virtual environment name.
:param cmd: Pip subcommand to run.
:param ignore_activated:
Ignore activated virtual environment and use given venv instead. By
d... | r"""Run pip command in given or activated virtual environment.
:param env: Virtual environment name.
:param cmd: Pip subcommand to run.
:param ignore_activated:
Ignore activated virtual environment and use given venv instead. By
default: False
:param \*\*kwargs:
Additional keywo... |
def create(cls, name, address, time_to_live=20, update_interval=10,
secondary=None, comment=None):
"""
Create a DNS Server element.
:param str name: Name of DNS Server
:param str address: IP address for DNS Server element
:param int time_to_live: Defines h... | Create a DNS Server element.
:param str name: Name of DNS Server
:param str address: IP address for DNS Server element
:param int time_to_live: Defines how long a DNS entry can be cached
before querying the DNS server again (default: 20)
:param int update_interval: D... |
def _get_observation(self):
"""
Returns an OrderedDict containing observations [(name_string, np.array), ...].
Important keys:
robot-state: contains robot-centric information.
object-state: requires @self.use_object_obs to be True.
contains object-centric... | Returns an OrderedDict containing observations [(name_string, np.array), ...].
Important keys:
robot-state: contains robot-centric information.
object-state: requires @self.use_object_obs to be True.
contains object-centric information.
image: requires @self.... |
def to_html(self):
"""Render a Cell MessageElement as html
:returns: The html representation of the Cell MessageElement
:rtype: basestring
"""
# Apply bootstrap alignment classes first
if self.align is 'left':
if self.style_class is None:
self... | Render a Cell MessageElement as html
:returns: The html representation of the Cell MessageElement
:rtype: basestring |
def committors(sources, sinks, msm):
"""
Get the forward committors of the reaction sources -> sinks.
Parameters
----------
sources : array_like, int
The set of unfolded/reactant states.
sinks : array_like, int
The set of folded/product states.
msm : msmbuilder.MarkovStateMo... | Get the forward committors of the reaction sources -> sinks.
Parameters
----------
sources : array_like, int
The set of unfolded/reactant states.
sinks : array_like, int
The set of folded/product states.
msm : msmbuilder.MarkovStateModel
MSM fit to the data.
Returns
... |
def plot(self, hist=False, show=False, **kwargs):
"""
Plot the distribution of the UncertainVariable. Continuous
distributions are plotted with a line plot and discrete distributions
are plotted with discrete circles.
Optional
--------
hist : bool
... | Plot the distribution of the UncertainVariable. Continuous
distributions are plotted with a line plot and discrete distributions
are plotted with discrete circles.
Optional
--------
hist : bool
If true, a histogram is displayed
show : bool
... |
def multicolumn_map_expectation(cls, func):
"""
The multicolumn_map_expectation decorator handles boilerplate issues surrounding the common pattern of
evaluating truthiness of some condition on a per row basis across a set of columns.
"""
if PY3:
argspec = inspect.get... | The multicolumn_map_expectation decorator handles boilerplate issues surrounding the common pattern of
evaluating truthiness of some condition on a per row basis across a set of columns. |
def from_raw_message(cls, rawmessage):
"""Create a message from a raw byte stream."""
userdata_dict = Userdata(rawmessage[8:22])
return ExtendedSend(rawmessage[2:5],
{'cmd1': rawmessage[6],
'cmd2': rawmessage[7]},
... | Create a message from a raw byte stream. |
def netconf_confirmed_commit_source_host(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
netconf_confirmed_commit = ET.SubElement(config, "netconf-confirmed-commit", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-notifications")
source_host = ET.SubElem... | Auto Generated Code |
def get_lswitch_ids_for_network(self, context, network_id):
"""Public interface for fetching lswitch ids for a given network.
NOTE(morgabra) This is here because calling private methods
from outside the class feels wrong, and we need to be able to
fetch lswitch ids for use in other driv... | Public interface for fetching lswitch ids for a given network.
NOTE(morgabra) This is here because calling private methods
from outside the class feels wrong, and we need to be able to
fetch lswitch ids for use in other drivers. |
def _ToString(x):
"""The default default formatter!."""
# Some cross-language values for primitives. This is tested in
# jsontemplate_test.py.
if x is None:
return 'null'
if isinstance(x, six.string_types):
return x
return pprint.pformat(x) | The default default formatter!. |
def groups_filter_from_query(query, field_map={}):
"""Creates an F object for the groups of a search query."""
f = None
# filter groups
for group in query.get("groups", []):
group_f = MatchAll()
for condition in group.get("conditions", []):
field_name = condition["field"]
... | Creates an F object for the groups of a search query. |
def modify_karma(self, words):
"""
Given a regex object, look through the groups and modify karma
as necessary
"""
# 'user': karma
k = defaultdict(int)
if words:
# For loop through all of the group members
for word_tuple in words:
... | Given a regex object, look through the groups and modify karma
as necessary |
def detect_function_shadowing(contracts, direct_shadowing=True, indirect_shadowing=True):
"""
Detects all overshadowing and overshadowed functions in the provided contracts.
:param contracts: The contracts to detect shadowing within.
:param direct_shadowing: Include results from direct inheritance/inher... | Detects all overshadowing and overshadowed functions in the provided contracts.
:param contracts: The contracts to detect shadowing within.
:param direct_shadowing: Include results from direct inheritance/inheritance ancestry.
:param indirect_shadowing: Include results from indirect inheritance collisions a... |
def sample(self):
""" Sample from M-H algorithm
Returns
----------
chain : np.array
Chains for each parameter
mean_est : np.array
Mean values for each parameter
median_est : np.array
Median values for each parameter
upper_95... | Sample from M-H algorithm
Returns
----------
chain : np.array
Chains for each parameter
mean_est : np.array
Mean values for each parameter
median_est : np.array
Median values for each parameter
upper_95_est : np.array
Up... |
def is_varchar(self):
"""Determine if a data record is of the type VARCHAR."""
dt = DATA_TYPES['varchar']
if type(self.data) is dt['type'] and len(self.data) < dt['max']:
self.type = 'VARCHAR'
self.len = len(self.data)
return True | Determine if a data record is of the type VARCHAR. |
def try_printout(data, out, opts, **kwargs):
'''
Safely get the string to print out, try the configured outputter, then
fall back to nested and then to raw
'''
try:
printout = get_printout(out, opts)(data, **kwargs)
if printout is not None:
return printout.rstrip()
ex... | Safely get the string to print out, try the configured outputter, then
fall back to nested and then to raw |
def generate_complementary_strand(strand1):
"""Takes a SingleStrandHelix and creates the antisense strand."""
rise_adjust = (
strand1.rise_per_nucleotide * strand1.axis.unit_tangent) * 2
strand2 = NucleicAcidStrand.from_start_and_end(
strand1.helix_end - rise_adjust, stra... | Takes a SingleStrandHelix and creates the antisense strand. |
def get(self, report_id):
"""Retrieve report by ID
Args:
report_id (str): Full report ID
Returns:
Report: Corresponding Report instance
"""
return Report(
self._app,
self._swimlane.request('get', "reports/{0}".format(report_id)).j... | Retrieve report by ID
Args:
report_id (str): Full report ID
Returns:
Report: Corresponding Report instance |
def _init_params_default(self):
"""
Internal method for default parameter initialization
"""
# if there are some nan -> mean impute
Yimp = self.Y.copy()
Inan = sp.isnan(Yimp)
Yimp[Inan] = Yimp[~Inan].mean()
if self.P==1: C = sp.array([[Yimp.var()]])
... | Internal method for default parameter initialization |
def iterfile(path, since=-1):
'''
Generator which yields msgpack objects from a file path.
Args:
path: File path to open and consume data from.
Notes:
String objects are decoded using utf8 encoding. In order to handle
potentially malformed input, ``unicode_errors='surrogatepas... | Generator which yields msgpack objects from a file path.
Args:
path: File path to open and consume data from.
Notes:
String objects are decoded using utf8 encoding. In order to handle
potentially malformed input, ``unicode_errors='surrogatepass'`` is set
to allow decoding bad ... |
def is_zero(pauli_object):
"""
Tests to see if a PauliTerm or PauliSum is zero.
:param pauli_object: Either a PauliTerm or PauliSum
:returns: True if PauliTerm is zero, False otherwise
:rtype: bool
"""
if isinstance(pauli_object, PauliTerm):
return np.isclose(pauli_object.coefficien... | Tests to see if a PauliTerm or PauliSum is zero.
:param pauli_object: Either a PauliTerm or PauliSum
:returns: True if PauliTerm is zero, False otherwise
:rtype: bool |
def getPrimaryKeys(self, sortByAge=False):
'''
getPrimaryKeys - Returns all primary keys matching current filterset.
@param sortByAge <bool> - If False, return will be a set and may not be ordered.
If True, return will be a list and is guarenteed to represent objects oldest->newest
@return <set> - A se... | getPrimaryKeys - Returns all primary keys matching current filterset.
@param sortByAge <bool> - If False, return will be a set and may not be ordered.
If True, return will be a list and is guarenteed to represent objects oldest->newest
@return <set> - A set of all primary keys associated with current filter... |
def _entity_to_region_map(self):
"""
A dict whose keys are the UUIDs (or just IDs, in some cases) of
entities, and whose values are the `(rx, ry)` coordinates in which that
entity can be found. This can be used to easily locate particular
entities inside the world.
"""
... | A dict whose keys are the UUIDs (or just IDs, in some cases) of
entities, and whose values are the `(rx, ry)` coordinates in which that
entity can be found. This can be used to easily locate particular
entities inside the world. |
def html(text, extensions=0, render_flags=0):
"""
Convert markdown text to HTML.
``extensions`` can be a list or tuple of extensions (e.g.
``('fenced-code', 'footnotes', 'strikethrough')``) or an integer
(e.g. ``EXT_FENCED_CODE | EXT_FOOTNOTES | EXT_STRIKETHROUGH``).
``render_flags`` can be a ... | Convert markdown text to HTML.
``extensions`` can be a list or tuple of extensions (e.g.
``('fenced-code', 'footnotes', 'strikethrough')``) or an integer
(e.g. ``EXT_FENCED_CODE | EXT_FOOTNOTES | EXT_STRIKETHROUGH``).
``render_flags`` can be a list or tuple of flags (e.g.
``('skip-html', 'hard-wra... |
def ngram_diff(args, parser):
"""Outputs the results of performing a diff query."""
store = utils.get_data_store(args)
corpus = utils.get_corpus(args)
catalogue = utils.get_catalogue(args)
tokenizer = utils.get_tokenizer(args)
store.validate(corpus, catalogue)
if args.asymmetric:
sto... | Outputs the results of performing a diff query. |
def album_primary_image_url(self):
'''The image of the album'''
path = '/Items/{}/Images/Primary'.format(self.album_id)
return self.connector.get_url(path, attach_api_key=False) | The image of the album |
def funding_info2marc(self, key, value):
"""Populate the ``536`` MARC field."""
return {
'a': value.get('agency'),
'c': value.get('grant_number'),
'f': value.get('project_number'),
} | Populate the ``536`` MARC field. |
def save_state_machine(delete_old_state_machine=False, recent_opened_notification=False, as_copy=False, copy_path=None):
""" Save selected state machine
The function checks if states of the state machine has not stored script data abd triggers dialog windows to
take user input how to continue (ignoring o... | Save selected state machine
The function checks if states of the state machine has not stored script data abd triggers dialog windows to
take user input how to continue (ignoring or storing this script changes).
If the state machine file_system_path is None function save_state_machine_as is used to coll... |
def purge(self, connection):
"""Remove the connection from rotation"""
self._checkpid()
if connection.pid == self.pid:
idx = connection._pattern_idx
if connection in self._in_use_connections[idx]:
self._in_use_connections[idx].remove(connection)
... | Remove the connection from rotation |
def _get_batch_representative(items, key):
"""Retrieve a representative data item from a batch.
Handles standard bcbio cases (a single data item) and CWL cases with
batches that have a consistent variant file.
"""
if isinstance(items, dict):
return items, items
else:
vals = set(... | Retrieve a representative data item from a batch.
Handles standard bcbio cases (a single data item) and CWL cases with
batches that have a consistent variant file. |
def _from_dict(cls, _dict):
"""Initialize a SemanticRolesResult object from a json dictionary."""
args = {}
if 'sentence' in _dict:
args['sentence'] = _dict.get('sentence')
if 'subject' in _dict:
args['subject'] = SemanticRolesResultSubject._from_dict(
... | Initialize a SemanticRolesResult object from a json dictionary. |
def refresh(self, props, body):
"""
the refresh method called when on demand refresh service receive a message. then call the parent actor sniff
method if message is compliant on what is attended
:param props: the message properties
:param body: the message body
:return:
... | the refresh method called when on demand refresh service receive a message. then call the parent actor sniff
method if message is compliant on what is attended
:param props: the message properties
:param body: the message body
:return: |
async def publish_changes(self, zone, changes):
"""Post changes to a zone.
Args:
zone (str): DNS zone of the change.
changes (dict): JSON compatible dict of a `Change
<https://cloud.google.com/dns/api/v1/changes>`_.
Returns:
string identifier ... | Post changes to a zone.
Args:
zone (str): DNS zone of the change.
changes (dict): JSON compatible dict of a `Change
<https://cloud.google.com/dns/api/v1/changes>`_.
Returns:
string identifier of the change. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.