code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|
def add_route(app, fn, context=default_context):
transmute_func = TransmuteFunction(
fn,
args_not_from_request=["request"]
)
handler = create_handler(transmute_func, context=context)
get_swagger_spec(app).add_func(transmute_func, context)
for p in transmute_func.paths:
... | a decorator that adds a transmute route to the application. |
def get_roles_for_permission(permission, brain_or_object):
obj = api.get_object(brain_or_object)
valid_roles = get_valid_roles_for(obj)
for item in obj.ac_inherited_permissions(1):
name, value = item[:2]
if name == permission:
permission = Permission(na... | Return the roles of the permission that is granted on the object
Code extracted from `IRoleManager.rolesOfPermission`
:param permission: The permission to get the roles
:param brain_or_object: Catalog brain or object
:returns: List of roles having the permission |
def remove_move(name):
try:
delattr(_MovedItems, name)
except AttributeError:
try:
del moves.__dict__[name]
except KeyError:
raise AttributeError("no such move, %r" % (name,)) | Remove item from six.moves. |
def from_start_and_end(cls, start, end, aa=None, helix_type=):
start = numpy.array(start)
end = numpy.array(end)
if aa is None:
rise_per_residue = _helix_parameters[helix_type][1]
aa = int((numpy.linalg.norm(end - start) / rise_per_residue) + 1)
instance ... | Creates a `Helix` between `start` and `end`.
Parameters
----------
start : 3D Vector (tuple or list or numpy.array)
The coordinate of the start of the helix primitive.
end : 3D Vector (tuple or list or numpy.array)
The coordinate of the end of the helix primitive... |
def liftover(self, intersecting_region):
if not self.intersects(intersecting_region):
raise RetrotransposonError("trying to lift " + str(intersecting_region) +
" from genomic to transposon coordinates " +
"in " + str(self) + ", but i... | Lift a region that overlaps the genomic occurrence of the retrotransposon
to consensus sequence co-ordinates. This method will behave differently
depending on whether this retrotransposon occurrance contains a full
alignment or not. If it does, the alignment is used to do the liftover and
an exact resul... |
def otu_iter_nexson_proxy(nexson_proxy, otu_sort=None):
nexml_el = nexson_proxy._nexml_el
og_order = nexml_el[]
ogd = nexml_el[]
for og_id in og_order:
og = ogd[og_id]
if otu_sort is None:
for k, v in og:
yield nexson_proxy._create_otu_proxy(k, v)
... | otu_sort can be None (not sorted or stable), True (sorted by ID lexigraphically)
or a key function for a sort function on list of otuIDs
Note that if there are multiple OTU groups, the NexSON specifies the order of sorting
of the groups (so the sort argument here only refers to the sorting of OTUs with... |
def get_cds_ranges_for_transcript(self, transcript_id):
headers = {"content-type": "application/json"}
self.attempt = 0
ext = "/overlap/id/{}?feature=cds".format(transcript_id)
r = self.ensembl_request(ext, headers)
cds_ranges = []
for ... | obtain the sequence for a transcript from ensembl |
def last_available_business_date(self, asset_manager_id, asset_ids, page_no=None, page_size=None):
self.logger.info()
url = % self.endpoint
params = {: [asset_manager_id],
: .join(asset_ids)}
if page_no:
params[] = page_no
if page_size:
... | Returns the last available business date for the assets so we know the
starting date for new data which needs to be downloaded from data providers.
This method can only be invoked by system user |
def _get_pattern_for_schema(self, schema_name, httpStatus):
defaultPattern = if self._is_http_error_rescode(httpStatus) else
model = self._models().get(schema_name)
patterns = self._find_patterns(model)
return patterns[0] if patterns else defaultPattern | returns the pattern specified in a response schema |
def release(self, conn):
self._pool_lock.acquire()
self._pool.put(ConnectionWrapper(self._pool, conn))
self._current_acquired -= 1
self._pool_lock.release() | Release a previously acquired connection.
The connection is put back into the pool. |
def cli(env, volume_id, reason, immediate):
file_storage_manager = SoftLayer.FileStorageManager(env.client)
if not (env.skip_confirmations or formatting.no_going_back(volume_id)):
raise exceptions.CLIAbort()
cancelled = file_storage_manager.cancel_snapshot_space(
volume_id, reason, i... | Cancel existing snapshot space for a given volume. |
def request_add_sensor(self, sock, msg):
self.add_sensor(Sensor(int, % len(self._sensors),
, , params=[-10, 10]))
return Message.reply(, ) | add a sensor |
def fullName(self):
if self.givenName and self.sn:
return "{0} {1}".format(self.givenName, self.sn)
if self.givenName:
return self.givenName
if self.sn:
return self.sn
return self.uid | Returns a reliable full name (firstName lastName) for every
member (as of the writing of this comment.) |
def custom_parser(cards: list, parser: Optional[Callable[[list], Optional[list]]]=None) -> Optional[list]:
if not parser:
return cards
else:
return parser(cards) | parser for CUSTOM [1] issue mode,
please provide your custom parser as argument |
def read(self, size=None):
if not self._is_open:
raise IOError()
if self._current_offset < 0:
raise IOError(
.format(
self._current_offset))
if self._file_data is None or self._current_offset >= self._size:
return b
if size is None:
size = self._si... | Reads a byte string from the file-like object at the current offset.
The function will read a byte string of the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read, where None is all
remaining data.
Returns:
... |
def mode_number(self, rows: List[Row], column: NumberColumn) -> Number:
most_frequent_list = self._get_most_frequent_values(rows, column)
if not most_frequent_list:
return 0.0
most_frequent_value = most_frequent_list[0]
if not isinstance(most_frequent_value, Number... | Takes a list of rows and a column and returns the most frequent value under
that column in those rows. |
def wploader(self):
if self.target_system not in self.wploader_by_sysid:
self.wploader_by_sysid[self.target_system] = mavwp.MAVWPLoader()
return self.wploader_by_sysid[self.target_system] | per-sysid wploader |
def transform_qubits(self: TSelf_Operation,
func: Callable[[Qid], Qid]) -> TSelf_Operation:
return self.with_qubits(*(func(q) for q in self.qubits)) | Returns the same operation, but with different qubits.
Args:
func: The function to use to turn each current qubit into a desired
new qubit.
Returns:
The receiving operation but with qubits transformed by the given
function. |
def make_name(self):
if self.title:
self.name = six.text_type(make_name(self.title_for_name, maxlength=self.__name_length__)) | Autogenerates a :attr:`name` from :attr:`title_for_name` |
def coerce_to_target_dtype(self, other):
dtype, _ = infer_dtype_from(other, pandas_dtype=True)
if is_dtype_equal(self.dtype, dtype):
return self
if self.is_bool or is_object_dtype(dtype) or is_bool_dtype(dtype):
return self
elif ... | coerce the current block to a dtype compat for other
we will return a block, possibly object, and not raise
we can also safely try to coerce to the same dtype
and will receive the same block |
def LinearContrast(alpha=1, per_channel=False, name=None, deterministic=False, random_state=None):
params1d = [
iap.handle_continuous_param(alpha, "alpha", value_range=None, tuple_to_uniform=True, list_to_choice=True)
]
func = adjust_contrast_linear
return _ContrastFuncWrapper(
func... | Adjust contrast by scaling each pixel value to ``127 + alpha*(I_ij-127)``.
dtype support::
See :func:`imgaug.augmenters.contrast.adjust_contrast_linear`.
Parameters
----------
alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
Multip... |
def declare_list(self, name, sep=os.pathsep):
self._declare_special(name, sep, ListVariable) | Declare an environment variable as a list-like special variable.
This can be used even if the environment variable is not
present.
:param name: The name of the environment variable that should
be considered list-like.
:param sep: The separator to be used. Defaults ... |
def _restore_stdout(self):
if self.buffer:
if self._mirror_output:
output = sys.stdout.getvalue()
error = sys.stderr.getvalue()
if output:
if not output.endswith():
output +=
sel... | Unhook stdout and stderr if buffering is enabled. |
def prompt_save_images(args):
if args[] or args[]:
return
if (args[] or args[]) and (args[] or args[]):
save_msg = (
)
try:
save_images = utils.confirm_input(input(save_msg))
except (KeyboardInterrupt, EOFError):
return
a... | Prompt user to save images when crawling (for pdf and HTML formats). |
def IV(abf,T1,T2,plotToo=True,color=):
rangeData=abf.average_data([[T1,T2]])
AV,SD=rangeData[:,0,0],rangeData[:,0,1]
Xs=abf.clampValues(T1)
if plotToo:
new(abf)
pylab.margins(.1,.1)
annotate(abf)
return AV,SD | Given two time points (seconds) return IV data.
Optionally plots a fancy graph (with errorbars)
Returns [[AV],[SD]] for the given range. |
def show_worst_drawdown_periods(returns, top=5):
drawdown_df = timeseries.gen_drawdown_table(returns, top=top)
utils.print_table(
drawdown_df.sort_values(, ascending=False),
name=,
float_format=.format,
) | Prints information about the worst drawdown periods.
Prints peak dates, valley dates, recovery dates, and net
drawdowns.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
top : int, o... |
def DeleteAttachment(self, attachment_link, options=None):
if options is None:
options = {}
path = base.GetPathFromLink(attachment_link)
attachment_id = base.GetResourceIdOrFullNameFromLink(attachment_link)
return self.DeleteResource(path,
... | Deletes an attachment.
:param str attachment_link:
The link to the attachment.
:param dict options:
The request options for the request.
:return:
The deleted Attachment.
:rtype:
dict |
def read_index_iter(self):
with fopen(self.vpk_path, ) as f:
f.seek(self.header_length)
while True:
if self.version > 0 and f.tell() > self.tree_length + self.header_length:
raise ValueError("Error parsing index (out of bounds)")
... | Generator function that reads the file index from the vpk file
yeilds (file_path, metadata) |
def load_from_namespace(module_name):
class_inst = None
name = "py3status.modules.{}".format(module_name)
py_mod = __import__(name)
components = name.split(".")
for comp in components[1:]:
py_mod = getattr(py_mod, comp)
class_inst = py_mod.Py3status()... | Load a py3status bundled module. |
def _add_loss_summaries(total_loss):
loss_averages = tf.train.ExponentialMovingAverage(0.9, name=)
losses = tf.get_collection()
loss_averages_op = loss_averages.apply(losses + [total_loss])
for l in losses + [total_loss]:
tf.summary.scalar(l.op.name + , l)
tf.summary.scalar(l.op.n... | Add summaries for losses in CIFAR-10 model.
Generates moving average for all losses and associated summaries for
visualizing the performance of the network.
Args:
total_loss: Total loss from loss().
Returns:
loss_averages_op: op for generating moving averages of losses. |
def _download_libraries(self, libname):
self._logger.info("Downloading and generating Enrichr library gene sets......")
s = retry(5)
ENRICHR_URL =
query_string =
response = s.get( ENRICHR_URL + query_string % libname, timeout=None)
if not resp... | download enrichr libraries. |
def _set_config(c):
gl_attribs = [glcanvas.WX_GL_RGBA,
glcanvas.WX_GL_DEPTH_SIZE, c[],
glcanvas.WX_GL_STENCIL_SIZE, c[],
glcanvas.WX_GL_MIN_RED, c[],
glcanvas.WX_GL_MIN_GREEN, c[],
glcanvas.WX_GL_MIN_BLUE, c[],
... | Set gl configuration |
def error(self):
status_code, error_msg, payload = self.check_error()
if status_code != 200 and not error_msg and not payload:
return "Async error (%s). Status code: %r" % (self.async_id, status_code)
return error_msg | Check if the async response is an error.
Take care to call `is_done` before calling `error`. Note that the error
messages are always encoded as strings.
:raises CloudUnhandledError: When not checking `is_done` first
:return: the error value/payload, if found.
:rtype: str |
def fluxfrac(*mags):
Ftot = 0
for mag in mags:
Ftot += 10**(-0.4*mag)
F1 = 10**(-0.4*mags[0])
return F1/Ftot | Returns fraction of total flux in first argument, assuming all are magnitudes. |
def GetUserInfo(knowledge_base, user):
if "\\" in user:
domain, user = user.split("\\", 1)
users = [
u for u in knowledge_base.users
if u.username == user and u.userdomain == domain
]
else:
users = [u for u in knowledge_base.users if u.username == user]
if not us... | Get a User protobuf for a specific user.
Args:
knowledge_base: An rdf_client.KnowledgeBase object.
user: Username as string. May contain domain like DOMAIN\\user.
Returns:
A User rdfvalue or None |
def __geomToPointList(self, geom):
if arcpyFound and isinstance(geom, arcpy.Multipoint):
feature_geom = []
fPart = []
for part in geom:
fPart = []
for pnt in part:
fPart.append(Point(coord=[pnt.X, pnt.Y],
... | converts a geometry object to a common.Geometry object |
def get_hash(self):
if self._hash is None:
self._hash = self._source.get_hash(self._handle).strip()
return self._hash | Returns the associated hash for this template version
Returns:
str: Hash for this version |
def RGB_color_picker(obj):
digest = hashlib.sha384(str(obj).encode()).hexdigest()
subsize = int(len(digest) / 3)
splitted_digest = [digest[i * subsize: (i + 1) * subsize]
for i in range(3)]
max_value = float(int("f" * subsize, 16))
compone... | Build a color representation from the string representation of an object
This allows to quickly get a color from some data, with the
additional benefit that the color will be the same as long as the
(string representation of the) data is the same::
>>> from colour import RGB_color_picker, Color
... |
def build_dependencies(self):
for m in self.modules:
m.build_dependencies()
for p in self.packages:
p.build_dependencies() | Recursively build the dependencies for sub-modules and sub-packages.
Iterate on node's modules then packages and call their
build_dependencies methods. |
def __setup():
global __collaborators, __flag_first
import f311
__flag_first = False
for pkgname in f311.COLLABORATORS_C:
try:
pkg = importlib.import_module(pkgname)
a99.get_python_logger().info("Imported collaborator package ".format(pkgname))
try:
... | Will be executed in the first time someone calls classes_*() |
def createPolyline(self, points, strokewidth=1, stroke=):
style_dict = {:, :strokewidth, :stroke}
myStyle = StyleBuilder(style_dict)
p = Polyline(points=points)
p.set_style(myStyle.getStyle())
return p | Creates a Polyline
@type points: string in the form "x1,y1 x2,y2 x3,y3"
@param points: all points relevant to the polygon
@type strokewidth: string or int
@param strokewidth: width of the pen used to draw
@type stroke: string (either css constants like "black" or numerical v... |
def remove_programmer(programmer_id):
log.debug(, programmer_id)
lines = programmers_txt().lines()
lines = filter(
lambda x: not x.strip().startswith(programmer_id + ), lines)
programmers_txt().write_lines(lines) | remove programmer.
:param programmer_id: programmer id (e.g. 'avrisp')
:rtype: None |
def logistic_regression(X, y, coef_only=False, alpha=0.05,
as_dataframe=True, remove_na=False, **kwargs):
from pingouin.utils import _is_sklearn_installed
_is_sklearn_installed(raise_error=True)
from sklearn.linear_model import LogisticRegression
if isinstance(X, ... | (Multiple) Binary logistic regression.
Parameters
----------
X : np.array or list
Predictor(s). Shape = (n_samples, n_features) or (n_samples,).
y : np.array or list
Dependent variable. Shape = (n_samples).
Must be binary.
coef_only : bool
If True, return only the re... |
def _generate_iam_invoke_role_policy(self):
invoke_pol = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Resource": ["*"],
"Action": ["lambda:InvokeFunction"]
}
... | Generate the policy for the IAM role used by API Gateway to invoke
the lambda function.
Terraform name: aws_iam_role.invoke_role |
def _dusty_hosts_config(hosts_specs):
rules = .join([.format(spec[], spec[]) for spec in hosts_specs])
return config_file.create_config_section(rules) | Return a string of all host rules required to match
the given spec. This string is wrapped in the Dusty hosts
header and footer so it can be easily removed later. |
def modify_schema(self, field_schema):
field_schema[] = self.maximum_value
if self.exclusive:
field_schema[] = True | Modify field schema. |
def normalize_url(url):
if not url or len(url) == 0:
return
if not url.startswith():
url = + url
if len(url) > 1 and url.endswith():
url = url[0:len(url) - 1]
return url | Return a normalized url with trailing and without leading slash.
>>> normalize_url(None)
'/'
>>> normalize_url('/')
'/'
>>> normalize_url('/foo/bar')
'/foo/bar'
>>> normalize_url('foo/bar')
'/foo/bar'
>>> normalize_url('/foo/bar/')
'/foo/bar' |
def visualize(G, settings, filename="dependencies", no_graphviz=False):
error = settings["error"]
if no_graphviz:
write_dot_file(G, filename)
return 0
write_dot_file(G, "tempdot")
renderer = "svg"
if re.search("\.jpg$", filename, re.IGNORECASE):
renderer = "jpg"
elif... | Uses networkX to draw a graphviz dot file either (a) calls the
graphviz command "dot" to turn it into a SVG and remove the
dotfile (default), or (b) if no_graphviz is True, just output
the graphviz dot file
Args:
a NetworkX DiGraph
the settings dictionary
a filename (a default i... |
def check_row(state, index, missing_msg=None, expand_msg=None):
if missing_msg is None:
missing_msg = "The system wants to verify row {{index + 1}} of your query result, but couldnre trying to fetch the row at index {}".format(
n_sol, index
)
)
if index >= n_st... | Zoom in on a particular row in the query result, by index.
After zooming in on a row, which is represented as a single-row query result,
you can use ``has_equal_value()`` to verify whether all columns in the zoomed in solution
query result have a match in the student query result.
Args:
index:... |
def replace(self, **kwargs):
return SlashSeparatedCourseKey(
kwargs.pop(, self.org),
kwargs.pop(, self.course),
kwargs.pop(, self.run),
**kwargs
) | Return: a new :class:`SlashSeparatedCourseKey` with specific ``kwargs`` replacing
their corresponding values.
Using CourseLocator's replace function results in a mismatch of __init__ args and kwargs.
Replace tries to instantiate a SlashSeparatedCourseKey object with CourseLocator args a... |
def dtype(self):
try:
return self.data.dtype
except AttributeError:
return numpy.dtype( % (self._sample_type, self._sample_bytes)) | Pixel data type. |
def reverse(view, *args, **kwargs):
s `reverse`
as `args` and `kwargs` arguments, respectively.
The special optional keyword argument `query` is a dictionary of query (or GET) parameters
that can be appended to the `reverse`d URL.
Example:
reverse(, categoryId = 5, query = {: 2})
is equivalent to
django.... | User-friendly reverse. Pass arguments and keyword arguments to Django's `reverse`
as `args` and `kwargs` arguments, respectively.
The special optional keyword argument `query` is a dictionary of query (or GET) parameters
that can be appended to the `reverse`d URL.
Example:
reverse('products:category', category... |
def hacking_assert_equal(logical_line, noqa):
r
if noqa:
return
methods = [, ]
for method in methods:
start = logical_line.find( % method) + 1
if start != 0:
break
else:
return
comparisons = [ast.Eq, ast.NotEq]
checker = AssertTrueFalseChecker(met... | r"""Check that self.assertEqual and self.assertNotEqual are used.
Okay: self.assertEqual(x, y)
Okay: self.assertNotEqual(x, y)
H204: self.assertTrue(x == y)
H204: self.assertTrue(x != y)
H204: self.assertFalse(x == y)
H204: self.assertFalse(x != y) |
def delete_feed(self, pid):
logger.info("delete_feed(pid=\"%s\") [lid=%s]", pid, self.__lid)
return self.__delete_point(R_FEED, pid) | Delete a feed, identified by its local id.
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing the error if the infrastructure detects a problem
Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
if there is a... |
def send(self, url, data, headers):
eventlet.spawn(self._send_payload, (url, data, headers)) | Spawn an async request to a remote webserver. |
def team(self, name=None, id=None, is_hidden=False, **kwargs):
_teams = self.teams(name=name, id=id, **kwargs)
if len(_teams) == 0:
raise NotFoundError("No team criteria matches")
if len(_teams) != 1:
raise MultipleFoundError("Multiple teams fit criteria")
... | Team of KE-chain.
Provides a team of :class:`Team` of KE-chain. You can filter on team name or provide id.
:param name: (optional) team name to filter
:type name: basestring or None
:param id: (optional) id of the user to filter
:type id: basestring or None
:param is_hi... |
def _extend(self, newsub):
current = self
while hasattr(current, ):
current = current._sub
_set(current, , newsub)
try:
object.__delattr__(self, )
except:
pass | Append a subclass (extension) after the base class. For parser internal use. |
def subclass(self, klass):
return bool(lib.EnvSubclassP(self._env, self._cls, klass._cls)) | True if the Class is a subclass of the given one. |
def put(self, item, *args, **kwargs):
if not self.enabled:
return
timeout = kwargs.pop(, None)
if timeout is None:
timeout = self.default_timeout
cache_key = self.make_key(args, kwargs)
with self._cache_lock:
self._ca... | Put an item into the cache, for this combination of args and kwargs.
Args:
*args: any arguments.
**kwargs: any keyword arguments. If ``timeout`` is specified as one
of the keyword arguments, the item will remain available
for retrieval for ``timeout`` s... |
def add_arguments(self, parser):
parser.add_argument(
,
action=,
default=False,
help="Output what wet actually do it."
)
parser.add_argument(
, ,
default=None,
help=u"Restrict cleanup to tasks matching t... | Add arguments to the command parser.
Uses argparse syntax. See documentation at
https://docs.python.org/3/library/argparse.html. |
def render_mail_template(subject_template, body_template, context):
try:
subject = strip_spaces(render_to_string(subject_template, context))
body = render_to_string(body_template, context)
finally:
pass
return subject, body | Renders both the subject and body templates in the given context.
Returns a tuple (subject, body) of the result. |
def use_strategy(new_strategy):
def wrapped_class(klass):
klass._meta.strategy = new_strategy
return klass
return wrapped_class | Force the use of a different strategy.
This is an alternative to setting default_strategy in the class definition. |
def cart_create(self, items, **kwargs):
if isinstance(items, dict):
items = [items]
if len(items) > 10:
raise CartException("You canItem.{0}.OfferListingIdItem.{0}.Quantityoffer_idquantity']
response = self.api.CartCreate(**kwargs)
root = objectify.fro... | CartCreate.
:param items:
A dictionary containing the items to be added to the cart.
Or a list containing these dictionaries.
It is not possible to create an empty cart!
example: [{'offer_id': 'rt2ofih3f389nwiuhf8934z87o3f4h',
'quantity': 1}]
... |
def mel_to_hz(mels, htk=False):
mels = np.asanyarray(mels)
if htk:
return 700.0 * (10.0**(mels / 2595.0) - 1.0)
f_min = 0.0
f_sp = 200.0 / 3
freqs = f_min + f_sp * mels
min_log_hz = 1000.0
min_log_mel = (min_log_hz - f_min) / f_sp
lo... | Convert mel bin numbers to frequencies
Examples
--------
>>> librosa.mel_to_hz(3)
200.
>>> librosa.mel_to_hz([1,2,3,4,5])
array([ 66.667, 133.333, 200. , 266.667, 333.333])
Parameters
----------
mels : np.ndarray [shape=(n,)], float
mel bins to convert
... |
def prepare_data(self):
result = {}
for field in self.fields:
data = self.data.get(field.name)
result[field.name] = field.prepare_data(data)
return result | Prepare widget data for template. |
def compute_ssm(X, metric="seuclidean"):
D = distance.pdist(X, metric=metric)
D = distance.squareform(D)
D /= D.max()
return 1 - D | Computes the self-similarity matrix of X. |
def id_request(self, device_id):
self.logger.info("\nid_request for device %s", device_id)
device_id = device_id.upper()
self.direct_command(device_id, , )
sleep(2)
status = self.get_buffer_status(device_id)
if not status:
sleep(1)
stat... | Get the device for the ID. ID request can return device type (cat/subcat),
firmware ver, etc. Cat is status['is_high'], sub cat is status['id_mid'] |
def on_send(self, frame):
if frame.cmd == CMD_CONNECT or frame.cmd == CMD_STOMP:
if self.heartbeats != (0, 0):
frame.headers[HDR_HEARTBEAT] = % self.heartbeats
if self.next_outbound_heartbeat is not None:
self.next_outbound_heartbeat = monotonic() + self... | Add the heartbeat header to the frame when connecting, and bump
next outbound heartbeat timestamp.
:param Frame frame: the Frame object |
def create_udf_node(name, fields):
definition = next(_udf_name_cache[name])
external_name = .format(name, definition)
return type(external_name, (BigQueryUDFNode,), fields) | Create a new UDF node type.
Parameters
----------
name : str
Then name of the UDF node
fields : OrderedDict
Mapping of class member name to definition
Returns
-------
result : type
A new BigQueryUDFNode subclass |
def visit_Module(self, node):
deps = sorted(self.dependencies)
headers = [Include(os.path.join("pythonic", "include", *t) + ".hpp")
for t in deps]
headers += [Include(os.path.join("pythonic", *t) + ".hpp")
for t in deps]
decls_n_... | Build a compilation unit. |
def adjust_internal_tacking_values(self,
min_non_zero_index,
max_index,
total_added):
if max_index >= 0:
max_value = self.get_highest_equivalent_value(self.get_value_from_ind... | Called during decoding and add to adjust the new min/max value and
total count
Args:
min_non_zero_index min nonzero index of all added counts (-1 if none)
max_index max index of all added counts (-1 if none) |
def has_method(obj, name):
if obj == None:
raise Exception("Object cannot be null")
if name == None:
raise Exception("Method name cannot be null")
name = name.lower()
for method_name in dir(obj):
if method_name.lower() != name:
... | Checks if object has a method with specified name.
:param obj: an object to introspect.
:param name: a name of the method to check.
:return: true if the object has the method and false if it doesn't. |
def copy(self, deep=True):
data = self._data.copy(deep=deep)
return self._constructor(data).__finalize__(self) | Make a copy of this object's indices and data.
When ``deep=True`` (default), a new object will be created with a
copy of the calling object's data and indices. Modifications to
the data or indices of the copy will not be reflected in the
original object (see notes below).
When ... |
def Shell(device, *command):
if command:
return device.StreamingShell(.join(command))
else:
terminal_prompt = device.InteractiveShell()
print(terminal_prompt.decode())
while True:
cmd = input()
if not cmd:
continue
... | Runs a command on the device and prints the stdout.
Args:
command: Command to run on the target. |
def iterate_sequences(
consumer_fn, output_template, sequences, length, chunk_length=None,
batch_size=None, num_epochs=1, padding_value=0):
if not length.shape[0].value:
raise ValueError()
num_sequences = length.shape[0].value
sequences = dict(sequence=sequences, length=length)
dataset = tf.data.... | Iterate over batches of chunks of sequences for multiple epochs.
The batch dimension of the length tensor must be set because it is used to
infer buffer sizes.
Args:
consumer_fn: Function creating the operation to process the data.
output_template: Nested tensors of same shape and dtype as outputs.
... |
def applyIndex(self, lst, right):
if len(right) != 1:
raise exceptions.EvaluationError( % (self.left, self.right))
right = right[0]
if isinstance(right, int):
return lst[right]
raise exceptions.EvaluationError("Can't apply %r to argument (%r): integer expected, got %r" % (self.left, s... | Apply a list to something else. |
def print_user(user):
email = user[]
domain = user[][]
role = user[]
print(
.format(domain, email, role)) | Prints information about the current user. |
def list_vms(self, allow_clone=False):
vbox_vms = []
result = yield from self.execute("list", ["vms"])
for line in result:
if len(line) == 0 or line[0] != or line[-1:] != "}":
continue
vmname, _ = line.rsplit(, 1)
vmname = vmname.s... | Gets VirtualBox VM list. |
def getReflexRuleSetup(self):
relations = {}
pc = getToolByName(self, )
methods = [obj.getObject() for obj in pc(
portal_type=,
is_active=True)]
bsc = getToolByName(self, )
for method in methods:
a... | Return a json dict with all the setup data necessary to build the
relations:
- Relations between methods and analysis services options.
- The current saved data
the functions returns:
{'<method_uid>': {
'analysisservices': {
'<as_uid>': {'as_id': '<as_... |
def affine_respective_zoom_matrix(w_range=0.8, h_range=1.1):
if isinstance(h_range, (float, int)):
zy = h_range
elif isinstance(h_range, tuple):
zy = np.random.uniform(h_range[0], h_range[1])
else:
raise Exception("h_range: float or tuple of 2 floats")
if isinstance(w_rang... | Get affine transform matrix for zooming/scaling that height and width are changed independently.
OpenCV format, x is width.
Parameters
-----------
w_range : float or tuple of 2 floats
The zooming/scaling ratio of width, greater than 1 means larger.
- float, a fixed ratio.
... |
def parent_suite(self):
if self.context and self.context.parent_suite_path:
return Suite.load(self.context.parent_suite_path)
return None | Get the current parent suite.
A parent suite exists when a context within a suite is active. That is,
during execution of a tool within a suite, or after a user has entered
an interactive shell in a suite context, for example via the command-
line syntax 'tool +i', where 'tool' is an al... |
def blt(f: List[SYM], x: List[SYM]) -> Dict[str, Any]:
J = ca.jacobian(f, x)
nblock, rowperm, colperm, rowblock, colblock, coarserow, coarsecol = J.sparsity().btf()
return {
: J,
: nblock,
: rowperm,
: colperm,
: rowblock,
: colblock,
: coarserow,... | Sort equations by dependence |
def get(self, instance, **kw):
try:
return self._get(instance, **kw)
except AttributeError:
logger.error("Could not get the value of the computed field "
.format(self.get_field_name()))
return None | Get the value of the field |
def validate_request(self, path, action, body=None, query=None):
path_name, path_spec = self.get_path_spec(path)
if path_spec is None:
logging.warn("there is no path")
return False
if action not in path_spec.keys():
logging.warn("this http metho... | Check if the given request is valid.
Validates the body and the query
# Rules to validate the BODY:
# Let's limit this to mime types that either contain 'text' or 'json'
# 1. if body is None, there must not be any required parameters in
# the given schema
... |
def _find_rule_no(self, mac):
ipt_cmd = [, , ]
cmdo = dsl.execute(ipt_cmd, self._root_helper, log_output=False)
for o in cmdo.split():
if mac in o.lower():
rule_no = o.split()[0]
LOG.info(,
{: rule_no, : mac})
... | Find rule number associated with a given mac. |
def modelsClearAll(self):
self._logger.info(,
self.modelsTableName)
with ConnectionFactory.get() as conn:
query = % (self.modelsTableName)
conn.cursor.execute(query) | Delete all models from the models table
Parameters:
---------------------------------------------------------------- |
def source(self, format=, accessible=False):
if accessible:
return self.http.get().value
return self.http.get(+format).value | Args:
format (str): only 'xml' and 'json' source types are supported
accessible (bool): when set to true, format is always 'json' |
def _init_metadata(self):
super(LabelOrthoFacesAnswerFormRecord, self)._init_metadata()
self._face_values_metadata = {
: Id(self.my_osid_object_form._authority,
self.my_osid_object_form._namespace,
),
: ,
... | stub |
def enable_apt_repositories(prefix, url, version, repositories):
with settings(hide(, , ),
warn_only=False, capture=True):
sudo( % (prefix,
url,
version,
... | adds an apt repository |
def plotres(psr,deleted=False,group=None,**kwargs):
res, t, errs = psr.residuals(), psr.toas(), psr.toaerrs
if (not deleted) and N.any(psr.deleted != 0):
res, t, errs = res[psr.deleted == 0], t[psr.deleted == 0], errs[psr.deleted == 0]
print("Plotting {0}/{1} nondeleted points.".forma... | Plot residuals, compute unweighted rms residual. |
def has_activity(graph: BELGraph, node: BaseEntity) -> bool:
return _node_has_modifier(graph, node, ACTIVITY) | Return true if over any of the node's edges, it has a molecular activity. |
def thread( mafs, species ):
for m in mafs:
new_maf = deepcopy( m )
new_components = get_components_for_species( new_maf, species )
if new_components:
remove_all_gap_columns( new_components )
new_maf.components = new_components
new_maf.sco... | Restrict an list of alignments to a given list of species by:
1) Removing components for any other species
2) Remove any columns containing all gaps
Example:
>>> import bx.align.maf
>>> block1 = bx.align.maf.from_string( '''
... a score=4964.0
... s hg18.ch... |
def get_component_tasks(self, component_id):
ret = []
for task_id, comp_id in self.task_to_component_map.items():
if comp_id == component_id:
ret.append(task_id)
return ret | Returns the task ids allocated for the given component id |
def check_stop_times(
feed: "Feed", *, as_df: bool = False, include_warnings: bool = False
) -> List:
table = "stop_times"
problems = []
if feed.stop_times is None:
problems.append(["error", "Missing table", table, []])
else:
f = feed.stop_times.copy().sort_values(["trip_i... | Analog of :func:`check_agency` for ``feed.stop_times``. |
def route(self, path=None, method=, callback=None, name=None,
apply=None, skip=None, **config):
if callable(path): path, callback = None, path
plugins = makelist(apply)
skiplist = makelist(skip)
if in config:
depr("The parameter was renamed to ")
... | A decorator to bind a function to a request URL. Example::
@app.route('/hello/:name')
def hello(name):
return 'Hello %s' % name
The ``:name`` part is a wildcard. See :class:`Router` for syntax
details.
:param path: Request path o... |
def _get_image(self, name):
document = self._control.document()
image = document.resource(QtGui.QTextDocument.ImageResource,
QtCore.QUrl(name))
return image | Returns the QImage stored as the ImageResource with 'name'. |
def retrieve_metar(station_icao) -> typing.Tuple[typing.Optional[str], typing.Optional[str]]:
url = _BASE_METAR_URL.format(station=station_icao)
with requests.get(url) as resp:
if not resp.ok:
return f \
f \
f, None
return None, resp.content... | Retrieves a METAR string from an online database
Args:
station_icao: ICAO of the station
Returns:
tuple of error, metar_str |
def _add_command(self, name, **parameters):
command = self._create_command(name, **parameters)
self._commands.append(command)
return command | Add a new command to the blueprint.
:param name: The command name
:type name: str
:param parameters: The command parameters
:type parameters: dict
:rtype: Fluent |
def browser(i):
r=find({:,
:})
if r[]>0:
if r[]!=16: return r
out(t find wfe module)!Please, install it via "ck pull repo:ck-web" and try again!returntemplaterepo_uoamodule_uoadata_uoa::actionstartmodule_uoawebbrowseryestemplatecidextra_urlextra_url')}) | Input: {
(template) - use this web template
(repo_uoa) -
(module_uoa) -
(data_uoa) - view a given entry
(extra_url) - extra URL
}
Output: {
return - return code = 0, if successful
... |
def read_file(filename):
infile = open(filename, )
lines = infile.readlines()
infile.close()
return lines | Read contents of the specified file.
Parameters:
-----------
filename : str
The name of the file to be read
Returns:
lines : list of str
The contents of the file, split by line |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.