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
BitString.asBinary
(self)
Get |ASN.1| value as a text string of bits.
Get |ASN.1| value as a text string of bits.
def asBinary(self): """Get |ASN.1| value as a text string of bits. """ binString = binary.bin(self._value)[2:] return '0' * (len(self._value) - len(binString)) + binString
[ "def", "asBinary", "(", "self", ")", ":", "binString", "=", "binary", ".", "bin", "(", "self", ".", "_value", ")", "[", "2", ":", "]", "return", "'0'", "*", "(", "len", "(", "self", ".", "_value", ")", "-", "len", "(", "binString", ")", ")", "+...
[ 585, 4 ]
[ 589, 68 ]
python
en
['en', 'en', 'en']
True
BitString.fromHexString
(cls, value, internalFormat=False, prepend=None)
Create a |ASN.1| object initialized from the hex string. Parameters ---------- value: :class:`str` Text string like 'DEADBEEF'
Create a |ASN.1| object initialized from the hex string.
def fromHexString(cls, value, internalFormat=False, prepend=None): """Create a |ASN.1| object initialized from the hex string. Parameters ---------- value: :class:`str` Text string like 'DEADBEEF' """ try: value = SizedInteger(value, 16).setBitLen...
[ "def", "fromHexString", "(", "cls", ",", "value", ",", "internalFormat", "=", "False", ",", "prepend", "=", "None", ")", ":", "try", ":", "value", "=", "SizedInteger", "(", "value", ",", "16", ")", ".", "setBitLength", "(", "len", "(", "value", ")", ...
[ 592, 4 ]
[ 614, 20 ]
python
en
['en', 'en', 'en']
True
BitString.fromBinaryString
(cls, value, internalFormat=False, prepend=None)
Create a |ASN.1| object initialized from a string of '0' and '1'. Parameters ---------- value: :class:`str` Text string like '1010111'
Create a |ASN.1| object initialized from a string of '0' and '1'.
def fromBinaryString(cls, value, internalFormat=False, prepend=None): """Create a |ASN.1| object initialized from a string of '0' and '1'. Parameters ---------- value: :class:`str` Text string like '1010111' """ try: value = SizedInteger(value or ...
[ "def", "fromBinaryString", "(", "cls", ",", "value", ",", "internalFormat", "=", "False", ",", "prepend", "=", "None", ")", ":", "try", ":", "value", "=", "SizedInteger", "(", "value", "or", "'0'", ",", "2", ")", ".", "setBitLength", "(", "len", "(", ...
[ 617, 4 ]
[ 639, 20 ]
python
en
['en', 'en', 'en']
True
BitString.fromOctetString
(cls, value, internalFormat=False, prepend=None, padding=0)
Create a |ASN.1| object initialized from a string. Parameters ---------- value: :class:`str` (Py2) or :class:`bytes` (Py3) Text string like '\\\\x01\\\\xff' (Py2) or b'\\\\x01\\\\xff' (Py3)
Create a |ASN.1| object initialized from a string.
def fromOctetString(cls, value, internalFormat=False, prepend=None, padding=0): """Create a |ASN.1| object initialized from a string. Parameters ---------- value: :class:`str` (Py2) or :class:`bytes` (Py3) Text string like '\\\\x01\\\\xff' (Py2) or b'\\\\x01\\\\xff' (Py3) ...
[ "def", "fromOctetString", "(", "cls", ",", "value", ",", "internalFormat", "=", "False", ",", "prepend", "=", "None", ",", "padding", "=", "0", ")", ":", "value", "=", "SizedInteger", "(", "integer", ".", "from_bytes", "(", "value", ")", ">>", "padding",...
[ 642, 4 ]
[ 660, 20 ]
python
en
['en', 'en', 'en']
True
OctetString.fromBinaryString
(value)
Create a |ASN.1| object initialized from a string of '0' and '1'. Parameters ---------- value: :class:`str` Text string like '1010111'
Create a |ASN.1| object initialized from a string of '0' and '1'.
def fromBinaryString(value): """Create a |ASN.1| object initialized from a string of '0' and '1'. Parameters ---------- value: :class:`str` Text string like '1010111' """ bitNo = 8 byte = 0 r = [] for v in value: if bitNo: ...
[ "def", "fromBinaryString", "(", "value", ")", ":", "bitNo", "=", "8", "byte", "=", "0", "r", "=", "[", "]", "for", "v", "in", "value", ":", "if", "bitNo", ":", "bitNo", "-=", "1", "else", ":", "bitNo", "=", "7", "r", ".", "append", "(", "byte",...
[ 973, 4 ]
[ 1001, 34 ]
python
en
['en', 'en', 'en']
True
OctetString.fromHexString
(value)
Create a |ASN.1| object initialized from the hex string. Parameters ---------- value: :class:`str` Text string like 'DEADBEEF'
Create a |ASN.1| object initialized from the hex string.
def fromHexString(value): """Create a |ASN.1| object initialized from the hex string. Parameters ---------- value: :class:`str` Text string like 'DEADBEEF' """ r = [] p = [] for v in value: if p: r.append(int(p + v,...
[ "def", "fromHexString", "(", "value", ")", ":", "r", "=", "[", "]", "p", "=", "[", "]", "for", "v", "in", "value", ":", "if", "p", ":", "r", ".", "append", "(", "int", "(", "p", "+", "v", ",", "16", ")", ")", "p", "=", "None", "else", ":"...
[ 1004, 4 ]
[ 1023, 34 ]
python
en
['en', 'en', 'en']
True
ObjectIdentifier.isPrefixOf
(self, other)
Indicate if this |ASN.1| object is a prefix of other |ASN.1| object. Parameters ---------- other: |ASN.1| object |ASN.1| object Returns ------- : :class:`bool` :obj:`True` if this |ASN.1| object is a parent (e.g. prefix) of the other |ASN.1| obje...
Indicate if this |ASN.1| object is a prefix of other |ASN.1| object.
def isPrefixOf(self, other): """Indicate if this |ASN.1| object is a prefix of other |ASN.1| object. Parameters ---------- other: |ASN.1| object |ASN.1| object Returns ------- : :class:`bool` :obj:`True` if this |ASN.1| object is a parent...
[ "def", "isPrefixOf", "(", "self", ",", "other", ")", ":", "l", "=", "len", "(", "self", ")", "if", "l", "<=", "len", "(", "other", ")", ":", "if", "self", ".", "_value", "[", ":", "l", "]", "==", "other", "[", ":", "l", "]", ":", "return", ...
[ 1209, 4 ]
[ 1227, 20 ]
python
en
['en', 'en', 'en']
True
Real.isPlusInf
(self)
Indicate PLUS-INFINITY object value Returns ------- : :class:`bool` :obj:`True` if calling object represents plus infinity or :obj:`False` otherwise.
Indicate PLUS-INFINITY object value
def isPlusInf(self): """Indicate PLUS-INFINITY object value Returns ------- : :class:`bool` :obj:`True` if calling object represents plus infinity or :obj:`False` otherwise. """ return self._value == self._plusInf
[ "def", "isPlusInf", "(", "self", ")", ":", "return", "self", ".", "_value", "==", "self", ".", "_plusInf" ]
[ 1387, 4 ]
[ 1397, 43 ]
python
en
['nl', 'en', 'en']
True
Real.isMinusInf
(self)
Indicate MINUS-INFINITY object value Returns ------- : :class:`bool` :obj:`True` if calling object represents minus infinity or :obj:`False` otherwise.
Indicate MINUS-INFINITY object value
def isMinusInf(self): """Indicate MINUS-INFINITY object value Returns ------- : :class:`bool` :obj:`True` if calling object represents minus infinity or :obj:`False` otherwise. """ return self._value == self._minusInf
[ "def", "isMinusInf", "(", "self", ")", ":", "return", "self", ".", "_value", "==", "self", ".", "_minusInf" ]
[ 1400, 4 ]
[ 1409, 44 ]
python
en
['nl', 'en', 'it']
False
SequenceOfAndSetOfBase.getComponentByPosition
(self, idx, default=noValue, instantiate=True)
Return |ASN.1| type component value by position. Equivalent to Python sequence subscription operation (e.g. `[]`). Parameters ---------- idx : :class:`int` Component index (zero-based). Must either refer to an existing component or to N+1 component (if *componen...
Return |ASN.1| type component value by position.
def getComponentByPosition(self, idx, default=noValue, instantiate=True): """Return |ASN.1| type component value by position. Equivalent to Python sequence subscription operation (e.g. `[]`). Parameters ---------- idx : :class:`int` Component index (zero-based). Mus...
[ "def", "getComponentByPosition", "(", "self", ",", "idx", ",", "default", "=", "noValue", ",", "instantiate", "=", "True", ")", ":", "if", "isinstance", "(", "idx", ",", "slice", ")", ":", "indices", "=", "tuple", "(", "range", "(", "len", "(", "self",...
[ 1747, 4 ]
[ 1838, 26 ]
python
en
['en', 'en', 'en']
True
SequenceOfAndSetOfBase.setComponentByPosition
(self, idx, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True)
Assign |ASN.1| type component by position. Equivalent to Python sequence item assignment operation (e.g. `[]`) or list.append() (when idx == len(self)). Parameters ---------- idx: :class:`int` Component index (zero-based). Must either refer to existing c...
Assign |ASN.1| type component by position.
def setComponentByPosition(self, idx, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True): """Assign |ASN.1| type component by position. Equivalent to Python sequence item assignment o...
[ "def", "setComponentByPosition", "(", "self", ",", "idx", ",", "value", "=", "noValue", ",", "verifyConstraints", "=", "True", ",", "matchTags", "=", "True", ",", "matchConstraints", "=", "True", ")", ":", "if", "isinstance", "(", "idx", ",", "slice", ")",...
[ 1840, 4 ]
[ 1949, 19 ]
python
en
['en', 'en', 'en']
True
SequenceOfAndSetOfBase.clear
(self)
Remove all components and become an empty |ASN.1| value object. Has the same effect on |ASN.1| object as it does on :class:`list` built-in.
Remove all components and become an empty |ASN.1| value object.
def clear(self): """Remove all components and become an empty |ASN.1| value object. Has the same effect on |ASN.1| object as it does on :class:`list` built-in. """ self._componentValues = {} return self
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_componentValues", "=", "{", "}", "return", "self" ]
[ 1961, 4 ]
[ 1968, 19 ]
python
en
['en', 'en', 'en']
True
SequenceOfAndSetOfBase.reset
(self)
Remove all components and become a |ASN.1| schema object. See :meth:`isValue` property for more information on the distinction between value and schema objects.
Remove all components and become a |ASN.1| schema object.
def reset(self): """Remove all components and become a |ASN.1| schema object. See :meth:`isValue` property for more information on the distinction between value and schema objects. """ self._componentValues = noValue return self
[ "def", "reset", "(", "self", ")", ":", "self", ".", "_componentValues", "=", "noValue", "return", "self" ]
[ 1970, 4 ]
[ 1977, 19 ]
python
en
['en', 'en', 'en']
True
SequenceOfAndSetOfBase.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:`int`, :c...
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 object ...
[ "def", "isValue", "(", "self", ")", ":", "if", "self", ".", "_componentValues", "is", "noValue", ":", "return", "False", "if", "len", "(", "self", ".", "_componentValues", ")", "!=", "len", "(", "self", ")", ":", "return", "False", "for", "componentValue...
[ 2006, 4 ]
[ 2042, 19 ]
python
en
['en', 'en', 'en']
True
SequenceOfAndSetOfBase.isInconsistent
(self)
Run necessary checks to ensure |ASN.1| object consistency. Default action is to verify |ASN.1| object against constraints imposed by `subtypeSpec`. Raises ------ :py:class:`~pyasn1.error.PyAsn1tError` on any inconsistencies found
Run necessary checks to ensure |ASN.1| object consistency.
def isInconsistent(self): """Run necessary checks to ensure |ASN.1| object consistency. Default action is to verify |ASN.1| object against constraints imposed by `subtypeSpec`. Raises ------ :py:class:`~pyasn1.error.PyAsn1tError` on any inconsistencies found """...
[ "def", "isInconsistent", "(", "self", ")", ":", "if", "self", ".", "componentType", "is", "noValue", "or", "not", "self", ".", "subtypeSpec", ":", "return", "False", "if", "self", ".", "_componentValues", "is", "noValue", ":", "return", "True", "mapping", ...
[ 2045, 4 ]
[ 2078, 20 ]
python
en
['en', 'mg', 'en']
True
SequenceAndSetBase.clear
(self)
Remove all components and become an empty |ASN.1| value object. Has the same effect on |ASN.1| object as it does on :class:`dict` built-in.
Remove all components and become an empty |ASN.1| value object.
def clear(self): """Remove all components and become an empty |ASN.1| value object. Has the same effect on |ASN.1| object as it does on :class:`dict` built-in. """ self._componentValues = [] self._dynamicNames = self.DynamicNames() return self
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_componentValues", "=", "[", "]", "self", ".", "_dynamicNames", "=", "self", ".", "DynamicNames", "(", ")", "return", "self" ]
[ 2293, 4 ]
[ 2301, 19 ]
python
en
['en', 'en', 'en']
True
SequenceAndSetBase.reset
(self)
Remove all components and become a |ASN.1| schema object. See :meth:`isValue` property for more information on the distinction between value and schema objects.
Remove all components and become a |ASN.1| schema object.
def reset(self): """Remove all components and become a |ASN.1| schema object. See :meth:`isValue` property for more information on the distinction between value and schema objects. """ self._componentValues = noValue self._dynamicNames = self.DynamicNames() retur...
[ "def", "reset", "(", "self", ")", ":", "self", ".", "_componentValues", "=", "noValue", "self", ".", "_dynamicNames", "=", "self", ".", "DynamicNames", "(", ")", "return", "self" ]
[ 2303, 4 ]
[ 2311, 19 ]
python
en
['en', 'en', 'en']
True
SequenceAndSetBase.getComponentByName
(self, name, default=noValue, instantiate=True)
Returns |ASN.1| type component by name. Equivalent to Python :class:`dict` subscription operation (e.g. `[]`). Parameters ---------- name: :class:`str` |ASN.1| type component name Keyword Args ------------ default: :class:`object` If set...
Returns |ASN.1| type component by name.
def getComponentByName(self, name, default=noValue, instantiate=True): """Returns |ASN.1| type component by name. Equivalent to Python :class:`dict` subscription operation (e.g. `[]`). Parameters ---------- name: :class:`str` |ASN.1| type component name Key...
[ "def", "getComponentByName", "(", "self", ",", "name", ",", "default", "=", "noValue", ",", "instantiate", "=", "True", ")", ":", "if", "self", ".", "_componentTypeLen", ":", "idx", "=", "self", ".", "componentType", ".", "getPositionByName", "(", "name", ...
[ 2330, 4 ]
[ 2367, 89 ]
python
en
['en', 'en', 'en']
True
SequenceAndSetBase.setComponentByName
(self, name, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True)
Assign |ASN.1| type component by name. Equivalent to Python :class:`dict` item assignment operation (e.g. `[]`). Parameters ---------- name: :class:`str` |ASN.1| type component name Keyword Args ------------ value: :class:`object` or :py:class:`~pya...
Assign |ASN.1| type component by name.
def setComponentByName(self, name, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True): """Assign |ASN.1| type component by name. Equivalent to Python :class:`dict` item assignment operation (e.g....
[ "def", "setComponentByName", "(", "self", ",", "name", ",", "value", "=", "noValue", ",", "verifyConstraints", "=", "True", ",", "matchTags", "=", "True", ",", "matchConstraints", "=", "True", ")", ":", "if", "self", ".", "_componentTypeLen", ":", "idx", "...
[ 2369, 4 ]
[ 2413, 9 ]
python
en
['en', 'en', 'en']
True
SequenceAndSetBase.getComponentByPosition
(self, idx, default=noValue, instantiate=True)
Returns |ASN.1| type component by index. Equivalent to Python sequence subscription operation (e.g. `[]`). Parameters ---------- idx: :class:`int` Component index (zero-based). Must either refer to an existing component or (if *componentType* is set) new ASN.1 s...
Returns |ASN.1| type component by index.
def getComponentByPosition(self, idx, default=noValue, instantiate=True): """Returns |ASN.1| type component by index. Equivalent to Python sequence subscription operation (e.g. `[]`). Parameters ---------- idx: :class:`int` Component index (zero-based). Must either ...
[ "def", "getComponentByPosition", "(", "self", ",", "idx", ",", "default", "=", "noValue", ",", "instantiate", "=", "True", ")", ":", "try", ":", "if", "self", ".", "_componentValues", "is", "noValue", ":", "componentValue", "=", "noValue", "else", ":", "co...
[ 2415, 4 ]
[ 2507, 26 ]
python
en
['en', 'en', 'en']
True
SequenceAndSetBase.setComponentByPosition
(self, idx, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True)
Assign |ASN.1| type component by position. Equivalent to Python sequence item assignment operation (e.g. `[]`). Parameters ---------- idx : :class:`int` Component index (zero-based). Must either refer to existing component (if *componentType* is set) or to N+1 c...
Assign |ASN.1| type component by position.
def setComponentByPosition(self, idx, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True): """Assign |ASN.1| type component by position. Equivalent to Python sequence item assignment o...
[ "def", "setComponentByPosition", "(", "self", ",", "idx", ",", "value", "=", "noValue", ",", "verifyConstraints", "=", "True", ",", "matchTags", "=", "True", ",", "matchConstraints", "=", "True", ")", ":", "componentType", "=", "self", ".", "componentType", ...
[ 2509, 4 ]
[ 2614, 19 ]
python
en
['en', 'en', 'en']
True
SequenceAndSetBase.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:`int`, :c...
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 object ...
[ "def", "isValue", "(", "self", ")", ":", "if", "self", ".", "_componentValues", "is", "noValue", ":", "return", "False", "componentType", "=", "self", ".", "componentType", "if", "componentType", ":", "for", "idx", ",", "subComponentType", "in", "enumerate", ...
[ 2617, 4 ]
[ 2672, 19 ]
python
en
['en', 'en', 'en']
True
SequenceAndSetBase.isInconsistent
(self)
Run necessary checks to ensure |ASN.1| object consistency. Default action is to verify |ASN.1| object against constraints imposed by `subtypeSpec`. Raises ------ :py:class:`~pyasn1.error.PyAsn1tError` on any inconsistencies found
Run necessary checks to ensure |ASN.1| object consistency.
def isInconsistent(self): """Run necessary checks to ensure |ASN.1| object consistency. Default action is to verify |ASN.1| object against constraints imposed by `subtypeSpec`. Raises ------ :py:class:`~pyasn1.error.PyAsn1tError` on any inconsistencies found """...
[ "def", "isInconsistent", "(", "self", ")", ":", "if", "self", ".", "componentType", "is", "noValue", "or", "not", "self", ".", "subtypeSpec", ":", "return", "False", "if", "self", ".", "_componentValues", "is", "noValue", ":", "return", "True", "mapping", ...
[ 2675, 4 ]
[ 2710, 20 ]
python
en
['en', 'mg', 'en']
True
SequenceAndSetBase.prettyPrint
(self, scope=0)
Return an object representation string. Returns ------- : :class:`str` Human-friendly object representation.
Return an object representation string.
def prettyPrint(self, scope=0): """Return an object representation string. Returns ------- : :class:`str` Human-friendly object representation. """ scope += 1 representation = self.__class__.__name__ + ':\n' for idx, componentValue in enumerat...
[ "def", "prettyPrint", "(", "self", ",", "scope", "=", "0", ")", ":", "scope", "+=", "1", "representation", "=", "self", ".", "__class__", ".", "__name__", "+", "':\\n'", "for", "idx", ",", "componentValue", "in", "enumerate", "(", "self", ".", "_componen...
[ 2712, 4 ]
[ 2732, 29 ]
python
en
['en', 'en', 'en']
True
Set.getComponentByType
(self, tagSet, default=noValue, instantiate=True, innerFlag=False)
Returns |ASN.1| type component by ASN.1 tag. Parameters ---------- tagSet : :py:class:`~pyasn1.type.tag.TagSet` Object representing ASN.1 tags to identify one of |ASN.1| object component Keyword Args ------------ default: :class:`object` ...
Returns |ASN.1| type component by ASN.1 tag.
def getComponentByType(self, tagSet, default=noValue, instantiate=True, innerFlag=False): """Returns |ASN.1| type component by ASN.1 tag. Parameters ---------- tagSet : :py:class:`~pyasn1.type.tag.TagSet` Object representing ASN.1 tags to identify ...
[ "def", "getComponentByType", "(", "self", ",", "tagSet", ",", "default", "=", "noValue", ",", "instantiate", "=", "True", ",", "innerFlag", "=", "False", ")", ":", "componentValue", "=", "self", ".", "getComponentByPosition", "(", "self", ".", "componentType",...
[ 2821, 4 ]
[ 2857, 33 ]
python
en
['en', 'en', 'en']
True
Set.setComponentByType
(self, tagSet, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True, innerFlag=False)
Assign |ASN.1| type component by ASN.1 tag. Parameters ---------- tagSet : :py:class:`~pyasn1.type.tag.TagSet` Object representing ASN.1 tags to identify one of |ASN.1| object component Keyword Args ------------ value: :class:`object` or :py:clas...
Assign |ASN.1| type component by ASN.1 tag.
def setComponentByType(self, tagSet, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True, innerFlag=False): """Assign |ASN.1| type component by ASN.1 tag. Parameters ...
[ "def", "setComponentByType", "(", "self", ",", "tagSet", ",", "value", "=", "noValue", ",", "verifyConstraints", "=", "True", ",", "matchTags", "=", "True", ",", "matchConstraints", "=", "True", ",", "innerFlag", "=", "False", ")", ":", "idx", "=", "self",...
[ 2859, 4 ]
[ 2912, 13 ]
python
en
['en', 'en', 'en']
True
clear_collection
(collection)
Removes every document from the collection, to make it easy to see what has been added by the current test run.
Removes every document from the collection, to make it easy to see what has been added by the current test run.
def clear_collection(collection): """ Removes every document from the collection, to make it easy to see what has been added by the current test run. """ for doc in collection.stream(): doc.reference.delete()
[ "def", "clear_collection", "(", "collection", ")", ":", "for", "doc", "in", "collection", ".", "stream", "(", ")", ":", "doc", ".", "reference", ".", "delete", "(", ")" ]
[ 21, 0 ]
[ 26, 30 ]
python
en
['en', 'en', 'en']
True
Filter.__init__
(self, source, allowed_elements=allowed_elements, allowed_attributes=allowed_attributes, allowed_css_properties=allowed_css_properties, allowed_css_keywords=allowed_css_keywords, allowed_svg_properties=allowed_svg_prop...
Creates a Filter :arg allowed_elements: set of elements to allow--everything else will be escaped :arg allowed_attributes: set of attributes to allow in elements--everything else will be stripped :arg allowed_css_properties: set of CSS properties to allow--everything ...
Creates a Filter
def __init__(self, source, allowed_elements=allowed_elements, allowed_attributes=allowed_attributes, allowed_css_properties=allowed_css_properties, allowed_css_keywords=allowed_css_keywords, allowed_svg_properties=allo...
[ "def", "__init__", "(", "self", ",", "source", ",", "allowed_elements", "=", "allowed_elements", ",", "allowed_attributes", "=", "allowed_attributes", ",", "allowed_css_properties", "=", "allowed_css_properties", ",", "allowed_css_keywords", "=", "allowed_css_keywords", "...
[ 725, 4 ]
[ 781, 56 ]
python
en
['en', 'gl', 'en']
True
ItemRecommendationEvaluation.__init__
(self, sep='\t', n_ranks=list([1, 3, 5, 10]), metrics=list(['PREC', 'RECALL', 'MAP', 'NDCG']), all_but_one_eval=False, verbose=True, as_table=False, table_sep='\t')
Class to evaluate predictions in a item recommendation (ranking) scenario :param sep: Delimiter for input files :type sep: str, default '\t' :param n_ranks: List of positions to evaluate the ranking :type n_ranks: list, default [1, 3, 5, 10] :param metrics: List of ev...
Class to evaluate predictions in a item recommendation (ranking) scenario
def __init__(self, sep='\t', n_ranks=list([1, 3, 5, 10]), metrics=list(['PREC', 'RECALL', 'MAP', 'NDCG']), all_but_one_eval=False, verbose=True, as_table=False, table_sep='\t'): """ Class to evaluate predictions in a item recommendation (ranking) scenario :para...
[ "def", "__init__", "(", "self", ",", "sep", "=", "'\\t'", ",", "n_ranks", "=", "list", "(", "[", "1", ",", "3", ",", "5", ",", "10", "]", ")", ",", "metrics", "=", "list", "(", "[", "'PREC'", ",", "'RECALL'", ",", "'MAP'", ",", "'NDCG'", "]", ...
[ 28, 4 ]
[ 61, 30 ]
python
en
['en', 'error', 'th']
False
ItemRecommendationEvaluation.evaluate
(self, predictions, test_set)
Method to calculate all the metrics for item recommendation scenario using dictionaries of ranking and test set. Use read() in ReadFile to transform your file in a dict :param predictions: Dictionary with ranking information :type predictions: dict :param test_set: Dictionary ...
Method to calculate all the metrics for item recommendation scenario using dictionaries of ranking and test set. Use read() in ReadFile to transform your file in a dict
def evaluate(self, predictions, test_set): """ Method to calculate all the metrics for item recommendation scenario using dictionaries of ranking and test set. Use read() in ReadFile to transform your file in a dict :param predictions: Dictionary with ranking information :type p...
[ "def", "evaluate", "(", "self", ",", "predictions", ",", "test_set", ")", ":", "eval_results", "=", "{", "}", "num_user", "=", "len", "(", "test_set", "[", "'users'", "]", ")", "partial_map_all", "=", "None", "if", "self", ".", "all_but_one_eval", ":", "...
[ 63, 4 ]
[ 129, 27 ]
python
en
['en', 'error', 'th']
False
deconstructible
(*args, path=None)
Class decorator that allows the decorated class to be serialized by the migrations subsystem. The `path` kwarg specifies the import path.
Class decorator that allows the decorated class to be serialized by the migrations subsystem.
def deconstructible(*args, path=None): """ Class decorator that allows the decorated class to be serialized by the migrations subsystem. The `path` kwarg specifies the import path. """ def decorator(klass): def __new__(cls, *args, **kwargs): # We capture the arguments to mak...
[ "def", "deconstructible", "(", "*", "args", ",", "path", "=", "None", ")", ":", "def", "decorator", "(", "klass", ")", ":", "def", "__new__", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# We capture the arguments to make returning the...
[ 5, 0 ]
[ 54, 27 ]
python
en
['en', 'error', 'th']
False
AppAssertionCredentials.__init__
(self, email=None, *args, **kwargs)
Constructor for AppAssertionCredentials Args: email: an email that specifies the service account to use. Only necessary if using custom service accounts (see https://cloud.google.com/compute/docs/access/create-enable-service-accounts-for-instances#createdefault...
Constructor for AppAssertionCredentials
def __init__(self, email=None, *args, **kwargs): """Constructor for AppAssertionCredentials Args: email: an email that specifies the service account to use. Only necessary if using custom service accounts (see https://cloud.google.com/compute/docs/acces...
[ "def", "__init__", "(", "self", ",", "email", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'scopes'", "in", "kwargs", ":", "warnings", ".", "warn", "(", "_SCOPES_WARNING", ")", "kwargs", "[", "'scopes'", "]", "=", "None", ...
[ 56, 4 ]
[ 74, 27 ]
python
en
['da', 'en', 'en']
True
AppAssertionCredentials.retrieve_scopes
(self, http)
Retrieves the canonical list of scopes for this access token. Overrides client.Credentials.retrieve_scopes. Fetches scopes info from the metadata server. Args: http: httplib2.Http, an http object to be used to make the refresh request. Returns: ...
Retrieves the canonical list of scopes for this access token.
def retrieve_scopes(self, http): """Retrieves the canonical list of scopes for this access token. Overrides client.Credentials.retrieve_scopes. Fetches scopes info from the metadata server. Args: http: httplib2.Http, an http object to be used to make the refresh ...
[ "def", "retrieve_scopes", "(", "self", ",", "http", ")", ":", "self", ".", "_retrieve_info", "(", "http", ")", "return", "self", ".", "scopes" ]
[ 85, 4 ]
[ 99, 26 ]
python
en
['en', 'en', 'en']
True
AppAssertionCredentials._retrieve_info
(self, http)
Retrieves service account info for invalid credentials. Args: http: an object to be used to make HTTP requests.
Retrieves service account info for invalid credentials.
def _retrieve_info(self, http): """Retrieves service account info for invalid credentials. Args: http: an object to be used to make HTTP requests. """ if self.invalid: info = _metadata.get_service_account_info( http, service_accoun...
[ "def", "_retrieve_info", "(", "self", ",", "http", ")", ":", "if", "self", ".", "invalid", ":", "info", "=", "_metadata", ".", "get_service_account_info", "(", "http", ",", "service_account", "=", "self", ".", "service_account_email", "or", "'default'", ")", ...
[ 101, 4 ]
[ 113, 40 ]
python
en
['en', 'en', 'en']
True
AppAssertionCredentials._refresh
(self, http)
Refreshes the access token. Skip all the storage hoops and just refresh using the API. Args: http: an object to be used to make HTTP requests. Raises: HttpAccessTokenRefreshError: When the refresh fails.
Refreshes the access token.
def _refresh(self, http): """Refreshes the access token. Skip all the storage hoops and just refresh using the API. Args: http: an object to be used to make HTTP requests. Raises: HttpAccessTokenRefreshError: When the refresh fails. """ try: ...
[ "def", "_refresh", "(", "self", ",", "http", ")", ":", "try", ":", "self", ".", "_retrieve_info", "(", "http", ")", "self", ".", "access_token", ",", "self", ".", "token_expiry", "=", "_metadata", ".", "get_token", "(", "http", ",", "service_account", "=...
[ 115, 4 ]
[ 131, 62 ]
python
en
['en', 'en', 'en']
True
AppAssertionCredentials.sign_blob
(self, blob)
Cryptographically sign a blob (of bytes). This method is provided to support a common interface, but the actual key used for a Google Compute Engine service account is not available, so it can't be used to sign content. Args: blob: bytes, Message to be signed. Rais...
Cryptographically sign a blob (of bytes).
def sign_blob(self, blob): """Cryptographically sign a blob (of bytes). This method is provided to support a common interface, but the actual key used for a Google Compute Engine service account is not available, so it can't be used to sign content. Args: blob: byte...
[ "def", "sign_blob", "(", "self", ",", "blob", ")", ":", "raise", "NotImplementedError", "(", "'Compute Engine service accounts cannot sign blobs'", ")" ]
[ 141, 4 ]
[ 155, 64 ]
python
en
['en', 'en', 'en']
True
check_cs_op
(result, func, cargs)
Check the status code of a coordinate sequence operation.
Check the status code of a coordinate sequence operation.
def check_cs_op(result, func, cargs): "Check the status code of a coordinate sequence operation." if result == 0: raise GEOSException('Could not set value on coordinate sequence') else: return result
[ "def", "check_cs_op", "(", "result", ",", "func", ",", "cargs", ")", ":", "if", "result", "==", "0", ":", "raise", "GEOSException", "(", "'Could not set value on coordinate sequence'", ")", "else", ":", "return", "result" ]
[ 9, 0 ]
[ 14, 21 ]
python
en
['en', 'en', 'en']
True
check_cs_get
(result, func, cargs)
Check the coordinate sequence retrieval.
Check the coordinate sequence retrieval.
def check_cs_get(result, func, cargs): "Check the coordinate sequence retrieval." check_cs_op(result, func, cargs) # Object in by reference, return its value. return last_arg_byref(cargs)
[ "def", "check_cs_get", "(", "result", ",", "func", ",", "cargs", ")", ":", "check_cs_op", "(", "result", ",", "func", ",", "cargs", ")", "# Object in by reference, return its value.", "return", "last_arg_byref", "(", "cargs", ")" ]
[ 17, 0 ]
[ 21, 32 ]
python
en
['en', 'en', 'en']
True
install_given_reqs
( requirements: List[InstallRequirement], install_options: List[str], global_options: Sequence[str], root: Optional[str], home: Optional[str], prefix: Optional[str], warn_script_location: bool, use_user_site: bool, pycompile: bool, )
Install everything in the given list. (to be called after having downloaded and unpacked the packages)
Install everything in the given list.
def install_given_reqs( requirements: List[InstallRequirement], install_options: List[str], global_options: Sequence[str], root: Optional[str], home: Optional[str], prefix: Optional[str], warn_script_location: bool, use_user_site: bool, pycompile: bool, ) -> List[InstallationResult]:...
[ "def", "install_given_reqs", "(", "requirements", ":", "List", "[", "InstallRequirement", "]", ",", "install_options", ":", "List", "[", "str", "]", ",", "global_options", ":", "Sequence", "[", "str", "]", ",", "root", ":", "Optional", "[", "str", "]", ","...
[ 34, 0 ]
[ 93, 20 ]
python
en
['en', 'error', 'th']
False
run
(argv=None)
The main function which creates the pipeline and runs it.
The main function which creates the pipeline and runs it.
def run(argv=None): """The main function which creates the pipeline and runs it.""" parser = argparse.ArgumentParser() # Here we add some specific command line arguments we expect. # Specifically we have the input file to read and the output table to write. # This is the final stage of the pipelin...
[ "def", "run", "(", "argv", "=", "None", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "# Here we add some specific command line arguments we expect.", "# Specifically we have the input file to read and the output table to write.", "# This is the final stage ...
[ 61, 0 ]
[ 128, 31 ]
python
en
['en', 'en', 'en']
True
DataIngestion.parse_method
(self, string_input)
This method translates a single line of comma separated values to a dictionary which can be loaded into BigQuery. Args: string_input: A comma separated list of values in the form of state_abbreviation,gender,year,name,count_of_babies,dataset_created_date Exam...
This method translates a single line of comma separated values to a dictionary which can be loaded into BigQuery.
def parse_method(self, string_input): """This method translates a single line of comma separated values to a dictionary which can be loaded into BigQuery. Args: string_input: A comma separated list of values in the form of state_abbreviation,gender,year,name,count_of...
[ "def", "parse_method", "(", "self", ",", "string_input", ")", ":", "# Strip out carriage return, newline and quote characters.", "values", "=", "re", ".", "split", "(", "\",\"", ",", "re", ".", "sub", "(", "'\\r\\n'", ",", "''", ",", "re", ".", "sub", "(", "...
[ 29, 4 ]
[ 58, 18 ]
python
en
['en', 'en', 'en']
True
View.__init__
(self, **kwargs)
Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.
Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.
def __init__(self, **kwargs): """ Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things. """ # Go through keyword arguments, and either save their values to our # instance, or raise an error. for key, value in kwargs.ite...
[ "def", "__init__", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Go through keyword arguments, and either save their values to our", "# instance, or raise an error.", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "setattr", "(", "self...
[ 37, 4 ]
[ 45, 37 ]
python
en
['en', 'error', 'th']
False
View.as_view
(cls, **initkwargs)
Main entry point for a request-response process.
Main entry point for a request-response process.
def as_view(cls, **initkwargs): """Main entry point for a request-response process.""" for key in initkwargs: if key in cls.http_method_names: raise TypeError( 'The method name %s is not accepted as a keyword argument ' 'to %s().' % (ke...
[ "def", "as_view", "(", "cls", ",", "*", "*", "initkwargs", ")", ":", "for", "key", "in", "initkwargs", ":", "if", "key", "in", "cls", ".", "http_method_names", ":", "raise", "TypeError", "(", "'The method name %s is not accepted as a keyword argument '", "'to %s()...
[ 48, 4 ]
[ 79, 19 ]
python
en
['en', 'en', 'en']
True
View.setup
(self, request, *args, **kwargs)
Initialize attributes shared by all view methods.
Initialize attributes shared by all view methods.
def setup(self, request, *args, **kwargs): """Initialize attributes shared by all view methods.""" if hasattr(self, 'get') and not hasattr(self, 'head'): self.head = self.get self.request = request self.args = args self.kwargs = kwargs
[ "def", "setup", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "hasattr", "(", "self", ",", "'get'", ")", "and", "not", "hasattr", "(", "self", ",", "'head'", ")", ":", "self", ".", "head", "=", "self", ...
[ 81, 4 ]
[ 87, 28 ]
python
en
['en', 'en', 'en']
True
View.options
(self, request, *args, **kwargs)
Handle responding to requests for the OPTIONS HTTP verb.
Handle responding to requests for the OPTIONS HTTP verb.
def options(self, request, *args, **kwargs): """Handle responding to requests for the OPTIONS HTTP verb.""" response = HttpResponse() response.headers['Allow'] = ', '.join(self._allowed_methods()) response.headers['Content-Length'] = '0' return response
[ "def", "options", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "response", "=", "HttpResponse", "(", ")", "response", ".", "headers", "[", "'Allow'", "]", "=", "', '", ".", "join", "(", "self", ".", "_allowed_meth...
[ 106, 4 ]
[ 111, 23 ]
python
en
['en', 'en', 'en']
True
TemplateResponseMixin.render_to_response
(self, context, **response_kwargs)
Return a response, using the `response_class` for this view, with a template rendered with the given context. Pass response_kwargs to the constructor of the response class.
Return a response, using the `response_class` for this view, with a template rendered with the given context.
def render_to_response(self, context, **response_kwargs): """ Return a response, using the `response_class` for this view, with a template rendered with the given context. Pass response_kwargs to the constructor of the response class. """ response_kwargs.setdefault('cont...
[ "def", "render_to_response", "(", "self", ",", "context", ",", "*", "*", "response_kwargs", ")", ":", "response_kwargs", ".", "setdefault", "(", "'content_type'", ",", "self", ".", "content_type", ")", "return", "self", ".", "response_class", "(", "request", "...
[ 124, 4 ]
[ 138, 9 ]
python
en
['en', 'error', 'th']
False
TemplateResponseMixin.get_template_names
(self)
Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response() is overridden.
Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response() is overridden.
def get_template_names(self): """ Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response() is overridden. """ if self.template_name is None: raise ImproperlyConfigured( "TemplateResponseM...
[ "def", "get_template_names", "(", "self", ")", ":", "if", "self", ".", "template_name", "is", "None", ":", "raise", "ImproperlyConfigured", "(", "\"TemplateResponseMixin requires either a definition of \"", "\"'template_name' or an implementation of 'get_template_names()'\"", ")"...
[ 140, 4 ]
[ 150, 39 ]
python
en
['en', 'error', 'th']
False
RedirectView.get_redirect_url
(self, *args, **kwargs)
Return the URL redirect to. Keyword arguments from the URL pattern match generating the redirect request are provided as kwargs to this method.
Return the URL redirect to. Keyword arguments from the URL pattern match generating the redirect request are provided as kwargs to this method.
def get_redirect_url(self, *args, **kwargs): """ Return the URL redirect to. Keyword arguments from the URL pattern match generating the redirect request are provided as kwargs to this method. """ if self.url: url = self.url % kwargs elif self.pattern_...
[ "def", "get_redirect_url", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "url", ":", "url", "=", "self", ".", "url", "%", "kwargs", "elif", "self", ".", "pattern_name", ":", "url", "=", "reverse", "(", "self",...
[ 169, 4 ]
[ 185, 18 ]
python
en
['en', 'error', 'th']
False
get_hstore_oids
(connection_alias)
Return hstore and hstore array OIDs.
Return hstore and hstore array OIDs.
def get_hstore_oids(connection_alias): """Return hstore and hstore array OIDs.""" with connections[connection_alias].cursor() as cursor: cursor.execute( "SELECT t.oid, typarray " "FROM pg_type t " "JOIN pg_namespace ns ON typnamespace = ns.oid " "WHERE typ...
[ "def", "get_hstore_oids", "(", "connection_alias", ")", ":", "with", "connections", "[", "connection_alias", "]", ".", "cursor", "(", ")", "as", "cursor", ":", "cursor", ".", "execute", "(", "\"SELECT t.oid, typarray \"", "\"FROM pg_type t \"", "\"JOIN pg_namespace ns...
[ 11, 0 ]
[ 25, 45 ]
python
en
['en', 'en', 'en']
True
get_citext_oids
(connection_alias)
Return citext array OIDs.
Return citext array OIDs.
def get_citext_oids(connection_alias): """Return citext array OIDs.""" with connections[connection_alias].cursor() as cursor: cursor.execute("SELECT typarray FROM pg_type WHERE typname = 'citext'") return tuple(row[0] for row in cursor)
[ "def", "get_citext_oids", "(", "connection_alias", ")", ":", "with", "connections", "[", "connection_alias", "]", ".", "cursor", "(", ")", "as", "cursor", ":", "cursor", ".", "execute", "(", "\"SELECT typarray FROM pg_type WHERE typname = 'citext'\"", ")", "return", ...
[ 29, 0 ]
[ 33, 46 ]
python
en
['en', 'fr', 'en']
True
generate_recommendations
(user_idx, user_rated, row_factor, col_factor, k)
Generate recommendations for a user. Args: user_idx: the row index of the user in the ratings matrix, user_rated: the list of item indexes (column indexes in the ratings matrix) previously rated by that user (which will be excluded from the recommendations), row_factor: the row factors of t...
Generate recommendations for a user.
def generate_recommendations(user_idx, user_rated, row_factor, col_factor, k): """Generate recommendations for a user. Args: user_idx: the row index of the user in the ratings matrix, user_rated: the list of item indexes (column indexes in the ratings matrix) previously rated by that user (which wil...
[ "def", "generate_recommendations", "(", "user_idx", ",", "user_rated", ",", "row_factor", ",", "col_factor", ",", "k", ")", ":", "# bounds checking for args", "assert", "(", "row_factor", ".", "shape", "[", "0", "]", "-", "len", "(", "user_rated", ")", ")", ...
[ 120, 0 ]
[ 161, 26 ]
python
en
['en', 'en', 'en']
True
Recommendations._load_model
(self, local_model_path)
Load recommendation model files from GCS. Args: local_model_path: (string) local path to model files
Load recommendation model files from GCS.
def _load_model(self, local_model_path): """Load recommendation model files from GCS. Args: local_model_path: (string) local path to model files """ # download files from GCS to local storage os.makedirs(os.path.join(local_model_path, 'model'), exist_ok=True) os.makedirs(os.path.join(loca...
[ "def", "_load_model", "(", "self", ",", "local_model_path", ")", ":", "# download files from GCS to local storage", "os", ".", "makedirs", "(", "os", ".", "path", ".", "join", "(", "local_model_path", ",", "'model'", ")", ",", "exist_ok", "=", "True", ")", "os...
[ 47, 2 ]
[ 83, 43 ]
python
en
['en', 'en', 'en']
True
Recommendations.get_recommendations
(self, user_id, num_recs)
Given a user id, return list of num_recs recommended item ids. Args: user_id: (string) The user id num_recs: (int) The number of recommended items to return Returns: [item_id_0, item_id_1, ... item_id_k-1]: The list of k recommended items, if user id is found. None: The user id...
Given a user id, return list of num_recs recommended item ids.
def get_recommendations(self, user_id, num_recs): """Given a user id, return list of num_recs recommended item ids. Args: user_id: (string) The user id num_recs: (int) The number of recommended items to return Returns: [item_id_0, item_id_1, ... item_id_k-1]: The list of k recommended it...
[ "def", "get_recommendations", "(", "self", ",", "user_id", ",", "num_recs", ")", ":", "article_recommendations", "=", "None", "# map user id into ratings matrix user index", "user_idx", "=", "np", ".", "searchsorted", "(", "self", ".", "user_map", ",", "user_id", ")...
[ 85, 2 ]
[ 117, 34 ]
python
en
['en', 'en', 'en']
True
ResponsiveBreakpointsCache.__init__
(self, **cache_options)
Initialize the cache :param cache_options: Cache configuration options
Initialize the cache
def __init__(self, **cache_options): """ Initialize the cache :param cache_options: Cache configuration options """ self._cache_adapter = None cache_adapter = cache_options.get("cache_adapter") self.set_cache_adapter(cache_adapter)
[ "def", "__init__", "(", "self", ",", "*", "*", "cache_options", ")", ":", "self", ".", "_cache_adapter", "=", "None", "cache_adapter", "=", "cache_options", ".", "get", "(", "\"cache_adapter\"", ")", "self", ".", "set_cache_adapter", "(", "cache_adapter", ")" ...
[ 13, 4 ]
[ 24, 45 ]
python
en
['en', 'error', 'th']
False
ResponsiveBreakpointsCache.set_cache_adapter
(self, cache_adapter)
Assigns cache adapter :param cache_adapter: The cache adapter used to store and retrieve values :return: Returns True if the cache_adapter is valid
Assigns cache adapter
def set_cache_adapter(self, cache_adapter): """ Assigns cache adapter :param cache_adapter: The cache adapter used to store and retrieve values :return: Returns True if the cache_adapter is valid """ if cache_adapter is None or not isinstance(cache_adapter, CacheAdapter...
[ "def", "set_cache_adapter", "(", "self", ",", "cache_adapter", ")", ":", "if", "cache_adapter", "is", "None", "or", "not", "isinstance", "(", "cache_adapter", ",", "CacheAdapter", ")", ":", "return", "False", "self", ".", "_cache_adapter", "=", "cache_adapter", ...
[ 26, 4 ]
[ 39, 19 ]
python
en
['en', 'error', 'th']
False
ResponsiveBreakpointsCache.enabled
(self)
Indicates whether cache is enabled or not :return: Rrue if a _cache_adapter has been set
Indicates whether cache is enabled or not
def enabled(self): """ Indicates whether cache is enabled or not :return: Rrue if a _cache_adapter has been set """ return self._cache_adapter is not None
[ "def", "enabled", "(", "self", ")", ":", "return", "self", ".", "_cache_adapter", "is", "not", "None" ]
[ 42, 4 ]
[ 48, 46 ]
python
en
['en', 'error', 'th']
False
ResponsiveBreakpointsCache._options_to_parameters
(**options)
Extract the parameters required in order to calculate the key of the cache. :param options: Input options :return: A list of values used to calculate the cache key
Extract the parameters required in order to calculate the key of the cache.
def _options_to_parameters(**options): """ Extract the parameters required in order to calculate the key of the cache. :param options: Input options :return: A list of values used to calculate the cache key """ options_copy = copy.deepcopy(options) transformatio...
[ "def", "_options_to_parameters", "(", "*", "*", "options", ")", ":", "options_copy", "=", "copy", ".", "deepcopy", "(", "options", ")", "transformation", ",", "_", "=", "cloudinary", ".", "utils", ".", "generate_transformation_string", "(", "*", "*", "options_...
[ 51, 4 ]
[ 65, 71 ]
python
en
['en', 'error', 'th']
False
ResponsiveBreakpointsCache.get
(self, public_id, **options)
Retrieve the breakpoints of a particular derived resource identified by the public_id and options :param public_id: The public ID of the resource :param options: The public ID of the resource :return: Array of responsive breakpoints, None if not found
Retrieve the breakpoints of a particular derived resource identified by the public_id and options
def get(self, public_id, **options): """ Retrieve the breakpoints of a particular derived resource identified by the public_id and options :param public_id: The public ID of the resource :param options: The public ID of the resource :return: Array of responsive breakpoints, Non...
[ "def", "get", "(", "self", ",", "public_id", ",", "*", "*", "options", ")", ":", "params", "=", "self", ".", "_options_to_parameters", "(", "*", "*", "options", ")", "return", "self", ".", "_cache_adapter", ".", "get", "(", "public_id", ",", "*", "para...
[ 68, 4 ]
[ 79, 58 ]
python
en
['en', 'error', 'th']
False
ResponsiveBreakpointsCache.set
(self, public_id, value, **options)
Set responsive breakpoints identified by public ID and options :param public_id: The public ID of the resource :param value: Array of responsive breakpoints to set :param options: Additional options :return: True on success or False on failure
Set responsive breakpoints identified by public ID and options
def set(self, public_id, value, **options): """ Set responsive breakpoints identified by public ID and options :param public_id: The public ID of the resource :param value: Array of responsive breakpoints to set :param options: Additional options :return: True on succe...
[ "def", "set", "(", "self", ",", "public_id", ",", "value", ",", "*", "*", "options", ")", ":", "if", "not", "(", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ")", ":", "raise", "ValueError", "(", "\"A list of breakpoints is exp...
[ 82, 4 ]
[ 97, 114 ]
python
en
['en', 'error', 'th']
False
ResponsiveBreakpointsCache.delete
(self, public_id, **options)
Delete responsive breakpoints identified by public ID and options :param public_id: The public ID of the resource :param options: Additional options :return: True on success or False on failure
Delete responsive breakpoints identified by public ID and options
def delete(self, public_id, **options): """ Delete responsive breakpoints identified by public ID and options :param public_id: The public ID of the resource :param options: Additional options :return: True on success or False on failure """ params = self._optio...
[ "def", "delete", "(", "self", ",", "public_id", ",", "*", "*", "options", ")", ":", "params", "=", "self", ".", "_options_to_parameters", "(", "*", "*", "options", ")", "return", "self", ".", "_cache_adapter", ".", "delete", "(", "public_id", ",", "*", ...
[ 100, 4 ]
[ 111, 61 ]
python
en
['en', 'error', 'th']
False
ResponsiveBreakpointsCache.flush_all
(self)
Flush all entries from cache :return: True on success or False on failure
Flush all entries from cache
def flush_all(self): """ Flush all entries from cache :return: True on success or False on failure """ return self._cache_adapter.flush_all()
[ "def", "flush_all", "(", "self", ")", ":", "return", "self", ".", "_cache_adapter", ".", "flush_all", "(", ")" ]
[ 114, 4 ]
[ 120, 46 ]
python
en
['en', 'error', 'th']
False
AddDiskResourcesIfNeeded
(context)
Checks context if disk resources need to be added.
Checks context if disk resources need to be added.
def AddDiskResourcesIfNeeded(context): """Checks context if disk resources need to be added.""" if default.DISK_RESOURCES in context.properties: return context.properties[default.DISK_RESOURCES] else: return []
[ "def", "AddDiskResourcesIfNeeded", "(", "context", ")", ":", "if", "default", ".", "DISK_RESOURCES", "in", "context", ".", "properties", ":", "return", "context", ".", "properties", "[", "default", ".", "DISK_RESOURCES", "]", "else", ":", "return", "[", "]" ]
[ 30, 0 ]
[ 35, 13 ]
python
en
['en', 'en', 'en']
True
AutoName
(base, resource, *args)
Helper method to generate names automatically based on default.
Helper method to generate names automatically based on default.
def AutoName(base, resource, *args): """Helper method to generate names automatically based on default.""" auto_name = '%s-%s' % (base, '-'.join(list(args) + [default.AKA[resource]])) if not RFC1035_RE.match(auto_name): raise Error('"%s" name for type %s does not match RFC1035 regex (%s)' % (a...
[ "def", "AutoName", "(", "base", ",", "resource", ",", "*", "args", ")", ":", "auto_name", "=", "'%s-%s'", "%", "(", "base", ",", "'-'", ".", "join", "(", "list", "(", "args", ")", "+", "[", "default", ".", "AKA", "[", "resource", "]", "]", ")", ...
[ 38, 0 ]
[ 44, 18 ]
python
en
['en', 'en', 'en']
True
AutoRef
(base, resource, *args)
Helper method that builds a reference for an auto-named resource.
Helper method that builds a reference for an auto-named resource.
def AutoRef(base, resource, *args): """Helper method that builds a reference for an auto-named resource.""" return Ref(AutoName(base, resource, *args))
[ "def", "AutoRef", "(", "base", ",", "resource", ",", "*", "args", ")", ":", "return", "Ref", "(", "AutoName", "(", "base", ",", "resource", ",", "*", "args", ")", ")" ]
[ 47, 0 ]
[ 49, 45 ]
python
en
['en', 'en', 'en']
True
OrderedItems
(dict_obj)
Convenient method to yield sorted iteritems of a dictionary.
Convenient method to yield sorted iteritems of a dictionary.
def OrderedItems(dict_obj): """Convenient method to yield sorted iteritems of a dictionary.""" keys = dict_obj.keys() keys.sort() for k in keys: yield (k, dict_obj[k])
[ "def", "OrderedItems", "(", "dict_obj", ")", ":", "keys", "=", "dict_obj", ".", "keys", "(", ")", "keys", ".", "sort", "(", ")", "for", "k", "in", "keys", ":", "yield", "(", "k", ",", "dict_obj", "[", "k", "]", ")" ]
[ 52, 0 ]
[ 57, 26 ]
python
en
['en', 'en', 'en']
True
ShortenZoneName
(zone)
Given a string that looks like a zone name, creates a shorter version.
Given a string that looks like a zone name, creates a shorter version.
def ShortenZoneName(zone): """Given a string that looks like a zone name, creates a shorter version.""" geo, coord, number, letter = re.findall(r'(\w+)-(\w+)(\d)-(\w)', zone)[0] geo = geo.lower() if len(geo) == 2 else default.LOC[geo.lower()] coord = default.LOC[coord.lower()] number = str(number) letter = ...
[ "def", "ShortenZoneName", "(", "zone", ")", ":", "geo", ",", "coord", ",", "number", ",", "letter", "=", "re", ".", "findall", "(", "r'(\\w+)-(\\w+)(\\d)-(\\w)'", ",", "zone", ")", "[", "0", "]", "geo", "=", "geo", ".", "lower", "(", ")", "if", "len"...
[ 60, 0 ]
[ 67, 44 ]
python
en
['en', 'en', 'en']
True
ZoneToRegion
(zone)
Derives the region from a zone name.
Derives the region from a zone name.
def ZoneToRegion(zone): """Derives the region from a zone name.""" parts = zone.split('-') if len(parts) != 3: raise Error('Cannot derive region from zone "%s"' % zone) return '-'.join(parts[:2])
[ "def", "ZoneToRegion", "(", "zone", ")", ":", "parts", "=", "zone", ".", "split", "(", "'-'", ")", "if", "len", "(", "parts", ")", "!=", "3", ":", "raise", "Error", "(", "'Cannot derive region from zone \"%s\"'", "%", "zone", ")", "return", "'-'", ".", ...
[ 70, 0 ]
[ 75, 28 ]
python
en
['en', 'en', 'en']
True
FormatException
(message)
Adds more information to the exception.
Adds more information to the exception.
def FormatException(message): """Adds more information to the exception.""" message = ('Exception Type: %s\n' 'Details: %s\n' 'Message: %s\n') % (sys.exc_type, traceback.format_exc(), message) return message
[ "def", "FormatException", "(", "message", ")", ":", "message", "=", "(", "'Exception Type: %s\\n'", "'Details: %s\\n'", "'Message: %s\\n'", ")", "%", "(", "sys", ".", "exc_type", ",", "traceback", ".", "format_exc", "(", ")", ",", "message", ")", "return", "me...
[ 78, 0 ]
[ 83, 16 ]
python
en
['en', 'en', 'en']
True
SummarizeResources
(res_dict)
Summarizes the name of resources per resource type.
Summarizes the name of resources per resource type.
def SummarizeResources(res_dict): """Summarizes the name of resources per resource type.""" result = {} for res in res_dict: result.setdefault(res['type'], []).append(res['name']) return result
[ "def", "SummarizeResources", "(", "res_dict", ")", ":", "result", "=", "{", "}", "for", "res", "in", "res_dict", ":", "result", ".", "setdefault", "(", "res", "[", "'type'", "]", ",", "[", "]", ")", ".", "append", "(", "res", "[", "'name'", "]", ")...
[ 160, 0 ]
[ 165, 15 ]
python
en
['en', 'en', 'en']
True
ListPropertyValuesOfType
(res_dict, prop, res_type)
Lists all the values for a property of a certain type.
Lists all the values for a property of a certain type.
def ListPropertyValuesOfType(res_dict, prop, res_type): """Lists all the values for a property of a certain type.""" return [r['properties'][prop] for r in res_dict if r['type'] == res_type]
[ "def", "ListPropertyValuesOfType", "(", "res_dict", ",", "prop", ",", "res_type", ")", ":", "return", "[", "r", "[", "'properties'", "]", "[", "prop", "]", "for", "r", "in", "res_dict", "if", "r", "[", "'type'", "]", "==", "res_type", "]" ]
[ 168, 0 ]
[ 170, 75 ]
python
en
['en', 'en', 'en']
True
MakeResource
(resource_list, output_list=None)
Wrapper for a DM template basic spec.
Wrapper for a DM template basic spec.
def MakeResource(resource_list, output_list=None): """Wrapper for a DM template basic spec.""" content = {'resources': resource_list} if output_list: content['outputs'] = output_list return yaml.dump(content)
[ "def", "MakeResource", "(", "resource_list", ",", "output_list", "=", "None", ")", ":", "content", "=", "{", "'resources'", ":", "resource_list", "}", "if", "output_list", ":", "content", "[", "'outputs'", "]", "=", "output_list", "return", "yaml", ".", "dum...
[ 173, 0 ]
[ 178, 27 ]
python
en
['en', 'en', 'en']
True
TakeZoneOut
(properties)
Given a properties dictionary, removes the zone specific information.
Given a properties dictionary, removes the zone specific information.
def TakeZoneOut(properties): """Given a properties dictionary, removes the zone specific information.""" def _CleanZoneUrl(value): value = value.split('/')[-1] if IsComputeLink(value) else value return value for name in default.VM_ZONE_PROPERTIES: if name in properties: properties[name] = _Cle...
[ "def", "TakeZoneOut", "(", "properties", ")", ":", "def", "_CleanZoneUrl", "(", "value", ")", ":", "value", "=", "value", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "if", "IsComputeLink", "(", "value", ")", "else", "value", "return", "value", ...
[ 181, 0 ]
[ 203, 80 ]
python
en
['en', 'en', 'en']
True
FormatErrorsDec
(func)
Decorator to format exceptions if they get raised.
Decorator to format exceptions if they get raised.
def FormatErrorsDec(func): """Decorator to format exceptions if they get raised.""" def FormatErrorsWrap(context): try: return func(context) except Exception as e: raise Error(FormatException(e.message)) return FormatErrorsWrap
[ "def", "FormatErrorsDec", "(", "func", ")", ":", "def", "FormatErrorsWrap", "(", "context", ")", ":", "try", ":", "return", "func", "(", "context", ")", "except", "Exception", "as", "e", ":", "raise", "Error", "(", "FormatException", "(", "e", ".", "mess...
[ 218, 0 ]
[ 227, 25 ]
python
en
['en', 'en', 'en']
True
ModelBackend.user_can_authenticate
(self, user)
Reject users with is_active=False. Custom user models that don't have that attribute are allowed.
Reject users with is_active=False. Custom user models that don't have that attribute are allowed.
def user_can_authenticate(self, user): """ Reject users with is_active=False. Custom user models that don't have that attribute are allowed. """ is_active = getattr(user, 'is_active', None) return is_active or is_active is None
[ "def", "user_can_authenticate", "(", "self", ",", "user", ")", ":", "is_active", "=", "getattr", "(", "user", ",", "'is_active'", ",", "None", ")", "return", "is_active", "or", "is_active", "is", "None" ]
[ 50, 4 ]
[ 56, 45 ]
python
en
['en', 'error', 'th']
False
ModelBackend._get_permissions
(self, user_obj, obj, from_name)
Return the permissions of `user_obj` from `from_name`. `from_name` can be either "group" or "user" to return permissions from `_get_group_permissions` or `_get_user_permissions` respectively.
Return the permissions of `user_obj` from `from_name`. `from_name` can be either "group" or "user" to return permissions from `_get_group_permissions` or `_get_user_permissions` respectively.
def _get_permissions(self, user_obj, obj, from_name): """ Return the permissions of `user_obj` from `from_name`. `from_name` can be either "group" or "user" to return permissions from `_get_group_permissions` or `_get_user_permissions` respectively. """ if not user_obj.is...
[ "def", "_get_permissions", "(", "self", ",", "user_obj", ",", "obj", ",", "from_name", ")", ":", "if", "not", "user_obj", ".", "is_active", "or", "user_obj", ".", "is_anonymous", "or", "obj", "is", "not", "None", ":", "return", "set", "(", ")", "perm_cac...
[ 66, 4 ]
[ 83, 49 ]
python
en
['en', 'error', 'th']
False
ModelBackend.get_user_permissions
(self, user_obj, obj=None)
Return a set of permission strings the user `user_obj` has from their `user_permissions`.
Return a set of permission strings the user `user_obj` has from their `user_permissions`.
def get_user_permissions(self, user_obj, obj=None): """ Return a set of permission strings the user `user_obj` has from their `user_permissions`. """ return self._get_permissions(user_obj, obj, 'user')
[ "def", "get_user_permissions", "(", "self", ",", "user_obj", ",", "obj", "=", "None", ")", ":", "return", "self", ".", "_get_permissions", "(", "user_obj", ",", "obj", ",", "'user'", ")" ]
[ 85, 4 ]
[ 90, 59 ]
python
en
['en', 'error', 'th']
False
ModelBackend.get_group_permissions
(self, user_obj, obj=None)
Return a set of permission strings the user `user_obj` has from the groups they belong.
Return a set of permission strings the user `user_obj` has from the groups they belong.
def get_group_permissions(self, user_obj, obj=None): """ Return a set of permission strings the user `user_obj` has from the groups they belong. """ return self._get_permissions(user_obj, obj, 'group')
[ "def", "get_group_permissions", "(", "self", ",", "user_obj", ",", "obj", "=", "None", ")", ":", "return", "self", ".", "_get_permissions", "(", "user_obj", ",", "obj", ",", "'group'", ")" ]
[ 92, 4 ]
[ 97, 60 ]
python
en
['en', 'error', 'th']
False
ModelBackend.has_module_perms
(self, user_obj, app_label)
Return True if user_obj has any permissions in the given app_label.
Return True if user_obj has any permissions in the given app_label.
def has_module_perms(self, user_obj, app_label): """ Return True if user_obj has any permissions in the given app_label. """ return user_obj.is_active and any( perm[:perm.index('.')] == app_label for perm in self.get_all_permissions(user_obj) )
[ "def", "has_module_perms", "(", "self", ",", "user_obj", ",", "app_label", ")", ":", "return", "user_obj", ".", "is_active", "and", "any", "(", "perm", "[", ":", "perm", ".", "index", "(", "'.'", ")", "]", "==", "app_label", "for", "perm", "in", "self"...
[ 109, 4 ]
[ 116, 9 ]
python
en
['en', 'error', 'th']
False
ModelBackend.with_perm
(self, perm, is_active=True, include_superusers=True, obj=None)
Return users that have permission "perm". By default, filter out inactive users and include superusers.
Return users that have permission "perm". By default, filter out inactive users and include superusers.
def with_perm(self, perm, is_active=True, include_superusers=True, obj=None): """ Return users that have permission "perm". By default, filter out inactive users and include superusers. """ if isinstance(perm, str): try: app_label, codename = perm.spli...
[ "def", "with_perm", "(", "self", ",", "perm", ",", "is_active", "=", "True", ",", "include_superusers", "=", "True", ",", "obj", "=", "None", ")", ":", "if", "isinstance", "(", "perm", ",", "str", ")", ":", "try", ":", "app_label", ",", "codename", "...
[ 118, 4 ]
[ 152, 56 ]
python
en
['en', 'error', 'th']
False
RemoteUserBackend.authenticate
(self, request, remote_user)
The username passed as ``remote_user`` is considered trusted. Return the ``User`` object with the given username. Create a new ``User`` object if ``create_unknown_user`` is ``True``. Return None if ``create_unknown_user`` is ``False`` and a ``User`` object with the given userna...
The username passed as ``remote_user`` is considered trusted. Return the ``User`` object with the given username. Create a new ``User`` object if ``create_unknown_user`` is ``True``.
def authenticate(self, request, remote_user): """ The username passed as ``remote_user`` is considered trusted. Return the ``User`` object with the given username. Create a new ``User`` object if ``create_unknown_user`` is ``True``. Return None if ``create_unknown_user`` is ``Fa...
[ "def", "authenticate", "(", "self", ",", "request", ",", "remote_user", ")", ":", "if", "not", "remote_user", ":", "return", "user", "=", "None", "username", "=", "self", ".", "clean_username", "(", "remote_user", ")", "# Note that this could be accomplished in on...
[ 182, 4 ]
[ 210, 65 ]
python
en
['en', 'error', 'th']
False
RemoteUserBackend.clean_username
(self, username)
Perform any cleaning on the "username" prior to using it to get or create the user object. Return the cleaned username. By default, return the username unchanged.
Perform any cleaning on the "username" prior to using it to get or create the user object. Return the cleaned username.
def clean_username(self, username): """ Perform any cleaning on the "username" prior to using it to get or create the user object. Return the cleaned username. By default, return the username unchanged. """ return username
[ "def", "clean_username", "(", "self", ",", "username", ")", ":", "return", "username" ]
[ 212, 4 ]
[ 219, 23 ]
python
en
['en', 'error', 'th']
False
RemoteUserBackend.configure_user
(self, request, user)
Configure a user after creation and return the updated user. By default, return the user unmodified.
Configure a user after creation and return the updated user.
def configure_user(self, request, user): """ Configure a user after creation and return the updated user. By default, return the user unmodified. """ return user
[ "def", "configure_user", "(", "self", ",", "request", ",", "user", ")", ":", "return", "user" ]
[ 221, 4 ]
[ 227, 19 ]
python
en
['en', 'error', 'th']
False
dollars_to_math
(source)
r""" Replace dollar signs with backticks. More precisely, do a regular expression search. Replace a plain dollar sign ($) by a backtick (`). Replace an escaped dollar sign (\$) by a dollar sign ($). Don't change a dollar sign preceded or followed by a backtick (`$ or $`), because of strings like...
r""" Replace dollar signs with backticks.
def dollars_to_math(source): r""" Replace dollar signs with backticks. More precisely, do a regular expression search. Replace a plain dollar sign ($) by a backtick (`). Replace an escaped dollar sign (\$) by a dollar sign ($). Don't change a dollar sign preceded or followed by a backtick (`...
[ "def", "dollars_to_math", "(", "source", ")", ":", "s", "=", "\"\\n\"", ".", "join", "(", "source", ")", "if", "s", ".", "find", "(", "\"$\"", ")", "==", "-", "1", ":", "return", "# This searches for \"$blah$\" inside a pair of curly braces --", "# don't change ...
[ 2, 0 ]
[ 49, 19 ]
python
cy
['en', 'cy', 'hi']
False
LayerMapping.__init__
(self, model, data, mapping, layer=0, source_srs=None, encoding='utf-8', transaction_mode='commit_on_success', transform=True, unique=None, using=None)
A LayerMapping object is initialized using the given Model (not an instance), a DataSource (or string path to an OGR-supported data file), and a mapping dictionary. See the module level docstring for more details and keyword argument usage.
A LayerMapping object is initialized using the given Model (not an instance), a DataSource (or string path to an OGR-supported data file), and a mapping dictionary. See the module level docstring for more details and keyword argument usage.
def __init__(self, model, data, mapping, layer=0, source_srs=None, encoding='utf-8', transaction_mode='commit_on_success', transform=True, unique=None, using=None): """ A LayerMapping object is initialized using the given Model (not an instance), ...
[ "def", "__init__", "(", "self", ",", "model", ",", "data", ",", "mapping", ",", "layer", "=", "0", ",", "source_srs", "=", "None", ",", "encoding", "=", "'utf-8'", ",", "transaction_mode", "=", "'commit_on_success'", ",", "transform", "=", "True", ",", "...
[ 85, 4 ]
[ 154, 87 ]
python
en
['en', 'error', 'th']
False
LayerMapping.check_fid_range
(self, fid_range)
Check the `fid_range` keyword.
Check the `fid_range` keyword.
def check_fid_range(self, fid_range): "Check the `fid_range` keyword." if fid_range: if isinstance(fid_range, (tuple, list)): return slice(*fid_range) elif isinstance(fid_range, slice): return fid_range else: raise TypeE...
[ "def", "check_fid_range", "(", "self", ",", "fid_range", ")", ":", "if", "fid_range", ":", "if", "isinstance", "(", "fid_range", ",", "(", "tuple", ",", "list", ")", ")", ":", "return", "slice", "(", "*", "fid_range", ")", "elif", "isinstance", "(", "f...
[ 157, 4 ]
[ 167, 23 ]
python
en
['en', 'hmn', 'en']
True
LayerMapping.check_layer
(self)
Check the Layer metadata and ensure that it's compatible with the mapping information and model. Unlike previous revisions, there is no need to increment through each feature in the Layer.
Check the Layer metadata and ensure that it's compatible with the mapping information and model. Unlike previous revisions, there is no need to increment through each feature in the Layer.
def check_layer(self): """ Check the Layer metadata and ensure that it's compatible with the mapping information and model. Unlike previous revisions, there is no need to increment through each feature in the Layer. """ # The geometry field of the model is set here. ...
[ "def", "check_layer", "(", "self", ")", ":", "# The geometry field of the model is set here.", "# TODO: Support more than one geometry field / model. However, this", "# depends on the GDAL Driver in use.", "self", ".", "geom_field", "=", "False", "self", ".", "fields", "=", "{",...
[ 169, 4 ]
[ 264, 48 ]
python
en
['en', 'error', 'th']
False
LayerMapping.check_srs
(self, source_srs)
Check the compatibility of the given spatial reference object.
Check the compatibility of the given spatial reference object.
def check_srs(self, source_srs): "Check the compatibility of the given spatial reference object." if isinstance(source_srs, SpatialReference): sr = source_srs elif isinstance(source_srs, self.spatial_backend.spatial_ref_sys()): sr = source_srs.srs elif isinstance...
[ "def", "check_srs", "(", "self", ",", "source_srs", ")", ":", "if", "isinstance", "(", "source_srs", ",", "SpatialReference", ")", ":", "sr", "=", "source_srs", "elif", "isinstance", "(", "source_srs", ",", "self", ".", "spatial_backend", ".", "spatial_ref_sys...
[ 266, 4 ]
[ 282, 21 ]
python
en
['en', 'en', 'en']
True
LayerMapping.check_unique
(self, unique)
Check the `unique` keyword parameter -- may be a sequence or string.
Check the `unique` keyword parameter -- may be a sequence or string.
def check_unique(self, unique): "Check the `unique` keyword parameter -- may be a sequence or string." if isinstance(unique, (list, tuple)): # List of fields to determine uniqueness with for attr in unique: if attr not in self.mapping: raise Va...
[ "def", "check_unique", "(", "self", ",", "unique", ")", ":", "if", "isinstance", "(", "unique", ",", "(", "list", ",", "tuple", ")", ")", ":", "# List of fields to determine uniqueness with", "for", "attr", "in", "unique", ":", "if", "attr", "not", "in", "...
[ 284, 4 ]
[ 296, 97 ]
python
en
['en', 'en', 'en']
True
LayerMapping.feature_kwargs
(self, feat)
Given an OGR Feature, return a dictionary of keyword arguments for constructing the mapped model.
Given an OGR Feature, return a dictionary of keyword arguments for constructing the mapped model.
def feature_kwargs(self, feat): """ Given an OGR Feature, return a dictionary of keyword arguments for constructing the mapped model. """ # The keyword arguments for model construction. kwargs = {} # Incrementing through each model field and OGR field in the ...
[ "def", "feature_kwargs", "(", "self", ",", "feat", ")", ":", "# The keyword arguments for model construction.", "kwargs", "=", "{", "}", "# Incrementing through each model field and OGR field in the", "# dictionary mapping.", "for", "field_name", ",", "ogr_name", "in", "self"...
[ 299, 4 ]
[ 330, 21 ]
python
en
['en', 'error', 'th']
False
LayerMapping.unique_kwargs
(self, kwargs)
Given the feature keyword arguments (from `feature_kwargs`), construct and return the uniqueness keyword arguments -- a subset of the feature kwargs.
Given the feature keyword arguments (from `feature_kwargs`), construct and return the uniqueness keyword arguments -- a subset of the feature kwargs.
def unique_kwargs(self, kwargs): """ Given the feature keyword arguments (from `feature_kwargs`), construct and return the uniqueness keyword arguments -- a subset of the feature kwargs. """ if isinstance(self.unique, str): return {self.unique: kwargs[self.uni...
[ "def", "unique_kwargs", "(", "self", ",", "kwargs", ")", ":", "if", "isinstance", "(", "self", ".", "unique", ",", "str", ")", ":", "return", "{", "self", ".", "unique", ":", "kwargs", "[", "self", ".", "unique", "]", "}", "else", ":", "return", "{...
[ 332, 4 ]
[ 341, 60 ]
python
en
['en', 'error', 'th']
False
LayerMapping.verify_ogr_field
(self, ogr_field, model_field)
Verify if the OGR Field contents are acceptable to the model field. If they are, return the verified value, otherwise raise an exception.
Verify if the OGR Field contents are acceptable to the model field. If they are, return the verified value, otherwise raise an exception.
def verify_ogr_field(self, ogr_field, model_field): """ Verify if the OGR Field contents are acceptable to the model field. If they are, return the verified value, otherwise raise an exception. """ if (isinstance(ogr_field, OFTString) and isinstance(model_field, (...
[ "def", "verify_ogr_field", "(", "self", ",", "ogr_field", ",", "model_field", ")", ":", "if", "(", "isinstance", "(", "ogr_field", ",", "OFTString", ")", "and", "isinstance", "(", "model_field", ",", "(", "models", ".", "CharField", ",", "models", ".", "Te...
[ 344, 4 ]
[ 399, 18 ]
python
en
['en', 'error', 'th']
False
LayerMapping.verify_fk
(self, feat, rel_model, rel_mapping)
Given an OGR Feature, the related model and its dictionary mapping, retrieve the related model for the ForeignKey mapping.
Given an OGR Feature, the related model and its dictionary mapping, retrieve the related model for the ForeignKey mapping.
def verify_fk(self, feat, rel_model, rel_mapping): """ Given an OGR Feature, the related model and its dictionary mapping, retrieve the related model for the ForeignKey mapping. """ # TODO: It is expensive to retrieve a model for every record -- # explore if an efficient...
[ "def", "verify_fk", "(", "self", ",", "feat", ",", "rel_model", ",", "rel_mapping", ")", ":", "# TODO: It is expensive to retrieve a model for every record --", "# explore if an efficient mechanism exists for caching related", "# ForeignKey models.", "# Constructing and verifying the...
[ 401, 4 ]
[ 422, 13 ]
python
en
['en', 'error', 'th']
False
LayerMapping.verify_geom
(self, geom, model_field)
Verify the geometry -- construct and return a GeometryCollection if necessary (for example if the model field is MultiPolygonField while the mapped shapefile only contains Polygons).
Verify the geometry -- construct and return a GeometryCollection if necessary (for example if the model field is MultiPolygonField while the mapped shapefile only contains Polygons).
def verify_geom(self, geom, model_field): """ Verify the geometry -- construct and return a GeometryCollection if necessary (for example if the model field is MultiPolygonField while the mapped shapefile only contains Polygons). """ # Downgrade a 3D geom to a 2D one, if n...
[ "def", "verify_geom", "(", "self", ",", "geom", ",", "model_field", ")", ":", "# Downgrade a 3D geom to a 2D one, if necessary.", "if", "self", ".", "coord_dim", "!=", "geom", ".", "coord_dim", ":", "geom", ".", "coord_dim", "=", "self", ".", "coord_dim", "if", ...
[ 424, 4 ]
[ 449, 20 ]
python
en
['en', 'error', 'th']
False
LayerMapping.coord_transform
(self)
Return the coordinate transformation object.
Return the coordinate transformation object.
def coord_transform(self): "Return the coordinate transformation object." SpatialRefSys = self.spatial_backend.spatial_ref_sys() try: # Getting the target spatial reference system target_srs = SpatialRefSys.objects.using(self.using).get(srid=self.geo_field.srid).srs ...
[ "def", "coord_transform", "(", "self", ")", ":", "SpatialRefSys", "=", "self", ".", "spatial_backend", ".", "spatial_ref_sys", "(", ")", "try", ":", "# Getting the target spatial reference system", "target_srs", "=", "SpatialRefSys", ".", "objects", ".", "using", "(...
[ 452, 4 ]
[ 464, 22 ]
python
en
['en', 'en', 'en']
True
LayerMapping.geometry_field
(self)
Return the GeometryField instance associated with the geographic column.
Return the GeometryField instance associated with the geographic column.
def geometry_field(self): "Return the GeometryField instance associated with the geographic column." # Use `get_field()` on the model's options so that we # get the correct field instance if there's model inheritance. opts = self.model._meta return opts.get_field(self.geom_field)
[ "def", "geometry_field", "(", "self", ")", ":", "# Use `get_field()` on the model's options so that we", "# get the correct field instance if there's model inheritance.", "opts", "=", "self", ".", "model", ".", "_meta", "return", "opts", ".", "get_field", "(", "self", ".", ...
[ 466, 4 ]
[ 471, 46 ]
python
en
['en', 'en', 'en']
True
LayerMapping.make_multi
(self, geom_type, model_field)
Given the OGRGeomType for a geometry and its associated GeometryField, determine whether the geometry should be turned into a GeometryCollection.
Given the OGRGeomType for a geometry and its associated GeometryField, determine whether the geometry should be turned into a GeometryCollection.
def make_multi(self, geom_type, model_field): """ Given the OGRGeomType for a geometry and its associated GeometryField, determine whether the geometry should be turned into a GeometryCollection. """ return (geom_type.num in self.MULTI_TYPES and model_field.__clas...
[ "def", "make_multi", "(", "self", ",", "geom_type", ",", "model_field", ")", ":", "return", "(", "geom_type", ".", "num", "in", "self", ".", "MULTI_TYPES", "and", "model_field", ".", "__class__", ".", "__name__", "==", "'Multi%s'", "%", "geom_type", ".", "...
[ 473, 4 ]
[ 479, 79 ]
python
en
['en', 'error', 'th']
False
LayerMapping.save
(self, verbose=False, fid_range=False, step=False, progress=False, silent=False, stream=sys.stdout, strict=False)
Save the contents from the OGR DataSource Layer into the database according to the mapping dictionary given at initialization. Keyword Parameters: verbose: If set, information will be printed subsequent to each model save executed on the database. fid_r...
Save the contents from the OGR DataSource Layer into the database according to the mapping dictionary given at initialization.
def save(self, verbose=False, fid_range=False, step=False, progress=False, silent=False, stream=sys.stdout, strict=False): """ Save the contents from the OGR DataSource Layer into the database according to the mapping dictionary given at initialization. Keyword Parameters: ...
[ "def", "save", "(", "self", ",", "verbose", "=", "False", ",", "fid_range", "=", "False", ",", "step", "=", "False", ",", "progress", "=", "False", ",", "silent", "=", "False", ",", "stream", "=", "sys", ".", "stdout", ",", "strict", "=", "False", ...
[ 481, 4 ]
[ 636, 19 ]
python
en
['en', 'error', 'th']
False
UserKNN.__init__
(self, train_file=None, test_file=None, output_file=None, similarity_metric="cosine", k_neighbors=None, rank_length=10, as_binary=False, as_similar_first=True, sep='\t', output_sep='\t')
User KNN for Item Recommendation This algorithm predicts a rank for each user based on the similar items that his neighbors (similar users) consumed. Usage:: >> UserKNN(train, test, as_similar_first=True).compute() >> UserKNN(train, test, ranking_file, as_bina...
User KNN for Item Recommendation
def __init__(self, train_file=None, test_file=None, output_file=None, similarity_metric="cosine", k_neighbors=None, rank_length=10, as_binary=False, as_similar_first=True, sep='\t', output_sep='\t'): """ User KNN for Item Recommendation This algorithm predicts a rank for each u...
[ "def", "__init__", "(", "self", ",", "train_file", "=", "None", ",", "test_file", "=", "None", ",", "output_file", "=", "None", ",", "similarity_metric", "=", "\"cosine\"", ",", "k_neighbors", "=", "None", ",", "rank_length", "=", "10", ",", "as_binary", "...
[ 20, 4 ]
[ 81, 40 ]
python
en
['en', 'error', 'th']
False
UserKNN.init_model
(self)
Method to initialize the model. Create and calculate a similarity matrix
Method to initialize the model. Create and calculate a similarity matrix
def init_model(self): """ Method to initialize the model. Create and calculate a similarity matrix """ self.users_id_viewed_item = {} self.create_matrix() self.su_matrix = self.compute_similarity(transpose=False) # Set the value for k if self.k_neighbor...
[ "def", "init_model", "(", "self", ")", ":", "self", ".", "users_id_viewed_item", "=", "{", "}", "self", ".", "create_matrix", "(", ")", "self", ".", "su_matrix", "=", "self", ".", "compute_similarity", "(", "transpose", "=", "False", ")", "# Set the value fo...
[ 83, 4 ]
[ 99, 97 ]
python
en
['en', 'error', 'th']
False
UserKNN.predict
(self)
Method to predict a rank for each user.
Method to predict a rank for each user.
def predict(self): """ Method to predict a rank for each user. """ for u_id, user in enumerate(self.users): if len(self.train_set['feedback'].get(user, [])) != 0: u_list = list(np.flatnonzero(self.matrix[u_id] == 0)) if self.as_similar_first...
[ "def", "predict", "(", "self", ")", ":", "for", "u_id", ",", "user", "in", "enumerate", "(", "self", ".", "users", ")", ":", "if", "len", "(", "self", ".", "train_set", "[", "'feedback'", "]", ".", "get", "(", "user", ",", "[", "]", ")", ")", "...
[ 101, 4 ]
[ 117, 20 ]
python
en
['en', 'error', 'th']
False