_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q8600 | DAWG.similar_keys | train | def similar_keys(self, key, replaces):
"""
Returns all variants of ``key`` in this DAWG according to
``replaces``.
``replaces`` is an object obtained from
``DAWG.compile_replaces(mapping)`` where mapping is a dict
that maps single-char unicode sitrings to another single-... | python | {
"resource": ""
} |
q8601 | DAWG.prefixes | train | def prefixes(self, key):
'''
Returns a list with keys of this DAWG that are prefixes of the ``key``.
'''
res = []
index = self.dct.ROOT
if not isinstance(key, bytes):
key = key.encode('utf8')
pos = 1
for ch in key:
index = self.dc... | python | {
"resource": ""
} |
q8602 | BytesDAWG.similar_item_values | train | def similar_item_values(self, key, replaces):
"""
Returns a list of values for all variants of the ``key``
in this DAWG according to ``replaces``.
``replaces`` is an object obtained from
``DAWG.compile_replaces(mapping)`` where mapping is a dict
that maps single-char uni... | python | {
"resource": ""
} |
q8603 | Dictionary.value | train | def value(self, index):
"Gets a value from a given index."
offset = units.offset(self._units[index])
value_index = (index ^ offset) & units.PRECISION_MASK
return units.value(self._units[value_index]) | python | {
"resource": ""
} |
q8604 | Dictionary.read | train | def read(self, fp):
"Reads a dictionary from an input stream."
base_size = struct.unpack(str("=I"), fp.read(4))[0]
self._units.fromfile(fp, base_size) | python | {
"resource": ""
} |
q8605 | Dictionary.contains | train | def contains(self, key):
"Exact matching."
index = self.follow_bytes(key, self.ROOT)
if index is None:
return False
return self.has_value(index) | python | {
"resource": ""
} |
q8606 | Dictionary.follow_char | train | def follow_char(self, label, index):
"Follows a transition"
offset = units.offset(self._units[index])
next_index = (index ^ offset ^ label) & units.PRECISION_MASK
if units.label(self._units[next_index]) != label:
return None
return next_index | python | {
"resource": ""
} |
q8607 | Dictionary.follow_bytes | train | def follow_bytes(self, s, index):
"Follows transitions."
for ch in s:
index = self.follow_char(int_from_byte(ch), index)
if index is None:
return None
return index | python | {
"resource": ""
} |
q8608 | Completer.next | train | def next(self):
"Gets the next key"
if not self._index_stack:
return False
index = self._index_stack[-1]
if self._last_index != self._dic.ROOT:
child_label = self._guide.child(index) # UCharType
if child_label:
# Follows a transit... | python | {
"resource": ""
} |
q8609 | convert_response | train | def convert_response(check_response, project_id):
"""Computes a http status code and message `CheckResponse`
The return value a tuple (code, message, api_key_is_bad) where
code: is the http status code
message: is the message to return
api_key_is_bad: indicates that a given api_key is bad
Arg... | python | {
"resource": ""
} |
q8610 | sign | train | def sign(check_request):
"""Obtains a signature for an operation in a `CheckRequest`
Args:
op (:class:`endpoints_management.gen.servicecontrol_v1_messages.Operation`): an
operation used in a `CheckRequest`
Returns:
string: a secure hash generated from the operation
"""
if no... | python | {
"resource": ""
} |
q8611 | Info.as_check_request | train | def as_check_request(self, timer=datetime.utcnow):
"""Makes a `ServicecontrolServicesCheckRequest` from this instance
Returns:
a ``ServicecontrolServicesCheckRequest``
Raises:
ValueError: if the fields in this instance are insufficient to
to create a valid ``Ser... | python | {
"resource": ""
} |
q8612 | Aggregator.check | train | def check(self, req):
"""Determine if ``req`` is in this instances cache.
Determine if there are cache hits for the request in this aggregator
instance.
Not in the cache
If req is not in the cache, it returns ``None`` to indicate that the
caller should send the request... | python | {
"resource": ""
} |
q8613 | compare | train | def compare(a, b):
"""Compares two timestamps.
``a`` and ``b`` must be the same type, in addition to normal
representations of timestamps that order naturally, they can be rfc3339
formatted strings.
Args:
a (string|object): a timestamp
b (string|object): another timestamp
Returns:... | python | {
"resource": ""
} |
q8614 | to_rfc3339 | train | def to_rfc3339(timestamp):
"""Converts ``timestamp`` to an RFC 3339 date string format.
``timestamp`` can be either a ``datetime.datetime`` or a
``datetime.timedelta``. Instances of the later are assumed to be a delta
with the beginining of the unix epoch, 1st of January, 1970
The returned string... | python | {
"resource": ""
} |
q8615 | from_rfc3339 | train | def from_rfc3339(rfc3339_text, with_nanos=False):
"""Parse a RFC 3339 date string format to datetime.date.
Example of accepted format: '1972-01-01T10:00:20.021-05:00'
- By default, the result is a datetime.datetime
- If with_nanos is true, the result is a 2-tuple, (datetime.datetime,
nanos), where... | python | {
"resource": ""
} |
q8616 | Info.as_operation | train | def as_operation(self, timer=datetime.utcnow):
"""Makes an ``Operation`` from this instance.
Returns:
an ``Operation``
"""
now = timer()
op = sc_messages.Operation(
endTime=timestamp.to_rfc3339(now),
startTime=timestamp.to_rfc3339(now),
... | python | {
"resource": ""
} |
q8617 | Aggregator.as_operation | train | def as_operation(self):
"""Obtains a single `Operation` representing this instances contents.
Returns:
:class:`endpoints_management.gen.servicecontrol_v1_messages.Operation`
"""
result = encoding.CopyProtoMessage(self._op)
names = sorted(self._metric_values_by_name_th... | python | {
"resource": ""
} |
q8618 | Aggregator.add | train | def add(self, other_op):
"""Combines `other_op` with the operation held by this aggregator.
N.B. It merges the operations log entries and metric values, but makes
the assumption the operation is consistent. It's the callers
responsibility to ensure consistency
Args:
... | python | {
"resource": ""
} |
q8619 | create_exponential | train | def create_exponential(num_finite_buckets, growth_factor, scale):
"""Creates a new instance of distribution with exponential buckets
Args:
num_finite_buckets (int): initializes number of finite buckets
growth_factor (float): initializes the growth factor
scale (float): initializes the scal... | python | {
"resource": ""
} |
q8620 | create_linear | train | def create_linear(num_finite_buckets, width, offset):
"""Creates a new instance of distribution with linear buckets.
Args:
num_finite_buckets (int): initializes number of finite buckets
width (float): initializes the width of each bucket
offset (float): initializes the offset
Return:
... | python | {
"resource": ""
} |
q8621 | create_explicit | train | def create_explicit(bounds):
"""Creates a new instance of distribution with explicit buckets.
bounds is an iterable of ordered floats that define the explicit buckets
Args:
bounds (iterable[float]): initializes the bounds
Return:
:class:`endpoints_management.gen.servicecontrol_v1_messag... | python | {
"resource": ""
} |
q8622 | add_sample | train | def add_sample(a_float, dist):
"""Adds `a_float` to `dist`, updating its existing buckets.
Args:
a_float (float): a new value
dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`):
the Distribution being updated
Raises:
ValueError: if `dist` does not ha... | python | {
"resource": ""
} |
q8623 | merge | train | def merge(prior, latest):
"""Merge `prior` into `latest`.
N.B, this mutates latest. It ensures that the statistics and histogram are
updated to correctly include the original values from both instances.
Args:
prior (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`):
... | python | {
"resource": ""
} |
q8624 | _buckets_nearly_equal | train | def _buckets_nearly_equal(a_dist, b_dist):
"""Determines whether two `Distributions` are nearly equal.
Args:
a_dist (:class:`Distribution`): an instance
b_dist (:class:`Distribution`): another instance
Return:
boolean: `True` if the two instances are approximately equal, otherwise
... | python | {
"resource": ""
} |
q8625 | _update_general_statistics | train | def _update_general_statistics(a_float, dist):
"""Adds a_float to distribution, updating the statistics fields.
Args:
a_float (float): a new value
dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`):
the Distribution being updated
"""
if not dist.count:... | python | {
"resource": ""
} |
q8626 | _update_exponential_bucket_count | train | def _update_exponential_bucket_count(a_float, dist):
"""Adds `a_float` to `dist`, updating its exponential buckets.
Args:
a_float (float): a new value
dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`):
the Distribution being updated
Raises:
ValueErr... | python | {
"resource": ""
} |
q8627 | _update_linear_bucket_count | train | def _update_linear_bucket_count(a_float, dist):
"""Adds `a_float` to `dist`, updating the its linear buckets.
Args:
a_float (float): a new value
dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`):
the Distribution being updated
Raises:
ValueError: if... | python | {
"resource": ""
} |
q8628 | _update_explicit_bucket_count | train | def _update_explicit_bucket_count(a_float, dist):
"""Adds `a_float` to `dist`, updating its explicit buckets.
Args:
a_float (float): a new value
dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`):
the Distribution being updated
Raises:
ValueError: if... | python | {
"resource": ""
} |
q8629 | scheduler.enterabs | train | def enterabs(self, time, priority, action, argument=(), kwargs=_sentinel):
"""Enter a new event in the queue at an absolute time.
Returns an ID for the event which can be used to remove it,
if necessary.
"""
if kwargs is _sentinel:
kwargs = {}
event = Event(... | python | {
"resource": ""
} |
q8630 | scheduler.enter | train | def enter(self, delay, priority, action, argument=(), kwargs=_sentinel):
"""A variant that specifies the time as a relative time.
This is actually the more commonly used interface.
"""
time = self.timefunc() + delay
return self.enterabs(time, priority, action, argument, kwargs) | python | {
"resource": ""
} |
q8631 | scheduler.cancel | train | def cancel(self, event):
"""Remove an event from the queue.
This must be presented the ID as returned by enter().
If the event is not in the queue, this raises ValueError.
"""
with self._lock:
self._queue.remove(event)
heapq.heapify(self._queue) | python | {
"resource": ""
} |
q8632 | check_valid | train | def check_valid(money):
"""Determine if an instance of `Money` is valid.
Args:
money (:class:`endpoints_management.gen.servicecontrol_v1_messages.Money`): the
instance to test
Raises:
ValueError: if the money instance is invalid
"""
if not isinstance(money, sc_messages.Money):
... | python | {
"resource": ""
} |
q8633 | add | train | def add(a, b, allow_overflow=False):
"""Adds two instances of `Money`.
Args:
a (:class:`endpoints_management.gen.servicecontrol_v1_messages.Money`): one money
value
b (:class:`endpoints_management.gen.servicecontrol_v1_messages.Money`): another
money value
allow_overflow: dete... | python | {
"resource": ""
} |
q8634 | _sign_of | train | def _sign_of(money):
"""Determines the amount sign of a money instance
Args:
money (:class:`endpoints_management.gen.servicecontrol_v1_messages.Money`): the
instance to test
Return:
int: 1, 0 or -1
"""
units = money.units
nanos = money.nanos
if units:
if units ... | python | {
"resource": ""
} |
q8635 | _check_jwt_claims | train | def _check_jwt_claims(jwt_claims):
"""Checks whether the JWT claims should be accepted.
Specifically, this method checks the "exp" claim and the "nbf" claim (if
present), and raises UnauthenticatedException if 1) the current time is
before the time identified by the "nbf" claim, or 2) the current time ... | python | {
"resource": ""
} |
q8636 | _verify_required_claims_exist | train | def _verify_required_claims_exist(jwt_claims):
"""Verifies that the required claims exist.
Args:
jwt_claims: the JWT claims to be verified.
Raises:
UnauthenticatedException: if some claim doesn't exist.
"""
for claim_name in [u"aud", u"exp", u"iss", u"sub"]:
if claim_name not i... | python | {
"resource": ""
} |
q8637 | Authenticator.authenticate | train | def authenticate(self, auth_token, auth_info, service_name):
"""Authenticates the current auth token.
Args:
auth_token: the auth token.
auth_info: the auth configurations of the API method being called.
service_name: the name of this service.
Returns:
A ... | python | {
"resource": ""
} |
q8638 | Authenticator.get_jwt_claims | train | def get_jwt_claims(self, auth_token):
"""Decodes the auth_token into JWT claims represented as a JSON object.
This method first tries to look up the cache and returns the result
immediately in case of a cache hit. When cache misses, the method tries to
decode the given auth token, verif... | python | {
"resource": ""
} |
q8639 | create | train | def create(options, timer=None, use_deque=True):
"""Create a cache specified by ``options``
``options`` is an instance of either
:class:`endpoints_management.control.caches.CheckOptions` or
:class:`endpoints_management.control.caches.ReportOptions`
The returned cache is wrapped in a :class:`Locked... | python | {
"resource": ""
} |
q8640 | to_cache_timer | train | def to_cache_timer(datetime_func):
"""Converts a datetime_func to a timestamp_func.
Args:
datetime_func (callable[[datatime]]): a func that returns the current
time
Returns:
time_func (callable[[timestamp]): a func that returns the timestamp
from the epoch
"""
if da... | python | {
"resource": ""
} |
q8641 | distribute | train | def distribute(build):
""" distribute the uranium package """
build.packages.install("wheel")
build.packages.install("twine")
build.executables.run([
"python", "setup.py",
"sdist", "bdist_wheel", "--universal", "upload",
])
build.executables.run([
"twine", "upload", "dist... | python | {
"resource": ""
} |
q8642 | use_gae_thread | train | def use_gae_thread():
"""Makes ``Client``s started after this use the appengine thread class."""
global _THREAD_CLASS # pylint: disable=global-statement
try:
from google.appengine.api.background_thread import background_thread
_THREAD_CLASS = background_thread.BackgroundThread
except Im... | python | {
"resource": ""
} |
q8643 | Client.start | train | def start(self):
"""Starts processing.
Calling this method
- starts the thread that regularly flushes all enabled caches.
- enables the other methods on the instance to be called successfully
"""
with self._lock:
if self._running:
return
... | python | {
"resource": ""
} |
q8644 | Client.check | train | def check(self, check_req):
"""Process a check_request.
The req is first passed to the check_aggregator. If there is a valid
cached response, that is returned, otherwise a response is obtained from
the transport.
Args:
check_req (``ServicecontrolServicesCheckRequest`... | python | {
"resource": ""
} |
q8645 | Client.report | train | def report(self, report_req):
"""Processes a report request.
It will aggregate it with prior report_requests to be send later
or it will send it immediately if that's appropriate.
"""
self.start()
# no thread running, run the scheduler to ensure any pending
# fl... | python | {
"resource": ""
} |
q8646 | create | train | def create(labels=None, **kw):
"""Constructs a new metric value.
This acts as an alternate to MetricValue constructor which
simplifies specification of labels. Rather than having to create
a MetricValue.Labels instance, all that's necessary to specify the
required string.
Args:
labels (... | python | {
"resource": ""
} |
q8647 | merge | train | def merge(metric_kind, prior, latest):
"""Merges `prior` and `latest`
Args:
metric_kind (:class:`MetricKind`): indicates the kind of metrics
being merged
prior (:class:`MetricValue`): an prior instance of the metric
latest (:class:`MetricValue`: the latest instance of the metric
... | python | {
"resource": ""
} |
q8648 | update_hash | train | def update_hash(a_hash, mv):
"""Adds ``mv`` to ``a_hash``
Args:
a_hash (`Hash`): the secure hash, e.g created by hashlib.md5
mv (:class:`MetricValue`): the instance to add to the hash
"""
if mv.labels:
signing.add_dict_to_hash(a_hash, encoding.MessageToPyValue(mv.labels))
mon... | python | {
"resource": ""
} |
q8649 | sign | train | def sign(mv):
"""Obtains a signature for a `MetricValue`
Args:
mv (:class:`endpoints_management.gen.servicecontrol_v1_messages.MetricValue`): a
MetricValue that's part of an operation
Returns:
string: a unique signature for that operation
"""
md5 = hashlib.md5()
update_h... | python | {
"resource": ""
} |
q8650 | KeyUriSupplier.supply | train | def supply(self, issuer):
"""Supplies the `jwks_uri` for the given issuer.
Args:
issuer: the issuer.
Returns:
The `jwks_uri` that is either statically configured or retrieved via
OpenId discovery. None is returned when the issuer is unknown or the
OpenId... | python | {
"resource": ""
} |
q8651 | JwksSupplier.supply | train | def supply(self, issuer):
"""Supplies the `Json Web Key Set` for the given issuer.
Args:
issuer: the issuer.
Returns:
The successfully retrieved Json Web Key Set. None is returned if the
issuer is unknown or the retrieval process fails.
Raises:
... | python | {
"resource": ""
} |
q8652 | KnownLabels.matches | train | def matches(self, desc):
"""Determines if a given label descriptor matches this enum instance
Args:
desc (:class:`endpoints_management.gen.servicemanagement_v1_messages.LabelDescriptor`):
the instance to test
Return:
`True` if desc is supported, otherwise `F... | python | {
"resource": ""
} |
q8653 | KnownLabels.do_labels_update | train | def do_labels_update(self, info, labels):
"""Updates a dictionary of labels using the assigned update_op_func
Args:
info (:class:`endpoints_management.control.report_request.Info`): the
info instance to update
labels (dict[string[string]]): the labels dictionary
... | python | {
"resource": ""
} |
q8654 | KnownLabels.is_supported | train | def is_supported(cls, desc):
"""Determines if the given label descriptor is supported.
Args:
desc (:class:`endpoints_management.gen.servicemanagement_v1_messages.LabelDescriptor`):
the label descriptor to test
Return:
`True` if desc is supported, otherwise `F... | python | {
"resource": ""
} |
q8655 | extract_report_spec | train | def extract_report_spec(
service,
label_is_supported=label_descriptor.KnownLabels.is_supported,
metric_is_supported=metric_descriptor.KnownMetrics.is_supported):
"""Obtains the used logs, metrics and labels from a service.
label_is_supported and metric_is_supported are filter functions ... | python | {
"resource": ""
} |
q8656 | MethodRegistry._extract_auth_config | train | def _extract_auth_config(self):
"""Obtains the authentication configurations."""
service = self._service
if not service.authentication:
return {}
auth_infos = {}
for auth_rule in service.authentication.rules:
selector = auth_rule.selector
pro... | python | {
"resource": ""
} |
q8657 | MethodRegistry._extract_methods | train | def _extract_methods(self):
"""Obtains the methods used in the service."""
service = self._service
all_urls = set()
urls_with_options = set()
if not service.http:
return
for rule in service.http.rules:
http_method, url = _detect_pattern_option(rule... | python | {
"resource": ""
} |
q8658 | fetch_service_config | train | def fetch_service_config(service_name=None, service_version=None):
"""Fetches the service config from Google Service Management API.
Args:
service_name: the service name. When this argument is unspecified, this
method uses the value of the "SERVICE_NAME" environment variable as the
servic... | python | {
"resource": ""
} |
q8659 | add_all | train | def add_all(application, project_id, control_client,
loader=service.Loaders.FROM_SERVICE_MANAGEMENT):
"""Adds all endpoints middleware to a wsgi application.
Sets up application to use all default endpoints middleware.
Example:
>>> application = MyWsgiApp() # an existing WSGI applicati... | python | {
"resource": ""
} |
q8660 | _sign_operation | train | def _sign_operation(op):
"""Obtains a signature for an operation in a ReportRequest.
Args:
op (:class:`endpoints_management.gen.servicecontrol_v1_messages.Operation`): an
operation used in a `ReportRequest`
Returns:
string: a unique signature for that operation
"""
md5 = has... | python | {
"resource": ""
} |
q8661 | ReportingRules.from_known_inputs | train | def from_known_inputs(cls, logs=None, metric_names=None, label_names=None):
"""An alternate constructor that assumes known metrics and labels.
This differs from the default constructor in that the metrics and labels
are iterables of names of 'known' metrics and labels respectively. The
... | python | {
"resource": ""
} |
q8662 | Info._as_log_entry | train | def _as_log_entry(self, name, now):
"""Makes a `LogEntry` from this instance for the given log_name.
Args:
rules (:class:`ReportingRules`): determines what labels, metrics and
logs to include in the report request.
now (:class:`datetime.DateTime`): the current time
... | python | {
"resource": ""
} |
q8663 | Info.as_report_request | train | def as_report_request(self, rules, timer=datetime.utcnow):
"""Makes a `ServicecontrolServicesReportRequest` from this instance
Args:
rules (:class:`ReportingRules`): determines what labels, metrics and
logs to include in the report request.
timer: a function that determi... | python | {
"resource": ""
} |
q8664 | Aggregator.clear | train | def clear(self):
"""Clears the cache."""
if self._cache is None:
return _NO_RESULTS
if self._cache is not None:
with self._cache as k:
res = [x.as_operation() for x in k.values()]
k.clear()
k.out_deque.clear()
... | python | {
"resource": ""
} |
q8665 | Aggregator.report | train | def report(self, req):
"""Adds a report request to the cache.
Returns ``None`` if it could not be aggregated, and callers need to
send the request to the server, otherwise it returns ``CACHED_OK``.
Args:
req (:class:`sc_messages.ReportRequest`): the request
to b... | python | {
"resource": ""
} |
q8666 | convert_response | train | def convert_response(allocate_quota_response, project_id):
"""Computes a http status code and message `AllocateQuotaResponse`
The return value a tuple (code, message) where
code: is the http status code
message: is the message to return
Args:
allocate_quota_response (:class:`endpoints_mana... | python | {
"resource": ""
} |
q8667 | sign | train | def sign(allocate_quota_request):
"""Obtains a signature for an operation in a `AllocateQuotaRequest`
Args:
op (:class:`endpoints_management.gen.servicecontrol_v1_messages.Operation`): an
operation used in a `AllocateQuotaRequest`
Returns:
string: a secure hash generated from the op... | python | {
"resource": ""
} |
q8668 | Info.as_allocate_quota_request | train | def as_allocate_quota_request(self, timer=datetime.utcnow):
"""Makes a `ServicecontrolServicesAllocateQuotaRequest` from this instance
Returns:
a ``ServicecontrolServicesAllocateQuotaRequest``
Raises:
ValueError: if the fields in this instance are insufficient to
... | python | {
"resource": ""
} |
q8669 | add_route | train | def add_route(app_or_blueprint, fn, context=default_context):
"""
a decorator that adds a transmute route to the application
"""
transmute_func = TransmuteFunction(
fn,
args_not_from_request=["request"]
)
handler = create_handler(transmute_func, context=context)
get_swagger_s... | python | {
"resource": ""
} |
q8670 | KnownMetrics.matches | train | def matches(self, desc):
"""Determines if a given metric descriptor matches this enum instance
Args:
desc (:class:`endpoints_management.gen.servicecontrol_v1_messages.MetricDescriptor`): the
instance to test
Return:
`True` if desc is supported, otherwise `Fa... | python | {
"resource": ""
} |
q8671 | KnownMetrics.do_operation_update | train | def do_operation_update(self, info, an_op):
"""Updates an operation using the assigned update_op_func
Args:
info: (:class:`endpoints_management.control.report_request.Info`): the
info instance to update
an_op: (:class:`endpoints_management.control.report_request.Info... | python | {
"resource": ""
} |
q8672 | KnownMetrics.is_supported | train | def is_supported(cls, desc):
"""Determines if the given metric descriptor is supported.
Args:
desc (:class:`endpoints_management.gen.servicecontrol_v1_messages.MetricDescriptor`): the
metric descriptor to test
Return:
`True` if desc is supported, otherwise `F... | python | {
"resource": ""
} |
q8673 | add_dict_to_hash | train | def add_dict_to_hash(a_hash, a_dict):
"""Adds `a_dict` to `a_hash`
Args:
a_hash (`Hash`): the secure hash, e.g created by hashlib.md5
a_dict (dict[string, [string]]): the dictionary to add to the hash
"""
if a_dict is None:
return
for k, v in a_dict.items():
a_hash.up... | python | {
"resource": ""
} |
q8674 | create_swagger_json_handler | train | def create_swagger_json_handler(app, **kwargs):
"""
Create a handler that returns the swagger definition
for an application.
This method assumes the application is using the
TransmuteUrlDispatcher as the router.
"""
spec = get_swagger_spec(app)
_add_blueprint_specs(app, spec)
spec_d... | python | {
"resource": ""
} |
q8675 | FQDN.absolute | train | def absolute(self):
"""
The FQDN as a string in absolute form
"""
if not self.is_valid:
raise ValueError('invalid FQDN `{0}`'.format(self.fqdn))
if self.is_valid_absolute:
return self.fqdn
return '{0}.'.format(self.fqdn) | python | {
"resource": ""
} |
q8676 | FQDN.relative | train | def relative(self):
"""
The FQDN as a string in relative form
"""
if not self.is_valid:
raise ValueError('invalid FQDN `{0}`'.format(self.fqdn))
if self.is_valid_absolute:
return self.fqdn[:-1]
return self.fqdn | python | {
"resource": ""
} |
q8677 | PipedGzipReader._raise_if_error | train | def _raise_if_error(self):
"""
Raise IOError if process is not running anymore and the
exit code is nonzero.
"""
retcode = self.process.poll()
if retcode is not None and retcode != 0:
message = self._stderr.read().strip()
raise IOError(message) | python | {
"resource": ""
} |
q8678 | MAB.run | train | def run(self, trials=100, strategy=None, parameters=None):
'''
Run MAB test with T trials.
Parameters
----------
trials : int
Number of trials to run.
strategy : str
Name of selected strategy.
parameters : dict
Parameters for s... | python | {
"resource": ""
} |
q8679 | MAB._run | train | def _run(self, strategy, parameters=None):
'''
Run single trial of MAB strategy.
Parameters
----------
strategy : function
parameters : dict
Returns
-------
None
'''
choice = self.run_strategy(strategy, parameters)
self.c... | python | {
"resource": ""
} |
q8680 | MAB.bayesian | train | def bayesian(self, params=None):
'''
Run the Bayesian Bandit algorithm which utilizes a beta distribution
for exploration and exploitation.
Parameters
----------
params : None
For API consistency, this function can take a parameters argument,
but ... | python | {
"resource": ""
} |
q8681 | MAB.softmax | train | def softmax(self, params):
'''
Run the softmax selection strategy.
Parameters
----------
Params : dict
Tau
Returns
-------
int
Index of chosen bandit
'''
default_tau = 0.1
if params and type(params) == di... | python | {
"resource": ""
} |
q8682 | MAB.ucb | train | def ucb(self, params=None):
'''
Run the upper confidence bound MAB selection strategy.
This is the UCB1 algorithm described in
https://homes.di.unimi.it/~cesabian/Pubblicazioni/ml-02.pdf
Parameters
----------
params : None
For API consistency, this f... | python | {
"resource": ""
} |
q8683 | MAB.best | train | def best(self):
'''
Return current 'best' choice of bandit.
Returns
-------
int
Index of bandit
'''
if len(self.choices) < 1:
print('slots: No trials run so far.')
return None
else:
return np.argmax(self.wi... | python | {
"resource": ""
} |
q8684 | MAB.est_payouts | train | def est_payouts(self):
'''
Calculate current estimate of average payout for each bandit.
Returns
-------
array of floats or None
'''
if len(self.choices) < 1:
print('slots: No trials run so far.')
return None
else:
ret... | python | {
"resource": ""
} |
q8685 | MAB.regret | train | def regret(self):
'''
Calculate expected regret, where expected regret is
maximum optimal reward - sum of collected rewards, i.e.
expected regret = T*max_k(mean_k) - sum_(t=1-->T) (reward_t)
Returns
-------
float
'''
return (sum(self.pulls)*np.m... | python | {
"resource": ""
} |
q8686 | MAB.crit_met | train | def crit_met(self):
'''
Determine if stopping criterion has been met.
Returns
-------
bool
'''
if True in (self.pulls < 3):
return False
else:
return self.criteria[self.criterion](self.stop_value) | python | {
"resource": ""
} |
q8687 | MAB.regret_met | train | def regret_met(self, threshold=None):
'''
Determine if regret criterion has been met.
Parameters
----------
threshold : float
Returns
-------
bool
'''
if not threshold:
return self.regret() <= self.stop_value
elif sel... | python | {
"resource": ""
} |
q8688 | MAB.online_trial | train | def online_trial(self, bandit=None, payout=None, strategy='eps_greedy',
parameters=None):
'''
Update the bandits with the results of the previous live, online trial.
Next run a the selection algorithm. If the stopping criteria is
met, return the best arm esti... | python | {
"resource": ""
} |
q8689 | MAB.update | train | def update(self, bandit, payout):
'''
Update bandit trials and payouts for given bandit.
Parameters
----------
bandit : int
Bandit index
payout : float
Returns
-------
None
'''
self.choices.append(bandit)
self... | python | {
"resource": ""
} |
q8690 | Bandits.pull | train | def pull(self, i):
'''
Return the payout from a single pull of the bandit i's arm.
Parameters
----------
i : int
Index of bandit.
Returns
-------
float or None
'''
if self.live:
if len(self.payouts[i]) > 0:
... | python | {
"resource": ""
} |
q8691 | click_table_printer | train | def click_table_printer(headers, _filter, data):
"""Generate space separated output for click commands."""
_filter = [h.lower() for h in _filter] + [h.upper() for h in _filter]
headers = [h for h in headers if not _filter or h in _filter]
# Maximum header width
header_widths = [len(h) for h in heade... | python | {
"resource": ""
} |
q8692 | calculate_hash_of_dir | train | def calculate_hash_of_dir(directory, file_list=None):
"""Calculate hash of directory."""
md5_hash = md5()
if not os.path.exists(directory):
return -1
try:
for subdir, dirs, files in os.walk(directory):
for _file in files:
file_path = os.path.join(subdir, _fil... | python | {
"resource": ""
} |
q8693 | calculate_job_input_hash | train | def calculate_job_input_hash(job_spec, workflow_json):
"""Calculate md5 hash of job specification and workflow json."""
if 'workflow_workspace' in job_spec:
del job_spec['workflow_workspace']
job_md5_buffer = md5()
job_md5_buffer.update(json.dumps(job_spec).encode('utf-8'))
job_md5_buffer.up... | python | {
"resource": ""
} |
q8694 | calculate_file_access_time | train | def calculate_file_access_time(workflow_workspace):
"""Calculate access times of files in workspace."""
access_times = {}
for subdir, dirs, files in os.walk(workflow_workspace):
for file in files:
file_path = os.path.join(subdir, file)
access_times[file_path] = os.stat(file_p... | python | {
"resource": ""
} |
q8695 | copy_openapi_specs | train | def copy_openapi_specs(output_path, component):
"""Copy generated and validated openapi specs to reana-commons module."""
if component == 'reana-server':
file = 'reana_server.json'
elif component == 'reana-workflow-controller':
file = 'reana_workflow_controller.json'
elif component == 'r... | python | {
"resource": ""
} |
q8696 | get_workflow_status_change_verb | train | def get_workflow_status_change_verb(status):
"""Give the correct verb conjugation depending on status tense.
:param status: String which represents the status the workflow changed to.
"""
verb = ''
if status.endswith('ing'):
verb = 'is'
elif status.endswith('ed'):
verb = 'has be... | python | {
"resource": ""
} |
q8697 | build_progress_message | train | def build_progress_message(total=None,
running=None,
finished=None,
failed=None,
cached=None):
"""Build the progress message with correct formatting."""
progress_message = {}
if total:
progres... | python | {
"resource": ""
} |
q8698 | build_caching_info_message | train | def build_caching_info_message(job_spec,
job_id,
workflow_workspace,
workflow_json,
result_path):
"""Build the caching info message with correct formatting."""
caching_info_message = {
... | python | {
"resource": ""
} |
q8699 | get_workspace_disk_usage | train | def get_workspace_disk_usage(workspace, summarize=False):
"""Retrieve disk usage information of a workspace."""
command = ['du', '-h']
if summarize:
command.append('-s')
else:
command.append('-a')
command.append(workspace)
disk_usage_info = subprocess.check_output(command).decode... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.