code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def colorbar(self, mappable=None, **kwargs):
"""Add a `~matplotlib.colorbar.Colorbar` to these `Axes`
Parameters
----------
mappable : matplotlib data collection, optional
collection against which to map the colouring, default will
be the last added mappable arti... | Add a `~matplotlib.colorbar.Colorbar` to these `Axes`
Parameters
----------
mappable : matplotlib data collection, optional
collection against which to map the colouring, default will
be the last added mappable artist (collection or image)
fraction : `float`, op... |
def clear_citation(self):
"""Clear the citation and if citation clearing is enabled, clear the evidence and annotations."""
self.citation.clear()
if self.citation_clearing:
self.evidence = None
self.annotations.clear() | Clear the citation and if citation clearing is enabled, clear the evidence and annotations. |
def handleStatus(self, version, code, message):
"extends handleStatus to instantiate a local response object"
proxy.ProxyClient.handleStatus(self, version, code, message)
# client.Response is currently just a container for needed data
self._response = client.Response(version, code, messa... | extends handleStatus to instantiate a local response object |
def start(self):
"""
Start daemonization process.
"""
# If pidfile already exists, we should read pid from there; to overwrite it, if locking
# will fail, because locking attempt somehow purges the file contents.
if os.path.isfile(self.pid):
with open(self.pid... | Start daemonization process. |
def build(self, format='qcow2', path='/tmp'):
'''
Build an image using Kiwi.
:param format:
:param path:
:return:
'''
if kiwi is None:
msg = 'Unable to build the image due to the missing dependencies: Kiwi module is not available.'
log.err... | Build an image using Kiwi.
:param format:
:param path:
:return: |
def get_log_events(awsclient, log_group_name, log_stream_name, start_ts=None):
"""Get log events for the specified log group and stream.
this is used in tenkai output instance diagnostics
:param log_group_name: log group name
:param log_stream_name: log stream name
:param start_ts: timestamp
:r... | Get log events for the specified log group and stream.
this is used in tenkai output instance diagnostics
:param log_group_name: log group name
:param log_stream_name: log stream name
:param start_ts: timestamp
:return: |
def run_command(self, config_file):
"""
:param str config_file: The name of config file.
"""
config = configparser.ConfigParser()
config.read(config_file)
rdbms = config.get('database', 'rdbms').lower()
wrapper = self.create_routine_wrapper_generator(rdbms)
... | :param str config_file: The name of config file. |
def AgregarFlete(self, descripcion, importe):
"Agrega la información referente al flete de la liquidación (opcional)"
flete = dict(descripcion=descripcion, importe=importe)
self.solicitud['flete'] = flete
return True | Agrega la información referente al flete de la liquidación (opcional) |
def withNamedValues(cls, **values):
"""Create a subclass with discreet named values constraint.
Reduce fully duplicate enumerations along the way.
"""
enums = set(cls.namedValues.items())
enums.update(values.items())
class X(cls):
namedValues = namedval.Name... | Create a subclass with discreet named values constraint.
Reduce fully duplicate enumerations along the way. |
def version(self, content_type="*/*"):
"""
versioning is based off of this post
http://urthen.github.io/2013/05/09/ways-to-version-your-api/
"""
v = ""
accept_header = self.get_header('accept', "")
if accept_header:
a = AcceptHeader(accept_header)
... | versioning is based off of this post
http://urthen.github.io/2013/05/09/ways-to-version-your-api/ |
def scan(audio_filepaths, *, album_gain=False, skip_tagged=False, thread_count=None, ffmpeg_path=None, executor=None):
""" Analyze files, and return a dictionary of filepath to loudness metadata or filepath to future if executor is not None. """
r128_data = {}
with contextlib.ExitStack() as cm:
if executor i... | Analyze files, and return a dictionary of filepath to loudness metadata or filepath to future if executor is not None. |
def normalise_key(self, key):
"""Make sure key is a valid python attribute"""
key = key.replace('-', '_')
if key.startswith("noy_"):
key = key[4:]
return key | Make sure key is a valid python attribute |
def look_up(self, **keys: Dict[InstanceName, ScalarValue]) -> "ArrayEntry":
"""Return the entry with matching keys.
Args:
keys: Keys and values specified as keyword arguments.
Raises:
InstanceValueError: If the receiver's value is not a YANG list.
Nonexisten... | Return the entry with matching keys.
Args:
keys: Keys and values specified as keyword arguments.
Raises:
InstanceValueError: If the receiver's value is not a YANG list.
NonexistentInstance: If no entry with matching keys exists. |
def get_service_references(self, clazz, ldap_filter=None):
# type: (Optional[str], Optional[str]) -> Optional[List[ServiceReference]]
"""
Returns the service references for services that were registered under
the specified class by this bundle and matching the given filter
:para... | Returns the service references for services that were registered under
the specified class by this bundle and matching the given filter
:param clazz: The class name with which the service was registered.
:param ldap_filter: A filter on service properties
:return: The list of references ... |
def add_back_ref(self, back_ref, attr=None):
"""Add reference from back_ref to self
:param back_ref: back_ref to add
:type back_ref: Resource
:rtype: Resource
"""
back_ref.add_ref(self, attr)
return self.fetch() | Add reference from back_ref to self
:param back_ref: back_ref to add
:type back_ref: Resource
:rtype: Resource |
def write(data, path, saltenv='base', index=0):
'''
Write the named file, by default the first file found is written, but the
index of the file can be specified to write to a lower priority file root
'''
if saltenv not in __opts__['pillar_roots']:
return 'Named environment {0} is not present... | Write the named file, by default the first file found is written, but the
index of the file can be specified to write to a lower priority file root |
def _prepare_graph(g, g_colors, q_cls, q_arg, adjust_graph):
"""Prepares a graph for use in :class:`.QueueNetwork`.
This function is called by ``__init__`` in the
:class:`.QueueNetwork` class. It creates the :class:`.QueueServer`
instances that sit on the edges, and sets various edge and node
prope... | Prepares a graph for use in :class:`.QueueNetwork`.
This function is called by ``__init__`` in the
:class:`.QueueNetwork` class. It creates the :class:`.QueueServer`
instances that sit on the edges, and sets various edge and node
properties that are used when drawing the graph.
Parameters
----... |
def hkl_transformation(transf, miller_index):
"""
Returns the Miller index from setting
A to B using a transformation matrix
Args:
transf (3x3 array): The transformation matrix
that transforms a lattice of A to B
miller_index ([h, k, l]): Miller index to transform to setting ... | Returns the Miller index from setting
A to B using a transformation matrix
Args:
transf (3x3 array): The transformation matrix
that transforms a lattice of A to B
miller_index ([h, k, l]): Miller index to transform to setting B |
def unlink(self):
"""Remove the daemon's pid file
:return: None
"""
logger.debug("Unlinking %s", self.pid_filename)
try:
os.unlink(self.pid_filename)
except OSError as exp:
logger.debug("Got an error unlinking our pid file: %s", exp) | Remove the daemon's pid file
:return: None |
def _handle_response(response, server_config, synchronous=False, timeout=None):
"""Handle a server's response in a typical fashion.
Do the following:
1. Check the server's response for an HTTP status code indicating an error.
2. Poll the server for a foreman task to complete if an HTTP 202 (accepted)
... | Handle a server's response in a typical fashion.
Do the following:
1. Check the server's response for an HTTP status code indicating an error.
2. Poll the server for a foreman task to complete if an HTTP 202 (accepted)
status code is returned and ``synchronous is True``.
3. Immediately return i... |
def avatar_url_from_openid(openid, size=64, default='retro', dns=False):
"""
Our own implementation since fas doesn't support this nicely yet.
"""
if dns:
# This makes an extra DNS SRV query, which can slow down our webapps.
# It is necessary for libravatar federation, though.
i... | Our own implementation since fas doesn't support this nicely yet. |
def write_update(rootfs_filepath: str,
progress_callback: Callable[[float], None],
chunk_size: int = 1024,
file_size: int = None) -> RootPartitions:
"""
Write the new rootfs to the next root partition
- Figure out, from the system, the correct root partiti... | Write the new rootfs to the next root partition
- Figure out, from the system, the correct root partition to write to
- Write the rootfs at ``rootfs_filepath`` there, with progress
:param rootfs_filepath: The path to a checked rootfs.ext4
:param progress_callback: A callback to call periodically with ... |
def _build_response(self, resp):
"""Build internal Response object from given response."""
# rememberLogin
# if self.method is 'LOGIN' and resp.json().get('code') == 200:
# cookiesJar.save_cookies(resp, NCloudBot.username)
self.response.content = resp.content
self.res... | Build internal Response object from given response. |
def read(self):
"""
Load the metrics file from the given path
"""
f = open(self.path, "r")
self.manifest_json = f.read() | Load the metrics file from the given path |
def pOparapar(self,Opar,apar,tdisrupt=None):
"""
NAME:
pOparapar
PURPOSE:
return the probability of a given parallel (frequency,angle) offset pair
INPUT:
Opar - parallel frequency offset (array) (can be Quantity)
apar - parallel angle off... | NAME:
pOparapar
PURPOSE:
return the probability of a given parallel (frequency,angle) offset pair
INPUT:
Opar - parallel frequency offset (array) (can be Quantity)
apar - parallel angle offset along the stream (scalar) (can be Quantity)
OUTPUT:
... |
def assistant_from_yaml(cls, source, y, superassistant, fully_loaded=True,
role=settings.DEFAULT_ASSISTANT_ROLE):
"""Constructs instance of YamlAssistant loaded from given structure y, loaded
from source file source.
Args:
source: path to assistant source... | Constructs instance of YamlAssistant loaded from given structure y, loaded
from source file source.
Args:
source: path to assistant source file
y: loaded yaml structure
superassistant: superassistant of this assistant
Returns:
YamlAssistant instan... |
def get_viscosity(medium="CellCarrier", channel_width=20.0, flow_rate=0.16,
temperature=23.0):
"""Returns the viscosity for RT-DC-specific media
Parameters
----------
medium: str
The medium to compute the viscosity for.
One of ["CellCarrier", "CellCarrier B", "water"].... | Returns the viscosity for RT-DC-specific media
Parameters
----------
medium: str
The medium to compute the viscosity for.
One of ["CellCarrier", "CellCarrier B", "water"].
channel_width: float
The channel width in µm
flow_rate: float
Flow rate in µl/s
temperature... |
def get_assessment(self, assessment_id):
"""Gets the ``Assessment`` specified by its ``Id``.
In plenary mode, the exact ``Id`` is found or a ``NotFound``
results. Otherwise, the returned ``Assessment`` may have a
different ``Id`` than requested, such as the case where a
duplicat... | Gets the ``Assessment`` specified by its ``Id``.
In plenary mode, the exact ``Id`` is found or a ``NotFound``
results. Otherwise, the returned ``Assessment`` may have a
different ``Id`` than requested, such as the case where a
duplicate ``Id`` was assigned to a ``Assessment`` and retain... |
def export(rv, code=None, headers=None):
"""
Create a suitable response
Args:
rv: return value of action
code: status code
headers: response headers
Returns:
flask.Response
"""
if isinstance(rv, ResponseBase):
return make_response(rv, code, headers)
e... | Create a suitable response
Args:
rv: return value of action
code: status code
headers: response headers
Returns:
flask.Response |
def allow(self, privilege):
"""Add an allowed privilege (read, write, execute, all)."""
assert privilege in PERMISSIONS['user'].keys()
reading = PERMISSIONS['user'][privilege] + PERMISSIONS['group'][privilege] + PERMISSIONS['other'][privilege]
os.chmod(self.file_path, reading) | Add an allowed privilege (read, write, execute, all). |
def authorize(self, names, payload=None, request_type="push"):
'''Authorize a client based on encrypting the payload with the client
token, which should be matched on the receiving server'''
if self.secrets is not None:
if "registry" in self.secrets:
# Use the payload to generate a... | Authorize a client based on encrypting the payload with the client
token, which should be matched on the receiving server |
def fill_treewidget(self, tree, parameters):
"""
fills a QTreeWidget with nested parameters, in future replace QTreeWidget with QTreeView and call fill_treeview
Args:
tree: QtWidgets.QTreeWidget
parameters: dictionary or Parameter object
show_all: boolean if t... | fills a QTreeWidget with nested parameters, in future replace QTreeWidget with QTreeView and call fill_treeview
Args:
tree: QtWidgets.QTreeWidget
parameters: dictionary or Parameter object
show_all: boolean if true show all parameters, if false only selected ones
Retu... |
def walk_oid(self, oid):
"""Get a list of SNMP varbinds in response to a walk for oid.
Each varbind in response list has a tag, iid, val and type attribute."""
var = netsnmp.Varbind(oid)
varlist = netsnmp.VarList(var)
data = self.walk(varlist)
if len(data) == 0:
... | Get a list of SNMP varbinds in response to a walk for oid.
Each varbind in response list has a tag, iid, val and type attribute. |
def handle_pubrel(self):
"""Handle incoming PUBREL packet."""
self.logger.info("PUBREL received")
ret, mid = self.in_packet.read_uint16()
if ret != NC.ERR_SUCCESS:
return ret
evt = event.EventPubrel(mid)
self.push_event(evt)
return NC.ERR_SUCCESS | Handle incoming PUBREL packet. |
def hmset(self, key, value_dict):
"""
Sets fields to values as in `value_dict` in the hash stored at `key`.
Sets the specified fields to their respective values in the hash
stored at `key`. This command overwrites any specified fields
already existing in the hash. If `key` doe... | Sets fields to values as in `value_dict` in the hash stored at `key`.
Sets the specified fields to their respective values in the hash
stored at `key`. This command overwrites any specified fields
already existing in the hash. If `key` does not exist, a new key
holding a hash is crea... |
def password_enter(self, wallet, password):
"""
Enters the **password** in to **wallet**
:param wallet: Wallet to enter password for
:type wallet: str
:param password: Password to enter
:type password: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> r... | Enters the **password** in to **wallet**
:param wallet: Wallet to enter password for
:type wallet: str
:param password: Password to enter
:type password: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.password_enter(
... wallet="000D1BAEC8EC208142C99... |
def onFolderTreeClicked(self, proxyIndex):
"""What to do when a Folder in the tree is clicked"""
if not proxyIndex.isValid():
return
index = self.proxyFileModel.mapToSource(proxyIndex)
settings = QSettings()
folder_path = self.fileModel.filePath(index)
settin... | What to do when a Folder in the tree is clicked |
def _push_next(self):
"""Assign next batch workload to workers."""
r = next(self._iter, None)
if r is None:
return
async_ret = self._worker_pool.apply_async(
self._worker_fn, (r, self._batchify_fn, self._dataset))
self._data_buffer[self._sent_idx] = async_... | Assign next batch workload to workers. |
def get_frames(self, frames='all', override=False, **kwargs):
"""
Extract frames from the trajectory file.
Depending on the passed parameters a frame, a list of particular
frames, a range of frames (from, to), or all frames can be extracted
with this function.
Parameter... | Extract frames from the trajectory file.
Depending on the passed parameters a frame, a list of particular
frames, a range of frames (from, to), or all frames can be extracted
with this function.
Parameters
----------
frames : :class:`int` or :class:`list` or :class:`tou... |
def merged(self):
'''The clean stats from all the hosts reporting to this host.'''
stats = {}
for topic in self.client.topics()['topics']:
for producer in self.client.lookup(topic)['producers']:
hostname = producer['broadcast_address']
port = producer[... | The clean stats from all the hosts reporting to this host. |
def delete(self, request, *args, **kwargs):
"""
Calls the delete() method on the fetched object and then
redirects to the success URL.
"""
self.object = self.get_object()
success_url = self.get_success_url()
self.object.delete()
if self.request.is_ajax():... | Calls the delete() method on the fetched object and then
redirects to the success URL. |
def get_nodes_with_recipe(recipe_name, environment=None):
"""Get all nodes which include a given recipe,
prefix-searches are also supported
"""
prefix_search = recipe_name.endswith("*")
if prefix_search:
recipe_name = recipe_name.rstrip("*")
for n in get_nodes(environment):
reci... | Get all nodes which include a given recipe,
prefix-searches are also supported |
def getfo(self, remotepath, fl, callback=None):
"""
Copy a remote file (``remotepath``) from the SFTP server and write to
an open file or file-like object, ``fl``. Any exception raised by
operations will be passed through. This method is primarily provided
as a convenience.
... | Copy a remote file (``remotepath``) from the SFTP server and write to
an open file or file-like object, ``fl``. Any exception raised by
operations will be passed through. This method is primarily provided
as a convenience.
:param object remotepath: opened file or file-like object to c... |
def setHint( self, hint ):
"""
Sets the hint for this line edit that will be displayed when in \
editable mode.
:param hint | <str>
"""
self._hint = hint
lineEdit = self.lineEdit()
if isinstance(lineEdit, XLineEdit):
li... | Sets the hint for this line edit that will be displayed when in \
editable mode.
:param hint | <str> |
def trace_symlink_target(link):
"""
Given a file that is known to be a symlink, trace it to its ultimate
target.
Raises TargetNotPresent when the target cannot be determined.
Raises ValueError when the specified link is not a symlink.
"""
if not is_symlink(link):
raise ValueError("link must point to a symlin... | Given a file that is known to be a symlink, trace it to its ultimate
target.
Raises TargetNotPresent when the target cannot be determined.
Raises ValueError when the specified link is not a symlink. |
def find_token(request, token_type, service, **kwargs):
"""
The access token can be in a number of places.
There are priority rules as to which one to use, abide by those:
1 If it's among the request parameters use that
2 If among the extra keyword arguments
3 Acquired by a previous run service... | The access token can be in a number of places.
There are priority rules as to which one to use, abide by those:
1 If it's among the request parameters use that
2 If among the extra keyword arguments
3 Acquired by a previous run service.
:param request:
:param token_type:
:param service:
... |
def set_channel_locations(self, channel_ids, locations):
'''This function sets the location properties of each specified channel
id with the corresponding locations of the passed in locations list.
Parameters
----------
channel_ids: array_like
The channel ids (ints) ... | This function sets the location properties of each specified channel
id with the corresponding locations of the passed in locations list.
Parameters
----------
channel_ids: array_like
The channel ids (ints) for which the locations will be specified
locations: array_l... |
def last(self):
"""
The last of a GridSpace is another GridSpace
constituted of the last of the individual elements. To access
the elements by their X,Y position, either index the position
directly or use the items() method.
"""
if self.type == HoloMap:
... | The last of a GridSpace is another GridSpace
constituted of the last of the individual elements. To access
the elements by their X,Y position, either index the position
directly or use the items() method. |
def __set_ethernet_uris(self, ethernet_names, operation="add"):
"""Updates network uris."""
if not isinstance(ethernet_names, list):
ethernet_names = [ethernet_names]
associated_enets = self.data.get('networkUris', [])
ethernet_uris = []
for i, enet in enumerate(eth... | Updates network uris. |
def _append(self, menu):
'''append this menu item to a menu'''
menu.AppendCheckItem(self.id(), self.name, self.description)
menu.Check(self.id(), self.checked) | append this menu item to a menu |
def save_artists(self, artists, filename="artist_lyrics", overwrite=False):
"""Save lyrics from multiple Artist objects as JSON object
:param artists: List of Artist objects to save lyrics from
:param filename: Name of output file (json)
:param overwrite: Overwrites preexisting file if T... | Save lyrics from multiple Artist objects as JSON object
:param artists: List of Artist objects to save lyrics from
:param filename: Name of output file (json)
:param overwrite: Overwrites preexisting file if True |
def get_allproductandrelease(self):
"""
Get All ProductAndReleases
:return: A duple: All product and Releses from SDC Catalog as a dict, the 'Request' response
"""
logger.info("Get all ProductAndReleases")
response = self.get(PRODUCTANDRELEASE_RESOURCE_ROOT_URI, headers=s... | Get All ProductAndReleases
:return: A duple: All product and Releses from SDC Catalog as a dict, the 'Request' response |
def vectorize_range(values):
"""
This function is for url encoding.
Takes a value or a tuple or list of tuples and returns a single result,
tuples are joined by "," if necessary, elements in tuple are joined by '_'
"""
if isinstance(values, tuple):
return '_'.join(str(i) for i in values)... | This function is for url encoding.
Takes a value or a tuple or list of tuples and returns a single result,
tuples are joined by "," if necessary, elements in tuple are joined by '_' |
def dictify(r,root=True):
"""http://stackoverflow.com/a/30923963/2946714"""
if root:
return {r.tag : dictify(r, False)}
d=copy(r.attrib)
if r.text:
d["_text"]=r.text
for x in r.findall("./*"):
if x.tag not in d:
d[x.tag]=[]
d[x.tag].append(dictify(x,False)... | http://stackoverflow.com/a/30923963/2946714 |
def allconcat(self, x, mesh_axis, concat_axis):
"""Grouped allconcat (like MPI allgather followed by concat).
Args:
x: a LaidOutTensor
mesh_axis: an integer - the mesh axis along which to group
concat_axis: an integer (the Tensor axis along which to concatenate)
Returns:
a LaidOutTe... | Grouped allconcat (like MPI allgather followed by concat).
Args:
x: a LaidOutTensor
mesh_axis: an integer - the mesh axis along which to group
concat_axis: an integer (the Tensor axis along which to concatenate)
Returns:
a LaidOutTensor |
def bods2c(name):
"""
Translate a string containing a body name or ID code to an integer code.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bods2c_c.html
:param name: String to be translated to an ID code.
:type name: str
:return: Integer ID code corresponding to name.
:rtype: i... | Translate a string containing a body name or ID code to an integer code.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bods2c_c.html
:param name: String to be translated to an ID code.
:type name: str
:return: Integer ID code corresponding to name.
:rtype: int |
def init_poolmanager(self, connections, maxsize, block=False, **pool_kwargs):
"""Called to initialize the HTTPAdapter when no proxy is used."""
try:
pool_kwargs['ssl_version'] = ssl.PROTOCOL_TLS
except AttributeError:
pool_kwargs['ssl_version'] = ssl.PROTOCOL_SSLv23
... | Called to initialize the HTTPAdapter when no proxy is used. |
def sg_arg():
r"""Gets current command line options
Returns:
tf.sg_opt instance that is updated with current commandd line options.
"""
if not tf.app.flags.FLAGS.__dict__['__parsed']:
tf.app.flags.FLAGS._parse_flags()
return tf.sg_opt(tf.app.flags.FLAGS.__dict__['__flags']) | r"""Gets current command line options
Returns:
tf.sg_opt instance that is updated with current commandd line options. |
def set_params(self, **params):
"""
Set the parameters of this estimator.
Returns
-------
self
"""
valid_params = self.get_params()
for key, value in params.items():
if key not in valid_params:
raise ValueError(
... | Set the parameters of this estimator.
Returns
-------
self |
def get_term_agents(self):
"""Return dict of INDRA Agents keyed by corresponding TERMs in the EKB.
This is meant to be used when entities e.g. "phosphorylated ERK",
rather than events need to be extracted from processed natural
language. These entities with their respective states are r... | Return dict of INDRA Agents keyed by corresponding TERMs in the EKB.
This is meant to be used when entities e.g. "phosphorylated ERK",
rather than events need to be extracted from processed natural
language. These entities with their respective states are represented
as INDRA Agents. Fu... |
def to_bytes(self):
'''
Takes a list of IPOption objects and returns a packed byte string
of options, appropriately padded if necessary.
'''
raw = b''
if not self._options:
return raw
for ipopt in self._options:
raw += ipopt.to_bytes()
... | Takes a list of IPOption objects and returns a packed byte string
of options, appropriately padded if necessary. |
def wait_for_jobs(jobs):
"""Waits for all the jobs to be runnning.
Args:
jobs(list): list of the python-grid5000 jobs to wait for
Raises:
Exception: if one of the job gets in error state.
"""
all_running = False
while not all_running:
all_running = True
time.s... | Waits for all the jobs to be runnning.
Args:
jobs(list): list of the python-grid5000 jobs to wait for
Raises:
Exception: if one of the job gets in error state. |
def authenticated(
method: Callable[..., Optional[Awaitable[None]]]
) -> Callable[..., Optional[Awaitable[None]]]:
"""Decorate methods with this to require that the user be logged in.
If the user is not logged in, they will be redirected to the configured
`login url <RequestHandler.get_login_url>`.
... | Decorate methods with this to require that the user be logged in.
If the user is not logged in, they will be redirected to the configured
`login url <RequestHandler.get_login_url>`.
If you configure a login url with a query parameter, Tornado will
assume you know what you're doing and use it as-is. I... |
def load(filenames, prepare_data_iterator=True, batch_size=None, exclude_parameter=False, parameter_only=False):
'''load
Load network information from files.
Args:
filenames (list): List of filenames.
Returns:
dict: Network information.
'''
class Info:
pass
info = In... | load
Load network information from files.
Args:
filenames (list): List of filenames.
Returns:
dict: Network information. |
def recursive_operation_ls(
self, endpoint_id, depth=3, filter_after_first=True, **params
):
"""
Makes recursive calls to ``GET /operation/endpoint/<endpoint_id>/ls``
Does not preserve access to top level operation_ls fields, but
adds a "path" field for every item that repres... | Makes recursive calls to ``GET /operation/endpoint/<endpoint_id>/ls``
Does not preserve access to top level operation_ls fields, but
adds a "path" field for every item that represents the full
path to that item.
:rtype: iterable of :class:`GlobusResponse
<globus_sdk.respo... |
def sam2fastq(line):
"""
print fastq from sam
"""
fastq = []
fastq.append('@%s' % line[0])
fastq.append(line[9])
fastq.append('+%s' % line[0])
fastq.append(line[10])
return fastq | print fastq from sam |
def get_public_key(self):
"""Get the PublicKey for this PrivateKey."""
return PublicKey.from_verifying_key(
self._private_key.get_verifying_key(),
network=self.network, compressed=self.compressed) | Get the PublicKey for this PrivateKey. |
def assess_angmom(X):
"""
Checks for change of sign in each component of the angular momentum.
Returns an array with ith entry 1 if no sign change in i component
and 0 if sign change.
Box = (0,0,0)
S.A loop = (0,0,1)
L.A loop = (1,0,0)
"""
L=angmom(X[0])
l... | Checks for change of sign in each component of the angular momentum.
Returns an array with ith entry 1 if no sign change in i component
and 0 if sign change.
Box = (0,0,0)
S.A loop = (0,0,1)
L.A loop = (1,0,0) |
def create_handler(target: str):
"""Create a handler for logging to ``target``"""
if target == 'stderr':
return logging.StreamHandler(sys.stderr)
elif target == 'stdout':
return logging.StreamHandler(sys.stdout)
else:
return logging.handlers.WatchedFileHandler(filename=target) | Create a handler for logging to ``target`` |
def decision_function(self, pairs):
"""Returns the decision function used to classify the pairs.
Returns the opposite of the learned metric value between samples in every
pair, to be consistent with scikit-learn conventions. Hence it should
ideally be low for dissimilar samples and high for similar sam... | Returns the decision function used to classify the pairs.
Returns the opposite of the learned metric value between samples in every
pair, to be consistent with scikit-learn conventions. Hence it should
ideally be low for dissimilar samples and high for similar samples.
This is the decision function tha... |
def render(template: typing.Union[str, Template], **kwargs):
"""
Renders a template string using Jinja2 and the Cauldron templating
environment.
:param template:
The string containing the template to be rendered
:param kwargs:
Any named arguments to pass to Jinja2 for use in renderi... | Renders a template string using Jinja2 and the Cauldron templating
environment.
:param template:
The string containing the template to be rendered
:param kwargs:
Any named arguments to pass to Jinja2 for use in rendering
:return:
The rendered template string |
def solve_with_sdpa(sdp, solverparameters=None):
"""Helper function to write out the SDP problem to a temporary
file, call the solver, and parse the output.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param solverparameters: Optional parameters to SDPA.
:ty... | Helper function to write out the SDP problem to a temporary
file, call the solver, and parse the output.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param solverparameters: Optional parameters to SDPA.
:type solverparameters: dict of str.
:returns: tuple of... |
def set_ntp_server(server):
"""Sets the NTP server on Linux
:param server: (str) NTP server IP or hostname
:return: None
:raises CommandError
"""
log = logging.getLogger(mod_logger + '.set_ntp_server')
# Ensure the hostname is a str
if not isinstance(server, basestring):
msg = ... | Sets the NTP server on Linux
:param server: (str) NTP server IP or hostname
:return: None
:raises CommandError |
def kill_line(event):
"""
Kill the text from the cursor to the end of the line.
If we are at the end of the line, this should remove the newline.
(That way, it is possible to delete multiple lines by executing this
command multiple times.)
"""
buff = event.current_buffer
if event.arg < ... | Kill the text from the cursor to the end of the line.
If we are at the end of the line, this should remove the newline.
(That way, it is possible to delete multiple lines by executing this
command multiple times.) |
def input_dir(self, dirname):
"""Check all files in this directory and all subdirectories."""
dirname = dirname.rstrip('/')
if self.excluded(dirname):
return 0
counters = self.options.report.counters
verbose = self.options.verbose
filepatterns = self.options.f... | Check all files in this directory and all subdirectories. |
def flushall(self, async_op=False):
"""
Remove all keys from all databases.
:param async_op: lets the entire dataset to be freed asynchronously. \
Defaults to False
"""
if async_op:
fut = self.execute(b'FLUSHALL', b'ASYNC')
else:
fut = sel... | Remove all keys from all databases.
:param async_op: lets the entire dataset to be freed asynchronously. \
Defaults to False |
def get_grade_entries_by_query(self, grade_entry_query):
"""Gets a list of entries matching the given grade entry query.
arg: grade_entry_query (osid.grading.GradeEntryQuery): the
grade entry query
return: (osid.grading.GradeEntryList) - the returned
``GradeEn... | Gets a list of entries matching the given grade entry query.
arg: grade_entry_query (osid.grading.GradeEntryQuery): the
grade entry query
return: (osid.grading.GradeEntryList) - the returned
``GradeEntryList``
raise: NullArgument - ``grade_entry_query`` is ``... |
def to_pb(self):
"""Converts the garbage collection rule to a protobuf.
:rtype: :class:`.table_v2_pb2.GcRule`
:returns: The converted current object.
"""
max_age = _helpers._timedelta_to_duration_pb(self.max_age)
return table_v2_pb2.GcRule(max_age=max_age) | Converts the garbage collection rule to a protobuf.
:rtype: :class:`.table_v2_pb2.GcRule`
:returns: The converted current object. |
def _fetch_targets(self, api_client, q, target):
'''
Make an API call defined in metadata.json.
Parse the returned object as implemented in the "parse_[object name]" method.
:param api_client:
:param q:
:param target:
:return:
'''
# Handle & forma... | Make an API call defined in metadata.json.
Parse the returned object as implemented in the "parse_[object name]" method.
:param api_client:
:param q:
:param target:
:return: |
def open_spec(f):
"""
:param f: file object with spec data
spec file is a yaml document that specifies which modules
can be loaded.
modules - list of base modules that can be loaded
pths - list of .pth files to load
"""
import ruamel.yaml as yaml
keys = ['modules', 'pths', 'tes... | :param f: file object with spec data
spec file is a yaml document that specifies which modules
can be loaded.
modules - list of base modules that can be loaded
pths - list of .pth files to load |
def _get_rows(self, table):
"""Returns rows from table"""
childnodes = table.childNodes
qname_childnodes = [(s.qname[1], s) for s in childnodes]
return [node for name, node in qname_childnodes
if name == u'table-row'] | Returns rows from table |
def prepare_axes(wave, flux, fig=None, ax_lower=(0.1, 0.1),
ax_dim=(0.85, 0.65)):
"""Create fig and axes if needed and layout axes in fig."""
# Axes location in figure.
if not fig:
fig = plt.figure()
ax = fig.add_axes([ax_lower[0], ax_lower[1], ax_dim[0], ax_dim[1]])
ax.plot... | Create fig and axes if needed and layout axes in fig. |
def get_extents(self, element, ranges, range_type='combined'):
"""
A Chord plot is always drawn on a unit circle.
"""
xdim, ydim = element.nodes.kdims[:2]
if range_type not in ('combined', 'data', 'extents'):
return xdim.range[0], ydim.range[0], xdim.range[1], ydim.ra... | A Chord plot is always drawn on a unit circle. |
def compute(self, *inputs, **kwargs):
"""
Compute based on NeuralVariable.
:type inputs: list of NeuralVariable
:return: NeuralVariable
"""
from deepy.core.neural_var import NeuralVariable
from deepy.core.graph import graph
if type(inputs[0]) != NeuralVar... | Compute based on NeuralVariable.
:type inputs: list of NeuralVariable
:return: NeuralVariable |
def watched(self, option):
"""
Set whether to filter by a user's watchlist. Options available are
user.ONLY, user.NOT, and None; default is None.
"""
params = join_params(self.parameters, {"watched": option})
return self.__class__(**params) | Set whether to filter by a user's watchlist. Options available are
user.ONLY, user.NOT, and None; default is None. |
def xpath(self, selector: str, *, first: bool = False, _encoding: str = None) -> _XPath:
"""Given an XPath selector, returns a list of
:class:`Element <Element>` objects or a single one.
:param selector: XPath Selector to use.
:param first: Whether or not to return just the first result... | Given an XPath selector, returns a list of
:class:`Element <Element>` objects or a single one.
:param selector: XPath Selector to use.
:param first: Whether or not to return just the first result.
:param _encoding: The encoding format.
If a sub-selector is specified (e.g. ``//a... |
def run(self):
'''
run - The thread main. Will attempt to stop and join the attached thread.
'''
# Try to silence default exception printing.
self.otherThread._Thread__stderr = self._stderr
if hasattr(self.otherThread, '_Thread__stop'):
# If py2, call thi... | run - The thread main. Will attempt to stop and join the attached thread. |
def securityEventWS(symbols=None, on_data=None):
'''https://iextrading.com/developer/docs/#security-event'''
symbols = _strToList(symbols)
sendinit = ({'symbols': symbols, 'channels': ['securityevent']},)
return _stream(_wsURL('deep'), sendinit, on_data) | https://iextrading.com/developer/docs/#security-event |
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._id_ is not None:
return False
if self._created is not None:
return False
if self._updated is not None:
return False
if self._avatar is not None:
return F... | :rtype: bool |
def make_sub_call(id_, lineno, params):
""" This will return an AST node for a sub/procedure call.
"""
return symbols.CALL.make_node(id_, params, lineno) | This will return an AST node for a sub/procedure call. |
def chain_HSPs(blast, xdist=100, ydist=100):
"""
Take a list of BlastLines (or a BlastSlow instance), and returns a list of
BlastLines.
"""
key = lambda x: (x.query, x.subject)
blast.sort(key=key)
clusters = Grouper()
for qs, points in groupby(blast, key=key):
points = sorted(li... | Take a list of BlastLines (or a BlastSlow instance), and returns a list of
BlastLines. |
def get(self, path, data=None, return_fields=None):
"""Call the Infoblox device to get the obj for the data passed in
:param str obj_reference: The object reference data
:param dict data: The data for the get request
:rtype: requests.Response
"""
return self.session.get... | Call the Infoblox device to get the obj for the data passed in
:param str obj_reference: The object reference data
:param dict data: The data for the get request
:rtype: requests.Response |
def guest_session_new(self, **kwargs):
"""
Generate a guest session id.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('guest_session_new')
response = self._GET(path, kwargs)
self._set_attrs_to_values(res... | Generate a guest session id.
Returns:
A dict respresentation of the JSON returned from the API. |
def _all_params(arr):
"""
Ensures that the argument is a list that either is empty or contains only GPParamSpec's
:param arr: list
:return:
"""
if not isinstance([], list):
raise TypeError("non-list value found for parameters")
return all(isinstance(x,... | Ensures that the argument is a list that either is empty or contains only GPParamSpec's
:param arr: list
:return: |
def set_page_property(self, page_id, data):
"""
Set the page (content) property e.g. add hash parameters
:param page_id: content_id format
:param data: data should be as json data
:return:
"""
url = 'rest/api/content/{page_id}/property'.format(page_id=page_id)
... | Set the page (content) property e.g. add hash parameters
:param page_id: content_id format
:param data: data should be as json data
:return: |
def _find_supported_challenge(authzr, responders):
"""
Find a challenge combination that consists of a single challenge that the
responder can satisfy.
:param ~acme.messages.AuthorizationResource auth: The authorization to
examine.
:type responder: List[`~txacme.interfaces.IResponder`]
... | Find a challenge combination that consists of a single challenge that the
responder can satisfy.
:param ~acme.messages.AuthorizationResource auth: The authorization to
examine.
:type responder: List[`~txacme.interfaces.IResponder`]
:param responder: The possible responders to use.
:raises... |
def Route(resource=None, methods=["get", "post", "put", "delete"],
schema=None):
"""
route
"""
def _route(func):
def wrapper(self, *args, **kwargs):
# "test" argument means no wrap func this time,
# return original func immediately.
if kwargs.get("te... | route |
def build_info_string(info):
"""
Build a new vcf INFO string based on the information in the info_dict.
The info is a dictionary with vcf info keys as keys and lists of vcf values
as values. If there is no value False is value in info
Args:
info (dict): A dictionary with informatio... | Build a new vcf INFO string based on the information in the info_dict.
The info is a dictionary with vcf info keys as keys and lists of vcf values
as values. If there is no value False is value in info
Args:
info (dict): A dictionary with information from the vcf file
Returns:
... |
def list_components(self):
"""List all of the registered component names.
This list will include all of the permanently stored components as
well as any temporary components that were added with a temporary=True
flag in this session.
Returns:
list of str: The list o... | List all of the registered component names.
This list will include all of the permanently stored components as
well as any temporary components that were added with a temporary=True
flag in this session.
Returns:
list of str: The list of component names.
Any of... |
def simxGetJointPosition(clientID, jointHandle, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
position = ct.c_float()
return c_GetJointPosition(clientID, jointHandle, ct.byref(position), operationMode), position.value | Please have a look at the function description/documentation in the V-REP user manual |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.