positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def reconall(subjfile, subjID=None, subjdir=None, runreconall=True):
"""
Carries out Freesurfer's reconall on T1 nifti file
WARNING: Reconall takes very long to run!!
http://nipy.sourceforge.net/nipype/users/examples/smri_freesurfer.html
Parameters
----------
subjfile: nifti file
... | Carries out Freesurfer's reconall on T1 nifti file
WARNING: Reconall takes very long to run!!
http://nipy.sourceforge.net/nipype/users/examples/smri_freesurfer.html
Parameters
----------
subjfile: nifti file
Path to subject's T1 nifti file
subjID: string
optional name... |
def solve(succ, orien, i, direc):
"""Can a laser leaving mirror i in direction direc reach exit ?
:param i: mirror index
:param direc: direction leaving mirror i
:param orient: orient[i]=orientation of mirror i
:param succ: succ[i][direc]=succ mirror reached
when leaving i in direc... | Can a laser leaving mirror i in direction direc reach exit ?
:param i: mirror index
:param direc: direction leaving mirror i
:param orient: orient[i]=orientation of mirror i
:param succ: succ[i][direc]=succ mirror reached
when leaving i in direction direc |
def notifyBlock(self, queue, blocked):
'''
Internal notify for sub-queues been blocked
'''
if blocked:
if self.prioritySet[-1] == queue.priority:
self.prioritySet.pop()
else:
pindex = bisect_left(self.prioritySet, queue.priority)
... | Internal notify for sub-queues been blocked |
def is_resource_protected(self, request, **kwargs):
"""
Determines if a resource should be protected.
Returns true if and only if the resource's access_state matches an entry in
the return value of get_protected_states().
"""
access_state = self._get_resource_access_stat... | Determines if a resource should be protected.
Returns true if and only if the resource's access_state matches an entry in
the return value of get_protected_states(). |
def status_code(self):
"""
Get the http status code for the response
"""
try:
return self._status_code
except AttributeError:
self._status_code = self._response.getcode()
return self._status_code | Get the http status code for the response |
def _ParseInformationalOptions(self, options):
"""Parses the informational options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
super(PsortTool, self)._ParseInformationalOptions(options)
self._quiet_mode = ge... | Parses the informational options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid. |
def numeric_columns(self, include_bool=True):
"""Returns the numeric columns of the Manager.
Returns:
List of index names.
"""
columns = []
for col, dtype in zip(self.columns, self.dtypes):
if is_numeric_dtype(dtype) and (
include_bool or ... | Returns the numeric columns of the Manager.
Returns:
List of index names. |
def neg_int(i):
""" Simple negative integer validation. """
try:
if isinstance(i, string_types):
i = int(i)
if not isinstance(i, int) or i > 0:
raise Exception()
except:
raise ValueError("Not a negative integer")
return i | Simple negative integer validation. |
def add_namespace(self, namespace, interface=None, check_extras=True,
load_now=False):
"""
register given namespace in global database of plugins
in case it's already registered, return the registration
"""
tempo = self._namespaces.get(namespace)
i... | register given namespace in global database of plugins
in case it's already registered, return the registration |
def load_spectrum_fits_messed_x(filename, sp_ref=None):
"""Loads FITS file spectrum that does not have the proper headers. Returns a Spectrum"""
import f311.filetypes as ft
# First tries to load as usual
f = load_with_classes(filename, (ft.FileSpectrumFits,))
if f is not None:
ret = f.spec... | Loads FITS file spectrum that does not have the proper headers. Returns a Spectrum |
def Pcn(x, dsz, Nv, dimN=2, dimC=1, crp=False, zm=False):
"""Constraint set projection for convolutional dictionary update
problem.
Parameters
----------
x : array_like
Input array
dsz : tuple
Filter support size(s), specified using the same format as the `dsz`
parameter of :... | Constraint set projection for convolutional dictionary update
problem.
Parameters
----------
x : array_like
Input array
dsz : tuple
Filter support size(s), specified using the same format as the `dsz`
parameter of :func:`bcrop`
Nv : tuple
Sizes of problem spatial indice... |
def register_user(self, user, allow_login=None, send_email=None,
_force_login_without_confirmation=False):
"""
Service method to register a user.
Sends signal `user_registered`.
Returns True if the user has been logged in, False otherwise.
"""
shou... | Service method to register a user.
Sends signal `user_registered`.
Returns True if the user has been logged in, False otherwise. |
def pause(self):
"""Set the execution mode to paused
"""
if self.state_machine_manager.active_state_machine_id is None:
logger.info("'Pause' is not a valid action to initiate state machine execution.")
return
if self.state_machine_manager.get_active_state_machine(... | Set the execution mode to paused |
def write_recovery(page, injList):
"""
Write injection recovery plots to markup.page object page
"""
th = ['']+injList
td = []
plots = ['sky_error_time','sky_error_mchirp','sky_error_distance']
text = { 'sky_error_time':'Sky error vs time',\
'sky_error_mchirp':'S... | Write injection recovery plots to markup.page object page |
def find_results_gen(search_term, field='title'):
'''
Return a generator of the results returned by a search of
the protein data bank. This generator is used internally.
Parameters
----------
search_term : str
The search keyword
field : str
The type of information to recor... | Return a generator of the results returned by a search of
the protein data bank. This generator is used internally.
Parameters
----------
search_term : str
The search keyword
field : str
The type of information to record about each entry
Examples
--------
>>> result_... |
def _get_create_kwargs(skip_translate=None,
ignore_collisions=False,
validate_ip_addrs=True,
client_args=None,
**kwargs):
'''
Take input kwargs and return a kwargs dict to pass to docker-py's
create_container() funct... | Take input kwargs and return a kwargs dict to pass to docker-py's
create_container() function. |
def newchild(self,chld=False):
"""Like givebirth(), but also appends the new child to the list of children."""
if not chld:
chld = self.givebirth()
lchld=[chld] if type(chld)!=list else chld
for chldx in lchld: chldx.parent=self
self.children.append(chld)
return chld | Like givebirth(), but also appends the new child to the list of children. |
def u64_to_hex16le(val):
"""! @brief Create 16-digit hexadecimal string from 64-bit register value"""
return ''.join("%02x" % (x & 0xFF) for x in (
val,
val >> 8,
val >> 16,
val >> 24,
val >> 32,
val >> 40,
val >> 48,
val >> 56,
)) | ! @brief Create 16-digit hexadecimal string from 64-bit register value |
def prepare_shell_data(self, shells, key, entry):
"""Prepare one shell or docker task."""
if self.can_process_shell(entry):
if key in ['python']:
entry['type'] = key
if 'with' in entry and isinstance(entry['with'], str):
rendered_with = ast.litera... | Prepare one shell or docker task. |
def lowest_common_hypernyms(self,target_synset):
"""Returns the common hypernyms of the synset and the target synset, which are furthest from the closest roots.
Parameters
----------
target_synset : Synset
Synset with which the common hypernyms are sought.
... | Returns the common hypernyms of the synset and the target synset, which are furthest from the closest roots.
Parameters
----------
target_synset : Synset
Synset with which the common hypernyms are sought.
Returns
-------
list of Synsets
... |
def get_first_result(threads):
""" this blocks, waiting for the first result that returns from a thread
:type threads: list[Thread]
"""
while True:
for thread in threads:
if not thread.is_alive():
return thread.queue.get() | this blocks, waiting for the first result that returns from a thread
:type threads: list[Thread] |
def _get_internal_slot(slot_key=None,
filler_pipeline_key=None,
slot_dict=None):
"""Gets information about a _SlotRecord for display in UI.
Args:
slot_key: The db.Key of the slot to fetch.
filler_pipeline_key: In the case the slot has not yet been filled, assum... | Gets information about a _SlotRecord for display in UI.
Args:
slot_key: The db.Key of the slot to fetch.
filler_pipeline_key: In the case the slot has not yet been filled, assume
that the given db.Key (for a _PipelineRecord) will be the filler of
the slot in the future.
slot_dict: The slot JS... |
def verify(self, connection_type=None):
"""
Verifies and update the remote system settings.
:param connection_type: same as the one in `create` method.
"""
req_body = self._cli.make_body(connectionType=connection_type)
resp = self.action('verify', **req_body)
re... | Verifies and update the remote system settings.
:param connection_type: same as the one in `create` method. |
def make_qemu_dirs(max_qemu_id, output_dir, topology_name):
"""
Create Qemu VM working directories if required
:param int max_qemu_id: Number of directories to create
:param str output_dir: Output directory
:param str topology_name: Topology name
"""
if max_qemu_id is not None:
for ... | Create Qemu VM working directories if required
:param int max_qemu_id: Number of directories to create
:param str output_dir: Output directory
:param str topology_name: Topology name |
def update_mutation_inputs(service):
"""
Args:
service : The service being updated by the mutation
Returns:
(list) : a list of all of the fields availible for the service. Pk
is a required field in order to filter the results
"""
# grab the default lis... | Args:
service : The service being updated by the mutation
Returns:
(list) : a list of all of the fields availible for the service. Pk
is a required field in order to filter the results |
def to_dictionary(self):
"""Serialize an object into dictionary form. Useful if you have to
serialize an array of objects into JSON. Otherwise, if you call the
:meth:`to_json` method on each object in the list and then try to
dump the array, you end up with an array with one string."""... | Serialize an object into dictionary form. Useful if you have to
serialize an array of objects into JSON. Otherwise, if you call the
:meth:`to_json` method on each object in the list and then try to
dump the array, you end up with an array with one string. |
def clear_stale_pids(pids, pid_dir='/tmp', prefix='', multi=False):
'check for and remove any pids which have no corresponding process'
if isinstance(pids, (int, float, long)):
pids = [pids]
pids = str2list(pids, map_=unicode)
procs = map(unicode, os.listdir('/proc'))
running = [pid for pid ... | check for and remove any pids which have no corresponding process |
def remove_security_group(self, name):
"""
Remove a security group from container
"""
for group in self.security_groups:
if group.isc_name == name:
group.delete() | Remove a security group from container |
def config_md5(self, source_config):
"""Compute MD5 hash of file."""
file_contents = source_config + "\n" # Cisco IOS automatically adds this
file_contents = file_contents.encode("UTF-8")
return hashlib.md5(file_contents).hexdigest() | Compute MD5 hash of file. |
def _build_query_dict(self, formdata=None):
"""
Take submitted data from form and create a query dict to be
used in a Q object (or filter)
"""
if self.is_valid() and formdata is None:
formdata = self.cleaned_data
key = "{field}__{operator}".format(**formdata)
... | Take submitted data from form and create a query dict to be
used in a Q object (or filter) |
def deaccent(text):
"""
Remove accentuation from the given string. Input text is either a unicode string or utf8 encoded bytestring.
Return input string with accents removed, as unicode.
>>> deaccent("Šéf chomutovských komunistů dostal poštou bílý prášek")
u'Sef chomutovskych komunistu dostal post... | Remove accentuation from the given string. Input text is either a unicode string or utf8 encoded bytestring.
Return input string with accents removed, as unicode.
>>> deaccent("Šéf chomutovských komunistů dostal poštou bílý prášek")
u'Sef chomutovskych komunistu dostal postou bily prasek' |
def get_success_url(self):
""" Returns the success URL to redirect the user to. """
return reverse(
'forum_conversation:topic',
kwargs={
'forum_slug': self.object.forum.slug,
'forum_pk': self.object.forum.pk,
'slug': self.object.slu... | Returns the success URL to redirect the user to. |
def getBitmapFromRect(self, x, y, w, h):
""" Capture the specified area of the (virtual) screen. """
min_x, min_y, screen_width, screen_height = self._getVirtualScreenRect()
img = self._getVirtualScreenBitmap() # TODO
# Limit the coordinates to the virtual screen
# Then offset so... | Capture the specified area of the (virtual) screen. |
def process_args():
"""
Parse command-line arguments.
"""
parser = argparse.ArgumentParser(description="A file for converting NeuroML v2 files into POVRay files for 3D rendering")
parser.add_argument('neuroml_file', type=str, metavar='<NeuroML file>',
help='NeuroML ... | Parse command-line arguments. |
def state_tomography_programs(state_prep, qubits=None,
rotation_generator=tomography.default_rotations):
"""
Yield tomographic sequences that prepare a state with Quil program `state_prep` and then append
tomographic rotations on the specified `qubits`. If `qubits is None`, it ... | Yield tomographic sequences that prepare a state with Quil program `state_prep` and then append
tomographic rotations on the specified `qubits`. If `qubits is None`, it assumes all qubits in
the program should be tomographically rotated.
:param Program state_prep: The program to prepare the state to be tom... |
def log(self, file, batch):
"""
Log that a migration was run.
:type file: str
:type batch: int
"""
record = {"migration": file, "batch": batch}
self.table().insert(**record) | Log that a migration was run.
:type file: str
:type batch: int |
def event_hint_with_exc_info(exc_info=None):
# type: (ExcInfo) -> Dict[str, Optional[ExcInfo]]
"""Creates a hint with the exc info filled in."""
if exc_info is None:
exc_info = sys.exc_info()
else:
exc_info = exc_info_from_error(exc_info)
if exc_info[0] is None:
exc_info = No... | Creates a hint with the exc info filled in. |
def format(self):
"""
Get format according to algorithm defined in RFC 5646 section 2.1.1.
:return: formatted tag string.
"""
tag = self.data['tag']
subtags = tag.split('-')
if len(subtags) == 1:
return subtags[0]
formatted_tag = subtags[0]
... | Get format according to algorithm defined in RFC 5646 section 2.1.1.
:return: formatted tag string. |
def _validate(self):
""" Enforce some structure to the config file """
# This could be done with a default config
# Check that specific keys exist
sections = odict([
('catalog',['dirname','basename',
'lon_field','lat_field','objid_field',
... | Enforce some structure to the config file |
def _process_all_any(self, func, **kwargs):
"""Calculates if any or all the values are true.
Return:
A new QueryCompiler object containing boolean values or boolean.
"""
axis = kwargs.get("axis", 0)
axis = 0 if axis is None else axis
kwargs["axis"] = axis
... | Calculates if any or all the values are true.
Return:
A new QueryCompiler object containing boolean values or boolean. |
def rm_known_host(user=None, hostname=None, config=None, port=None):
'''
Remove all keys belonging to hostname from a known_hosts file.
CLI Example:
.. code-block:: bash
salt '*' ssh.rm_known_host <user> <hostname>
'''
if not hostname:
return {'status': 'error',
... | Remove all keys belonging to hostname from a known_hosts file.
CLI Example:
.. code-block:: bash
salt '*' ssh.rm_known_host <user> <hostname> |
def _repr_html_(self, **kwargs):
"""Produce HTML for Jupyter Notebook"""
from jinja2 import Template
from markdown import markdown as convert_markdown
extensions = [
'markdown.extensions.extra',
'markdown.extensions.admonition'
]
return convert_m... | Produce HTML for Jupyter Notebook |
def close(self, child):
"""
Close a child position - alias for rebalance(0, child). This will also
flatten (close out all) the child's children.
Args:
* child (str): Child, specified by name.
"""
c = self.children[child]
# flatten if children not None... | Close a child position - alias for rebalance(0, child). This will also
flatten (close out all) the child's children.
Args:
* child (str): Child, specified by name. |
def _edit_main(self, request):
"""Adds the link to the new unit testing results on the repo's main wiki page.
"""
self.prefix = "{}_Pull_Request_{}".format(request.repo.name, request.pull.number)
if not self.testmode:
page = site.pages[self.basepage]
text = page.t... | Adds the link to the new unit testing results on the repo's main wiki page. |
def unfederate(self, serverId):
"""
This operation unfederates an ArcGIS Server from Portal for ArcGIS
"""
url = self._url + "/servers/{serverid}/unfederate".format(
serverid=serverId)
params = {"f" : "json"}
return self._get(url=url,
... | This operation unfederates an ArcGIS Server from Portal for ArcGIS |
def sentence_starts(self):
"""The list of start positions representing ``sentences`` layer elements."""
if not self.is_tagged(SENTENCES):
self.tokenize_sentences()
return self.starts(SENTENCES) | The list of start positions representing ``sentences`` layer elements. |
def stop_all(self, run_order=-1):
"""Runs stop method on all modules less than the passed-in run_order.
Used when target is exporting itself mid-build, so we clean up state
before committing run files etc.
"""
shutit_global.shutit_global_object.yield_to_draw()
# sort them so they're stopped in reverse order... | Runs stop method on all modules less than the passed-in run_order.
Used when target is exporting itself mid-build, so we clean up state
before committing run files etc. |
def append_faces(vertices_seq, faces_seq):
"""
Given a sequence of zero- indexed faces and vertices
combine them into a single array of faces and
a single array of vertices.
Parameters
-----------
vertices_seq : (n, ) sequence of (m, d) float
Multiple arrays of verticesvertex arrays
... | Given a sequence of zero- indexed faces and vertices
combine them into a single array of faces and
a single array of vertices.
Parameters
-----------
vertices_seq : (n, ) sequence of (m, d) float
Multiple arrays of verticesvertex arrays
faces_seq : (n, ) sequence of (p, j) int
Zero ... |
def transpose(vari):
"""
Transpose a shapeable quantety.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Quantety of interest.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Same type as ``vari``.
Examples:
>>> P = chaospy.reshape(chaospy.pra... | Transpose a shapeable quantety.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Quantety of interest.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Same type as ``vari``.
Examples:
>>> P = chaospy.reshape(chaospy.prange(4), (2,2))
>>> print(... |
def unregister(self, name, func):
"""
Remove a previously registered callback
:param str name: Hook name
:param callable func: A function reference\
that was registered previously
"""
try:
templatehook = self._registry[name]
except KeyError:
... | Remove a previously registered callback
:param str name: Hook name
:param callable func: A function reference\
that was registered previously |
def to_yellow(self, on: bool=False):
"""
Change the LED to yellow (on or off)
:param on: True or False
:return: None
"""
self._on = on
if on:
self._load_new(led_yellow_on)
if self._toggle_on_click:
self._canvas.bind('<Butto... | Change the LED to yellow (on or off)
:param on: True or False
:return: None |
def encrypt_with_caching(kms_cmk_arn, max_age_in_cache, cache_capacity):
"""Encrypts a string using an AWS KMS customer master key (CMK) and data key caching.
:param str kms_cmk_arn: Amazon Resource Name (ARN) of the KMS customer master key
:param float max_age_in_cache: Maximum time in seconds that a cach... | Encrypts a string using an AWS KMS customer master key (CMK) and data key caching.
:param str kms_cmk_arn: Amazon Resource Name (ARN) of the KMS customer master key
:param float max_age_in_cache: Maximum time in seconds that a cached entry can be used
:param int cache_capacity: Maximum number of entries to... |
def parse_tibiacom_content(content, *, html_class="BoxContent", tag="div", builder="lxml"):
"""Parses HTML content from Tibia.com into a BeautifulSoup object.
Parameters
----------
content: :class:`str`
The raw HTML content from Tibia.com
html_class: :class:`str`
The HTML class of t... | Parses HTML content from Tibia.com into a BeautifulSoup object.
Parameters
----------
content: :class:`str`
The raw HTML content from Tibia.com
html_class: :class:`str`
The HTML class of the parsed element. The default value is ``BoxContent``.
tag: :class:`str`
The HTML tag ... |
def get_and_order(self, ids, column=None, table=None):
"""Get specific entries and order them in the same way."""
command = """
SELECT rowid, * from "data"
WHERE rowid in (%s)
ORDER BY CASE rowid
%s
END;
"""
ordered = ','.join(map(str,ids))
... | Get specific entries and order them in the same way. |
def batch_for_variantcall(samples):
"""Prepare a set of samples for parallel variant calling.
CWL input target that groups samples into batches and variant callers
for parallel processing.
If doing joint calling, with `tools_on: [gvcf]`, split the sample into
individuals instead of combining into ... | Prepare a set of samples for parallel variant calling.
CWL input target that groups samples into batches and variant callers
for parallel processing.
If doing joint calling, with `tools_on: [gvcf]`, split the sample into
individuals instead of combining into a batch. |
def max_len(iterable, minimum=0):
"""Return the len() of the longest item in ``iterable`` or ``minimum``.
>>> max_len(['spam', 'ham'])
4
>>> max_len([])
0
>>> max_len(['ham'], 4)
4
"""
try:
result = max(map(len, iterable))
except ValueError:
result = minimum
... | Return the len() of the longest item in ``iterable`` or ``minimum``.
>>> max_len(['spam', 'ham'])
4
>>> max_len([])
0
>>> max_len(['ham'], 4)
4 |
def add(self, watch_key, tensor_value):
"""Add a tensor value.
Args:
watch_key: A string representing the debugger tensor watch, e.g.,
'Dense_1/BiasAdd:0:DebugIdentity'.
tensor_value: The value of the tensor as a numpy.ndarray.
"""
if watch_key not in self._tensor_data:
self._... | Add a tensor value.
Args:
watch_key: A string representing the debugger tensor watch, e.g.,
'Dense_1/BiasAdd:0:DebugIdentity'.
tensor_value: The value of the tensor as a numpy.ndarray. |
def _process_css_text(self, css_text, index, rules, head):
"""processes the given css_text by adding rules that can be
in-lined to the given rules list and adding any that cannot
be in-lined to the given `<head>` element.
"""
these_rules, these_leftover = self._parse_style_rules(... | processes the given css_text by adding rules that can be
in-lined to the given rules list and adding any that cannot
be in-lined to the given `<head>` element. |
def manifest(self, values, *paths, filename: str = None) -> Dict:
"""Load a manifest file and apply template values
"""
filename = filename or self.filename(*paths)
with open(filename, 'r') as fp:
template = Template(fp.read())
return yaml.load(template.render(values)... | Load a manifest file and apply template values |
def transpose(self, name=None):
"""Returns transpose batch reshape."""
if name is None:
name = self.module_name + "_transpose"
return BatchReshape(shape=lambda: self.input_shape,
preserve_dims=self._preserve_dims,
name=name) | Returns transpose batch reshape. |
def message_upperbound(self, tree, spins, subtheta):
"""Determine an upper bound on the energy of the elimination tree.
Args:
tree (dict): The current elimination tree
spins (dict): The current fixed spins
subtheta (dict): Theta with spins fixed.
Returns:
... | Determine an upper bound on the energy of the elimination tree.
Args:
tree (dict): The current elimination tree
spins (dict): The current fixed spins
subtheta (dict): Theta with spins fixed.
Returns:
The formula for the energy of the tree. |
def do_list_cap(self, line):
"""list_cap <peer>
"""
def f(p, args):
for i in p.netconf.server_capabilities:
print(i)
self._request(line, f) | list_cap <peer> |
def delete_record_set(self, record_set):
"""Append a record set to the 'deletions' for the change set.
:type record_set:
:class:`google.cloud.dns.resource_record_set.ResourceRecordSet`
:param record_set: the record set to append.
:raises: ``ValueError`` if ``record_set`` is... | Append a record set to the 'deletions' for the change set.
:type record_set:
:class:`google.cloud.dns.resource_record_set.ResourceRecordSet`
:param record_set: the record set to append.
:raises: ``ValueError`` if ``record_set`` is not of the required type. |
def match(self, messy_data, threshold=0.5, n_matches=1, generator=False): # pragma: no cover
"""Identifies pairs of records that refer to the same entity, returns
tuples containing a set of record ids and a confidence score as a float
between 0 and 1. The record_ids within each set should refer... | Identifies pairs of records that refer to the same entity, returns
tuples containing a set of record ids and a confidence score as a float
between 0 and 1. The record_ids within each set should refer to the
same entity and the confidence score is the estimated probability that
the record... |
def capture(cls, eval_env=0, reference=0):
"""Capture an execution environment from the stack.
If `eval_env` is already an :class:`EvalEnvironment`, it is returned
unchanged. Otherwise, we walk up the stack by ``eval_env + reference``
steps and capture that function's evaluation environm... | Capture an execution environment from the stack.
If `eval_env` is already an :class:`EvalEnvironment`, it is returned
unchanged. Otherwise, we walk up the stack by ``eval_env + reference``
steps and capture that function's evaluation environment.
For ``eval_env=0`` and ``reference=0``, t... |
def _parse_vars(self, tokens):
"""
Given an iterable of tokens, returns variables and their values as a
dictionary.
For example:
['dtap=prod', 'comment=some comment']
Returns:
{'dtap': 'prod', 'comment': 'some comment'}
"""
key_values = {}... | Given an iterable of tokens, returns variables and their values as a
dictionary.
For example:
['dtap=prod', 'comment=some comment']
Returns:
{'dtap': 'prod', 'comment': 'some comment'} |
def calc_b_value(magnitudes, completeness, max_mag=None, plotvar=True):
"""
Calculate the b-value for a range of completeness magnitudes.
Calculates a power-law fit to given magnitudes for each completeness
magnitude. Plots the b-values and residuals for the fitted catalogue
against the completene... | Calculate the b-value for a range of completeness magnitudes.
Calculates a power-law fit to given magnitudes for each completeness
magnitude. Plots the b-values and residuals for the fitted catalogue
against the completeness values. Computes fits using numpy.polyfit,
which uses a least-squares techniq... |
def setDefaultThread(self, thread_id, thread_type):
"""
Sets default thread to send messages to
:param thread_id: User/Group ID to default to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType
"""
self._def... | Sets default thread to send messages to
:param thread_id: User/Group ID to default to. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
:type thread_type: models.ThreadType |
def _db(self):
"""Database client for accessing storage.
:returns: :class:`livebridge.storages.base.BaseStorage` """
if not hasattr(self, "_db_client") or getattr(self, "_db_client") is None:
self._db_client = get_db_client()
return self._db_client | Database client for accessing storage.
:returns: :class:`livebridge.storages.base.BaseStorage` |
def home_abbreviation(self):
"""
Returns a ``string`` of the home team's abbreviation, such as 'KAN'.
"""
abbr = re.sub(r'.*/teams/', '', str(self._home_name))
abbr = re.sub(r'/.*', '', abbr)
return abbr | Returns a ``string`` of the home team's abbreviation, such as 'KAN'. |
def _get_key_value(string):
"""Return the (key, value) as a tuple from a string."""
# Normally all properties look like this:
# Unique Identifier: 600508B1001CE4ACF473EE9C826230FF
# Disk Name: /dev/sda
# Mount Points: None
key = ''
value = ''
try:
key, value = string.split(... | Return the (key, value) as a tuple from a string. |
def keyboard(self, default=None, heading=None, hidden=False):
'''Displays the keyboard input window to the user. If the user does not
cancel the modal, the value entered by the user will be returned.
:param default: The placeholder text used to prepopulate the input field.
:param headin... | Displays the keyboard input window to the user. If the user does not
cancel the modal, the value entered by the user will be returned.
:param default: The placeholder text used to prepopulate the input field.
:param heading: The heading for the window. Defaults to the current
... |
def run_steps_from_string(self, spec, language_name='en'):
""" Called from within step definitions to run other steps. """
caller = inspect.currentframe().f_back
line = caller.f_lineno - 1
fname = caller.f_code.co_filename
steps = parse_steps(spec, fname, line, ... | Called from within step definitions to run other steps. |
def relabel(self, label=None, group=None, depth=1):
"""Clone object and apply new group and/or label.
Applies relabeling to children up to the supplied depth.
Args:
label (str, optional): New label to apply to returned object
group (str, optional): New group to apply to... | Clone object and apply new group and/or label.
Applies relabeling to children up to the supplied depth.
Args:
label (str, optional): New label to apply to returned object
group (str, optional): New group to apply to returned object
depth (int, optional): Depth to wh... |
def paint( self, painter, option, widget ):
"""
Paints this item on the painter.
:param painter | <QPainter>
option | <QStyleOptionGraphicsItem>
widget | <QWidget>
"""
if ( self._rebuildRequired ):
self.... | Paints this item on the painter.
:param painter | <QPainter>
option | <QStyleOptionGraphicsItem>
widget | <QWidget> |
def find_mismatch(self, other, indent=''):
"""
Used in debugging unittests
"""
mismatch = super(Tree, self).find_mismatch(other, indent)
sub_indent = indent + ' '
if len(list(self.subjects)) != len(list(other.subjects)):
mismatch += ('\n{indent}mismatching su... | Used in debugging unittests |
def update(self):
"""Update the FS stats using the input method."""
# Init new stats
stats = self.get_init_value()
if self.input_method == 'local':
# Update stats using the standard system lib
# Grab the stats using the psutil disk_partitions
# If 'a... | Update the FS stats using the input method. |
def verify_url(url, secret_key, **kwargs):
"""
Verify a signed URL (excluding the domain and scheme).
:param url: URL to sign
:param secret_key: Secret key
:rtype: bool
:raises: URLError
"""
result = urlparse(url)
query_args = MultiValueDict(parse_qs(result.query))
return verif... | Verify a signed URL (excluding the domain and scheme).
:param url: URL to sign
:param secret_key: Secret key
:rtype: bool
:raises: URLError |
def parse_GFF_attribute_string(attrStr, extra_return_first_value=False):
"""Parses a GFF attribute string and returns it as a dictionary.
If 'extra_return_first_value' is set, a pair is returned: the dictionary
and the value of the first attribute. This might be useful if this is the
ID.
"""
if... | Parses a GFF attribute string and returns it as a dictionary.
If 'extra_return_first_value' is set, a pair is returned: the dictionary
and the value of the first attribute. This might be useful if this is the
ID. |
def push_external_commands(self, commands):
"""Send a HTTP request to the satellite (POST /r_un_external_commands)
to send the external commands to the satellite
:param results: Results list to send
:type results: list
:return: True on success, False on failure
:rtype: b... | Send a HTTP request to the satellite (POST /r_un_external_commands)
to send the external commands to the satellite
:param results: Results list to send
:type results: list
:return: True on success, False on failure
:rtype: bool |
def get_or_none(cls, mp, part_number):
"""Get part number."""
return cls.query.filter_by(
upload_id=mp.upload_id,
part_number=part_number
).one_or_none() | Get part number. |
async def release_forks(self, philosopher):
'''The ``philosopher`` has just eaten and is ready to release both
forks.
This method releases them, one by one, by sending the ``put_down``
action to the monitor.
'''
forks = self.forks
self.forks = []
self.sta... | The ``philosopher`` has just eaten and is ready to release both
forks.
This method releases them, one by one, by sending the ``put_down``
action to the monitor. |
def p_expr_BXOR_expr(p):
""" expr : expr BXOR expr
"""
p[0] = make_binary(p.lineno(2), 'BXOR', p[1], p[3], lambda x, y: x ^ y) | expr : expr BXOR expr |
def copy_reference(resource, doc, env, *args, **kwargs):
"""A row-generating function that yields from a reference. This permits an upstream package to be
copied and modified by this package, while being formally referenced as a dependency
The function will generate rows from a reference that has the same ... | A row-generating function that yields from a reference. This permits an upstream package to be
copied and modified by this package, while being formally referenced as a dependency
The function will generate rows from a reference that has the same name as the resource term |
def pin_rm(self, path, *paths, **kwargs):
"""Removes a pinned object from local storage.
Removes the pin from the given object allowing it to be garbage
collected if needed.
.. code-block:: python
>>> c.pin_rm('QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d')
{... | Removes a pinned object from local storage.
Removes the pin from the given object allowing it to be garbage
collected if needed.
.. code-block:: python
>>> c.pin_rm('QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d')
{'Pins': ['QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyG... |
def property(func):
"""Wrap a function as a property.
This differs from attribute by identifying properties explicitly listed
in the class definition rather than named attributes defined on instances
of a class at init time.
"""
attr = abc.abstractmethod(func)
attr.__iproperty__ = True
... | Wrap a function as a property.
This differs from attribute by identifying properties explicitly listed
in the class definition rather than named attributes defined on instances
of a class at init time. |
def weekend_to_monday(dt):
"""
If holiday falls on Sunday or Saturday,
use day thereafter (Monday) instead.
Needed for holidays such as Christmas observation in Europe
"""
if dt.weekday() == 6:
return dt + timedelta(1)
elif dt.weekday() == 5:
return dt + timedelta(2)
retu... | If holiday falls on Sunday or Saturday,
use day thereafter (Monday) instead.
Needed for holidays such as Christmas observation in Europe |
def _parseCounters(self, data):
"""Parse simple stats list of key, value pairs.
@param data: Multiline data with one key-value pair in each line.
@return: Dictionary of stats.
"""
info_dict = util.NestedDict()
for line in data.splitlines():
... | Parse simple stats list of key, value pairs.
@param data: Multiline data with one key-value pair in each line.
@return: Dictionary of stats. |
def sign_with_privkey(
digest: bytes,
privkey: Ed25519PrivateKey,
global_pubkey: Ed25519PublicPoint,
nonce: int,
global_commit: Ed25519PublicPoint,
) -> Ed25519Signature:
"""Create a CoSi signature of `digest` with the supplied private key.
This function needs to know the global public key a... | Create a CoSi signature of `digest` with the supplied private key.
This function needs to know the global public key and global commitment. |
def rmsd_eval(rmsd_params):
"""Builds a model and runs profit against a reference model.
Parameters
----------
rmsd_params
Returns
-------
rmsd: float
rmsd against reference model as calculated by profit.
"""
specification, sequence, parsed_ind, reference_pdb = rmsd_params
... | Builds a model and runs profit against a reference model.
Parameters
----------
rmsd_params
Returns
-------
rmsd: float
rmsd against reference model as calculated by profit. |
def undo_sign_out(entry, session=None):
"""Sign in a signed out entry.
:param entry: `models.Entry` object. The entry to sign back in.
:param session: (optional) SQLAlchemy session through which to access the database.
""" # noqa
if session is None:
session = Session()
else:
ses... | Sign in a signed out entry.
:param entry: `models.Entry` object. The entry to sign back in.
:param session: (optional) SQLAlchemy session through which to access the database. |
def censor_entity_types(self, entity_types):
# type: (set) -> TermDocMatrixFactory
'''
Entity types to exclude from feature construction. Terms matching
specificed entities, instead of labeled by their lower case orthographic
form or lemma, will be labeled by their entity type.
... | Entity types to exclude from feature construction. Terms matching
specificed entities, instead of labeled by their lower case orthographic
form or lemma, will be labeled by their entity type.
Parameters
----------
entity_types : set of entity types outputted by spaCy
'... |
def create_append(filename: str, layers: Union[np.ndarray, Dict[str, np.ndarray], loompy.LayerManager], row_attrs: Dict[str, np.ndarray], col_attrs: Dict[str, np.ndarray], *, file_attrs: Dict[str, str] = None, fill_values: Dict[str, np.ndarray] = None) -> None:
"""
**DEPRECATED** - Use `new` instead; see https://gith... | **DEPRECATED** - Use `new` instead; see https://github.com/linnarsson-lab/loompy/issues/42 |
def AppendSource(self, type_indicator, attributes):
"""Appends a source.
If you want to implement your own source type you should create a subclass
in source_type.py and change the AppendSource method to handle the new
subclass. This function raises FormatError if an unsupported source type
indicat... | Appends a source.
If you want to implement your own source type you should create a subclass
in source_type.py and change the AppendSource method to handle the new
subclass. This function raises FormatError if an unsupported source type
indicator is encountered.
Args:
type_indicator (str): s... |
def drain(self):
"""
Read until there is nothing more to be read. Only intended for test code/debugging!
@returns: True on success
@rtype: bool
"""
try:
unlock = self.stick.acquire()
return self.stick.drain()
finally:
unlock() | Read until there is nothing more to be read. Only intended for test code/debugging!
@returns: True on success
@rtype: bool |
def set_bucket_props(self, transport, bucket, props):
"""
set_bucket_props(bucket, props)
Sets bucket properties for the given bucket.
.. note:: This request is automatically retried :attr:`retries`
times if it fails due to network error.
:param bucket: the bucket w... | set_bucket_props(bucket, props)
Sets bucket properties for the given bucket.
.. note:: This request is automatically retried :attr:`retries`
times if it fails due to network error.
:param bucket: the bucket whose properties will be set
:type bucket: RiakBucket
:para... |
def poll_devices(self):
"""Request status updates from each device."""
for addr in self.devices:
device = self.devices[addr]
if not device.address.is_x10:
device.async_refresh_state() | Request status updates from each device. |
def get_value_as_list(self, dictionary, key):
"""Helper function to check and convert a value to list.
Helper function to check and convert a value to json list.
This helps the ribcl data to be generalized across the servers.
:param dictionary: a dictionary to check in if key is presen... | Helper function to check and convert a value to list.
Helper function to check and convert a value to json list.
This helps the ribcl data to be generalized across the servers.
:param dictionary: a dictionary to check in if key is present.
:param key: key to be checked if thats present... |
def _get_indicators(modules):
"""For all modules or classes listed, return the children that are instances of xclim.utils.Indicator.
modules : sequence
Sequence of modules to inspect.
"""
out = []
for obj in modules:
for key, val in obj.__dict__.items():
if isinstance(val,... | For all modules or classes listed, return the children that are instances of xclim.utils.Indicator.
modules : sequence
Sequence of modules to inspect. |
def Wm(self):
"""Return the smoothing regularization matrix Wm of the grid
"""
centroids = self.get_element_centroids()
Wm = scipy.sparse.csr_matrix(
(self.nr_of_elements, self.nr_of_elements))
# Wm = np.zeros((self.nr_of_elements, self.nr_of_elements))
for ... | Return the smoothing regularization matrix Wm of the grid |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.