code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def every_other(iterable):
"""
Yield every other item from the iterable
>>> ' '.join(every_other('abcdefg'))
'a c e g'
"""
items = iter(iterable)
while True:
try:
yield next(items)
next(items)
except StopIteration:
return | Yield every other item from the iterable
>>> ' '.join(every_other('abcdefg'))
'a c e g' |
def _check_dn(self, dn, attr_value):
"""Check dn attribute for issues."""
if dn is not None:
self._error('Two lines starting with dn: in one record.')
if not is_dn(attr_value):
self._error('No valid string-representation of '
'distinguished name %s.' % att... | Check dn attribute for issues. |
def devop_write(self, args, bustype):
'''write to a device'''
usage = "Usage: devop write <spi|i2c> name bus address regstart count <bytes>"
if len(args) < 5:
print(usage)
return
name = args[0]
bus = int(args[1],base=0)
address = int(args[2],base=0... | write to a device |
def help(i):
"""
Input: {
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
help - help text
}
"""
o=i.get('out','')... | Input: {
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
help - help text
} |
def split(self, k):
"""Return a tuple of two tables where the first table contains
``k`` rows randomly sampled and the second contains the remaining rows.
Args:
``k`` (int): The number of rows randomly sampled into the first
table. ``k`` must be between 1 and ``num_r... | Return a tuple of two tables where the first table contains
``k`` rows randomly sampled and the second contains the remaining rows.
Args:
``k`` (int): The number of rows randomly sampled into the first
table. ``k`` must be between 1 and ``num_rows - 1``.
Raises:
... |
def forget_subject(sid):
'''
forget_subject(sid) causes neuropythy's freesurfer module to forget about cached data for the
subject with subject id sid. The sid may be any sid that can be passed to the subject()
function.
This function is useful for batch-processing of subjects in a memory-limit... | forget_subject(sid) causes neuropythy's freesurfer module to forget about cached data for the
subject with subject id sid. The sid may be any sid that can be passed to the subject()
function.
This function is useful for batch-processing of subjects in a memory-limited environment; e.g.,
if you run ... |
def list_passwords(kwargs=None, call=None):
'''
List all password on the account
.. versionadded:: 2015.8.0
'''
response = _query('support', 'password/list')
ret = {}
for item in response['list']:
if 'server' in item:
server = item['server']['name']
if serve... | List all password on the account
.. versionadded:: 2015.8.0 |
def parse_mmtf_header(infile):
"""Parse an MMTF file and return basic header-like information.
Args:
infile (str): Path to MMTF file
Returns:
dict: Dictionary of parsed header
Todo:
- Can this be sped up by not parsing the 3D coordinate info somehow?
- OR just store th... | Parse an MMTF file and return basic header-like information.
Args:
infile (str): Path to MMTF file
Returns:
dict: Dictionary of parsed header
Todo:
- Can this be sped up by not parsing the 3D coordinate info somehow?
- OR just store the sequences when this happens since it... |
def integrate(self, outevent, inevent):
"""Propagate function time ratio along the function calls.
Must be called after finding the cycles.
See also:
- http://citeseer.ist.psu.edu/graham82gprof.html
"""
# Sanity checking
assert outevent not in self
for ... | Propagate function time ratio along the function calls.
Must be called after finding the cycles.
See also:
- http://citeseer.ist.psu.edu/graham82gprof.html |
def raise_for_missing_name(self, line: str, position: int, namespace: str, name: str) -> None:
"""Raise an exception if the namespace is not defined or if it does not validate the given name."""
self.raise_for_missing_namespace(line, position, namespace, name)
if self.has_enumerated_namespace(n... | Raise an exception if the namespace is not defined or if it does not validate the given name. |
def pause(self, remaining_pause_cycles):
"""Pause a subscription"""
url = urljoin(self._url, '/pause')
elem = ElementTreeBuilder.Element(self.nodename)
elem.append(Resource.element_for_value('remaining_pause_cycles',
remaining_pause_cycles))... | Pause a subscription |
def rule_role(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
rule = ET.SubElement(config, "rule", xmlns="urn:brocade.com:mgmt:brocade-aaa")
index_key = ET.SubElement(rule, "index")
index_key.text = kwargs.pop('index')
role = ET.SubElemen... | Auto Generated Code |
def _read_bytes_from_non_framed_body(self, b):
"""Reads the requested number of bytes from a streaming non-framed message body.
:param int b: Number of bytes to read
:returns: Decrypted bytes from source stream
:rtype: bytes
"""
_LOGGER.debug("starting non-framed body re... | Reads the requested number of bytes from a streaming non-framed message body.
:param int b: Number of bytes to read
:returns: Decrypted bytes from source stream
:rtype: bytes |
async def openurl(url, **opts):
'''
Open a URL to a remote telepath object.
Args:
url (str): A telepath URL.
**opts (dict): Telepath connect options.
Returns:
(synapse.telepath.Proxy): A telepath proxy object.
The telepath proxy may then be used for sync or async calls:
... | Open a URL to a remote telepath object.
Args:
url (str): A telepath URL.
**opts (dict): Telepath connect options.
Returns:
(synapse.telepath.Proxy): A telepath proxy object.
The telepath proxy may then be used for sync or async calls:
proxy = openurl(url)
value = ... |
def getWorkflowDir(workflowID, configWorkDir=None):
"""
Returns a path to the directory where worker directories and the cache will be located
for this workflow.
:param str workflowID: Unique identifier for the workflow
:param str configWorkDir: Value passed to the program using... | Returns a path to the directory where worker directories and the cache will be located
for this workflow.
:param str workflowID: Unique identifier for the workflow
:param str configWorkDir: Value passed to the program using the --workDir flag
:return: Path to the workflow directory
... |
def _get_or_add_image(self, image_file):
"""
Return an (rId, description, image_size) 3-tuple identifying the
related image part containing *image_file* and describing the image.
"""
image_part, rId = self.part.get_or_add_image_part(image_file)
desc, image_size = image_pa... | Return an (rId, description, image_size) 3-tuple identifying the
related image part containing *image_file* and describing the image. |
def _solve(self):
"""Solve the problem with the current objective."""
# Remove temporary constraints
while len(self._remove_constr) > 0:
self._remove_constr.pop().delete()
try:
self._prob.solve(lp.ObjectiveSense.Maximize)
except lp.SolverError as e:
... | Solve the problem with the current objective. |
def extract_subsection(im, shape):
r"""
Extracts the middle section of a image
Parameters
----------
im : ND-array
Image from which to extract the subsection
shape : array_like
Can either specify the size of the extracted section or the fractional
size of the image to e... | r"""
Extracts the middle section of a image
Parameters
----------
im : ND-array
Image from which to extract the subsection
shape : array_like
Can either specify the size of the extracted section or the fractional
size of the image to extact.
Returns
-------
ima... |
def update_with_result(self, result):
"""Update item-model with result from host
State is sent from host after processing had taken place
and represents the events that took place; including
log messages and completion status.
Arguments:
result (dict): Dictionary fo... | Update item-model with result from host
State is sent from host after processing had taken place
and represents the events that took place; including
log messages and completion status.
Arguments:
result (dict): Dictionary following the Result schema |
def restore_flattened_dict(i):
"""
Input: {
dict - flattened dict
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
dict - restored dict
... | Input: {
dict - flattened dict
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
dict - restored dict
} |
def _store_variable(self, j, key, m, value):
"""Store a copy of the variable in the history
"""
if hasattr(value, 'copy'):
v = value.copy()
else:
v = value
self.history[j][key][m].append(v) | Store a copy of the variable in the history |
def get_feature_info(feature):
"""Returns a dict with feature information"""
dimensions = feature.findall('position')
for dim in dimensions:
if dim.attrib['dim'] == '0':
rt = dim.text
elif dim.attrib['dim'] == '1':
mz = dim.text
return {'rt': float(rt), 'mz': floa... | Returns a dict with feature information |
def get_gene_symbols(chrom, start, stop):
"""Get the gene symbols that a interval overlaps"""
gene_symbols = query_gene_symbol(chrom, start, stop)
logger.debug("Found gene symbols: {0}".format(', '.join(gene_symbols)))
return gene_symbols | Get the gene symbols that a interval overlaps |
def view_count_plus(slug):
'''
View count plus one.
'''
entry = TabWiki.update(
view_count=TabWiki.view_count + 1,
).where(TabWiki.uid == slug)
entry.execute() | View count plus one. |
def getInvestigators(self, tags = None, seperator = ";", _getTag = False):
"""Returns a list of the names of investigators. The optional arguments are ignored.
# Returns
`list [str]`
> A list of all the found investigator's names
"""
if tags is None:
tags =... | Returns a list of the names of investigators. The optional arguments are ignored.
# Returns
`list [str]`
> A list of all the found investigator's names |
def translate_char(source_char, carrier, reverse=False, encoding=False):
u"""translate unicode emoji character to unicode carrier emoji character (or reverse)
Attributes:
source_char - emoji character. it must be unicode instance or have to set `encoding` attribute to decode
carrier ... | u"""translate unicode emoji character to unicode carrier emoji character (or reverse)
Attributes:
source_char - emoji character. it must be unicode instance or have to set `encoding` attribute to decode
carrier - the target carrier
reverse - if you want to translate CARRIE... |
def complete(self, stream):
"""Complete the pending stream.
Any connections made to :py:attr:`stream` are connected to `stream` once
this method returns.
Args:
stream(Stream): Stream that completes the connection.
"""
assert not s... | Complete the pending stream.
Any connections made to :py:attr:`stream` are connected to `stream` once
this method returns.
Args:
stream(Stream): Stream that completes the connection. |
def _get_default_namespace(self) -> Optional[Namespace]:
"""Get the reference BEL namespace if it exists."""
return self._get_query(Namespace).filter(Namespace.url == self._get_namespace_url()).one_or_none() | Get the reference BEL namespace if it exists. |
def _check_inplace_setting(self, value):
""" check whether we allow in-place setting with this type of value """
if self._is_mixed_type:
if not self._is_numeric_mixed_type:
# allow an actual np.nan thru
try:
if np.isnan(value):
... | check whether we allow in-place setting with this type of value |
def update_transfer_job(self, job_name, body):
"""
Updates a transfer job that runs periodically.
:param job_name: (Required) Name of the job to be updated
:type job_name: str
:param body: A request body, as described in
https://cloud.google.com/storage-transfer/docs... | Updates a transfer job that runs periodically.
:param job_name: (Required) Name of the job to be updated
:type job_name: str
:param body: A request body, as described in
https://cloud.google.com/storage-transfer/docs/reference/rest/v1/transferJobs/patch#request-body
:type bo... |
def add_output(self, address, value, unit='satoshi'):
"""
Add an output (a person who will receive funds via this tx).
If no unit is specified, satoshi is implied.
"""
value_satoshi = self.from_unit_to_satoshi(value, unit)
if self.verbose:
print("Adding outpu... | Add an output (a person who will receive funds via this tx).
If no unit is specified, satoshi is implied. |
def _select_date_range(self, lines):
"""Identify lines containing headers within the range begin_date to end_date.
Parameters
-----
lines: list
list of lines from the IGRA2 data file.
"""
headers = []
num_lev = []
dates = []
# Get in... | Identify lines containing headers within the range begin_date to end_date.
Parameters
-----
lines: list
list of lines from the IGRA2 data file. |
def _build(self, name, **params):
"""
Rebuild operations by removing open modules that no longer need to be
watched, and adding new modules if they are not currently being watched.
This is done by comparing self.modules to watch_files.paths_open
"""
log = self._getparam('log... | Rebuild operations by removing open modules that no longer need to be
watched, and adding new modules if they are not currently being watched.
This is done by comparing self.modules to watch_files.paths_open |
def get_or_create_media(self, api_media):
"""
Find or create a Media object given API data.
:param api_media: the API data for the Media
:return: a tuple of an Media instance and a boolean indicating whether the Media was created or not
"""
return Media.objects.get_or_cr... | Find or create a Media object given API data.
:param api_media: the API data for the Media
:return: a tuple of an Media instance and a boolean indicating whether the Media was created or not |
def get_summary_stats(self, output_csv=None):
"""Generates a CSV report with summary statistics about the assembly
The calculated statistics are:
- Number of contigs
- Average contig size
- N50
- Total assembly length
- Average GC content
... | Generates a CSV report with summary statistics about the assembly
The calculated statistics are:
- Number of contigs
- Average contig size
- N50
- Total assembly length
- Average GC content
- Amount of missing data
Parameters
... |
def create(cls, name, key_chain_entry):
"""
Create a key chain with list of keys
Key_chain_entry format is::
[{'key': 'xxxx', 'key_id': 1-255, 'send_key': True|False}]
:param str name: Name of key chain
:param list key_chain_entry: list of key chain entries
... | Create a key chain with list of keys
Key_chain_entry format is::
[{'key': 'xxxx', 'key_id': 1-255, 'send_key': True|False}]
:param str name: Name of key chain
:param list key_chain_entry: list of key chain entries
:raises CreateElementFailed: create failed with reason
... |
def format(self, vertices):
"""Format instance to dump
vertices is dict of name to Vertex
"""
index = ' '.join(str(vertices[vn].index) for vn in self.vnames)
vcom = ' '.join(self.vnames) # for comment
buf = io.StringIO()
buf.write('spline {0:s} ... | Format instance to dump
vertices is dict of name to Vertex |
def run_until_disconnected(self):
"""
Runs the event loop until `disconnect` is called or if an error
while connecting/sending/receiving occurs in the background. In
the latter case, said error will ``raise`` so you have a chance
to ``except`` it on your own code.
If the... | Runs the event loop until `disconnect` is called or if an error
while connecting/sending/receiving occurs in the background. In
the latter case, said error will ``raise`` so you have a chance
to ``except`` it on your own code.
If the loop is already running, this method returns a corout... |
def docpie(doc, argv=None, help=True, version=None,
stdopt=True, attachopt=True, attachvalue=True,
helpstyle='python',
auto2dashes=True, name=None, case_sensitive=False,
optionsfirst=False, appearedonly=False, namedoptions=False,
extra=None):
"""
Parse `arg... | Parse `argv` based on command-line interface described in `doc`.
`docpie` creates your command-line interface based on its
description that you pass as `doc`. Such description can contain
--options, <positional-argument>, commands, which could be
[optional], (required), (mutually | exclusive) or repeat... |
def run_all(logdir, verbose=False):
"""Run simulations on a reasonable set of parameters.
Arguments:
logdir: the directory into which to store all the runs' data
verbose: if true, print out each run's name as it begins
"""
run_box_to_gaussian(logdir, verbose=verbose)
run_sobel(logdir, verbose=verbose... | Run simulations on a reasonable set of parameters.
Arguments:
logdir: the directory into which to store all the runs' data
verbose: if true, print out each run's name as it begins |
def arg_completions(
completion_text: str,
parent_function: str,
args: list,
arg_idx: int,
bel_spec: BELSpec,
bel_fmt: str,
species_id: str,
namespace: str,
size: int,
):
"""Function argument completion
Only allow legal options for completion given function name, arguments a... | Function argument completion
Only allow legal options for completion given function name, arguments and index of argument
to replace.
Args:
completion_text: text to use for completion - used for creating highlight
parent_function: BEL function containing these args
args: arguments ... |
def post_step(self, ctxt, step, idx, result):
"""
Called after executing a step.
:param ctxt: An instance of ``timid.context.Context``.
:param step: An instance of ``timid.steps.Step`` describing
the step that was executed.
:param idx: The index of the step ... | Called after executing a step.
:param ctxt: An instance of ``timid.context.Context``.
:param step: An instance of ``timid.steps.Step`` describing
the step that was executed.
:param idx: The index of the step in the list of steps.
:param result: An instance of ``timi... |
def add_intern_pattern(self, url=None):
"""Add intern URL regex to config."""
try:
pat = self.get_intern_pattern(url=url)
if pat:
log.debug(LOG_CHECK, "Add intern pattern %r", pat)
self.aggregate.config['internlinks'].append(get_link_pat(pat))
... | Add intern URL regex to config. |
def _from_dict(cls, _dict):
"""Initialize a TableReturn object from a json dictionary."""
args = {}
if 'document' in _dict:
args['document'] = DocInfo._from_dict(_dict.get('document'))
if 'model_id' in _dict:
args['model_id'] = _dict.get('model_id')
if 'mo... | Initialize a TableReturn object from a json dictionary. |
def osx_clipboard_get():
""" Get the clipboard's text on OS X.
"""
p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'],
stdout=subprocess.PIPE)
text, stderr = p.communicate()
# Text comes in with old Mac \r line endings. Change them to \n.
text = text.replace('\r', '\n')
return text | Get the clipboard's text on OS X. |
def addbr(name):
''' Create new bridge with the given name '''
fcntl.ioctl(ifconfig.sockfd, SIOCBRADDBR, name)
return Bridge(name) | Create new bridge with the given name |
def print_roi(self, loglevel=logging.INFO):
"""Print information about the spectral and spatial properties
of the ROI (sources, diffuse components)."""
self.logger.log(loglevel, '\n' + str(self.roi)) | Print information about the spectral and spatial properties
of the ROI (sources, diffuse components). |
def disconnect_async(self, connection_id, callback):
"""Asynchronously disconnect from a device that has previously been connected
Args:
connection_id (int): A unique identifier for this connection on the DeviceManager that owns this adapter.
callback (callable): A function call... | Asynchronously disconnect from a device that has previously been connected
Args:
connection_id (int): A unique identifier for this connection on the DeviceManager that owns this adapter.
callback (callable): A function called as callback(connection_id, adapter_id, success, failure_reaso... |
def delete_rule(name=None,
localport=None,
protocol=None,
dir=None,
remoteip=None):
'''
.. versionadded:: 2015.8.0
Delete an existing firewall rule identified by name and optionally by ports,
protocols, direction, and remote IP.
Args:... | .. versionadded:: 2015.8.0
Delete an existing firewall rule identified by name and optionally by ports,
protocols, direction, and remote IP.
Args:
name (str): The name of the rule to delete. If the name ``all`` is used
you must specify additional parameters.
localport (Option... |
def cmd_zf(self, ch=None):
"""zf ch=chname
Zoom the image for the given viewer/channel to fit the window.
"""
viewer = self.get_viewer(ch)
if viewer is None:
self.log("No current viewer/channel.")
return
viewer.zoom_fit()
cur_lvl = viewer... | zf ch=chname
Zoom the image for the given viewer/channel to fit the window. |
def makediagram(edges):
"""make the diagram with the edges"""
graph = pydot.Dot(graph_type='digraph')
nodes = edges2nodes(edges)
epnodes = [(node,
makeanode(node[0])) for node in nodes if nodetype(node)=="epnode"]
endnodes = [(node,
makeendnode(node[0])) for node in nodes if nodety... | make the diagram with the edges |
def set_elements_text(parent_to_parse, element_path=None, text_values=None):
"""
Assigns an array of text values to each of the elements parsed from the parent. The
text values are assigned in the same order they are provided.
If there are less values then elements, the remaining elements are skipped; b... | Assigns an array of text values to each of the elements parsed from the parent. The
text values are assigned in the same order they are provided.
If there are less values then elements, the remaining elements are skipped; but if
there are more, new elements will be inserted for each with the remaining text ... |
def _michael_b(m_l, m_r):
"""Defined in 802.11i p.49"""
m_r = m_r ^ _rotate_left32(m_l, 17)
m_l = (m_l + m_r) % 2**32
m_r = m_r ^ _XSWAP(m_l)
m_l = (m_l + m_r) % 2**32
m_r = m_r ^ _rotate_left32(m_l, 3)
m_l = (m_l + m_r) % 2**32
m_r = m_r ^ _rotate_right32(m_l, 2)
m_l = (m_l + m_r) %... | Defined in 802.11i p.49 |
def forward_kinematics(self, joints, full_kinematics=False):
"""Returns the transformation matrix of the forward kinematics
Parameters
----------
joints: list
The list of the positions of each joint. Note : Inactive joints must be in the list.
full_kinematics: bool
... | Returns the transformation matrix of the forward kinematics
Parameters
----------
joints: list
The list of the positions of each joint. Note : Inactive joints must be in the list.
full_kinematics: bool
Return the transformation matrices of each joint
Ret... |
def volume(self):
"""
Mesh volume - will throw a VTK error/warning if not a closed surface
Returns
-------
volume : float
Total volume of the mesh.
"""
mprop = vtk.vtkMassProperties()
mprop.SetInputData(self.tri_filter())
return mprop... | Mesh volume - will throw a VTK error/warning if not a closed surface
Returns
-------
volume : float
Total volume of the mesh. |
def datum_to_value(self, instance, datum):
"""Convert a given MAAS-side datum to a Python-side value.
:param instance: The `Object` instance on which this field is
currently operating. This method should treat it as read-only, for
example to perform validation with regards to ot... | Convert a given MAAS-side datum to a Python-side value.
:param instance: The `Object` instance on which this field is
currently operating. This method should treat it as read-only, for
example to perform validation with regards to other fields.
:param datum: The MAAS-side datum ... |
def get_unicodedata(version, output=HOME, no_zip=False):
"""Ensure we have Unicode data to generate Unicode tables."""
target = os.path.join(output, 'unicodedata', version)
zip_target = os.path.join(output, 'unicodedata', '%s.zip' % version)
if not os.path.exists(target) and os.path.exists(zip_target)... | Ensure we have Unicode data to generate Unicode tables. |
def get_category_drilldown(parser, token):
"""
Retrieves the specified category, its ancestors and its immediate children
as an iterable.
Syntax::
{% get_category_drilldown "category name" [using "app.Model"] as varname %}
Example::
{% get_category_drilldown "/Grandparent/Parent"... | Retrieves the specified category, its ancestors and its immediate children
as an iterable.
Syntax::
{% get_category_drilldown "category name" [using "app.Model"] as varname %}
Example::
{% get_category_drilldown "/Grandparent/Parent" [using "app.Model"] as family %}
or ::
{... |
def is_intersection(g, n):
"""
Determine if a node is an intersection
graph: 1 -->-- 2 -->-- 3
>>> is_intersection(g, 2)
False
graph:
1 -- 2 -- 3
|
4
>>> is_intersection(g, 2)
True
Parameters
----------
g : networkx DiGraph
n : node id
R... | Determine if a node is an intersection
graph: 1 -->-- 2 -->-- 3
>>> is_intersection(g, 2)
False
graph:
1 -- 2 -- 3
|
4
>>> is_intersection(g, 2)
True
Parameters
----------
g : networkx DiGraph
n : node id
Returns
-------
bool |
def make_index_for(package, index_dir, verbose=True):
"""
Create an 'index.html' for one package.
:param package: Package object to use.
:param index_dir: Where 'index.html' should be created.
"""
index_template = """\
<html>
<head><title>{title}</title></head>
<body>
<h1>{title}</h1>
<ul>
{p... | Create an 'index.html' for one package.
:param package: Package object to use.
:param index_dir: Where 'index.html' should be created. |
def _check_query(self, query, style_cols=None):
"""Checks if query from Layer or QueryLayer is valid"""
try:
self.sql_client.send(
utils.minify_sql((
'EXPLAIN',
'SELECT',
' {style_cols}{comma}',
... | Checks if query from Layer or QueryLayer is valid |
def create_ports(port, mpi, rank):
"""create a list of ports for the current rank"""
if port == "random" or port is None:
# ports will be filled in using random binding
ports = {}
else:
port = int(port)
ports = {
"REQ": port + 0,
... | create a list of ports for the current rank |
def add_request(self, request):
"""
Add a request object
"""
# Duplicate request name?
if request.name in self.requests:
raise ValueError('redefinition of request "{0}"'.format(request.name))
self.requests[request.name] = request
# Add the request UR... | Add a request object |
def from_text(text):
"""Convert text into an opcode.
@param text: the textual opcode
@type text: string
@raises UnknownOpcode: the opcode is unknown
@rtype: int
"""
if text.isdigit():
value = int(text)
if value >= 0 and value <= 15:
return value
value = _by_... | Convert text into an opcode.
@param text: the textual opcode
@type text: string
@raises UnknownOpcode: the opcode is unknown
@rtype: int |
def _init_index(root_dir, schema, index_name):
""" Creates new index or opens existing.
Args:
root_dir (str): root dir where to find or create index.
schema (whoosh.fields.Schema): schema of the index to create or open.
index_name (str): name of the index.
Returns:
tuple ((... | Creates new index or opens existing.
Args:
root_dir (str): root dir where to find or create index.
schema (whoosh.fields.Schema): schema of the index to create or open.
index_name (str): name of the index.
Returns:
tuple ((whoosh.index.FileIndex, str)): first element is index, ... |
def validate_subfolders(filedir, metadata):
"""
Check that all folders in the given directory have a corresponding
entry in the metadata file, and vice versa.
:param filedir: This field is the target directory from which to
match metadata
:param metadata: This field contains the metadata to... | Check that all folders in the given directory have a corresponding
entry in the metadata file, and vice versa.
:param filedir: This field is the target directory from which to
match metadata
:param metadata: This field contains the metadata to be matched. |
def match_aspect_to_viewport(self):
"""Updates Camera.aspect to match the viewport's aspect ratio."""
viewport = self.viewport
self.aspect = float(viewport.width) / viewport.height | Updates Camera.aspect to match the viewport's aspect ratio. |
def get_user(self, user):
"""Get user's data (first and last name, email, etc).
Args:
user (string): User name.
Returns:
(dictionary): User's data encoded in a dictionary.
Raises:
requests.HTTPError on failure.
"""
return self.servic... | Get user's data (first and last name, email, etc).
Args:
user (string): User name.
Returns:
(dictionary): User's data encoded in a dictionary.
Raises:
requests.HTTPError on failure. |
def average_gradient(data, *kwargs):
""" Compute average gradient norm of an image
"""
return np.average(np.array(np.gradient(data))**2) | Compute average gradient norm of an image |
def natsorted(seq, key=lambda x: x, number_type=float, signed=True, exp=True):
"""\
Sorts a sequence naturally (alphabetically and numerically),
not lexicographically.
>>> a = ['num3', 'num5', 'num2']
>>> natsorted(a)
['num2', 'num3', 'num5']
>>> b = [('a', 'num3'), ('b', 'n... | \
Sorts a sequence naturally (alphabetically and numerically),
not lexicographically.
>>> a = ['num3', 'num5', 'num2']
>>> natsorted(a)
['num2', 'num3', 'num5']
>>> b = [('a', 'num3'), ('b', 'num5'), ('c', 'num2')]
>>> from operator import itemgetter
>>> natsorte... |
def send_output_report(self, data):
"""Send input/output/feature report ID = report_id, data should be a
c_ubyte object with included the required report data
"""
assert( self.is_opened() )
#make sure we have c_ubyte array storage
if not ( isinstance(data, ctypes.Ar... | Send input/output/feature report ID = report_id, data should be a
c_ubyte object with included the required report data |
def miraligner(args):
"""
Realign BAM hits to miRBAse to get better accuracy and annotation
"""
hairpin, mirna = _download_mirbase(args)
precursors = _read_precursor(args.hairpin, args.sps)
matures = _read_mature(args.mirna, args.sps)
gtf = _read_gtf(args.gtf)
out_dts = []
out_files ... | Realign BAM hits to miRBAse to get better accuracy and annotation |
def do_powershell_complete(cli, prog_name):
"""Do the powershell completion
Parameters
----------
cli : click.Command
The main click Command of the program
prog_name : str
The program name on the command line
Returns
-------
bool
True if the completion was succe... | Do the powershell completion
Parameters
----------
cli : click.Command
The main click Command of the program
prog_name : str
The program name on the command line
Returns
-------
bool
True if the completion was successful, False otherwise |
def single_value(cls, value, shape, pixel_scale, origin=(0.0, 0.0)):
"""
Creates an instance of Array and fills it with a single value
Parameters
----------
value: float
The value with which the array should be filled
shape: (int, int)
The shape o... | Creates an instance of Array and fills it with a single value
Parameters
----------
value: float
The value with which the array should be filled
shape: (int, int)
The shape of the array
pixel_scale: float
The scale of a pixel in arc seconds
... |
def minimum_katcp_version(major, minor=0):
"""Decorator; exclude handler if server's protocol version is too low
Useful for including default handler implementations for KATCP features that
are only present in certain KATCP protocol versions
Examples
--------
>>> class MyDevice(DeviceServer):
... | Decorator; exclude handler if server's protocol version is too low
Useful for including default handler implementations for KATCP features that
are only present in certain KATCP protocol versions
Examples
--------
>>> class MyDevice(DeviceServer):
... '''This device server will expose ?myr... |
def focusd(task):
""" Forks the current process as a daemon to run a task.
`task`
``Task`` instance for the task to run.
"""
# determine if command server should be started
if registration.get_registered(event_hooks=True, root_access=True):
# root event plugins availabl... | Forks the current process as a daemon to run a task.
`task`
``Task`` instance for the task to run. |
def get_task(self, task=0, timeout=None, block=True):
"""
Returns an iterator which results are limited to one **task**. The
default iterator the one which e.g. will be used in a for loop is the
iterator for the first task (task =0). The returned iterator is a
``_NuMapTask`` in... | Returns an iterator which results are limited to one **task**. The
default iterator the one which e.g. will be used in a for loop is the
iterator for the first task (task =0). The returned iterator is a
``_NuMapTask`` instance.
Compare::
for result_from_task_0 in ... |
def getTotalw(self):
"""Returns the cumulative w for all the fields in the dataset"""
w = sum([field.w for field in self.fields])
return w | Returns the cumulative w for all the fields in the dataset |
def is_training_modified(self):
""" Returns `True` if training data
was modified since last training.
Returns `False` otherwise,
or if using builtin training data.
"""
last_modified = self.trainer.get_last_modified()
if last_modified > self.training_t... | Returns `True` if training data
was modified since last training.
Returns `False` otherwise,
or if using builtin training data. |
def list(self, **params):
"""
Retrieve visit outcomes
Returns Visit Outcomes, according to the parameters provided
:calls: ``get /visit_outcomes``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which rep... | Retrieve visit outcomes
Returns Visit Outcomes, according to the parameters provided
:calls: ``get /visit_outcomes``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of VisitOutcomes.
:r... |
def addGlobalServices(self):
"""
This is where we put service that we don't want to be duplicated on
worker subprocesses
"""
if self.options.get('global_cache') and self.options.get('cache'):
# only add the cache service here if the global_cache and cache
... | This is where we put service that we don't want to be duplicated on
worker subprocesses |
def untranslateName(s):
"""Undo Python conversion of CL parameter or variable name."""
s = s.replace('DOT', '.')
s = s.replace('DOLLAR', '$')
# delete 'PY' at start of name components
if s[:2] == 'PY': s = s[2:]
s = s.replace('.PY', '.')
return s | Undo Python conversion of CL parameter or variable name. |
def make_matrix(version, reserve_regions=True, add_timing=True):
"""\
Creates a matrix of the provided `size` (w x h) initialized with the
(illegal) value 0x2.
The "timing pattern" is already added to the matrix and the version
and format areas are initialized with 0x0.
:param int version: The... | \
Creates a matrix of the provided `size` (w x h) initialized with the
(illegal) value 0x2.
The "timing pattern" is already added to the matrix and the version
and format areas are initialized with 0x0.
:param int version: The (Micro) QR Code version
:rtype: tuple of bytearrays |
def Datetime(null=True, **kwargs):
"""A datetime property."""
return Property(
types=datetime.datetime,
convert=util.local_timezone,
load=dateutil.parser.parse,
null=null,
**kwargs
) | A datetime property. |
def defaults(d1, d2):
"""
Update a copy of d1 with the contents of d2 that are
not in d1. d1 and d2 are dictionary like objects.
Parameters
----------
d1 : dict | dataframe
dict with the preferred values
d2 : dict | dataframe
dict with the default values
Returns
---... | Update a copy of d1 with the contents of d2 that are
not in d1. d1 and d2 are dictionary like objects.
Parameters
----------
d1 : dict | dataframe
dict with the preferred values
d2 : dict | dataframe
dict with the default values
Returns
-------
out : dict | dataframe
... |
def find_and_filter_sgf_files(base_dir, min_year=None, komi=None):
"""Finds all sgf files in base_dir with year >= min_year and komi"""
sgf_files = []
for dirpath, dirnames, filenames in os.walk(base_dir):
for filename in filenames:
if filename.endswith('.sgf'):
path = os... | Finds all sgf files in base_dir with year >= min_year and komi |
def Points(plist, r=5, c="gray", alpha=1):
"""
Build a point ``Actor`` for a list of points.
:param float r: point radius.
:param c: color name, number, or list of [R,G,B] colors of same length as plist.
:type c: int, str, list
:param float alpha: transparency in range [0,1].
.. hint:: |lo... | Build a point ``Actor`` for a list of points.
:param float r: point radius.
:param c: color name, number, or list of [R,G,B] colors of same length as plist.
:type c: int, str, list
:param float alpha: transparency in range [0,1].
.. hint:: |lorenz| |lorenz.py|_ |
def vcs_upload():
"""
Uploads the project with the selected VCS tool.
"""
if env.deploy_tool == "git":
remote_path = "ssh://%s@%s%s" % (env.user, env.host_string,
env.repo_path)
if not exists(env.repo_path):
run("mkdir -p %s" % env.rep... | Uploads the project with the selected VCS tool. |
def inFootprint(footprint,ra,dec):
"""
Check if set of ra,dec combinations are in footprint.
Careful, input files must be in celestial coordinates.
filename : Either healpix map or mangle polygon file
ra,dec : Celestial coordinates
Returns:
inside : boolean array of coordinates in ... | Check if set of ra,dec combinations are in footprint.
Careful, input files must be in celestial coordinates.
filename : Either healpix map or mangle polygon file
ra,dec : Celestial coordinates
Returns:
inside : boolean array of coordinates in footprint |
def values(self):
"""return a list of all state values"""
values = []
for __, data in self.items():
values.append(data)
return values | return a list of all state values |
def remove(self, branch, turn, tick):
"""Delete data on or after this tick
On the assumption that the future has been invalidated.
"""
for parent, entitys in list(self.parents.items()):
for entity, keys in list(entitys.items()):
for key, branchs in list(keys... | Delete data on or after this tick
On the assumption that the future has been invalidated. |
def hmget(self, *args):
"""
This command on the model allow getting many instancehash fields with only
one redis call. You must pass hash name to retrieve as arguments.
"""
if args and not any(arg in self._instancehash_fields for arg in args):
raise ValueError("Only I... | This command on the model allow getting many instancehash fields with only
one redis call. You must pass hash name to retrieve as arguments. |
def add(self, data):
"""
Add a list of item into the container
:data: dict of items & value per hostname
"""
for host in data:
for key in data[host]:
if not data[host][key] == []:
self.add_item(host, key, data[host][key]) | Add a list of item into the container
:data: dict of items & value per hostname |
def _validate_num_units(num_units, service_name, add_error):
"""Check that the given num_units is valid.
Use the given service name to describe possible errors.
Use the given add_error callable to register validation error.
If no errors are encountered, return the number of units as an integer.
Re... | Check that the given num_units is valid.
Use the given service name to describe possible errors.
Use the given add_error callable to register validation error.
If no errors are encountered, return the number of units as an integer.
Return None otherwise. |
def color(self):
"""Line color in IDA View"""
color = idc.GetColor(self.ea, idc.CIC_ITEM)
if color == 0xFFFFFFFF:
return None
return color | Line color in IDA View |
def search(self, word, limit=30):
"""
Search for a word within the wordgatherer collection.
:param word: Word to search for.
:param limit: Maximum number of results to return.
"""
search = Search(PrefixQuery("word", word), sort={"count": "desc"})
for doc in self.c... | Search for a word within the wordgatherer collection.
:param word: Word to search for.
:param limit: Maximum number of results to return. |
def put(self, key, value):
'''Stores the object `value` named by `key` in `service`.
Args:
key: Key naming `value`.
value: the object to store.
'''
key = self._service_key(key)
self._service_ops['put'](key, value) | Stores the object `value` named by `key` in `service`.
Args:
key: Key naming `value`.
value: the object to store. |
def meanprecision(a):
'''Mean and precision of Dirichlet distribution.
Parameters
----------
a : array
Parameters of Dirichlet distribution.
Returns
-------
mean : array
Numbers [0,1] of the means of the Dirichlet distribution.
precision : float
Precision or con... | Mean and precision of Dirichlet distribution.
Parameters
----------
a : array
Parameters of Dirichlet distribution.
Returns
-------
mean : array
Numbers [0,1] of the means of the Dirichlet distribution.
precision : float
Precision or concentration parameter of the D... |
def t_RP(self, t):
r'[])]'
if t.value != ']' and OPTIONS.bracket.value:
t.type = 'RPP'
return t | r'[])] |
def initialize_layers(self, layers=None):
"""Sets up the Lasagne layers
:param layers: The dictionary of layers, or a
:class:`lasagne.Layers` instance, describing the underlying
network
:return: the output layer of the underlying lasagne network.
:seealso: :ref:`layer-... | Sets up the Lasagne layers
:param layers: The dictionary of layers, or a
:class:`lasagne.Layers` instance, describing the underlying
network
:return: the output layer of the underlying lasagne network.
:seealso: :ref:`layer-def` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.