code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def iteritems(self):
r"""
Iterator over (column name, Series) pairs.
Iterates over the DataFrame columns, returning a tuple with
the column name and the content as a Series.
Yields
------
label : object
The column names for the DataFrame being iterat... | r"""
Iterator over (column name, Series) pairs.
Iterates over the DataFrame columns, returning a tuple with
the column name and the content as a Series.
Yields
------
label : object
The column names for the DataFrame being iterated over.
content : Se... |
def saturation_equivalent_potential_temperature(pressure, temperature):
r"""Calculate saturation equivalent potential temperature.
This calculation must be given an air parcel's pressure and temperature.
The implementation uses the formula outlined in [Bolton1980]_ for the
equivalent potential temperat... | r"""Calculate saturation equivalent potential temperature.
This calculation must be given an air parcel's pressure and temperature.
The implementation uses the formula outlined in [Bolton1980]_ for the
equivalent potential temperature, and assumes a saturated process.
First, because we assume a satura... |
def get_config_parameter_loglevel(config: ConfigParser,
section: str,
param: str,
default: int) -> int:
"""
Get ``loglevel`` parameter from ``configparser`` ``.INI`` file, e.g.
mapping ``'debug'`` to ``logg... | Get ``loglevel`` parameter from ``configparser`` ``.INI`` file, e.g.
mapping ``'debug'`` to ``logging.DEBUG``.
Args:
config: :class:`ConfigParser` object
section: section name within config file
param: name of parameter within section
default: default value
Returns:
... |
def decr(self, field, by=1):
""" :see::meth:RedisMap.decr """
return self._client.hincrby(self.key_prefix, field, by * -1) | :see::meth:RedisMap.decr |
def get_file_checksum(path):
"""Get the checksum of a file (using ``sum``, Unix-only).
This function is only available on certain platforms.
Parameters
----------
path: str
The path of the file.
Returns
-------
int
The checksum.
Raises
------
IOError
... | Get the checksum of a file (using ``sum``, Unix-only).
This function is only available on certain platforms.
Parameters
----------
path: str
The path of the file.
Returns
-------
int
The checksum.
Raises
------
IOError
If the file does not exist. |
def match(self, ra1, dec1, ra2, dec2, radius, maxmatch=1, convertToArray=True):
"""*Crossmatch two lists of ra/dec points*
This is very efficient for large search angles and large lists. Note, if you need to match against the same points many times, you should use a `Matcher` object
**Key Argu... | *Crossmatch two lists of ra/dec points*
This is very efficient for large search angles and large lists. Note, if you need to match against the same points many times, you should use a `Matcher` object
**Key Arguments:**
- ``ra1`` -- list, numpy array or single ra value (first coordinate se... |
def add_dimension(dimension,**kwargs):
"""
Add the dimension defined into the object "dimension" to the DB
If dimension["project_id"] is None it means that the dimension is global, otherwise is property of a project
If the dimension exists emits an exception
"""
if numpy.isscalar(dim... | Add the dimension defined into the object "dimension" to the DB
If dimension["project_id"] is None it means that the dimension is global, otherwise is property of a project
If the dimension exists emits an exception |
def get_version(model_instance, version):
"""
try go load from the database one object with specific version
:param model_instance: instance in memory
:param version: version number
:return:
"""
version_field = get_version_fieldname(model_instance)
kwargs = {'pk': model_instance.pk,... | try go load from the database one object with specific version
:param model_instance: instance in memory
:param version: version number
:return: |
def get_learning_path_session_for_objective_bank(self, objective_bank_id=None):
"""Gets the OsidSession associated with the learning path service
for the given objective bank.
arg: objectiveBankId (osid.id.Id): the Id of the
ObjectiveBank
return: (osid.learning.Learni... | Gets the OsidSession associated with the learning path service
for the given objective bank.
arg: objectiveBankId (osid.id.Id): the Id of the
ObjectiveBank
return: (osid.learning.LearningPathSession) - a
LearningPathSession
raise: NotFound - no object... |
def fnmatch( name, pat ):
"""Test whether FILENAME matches PATTERN.
Patterns are Unix shell style:
* matches everything
? matches any single character
[seq] matches any character in seq
[!seq] matches any char not in seq
An initial period in FILENAME is not special.
Bot... | Test whether FILENAME matches PATTERN.
Patterns are Unix shell style:
* matches everything
? matches any single character
[seq] matches any character in seq
[!seq] matches any char not in seq
An initial period in FILENAME is not special.
Both FILENAME and PATTERN are first ... |
def word_wrap(self):
"""
Read-write setting determining whether lines of text in this shape
are wrapped to fit within the shape's width. Valid values are True,
False, or None. True and False turn word wrap on and off,
respectively. Assigning None to word wrap causes any word wrap... | Read-write setting determining whether lines of text in this shape
are wrapped to fit within the shape's width. Valid values are True,
False, or None. True and False turn word wrap on and off,
respectively. Assigning None to word wrap causes any word wrap
setting to be removed from the t... |
def add_to_inventory(self):
"""Adds host to stack inventory"""
if not self.server_attrs:
return
for addy in self.server_attrs[A.server.PUBLIC_IPS]:
self.stack.add_host(addy, self.groups, self.hostvars) | Adds host to stack inventory |
def clear(self):
"""Clears the cache."""
if self._cache is None:
return _NO_RESULTS
if self._cache is not None:
with self._cache as k:
res = [x.as_operation() for x in k.values()]
k.clear()
k.out_deque.clear()
... | Clears the cache. |
def bind_rows(df, other, join='outer', ignore_index=False):
"""
Binds DataFrames "vertically", stacking them together. This is equivalent
to `pd.concat` with `axis=0`.
Args:
df (pandas.DataFrame): Top DataFrame (passed in via pipe).
other (pandas.DataFrame): Bottom DataFrame.
Kwarg... | Binds DataFrames "vertically", stacking them together. This is equivalent
to `pd.concat` with `axis=0`.
Args:
df (pandas.DataFrame): Top DataFrame (passed in via pipe).
other (pandas.DataFrame): Bottom DataFrame.
Kwargs:
join (str): One of `"outer"` or `"inner"`. Outer join will pr... |
def _get_installed(self):
"""Gets a list of the file paths to repo settings files that are
being monitored by the CI server.
"""
from utility import get_json
#This is a little tricky because the data file doesn't just have a list
#of installed servers. It also manages the... | Gets a list of the file paths to repo settings files that are
being monitored by the CI server. |
def to_file(self, f, sorted=True, relativize=True, nl=None):
"""Write a zone to a file.
@param f: file or string. If I{f} is a string, it is treated
as the name of a file to open.
@param sorted: if True, the file will be written with the
names sorted in DNSSEC order from least ... | Write a zone to a file.
@param f: file or string. If I{f} is a string, it is treated
as the name of a file to open.
@param sorted: if True, the file will be written with the
names sorted in DNSSEC order from least to greatest. Otherwise
the names will be written in whatever or... |
def AddAnalogShortIdRecordNoStatus(site_service, tag, time_value, value):
"""
This function will add an analog value to the specified eDNA service and
tag, without an associated point status.
:param site_service: The site.service where data will be pushed
:param tag: The eDNA tag to push data. Tag ... | This function will add an analog value to the specified eDNA service and
tag, without an associated point status.
:param site_service: The site.service where data will be pushed
:param tag: The eDNA tag to push data. Tag only (e.g. ADE1CA01)
:param time_value: The time of the point, which MUST be in UT... |
def _onIdle(self, evt):
'a GUI idle event'
evt.Skip()
FigureCanvasBase.idle_event(self, guiEvent=evt) | a GUI idle event |
def printUniqueTFAM(tfam, samples, prefix):
"""Prints a new TFAM with only unique samples.
:param tfam: a representation of a TFAM file.
:param samples: the position of the samples
:param prefix: the prefix of the output file name
:type tfam: list
:type samples: dict
:type prefix: str
... | Prints a new TFAM with only unique samples.
:param tfam: a representation of a TFAM file.
:param samples: the position of the samples
:param prefix: the prefix of the output file name
:type tfam: list
:type samples: dict
:type prefix: str |
def wait_for(self, timeout=None, **kwargs):
"""Wait for a specific matching message or timeout.
You specify the message by passing name=value keyword arguments to
this method. The first message received after this function has been
called that has all of the given keys with the given v... | Wait for a specific matching message or timeout.
You specify the message by passing name=value keyword arguments to
this method. The first message received after this function has been
called that has all of the given keys with the given values will be
returned when this function is aw... |
def ast_to_html(self, ast, link_resolver):
"""
See the documentation of `to_ast` for
more information.
Args:
ast: PyCapsule, a capsule as returned by `to_ast`
link_resolver: hotdoc.core.links.LinkResolver, a link
resolver instance.
"""
... | See the documentation of `to_ast` for
more information.
Args:
ast: PyCapsule, a capsule as returned by `to_ast`
link_resolver: hotdoc.core.links.LinkResolver, a link
resolver instance. |
def cache_status(db, aid, force=False):
"""Calculate and cache status for given anime.
Don't do anything if status already exists and force is False.
"""
with db:
cur = db.cursor()
if not force:
# We don't do anything if we already have this aid in our
# cache.
... | Calculate and cache status for given anime.
Don't do anything if status already exists and force is False. |
def set_experiment_winner(experiment):
"""Mark an alternative as the winner of the experiment."""
redis = _get_redis_connection()
experiment = Experiment.find(redis, experiment)
if experiment:
alternative_name = request.form.get('alternative')
alternative = Alternative(redis, alternative... | Mark an alternative as the winner of the experiment. |
def cov_from_scales(self, scales):
"""Return a covariance matrix built from a dictionary of scales.
`scales` is a dictionary keyed by stochastic instances, and the
values refer are the variance of the jump distribution for each
stochastic. If a stochastic is a sequence, the variance mus... | Return a covariance matrix built from a dictionary of scales.
`scales` is a dictionary keyed by stochastic instances, and the
values refer are the variance of the jump distribution for each
stochastic. If a stochastic is a sequence, the variance must
have the same length. |
def _compute_fluxes(self):
"""
Compute integrated flux inside ellipse, as well as inside a
circle defined with the same semimajor axis.
Pixels in a square section enclosing circle are scanned; the
distance of each pixel to the isophote center is compared both
with the se... | Compute integrated flux inside ellipse, as well as inside a
circle defined with the same semimajor axis.
Pixels in a square section enclosing circle are scanned; the
distance of each pixel to the isophote center is compared both
with the semimajor axis length and with the length of the
... |
def get_inventory(self):
""" Request the api endpoint to retrieve information about the inventory
:return: Main Collection
:rtype: Collection
"""
if self._inventory is not None:
return self._inventory
self._inventory = self.resolver.getMetadata()
ret... | Request the api endpoint to retrieve information about the inventory
:return: Main Collection
:rtype: Collection |
def _parse(cls, scope):
"""Parses the input scope into a normalized set of strings.
:param scope: A string or tuple containing zero or more scope names.
:return: A set of scope name strings, or a tuple with the default scope name.
:rtype: set
"""
if not scope:
return ('default',)
if i... | Parses the input scope into a normalized set of strings.
:param scope: A string or tuple containing zero or more scope names.
:return: A set of scope name strings, or a tuple with the default scope name.
:rtype: set |
def api_notifications():
"""Receive MTurk REST notifications."""
event_type = request.values['Event.1.EventType']
assignment_id = request.values['Event.1.AssignmentId']
# Add the notification to the queue.
db.logger.debug('rq: Queueing %s with id: %s for worker_function',
event_... | Receive MTurk REST notifications. |
def info(self, correlation_id, message, *args, **kwargs):
"""
Logs an important information message
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param message: a human-readable message to log.
:param args: arguments to parameterize t... | Logs an important information message
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param message: a human-readable message to log.
:param args: arguments to parameterize the message.
:param kwargs: arguments to parameterize the message. |
def morph(clm1, clm2, t, lmax):
"""Interpolate linearly the two sets of sph harm. coeeficients."""
clm = (1 - t) * clm1 + t * clm2
grid_reco = clm.expand(lmax=lmax) # cut "high frequency" components
agrid_reco = grid_reco.to_array()
pts = []
for i, longs in enumerate(agrid_reco):
ilat =... | Interpolate linearly the two sets of sph harm. coeeficients. |
def transform_doc_comments(text):
"""
Parse XML content for references and other syntax.
This avoids an LXML dependency, we only need to parse out a small subset
of elements here. Iterate over string to reduce regex pattern complexity
and make substitutions easier
.. se... | Parse XML content for references and other syntax.
This avoids an LXML dependency, we only need to parse out a small subset
of elements here. Iterate over string to reduce regex pattern complexity
and make substitutions easier
.. seealso::
`Doc comment reference <https://m... |
def chmod(self, path, mode, follow_symlinks=True):
"""Change the permissions of a file as encoded in integer mode.
Args:
path: (str) Path to the file.
mode: (int) Permissions.
follow_symlinks: If `False` and `path` points to a symlink,
the link itself... | Change the permissions of a file as encoded in integer mode.
Args:
path: (str) Path to the file.
mode: (int) Permissions.
follow_symlinks: If `False` and `path` points to a symlink,
the link itself is affected instead of the linked object. |
def parse_variant_id(chrom, pos, ref, alt, variant_type):
"""Parse the variant id for a variant
variant_id is used to identify variants within a certain type of
analysis. It is not human readable since it is a md5 key.
Args:
chrom(str)
pos(str)
ref(str)
alt(str)
... | Parse the variant id for a variant
variant_id is used to identify variants within a certain type of
analysis. It is not human readable since it is a md5 key.
Args:
chrom(str)
pos(str)
ref(str)
alt(str)
variant_type(str): 'clinical' or 'research'
Returns:
... |
def ucc_circuit(theta):
"""
Implements
exp(-i theta X_{0}Y_{1})
:param theta: rotation parameter
:return: pyquil.Program
"""
generator = sX(0) * sY(1)
initial_prog = Program().inst(X(1), X(0))
# compiled program
program = initial_prog + exponentiate(float(theta) * generator) ... | Implements
exp(-i theta X_{0}Y_{1})
:param theta: rotation parameter
:return: pyquil.Program |
def add_func_edges(dsp, fun_id, nodes_bunch, edge_weights=None, input=True,
data_nodes=None):
"""
Adds function node edges.
:param dsp:
A dispatcher that identifies the model adopted.
:type dsp: schedula.Dispatcher
:param fun_id:
Function node id.
:type fun_i... | Adds function node edges.
:param dsp:
A dispatcher that identifies the model adopted.
:type dsp: schedula.Dispatcher
:param fun_id:
Function node id.
:type fun_id: str
:param nodes_bunch:
A container of nodes which will be iterated through once.
:type nodes_bunch: iter... |
def _insert_lcl_level(pressure, temperature, lcl_pressure):
"""Insert the LCL pressure into the profile."""
interp_temp = interpolate_1d(lcl_pressure, pressure, temperature)
# Pressure needs to be increasing for searchsorted, so flip it and then convert
# the index back to the original array
loc = ... | Insert the LCL pressure into the profile. |
def instantiate(self, **extra_args):
""" Instantiate the model """
input_block = self.input_block.instantiate()
backbone = self.backbone.instantiate(**extra_args)
return StochasticPolicyModel(input_block, backbone, extra_args['action_space']) | Instantiate the model |
def iterstruct(self):
"""Yield data structures built from the JSON header specifications in a table"""
from rowgenerators.rowpipe.json import add_to_struct
json_headers = self.json_headers
for row in islice(self, 1, None): # islice skips header
d = {}
for pos, j... | Yield data structures built from the JSON header specifications in a table |
def channel2int(channel):
"""Try to convert the channel to an integer.
:param channel:
Channel string (e.g. can0, CAN1) or integer
:returns: Channel integer or `None` if unsuccessful
:rtype: int
"""
if channel is None:
return None
if isinstance(channel, int):
re... | Try to convert the channel to an integer.
:param channel:
Channel string (e.g. can0, CAN1) or integer
:returns: Channel integer or `None` if unsuccessful
:rtype: int |
def z_axis_rotation(theta):
"""Generates a 3x3 rotation matrix for a rotation of angle
theta about the z axis.
Parameters
----------
theta : float
amount to rotate, in radians
Returns
-------
:obj:`numpy.ndarray` of float
A random... | Generates a 3x3 rotation matrix for a rotation of angle
theta about the z axis.
Parameters
----------
theta : float
amount to rotate, in radians
Returns
-------
:obj:`numpy.ndarray` of float
A random 3x3 rotation matrix. |
def parsemeta(metadataloc):
"""Parses the metadata from a Landsat image bundle.
Arguments:
metadataloc: a filename or a directory.
Returns metadata dictionary
"""
# filename or directory? if several fit, use first one and warn
if os.path.isdir(metadataloc):
me... | Parses the metadata from a Landsat image bundle.
Arguments:
metadataloc: a filename or a directory.
Returns metadata dictionary |
def get_file_language(self, file):
"""
Returns the language of given file.
:param file: File to get language of.
:type file: unicode
:return: File language.
:rtype: Language
"""
for language in self.__languages:
if re.search(language.extensio... | Returns the language of given file.
:param file: File to get language of.
:type file: unicode
:return: File language.
:rtype: Language |
def set_col_width(self, col, tab, width):
"""Sets column width"""
try:
old_width = self.col_widths.pop((col, tab))
except KeyError:
old_width = None
if width is not None:
self.col_widths[(col, tab)] = float(width) | Sets column width |
def _set_and_filter(self):
"""Filters the registered updates and sort out what is not needed
This method filters out the formatoptions that have not changed, sets
the new value and returns an iterable that is sorted by the priority
(highest priority comes first) and dependencies
... | Filters the registered updates and sort out what is not needed
This method filters out the formatoptions that have not changed, sets
the new value and returns an iterable that is sorted by the priority
(highest priority comes first) and dependencies
Returns
-------
list... |
def get_or_create(cls, name):
"""
Return the instance of the class with the specified name. If it doesn't
already exist, create it.
"""
obj = cls.query.filter_by(name=name).one_or_none()
if obj:
return obj
try:
with session.begin_nested():
... | Return the instance of the class with the specified name. If it doesn't
already exist, create it. |
def _set_motion_detection(self, enable):
"""Set desired motion detection state on camera"""
url = ('%s/ISAPI/System/Video/inputs/'
'channels/1/motionDetection') % self.root_url
enabled = self._motion_detection_xml.find(self.element_query('enabled'))
if enabled is None:
... | Set desired motion detection state on camera |
def page_missing(request, page_name, revision_requested, protected=False):
"""Displayed if page or revision does not exist."""
return Response(
generate_template(
"page_missing.html",
page_name=page_name,
revision_requested=revision_requested,
protected=pr... | Displayed if page or revision does not exist. |
def load_ensembl_coverage(cohort, coverage_path, min_tumor_depth, min_normal_depth=0,
pageant_dir_fn=None):
"""
Load in Pageant CoverageDepth results with Ensembl loci.
coverage_path is a path to Pageant CoverageDepth output directory, with
one subdirectory per patient and a `... | Load in Pageant CoverageDepth results with Ensembl loci.
coverage_path is a path to Pageant CoverageDepth output directory, with
one subdirectory per patient and a `cdf.csv` file inside each patient subdir.
If min_normal_depth is 0, calculate tumor coverage. Otherwise, calculate
join tumor/normal cove... |
def Match(self, artifact=None, os_name=None, cpe=None, label=None):
"""Test if host data should trigger a check.
Args:
artifact: An artifact name.
os_name: An OS string.
cpe: A CPE string.
label: A label string.
Returns:
A list of conditions that match.
"""
return [
... | Test if host data should trigger a check.
Args:
artifact: An artifact name.
os_name: An OS string.
cpe: A CPE string.
label: A label string.
Returns:
A list of conditions that match. |
def export(self, filepath, encoding="utf-8", gzipped=True):
""" Export the word frequency list for import in the future
Args:
filepath (str): The filepath to the exported dictionary
encoding (str): The encoding of the resulting output
gzipped (bool):... | Export the word frequency list for import in the future
Args:
filepath (str): The filepath to the exported dictionary
encoding (str): The encoding of the resulting output
gzipped (bool): Whether to gzip the dictionary or not |
def app_versions(self):
"""List of the versions of the internal KE-chain 'app' modules."""
if not self._app_versions:
app_versions_url = self._build_url('versions')
response = self._request('GET', app_versions_url)
if response.status_code == requests.codes.not_found... | List of the versions of the internal KE-chain 'app' modules. |
def update_progress(opts, progress, progress_iter, out):
'''
Update the progress iterator for the given outputter
'''
# Look up the outputter
try:
progress_outputter = salt.loader.outputters(opts)[out]
except KeyError: # Outputter is not loaded
log.warning('Progress outputter no... | Update the progress iterator for the given outputter |
def summed_probabilities(self, choosers, alternatives):
"""
Returns the sum of probabilities for alternatives across all
chooser segments.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
... | Returns the sum of probabilities for alternatives across all
chooser segments.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
Must have a column matching the .segmentation_col attribute.
alte... |
def vsound(H):
"""Speed of sound"""
T = temperature(H)
a = np.sqrt(gamma * R * T)
return a | Speed of sound |
def open_tablebase(directory: PathLike, *, libgtb: Any = None, LibraryLoader: Any = ctypes.cdll) -> Union[NativeTablebase, PythonTablebase]:
"""
Opens a collection of tables for probing.
First native access via the shared library libgtb is tried. You can
optionally provide a specific library name or a ... | Opens a collection of tables for probing.
First native access via the shared library libgtb is tried. You can
optionally provide a specific library name or a library loader.
The shared library has global state and caches, so only one instance can
be open at a time.
Second, pure Python probing code... |
def get_phonetic_info(self, lang):
"""For a specified language (lang), it returns the matrix and the vecto
containing specifications of the characters.
"""
phonetic_data = self.all_phonetic_data if lang != LC_TA else self.tamil_phonetic_data
phonetic_vectors = self.all_phonetic... | For a specified language (lang), it returns the matrix and the vecto
containing specifications of the characters. |
def keys_to_datetime(obj, *keys):
""" Converts all the keys in an object to DateTime instances.
Args:
obj (dict): the JSON-like ``dict`` object to modify inplace.
keys (str): keys of the object being converted into DateTime
instances.
Returns:
di... | Converts all the keys in an object to DateTime instances.
Args:
obj (dict): the JSON-like ``dict`` object to modify inplace.
keys (str): keys of the object being converted into DateTime
instances.
Returns:
dict: ``obj`` inplace.
>>> keys_to_... |
def get_ready_user_tasks(self):
"""
Returns a list of User Tasks that are READY for user action
"""
return [t for t in self.get_tasks(Task.READY)
if not self._is_engine_task(t.task_spec)] | Returns a list of User Tasks that are READY for user action |
def create_shepherd_tour(self, name=None, theme=None):
""" Creates a Shepherd JS website tour.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
theme - Sets the default theme for the tour.
... | Creates a Shepherd JS website tour.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
theme - Sets the default theme for the tour.
Choose from "light"/"arrows", "dark", "default", "... |
def loc_info(text, index):
'''Location of `index` in source code `text`.'''
if index > len(text):
raise ValueError('Invalid index.')
line, last_ln = text.count('\n', 0, index), text.rfind('\n', 0, index)
col = index - (last_ln + 1)
return (line, col) | Location of `index` in source code `text`. |
def enqueue(self, message, *, delay=None):
"""Enqueue a message.
Parameters:
message(Message): The message to enqueue.
delay(int): The minimum amount of time, in milliseconds, to
delay the message by. Must be less than 7 days.
Raises:
ValueError: If `... | Enqueue a message.
Parameters:
message(Message): The message to enqueue.
delay(int): The minimum amount of time, in milliseconds, to
delay the message by. Must be less than 7 days.
Raises:
ValueError: If ``delay`` is longer than 7 days. |
def pgrrec(body, lon, lat, alt, re, f):
"""
Convert planetographic coordinates to rectangular coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pgrrec_c.html
:param body: Body with which coordinate system is associated.
:type body: str
:param lon: Planetographic longitude of... | Convert planetographic coordinates to rectangular coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pgrrec_c.html
:param body: Body with which coordinate system is associated.
:type body: str
:param lon: Planetographic longitude of a point (radians).
:type lon: float
:param ... |
def from_collection_xml(cls, xml_content):
"""Build a :class:`~zenodio.harvest.Datacite3Collection` from
Datecite3-formatted XML.
Users should use :func:`zenodio.harvest.harvest_collection` to build a
:class:`~zenodio.harvest.Datacite3Collection` for a Community.
Parameters
... | Build a :class:`~zenodio.harvest.Datacite3Collection` from
Datecite3-formatted XML.
Users should use :func:`zenodio.harvest.harvest_collection` to build a
:class:`~zenodio.harvest.Datacite3Collection` for a Community.
Parameters
----------
xml_content : str
... |
def get_foldrate(seq, secstruct):
"""Submit sequence and structural class to FOLD-RATE calculator (http://www.iitm.ac.in/bioinfo/fold-rate/)
to calculate kinetic folding rate.
Args:
seq (str, Seq, SeqRecord): Amino acid sequence
secstruct (str): Structural class: `all-alpha``, ``all-beta``,... | Submit sequence and structural class to FOLD-RATE calculator (http://www.iitm.ac.in/bioinfo/fold-rate/)
to calculate kinetic folding rate.
Args:
seq (str, Seq, SeqRecord): Amino acid sequence
secstruct (str): Structural class: `all-alpha``, ``all-beta``, ``mixed``, or ``unknown``
Returns:
... |
def widths_in_range_mm(
self,
minwidth=EMIR_MINIMUM_SLITLET_WIDTH_MM,
maxwidth=EMIR_MAXIMUM_SLITLET_WIDTH_MM
):
"""Return list of slitlets which width is within given range
Parameters
----------
minwidth : float
Minimum slit width (mm)... | Return list of slitlets which width is within given range
Parameters
----------
minwidth : float
Minimum slit width (mm).
maxwidth : float
Maximum slit width (mm).
Returns
-------
list_ok : list
List of booleans indicating whe... |
def calc_freefree_kappa(ne, t, hz):
"""Dulk (1985) eq 20, assuming pure hydrogen."""
return 9.78e-3 * ne**2 * hz**-2 * t**-1.5 * (24.5 + np.log(t) - np.log(hz)) | Dulk (1985) eq 20, assuming pure hydrogen. |
def _get_button_attrs(self, tool):
"""
Get the HTML attributes associated with a tool.
There are some standard attributes (class and title) that the template
will always want. Any number of additional attributes can be specified
and passed on. This is kinda awkward and due for a... | Get the HTML attributes associated with a tool.
There are some standard attributes (class and title) that the template
will always want. Any number of additional attributes can be specified
and passed on. This is kinda awkward and due for a refactor for
readability. |
def check_ip(ip, log=False):
"""Attempts a connection to the TV and checks if there really is a TV."""
if log:
print('Checking ip: {}...'.format(ip))
request_timeout = 0.1
try:
tv_url = 'http://{}:6095/request?action=isalive'.format(ip)
requ... | Attempts a connection to the TV and checks if there really is a TV. |
def _reproject(wcs1, wcs2):
"""
Perform the forward transformation of ``wcs1`` followed by the
inverse transformation of ``wcs2``.
Parameters
----------
wcs1, wcs2 : `~astropy.wcs.WCS` or `~gwcs.wcs.WCS`
The WCS objects.
Returns
-------
... | Perform the forward transformation of ``wcs1`` followed by the
inverse transformation of ``wcs2``.
Parameters
----------
wcs1, wcs2 : `~astropy.wcs.WCS` or `~gwcs.wcs.WCS`
The WCS objects.
Returns
-------
result : func
Function to compute... |
def broadcast(self, msg):
"""
Broadcasts msg to Scratch. msg can be a single message or an iterable
(list, tuple, set, generator, etc.) of messages.
"""
if getattr(msg, '__iter__', False): # iterable
for m in msg:
self._send('broadcast "%s"' % self._e... | Broadcasts msg to Scratch. msg can be a single message or an iterable
(list, tuple, set, generator, etc.) of messages. |
def search_windows(
self, winname=None, winclass=None, winclassname=None,
pid=None, only_visible=False, screen=None, require=False,
searchmask=0, desktop=None, limit=0, max_depth=-1):
"""
Search for windows.
:param winname:
Regexp to be matched ag... | Search for windows.
:param winname:
Regexp to be matched against window name
:param winclass:
Regexp to be matched against window class
:param winclassname:
Regexp to be matched against window class name
:param pid:
Only return windows fro... |
def sparse_dot_product_attention(q, k, v, bi, use_map_fn, experts_params):
"""Sparse multihead self attention.
Perform an approximation of the full multihead attention by dispatching
the tokens using their keys/values. Thus the attention matrix are only
computed each times on a subset of the tokens.
Notes:
... | Sparse multihead self attention.
Perform an approximation of the full multihead attention by dispatching
the tokens using their keys/values. Thus the attention matrix are only
computed each times on a subset of the tokens.
Notes:
* The function don't perform scaling here (multihead_attention does
the /sq... |
def _set_ccm_interval(self, v, load=False):
"""
Setter method for ccm_interval, mapped from YANG variable /cfm_state/cfm_detail/domain/ma/ccm_interval (ccm-intervals)
If this variable is read-only (config: false) in the
source YANG file, then _set_ccm_interval is considered as a private
method. Back... | Setter method for ccm_interval, mapped from YANG variable /cfm_state/cfm_detail/domain/ma/ccm_interval (ccm-intervals)
If this variable is read-only (config: false) in the
source YANG file, then _set_ccm_interval is considered as a private
method. Backends looking to populate this variable should
do so ... |
def _get_dataset_showcase_dict(self, showcase):
# type: (Union[hdx.data.showcase.Showcase, Dict,str]) -> Dict
"""Get dataset showcase dict
Args:
showcase (Union[Showcase,Dict,str]): Either a showcase id or Showcase metadata from a Showcase object or dictionary
Returns:
... | Get dataset showcase dict
Args:
showcase (Union[Showcase,Dict,str]): Either a showcase id or Showcase metadata from a Showcase object or dictionary
Returns:
dict: dataset showcase dict |
def load(self, buf = None):
"""This method opens an existing database.
self.password/self.keyfile and self.filepath must be set.
"""
if self.password is None and self.keyfile is None:
raise KPError('Need a password or keyfile')
elif self.filepath is None an... | This method opens an existing database.
self.password/self.keyfile and self.filepath must be set. |
def create_form_data(self, **kwargs):
"""Create groupings of form elements."""
# Get the specified keyword arguments.
children = kwargs.get('children', [])
sort_order = kwargs.get('sort_order', None)
solr_response = kwargs.get('solr_response', None)
superuser = kwargs.get... | Create groupings of form elements. |
def create(self, healthCheckNotification, instance, ipAddressResourceId, name, notificationContacts, rules,
loadBalancerClassOfServiceID=1, *args, **kwargs):
"""
:type healthCheckNotification: bool
:type instance: list[Instance]
:type ipAddressResourceId: list[int]
... | :type healthCheckNotification: bool
:type instance: list[Instance]
:type ipAddressResourceId: list[int]
:type loadBalancerClassOfServiceID: int
:type name: str
:type notificationContacts: NotificationContacts or list[NotificationContact]
:type rules: Rules
:param ... |
def fromXml(xml):
"""
Creates a new slide from XML.
:return <XWalkthroughSlide>
"""
slide = XWalkthroughSlide(**xml.attrib)
# create the items
for xgraphic in xml:
slide.addItem(XWalkthroughItem.fromXml(xgraphic))
... | Creates a new slide from XML.
:return <XWalkthroughSlide> |
def ndwi(self):
"""
Calculates Normalized Difference Water Index using Coastal and NIR2 bands for WV02, WV03.
For Landsat8 and sentinel2 calculated by using Green and NIR bands.
Returns: numpy array of ndwi values
"""
data = self._read(self[self._ndwi_bands,...]).astype(... | Calculates Normalized Difference Water Index using Coastal and NIR2 bands for WV02, WV03.
For Landsat8 and sentinel2 calculated by using Green and NIR bands.
Returns: numpy array of ndwi values |
def sha1_hexdigest(self):
# type: () -> str
"""
A SHA-1 digest of the whole object for easy differentiation.
.. versionadded:: 18.1.0
"""
if self._sha1_hexdigest is None:
self._sha1_hexdigest = hashlib.sha1(self._pem_bytes).hexdigest()
return self._s... | A SHA-1 digest of the whole object for easy differentiation.
.. versionadded:: 18.1.0 |
def get_abi_size(self, target_data, context=None):
"""
Get the ABI size of this type according to data layout *target_data*.
"""
llty = self._get_ll_pointer_type(target_data, context)
return target_data.get_pointee_abi_size(llty) | Get the ABI size of this type according to data layout *target_data*. |
def conv_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs):
"""A block of standard 2d convolutions."""
return conv_block_internal(conv, inputs, filters,
dilation_rates_and_kernel_sizes, **kwargs) | A block of standard 2d convolutions. |
def context_spec(self):
"""Spec for specifying context options"""
from harpoon.option_spec import image_objs
return dict_from_bool_spec(lambda meta, val: {"enabled": val}
, create_spec(image_objs.Context
, validators.deprecated_key("use_git_timestamps", "Since docker ... | Spec for specifying context options |
def merge_results(x, y):
"""
Given two dicts, x and y, merge them into a new dict as a shallow copy.
The result only differs from `x.update(y)` in the way that it handles list
values when both x and y have list values for the same key. In which case
the returned dictionary, z, has a value according... | Given two dicts, x and y, merge them into a new dict as a shallow copy.
The result only differs from `x.update(y)` in the way that it handles list
values when both x and y have list values for the same key. In which case
the returned dictionary, z, has a value according to:
z[key] = x[key] + z[key]
... |
def _get_variables(self) -> Dict[str, str]:
"""
Gets the variables that should be set for this project.
:return: the variables
"""
variables = {} # type: Dict[str, str]
for group in self.groups:
setting_variables = self._read_group_variables(group)
... | Gets the variables that should be set for this project.
:return: the variables |
def _get_option(config, supplement, section, option, fallback=None):
"""
Reads an option for a configuration file.
:param configparser.ConfigParser config: The main config file.
:param configparser.ConfigParser supplement: The supplement config file.
:param str section: The name... | Reads an option for a configuration file.
:param configparser.ConfigParser config: The main config file.
:param configparser.ConfigParser supplement: The supplement config file.
:param str section: The name of the section op the option.
:param str option: The name of the option.
... |
def runInParallel(*fns):
"""
Runs multiple processes in parallel.
:type: fns: def
"""
proc = []
for fn in fns:
p = Process(target=fn)
p.start()
proc.append(p)
for p in proc:
p.join() | Runs multiple processes in parallel.
:type: fns: def |
def age_to_BP(age, age_unit):
"""
Convert an age value into the equivalent in time Before Present(BP) where Present is 1950
Returns
---------
ageBP : number
"""
ageBP = -1e9
if age_unit == "Years AD (+/-)" or age_unit == "Years Cal AD (+/-)":
if age < 0:
age = age+1 ... | Convert an age value into the equivalent in time Before Present(BP) where Present is 1950
Returns
---------
ageBP : number |
def trace_plot(precisions, path, n_edges=20, ground_truth=None, edges=[]):
"""Plot the change in precision (or covariance) coefficients as a function
of changing lambda and l1-norm. Always ignores diagonals.
Parameters
-----------
precisions : array of len(path) 2D ndarray, shape (n_features, n_fe... | Plot the change in precision (or covariance) coefficients as a function
of changing lambda and l1-norm. Always ignores diagonals.
Parameters
-----------
precisions : array of len(path) 2D ndarray, shape (n_features, n_features)
This is either precision_ or covariance_ from an InverseCovariance... |
def error(self, msg='Program error: {err}', exit=None):
""" Error handler factory
This function takes a message with optional ``{err}`` placeholder and
returns a function that takes an exception object, prints the error
message to STDERR and optionally quits.
If no message is s... | Error handler factory
This function takes a message with optional ``{err}`` placeholder and
returns a function that takes an exception object, prints the error
message to STDERR and optionally quits.
If no message is supplied (e.g., passing ``None`` or ``False`` or empty
string... |
def hub_virtual_network_connections(self):
"""Instance depends on the API version:
* 2018-04-01: :class:`HubVirtualNetworkConnectionsOperations<azure.mgmt.network.v2018_04_01.operations.HubVirtualNetworkConnectionsOperations>`
"""
api_version = self._get_api_version('hub_virtual_netw... | Instance depends on the API version:
* 2018-04-01: :class:`HubVirtualNetworkConnectionsOperations<azure.mgmt.network.v2018_04_01.operations.HubVirtualNetworkConnectionsOperations>` |
def load_yaml(yaml_file: str) -> Any:
"""
Load YAML from file.
:param yaml_file: path to YAML file
:return: content of the YAML as dict/list
"""
with open(yaml_file, 'r') as file:
return ruamel.yaml.load(file, ruamel.yaml.RoundTripLoader) | Load YAML from file.
:param yaml_file: path to YAML file
:return: content of the YAML as dict/list |
def post(self, command, data=None):
"""Post data to API."""
now = calendar.timegm(datetime.datetime.now().timetuple())
if now > self.expiration:
auth = self.__open("/oauth/token", data=self.oauth)
self.__sethead(auth['access_token'])
return self.__open("%s%s" % (s... | Post data to API. |
def from_domain(cls, domain, version=None, require_https=True):
"""
Try to find a hive for the given domain; raise an error if we have to
failover to HTTP and haven't explicitly suppressed it in the call.
"""
url = 'https://' + domain + '/api/hive.json'
try:
r... | Try to find a hive for the given domain; raise an error if we have to
failover to HTTP and haven't explicitly suppressed it in the call. |
def search_feature_sets(self, dataset_id):
"""
Returns an iterator over the FeatureSets fulfilling the specified
conditions from the specified Dataset.
:param str dataset_id: The ID of the
:class:`ga4gh.protocol.Dataset` of interest.
:return: An iterator over the :cl... | Returns an iterator over the FeatureSets fulfilling the specified
conditions from the specified Dataset.
:param str dataset_id: The ID of the
:class:`ga4gh.protocol.Dataset` of interest.
:return: An iterator over the :class:`ga4gh.protocol.FeatureSet`
objects defined by ... |
def check_files(cls, dap):
'''Check that there are only those files the standard accepts.
Return list of DapProblems.'''
problems = list()
dirname = os.path.dirname(dap._meta_location)
if dirname:
dirname += '/'
files = [f for f in dap.files if f.startswith(... | Check that there are only those files the standard accepts.
Return list of DapProblems. |
def _boxFromData(self, messageData):
"""
A box.
@param messageData: a serialized AMP box representing either a message
or an error.
@type messageData: L{str}
@raise MalformedMessage: if the C{messageData} parameter does not parse
to exactly one AMP box.
... | A box.
@param messageData: a serialized AMP box representing either a message
or an error.
@type messageData: L{str}
@raise MalformedMessage: if the C{messageData} parameter does not parse
to exactly one AMP box. |
def show(i):
"""
Input: {
(data_uoa) - repo UOA
(reset) - if 'yes', reset repos
(stable) - take stable version (highly experimental)
(version) - checkout version (default - stable)
}
Output: {
return - return c... | Input: {
(data_uoa) - repo UOA
(reset) - if 'yes', reset repos
(stable) - take stable version (highly experimental)
(version) - checkout version (default - stable)
}
Output: {
return - return code = 0, if successful
... |
def organization_memberships(self, user):
"""
Retrieve the organization memberships for this user.
:param user: User object or id
"""
return self._query_zendesk(self.endpoint.organization_memberships, 'organization_membership', id=user) | Retrieve the organization memberships for this user.
:param user: User object or id |
def image_export(self, image_name, dest_url, remote_host=None):
"""Export the image to the specified location
:param image_name: image name that can be uniquely identify an image
:param dest_url: the location of exported image, eg.
file:///opt/images/export.img, now only support export t... | Export the image to the specified location
:param image_name: image name that can be uniquely identify an image
:param dest_url: the location of exported image, eg.
file:///opt/images/export.img, now only support export to remote server
or local server's file system
:param remote... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.