code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def run(self, data, rewrap=False, prefetch=0):
"""
Wires the pipeline and returns a lazy object of
the transformed data.
:param data: must be an iterable, where a full document
must be returned for each loop
:param rewrap: (optional) is a bool that indicates the need to... | Wires the pipeline and returns a lazy object of
the transformed data.
:param data: must be an iterable, where a full document
must be returned for each loop
:param rewrap: (optional) is a bool that indicates the need to rewrap
data in cases where iterating over it produces unde... |
def get_edge(self, edge_id):
"""Returns the edge object identified by "edge_id"."""
try:
edge_object = self.edges[edge_id]
except KeyError:
raise NonexistentEdgeError(edge_id)
return edge_object | Returns the edge object identified by "edge_id". |
def copy(self):
"""Make a deep copy of this object.
Example::
>>> c2 = c.copy()
"""
vec1 = np.copy(self.scoef1._vec)
vec2 = np.copy(self.scoef2._vec)
return VectorCoefs(vec1, vec2, self.nmax, self.mmax) | Make a deep copy of this object.
Example::
>>> c2 = c.copy() |
def DiamAns(cmd, **fields):
"""Craft Diameter answer commands"""
upfields, name = getCmdParams(cmd, False, **fields)
p = DiamG(**upfields)
p.name = name
return p | Craft Diameter answer commands |
def downstream(self, step_name):
"""Returns the direct dependencies of the given step"""
return list(self.steps[dep] for dep in self.dag.downstream(step_name)) | Returns the direct dependencies of the given step |
def git_get_title_and_message(begin, end):
"""Get title and message summary for patches between 2 commits.
:param begin: first commit to look at
:param end: last commit to look at
:return: number of commits, title, message
"""
titles = git_get_log_titles(begin, end)
title = "Pull request fo... | Get title and message summary for patches between 2 commits.
:param begin: first commit to look at
:param end: last commit to look at
:return: number of commits, title, message |
def _intersect(start1, end1, start2, end2):
"""
Returns the intersection of two intervals. Returns (None,None) if the intersection is empty.
:param int start1: The start date of the first interval.
:param int end1: The end date of the first interval.
:param int start2: The start... | Returns the intersection of two intervals. Returns (None,None) if the intersection is empty.
:param int start1: The start date of the first interval.
:param int end1: The end date of the first interval.
:param int start2: The start date of the second interval.
:param int end2: The end d... |
def assemble_to_object(self, in_filename, verbose=False):
"""
Assemble *in_filename* assembly into *out_filename* object.
If *iaca_marked* is set to true, markers are inserted around the block with most packed
instructions or (if no packed instr. were found) the largest block and modifi... | Assemble *in_filename* assembly into *out_filename* object.
If *iaca_marked* is set to true, markers are inserted around the block with most packed
instructions or (if no packed instr. were found) the largest block and modified file is
saved to *in_file*.
*asm_block* controls how the t... |
def deconstruct(self):
"""Gets the values to pass to :see:__init__ when
re-creating this object."""
name, path, args, kwargs = super(
HStoreField, self).deconstruct()
if self.uniqueness is not None:
kwargs['uniqueness'] = self.uniqueness
if self.require... | Gets the values to pass to :see:__init__ when
re-creating this object. |
def save(self, *args, **kwargs):
"""
**uid**: :code:`cycle:{year}`
"""
self.slug = slugify(self.name)
self.uid = 'cycle:{}'.format(self.slug)
super(ElectionCycle, self).save(*args, **kwargs) | **uid**: :code:`cycle:{year}` |
def _state_delete(self):
'''Try to delete the state.yml file and the folder .blockade'''
try:
os.remove(self._state_file)
except OSError as err:
if err.errno not in (errno.EPERM, errno.ENOENT):
raise
try:
os.rmdir(self._state_dir)
... | Try to delete the state.yml file and the folder .blockade |
def _check_response_status(self, response):
"""
Checks the speficied HTTP response from the requests package and
raises an exception if a non-200 HTTP code was returned by the
server.
"""
if response.status_code != requests.codes.ok:
self._logger.error("%s %s"... | Checks the speficied HTTP response from the requests package and
raises an exception if a non-200 HTTP code was returned by the
server. |
def corr_flat_und(a1, a2):
'''
Returns the correlation coefficient between two flattened adjacency
matrices. Only the upper triangular part is used to avoid double counting
undirected matrices. Similarity metric for weighted matrices.
Parameters
----------
A1 : NxN np.ndarray
undi... | Returns the correlation coefficient between two flattened adjacency
matrices. Only the upper triangular part is used to avoid double counting
undirected matrices. Similarity metric for weighted matrices.
Parameters
----------
A1 : NxN np.ndarray
undirected matrix 1
A2 : NxN np.ndarray... |
def time_range(self, start, end):
"""Add a request for a time range to the query.
This modifies the query in-place, but returns `self` so that multiple queries
can be chained together on one line.
This replaces any existing temporal queries that have been set.
Parameters
... | Add a request for a time range to the query.
This modifies the query in-place, but returns `self` so that multiple queries
can be chained together on one line.
This replaces any existing temporal queries that have been set.
Parameters
----------
start : datetime.dateti... |
def _construct_derivatives(self, coefs, **kwargs):
"""Return a list of derivatives given a list of coefficients."""
return [self.basis_functions.derivatives_factory(coef, **kwargs) for coef in coefs] | Return a list of derivatives given a list of coefficients. |
def single_html(epub_file_path, html_out=sys.stdout, mathjax_version=None,
numchapters=None, includes=None):
"""Generate complete book HTML."""
epub = cnxepub.EPUB.from_file(epub_file_path)
if len(epub) != 1:
raise Exception('Expecting an epub with one book')
package = epub[0]
... | Generate complete book HTML. |
def writeToCheckpoint(self, checkpointDir):
"""Serializes model using capnproto and writes data to ``checkpointDir``"""
proto = self.getSchema().new_message()
self.write(proto)
checkpointPath = self._getModelCheckpointFilePath(checkpointDir)
# Clean up old saved state, if any
if os.path.exist... | Serializes model using capnproto and writes data to ``checkpointDir`` |
def notify(self):
"""
Calls the notification method
:return: True if the notification method has been called
"""
if self.__method is not None:
self.__method(self.__peer)
return True
return False | Calls the notification method
:return: True if the notification method has been called |
def node_vectors(node_id):
"""Get the vectors of a node.
You must specify the node id in the url.
You can pass direction (incoming/outgoing/all) and failed
(True/False/all).
"""
exp = Experiment(session)
# get the parameters
direction = request_parameter(parameter="direction", default="... | Get the vectors of a node.
You must specify the node id in the url.
You can pass direction (incoming/outgoing/all) and failed
(True/False/all). |
def resolve_type(arg):
# type: (object) -> InternalType
"""
Resolve object to one of our internal collection types or generic built-in type.
Args:
arg: object to resolve
"""
arg_type = type(arg)
if arg_type == list:
assert isinstance(arg, list) # this line helps mypy figure... | Resolve object to one of our internal collection types or generic built-in type.
Args:
arg: object to resolve |
def put(self, name, value):
"""Put a variable to MATLAB workspace.
"""
pm = ndarray_to_mxarray(self._libmx, value)
self._libeng.engPutVariable(self._ep, name, pm)
self._libmx.mxDestroyArray(pm) | Put a variable to MATLAB workspace. |
def notify(self, resource):
"""
Notifies the observers of a certain resource.
:param resource: the resource
"""
observers = self._observeLayer.notify(resource)
logger.debug("Notify")
for transaction in observers:
with transaction:
tran... | Notifies the observers of a certain resource.
:param resource: the resource |
def getFailureMessage(failure):
"""
Return a short message based on L{twisted.python.failure.Failure}.
Tries to find where the exception was triggered.
"""
str(failure.type)
failure.getErrorMessage()
if len(failure.frames) == 0:
return "failure %(exc)s: %(msg)s" % locals()
(func... | Return a short message based on L{twisted.python.failure.Failure}.
Tries to find where the exception was triggered. |
def to_html(data):
"""
Serializes a python object as HTML
This method uses the to_json method to turn the given data object into
formatted JSON that is displayed in an HTML page. If pygments in installed,
syntax highlighting will also be applied to the JSON.
"""
base_html_template = Templat... | Serializes a python object as HTML
This method uses the to_json method to turn the given data object into
formatted JSON that is displayed in an HTML page. If pygments in installed,
syntax highlighting will also be applied to the JSON. |
def get_config_value(self, name, defaultValue):
"""
Parameters:
- name
- defaultValue
"""
self.send_get_config_value(name, defaultValue)
return self.recv_get_config_value() | Parameters:
- name
- defaultValue |
def random(self, cascadeFetch=False):
'''
Random - Returns a random record in current filterset.
@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model
will be fetched immediately. If False, foreign objects will be fetched on-access.
@return - Instance of M... | Random - Returns a random record in current filterset.
@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model
will be fetched immediately. If False, foreign objects will be fetched on-access.
@return - Instance of Model object, or None if no items math current f... |
def get_mac_addr(mac_addr):
"""converts bytes to mac addr format
:mac_addr: ctypes.structure
:return: str
mac addr in format
11:22:33:aa:bb:cc
"""
mac_addr = bytearray(mac_addr)
mac = b':'.join([('%02x' % o).encode('ascii') for o in mac_addr])
... | converts bytes to mac addr format
:mac_addr: ctypes.structure
:return: str
mac addr in format
11:22:33:aa:bb:cc |
def partof(self, ns1, id1, ns2, id2):
"""Return True if one entity is "partof" another.
Parameters
----------
ns1 : str
Namespace code for an entity.
id1 : str
URI for an entity.
ns2 : str
Namespace code for an entity.
id2 : st... | Return True if one entity is "partof" another.
Parameters
----------
ns1 : str
Namespace code for an entity.
id1 : str
URI for an entity.
ns2 : str
Namespace code for an entity.
id2 : str
URI for an entity.
Returns... |
def bck_from_spt (spt):
"""Calculate a bolometric correction constant for a J band magnitude based on
a spectral type, using the fits of Wilking+ (1999AJ....117..469W), Dahn+
(2002AJ....124.1170D), and Nakajima+ (2004ApJ...607..499N).
spt - Numerical spectral type. M0=0, M9=9, L0=10, ...
Returns: ... | Calculate a bolometric correction constant for a J band magnitude based on
a spectral type, using the fits of Wilking+ (1999AJ....117..469W), Dahn+
(2002AJ....124.1170D), and Nakajima+ (2004ApJ...607..499N).
spt - Numerical spectral type. M0=0, M9=9, L0=10, ...
Returns: the correction `bck` such that ... |
def liftover_to_genome(pass_pos, gtf):
"""Liftover from precursor to genome"""
fixed_pos = []
for pos in pass_pos:
if pos["chrom"] not in gtf:
continue
db_pos = gtf[pos["chrom"]][0]
mut = _parse_mut(pos["sv"])
print([db_pos, pos])
if db_pos[3] == "+":
... | Liftover from precursor to genome |
def get_config(self):
"""Returns the config of this layer.
This Layer's `make_distribution_fn` is serialized via a library built on
Python pickle. This serialization of Python functions is provided for
convenience, but:
1. The use of this format for long-term storage of models is discouraged.
... | Returns the config of this layer.
This Layer's `make_distribution_fn` is serialized via a library built on
Python pickle. This serialization of Python functions is provided for
convenience, but:
1. The use of this format for long-term storage of models is discouraged.
In particular, it may... |
def maybeparens(lparen, item, rparen):
"""Wrap an item in optional parentheses, only applying them if necessary."""
return item | lparen.suppress() + item + rparen.suppress() | Wrap an item in optional parentheses, only applying them if necessary. |
async def _get_security_token(self) -> None:
"""Request a security token."""
_LOGGER.debug('Requesting security token.')
if self._credentials is None:
return
# Make sure only 1 request can be sent at a time.
async with self._security_token_lock:
# Confirm... | Request a security token. |
def process_node(self, node, parent, end, open_list, open_value=True):
'''
we check if the given node is path of the path by calculating its
cost and add or remove it from our path
:param node: the node we like to test
(the neighbor in A* or jump-node in JumpPointSearch)
... | we check if the given node is path of the path by calculating its
cost and add or remove it from our path
:param node: the node we like to test
(the neighbor in A* or jump-node in JumpPointSearch)
:param parent: the parent node (the current node we like to test)
:param end: t... |
def update_bounds(self, bounds):
'''Update the bounds inplace'''
self.bounds = np.array(bounds, dtype='float32')
vertices, directions = self._gen_bounds(self.bounds)
self._verts_vbo.set_data(vertices)
self._directions_vbo.set_data(directions)
self.widget.update(... | Update the bounds inplace |
def goto_step(self, inst: InstanceNode) -> InstanceNode:
"""Return member instance of `inst` addressed by the receiver.
Args:
inst: Current instance.
"""
return inst.look_up(**self.parse_keys(inst.schema_node)) | Return member instance of `inst` addressed by the receiver.
Args:
inst: Current instance. |
def is_valid(self, qstr=None):
"""Return True if string is valid"""
if qstr is None:
qstr = self.currentText()
return is_module_or_package(to_text_string(qstr)) | Return True if string is valid |
def compose(request, recipient=None, form_class=ComposeForm,
template_name='django_messages/compose.html', success_url=None, recipient_filter=None):
"""
Displays and handles the ``form_class`` form to compose new messages.
Required Arguments: None
Optional Arguments:
``recipient``: usern... | Displays and handles the ``form_class`` form to compose new messages.
Required Arguments: None
Optional Arguments:
``recipient``: username of a `django.contrib.auth` User, who should
receive the message, optionally multiple usernames
could be separated by a ... |
def inference(self, kern_r, kern_c, Xr, Xc, Zr, Zc, likelihood, Y, qU_mean ,qU_var_r, qU_var_c, indexD, output_dim):
"""
The SVI-VarDTC inference
"""
N, D, Mr, Mc, Qr, Qc = Y.shape[0], output_dim,Zr.shape[0], Zc.shape[0], Zr.shape[1], Zc.shape[1]
uncertain_inputs_r = isinstance... | The SVI-VarDTC inference |
def json_template(data, template_name, template_context):
"""Old style, use JSONTemplateResponse instead of this.
"""
html = render_to_string(template_name, template_context)
data = data or {}
data['html'] = html
return HttpResponse(json_encode(data), content_type='application/json') | Old style, use JSONTemplateResponse instead of this. |
def _blast(bvname2vals, name_map):
"""Helper function to expand (blast) str -> int map into str ->
bool map. This is used to send word level inputs to aiger."""
if len(name_map) == 0:
return dict()
return fn.merge(*(dict(zip(names, bvname2vals[bvname]))
for bvname, names in... | Helper function to expand (blast) str -> int map into str ->
bool map. This is used to send word level inputs to aiger. |
def search_accounts(self, **kwargs):
"""
Return a list of up to 5 matching account domains. Partial matches on
name and domain are supported.
:calls: `GET /api/v1/accounts/search \
<https://canvas.instructure.com/doc/api/account_domain_lookups.html#method.account_domain_lookups.... | Return a list of up to 5 matching account domains. Partial matches on
name and domain are supported.
:calls: `GET /api/v1/accounts/search \
<https://canvas.instructure.com/doc/api/account_domain_lookups.html#method.account_domain_lookups.search>`_
:rtype: dict |
def from_definition(self, table: Table, version: int):
"""Add all columns from the table added in the specified version"""
self.table(table)
self.add_columns(*table.columns.get_with_version(version))
return self | Add all columns from the table added in the specified version |
def _estimate_gas(self, initializer: bytes, salt_nonce: int,
payment_token: str, payment_receiver: str) -> int:
"""
Gas estimation done using web3 and calling the node
Payment cannot be estimated, as no ether is in the address. So we add some gas later.
:param initi... | Gas estimation done using web3 and calling the node
Payment cannot be estimated, as no ether is in the address. So we add some gas later.
:param initializer: Data initializer to send to GnosisSafe setup method
:param salt_nonce: Nonce that will be used to generate the salt to calculate
t... |
def items_iter(self, limit):
'''Get an iterator of the 'items' in each page. Instead of a feature
collection from each page, the iterator yields the features.
:param int limit: The number of 'items' to limit to.
:return: iter of items in page
'''
pages = (page.get() for... | Get an iterator of the 'items' in each page. Instead of a feature
collection from each page, the iterator yields the features.
:param int limit: The number of 'items' to limit to.
:return: iter of items in page |
def preprocess_data(self, div=1, downsample=0, sum_norm=None,
include_genes=None, exclude_genes=None,
include_cells=None, exclude_cells=None,
norm='log', min_expression=1, thresh=0.01,
filter_genes=True):
"""Log-norm... | Log-normalizes and filters the expression data.
Parameters
----------
div : float, optional, default 1
The factor by which the gene expression will be divided prior to
log normalization.
downsample : float, optional, default 0
The factor by which to... |
def imresize(img, size, interpolate="bilinear", channel_first=False):
"""
Resize image by pil module.
Args:
img (numpy.ndarray): Image array to save.
Image shape is considered as (height, width, channel) for RGB or (height, width) for gray-scale by default.
size (tupple of int): ... | Resize image by pil module.
Args:
img (numpy.ndarray): Image array to save.
Image shape is considered as (height, width, channel) for RGB or (height, width) for gray-scale by default.
size (tupple of int): (width, height).
channel_first (bool):
This argument specifies... |
def build_tf_to_pytorch_map(model, config):
""" A map of modules from TF to PyTorch.
This time I use a map to keep the PyTorch model as identical to the original PyTorch model as possible.
"""
tf_to_pt_map = {}
if hasattr(model, 'transformer'):
# We are loading in a TransfoXLLMHeadModel... | A map of modules from TF to PyTorch.
This time I use a map to keep the PyTorch model as identical to the original PyTorch model as possible. |
def createphysicalnetwork(type, create_processor = partial(default_processor, excluding=('id', 'type')),
reorder_dict = default_iterate_dict):
"""
:param type: physical network type
:param create_processor: create_processor(physicalnetwork, walk, write, \*, paramet... | :param type: physical network type
:param create_processor: create_processor(physicalnetwork, walk, write, \*, parameters) |
def energy_density(self, strain, convert_GPa_to_eV=True):
"""
Calculates the elastic energy density due to a strain
"""
e_density = np.sum(self.calculate_stress(strain)*strain) / self.order
if convert_GPa_to_eV:
e_density *= self.GPa_to_eV_A3 # Conversion factor for ... | Calculates the elastic energy density due to a strain |
def _folder_item_instrument(self, analysis_brain, item):
"""Fills the analysis' instrument to the item passed in.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row
"""
item['Instrument'] = ''
if n... | Fills the analysis' instrument to the item passed in.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row |
def formfield(self, form_class=None, choices_form_class=None, **kwargs):
"""
Returns a django.forms.Field instance for this database Field.
"""
defaults = {
'required': not self.blank,
'label': capfirst(self.verbose_name),
'help_text': self.help_text,
... | Returns a django.forms.Field instance for this database Field. |
def extendedboldqc(auth, label, scan_ids=None, project=None, aid=None):
'''
Get ExtendedBOLDQC data as a sequence of dictionaries.
Example:
>>> import yaxil
>>> import json
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> for eqc in yaxil.extendedbold... | Get ExtendedBOLDQC data as a sequence of dictionaries.
Example:
>>> import yaxil
>>> import json
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> for eqc in yaxil.extendedboldqc2(auth, 'AB1234C')
... print(json.dumps(eqc, indent=2))
:param au... |
def autosave_all(self):
"""Autosave all opened files."""
for index in range(self.stack.get_stack_count()):
self.autosave(index) | Autosave all opened files. |
def comment_form(context, object):
"""
Usage:
{% comment_form obj as comment_form %}
Will read the `user` var out of the contex to know if the form should be
form an auth'd user or not.
"""
user = context.get("user")
form_class = context.get("form", CommentForm)
form = form_class... | Usage:
{% comment_form obj as comment_form %}
Will read the `user` var out of the contex to know if the form should be
form an auth'd user or not. |
def render_image(**kwargs):
"""
Unstrict template block for rendering an image:
<img alt="{alt_text}" title="{title}" src="{url}">
"""
html = ''
url = kwargs.get('url', None)
if url:
html = '<img'
alt_text = kwargs.get('alt_text', None)
if alt_text:
html... | Unstrict template block for rendering an image:
<img alt="{alt_text}" title="{title}" src="{url}"> |
def path_order (x, y):
""" Helper for as_path, below. Orders properties with the implicit ones
first, and within the two sections in alphabetical order of feature
name.
"""
if x == y:
return 0
xg = get_grist (x)
yg = get_grist (y)
if yg and not xg:
return -1
... | Helper for as_path, below. Orders properties with the implicit ones
first, and within the two sections in alphabetical order of feature
name. |
def _make_cloud_datastore_context(app_id, external_app_ids=()):
"""Creates a new context to connect to a remote Cloud Datastore instance.
This should only be used outside of Google App Engine.
Args:
app_id: The application id to connect to. This differs from the project
id as it may have an additional... | Creates a new context to connect to a remote Cloud Datastore instance.
This should only be used outside of Google App Engine.
Args:
app_id: The application id to connect to. This differs from the project
id as it may have an additional prefix, e.g. "s~" or "e~".
external_app_ids: A list of apps that... |
def cyber_observable_check(original_function):
"""Decorator for functions that require cyber observable data.
"""
def new_function(*args, **kwargs):
if not has_cyber_observable_data(args[0]):
return
func = original_function(*args, **kwargs)
if isinstance(func, Iterable):
... | Decorator for functions that require cyber observable data. |
def get_warmer(self, doc_types=None, indices=None, name=None, querystring_args=None):
"""
Retrieve warmer
:param doc_types: list of document types
:param warmer: anything with ``serialize`` method or a dictionary
:param name: warmer name. If not provided, all warmers will be ret... | Retrieve warmer
:param doc_types: list of document types
:param warmer: anything with ``serialize`` method or a dictionary
:param name: warmer name. If not provided, all warmers will be returned
:param querystring_args: additional arguments passed as GET params to ES |
def _next_pattern(self):
"""Parses the next pattern by matching each in turn."""
current_state = self.state_stack[-1]
position = self._position
for pattern in self.patterns:
if current_state not in pattern.states:
continue
m = pattern.regex.match(... | Parses the next pattern by matching each in turn. |
def _start_loop(self, websocket, event_handler):
"""
We will listen for websockets events, sending a heartbeat/pong everytime
we react a TimeoutError. If we don't the webserver would close the idle connection,
forcing us to reconnect.
"""
log.debug('Starting websocket loop')
while True:
try:
yield ... | We will listen for websockets events, sending a heartbeat/pong everytime
we react a TimeoutError. If we don't the webserver would close the idle connection,
forcing us to reconnect. |
def to_file(self, filename, format='shtools', header=None, errors=False,
**kwargs):
"""
Save spherical harmonic coefficients to a file.
Usage
-----
x.to_file(filename, [format='shtools', header, errors])
x.to_file(filename, [format='npy', **kwargs])
... | Save spherical harmonic coefficients to a file.
Usage
-----
x.to_file(filename, [format='shtools', header, errors])
x.to_file(filename, [format='npy', **kwargs])
Parameters
----------
filename : str
Name of the output file.
format : str, opti... |
def clear(self):
"""Clears the Merkle Tree by releasing the Merkle root and each leaf's references, the rest
should be garbage collected. This may be useful for situations where you want to take an existing
tree, make changes to the leaves, but leave it uncalculated for some time, without node
... | Clears the Merkle Tree by releasing the Merkle root and each leaf's references, the rest
should be garbage collected. This may be useful for situations where you want to take an existing
tree, make changes to the leaves, but leave it uncalculated for some time, without node
references that are ... |
def uniqueify_all(init_reqs, *other_reqs):
"""Find the union of all the given requirements."""
union = set(init_reqs)
for reqs in other_reqs:
union.update(reqs)
return list(union) | Find the union of all the given requirements. |
def msgDict(d,matching=None,sep1="=",sep2="\n",sort=True,cantEndWith=None):
"""convert a dictionary to a pretty formatted string."""
msg=""
if "record" in str(type(d)):
keys=d.dtype.names
else:
keys=d.keys()
if sort:
keys=sorted(keys)
for key in keys:
if key[0]=="... | convert a dictionary to a pretty formatted string. |
def create_scoped_session(self, options=None):
"""Create a :class:`~sqlalchemy.orm.scoping.scoped_session`
on the factory from :meth:`create_session`.
An extra key ``'scopefunc'`` can be set on the ``options`` dict to
specify a custom scope function. If it's not provided, Flask's app
... | Create a :class:`~sqlalchemy.orm.scoping.scoped_session`
on the factory from :meth:`create_session`.
An extra key ``'scopefunc'`` can be set on the ``options`` dict to
specify a custom scope function. If it's not provided, Flask's app
context stack identity is used. This will ensure th... |
def select(self, key, where=None, start=None, stop=None, columns=None,
iterator=False, chunksize=None, auto_close=False, **kwargs):
"""
Retrieve pandas object stored in file, optionally based on where
criteria
Parameters
----------
key : object
whe... | Retrieve pandas object stored in file, optionally based on where
criteria
Parameters
----------
key : object
where : list of Term (or convertible) objects, optional
start : integer (defaults to None), row number to start selection
stop : integer (defaults to Non... |
def save_to_local(self, callback_etat=print):
"""
Saved current in memory base to local file.
It's a backup, not a convenient way to update datas
:param callback_etat: state callback, taking str,int,int as args
"""
callback_etat("Aquisition...", 0, 3)
d = self.d... | Saved current in memory base to local file.
It's a backup, not a convenient way to update datas
:param callback_etat: state callback, taking str,int,int as args |
def addchild(self, startip, endip, name, description):
"""
Method takes inpur of str startip, str endip, name, and description and adds a child scope.
The startip and endip MUST be in the IP address range of the parent scope.
:param startip: str of ipv4 address of the first address in th... | Method takes inpur of str startip, str endip, name, and description and adds a child scope.
The startip and endip MUST be in the IP address range of the parent scope.
:param startip: str of ipv4 address of the first address in the child scope
:param endip: str of ipv4 address of the last address... |
def generic_find_fk_constraint_names(table, columns, referenced, insp):
"""Utility to find foreign-key constraint names in alembic migrations"""
names = set()
for fk in insp.get_foreign_keys(table):
if fk['referred_table'] == referenced and set(fk['referred_columns']) == columns:
names.... | Utility to find foreign-key constraint names in alembic migrations |
def parse(url):
"""
Parses out the information for this url, returning its components
expanded out to Python objects.
:param url | <str>
:return (<str> path, <dict> query, <str> fragment)
"""
result = urlparse.urlparse(nstr(url))
path = result.scheme + '://' + result.... | Parses out the information for this url, returning its components
expanded out to Python objects.
:param url | <str>
:return (<str> path, <dict> query, <str> fragment) |
def augment_audio_with_sox(path, sample_rate, tempo, gain):
"""
Changes tempo and gain of the recording with sox and loads it.
"""
with NamedTemporaryFile(suffix=".wav") as augmented_file:
augmented_filename = augmented_file.name
sox_augment_params = ["tempo", "{:.3f}".format(tempo), "ga... | Changes tempo and gain of the recording with sox and loads it. |
def get_title():
''' Returns console title string.
https://docs.microsoft.com/en-us/windows/console/getconsoletitle
'''
MAX_LEN = 256
buffer_ = create_unicode_buffer(MAX_LEN)
kernel32.GetConsoleTitleW(buffer_, MAX_LEN)
log.debug('%s', buffer_.value)
return buffer_.value | Returns console title string.
https://docs.microsoft.com/en-us/windows/console/getconsoletitle |
def check(self, order, sids):
''' Check if a message is available '''
payload = "{}"
#TODO store hashes {'intuition': {'id1': value, 'id2': value}}
# Block self.timeout seconds on self.channel for a message
raw_msg = self.client.blpop(self.channel, timeout=self.timeout)
i... | Check if a message is available |
def value(val, transform=None):
''' Convenience function to explicitly return a "value" specification for
a Bokeh :class:`~bokeh.core.properties.DataSpec` property.
Args:
val (any) : a fixed value to specify for a ``DataSpec`` property.
transform (Transform, optional) : a transform to appl... | Convenience function to explicitly return a "value" specification for
a Bokeh :class:`~bokeh.core.properties.DataSpec` property.
Args:
val (any) : a fixed value to specify for a ``DataSpec`` property.
transform (Transform, optional) : a transform to apply (default: None)
Returns:
... |
def create_geom_filter(request, mapped_class, geom_attr):
"""Create MapFish geometry filter based on the request params. Either
a box or within or geometry filter, depending on the request params.
Additional named arguments are passed to the spatial filter.
Arguments:
request
the request.
... | Create MapFish geometry filter based on the request params. Either
a box or within or geometry filter, depending on the request params.
Additional named arguments are passed to the spatial filter.
Arguments:
request
the request.
mapped_class
the SQLAlchemy mapped class.
geom_... |
def getref():
"""Current default values for graph and component tables, primary area,
and wavelength set.
.. note::
Also see :func:`setref`.
Returns
-------
ans : dict
Mapping of parameter names to their current values.
"""
ans=dict(graphtable=GRAPHTABLE,
... | Current default values for graph and component tables, primary area,
and wavelength set.
.. note::
Also see :func:`setref`.
Returns
-------
ans : dict
Mapping of parameter names to their current values. |
def build_board_checkers():
""" builds a checkers starting board
Printing Grid
0 B 0 B 0 B 0 B
B 0 B 0 B 0 B 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0... | builds a checkers starting board
Printing Grid
0 B 0 B 0 B 0 B
B 0 B 0 B 0 B 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 ... |
def write_config(config_data: Dict[str, Path],
path: Path = None):
""" Save the config file.
:param config_data: The index to save
:param base_dir: The place to save the file. If ``None``,
:py:meth:`infer_config_base_dir()` will be used
Only keys that are in the c... | Save the config file.
:param config_data: The index to save
:param base_dir: The place to save the file. If ``None``,
:py:meth:`infer_config_base_dir()` will be used
Only keys that are in the config elements will be saved. |
def copy_fields(layer, fields_to_copy):
"""Copy fields inside an attribute table.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:param fields_to_copy: Dictionary of fields to copy.
:type fields_to_copy: dict
"""
for field in fields_to_copy:
index = layer.fields().loo... | Copy fields inside an attribute table.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:param fields_to_copy: Dictionary of fields to copy.
:type fields_to_copy: dict |
def main(sample_id, fastq_pair, gsize, minimum_coverage, opts):
""" Main executor of the integrity_coverage template.
Parameters
----------
sample_id : str
Sample Identification string.
fastq_pair : list
Two element list containing the paired FastQ files.
gsize : float or int
... | Main executor of the integrity_coverage template.
Parameters
----------
sample_id : str
Sample Identification string.
fastq_pair : list
Two element list containing the paired FastQ files.
gsize : float or int
Estimate of genome size in Mb.
minimum_coverage : float or int... |
def countries(self):
"""
Access the countries
:returns: twilio.rest.voice.v1.dialing_permissions.country.CountryList
:rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryList
"""
if self._countries is None:
self._countries = CountryList(self._versi... | Access the countries
:returns: twilio.rest.voice.v1.dialing_permissions.country.CountryList
:rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryList |
def download(
self,
file: Union[IO[bytes], asyncio.StreamWriter, None]=None,
raw: bool=False, rewind: bool=True,
duration_timeout: Optional[float]=None):
'''Read the response content into file.
Args:
file: A file object or asyncio stream.
... | Read the response content into file.
Args:
file: A file object or asyncio stream.
raw: Whether chunked transfer encoding should be included.
rewind: Seek the given file back to its original offset after
reading is finished.
duration_timeout: Maxim... |
def check(text):
"""Check the text."""
err = "MSC104"
msg = u"Don't fail to capitalize roman numeral abbreviations."
pwd_regex = " (I(i*)|i*)"
password = [
"World War{}".format(pwd_regex),
]
return blacklist(text, password, err, msg) | Check the text. |
def apply_noise(self, noise_weights=None, uniform_amount=0.1):
"""
Add noise to every link in the network.
Can use either a ``uniform_amount`` or a ``noise_weight`` weight
profile. If ``noise_weight`` is set, ``uniform_amount`` will be
ignored.
Args:
noise_w... | Add noise to every link in the network.
Can use either a ``uniform_amount`` or a ``noise_weight`` weight
profile. If ``noise_weight`` is set, ``uniform_amount`` will be
ignored.
Args:
noise_weights (list): a list of weight tuples
of form ``(float, float)`` c... |
def raise_for_status(self):
"""Raises HTTPError if the request got an error."""
if 400 <= self.status_code < 600:
message = 'Error %s for %s' % (self.status_code, self.url)
raise HTTPError(message) | Raises HTTPError if the request got an error. |
def ensure_crops(self, *required_crops):
"""
Make sure a crop exists for each crop in required_crops.
Existing crops will not be changed.
If settings.ASSET_CELERY is specified then
the task will be run async
"""
if self._can_crop():
if settings.CELERY... | Make sure a crop exists for each crop in required_crops.
Existing crops will not be changed.
If settings.ASSET_CELERY is specified then
the task will be run async |
def set_umr_namelist(self):
"""Set UMR excluded modules name list"""
arguments, valid = QInputDialog.getText(self, _('UMR'),
_("Set the list of excluded modules as "
"this: <i>numpy, scipy</i>"),
... | Set UMR excluded modules name list |
def connect(self):
"""
Starts up an authentication session for the client using cookie
authentication if necessary.
"""
if self.r_session:
self.session_logout()
if self.admin_party:
self._use_iam = False
self.r_session = ClientSession(... | Starts up an authentication session for the client using cookie
authentication if necessary. |
def GenerateLabels(self, hash_information):
"""Generates a list of strings that will be used in the event tag.
Args:
hash_information (dict[str, object]): JSON decoded contents of the result
of a Viper lookup, as produced by the ViperAnalyzer.
Returns:
list[str]: list of labels to ap... | Generates a list of strings that will be used in the event tag.
Args:
hash_information (dict[str, object]): JSON decoded contents of the result
of a Viper lookup, as produced by the ViperAnalyzer.
Returns:
list[str]: list of labels to apply to events. |
def convert_to_int(x: Any, default: int = None) -> int:
"""
Transforms its input into an integer, or returns ``default``.
"""
try:
return int(x)
except (TypeError, ValueError):
return default | Transforms its input into an integer, or returns ``default``. |
def getBucketInfo(self, buckets):
""" See the function description in base.py
"""
if self.ncategories==0:
return 0
topDownMappingM = self._getTopDownMapping()
categoryIndex = buckets[0]
category = self.categories[categoryIndex]
encoding = topDownMappingM.getRow(categoryIndex)
r... | See the function description in base.py |
def search_device_by_id(self, deviceID) -> Device:
""" searches a device by given id
Args:
deviceID(str): the device to search for
Returns
the Device object or None if it couldn't find a device
"""
for d in self.devices:
... | searches a device by given id
Args:
deviceID(str): the device to search for
Returns
the Device object or None if it couldn't find a device |
def mkdir(self, paths, create_parent=False, mode=0o755):
''' Create a directoryCount
:param paths: Paths to create
:type paths: list of strings
:param create_parent: Also create the parent directories
:type create_parent: boolean
:param mode: Mode the directory should be... | Create a directoryCount
:param paths: Paths to create
:type paths: list of strings
:param create_parent: Also create the parent directories
:type create_parent: boolean
:param mode: Mode the directory should be created with
:type mode: int
:returns: a generator t... |
def remote_pdb_handler(signum, frame):
""" Handler to drop us into a remote debugger upon receiving SIGUSR1 """
try:
from remote_pdb import RemotePdb
rdb = RemotePdb(host="127.0.0.1", port=0)
rdb.set_trace(frame=frame)
except ImportError:
log.warning(
"remote_pdb... | Handler to drop us into a remote debugger upon receiving SIGUSR1 |
def _open_file(self, filename):
"""Open a file to be tailed"""
if not self._os_is_windows:
self._fh = open(filename, "rb")
self.filename = filename
self._fh.seek(0, os.SEEK_SET)
self.oldsize = 0
return
# if we're in Windows, we need t... | Open a file to be tailed |
def read_until(self, marker):
"""
Reads data from the socket until a marker is found. Data read includes
the marker.
:param marker:
A byte string or regex object from re.compile(). Used to determine
when to stop reading. Regex objects are more inefficient since
... | Reads data from the socket until a marker is found. Data read includes
the marker.
:param marker:
A byte string or regex object from re.compile(). Used to determine
when to stop reading. Regex objects are more inefficient since
they must scan the entire byte string o... |
async def ensure_usable_media(self, media: BaseMedia) -> UrlMedia:
"""
So far, let's just accept URL media. We'll see in the future how it
goes.
"""
if not isinstance(media, UrlMedia):
raise ValueError('Facebook platform only accepts URL media')
return media | So far, let's just accept URL media. We'll see in the future how it
goes. |
def prop_budget(self, budget):
"""
Set limit on the number of propagations.
"""
if self.minisat:
pysolvers.minisatgh_pbudget(self.minisat, budget) | Set limit on the number of propagations. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.