code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def make_tophat_ee (lower, upper):
"""Return a ufunc-like tophat function on the defined range, left-exclusive
and right-exclusive. Returns 1 if lower < x < upper, 0 otherwise.
"""
if not np.isfinite (lower):
raise ValueError ('"lower" argument must be finite number; got %r' % lower)
if not... | Return a ufunc-like tophat function on the defined range, left-exclusive
and right-exclusive. Returns 1 if lower < x < upper, 0 otherwise. |
def _get_type(self, obj):
"""Return the type of an object."""
typever = obj['Type']
typesplit = typever.split('.')
return typesplit[0] + '.' + typesplit[1] | Return the type of an object. |
def cov_pmrapmdec_to_pmllpmbb(cov_pmradec,ra,dec,degree=False,epoch=2000.0):
"""
NAME:
cov_pmrapmdec_to_pmllpmbb
PURPOSE:
propagate the proper motions errors through the rotation from (ra,dec) to (l,b)
INPUT:
covar_pmradec - uncertainty covariance matrix of the proper motion in... | NAME:
cov_pmrapmdec_to_pmllpmbb
PURPOSE:
propagate the proper motions errors through the rotation from (ra,dec) to (l,b)
INPUT:
covar_pmradec - uncertainty covariance matrix of the proper motion in ra (multplied with cos(dec)) and dec [2,2] or [:,2,2]
ra - right ascension
... |
def getOverlayTexture(self, ulOverlayHandle, pNativeTextureRef):
"""
Get the native texture handle/device for an overlay you have created.
On windows this handle will be a ID3D11ShaderResourceView with a ID3D11Texture2D bound.
* The texture will always be sized to match the backing textu... | Get the native texture handle/device for an overlay you have created.
On windows this handle will be a ID3D11ShaderResourceView with a ID3D11Texture2D bound.
* The texture will always be sized to match the backing texture you supplied in SetOverlayTexture above.
* You MUST call ReleaseNativeOver... |
def set_block(arr, arr_block):
""" Sets the diagonal blocks of an array to an given array
Parameters
----------
arr : numpy ndarray
the original array
block_arr : numpy ndarray
the block array for the new diagonal
Returns
-------
numpy ndarray (the modified array)
... | Sets the diagonal blocks of an array to an given array
Parameters
----------
arr : numpy ndarray
the original array
block_arr : numpy ndarray
the block array for the new diagonal
Returns
-------
numpy ndarray (the modified array) |
def delete_commit_branches(self, enrich_backend):
"""Delete the information about branches from the documents representing
commits in the enriched index.
:param enrich_backend: the enrich backend
"""
fltr = """
"filter": [
{
"term"... | Delete the information about branches from the documents representing
commits in the enriched index.
:param enrich_backend: the enrich backend |
def sort_by_decreasing_count(self):
"""Return a **new** `Vocab` object that is ordered by decreasing count.
The word at index 1 will be most common, the word at index 2 will be
next most common, and so on.
:return: A new vocabulary sorted by decreasing count.
NOTE: UNK will re... | Return a **new** `Vocab` object that is ordered by decreasing count.
The word at index 1 will be most common, the word at index 2 will be
next most common, and so on.
:return: A new vocabulary sorted by decreasing count.
NOTE: UNK will remain at index 0, regardless of its frequency. |
def image_path_from_index(self, index):
"""
given image index, find out full path
Parameters
----------
index: int
index of a specific image
Returns
----------
full path of this image
"""
assert self.image_set_index is not Non... | given image index, find out full path
Parameters
----------
index: int
index of a specific image
Returns
----------
full path of this image |
def enable_tracing(self):
"""Open the tracing interface and accumulate traces in a queue.
This method is safe to call multiple times in a single device
connection. There is no way to check if the tracing interface is
opened or to close it once it is opened (apart from disconnecting from... | Open the tracing interface and accumulate traces in a queue.
This method is safe to call multiple times in a single device
connection. There is no way to check if the tracing interface is
opened or to close it once it is opened (apart from disconnecting from
the device).
The fi... |
def make_tophat_ie (lower, upper):
"""Return a ufunc-like tophat function on the defined range, left-inclusive
and right-exclusive. Returns 1 if lower <= x < upper, 0 otherwise.
"""
if not np.isfinite (lower):
raise ValueError ('"lower" argument must be finite number; got %r' % lower)
if no... | Return a ufunc-like tophat function on the defined range, left-inclusive
and right-exclusive. Returns 1 if lower <= x < upper, 0 otherwise. |
def add(
self, job, job_add_options=None, custom_headers=None, raw=False, **operation_config):
"""Adds a job to the specified account.
The Batch service supports two ways to control the work done as part of
a job. In the first approach, the user specifies a Job Manager task.
... | Adds a job to the specified account.
The Batch service supports two ways to control the work done as part of
a job. In the first approach, the user specifies a Job Manager task.
The Batch service launches this task when it is ready to start the job.
The Job Manager task controls all oth... |
def get_input_list_from_task(task, placeholder_dict):
"""
Purpose: Parse a Task object to extract the files to be staged as the output.
Details: The extracted data is then converted into the appropriate RP directive depending on whether the data
is to be copied/downloaded.
:arguments:
:tas... | Purpose: Parse a Task object to extract the files to be staged as the output.
Details: The extracted data is then converted into the appropriate RP directive depending on whether the data
is to be copied/downloaded.
:arguments:
:task: EnTK Task object
:placeholder_dict: dictionary holding ... |
def emit_data_changed(self):
"""Emit the data changed signal on the model of the treeitem
if the treeitem has a model.
:returns: None
:rtype: None
:raises: None
"""
item = self.get_treeitem()
m = item.get_model()
if m:
start = m.index_... | Emit the data changed signal on the model of the treeitem
if the treeitem has a model.
:returns: None
:rtype: None
:raises: None |
def log_html(self, log) -> str:
"""Return single check sub-result string as HTML or not if below log
level."""
if not self.omit_loglevel(log["status"]):
emoticon = EMOTICON[log["status"]]
status = log["status"]
message = html.escape(log["message"]).replace("\n... | Return single check sub-result string as HTML or not if below log
level. |
def find_dependencies(self, depslock_file_path, property_validate=True, deps_content=None):
"""
Find all dependencies by package
:param depslock_file_path:
:param property_validate: for `root` packages we need check property, bad if we find packages from `lock` file,
:param deps_... | Find all dependencies by package
:param depslock_file_path:
:param property_validate: for `root` packages we need check property, bad if we find packages from `lock` file,
:param deps_content: HACK for use --dependencies-content and existed dependencies.txt.lock file
we can skip validate... |
def get_element_centroids(self):
"""return the central points of all elements
Returns
-------
Nx2 array
x/z coordinates for all (N) elements
"""
centroids = np.vstack((
np.mean(self.grid['x'], axis=1), np.mean(self.grid['z'], axis=1)
)).T
... | return the central points of all elements
Returns
-------
Nx2 array
x/z coordinates for all (N) elements |
def is_functional(cls):
"""
Checks lazily whether a convex solver is installed that handles positivity constraints.
:return: True if a solver supporting positivity constraints is installed.
:rtype: bool
"""
if not cls._tested:
cls._tested = True
n... | Checks lazily whether a convex solver is installed that handles positivity constraints.
:return: True if a solver supporting positivity constraints is installed.
:rtype: bool |
def level_matches(self, level, consumer_level):
"""
>>> l = Logger([])
>>> l.level_matches(3, 4)
False
>>> l.level_matches(3, 2)
True
>>> l.level_matches(slice(None, 3), 3)
False
>>> l.level_matches(slice(None, 3), 2)
True
>>> l.lev... | >>> l = Logger([])
>>> l.level_matches(3, 4)
False
>>> l.level_matches(3, 2)
True
>>> l.level_matches(slice(None, 3), 3)
False
>>> l.level_matches(slice(None, 3), 2)
True
>>> l.level_matches(slice(1, 3), 1)
True
>>> l.level_matches(... |
def timing(function):
'''
Decorator wrapper to log execution time, for profiling purposes
'''
@wraps(function)
def wrapped(*args, **kwargs):
start_time = time.time()
ret = function(*args, **salt.utils.args.clean_kwargs(**kwargs))
end_time = time.time()
if function.__m... | Decorator wrapper to log execution time, for profiling purposes |
def _get_site_type_dummy_variables(self, sites):
"""
Get site type dummy variables, which classified the sites into
different site classes based on the shear wave velocity in the
upper 30 m (Vs30) according to the EC8 (CEN 2003):
class A: Vs30 > 800 m/s
class B: Vs30 = 36... | Get site type dummy variables, which classified the sites into
different site classes based on the shear wave velocity in the
upper 30 m (Vs30) according to the EC8 (CEN 2003):
class A: Vs30 > 800 m/s
class B: Vs30 = 360 - 800 m/s
class C*: Vs30 = 180 - 360 m/s
class D: V... |
def get_proteins_for_db(fastafn):
"""Runs through fasta file and returns proteins accession nrs, sequences
and evidence levels for storage in lookup DB. Duplicate accessions in
fasta are accepted and removed by keeping only the last one.
"""
objects = {}
for record in parse_fasta(fastafn):
... | Runs through fasta file and returns proteins accession nrs, sequences
and evidence levels for storage in lookup DB. Duplicate accessions in
fasta are accepted and removed by keeping only the last one. |
def closest(self):
"""Match closest ancestor."""
current = self.tag
closest = None
while closest is None and current is not None:
if self.match(current):
closest = current
else:
current = self.get_parent(current)
return clo... | Match closest ancestor. |
def add_command_formatting(self, command):
"""A utility function to format commands and groups.
Parameters
------------
command: :class:`Command`
The command to format.
"""
if command.description:
self.paginator.add_line(command.description, empt... | A utility function to format commands and groups.
Parameters
------------
command: :class:`Command`
The command to format. |
def get_urn(self):
"""
TODO
"""
urn = self.ecrm_P1_is_identified_by.one
try:
return CTS_URN(urn)
except Exception, e:
raise e | TODO |
def search_dashboard_for_facet(self, facet, **kwargs): # noqa: E501
"""Lists the values of a specific facet over the customer's non-deleted dashboards # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass... | Lists the values of a specific facet over the customer's non-deleted dashboards # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.search_dashboard_for_facet(facet, async... |
def chat(self, id):
"""
Get a single conversation by identifier.
Args:
id (str): single or group chat identifier
"""
json = self.skype.conn("GET", "{0}/users/ME/conversations/{1}".format(self.skype.conn.msgsHost, id),
auth=SkypeConnecti... | Get a single conversation by identifier.
Args:
id (str): single or group chat identifier |
def write_pdf_files(args, infilenames, outfilename):
"""Write pdf file(s) to disk using pdfkit.
Keyword arguments:
args -- program arguments (dict)
infilenames -- names of user-inputted and/or downloaded files (list)
outfilename -- name of output pdf file (str)
"""
if not outfilename.endswi... | Write pdf file(s) to disk using pdfkit.
Keyword arguments:
args -- program arguments (dict)
infilenames -- names of user-inputted and/or downloaded files (list)
outfilename -- name of output pdf file (str) |
def _parse_ISBN_EAN(details):
"""
Parse ISBN and EAN.
Args:
details (obj): HTMLElement containing slice of the page with details.
Returns:
(ISBN, EAN): Tuple with two string or two None.
"""
isbn_ean = _get_td_or_none(
details,
"ctl00_ContentPlaceHolder1_tblRowI... | Parse ISBN and EAN.
Args:
details (obj): HTMLElement containing slice of the page with details.
Returns:
(ISBN, EAN): Tuple with two string or two None. |
def _netstat_sunos():
'''
Return netstat information for SunOS flavors
'''
log.warning('User and program not (yet) supported on SunOS')
ret = []
for addr_family in ('inet', 'inet6'):
# Lookup TCP connections
cmd = 'netstat -f {0} -P tcp -an | tail +5'.format(addr_family)
... | Return netstat information for SunOS flavors |
def get_value(self, **kwargs):
"""Return the value for a specific key."""
key = tuple(kwargs[group] for group in self.groups)
if key not in self.data:
self.data[key] = 0
return self.data[key] | Return the value for a specific key. |
def reread(user=None, conf_file=None, bin_env=None):
'''
Reload the daemon's configuration files
user
user to run supervisorctl as
conf_file
path to supervisord config file
bin_env
path to supervisorctl bin or path to virtualenv with supervisor
installed
CLI Exa... | Reload the daemon's configuration files
user
user to run supervisorctl as
conf_file
path to supervisord config file
bin_env
path to supervisorctl bin or path to virtualenv with supervisor
installed
CLI Example:
.. code-block:: bash
salt '*' supervisord.rer... |
def compute_venn2_colors(set_colors):
'''
Given two base colors, computes combinations of colors corresponding to all regions of the venn diagram.
returns a list of 3 elements, providing colors for regions (10, 01, 11).
>>> compute_venn2_colors(('r', 'g'))
(array([ 1., 0., 0.]), array([ 0. , 0.5... | Given two base colors, computes combinations of colors corresponding to all regions of the venn diagram.
returns a list of 3 elements, providing colors for regions (10, 01, 11).
>>> compute_venn2_colors(('r', 'g'))
(array([ 1., 0., 0.]), array([ 0. , 0.5, 0. ]), array([ 0.7 , 0.35, 0. ])) |
def send_message(self, chat_id, text, **options):
"""
Send a text message to chat
:param int chat_id: ID of the chat to send the message to
:param str text: Text to send
:param options: Additional sendMessage options
(see https://core.telegram.org/bots/api#sendmessag... | Send a text message to chat
:param int chat_id: ID of the chat to send the message to
:param str text: Text to send
:param options: Additional sendMessage options
(see https://core.telegram.org/bots/api#sendmessage) |
def _read_certificates(self):
"""
Reads end-entity and intermediate certificate information from the
TLS session
"""
stack_pointer = libssl.SSL_get_peer_cert_chain(self._ssl)
if is_null(stack_pointer):
handle_openssl_error(0, TLSError)
if libcrypto_v... | Reads end-entity and intermediate certificate information from the
TLS session |
def hardware_info():
"""
Returns basic hardware information about the computer.
Gives actual number of CPU's in the machine, even when hyperthreading is
turned on.
Returns
-------
info : dict
Dictionary containing cpu and memory information.
"""
try:
if sys.platfor... | Returns basic hardware information about the computer.
Gives actual number of CPU's in the machine, even when hyperthreading is
turned on.
Returns
-------
info : dict
Dictionary containing cpu and memory information. |
def addDataModels(self, mods):
'''
Add a list of (name, mdef) tuples.
A model definition (mdef) is structured as follows::
{
"ctors":(
('name', 'class.path.ctor', {}, {'doc': 'The foo thing.'}),
),
"types":(
... | Add a list of (name, mdef) tuples.
A model definition (mdef) is structured as follows::
{
"ctors":(
('name', 'class.path.ctor', {}, {'doc': 'The foo thing.'}),
),
"types":(
('name', ('basetype', {typeopts}), {... |
def result(self):
"""
Return the final result or raise an Exception if errors were
encountered. If the final result or error has not been set
yet, this method will block until it is set, or the timeout
set for the request expires.
Timeout is specified in the Session req... | Return the final result or raise an Exception if errors were
encountered. If the final result or error has not been set
yet, this method will block until it is set, or the timeout
set for the request expires.
Timeout is specified in the Session request execution functions.
If t... |
def default_cy(self):
"""
Native height of this image, calculated from its height in pixels and
vertical dots per inch (dpi).
"""
px_height = self.image.px_height
horz_dpi = self.image.horz_dpi
height_in_emu = 914400 * px_height / horz_dpi
return Emu(heigh... | Native height of this image, calculated from its height in pixels and
vertical dots per inch (dpi). |
def _list_resource_descriptors(args, _):
"""Lists the resource descriptors in the project."""
project_id = args['project']
pattern = args['type'] or '*'
descriptors = gcm.ResourceDescriptors(project_id=project_id)
dataframe = descriptors.as_dataframe(pattern=pattern)
return _render_dataframe(dataframe) | Lists the resource descriptors in the project. |
def _make_repr(attrs, ns):
"""
Make a repr method for *attr_names* adding *ns* to the full name.
"""
attr_names = tuple(a.name for a in attrs if a.repr)
def __repr__(self):
"""
Automatically created by attrs.
"""
try:
working_set = _already_repring.workin... | Make a repr method for *attr_names* adding *ns* to the full name. |
def get_machines(self, origin, hostnames):
"""Return a set of machines based on `hostnames`.
Any hostname that is not found will result in an error.
"""
hostnames = {
hostname: True
for hostname in hostnames
}
machines = origin.Machines.read(hostn... | Return a set of machines based on `hostnames`.
Any hostname that is not found will result in an error. |
def console_to_str(data):
# type: (bytes) -> Text
"""Return a string, safe for output, of subprocess output.
We assume the data is in the locale preferred encoding.
If it won't decode properly, we warn the user but decode as
best we can.
We also ensure that the output can be safely written to
... | Return a string, safe for output, of subprocess output.
We assume the data is in the locale preferred encoding.
If it won't decode properly, we warn the user but decode as
best we can.
We also ensure that the output can be safely written to
standard output without encoding errors. |
def to_json(self):
"""
Returns:
str: Json for commands array object and all of the commands inside the array."""
commands = ",".join(map(lambda x: x.to_json(), self._commands))
return "{\"commands\": [" + commands + "]}" | Returns:
str: Json for commands array object and all of the commands inside the array. |
def parse(self, data):
"""Parse a 9 bytes packet in the Humidity format and return a
dictionary containing the data extracted. An example of a return value
would be:
.. code-block:: python
{
'id': "0x2EB2",
'packet_length': 8,
... | Parse a 9 bytes packet in the Humidity format and return a
dictionary containing the data extracted. An example of a return value
would be:
.. code-block:: python
{
'id': "0x2EB2",
'packet_length': 8,
'packet_type': 81,
... |
def parse_usearch61_failures(seq_path,
failures,
output_fasta_fp):
""" Parses seq IDs from failures list, writes to output_fasta_fp
seq_path: filepath of original input fasta file.
failures: list/set of failure seq IDs
output_fasta_fp: path to w... | Parses seq IDs from failures list, writes to output_fasta_fp
seq_path: filepath of original input fasta file.
failures: list/set of failure seq IDs
output_fasta_fp: path to write parsed sequences |
def stop(self, reason=None):
"""Shutdown the service with a reason."""
self.logger.info('stopping')
self.loop.stop(pyev.EVBREAK_ALL) | Shutdown the service with a reason. |
def parse_links(self, markup):
""" Returns a list of internal Wikipedia links in the markup.
# A Wikipedia link looks like:
# [[List of operating systems#Embedded | List of embedded operating systems]]
# It does not contain a colon, this indicates images, users, languages, etc.... | Returns a list of internal Wikipedia links in the markup.
# A Wikipedia link looks like:
# [[List of operating systems#Embedded | List of embedded operating systems]]
# It does not contain a colon, this indicates images, users, languages, etc.
The return value is a list contain... |
def DateTimeField(formatter=types.DEFAULT_DATETIME_FORMAT, default=NOTHING,
required=True, repr=True, cmp=True, key=None):
"""
Create new datetime field on a model.
:param formatter: datetime formatter string (default: "ISO_FORMAT")
:param default: any datetime or string that can be c... | Create new datetime field on a model.
:param formatter: datetime formatter string (default: "ISO_FORMAT")
:param default: any datetime or string that can be converted to a datetime
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should ap... |
def sendMessage(self,chat_id,text,parse_mode=None,disable_web=None,reply_msg_id=None,markup=None):
''' On failure returns False
On success returns Message Object '''
payload={'chat_id' : chat_id, 'text' : text, 'parse_mode': parse_mode , 'disable_web_page_preview' : disable_web , 'reply_to_message_id' : reply_msg... | On failure returns False
On success returns Message Object |
def _fill_disk_filename(vm_name, disk, hypervisor, **kwargs):
'''
Compute the disk file name and update it in the disk value.
'''
base_dir = disk.get('pool', None)
if hypervisor in ['qemu', 'kvm', 'xen']:
# Compute the base directory from the pool property. We may have either a path
... | Compute the disk file name and update it in the disk value. |
def is_on(self):
"""
Get sensor state.
Assume offline or open (worst case).
"""
return self.status not in (CONST.STATUS_OFF, CONST.STATUS_OFFLINE,
CONST.STATUS_CLOSED, CONST.STATUS_OPEN) | Get sensor state.
Assume offline or open (worst case). |
def evaluate(self, x, y, flux, x_0, y_0, sigma):
"""Model function Gaussian PSF model."""
return (flux / 4 *
((self._erf((x - x_0 + 0.5) / (np.sqrt(2) * sigma)) -
self._erf((x - x_0 - 0.5) / (np.sqrt(2) * sigma))) *
(self._erf((y - y_0 + 0.5) / (np.sqr... | Model function Gaussian PSF model. |
def remove_highdepth_regions(in_file, items):
"""Remove high depth regions from a BED file for analyzing a set of calls.
Tries to avoid spurious errors and slow run times in collapsed repeat regions.
Also adds ENCODE blacklist regions which capture additional collapsed repeats
around centromeres.
... | Remove high depth regions from a BED file for analyzing a set of calls.
Tries to avoid spurious errors and slow run times in collapsed repeat regions.
Also adds ENCODE blacklist regions which capture additional collapsed repeats
around centromeres. |
def hold(self, policy="combine"):
''' Activate a document hold.
While a hold is active, no model changes will be applied, or trigger
callbacks. Once ``unhold`` is called, the events collected during the
hold will be applied according to the hold policy.
Args:
hold (... | Activate a document hold.
While a hold is active, no model changes will be applied, or trigger
callbacks. Once ``unhold`` is called, the events collected during the
hold will be applied according to the hold policy.
Args:
hold ('combine' or 'collect', optional)
... |
def Parse(self, how):
'''Parse the message.
'''
if type(how) == types.ClassType: how = how.typecode
return how.parse(self.body_root, self) | Parse the message. |
def position(self):
"""
Read/write :ref:`XlDataLabelPosition` member specifying the position
of this data label with respect to its data point, or |None| if no
position is specified. Assigning |None| causes PowerPoint to choose
the default position, which varies by chart type.
... | Read/write :ref:`XlDataLabelPosition` member specifying the position
of this data label with respect to its data point, or |None| if no
position is specified. Assigning |None| causes PowerPoint to choose
the default position, which varies by chart type. |
def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
datacent... | Return a list of VMs that are on the provider |
def retrieve_all(self, sids, default_none=False):
"""
Retrieve all assets in `sids`.
Parameters
----------
sids : iterable of string
Assets to retrieve.
default_none : bool
If True, return None for failed lookups.
If False, raise `Sids... | Retrieve all assets in `sids`.
Parameters
----------
sids : iterable of string
Assets to retrieve.
default_none : bool
If True, return None for failed lookups.
If False, raise `SidsNotFound`.
Returns
-------
assets : list[Asse... |
def stretch(self, factor, window=20):
'''Change the audio duration (but not its pitch).
**Unless factor is close to 1, use the tempo effect instead.**
This effect is broadly equivalent to the tempo effect with search set
to zero, so in general, its results are comparatively poor; it is
... | Change the audio duration (but not its pitch).
**Unless factor is close to 1, use the tempo effect instead.**
This effect is broadly equivalent to the tempo effect with search set
to zero, so in general, its results are comparatively poor; it is
retained as it can sometimes out-perform ... |
def _set_redistribute_bgp(self, v, load=False):
"""
Setter method for redistribute_bgp, mapped from YANG variable /rbridge_id/ipv6/router/ospf/redistribute/redistribute_bgp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_redistribute_bgp is considered as a pr... | Setter method for redistribute_bgp, mapped from YANG variable /rbridge_id/ipv6/router/ospf/redistribute/redistribute_bgp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_redistribute_bgp is considered as a private
method. Backends looking to populate this variable... |
def _obj_getattr(obj, fqdn, start=1):
"""Returns the attribute specified by the fqdn list from obj.
"""
node = obj
for chain in fqdn.split('.')[start:]:
if hasattr(node, chain):
node = getattr(node, chain)
else:
node = None
break
return node | Returns the attribute specified by the fqdn list from obj. |
def findSnpWithMaf0(freqFileName, prefix):
"""Finds SNPs with MAF of 0 and put them in a file.
:param freqFileName: the name of the frequency file.
:param prefix: the prefix of all the files.
:type freqFileName: str
:type prefix: str
Reads a frequency file from Plink, and find markers with a ... | Finds SNPs with MAF of 0 and put them in a file.
:param freqFileName: the name of the frequency file.
:param prefix: the prefix of all the files.
:type freqFileName: str
:type prefix: str
Reads a frequency file from Plink, and find markers with a minor allele
frequency of zero. |
def tolist(val):
"""Convert a value that may be a list or a (possibly comma-separated)
string into a list. The exception: None is returned as None, not [None].
>>> tolist(["one", "two"])
['one', 'two']
>>> tolist("hello")
['hello']
>>> tolist("separate,values, with, commas, spaces , are ... | Convert a value that may be a list or a (possibly comma-separated)
string into a list. The exception: None is returned as None, not [None].
>>> tolist(["one", "two"])
['one', 'two']
>>> tolist("hello")
['hello']
>>> tolist("separate,values, with, commas, spaces , are ,ok")
['separate', ... |
def seal_aes_ctr_legacy(key_service, secret, digest_method=DEFAULT_DIGEST):
"""
Encrypts `secret` using the key service.
You can decrypt with the companion method `open_aes_ctr_legacy`.
"""
# generate a a 64 byte key.
# Half will be for data encryption, the other half for HMAC
key, encoded_k... | Encrypts `secret` using the key service.
You can decrypt with the companion method `open_aes_ctr_legacy`. |
def compute_extra_rows(self,
all_dates,
start_date,
end_date,
min_extra_rows):
"""
Ensure that min_extra_rows pushes us back to a computation date.
Parameters
----------
a... | Ensure that min_extra_rows pushes us back to a computation date.
Parameters
----------
all_dates : pd.DatetimeIndex
The trading sessions against which ``self`` will be computed.
start_date : pd.Timestamp
The first date for which final output is requested.
... |
def user_organization_membership_show(self, user_id, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/organization_memberships#show-membership"
api_path = "/api/v2/users/{user_id}/organization_memberships/{id}.json"
api_path = api_path.format(user_id=user_id, id=id)
retur... | https://developer.zendesk.com/rest_api/docs/core/organization_memberships#show-membership |
def median_depth_img(self, num_img=1, fill_depth=0.0):
"""Collect a series of depth images and return the median of the set.
Parameters
----------
num_img : int
The number of consecutive frames to process.
Returns
-------
DepthImage
The m... | Collect a series of depth images and return the median of the set.
Parameters
----------
num_img : int
The number of consecutive frames to process.
Returns
-------
DepthImage
The median DepthImage collected from the frames. |
def iterShapes(self):
"""Serves up shapes in a shapefile as an iterator. Useful
for handling large shapefiles."""
shp = self.__getFileObj(self.shp)
shp.seek(0,2)
self.shpLength = shp.tell()
shp.seek(100)
while shp.tell() < self.shpLength:
yield... | Serves up shapes in a shapefile as an iterator. Useful
for handling large shapefiles. |
def action_size(self) -> Sequence[Sequence[int]]:
'''The size of each action fluent in canonical order.
Returns:
Sequence[Sequence[int]]: A tuple of tuple of integers
representing the shape and size of each fluent.
'''
fluents = self.domain.action_fluents
... | The size of each action fluent in canonical order.
Returns:
Sequence[Sequence[int]]: A tuple of tuple of integers
representing the shape and size of each fluent. |
def download_data(identifier, outdir):
"""Download data from a separate data repository for testing.
Parameters
----------
identifier: string
The identifier used to find the data set
outdir: string
unzip the data in this directory
"""
# determine target
if use_local_data... | Download data from a separate data repository for testing.
Parameters
----------
identifier: string
The identifier used to find the data set
outdir: string
unzip the data in this directory |
def get_el_from_z(z):
'''
Very simple Vfunction that gives the atomic number AS A STRING when given the element symbol.
Uses predefined a dictionnary.
Parameter :
z : string or number
For the other way, see get_z_from_el
'''
if(type(z)==float):
z=int(z)
if(type(z)==int):
... | Very simple Vfunction that gives the atomic number AS A STRING when given the element symbol.
Uses predefined a dictionnary.
Parameter :
z : string or number
For the other way, see get_z_from_el |
def mkproject_cmd(argv):
"""Create a new project directory and its associated virtualenv."""
if '-l' in argv or '--list' in argv:
templates = [t.name[9:] for t in workon_home.glob("template_*")]
print("Available project templates:", *templates, sep='\n')
return
parser = mkvirtualenv... | Create a new project directory and its associated virtualenv. |
def _keplerian_circular_to_keplerian(cls, coord, center):
"""Conversion from Keplerian near-circular elements to Mean Keplerian
"""
a, ex, ey, i, Ω, u = coord
e = sqrt(ex ** 2 + ey ** 2)
ω = arctan2(ey / e, ex / e)
ν = u - ω
return np.array([a, e, i, Ω, ω, ν], d... | Conversion from Keplerian near-circular elements to Mean Keplerian |
def copy(self):
"""
Returns a "T" (tee) copy of the given stream, allowing the calling
stream to continue being used.
"""
a, b = it.tee(self._data) # 2 generators, not thread-safe
self._data = a
return Stream(b) | Returns a "T" (tee) copy of the given stream, allowing the calling
stream to continue being used. |
def build_machine(network=None,
machine_type=None,
preemptible=None,
service_account=None,
boot_disk_size_gb=None,
disks=None,
accelerators=None,
labels=None,
cpu_platform=None... | Build a VirtualMachine object for a Pipeline request.
Args:
network (dict): Network details for the pipeline to run in.
machine_type (str): GCE Machine Type string for the pipeline.
preemptible (bool): Use a preemptible VM for the job.
service_account (dict): Service account configuration for the VM.... |
def list_to_file(orig_list, file_name, file_location):
"""
Function to export a list to a text file
Args:
orig_list: The list you want exported
file_name: The name of the exported file
file_location: The location of the file, derive from the os module
Returns: returns the filena... | Function to export a list to a text file
Args:
orig_list: The list you want exported
file_name: The name of the exported file
file_location: The location of the file, derive from the os module
Returns: returns the filename info |
def unselect(self, value=None, field=None, **kwargs):
"""
Find a select box on the page and unselect a particular option from it. If the select box is
a multiple select, ``unselect`` can be called multiple times to unselect more than one
option. The select box can be found via its name, ... | Find a select box on the page and unselect a particular option from it. If the select box is
a multiple select, ``unselect`` can be called multiple times to unselect more than one
option. The select box can be found via its name, id, or label text. ::
page.unselect("March", field="Month")
... |
def sort_by_distance(cls, consumer_offsets_metadata):
"""Receives a dict of (topic_name: ConsumerPartitionOffset) and returns a
similar dict where the topics are sorted by total offset distance."""
sorted_offsets = sorted(
list(consumer_offsets_metadata.items()),
key=lamb... | Receives a dict of (topic_name: ConsumerPartitionOffset) and returns a
similar dict where the topics are sorted by total offset distance. |
def _set_show_ntp(self, v, load=False):
"""
Setter method for show_ntp, mapped from YANG variable /brocade_ntp_rpc/show_ntp (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_ntp is considered as a private
method. Backends looking to populate this variable sh... | Setter method for show_ntp, mapped from YANG variable /brocade_ntp_rpc/show_ntp (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_ntp is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_show_ntp() d... |
def savemap(self, filename, filetype='png', papertype="a4"):
"""
Save the figure
"""
self.fig.savefig(filename,
dpi=self.dpi,
format=filetype,
papertype=papertype) | Save the figure |
def relative_resources(pathstring, failover='nifstd/resources'):
""" relative paths to resources in this repository
`failover` matches the location relative to the
github location (usually for prov purposes) """
if working_dir is None:
return Path(failover, pathstring).resolve()
els... | relative paths to resources in this repository
`failover` matches the location relative to the
github location (usually for prov purposes) |
def get_properties(cls):
"""Get all properties of the MessageFlags class."""
property_names = [p for p in dir(cls)
if isinstance(getattr(cls, p), property)]
return property_names | Get all properties of the MessageFlags class. |
def when(self, key):
""" Specify context, i.e. condition that must be met.
Arguments:
key (str): Name of the context whose value you want to query.
Returns:
Context:
"""
ctx = Context(key, self)
self.context.append(ctx)
return ctx | Specify context, i.e. condition that must be met.
Arguments:
key (str): Name of the context whose value you want to query.
Returns:
Context: |
def heartbeat(self):
"""
Override the scheduler heartbeat to determine when the test is complete
"""
super(SchedulerMetricsJob, self).heartbeat()
session = settings.Session()
# Get all the relevant task instances
TI = TaskInstance
successful_tis = (
... | Override the scheduler heartbeat to determine when the test is complete |
def _ul_per_mm(self, ul: float, func: str) -> float:
"""
:param ul: microliters as a float
:param func: must be one of 'aspirate' or 'dispense'
:return: microliters/mm as a float
"""
sequence = self.ul_per_mm[func]
return pipette_config.piecewise_volume_conversion... | :param ul: microliters as a float
:param func: must be one of 'aspirate' or 'dispense'
:return: microliters/mm as a float |
def type(self, variant_probe_coverages, variant=None):
"""
Takes a list of VariantProbeCoverages and returns a Call for the Variant.
Note, in the simplest case the list will be of length one. However, we may be typing the
Variant on multiple backgrouds leading to multiple Var... | Takes a list of VariantProbeCoverages and returns a Call for the Variant.
Note, in the simplest case the list will be of length one. However, we may be typing the
Variant on multiple backgrouds leading to multiple VariantProbes for a single Variant. |
def getSingleVisualPropertyValue(self, networkId, viewId, objectType, objectId, visualProperty, verbose=None):
"""
Gets the Visual Property specificed by the `visualProperty` parameter for the node or edge specified by the `objectId` parameter in the Network View specified by the `viewId` and `networkId... | Gets the Visual Property specificed by the `visualProperty` parameter for the node or edge specified by the `objectId` parameter in the Network View specified by the `viewId` and `networkId` parameters.
Additional details on common Visual Properties can be found in the [Basic Visual Lexicon JavaDoc API... |
def _match_exec(self, i):
"""Looks at line 'i' for a subroutine or function definition."""
self.col_match = self.RE_EXEC.match(self._source[i])
if self.col_match is not None:
if self.col_match.group("codetype") == "function":
self.el_type = Function
else:
... | Looks at line 'i' for a subroutine or function definition. |
def DocbookSlidesHtml(env, target, source=None, *args, **kw):
"""
A pseudo-Builder, providing a Docbook toolchain for HTML slides output.
"""
# Init list of targets/sources
if not SCons.Util.is_List(target):
target = [target]
if not source:
source = target
target = ['inde... | A pseudo-Builder, providing a Docbook toolchain for HTML slides output. |
def lev_bounds(self):
"""Pressure levels at grid interfaces (hPa or mb)
:getter: Returns the bounds of axis ``'lev'`` if availible in the
process's domains.
:type: array
:raises: :exc:`ValueError`
if no ``'lev'`` axis can be found.
... | Pressure levels at grid interfaces (hPa or mb)
:getter: Returns the bounds of axis ``'lev'`` if availible in the
process's domains.
:type: array
:raises: :exc:`ValueError`
if no ``'lev'`` axis can be found. |
def get_dataset(self, key, info):
"""Get the dataset designated by *key*."""
res = super(HRITJMAFileHandler, self).get_dataset(key, info)
# Filenames of segmented data is identical for MTSAT-1R, MTSAT-2
# and Himawari-8/9. Make sure we have the correct reader for the data
# at h... | Get the dataset designated by *key*. |
def play_env_problem_randomly(env_problem,
num_steps):
"""Plays the env problem by randomly sampling actions for `num_steps`."""
# Reset all environments.
env_problem.reset()
# Play all environments, sampling random actions each time.
for _ in range(num_steps):
# Sample batc... | Plays the env problem by randomly sampling actions for `num_steps`. |
def update_key(
self, vault_base_url, key_name, key_version, key_ops=None, key_attributes=None, tags=None, custom_headers=None, raw=False, **operation_config):
"""The update key operation changes specified attributes of a stored key
and can be applied to any key type and key version stored i... | The update key operation changes specified attributes of a stored key
and can be applied to any key type and key version stored in Azure Key
Vault.
In order to perform this operation, the key must already exist in the
Key Vault. Note: The cryptographic material of a key itself cannot be... |
def tracking_save(sender, instance, raw, using, update_fields, **kwargs):
"""
Post save, detect creation or changes and log them.
We need post_save to have the object for a create.
"""
if _has_changed(instance):
if instance._original_fields['pk'] is None:
# Create
_cr... | Post save, detect creation or changes and log them.
We need post_save to have the object for a create. |
def QA_util_future_to_tradedatetime(real_datetime):
"""输入是真实交易时间,返回按期货交易所规定的时间* 适用于tb/文华/博弈的转换
Arguments:
real_datetime {[type]} -- [description]
Returns:
[type] -- [description]
"""
if len(str(real_datetime)) >= 19:
dt = datetime.datetime.strptime(
str(real_dat... | 输入是真实交易时间,返回按期货交易所规定的时间* 适用于tb/文华/博弈的转换
Arguments:
real_datetime {[type]} -- [description]
Returns:
[type] -- [description] |
def xstatus(self):
"""
UNIX-like exit status, only coherent if the context has stopped.
"""
return max(node.xstatus for node in self.nodes) if len(self.nodes) else 0 | UNIX-like exit status, only coherent if the context has stopped. |
def SetStatus(self, status, message="", backtrace=None):
"""Set a status to report back to the server."""
self.status.status = status
self.status.error_message = utils.SmartUnicode(message)
if backtrace:
self.status.backtrace = utils.SmartUnicode(backtrace) | Set a status to report back to the server. |
def add_platform(name, platform_set, server_url):
'''
To add an ASAM platform using the specified ASAM platform set on the Novell
Fan-Out Driver
CLI Example:
.. code-block:: bash
salt-run asam.add_platform my-test-vm test-platform-set prov1.domain.com
'''
config = _get_asam_config... | To add an ASAM platform using the specified ASAM platform set on the Novell
Fan-Out Driver
CLI Example:
.. code-block:: bash
salt-run asam.add_platform my-test-vm test-platform-set prov1.domain.com |
def team_names_to_ids(self):
"""Mapping from full team names to 3-letter team IDs.
:returns: Dictionary with tean names as keys and team IDs as values.
"""
d = self.team_ids_to_names()
return {v: k for k, v in d.items()} | Mapping from full team names to 3-letter team IDs.
:returns: Dictionary with tean names as keys and team IDs as values. |
def UNIFAC_groups(self):
r'''Dictionary of UNIFAC subgroup: count groups for the original
UNIFAC subgroups, as determined by `DDBST's online service <http://www.ddbst.com/unifacga.html>`_.
Examples
--------
>>> pprint(Chemical('Cumene').UNIFAC_groups)
{1: 2, 9: 5, 13: 1}... | r'''Dictionary of UNIFAC subgroup: count groups for the original
UNIFAC subgroups, as determined by `DDBST's online service <http://www.ddbst.com/unifacga.html>`_.
Examples
--------
>>> pprint(Chemical('Cumene').UNIFAC_groups)
{1: 2, 9: 5, 13: 1} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.