Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
Http.clear_credentials
(self)
Remove all the names and passwords that are used for authentication
Remove all the names and passwords that are used for authentication
def clear_credentials(self): """Remove all the names and passwords that are used for authentication""" self.credentials.clear() self.authorizations = []
[ "def", "clear_credentials", "(", "self", ")", ":", "self", ".", "credentials", ".", "clear", "(", ")", "self", ".", "authorizations", "=", "[", "]" ]
[ 1687, 4 ]
[ 1691, 32 ]
python
en
['en', 'en', 'en']
True
Http._request
( self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey, )
Do the actual request using the connection object and also follow one level of redirects if necessary
Do the actual request using the connection object and also follow one level of redirects if necessary
def _request( self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey, ): """Do the actual request using the connection object and also follow one level of redirects if necessary""" ...
[ "def", "_request", "(", "self", ",", "conn", ",", "host", ",", "absolute_uri", ",", "request_uri", ",", "method", ",", "body", ",", "headers", ",", "redirections", ",", "cachekey", ",", ")", ":", "auths", "=", "[", "(", "auth", ".", "depth", "(", "re...
[ 1770, 4 ]
[ 1887, 34 ]
python
en
['en', 'en', 'en']
True
Http.request
( self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None, )
Performs a single HTTP request. The 'uri' is the URI of the HTTP resource and can begin with either 'http' or 'https'. The value of 'uri' must be an absolute URI. The 'method' is the HTTP method to perform, such as GET, POST, DELETE, etc. There is no restriction on the methods allowed...
Performs a single HTTP request.
def request( self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None, ): """ Performs a single HTTP request. The 'uri' is the URI of the HTTP resource and can begin with either 'http' ...
[ "def", "request", "(", "self", ",", "uri", ",", "method", "=", "\"GET\"", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "redirections", "=", "DEFAULT_MAX_REDIRECTS", ",", "connection_type", "=", "None", ",", ")", ":", "conn_key", "=", "''",...
[ 1896, 4 ]
[ 2172, 34 ]
python
en
['en', 'en', 'en']
True
Http._get_proxy_info
(self, scheme, authority)
Return a ProxyInfo instance (or None) based on the scheme and authority.
Return a ProxyInfo instance (or None) based on the scheme and authority.
def _get_proxy_info(self, scheme, authority): """Return a ProxyInfo instance (or None) based on the scheme and authority. """ hostname, port = urllib.splitport(authority) proxy_info = self.proxy_info if callable(proxy_info): proxy_info = proxy_info(scheme) ...
[ "def", "_get_proxy_info", "(", "self", ",", "scheme", ",", "authority", ")", ":", "hostname", ",", "port", "=", "urllib", ".", "splitport", "(", "authority", ")", "proxy_info", "=", "self", ".", "proxy_info", "if", "callable", "(", "proxy_info", ")", ":", ...
[ 2174, 4 ]
[ 2185, 25 ]
python
en
['en', 'en', 'en']
True
AttentionSelfAttention.__init__
(self, depth, spatial_dims, num_heads=1, positional_encoding=True, name="attention_self_attention")
depth : number of output channels spatial_dim : spatial dimensions of input tensor (x , y) if positional_encoding: depth must correspond to input channel number adapted from: https://www.tensorflow.org/tutorials/text/transformer
depth : number of output channels spatial_dim : spatial dimensions of input tensor (x , y) if positional_encoding: depth must correspond to input channel number adapted from: https://www.tensorflow.org/tutorials/text/transformer
def __init__(self, depth, spatial_dims, num_heads=1, positional_encoding=True, name="attention_self_attention"): ''' depth : number of output channels spatial_dim : spatial dimensions of input tensor (x , y) if positional_encoding: depth must correspond to input channel numbe...
[ "def", "__init__", "(", "self", ",", "depth", ",", "spatial_dims", ",", "num_heads", "=", "1", ",", "positional_encoding", "=", "True", ",", "name", "=", "\"attention_self_attention\"", ")", ":", "super", "(", ")", ".", "__init__", "(", "name", "=", "name"...
[ 7, 4 ]
[ 27, 93 ]
python
en
['en', 'error', 'th']
False
AttentionSelfAttention.split_heads
(self, x, batch_size, num_heads)
Split the last dimension into (num_heads, depth). Transpose the result such that the shape is (batch_size, num_heads, spa_dim, depth)
Split the last dimension into (num_heads, depth). Transpose the result such that the shape is (batch_size, num_heads, spa_dim, depth)
def split_heads(self, x, batch_size, num_heads): """Split the last dimension into (num_heads, depth). Transpose the result such that the shape is (batch_size, num_heads, spa_dim, depth) """ x = tf.reshape(x, (batch_size, self.spatial_dim, num_heads, self.depth)) return tf.transpose(x, perm...
[ "def", "split_heads", "(", "self", ",", "x", ",", "batch_size", ",", "num_heads", ")", ":", "x", "=", "tf", ".", "reshape", "(", "x", ",", "(", "batch_size", ",", "self", ".", "spatial_dim", ",", "num_heads", ",", "self", ".", "depth", ")", ")", "r...
[ 29, 4 ]
[ 34, 47 ]
python
en
['en', 'fr', 'en']
True
AttentionSelfAttention.call
(self, x)
x : list of 2 tensor with shape (batch_size, y, x, channels)
x : list of 2 tensor with shape (batch_size, y, x, channels)
def call(self, x): ''' x : list of 2 tensor with shape (batch_size, y, x, channels) ''' [kvx, qx] = x shape = tf.shape(qx) batch_size = shape[0] #spatial_dims = shape[1:-1] #spatial_dim = tf.reduce_prod(spatial_dims) depth_dim = shape[3] ...
[ "def", "call", "(", "self", ",", "x", ")", ":", "[", "kvx", ",", "qx", "]", "=", "x", "shape", "=", "tf", ".", "shape", "(", "qx", ")", "batch_size", "=", "shape", "[", "0", "]", "#spatial_dims = shape[1:-1]", "#spatial_dim = tf.reduce_prod(spatial_dims)",...
[ 36, 4 ]
[ 76, 40 ]
python
en
['en', 'error', 'th']
False
is_iterable
(x)
An implementation independent way of checking for iterables
An implementation independent way of checking for iterables
def is_iterable(x): "An implementation independent way of checking for iterables" try: iter(x) except TypeError: return False else: return True
[ "def", "is_iterable", "(", "x", ")", ":", "try", ":", "iter", "(", "x", ")", "except", "TypeError", ":", "return", "False", "else", ":", "return", "True" ]
[ 0, 0 ]
[ 7, 19 ]
python
en
['en', 'en', 'en']
True
Envelope.__init__
(self, *args)
The initialization function may take an OGREnvelope structure, 4-element tuple or list, or 4 individual arguments.
The initialization function may take an OGREnvelope structure, 4-element tuple or list, or 4 individual arguments.
def __init__(self, *args): """ The initialization function may take an OGREnvelope structure, 4-element tuple or list, or 4 individual arguments. """ if len(args) == 1: if isinstance(args[0], OGREnvelope): # OGREnvelope (a ctypes Structure) was passed...
[ "def", "__init__", "(", "self", ",", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "if", "isinstance", "(", "args", "[", "0", "]", ",", "OGREnvelope", ")", ":", "# OGREnvelope (a ctypes Structure) was passed in.", "self", ".", "_e...
[ 36, 4 ]
[ 65, 66 ]
python
en
['en', 'error', 'th']
False
Envelope.__eq__
(self, other)
Return True if the envelopes are equivalent; can compare against other Envelopes and 4-tuples.
Return True if the envelopes are equivalent; can compare against other Envelopes and 4-tuples.
def __eq__(self, other): """ Return True if the envelopes are equivalent; can compare against other Envelopes and 4-tuples. """ if isinstance(other, Envelope): return (self.min_x == other.min_x) and (self.min_y == other.min_y) and \ (self.max_x == o...
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "Envelope", ")", ":", "return", "(", "self", ".", "min_x", "==", "other", ".", "min_x", ")", "and", "(", "self", ".", "min_y", "==", "other", ".", "min_y",...
[ 67, 4 ]
[ 79, 87 ]
python
en
['en', 'error', 'th']
False
Envelope.__str__
(self)
Return a string representation of the tuple.
Return a string representation of the tuple.
def __str__(self): "Return a string representation of the tuple." return str(self.tuple)
[ "def", "__str__", "(", "self", ")", ":", "return", "str", "(", "self", ".", "tuple", ")" ]
[ 81, 4 ]
[ 83, 30 ]
python
en
['en', 'en', 'en']
True
Envelope._from_sequence
(self, seq)
Initialize the C OGR Envelope structure from the given sequence.
Initialize the C OGR Envelope structure from the given sequence.
def _from_sequence(self, seq): "Initialize the C OGR Envelope structure from the given sequence." self._envelope = OGREnvelope() self._envelope.MinX = seq[0] self._envelope.MinY = seq[1] self._envelope.MaxX = seq[2] self._envelope.MaxY = seq[3]
[ "def", "_from_sequence", "(", "self", ",", "seq", ")", ":", "self", ".", "_envelope", "=", "OGREnvelope", "(", ")", "self", ".", "_envelope", ".", "MinX", "=", "seq", "[", "0", "]", "self", ".", "_envelope", ".", "MinY", "=", "seq", "[", "1", "]", ...
[ 85, 4 ]
[ 91, 36 ]
python
en
['en', 'en', 'en']
True
Envelope.expand_to_include
(self, *args)
Modify the envelope to expand to include the boundaries of the passed-in 2-tuple (a point), 4-tuple (an extent) or envelope.
Modify the envelope to expand to include the boundaries of the passed-in 2-tuple (a point), 4-tuple (an extent) or envelope.
def expand_to_include(self, *args): """ Modify the envelope to expand to include the boundaries of the passed-in 2-tuple (a point), 4-tuple (an extent) or envelope. """ # We provide a number of different signatures for this method, # and the logic here is all abou...
[ "def", "expand_to_include", "(", "self", ",", "*", "args", ")", ":", "# We provide a number of different signatures for this method,", "# and the logic here is all about converting them into a", "# 4-tuple single parameter which does the actual work of", "# expanding the envelope.", "if", ...
[ 93, 4 ]
[ 133, 85 ]
python
en
['en', 'error', 'th']
False
Envelope.min_x
(self)
Return the value of the minimum X coordinate.
Return the value of the minimum X coordinate.
def min_x(self): "Return the value of the minimum X coordinate." return self._envelope.MinX
[ "def", "min_x", "(", "self", ")", ":", "return", "self", ".", "_envelope", ".", "MinX" ]
[ 136, 4 ]
[ 138, 34 ]
python
en
['en', 'la', 'en']
True
Envelope.min_y
(self)
Return the value of the minimum Y coordinate.
Return the value of the minimum Y coordinate.
def min_y(self): "Return the value of the minimum Y coordinate." return self._envelope.MinY
[ "def", "min_y", "(", "self", ")", ":", "return", "self", ".", "_envelope", ".", "MinY" ]
[ 141, 4 ]
[ 143, 34 ]
python
en
['en', 'la', 'en']
True
Envelope.max_x
(self)
Return the value of the maximum X coordinate.
Return the value of the maximum X coordinate.
def max_x(self): "Return the value of the maximum X coordinate." return self._envelope.MaxX
[ "def", "max_x", "(", "self", ")", ":", "return", "self", ".", "_envelope", ".", "MaxX" ]
[ 146, 4 ]
[ 148, 34 ]
python
en
['en', 'la', 'en']
True
Envelope.max_y
(self)
Return the value of the maximum Y coordinate.
Return the value of the maximum Y coordinate.
def max_y(self): "Return the value of the maximum Y coordinate." return self._envelope.MaxY
[ "def", "max_y", "(", "self", ")", ":", "return", "self", ".", "_envelope", ".", "MaxY" ]
[ 151, 4 ]
[ 153, 34 ]
python
en
['en', 'la', 'en']
True
Envelope.ur
(self)
Return the upper-right coordinate.
Return the upper-right coordinate.
def ur(self): "Return the upper-right coordinate." return (self.max_x, self.max_y)
[ "def", "ur", "(", "self", ")", ":", "return", "(", "self", ".", "max_x", ",", "self", ".", "max_y", ")" ]
[ 156, 4 ]
[ 158, 39 ]
python
en
['en', 'en', 'en']
True
Envelope.ll
(self)
Return the lower-left coordinate.
Return the lower-left coordinate.
def ll(self): "Return the lower-left coordinate." return (self.min_x, self.min_y)
[ "def", "ll", "(", "self", ")", ":", "return", "(", "self", ".", "min_x", ",", "self", ".", "min_y", ")" ]
[ 161, 4 ]
[ 163, 39 ]
python
en
['en', 'en', 'en']
True
Envelope.tuple
(self)
Return a tuple representing the envelope.
Return a tuple representing the envelope.
def tuple(self): "Return a tuple representing the envelope." return (self.min_x, self.min_y, self.max_x, self.max_y)
[ "def", "tuple", "(", "self", ")", ":", "return", "(", "self", ".", "min_x", ",", "self", ".", "min_y", ",", "self", ".", "max_x", ",", "self", ".", "max_y", ")" ]
[ 166, 4 ]
[ 168, 63 ]
python
en
['en', 'en', 'en']
True
Envelope.wkt
(self)
Return WKT representing a Polygon for this envelope.
Return WKT representing a Polygon for this envelope.
def wkt(self): "Return WKT representing a Polygon for this envelope." # TODO: Fix significant figures. return 'POLYGON((%s %s,%s %s,%s %s,%s %s,%s %s))' % \ (self.min_x, self.min_y, self.min_x, self.max_y, self.max_x, self.max_y, self.max_x, self.min_y, ...
[ "def", "wkt", "(", "self", ")", ":", "# TODO: Fix significant figures.", "return", "'POLYGON((%s %s,%s %s,%s %s,%s %s,%s %s))'", "%", "(", "self", ".", "min_x", ",", "self", ".", "min_y", ",", "self", ".", "min_x", ",", "self", ".", "max_y", ",", "self", ".", ...
[ 171, 4 ]
[ 177, 39 ]
python
en
['en', 'en', 'en']
True
validate_twilio_request
(f)
Validates that incoming requests genuinely originated from Twilio
Validates that incoming requests genuinely originated from Twilio
def validate_twilio_request(f): """Validates that incoming requests genuinely originated from Twilio""" @wraps(f) def decorated_function(request, *args, **kwargs): # Create an instance of the RequestValidator class validator = RequestValidator(os.environ.get('TWILIO_AUTH_TOKEN')) # ...
[ "def", "validate_twilio_request", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "decorated_function", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Create an instance of the RequestValidator class", "validator", "=", "RequestV...
[ 8, 0 ]
[ 28, 29 ]
python
en
['en', 'en', 'en']
True
Asn1Type.effectiveTagSet
(self)
For |ASN.1| type is equivalent to *tagSet*
For |ASN.1| type is equivalent to *tagSet*
def effectiveTagSet(self): """For |ASN.1| type is equivalent to *tagSet* """ return self.tagSet
[ "def", "effectiveTagSet", "(", "self", ")", ":", "return", "self", ".", "tagSet" ]
[ 76, 4 ]
[ 79, 26 ]
python
en
['en', 'en', 'en']
True
Asn1Type.tagMap
(self)
Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping ASN.1 tags to ASN.1 objects within callee object.
Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping ASN.1 tags to ASN.1 objects within callee object.
def tagMap(self): """Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping ASN.1 tags to ASN.1 objects within callee object. """ return tagmap.TagMap({self.tagSet: self})
[ "def", "tagMap", "(", "self", ")", ":", "return", "tagmap", ".", "TagMap", "(", "{", "self", ".", "tagSet", ":", "self", "}", ")" ]
[ 82, 4 ]
[ 85, 49 ]
python
en
['en', 'en', 'en']
True
Asn1Type.isSameTypeWith
(self, other, matchTags=True, matchConstraints=True)
Examine |ASN.1| type for equality with other ASN.1 type. ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints (:py:mod:`~pyasn1.type.constraint`) are examined when carrying out ASN.1 types comparison. Python class inheritance relationship is NOT considered. Parameters ...
Examine |ASN.1| type for equality with other ASN.1 type.
def isSameTypeWith(self, other, matchTags=True, matchConstraints=True): """Examine |ASN.1| type for equality with other ASN.1 type. ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints (:py:mod:`~pyasn1.type.constraint`) are examined when carrying out ASN.1 types comparison. ...
[ "def", "isSameTypeWith", "(", "self", ",", "other", ",", "matchTags", "=", "True", ",", "matchConstraints", "=", "True", ")", ":", "return", "(", "self", "is", "other", "or", "(", "not", "matchTags", "or", "self", ".", "tagSet", "==", "other", ".", "ta...
[ 87, 4 ]
[ 109, 80 ]
python
en
['en', 'en', 'en']
True
Asn1Type.isSuperTypeOf
(self, other, matchTags=True, matchConstraints=True)
Examine |ASN.1| type for subtype relationship with other ASN.1 type. ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints (:py:mod:`~pyasn1.type.constraint`) are examined when carrying out ASN.1 types comparison. Python class inheritance relationship is NOT considered. Para...
Examine |ASN.1| type for subtype relationship with other ASN.1 type.
def isSuperTypeOf(self, other, matchTags=True, matchConstraints=True): """Examine |ASN.1| type for subtype relationship with other ASN.1 type. ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints (:py:mod:`~pyasn1.type.constraint`) are examined when carrying out ASN.1 types compariso...
[ "def", "isSuperTypeOf", "(", "self", ",", "other", ",", "matchTags", "=", "True", ",", "matchConstraints", "=", "True", ")", ":", "return", "(", "not", "matchTags", "or", "(", "self", ".", "tagSet", ".", "isSuperTagSetOf", "(", "other", ".", "tagSet", ")...
[ 111, 4 ]
[ 133, 93 ]
python
en
['en', 'en', 'en']
True
SimpleAsn1Type.isValue
(self)
Indicate that |ASN.1| object represents ASN.1 value. If *isValue* is :obj:`False` then this object represents just ASN.1 schema. If *isValue* is :obj:`True` then, in addition to its ASN.1 schema features, this object can also be used like a Python built-in object (e.g. :class:`...
Indicate that |ASN.1| object represents ASN.1 value.
def isValue(self): """Indicate that |ASN.1| object represents ASN.1 value. If *isValue* is :obj:`False` then this object represents just ASN.1 schema. If *isValue* is :obj:`True` then, in addition to its ASN.1 schema features, this object can also be used like a Python built-in...
[ "def", "isValue", "(", "self", ")", ":", "return", "self", ".", "_value", "is", "not", "noValue" ]
[ 321, 4 ]
[ 348, 41 ]
python
en
['en', 'en', 'en']
True
SimpleAsn1Type.clone
(self, value=noValue, **kwargs)
Create a modified version of |ASN.1| schema or value object. The `clone()` method accepts the same set arguments as |ASN.1| class takes on instantiation except that all arguments of the `clone()` method are optional. Whatever arguments are supplied, they are used to create a copy ...
Create a modified version of |ASN.1| schema or value object.
def clone(self, value=noValue, **kwargs): """Create a modified version of |ASN.1| schema or value object. The `clone()` method accepts the same set arguments as |ASN.1| class takes on instantiation except that all arguments of the `clone()` method are optional. Whatever argumen...
[ "def", "clone", "(", "self", ",", "value", "=", "noValue", ",", "*", "*", "kwargs", ")", ":", "if", "value", "is", "noValue", ":", "if", "not", "kwargs", ":", "return", "self", "value", "=", "self", ".", "_value", "initializers", "=", "self", ".", ...
[ 350, 4 ]
[ 375, 52 ]
python
en
['en', 'en', 'en']
True
SimpleAsn1Type.subtype
(self, value=noValue, **kwargs)
Create a specialization of |ASN.1| schema or value object. The subtype relationship between ASN.1 types has no correlation with subtype relationship between Python types. ASN.1 type is mainly identified by its tag(s) (:py:class:`~pyasn1.type.tag.TagSet`) and value range constraints (:py...
Create a specialization of |ASN.1| schema or value object.
def subtype(self, value=noValue, **kwargs): """Create a specialization of |ASN.1| schema or value object. The subtype relationship between ASN.1 types has no correlation with subtype relationship between Python types. ASN.1 type is mainly identified by its tag(s) (:py:class:`~pyasn1.typ...
[ "def", "subtype", "(", "self", ",", "value", "=", "noValue", ",", "*", "*", "kwargs", ")", ":", "if", "value", "is", "noValue", ":", "if", "not", "kwargs", ":", "return", "self", "value", "=", "self", ".", "_value", "initializers", "=", "self", ".", ...
[ 377, 4 ]
[ 443, 52 ]
python
en
['en', 'en', 'en']
True
ConstructedAsn1Type.clone
(self, **kwargs)
Create a modified version of |ASN.1| schema object. The `clone()` method accepts the same set arguments as |ASN.1| class takes on instantiation except that all arguments of the `clone()` method are optional. Whatever arguments are supplied, they are used to create a copy of `se...
Create a modified version of |ASN.1| schema object.
def clone(self, **kwargs): """Create a modified version of |ASN.1| schema object. The `clone()` method accepts the same set arguments as |ASN.1| class takes on instantiation except that all arguments of the `clone()` method are optional. Whatever arguments are supplied, they ar...
[ "def", "clone", "(", "self", ",", "*", "*", "kwargs", ")", ":", "cloneValueFlag", "=", "kwargs", ".", "pop", "(", "'cloneValueFlag'", ",", "False", ")", "initializers", "=", "self", ".", "readOnly", ".", "copy", "(", ")", "initializers", ".", "update", ...
[ 580, 4 ]
[ 613, 20 ]
python
en
['en', 'en', 'en']
True
ConstructedAsn1Type.subtype
(self, **kwargs)
Create a specialization of |ASN.1| schema object. The `subtype()` method accepts the same set arguments as |ASN.1| class takes on instantiation except that all parameters of the `subtype()` method are optional. With the exception of the arguments described below, the rest of su...
Create a specialization of |ASN.1| schema object.
def subtype(self, **kwargs): """Create a specialization of |ASN.1| schema object. The `subtype()` method accepts the same set arguments as |ASN.1| class takes on instantiation except that all parameters of the `subtype()` method are optional. With the exception of the arguments...
[ "def", "subtype", "(", "self", ",", "*", "*", "kwargs", ")", ":", "initializers", "=", "self", ".", "readOnly", ".", "copy", "(", ")", "cloneValueFlag", "=", "kwargs", ".", "pop", "(", "'cloneValueFlag'", ",", "False", ")", "implicitTag", "=", "kwargs", ...
[ 615, 4 ]
[ 677, 20 ]
python
en
['en', 'co', 'en']
True
_byte_string
(s)
Cast a string or byte string to an ASCII byte string.
Cast a string or byte string to an ASCII byte string.
def _byte_string(s): """Cast a string or byte string to an ASCII byte string.""" return s.encode('ASCII')
[ "def", "_byte_string", "(", "s", ")", ":", "return", "s", ".", "encode", "(", "'ASCII'", ")" ]
[ 11, 0 ]
[ 13, 28 ]
python
en
['en', 'en', 'en']
True
_std_string
(s)
Cast a string or byte string to an ASCII string.
Cast a string or byte string to an ASCII string.
def _std_string(s): """Cast a string or byte string to an ASCII string.""" return str(s.decode('ASCII'))
[ "def", "_std_string", "(", "s", ")", ":", "return", "str", "(", "s", ".", "decode", "(", "'ASCII'", ")", ")" ]
[ 18, 0 ]
[ 20, 33 ]
python
en
['en', 'en', 'en']
True
normalize_version_info
(py_version_info)
Convert a tuple of ints representing a Python version to one of length three. :param py_version_info: a tuple of ints representing a Python version, or None to specify no version. The tuple can have any length. :return: a tuple of length three if `py_version_info` is non-None. Otherwi...
Convert a tuple of ints representing a Python version to one of length three.
def normalize_version_info(py_version_info): # type: (Tuple[int, ...]) -> Tuple[int, int, int] """ Convert a tuple of ints representing a Python version to one of length three. :param py_version_info: a tuple of ints representing a Python version, or None to specify no version. The tuple ca...
[ "def", "normalize_version_info", "(", "py_version_info", ")", ":", "# type: (Tuple[int, ...]) -> Tuple[int, int, int]", "if", "len", "(", "py_version_info", ")", "<", "3", ":", "py_version_info", "+=", "(", "3", "-", "len", "(", "py_version_info", ")", ")", "*", "...
[ 85, 0 ]
[ 102, 47 ]
python
en
['en', 'error', 'th']
False
ensure_dir
(path)
os.path.makedirs without EEXIST.
os.path.makedirs without EEXIST.
def ensure_dir(path): # type: (AnyStr) -> None """os.path.makedirs without EEXIST.""" try: os.makedirs(path) except OSError as e: # Windows can raise spurious ENOTEMPTY errors. See #6426. if e.errno != errno.EEXIST and e.errno != errno.ENOTEMPTY: raise
[ "def", "ensure_dir", "(", "path", ")", ":", "# type: (AnyStr) -> None", "try", ":", "os", ".", "makedirs", "(", "path", ")", "except", "OSError", "as", "e", ":", "# Windows can raise spurious ENOTEMPTY errors. See #6426.", "if", "e", ".", "errno", "!=", "errno", ...
[ 105, 0 ]
[ 113, 17 ]
python
en
['en', 'en', 'en']
True
rmtree_errorhandler
(func, path, exc_info)
On Windows, the files in .svn are read-only, so when rmtree() tries to remove them, an exception is thrown. We catch that here, remove the read-only attribute, and hopefully continue without problems.
On Windows, the files in .svn are read-only, so when rmtree() tries to remove them, an exception is thrown. We catch that here, remove the read-only attribute, and hopefully continue without problems.
def rmtree_errorhandler(func, path, exc_info): # type: (Callable[..., Any], str, ExcInfo) -> None """On Windows, the files in .svn are read-only, so when rmtree() tries to remove them, an exception is thrown. We catch that here, remove the read-only attribute, and hopefully continue without problems.""...
[ "def", "rmtree_errorhandler", "(", "func", ",", "path", ",", "exc_info", ")", ":", "# type: (Callable[..., Any], str, ExcInfo) -> None", "try", ":", "has_attr_readonly", "=", "not", "(", "os", ".", "stat", "(", "path", ")", ".", "st_mode", "&", "stat", ".", "S...
[ 137, 0 ]
[ 155, 13 ]
python
en
['en', 'en', 'en']
True
display_path
(path)
Gives the display value for a given path, making it relative to cwd if possible.
Gives the display value for a given path, making it relative to cwd if possible.
def display_path(path): # type: (str) -> str """Gives the display value for a given path, making it relative to cwd if possible.""" path = os.path.normcase(os.path.abspath(path)) if path.startswith(os.getcwd() + os.path.sep): path = "." + path[len(os.getcwd()) :] return path
[ "def", "display_path", "(", "path", ")", ":", "# type: (str) -> str", "path", "=", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "abspath", "(", "path", ")", ")", "if", "path", ".", "startswith", "(", "os", ".", "getcwd", "(", ")",...
[ 158, 0 ]
[ 165, 15 ]
python
en
['en', 'en', 'en']
True
backup_dir
(dir, ext=".bak")
Figure out the name of a directory to back up the given dir to (adding .bak, .bak2, etc)
Figure out the name of a directory to back up the given dir to (adding .bak, .bak2, etc)
def backup_dir(dir, ext=".bak"): # type: (str, str) -> str """Figure out the name of a directory to back up the given dir to (adding .bak, .bak2, etc)""" n = 1 extension = ext while os.path.exists(dir + extension): n += 1 extension = ext + str(n) return dir + extension
[ "def", "backup_dir", "(", "dir", ",", "ext", "=", "\".bak\"", ")", ":", "# type: (str, str) -> str", "n", "=", "1", "extension", "=", "ext", "while", "os", ".", "path", ".", "exists", "(", "dir", "+", "extension", ")", ":", "n", "+=", "1", "extension",...
[ 168, 0 ]
[ 177, 26 ]
python
en
['en', 'en', 'en']
True
_check_no_input
(message)
Raise an error if no input is allowed.
Raise an error if no input is allowed.
def _check_no_input(message): # type: (str) -> None """Raise an error if no input is allowed.""" if os.environ.get("PIP_NO_INPUT"): raise Exception( f"No input was expected ($PIP_NO_INPUT set); question: {message}" )
[ "def", "_check_no_input", "(", "message", ")", ":", "# type: (str) -> None", "if", "os", ".", "environ", ".", "get", "(", "\"PIP_NO_INPUT\"", ")", ":", "raise", "Exception", "(", "f\"No input was expected ($PIP_NO_INPUT set); question: {message}\"", ")" ]
[ 188, 0 ]
[ 194, 9 ]
python
en
['en', 'lb', 'en']
True
ask
(message, options)
Ask the message interactively, with the given possible responses
Ask the message interactively, with the given possible responses
def ask(message, options): # type: (str, Iterable[str]) -> str """Ask the message interactively, with the given possible responses""" while 1: _check_no_input(message) response = input(message) response = response.strip().lower() if response not in options: print(...
[ "def", "ask", "(", "message", ",", "options", ")", ":", "# type: (str, Iterable[str]) -> str", "while", "1", ":", "_check_no_input", "(", "message", ")", "response", "=", "input", "(", "message", ")", "response", "=", "response", ".", "strip", "(", ")", ".",...
[ 197, 0 ]
[ 210, 27 ]
python
en
['en', 'en', 'en']
True
ask_input
(message)
Ask for input interactively.
Ask for input interactively.
def ask_input(message): # type: (str) -> str """Ask for input interactively.""" _check_no_input(message) return input(message)
[ "def", "ask_input", "(", "message", ")", ":", "# type: (str) -> str", "_check_no_input", "(", "message", ")", "return", "input", "(", "message", ")" ]
[ 213, 0 ]
[ 217, 25 ]
python
en
['en', 'en', 'en']
True
ask_password
(message)
Ask for a password interactively.
Ask for a password interactively.
def ask_password(message): # type: (str) -> str """Ask for a password interactively.""" _check_no_input(message) return getpass.getpass(message)
[ "def", "ask_password", "(", "message", ")", ":", "# type: (str) -> str", "_check_no_input", "(", "message", ")", "return", "getpass", ".", "getpass", "(", "message", ")" ]
[ 220, 0 ]
[ 224, 35 ]
python
en
['en', 'en', 'en']
True
strtobool
(val)
Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else.
Convert a string representation of truth to true (1) or false (0).
def strtobool(val): # type: (str) -> int """Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else. """ val = val.lower(...
[ "def", "strtobool", "(", "val", ")", ":", "# type: (str) -> int", "val", "=", "val", ".", "lower", "(", ")", "if", "val", "in", "(", "\"y\"", ",", "\"yes\"", ",", "\"t\"", ",", "\"true\"", ",", "\"on\"", ",", "\"1\"", ")", ":", "return", "1", "elif",...
[ 227, 0 ]
[ 241, 56 ]
python
en
['en', 'pt', 'en']
True
tabulate
(rows)
Return a list of formatted rows and a list of column sizes. For example:: >>> tabulate([['foobar', 2000], [0xdeadbeef]]) (['foobar 2000', '3735928559'], [10, 4])
Return a list of formatted rows and a list of column sizes.
def tabulate(rows): # type: (Iterable[Iterable[Any]]) -> Tuple[List[str], List[int]] """Return a list of formatted rows and a list of column sizes. For example:: >>> tabulate([['foobar', 2000], [0xdeadbeef]]) (['foobar 2000', '3735928559'], [10, 4]) """ rows = [tuple(map(str, row)) for...
[ "def", "tabulate", "(", "rows", ")", ":", "# type: (Iterable[Iterable[Any]]) -> Tuple[List[str], List[int]]", "rows", "=", "[", "tuple", "(", "map", "(", "str", ",", "row", ")", ")", "for", "row", "in", "rows", "]", "sizes", "=", "[", "max", "(", "map", "(...
[ 256, 0 ]
[ 268, 23 ]
python
en
['en', 'en', 'en']
True
is_installable_dir
(path: str)
Is path is a directory containing pyproject.toml or setup.py? If pyproject.toml exists, this is a PEP 517 project. Otherwise we look for a legacy setuptools layout by identifying setup.py. We don't check for the setup.cfg because using it without setup.py is only available for PEP 517 projects, which a...
Is path is a directory containing pyproject.toml or setup.py?
def is_installable_dir(path: str) -> bool: """Is path is a directory containing pyproject.toml or setup.py? If pyproject.toml exists, this is a PEP 517 project. Otherwise we look for a legacy setuptools layout by identifying setup.py. We don't check for the setup.cfg because using it without setup.py i...
[ "def", "is_installable_dir", "(", "path", ":", "str", ")", "->", "bool", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "return", "False", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "("...
[ 271, 0 ]
[ 285, 16 ]
python
en
['en', 'en', 'en']
True
read_chunks
(file, size=io.DEFAULT_BUFFER_SIZE)
Yield pieces of data from a file-like object until EOF.
Yield pieces of data from a file-like object until EOF.
def read_chunks(file, size=io.DEFAULT_BUFFER_SIZE): # type: (BinaryIO, int) -> Iterator[bytes] """Yield pieces of data from a file-like object until EOF.""" while True: chunk = file.read(size) if not chunk: break yield chunk
[ "def", "read_chunks", "(", "file", ",", "size", "=", "io", ".", "DEFAULT_BUFFER_SIZE", ")", ":", "# type: (BinaryIO, int) -> Iterator[bytes]", "while", "True", ":", "chunk", "=", "file", ".", "read", "(", "size", ")", "if", "not", "chunk", ":", "break", "yie...
[ 288, 0 ]
[ 295, 19 ]
python
en
['en', 'en', 'en']
True
normalize_path
(path, resolve_symlinks=True)
Convert a path to its canonical, case-normalized, absolute version.
Convert a path to its canonical, case-normalized, absolute version.
def normalize_path(path, resolve_symlinks=True): # type: (str, bool) -> str """ Convert a path to its canonical, case-normalized, absolute version. """ path = os.path.expanduser(path) if resolve_symlinks: path = os.path.realpath(path) else: path = os.path.abspath(path) r...
[ "def", "normalize_path", "(", "path", ",", "resolve_symlinks", "=", "True", ")", ":", "# type: (str, bool) -> str", "path", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "if", "resolve_symlinks", ":", "path", "=", "os", ".", "path", ".", "re...
[ 298, 0 ]
[ 309, 33 ]
python
en
['en', 'error', 'th']
False
splitext
(path)
Like os.path.splitext, but take off .tar too
Like os.path.splitext, but take off .tar too
def splitext(path): # type: (str) -> Tuple[str, str] """Like os.path.splitext, but take off .tar too""" base, ext = posixpath.splitext(path) if base.lower().endswith(".tar"): ext = base[-4:] + ext base = base[:-4] return base, ext
[ "def", "splitext", "(", "path", ")", ":", "# type: (str) -> Tuple[str, str]", "base", ",", "ext", "=", "posixpath", ".", "splitext", "(", "path", ")", "if", "base", ".", "lower", "(", ")", ".", "endswith", "(", "\".tar\"", ")", ":", "ext", "=", "base", ...
[ 312, 0 ]
[ 319, 20 ]
python
en
['en', 'en', 'en']
True
renames
(old, new)
Like os.renames(), but handles renaming across devices.
Like os.renames(), but handles renaming across devices.
def renames(old, new): # type: (str, str) -> None """Like os.renames(), but handles renaming across devices.""" # Implementation borrowed from os.renames(). head, tail = os.path.split(new) if head and tail and not os.path.exists(head): os.makedirs(head) shutil.move(old, new) head, ...
[ "def", "renames", "(", "old", ",", "new", ")", ":", "# type: (str, str) -> None", "# Implementation borrowed from os.renames().", "head", ",", "tail", "=", "os", ".", "path", ".", "split", "(", "new", ")", "if", "head", "and", "tail", "and", "not", "os", "."...
[ 322, 0 ]
[ 337, 16 ]
python
en
['en', 'en', 'en']
True
is_local
(path)
Return True if path is within sys.prefix, if we're running in a virtualenv. If we're not in a virtualenv, all paths are considered "local." Caution: this function assumes the head of path has been normalized with normalize_path.
Return True if path is within sys.prefix, if we're running in a virtualenv.
def is_local(path): # type: (str) -> bool """ Return True if path is within sys.prefix, if we're running in a virtualenv. If we're not in a virtualenv, all paths are considered "local." Caution: this function assumes the head of path has been normalized with normalize_path. """ if not ...
[ "def", "is_local", "(", "path", ")", ":", "# type: (str) -> bool", "if", "not", "running_under_virtualenv", "(", ")", ":", "return", "True", "return", "path", ".", "startswith", "(", "normalize_path", "(", "sys", ".", "prefix", ")", ")" ]
[ 340, 0 ]
[ 352, 54 ]
python
en
['en', 'error', 'th']
False
dist_is_local
(dist)
Return True if given Distribution object is installed locally (i.e. within current virtualenv). Always True if we're not in a virtualenv.
Return True if given Distribution object is installed locally (i.e. within current virtualenv).
def dist_is_local(dist): # type: (Distribution) -> bool """ Return True if given Distribution object is installed locally (i.e. within current virtualenv). Always True if we're not in a virtualenv. """ return is_local(dist_location(dist))
[ "def", "dist_is_local", "(", "dist", ")", ":", "# type: (Distribution) -> bool", "return", "is_local", "(", "dist_location", "(", "dist", ")", ")" ]
[ 355, 0 ]
[ 364, 40 ]
python
en
['en', 'error', 'th']
False
dist_in_usersite
(dist)
Return True if given Distribution is installed in user site.
Return True if given Distribution is installed in user site.
def dist_in_usersite(dist): # type: (Distribution) -> bool """ Return True if given Distribution is installed in user site. """ return dist_location(dist).startswith(normalize_path(user_site))
[ "def", "dist_in_usersite", "(", "dist", ")", ":", "# type: (Distribution) -> bool", "return", "dist_location", "(", "dist", ")", ".", "startswith", "(", "normalize_path", "(", "user_site", ")", ")" ]
[ 367, 0 ]
[ 372, 68 ]
python
en
['en', 'error', 'th']
False
dist_in_site_packages
(dist)
Return True if given Distribution is installed in sysconfig.get_python_lib().
Return True if given Distribution is installed in sysconfig.get_python_lib().
def dist_in_site_packages(dist): # type: (Distribution) -> bool """ Return True if given Distribution is installed in sysconfig.get_python_lib(). """ return dist_location(dist).startswith(normalize_path(site_packages))
[ "def", "dist_in_site_packages", "(", "dist", ")", ":", "# type: (Distribution) -> bool", "return", "dist_location", "(", "dist", ")", ".", "startswith", "(", "normalize_path", "(", "site_packages", ")", ")" ]
[ 375, 0 ]
[ 381, 72 ]
python
en
['en', 'error', 'th']
False
dist_is_editable
(dist)
Return True if given Distribution is an editable install.
Return True if given Distribution is an editable install.
def dist_is_editable(dist): # type: (Distribution) -> bool """ Return True if given Distribution is an editable install. """ for path_item in sys.path: egg_link = os.path.join(path_item, dist.project_name + ".egg-link") if os.path.isfile(egg_link): return True return ...
[ "def", "dist_is_editable", "(", "dist", ")", ":", "# type: (Distribution) -> bool", "for", "path_item", "in", "sys", ".", "path", ":", "egg_link", "=", "os", ".", "path", ".", "join", "(", "path_item", ",", "dist", ".", "project_name", "+", "\".egg-link\"", ...
[ 384, 0 ]
[ 393, 16 ]
python
en
['en', 'error', 'th']
False
get_installed_distributions
( local_only=True, # type: bool skip=stdlib_pkgs, # type: Container[str] include_editables=True, # type: bool editables_only=False, # type: bool user_only=False, # type: bool paths=None, # type: Optional[List[str]] )
Return a list of installed Distribution objects. Left for compatibility until direct pkg_resources uses are refactored out.
Return a list of installed Distribution objects.
def get_installed_distributions( local_only=True, # type: bool skip=stdlib_pkgs, # type: Container[str] include_editables=True, # type: bool editables_only=False, # type: bool user_only=False, # type: bool paths=None, # type: Optional[List[str]] ): # type: (...) -> List[Distribution] ...
[ "def", "get_installed_distributions", "(", "local_only", "=", "True", ",", "# type: bool", "skip", "=", "stdlib_pkgs", ",", "# type: Container[str]", "include_editables", "=", "True", ",", "# type: bool", "editables_only", "=", "False", ",", "# type: bool", "user_only",...
[ 396, 0 ]
[ 423, 54 ]
python
en
['en', 'en', 'en']
True
get_distribution
(req_name)
Given a requirement name, return the installed Distribution object. This searches from *all* distributions available in the environment, to match the behavior of ``pkg_resources.get_distribution()``. Left for compatibility until direct pkg_resources uses are refactored out.
Given a requirement name, return the installed Distribution object.
def get_distribution(req_name): # type: (str) -> Optional[Distribution] """Given a requirement name, return the installed Distribution object. This searches from *all* distributions available in the environment, to match the behavior of ``pkg_resources.get_distribution()``. Left for compatibility ...
[ "def", "get_distribution", "(", "req_name", ")", ":", "# type: (str) -> Optional[Distribution]", "from", "pip", ".", "_internal", ".", "metadata", "import", "get_default_environment", "from", "pip", ".", "_internal", ".", "metadata", ".", "pkg_resources", "import", "D...
[ 426, 0 ]
[ 441, 34 ]
python
en
['en', 'en', 'en']
True
egg_link_path
(dist)
Return the path for the .egg-link file if it exists, otherwise, None. There's 3 scenarios: 1) not in a virtualenv try to find in site.USER_SITE, then site_packages 2) in a no-global virtualenv try to find in site_packages 3) in a yes-global virtualenv try to find in site_packa...
Return the path for the .egg-link file if it exists, otherwise, None.
def egg_link_path(dist): # type: (Distribution) -> Optional[str] """ Return the path for the .egg-link file if it exists, otherwise, None. There's 3 scenarios: 1) not in a virtualenv try to find in site.USER_SITE, then site_packages 2) in a no-global virtualenv try to find in site...
[ "def", "egg_link_path", "(", "dist", ")", ":", "# type: (Distribution) -> Optional[str]", "sites", "=", "[", "]", "if", "running_under_virtualenv", "(", ")", ":", "sites", ".", "append", "(", "site_packages", ")", "if", "not", "virtualenv_no_global", "(", ")", "...
[ 444, 0 ]
[ 477, 15 ]
python
en
['en', 'error', 'th']
False
dist_location
(dist)
Get the site-packages location of this distribution. Generally this is dist.location, except in the case of develop-installed packages, where dist.location is the source code location, and we want to know where the egg-link file is. The returned location is normalized (in particular, with symlinks...
Get the site-packages location of this distribution. Generally this is dist.location, except in the case of develop-installed packages, where dist.location is the source code location, and we want to know where the egg-link file is.
def dist_location(dist): # type: (Distribution) -> str """ Get the site-packages location of this distribution. Generally this is dist.location, except in the case of develop-installed packages, where dist.location is the source code location, and we want to know where the egg-link file is. ...
[ "def", "dist_location", "(", "dist", ")", ":", "# type: (Distribution) -> str", "egg_link", "=", "egg_link_path", "(", "dist", ")", "if", "egg_link", ":", "return", "normalize_path", "(", "egg_link", ")", "return", "normalize_path", "(", "dist", ".", "location", ...
[ 480, 0 ]
[ 493, 40 ]
python
en
['en', 'error', 'th']
False
captured_output
(stream_name)
Return a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO. Taken from Lib/support/__init__.py in the CPython repo.
Return a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO.
def captured_output(stream_name): # type: (str) -> Iterator[StreamWrapper] """Return a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO. Taken from Lib/support/__init__.py in the CPython repo. """ orig_stdout = getattr(s...
[ "def", "captured_output", "(", "stream_name", ")", ":", "# type: (str) -> Iterator[StreamWrapper]", "orig_stdout", "=", "getattr", "(", "sys", ",", "stream_name", ")", "setattr", "(", "sys", ",", "stream_name", ",", "StreamWrapper", ".", "from_stream", "(", "orig_st...
[ 518, 0 ]
[ 530, 46 ]
python
en
['en', 'en', 'en']
True
captured_stdout
()
Capture the output of sys.stdout: with captured_stdout() as stdout: print('hello') self.assertEqual(stdout.getvalue(), 'hello\n') Taken from Lib/support/__init__.py in the CPython repo.
Capture the output of sys.stdout:
def captured_stdout(): # type: () -> ContextManager[StreamWrapper] """Capture the output of sys.stdout: with captured_stdout() as stdout: print('hello') self.assertEqual(stdout.getvalue(), 'hello\n') Taken from Lib/support/__init__.py in the CPython repo. """ return captur...
[ "def", "captured_stdout", "(", ")", ":", "# type: () -> ContextManager[StreamWrapper]", "return", "captured_output", "(", "\"stdout\"", ")" ]
[ 533, 0 ]
[ 543, 36 ]
python
en
['en', 'en', 'en']
True
captured_stderr
()
See captured_stdout().
See captured_stdout().
def captured_stderr(): # type: () -> ContextManager[StreamWrapper] """ See captured_stdout(). """ return captured_output("stderr")
[ "def", "captured_stderr", "(", ")", ":", "# type: () -> ContextManager[StreamWrapper]", "return", "captured_output", "(", "\"stderr\"", ")" ]
[ 546, 0 ]
[ 551, 36 ]
python
en
['en', 'error', 'th']
False
build_netloc
(host, port)
Build a netloc from a host-port pair
Build a netloc from a host-port pair
def build_netloc(host, port): # type: (str, Optional[int]) -> str """ Build a netloc from a host-port pair """ if port is None: return host if ":" in host: # Only wrap host with square brackets when it is IPv6 host = f"[{host}]" return f"{host}:{port}"
[ "def", "build_netloc", "(", "host", ",", "port", ")", ":", "# type: (str, Optional[int]) -> str", "if", "port", "is", "None", ":", "return", "host", "if", "\":\"", "in", "host", ":", "# Only wrap host with square brackets when it is IPv6", "host", "=", "f\"[{host}]\""...
[ 563, 0 ]
[ 573, 27 ]
python
en
['en', 'error', 'th']
False
build_url_from_netloc
(netloc, scheme="https")
Build a full URL from a netloc.
Build a full URL from a netloc.
def build_url_from_netloc(netloc, scheme="https"): # type: (str, str) -> str """ Build a full URL from a netloc. """ if netloc.count(":") >= 2 and "@" not in netloc and "[" not in netloc: # It must be a bare IPv6 address, so wrap it with brackets. netloc = f"[{netloc}]" return f"...
[ "def", "build_url_from_netloc", "(", "netloc", ",", "scheme", "=", "\"https\"", ")", ":", "# type: (str, str) -> str", "if", "netloc", ".", "count", "(", "\":\"", ")", ">=", "2", "and", "\"@\"", "not", "in", "netloc", "and", "\"[\"", "not", "in", "netloc", ...
[ 576, 0 ]
[ 584, 33 ]
python
en
['en', 'error', 'th']
False
parse_netloc
(netloc)
Return the host-port pair from a netloc.
Return the host-port pair from a netloc.
def parse_netloc(netloc): # type: (str) -> Tuple[str, Optional[int]] """ Return the host-port pair from a netloc. """ url = build_url_from_netloc(netloc) parsed = urllib.parse.urlparse(url) return parsed.hostname, parsed.port
[ "def", "parse_netloc", "(", "netloc", ")", ":", "# type: (str) -> Tuple[str, Optional[int]]", "url", "=", "build_url_from_netloc", "(", "netloc", ")", "parsed", "=", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", "return", "parsed", ".", "hostname", "...
[ 587, 0 ]
[ 594, 39 ]
python
en
['en', 'error', 'th']
False
split_auth_from_netloc
(netloc)
Parse out and remove the auth information from a netloc. Returns: (netloc, (username, password)).
Parse out and remove the auth information from a netloc.
def split_auth_from_netloc(netloc): # type: (str) -> NetlocTuple """ Parse out and remove the auth information from a netloc. Returns: (netloc, (username, password)). """ if "@" not in netloc: return netloc, (None, None) # Split from the right because that's how urllib.parse.urlspl...
[ "def", "split_auth_from_netloc", "(", "netloc", ")", ":", "# type: (str) -> NetlocTuple", "if", "\"@\"", "not", "in", "netloc", ":", "return", "netloc", ",", "(", "None", ",", "None", ")", "# Split from the right because that's how urllib.parse.urlsplit()", "# behaves if ...
[ 597, 0 ]
[ 624, 29 ]
python
en
['en', 'error', 'th']
False
redact_netloc
(netloc)
Replace the sensitive data in a netloc with "****", if it exists. For example: - "user:pass@example.com" returns "user:****@example.com" - "accesstoken@example.com" returns "****@example.com"
Replace the sensitive data in a netloc with "****", if it exists.
def redact_netloc(netloc): # type: (str) -> str """ Replace the sensitive data in a netloc with "****", if it exists. For example: - "user:pass@example.com" returns "user:****@example.com" - "accesstoken@example.com" returns "****@example.com" """ netloc, (user, password) = spli...
[ "def", "redact_netloc", "(", "netloc", ")", ":", "# type: (str) -> str", "netloc", ",", "(", "user", ",", "password", ")", "=", "split_auth_from_netloc", "(", "netloc", ")", "if", "user", "is", "None", ":", "return", "netloc", "if", "password", "is", "None",...
[ 627, 0 ]
[ 647, 5 ]
python
en
['en', 'error', 'th']
False
_transform_url
(url, transform_netloc)
Transform and replace netloc in a url. transform_netloc is a function taking the netloc and returning a tuple. The first element of this tuple is the new netloc. The entire tuple is returned. Returns a tuple containing the transformed url as item 0 and the original tuple returned by transform_netl...
Transform and replace netloc in a url.
def _transform_url(url, transform_netloc): # type: (str, Callable[[str], Tuple[Any, ...]]) -> Tuple[str, NetlocTuple] """Transform and replace netloc in a url. transform_netloc is a function taking the netloc and returning a tuple. The first element of this tuple is the new netloc. The entire tuple...
[ "def", "_transform_url", "(", "url", ",", "transform_netloc", ")", ":", "# type: (str, Callable[[str], Tuple[Any, ...]]) -> Tuple[str, NetlocTuple]", "purl", "=", "urllib", ".", "parse", ".", "urlsplit", "(", "url", ")", "netloc_tuple", "=", "transform_netloc", "(", "pu...
[ 650, 0 ]
[ 666, 50 ]
python
en
['en', 'en', 'en']
True
split_auth_netloc_from_url
(url)
Parse a url into separate netloc, auth, and url with no auth. Returns: (url_without_auth, netloc, (username, password))
Parse a url into separate netloc, auth, and url with no auth.
def split_auth_netloc_from_url(url): # type: (str) -> Tuple[str, str, Tuple[str, str]] """ Parse a url into separate netloc, auth, and url with no auth. Returns: (url_without_auth, netloc, (username, password)) """ url_without_auth, (netloc, auth) = _transform_url(url, _get_netloc) return u...
[ "def", "split_auth_netloc_from_url", "(", "url", ")", ":", "# type: (str) -> Tuple[str, str, Tuple[str, str]]", "url_without_auth", ",", "(", "netloc", ",", "auth", ")", "=", "_transform_url", "(", "url", ",", "_get_netloc", ")", "return", "url_without_auth", ",", "ne...
[ 679, 0 ]
[ 687, 41 ]
python
en
['en', 'error', 'th']
False
remove_auth_from_url
(url)
Return a copy of url with 'username:password@' removed.
Return a copy of url with 'username:password
def remove_auth_from_url(url): # type: (str) -> str """Return a copy of url with 'username:password@' removed.""" # username/pass params are passed to subversion through flags # and are not recognized in the url. return _transform_url(url, _get_netloc)[0]
[ "def", "remove_auth_from_url", "(", "url", ")", ":", "# type: (str) -> str", "# username/pass params are passed to subversion through flags", "# and are not recognized in the url.", "return", "_transform_url", "(", "url", ",", "_get_netloc", ")", "[", "0", "]" ]
[ 690, 0 ]
[ 695, 46 ]
python
en
['en', 'en', 'en']
True
redact_auth_from_url
(url)
Replace the password in a given url with ****.
Replace the password in a given url with ****.
def redact_auth_from_url(url): # type: (str) -> str """Replace the password in a given url with ****.""" return _transform_url(url, _redact_netloc)[0]
[ "def", "redact_auth_from_url", "(", "url", ")", ":", "# type: (str) -> str", "return", "_transform_url", "(", "url", ",", "_redact_netloc", ")", "[", "0", "]" ]
[ 698, 0 ]
[ 701, 49 ]
python
en
['en', 'en', 'en']
True
protect_pip_from_modification_on_windows
(modifying_pip)
Protection of pip.exe from modification on Windows On Windows, any operation modifying pip should be run as: python -m pip ...
Protection of pip.exe from modification on Windows
def protect_pip_from_modification_on_windows(modifying_pip): # type: (bool) -> None """Protection of pip.exe from modification on Windows On Windows, any operation modifying pip should be run as: python -m pip ... """ pip_names = [ "pip.exe", "pip{}.exe".format(sys.version_i...
[ "def", "protect_pip_from_modification_on_windows", "(", "modifying_pip", ")", ":", "# type: (bool) -> None", "pip_names", "=", "[", "\"pip.exe\"", ",", "\"pip{}.exe\"", ".", "format", "(", "sys", ".", "version_info", "[", "0", "]", ")", ",", "\"pip{}.{}.exe\"", ".",...
[ 744, 0 ]
[ 768, 9 ]
python
en
['en', 'en', 'en']
True
is_console_interactive
()
Is this console interactive?
Is this console interactive?
def is_console_interactive(): # type: () -> bool """Is this console interactive?""" return sys.stdin is not None and sys.stdin.isatty()
[ "def", "is_console_interactive", "(", ")", ":", "# type: () -> bool", "return", "sys", ".", "stdin", "is", "not", "None", "and", "sys", ".", "stdin", ".", "isatty", "(", ")" ]
[ 771, 0 ]
[ 774, 55 ]
python
en
['en', 'en', 'en']
True
hash_file
(path, blocksize=1 << 20)
Return (hash, length) for path using hashlib.sha256()
Return (hash, length) for path using hashlib.sha256()
def hash_file(path, blocksize=1 << 20): # type: (str, int) -> Tuple[Any, int] """Return (hash, length) for path using hashlib.sha256()""" h = hashlib.sha256() length = 0 with open(path, "rb") as f: for block in read_chunks(f, size=blocksize): length += len(block) h.u...
[ "def", "hash_file", "(", "path", ",", "blocksize", "=", "1", "<<", "20", ")", ":", "# type: (str, int) -> Tuple[Any, int]", "h", "=", "hashlib", ".", "sha256", "(", ")", "length", "=", "0", "with", "open", "(", "path", ",", "\"rb\"", ")", "as", "f", ":...
[ 777, 0 ]
[ 787, 20 ]
python
en
['en', 'hi-Latn', 'en']
True
is_wheel_installed
()
Return whether the wheel package is installed.
Return whether the wheel package is installed.
def is_wheel_installed(): # type: () -> bool """ Return whether the wheel package is installed. """ try: import wheel # noqa: F401 except ImportError: return False return True
[ "def", "is_wheel_installed", "(", ")", ":", "# type: () -> bool", "try", ":", "import", "wheel", "# noqa: F401", "except", "ImportError", ":", "return", "False", "return", "True" ]
[ 790, 0 ]
[ 800, 15 ]
python
en
['en', 'error', 'th']
False
pairwise
(iterable)
Return paired elements. For example: s -> (s0, s1), (s2, s3), (s4, s5), ...
Return paired elements.
def pairwise(iterable): # type: (Iterable[Any]) -> Iterator[Tuple[Any, Any]] """ Return paired elements. For example: s -> (s0, s1), (s2, s3), (s4, s5), ... """ iterable = iter(iterable) return zip_longest(iterable, iterable)
[ "def", "pairwise", "(", "iterable", ")", ":", "# type: (Iterable[Any]) -> Iterator[Tuple[Any, Any]]", "iterable", "=", "iter", "(", "iterable", ")", "return", "zip_longest", "(", "iterable", ",", "iterable", ")" ]
[ 803, 0 ]
[ 812, 42 ]
python
en
['en', 'error', 'th']
False
partition
( pred, # type: Callable[[T], bool] iterable, # type: Iterable[T] )
Use a predicate to partition entries into false entries and true entries, like partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
Use a predicate to partition entries into false entries and true entries, like
def partition( pred, # type: Callable[[T], bool] iterable, # type: Iterable[T] ): # type: (...) -> Tuple[Iterable[T], Iterable[T]] """ Use a predicate to partition entries into false entries and true entries, like partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9 """ ...
[ "def", "partition", "(", "pred", ",", "# type: Callable[[T], bool]", "iterable", ",", "# type: Iterable[T]", ")", ":", "# type: (...) -> Tuple[Iterable[T], Iterable[T]]", "t1", ",", "t2", "=", "tee", "(", "iterable", ")", "return", "filterfalse", "(", "pred", ",", "...
[ 815, 0 ]
[ 827, 50 ]
python
en
['en', 'error', 'th']
False
extract_all_gold_standard_data
(data_dir, nprocesses=1, overwrite=False, **kwargs)
Extract the gold standard block-level content and comment percentages from a directory of labeled data (only those for which the gold standard blocks are not found), and save results to corresponding files in a block-level gold standard directory under ``data_dir``. Args: data_dir (str): D...
Extract the gold standard block-level content and comment percentages from a directory of labeled data (only those for which the gold standard blocks are not found), and save results to corresponding files in a block-level gold standard directory under ``data_dir``.
def extract_all_gold_standard_data(data_dir, nprocesses=1, overwrite=False, **kwargs): """ Extract the gold standard block-level content and comment percentages from a directory of labeled data (only those for which the gold standard blocks are not found), and save res...
[ "def", "extract_all_gold_standard_data", "(", "data_dir", ",", "nprocesses", "=", "1", ",", "overwrite", "=", "False", ",", "*", "*", "kwargs", ")", ":", "use_pool", "=", "nprocesses", ">", "1", "if", "use_pool", ":", "pool", "=", "multiprocessing", ".", "...
[ 28, 0 ]
[ 85, 19 ]
python
en
['en', 'error', 'th']
False
extract_gold_standard_blocks
(data_dir, fileroot, encoding=None, tokenizer=simple_tokenizer, cetr=False)
Extract the gold standard block-level content and comments for a single observation identified by ``fileroot``, and write the results to file. Args: data_dir (str): The root directory containing sub-directories for raw HTML, gold standard extracted content, and gold standard blocks. ...
Extract the gold standard block-level content and comments for a single observation identified by ``fileroot``, and write the results to file.
def extract_gold_standard_blocks(data_dir, fileroot, encoding=None, tokenizer=simple_tokenizer, cetr=False): """ Extract the gold standard block-level content and comments for a single observation identified by ``fileroot``, and write the results to file. Args: ...
[ "def", "extract_gold_standard_blocks", "(", "data_dir", ",", "fileroot", ",", "encoding", "=", "None", ",", "tokenizer", "=", "simple_tokenizer", ",", "cetr", "=", "False", ")", ":", "# read the raw html, split it into blocks, and tokenize each block", "raw_html", "=", ...
[ 88, 0 ]
[ 195, 25 ]
python
en
['en', 'error', 'th']
False
get_filenames
(dirname, full_path=False, match_regex=None, extension=None)
Get all filenames under ``dirname`` that match ``match_regex`` or have file extension equal to ``extension``, optionally prepending the full path. Args: dirname (str): /path/to/dir on disk where files to read are saved full_path (bool): if False, return filenames without path; if True, ...
Get all filenames under ``dirname`` that match ``match_regex`` or have file extension equal to ``extension``, optionally prepending the full path.
def get_filenames(dirname, full_path=False, match_regex=None, extension=None): """ Get all filenames under ``dirname`` that match ``match_regex`` or have file extension equal to ``extension``, optionally prepending the full path. Args: dirname (str): /path/to/dir on disk where files to read are...
[ "def", "get_filenames", "(", "dirname", ",", "full_path", "=", "False", ",", "match_regex", "=", "None", ",", "extension", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "dirname", ")", ":", "raise", "OSError", "(", "'direct...
[ 198, 0 ]
[ 225, 26 ]
python
en
['en', 'error', 'th']
False
read_html_file
(data_dir, fileroot, encoding=None)
Read the HTML file corresponding to identifier ``fileroot`` in the raw HTML directory below the root ``data_dir``. Args: data_dir (str) fileroot (str) encoding (str) Returns: str
Read the HTML file corresponding to identifier ``fileroot`` in the raw HTML directory below the root ``data_dir``.
def read_html_file(data_dir, fileroot, encoding=None): """ Read the HTML file corresponding to identifier ``fileroot`` in the raw HTML directory below the root ``data_dir``. Args: data_dir (str) fileroot (str) encoding (str) Returns: str """ fname = os.path....
[ "def", "read_html_file", "(", "data_dir", ",", "fileroot", ",", "encoding", "=", "None", ")", ":", "fname", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "RAW_HTML_DIRNAME", ",", "fileroot", "+", "RAW_HTML_EXT", ")", "encodings", "=", "(", "...
[ 228, 0 ]
[ 252, 46 ]
python
en
['en', 'error', 'th']
False
read_gold_standard_file
(data_dir, fileroot, encoding=None, cetr=False)
Read the gold standard content file corresponding to identifier ``fileroot`` in the gold standard directory below the root ``data_dir``. Args: data_dir (str) fileroot (str) encoding (str) cetr (bool): if True, assume no comments and parse the gold standard to re...
Read the gold standard content file corresponding to identifier ``fileroot`` in the gold standard directory below the root ``data_dir``.
def read_gold_standard_file(data_dir, fileroot, encoding=None, cetr=False): """ Read the gold standard content file corresponding to identifier ``fileroot`` in the gold standard directory below the root ``data_dir``. Args: data_dir (str) fileroot (str) encoding (str) cet...
[ "def", "read_gold_standard_file", "(", "data_dir", ",", "fileroot", ",", "encoding", "=", "None", ",", "cetr", "=", "False", ")", ":", "fname", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "GOLD_STANDARD_DIRNAME", ",", "fileroot", "+", "GOLD_...
[ 255, 0 ]
[ 297, 27 ]
python
en
['en', 'error', 'th']
False
read_gold_standard_blocks_file
(data_dir, fileroot, split_blocks=True)
Read the gold standard blocks file corresponding to identifier ``fileroot`` in the gold standard blocks directory below the root ``data_dir``. Args: data_dir (str) fileroot (str) split_blocks (bool): If True, split the file's content into blocks. Returns: str or List[s...
Read the gold standard blocks file corresponding to identifier ``fileroot`` in the gold standard blocks directory below the root ``data_dir``.
def read_gold_standard_blocks_file(data_dir, fileroot, split_blocks=True): """ Read the gold standard blocks file corresponding to identifier ``fileroot`` in the gold standard blocks directory below the root ``data_dir``. Args: data_dir (str) fileroot (str) split_blocks (bool): ...
[ "def", "read_gold_standard_blocks_file", "(", "data_dir", ",", "fileroot", ",", "split_blocks", "=", "True", ")", ":", "fname", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "GOLD_STANDARD_BLOCKS_DIRNAME", ",", "fileroot", "+", "GOLD_STANDARD_BLOCKS_E...
[ 300, 0 ]
[ 319, 29 ]
python
en
['en', 'error', 'th']
False
prepare_data
(data_dir, fileroot, block_pct_tokens_thresh=0.1)
Prepare data for a single HTML + gold standard blocks example, uniquely identified by ``fileroot``. Args: data_dir (str) fileroot (str) block_pct_tokens_thresh (float): must be in [0.0, 1.0] Returns: Tuple[str, Tuple[np.array[int], np.array[int], List[str]], Tuple[np.a...
Prepare data for a single HTML + gold standard blocks example, uniquely identified by ``fileroot``.
def prepare_data(data_dir, fileroot, block_pct_tokens_thresh=0.1): """ Prepare data for a single HTML + gold standard blocks example, uniquely identified by ``fileroot``. Args: data_dir (str) fileroot (str) block_pct_tokens_thresh (float): must be in [0.0, 1.0] Returns: ...
[ "def", "prepare_data", "(", "data_dir", ",", "fileroot", ",", "block_pct_tokens_thresh", "=", "0.1", ")", ":", "if", "not", "0.0", "<=", "block_pct_tokens_thresh", "<=", "1.0", ":", "raise", "ValueError", "(", "'block_pct_tokens_thresh must be in the range [0.0, 1.0]'",...
[ 330, 0 ]
[ 376, 64 ]
python
en
['en', 'error', 'th']
False
prepare_all_data
(data_dir, block_pct_tokens_thresh=0.1)
Prepare data for all HTML + gold standard blocks examples in ``data_dir``. Args: data_dir (str) block_pct_tokens_thresh (float): must be in [0.0, 1.0] Returns: List[Tuple[str, List[float, int, List[str]], List[float, int, List[str]]]] See Also: :func:`prepare_data` ...
Prepare data for all HTML + gold standard blocks examples in ``data_dir``.
def prepare_all_data(data_dir, block_pct_tokens_thresh=0.1): """ Prepare data for all HTML + gold standard blocks examples in ``data_dir``. Args: data_dir (str) block_pct_tokens_thresh (float): must be in [0.0, 1.0] Returns: List[Tuple[str, List[float, int, List[str]], List[flo...
[ "def", "prepare_all_data", "(", "data_dir", ",", "block_pct_tokens_thresh", "=", "0.1", ")", ":", "gs_blocks_dir", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "GOLD_STANDARD_BLOCKS_DIRNAME", ")", "gs_blocks_filenames", "=", "get_filenames", "(", "gs...
[ 379, 0 ]
[ 401, 48 ]
python
en
['en', 'error', 'th']
False
rnn_multistation_sampling_temperature_sequencer
(filenames, resample_by=1, batch_size=sys.maxsize, sequence_size=sys.maxsize, n_forward=0, nb_epochs=1, tminmax=False, keepinmem=True)
Loads temperature data from CSV files. Each data sequence is resampled by "resample_by". Use 1 not to resample. The data is also shifted by n_forward after resampling to generate target training sequences. n_forward is typically 1 but can be 0 to disable shifting or >1 to train to predict further in ad...
Loads temperature data from CSV files. Each data sequence is resampled by "resample_by". Use 1 not to resample. The data is also shifted by n_forward after resampling to generate target training sequences. n_forward is typically 1 but can be 0 to disable shifting or >1 to train to predict further in ad...
def rnn_multistation_sampling_temperature_sequencer(filenames, resample_by=1, batch_size=sys.maxsize, sequence_size=sys.maxsize, n_forward=0, nb_epochs=1, tminmax=False, keepinmem=True): """ Loads temperature data from CSV files. Each data sequence is resampled by "resample_by". Use 1 not to resample. T...
[ "def", "rnn_multistation_sampling_temperature_sequencer", "(", "filenames", ",", "resample_by", "=", "1", ",", "batch_size", "=", "sys", ".", "maxsize", ",", "sequence_size", "=", "sys", ".", "maxsize", ",", "n_forward", "=", "0", ",", "nb_epochs", "=", "1", "...
[ 21, 0 ]
[ 112, 37 ]
python
en
['en', 'error', 'th']
False
rnn_minibatch_sequencer
(data, batch_size, sequence_size, nb_epochs)
Divides the data into batches of sequences so that all the sequences in one batch continue in the next batch. This is a generator that will keep returning batches until the input data has been seen nb_epochs times. Sequences are continued even between epochs, apart from one, the one corresponding to th...
Divides the data into batches of sequences so that all the sequences in one batch continue in the next batch. This is a generator that will keep returning batches until the input data has been seen nb_epochs times. Sequences are continued even between epochs, apart from one, the one corresponding to th...
def rnn_minibatch_sequencer(data, batch_size, sequence_size, nb_epochs): """ Divides the data into batches of sequences so that all the sequences in one batch continue in the next batch. This is a generator that will keep returning batches until the input data has been seen nb_epochs times. Sequences ar...
[ "def", "rnn_minibatch_sequencer", "(", "data", ",", "batch_size", ",", "sequence_size", ",", "nb_epochs", ")", ":", "data_len", "=", "data", ".", "shape", "[", "0", "]", "# using (data_len-1) because we must provide for the sequence shifted by 1 too", "nb_batches", "=", ...
[ 115, 0 ]
[ 149, 29 ]
python
en
['en', 'error', 'th']
False
dumb_minibatch_sequencer
(data, batch_size, sequence_size, nb_epochs)
Divides the data into batches of sequences in the simplest way: sequentially. :param data: the training sequence :param batch_size: the size of a training minibatch :param sequence_size: the unroll size of the RNN :param nb_epochs: number of epochs to train on :return: x: one batch of t...
Divides the data into batches of sequences in the simplest way: sequentially. :param data: the training sequence :param batch_size: the size of a training minibatch :param sequence_size: the unroll size of the RNN :param nb_epochs: number of epochs to train on :return: x: one batch of t...
def dumb_minibatch_sequencer(data, batch_size, sequence_size, nb_epochs): """ Divides the data into batches of sequences in the simplest way: sequentially. :param data: the training sequence :param batch_size: the size of a training minibatch :param sequence_size: the unroll size of the RNN :par...
[ "def", "dumb_minibatch_sequencer", "(", "data", ",", "batch_size", ",", "sequence_size", ",", "nb_epochs", ")", ":", "data_len", "=", "data", ".", "shape", "[", "0", "]", "nb_batches", "=", "data_len", "//", "(", "batch_size", "*", "sequence_size", ")", "rou...
[ 152, 0 ]
[ 174, 59 ]
python
en
['en', 'error', 'th']
False
release_local
(local)
Releases the contents of the local for the current context. This makes it possible to use locals without a manager. Example:: >>> loc = Local() >>> loc.foo = 42 >>> release_local(loc) >>> hasattr(loc, 'foo') False With this function one can release :class:`Local` o...
Releases the contents of the local for the current context. This makes it possible to use locals without a manager.
def release_local(local): """Releases the contents of the local for the current context. This makes it possible to use locals without a manager. Example:: >>> loc = Local() >>> loc.foo = 42 >>> release_local(loc) >>> hasattr(loc, 'foo') False With this function...
[ "def", "release_local", "(", "local", ")", ":", "local", ".", "__release_local__", "(", ")" ]
[ 29, 0 ]
[ 49, 29 ]
python
en
['en', 'en', 'en']
True
Local.__call__
(self, proxy)
Create a proxy for a name.
Create a proxy for a name.
def __call__(self, proxy): """Create a proxy for a name.""" return LocalProxy(self, proxy)
[ "def", "__call__", "(", "self", ",", "proxy", ")", ":", "return", "LocalProxy", "(", "self", ",", "proxy", ")" ]
[ 62, 4 ]
[ 64, 38 ]
python
en
['en', 'en', 'en']
True
LocalStack.push
(self, obj)
Pushes a new item to the stack
Pushes a new item to the stack
def push(self, obj): """Pushes a new item to the stack""" rv = getattr(self._local, "stack", None) if rv is None: self._local.stack = rv = [] rv.append(obj) return rv
[ "def", "push", "(", "self", ",", "obj", ")", ":", "rv", "=", "getattr", "(", "self", ".", "_local", ",", "\"stack\"", ",", "None", ")", "if", "rv", "is", "None", ":", "self", ".", "_local", ".", "stack", "=", "rv", "=", "[", "]", "rv", ".", "...
[ 141, 4 ]
[ 147, 17 ]
python
en
['en', 'en', 'en']
True
LocalStack.pop
(self)
Removes the topmost item from the stack, will return the old value or `None` if the stack was already empty.
Removes the topmost item from the stack, will return the old value or `None` if the stack was already empty.
def pop(self): """Removes the topmost item from the stack, will return the old value or `None` if the stack was already empty. """ stack = getattr(self._local, "stack", None) if stack is None: return None elif len(stack) == 1: release_local(self._l...
[ "def", "pop", "(", "self", ")", ":", "stack", "=", "getattr", "(", "self", ".", "_local", ",", "\"stack\"", ",", "None", ")", "if", "stack", "is", "None", ":", "return", "None", "elif", "len", "(", "stack", ")", "==", "1", ":", "release_local", "("...
[ 149, 4 ]
[ 160, 30 ]
python
en
['en', 'en', 'en']
True
LocalStack.top
(self)
The topmost item on the stack. If the stack is empty, `None` is returned.
The topmost item on the stack. If the stack is empty, `None` is returned.
def top(self): """The topmost item on the stack. If the stack is empty, `None` is returned. """ try: return self._local.stack[-1] except (AttributeError, IndexError): return None
[ "def", "top", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_local", ".", "stack", "[", "-", "1", "]", "except", "(", "AttributeError", ",", "IndexError", ")", ":", "return", "None" ]
[ 163, 4 ]
[ 170, 23 ]
python
en
['en', 'en', 'en']
True
LocalManager.get_ident
(self)
Return the context identifier the local objects use internally for this context. You cannot override this method to change the behavior but use it to link other context local objects (such as SQLAlchemy's scoped sessions) to the Werkzeug locals. .. versionchanged:: 0.7 You c...
Return the context identifier the local objects use internally for this context. You cannot override this method to change the behavior but use it to link other context local objects (such as SQLAlchemy's scoped sessions) to the Werkzeug locals.
def get_ident(self): """Return the context identifier the local objects use internally for this context. You cannot override this method to change the behavior but use it to link other context local objects (such as SQLAlchemy's scoped sessions) to the Werkzeug locals. .. versi...
[ "def", "get_ident", "(", "self", ")", ":", "return", "self", ".", "ident_func", "(", ")" ]
[ 204, 4 ]
[ 215, 32 ]
python
en
['en', 'en', 'en']
True
LocalManager.cleanup
(self)
Manually clean up the data in the locals for this context. Call this at the end of the request or use `make_middleware()`.
Manually clean up the data in the locals for this context. Call this at the end of the request or use `make_middleware()`.
def cleanup(self): """Manually clean up the data in the locals for this context. Call this at the end of the request or use `make_middleware()`. """ for local in self.locals: release_local(local)
[ "def", "cleanup", "(", "self", ")", ":", "for", "local", "in", "self", ".", "locals", ":", "release_local", "(", "local", ")" ]
[ 217, 4 ]
[ 222, 32 ]
python
en
['en', 'en', 'en']
True
LocalManager.make_middleware
(self, app)
Wrap a WSGI application so that cleaning up happens after request end.
Wrap a WSGI application so that cleaning up happens after request end.
def make_middleware(self, app): """Wrap a WSGI application so that cleaning up happens after request end. """ def application(environ, start_response): return ClosingIterator(app(environ, start_response), self.cleanup) return application
[ "def", "make_middleware", "(", "self", ",", "app", ")", ":", "def", "application", "(", "environ", ",", "start_response", ")", ":", "return", "ClosingIterator", "(", "app", "(", "environ", ",", "start_response", ")", ",", "self", ".", "cleanup", ")", "retu...
[ 224, 4 ]
[ 232, 26 ]
python
en
['en', 'en', 'en']
True
LocalManager.middleware
(self, func)
Like `make_middleware` but for decorating functions. Example usage:: @manager.middleware def application(environ, start_response): ... The difference to `make_middleware` is that the function passed will have all the arguments copied from the inner appl...
Like `make_middleware` but for decorating functions.
def middleware(self, func): """Like `make_middleware` but for decorating functions. Example usage:: @manager.middleware def application(environ, start_response): ... The difference to `make_middleware` is that the function passed will have all t...
[ "def", "middleware", "(", "self", ",", "func", ")", ":", "return", "update_wrapper", "(", "self", ".", "make_middleware", "(", "func", ")", ",", "func", ")" ]
[ 234, 4 ]
[ 247, 63 ]
python
en
['en', 'en', 'en']
True
splitPackageName
(packageName)
e.g. given com.example.appname.library.widgetname returns com com.example com.example.appname etc.
e.g. given com.example.appname.library.widgetname returns com com.example com.example.appname etc.
def splitPackageName(packageName): """e.g. given com.example.appname.library.widgetname returns com com.example com.example.appname etc. """ result = [] end = packageName.find('.') while end > 0: result.append(packageName[0:end]) end = packageNa...
[ "def", "splitPackageName", "(", "packageName", ")", ":", "result", "=", "[", "]", "end", "=", "packageName", ".", "find", "(", "'.'", ")", "while", "end", ">", "0", ":", "result", ".", "append", "(", "packageName", "[", "0", ":", "end", "]", ")", "...
[ 22, 0 ]
[ 35, 16 ]
python
en
['en', 'en', 'pt']
True
make_distribution_for_install_requirement
( install_req: InstallRequirement, )
Returns a Distribution for the given InstallRequirement
Returns a Distribution for the given InstallRequirement
def make_distribution_for_install_requirement( install_req: InstallRequirement, ) -> AbstractDistribution: """Returns a Distribution for the given InstallRequirement""" # Editable requirements will always be source distributions. They use the # legacy logic until we create a modern standard for them. ...
[ "def", "make_distribution_for_install_requirement", "(", "install_req", ":", "InstallRequirement", ",", ")", "->", "AbstractDistribution", ":", "# Editable requirements will always be source distributions. They use the", "# legacy logic until we create a modern standard for them.", "if", ...
[ 6, 0 ]
[ 20, 42 ]
python
en
['en', 'en', 'en']
True
estimator_1st_order.__init__
(self, sims, fiducial_point, offsets, print_params=False, tf_dtype=tf.float32, tikohnov=0.0)
Initsalizes the first order estimator from a given evaluation of a function around a fiducial point :param sims: prediction of the fiducial point and its perturbations, shape [2*n_params + 1, n_sims, n_output] :param fiducial_point: the fiducial point of the expansion :param offsets: th...
Initsalizes the first order estimator from a given evaluation of a function around a fiducial point :param sims: prediction of the fiducial point and its perturbations, shape [2*n_params + 1, n_sims, n_output] :param fiducial_point: the fiducial point of the expansion :param offsets: th...
def __init__(self, sims, fiducial_point, offsets, print_params=False, tf_dtype=tf.float32, tikohnov=0.0): """ Initsalizes the first order estimator from a given evaluation of a function around a fiducial point :param sims: prediction of the fiducial point and its perturbations, ...
[ "def", "__init__", "(", "self", ",", "sims", ",", "fiducial_point", ",", "offsets", ",", "print_params", "=", "False", ",", "tf_dtype", "=", "tf", ".", "float32", ",", "tikohnov", "=", "0.0", ")", ":", "self", ".", "tf_dtype", "=", "tf_dtype", "# dimensi...
[ 10, 4 ]
[ 114, 70 ]
python
en
['en', 'error', 'th']
False
estimator_1st_order.__call__
(self, predictions, numpy=False)
Given some prediction it estimates to underlying parameters to first order :param predictions: The predictions i.e. summaries [n_summaries, n_output] :param numpy: perform the calculation in numpy instead of tensorflow :return: the estimates [n_summaries, n_output]
Given some prediction it estimates to underlying parameters to first order :param predictions: The predictions i.e. summaries [n_summaries, n_output] :param numpy: perform the calculation in numpy instead of tensorflow :return: the estimates [n_summaries, n_output]
def __call__(self, predictions, numpy=False): """ Given some prediction it estimates to underlying parameters to first order :param predictions: The predictions i.e. summaries [n_summaries, n_output] :param numpy: perform the calculation in numpy instead of tensorflow :return: th...
[ "def", "__call__", "(", "self", ",", "predictions", ",", "numpy", "=", "False", ")", ":", "if", "numpy", ":", "return", "self", ".", "fidu_point", "+", "np", ".", "einsum", "(", "\"ij,aj->ai\"", ",", "self", ".", "inv_jac", ",", "predictions", "-", "se...
[ 116, 4 ]
[ 127, 112 ]
python
en
['en', 'error', 'th']
False