code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def networkMultiLevel(self, *modes, nodeCount = True, edgeWeight = True, stemmer = None, edgeAttribute = None, nodeAttribute = None, _networkTypeString = 'n-level network'):
"""Creates a network of the objects found by any number of tags _modes_, with edges between all co-occurring values. IF you only want edge... | Creates a network of the objects found by any number of tags _modes_, with edges between all co-occurring values. IF you only want edges between co-occurring values from different tags use [networkMultiMode()](#metaknowledge.CollectionWithIDs.networkMultiMode).
A **networkMultiLevel**() looks are each entry in... |
def _finalize_run(self):
"""Called by the environment after storing to perform some rollback operations.
All results and derived parameters created in the current run are removed.
Important for single processing to not blow up the parent trajectory with the results
of all runs.
... | Called by the environment after storing to perform some rollback operations.
All results and derived parameters created in the current run are removed.
Important for single processing to not blow up the parent trajectory with the results
of all runs. |
def parse(cls, spec, relative_to='', subproject_roots=None):
"""Parses an address from its serialized form.
:param string spec: An address in string form <path>:<name>.
:param string relative_to: For sibling specs, ie: ':another_in_same_build_family', interprets
the missing s... | Parses an address from its serialized form.
:param string spec: An address in string form <path>:<name>.
:param string relative_to: For sibling specs, ie: ':another_in_same_build_family', interprets
the missing spec_path part as `relative_to`.
:param list subproject_roots: Pa... |
def write_modes_to_file(self, filename="mode.dat", plot=True, analyse=True):
"""
Writes the mode fields to a file and optionally plots them.
Args:
filename (str): The nominal filename to use for the saved
data. The suffix will be automatically be changed to
... | Writes the mode fields to a file and optionally plots them.
Args:
filename (str): The nominal filename to use for the saved
data. The suffix will be automatically be changed to
identifiy each mode number. Default is 'mode.dat'
plot (bool): `True` if plo... |
def main():
"""Handles calling this module as a script
:return: None
"""
log = logging.getLogger(mod_logger + '.main')
parser = argparse.ArgumentParser(description='This Python module retrieves artifacts from Nexus.')
parser.add_argument('-u', '--url', help='Nexus Server URL', required=False)
... | Handles calling this module as a script
:return: None |
def filter_data(d, x, model="lms", **kwargs):
"""
Function that filter data with selected adaptive filter.
**Args:**
* `d` : desired value (1 dimensional array)
* `x` : input matrix (2-dimensional array). Rows are samples, columns are
input arrays.
**Kwargs:**
* An... | Function that filter data with selected adaptive filter.
**Args:**
* `d` : desired value (1 dimensional array)
* `x` : input matrix (2-dimensional array). Rows are samples, columns are
input arrays.
**Kwargs:**
* Any key argument that can be accepted with selected filter m... |
def parse_readme(cls, readme_path: str = 'README.rst', encoding: str = 'utf-8') -> str:
"""Parse readme and resolve relative links in it if it is feasible.
Links are resolved if readme is in rst format and the package is hosted on GitHub.
"""
with HERE.joinpath(readme_path).open(encodin... | Parse readme and resolve relative links in it if it is feasible.
Links are resolved if readme is in rst format and the package is hosted on GitHub. |
def overlay(ctx): # pragma: no cover
""" Install gilt dependencies """
args = ctx.obj.get('args')
filename = args.get('config')
debug = args.get('debug')
_setup(filename)
for c in config.config(filename):
with fasteners.InterProcessLock(c.lock_file):
util.print_info('{}:'.f... | Install gilt dependencies |
def find_prime_polys(generator=2, c_exp=8, fast_primes=False, single=False):
'''Compute the list of prime polynomials for the given generator and galois field characteristic exponent.'''
# fast_primes will output less results but will be significantly faster.
# single will output the first prime polynomial ... | Compute the list of prime polynomials for the given generator and galois field characteristic exponent. |
def __AddEntryType(self, entry_type_name, entry_schema, parent_name):
"""Add a type for a list entry."""
entry_schema.pop('description', None)
description = 'Single entry in a %s.' % parent_name
schema = {
'id': entry_type_name,
'type': 'object',
'desc... | Add a type for a list entry. |
def status_reply(self, to_status, status, media_ids=None, sensitive=False, visibility=None,
spoiler_text=None, language=None, idempotency_key=None, content_type=None,
scheduled_at=None, poll=None, untag=False):
"""
Helper function - acts like status_post, but p... | Helper function - acts like status_post, but prepends the name of all
the users that are being replied to to the status text and retains
CW and visibility if not explicitly overridden.
Set `untag` to True if you want the reply to only go to the user you
are replying to, removing... |
def distance_between(self, string, start, end):
"""Returns number of lines between start and end"""
count = 0
started = False
for line in string.split("\n"):
if self.scan_line(line, start) and not started:
started = True
if self.scan_line(line, ... | Returns number of lines between start and end |
def _parse_rnaseq_qualimap_metrics(report_file):
"""Extract useful metrics from the qualimap HTML report file.
"""
from bs4 import BeautifulSoup
out = {}
parsers = ["Reads alignment", "Reads genomic origin", "Transcript coverage profile"]
with open(report_file) as in_handle:
root = Beaut... | Extract useful metrics from the qualimap HTML report file. |
def newDocNodeEatName(self, doc, name, content):
"""Creation of a new node element within a document. @ns and
@content are optional (None). NOTE: @content is supposed to
be a piece of XML CDATA, so it allow entities references,
but XML special chars need to be escaped first by usin... | Creation of a new node element within a document. @ns and
@content are optional (None). NOTE: @content is supposed to
be a piece of XML CDATA, so it allow entities references,
but XML special chars need to be escaped first by using
xmlEncodeEntitiesReentrant(). Use xmlNewDocRawNo... |
def update(self):
"""Update |KI2| based on |EQI2| and |TInd|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> eqi2(1.0)
>>> tind.value = 10.0
>>> derived.ki2.update()
>>> derived.ki2
ki2(10.0)
"""
con = self.subpars.pars.c... | Update |KI2| based on |EQI2| and |TInd|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> eqi2(1.0)
>>> tind.value = 10.0
>>> derived.ki2.update()
>>> derived.ki2
ki2(10.0) |
def mmap_key(metric_name, name, labelnames, labelvalues):
"""Format a key for use in the mmap file."""
# ensure labels are in consistent order for identity
labels = dict(zip(labelnames, labelvalues))
return json.dumps([metric_name, name, labels], sort_keys=True) | Format a key for use in the mmap file. |
def get_perm_model():
"""
Returns the Perm model that is active in this project.
"""
try:
return django_apps.get_model(settings.PERM_MODEL, require_ready=False)
except ValueError:
raise ImproperlyConfigured("PERM_MODEL must be of the form 'app_label.model_name'")
except LookupErr... | Returns the Perm model that is active in this project. |
def pre_save(self, model_instance, add):
"""
Process the source image through the defined processors.
"""
file = getattr(model_instance, self.attname)
if file and not file._committed:
image_file = file
if self.resize_source_to:
file.seek(0... | Process the source image through the defined processors. |
def _write(self, content, mode, encoding=None, linesep=False):
"""Handles file writes."""
makedirs(self.path)
try:
encoding = encoding or ENCODING
if "b" not in mode:
try:
content = str(content)
except:
... | Handles file writes. |
def asfactor(self):
"""
Convert columns in the current frame to categoricals.
:returns: new H2OFrame with columns of the "enum" type.
"""
for colname in self.names:
t = self.types[colname]
if t not in {"bool", "int", "string", "enum"}:
rai... | Convert columns in the current frame to categoricals.
:returns: new H2OFrame with columns of the "enum" type. |
def storage_factory(storage_service, trajectory=None, **kwargs):
"""Creates a storage service, to be extended if new storage services are added
:param storage_service:
Storage Service instance of constructor or a string pointing to a file
:param trajectory:
A trajectory instance
:pa... | Creates a storage service, to be extended if new storage services are added
:param storage_service:
Storage Service instance of constructor or a string pointing to a file
:param trajectory:
A trajectory instance
:param kwargs:
Arguments passed to the storage service
:retur... |
def zero_extend(self, new_length):
"""
Unary operation: ZeroExtend
:param new_length: New length after zero-extension
:return: A new StridedInterval
"""
si = self.copy()
si._bits = new_length
return si | Unary operation: ZeroExtend
:param new_length: New length after zero-extension
:return: A new StridedInterval |
def dict_merge(self, merge_to, merge_in):
'''
Recursively merges two dicts
Overwrites any non-dictionary items
merge_to <- merge_in
Modifies merge_to dictionary
@param merge_to: Base dictionary to merge into
@param merge_in: Dictionary that may overwrite element... | Recursively merges two dicts
Overwrites any non-dictionary items
merge_to <- merge_in
Modifies merge_to dictionary
@param merge_to: Base dictionary to merge into
@param merge_in: Dictionary that may overwrite elements in merge_in |
def configure_plugin(self, name, options):
"""
Configure a plugin.
Args:
name (string): The name of the plugin. The ``:latest`` tag is
optional, and is the default if omitted.
options (dict): A key-value mapping of options
... | Configure a plugin.
Args:
name (string): The name of the plugin. The ``:latest`` tag is
optional, and is the default if omitted.
options (dict): A key-value mapping of options
Returns:
``True`` if successful |
def make_outpoint(tx_id_le, index, tree=None):
'''
byte-like, int, int -> Outpoint
'''
if 'decred' in riemann.get_current_network_name():
return tx.DecredOutpoint(tx_id=tx_id_le,
index=utils.i2le_padded(index, 4),
tree=utils.i2le_... | byte-like, int, int -> Outpoint |
def load_remote_trajectory(url, format=None):
'''Load a trajectory file from a remote location specified by *url*.
.. seealso:: load_remote_system
'''
from urllib import urlretrieve
filename, headers = urlretrieve(url)
load_trajectory(filename, format) | Load a trajectory file from a remote location specified by *url*.
.. seealso:: load_remote_system |
def dfsmooth (window, df, ucol, k=None):
"""Smooth a :class:`pandas.DataFrame` according to a window, weighting based on
uncertainties.
Arguments are:
window
The smoothing window.
df
The :class:`pandas.DataFrame`.
ucol
The name of the column in *df* that contains the uncertai... | Smooth a :class:`pandas.DataFrame` according to a window, weighting based on
uncertainties.
Arguments are:
window
The smoothing window.
df
The :class:`pandas.DataFrame`.
ucol
The name of the column in *df* that contains the uncertainties to weight
by.
k = None
If ... |
def get_service_details(self, service_id):
"""List detailed information on a specified service."""
content = self._fetch("/service/%s/details" % service_id)
return FastlyService(self, content) | List detailed information on a specified service. |
def getProcList(self, fields=('pid', 'user', 'cmd',), threads=False,
**kwargs):
"""Execute ps command with custom output format with columns columns
from fields, select lines using the filters defined by kwargs and return
result as a nested list.
The Standa... | Execute ps command with custom output format with columns columns
from fields, select lines using the filters defined by kwargs and return
result as a nested list.
The Standard Format Specifiers from ps man page must be used for the
fields parameter.
@param fi... |
def from_dict(cls, d):
"""
As in :Class: `pymatgen.core.Molecule` except
restoring graphs using `from_dict_of_dicts`
from NetworkX to restore graph information.
"""
m = Molecule.from_dict(d['molecule'])
return cls(m, d['graphs']) | As in :Class: `pymatgen.core.Molecule` except
restoring graphs using `from_dict_of_dicts`
from NetworkX to restore graph information. |
def zip_dir(zip_name, source_dir,rename_source_dir=False):
'''
https://stackoverflow.com/questions/1855095/how-to-create-a-zip-archive-of-a-directory
'''
src_path = Path(source_dir).expanduser().resolve()
with ZipFile(zip_name, 'w', ZIP_DEFLATED) as zf:
for file in src_path.rglob('*'):
... | https://stackoverflow.com/questions/1855095/how-to-create-a-zip-archive-of-a-directory |
def get_farthest_entries(self, type_measurement):
"""!
@brief Find pair of farthest entries of the node.
@param[in] type_measurement (measurement_type): Measurement type that is used for obtaining farthest entries.
@return (list) Pair of farthest entries of the no... | !
@brief Find pair of farthest entries of the node.
@param[in] type_measurement (measurement_type): Measurement type that is used for obtaining farthest entries.
@return (list) Pair of farthest entries of the node that are represented by list. |
def _guess_header(info):
"""Add the first group to get report with some factor"""
value = "group"
if "metadata" in info:
if info["metadata"]:
return ",".join(map(str, info["metadata"].keys()))
return value | Add the first group to get report with some factor |
def to_html_(self) -> str:
"""Convert the main dataframe to html
:return: html data
:rtype: str
:example: ``ds.to_html_()``
"""
try:
renderer = pytablewriter.HtmlTableWriter
data = self._build_export(renderer)
return data
exce... | Convert the main dataframe to html
:return: html data
:rtype: str
:example: ``ds.to_html_()`` |
def update(self):
""" Update reviewers' anomalous scores and products' summaries.
The update consists of 2 steps;
Step1 (updating summaries):
Update summaries of products with anomalous scores of reviewers
and weight function. The weight is calculated by the manner in
... | Update reviewers' anomalous scores and products' summaries.
The update consists of 2 steps;
Step1 (updating summaries):
Update summaries of products with anomalous scores of reviewers
and weight function. The weight is calculated by the manner in
:class:`ria.biparti... |
def decrypt_file(self, filename):
'''
Decrypt File
Args:
filename: Pass the filename to encrypt.
Returns:
No return.
'''
if not os.path.exists(filename):
print "Invalid filename %s. Does not exist" % filename
return
... | Decrypt File
Args:
filename: Pass the filename to encrypt.
Returns:
No return. |
def get_attrs_to_paths(schema, attrs_to_paths=None, path=None):
"""Analyze PREMIS-element-as-tuple ``schema`` and return a dict that maps
attribute names to the simplified XPaths needed to retrieve them, e.g.,::
>>> {'object_identifier_type':
'object_identifier/object_identifier_type',
... | Analyze PREMIS-element-as-tuple ``schema`` and return a dict that maps
attribute names to the simplified XPaths needed to retrieve them, e.g.,::
>>> {'object_identifier_type':
'object_identifier/object_identifier_type',
'object_identifier_value':
'object_identif... |
def blast(args):
"""
%prog blast ref.fasta query.fasta
Calls blast and then filter the BLAST hits. Default is megablast.
"""
task_choices = ("blastn", "blastn-short", "dc-megablast", \
"megablast", "vecscreen")
p = OptionParser(blast.__doc__)
p.set_align(pctid=0, evalue=... | %prog blast ref.fasta query.fasta
Calls blast and then filter the BLAST hits. Default is megablast. |
def install():
""" Install the import hook to load extensions from the app Lib folder.
Like imports but leaves it in the meta_path, thus it is slower.
"""
from .core.import_hooks import ExtensionImporter
importer = ExtensionImporter()
sys.meta_path.append(importer) | Install the import hook to load extensions from the app Lib folder.
Like imports but leaves it in the meta_path, thus it is slower. |
def transform_conf_module(cls):
"""Transform usages of the conf module by updating locals."""
global CONF_NODE
if cls.name == 'openhtf.conf':
# Put all the attributes in Configuration into the openhtf.conf node.
cls._locals.update(cls.locals['Configuration'][0].locals)
# Store reference to this node... | Transform usages of the conf module by updating locals. |
def get_all_deferred_code_breakpoints(self):
"""
Returns a list of deferred code breakpoints.
@rtype: tuple of (int, str, callable, bool)
@return: Tuple containing the following elements:
- Process ID where to set the breakpoint.
- Label pointing to the addres... | Returns a list of deferred code breakpoints.
@rtype: tuple of (int, str, callable, bool)
@return: Tuple containing the following elements:
- Process ID where to set the breakpoint.
- Label pointing to the address where to set the breakpoint.
- Action callback for... |
def _create_json(self):
"""
JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Repository+Configuration+JSON
"""
data_json = {
"rclass": "virtual",
"key": self.name,
"description": self.description,
"packageType": self.package... | JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Repository+Configuration+JSON |
def claim(self, ttl, grace, count=None):
"""
Claims up to `count` unclaimed messages from this queue. If count is
not specified, the default is to claim 10 messages.
The `ttl` parameter specifies how long the server should wait before
releasing the claim. The ttl value MUST be b... | Claims up to `count` unclaimed messages from this queue. If count is
not specified, the default is to claim 10 messages.
The `ttl` parameter specifies how long the server should wait before
releasing the claim. The ttl value MUST be between 60 and 43200 seconds.
The `grace` parameter i... |
def find_shows_by_related(self, show_id,
count=20):
"""doc: http://open.youku.com/docs/doc?id=63
"""
url = 'https://openapi.youku.com/v2/shows/by_related.json'
params = {
'client_id': self.client_id,
'show_id': show_id,
'c... | doc: http://open.youku.com/docs/doc?id=63 |
def update_company(self, company):
"""Update company settings
:param company: updated settings
:type company: ``dict``
:rtype: ``bool``
"""
if not isinstance(company, dict):
raise AttributeError('company must be a <dict>')
method, url = get_URL('com... | Update company settings
:param company: updated settings
:type company: ``dict``
:rtype: ``bool`` |
def get_table_content(self, table):
"""trick to get table content without actually writing it
return an aligned list of lists containing table cells values as string
"""
result = [[]]
cols = table.cols
for cell in self.compute_content(table):
if cols == 0:
... | trick to get table content without actually writing it
return an aligned list of lists containing table cells values as string |
def _get_pubkey_hash(cert):
'''
Returns the sha1 hash of the modulus of a public key in a cert
Used for generating subject key identifiers
'''
sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()
return _pretty_hex(sha_hash) | Returns the sha1 hash of the modulus of a public key in a cert
Used for generating subject key identifiers |
def get_properties_by_type(self, type, recursive=True, parent_path=""):
"""
Returns a sorted list of fields that match the type.
:param type the type of the field "string","integer" or a list of types
:param recursive recurse to sub object
:returns a sorted list of fields the ma... | Returns a sorted list of fields that match the type.
:param type the type of the field "string","integer" or a list of types
:param recursive recurse to sub object
:returns a sorted list of fields the match the type |
def as_dict(self):
"""
Returns this Record as a dictionary using the field names as keys
:return: dict
"""
return dict((f, self[i]) for f, i in self.__field_positions.items()) | Returns this Record as a dictionary using the field names as keys
:return: dict |
def clean_source_files(self):
"""Remove the schema.csv and source_schema.csv files"""
self.build_source_files.file(File.BSFILE.SOURCESCHEMA).remove()
self.build_source_files.file(File.BSFILE.SCHEMA).remove()
self.commit() | Remove the schema.csv and source_schema.csv files |
def remove_all_containers(self, stop_timeout=10, list_only=False):
"""
First stops (if necessary) and them removes all containers present on the Docker instance.
:param stop_timeout: Timeout to stopping each container.
:type stop_timeout: int
:param list_only: When set to ``True... | First stops (if necessary) and them removes all containers present on the Docker instance.
:param stop_timeout: Timeout to stopping each container.
:type stop_timeout: int
:param list_only: When set to ``True`` only lists containers, but does not actually stop or remove them.
:type list... |
def send_error_email(subject, message, additional_recipients=None):
"""
Sends an email to the configured error email, if it's configured.
"""
recipients = _email_recipients(additional_recipients)
sender = email().sender
send_email(
subject=subject,
message=message,
sender... | Sends an email to the configured error email, if it's configured. |
def get_vlan_brief_output_unprovisioned_vlans_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
unprovisioned_vlans... | Auto Generated Code |
def get_historical_output(self, assessment, options):
"""
To get output of a historical Assessment
:param assessment: string
:param options: dict
"""
responseFormat=None
if options and 'format' in options and options['format'] is not None:
responseForm... | To get output of a historical Assessment
:param assessment: string
:param options: dict |
def load_object(self, value):
"""The reversal of :meth:`dump_object`. This might be callde with
None.
"""
if value is None:
return None
if value.startswith(b'!'):
try:
return pickle.loads(value[1:])
except pickle.PickleError:
... | The reversal of :meth:`dump_object`. This might be callde with
None. |
def full_url(url='', domain=None, protocol='https'):
"""
Prepend protocol (default to https) and domain name (default from the Site framework) to an url
"""
if domain is None:
from django.contrib.sites.models import Site
domain = Site.objects.get_current().domain
return f'{protocol}:... | Prepend protocol (default to https) and domain name (default from the Site framework) to an url |
def source_loader(self, source_paths, create_missing_tables=True):
"""Load source from 3 csv files.
First file should contain global settings:
* ``native_lagnauge,languages`` header on first row
* appropriate values on following rows
Example::
native_lagnauge,lang... | Load source from 3 csv files.
First file should contain global settings:
* ``native_lagnauge,languages`` header on first row
* appropriate values on following rows
Example::
native_lagnauge,languages
ru,ru
,en
Second file should contain ... |
def raise_402(instance, msg=None):
"""Abort the current request with a 402 (Payment Required) response code.
If the message is given it's output as an error message in the response
body (correctly converted to the requested MIME type).
:param instance: Resource instance (used to access the response)
... | Abort the current request with a 402 (Payment Required) response code.
If the message is given it's output as an error message in the response
body (correctly converted to the requested MIME type).
:param instance: Resource instance (used to access the response)
:type instance: :class:`webob.resource.R... |
def save_state(self):
"""Store the options into the user's stored session info.
.. versionadded: 4.3.0
"""
settings = QtCore.QSettings()
settings.setValue(
'inasafe/useDefaultTemplates',
self.default_template_radio.isChecked())
settings.setValue(
... | Store the options into the user's stored session info.
.. versionadded: 4.3.0 |
def quadraticEval(a, b, c, x):
"""given all params return the result of quadratic equation a*x^2 + b*x + c"""
return a*(x**2) + b*x + c | given all params return the result of quadratic equation a*x^2 + b*x + c |
def start(self, input_data=None):
"""
Calls Docker API to start the container. The container must be created at the first place to run.
It waits for the container to complete, fetches both stdout and stderr logs and returns through the
given streams.
Parameters
---------... | Calls Docker API to start the container. The container must be created at the first place to run.
It waits for the container to complete, fetches both stdout and stderr logs and returns through the
given streams.
Parameters
----------
input_data
Optional. Input data ... |
def connect(self):
"""Connects the client object to redis.
It's safe to use this method even if you are already connected.
Note: this method is useless with autoconnect mode (default).
Returns:
a Future object with True as result if the connection was ok.
"""
... | Connects the client object to redis.
It's safe to use this method even if you are already connected.
Note: this method is useless with autoconnect mode (default).
Returns:
a Future object with True as result if the connection was ok. |
def chunks(stream, size=None):
'''
Returns a generator of chunks from the `stream` with a maximum
size of `size`. I don't know why this isn't part of core Python.
:Parameters:
stream : file-like object
The stream to fetch the chunks from. Note that the stream will
not be repositioned in any way.
... | Returns a generator of chunks from the `stream` with a maximum
size of `size`. I don't know why this isn't part of core Python.
:Parameters:
stream : file-like object
The stream to fetch the chunks from. Note that the stream will
not be repositioned in any way.
size : int | 'lines'; default: null
... |
def footer(self):
'''
Returns the axis instance where the footer will be printed
'''
return self.footer_left(on=False), self.footer_center(on=False), \
self.footer_right(on=False) | Returns the axis instance where the footer will be printed |
def transferring_item(self, item, increment_amt=1):
"""
Update progress that item is about to be transferred.
:param item: LocalFile, LocalFolder, or LocalContent(project) that is about to be sent.
:param increment_amt: int amount to increase our count(how much progress have we made)
... | Update progress that item is about to be transferred.
:param item: LocalFile, LocalFolder, or LocalContent(project) that is about to be sent.
:param increment_amt: int amount to increase our count(how much progress have we made) |
def create_lead(self, first_name, last_name, email=None, position=None,
company=None, company_industry=None, company_size=None,
confidence_score=None, website=None, country_code=None,
postal_code=None, source=None, linkedin_url=None,
phone_... | Create a lead on your account.
:param first_name: The first name of the lead to create. Must be
defined.
:param last_name: The last name of the lead to create. Must be defined.
:param email: The email of the lead to create.
:param position: The professional position of the le... |
def _reduce_opacity(self, watermark, opacity):
"""
Returns an image with reduced opacity. Converts image to RGBA if needs.
Simple watermark.opacity(65535 - int(65535 * opacity) would not work for
images with the Opacity channel (RGBA images). So we have to convert RGB or any
oth... | Returns an image with reduced opacity. Converts image to RGBA if needs.
Simple watermark.opacity(65535 - int(65535 * opacity) would not work for
images with the Opacity channel (RGBA images). So we have to convert RGB or any
other type to RGBA in this case |
def _get_extra(self, attrs, exclude):
"""Read the extra properties, taking into account an exclude list"""
result = {}
for key in attrs.getNames():
if key not in exclude:
result[str(key)] = str(attrs[key])
return result | Read the extra properties, taking into account an exclude list |
def uncancel(self):
"""Uncancel an EighthScheduledActivity.
This does nothing besides unset the cancelled flag and save the
object.
"""
if self.cancelled:
logger.debug("Uncancelling {}".format(self))
self.cancelled = False
self.save()
# ... | Uncancel an EighthScheduledActivity.
This does nothing besides unset the cancelled flag and save the
object. |
def estimate_assignment_probs(q, trials, cxn, p0=None):
"""
Estimate the readout assignment probabilities for a given qubit ``q``.
The returned matrix is of the form::
[[p00 p01]
[p10 p11]]
:param int q: The index of the qubit.
:param int trials: The number of samples for ... | Estimate the readout assignment probabilities for a given qubit ``q``.
The returned matrix is of the form::
[[p00 p01]
[p10 p11]]
:param int q: The index of the qubit.
:param int trials: The number of samples for each state preparation.
:param Union[QVMConnection,QPUConnection... |
def Gharagheizi_liquid(T, M, Tb, Pc, omega):
r'''Estimates the thermal conductivity of a liquid as a function of
temperature using the CSP method of Gharagheizi [1]_. A convoluted
method claiming high-accuracy and using only statistically significant
variable following analalysis.
Requires tempera... | r'''Estimates the thermal conductivity of a liquid as a function of
temperature using the CSP method of Gharagheizi [1]_. A convoluted
method claiming high-accuracy and using only statistically significant
variable following analalysis.
Requires temperature, molecular weight, boiling temperature and c... |
def print_device_list(self, device_list=None):
"""
Optional parameter is a list of device objects. If omitted, will
just print all portal devices objects.
"""
dev_list = device_list if device_list is not None else self.get_all_devices_in_portal()
for dev in dev_l... | Optional parameter is a list of device objects. If omitted, will
just print all portal devices objects. |
def render_to(self, path, template, **data):
"""Render data with template and then write to path"""
html = self.render(template, **data)
with open(path, 'w') as f:
f.write(html.encode(charset)) | Render data with template and then write to path |
def create_bootstrap_tour(self, name=None):
""" Creates a Bootstrap tour for a website.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
"""
if not name:
name = "default"
... | Creates a Bootstrap tour for a website.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to. |
def move_drive_to_H(slh, which=None, expand_simplify=True):
r'''Move coherent drives from the Lindblad operators to the Hamiltonian.
For the given SLH model, move inhomogeneities in the Lindblad operators (resulting
from the presence of a coherent drive, see :class:`CoherentDriveCC`) to the
Hamiltonian... | r'''Move coherent drives from the Lindblad operators to the Hamiltonian.
For the given SLH model, move inhomogeneities in the Lindblad operators (resulting
from the presence of a coherent drive, see :class:`CoherentDriveCC`) to the
Hamiltonian.
This exploits the invariance of the Lindblad master equat... |
def angle(self, other):
"""Return the angle to the vector other"""
return math.acos(self.dot(other) / (self.magnitude() * other.magnitude())) | Return the angle to the vector other |
def get_glyph(self, char):
'''Retrieves a :class:`Glyph` that renders the given character.
:param char: the character (a string)
'''
try:
return self._glyphs[char]
except KeyError:
glyph = self._font_file.get_glyph(self._size, self._content_scale, char, s... | Retrieves a :class:`Glyph` that renders the given character.
:param char: the character (a string) |
def locally_linear_embedding(geom, n_components, reg=1e-3,
eigen_solver='auto', random_state=None,
solver_kwds=None):
"""
Perform a Locally Linear Embedding analysis on the data.
Parameters
----------
geom : a Geometry object from megaman.geo... | Perform a Locally Linear Embedding analysis on the data.
Parameters
----------
geom : a Geometry object from megaman.geometry.geometry
n_components : integer
number of coordinates for the manifold.
reg : float
regularization constant, multiplies the trace of the local covariance
... |
def get_grade_systems_by_query(self, grade_system_query):
"""Gets a list of ``GradeSystem`` objects matching the given grade system query.
arg: grade_system_query (osid.grading.GradeSystemQuery): the
grade system query
return: (osid.grading.GradeSystemList) - the returned
... | Gets a list of ``GradeSystem`` objects matching the given grade system query.
arg: grade_system_query (osid.grading.GradeSystemQuery): the
grade system query
return: (osid.grading.GradeSystemList) - the returned
``GradeSystemList``
raise: NullArgument - ``gra... |
def get_sec2gos(sortobj):
"""Initialize section_name2goids."""
sec_gos = []
for section_name, nts in sortobj.get_desc2nts_fnc(hdrgo_prt=True)['sections']:
sec_gos.append((section_name, set(nt.GO for nt in nts)))
return cx.OrderedDict(sec_gos) | Initialize section_name2goids. |
def visualize(x, y, xlabel=None, ylabel=None, title=None, ylim=None):
"""A universal function plot arbitrary time series data.
"""
total_seconds = (x[-1] - x[0]).total_seconds()
if total_seconds <= 86400 * 1 * 3:
return plot_one_day(x, y, xlabel, ylabel, title, ylim)
elif total_seconds ... | A universal function plot arbitrary time series data. |
def to_file(self, path, precision='%.2g'):
"""
Create a CSV report of the trackables
:param path: path to file
:param precision: numeric string formatter
"""
table_info = self.get_table_info()
def dump_rows(rows):
if len(rows) > 1:
for... | Create a CSV report of the trackables
:param path: path to file
:param precision: numeric string formatter |
def skus(self):
"""Instance depends on the API version:
* 2017-06-01: :class:`SkusOperations<azure.mgmt.storage.v2017_06_01.operations.SkusOperations>`
* 2017-10-01: :class:`SkusOperations<azure.mgmt.storage.v2017_10_01.operations.SkusOperations>`
* 2018-02-01: :class:`SkusOper... | Instance depends on the API version:
* 2017-06-01: :class:`SkusOperations<azure.mgmt.storage.v2017_06_01.operations.SkusOperations>`
* 2017-10-01: :class:`SkusOperations<azure.mgmt.storage.v2017_10_01.operations.SkusOperations>`
* 2018-02-01: :class:`SkusOperations<azure.mgmt.storage.v... |
def call(args, stdout=None, stderr=None, stdin=None, daemonize=False,
preexec_fn=None, shell=False, cwd=None, env=None):
"""
Run an external command in a separate process and detach it from the current process. Excepting
`stdout`, `stderr`, and `stdin` all file descriptors are closed after forking.... | Run an external command in a separate process and detach it from the current process. Excepting
`stdout`, `stderr`, and `stdin` all file descriptors are closed after forking. If `daemonize`
is True then the parent process exits. All stdio is redirected to `os.devnull` unless
specified. The `preexec_fn`, `sh... |
def check_bounds(self):
"""Make sure the camera is not outside if its legal range."""
if not (self.camera_bounds == None):
if self.__pan.X < self.camera_bounds.Left:
self.__pan[0] = self.camera_bounds.Left
if self.__pan.X > self.camera_bounds.Right:
... | Make sure the camera is not outside if its legal range. |
def command_start(self, daemonize=False):
'''
Start a server::
./manage.py flup:start [--daemonize]
'''
if daemonize:
safe_makedirs(self.logfile, self.pidfile)
flup_fastcgi(self.app, bind=self.bind, pidfile=self.pidfile,
logfile=self.... | Start a server::
./manage.py flup:start [--daemonize] |
def compute(datetimes, to_np=None): # @NoSelf
"""
Computes the provided date/time components into CDF epoch value(s).
For CDF_EPOCH:
For computing into CDF_EPOCH value, each date/time elements should
have exactly seven (7) components, as year, month, day, hour, ... | Computes the provided date/time components into CDF epoch value(s).
For CDF_EPOCH:
For computing into CDF_EPOCH value, each date/time elements should
have exactly seven (7) components, as year, month, day, hour, minute,
second and millisecond, in a list. For exam... |
def from_raw_seed(cls, raw_seed):
"""Generate a :class:`Keypair` object via a sequence of bytes.
Typically these bytes are random, such as the usage of
:func:`os.urandom` in :meth:`Keypair.random`. However this class method
allows you to use an arbitrary sequence of bytes, provided the ... | Generate a :class:`Keypair` object via a sequence of bytes.
Typically these bytes are random, such as the usage of
:func:`os.urandom` in :meth:`Keypair.random`. However this class method
allows you to use an arbitrary sequence of bytes, provided the sequence
is 32 bytes long.
:... |
def save_as(self, new_filename):
"""
Save our file with the name provided.
Args:
new_filename: New name for the workbook file. String.
Returns:
Nothing.
"""
xfile._save_file(
self._filename, self._workbookTree, new_filename) | Save our file with the name provided.
Args:
new_filename: New name for the workbook file. String.
Returns:
Nothing. |
def _rsplit(expr, pat=None, n=-1):
"""
Split each string in the Series/Index by the given delimiter string,
starting at the end of the string and working to the front.
Equivalent to str.rsplit().
:param expr:
:param pat: Separator to split on. If None, splits on whitespace
:param n: None, 0... | Split each string in the Series/Index by the given delimiter string,
starting at the end of the string and working to the front.
Equivalent to str.rsplit().
:param expr:
:param pat: Separator to split on. If None, splits on whitespace
:param n: None, 0 and -1 will be interpreted as return all split... |
def Client(api_version, *args, **kwargs):
"""Return an neutron client.
@param api_version: only 2.0 is supported now
"""
neutron_client = utils.get_client_class(
API_NAME,
api_version,
API_VERSIONS,
)
return neutron_client(*args, **kwargs) | Return an neutron client.
@param api_version: only 2.0 is supported now |
def is_image(f, types=('png', 'jpeg', 'gif'), set_content_type=True):
"""
Return True if file f is image (types type) and set its correct content_type and filename extension.
Example:
if is_image(request.FILES['file']):
print 'File is image'
if is_image(open('/tmp/image.jpeg', '... | Return True if file f is image (types type) and set its correct content_type and filename extension.
Example:
if is_image(request.FILES['file']):
print 'File is image'
if is_image(open('/tmp/image.jpeg', 'rb')):
print 'File is image' |
def remove_all_gap_columns( components ):
"""
Remove any columns containing only gaps from a set of alignment components,
text of components is modified IN PLACE.
TODO: Optimize this with Pyrex.
"""
seqs = [ list( c.text ) for c in components ]
i = 0
text_size = len( seqs[0]... | Remove any columns containing only gaps from a set of alignment components,
text of components is modified IN PLACE.
TODO: Optimize this with Pyrex. |
async def iter_lines(self, chunk_size=1024):
"""Return an iterator to yield lines from the raw stream.
This is achieved by reading chunk of bytes (of size chunk_size) at a
time from the raw stream, and then yielding lines from there.
"""
pending = b''
async for chunk in ... | Return an iterator to yield lines from the raw stream.
This is achieved by reading chunk of bytes (of size chunk_size) at a
time from the raw stream, and then yielding lines from there. |
def set_logging_config(log_level, handlers):
"""Set python logging library config.
Run this ONCE at the start of your process. It formats the python logging
module's output.
Defaults logging level to INFO = 20)
"""
logging.basicConfig(
format='%(asctime)s %(levelname)s:%(name)s:%(funcNa... | Set python logging library config.
Run this ONCE at the start of your process. It formats the python logging
module's output.
Defaults logging level to INFO = 20) |
def _create_min_max_boundaries(
max_length, min_boundary=_MIN_BOUNDARY, boundary_scale=_BOUNDARY_SCALE):
"""Create min and max boundary lists up to max_length.
For example, when max_length=24, min_boundary=4 and boundary_scale=2, the
returned values will be:
buckets_min = [0, 4, 8, 16, 24]
buckets_ma... | Create min and max boundary lists up to max_length.
For example, when max_length=24, min_boundary=4 and boundary_scale=2, the
returned values will be:
buckets_min = [0, 4, 8, 16, 24]
buckets_max = [4, 8, 16, 24, 25]
Args:
max_length: The maximum length of example in dataset.
min_boundary: Minimu... |
def glir(self):
""" The GLIR queue corresponding to the current canvas
"""
canvas = get_current_canvas()
if canvas is None:
msg = ("If you want to use gloo without vispy.app, " +
"use a gloo.context.FakeCanvas.")
raise RuntimeError('Gloo requir... | The GLIR queue corresponding to the current canvas |
def base_url(klass, space_id, webhook_id, resource_id=None):
"""
Returns the URI for the webhook call.
"""
return "spaces/{0}/webhooks/{1}/calls/{2}".format(
space_id,
webhook_id,
resource_id if resource_id is not None else ''
) | Returns the URI for the webhook call. |
def create(self, max_wait=180, **kwargs):
"""
Create an instance of the Predix Cache Service with they typical
starting settings.
:param max_wait: service is created asynchronously, so will only wait
this number of seconds before giving up.
"""
# Will need t... | Create an instance of the Predix Cache Service with they typical
starting settings.
:param max_wait: service is created asynchronously, so will only wait
this number of seconds before giving up. |
def surface_area(self):
r"""Calculate all atomic surface area.
:rtype: [float]
"""
return [self.atomic_sa(i) for i in range(len(self.rads))] | r"""Calculate all atomic surface area.
:rtype: [float] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.