repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
cloudendpoints/endpoints-management-python | endpoints_management/control/check_request.py | Aggregator.clear | def clear(self):
"""Clears this instance's cache."""
if self._cache is not None:
with self._cache as c:
c.clear()
c.out_deque.clear() | python | def clear(self):
"""Clears this instance's cache."""
if self._cache is not None:
with self._cache as c:
c.clear()
c.out_deque.clear() | [
"def",
"clear",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cache",
"is",
"not",
"None",
":",
"with",
"self",
".",
"_cache",
"as",
"c",
":",
"c",
".",
"clear",
"(",
")",
"c",
".",
"out_deque",
".",
"clear",
"(",
")"
] | Clears this instance's cache. | [
"Clears",
"this",
"instance",
"s",
"cache",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/check_request.py#L369-L374 |
cloudendpoints/endpoints-management-python | endpoints_management/control/check_request.py | Aggregator.add_response | def add_response(self, req, resp):
"""Adds the response from sending to `req` to this instance's cache.
Args:
req (`ServicecontrolServicesCheckRequest`): the request
resp (CheckResponse): the response from sending the request
"""
if self._cache is None:
r... | python | def add_response(self, req, resp):
"""Adds the response from sending to `req` to this instance's cache.
Args:
req (`ServicecontrolServicesCheckRequest`): the request
resp (CheckResponse): the response from sending the request
"""
if self._cache is None:
r... | [
"def",
"add_response",
"(",
"self",
",",
"req",
",",
"resp",
")",
":",
"if",
"self",
".",
"_cache",
"is",
"None",
":",
"return",
"signature",
"=",
"sign",
"(",
"req",
".",
"checkRequest",
")",
"with",
"self",
".",
"_cache",
"as",
"c",
":",
"now",
"... | Adds the response from sending to `req` to this instance's cache.
Args:
req (`ServicecontrolServicesCheckRequest`): the request
resp (CheckResponse): the response from sending the request | [
"Adds",
"the",
"response",
"from",
"sending",
"to",
"req",
"to",
"this",
"instance",
"s",
"cache",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/check_request.py#L376-L399 |
cloudendpoints/endpoints-management-python | endpoints_management/control/check_request.py | Aggregator.check | 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 | 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... | [
"def",
"check",
"(",
"self",
",",
"req",
")",
":",
"if",
"self",
".",
"_cache",
"is",
"None",
":",
"return",
"None",
"# no cache, send request now",
"if",
"not",
"isinstance",
"(",
"req",
",",
"sc_messages",
".",
"ServicecontrolServicesCheckRequest",
")",
":",... | 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.
Cache Hit; response ha... | [
"Determine",
"if",
"req",
"is",
"in",
"this",
"instances",
"cache",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/check_request.py#L401-L467 |
cloudendpoints/endpoints-management-python | endpoints_management/control/timestamp.py | compare | 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 | 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:... | [
"def",
"compare",
"(",
"a",
",",
"b",
")",
":",
"a_is_text",
"=",
"isinstance",
"(",
"a",
",",
"basestring",
")",
"b_is_text",
"=",
"isinstance",
"(",
"b",
",",
"basestring",
")",
"if",
"type",
"(",
"a",
")",
"!=",
"type",
"(",
"b",
")",
"and",
"... | 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:
int: -1 if a < b, 0... | [
"Compares",
"two",
"timestamps",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/timestamp.py#L38-L73 |
cloudendpoints/endpoints-management-python | endpoints_management/control/timestamp.py | to_rfc3339 | 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 | 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... | [
"def",
"to_rfc3339",
"(",
"timestamp",
")",
":",
"if",
"isinstance",
"(",
"timestamp",
",",
"datetime",
".",
"datetime",
")",
":",
"timestamp",
"=",
"timestamp",
"-",
"_EPOCH_START",
"if",
"not",
"isinstance",
"(",
"timestamp",
",",
"datetime",
".",
"timedel... | 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 is always Z-normalized. Examples... | [
"Converts",
"timestamp",
"to",
"an",
"RFC",
"3339",
"date",
"string",
"format",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/timestamp.py#L76-L102 |
cloudendpoints/endpoints-management-python | endpoints_management/control/timestamp.py | from_rfc3339 | 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 | 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... | [
"def",
"from_rfc3339",
"(",
"rfc3339_text",
",",
"with_nanos",
"=",
"False",
")",
":",
"timestamp",
"=",
"strict_rfc3339",
".",
"rfc3339_to_timestamp",
"(",
"rfc3339_text",
")",
"result",
"=",
"datetime",
".",
"datetime",
".",
"utcfromtimestamp",
"(",
"timestamp",... | 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 the second field represents the possible nanosecond
... | [
"Parse",
"a",
"RFC",
"3339",
"date",
"string",
"format",
"to",
"datetime",
".",
"date",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/timestamp.py#L105-L133 |
cloudendpoints/endpoints-management-python | endpoints_management/control/operation.py | Info.as_operation | 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 | 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),
... | [
"def",
"as_operation",
"(",
"self",
",",
"timer",
"=",
"datetime",
".",
"utcnow",
")",
":",
"now",
"=",
"timer",
"(",
")",
"op",
"=",
"sc_messages",
".",
"Operation",
"(",
"endTime",
"=",
"timestamp",
".",
"to_rfc3339",
"(",
"now",
")",
",",
"startTime... | Makes an ``Operation`` from this instance.
Returns:
an ``Operation`` | [
"Makes",
"an",
"Operation",
"from",
"this",
"instance",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/operation.py#L107-L127 |
cloudendpoints/endpoints-management-python | endpoints_management/control/operation.py | Aggregator.as_operation | 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 | 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... | [
"def",
"as_operation",
"(",
"self",
")",
":",
"result",
"=",
"encoding",
".",
"CopyProtoMessage",
"(",
"self",
".",
"_op",
")",
"names",
"=",
"sorted",
"(",
"self",
".",
"_metric_values_by_name_then_sign",
".",
"keys",
"(",
")",
")",
"for",
"name",
"in",
... | Obtains a single `Operation` representing this instances contents.
Returns:
:class:`endpoints_management.gen.servicecontrol_v1_messages.Operation` | [
"Obtains",
"a",
"single",
"Operation",
"representing",
"this",
"instances",
"contents",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/operation.py#L162-L175 |
cloudendpoints/endpoints-management-python | endpoints_management/control/operation.py | Aggregator.add | 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 | 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:
... | [
"def",
"add",
"(",
"self",
",",
"other_op",
")",
":",
"self",
".",
"_op",
".",
"logEntries",
".",
"extend",
"(",
"other_op",
".",
"logEntries",
")",
"self",
".",
"_merge_timestamps",
"(",
"other_op",
")",
"self",
".",
"_merge_metric_values",
"(",
"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:
other_op (
class:`endp... | [
"Combines",
"other_op",
"with",
"the",
"operation",
"held",
"by",
"this",
"aggregator",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/operation.py#L177-L192 |
cloudendpoints/endpoints-management-python | endpoints_management/control/distribution.py | create_exponential | 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 | 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... | [
"def",
"create_exponential",
"(",
"num_finite_buckets",
",",
"growth_factor",
",",
"scale",
")",
":",
"if",
"num_finite_buckets",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"_BAD_NUM_FINITE_BUCKETS",
")",
"if",
"growth_factor",
"<=",
"1.0",
":",
"raise",
"ValueEr... | 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 scale
Return:
:class:`endpoints_management.gen.servicecontrol_v1_... | [
"Creates",
"a",
"new",
"instance",
"of",
"distribution",
"with",
"exponential",
"buckets"
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/distribution.py#L45-L70 |
cloudendpoints/endpoints-management-python | endpoints_management/control/distribution.py | create_linear | 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 | 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:
... | [
"def",
"create_linear",
"(",
"num_finite_buckets",
",",
"width",
",",
"offset",
")",
":",
"if",
"num_finite_buckets",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"_BAD_NUM_FINITE_BUCKETS",
")",
"if",
"width",
"<=",
"0.0",
":",
"raise",
"ValueError",
"(",
"_BAD... | 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:
:class:`endpoints_management.gen.servicecontrol_v1_mes... | [
"Creates",
"a",
"new",
"instance",
"of",
"distribution",
"with",
"linear",
"buckets",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/distribution.py#L73-L96 |
cloudendpoints/endpoints-management-python | endpoints_management/control/distribution.py | create_explicit | 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 | 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... | [
"def",
"create_explicit",
"(",
"bounds",
")",
":",
"safe_bounds",
"=",
"sorted",
"(",
"float",
"(",
"x",
")",
"for",
"x",
"in",
"bounds",
")",
"if",
"len",
"(",
"safe_bounds",
")",
"!=",
"len",
"(",
"set",
"(",
"safe_bounds",
")",
")",
":",
"raise",
... | 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_messages.Distribution`
Raises:
... | [
"Creates",
"a",
"new",
"instance",
"of",
"distribution",
"with",
"explicit",
"buckets",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/distribution.py#L99-L118 |
cloudendpoints/endpoints-management-python | endpoints_management/control/distribution.py | add_sample | 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 | 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... | [
"def",
"add_sample",
"(",
"a_float",
",",
"dist",
")",
":",
"dist_type",
",",
"_",
"=",
"_detect_bucket_option",
"(",
"dist",
")",
"if",
"dist_type",
"==",
"u'exponentialBuckets'",
":",
"_update_general_statistics",
"(",
"a_float",
",",
"dist",
")",
"_update_exp... | 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 have known bucket options defined
... | [
"Adds",
"a_float",
"to",
"dist",
"updating",
"its",
"existing",
"buckets",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/distribution.py#L121-L145 |
cloudendpoints/endpoints-management-python | endpoints_management/control/distribution.py | merge | 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 | 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`):
... | [
"def",
"merge",
"(",
"prior",
",",
"latest",
")",
":",
"if",
"not",
"_buckets_nearly_equal",
"(",
"prior",
",",
"latest",
")",
":",
"_logger",
".",
"error",
"(",
"u'Bucket options do not match. From %s To: %s'",
",",
"prior",
",",
"latest",
")",
"raise",
"Valu... | 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`):
an instance
latest (:cl... | [
"Merge",
"prior",
"into",
"latest",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/distribution.py#L148-L194 |
cloudendpoints/endpoints-management-python | endpoints_management/control/distribution.py | _buckets_nearly_equal | 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 | 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
... | [
"def",
"_buckets_nearly_equal",
"(",
"a_dist",
",",
"b_dist",
")",
":",
"a_type",
",",
"a_buckets",
"=",
"_detect_bucket_option",
"(",
"a_dist",
")",
"b_type",
",",
"b_buckets",
"=",
"_detect_bucket_option",
"(",
"b_dist",
")",
"if",
"a_type",
"!=",
"b_type",
... | 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
False | [
"Determines",
"whether",
"two",
"Distributions",
"are",
"nearly",
"equal",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/distribution.py#L242-L265 |
cloudendpoints/endpoints-management-python | endpoints_management/control/distribution.py | _update_general_statistics | 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 | 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:... | [
"def",
"_update_general_statistics",
"(",
"a_float",
",",
"dist",
")",
":",
"if",
"not",
"dist",
".",
"count",
":",
"dist",
".",
"count",
"=",
"1",
"dist",
".",
"maximum",
"=",
"a_float",
"dist",
".",
"minimum",
"=",
"a_float",
"dist",
".",
"mean",
"="... | 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 | [
"Adds",
"a_float",
"to",
"distribution",
"updating",
"the",
"statistics",
"fields",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/distribution.py#L268-L292 |
cloudendpoints/endpoints-management-python | endpoints_management/control/distribution.py | _update_exponential_bucket_count | 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 | 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... | [
"def",
"_update_exponential_bucket_count",
"(",
"a_float",
",",
"dist",
")",
":",
"buckets",
"=",
"dist",
".",
"exponentialBuckets",
"if",
"buckets",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"_BAD_UNSET_BUCKETS",
"%",
"(",
"u'exponential buckets'",
")",
")",... | 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:
ValueError: if `dist` does not already have exponential buckets defi... | [
"Adds",
"a_float",
"to",
"dist",
"updating",
"its",
"exponential",
"buckets",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/distribution.py#L299-L327 |
cloudendpoints/endpoints-management-python | endpoints_management/control/distribution.py | _update_linear_bucket_count | 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 | 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... | [
"def",
"_update_linear_bucket_count",
"(",
"a_float",
",",
"dist",
")",
":",
"buckets",
"=",
"dist",
".",
"linearBuckets",
"if",
"buckets",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"_BAD_UNSET_BUCKETS",
"%",
"(",
"u'linear buckets'",
")",
")",
"bucket_coun... | 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 `dist` does not already have linear buckets defined
... | [
"Adds",
"a_float",
"to",
"dist",
"updating",
"the",
"its",
"linear",
"buckets",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/distribution.py#L330-L360 |
cloudendpoints/endpoints-management-python | endpoints_management/control/distribution.py | _update_explicit_bucket_count | 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 | 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... | [
"def",
"_update_explicit_bucket_count",
"(",
"a_float",
",",
"dist",
")",
":",
"buckets",
"=",
"dist",
".",
"explicitBuckets",
"if",
"buckets",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"_BAD_UNSET_BUCKETS",
"%",
"(",
"u'explicit buckets'",
")",
")",
"bucke... | 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 `dist` does not already have explict buckets defined
... | [
"Adds",
"a_float",
"to",
"dist",
"updating",
"its",
"explicit",
"buckets",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/distribution.py#L363-L382 |
cloudendpoints/endpoints-management-python | endpoints_management/control/vendor/py3/sched.py | scheduler.enterabs | 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 | 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(... | [
"def",
"enterabs",
"(",
"self",
",",
"time",
",",
"priority",
",",
"action",
",",
"argument",
"=",
"(",
")",
",",
"kwargs",
"=",
"_sentinel",
")",
":",
"if",
"kwargs",
"is",
"_sentinel",
":",
"kwargs",
"=",
"{",
"}",
"event",
"=",
"Event",
"(",
"ti... | 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. | [
"Enter",
"a",
"new",
"event",
"in",
"the",
"queue",
"at",
"an",
"absolute",
"time",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/vendor/py3/sched.py#L71-L83 |
cloudendpoints/endpoints-management-python | endpoints_management/control/vendor/py3/sched.py | scheduler.enter | 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 | 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) | [
"def",
"enter",
"(",
"self",
",",
"delay",
",",
"priority",
",",
"action",
",",
"argument",
"=",
"(",
")",
",",
"kwargs",
"=",
"_sentinel",
")",
":",
"time",
"=",
"self",
".",
"timefunc",
"(",
")",
"+",
"delay",
"return",
"self",
".",
"enterabs",
"... | A variant that specifies the time as a relative time.
This is actually the more commonly used interface. | [
"A",
"variant",
"that",
"specifies",
"the",
"time",
"as",
"a",
"relative",
"time",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/vendor/py3/sched.py#L85-L92 |
cloudendpoints/endpoints-management-python | endpoints_management/control/vendor/py3/sched.py | scheduler.cancel | 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 | 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) | [
"def",
"cancel",
"(",
"self",
",",
"event",
")",
":",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_queue",
".",
"remove",
"(",
"event",
")",
"heapq",
".",
"heapify",
"(",
"self",
".",
"_queue",
")"
] | 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. | [
"Remove",
"an",
"event",
"from",
"the",
"queue",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/vendor/py3/sched.py#L94-L103 |
cloudendpoints/endpoints-management-python | endpoints_management/control/vendor/py3/sched.py | scheduler.run | def run(self, blocking=True):
"""Execute events until the queue is empty.
If blocking is False executes the scheduled events due to
expire soonest (if any) and then return the deadline of the
next scheduled call in the scheduler.
When there is a positive delay until the first ev... | python | def run(self, blocking=True):
"""Execute events until the queue is empty.
If blocking is False executes the scheduled events due to
expire soonest (if any) and then return the deadline of the
next scheduled call in the scheduler.
When there is a positive delay until the first ev... | [
"def",
"run",
"(",
"self",
",",
"blocking",
"=",
"True",
")",
":",
"# localize variable access to minimize overhead",
"# and to improve thread safety",
"lock",
"=",
"self",
".",
"_lock",
"q",
"=",
"self",
".",
"_queue",
"delayfunc",
"=",
"self",
".",
"delayfunc",
... | Execute events until the queue is empty.
If blocking is False executes the scheduled events due to
expire soonest (if any) and then return the deadline of the
next scheduled call in the scheduler.
When there is a positive delay until the first event, the
delay function is called... | [
"Execute",
"events",
"until",
"the",
"queue",
"is",
"empty",
".",
"If",
"blocking",
"is",
"False",
"executes",
"the",
"scheduled",
"events",
"due",
"to",
"expire",
"soonest",
"(",
"if",
"any",
")",
"and",
"then",
"return",
"the",
"deadline",
"of",
"the",
... | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/vendor/py3/sched.py#L110-L158 |
cloudendpoints/endpoints-management-python | endpoints_management/control/money.py | check_valid | 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 | 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):
... | [
"def",
"check_valid",
"(",
"money",
")",
":",
"if",
"not",
"isinstance",
"(",
"money",
",",
"sc_messages",
".",
"Money",
")",
":",
"raise",
"ValueError",
"(",
"u'Inputs should be of type %s'",
"%",
"(",
"sc_messages",
".",
"Money",
",",
")",
")",
"currency",... | 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 | [
"Determine",
"if",
"an",
"instance",
"of",
"Money",
"is",
"valid",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/money.py#L40-L60 |
cloudendpoints/endpoints-management-python | endpoints_management/control/money.py | add | 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 | 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... | [
"def",
"add",
"(",
"a",
",",
"b",
",",
"allow_overflow",
"=",
"False",
")",
":",
"for",
"m",
"in",
"(",
"a",
",",
"b",
")",
":",
"if",
"not",
"isinstance",
"(",
"m",
",",
"sc_messages",
".",
"Money",
")",
":",
"raise",
"ValueError",
"(",
"u'Input... | 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: determines if the addition is allowed to overflo... | [
"Adds",
"two",
"instances",
"of",
"Money",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/money.py#L63-L118 |
cloudendpoints/endpoints-management-python | endpoints_management/control/money.py | _sign_of | 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 | 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 ... | [
"def",
"_sign_of",
"(",
"money",
")",
":",
"units",
"=",
"money",
".",
"units",
"nanos",
"=",
"money",
".",
"nanos",
"if",
"units",
":",
"if",
"units",
">",
"0",
":",
"return",
"1",
"elif",
"units",
"<",
"0",
":",
"return",
"-",
"1",
"if",
"nanos... | 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 | [
"Determines",
"the",
"amount",
"sign",
"of",
"a",
"money",
"instance"
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/money.py#L133-L156 |
cloudendpoints/endpoints-management-python | endpoints_management/auth/tokens.py | _check_jwt_claims | 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 | 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 ... | [
"def",
"_check_jwt_claims",
"(",
"jwt_claims",
")",
":",
"current_time",
"=",
"time",
".",
"time",
"(",
")",
"expiration",
"=",
"jwt_claims",
"[",
"u\"exp\"",
"]",
"if",
"not",
"isinstance",
"(",
"expiration",
",",
"INT_TYPES",
")",
":",
"raise",
"suppliers"... | 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 is
equal to or after the time identifi... | [
"Checks",
"whether",
"the",
"JWT",
"claims",
"should",
"be",
"accepted",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/auth/tokens.py#L169-L199 |
cloudendpoints/endpoints-management-python | endpoints_management/auth/tokens.py | _verify_required_claims_exist | 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 | 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... | [
"def",
"_verify_required_claims_exist",
"(",
"jwt_claims",
")",
":",
"for",
"claim_name",
"in",
"[",
"u\"aud\"",
",",
"u\"exp\"",
",",
"u\"iss\"",
",",
"u\"sub\"",
"]",
":",
"if",
"claim_name",
"not",
"in",
"jwt_claims",
":",
"raise",
"suppliers",
".",
"Unauth... | Verifies that the required claims exist.
Args:
jwt_claims: the JWT claims to be verified.
Raises:
UnauthenticatedException: if some claim doesn't exist. | [
"Verifies",
"that",
"the",
"required",
"claims",
"exist",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/auth/tokens.py#L202-L213 |
cloudendpoints/endpoints-management-python | endpoints_management/auth/tokens.py | Authenticator.authenticate | 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 | 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 ... | [
"def",
"authenticate",
"(",
"self",
",",
"auth_token",
",",
"auth_info",
",",
"service_name",
")",
":",
"try",
":",
"jwt_claims",
"=",
"self",
".",
"get_jwt_claims",
"(",
"auth_token",
")",
"except",
"Exception",
"as",
"error",
":",
"raise",
"suppliers",
"."... | 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 constructed UserInfo object representing the identity of the caller.
... | [
"Authenticates",
"the",
"current",
"auth",
"token",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/auth/tokens.py#L54-L100 |
cloudendpoints/endpoints-management-python | endpoints_management/auth/tokens.py | Authenticator.get_jwt_claims | 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 | 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... | [
"def",
"get_jwt_claims",
"(",
"self",
",",
"auth_token",
")",
":",
"def",
"_decode_and_verify",
"(",
")",
":",
"jwt_claims",
"=",
"jwt",
".",
"JWT",
"(",
")",
".",
"unpack",
"(",
"auth_token",
")",
".",
"payload",
"(",
")",
"_verify_required_claims_exist",
... | 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, verify its signature, and check the existence
... | [
"Decodes",
"the",
"auth_token",
"into",
"JWT",
"claims",
"represented",
"as",
"a",
"JSON",
"object",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/auth/tokens.py#L102-L135 |
cloudendpoints/endpoints-management-python | endpoints_management/control/caches.py | create | 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 | 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... | [
"def",
"create",
"(",
"options",
",",
"timer",
"=",
"None",
",",
"use_deque",
"=",
"True",
")",
":",
"if",
"options",
"is",
"None",
":",
"# no options, don't create cache",
"return",
"None",
"if",
"not",
"isinstance",
"(",
"options",
",",
"(",
"CheckOptions"... | 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:`LockedObject`, requiring it to
be accessed in a with state... | [
"Create",
"a",
"cache",
"specified",
"by",
"options"
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/caches.py#L166-L219 |
cloudendpoints/endpoints-management-python | endpoints_management/control/caches.py | to_cache_timer | 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 | 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... | [
"def",
"to_cache_timer",
"(",
"datetime_func",
")",
":",
"if",
"datetime_func",
"is",
"None",
":",
"datetime_func",
"=",
"datetime",
".",
"utcnow",
"def",
"_timer",
"(",
")",
":",
"\"\"\"Return the timestamp since the epoch.\"\"\"",
"return",
"(",
"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 | [
"Converts",
"a",
"datetime_func",
"to",
"a",
"timestamp_func",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/caches.py#L321-L339 |
cloudendpoints/endpoints-management-python | endpoints_management/control/caches.py | DequeOutTTLCache.out_deque | def out_deque(self):
"""The :class:`collections.deque` to which expired items are added."""
self.expire()
expired = {k: v for (k, v) in self._tracking.items() if self.get(k) is None}
for k, v in expired.items():
del self._tracking[k]
self._out_deque.append(v)
... | python | def out_deque(self):
"""The :class:`collections.deque` to which expired items are added."""
self.expire()
expired = {k: v for (k, v) in self._tracking.items() if self.get(k) is None}
for k, v in expired.items():
del self._tracking[k]
self._out_deque.append(v)
... | [
"def",
"out_deque",
"(",
"self",
")",
":",
"self",
".",
"expire",
"(",
")",
"expired",
"=",
"{",
"k",
":",
"v",
"for",
"(",
"k",
",",
"v",
")",
"in",
"self",
".",
"_tracking",
".",
"items",
"(",
")",
"if",
"self",
".",
"get",
"(",
"k",
")",
... | The :class:`collections.deque` to which expired items are added. | [
"The",
":",
"class",
":",
"collections",
".",
"deque",
"to",
"which",
"expired",
"items",
"are",
"added",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/caches.py#L253-L260 |
yunstanford/sanic-transmute | ubuild.py | distribute | 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 | 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... | [
"def",
"distribute",
"(",
"build",
")",
":",
"build",
".",
"packages",
".",
"install",
"(",
"\"wheel\"",
")",
"build",
".",
"packages",
".",
"install",
"(",
"\"twine\"",
")",
"build",
".",
"executables",
".",
"run",
"(",
"[",
"\"python\"",
",",
"\"setup.... | distribute the uranium package | [
"distribute",
"the",
"uranium",
"package"
] | train | https://github.com/yunstanford/sanic-transmute/blob/5040819d0bd6024e257603f69d12984a3b112cf0/ubuild.py#L25-L35 |
cloudendpoints/endpoints-management-python | endpoints_management/control/client.py | use_gae_thread | 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 | 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... | [
"def",
"use_gae_thread",
"(",
")",
":",
"global",
"_THREAD_CLASS",
"# pylint: disable=global-statement",
"try",
":",
"from",
"google",
".",
"appengine",
".",
"api",
".",
"background_thread",
"import",
"background_thread",
"_THREAD_CLASS",
"=",
"background_thread",
".",
... | Makes ``Client``s started after this use the appengine thread class. | [
"Makes",
"Client",
"s",
"started",
"after",
"this",
"use",
"the",
"appengine",
"thread",
"class",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/client.py#L506-L515 |
cloudendpoints/endpoints-management-python | endpoints_management/control/client.py | Client.start | 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 | 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
... | [
"def",
"start",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"_running",
":",
"return",
"self",
".",
"_stopped",
"=",
"False",
"self",
".",
"_running",
"=",
"True",
"self",
".",
"_start_idle_timer",
"(",
")",
"_logger",
... | 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 | [
"Starts",
"processing",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/client.py#L228-L253 |
cloudendpoints/endpoints-management-python | endpoints_management/control/client.py | Client.stop | def stop(self):
"""Halts processing
This will lead to the reports being flushed, the caches being cleared
and a stop to the current processing thread.
"""
with self._lock:
if self._stopped:
_logger.debug(u'%s is already stopped', self)
... | python | def stop(self):
"""Halts processing
This will lead to the reports being flushed, the caches being cleared
and a stop to the current processing thread.
"""
with self._lock:
if self._stopped:
_logger.debug(u'%s is already stopped', self)
... | [
"def",
"stop",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"_stopped",
":",
"_logger",
".",
"debug",
"(",
"u'%s is already stopped'",
",",
"self",
")",
"return",
"self",
".",
"_flush_all_reports",
"(",
")",
"self",
".",
... | Halts processing
This will lead to the reports being flushed, the caches being cleared
and a stop to the current processing thread. | [
"Halts",
"processing"
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/client.py#L255-L278 |
cloudendpoints/endpoints-management-python | endpoints_management/control/client.py | Client.check | 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 | 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`... | [
"def",
"check",
"(",
"self",
",",
"check_req",
")",
":",
"self",
".",
"start",
"(",
")",
"res",
"=",
"self",
".",
"_check_aggregator",
".",
"check",
"(",
"check_req",
")",
"if",
"res",
":",
"_logger",
".",
"debug",
"(",
"u'using cached check response for %... | 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``): to be sent to
the servi... | [
"Process",
"a",
"check_request",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/client.py#L280-L316 |
cloudendpoints/endpoints-management-python | endpoints_management/control/client.py | Client.report | 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 | 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... | [
"def",
"report",
"(",
"self",
",",
"report_req",
")",
":",
"self",
".",
"start",
"(",
")",
"# no thread running, run the scheduler to ensure any pending",
"# flush tasks are executed.",
"if",
"self",
".",
"_run_scheduler_directly",
":",
"self",
".",
"_scheduler",
".",
... | 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. | [
"Processes",
"a",
"report",
"request",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/client.py#L340-L360 |
cloudendpoints/endpoints-management-python | endpoints_management/control/metric_value.py | create | 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 | 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 (... | [
"def",
"create",
"(",
"labels",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"if",
"labels",
"is",
"not",
"None",
":",
"kw",
"[",
"u'labels'",
"]",
"=",
"encoding",
".",
"PyValueToMessage",
"(",
"MetricValue",
".",
"LabelsValue",
",",
"labels",
")",
"... | 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 (dict([string, [string]]):
**kw: ... | [
"Constructs",
"a",
"new",
"metric",
"value",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/metric_value.py#L37-L56 |
cloudendpoints/endpoints-management-python | endpoints_management/control/metric_value.py | merge | 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 | 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
... | [
"def",
"merge",
"(",
"metric_kind",
",",
"prior",
",",
"latest",
")",
":",
"prior_type",
",",
"_",
"=",
"_detect_value",
"(",
"prior",
")",
"latest_type",
",",
"_",
"=",
"_detect_value",
"(",
"latest",
")",
"if",
"prior_type",
"!=",
"latest_type",
":",
"... | 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 | [
"Merges",
"prior",
"and",
"latest"
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/metric_value.py#L59-L82 |
cloudendpoints/endpoints-management-python | endpoints_management/control/metric_value.py | update_hash | 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 | 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... | [
"def",
"update_hash",
"(",
"a_hash",
",",
"mv",
")",
":",
"if",
"mv",
".",
"labels",
":",
"signing",
".",
"add_dict_to_hash",
"(",
"a_hash",
",",
"encoding",
".",
"MessageToPyValue",
"(",
"mv",
".",
"labels",
")",
")",
"money_value",
"=",
"mv",
".",
"g... | 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 | [
"Adds",
"mv",
"to",
"a_hash"
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/metric_value.py#L85-L98 |
cloudendpoints/endpoints-management-python | endpoints_management/control/metric_value.py | sign | 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 | 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... | [
"def",
"sign",
"(",
"mv",
")",
":",
"md5",
"=",
"hashlib",
".",
"md5",
"(",
")",
"update_hash",
"(",
"md5",
",",
"mv",
")",
"return",
"md5",
".",
"digest",
"(",
")"
] | 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 | [
"Obtains",
"a",
"signature",
"for",
"a",
"MetricValue"
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/metric_value.py#L101-L113 |
cloudendpoints/endpoints-management-python | endpoints_management/auth/suppliers.py | KeyUriSupplier.supply | 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 | 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... | [
"def",
"supply",
"(",
"self",
",",
"issuer",
")",
":",
"issuer_uri_config",
"=",
"self",
".",
"_issuer_uri_configs",
".",
"get",
"(",
"issuer",
")",
"if",
"not",
"issuer_uri_config",
":",
"# The issuer is unknown.",
"return",
"jwks_uri",
"=",
"issuer_uri_config",
... | 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 discovery fails. | [
"Supplies",
"the",
"jwks_uri",
"for",
"the",
"given",
"issuer",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/auth/suppliers.py#L44-L73 |
cloudendpoints/endpoints-management-python | endpoints_management/auth/suppliers.py | JwksSupplier.supply | 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 | 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:
... | [
"def",
"supply",
"(",
"self",
",",
"issuer",
")",
":",
"def",
"_retrieve_jwks",
"(",
")",
":",
"\"\"\"Retrieve the JWKS from the given jwks_uri when cache misses.\"\"\"",
"jwks_uri",
"=",
"self",
".",
"_key_uri_supplier",
".",
"supply",
"(",
"issuer",
")",
"if",
"no... | 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:
UnauthenticatedException: When this... | [
"Supplies",
"the",
"Json",
"Web",
"Key",
"Set",
"for",
"the",
"given",
"issuer",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/auth/suppliers.py#L90-L131 |
cloudendpoints/endpoints-management-python | endpoints_management/control/label_descriptor.py | KnownLabels.matches | 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 | 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... | [
"def",
"matches",
"(",
"self",
",",
"desc",
")",
":",
"desc_value_type",
"=",
"desc",
".",
"valueType",
"or",
"ValueType",
".",
"STRING",
"# default not parsed",
"return",
"(",
"self",
".",
"label_name",
"==",
"desc",
".",
"key",
"and",
"self",
".",
"value... | 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 `False` | [
"Determines",
"if",
"a",
"given",
"label",
"descriptor",
"matches",
"this",
"enum",
"instance"
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/label_descriptor.py#L249-L262 |
cloudendpoints/endpoints-management-python | endpoints_management/control/label_descriptor.py | KnownLabels.do_labels_update | 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 | 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
... | [
"def",
"do_labels_update",
"(",
"self",
",",
"info",
",",
"labels",
")",
":",
"if",
"self",
".",
"update_label_func",
":",
"self",
".",
"update_label_func",
"(",
"self",
".",
"label_name",
",",
"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
Return:
`True` if desc is supported, ... | [
"Updates",
"a",
"dictionary",
"of",
"labels",
"using",
"the",
"assigned",
"update_op_func"
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/label_descriptor.py#L264-L277 |
cloudendpoints/endpoints-management-python | endpoints_management/control/label_descriptor.py | KnownLabels.is_supported | 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 | 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... | [
"def",
"is_supported",
"(",
"cls",
",",
"desc",
")",
":",
"for",
"l",
"in",
"cls",
":",
"if",
"l",
".",
"matches",
"(",
"desc",
")",
":",
"return",
"True",
"return",
"False"
] | 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 `False` | [
"Determines",
"if",
"the",
"given",
"label",
"descriptor",
"is",
"supported",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/label_descriptor.py#L280-L294 |
cloudendpoints/endpoints-management-python | endpoints_management/control/service.py | extract_report_spec | 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 | 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 ... | [
"def",
"extract_report_spec",
"(",
"service",
",",
"label_is_supported",
"=",
"label_descriptor",
".",
"KnownLabels",
".",
"is_supported",
",",
"metric_is_supported",
"=",
"metric_descriptor",
".",
"KnownMetrics",
".",
"is_supported",
")",
":",
"resource_descs",
"=",
... | Obtains the used logs, metrics and labels from a service.
label_is_supported and metric_is_supported are filter functions used to
determine if label_descriptors or metric_descriptors found in the service
are supported.
Args:
service (:class:`endpoints_management.gen.servicecontrol_v1_messages.S... | [
"Obtains",
"the",
"used",
"logs",
"metrics",
"and",
"labels",
"from",
"a",
"service",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/service.py#L380-L426 |
cloudendpoints/endpoints-management-python | endpoints_management/control/service.py | MethodRegistry._extract_auth_config | 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 | 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... | [
"def",
"_extract_auth_config",
"(",
"self",
")",
":",
"service",
"=",
"self",
".",
"_service",
"if",
"not",
"service",
".",
"authentication",
":",
"return",
"{",
"}",
"auth_infos",
"=",
"{",
"}",
"for",
"auth_rule",
"in",
"service",
".",
"authentication",
... | Obtains the authentication configurations. | [
"Obtains",
"the",
"authentication",
"configurations",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/service.py#L180-L197 |
cloudendpoints/endpoints-management-python | endpoints_management/control/service.py | MethodRegistry._extract_methods | 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 | 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... | [
"def",
"_extract_methods",
"(",
"self",
")",
":",
"service",
"=",
"self",
".",
"_service",
"all_urls",
"=",
"set",
"(",
")",
"urls_with_options",
"=",
"set",
"(",
")",
"if",
"not",
"service",
".",
"http",
":",
"return",
"for",
"rule",
"in",
"service",
... | Obtains the methods used in the service. | [
"Obtains",
"the",
"methods",
"used",
"in",
"the",
"service",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/service.py#L212-L238 |
yunstanford/sanic-transmute | examples/example_attrs_model.py | get_blueprint_params | async def get_blueprint_params(request, left: int, right: int) -> str:
"""
API Description: Multiply, left * right. This will show in the swagger page (localhost:8000/api/v1/).
"""
res = left * right
return "{left}*{right}={res}".format(left=left, right=right, res=res) | python | async def get_blueprint_params(request, left: int, right: int) -> str:
"""
API Description: Multiply, left * right. This will show in the swagger page (localhost:8000/api/v1/).
"""
res = left * right
return "{left}*{right}={res}".format(left=left, right=right, res=res) | [
"async",
"def",
"get_blueprint_params",
"(",
"request",
",",
"left",
":",
"int",
",",
"right",
":",
"int",
")",
"->",
"str",
":",
"res",
"=",
"left",
"*",
"right",
"return",
"\"{left}*{right}={res}\"",
".",
"format",
"(",
"left",
"=",
"left",
",",
"right... | API Description: Multiply, left * right. This will show in the swagger page (localhost:8000/api/v1/). | [
"API",
"Description",
":",
"Multiply",
"left",
"*",
"right",
".",
"This",
"will",
"show",
"in",
"the",
"swagger",
"page",
"(",
"localhost",
":",
"8000",
"/",
"api",
"/",
"v1",
"/",
")",
"."
] | train | https://github.com/yunstanford/sanic-transmute/blob/5040819d0bd6024e257603f69d12984a3b112cf0/examples/example_attrs_model.py#L54-L59 |
cloudendpoints/endpoints-management-python | endpoints_management/config/service_config.py | fetch_service_config | 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 | 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... | [
"def",
"fetch_service_config",
"(",
"service_name",
"=",
"None",
",",
"service_version",
"=",
"None",
")",
":",
"if",
"not",
"service_name",
":",
"service_name",
"=",
"_get_env_var_or_raise",
"(",
"_SERVICE_NAME_ENV_KEY",
")",
"if",
"not",
"service_version",
":",
... | 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
service name, and raises ValueError if the environment variable is unset.
... | [
"Fetches",
"the",
"service",
"config",
"from",
"Google",
"Service",
"Management",
"API",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/config/service_config.py#L46-L78 |
cloudendpoints/endpoints-management-python | endpoints_management/control/wsgi.py | add_all | 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 | 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... | [
"def",
"add_all",
"(",
"application",
",",
"project_id",
",",
"control_client",
",",
"loader",
"=",
"service",
".",
"Loaders",
".",
"FROM_SERVICE_MANAGEMENT",
")",
":",
"return",
"ConfigFetchWrapper",
"(",
"application",
",",
"project_id",
",",
"control_client",
"... | Adds all endpoints middleware to a wsgi application.
Sets up application to use all default endpoints middleware.
Example:
>>> application = MyWsgiApp() # an existing WSGI application
>>>
>>> # the name of the controlled service
>>> service_name = 'my-service-name'
>>>
>>... | [
"Adds",
"all",
"endpoints",
"middleware",
"to",
"a",
"wsgi",
"application",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/wsgi.py#L94-L125 |
cloudendpoints/endpoints-management-python | endpoints_management/control/wsgi.py | _create_authenticator | def _create_authenticator(a_service):
"""Create an instance of :class:`google.auth.tokens.Authenticator`.
Args:
a_service (:class:`endpoints_management.gen.servicemanagement_v1_messages.Service`): a
service instance
"""
if not isinstance(a_service, sm_messages.Service):
raise Valu... | python | def _create_authenticator(a_service):
"""Create an instance of :class:`google.auth.tokens.Authenticator`.
Args:
a_service (:class:`endpoints_management.gen.servicemanagement_v1_messages.Service`): a
service instance
"""
if not isinstance(a_service, sm_messages.Service):
raise Valu... | [
"def",
"_create_authenticator",
"(",
"a_service",
")",
":",
"if",
"not",
"isinstance",
"(",
"a_service",
",",
"sm_messages",
".",
"Service",
")",
":",
"raise",
"ValueError",
"(",
"u\"service is None or not an instance of Service\"",
")",
"authentication",
"=",
"a_serv... | Create an instance of :class:`google.auth.tokens.Authenticator`.
Args:
a_service (:class:`endpoints_management.gen.servicemanagement_v1_messages.Service`): a
service instance | [
"Create",
"an",
"instance",
"of",
":",
"class",
":",
"google",
".",
"auth",
".",
"tokens",
".",
"Authenticator",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/wsgi.py#L658-L688 |
cloudendpoints/endpoints-management-python | endpoints_management/control/report_request.py | _sign_operation | 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 | 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... | [
"def",
"_sign_operation",
"(",
"op",
")",
":",
"md5",
"=",
"hashlib",
".",
"md5",
"(",
")",
"md5",
".",
"update",
"(",
"op",
".",
"consumerId",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"md5",
".",
"update",
"(",
"b'\\x00'",
")",
"md5",
".",
"update... | 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 | [
"Obtains",
"a",
"signature",
"for",
"an",
"operation",
"in",
"a",
"ReportRequest",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/report_request.py#L555-L571 |
cloudendpoints/endpoints-management-python | endpoints_management/control/report_request.py | ReportingRules.from_known_inputs | 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 | 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
... | [
"def",
"from_known_inputs",
"(",
"cls",
",",
"logs",
"=",
"None",
",",
"metric_names",
"=",
"None",
",",
"label_names",
"=",
"None",
")",
":",
"if",
"not",
"metric_names",
":",
"metric_names",
"=",
"(",
")",
"if",
"not",
"label_names",
":",
"label_names",
... | 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
names are used to obtain the metrics and labels from
:class:`endpoints_manageme... | [
"An",
"alternate",
"constructor",
"that",
"assumes",
"known",
"metrics",
"and",
"labels",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/report_request.py#L76-L112 |
cloudendpoints/endpoints-management-python | endpoints_management/control/report_request.py | Info._as_log_entry | 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 | 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
... | [
"def",
"_as_log_entry",
"(",
"self",
",",
"name",
",",
"now",
")",
":",
"# initialize the struct with fields that are always present",
"d",
"=",
"{",
"u'http_response_code'",
":",
"self",
".",
"response_code",
",",
"u'timestamp'",
":",
"time",
".",
"mktime",
"(",
... | 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
Return:
a ``LogEntry`` generated ... | [
"Makes",
"a",
"LogEntry",
"from",
"this",
"instance",
"for",
"the",
"given",
"log_name",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/report_request.py#L293-L342 |
cloudendpoints/endpoints-management-python | endpoints_management/control/report_request.py | Info.as_report_request | 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 | 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... | [
"def",
"as_report_request",
"(",
"self",
",",
"rules",
",",
"timer",
"=",
"datetime",
".",
"utcnow",
")",
":",
"if",
"not",
"self",
".",
"service_name",
":",
"raise",
"ValueError",
"(",
"u'the service name must be set'",
")",
"op",
"=",
"super",
"(",
"Info",... | 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 determines the current time
Return:
a ``ServicecontrolServ... | [
"Makes",
"a",
"ServicecontrolServicesReportRequest",
"from",
"this",
"instance"
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/report_request.py#L344-L393 |
cloudendpoints/endpoints-management-python | endpoints_management/control/report_request.py | Aggregator.flush | def flush(self):
"""Flushes this instance's cache.
The driver of this instance should call this method every
`flush_interval`.
Returns:
list[``ServicecontrolServicesReportRequest``]: corresponding to the
pending cached operations
"""
if self._cach... | python | def flush(self):
"""Flushes this instance's cache.
The driver of this instance should call this method every
`flush_interval`.
Returns:
list[``ServicecontrolServicesReportRequest``]: corresponding to the
pending cached operations
"""
if self._cach... | [
"def",
"flush",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cache",
"is",
"None",
":",
"return",
"_NO_RESULTS",
"with",
"self",
".",
"_cache",
"as",
"c",
":",
"flushed_ops",
"=",
"[",
"x",
".",
"as_operation",
"(",
")",
"for",
"x",
"in",
"c",
".",
... | Flushes this instance's cache.
The driver of this instance should call this method every
`flush_interval`.
Returns:
list[``ServicecontrolServicesReportRequest``]: corresponding to the
pending cached operations | [
"Flushes",
"this",
"instance",
"s",
"cache",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/report_request.py#L449-L475 |
cloudendpoints/endpoints-management-python | endpoints_management/control/report_request.py | Aggregator.clear | 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 | 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()
... | [
"def",
"clear",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cache",
"is",
"None",
":",
"return",
"_NO_RESULTS",
"if",
"self",
".",
"_cache",
"is",
"not",
"None",
":",
"with",
"self",
".",
"_cache",
"as",
"k",
":",
"res",
"=",
"[",
"x",
".",
"as_o... | Clears the cache. | [
"Clears",
"the",
"cache",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/report_request.py#L477-L486 |
cloudendpoints/endpoints-management-python | endpoints_management/control/report_request.py | Aggregator.report | 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 | 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... | [
"def",
"report",
"(",
"self",
",",
"req",
")",
":",
"if",
"self",
".",
"_cache",
"is",
"None",
":",
"return",
"None",
"# no cache, send request now",
"if",
"not",
"isinstance",
"(",
"req",
",",
"sc_messages",
".",
"ServicecontrolServicesReportRequest",
")",
":... | 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 be aggregated
Result:
... | [
"Adds",
"a",
"report",
"request",
"to",
"the",
"cache",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/report_request.py#L488-L531 |
cloudendpoints/endpoints-management-python | endpoints_management/control/quota_request.py | convert_response | 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 | 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... | [
"def",
"convert_response",
"(",
"allocate_quota_response",
",",
"project_id",
")",
":",
"if",
"not",
"allocate_quota_response",
"or",
"not",
"allocate_quota_response",
".",
"allocateErrors",
":",
"return",
"_IS_OK",
"# only allocate_quota the first error for now, as per ESP",
... | 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_management.gen.servicecontrol_v1_messages.AllocateQuotaResponse`):
... | [
"Computes",
"a",
"http",
"status",
"code",
"and",
"message",
"AllocateQuotaResponse"
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/quota_request.py#L82-L107 |
cloudendpoints/endpoints-management-python | endpoints_management/control/quota_request.py | sign | 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 | 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... | [
"def",
"sign",
"(",
"allocate_quota_request",
")",
":",
"if",
"not",
"isinstance",
"(",
"allocate_quota_request",
",",
"sc_messages",
".",
"AllocateQuotaRequest",
")",
":",
"raise",
"ValueError",
"(",
"u'Invalid request'",
")",
"op",
"=",
"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 operation | [
"Obtains",
"a",
"signature",
"for",
"an",
"operation",
"in",
"a",
"AllocateQuotaRequest"
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/quota_request.py#L110-L139 |
cloudendpoints/endpoints-management-python | endpoints_management/control/quota_request.py | Info.as_allocate_quota_request | 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 | 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
... | [
"def",
"as_allocate_quota_request",
"(",
"self",
",",
"timer",
"=",
"datetime",
".",
"utcnow",
")",
":",
"if",
"not",
"self",
".",
"service_name",
":",
"raise",
"ValueError",
"(",
"u'the service name must be set'",
")",
"if",
"not",
"self",
".",
"operation_id",
... | Makes a `ServicecontrolServicesAllocateQuotaRequest` from this instance
Returns:
a ``ServicecontrolServicesAllocateQuotaRequest``
Raises:
ValueError: if the fields in this instance are insufficient to
to create a valid ``ServicecontrolServicesAllocateQuotaRequest`` | [
"Makes",
"a",
"ServicecontrolServicesAllocateQuotaRequest",
"from",
"this",
"instance"
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/quota_request.py#L163-L209 |
cloudendpoints/endpoints-management-python | endpoints_management/control/quota_request.py | Aggregator.flush | def flush(self):
"""Flushes this instance's cache.
The driver of this instance should call this method every
`flush_interval`.
Returns:
list['ServicecontrolServicesAllocateQuotaRequest']: corresponding
to AllocateQuotaRequests that were pending
"""
... | python | def flush(self):
"""Flushes this instance's cache.
The driver of this instance should call this method every
`flush_interval`.
Returns:
list['ServicecontrolServicesAllocateQuotaRequest']: corresponding
to AllocateQuotaRequests that were pending
"""
... | [
"def",
"flush",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cache",
"is",
"None",
":",
"return",
"[",
"]",
"with",
"self",
".",
"_cache",
"as",
"c",
",",
"self",
".",
"_out",
"as",
"out",
":",
"c",
".",
"expire",
"(",
")",
"now",
"=",
"self",
... | Flushes this instance's cache.
The driver of this instance should call this method every
`flush_interval`.
Returns:
list['ServicecontrolServicesAllocateQuotaRequest']: corresponding
to AllocateQuotaRequests that were pending | [
"Flushes",
"this",
"instance",
"s",
"cache",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/quota_request.py#L261-L287 |
cloudendpoints/endpoints-management-python | endpoints_management/control/quota_request.py | Aggregator.clear | def clear(self):
"""Clears this instance's cache."""
if self._cache is not None:
with self._cache as c, self._out as out:
self.in_flush_all = True
c.clear()
out.clear() # pylint: disable=no-member
self.in_flush_all = False | python | def clear(self):
"""Clears this instance's cache."""
if self._cache is not None:
with self._cache as c, self._out as out:
self.in_flush_all = True
c.clear()
out.clear() # pylint: disable=no-member
self.in_flush_all = False | [
"def",
"clear",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cache",
"is",
"not",
"None",
":",
"with",
"self",
".",
"_cache",
"as",
"c",
",",
"self",
".",
"_out",
"as",
"out",
":",
"self",
".",
"in_flush_all",
"=",
"True",
"c",
".",
"clear",
"(",
... | Clears this instance's cache. | [
"Clears",
"this",
"instance",
"s",
"cache",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/quota_request.py#L289-L296 |
cloudendpoints/endpoints-management-python | endpoints_management/control/quota_request.py | Aggregator.add_response | def add_response(self, req, resp):
"""Adds the response from sending to `req` to this instance's cache.
Args:
req (`ServicecontrolServicesAllocateQuotaRequest`): the request
resp (AllocateQuotaResponse): the response from sending the request
"""
if self._cache is Non... | python | def add_response(self, req, resp):
"""Adds the response from sending to `req` to this instance's cache.
Args:
req (`ServicecontrolServicesAllocateQuotaRequest`): the request
resp (AllocateQuotaResponse): the response from sending the request
"""
if self._cache is Non... | [
"def",
"add_response",
"(",
"self",
",",
"req",
",",
"resp",
")",
":",
"if",
"self",
".",
"_cache",
"is",
"None",
":",
"return",
"signature",
"=",
"sign",
"(",
"req",
".",
"allocateQuotaRequest",
")",
"with",
"self",
".",
"_cache",
"as",
"c",
":",
"n... | Adds the response from sending to `req` to this instance's cache.
Args:
req (`ServicecontrolServicesAllocateQuotaRequest`): the request
resp (AllocateQuotaResponse): the response from sending the request | [
"Adds",
"the",
"response",
"from",
"sending",
"to",
"req",
"to",
"this",
"instance",
"s",
"cache",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/quota_request.py#L298-L319 |
yunstanford/sanic-transmute | sanic_transmute/route.py | add_route | 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 | 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... | [
"def",
"add_route",
"(",
"app_or_blueprint",
",",
"fn",
",",
"context",
"=",
"default_context",
")",
":",
"transmute_func",
"=",
"TransmuteFunction",
"(",
"fn",
",",
"args_not_from_request",
"=",
"[",
"\"request\"",
"]",
")",
"handler",
"=",
"create_handler",
"(... | a decorator that adds a transmute route to the application | [
"a",
"decorator",
"that",
"adds",
"a",
"transmute",
"route",
"to",
"the",
"application"
] | train | https://github.com/yunstanford/sanic-transmute/blob/5040819d0bd6024e257603f69d12984a3b112cf0/sanic_transmute/route.py#L6-L18 |
cloudendpoints/endpoints-management-python | endpoints_management/control/metric_descriptor.py | KnownMetrics.matches | 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 | 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... | [
"def",
"matches",
"(",
"self",
",",
"desc",
")",
":",
"return",
"(",
"self",
".",
"metric_name",
"==",
"desc",
".",
"name",
"and",
"self",
".",
"kind",
"==",
"desc",
".",
"metricKind",
"and",
"self",
".",
"value_type",
"==",
"desc",
".",
"valueType",
... | 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 `False` | [
"Determines",
"if",
"a",
"given",
"metric",
"descriptor",
"matches",
"this",
"enum",
"instance"
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/metric_descriptor.py#L276-L289 |
cloudendpoints/endpoints-management-python | endpoints_management/control/metric_descriptor.py | KnownMetrics.do_operation_update | 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 | 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... | [
"def",
"do_operation_update",
"(",
"self",
",",
"info",
",",
"an_op",
")",
":",
"self",
".",
"update_op_func",
"(",
"self",
".",
"metric_name",
",",
"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`):
the info instance to update
... | [
"Updates",
"an",
"operation",
"using",
"the",
"assigned",
"update_op_func"
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/metric_descriptor.py#L291-L304 |
cloudendpoints/endpoints-management-python | endpoints_management/control/metric_descriptor.py | KnownMetrics.is_supported | 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 | 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... | [
"def",
"is_supported",
"(",
"cls",
",",
"desc",
")",
":",
"for",
"m",
"in",
"cls",
":",
"if",
"m",
".",
"matches",
"(",
"desc",
")",
":",
"return",
"True",
"return",
"False"
] | 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 `False` | [
"Determines",
"if",
"the",
"given",
"metric",
"descriptor",
"is",
"supported",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/metric_descriptor.py#L321-L335 |
cloudendpoints/endpoints-management-python | endpoints_management/control/signing.py | add_dict_to_hash | 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 | 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... | [
"def",
"add_dict_to_hash",
"(",
"a_hash",
",",
"a_dict",
")",
":",
"if",
"a_dict",
"is",
"None",
":",
"return",
"for",
"k",
",",
"v",
"in",
"a_dict",
".",
"items",
"(",
")",
":",
"a_hash",
".",
"update",
"(",
"b'\\x00'",
"+",
"k",
".",
"encode",
"(... | 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 | [
"Adds",
"a_dict",
"to",
"a_hash"
] | train | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/signing.py#L20-L31 |
yunstanford/sanic-transmute | sanic_transmute/swagger.py | add_swagger | def add_swagger(app, json_route, html_route):
"""
a convenience method for both adding a swagger.json route,
as well as adding a page showing the html documentation
"""
app.add_route(create_swagger_json_handler(app), json_route, methods=["GET"])
add_swagger_api_route(app, html_route, json_route) | python | def add_swagger(app, json_route, html_route):
"""
a convenience method for both adding a swagger.json route,
as well as adding a page showing the html documentation
"""
app.add_route(create_swagger_json_handler(app), json_route, methods=["GET"])
add_swagger_api_route(app, html_route, json_route) | [
"def",
"add_swagger",
"(",
"app",
",",
"json_route",
",",
"html_route",
")",
":",
"app",
".",
"add_route",
"(",
"create_swagger_json_handler",
"(",
"app",
")",
",",
"json_route",
",",
"methods",
"=",
"[",
"\"GET\"",
"]",
")",
"add_swagger_api_route",
"(",
"a... | a convenience method for both adding a swagger.json route,
as well as adding a page showing the html documentation | [
"a",
"convenience",
"method",
"for",
"both",
"adding",
"a",
"swagger",
".",
"json",
"route",
"as",
"well",
"as",
"adding",
"a",
"page",
"showing",
"the",
"html",
"documentation"
] | train | https://github.com/yunstanford/sanic-transmute/blob/5040819d0bd6024e257603f69d12984a3b112cf0/sanic_transmute/swagger.py#L21-L27 |
yunstanford/sanic-transmute | sanic_transmute/swagger.py | add_swagger_api_route | def add_swagger_api_route(app, target_route, swagger_json_route):
"""
mount a swagger statics page.
app: the sanic app object
target_route: the path to mount the statics page.
swagger_json_route: the path where the swagger json definitions is
expected to be.
"""
stati... | python | def add_swagger_api_route(app, target_route, swagger_json_route):
"""
mount a swagger statics page.
app: the sanic app object
target_route: the path to mount the statics page.
swagger_json_route: the path where the swagger json definitions is
expected to be.
"""
stati... | [
"def",
"add_swagger_api_route",
"(",
"app",
",",
"target_route",
",",
"swagger_json_route",
")",
":",
"static_root",
"=",
"get_swagger_static_root",
"(",
")",
"swagger_body",
"=",
"generate_swagger_html",
"(",
"STATIC_ROOT",
",",
"swagger_json_route",
")",
".",
"encod... | mount a swagger statics page.
app: the sanic app object
target_route: the path to mount the statics page.
swagger_json_route: the path where the swagger json definitions is
expected to be. | [
"mount",
"a",
"swagger",
"statics",
"page",
".",
"app",
":",
"the",
"sanic",
"app",
"object",
"target_route",
":",
"the",
"path",
"to",
"mount",
"the",
"statics",
"page",
".",
"swagger_json_route",
":",
"the",
"path",
"where",
"the",
"swagger",
"json",
"de... | train | https://github.com/yunstanford/sanic-transmute/blob/5040819d0bd6024e257603f69d12984a3b112cf0/sanic_transmute/swagger.py#L30-L50 |
yunstanford/sanic-transmute | sanic_transmute/swagger.py | create_swagger_json_handler | 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 | 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... | [
"def",
"create_swagger_json_handler",
"(",
"app",
",",
"*",
"*",
"kwargs",
")",
":",
"spec",
"=",
"get_swagger_spec",
"(",
"app",
")",
"_add_blueprint_specs",
"(",
"app",
",",
"spec",
")",
"spec_dict",
"=",
"spec",
".",
"swagger_definition",
"(",
"*",
"*",
... | Create a handler that returns the swagger definition
for an application.
This method assumes the application is using the
TransmuteUrlDispatcher as the router. | [
"Create",
"a",
"handler",
"that",
"returns",
"the",
"swagger",
"definition",
"for",
"an",
"application",
".",
"This",
"method",
"assumes",
"the",
"application",
"is",
"using",
"the",
"TransmuteUrlDispatcher",
"as",
"the",
"router",
"."
] | train | https://github.com/yunstanford/sanic-transmute/blob/5040819d0bd6024e257603f69d12984a3b112cf0/sanic_transmute/swagger.py#L53-L75 |
onysos/django-composite-foreignkey | compositefk/fields.py | CompositeForeignKey.compute_to_fields | def compute_to_fields(self, to_fields):
"""
compute the to_fields parameterse to make it uniformly a dict of CompositePart
:param set[unicode]|dict[unicode, unicode] to_fields: the list/dict of fields to match
:return: the well formated to_field containing only subclasses of CompositePar... | python | def compute_to_fields(self, to_fields):
"""
compute the to_fields parameterse to make it uniformly a dict of CompositePart
:param set[unicode]|dict[unicode, unicode] to_fields: the list/dict of fields to match
:return: the well formated to_field containing only subclasses of CompositePar... | [
"def",
"compute_to_fields",
"(",
"self",
",",
"to_fields",
")",
":",
"# for problem in trim_join, we must try to give the fields in a consistent order with others models...",
"# see #26515 at https://code.djangoproject.com/ticket/26515",
"return",
"OrderedDict",
"(",
"(",
"k",
",",
... | compute the to_fields parameterse to make it uniformly a dict of CompositePart
:param set[unicode]|dict[unicode, unicode] to_fields: the list/dict of fields to match
:return: the well formated to_field containing only subclasses of CompositePart
:rtype: dict[str, CompositePart] | [
"compute",
"the",
"to_fields",
"parameterse",
"to",
"make",
"it",
"uniformly",
"a",
"dict",
"of",
"CompositePart",
":",
"param",
"set",
"[",
"unicode",
"]",
"|dict",
"[",
"unicode",
"unicode",
"]",
"to_fields",
":",
"the",
"list",
"/",
"dict",
"of",
"field... | train | https://github.com/onysos/django-composite-foreignkey/blob/11e9370e32b3e5ec3fca7b1486b0fa52da0a54c1/compositefk/fields.py#L214-L227 |
onysos/django-composite-foreignkey | compositefk/fields.py | RawFieldValue.get_lookup | def get_lookup(self, main_field, for_remote, alias):
"""
create a fake field for the lookup capability
:param CompositeForeignKey main_field: the local fk
:param Field for_remote: the remote field to match
:return:
"""
lookup_class = for_remote.get_lookup("exact")... | python | def get_lookup(self, main_field, for_remote, alias):
"""
create a fake field for the lookup capability
:param CompositeForeignKey main_field: the local fk
:param Field for_remote: the remote field to match
:return:
"""
lookup_class = for_remote.get_lookup("exact")... | [
"def",
"get_lookup",
"(",
"self",
",",
"main_field",
",",
"for_remote",
",",
"alias",
")",
":",
"lookup_class",
"=",
"for_remote",
".",
"get_lookup",
"(",
"\"exact\"",
")",
"return",
"lookup_class",
"(",
"for_remote",
".",
"get_col",
"(",
"alias",
")",
",",
... | create a fake field for the lookup capability
:param CompositeForeignKey main_field: the local fk
:param Field for_remote: the remote field to match
:return: | [
"create",
"a",
"fake",
"field",
"for",
"the",
"lookup",
"capability",
":",
"param",
"CompositeForeignKey",
"main_field",
":",
"the",
"local",
"fk",
":",
"param",
"Field",
"for_remote",
":",
"the",
"remote",
"field",
"to",
"match",
":",
"return",
":"
] | train | https://github.com/onysos/django-composite-foreignkey/blob/11e9370e32b3e5ec3fca7b1486b0fa52da0a54c1/compositefk/fields.py#L321-L329 |
guyhughes/fqdn | fqdn/__init__.py | FQDN.is_valid | def is_valid(self):
"""
True for a validated fully-qualified domain nam (FQDN), in full
compliance with RFC 1035, and the "preferred form" specified in RFC
3686 s. 2, whether relative or absolute.
https://tools.ietf.org/html/rfc3696#section-2
https://tools.ietf.org/html/... | python | def is_valid(self):
"""
True for a validated fully-qualified domain nam (FQDN), in full
compliance with RFC 1035, and the "preferred form" specified in RFC
3686 s. 2, whether relative or absolute.
https://tools.ietf.org/html/rfc3696#section-2
https://tools.ietf.org/html/... | [
"def",
"is_valid",
"(",
"self",
")",
":",
"length",
"=",
"len",
"(",
"self",
".",
"fqdn",
")",
"if",
"self",
".",
"fqdn",
".",
"endswith",
"(",
"'.'",
")",
":",
"length",
"-=",
"1",
"if",
"length",
">",
"253",
":",
"return",
"False",
"return",
"b... | True for a validated fully-qualified domain nam (FQDN), in full
compliance with RFC 1035, and the "preferred form" specified in RFC
3686 s. 2, whether relative or absolute.
https://tools.ietf.org/html/rfc3696#section-2
https://tools.ietf.org/html/rfc1035
If and only if the FQDN... | [
"True",
"for",
"a",
"validated",
"fully",
"-",
"qualified",
"domain",
"nam",
"(",
"FQDN",
")",
"in",
"full",
"compliance",
"with",
"RFC",
"1035",
"and",
"the",
"preferred",
"form",
"specified",
"in",
"RFC",
"3686",
"s",
".",
"2",
"whether",
"relative",
"... | train | https://github.com/guyhughes/fqdn/blob/1ad687d6cd1d74c5781f673194a744ff105e345c/fqdn/__init__.py#L42-L60 |
guyhughes/fqdn | fqdn/__init__.py | FQDN.absolute | 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 | 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) | [
"def",
"absolute",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_valid",
":",
"raise",
"ValueError",
"(",
"'invalid FQDN `{0}`'",
".",
"format",
"(",
"self",
".",
"fqdn",
")",
")",
"if",
"self",
".",
"is_valid_absolute",
":",
"return",
"self",
"."... | The FQDN as a string in absolute form | [
"The",
"FQDN",
"as",
"a",
"string",
"in",
"absolute",
"form"
] | train | https://github.com/guyhughes/fqdn/blob/1ad687d6cd1d74c5781f673194a744ff105e345c/fqdn/__init__.py#L82-L92 |
guyhughes/fqdn | fqdn/__init__.py | FQDN.relative | 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 | 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 | [
"def",
"relative",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_valid",
":",
"raise",
"ValueError",
"(",
"'invalid FQDN `{0}`'",
".",
"format",
"(",
"self",
".",
"fqdn",
")",
")",
"if",
"self",
".",
"is_valid_absolute",
":",
"return",
"self",
"."... | The FQDN as a string in relative form | [
"The",
"FQDN",
"as",
"a",
"string",
"in",
"relative",
"form"
] | train | https://github.com/guyhughes/fqdn/blob/1ad687d6cd1d74c5781f673194a744ff105e345c/fqdn/__init__.py#L95-L105 |
marcelm/xopen | src/xopen/__init__.py | _available_cpu_count | def _available_cpu_count():
"""
Number of available virtual or physical CPUs on this system
Adapted from http://stackoverflow.com/a/1006301/715090
"""
try:
return len(os.sched_getaffinity(0))
except AttributeError:
pass
import re
try:
with open('/proc/self/status'... | python | def _available_cpu_count():
"""
Number of available virtual or physical CPUs on this system
Adapted from http://stackoverflow.com/a/1006301/715090
"""
try:
return len(os.sched_getaffinity(0))
except AttributeError:
pass
import re
try:
with open('/proc/self/status'... | [
"def",
"_available_cpu_count",
"(",
")",
":",
"try",
":",
"return",
"len",
"(",
"os",
".",
"sched_getaffinity",
"(",
"0",
")",
")",
"except",
"AttributeError",
":",
"pass",
"import",
"re",
"try",
":",
"with",
"open",
"(",
"'/proc/self/status'",
")",
"as",
... | Number of available virtual or physical CPUs on this system
Adapted from http://stackoverflow.com/a/1006301/715090 | [
"Number",
"of",
"available",
"virtual",
"or",
"physical",
"CPUs",
"on",
"this",
"system",
"Adapted",
"from",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"1006301",
"/",
"715090"
] | train | https://github.com/marcelm/xopen/blob/891ca71fb9b8b2b599de74caa4ed92206e5719f2/src/xopen/__init__.py#L52-L76 |
marcelm/xopen | src/xopen/__init__.py | xopen | def xopen(filename, mode='r', compresslevel=6, threads=None):
"""
A replacement for the "open" function that can also open files that have
been compressed with gzip, bzip2 or xz. If the filename is '-', standard
output (mode 'w') or input (mode 'r') is returned.
The file type is determined based on... | python | def xopen(filename, mode='r', compresslevel=6, threads=None):
"""
A replacement for the "open" function that can also open files that have
been compressed with gzip, bzip2 or xz. If the filename is '-', standard
output (mode 'w') or input (mode 'r') is returned.
The file type is determined based on... | [
"def",
"xopen",
"(",
"filename",
",",
"mode",
"=",
"'r'",
",",
"compresslevel",
"=",
"6",
",",
"threads",
"=",
"None",
")",
":",
"if",
"mode",
"in",
"(",
"'r'",
",",
"'w'",
",",
"'a'",
")",
":",
"mode",
"+=",
"'t'",
"if",
"mode",
"not",
"in",
"... | A replacement for the "open" function that can also open files that have
been compressed with gzip, bzip2 or xz. If the filename is '-', standard
output (mode 'w') or input (mode 'r') is returned.
The file type is determined based on the filename: .gz is gzip, .bz2 is bzip2 and .xz is
xz/lzma.
Whe... | [
"A",
"replacement",
"for",
"the",
"open",
"function",
"that",
"can",
"also",
"open",
"files",
"that",
"have",
"been",
"compressed",
"with",
"gzip",
"bzip2",
"or",
"xz",
".",
"If",
"the",
"filename",
"is",
"-",
"standard",
"output",
"(",
"mode",
"w",
")",... | train | https://github.com/marcelm/xopen/blob/891ca71fb9b8b2b599de74caa4ed92206e5719f2/src/xopen/__init__.py#L290-L343 |
marcelm/xopen | src/xopen/__init__.py | PipedGzipReader._raise_if_error | 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 | 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) | [
"def",
"_raise_if_error",
"(",
"self",
")",
":",
"retcode",
"=",
"self",
".",
"process",
".",
"poll",
"(",
")",
"if",
"retcode",
"is",
"not",
"None",
"and",
"retcode",
"!=",
"0",
":",
"message",
"=",
"self",
".",
"_stderr",
".",
"read",
"(",
")",
"... | Raise IOError if process is not running anymore and the
exit code is nonzero. | [
"Raise",
"IOError",
"if",
"process",
"is",
"not",
"running",
"anymore",
"and",
"the",
"exit",
"code",
"is",
"nonzero",
"."
] | train | https://github.com/marcelm/xopen/blob/891ca71fb9b8b2b599de74caa4ed92206e5719f2/src/xopen/__init__.py#L208-L216 |
roycoding/slots | slots/slots.py | MAB.run | 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 | 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... | [
"def",
"run",
"(",
"self",
",",
"trials",
"=",
"100",
",",
"strategy",
"=",
"None",
",",
"parameters",
"=",
"None",
")",
":",
"if",
"trials",
"<",
"1",
":",
"raise",
"Exception",
"(",
"'MAB.run: Number of trials cannot be less than 1!'",
")",
"if",
"not",
... | Run MAB test with T trials.
Parameters
----------
trials : int
Number of trials to run.
strategy : str
Name of selected strategy.
parameters : dict
Parameters for selected strategy.
Available strategies:
- Epsilon-greedy (... | [
"Run",
"MAB",
"test",
"with",
"T",
"trials",
"."
] | train | https://github.com/roycoding/slots/blob/1ed9b203fa02002c09b9dad73e2a97c04a45ef20/slots/slots.py#L85-L119 |
roycoding/slots | slots/slots.py | MAB._run | 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 | 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... | [
"def",
"_run",
"(",
"self",
",",
"strategy",
",",
"parameters",
"=",
"None",
")",
":",
"choice",
"=",
"self",
".",
"run_strategy",
"(",
"strategy",
",",
"parameters",
")",
"self",
".",
"choices",
".",
"append",
"(",
"choice",
")",
"payout",
"=",
"self"... | Run single trial of MAB strategy.
Parameters
----------
strategy : function
parameters : dict
Returns
-------
None | [
"Run",
"single",
"trial",
"of",
"MAB",
"strategy",
"."
] | train | https://github.com/roycoding/slots/blob/1ed9b203fa02002c09b9dad73e2a97c04a45ef20/slots/slots.py#L121-L143 |
roycoding/slots | slots/slots.py | MAB.bayesian | 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 | 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 ... | [
"def",
"bayesian",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"p_success_arms",
"=",
"[",
"np",
".",
"random",
".",
"beta",
"(",
"self",
".",
"wins",
"[",
"i",
"]",
"+",
"1",
",",
"self",
".",
"pulls",
"[",
"i",
"]",
"-",
"self",
".",
... | 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 it is ignored.
Returns
-------
... | [
"Run",
"the",
"Bayesian",
"Bandit",
"algorithm",
"which",
"utilizes",
"a",
"beta",
"distribution",
"for",
"exploration",
"and",
"exploitation",
"."
] | train | https://github.com/roycoding/slots/blob/1ed9b203fa02002c09b9dad73e2a97c04a45ef20/slots/slots.py#L177-L198 |
roycoding/slots | slots/slots.py | MAB.eps_greedy | def eps_greedy(self, params):
'''
Run the epsilon-greedy strategy and update self.max_mean()
Parameters
----------
Params : dict
Epsilon
Returns
-------
int
Index of chosen bandit
'''
if params and type(params) ==... | python | def eps_greedy(self, params):
'''
Run the epsilon-greedy strategy and update self.max_mean()
Parameters
----------
Params : dict
Epsilon
Returns
-------
int
Index of chosen bandit
'''
if params and type(params) ==... | [
"def",
"eps_greedy",
"(",
"self",
",",
"params",
")",
":",
"if",
"params",
"and",
"type",
"(",
"params",
")",
"==",
"dict",
":",
"eps",
"=",
"params",
".",
"get",
"(",
"'epsilon'",
")",
"else",
":",
"eps",
"=",
"0.1",
"r",
"=",
"np",
".",
"random... | Run the epsilon-greedy strategy and update self.max_mean()
Parameters
----------
Params : dict
Epsilon
Returns
-------
int
Index of chosen bandit | [
"Run",
"the",
"epsilon",
"-",
"greedy",
"strategy",
"and",
"update",
"self",
".",
"max_mean",
"()"
] | train | https://github.com/roycoding/slots/blob/1ed9b203fa02002c09b9dad73e2a97c04a45ef20/slots/slots.py#L200-L226 |
roycoding/slots | slots/slots.py | MAB.softmax | 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 | 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... | [
"def",
"softmax",
"(",
"self",
",",
"params",
")",
":",
"default_tau",
"=",
"0.1",
"if",
"params",
"and",
"type",
"(",
"params",
")",
"==",
"dict",
":",
"tau",
"=",
"params",
".",
"get",
"(",
"'tau'",
")",
"try",
":",
"float",
"(",
"tau",
")",
"e... | Run the softmax selection strategy.
Parameters
----------
Params : dict
Tau
Returns
-------
int
Index of chosen bandit | [
"Run",
"the",
"softmax",
"selection",
"strategy",
"."
] | train | https://github.com/roycoding/slots/blob/1ed9b203fa02002c09b9dad73e2a97c04a45ef20/slots/slots.py#L228-L279 |
roycoding/slots | slots/slots.py | MAB.ucb | 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 | 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... | [
"def",
"ucb",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"# UCB = j_max(payout_j + sqrt(2ln(n_tot)/n_j))",
"# Handle cold start. Not all bandits tested yet.",
"if",
"True",
"in",
"(",
"self",
".",
"pulls",
"<",
"3",
")",
":",
"return",
"np",
".",
"random",... | 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 function can take a parameters argument,
... | [
"Run",
"the",
"upper",
"confidence",
"bound",
"MAB",
"selection",
"strategy",
"."
] | train | https://github.com/roycoding/slots/blob/1ed9b203fa02002c09b9dad73e2a97c04a45ef20/slots/slots.py#L281-L310 |
roycoding/slots | slots/slots.py | MAB.best | 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 | 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... | [
"def",
"best",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"choices",
")",
"<",
"1",
":",
"print",
"(",
"'slots: No trials run so far.'",
")",
"return",
"None",
"else",
":",
"return",
"np",
".",
"argmax",
"(",
"self",
".",
"wins",
"/",
"(",... | Return current 'best' choice of bandit.
Returns
-------
int
Index of bandit | [
"Return",
"current",
"best",
"choice",
"of",
"bandit",
"."
] | train | https://github.com/roycoding/slots/blob/1ed9b203fa02002c09b9dad73e2a97c04a45ef20/slots/slots.py#L314-L328 |
roycoding/slots | slots/slots.py | MAB.est_payouts | 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 | 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... | [
"def",
"est_payouts",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"choices",
")",
"<",
"1",
":",
"print",
"(",
"'slots: No trials run so far.'",
")",
"return",
"None",
"else",
":",
"return",
"self",
".",
"wins",
"/",
"(",
"self",
".",
"pulls"... | Calculate current estimate of average payout for each bandit.
Returns
-------
array of floats or None | [
"Calculate",
"current",
"estimate",
"of",
"average",
"payout",
"for",
"each",
"bandit",
"."
] | train | https://github.com/roycoding/slots/blob/1ed9b203fa02002c09b9dad73e2a97c04a45ef20/slots/slots.py#L330-L343 |
roycoding/slots | slots/slots.py | MAB.regret | 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 | 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... | [
"def",
"regret",
"(",
"self",
")",
":",
"return",
"(",
"sum",
"(",
"self",
".",
"pulls",
")",
"*",
"np",
".",
"max",
"(",
"np",
".",
"nan_to_num",
"(",
"self",
".",
"wins",
"/",
"self",
".",
"pulls",
")",
")",
"-",
"sum",
"(",
"self",
".",
"w... | 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 | [
"Calculate",
"expected",
"regret",
"where",
"expected",
"regret",
"is",
"maximum",
"optimal",
"reward",
"-",
"sum",
"of",
"collected",
"rewards",
"i",
".",
"e",
"."
] | train | https://github.com/roycoding/slots/blob/1ed9b203fa02002c09b9dad73e2a97c04a45ef20/slots/slots.py#L345-L358 |
roycoding/slots | slots/slots.py | MAB.crit_met | 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 | 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) | [
"def",
"crit_met",
"(",
"self",
")",
":",
"if",
"True",
"in",
"(",
"self",
".",
"pulls",
"<",
"3",
")",
":",
"return",
"False",
"else",
":",
"return",
"self",
".",
"criteria",
"[",
"self",
".",
"criterion",
"]",
"(",
"self",
".",
"stop_value",
")"
... | Determine if stopping criterion has been met.
Returns
-------
bool | [
"Determine",
"if",
"stopping",
"criterion",
"has",
"been",
"met",
"."
] | train | https://github.com/roycoding/slots/blob/1ed9b203fa02002c09b9dad73e2a97c04a45ef20/slots/slots.py#L360-L372 |
roycoding/slots | slots/slots.py | MAB.regret_met | 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 | 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... | [
"def",
"regret_met",
"(",
"self",
",",
"threshold",
"=",
"None",
")",
":",
"if",
"not",
"threshold",
":",
"return",
"self",
".",
"regret",
"(",
")",
"<=",
"self",
".",
"stop_value",
"elif",
"self",
".",
"regret",
"(",
")",
"<=",
"threshold",
":",
"re... | Determine if regret criterion has been met.
Parameters
----------
threshold : float
Returns
-------
bool | [
"Determine",
"if",
"regret",
"criterion",
"has",
"been",
"met",
"."
] | train | https://github.com/roycoding/slots/blob/1ed9b203fa02002c09b9dad73e2a97c04a45ef20/slots/slots.py#L374-L392 |
roycoding/slots | slots/slots.py | MAB.online_trial | 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 | 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... | [
"def",
"online_trial",
"(",
"self",
",",
"bandit",
"=",
"None",
",",
"payout",
"=",
"None",
",",
"strategy",
"=",
"'eps_greedy'",
",",
"parameters",
"=",
"None",
")",
":",
"if",
"bandit",
"is",
"not",
"None",
"and",
"payout",
"is",
"not",
"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 estimate. Otherwise return the next arm to
try.
Parameters
----------
bandit : int
Ban... | [
"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... | train | https://github.com/roycoding/slots/blob/1ed9b203fa02002c09b9dad73e2a97c04a45ef20/slots/slots.py#L395-L432 |
roycoding/slots | slots/slots.py | MAB.update | 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 | 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... | [
"def",
"update",
"(",
"self",
",",
"bandit",
",",
"payout",
")",
":",
"self",
".",
"choices",
".",
"append",
"(",
"bandit",
")",
"self",
".",
"pulls",
"[",
"bandit",
"]",
"+=",
"1",
"self",
".",
"wins",
"[",
"bandit",
"]",
"+=",
"payout",
"self",
... | Update bandit trials and payouts for given bandit.
Parameters
----------
bandit : int
Bandit index
payout : float
Returns
-------
None | [
"Update",
"bandit",
"trials",
"and",
"payouts",
"for",
"given",
"bandit",
"."
] | train | https://github.com/roycoding/slots/blob/1ed9b203fa02002c09b9dad73e2a97c04a45ef20/slots/slots.py#L434-L452 |
roycoding/slots | slots/slots.py | Bandits.pull | 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 | 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:
... | [
"def",
"pull",
"(",
"self",
",",
"i",
")",
":",
"if",
"self",
".",
"live",
":",
"if",
"len",
"(",
"self",
".",
"payouts",
"[",
"i",
"]",
")",
">",
"0",
":",
"return",
"self",
".",
"payouts",
"[",
"i",
"]",
".",
"pop",
"(",
")",
"else",
":",... | Return the payout from a single pull of the bandit i's arm.
Parameters
----------
i : int
Index of bandit.
Returns
-------
float or None | [
"Return",
"the",
"payout",
"from",
"a",
"single",
"pull",
"of",
"the",
"bandit",
"i",
"s",
"arm",
"."
] | train | https://github.com/roycoding/slots/blob/1ed9b203fa02002c09b9dad73e2a97c04a45ef20/slots/slots.py#L489-L512 |
reanahub/reana-commons | reana_commons/utils.py | click_table_printer | 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 | 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... | [
"def",
"click_table_printer",
"(",
"headers",
",",
"_filter",
",",
"data",
")",
":",
"_filter",
"=",
"[",
"h",
".",
"lower",
"(",
")",
"for",
"h",
"in",
"_filter",
"]",
"+",
"[",
"h",
".",
"upper",
"(",
")",
"for",
"h",
"in",
"_filter",
"]",
"hea... | Generate space separated output for click commands. | [
"Generate",
"space",
"separated",
"output",
"for",
"click",
"commands",
"."
] | train | https://github.com/reanahub/reana-commons/blob/abf31d9f495e0d93171c43fc4a414cd292091b11/reana_commons/utils.py#L23-L42 |
reanahub/reana-commons | reana_commons/utils.py | calculate_hash_of_dir | 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 | 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... | [
"def",
"calculate_hash_of_dir",
"(",
"directory",
",",
"file_list",
"=",
"None",
")",
":",
"md5_hash",
"=",
"md5",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"directory",
")",
":",
"return",
"-",
"1",
"try",
":",
"for",
"subdir",
"... | Calculate hash of directory. | [
"Calculate",
"hash",
"of",
"directory",
"."
] | train | https://github.com/reanahub/reana-commons/blob/abf31d9f495e0d93171c43fc4a414cd292091b11/reana_commons/utils.py#L45-L75 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.