code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def fromJSON(value):
"""loads the GP object from a JSON string """
j = json.loads(value)
v = GPLong()
if "defaultValue" in j:
v.value = j['defaultValue']
else:
v.value = j['value']
if 'paramName' in j:
v.paramName = j['paramName']
... | loads the GP object from a JSON string |
def awscli_defaults(os_type=None):
"""
Summary:
Parse, update local awscli config credentials
Args:
:user (str): USERNAME, only required when run on windows os
Returns:
TYPE: dict object containing key, value pairs describing
os information
"""
try:
if o... | Summary:
Parse, update local awscli config credentials
Args:
:user (str): USERNAME, only required when run on windows os
Returns:
TYPE: dict object containing key, value pairs describing
os information |
def p_object_literal(self, p):
"""object_literal : LBRACE RBRACE
| LBRACE property_list RBRACE
| LBRACE property_list COMMA RBRACE
"""
if len(p) == 3:
p[0] = self.asttypes.Object()
else:
p[0] = self.asttypes.Obje... | object_literal : LBRACE RBRACE
| LBRACE property_list RBRACE
| LBRACE property_list COMMA RBRACE |
def register_message(self, message):
"""Register a MessageDefinition with consistency in mind.
:param MessageDefinition message: The message definition being added.
"""
self._check_id_and_symbol_consistency(message.msgid, message.symbol)
self._check_symbol(message.msgid, message... | Register a MessageDefinition with consistency in mind.
:param MessageDefinition message: The message definition being added. |
def compile_validation_pattern(self, units=None):
"""
Assure that passed in units are valid size units, or if missing, use all possible units.
Return a tuple with a regular expression to be used for validating and an error message
in case this validation failed.
"""
if un... | Assure that passed in units are valid size units, or if missing, use all possible units.
Return a tuple with a regular expression to be used for validating and an error message
in case this validation failed. |
def get_memory(self,
shutit_pexpect_child=None,
note=None):
"""Returns memory available for use in k as an int"""
shutit_global.shutit_global_object.yield_to_draw()
shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child
shutit_pexpe... | Returns memory available for use in k as an int |
def _rm_get_reference_coords_from_header(parts):
"""
extract the reference (genomic sequence match) coordinates of a repeat
occurrence from a repeatmakser header line. An example header line is::
239 29.42 1.92 0.97 chr1 11 17 (41) C XX#YY (74) 104 1 m_b1s502i1 4
the genomic start and end are always at po... | extract the reference (genomic sequence match) coordinates of a repeat
occurrence from a repeatmakser header line. An example header line is::
239 29.42 1.92 0.97 chr1 11 17 (41) C XX#YY (74) 104 1 m_b1s502i1 4
the genomic start and end are always at positions 5 and 6 resepctively. In
the repeatmasker forma... |
async def xdel(self, name: str, stream_id: str) -> int:
"""
[NOTICE] Not officially released yet
[NOTICE] In the current implementation, memory is not
really reclaimed until a macro node is completely empty,
so you should not abuse this feature.
remove items from the mid... | [NOTICE] Not officially released yet
[NOTICE] In the current implementation, memory is not
really reclaimed until a macro node is completely empty,
so you should not abuse this feature.
remove items from the middle of a stream, just by ID.
:param name: name of the stream
... |
def on_finish(self, exc=None):
"""Used to initiate the garbage collection"""
super(GarbageCollector, self).on_finish(exc)
self._cycles_left -= 1
if self._cycles_left <= 0:
num_collected = gc.collect()
self._cycles_left = self.collection_cycle
LOGGER.de... | Used to initiate the garbage collection |
def _execute(self, command, stdin=None, stdout=subprocess.PIPE):
"""Executes the specified command relative to the repository root.
Returns a tuple containing the return code and the process output.
"""
process = subprocess.Popen(command, shell=True, cwd=self.root_path, stdin=stdin, stdo... | Executes the specified command relative to the repository root.
Returns a tuple containing the return code and the process output. |
def clone(self, substitutions, **kwargs):
"""
Clone a DAG.
"""
dag = self.explain(**kwargs)
dag.substitutions.update(substitutions)
cloned_dag = dag.clone(ignore=self.ignore)
return self.update_nodes(self.add_edges(cloned_dag)) | Clone a DAG. |
def cmd_hasher(f, algorithm):
"""Compute various hashes for the input data, that can be a file or a stream.
Example:
\b
$ habu.hasher README.rst
md5 992a833cd162047daaa6a236b8ac15ae README.rst
ripemd160 0566f9141e65e57cae93e0e3b70d1d8c2ccb0623 README.rst
sha1 d7dbfd2c5e... | Compute various hashes for the input data, that can be a file or a stream.
Example:
\b
$ habu.hasher README.rst
md5 992a833cd162047daaa6a236b8ac15ae README.rst
ripemd160 0566f9141e65e57cae93e0e3b70d1d8c2ccb0623 README.rst
sha1 d7dbfd2c5e2828eb22f776550c826e4166526253 README... |
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
thread = self.threads.get(item['tid'])
link = local("origin") + thr... | @api {get} / get comments
@apiGroup Thread
@apiDescription Queries the comments of a thread.
@apiParam {string} uri
The URI of thread to get the comments from.
@apiParam {number} [parent]
Return only comments that are children of the comment with the provided ID.... |
def tf(self, term):
r"""Return term frequency.
Parameters
----------
term : str
The term for which to calculate tf
Returns
-------
float
The term frequency (tf)
Raises
------
ValueError
tf can only cal... | r"""Return term frequency.
Parameters
----------
term : str
The term for which to calculate tf
Returns
-------
float
The term frequency (tf)
Raises
------
ValueError
tf can only calculate the frequency of indi... |
def get_hardware_source_by_id(self, hardware_source_id: str, version: str):
"""Return the hardware source API matching the hardware_source_id and version.
.. versionadded:: 1.0
Scriptable: Yes
"""
actual_version = "1.0.0"
if Utility.compare_versions(version, actual_vers... | Return the hardware source API matching the hardware_source_id and version.
.. versionadded:: 1.0
Scriptable: Yes |
def create_cookie(name, value, **kwargs):
"""Make a cookie from underspecified parameters.
By default, the pair of `name` and `value` will be set for the domain ''
and sent on every request (this is sometimes called a "supercookie").
"""
result = {
'version': 0,
'name': name,
... | Make a cookie from underspecified parameters.
By default, the pair of `name` and `value` will be set for the domain ''
and sent on every request (this is sometimes called a "supercookie"). |
def run(self, args):
"""
Give the user with user_full_name the auth_role permissions on the remote project with project_name.
:param args Namespace arguments parsed from the command line
"""
email = args.email # email of person to give permissions, will be None i... | Give the user with user_full_name the auth_role permissions on the remote project with project_name.
:param args Namespace arguments parsed from the command line |
def unwire(awsclient, events, lambda_name, alias_name=ALIAS_NAME):
"""Unwire a list of event from an AWS Lambda function.
'events' is a list of dictionaries, where the dict must contains the
'schedule' of the event as string, and an optional 'name' and 'description'.
:param awsclient:
:param event... | Unwire a list of event from an AWS Lambda function.
'events' is a list of dictionaries, where the dict must contains the
'schedule' of the event as string, and an optional 'name' and 'description'.
:param awsclient:
:param events: list of events
:param lambda_name:
:param alias_name:
:retu... |
def search_data_std(Channel, RunNos, RepeatNos, directoryPath='.'):
"""
Lets you find multiple datasets at once assuming they have a
filename which contains a pattern of the form:
CH<ChannelNo>_RUN00...<RunNo>_REPEAT00...<RepeatNo>
Parameters
----------
Channel : int
The channe... | Lets you find multiple datasets at once assuming they have a
filename which contains a pattern of the form:
CH<ChannelNo>_RUN00...<RunNo>_REPEAT00...<RepeatNo>
Parameters
----------
Channel : int
The channel you want to load
RunNos : sequence
Sequence of run numbers you wan... |
def run(self):
"""
Run the plugin.
"""
if self.workflow.builder.base_from_scratch:
self.log.info("Skipping comparing components: unsupported for FROM-scratch images")
return
worker_metadatas = self.workflow.postbuild_results.get(PLUGIN_FETCH_WORKER_METADA... | Run the plugin. |
def store_psm_protein_relations(fn, header, pgdb, proteins):
"""Reads PSMs from file, extracts their proteins and peptides and passes
them to a database backend in chunks.
"""
# TODO do we need an OrderedDict or is regular dict enough?
# Sorting for psm_id useful?
allpsms = OrderedDict()
las... | Reads PSMs from file, extracts their proteins and peptides and passes
them to a database backend in chunks. |
def cli(url, user_agent):
"""
Archives the provided URL using archive.is.
"""
kwargs = {}
if user_agent:
kwargs['user_agent'] = user_agent
archive_url = capture(url, **kwargs)
click.echo(archive_url) | Archives the provided URL using archive.is. |
def close(self):
'''
Closes the CDF Class.
1. If compression was set, this is where the compressed file is
written.
2. If a checksum is needed, this will place the checksum at the end
of the file.
'''
if self.compressed_file is Non... | Closes the CDF Class.
1. If compression was set, this is where the compressed file is
written.
2. If a checksum is needed, this will place the checksum at the end
of the file. |
def get_connect_redirect_url(self, request, socialaccount):
"""
Returns the default URL to redirect to after successfully
connecting a social account.
"""
assert request.user.is_authenticated
url = reverse('socialaccount_connections')
return url | Returns the default URL to redirect to after successfully
connecting a social account. |
def _release_lock(self, identifier):
'''Release the lock.
This requires you to actually have owned the lock. On return
you definitely do not own it, but if somebody else owned it
before calling this function, they still do.
:param str identifier: the session lock identifier
... | Release the lock.
This requires you to actually have owned the lock. On return
you definitely do not own it, but if somebody else owned it
before calling this function, they still do.
:param str identifier: the session lock identifier
:return: :const:`True` if you actually did... |
def get_default_filepath(cls):
"""Get the default filepath for the configuratin file."""
if not cls.config_files:
return None
if not cls.config_searchpath:
return None
filename = cls.config_files[0]
filepath = cls.config_searchpath[0]
return os.pat... | Get the default filepath for the configuratin file. |
def GetRunlevelsNonLSB(states):
"""Accepts a string and returns a list of strings of numeric LSB runlevels."""
if not states:
return set()
convert_table = {
"0": "0",
"1": "1",
"2": "2",
"3": "3",
"4": "4",
"5": "5",
"6": "6",
# SysV, Gentoo, Solaris, HP-UX all ... | Accepts a string and returns a list of strings of numeric LSB runlevels. |
def send_mass_text(self, group_or_users, content,
is_to_all=False, preview=False,
send_ignore_reprint=0, client_msg_id=None):
"""
群发文本消息
详情请参考
https://mp.weixin.qq.com/wiki?id=mp1481187827_i0l21
:param group_or_users: 值为整型数字时为按分组群发,... | 群发文本消息
详情请参考
https://mp.weixin.qq.com/wiki?id=mp1481187827_i0l21
:param group_or_users: 值为整型数字时为按分组群发,值为列表/元组时为按 OpenID 列表群发
当 is_to_all 为 True 时,传入 None 即对所有用户发送。
:param content: 消息正文
:param is_to_all: 用于设定是否向全部用户发送,值为true或false,选择true该消息群发给所有用户
... |
def get_oxi_state_decorated_structure(self, structure):
"""
Get an oxidation state decorated structure. This currently works only
for ordered structures only.
Args:
structure: Structure to analyze
Returns:
A modified structure that is oxidation state dec... | Get an oxidation state decorated structure. This currently works only
for ordered structures only.
Args:
structure: Structure to analyze
Returns:
A modified structure that is oxidation state decorated.
Raises:
ValueError if the valences cannot be de... |
def get_stats(self):
"""
Get repository descriptive stats
:Returns:
#. numberOfDirectories (integer): Number of diretories in repository
#. numberOfFiles (integer): Number of files in repository
"""
if self.__path is None:
return 0,0
n... | Get repository descriptive stats
:Returns:
#. numberOfDirectories (integer): Number of diretories in repository
#. numberOfFiles (integer): Number of files in repository |
def set(self, name, value):
"""Set an option value.
Args:
name (str): The name of the option.
value: The value to set the option to.
Raises:
TypeError: If the value is not a string or appropriate native type.
ValueError: If the value is ... | Set an option value.
Args:
name (str): The name of the option.
value: The value to set the option to.
Raises:
TypeError: If the value is not a string or appropriate native type.
ValueError: If the value is a string but cannot be coerced.
... |
def _compute_ticks(self, element, edges, widths, lims):
"""
Compute the ticks either as cyclic values in degrees or as roughly
evenly spaced bin centers.
"""
if self.xticks is None or not isinstance(self.xticks, int):
return None
if self.cyclic:
x0... | Compute the ticks either as cyclic values in degrees or as roughly
evenly spaced bin centers. |
def invalidate(self, key):
'''Clear an item from the cache'''
path = self.path(self.xform_key(key))
try:
LOG.debug('invalidate %s (%s)', key, path)
path.unlink()
except OSError:
pass | Clear an item from the cache |
def get_bool(self, key, default=None):
"""
Same as :meth:`dict.get`, but the value is converted to a bool.
The boolean value is considered, respectively, :obj:`True` or
:obj:`False` if the string is equal, ignoring case, to
``'true'`` or ``'false'``.
"""
v = self... | Same as :meth:`dict.get`, but the value is converted to a bool.
The boolean value is considered, respectively, :obj:`True` or
:obj:`False` if the string is equal, ignoring case, to
``'true'`` or ``'false'``. |
def _remove_string_from_commastring(self, field, string):
# type: (str, str) -> bool
"""Remove a string from a comma separated list of strings
Args:
field (str): Field containing comma separated list
string (str): String to remove
Returns:
bool: True... | Remove a string from a comma separated list of strings
Args:
field (str): Field containing comma separated list
string (str): String to remove
Returns:
bool: True if string removed or False if not |
def prep_db_parallel(samples, parallel_fn):
"""Prepares gemini databases in parallel, handling jointly called populations.
"""
batch_groups, singles, out_retrieve, extras = _group_by_batches(samples, _has_variant_calls)
to_process = []
has_batches = False
for (name, caller), info in batch_groups... | Prepares gemini databases in parallel, handling jointly called populations. |
def remove_file(self, path):
"""Removes the given file"""
self.get_file(path).remove()
self.remove_cache_buster(path) | Removes the given file |
def determine_orig_wcsname(header, wnames, wkeys):
"""
Determine the name of the original, unmodified WCS solution
"""
orig_wcsname = None
orig_key = None
if orig_wcsname is None:
for k,w in wnames.items():
if w[:4] == 'IDC_':
orig_wcsname = w
... | Determine the name of the original, unmodified WCS solution |
def local_open(url):
"""Read a local path, with special support for directories"""
scheme, server, path, param, query, frag = urllib.parse.urlparse(url)
filename = urllib.request.url2pathname(path)
if os.path.isfile(filename):
return urllib.request.urlopen(url)
elif path.endswith('/') and os... | Read a local path, with special support for directories |
def lat_from_pole(ref_loc_lon, ref_loc_lat, pole_plon, pole_plat):
"""
Calculate paleolatitude for a reference location based on a paleomagnetic pole
Required Parameters
----------
ref_loc_lon: longitude of reference location in degrees
ref_loc_lat: latitude of reference location
pole_plon:... | Calculate paleolatitude for a reference location based on a paleomagnetic pole
Required Parameters
----------
ref_loc_lon: longitude of reference location in degrees
ref_loc_lat: latitude of reference location
pole_plon: paleopole longitude in degrees
pole_plat: paleopole latitude in degrees |
def get(self, file_id):
"""Get a file from GridFS by ``"_id"``.
Returns an instance of :class:`~gridfs.grid_file.GridOut`,
which provides a file-like interface for reading.
:Parameters:
- `file_id`: ``"_id"`` of the file to get
.. versionadded:: 1.6
"""
... | Get a file from GridFS by ``"_id"``.
Returns an instance of :class:`~gridfs.grid_file.GridOut`,
which provides a file-like interface for reading.
:Parameters:
- `file_id`: ``"_id"`` of the file to get
.. versionadded:: 1.6 |
def is_valid_mpls_labels(labels):
"""Returns True if the given value is a list of valid MPLS labels.
"""
if not isinstance(labels, (list, tuple)):
return False
for label in labels:
if not is_valid_mpls_label(label):
return False
return True | Returns True if the given value is a list of valid MPLS labels. |
def update_image(self, container_name, image_name):
"""
update a container's image,
:param container_name: `class`:`str`, container name
:param image_name: `class`:`str`, the full image name, like alpine:3.3
:return: `class`:`bool`, True if success, otherwise False.
... | update a container's image,
:param container_name: `class`:`str`, container name
:param image_name: `class`:`str`, the full image name, like alpine:3.3
:return: `class`:`bool`, True if success, otherwise False. |
def rectgal_to_sphergal(X,Y,Z,vx,vy,vz,degree=False):
"""
NAME:
rectgal_to_sphergal
PURPOSE:
transform phase-space coordinates in rectangular Galactic coordinates to spherical Galactic coordinates (can take vector inputs)
INPUT:
X - component towards the Galactic Center (kpc)
... | NAME:
rectgal_to_sphergal
PURPOSE:
transform phase-space coordinates in rectangular Galactic coordinates to spherical Galactic coordinates (can take vector inputs)
INPUT:
X - component towards the Galactic Center (kpc)
Y - component in the direction of Galactic rotation (kpc)
... |
def _return_response(self, response):
"""
:type result: HTTPResponse
"""
self.filter_headers(response.msg)
if "content-length" in response.msg:
del response.msg["content-length"]
self.send_response(response.status, response.reason)
for header_key, hea... | :type result: HTTPResponse |
def update_properties(self, properties):
"""
Update writeable properties of this PasswordRule.
The Password Rule must be user-defined. System-defined Password Rules
cannot be updated.
Authorization requirements:
* Task permission to the "Manage Password Rules" task.
... | Update writeable properties of this PasswordRule.
The Password Rule must be user-defined. System-defined Password Rules
cannot be updated.
Authorization requirements:
* Task permission to the "Manage Password Rules" task.
Parameters:
properties (dict): New values f... |
def task_add(self, t, periodic=None):
"""
Register a task in this legion. "periodic" should be None, or
a callback function which will be called periodically when the
legion is otherwise idle.
"""
name = t.get_name()
if name in self._tasknames:
raise Task... | Register a task in this legion. "periodic" should be None, or
a callback function which will be called periodically when the
legion is otherwise idle. |
def incidence(boundary):
"""
given an Nxm matrix containing boundary info between simplices,
compute indidence info matrix
not very reusable; should probably not be in this lib
"""
return GroupBy(boundary).split(np.arange(boundary.size) // boundary.shape[1]) | given an Nxm matrix containing boundary info between simplices,
compute indidence info matrix
not very reusable; should probably not be in this lib |
def max_play(w, i, grid):
"Play like Spock, except breaking ties by drunk_value."
return min(successors(grid),
key=lambda succ: (evaluate(succ), drunk_value(succ))) | Play like Spock, except breaking ties by drunk_value. |
def findCells(fnames):
"""
given a list of files, return a list of cells by their ID.
A cell is indicated when an ABF name matches the start of another file.
Example:
123456.abf
123456-whatever.tif
"""
IDs=[]
filesByExt = filesByExtension(fnames)
for abfFname in fil... | given a list of files, return a list of cells by their ID.
A cell is indicated when an ABF name matches the start of another file.
Example:
123456.abf
123456-whatever.tif |
def get(self, guild_id):
""" Returns a player from the cache, or creates one if it does not exist. """
if guild_id not in self._players:
p = self._player(lavalink=self.lavalink, guild_id=guild_id)
self._players[guild_id] = p
return self._players[guild_id] | Returns a player from the cache, or creates one if it does not exist. |
def text(self):
"""Content as string
If :attr:`encoding` is None, the encoding is guessed with :meth:`guess_encoding`
"""
if not self.content:
return
if self.encoding:
return self.content.decode(self.encoding, errors='replace')
return self.cont... | Content as string
If :attr:`encoding` is None, the encoding is guessed with :meth:`guess_encoding` |
def get_power(self,callb=None):
"""Convenience method to request the power status from the device
This method will check whether the value has already been retrieved from the device,
if so, it will simply return it. If no, it will request the information from the device
and request that... | Convenience method to request the power status from the device
This method will check whether the value has already been retrieved from the device,
if so, it will simply return it. If no, it will request the information from the device
and request that callb be executed when a response is recei... |
def plot_heat_map(z, include_values=False,
cmap=matplotlib.cm.Reds,
ax=None,
xlabel='auto', ylabel='auto',
xtick_labels='auto', ytick_labels='auto',
xtick_locs=None, ytick_locs=None,
xtick_kwargs={}, ytick_kwargs... | Plot a heat map of z.
Parameters
-------------
z : ndarray | DataFrame
ax : None # NOT IMPLEMENTED YET
Axis to be used. If None uses the current axis.
xlabel : str | 'auto' | None
name for the x-axis
ylabel : str | 'auto' | None
name for the y-axis
xtick_labels : li... |
def get_badge(self):
"""
The related ``Badge`` object.
"""
try:
obj = Badge.objects.using(self.db_read).get(slug=self.slug)
logger.debug('✓ Badge %s: fetched from db (%s)', obj.slug, self.db_read)
except Badge.DoesNotExist:
obj = None
r... | The related ``Badge`` object. |
def ensure_dir(directory: str) -> None:
"""Create a directory if it doesn't exist."""
if not os.path.isdir(directory):
LOG.debug(f"Directory {directory} does not exist, creating it.")
os.makedirs(directory) | Create a directory if it doesn't exist. |
def get_java_home():
"""\
Try getting JAVA_HOME from system properties.
We are interested in the JDK home, containing include/jni.h, while the
java.home property points to the JRE home. If a JDK is installed, however,
the two are (usually) related: the JDK home is either the same directory
as t... | \
Try getting JAVA_HOME from system properties.
We are interested in the JDK home, containing include/jni.h, while the
java.home property points to the JRE home. If a JDK is installed, however,
the two are (usually) related: the JDK home is either the same directory
as the JRE home (recent java ver... |
def component(self, *components):
r"""
When search() is called it will limit results to items in a component.
:param component: items passed in will be turned into a list
:returns: :class:`Search`
"""
for component in components:
self._component.a... | r"""
When search() is called it will limit results to items in a component.
:param component: items passed in will be turned into a list
:returns: :class:`Search` |
def has_selector(selector):
"Determine if the current platform has the selector available"
try:
if selector == 'poll':
# the select module offers the poll selector even if the platform
# doesn't support it. Attempt to poll for nothing to make sure
# poll is available
... | Determine if the current platform has the selector available |
def model_from_list(l, header):
"""Return a model with a collection from a list of entry"""
col = groups.sortableListe(PseudoAccesCategorie(n) for n in l)
return MultiSelectModel(col, header) | Return a model with a collection from a list of entry |
def sanity_check_states(states_spec):
"""
Sanity checks a states dict, used to define the state space for an MDP.
Throws an error or warns if mismatches are found.
Args:
states_spec (Union[None,dict]): The spec-dict to check (or None).
Returns: Tuple of 1) the state space desc and 2) wheth... | Sanity checks a states dict, used to define the state space for an MDP.
Throws an error or warns if mismatches are found.
Args:
states_spec (Union[None,dict]): The spec-dict to check (or None).
Returns: Tuple of 1) the state space desc and 2) whether there is only one component in the state space. |
def warning(self, msg: str) -> None:
"""
Write a warning message to the Windows Application log
(± to the Python disk log).
"""
# Log messages go to the Windows APPLICATION log.
# noinspection PyUnresolvedReferences
s = "{}: {}".format(self.fullname, msg)
... | Write a warning message to the Windows Application log
(± to the Python disk log). |
def delete_router(self, name, tenant_id, rout_id, subnet_lst):
"""Delete the openstack router.
Delete the router and remove the interfaces attached to it.
"""
ret = self.delete_intf_router(name, tenant_id, rout_id, subnet_lst)
if not ret:
return False
try:
... | Delete the openstack router.
Delete the router and remove the interfaces attached to it. |
def applyStyleOnShape(self, shape, node, only_explicit=False):
"""
Apply styles from an SVG element to an RLG shape.
If only_explicit is True, only attributes really present are applied.
"""
# RLG-specific: all RLG shapes
"Apply style attributes of a sequence of nodes to... | Apply styles from an SVG element to an RLG shape.
If only_explicit is True, only attributes really present are applied. |
def targets(tgt, tgt_type='glob', **kwargs): # pylint: disable=W0613
'''
Return the targets from the flat yaml file, checks opts for location but
defaults to /etc/salt/roster
'''
ret = {}
cloud_opts = salt.config.cloud_config(
os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud... | Return the targets from the flat yaml file, checks opts for location but
defaults to /etc/salt/roster |
def _make_dispatch(cls, func):
'''
Create a dispatch pair for func- a tuple of (bind_args, func), where
bind_args is a function that, when called with (args, kwargs), attempts
to bind those args to the type signature of func, or else raise a
TypeError
'''
sig = si... | Create a dispatch pair for func- a tuple of (bind_args, func), where
bind_args is a function that, when called with (args, kwargs), attempts
to bind those args to the type signature of func, or else raise a
TypeError |
def _get_input_name(self, input_str, region=None, describe_output=None):
'''
:param input_str: A string of one of the forms: "<exported input field name>", "<explicit workflow input field name>", "<stage ID>.<input field name>", "<stage index>.<input field name>", "<stage name>.<input field name>"
... | :param input_str: A string of one of the forms: "<exported input field name>", "<explicit workflow input field name>", "<stage ID>.<input field name>", "<stage index>.<input field name>", "<stage name>.<input field name>"
:type input_str: string
:returns: If the given form was one of those which uses th... |
def recv(self, topic, payload, qos):
"""Receive a MQTT message.
Call this method when a message is received from the MQTT broker.
"""
data = self._parse_mqtt_to_message(topic, payload, qos)
if data is None:
return
_LOGGER.debug('Receiving %s', data)
s... | Receive a MQTT message.
Call this method when a message is received from the MQTT broker. |
def lastNode(class_, hot_map):
''' Return the very last node (recursively) in the hot map. '''
children = hot_map[-1][2]
if children:
return class_.lastNode(children)
else:
return hot_map[-1][1] | Return the very last node (recursively) in the hot map. |
def pixels_from_coordinates(lat, lon, max_y, max_x):
"""
Return the 2 matrix with lat and lon of each pixel.
Keyword arguments:
lat -- A latitude matrix
lon -- A longitude matrix
max_y -- The max vertical pixels amount of an orthorectified image.
max_x -- The max horizontal pixels amount of... | Return the 2 matrix with lat and lon of each pixel.
Keyword arguments:
lat -- A latitude matrix
lon -- A longitude matrix
max_y -- The max vertical pixels amount of an orthorectified image.
max_x -- The max horizontal pixels amount of an orthorectified image. |
async def close(self) -> None:
"""
Explicit exit. If so configured, populate cache to prove for any creds on schemata,
cred defs, and rev regs marked of interest in configuration at initialization,
archive cache, and purge prior cache archives.
:return: current object
""... | Explicit exit. If so configured, populate cache to prove for any creds on schemata,
cred defs, and rev regs marked of interest in configuration at initialization,
archive cache, and purge prior cache archives.
:return: current object |
def cli(env, date_min, date_max, obj_event, obj_id, obj_type, utc_offset, metadata, limit):
"""Get Event Logs
Example:
slcli event-log get -d 01/01/2019 -D 02/01/2019 -t User -l 10
"""
columns = ['Event', 'Object', 'Type', 'Date', 'Username']
event_mgr = SoftLayer.EventLogManager(env.clien... | Get Event Logs
Example:
slcli event-log get -d 01/01/2019 -D 02/01/2019 -t User -l 10 |
def member_at_in(self, leaderboard_name, position, **options):
'''
Retrieve a member at the specified index from the leaderboard.
@param leaderboard_name [String] Name of the leaderboard.
@param position [int] Position in named leaderboard.
@param options [Hash] Options to be us... | Retrieve a member at the specified index from the leaderboard.
@param leaderboard_name [String] Name of the leaderboard.
@param position [int] Position in named leaderboard.
@param options [Hash] Options to be used when retrieving the member from the named leaderboard.
@return a page of... |
def _validate_auth(self, path, obj, _):
""" validate that apiKey and oauth2 requirements """
errs = []
if obj.type == 'apiKey':
if not obj.passAs:
errs.append('need "passAs" for apiKey')
if not obj.keyname:
errs.append('need "keyname" for ... | validate that apiKey and oauth2 requirements |
def unset_values(self):
"""
Resets the user values of all symbols, as if Kconfig.load_config() or
Symbol.set_value() had never been called.
"""
self._warn_for_no_prompt = False
try:
# set_value() already rejects undefined symbols, and they don't
# ... | Resets the user values of all symbols, as if Kconfig.load_config() or
Symbol.set_value() had never been called. |
def get_location_from_sina(ip):
"""
{
"ret":1,
"start":"58.18.0.0",
"end":"58.18.15.255",
"country":"中国",
"province":"内蒙古",
"city":"兴安",
"district":"",
"isp":"联通",
"type":"",
"desc":""
... | {
"ret":1,
"start":"58.18.0.0",
"end":"58.18.15.255",
"country":"中国",
"province":"内蒙古",
"city":"兴安",
"district":"",
"isp":"联通",
"type":"",
"desc":""
} |
def append(self, lines):
"""
Args:
lines (list): List of line strings to append to the end of the editor
"""
if isinstance(lines, list):
self._lines = self._lines + lines
elif isinstance(lines, str):
lines = lines.split('\n')
self._... | Args:
lines (list): List of line strings to append to the end of the editor |
def last_edit_time(self):
"""
:return: 问题最后编辑时间
:rtype: datetime.datetime
"""
data = {'_xsrf': self.xsrf, 'offset': '1'}
res = self._session.post(self.url + 'log', data=data)
_, content = res.json()['msg']
soup = BeautifulSoup(content)
time_string ... | :return: 问题最后编辑时间
:rtype: datetime.datetime |
def _original_path(self, path):
"""Return a normalized case version of the given path for
case-insensitive file systems. For case-sensitive file systems,
return path unchanged.
Args:
path: the file path to be transformed
Returns:
A version of path matchi... | Return a normalized case version of the given path for
case-insensitive file systems. For case-sensitive file systems,
return path unchanged.
Args:
path: the file path to be transformed
Returns:
A version of path matching the case of existing path elements. |
def oldest_peer(peers):
"""Determines who the oldest peer is by comparing unit numbers."""
local_unit_no = int(os.getenv('JUJU_UNIT_NAME').split('/')[1])
for peer in peers:
remote_unit_no = int(peer.split('/')[1])
if remote_unit_no < local_unit_no:
return False
return True | Determines who the oldest peer is by comparing unit numbers. |
def _config_bootstrap(self):
"""Go through and establish the defaults on the file system.
The approach here was stolen from the CLI tool provided with the
module. Idea being that the user should not always need to provide a
username and password in order to run the script. If the config... | Go through and establish the defaults on the file system.
The approach here was stolen from the CLI tool provided with the
module. Idea being that the user should not always need to provide a
username and password in order to run the script. If the configuration
file is already present ... |
def sound_touch_stop(self, call_params):
"""REST Remove soundtouch audio effects on a Call
"""
path = '/' + self.api_version + '/SoundTouchStop/'
method = 'POST'
return self.request(path, method, call_params) | REST Remove soundtouch audio effects on a Call |
def authenticate_keystone(self, keystone_ip, username, password,
api_version=False, admin_port=False,
user_domain_name=None, domain_name=None,
project_domain_name=None, project_name=None):
"""Authenticate with Keystone"""
... | Authenticate with Keystone |
def client_auth(self):
"""Generate an XML element with client auth data populated."""
if not self._client_auth:
self._client_auth = E.Element('merchantAuthentication')
E.SubElement(self._client_auth, 'name').text = self.config.login_id
E.SubElement(self._client_auth, ... | Generate an XML element with client auth data populated. |
def smart_truncate(value, max_length=0, word_boundaries=False, separator=' '):
""" Truncate a string """
value = value.strip(separator)
if not max_length:
return value
if len(value) < max_length:
return value
if not word_boundaries:
return value[:max_length].strip(separat... | Truncate a string |
def _set_ldp_protocol_stats_instance_total(self, v, load=False):
"""
Setter method for ldp_protocol_stats_instance_total, mapped from YANG variable /mpls_state/ldp/statistics/ldp_protocol_stats_instance_total (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ld... | Setter method for ldp_protocol_stats_instance_total, mapped from YANG variable /mpls_state/ldp/statistics/ldp_protocol_stats_instance_total (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ldp_protocol_stats_instance_total is considered as a private
method. Backen... |
def nullval(cls):
"""Create a new instance where all of the values are 0"""
d = dict(cls.__dict__.items())
for k in d:
d[k] = 0
d['sl'] = cls.sl
d[cls.level] = 0
return cls(**d) | Create a new instance where all of the values are 0 |
def rt_location_log(logfile):
"""
Extract location information from a RefTek raw log-file.
Function to read a specific RefTek RT130 log-file and find all location
information.
:type logfile: str
:param logfile: The logfile to look in
:returns: list of tuples of lat, lon, elevation in deci... | Extract location information from a RefTek raw log-file.
Function to read a specific RefTek RT130 log-file and find all location
information.
:type logfile: str
:param logfile: The logfile to look in
:returns: list of tuples of lat, lon, elevation in decimal degrees and km.
:rtype: list |
def img(self):
'''return a wx image'''
import wx
with warnings.catch_warnings():
warnings.simplefilter('ignore')
img = wx.EmptyImage(self.width, self.height)
img.SetData(self.imgstr)
return img | return a wx image |
def get_country_by_id(self, country_id) -> 'Country':
"""
Gets a country in this coalition by its ID
Args:
country_id: country Id
Returns: Country
"""
VALID_POSITIVE_INT.validate(country_id, 'get_country_by_id', exc=ValueError)
if country_id not in s... | Gets a country in this coalition by its ID
Args:
country_id: country Id
Returns: Country |
def add_health_monitor(self, loadbalancer, type, delay=10, timeout=10,
attemptsBeforeDeactivation=3, path="/", statusRegex=None,
bodyRegex=None, hostHeader=None):
"""
Adds a health monitor to the load balancer. If a monitor already
exists, it is updated with the supplied ... | Adds a health monitor to the load balancer. If a monitor already
exists, it is updated with the supplied settings. |
def get_datatype(self, table: str, column: str) -> str:
"""Returns database SQL datatype for a column: e.g. VARCHAR."""
return self.flavour.get_datatype(self, table, column).upper() | Returns database SQL datatype for a column: e.g. VARCHAR. |
def infer(self, number_of_processes=1, *args, **kwargs):
"""
:param number_of_processes: If set to more than 1, the inference routines will be paralellised
using ``multiprocessing`` module
:param args: arguments to pass to :meth:`Inference.infer`
:para... | :param number_of_processes: If set to more than 1, the inference routines will be paralellised
using ``multiprocessing`` module
:param args: arguments to pass to :meth:`Inference.infer`
:param kwargs: keyword arguments to pass to :meth:`Inference.infer`
:retur... |
def ip_rtm_config_route_static_route_oif_vrf_static_route_oif_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def")
rtm_config = ET.SubElement(ip, "rtm-config", xmlns="urn:b... | Auto Generated Code |
def _property_set(self, msg):
"""Set command received and acknowledged."""
prop = self._sent_property.get('prop')
if prop and hasattr(self, prop):
setattr(self, prop, self._sent_property.get('val'))
self._sent_property = {} | Set command received and acknowledged. |
def svm_predict(y, x, m, options=""):
"""
svm_predict(y, x, m [, options]) -> (p_labels, p_acc, p_vals)
y: a list/tuple/ndarray of l true labels (type must be int/double).
It is used for calculating the accuracy. Use [] if true labels are
unavailable.
x: 1. a list/tuple of l training instances. Feature ve... | svm_predict(y, x, m [, options]) -> (p_labels, p_acc, p_vals)
y: a list/tuple/ndarray of l true labels (type must be int/double).
It is used for calculating the accuracy. Use [] if true labels are
unavailable.
x: 1. a list/tuple of l training instances. Feature vector of
each training instance is a l... |
def unload_plugin(name, category=None):
""" remove single plugin
Parameters
----------
name : str
plugin name
category : str
plugin category
Examples
--------
>>> from pprint import pprint
>>> pprint(view_plugins())
{'decoders': {}, 'encoders': {}, 'parsers': {... | remove single plugin
Parameters
----------
name : str
plugin name
category : str
plugin category
Examples
--------
>>> from pprint import pprint
>>> pprint(view_plugins())
{'decoders': {}, 'encoders': {}, 'parsers': {}}
>>> class DecoderPlugin(object):
...... |
def create_tcp_socket (self, host):
"""Create tcp socket, connect to it and return socket object."""
port = int(self['TCPSocket'])
sockinfo = get_sockinfo(host, port=port)
sock = create_socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect(sockinfo[0][4])
... | Create tcp socket, connect to it and return socket object. |
def plot_rolling_volatility(returns, factor_returns=None,
rolling_window=APPROX_BDAYS_PER_MONTH * 6,
legend_loc='best', ax=None, **kwargs):
"""
Plots the rolling volatility versus date.
Parameters
----------
returns : pd.Series
Daily r... | Plots the rolling volatility versus date.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
factor_returns : pd.Series, optional
Daily noncumulative returns of the benchmark factor to ... |
def create_providerinfo(self, capabilities):
"""
Dynamically create the provider info response
:param capabilities:
:return:
"""
_pinfo = self.package_capabilities()
not_supported = {}
for key, val in capabilities.items():
try:
... | Dynamically create the provider info response
:param capabilities:
:return: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.