code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def configure_firewall(self, FirewallRules):
"""
Helper function for automatically adding several FirewallRules in series.
"""
firewall_rule_bodies = [
FirewallRule.to_dict()
for FirewallRule in FirewallRules
]
return self.cloud_manager.configure_f... | Helper function for automatically adding several FirewallRules in series. |
def draw_polygon(
self,
*pts,
close_path=True,
stroke=None,
stroke_width=1,
stroke_dash=None,
fill=None
) -> None:
"""Draws the given polygon."""
c = self.c
c.saveState()
if stroke is not Non... | Draws the given polygon. |
def search_bm25(cls, term, weights=None, with_score=False,
score_alias='score', explicit_ordering=False):
"""Full-text search using selected `term`."""
if not weights:
rank = SQL('rank')
elif isinstance(weights, dict):
weight_args = []
for ... | Full-text search using selected `term`. |
def _GetPluginData(self):
"""Retrieves the version and various plugin information.
Returns:
dict[str, list[str]]: available parsers and plugins.
"""
return_dict = {}
return_dict['Versions'] = [
('plaso engine', plaso.__version__),
('python', sys.version)]
hashers_informa... | Retrieves the version and various plugin information.
Returns:
dict[str, list[str]]: available parsers and plugins. |
def load_collection_from_stream(resource, stream, content_type):
"""
Creates a new collection for the registered resource and calls
`load_into_collection_from_stream` with it.
"""
coll = create_staging_collection(resource)
load_into_collection_from_stream(coll, stream, content_type)
return c... | Creates a new collection for the registered resource and calls
`load_into_collection_from_stream` with it. |
def find_token(self, start_token, tok_type, tok_str=None, reverse=False):
"""
Looks for the first token, starting at start_token, that matches tok_type and, if given, the
token string. Searches backwards if reverse is True. Returns ENDMARKER token if not found (you
can check it with `token.ISEOF(t.type)... | Looks for the first token, starting at start_token, that matches tok_type and, if given, the
token string. Searches backwards if reverse is True. Returns ENDMARKER token if not found (you
can check it with `token.ISEOF(t.type)`. |
def restart(self):
"""
Restarts the whole wizard from the beginning.
"""
# hide all of the pages
for page in self._pages.values():
page.hide()
pageId = self.startId()
try:
first_page = self._pages[pageId]
except KeyError:
... | Restarts the whole wizard from the beginning. |
def bundle(self, bundle_id, channel=None):
'''Get the default data for a bundle.
@param bundle_id The bundle's id.
@param channel Optional channel name.
'''
return self.entity(bundle_id, get_files=True, channel=channel) | Get the default data for a bundle.
@param bundle_id The bundle's id.
@param channel Optional channel name. |
def put_archive(request, pid):
"""MNStorage.archive(session, did) → Identifier."""
d1_gmn.app.views.assert_db.is_not_replica(pid)
d1_gmn.app.views.assert_db.is_not_archived(pid)
d1_gmn.app.sysmeta.archive_sciobj(pid)
return pid | MNStorage.archive(session, did) → Identifier. |
def getreferingobjs(referedobj, iddgroups=None, fields=None):
"""Get a list of objects that refer to this object"""
# pseudocode for code below
# referringobjs = []
# referedobj has: -> Name
# -> reference
# for each obj in idf:
# [optional filter -> objects in iddgroup]
... | Get a list of objects that refer to this object |
def keyPressEvent(self, event):
"""Qt Override."""
key = event.key()
if key in [Qt.Key_Enter, Qt.Key_Return]:
self.show_editor()
elif key in [Qt.Key_Tab]:
self.finder.setFocus()
elif key in [Qt.Key_Backtab]:
self.parent().reset_btn.setF... | Qt Override. |
def rpc_get_docstring(self, filename, source, offset):
"""Get the docstring for the symbol at the offset.
"""
return self._call_backend("rpc_get_docstring", None, filename,
get_source(source), offset) | Get the docstring for the symbol at the offset. |
def get_any_nt_unit_rule(g):
"""Returns a non-terminal unit rule from 'g', or None if there is none."""
for rule in g.rules:
if len(rule.rhs) == 1 and isinstance(rule.rhs[0], NT):
return rule
return None | Returns a non-terminal unit rule from 'g', or None if there is none. |
def gaussian(x, y, xsigma, ysigma):
"""
Two-dimensional oriented Gaussian pattern (i.e., 2D version of a
bell curve, like a normal distribution but not necessarily summing
to 1.0).
"""
if xsigma==0.0 or ysigma==0.0:
return x*0.0
with float_error_ignore():
x_w = np.divide(x,x... | Two-dimensional oriented Gaussian pattern (i.e., 2D version of a
bell curve, like a normal distribution but not necessarily summing
to 1.0). |
def symmetrise(matrix, tri='upper'):
"""
Will copy the selected (upper or lower) triangle of a square matrix
to the opposite side, so that the matrix is symmetrical.
Alters in place.
"""
if tri == 'upper':
tri_fn = np.triu_indices
else:
tri_fn = np.tril_indices
size = mat... | Will copy the selected (upper or lower) triangle of a square matrix
to the opposite side, so that the matrix is symmetrical.
Alters in place. |
def _reset(self, server, **kwargs):
"""
Reset the server object with new values given as params.
- server: a dict representing the server. e.g the API response.
- kwargs: any meta fields such as cloud_manager and populated.
Note: storage_devices and ip_addresses may be given in... | Reset the server object with new values given as params.
- server: a dict representing the server. e.g the API response.
- kwargs: any meta fields such as cloud_manager and populated.
Note: storage_devices and ip_addresses may be given in server as dicts or
in kwargs as lists containin... |
def method_name(func):
"""Method wrapper that adds the name of the method being called to its arguments list in Pascal case
"""
@wraps(func)
def _method_name(*args, **kwargs):
name = to_pascal_case(func.__name__)
return func(name=name, *args, **kwargs)
return _method_name | Method wrapper that adds the name of the method being called to its arguments list in Pascal case |
def start(self) -> None:
"""
Starts a new thread that handles the input. If a thread is already running, the thread will be restarted.
"""
self.stop() # stop an existing thread
self._thread = receiverThread(socket=self.sock, callbacks=self._callbacks)
self._thread.start(... | Starts a new thread that handles the input. If a thread is already running, the thread will be restarted. |
def zip_ll(data, means, M):
"""
Calculates the zero-inflated Poisson log-likelihood.
Args:
data (array): genes x cells
means (array): genes x k
M (array): genes x k - this is the zero-inflation parameter.
Returns:
cells x k array of log-likelihood for each cell/cluster ... | Calculates the zero-inflated Poisson log-likelihood.
Args:
data (array): genes x cells
means (array): genes x k
M (array): genes x k - this is the zero-inflation parameter.
Returns:
cells x k array of log-likelihood for each cell/cluster pair. |
def accuracy_study(tdm=None, u=None, s=None, vt=None, verbosity=0, **kwargs):
""" Reconstruct the term-document matrix and measure error as SVD terms are truncated
"""
smat = np.zeros((len(u), len(vt)))
np.fill_diagonal(smat, s)
smat = pd.DataFrame(smat, columns=vt.index, index=u.index)
if verbo... | Reconstruct the term-document matrix and measure error as SVD terms are truncated |
def run(self):
"""
Begin reading through audio files, saving false
activations and retraining when necessary
"""
for fn in glob_all(self.args.random_data_folder, '*.wav'):
if fn in self.trained_fns:
print('Skipping ' + fn + '...')
conti... | Begin reading through audio files, saving false
activations and retraining when necessary |
def get_router_for_floatingip(self, context, internal_port,
internal_subnet, external_network_id):
"""We need to over-load this function so that we only return the
user visible router and never its redundancy routers (as they never
have floatingips associated wi... | We need to over-load this function so that we only return the
user visible router and never its redundancy routers (as they never
have floatingips associated with them). |
def holdAcknowledge():
"""HOLD ACKNOWLEDGE Section 9.3.11"""
a = TpPd(pd=0x3)
b = MessageType(mesType=0x19) # 00011001
packet = a / b
return packet | HOLD ACKNOWLEDGE Section 9.3.11 |
def _set_cdn_access(self, container, public, ttl=None):
"""
Enables or disables CDN access for the specified container, and
optionally sets the TTL for the container when enabling access.
"""
headers = {"X-Cdn-Enabled": "%s" % public}
if public and ttl:
header... | Enables or disables CDN access for the specified container, and
optionally sets the TTL for the container when enabling access. |
def get_scoped_variable_m(self, data_port_id):
"""Returns the scoped variable model for the given data port id
:param data_port_id: The data port id to search for
:return: The model of the scoped variable with the given id
"""
for scoped_variable_m in self.scoped_variables:
... | Returns the scoped variable model for the given data port id
:param data_port_id: The data port id to search for
:return: The model of the scoped variable with the given id |
def _check_curtailment_target(curtailment, curtailment_target,
curtailment_key):
"""
Raises an error if curtailment target was not met in any time step.
Parameters
-----------
curtailment : :pandas:`pandas:DataFrame<dataframe>`
Dataframe containing the curtailm... | Raises an error if curtailment target was not met in any time step.
Parameters
-----------
curtailment : :pandas:`pandas:DataFrame<dataframe>`
Dataframe containing the curtailment in kW per generator and time step.
Index is a :pandas:`pandas.DatetimeIndex<datetimeindex>`, columns are
... |
def composite(
background_image,
foreground_image,
foreground_width_ratio=0.25,
foreground_position=(0.0, 0.0),
):
"""Takes two images and composites them."""
if foreground_width_ratio <= 0:
return background_image
composite = background_image.copy()
width = int(foreground_widt... | Takes two images and composites them. |
def minion_pub(self, clear_load):
'''
Publish a command initiated from a minion, this method executes minion
restrictions so that the minion publication will only work if it is
enabled in the config.
The configuration on the master allows minions to be matched to
salt fu... | Publish a command initiated from a minion, this method executes minion
restrictions so that the minion publication will only work if it is
enabled in the config.
The configuration on the master allows minions to be matched to
salt functions, so the minions can only publish allowed salt ... |
def solid_angles(self, permutation=None):
"""
Returns the list of "perfect" solid angles Each edge is given as a
list of its end vertices coordinates.
"""
if permutation is None:
return self._solid_angles
else:
return [self._solid_angles[ii] for ii... | Returns the list of "perfect" solid angles Each edge is given as a
list of its end vertices coordinates. |
def dump_json_data(page):
"""
Return a python dict representation of this page for use as part of
a JSON export.
"""
def content_langs_ordered():
"""
Return a list of languages ordered by the page content
with the latest creation date in each. This will be used
to ma... | Return a python dict representation of this page for use as part of
a JSON export. |
def getModelPosterior(self,min):
"""
USES LAPLACE APPROXIMATION TO CALCULATE THE BAYESIAN MODEL POSTERIOR
"""
Sigma = self.getLaplaceCovar(min)
n_params = self.vd.getNumberScales()
ModCompl = 0.5*n_params*SP.log(2*SP.pi)+0.5*SP.log(SP.linalg.det(Sigma))
RV = min['... | USES LAPLACE APPROXIMATION TO CALCULATE THE BAYESIAN MODEL POSTERIOR |
def _animate_bbvi(self,stored_latent_variables,stored_predictive_likelihood):
""" Produces animated plot of BBVI optimization
Returns
----------
None (changes model attributes)
"""
from matplotlib.animation import FuncAnimation, writers
import matplotlib.pyplot ... | Produces animated plot of BBVI optimization
Returns
----------
None (changes model attributes) |
def distance(self, loc):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
assert type(loc) == type(self)
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [
self.lon,
... | Calculate the great circle distance between two points
on the earth (specified in decimal degrees) |
def run(command, parser, cl_args, unknown_args):
'''
:param command:
:param parser:
:param cl_args:
:param unknown_args:
:return:
'''
Log.debug("Deactivate Args: %s", cl_args)
return cli_helper.run(command, cl_args, "deactivate topology") | :param command:
:param parser:
:param cl_args:
:param unknown_args:
:return: |
def write_unchecked_hmac_data(self, offsets, data):
# type: (Descriptor, Offsets, bytes) -> None
"""Write unchecked encrypted data to disk
:param Descriptor self: this
:param Offsets offsets: download offsets
:param bytes data: hmac/encrypted data
"""
fname = None... | Write unchecked encrypted data to disk
:param Descriptor self: this
:param Offsets offsets: download offsets
:param bytes data: hmac/encrypted data |
def log_interpolate_1d(x, xp, *args, **kwargs):
r"""Interpolates data with logarithmic x-scale over a specified axis.
Interpolation on a logarithmic x-scale for interpolation values in pressure coordintates.
Parameters
----------
x : array-like
1-D array of desired interpolated values.
... | r"""Interpolates data with logarithmic x-scale over a specified axis.
Interpolation on a logarithmic x-scale for interpolation values in pressure coordintates.
Parameters
----------
x : array-like
1-D array of desired interpolated values.
xp : array-like
The x-coordinates of the d... |
def get_pubkey(self):
"""
Get the public key of this certificate.
:return: The public key.
:rtype: :py:class:`PKey`
"""
pkey = PKey.__new__(PKey)
pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki)
_openssl_assert(pkey._pkey != _ffi.NULL)
pkey.... | Get the public key of this certificate.
:return: The public key.
:rtype: :py:class:`PKey` |
def parse(self, filepath, dependencies=False, recursive=False, greedy=False):
"""Parses the fortran code in the specified file.
:arg dependencies: if true, all folder paths will be searched for modules
that have been referenced but aren't loaded in the parser.
:arg greedy: if true, when... | Parses the fortran code in the specified file.
:arg dependencies: if true, all folder paths will be searched for modules
that have been referenced but aren't loaded in the parser.
:arg greedy: if true, when a module cannot be found using a file name
of module_name.f90, all modules in al... |
def filter_generic(self, content_object=None, **kwargs):
"""Filter by a generic object.
:param content_object: the content object to filter on.
"""
if content_object:
kwargs['content_type'] = ContentType.objects.get_for_model(
content_object
)
... | Filter by a generic object.
:param content_object: the content object to filter on. |
def save(self, *args, **kwargs):
"""
Generate a name, and ensure amount is less than or equal to 100
"""
self.name = str(self.parent.name) + " - " + str(self.child.name) + " - " + str(self.ownership_type)
if self.amount > 100:
raise ValueError("Ownership amoun... | Generate a name, and ensure amount is less than or equal to 100 |
def free_index(self, name, free=True, **kwargs):
"""Free/Fix index of a source.
Parameters
----------
name : str
Source name.
free : bool
Choose whether to free (free=True) or fix (free=False).
"""
src = self.roi.get_source_by_name(name... | Free/Fix index of a source.
Parameters
----------
name : str
Source name.
free : bool
Choose whether to free (free=True) or fix (free=False). |
def remove_schema(self, database, schema):
"""Remove a schema from the set of known schemas (case-insensitive)
If the schema does not exist, it will be ignored - it could just be a
temporary table.
:param str database: The database name to remove.
:param str schema: The schema ... | Remove a schema from the set of known schemas (case-insensitive)
If the schema does not exist, it will be ignored - it could just be a
temporary table.
:param str database: The database name to remove.
:param str schema: The schema name to remove. |
def _round_whole_even(i):
r'''Round a number to the nearest whole number. If the number is exactly
between two numbers, round to the even whole number. Used by
`viscosity_index`.
Parameters
----------
i : float
Number, [-]
Returns
-------
i : int
Rounded number, [-]... | r'''Round a number to the nearest whole number. If the number is exactly
between two numbers, round to the even whole number. Used by
`viscosity_index`.
Parameters
----------
i : float
Number, [-]
Returns
-------
i : int
Rounded number, [-]
Notes
-----
Shou... |
def get_object_by_name(content, object_type, name, regex=False):
'''
Get the vsphere object associated with a given text name
Source: https://github.com/rreubenur/vmware-pyvmomi-examples/blob/master/create_template.py
'''
container = content.viewManager.CreateContainerView(
content.rootFolde... | Get the vsphere object associated with a given text name
Source: https://github.com/rreubenur/vmware-pyvmomi-examples/blob/master/create_template.py |
def create_invoice_from_albaran(pk, list_lines):
"""
la pk y list_lines son de albaranes, necesitamos la info de las lineas de pedidos
"""
context = {}
if list_lines:
new_list_lines = [x[0] for x in SalesLineAlbaran.objects.values_list('line_order__pk').filter(
... | la pk y list_lines son de albaranes, necesitamos la info de las lineas de pedidos |
def _run(command, quiet=False, timeout=None):
"""Run a command, returns command output."""
try:
with _spawn(command, quiet, timeout) as child:
command_output = child.read().strip().replace("\r\n", "\n")
except pexpect.TIMEOUT:
logger.info(f"command {command} timed out")
r... | Run a command, returns command output. |
def install_package_requirements(self, psrc, stream_output=None):
"""
Install from requirements.txt file found in psrc
:param psrc: name of directory in environment directory
"""
package = self.target + '/' + psrc
assert isdir(package), package
reqname = '/requir... | Install from requirements.txt file found in psrc
:param psrc: name of directory in environment directory |
def dinic(graph, capacity, source, target):
"""Maximum flow by Dinic
:param graph: directed graph in listlist or listdict format
:param capacity: in matrix format or same listdict graph
:param int source: vertex
:param int target: vertex
:returns: skew symmetric flow matrix, flow value
:com... | Maximum flow by Dinic
:param graph: directed graph in listlist or listdict format
:param capacity: in matrix format or same listdict graph
:param int source: vertex
:param int target: vertex
:returns: skew symmetric flow matrix, flow value
:complexity: :math:`O(|V|^2 |E|)` |
def new(self, limit=None):
"""GETs new links from this subreddit. Calls :meth:`narwal.Reddit.new`.
:param limit: max number of links to return
"""
return self._reddit.new(self.display_name, limit=limit) | GETs new links from this subreddit. Calls :meth:`narwal.Reddit.new`.
:param limit: max number of links to return |
def get_obj(self, vimtype, name, folder=None):
"""
Return an object by name, if name is None the
first found object is returned
"""
obj = None
content = self.service_instance.RetrieveContent()
if folder is None:
folder = content.rootFolder
co... | Return an object by name, if name is None the
first found object is returned |
def rewriteFasta(sequence, sequence_name, fasta_in, fasta_out):
"""
Rewrites a specific sequence in a multifasta file while keeping the sequence header.
:param sequence: a string with the sequence to be written
:param sequence_name: the name of the sequence to be retrieved eg. for '>2 dna:chromosome ch... | Rewrites a specific sequence in a multifasta file while keeping the sequence header.
:param sequence: a string with the sequence to be written
:param sequence_name: the name of the sequence to be retrieved eg. for '>2 dna:chromosome chromosome:GRCm38:2:1:182113224:1 REF' use: sequence_name=str(2)
:param fa... |
def is_ready(self):
"""Is thread & ioloop ready.
:returns bool:
"""
if not self._thread:
return False
if not self._ready.is_set():
return False
return True | Is thread & ioloop ready.
:returns bool: |
def score_x_of_a_kind_yahtzee(dice: List[int], min_same_faces: int) -> int:
"""Return sum of dice if there are a minimum of equal min_same_faces dice, otherwise
return zero. Only works for 3 or more min_same_faces.
"""
for die, count in Counter(dice).most_common(1):
if count >= min_same_faces:
... | Return sum of dice if there are a minimum of equal min_same_faces dice, otherwise
return zero. Only works for 3 or more min_same_faces. |
def digest_file(fname):
"""
Digest files using SHA-2 (256-bit)
TESTING
Produces identical output to `openssl sha256 FILE` for the following:
* on all source .py files and some binary pyc files in parent dir
* empty files with different names
* 3.3GB DNAse Hypersensitive file
* ... | Digest files using SHA-2 (256-bit)
TESTING
Produces identical output to `openssl sha256 FILE` for the following:
* on all source .py files and some binary pyc files in parent dir
* empty files with different names
* 3.3GB DNAse Hypersensitive file
* empty file, file with one space, fil... |
def parse_scalar_type_definition(lexer: Lexer) -> ScalarTypeDefinitionNode:
"""ScalarTypeDefinition: Description? scalar Name Directives[Const]?"""
start = lexer.token
description = parse_description(lexer)
expect_keyword(lexer, "scalar")
name = parse_name(lexer)
directives = parse_directives(le... | ScalarTypeDefinition: Description? scalar Name Directives[Const]? |
def Server(self):
"""Return server associated with this request.
>>> d = clc.v2.Datacenter()
>>> q = clc.v2.Server.Create(name="api2",cpu=1,memory=1,group_id=d.Groups().Get("Default Group").id,template=d.Templates().Search("centos-6-64")[0].id,network_id=d.Networks().networks[0].id,ttl=4000)
>>> q.WaitUntilCom... | Return server associated with this request.
>>> d = clc.v2.Datacenter()
>>> q = clc.v2.Server.Create(name="api2",cpu=1,memory=1,group_id=d.Groups().Get("Default Group").id,template=d.Templates().Search("centos-6-64")[0].id,network_id=d.Networks().networks[0].id,ttl=4000)
>>> q.WaitUntilComplete()
0
>>> q.suc... |
def isdir(self, path):
"""Return true if the path refers to an existing directory.
Parameters
----------
path : str
Path of directory on the remote side to check.
"""
result = True
try:
self.sftp_client.lstat(path)
except FileNotFo... | Return true if the path refers to an existing directory.
Parameters
----------
path : str
Path of directory on the remote side to check. |
def get_or_create(self, um_from_user, um_to_user, message):
"""
Get or create a Contact
We override Django's :func:`get_or_create` because we want contact to
be unique in a bi-directional manner.
"""
created = False
try:
contact = self.get(Q(um_from_... | Get or create a Contact
We override Django's :func:`get_or_create` because we want contact to
be unique in a bi-directional manner. |
async def step(self, step_id, session, scenario=None):
""" single scenario call.
When it returns 1, it works. -1 the script failed,
0 the test is stopping or needs to stop.
"""
if scenario is None:
scenario = pick_scenario(self.wid, step_id)
try:
... | single scenario call.
When it returns 1, it works. -1 the script failed,
0 the test is stopping or needs to stop. |
def add_statements(self, pmid, stmts):
"""Add INDRA Statements to the incremental model indexed by PMID.
Parameters
----------
pmid : str
The PMID of the paper from which statements were extracted.
stmts : list[indra.statements.Statement]
A list of INDRA ... | Add INDRA Statements to the incremental model indexed by PMID.
Parameters
----------
pmid : str
The PMID of the paper from which statements were extracted.
stmts : list[indra.statements.Statement]
A list of INDRA Statements to be added to the model. |
def recursive_refs(envs, name):
"""
Return set of recursive refs for given env name
>>> local_refs = sorted(recursive_refs([
... {'name': 'base', 'refs': []},
... {'name': 'test', 'refs': ['base']},
... {'name': 'local', 'refs': ['test']},
... ], 'local'))
>>> local_refs == ... | Return set of recursive refs for given env name
>>> local_refs = sorted(recursive_refs([
... {'name': 'base', 'refs': []},
... {'name': 'test', 'refs': ['base']},
... {'name': 'local', 'refs': ['test']},
... ], 'local'))
>>> local_refs == ['base', 'test']
True |
def em_schedule(**kwargs):
"""Run multiple energy minimizations one after each other.
:Keywords:
*integrators*
list of integrators (from 'l-bfgs', 'cg', 'steep')
[['bfgs', 'steep']]
*nsteps*
list of maximum number of steps; one for each integrator in
in t... | Run multiple energy minimizations one after each other.
:Keywords:
*integrators*
list of integrators (from 'l-bfgs', 'cg', 'steep')
[['bfgs', 'steep']]
*nsteps*
list of maximum number of steps; one for each integrator in
in the *integrators* list [[100,1000]]... |
def loads(s, model=None, parser=None):
"""Deserialize s (a str) to a Python object."""
with StringIO(s) as f:
return load(f, model=model, parser=parser) | Deserialize s (a str) to a Python object. |
def offset_mask(mask):
""" Returns a mask shrunk to the 'minimum bounding rectangle' of the
nonzero portion of the previous mask, and its offset from the original.
Useful to find the smallest rectangular section of the image that can be
extracted to include the entire geometry. Conforms to t... | Returns a mask shrunk to the 'minimum bounding rectangle' of the
nonzero portion of the previous mask, and its offset from the original.
Useful to find the smallest rectangular section of the image that can be
extracted to include the entire geometry. Conforms to the y-first
expectations... |
def _get_writable_metadata(self):
"""Get the object / blob metadata which is writable.
This is intended to be used when creating a new object / blob.
See the `API reference docs`_ for more information, the fields
marked as writable are:
* ``acl``
* ``cacheControl``
... | Get the object / blob metadata which is writable.
This is intended to be used when creating a new object / blob.
See the `API reference docs`_ for more information, the fields
marked as writable are:
* ``acl``
* ``cacheControl``
* ``contentDisposition``
* ``con... |
def process_module(self, module):
"""inspect the source file to find encoding problem"""
if module.file_encoding:
encoding = module.file_encoding
else:
encoding = "ascii"
with module.stream() as stream:
for lineno, line in enumerate(stream):
... | inspect the source file to find encoding problem |
def advance_operation_time(self, operation_time):
"""Update the operation time for this session.
:Parameters:
- `operation_time`: The
:data:`~pymongo.client_session.ClientSession.operation_time` from
another `ClientSession` instance.
"""
if not isinstan... | Update the operation time for this session.
:Parameters:
- `operation_time`: The
:data:`~pymongo.client_session.ClientSession.operation_time` from
another `ClientSession` instance. |
def print_experiments(experiments):
"""
Prints job details in a table. Includes urls and mode parameters
"""
headers = ["JOB NAME", "CREATED", "STATUS", "DURATION(s)", "INSTANCE", "DESCRIPTION", "METRICS"]
expt_list = []
for experiment in experiments:
expt_list.append([normalize_job_name... | Prints job details in a table. Includes urls and mode parameters |
def DeleteInstance(self, si, logger, session, vcenter_data_model, vm_uuid, vm_name):
"""
:param logger:
:param CloudShellAPISession session:
:param str vm_name: This is the resource name
:return:
"""
# find vm
vm = self.pv_service.find_by_uuid(si, vm_uuid)... | :param logger:
:param CloudShellAPISession session:
:param str vm_name: This is the resource name
:return: |
def to_json(self):
"""
Returns the JSON representation of the content type.
"""
result = super(ContentType, self).to_json()
result.update({
'name': self.name,
'description': self.description,
'displayField': self.display_field,
'fi... | Returns the JSON representation of the content type. |
def _close(self):
"""Same as `_close` but expects `lock` acquired.
"""
if self._state != "closed":
self.event(DisconnectedEvent(self._dst_addr))
self._set_state("closed")
if self._socket is None:
return
try:
self._socket.shutdown(so... | Same as `_close` but expects `lock` acquired. |
def hash(self):
'''
:rtype: int
:return: hash of the field
'''
hashed = super(Group, self).hash()
return khash(hashed, frozenset(self._values)) | :rtype: int
:return: hash of the field |
def crc(self):
"""
A checksum for the current visual object and its parent mesh.
Returns
----------
crc: int, checksum of data in visual object and its parent mesh
"""
# will make sure everything has been transferred
# to datastore that needs to be before... | A checksum for the current visual object and its parent mesh.
Returns
----------
crc: int, checksum of data in visual object and its parent mesh |
def restore_review_history_for(brain_or_object):
"""Restores the review history for the given brain or object
"""
# Get the review history. Note this comes sorted from oldest to newest
review_history = get_purged_review_history_for(brain_or_object)
obj = api.get_object(brain_or_object)
wf_tool ... | Restores the review history for the given brain or object |
def request(self, method, path, contents, headers, decode_json=False,
stream=False, query=None, cdn=False):
"""
See :py:func:`swiftly.client.client.Client.request`
"""
if cdn:
raise Exception('CDN not yet supported with LocalClient')
if isinstance(cont... | See :py:func:`swiftly.client.client.Client.request` |
def build_model(hparams_set, model_name, data_dir, problem_name, beam_size=1):
"""Build the graph required to fetch the attention weights.
Args:
hparams_set: HParams set to build the model with.
model_name: Name of model.
data_dir: Path to directory containing training data.
problem_name: Name of p... | Build the graph required to fetch the attention weights.
Args:
hparams_set: HParams set to build the model with.
model_name: Name of model.
data_dir: Path to directory containing training data.
problem_name: Name of problem.
beam_size: (Optional) Number of beams to use when decoding a translation... |
def expandService(service_element):
"""Take a service element and expand it into an iterator of:
([type_uri], uri, service_element)
"""
uris = sortedURIs(service_element)
if not uris:
uris = [None]
expanded = []
for uri in uris:
type_uris = getTypeURIs(service_element)
... | Take a service element and expand it into an iterator of:
([type_uri], uri, service_element) |
def filter_iqr(array, lower, upper):
"""
Return elements which falls within specified interquartile range.
Arguments:
array (list): Sequence of numbers.
lower (float): Lower bound for IQR, in range 0 <= lower <= 1.
upper (float): Upper bound for IQR, in range 0 <= upper <= 1.
... | Return elements which falls within specified interquartile range.
Arguments:
array (list): Sequence of numbers.
lower (float): Lower bound for IQR, in range 0 <= lower <= 1.
upper (float): Upper bound for IQR, in range 0 <= upper <= 1.
Returns:
list: Copy of original list, wi... |
def stats(self, start, end, fields=None):
'''Perform a multivariate statistic calculation of this
:class:`ColumnTS` from a *start* date/datetime to an
*end* date/datetime.
:param start: Start date for analysis.
:param end: End date for analysis.
:param fields: Optional subset of :meth:`fields` to perfo... | Perform a multivariate statistic calculation of this
:class:`ColumnTS` from a *start* date/datetime to an
*end* date/datetime.
:param start: Start date for analysis.
:param end: End date for analysis.
:param fields: Optional subset of :meth:`fields` to perform analysis on.
If not provided all fields are in... |
def _make_walker(self, *args, **kwargs):
# type: (*Any, **Any) -> Walker
"""Create a walker instance.
"""
walker = self.walker_class(*args, **kwargs)
return walker | Create a walker instance. |
def check_label(labels, required, value_regex, target_labels):
"""
Check if the label is required and match the regex
:param labels: [str]
:param required: bool (if the presence means pass or not)
:param value_regex: str (using search method)
:param target_labels: [str]
:return: bool (requi... | Check if the label is required and match the regex
:param labels: [str]
:param required: bool (if the presence means pass or not)
:param value_regex: str (using search method)
:param target_labels: [str]
:return: bool (required==True: True if the label is present and match the regex if specified)
... |
def show_vcs_output_virtual_ip_address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_vcs = ET.Element("show_vcs")
config = show_vcs
output = ET.SubElement(show_vcs, "output")
virtual_ip_address = ET.SubElement(output, "virtual-ip-a... | Auto Generated Code |
def path_to_resource(project, path, type=None):
"""Get the resource at path
You only need to specify `type` if `path` does not exist. It can
be either 'file' or 'folder'. If the type is `None` it is assumed
that the resource already exists.
Note that this function uses `Project.get_resource()`,
... | Get the resource at path
You only need to specify `type` if `path` does not exist. It can
be either 'file' or 'folder'. If the type is `None` it is assumed
that the resource already exists.
Note that this function uses `Project.get_resource()`,
`Project.get_file()`, and `Project.get_folder()` me... |
def getmergerequests(self, project_id, page=1, per_page=20, state=None):
"""
Get all the merge requests for a project.
:param project_id: ID of the project to retrieve merge requests for
:param page: Page Number
:param per_page: Records per page
:param state: Passes merg... | Get all the merge requests for a project.
:param project_id: ID of the project to retrieve merge requests for
:param page: Page Number
:param per_page: Records per page
:param state: Passes merge request state to filter them by it
:return: list with all the merge requests |
def connect(db_url=None,
pooling=hgvs.global_config.uta.pooling,
application_name=None,
mode=None,
cache=None):
"""Connect to a uta/ncbi database instance.
:param db_url: URL for database connection
:type db_url: string
:param pooling: whether to use conn... | Connect to a uta/ncbi database instance.
:param db_url: URL for database connection
:type db_url: string
:param pooling: whether to use connection pooling (postgresql only)
:type pooling: bool
:param application_name: log application name in connection (useful for debugging; PostgreSQL only)
:t... |
def crc(self):
"""
A zlib.crc32 or zlib.adler32 checksum
of the current data.
Returns
-----------
crc: int, checksum from zlib.crc32 or zlib.adler32
"""
if self._modified_c or not hasattr(self, '_hashed_crc'):
if self.flags['C_CONTIGUOUS']:
... | A zlib.crc32 or zlib.adler32 checksum
of the current data.
Returns
-----------
crc: int, checksum from zlib.crc32 or zlib.adler32 |
def reset(self, labels=None):
"""Reset specified timer(s).
Parameters
----------
labels : string or list, optional (default None)
Specify the label(s) of the timer(s) to be stopped. If it is
``None``, stop the default timer with label specified by the
``dfl... | Reset specified timer(s).
Parameters
----------
labels : string or list, optional (default None)
Specify the label(s) of the timer(s) to be stopped. If it is
``None``, stop the default timer with label specified by the
``dfltlbl`` parameter of :meth:`__init__`. If ... |
def origin_west_asia(origin):
"""\
Returns if the origin is located in Western Asia.
Holds true for the following countries:
* Armenia
* Azerbaijan
* Bahrain
* Cyprus
* Georgia
* Iraq
* Israel
* Jordan
* Kuwait
* Lebanon
... | \
Returns if the origin is located in Western Asia.
Holds true for the following countries:
* Armenia
* Azerbaijan
* Bahrain
* Cyprus
* Georgia
* Iraq
* Israel
* Jordan
* Kuwait
* Lebanon
* Oman
* Qatar
* Sa... |
def get_file_listing_sha(listing_paths: Iterable) -> str:
"""Return sha256 string for group of FTP listings."""
return sha256(''.join(sorted(listing_paths)).encode('utf-8')).hexdigest() | Return sha256 string for group of FTP listings. |
def init(self):
"""Initialize histograms."""
evclass_shape = [16, 40, 10]
evtype_shape = [16, 16, 40, 10]
evclass_psf_shape = [16, 40, 10, 100]
evtype_psf_shape = [16, 16, 40, 10, 100]
self._hists_eff = dict()
self._hists = dict(evclass_on=np.zeros(evclass_shape... | Initialize histograms. |
def bind_bar(self, sender=None, **kwargs):
"""Binds a navigation bar into this extension instance."""
bar = kwargs.pop('bar')
self.bars[bar.name] = bar | Binds a navigation bar into this extension instance. |
def get_ajax_url(self):
"""Get ajax url"""
if self.ajax_url:
return self.ajax_url
return reverse('trionyx:model-list-ajax', kwargs=self.kwargs) | Get ajax url |
def replace_markdown_cells(src, dst):
"""
Overwrite markdown cells in notebook object `dst` with corresponding
cells in notebook object `src`.
"""
# It is an error to attempt markdown replacement if src and dst
# have different numbers of cells
if len(src['cells']) != len(dst['cells']):
... | Overwrite markdown cells in notebook object `dst` with corresponding
cells in notebook object `src`. |
def drop_scored_calls(self,names):
"""
Take a name or list of scored call names and drop those from the scored calls
Args:
names (list): list of names to drop or a single string name to drop
Returns:
CellDataFrame: The CellDataFrame modified.
"""
... | Take a name or list of scored call names and drop those from the scored calls
Args:
names (list): list of names to drop or a single string name to drop
Returns:
CellDataFrame: The CellDataFrame modified. |
def _G(self, x, p):
"""
analytic solution of the 2d projected mass integral
integral: 2 * pi * x * kappa * dx
:param x:
:param p:
:return:
"""
prefactor = (p + p ** 3) ** -1 * p
if isinstance(x, np.ndarray):
inds0 = np.where(x * p ==... | analytic solution of the 2d projected mass integral
integral: 2 * pi * x * kappa * dx
:param x:
:param p:
:return: |
def with_wrapper(self, wrapper=None, name=None):
""" Copy this BarSet, and return a new BarSet with the specified
name and wrapper.
If no name is given, `{self.name}_custom_wrapper` is used.
If no wrapper is given, the new BarSet will have no wrapper.
"""
name... | Copy this BarSet, and return a new BarSet with the specified
name and wrapper.
If no name is given, `{self.name}_custom_wrapper` is used.
If no wrapper is given, the new BarSet will have no wrapper. |
def guess_locktime(redeem_script):
'''
str -> int
If OP_CLTV is used, guess an appropriate lock_time
Otherwise return 0 (no lock time)
Fails if there's not a constant before OP_CLTV
'''
try:
script_array = redeem_script.split()
loc = script_array.index('OP_CHECKLOCKTIMEVERIFY... | str -> int
If OP_CLTV is used, guess an appropriate lock_time
Otherwise return 0 (no lock time)
Fails if there's not a constant before OP_CLTV |
def _update_states(self,
final_states: RnnStateStorage,
restoration_indices: torch.LongTensor) -> None:
"""
After the RNN has run forward, the states need to be updated.
This method just sets the state to the updated new state, performing
sev... | After the RNN has run forward, the states need to be updated.
This method just sets the state to the updated new state, performing
several pieces of book-keeping along the way - namely, unsorting the
states and ensuring that the states of completely padded sequences are
not updated. Fina... |
def formatted_message(self):
"""Method that will return the formatted message for the event.
This formatting is done with Jinja and the template text is stored in
the ``body`` attribute. The template is supplied the following
variables, as well as the built in Flask ones:
- ``e... | Method that will return the formatted message for the event.
This formatting is done with Jinja and the template text is stored in
the ``body`` attribute. The template is supplied the following
variables, as well as the built in Flask ones:
- ``event``: This is the event instance that ... |
def find_element_by_id(self, id_):
"""Finds an element by id.
:Args:
- id\\_ - The id of the element to be found.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
... | Finds an element by id.
:Args:
- id\\_ - The id of the element to be found.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.find_el... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.