Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
3,400 | def get_distributions(cls, ctx, extra_dist_dirs=[]):
if extra_dist_dirs:
raise BuildInterruptingException(
)
dist_dir = ctx.dist_dir
folders = glob.glob(join(dist_dir, ))
for dir in extra_dist_dirs:
folders.extend(glob.glo... | Returns all the distributions found locally. |
3,401 | def thaw_parameter(self, name):
i = self.get_parameter_names(include_frozen=True).index(name)
self.unfrozen_mask[i] = True | Thaw a parameter by name
Args:
name: The name of the parameter |
3,402 | def send_with_media(
self,
*,
text: str,
files: List[str],
captions: List[str]=[],
) -> List[OutputRecord]:
try:
self.ldebug(f"Uploading files {files}.")
if captions is None:
captions = []
... | Upload media to mastodon,
and send status and media,
and captions if present.
:param text: post text.
:param files: list of files to upload with post.
:param captions: list of captions to include as alt-text with files.
:returns: list of output records,
each ... |
3,403 | def index_config(request):
if _permission_denied_check(request):
return HttpResponseForbidden(, content_type=)
content_list = getattr(settings, , [])
if not content_list:
for cls in six.itervalues(DigitalObject.defined_types):
content_group = [m... | This view returns the index configuration of the current
application as JSON. Currently, this consists of a Solr index url
and the Fedora content models that this application expects to index.
.. Note::
By default, Fedora system content models (such as
``fedora-system:ContentModel-3.0``) ar... |
3,404 | def _engineServicesRunning():
process = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE)
stdout = process.communicate()[0]
result = process.returncode
if result != 0:
raise RuntimeError("Unable to check for running client job manager")
running = False
for line in stdout.split("\n"):
i... | Return true if the engine services are running |
3,405 | def parse_parameters_from_response(self, response):
lines = response.splitlines()
pairs = [line.strip().split(, 1) for line in lines if in line]
pairs = sorted(pairs)
signature = ([unquote(v) for k, v in pairs if k == ] or [None])[0]
query_string = . join([k +... | Returns a response signature and query string generated from the
server response. 'h' aka signature argument is stripped from the
returned query string. |
3,406 | def TermsProcessor(instance, placeholder, rendered_content, original_context):
if in original_context:
return rendered_content
return mark_safe(replace_terms(rendered_content)) | Adds links all placeholders plugins except django-terms plugins |
3,407 | def spans_columns(self, column_names):
columns = self.get_columns()
number_of_columns = len(columns)
same_columns = True
for i in range(number_of_columns):
column = self._trim_quotes(columns[i].lower())
if i >= len(column_names) or column != self._trim_q... | Checks if this index exactly spans the given column names in the correct order.
:type column_names: list
:rtype: bool |
3,408 | def wait_until_running(self, callback=None):
status = self.machine.scheduler.wait_until_running(
self.job, self.worker_config.time_out)
if status.running:
self.online = True
if callback:
callback(self)
else:
raise Time... | Waits until the remote worker is running, then calls the callback.
Usually, this method is passed to a different thread; the callback
is then a function patching results through to the result queue. |
3,409 | def set_zone(time_zone):
*
if time_zone not in list_zones():
raise SaltInvocationError(.format(time_zone))
salt.utils.mac_utils.execute_return_success(
.format(time_zone))
return time_zone in get_zone() | Set the local time zone. Use ``timezone.list_zones`` to list valid time_zone
arguments
:param str time_zone: The time zone to apply
:return: True if successful, False if not
:rtype: bool
:raises: SaltInvocationError on Invalid Timezone
:raises: CommandExecutionError on failure
CLI Exampl... |
3,410 | def remove(self):
if not self.can_remove():
raise AttributeError()
data = self.data
self.parents.remove(self)
self.delete()
return data | Removes the node from the graph. Note this does not remove the
associated data object. See :func:`Node.can_remove` for limitations
on what can be deleted.
:returns:
:class:`BaseNodeData` subclass associated with the deleted Node
:raises AttributeError:
if call... |
3,411 | def _sim_trajectories(self, time_size, start_pos, rs,
total_emission=False, save_pos=False, radial=False,
wrap_func=wrap_periodic):
time_size = int(time_size)
num_particles = self.num_particles
if total_emission:
em = np.ze... | Simulate (in-memory) `time_size` steps of trajectories.
Simulate Brownian motion diffusion and emission of all the particles.
Uses the attributes: num_particles, sigma_1d, box, psf.
Arguments:
time_size (int): number of time steps to be simulated.
start_pos (array): sha... |
3,412 | def fetch(dataset_uri, item_identifier):
dataset = dtoolcore.DataSet.from_uri(dataset_uri)
click.secho(dataset.item_content_abspath(item_identifier)) | Return abspath to file with item content.
Fetches the file from remote storage if required. |
3,413 | def parse_record( self, lines ):
temp_lines = []
for line in lines:
fields = line.rstrip( "\r\n" ).split( None, 1 )
if len( fields ) == 1:
fields.append( "" )
temp_lines.append( fields )
lines = temp_lines
mot... | Parse a TRANSFAC record out of `lines` and return a motif. |
3,414 | def _weighting(weights, exponent):
if np.isscalar(weights):
weighting = NumpyTensorSpaceConstWeighting(weights, exponent)
elif weights is None:
weighting = NumpyTensorSpaceConstWeighting(1.0, exponent)
else:
arr = np.asarray(weights)
weighting = NumpyTensorSpaceArrayWe... | Return a weighting whose type is inferred from the arguments. |
3,415 | def rec_new(self, zone, record_type, name, content, ttl=1, priority=None, service=None, service_name=None,
protocol=None, weight=None, port=None, target=None):
params = {
: ,
: zone,
: record_type,
: name,
: content,
... | Create a DNS record for the given zone
:param zone: domain name
:type zone: str
:param record_type: Type of DNS record. Valid values are [A/CNAME/MX/TXT/SPF/AAAA/NS/SRV/LOC]
:type record_type: str
:param name: name of the DNS record
:type name: str
:param content:... |
3,416 | def set_unit_desired_state(self, unit, desired_state):
if desired_state not in self._STATES:
raise ValueError(.format(
self._STATES
))
})
return self.get_unit(unit) | Update the desired state of a unit running in the cluster
Args:
unit (str, Unit): The Unit, or name of the unit to update
desired_state: State the user wishes the Unit to be in
("inactive", "loaded", or "launched")
Returns:
Unit: The unit t... |
3,417 | def parse_ts(ts):
dt = maya.parse(ts.strip())
return dt.datetime(naive=True) | parse timestamp.
:param ts: timestamp in ISO8601 format
:return: tbd!!! |
3,418 | def _conditional_toward_zero(method, sign):
return method is RoundingMethods.ROUND_HALF_ZERO or \
(method is RoundingMethods.ROUND_HALF_DOWN and sign == 1) or \
(method is RoundingMethods.ROUND_HALF_UP and sign == -1) | Whether to round toward zero.
:param method: rounding method
:type method: element of RoundingMethods.METHODS()
:param int sign: -1, 0, or 1 as appropriate
Complexity: O(1) |
3,419 | def _social_auth_login(self, request, **kwargs):
if request.user.is_authenticated():
if not request.user.is_active or not request.user.is_staff:
raise PermissionDenied()
else:
messages.add_message(request, messages.WARNING, )
return redirect_to_login(request.get_full_pat... | View function that redirects to social auth login,
in case the user is not logged in. |
3,420 | def files_mkdir(self, path, parents=False, **kwargs):
kwargs.setdefault("opts", {"parents": parents})
args = (path,)
return self._client.request(, args, **kwargs) | Creates a directory within the MFS.
.. code-block:: python
>>> c.files_mkdir("/test")
b''
Parameters
----------
path : str
Filepath within the MFS
parents : bool
Create parent directories as needed and do not raise an exception
... |
3,421 | def _onCompletionListItemSelected(self, index):
model = self._widget.model()
selectedWord = model.words[index]
textToInsert = selectedWord[len(model.typedText()):]
self._qpart.textCursor().insertText(textToInsert)
self._closeCompletion() | Item selected. Insert completion to editor |
3,422 | def process_view(self, request, view_func, view_args, view_kwargs):
if view_func == login:
return cas_login(request, *view_args, **view_kwargs)
elif view_func == logout:
return cas_logout(request, *view_args, **view_kwargs)
if settings.CAS_ADMIN_PREFIX:
... | Forwards unauthenticated requests to the admin page to the CAS
login URL, as well as calls to django.contrib.auth.views.login and
logout. |
3,423 | def exists(name, region=None, key=None, keyid=None, profile=None):
topics = get_all_topics(region=region, key=key, keyid=keyid,
profile=profile)
if name.startswith():
return name in list(topics.values())
else:
return name in list(topics.keys()) | Check to see if an SNS topic exists.
CLI example::
salt myminion boto_sns.exists mytopic region=us-east-1 |
3,424 | def create_parser(subparsers):
parser = subparsers.add_parser(
,
help=,
usage="%(prog)s [options] cluster/[role]/[env] <topology-name> [container-id]",
add_help=True)
args.add_titles(parser)
args.add_cluster_role_env(parser)
args.add_topology(parser)
parser.add_argument(
,
... | :param subparsers:
:return: |
3,425 | def get_filter_solvers(self, filter_):
solvers_classes = [s for s in self.filter_solver_classes if s.can_solve(filter_)]
if solvers_classes:
solvers = []
for solver_class in solvers_classes:
if solver_class not in self._filter_solvers... | Returns the filter solvers that can solve the given filter.
Arguments
---------
filter : dataql.resources.BaseFilter
An instance of the a subclass of ``BaseFilter`` for which we want to get the solver
classes that can solve it.
Returns
-------
li... |
3,426 | def receiver(url, **kwargs):
res = url_to_resources(url)
fnc = res["receiver"]
return fnc(res.get("url"), **kwargs) | Return receiver instance from connection url string
url <str> connection url eg. 'tcp://0.0.0.0:8080' |
3,427 | def set_learning_objectives(self, objective_ids):
if not isinstance(objective_ids, list):
raise errors.InvalidArgument()
if self.get_learning_objectives_metadata().is_read_only():
raise errors.NoAccess()
idstr_list = []
for object_id in objective... | Sets the learning objectives.
arg: objective_ids (osid.id.Id[]): the learning objective
``Ids``
raise: InvalidArgument - ``objective_ids`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* |
3,428 | def add_assay(self, name, assay):
if not type(assay) is numpy.ndarray:
raise Exception("Invalid assay. It must be a numpy array.")
elif not assay.shape == (self.size_class_count,):
raise Exception(
"Invalid assay: It must have the same number of elements... | Add an assay to the material.
:param name: The name of the new assay.
:param assay: A numpy array containing the size class mass fractions
for the assay. The sequence of the assay's elements must correspond
to the sequence of the material's size classes. |
3,429 | def get_count(self, *args, **selectors):
obj = self.get_object(**selectors)
return self.get_count_of_object(obj) | Return the count of UI object with *selectors*
Example:
| ${count} | Get Count | text=Accessibility | # Get the count of UI object text=Accessibility |
| ${accessibility_text} | Get Object | text=Accessibility | # These two keywords combination ... |
3,430 | def _submit_gauges_from_histogram(self, metric_name, metric, scraper_config, hostname=None):
for sample in metric.samples:
val = sample[self.SAMPLE_VALUE]
if not self._is_value_valid(val):
self.log.debug("Metric value is not supported for metric {}".format(sample... | Extracts metrics from a prometheus histogram and sends them as gauges |
3,431 | def replace_handler(logger, match_handler, reconfigure):
handler, other_logger = find_handler(logger, match_handler)
if handler and other_logger and reconfigure:
other_logger.removeHandler(handler)
logger = other_logger
return handler, logger | Prepare to replace a handler.
:param logger: Refer to :func:`find_handler()`.
:param match_handler: Refer to :func:`find_handler()`.
:param reconfigure: :data:`True` if an existing handler should be replaced,
:data:`False` otherwise.
:returns: A tuple of two values:
... |
3,432 | def setup_columns(self):
tv = self.view[]
tv.set_model(self.model)
cell = gtk.CellRendererText()
tvcol = gtk.TreeViewColumn(, cell)
def cell_data_func(col, cell, mod, it):
if mod[it][0]: cell.set_property(, mod[it][0].name)
... | Creates the treeview stuff |
3,433 | def dump_http(method, url, request_headers, response, output_stream):
output_stream.write()
parsed_url = urlsplit(url)
http_path = parsed_url.path
if parsed_url.query:
http_path = http_path + + parsed_url.query
output_stream.write(.format(method,
... | Dump all headers and response headers into output_stream.
:param request_headers: Dictionary of HTTP request headers.
:param response_headers: Dictionary of HTTP response headers.
:param output_stream: Stream where the request is being dumped at. |
3,434 | def _gatherDataFromLookups(gpos, scriptOrder):
lookupIndexes = _gatherLookupIndexes(gpos)
seenLookups = set()
kerningDictionaries = []
leftClassDictionaries = []
rightClassDictionaries = []
for script in scriptOrder:
kerning = []
leftClasses = []
rightClasses = []
... | Gather kerning and classes from the applicable lookups
and return them in script order. |
3,435 | def parse_args():
description = (
"Get Wikipedia article info and Wikidata via MediaWiki APIs.\n\n"
"Gets a random English Wikipedia article by default, or in the\n"
"language -lang, or from the wikisite -wiki, or by specific\n"
"title -title. The output is a plain text extract ... | parse main() args |
3,436 | def first_true(iterable, default=False, pred=None):
return next(filter(pred, iterable), default) | Returns the first true value in the iterable.
If no true value is found, returns *default*
If *pred* is not None, returns the first item
for which pred(item) is true. |
3,437 | def _back_transform(self,inplace=True):
if not self.istransformed:
raise Exception("ParameterEnsemble already back transformed")
istransformed = self.pst.parameter_data.loc[:,"partrans"] == "log"
if inplace:
self.loc[:,istransformed] = 10.0**(self.loc[:,istransf... | Private method to remove log10 transformation from ensemble
Parameters
----------
inplace: bool
back transform self in place
Returns
------
ParameterEnsemble : ParameterEnsemble
if inplace if False
Note
----
Don't call th... |
3,438 | def reconfigure_messaging(self, msg_host, msg_port):
self._messaging.create_external_route(
, host=msg_host, port=msg_port) | force messaging reconnector to the connect to the (host, port) |
3,439 | def create_task_from_cu(cu, prof=None):
try:
logger.debug( % cu.name)
if prof:
prof.prof(,
uid=cu.name.split()[0].strip())
task = Task()
task.uid = cu.name.split()[0].strip()
task.name = cu.name.split()[1].strip()
task.parent... | Purpose: Create a Task based on the Compute Unit.
Details: Currently, only the uid, parent_stage and parent_pipeline are retrieved. The exact initial Task (that was
converted to a CUD) cannot be recovered as the RP API does not provide the same attributes for a CU as for a CUD.
Also, this is not required f... |
3,440 | def add_loaded_callback(self, callback):
if callback not in self._cb_aldb_loaded:
self._cb_aldb_loaded.append(callback) | Add a callback to be run when the ALDB load is complete. |
3,441 | def unchunk(self):
plan, padding, vshape, split = self.plan, self.padding, self.vshape, self.split
nchunks = self.getnumber(plan, vshape)
full_shape = concatenate((nchunks, plan))
n = len(vshape)
perm = concatenate(list(zip(range(n), range(n, 2*n))))
if self.uni... | Convert a chunked array back into a full array with (key,value) pairs
where key is a tuple of indices, and value is an ndarray. |
3,442 | def _calculate_comparison_stats(truth_vcf):
min_stat_size = 50
min_median_size = 250
sizes = []
svtypes = set([])
with utils.open_gzipsafe(truth_vcf) as in_handle:
for call in (l.rstrip().split("\t") for l in in_handle if not l.startswith("
stats = _summarize_call(call)... | Identify calls to validate from the input truth VCF. |
3,443 | def open(uri, mode, kerberos=False, user=None, password=None):
if mode == :
return BufferedInputBase(uri, mode, kerberos=kerberos, user=user, password=password)
else:
raise NotImplementedError( % mode) | Implement streamed reader from a web site.
Supports Kerberos and Basic HTTP authentication.
Parameters
----------
url: str
The URL to open.
mode: str
The mode to open using.
kerberos: boolean, optional
If True, will attempt to use the local Kerberos credentials
user... |
3,444 | def find_all_matches(finder, ireq, pre=False):
candidates = clean_requires_python(finder.find_all_candidates(ireq.name))
versions = {candidate.version for candidate in candidates}
allowed_versions = _get_filtered_versions(ireq, versions, pre)
if not pre and not allowed_versions:
allo... | Find all matching dependencies using the supplied finder and the
given ireq.
:param finder: A package finder for discovering matching candidates.
:type finder: :class:`~pip._internal.index.PackageFinder`
:param ireq: An install requirement.
:type ireq: :class:`~pip._internal.req.req_install.Install... |
3,445 | def set_tile(self, row, col, value):
if col < 0:
print("ERROR - x less than zero", col)
col = 0
if col > self.grid_width - 1 :
print("ERROR - x larger than grid", col)
col = self.grid_width - 1
... | Set the tile at position row, col to have the given value. |
3,446 | def tarbell_configure(command, args):
puts("Configuring Tarbell. Press ctrl-c to bail out!")
puts("\nWriting {0}".format(colored.green(path)))
settings.save()
if all:
puts("\n- Done configuring Tarbell. Type `{0}` for help.\n"
.format(colored.green("tarbell")))
... | Tarbell configuration routine. |
3,447 | def createJobSubscriptionAsync(self, ackCallback, callback, jobExecutionType=jobExecutionTopicType.JOB_WILDCARD_TOPIC, jobReplyType=jobExecutionTopicReplyType.JOB_REQUEST_TYPE, jobId=None):
topic = self._thingJobManager.getJobTopic(jobExecutionType, jobReplyType, jobId)
return self._AWSIoTMQTTC... | **Description**
Asynchronously creates an MQTT subscription to a jobs related topic based on the provided arguments
**Syntax**
.. code:: python
#Subscribe to notify-next topic to monitor change in job referred to by $next
myAWSIoTMQTTJobsClient.createJobSubscriptionAsync(... |
3,448 | def Register(self, name, constructor):
precondition.AssertType(name, Text)
if name in self._constructors:
message = "Duplicated constructors %r and %r for name "
message %= (constructor, self._constructors[name], name)
raise ValueError(message)
self._constructors[name] = constructor | Registers a new constructor in the factory.
Args:
name: A name associated with given constructor.
constructor: A constructor function that creates instances.
Raises:
ValueError: If there already is a constructor associated with given name. |
3,449 | def insertValue(self, pos, configValue, displayValue=None):
self._configValues.insert(pos, configValue)
self._displayValues.insert(pos, displayValue if displayValue is not None else configValue) | Will insert the configValue in the configValues and the displayValue in the
displayValues list.
If displayValue is None, the configValue is set in the displayValues as well |
3,450 | def _execute(self, sql, params):
try:
return self._execute_unsafe(sql, params)
except MySQLdb.OperationalError as ex:
if ex.args[0] in (2006, 2013, 2055):
self._log("Connection with server is lost. Trying to reconnect.")
self.connect()
... | Execute statement with reconnecting by connection closed error codes.
2006 (CR_SERVER_GONE_ERROR): MySQL server has gone away
2013 (CR_SERVER_LOST): Lost connection to MySQL server during query
2055 (CR_SERVER_LOST_EXTENDED): Lost connection to MySQL server at '%s', system error: %d |
3,451 | def find_field_by_name(browser, field_type, name):
return ElementSelector(
browser,
field_xpath(field_type, ) %
string_literal(name),
filter_displayed=True,
) | Locate the control input with the given ``name``.
:param browser: ``world.browser``
:param string field_type: a field type (i.e. `button`)
:param string name: ``name`` attribute
Returns: an :class:`ElementSelector` |
3,452 | def table(self, name, database=None, schema=None):
if database is not None and database != self.current_database:
return self.database(name=database).table(name=name, schema=schema)
else:
alch_table = self._get_sqla_table(name, schema=schema)
node = self.tabl... | Create a table expression that references a particular a table
called `name` in a MySQL database called `database`.
Parameters
----------
name : str
The name of the table to retrieve.
database : str, optional
The database in which the table referred to by... |
3,453 | def build(self):
self.defined_gates = set(STANDARD_GATE_NAMES)
prog = self._recursive_builder(self.operation,
self.gate_name,
self.control_qubits,
self.target_qubit)
retu... | Builds this controlled gate.
:return: The controlled gate, defined by this object.
:rtype: Program |
3,454 | def item_count(self, request, variant_id=None):
bid = utils.basket_id(request)
item = ProductVariant.objects.get(id=variant_id)
try:
count = BasketItem.objects.get(basket_id=bid, variant=item).quantity
except BasketItem.DoesNotExist:
count = 0
... | Get quantity of a single item in the basket |
3,455 | async def download(self, resource_url):
resolver_path = self.find_path_from_url(resource_url)
await self.apply_resolver_path(resource_url, resolver_path) | Download given Resource URL by finding path through graph and applying
each step |
3,456 | def build_bam_tags():
def _combine_filters(fam, paired_align, align):
filters = [x.filter_value for x in [fam, align] if x and x.filter_value]
if filters:
return ";".join(filters).replace(, )
return None
boolean_tag_value = {True:1}
tags = [
BamTag("X0"... | builds the list of BAM tags to be added to output BAMs |
3,457 | def validate(self):
if self.unique_identifier is not None:
if not isinstance(self.unique_identifier,
attributes.UniqueIdentifier):
msg = "invalid unique identifier"
raise TypeError(msg)
if self.compromise_occurrence_date ... | Error check the attributes of the ActivateRequestPayload object. |
3,458 | def unicode_to_hex(unicode_string):
if unicode_string is None:
return None
acc = []
for c in unicode_string:
s = hex(ord(c)).replace("0x", "").upper()
acc.append("U+" + ("0" * (4 - len(s))) + s)
return u" ".join(acc) | Return a string containing the Unicode hexadecimal codepoint
of each Unicode character in the given Unicode string.
Return ``None`` if ``unicode_string`` is ``None``.
Example::
a => U+0061
ab => U+0061 U+0062
:param str unicode_string: the Unicode string to convert
:rtype: (Unico... |
3,459 | def _encode_observations(self, observations):
return [
Observation(
self._session.obj.run(
self._encoded_image_t.obj,
feed_dict={self._decoded_image_p.obj: observation}
),
self._decode_png
)
for observation in observati... | Encodes observations as PNG. |
3,460 | def retweet(self, id):
try:
self._client.retweet(id=id)
return True
except TweepError as e:
if e.api_code == TWITTER_PAGE_DOES_NOT_EXISTS_ERROR:
return False
raise | Retweet a tweet.
:param id: ID of the tweet in question
:return: True if success, False otherwise |
3,461 | def bytes_to_number(b, endian=):
if endian == :
b = reversed(b)
n = 0
for i, ch in enumerate(bytearray(b)):
n ^= ch << i * 8
return n | Convert a string to an integer.
:param b:
String or bytearray to convert.
:param endian:
Byte order to convert into ('big' or 'little' endian-ness, default
'big')
Assumes bytes are 8 bits.
This is a special-case version of string_to_number with a full base-256
ASCII alpha... |
3,462 | def http_post(self, path, query_data={}, post_data={}, files=None,
**kwargs):
result = self.http_request(, path, query_data=query_data,
post_data=post_data, files=files, **kwargs)
try:
if result.headers.get(, None) == :
... | Make a POST request to the Gitlab server.
Args:
path (str): Path or full URL to query ('/projects' or
'http://whatever/v4/api/projecs')
query_data (dict): Data to send as query parameters
post_data (dict): Data to send in the body (will be converted t... |
3,463 | def main():
expr_list = [
"max(-_.千幸福的笑脸{घोड़ा=馬, "
"dn2=dv2,千幸福的笑脸घ=千幸福的笑脸घ}) gte 100 "
"times 3 && "
"(min(ເຮືອນ{dn3=dv3,家=дом}) < 10 or sum(biz{dn5=dv5}) >99 and "
"count(fizzle) lt 0or count(baz) > 1)".decode(),
"max(foo{hostname=mini-mon,千=千}, 120) > 100 ... | Used for development and testing. |
3,464 | def applicationpolicy(arg=None):
def _mutator(func):
wrapped = singledispatch(func)
@wraps(wrapped)
def wrapper(*args, **kwargs):
event = kwargs.get() or args[-1]
return wrapped.dispatch(type(event))(*args, **kwargs)
wrapper.register = wrapped.register... | Decorator for application policy method.
Allows policy to be built up from methods
registered for different event classes. |
3,465 | def _find_by_android(self, browser, criteria, tag, constraints):
return self._filter_elements(
browser.find_elements_by_android_uiautomator(criteria),
tag, constraints) | Find element matches by UI Automator. |
3,466 | def selectlastrow(self, window_name, object_name):
object_handle = self._get_object_handle(window_name, object_name)
if not object_handle.AXEnabled:
raise LdtpServerException(u"Object %s state disabled" % object_name)
cell = object_handle.AXRows[-1]
if not cell.AXSe... | Select last row
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type object_name: strin... |
3,467 | async def get_creds(self, proof_req_json: str, filt: dict = None, filt_dflt_incl: bool = False) -> (Set[str], str):
LOGGER.debug(, proof_req_json, filt)
if filt is None:
filt = {}
rv = None
creds_json = await anoncreds.prover_get_credentials_for_proof_req(self.wall... | Get credentials from HolderProver wallet corresponding to proof request and
filter criteria; return credential identifiers from wallet and credentials json.
Return empty set and empty production for no such credentials.
:param proof_req_json: proof request json as Verifier creates; has entries ... |
3,468 | def get_reference_templates(self, ref_types):
return OrderedDict([(x, self.get_reference_template(x)) for x in ref_types]) | Return the reference templates for the types as an ordered dictionary. |
3,469 | def putscript(self, name, content):
content = tools.to_bytes(content)
content = tools.to_bytes("{%d+}" % len(content)) + CRLF + content
code, data = (
self.__send_command("PUTSCRIPT", [name.encode("utf-8"), content]))
if code == "OK":
return True
... | Upload a script to the server
See MANAGESIEVE specifications, section 2.6
:param name: script's name
:param content: script's content
:rtype: boolean |
3,470 | def svm_version_path(version):
return os.path.join(Spark.HOME_DIR, Spark.SVM_DIR, .format(version)) | Path to specified spark version. Accepts semantic version numbering.
:param version: Spark version as String
:return: String. |
3,471 | def insert(self, cache_key, paths, overwrite=False):
missing_files = [f for f in paths if not os.path.exists(f)]
if missing_files:
raise ArtifactCacheError(.format(missing_files))
if not overwrite:
if self.has(cache_key):
logger.debug(.format(cache_key))
return False
t... | Cache the output of a build.
By default, checks cache.has(key) first, only proceeding to create and insert an artifact
if it is not already in the cache (though `overwrite` can be used to skip the check and
unconditionally insert).
:param CacheKey cache_key: A CacheKey object.
:param list<str> pat... |
3,472 | def create_build_configuration_set_raw(**kwargs):
config_set = _create_build_config_set_object(**kwargs)
response = utils.checked_api_call(pnc_api.build_group_configs, , body=config_set)
if response:
return response.content | Create a new BuildConfigurationSet. |
3,473 | def set_scanner (type, scanner):
if __debug__:
from .scanner import Scanner
assert isinstance(type, basestring)
assert issubclass(scanner, Scanner)
validate (type)
__types [type][] = scanner | Sets a scanner class that will be used for this 'type'. |
3,474 | def missing_intervals(startdate, enddate, start, end,
dateconverter=None,
parseinterval=None,
intervals=None):
parseinterval = parseinterval or default_parse_interval
dateconverter = dateconverter or todate
startdate = dateconvert... | Given a ``startdate`` and an ``enddate`` dates, evaluate the
date intervals from which data is not available. It return a list of
two-dimensional tuples containing start and end date for the interval.
The list could countain 0,1 or 2 tuples. |
3,475 | def showMetadata(dat):
_tmp = rm_values_fields(copy.deepcopy(dat))
print(json.dumps(_tmp, indent=2))
return | Display the metadata specified LiPD in pretty print
| Example
| showMetadata(D["Africa-ColdAirCave.Sundqvist.2013"])
:param dict dat: Metadata
:return none: |
3,476 | def _latex_format(obj: Any) -> str:
if isinstance(obj, float):
try:
return sympy.latex(symbolize(obj))
except ValueError:
return "{0:.4g}".format(obj)
return str(obj) | Format an object as a latex string. |
3,477 | def _get_required_fn(fn, root_path):
if not fn.startswith(root_path):
raise ValueError("Both paths have to be absolute or local!")
replacer = "/" if root_path.endswith("/") else ""
return fn.replace(root_path, replacer, 1) | Definition of the MD5 file requires, that all paths will be absolute
for the package directory, not for the filesystem.
This function converts filesystem-absolute paths to package-absolute paths.
Args:
fn (str): Local/absolute path to the file.
root_path (str): Local/absolute path to the p... |
3,478 | def write(self, data, auto_flush=True):
self.temporary_file.write(data)
if auto_flush:
self.flush() | <Purpose>
Writes a data string to the file.
<Arguments>
data:
A string containing some data.
auto_flush:
Boolean argument, if set to 'True', all data will be flushed from
internal buffer.
<Exceptions>
None.
<Return>
None. |
3,479 | def upload(self, *args, **kwargs):
for job in self.jobs:
job.upload(*args, **kwargs) | Runs command on every job in the run. |
3,480 | def load_plugins(self):
logger.info("Loading plugins...")
for (plugin_name, plugin_path, plugin_cfg) in self.config.plugins:
logger.debug("Loading plugin %s from %s", plugin_name, plugin_path)
if plugin_path == "yandextank.plugins.Overload":
logger.warnin... | Tells core to take plugin options and instantiate plugin classes |
3,481 | def tag(self, text):
matches = self._match(text.text)
matches = self._resolve_conflicts(matches)
if self.return_layer:
return matches
else:
text[self.layer_name] = matches | Retrieves list of regex_matches in text.
Parameters
----------
text: Text
The estnltk text object to search for events.
Returns
-------
list of matches |
3,482 | def parse_arguments(filters, arguments, modern=False):
params = DotDict()
for i in filters:
count = len(i)
param = None
if count <= 1:
param = arguments.get(i[0])
else:
param = arguments.get(i[0], i[1])
if count >= 3:
t... | Return a dict of parameters.
Take a list of filters and for each try to get the corresponding
value in arguments or a default value. Then check that value's type.
The @modern parameter indicates how the arguments should be
interpreted. The old way is that you always specify a list and in
the list yo... |
3,483 | def _show_doc(cls, fmt_func, keys=None, indent=0, grouped=False,
func=None, include_links=False, *args, **kwargs):
def titled_group(groupname):
bars = str_indent + * len(groupname) +
return bars + str_indent + groupname + + bars
func = func or defau... | Classmethod to print the formatoptions and their documentation
This function is the basis for the :meth:`show_summaries` and
:meth:`show_docs` methods
Parameters
----------
fmt_func: function
A function that takes the key, the key as it is printed, and the
... |
3,484 | def flatten(struct):
if struct is None:
return []
flat = []
if isinstance(struct, dict):
for _, result in six.iteritems(struct):
flat += flatten(result)
return flat
if isinstance(struct, six.string_types):
return [struct]
try:
iterat... | Creates a flat list of all all items in structured output (dicts, lists, items):
.. code-block:: python
>>> sorted(flatten({'a': 'foo', 'b': 'bar'}))
['bar', 'foo']
>>> sorted(flatten(['foo', ['bar', 'troll']]))
['bar', 'foo', 'troll']
>>> flatten('foo')
['foo']
... |
3,485 | def from_opcode(cls, opcode, arg=_no_arg):
return type(cls)(opname[opcode], (cls,), {}, opcode=opcode)(arg) | Create an instruction from an opcode and raw argument.
Parameters
----------
opcode : int
Opcode for the instruction to create.
arg : int, optional
The argument for the instruction.
Returns
-------
intsr : Instruction
An insta... |
3,486 | def toVerticalPotential(Pot,R,phi=None):
Pot= flatten(Pot)
if _APY_LOADED:
if isinstance(R,units.Quantity):
if hasattr(Pot,):
R= R.to(units.kpc).value/Pot._ro
else:
R= R.to(units.kpc).value/Pot[0]._ro
if isinstance(phi,units.Quantity):... | NAME:
toVerticalPotential
PURPOSE:
convert a Potential to a vertical potential at a given R
INPUT:
Pot - Potential instance or list of such instances
R - Galactocentric radius at which to evaluate the vertical potential (can be Quantity)
phi= (None) Galactocentric azimu... |
3,487 | def last_commit():
try:
root = subprocess.check_output(
[, , ],
stderr=subprocess.STDOUT).strip()
return root.decode()
except subprocess.CalledProcessError:
return None | Returns the SHA1 of the last commit. |
3,488 | def hil_controls_send(self, time_usec, roll_ailerons, pitch_elevator, yaw_rudder, throttle, aux1, aux2, aux3, aux4, mode, nav_mode, force_mavlink1=False):
return self.send(self.hil_controls_encode(time_usec, roll_ailerons, pitch_elevator, yaw_rudder, throttle, aux1, aux2, aux3, aux4, mo... | Sent from autopilot to simulation. Hardware in the loop control
outputs
time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t)
roll_ailerons : Control output -1 .. 1 (float)
pitch_ele... |
3,489 | def _future_completed(future):
exc = future.exception()
if exc:
log.debug("Failed to run task on executor", exc_info=exc) | Helper for run_in_executor() |
3,490 | def write_mates(self):
if self.chrom is not None:
U.debug("Dumping %i mates for contig %s" % (
len(self.read1s), self.chrom))
for read in self.infile.fetch(reference=self.chrom, multiple_iterators=True):
if any((read.is_unmapped, read.mate_is_unmapped, r... | Scan the current chromosome for matches to any of the reads stored
in the read1s buffer |
3,491 | def _add_redundancy_router_interfaces(self, context, router, itfc_info,
new_port, redundancy_router_ids=None,
ha_settings_db=None,
create_ha_group=True):
... | To be called in add_router_interface() AFTER interface has been
added to router in DB. |
3,492 | def session_dump(self, cell, hash, fname_session):
logging.debug(.format(hash, fname_session))
inject_code = [,
.format(fname_session),
]
inject_cell = nbf.v4.new_code_cell(.join(inject_code))
reply, outputs = super().run_cell(inj... | Dump ipython session to file
:param hash: cell hash
:param fname_session: output filename
:return: |
3,493 | def meanAndStdDev(self, limit=None):
if limit is None or len(self.values) < limit:
limit = len(self.values)
if limit > 0:
mean = sum(self.values[-limit:]) / float(limit)
sumSq = 0.
for v in self.values[-limit:]:
sumSq += (v - mean)... | return the mean and the standard deviation optionally limited to the last limit values |
3,494 | def add_cell_markdown(self, cell_str):
logging.debug("add_cell_markdown: {}".format(cell_str))
cell = .join(cell_str.split())
cell = nbf.v4.new_markdown_cell(cell)
self.nb[].append(cell) | Add a markdown cell
:param cell_str: markdown text
:return: |
3,495 | def clear_database(engine: Connectable, schemas: Iterable[str] = ()) -> None:
assert check_argument_types()
metadatas = []
all_schemas = (None,)
all_schemas += tuple(schemas)
for schema in all_schemas:
metadata = MetaData()
metadata.reflect(engine, schema=schema, view... | Clear any tables from an existing database.
:param engine: the engine or connection to use
:param schemas: full list of schema names to expect (ignored for SQLite) |
3,496 | def auto_assign_decodings(self, decodings):
nrz_decodings = [decoding for decoding in decodings if decoding.is_nrz or decoding.is_nrzi]
fallback = nrz_decodings[0] if nrz_decodings else None
candidate_decodings = [decoding for decoding in decodings
if deco... | :type decodings: list of Encoding |
3,497 | def _split_path(path):
path = path.strip()
list_path = path.split()
sentinel = list_path.pop(0)
return sentinel, list_path, path | split a path return by the api
return
- the sentinel:
- the rest of the path as a list.
- the original path stripped of / for normalisation. |
3,498 | def on_menu_make_MagIC_results_tables(self, event):
self.on_menu_save_interpretation(None)
dia = demag_dialogs.magic_pmag_specimens_table_dialog(None)
CoorTypes = []
if self.test_mode:
CoorTypes = []
eli... | Creates or Updates Specimens or Pmag Specimens MagIC table,
overwrites .redo file for safety, and starts User dialog to
generate other MagIC tables for later contribution to the MagIC
database. The following describes the steps used in the 2.5 data
format to do this:
1. rea... |
3,499 | def train_nn_segmentation_classifier(X, y):
def build_mlp(input_var=None):
n_classes = 2
l_in = lasagne.layers.InputLayer(shape=X.shape,
input_var=input_var)
hiddens = [64, 64, 64]
layers = [l_in]
... | Train a neural network classifier.
Parameters
----------
X : numpy array
A list of feature vectors
y : numpy array
A list of labels
Returns
-------
Theano expression :
The trained neural network |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.