code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def getFiledAgainst(self, filedagainst_name, projectarea_id=None,
projectarea_name=None, archived=False):
"""Get :class:`rtcclient.models.FiledAgainst` object by its name
:param filedagainst_name: the filedagainst name
:param projectarea_id: the :class:`rtcclient.project... | Get :class:`rtcclient.models.FiledAgainst` object by its name
:param filedagainst_name: the filedagainst name
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
id
:param projectarea_name: the project area name
:param archived: (default is False) whether ... |
def prepare_encoder(inputs, hparams, attention_type="local_1d"):
"""Prepare encoder for images."""
x = prepare_image(inputs, hparams, name="enc_channels")
# Add position signals.
x = add_pos_signals(x, hparams, "enc_pos")
x_shape = common_layers.shape_list(x)
if attention_type == "local_1d":
x = tf.resh... | Prepare encoder for images. |
def x_lower_limit(self, limit=None):
"""Returns or sets (if a value is provided) the value at which the
x-axis should start. By default this is zero (unless there are negative
values).
:param limit: If given, the chart's x_lower_limit will be set to this.
:raises ValueError: if ... | Returns or sets (if a value is provided) the value at which the
x-axis should start. By default this is zero (unless there are negative
values).
:param limit: If given, the chart's x_lower_limit will be set to this.
:raises ValueError: if you try to make the lower limit larger than the\... |
def element(element, name, default=None):
"""
Returns the value of an element, or a default if it's not defined
:param element: The XML Element object
:type element: etree._Element
:param name: The name of the element to evaluate
:type name: str
:param default: The default value to retur... | Returns the value of an element, or a default if it's not defined
:param element: The XML Element object
:type element: etree._Element
:param name: The name of the element to evaluate
:type name: str
:param default: The default value to return if the element is not defined |
def _next_regular(target):
"""
Find the next regular number greater than or equal to target.
Regular numbers are composites of the prime factors 2, 3, and 5.
Also known as 5-smooth numbers or Hamming numbers, these are the optimal
size for inputs to FFTPACK.
Target must be a positive integer.
... | Find the next regular number greater than or equal to target.
Regular numbers are composites of the prime factors 2, 3, and 5.
Also known as 5-smooth numbers or Hamming numbers, these are the optimal
size for inputs to FFTPACK.
Target must be a positive integer. |
def _get_result_paths(self, data):
""" Return a dict of ResultPath objects representing all possible output
"""
assignment_fp = str(self.Parameters['-o'].Value).strip('"')
if not os.path.isabs(assignment_fp):
assignment_fp = os.path.relpath(assignment_fp, self.WorkingDir)
... | Return a dict of ResultPath objects representing all possible output |
def cutadaptit_pairs(data, sample):
"""
Applies trim & filters to pairs, including adapter detection. If we have
barcode information then we use it to trim reversecut+bcode+adapter from
reverse read, if not then we have to apply a more general cut to make sure
we remove the barcode, this uses wild... | Applies trim & filters to pairs, including adapter detection. If we have
barcode information then we use it to trim reversecut+bcode+adapter from
reverse read, if not then we have to apply a more general cut to make sure
we remove the barcode, this uses wildcards and so will have more false
positives... |
def simplex_connect(self, solution_g):
'''
API:
simplex_connect(self, solution_g)
Description:
At this point we assume that the solution does not have a cycle.
We check if all the nodes are connected, if not we add an arc to
solution_g that does no... | API:
simplex_connect(self, solution_g)
Description:
At this point we assume that the solution does not have a cycle.
We check if all the nodes are connected, if not we add an arc to
solution_g that does not create a cycle and return True. Otherwise
we ... |
def get_revisions(page, page_num=1):
"""
Returns paginated queryset of PageRevision instances for
specified Page instance.
:param page: the page instance.
:param page_num: the pagination page number.
:rtype: django.db.models.query.QuerySet.
"""
revisions = page.revisions.order_by('-cr... | Returns paginated queryset of PageRevision instances for
specified Page instance.
:param page: the page instance.
:param page_num: the pagination page number.
:rtype: django.db.models.query.QuerySet. |
def tag_add(self, item, tag):
"""
Add tag to the tags of item.
:param item: item identifier
:type item: str
:param tag: tag name
:type tag: str
"""
tags = self.item(item, "tags")
self.item(item, tags=tags + (tag,)) | Add tag to the tags of item.
:param item: item identifier
:type item: str
:param tag: tag name
:type tag: str |
def save_params(self, fname):
"""Saves model parameters to file.
Parameters
----------
fname : str
Path to output param file.
Examples
--------
>>> # An example of saving module parameters.
>>> mod.save_params('myfile')
"""
ar... | Saves model parameters to file.
Parameters
----------
fname : str
Path to output param file.
Examples
--------
>>> # An example of saving module parameters.
>>> mod.save_params('myfile') |
def DbGetProperty(self, argin):
""" Get free object property
:param argin: Str[0] = Object name
Str[1] = Property name
Str[n] = Property name
:type: tango.DevVarStringArray
:return: Str[0] = Object name
Str[1] = Property number
Str[2] = Property name
... | Get free object property
:param argin: Str[0] = Object name
Str[1] = Property name
Str[n] = Property name
:type: tango.DevVarStringArray
:return: Str[0] = Object name
Str[1] = Property number
Str[2] = Property name
Str[3] = Property value number (array ca... |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: PhoneNumberContext for this PhoneNumberInstance
:rtype: twilio.rest.lookups.v1.phone_number.Phone... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: PhoneNumberContext for this PhoneNumberInstance
:rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberContext |
def _add_to_typedef(self, typedef_curr, line, lnum):
"""Add new fields to the current typedef."""
mtch = re.match(r'^(\S+):\s*(\S.*)$', line)
if mtch:
field_name = mtch.group(1)
field_value = mtch.group(2).split('!')[0].rstrip()
if field_name == "id":
... | Add new fields to the current typedef. |
def rand_unicode(min_char=MIN_UNICHR, max_char=MAX_UNICHR, min_len=MIN_STRLEN,
max_len=MAX_STRLEN, **kwargs):
'''For values in the unicode range, regardless of Python version.
'''
from syn.five import unichr
return unicode(rand_str(min_char, max_char, min_len, max_len, unichr)) | For values in the unicode range, regardless of Python version. |
def create(cls, name, protocol_number, protocol_agent=None, comment=None):
"""
Create the IP Service
:param str name: name of ip-service
:param int protocol_number: ip proto number for this service
:param str,ProtocolAgent protocol_agent: optional protocol agent for
... | Create the IP Service
:param str name: name of ip-service
:param int protocol_number: ip proto number for this service
:param str,ProtocolAgent protocol_agent: optional protocol agent for
this service
:param str comment: optional comment
:raises CreateElementFailed: ... |
def errprt(op, lenout, inlist):
"""
Retrieve or set the list of error message items to be output when an
error is detected.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/errprt_c.html
:param op: The operation, "GET" or "SET".
:type op: str
:param lenout: Length of list for output... | Retrieve or set the list of error message items to be output when an
error is detected.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/errprt_c.html
:param op: The operation, "GET" or "SET".
:type op: str
:param lenout: Length of list for output.
:type lenout: int
:param inlist: S... |
def refocus(self, distance, method="helmholtz", h5file=None, h5mode="a"):
"""Compute a numerically refocused QPImage
Parameters
----------
distance: float
Focusing distance [m]
method: str
Refocusing method, one of ["helmholtz","fresnel"]
h5file: ... | Compute a numerically refocused QPImage
Parameters
----------
distance: float
Focusing distance [m]
method: str
Refocusing method, one of ["helmholtz","fresnel"]
h5file: str, h5py.Group, h5py.File, or None
A path to an hdf5 data file where the... |
def setGroupIcon( cls, groupName, icon ):
"""
Sets the group icon for the wizard plugin to the inputed icon.
:param groupName | <str>
icon | <str>
"""
if ( cls._groupIcons is None ):
cls._groupIcons = {}
... | Sets the group icon for the wizard plugin to the inputed icon.
:param groupName | <str>
icon | <str> |
def multivariate_neg_logposterior(self,beta):
""" Returns negative log posterior, for a model with a covariance matrix
Parameters
----------
beta : np.array
Contains untransformed starting values for latent_variables
Returns
----------
Negative log ... | Returns negative log posterior, for a model with a covariance matrix
Parameters
----------
beta : np.array
Contains untransformed starting values for latent_variables
Returns
----------
Negative log posterior |
def set_owner(self):
"""Parses owner name and email then sets value"""
owner = self.soup.find('itunes:owner')
try:
self.owner_name = owner.find('itunes:name').string
except AttributeError:
self.owner_name = None
try:
self.owner_email = owner.fi... | Parses owner name and email then sets value |
def inFocus(self):
"""Set GUI on-top flag"""
previous_flags = self.window.flags()
self.window.setFlags(previous_flags |
QtCore.Qt.WindowStaysOnTopHint) | Set GUI on-top flag |
def import_event_definition_elements(diagram_graph, element, event_definitions):
"""
Helper function, that adds event definition elements (defines special types of events) to corresponding events.
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param element: ... | Helper function, that adds event definition elements (defines special types of events) to corresponding events.
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param element: object representing a BPMN XML event element,
:param event_definitions: list of event definit... |
def attach_to_fbo(self):
"""Attach the texture to a bound FBO object, for rendering to texture."""
gl.glFramebufferTexture2DEXT(gl.GL_FRAMEBUFFER_EXT, self.attachment_point, self.target0, self.id, 0) | Attach the texture to a bound FBO object, for rendering to texture. |
def prep_fastq_inputs(in_files, data):
"""Prepare bgzipped fastq inputs
"""
if len(in_files) == 1 and _is_bam_input(in_files):
out = _bgzip_from_bam(in_files[0], data["dirs"], data)
elif len(in_files) == 1 and _is_cram_input(in_files):
out = _bgzip_from_cram(in_files[0], data["dirs"], da... | Prepare bgzipped fastq inputs |
def _bbox(nodes):
"""Get the bounding box for set of points.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
Args:
nodes (numpy.ndarray): A set of points.
Returns:
Tuple[float, float, float, float]: The left, righ... | Get the bounding box for set of points.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
Args:
nodes (numpy.ndarray): A set of points.
Returns:
Tuple[float, float, float, float]: The left, right,
bottom and top... |
def _create_related(self, obj, related, subfield_dict):
"""
create DB objects related to a base object
obj: a base object to create related
related: dict mapping field names to lists of related objects
subfield_list: where to get the next layer of s... | create DB objects related to a base object
obj: a base object to create related
related: dict mapping field names to lists of related objects
subfield_list: where to get the next layer of subfields |
def get_dates_file(path):
""" parse dates file of dates and probability of choosing"""
with open(path) as f:
dates = f.readlines()
return [(convert_time_string(date_string.split(" ")[0]), float(date_string.split(" ")[1]))
for date_string in dates] | parse dates file of dates and probability of choosing |
def where_equals(self, field_name, value, exact=False):
"""
To get all the document that equal to the value in the given field_name
@param str field_name: The field name in the index you want to query.
@param value: The value will be the fields value you want to query
@param boo... | To get all the document that equal to the value in the given field_name
@param str field_name: The field name in the index you want to query.
@param value: The value will be the fields value you want to query
@param bool exact: If True getting exact match of the query |
def delete_repository(self, namespace, repository):
"""DELETE /v1/repositories/(namespace)/(repository)/"""
return self._http_call(self.REPO, delete,
namespace=namespace, repository=repository) | DELETE /v1/repositories/(namespace)/(repository)/ |
def image_predict(self, X):
"""
Predicts class label for the entire image.
:param X: Array of images to be classified.
:type X: numpy array, shape = [n_images, n_pixels_y, n_pixels_x, n_bands]
:return: raster classification map
:rtype: numpy array, [n_samples, n_pixels_... | Predicts class label for the entire image.
:param X: Array of images to be classified.
:type X: numpy array, shape = [n_images, n_pixels_y, n_pixels_x, n_bands]
:return: raster classification map
:rtype: numpy array, [n_samples, n_pixels_y, n_pixels_x] |
def get_next_redirect_url(request, redirect_field_name="next"):
"""
Returns the next URL to redirect to, if it was explicitly passed
via the request.
"""
redirect_to = get_request_param(request, redirect_field_name)
if not get_adapter(request).is_safe_url(redirect_to):
redirect_to = None... | Returns the next URL to redirect to, if it was explicitly passed
via the request. |
def load_servers_from_env(self, filter=[], dynamic=None):
'''Load the name servers environment variable and parse each server in
the list.
@param filter Restrict the parsed objects to only those in this
path. For example, setting filter to [['/',
'loc... | Load the name servers environment variable and parse each server in
the list.
@param filter Restrict the parsed objects to only those in this
path. For example, setting filter to [['/',
'localhost', 'host.cxt', 'comp1.rtc']] will
prevent... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'entities') and self.entities is not None:
_dict['entities'] = [x._to_dict() for x in self.entities]
return _dict | Return a json dictionary representing this model. |
def diamond_search_output_basename(self, out_path):
'''Does not include the .daa part that diamond creates'''
return os.path.join(self.outdir, out_path, "%s_diamond_search" % self.basename) | Does not include the .daa part that diamond creates |
def find():
"""Find the configuration file if any."""
names = ('archan.yml', 'archan.yaml', '.archan.yml', '.archan.yaml')
current_dir = os.getcwd()
configconfig_file = os.path.join(current_dir, '.configconfig')
default_config_dir = os.path.join(current_dir, 'config')
if ... | Find the configuration file if any. |
def _get_key_redis_key(bank, key):
'''
Return the Redis key given the bank name and the key name.
'''
opts = _get_redis_keys_opts()
return '{prefix}{separator}{bank}/{key}'.format(
prefix=opts['key_prefix'],
separator=opts['separator'],
bank=bank,
key=key
) | Return the Redis key given the bank name and the key name. |
def general_setting(key, default=None, expected_type=None, qsettings=None):
"""Helper function to get a value from settings.
:param key: Unique key for setting.
:type key: basestring
:param default: The default value in case of the key is not found or there
is an error.
:type default: base... | Helper function to get a value from settings.
:param key: Unique key for setting.
:type key: basestring
:param default: The default value in case of the key is not found or there
is an error.
:type default: basestring, None, boolean, int, float
:param expected_type: The type of object exp... |
def to_html(self,
protocol='http',
d3_url=None,
d3_scale_chromatic_url=None,
html_base=None):
'''
Parameters
----------
protocol : str
'http' or 'https' for including external urls
d3_url, str
None... | Parameters
----------
protocol : str
'http' or 'https' for including external urls
d3_url, str
None by default. The url (or path) of
d3, to be inserted into <script src="..."/>
By default, this is `DEFAULT_D3_URL` declared in `ScatterplotStructure`.
... |
def _compute_and_transfer_to_final_run(self, process_name, start_timeperiod, end_timeperiod, job_record):
""" method computes new unit_of_work and transfers the job to STATE_FINAL_RUN
it also shares _fuzzy_ DuplicateKeyError logic from _compute_and_transfer_to_progress method"""
source_collectio... | method computes new unit_of_work and transfers the job to STATE_FINAL_RUN
it also shares _fuzzy_ DuplicateKeyError logic from _compute_and_transfer_to_progress method |
def extract_subnetworks(
partition_file,
network_file,
output_dir,
max_cores=DEFAULT_MAX_CORES,
max_size_matrix=DEFAULT_MAX_SIZE_MATRIX,
saturation_threshold=DEFAULT_SATURATION_THRESHOLD,
):
"""Extract bin subnetworks from the main network
Identify bins, extract subnets, draws the adjac... | Extract bin subnetworks from the main network
Identify bins, extract subnets, draws the adjacency matrices,
saves it all in a specified output directory.
Parameters
----------
partition_file : file, str or pathlib.Path
The file containing, for each chunk, the communities it was
ass... |
def prompt(msg, default=NO_DEFAULT, validate=None):
""" Prompt user for input """
while True:
response = input(msg + " ").strip()
if not response:
if default is NO_DEFAULT:
continue
return default
if validate is None or validate(response):
... | Prompt user for input |
def _get_client_fqdn(self, client_info_contents):
"""Extracts a GRR client's FQDN from its client_info.yaml file.
Args:
client_info_contents: The contents of the client_info.yaml file.
Returns:
A (str, str) tuple representing client ID and client FQDN.
"""
yamldict = yaml.safe_load(cli... | Extracts a GRR client's FQDN from its client_info.yaml file.
Args:
client_info_contents: The contents of the client_info.yaml file.
Returns:
A (str, str) tuple representing client ID and client FQDN. |
def present(name,
object_name,
object_type,
defprivileges=None,
grant_option=None,
prepend='public',
maintenance_db=None,
user=None,
db_password=None,
db_host=None,
db_port=None,
db_user=N... | Grant the requested privilege(s) on the specified object to a role
name
Name of the role to which privileges should be granted
object_name
Name of the object on which the grant is to be performed.
'ALL' may be used for objects of type 'table' or 'sequence'.
object_type
The ob... |
def evaluate(self, num_eval_batches=None):
"""Run one round of evaluation, return loss and accuracy."""
num_eval_batches = num_eval_batches or self.num_eval_batches
with tf.Graph().as_default() as graph:
self.tensors = self.model.build_eval_graph(self.eval_data_paths,
... | Run one round of evaluation, return loss and accuracy. |
def from_dict(cls, data, intersect=False, orient='items', dtype=None):
"""
Construct Panel from dict of DataFrame objects.
Parameters
----------
data : dict
{field : DataFrame}
intersect : boolean
Intersect indexes of input DataFrames
orie... | Construct Panel from dict of DataFrame objects.
Parameters
----------
data : dict
{field : DataFrame}
intersect : boolean
Intersect indexes of input DataFrames
orient : {'items', 'minor'}, default 'items'
The "orientation" of the data. If the ... |
def enable_console_debug_logging(): # pragma no cover (Function useful only outside test environment)
"""
This function sets up a very simple logging configuration (log everything on standard output) that is useful for troubleshooting.
"""
logger = logging.getLogger("github")
logger.setLevel(loggi... | This function sets up a very simple logging configuration (log everything on standard output) that is useful for troubleshooting. |
def add_parser_arguments(parser, args, group=None, prefix=DATA_PREFIX):
"""
Helper method that populates parser arguments. The argument values can
be later retrieved with `extract_arguments` method.
The `args` argument to this method should be a dict with strings as
keys and dicts as values. The ke... | Helper method that populates parser arguments. The argument values can
be later retrieved with `extract_arguments` method.
The `args` argument to this method should be a dict with strings as
keys and dicts as values. The keys will be used as keys in returned
data. Their values will be passed as kwargs ... |
def get_compiler(compiler, **compiler_attrs):
"""get and customize a compiler"""
if compiler is None or isinstance(compiler, str):
cc = ccompiler.new_compiler(compiler=compiler, verbose=0)
customize_compiler(cc)
if cc.compiler_type == 'mingw32':
customize_mingw(cc)
else:
... | get and customize a compiler |
def _getPattern(self, ipattern, done=None):
"""Parses sort pattern.
:ipattern: A pattern to parse.
:done: If :ipattern: refers to done|undone,
use this to indicate proper state.
:returns: A pattern suitable for Model.modify.
"""
if ipattern is None:
... | Parses sort pattern.
:ipattern: A pattern to parse.
:done: If :ipattern: refers to done|undone,
use this to indicate proper state.
:returns: A pattern suitable for Model.modify. |
def _find_listeners():
"""Find GPIB listeners.
"""
for i in range(31):
try:
if gpib.listener(BOARD, i) and gpib.ask(BOARD, 1) != i:
yield i
except gpib.GpibError as e:
logger.debug("GPIB error in _find_listeners(): %s", repr(e)) | Find GPIB listeners. |
def depth(args):
"""
%prog depth DP.tsv
Plot read depths across all TREDs.
"""
import seaborn as sns
p = OptionParser(depth.__doc__)
opts, args, iopts = p.set_image_options(args, figsize="14x14")
if len(args) != 1:
sys.exit(not p.print_help())
tsvfile, = args
fig, ((a... | %prog depth DP.tsv
Plot read depths across all TREDs. |
def RFC3156_micalg_from_algo(hash_algo):
"""
Converts a GPGME hash algorithm name to one conforming to RFC3156.
GPGME returns hash algorithm names such as "SHA256", but RFC3156 says that
programs need to use names such as "pgp-sha256" instead.
:param str hash_algo: GPGME hash_algo
:returns: th... | Converts a GPGME hash algorithm name to one conforming to RFC3156.
GPGME returns hash algorithm names such as "SHA256", but RFC3156 says that
programs need to use names such as "pgp-sha256" instead.
:param str hash_algo: GPGME hash_algo
:returns: the lowercase name of of the algorithm with "pgp-" prep... |
def erase_up (self): # <ESC>[1J
'''Erases the screen from the current line up to the top of the
screen.'''
self.erase_start_of_line ()
self.fill_region (self.cur_r-1, 1, 1, self.cols) | Erases the screen from the current line up to the top of the
screen. |
def rest(self, method, uri, data=None, status_codes=None, parse=True, **kwargs):
""" Rest helpers
"""
r = self.pool.request_encode_body(method, uri, fields=data, encode_multipart=False)
if not r.status in (status_codes if status_codes else (200,201)):
print cl('\n---------\nURI / REQUEST TYPE : %s... | Rest helpers |
def __update_action(self, revision):
"""Update a master document and revision history document
:param dict revision: The revision dictionary
"""
patch = revision.get("patch")
if patch.get("_id"):
del patch["_id"]
update_response = yield self.collection.patc... | Update a master document and revision history document
:param dict revision: The revision dictionary |
def spline_fit_magseries(times, mags, errs, period,
knotfraction=0.01,
maxknots=30,
sigclip=30.0,
plotfit=False,
ignoreinitfail=False,
magsarefluxes=False,
... | This fits a univariate cubic spline to the phased light curve.
This fit may be better than the Fourier fit for sharply variable objects,
like EBs, so can be used to distinguish them from other types of variables.
Parameters
----------
times,mags,errs : np.array
The input mag/flux time-ser... |
def cublasDspr2(handle, uplo, n, alpha, x, incx, y, incy, AP):
"""
Rank-2 operation on real symmetric-packed matrix.
"""
status = _libcublas.cublasDspr2_v2(handle,
_CUBLAS_FILL_MODE[uplo], n,
ctypes.byref(ctypes.c_double(a... | Rank-2 operation on real symmetric-packed matrix. |
def get_object(self, queryset=None):
"""
Return the object the view is displaying.
Same as rest_framework.generics.GenericAPIView, but:
- Failed assertions instead of deprecations
"""
# Determine the base queryset to use.
assert queryset is None, "Passing a query... | Return the object the view is displaying.
Same as rest_framework.generics.GenericAPIView, but:
- Failed assertions instead of deprecations |
def dateint_to_datetime(dateint):
"""Converts the given dateint to a datetime object, in local timezone.
Arguments
---------
dateint : int
An integer object decipting a specific calendaric day; e.g. 20161225.
Returns
-------
datetime.datetime
A timezone-unaware datetime obj... | Converts the given dateint to a datetime object, in local timezone.
Arguments
---------
dateint : int
An integer object decipting a specific calendaric day; e.g. 20161225.
Returns
-------
datetime.datetime
A timezone-unaware datetime object representing the start of the given
... |
def master_ref(self):
"""
Filters the current DataFrame to only contain those rows whose reference is master.
>>> master_df = refs_df.master_ref
:rtype: ReferencesDataFrame
"""
return ReferencesDataFrame(self._engine_dataframe.getMaster(),
... | Filters the current DataFrame to only contain those rows whose reference is master.
>>> master_df = refs_df.master_ref
:rtype: ReferencesDataFrame |
def _upgrade_schema(engine):
"""
Ensure the database schema is up to date with the codebase.
:param engine: SQLAlchemy engine of the underlying database.
"""
inspector = reflection.Inspector.from_engine(engine)
with engine.connect() as conn:
# Upgrade 1. Add task_id column and index t... | Ensure the database schema is up to date with the codebase.
:param engine: SQLAlchemy engine of the underlying database. |
def all_pairs_normalized_distances_reference(X):
"""
Reference implementation of normalized all-pairs distance, used
for testing the more efficient implementation above for equivalence.
"""
n_samples, n_cols = X.shape
# matrix of mean squared difference between between samples
D = np.ones((n... | Reference implementation of normalized all-pairs distance, used
for testing the more efficient implementation above for equivalence. |
def do_lmfit(data, params, B=None, errs=None, dojac=True):
"""
Fit the model to the data
data may contain 'flagged' or 'masked' data with the value of np.NaN
Parameters
----------
data : 2d-array
Image data
params : lmfit.Parameters
Initial model guess.
B : 2d-array
... | Fit the model to the data
data may contain 'flagged' or 'masked' data with the value of np.NaN
Parameters
----------
data : 2d-array
Image data
params : lmfit.Parameters
Initial model guess.
B : 2d-array
B matrix to be used in residual calculations.
Default = N... |
def _get_containing_contigs(self, hits_dict):
'''Given dictionary of nucmer hits (made by self._load_nucmer_hits()), returns a dictionary.
key=contig name. Value = set of contigs that contain the key.'''
containing = {}
for qry_name in hits_dict:
d = self._containing_cont... | Given dictionary of nucmer hits (made by self._load_nucmer_hits()), returns a dictionary.
key=contig name. Value = set of contigs that contain the key. |
def print_attrs(data_file, node_name='/', which='user', compress=False):
"""Print the HDF5 attributes for `node_name`.
Parameters:
data_file (pytables HDF5 file object): the data file to print
node_name (string): name of the path inside the file to be printed.
Can be either a group ... | Print the HDF5 attributes for `node_name`.
Parameters:
data_file (pytables HDF5 file object): the data file to print
node_name (string): name of the path inside the file to be printed.
Can be either a group or a leaf-node. Default: '/', the root node.
which (string): Valid value... |
def EMAIL_REQUIRED(self):
"""
The user is required to hand over an e-mail address when signing up
"""
from allauth.account import app_settings as account_settings
return self._setting("EMAIL_REQUIRED", account_settings.EMAIL_REQUIRED) | The user is required to hand over an e-mail address when signing up |
def plugins(self):
"""
:returns: [(plugin_name, plugin_package, plugin_config), ...]
:rtype: list of tuple
"""
if not self._plugins:
self._plugins = [
(plugin_name,
plugin_cfg['package'],
plugin_cfg) for plugin... | :returns: [(plugin_name, plugin_package, plugin_config), ...]
:rtype: list of tuple |
def send_UDP_message(self, message):
"""Send UDP message."""
x = 0
if self.tracking_enabled:
try:
proc = udp_messenger(self.domain_name, self.UDP_IP, self.UDP_PORT, self.sock_timeout, message)
self.procs.append(proc)
except Exception as e:
... | Send UDP message. |
def render(self, dt):
'''Draw all bodies in the world.'''
for frame in self._frozen:
for body in frame:
self.draw_body(body)
for body in self.world.bodies:
self.draw_body(body)
if hasattr(self.world, 'markers'):
# draw line between anc... | Draw all bodies in the world. |
def find_table_links(self):
"""
When given a url, this function will find all the available table names
for that EPA dataset.
"""
html = urlopen(self.model_url).read()
doc = lh.fromstring(html)
href_list = [area.attrib['href'] for area in doc.cssselect('map area')... | When given a url, this function will find all the available table names
for that EPA dataset. |
def ref(self, tickers, flds, ovrds=None):
"""
Make a reference data request, get tickers and fields, return long
pandas DataFrame with columns [ticker, field, value]
Parameters
----------
tickers: {list, string}
String or list of strings corresponding to tick... | Make a reference data request, get tickers and fields, return long
pandas DataFrame with columns [ticker, field, value]
Parameters
----------
tickers: {list, string}
String or list of strings corresponding to tickers
flds: {list, string}
String or list of... |
def ot_validate(nexson, **kwargs):
"""Returns three objects:
an annotation dict (NexSON formmatted),
the validation_log object created when NexSON validation was performed, and
the object of class NexSON which was created from nexson. This object may
alias parts of the nexson dic... | Returns three objects:
an annotation dict (NexSON formmatted),
the validation_log object created when NexSON validation was performed, and
the object of class NexSON which was created from nexson. This object may
alias parts of the nexson dict that is passed in as an argument.
C... |
def save_file(self, filename, text):
"""Save the given text under the given condition filename and the
current path.
If the current directory is not defined explicitly, the directory
name is constructed with the actual simulation end date. If
such an directory does not exist, i... | Save the given text under the given condition filename and the
current path.
If the current directory is not defined explicitly, the directory
name is constructed with the actual simulation end date. If
such an directory does not exist, it is created immediately. |
def close(self):
"""
Close and release the current usb device.
:return: None
"""
# This may not be absolutely necessary, but it is safe.
# It's the closest thing to a close() method.
if self._dev is not None:
usb.util.dispose_resources(self._dev)
... | Close and release the current usb device.
:return: None |
def save(self, savefile):
"""Do the TTS API request and write result to file.
Args:
savefile (string): The path and file name to save the ``mp3`` to.
Raises:
:class:`gTTSError`: When there's an error with the API request.
"""
with open(str(savefile), 'w... | Do the TTS API request and write result to file.
Args:
savefile (string): The path and file name to save the ``mp3`` to.
Raises:
:class:`gTTSError`: When there's an error with the API request. |
def get(self, path_or_index, default=None):
"""
Get details about a given result
:param path_or_index: The path (or index) of the result to fetch.
:param default: If the given result does not exist, return this value
instead
:return: A tuple of `(error, value)`. If t... | Get details about a given result
:param path_or_index: The path (or index) of the result to fetch.
:param default: If the given result does not exist, return this value
instead
:return: A tuple of `(error, value)`. If the entry does not exist
then `(err, default)` is ret... |
def analyze(fqdn, result, argl, argd):
"""Analyzes the result from calling the method with the specified FQDN.
Args:
fqdn (str): full-qualified name of the method that was called.
result: result of calling the method with `fqdn`.
argl (tuple): positional arguments passed to the method c... | Analyzes the result from calling the method with the specified FQDN.
Args:
fqdn (str): full-qualified name of the method that was called.
result: result of calling the method with `fqdn`.
argl (tuple): positional arguments passed to the method call.
argd (dict): keyword arguments pa... |
def expand_hostdef(self, hostdef):
"""
Expand a host definition (e.g. "foo[001:010].bar.com") into seperate
hostnames. Supports zero-padding, numbered ranges and alphabetical
ranges. Multiple patterns in a host defnition are also supported.
Returns a list of the fully expanded ho... | Expand a host definition (e.g. "foo[001:010].bar.com") into seperate
hostnames. Supports zero-padding, numbered ranges and alphabetical
ranges. Multiple patterns in a host defnition are also supported.
Returns a list of the fully expanded hostnames. Ports are also removed
from hostnames ... |
def norm(self, order=2):
"""Find the vector norm, with the given order, of the values"""
return (sum(val**order for val in abs(self).values()))**(1/order) | Find the vector norm, with the given order, of the values |
def add_pool(arg, opts, shell_opts):
""" Add a pool.
"""
p = Pool()
p.name = opts.get('name')
p.description = opts.get('description')
p.default_type = opts.get('default-type')
p.ipv4_default_prefix_length = opts.get('ipv4_default_prefix_length')
p.ipv6_default_prefix_length = opts.get('... | Add a pool. |
def cmd_center(self, args):
'''control center of view'''
if len(args) < 3:
print("map center LAT LON")
return
lat = float(args[1])
lon = float(args[2])
self.map.set_center(lat, lon) | control center of view |
def search(connect_spec, base, scope='subtree', filterstr='(objectClass=*)',
attrlist=None, attrsonly=0):
'''Search an LDAP database.
:param connect_spec:
See the documentation for the ``connect_spec`` parameter for
:py:func:`connect`.
:param base:
Distinguished name of ... | Search an LDAP database.
:param connect_spec:
See the documentation for the ``connect_spec`` parameter for
:py:func:`connect`.
:param base:
Distinguished name of the entry at which to start the search.
:param scope:
One of the following:
* ``'subtree'``
... |
def get_active_sessions(self):
"""
Retrieves the active, unexpired sessions.
:Returns:
A generator of :class:`~mwsessions.Session`
"""
for last_timestamp, i, events in self.recently_active:
yield Session(events[-1].user, unpack_events(events)) | Retrieves the active, unexpired sessions.
:Returns:
A generator of :class:`~mwsessions.Session` |
def make_dict(name, words, *args, **kwargs):
"""
make_dict(name, words, *args, **kwargs) -> mapping subclass
Takes a sequence of words (or a pre-built Czech HashInfo) and returns a
mapping subclass called `name` (used a dict) that employs the use of the
minimal perfect hash.
This mapping subcl... | make_dict(name, words, *args, **kwargs) -> mapping subclass
Takes a sequence of words (or a pre-built Czech HashInfo) and returns a
mapping subclass called `name` (used a dict) that employs the use of the
minimal perfect hash.
This mapping subclass has guaranteed O(1) worst-case lookups, additions,
... |
def parse_date(date, default=None):
""" Parse a valid date """
if date == "":
if default is not None:
return default
else:
raise Exception("Unknown format for " + date)
for format_type in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d %H", "%Y-%m-%d", "%d/%m/%Y %H... | Parse a valid date |
def find_by_id(self, attachment, params={}, **options):
"""Returns the full record for a single attachment.
Parameters
----------
attachment : {Id} Globally unique identifier for the attachment.
[params] : {Object} Parameters for the request
"""
path = "/attachm... | Returns the full record for a single attachment.
Parameters
----------
attachment : {Id} Globally unique identifier for the attachment.
[params] : {Object} Parameters for the request |
def random_matrix(rows, cols, mean=0, std=1, sparsity=0, radius=0, diagonal=0, rng=None):
'''Create a matrix of randomly-initialized weights.
Parameters
----------
rows : int
Number of rows of the weight matrix -- equivalently, the number of
"input" units that the weight matrix connects... | Create a matrix of randomly-initialized weights.
Parameters
----------
rows : int
Number of rows of the weight matrix -- equivalently, the number of
"input" units that the weight matrix connects.
cols : int
Number of columns of the weight matrix -- equivalently, the number
... |
def open_config(self,type="shared"):
"""
Opens the configuration of the currently connected device
Args:
:type: The type of configuration you want to open. Any string can be provided, however the standard supported options are: **exclusive**, **private**, and **shared**. The default... | Opens the configuration of the currently connected device
Args:
:type: The type of configuration you want to open. Any string can be provided, however the standard supported options are: **exclusive**, **private**, and **shared**. The default mode is **shared**.
Examples:
.. code-... |
def check_hash(self, checker, filename, tfp):
"""
checker is a ContentChecker
"""
checker.report(
self.debug,
"Validating %%s checksum for %s" % filename)
if not checker.is_valid():
tfp.close()
os.unlink(filename)
raise ... | checker is a ContentChecker |
def param_extract(args, short_form, long_form, default=None):
"""
Quick extraction of a parameter from the command line argument list.
In some cases we need to parse a few arguments before the official
arg-parser starts.
Returns parameter value, or None if not present.
"""
val = default
... | Quick extraction of a parameter from the command line argument list.
In some cases we need to parse a few arguments before the official
arg-parser starts.
Returns parameter value, or None if not present. |
def extern_store_tuple(self, context_handle, vals_ptr, vals_len):
"""Given storage and an array of Handles, return a new Handle to represent the list."""
c = self._ffi.from_handle(context_handle)
return c.to_value(tuple(c.from_value(val[0]) for val in self._ffi.unpack(vals_ptr, vals_len))) | Given storage and an array of Handles, return a new Handle to represent the list. |
def followers(self):
"""
:return: Iterator of :class:`stravalib.model.Athlete` followers objects for this athlete.
"""
if self._followers is None:
self.assert_bind_client()
if self.follower_count > 0:
self._followers = self.bind_client.get_athlete_... | :return: Iterator of :class:`stravalib.model.Athlete` followers objects for this athlete. |
def toDict(self):
"""
Get information about this read in a dictionary.
@return: A C{dict} with keys/values for the attributes of self.
"""
if six.PY3:
result = super().toDict()
else:
result = AARead.toDict(self)
result.update({
... | Get information about this read in a dictionary.
@return: A C{dict} with keys/values for the attributes of self. |
def SetAndLoadTagFile(self, tagging_file_path):
"""Sets the tag file to be used by the plugin.
Args:
tagging_file_path (str): path of the tagging file.
"""
tag_file = tagging_file.TaggingFile(tagging_file_path)
self._tagging_rules = tag_file.GetEventTaggingRules() | Sets the tag file to be used by the plugin.
Args:
tagging_file_path (str): path of the tagging file. |
def create_address(kwargs=None, call=None):
'''
Create a static address in a region.
CLI Example:
.. code-block:: bash
salt-cloud -f create_address gce name=my-ip region=us-central1 address=IP
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_addres... | Create a static address in a region.
CLI Example:
.. code-block:: bash
salt-cloud -f create_address gce name=my-ip region=us-central1 address=IP |
def draw_if_interactive():
"""
Is called after every pylab drawing command
"""
# signal that the current active figure should be sent at the end of
# execution. Also sets the _draw_called flag, signaling that there will be
# something to send. At the end of the code execution, a separate call ... | Is called after every pylab drawing command |
def get_order(self, order_id):
'''Get an order'''
resp = self.get('/orders/{}'.format(order_id))
return Order(resp) | Get an order |
def raw(self, raw):
"""Sets the raw of this RuntimeRawExtension.
Raw is the underlying serialization of this object. # noqa: E501
:param raw: The raw of this RuntimeRawExtension. # noqa: E501
:type: str
"""
if raw is None:
raise ValueError("Invalid value f... | Sets the raw of this RuntimeRawExtension.
Raw is the underlying serialization of this object. # noqa: E501
:param raw: The raw of this RuntimeRawExtension. # noqa: E501
:type: str |
def get_system_data() -> typing.Union[None, dict]:
"""
Returns information about the system in which Cauldron is running.
If the information cannot be found, None is returned instead.
:return:
Dictionary containing information about the Cauldron system, whic
includes:
* name
... | Returns information about the system in which Cauldron is running.
If the information cannot be found, None is returned instead.
:return:
Dictionary containing information about the Cauldron system, whic
includes:
* name
* location
* version |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.