nwo
stringlengths 5
106
| sha
stringlengths 40
40
| path
stringlengths 4
174
| language
stringclasses 1
value | identifier
stringlengths 1
140
| parameters
stringlengths 0
87.7k
| argument_list
stringclasses 1
value | return_statement
stringlengths 0
426k
| docstring
stringlengths 0
64.3k
| docstring_summary
stringlengths 0
26.3k
| docstring_tokens
list | function
stringlengths 18
4.83M
| function_tokens
list | url
stringlengths 83
304
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
matt852/netconfig
|
7d3df1d0678974d5196f534d6f228351758befe0
|
app/device_classes/device_definitions/cisco/cisco_ios.py
|
python
|
CiscoIOS.pull_interface_config
|
(self, activeSession)
|
return self.get_cmd_output(command, activeSession)
|
Retrieve configuration for interface on device.
|
Retrieve configuration for interface on device.
|
[
"Retrieve",
"configuration",
"for",
"interface",
"on",
"device",
"."
] |
def pull_interface_config(self, activeSession):
"""Retrieve configuration for interface on device."""
command = "show run interface %s | exclude configuration|!" % (self.interface)
return self.get_cmd_output(command, activeSession)
|
[
"def",
"pull_interface_config",
"(",
"self",
",",
"activeSession",
")",
":",
"command",
"=",
"\"show run interface %s | exclude configuration|!\"",
"%",
"(",
"self",
".",
"interface",
")",
"return",
"self",
".",
"get_cmd_output",
"(",
"command",
",",
"activeSession",
")"
] |
https://github.com/matt852/netconfig/blob/7d3df1d0678974d5196f534d6f228351758befe0/app/device_classes/device_definitions/cisco/cisco_ios.py#L39-L42
|
|
Chaffelson/nipyapi
|
d3b186fd701ce308c2812746d98af9120955e810
|
nipyapi/nifi/models/bulletin_entity.py
|
python
|
BulletinEntity.node_address
|
(self)
|
return self._node_address
|
Gets the node_address of this BulletinEntity.
:return: The node_address of this BulletinEntity.
:rtype: str
|
Gets the node_address of this BulletinEntity.
|
[
"Gets",
"the",
"node_address",
"of",
"this",
"BulletinEntity",
"."
] |
def node_address(self):
"""
Gets the node_address of this BulletinEntity.
:return: The node_address of this BulletinEntity.
:rtype: str
"""
return self._node_address
|
[
"def",
"node_address",
"(",
"self",
")",
":",
"return",
"self",
".",
"_node_address"
] |
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/bulletin_entity.py#L168-L175
|
|
NoGameNoLife00/mybolg
|
afe17ea5bfe405e33766e5682c43a4262232ee12
|
libs/sqlalchemy/events.py
|
python
|
ConnectionEvents.begin
|
(self, conn)
|
Intercept begin() events.
:param conn: :class:`.Connection` object
|
Intercept begin() events.
|
[
"Intercept",
"begin",
"()",
"events",
"."
] |
def begin(self, conn):
"""Intercept begin() events.
:param conn: :class:`.Connection` object
"""
|
[
"def",
"begin",
"(",
"self",
",",
"conn",
")",
":"
] |
https://github.com/NoGameNoLife00/mybolg/blob/afe17ea5bfe405e33766e5682c43a4262232ee12/libs/sqlalchemy/events.py#L837-L842
|
||
arizvisa/ida-minsc
|
8627a60f047b5e55d3efeecde332039cd1a16eea
|
base/structure.py
|
python
|
member_t.parent
|
(self)
|
return self.__parent__
|
Return the structure_t that owns the member.
|
Return the structure_t that owns the member.
|
[
"Return",
"the",
"structure_t",
"that",
"owns",
"the",
"member",
"."
] |
def parent(self):
'''Return the structure_t that owns the member.'''
return self.__parent__
|
[
"def",
"parent",
"(",
"self",
")",
":",
"return",
"self",
".",
"__parent__"
] |
https://github.com/arizvisa/ida-minsc/blob/8627a60f047b5e55d3efeecde332039cd1a16eea/base/structure.py#L2035-L2037
|
|
cleverhans-lab/cleverhans
|
e5d00e537ce7ad6119ed5a8db1f0e9736d1f6e1d
|
cleverhans_v3.1.0/cleverhans/utils_keras.py
|
python
|
KerasModelWrapper.get_layer_names
|
(self)
|
return layer_names
|
:return: Names of all the layers kept by Keras
|
:return: Names of all the layers kept by Keras
|
[
":",
"return",
":",
"Names",
"of",
"all",
"the",
"layers",
"kept",
"by",
"Keras"
] |
def get_layer_names(self):
"""
:return: Names of all the layers kept by Keras
"""
layer_names = [x.name for x in self.model.layers]
return layer_names
|
[
"def",
"get_layer_names",
"(",
"self",
")",
":",
"layer_names",
"=",
"[",
"x",
".",
"name",
"for",
"x",
"in",
"self",
".",
"model",
".",
"layers",
"]",
"return",
"layer_names"
] |
https://github.com/cleverhans-lab/cleverhans/blob/e5d00e537ce7ad6119ed5a8db1f0e9736d1f6e1d/cleverhans_v3.1.0/cleverhans/utils_keras.py#L207-L212
|
|
openstack/manila
|
142990edc027e14839d5deaf4954dd6fc88de15e
|
manila/share/drivers/zfssa/zfssarest.py
|
python
|
ZFSSAApi.login
|
(self, auth_str)
|
Login to the appliance.
|
Login to the appliance.
|
[
"Login",
"to",
"the",
"appliance",
"."
] |
def login(self, auth_str):
"""Login to the appliance."""
if self.rclient and not self.rclient.islogin():
self.rclient.login(auth_str)
|
[
"def",
"login",
"(",
"self",
",",
"auth_str",
")",
":",
"if",
"self",
".",
"rclient",
"and",
"not",
"self",
".",
"rclient",
".",
"islogin",
"(",
")",
":",
"self",
".",
"rclient",
".",
"login",
"(",
"auth_str",
")"
] |
https://github.com/openstack/manila/blob/142990edc027e14839d5deaf4954dd6fc88de15e/manila/share/drivers/zfssa/zfssarest.py#L80-L83
|
||
khanhnamle1994/natural-language-processing
|
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
|
assignment1/.env/lib/python2.7/site-packages/numpy/linalg/linalg.py
|
python
|
eig
|
(a)
|
return w.astype(result_t), wrap(vt)
|
Compute the eigenvalues and right eigenvectors of a square array.
Parameters
----------
a : (..., M, M) array
Matrices for which the eigenvalues and right eigenvectors will
be computed
Returns
-------
w : (..., M) array
The eigenvalues, each repeated according to its multiplicity.
The eigenvalues are not necessarily ordered. The resulting
array will be always be of complex type. When `a` is real
the resulting eigenvalues will be real (0 imaginary part) or
occur in conjugate pairs
v : (..., M, M) array
The normalized (unit "length") eigenvectors, such that the
column ``v[:,i]`` is the eigenvector corresponding to the
eigenvalue ``w[i]``.
Raises
------
LinAlgError
If the eigenvalue computation does not converge.
See Also
--------
eigvalsh : eigenvalues of a symmetric or Hermitian (conjugate symmetric)
array.
eigvals : eigenvalues of a non-symmetric array.
Notes
-----
Broadcasting rules apply, see the `numpy.linalg` documentation for
details.
This is implemented using the _geev LAPACK routines which compute
the eigenvalues and eigenvectors of general square arrays.
The number `w` is an eigenvalue of `a` if there exists a vector
`v` such that ``dot(a,v) = w * v``. Thus, the arrays `a`, `w`, and
`v` satisfy the equations ``dot(a[:,:], v[:,i]) = w[i] * v[:,i]``
for :math:`i \\in \\{0,...,M-1\\}`.
The array `v` of eigenvectors may not be of maximum rank, that is, some
of the columns may be linearly dependent, although round-off error may
obscure that fact. If the eigenvalues are all different, then theoretically
the eigenvectors are linearly independent. Likewise, the (complex-valued)
matrix of eigenvectors `v` is unitary if the matrix `a` is normal, i.e.,
if ``dot(a, a.H) = dot(a.H, a)``, where `a.H` denotes the conjugate
transpose of `a`.
Finally, it is emphasized that `v` consists of the *right* (as in
right-hand side) eigenvectors of `a`. A vector `y` satisfying
``dot(y.T, a) = z * y.T`` for some number `z` is called a *left*
eigenvector of `a`, and, in general, the left and right eigenvectors
of a matrix are not necessarily the (perhaps conjugate) transposes
of each other.
References
----------
G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, FL,
Academic Press, Inc., 1980, Various pp.
Examples
--------
>>> from numpy import linalg as LA
(Almost) trivial example with real e-values and e-vectors.
>>> w, v = LA.eig(np.diag((1, 2, 3)))
>>> w; v
array([ 1., 2., 3.])
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
Real matrix possessing complex e-values and e-vectors; note that the
e-values are complex conjugates of each other.
>>> w, v = LA.eig(np.array([[1, -1], [1, 1]]))
>>> w; v
array([ 1. + 1.j, 1. - 1.j])
array([[ 0.70710678+0.j , 0.70710678+0.j ],
[ 0.00000000-0.70710678j, 0.00000000+0.70710678j]])
Complex-valued matrix with real e-values (but complex-valued e-vectors);
note that a.conj().T = a, i.e., a is Hermitian.
>>> a = np.array([[1, 1j], [-1j, 1]])
>>> w, v = LA.eig(a)
>>> w; v
array([ 2.00000000e+00+0.j, 5.98651912e-36+0.j]) # i.e., {2, 0}
array([[ 0.00000000+0.70710678j, 0.70710678+0.j ],
[ 0.70710678+0.j , 0.00000000+0.70710678j]])
Be careful about round-off error!
>>> a = np.array([[1 + 1e-9, 0], [0, 1 - 1e-9]])
>>> # Theor. e-values are 1 +/- 1e-9
>>> w, v = LA.eig(a)
>>> w; v
array([ 1., 1.])
array([[ 1., 0.],
[ 0., 1.]])
|
Compute the eigenvalues and right eigenvectors of a square array.
|
[
"Compute",
"the",
"eigenvalues",
"and",
"right",
"eigenvectors",
"of",
"a",
"square",
"array",
"."
] |
def eig(a):
"""
Compute the eigenvalues and right eigenvectors of a square array.
Parameters
----------
a : (..., M, M) array
Matrices for which the eigenvalues and right eigenvectors will
be computed
Returns
-------
w : (..., M) array
The eigenvalues, each repeated according to its multiplicity.
The eigenvalues are not necessarily ordered. The resulting
array will be always be of complex type. When `a` is real
the resulting eigenvalues will be real (0 imaginary part) or
occur in conjugate pairs
v : (..., M, M) array
The normalized (unit "length") eigenvectors, such that the
column ``v[:,i]`` is the eigenvector corresponding to the
eigenvalue ``w[i]``.
Raises
------
LinAlgError
If the eigenvalue computation does not converge.
See Also
--------
eigvalsh : eigenvalues of a symmetric or Hermitian (conjugate symmetric)
array.
eigvals : eigenvalues of a non-symmetric array.
Notes
-----
Broadcasting rules apply, see the `numpy.linalg` documentation for
details.
This is implemented using the _geev LAPACK routines which compute
the eigenvalues and eigenvectors of general square arrays.
The number `w` is an eigenvalue of `a` if there exists a vector
`v` such that ``dot(a,v) = w * v``. Thus, the arrays `a`, `w`, and
`v` satisfy the equations ``dot(a[:,:], v[:,i]) = w[i] * v[:,i]``
for :math:`i \\in \\{0,...,M-1\\}`.
The array `v` of eigenvectors may not be of maximum rank, that is, some
of the columns may be linearly dependent, although round-off error may
obscure that fact. If the eigenvalues are all different, then theoretically
the eigenvectors are linearly independent. Likewise, the (complex-valued)
matrix of eigenvectors `v` is unitary if the matrix `a` is normal, i.e.,
if ``dot(a, a.H) = dot(a.H, a)``, where `a.H` denotes the conjugate
transpose of `a`.
Finally, it is emphasized that `v` consists of the *right* (as in
right-hand side) eigenvectors of `a`. A vector `y` satisfying
``dot(y.T, a) = z * y.T`` for some number `z` is called a *left*
eigenvector of `a`, and, in general, the left and right eigenvectors
of a matrix are not necessarily the (perhaps conjugate) transposes
of each other.
References
----------
G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, FL,
Academic Press, Inc., 1980, Various pp.
Examples
--------
>>> from numpy import linalg as LA
(Almost) trivial example with real e-values and e-vectors.
>>> w, v = LA.eig(np.diag((1, 2, 3)))
>>> w; v
array([ 1., 2., 3.])
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
Real matrix possessing complex e-values and e-vectors; note that the
e-values are complex conjugates of each other.
>>> w, v = LA.eig(np.array([[1, -1], [1, 1]]))
>>> w; v
array([ 1. + 1.j, 1. - 1.j])
array([[ 0.70710678+0.j , 0.70710678+0.j ],
[ 0.00000000-0.70710678j, 0.00000000+0.70710678j]])
Complex-valued matrix with real e-values (but complex-valued e-vectors);
note that a.conj().T = a, i.e., a is Hermitian.
>>> a = np.array([[1, 1j], [-1j, 1]])
>>> w, v = LA.eig(a)
>>> w; v
array([ 2.00000000e+00+0.j, 5.98651912e-36+0.j]) # i.e., {2, 0}
array([[ 0.00000000+0.70710678j, 0.70710678+0.j ],
[ 0.70710678+0.j , 0.00000000+0.70710678j]])
Be careful about round-off error!
>>> a = np.array([[1 + 1e-9, 0], [0, 1 - 1e-9]])
>>> # Theor. e-values are 1 +/- 1e-9
>>> w, v = LA.eig(a)
>>> w; v
array([ 1., 1.])
array([[ 1., 0.],
[ 0., 1.]])
"""
a, wrap = _makearray(a)
_assertRankAtLeast2(a)
_assertNdSquareness(a)
_assertFinite(a)
t, result_t = _commonType(a)
extobj = get_linalg_error_extobj(
_raise_linalgerror_eigenvalues_nonconvergence)
signature = 'D->DD' if isComplexType(t) else 'd->DD'
w, vt = _umath_linalg.eig(a, signature=signature, extobj=extobj)
if not isComplexType(t) and all(w.imag == 0.0):
w = w.real
vt = vt.real
result_t = _realType(result_t)
else:
result_t = _complexType(result_t)
vt = vt.astype(result_t)
return w.astype(result_t), wrap(vt)
|
[
"def",
"eig",
"(",
"a",
")",
":",
"a",
",",
"wrap",
"=",
"_makearray",
"(",
"a",
")",
"_assertRankAtLeast2",
"(",
"a",
")",
"_assertNdSquareness",
"(",
"a",
")",
"_assertFinite",
"(",
"a",
")",
"t",
",",
"result_t",
"=",
"_commonType",
"(",
"a",
")",
"extobj",
"=",
"get_linalg_error_extobj",
"(",
"_raise_linalgerror_eigenvalues_nonconvergence",
")",
"signature",
"=",
"'D->DD'",
"if",
"isComplexType",
"(",
"t",
")",
"else",
"'d->DD'",
"w",
",",
"vt",
"=",
"_umath_linalg",
".",
"eig",
"(",
"a",
",",
"signature",
"=",
"signature",
",",
"extobj",
"=",
"extobj",
")",
"if",
"not",
"isComplexType",
"(",
"t",
")",
"and",
"all",
"(",
"w",
".",
"imag",
"==",
"0.0",
")",
":",
"w",
"=",
"w",
".",
"real",
"vt",
"=",
"vt",
".",
"real",
"result_t",
"=",
"_realType",
"(",
"result_t",
")",
"else",
":",
"result_t",
"=",
"_complexType",
"(",
"result_t",
")",
"vt",
"=",
"vt",
".",
"astype",
"(",
"result_t",
")",
"return",
"w",
".",
"astype",
"(",
"result_t",
")",
",",
"wrap",
"(",
"vt",
")"
] |
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/numpy/linalg/linalg.py#L982-L1113
|
|
zigpy/zigpy
|
db10b078874d93ad1c546ec810706c2e5dc33d7f
|
zigpy/zcl/foundation.py
|
python
|
DataTypes.pytype_to_datatype_id
|
(self, python_type)
|
return 0xFF
|
Return Zigbee Datatype ID for a give python type.
|
Return Zigbee Datatype ID for a give python type.
|
[
"Return",
"Zigbee",
"Datatype",
"ID",
"for",
"a",
"give",
"python",
"type",
"."
] |
def pytype_to_datatype_id(self, python_type) -> int:
"""Return Zigbee Datatype ID for a give python type."""
# We return the most specific parent class
for cls in python_type.__mro__:
if cls in self._idx_by_class:
return self._idx_by_class[cls]
return 0xFF
|
[
"def",
"pytype_to_datatype_id",
"(",
"self",
",",
"python_type",
")",
"->",
"int",
":",
"# We return the most specific parent class",
"for",
"cls",
"in",
"python_type",
".",
"__mro__",
":",
"if",
"cls",
"in",
"self",
".",
"_idx_by_class",
":",
"return",
"self",
".",
"_idx_by_class",
"[",
"cls",
"]",
"return",
"0xFF"
] |
https://github.com/zigpy/zigpy/blob/db10b078874d93ad1c546ec810706c2e5dc33d7f/zigpy/zcl/foundation.py#L135-L143
|
|
exodrifter/unity-python
|
bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d
|
Lib/genericpath.py
|
python
|
commonprefix
|
(m)
|
return s1
|
Given a list of pathnames, returns the longest common leading component
|
Given a list of pathnames, returns the longest common leading component
|
[
"Given",
"a",
"list",
"of",
"pathnames",
"returns",
"the",
"longest",
"common",
"leading",
"component"
] |
def commonprefix(m):
"Given a list of pathnames, returns the longest common leading component"
if not m: return ''
s1 = min(m)
s2 = max(m)
for i, c in enumerate(s1):
if c != s2[i]:
return s1[:i]
return s1
|
[
"def",
"commonprefix",
"(",
"m",
")",
":",
"if",
"not",
"m",
":",
"return",
"''",
"s1",
"=",
"min",
"(",
"m",
")",
"s2",
"=",
"max",
"(",
"m",
")",
"for",
"i",
",",
"c",
"in",
"enumerate",
"(",
"s1",
")",
":",
"if",
"c",
"!=",
"s2",
"[",
"i",
"]",
":",
"return",
"s1",
"[",
":",
"i",
"]",
"return",
"s1"
] |
https://github.com/exodrifter/unity-python/blob/bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d/Lib/genericpath.py#L76-L84
|
|
JimmXinu/FanFicFare
|
bc149a2deb2636320fe50a3e374af6eef8f61889
|
included_dependencies/urllib3/util/wait.py
|
python
|
wait_for_write
|
(sock, timeout=None)
|
return wait_for_socket(sock, write=True, timeout=timeout)
|
Waits for writing to be available on a given socket.
Returns True if the socket is readable, or False if the timeout expired.
|
Waits for writing to be available on a given socket.
Returns True if the socket is readable, or False if the timeout expired.
|
[
"Waits",
"for",
"writing",
"to",
"be",
"available",
"on",
"a",
"given",
"socket",
".",
"Returns",
"True",
"if",
"the",
"socket",
"is",
"readable",
"or",
"False",
"if",
"the",
"timeout",
"expired",
"."
] |
def wait_for_write(sock, timeout=None):
"""Waits for writing to be available on a given socket.
Returns True if the socket is readable, or False if the timeout expired.
"""
return wait_for_socket(sock, write=True, timeout=timeout)
|
[
"def",
"wait_for_write",
"(",
"sock",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"wait_for_socket",
"(",
"sock",
",",
"write",
"=",
"True",
",",
"timeout",
"=",
"timeout",
")"
] |
https://github.com/JimmXinu/FanFicFare/blob/bc149a2deb2636320fe50a3e374af6eef8f61889/included_dependencies/urllib3/util/wait.py#L149-L153
|
|
ethereum/trinity
|
6383280c5044feb06695ac2f7bc1100b7bcf4fe0
|
p2p/commands.py
|
python
|
NoneSerializationCodec.decode
|
(self, data: bytes)
|
[] |
def decode(self, data: bytes) -> None:
if data == b'\xc0':
return None
else:
raise MalformedMessage(f"Should be empty. Got {len(data)} bytes: {data.hex()}")
|
[
"def",
"decode",
"(",
"self",
",",
"data",
":",
"bytes",
")",
"->",
"None",
":",
"if",
"data",
"==",
"b'\\xc0'",
":",
"return",
"None",
"else",
":",
"raise",
"MalformedMessage",
"(",
"f\"Should be empty. Got {len(data)} bytes: {data.hex()}\"",
")"
] |
https://github.com/ethereum/trinity/blob/6383280c5044feb06695ac2f7bc1100b7bcf4fe0/p2p/commands.py#L32-L36
|
||||
Ericsson/codechecker
|
c4e43f62dc3acbf71d3109b337db7c97f7852f43
|
codechecker_common/checker_labels.py
|
python
|
CheckerLabels.labels_of_checker
|
(
self,
checker: str,
analyzer: Optional[str] = None
)
|
return list(set(labels))
|
Return the list of labels of a checker. The list contains (label,
value) pairs. If the checker name is not found in the label config file
then its prefixes are also searched. For example "clang-diagnostic" in
the config file matches "clang-diagnostic-unused-argument".
|
Return the list of labels of a checker. The list contains (label,
value) pairs. If the checker name is not found in the label config file
then its prefixes are also searched. For example "clang-diagnostic" in
the config file matches "clang-diagnostic-unused-argument".
|
[
"Return",
"the",
"list",
"of",
"labels",
"of",
"a",
"checker",
".",
"The",
"list",
"contains",
"(",
"label",
"value",
")",
"pairs",
".",
"If",
"the",
"checker",
"name",
"is",
"not",
"found",
"in",
"the",
"label",
"config",
"file",
"then",
"its",
"prefixes",
"are",
"also",
"searched",
".",
"For",
"example",
"clang",
"-",
"diagnostic",
"in",
"the",
"config",
"file",
"matches",
"clang",
"-",
"diagnostic",
"-",
"unused",
"-",
"argument",
"."
] |
def labels_of_checker(
self,
checker: str,
analyzer: Optional[str] = None
) -> List[Tuple[str, str]]:
"""
Return the list of labels of a checker. The list contains (label,
value) pairs. If the checker name is not found in the label config file
then its prefixes are also searched. For example "clang-diagnostic" in
the config file matches "clang-diagnostic-unused-argument".
"""
labels: List[Tuple[str, str]] = []
for _, checkers in self.__get_analyzer_data(analyzer):
c: Optional[str] = checker
if c not in checkers:
c = next(filter(
lambda c: checker.startswith(cast(str, c)),
iter(checkers.keys())), None)
labels.extend(
map(self.__get_label_key_value, checkers.get(c, [])))
# TODO set() is used for uniqueing results in case a checker name is
# provided by multiple analyzers. This will be unnecessary when we
# cover this case properly.
return list(set(labels))
|
[
"def",
"labels_of_checker",
"(",
"self",
",",
"checker",
":",
"str",
",",
"analyzer",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
":",
"labels",
":",
"List",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
"=",
"[",
"]",
"for",
"_",
",",
"checkers",
"in",
"self",
".",
"__get_analyzer_data",
"(",
"analyzer",
")",
":",
"c",
":",
"Optional",
"[",
"str",
"]",
"=",
"checker",
"if",
"c",
"not",
"in",
"checkers",
":",
"c",
"=",
"next",
"(",
"filter",
"(",
"lambda",
"c",
":",
"checker",
".",
"startswith",
"(",
"cast",
"(",
"str",
",",
"c",
")",
")",
",",
"iter",
"(",
"checkers",
".",
"keys",
"(",
")",
")",
")",
",",
"None",
")",
"labels",
".",
"extend",
"(",
"map",
"(",
"self",
".",
"__get_label_key_value",
",",
"checkers",
".",
"get",
"(",
"c",
",",
"[",
"]",
")",
")",
")",
"# TODO set() is used for uniqueing results in case a checker name is",
"# provided by multiple analyzers. This will be unnecessary when we",
"# cover this case properly.",
"return",
"list",
"(",
"set",
"(",
"labels",
")",
")"
] |
https://github.com/Ericsson/codechecker/blob/c4e43f62dc3acbf71d3109b337db7c97f7852f43/codechecker_common/checker_labels.py#L216-L243
|
|
fabioz/PyDev.Debugger
|
0f8c02a010fe5690405da1dd30ed72326191ce63
|
pydevd_attach_to_process/winappdbg/breakpoint.py
|
python
|
_BreakpointContainer.break_at
|
(self, pid, address, action = None)
|
return bp is not None
|
Sets a code breakpoint at the given process and address.
If instead of an address you pass a label, the breakpoint may be
deferred until the DLL it points to is loaded.
@see: L{stalk_at}, L{dont_break_at}
@type pid: int
@param pid: Process global ID.
@type address: int or str
@param address:
Memory address of code instruction to break at. It can be an
integer value for the actual address or a string with a label
to be resolved.
@type action: function
@param action: (Optional) Action callback function.
See L{define_code_breakpoint} for more details.
@rtype: bool
@return: C{True} if the breakpoint was set immediately, or C{False} if
it was deferred.
|
Sets a code breakpoint at the given process and address.
|
[
"Sets",
"a",
"code",
"breakpoint",
"at",
"the",
"given",
"process",
"and",
"address",
"."
] |
def break_at(self, pid, address, action = None):
"""
Sets a code breakpoint at the given process and address.
If instead of an address you pass a label, the breakpoint may be
deferred until the DLL it points to is loaded.
@see: L{stalk_at}, L{dont_break_at}
@type pid: int
@param pid: Process global ID.
@type address: int or str
@param address:
Memory address of code instruction to break at. It can be an
integer value for the actual address or a string with a label
to be resolved.
@type action: function
@param action: (Optional) Action callback function.
See L{define_code_breakpoint} for more details.
@rtype: bool
@return: C{True} if the breakpoint was set immediately, or C{False} if
it was deferred.
"""
bp = self.__set_break(pid, address, action, oneshot = False)
return bp is not None
|
[
"def",
"break_at",
"(",
"self",
",",
"pid",
",",
"address",
",",
"action",
"=",
"None",
")",
":",
"bp",
"=",
"self",
".",
"__set_break",
"(",
"pid",
",",
"address",
",",
"action",
",",
"oneshot",
"=",
"False",
")",
"return",
"bp",
"is",
"not",
"None"
] |
https://github.com/fabioz/PyDev.Debugger/blob/0f8c02a010fe5690405da1dd30ed72326191ce63/pydevd_attach_to_process/winappdbg/breakpoint.py#L3908-L3936
|
|
zhl2008/awd-platform
|
0416b31abea29743387b10b3914581fbe8e7da5e
|
web_flaskbb/lib/python2.7/site-packages/werkzeug/wrappers.py
|
python
|
BaseRequest.headers
|
(self)
|
return EnvironHeaders(self.environ)
|
The headers from the WSGI environ as immutable
:class:`~werkzeug.datastructures.EnvironHeaders`.
|
The headers from the WSGI environ as immutable
:class:`~werkzeug.datastructures.EnvironHeaders`.
|
[
"The",
"headers",
"from",
"the",
"WSGI",
"environ",
"as",
"immutable",
":",
"class",
":",
"~werkzeug",
".",
"datastructures",
".",
"EnvironHeaders",
"."
] |
def headers(self):
"""The headers from the WSGI environ as immutable
:class:`~werkzeug.datastructures.EnvironHeaders`.
"""
return EnvironHeaders(self.environ)
|
[
"def",
"headers",
"(",
"self",
")",
":",
"return",
"EnvironHeaders",
"(",
"self",
".",
"environ",
")"
] |
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/werkzeug/wrappers.py#L583-L587
|
|
DataDog/dd-agent
|
526559be731b6e47b12d7aa8b6d45cb8d9ac4d68
|
agent.py
|
python
|
Agent.run
|
(self, config=None)
|
Main loop of the collector
|
Main loop of the collector
|
[
"Main",
"loop",
"of",
"the",
"collector"
] |
def run(self, config=None):
"""Main loop of the collector"""
# Gracefully exit on sigterm.
signal.signal(signal.SIGTERM, self._handle_sigterm)
if not Platform.is_windows():
# A SIGUSR1 signals an exit with an autorestart
signal.signal(signal.SIGUSR1, self._handle_sigusr1)
# Handle Keyboard Interrupt
signal.signal(signal.SIGINT, self._handle_sigterm)
# A SIGHUP signals a configuration reload
signal.signal(signal.SIGHUP, self._handle_sighup)
else:
sdk_integrations = get_sdk_integration_paths()
for name, path in sdk_integrations.iteritems():
lib_path = os.path.join(path, 'lib')
if os.path.exists(lib_path):
sys.path.append(lib_path)
# Save the agent start-up stats.
CollectorStatus().persist()
# Intialize the collector.
if not config:
try:
config = get_config(parse_args=True)
except:
log.warning("Failed to load configuration")
sys.exit(2)
self._agentConfig = self._set_agent_config_hostname(config)
hostname = get_hostname(self._agentConfig)
systemStats = get_system_stats(
proc_path=self._agentConfig.get('procfs_path', '/proc').rstrip('/')
)
emitters = self._get_emitters()
# Initialize service discovery
if self._agentConfig.get('service_discovery'):
self.sd_backend = get_sd_backend(self._agentConfig)
if self.sd_backend and _is_affirmative(self._agentConfig.get('sd_jmx_enable', False)):
pipe_path = get_jmx_pipe_path()
if Platform.is_windows():
pipe_name = pipe_path.format(pipename=SD_PIPE_NAME)
else:
pipe_name = os.path.join(pipe_path, SD_PIPE_NAME)
if os.access(pipe_path, os.W_OK):
if not os.path.exists(pipe_name):
os.mkfifo(pipe_name)
self.sd_pipe = os.open(pipe_name, os.O_RDWR) # RW to avoid blocking (will only W)
# Initialize Supervisor proxy
self.supervisor_proxy = self._get_supervisor_socket(self._agentConfig)
else:
log.debug('Unable to create pipe in temporary directory. JMX service discovery disabled.')
# Load the checks.d checks
self._checksd = load_check_directory(self._agentConfig, hostname)
# Load JMX configs if available
if self._jmx_service_discovery_enabled:
self.sd_pipe_jmx_configs(hostname)
# Initialize the Collector
self.collector = Collector(self._agentConfig, emitters, systemStats, hostname)
# In developer mode, the number of runs to be included in a single collector profile
try:
self.collector_profile_interval = int(
self._agentConfig.get('collector_profile_interval', DEFAULT_COLLECTOR_PROFILE_INTERVAL))
except ValueError:
log.warn('collector_profile_interval is invalid. '
'Using default value instead (%s).' % DEFAULT_COLLECTOR_PROFILE_INTERVAL)
self.collector_profile_interval = DEFAULT_COLLECTOR_PROFILE_INTERVAL
# Configure the watchdog.
self.check_frequency = int(self._agentConfig['check_freq'])
watchdog = self._get_watchdog(self.check_frequency)
# Initialize the auto-restarter
self.restart_interval = int(self._agentConfig.get('restart_interval', RESTART_INTERVAL))
self.agent_start = time.time()
self.allow_profiling = _is_affirmative(self._agentConfig.get('allow_profiling', True))
profiled = False
collector_profiled_runs = 0
# Run the main loop.
while self.run_forever:
# Setup profiling if necessary
if self.allow_profiling and self.in_developer_mode and not profiled:
try:
profiler = AgentProfiler()
profiler.enable_profiling()
profiled = True
except Exception as e:
log.warn("Cannot enable profiler: %s" % str(e))
if self.reload_configs_flag:
if isinstance(self.reload_configs_flag, set):
self.reload_configs(checks_to_reload=self.reload_configs_flag)
else:
self.reload_configs()
# JMXFetch restarts should prompt re-piping *all* JMX configs
if self._jmx_service_discovery_enabled and \
(not self.reload_configs_flag or isinstance(self.reload_configs_flag, set)):
try:
jmx_launch = JMXFetch._get_jmx_launchtime()
if self.last_jmx_piped and self.last_jmx_piped < jmx_launch:
self.sd_pipe_jmx_configs(hostname)
except Exception as e:
log.debug("could not stat JMX lunch file: %s", e)
# Do the work. Pass `configs_reloaded` to let the collector know if it needs to
# look for the AgentMetrics check and pop it out.
self.collector.run(checksd=self._checksd,
start_event=self.start_event,
configs_reloaded=True if self.reload_configs_flag else False)
self.reload_configs_flag = False
# Look for change in the config template store.
# The self.sd_backend.reload_check_configs flag is set
# to True if a config reload is needed.
if self._agentConfig.get('service_discovery') and self.sd_backend and \
not self.sd_backend.reload_check_configs:
try:
self.sd_backend.reload_check_configs = get_config_store(
self._agentConfig).crawl_config_template()
except Exception as e:
log.warn('Something went wrong while looking for config template changes: %s' % str(e))
# Check if we should run service discovery
# The `reload_check_configs` flag can be set through the docker_daemon check or
# using ConfigStore.crawl_config_template
if self._agentConfig.get('service_discovery') and self.sd_backend and \
self.sd_backend.reload_check_configs:
self.reload_configs_flag = self.sd_backend.reload_check_configs
self.sd_backend.reload_check_configs = False
if profiled:
if collector_profiled_runs >= self.collector_profile_interval:
try:
profiler.disable_profiling()
profiled = False
collector_profiled_runs = 0
except Exception as e:
log.warn("Cannot disable profiler: %s" % str(e))
# Check if we should restart.
if self.autorestart and self._should_restart():
self._do_restart()
# Only plan for next loop if we will continue, otherwise exit quickly.
if self.run_forever:
if watchdog:
watchdog.reset()
if profiled:
collector_profiled_runs += 1
log.debug("Sleeping for {0} seconds".format(self.check_frequency))
time.sleep(self.check_frequency)
# Now clean-up.
try:
CollectorStatus.remove_latest_status()
except Exception:
pass
# Explicitly kill the process, because it might be running as a daemon.
log.info("Exiting. Bye bye.")
sys.exit(0)
|
[
"def",
"run",
"(",
"self",
",",
"config",
"=",
"None",
")",
":",
"# Gracefully exit on sigterm.",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"self",
".",
"_handle_sigterm",
")",
"if",
"not",
"Platform",
".",
"is_windows",
"(",
")",
":",
"# A SIGUSR1 signals an exit with an autorestart",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGUSR1",
",",
"self",
".",
"_handle_sigusr1",
")",
"# Handle Keyboard Interrupt",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"self",
".",
"_handle_sigterm",
")",
"# A SIGHUP signals a configuration reload",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGHUP",
",",
"self",
".",
"_handle_sighup",
")",
"else",
":",
"sdk_integrations",
"=",
"get_sdk_integration_paths",
"(",
")",
"for",
"name",
",",
"path",
"in",
"sdk_integrations",
".",
"iteritems",
"(",
")",
":",
"lib_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'lib'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"lib_path",
")",
":",
"sys",
".",
"path",
".",
"append",
"(",
"lib_path",
")",
"# Save the agent start-up stats.",
"CollectorStatus",
"(",
")",
".",
"persist",
"(",
")",
"# Intialize the collector.",
"if",
"not",
"config",
":",
"try",
":",
"config",
"=",
"get_config",
"(",
"parse_args",
"=",
"True",
")",
"except",
":",
"log",
".",
"warning",
"(",
"\"Failed to load configuration\"",
")",
"sys",
".",
"exit",
"(",
"2",
")",
"self",
".",
"_agentConfig",
"=",
"self",
".",
"_set_agent_config_hostname",
"(",
"config",
")",
"hostname",
"=",
"get_hostname",
"(",
"self",
".",
"_agentConfig",
")",
"systemStats",
"=",
"get_system_stats",
"(",
"proc_path",
"=",
"self",
".",
"_agentConfig",
".",
"get",
"(",
"'procfs_path'",
",",
"'/proc'",
")",
".",
"rstrip",
"(",
"'/'",
")",
")",
"emitters",
"=",
"self",
".",
"_get_emitters",
"(",
")",
"# Initialize service discovery",
"if",
"self",
".",
"_agentConfig",
".",
"get",
"(",
"'service_discovery'",
")",
":",
"self",
".",
"sd_backend",
"=",
"get_sd_backend",
"(",
"self",
".",
"_agentConfig",
")",
"if",
"self",
".",
"sd_backend",
"and",
"_is_affirmative",
"(",
"self",
".",
"_agentConfig",
".",
"get",
"(",
"'sd_jmx_enable'",
",",
"False",
")",
")",
":",
"pipe_path",
"=",
"get_jmx_pipe_path",
"(",
")",
"if",
"Platform",
".",
"is_windows",
"(",
")",
":",
"pipe_name",
"=",
"pipe_path",
".",
"format",
"(",
"pipename",
"=",
"SD_PIPE_NAME",
")",
"else",
":",
"pipe_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"pipe_path",
",",
"SD_PIPE_NAME",
")",
"if",
"os",
".",
"access",
"(",
"pipe_path",
",",
"os",
".",
"W_OK",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"pipe_name",
")",
":",
"os",
".",
"mkfifo",
"(",
"pipe_name",
")",
"self",
".",
"sd_pipe",
"=",
"os",
".",
"open",
"(",
"pipe_name",
",",
"os",
".",
"O_RDWR",
")",
"# RW to avoid blocking (will only W)",
"# Initialize Supervisor proxy",
"self",
".",
"supervisor_proxy",
"=",
"self",
".",
"_get_supervisor_socket",
"(",
"self",
".",
"_agentConfig",
")",
"else",
":",
"log",
".",
"debug",
"(",
"'Unable to create pipe in temporary directory. JMX service discovery disabled.'",
")",
"# Load the checks.d checks",
"self",
".",
"_checksd",
"=",
"load_check_directory",
"(",
"self",
".",
"_agentConfig",
",",
"hostname",
")",
"# Load JMX configs if available",
"if",
"self",
".",
"_jmx_service_discovery_enabled",
":",
"self",
".",
"sd_pipe_jmx_configs",
"(",
"hostname",
")",
"# Initialize the Collector",
"self",
".",
"collector",
"=",
"Collector",
"(",
"self",
".",
"_agentConfig",
",",
"emitters",
",",
"systemStats",
",",
"hostname",
")",
"# In developer mode, the number of runs to be included in a single collector profile",
"try",
":",
"self",
".",
"collector_profile_interval",
"=",
"int",
"(",
"self",
".",
"_agentConfig",
".",
"get",
"(",
"'collector_profile_interval'",
",",
"DEFAULT_COLLECTOR_PROFILE_INTERVAL",
")",
")",
"except",
"ValueError",
":",
"log",
".",
"warn",
"(",
"'collector_profile_interval is invalid. '",
"'Using default value instead (%s).'",
"%",
"DEFAULT_COLLECTOR_PROFILE_INTERVAL",
")",
"self",
".",
"collector_profile_interval",
"=",
"DEFAULT_COLLECTOR_PROFILE_INTERVAL",
"# Configure the watchdog.",
"self",
".",
"check_frequency",
"=",
"int",
"(",
"self",
".",
"_agentConfig",
"[",
"'check_freq'",
"]",
")",
"watchdog",
"=",
"self",
".",
"_get_watchdog",
"(",
"self",
".",
"check_frequency",
")",
"# Initialize the auto-restarter",
"self",
".",
"restart_interval",
"=",
"int",
"(",
"self",
".",
"_agentConfig",
".",
"get",
"(",
"'restart_interval'",
",",
"RESTART_INTERVAL",
")",
")",
"self",
".",
"agent_start",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"allow_profiling",
"=",
"_is_affirmative",
"(",
"self",
".",
"_agentConfig",
".",
"get",
"(",
"'allow_profiling'",
",",
"True",
")",
")",
"profiled",
"=",
"False",
"collector_profiled_runs",
"=",
"0",
"# Run the main loop.",
"while",
"self",
".",
"run_forever",
":",
"# Setup profiling if necessary",
"if",
"self",
".",
"allow_profiling",
"and",
"self",
".",
"in_developer_mode",
"and",
"not",
"profiled",
":",
"try",
":",
"profiler",
"=",
"AgentProfiler",
"(",
")",
"profiler",
".",
"enable_profiling",
"(",
")",
"profiled",
"=",
"True",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"warn",
"(",
"\"Cannot enable profiler: %s\"",
"%",
"str",
"(",
"e",
")",
")",
"if",
"self",
".",
"reload_configs_flag",
":",
"if",
"isinstance",
"(",
"self",
".",
"reload_configs_flag",
",",
"set",
")",
":",
"self",
".",
"reload_configs",
"(",
"checks_to_reload",
"=",
"self",
".",
"reload_configs_flag",
")",
"else",
":",
"self",
".",
"reload_configs",
"(",
")",
"# JMXFetch restarts should prompt re-piping *all* JMX configs",
"if",
"self",
".",
"_jmx_service_discovery_enabled",
"and",
"(",
"not",
"self",
".",
"reload_configs_flag",
"or",
"isinstance",
"(",
"self",
".",
"reload_configs_flag",
",",
"set",
")",
")",
":",
"try",
":",
"jmx_launch",
"=",
"JMXFetch",
".",
"_get_jmx_launchtime",
"(",
")",
"if",
"self",
".",
"last_jmx_piped",
"and",
"self",
".",
"last_jmx_piped",
"<",
"jmx_launch",
":",
"self",
".",
"sd_pipe_jmx_configs",
"(",
"hostname",
")",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"debug",
"(",
"\"could not stat JMX lunch file: %s\"",
",",
"e",
")",
"# Do the work. Pass `configs_reloaded` to let the collector know if it needs to",
"# look for the AgentMetrics check and pop it out.",
"self",
".",
"collector",
".",
"run",
"(",
"checksd",
"=",
"self",
".",
"_checksd",
",",
"start_event",
"=",
"self",
".",
"start_event",
",",
"configs_reloaded",
"=",
"True",
"if",
"self",
".",
"reload_configs_flag",
"else",
"False",
")",
"self",
".",
"reload_configs_flag",
"=",
"False",
"# Look for change in the config template store.",
"# The self.sd_backend.reload_check_configs flag is set",
"# to True if a config reload is needed.",
"if",
"self",
".",
"_agentConfig",
".",
"get",
"(",
"'service_discovery'",
")",
"and",
"self",
".",
"sd_backend",
"and",
"not",
"self",
".",
"sd_backend",
".",
"reload_check_configs",
":",
"try",
":",
"self",
".",
"sd_backend",
".",
"reload_check_configs",
"=",
"get_config_store",
"(",
"self",
".",
"_agentConfig",
")",
".",
"crawl_config_template",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"warn",
"(",
"'Something went wrong while looking for config template changes: %s'",
"%",
"str",
"(",
"e",
")",
")",
"# Check if we should run service discovery",
"# The `reload_check_configs` flag can be set through the docker_daemon check or",
"# using ConfigStore.crawl_config_template",
"if",
"self",
".",
"_agentConfig",
".",
"get",
"(",
"'service_discovery'",
")",
"and",
"self",
".",
"sd_backend",
"and",
"self",
".",
"sd_backend",
".",
"reload_check_configs",
":",
"self",
".",
"reload_configs_flag",
"=",
"self",
".",
"sd_backend",
".",
"reload_check_configs",
"self",
".",
"sd_backend",
".",
"reload_check_configs",
"=",
"False",
"if",
"profiled",
":",
"if",
"collector_profiled_runs",
">=",
"self",
".",
"collector_profile_interval",
":",
"try",
":",
"profiler",
".",
"disable_profiling",
"(",
")",
"profiled",
"=",
"False",
"collector_profiled_runs",
"=",
"0",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"warn",
"(",
"\"Cannot disable profiler: %s\"",
"%",
"str",
"(",
"e",
")",
")",
"# Check if we should restart.",
"if",
"self",
".",
"autorestart",
"and",
"self",
".",
"_should_restart",
"(",
")",
":",
"self",
".",
"_do_restart",
"(",
")",
"# Only plan for next loop if we will continue, otherwise exit quickly.",
"if",
"self",
".",
"run_forever",
":",
"if",
"watchdog",
":",
"watchdog",
".",
"reset",
"(",
")",
"if",
"profiled",
":",
"collector_profiled_runs",
"+=",
"1",
"log",
".",
"debug",
"(",
"\"Sleeping for {0} seconds\"",
".",
"format",
"(",
"self",
".",
"check_frequency",
")",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"check_frequency",
")",
"# Now clean-up.",
"try",
":",
"CollectorStatus",
".",
"remove_latest_status",
"(",
")",
"except",
"Exception",
":",
"pass",
"# Explicitly kill the process, because it might be running as a daemon.",
"log",
".",
"info",
"(",
"\"Exiting. Bye bye.\"",
")",
"sys",
".",
"exit",
"(",
"0",
")"
] |
https://github.com/DataDog/dd-agent/blob/526559be731b6e47b12d7aa8b6d45cb8d9ac4d68/agent.py#L227-L404
|
||
bruderstein/PythonScript
|
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
|
PythonLib/min/zipfile.py
|
python
|
Path.__str__
|
(self)
|
return posixpath.join(self.root.filename, self.at)
|
[] |
def __str__(self):
return posixpath.join(self.root.filename, self.at)
|
[
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"posixpath",
".",
"join",
"(",
"self",
".",
"root",
".",
"filename",
",",
"self",
".",
"at",
")"
] |
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/zipfile.py#L2379-L2380
|
|||
google-research/pegasus
|
649a5978e45a078e1574ed01c92fc12d3aa05f7f
|
pegasus/eval/bleu/bleu_scorer.py
|
python
|
BleuScorer.score
|
(self, target_text, prediction_text)
|
return {"bleu": BleuScore(bleu_score.score)}
|
Calculates bleu scores between target and prediction text.
|
Calculates bleu scores between target and prediction text.
|
[
"Calculates",
"bleu",
"scores",
"between",
"target",
"and",
"prediction",
"text",
"."
] |
def score(self, target_text, prediction_text):
"""Calculates bleu scores between target and prediction text."""
bleu_score = sacrebleu.corpus_bleu([prediction_text], [[target_text]],
smooth_method="exp",
smooth_value=0.0,
force=False,
lowercase=False,
tokenize="intl",
use_effective_order=False)
return {"bleu": BleuScore(bleu_score.score)}
|
[
"def",
"score",
"(",
"self",
",",
"target_text",
",",
"prediction_text",
")",
":",
"bleu_score",
"=",
"sacrebleu",
".",
"corpus_bleu",
"(",
"[",
"prediction_text",
"]",
",",
"[",
"[",
"target_text",
"]",
"]",
",",
"smooth_method",
"=",
"\"exp\"",
",",
"smooth_value",
"=",
"0.0",
",",
"force",
"=",
"False",
",",
"lowercase",
"=",
"False",
",",
"tokenize",
"=",
"\"intl\"",
",",
"use_effective_order",
"=",
"False",
")",
"return",
"{",
"\"bleu\"",
":",
"BleuScore",
"(",
"bleu_score",
".",
"score",
")",
"}"
] |
https://github.com/google-research/pegasus/blob/649a5978e45a078e1574ed01c92fc12d3aa05f7f/pegasus/eval/bleu/bleu_scorer.py#L29-L38
|
|
DataDog/integrations-core
|
934674b29d94b70ccc008f76ea172d0cdae05e1e
|
couch/datadog_checks/couch/config_models/defaults.py
|
python
|
instance_headers
|
(field, value)
|
return get_default_field_value(field, value)
|
[] |
def instance_headers(field, value):
return get_default_field_value(field, value)
|
[
"def",
"instance_headers",
"(",
"field",
",",
"value",
")",
":",
"return",
"get_default_field_value",
"(",
"field",
",",
"value",
")"
] |
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/couch/datadog_checks/couch/config_models/defaults.py#L77-L78
|
|||
librahfacebook/Detection
|
84504d086634950224716f4de0e4c8a684493c34
|
object_detection/utils/vrd_evaluation.py
|
python
|
VRDDetectionEvaluator.add_single_ground_truth_image_info
|
(self, image_id, groundtruth_dict)
|
Adds groundtruth for a single image to be used for evaluation.
Args:
image_id: A unique string/integer identifier for the image.
groundtruth_dict: A dictionary containing -
standard_fields.InputDataFields.groundtruth_boxes: A numpy array
of structures with the shape [M, 1], representing M tuples, each tuple
containing the same number of named bounding boxes.
Each box is of the format [y_min, x_min, y_max, x_max] (see
datatype vrd_box_data_type, single_box_data_type above).
standard_fields.InputDataFields.groundtruth_classes: A numpy array of
structures shape [M, 1], representing the class labels of the
corresponding bounding boxes and possibly additional classes (see
datatype label_data_type above).
standard_fields.InputDataFields.groundtruth_image_classes: numpy array
of shape [K] containing verified labels.
Raises:
ValueError: On adding groundtruth for an image more than once.
|
Adds groundtruth for a single image to be used for evaluation.
|
[
"Adds",
"groundtruth",
"for",
"a",
"single",
"image",
"to",
"be",
"used",
"for",
"evaluation",
"."
] |
def add_single_ground_truth_image_info(self, image_id, groundtruth_dict):
"""Adds groundtruth for a single image to be used for evaluation.
Args:
image_id: A unique string/integer identifier for the image.
groundtruth_dict: A dictionary containing -
standard_fields.InputDataFields.groundtruth_boxes: A numpy array
of structures with the shape [M, 1], representing M tuples, each tuple
containing the same number of named bounding boxes.
Each box is of the format [y_min, x_min, y_max, x_max] (see
datatype vrd_box_data_type, single_box_data_type above).
standard_fields.InputDataFields.groundtruth_classes: A numpy array of
structures shape [M, 1], representing the class labels of the
corresponding bounding boxes and possibly additional classes (see
datatype label_data_type above).
standard_fields.InputDataFields.groundtruth_image_classes: numpy array
of shape [K] containing verified labels.
Raises:
ValueError: On adding groundtruth for an image more than once.
"""
if image_id in self._image_ids:
raise ValueError('Image with id {} already added.'.format(image_id))
groundtruth_class_tuples = (
groundtruth_dict[standard_fields.InputDataFields.groundtruth_classes])
groundtruth_box_tuples = (
groundtruth_dict[standard_fields.InputDataFields.groundtruth_boxes])
self._evaluation.add_single_ground_truth_image_info(
image_key=image_id,
groundtruth_box_tuples=self._process_groundtruth_boxes(
groundtruth_box_tuples),
groundtruth_class_tuples=groundtruth_class_tuples)
self._image_ids.update([image_id])
all_classes = []
for field in groundtruth_box_tuples.dtype.fields:
all_classes.append(groundtruth_class_tuples[field])
groudtruth_positive_classes = np.unique(np.concatenate(all_classes))
verified_labels = groundtruth_dict.get(
standard_fields.InputDataFields.groundtruth_image_classes,
np.array([], dtype=int))
self._evaluatable_labels[image_id] = np.unique(
np.concatenate((verified_labels, groudtruth_positive_classes)))
self._negative_labels[image_id] = np.setdiff1d(verified_labels,
groudtruth_positive_classes)
|
[
"def",
"add_single_ground_truth_image_info",
"(",
"self",
",",
"image_id",
",",
"groundtruth_dict",
")",
":",
"if",
"image_id",
"in",
"self",
".",
"_image_ids",
":",
"raise",
"ValueError",
"(",
"'Image with id {} already added.'",
".",
"format",
"(",
"image_id",
")",
")",
"groundtruth_class_tuples",
"=",
"(",
"groundtruth_dict",
"[",
"standard_fields",
".",
"InputDataFields",
".",
"groundtruth_classes",
"]",
")",
"groundtruth_box_tuples",
"=",
"(",
"groundtruth_dict",
"[",
"standard_fields",
".",
"InputDataFields",
".",
"groundtruth_boxes",
"]",
")",
"self",
".",
"_evaluation",
".",
"add_single_ground_truth_image_info",
"(",
"image_key",
"=",
"image_id",
",",
"groundtruth_box_tuples",
"=",
"self",
".",
"_process_groundtruth_boxes",
"(",
"groundtruth_box_tuples",
")",
",",
"groundtruth_class_tuples",
"=",
"groundtruth_class_tuples",
")",
"self",
".",
"_image_ids",
".",
"update",
"(",
"[",
"image_id",
"]",
")",
"all_classes",
"=",
"[",
"]",
"for",
"field",
"in",
"groundtruth_box_tuples",
".",
"dtype",
".",
"fields",
":",
"all_classes",
".",
"append",
"(",
"groundtruth_class_tuples",
"[",
"field",
"]",
")",
"groudtruth_positive_classes",
"=",
"np",
".",
"unique",
"(",
"np",
".",
"concatenate",
"(",
"all_classes",
")",
")",
"verified_labels",
"=",
"groundtruth_dict",
".",
"get",
"(",
"standard_fields",
".",
"InputDataFields",
".",
"groundtruth_image_classes",
",",
"np",
".",
"array",
"(",
"[",
"]",
",",
"dtype",
"=",
"int",
")",
")",
"self",
".",
"_evaluatable_labels",
"[",
"image_id",
"]",
"=",
"np",
".",
"unique",
"(",
"np",
".",
"concatenate",
"(",
"(",
"verified_labels",
",",
"groudtruth_positive_classes",
")",
")",
")",
"self",
".",
"_negative_labels",
"[",
"image_id",
"]",
"=",
"np",
".",
"setdiff1d",
"(",
"verified_labels",
",",
"groudtruth_positive_classes",
")"
] |
https://github.com/librahfacebook/Detection/blob/84504d086634950224716f4de0e4c8a684493c34/object_detection/utils/vrd_evaluation.py#L116-L161
|
||
karpathy/find-birds
|
f99b57a918f9fe0ead7f1f69b763d0b4385682cc
|
common.py
|
python
|
api_iter
|
(api_func, user, limit)
|
return elements
|
Iterates API while error fetching correct. can't believe I have to do this manually and that
it is not supported by tweepy. It claims to have it, but when I tried it crashed with an error.
|
Iterates API while error fetching correct. can't believe I have to do this manually and that
it is not supported by tweepy. It claims to have it, but when I tried it crashed with an error.
|
[
"Iterates",
"API",
"while",
"error",
"fetching",
"correct",
".",
"can",
"t",
"believe",
"I",
"have",
"to",
"do",
"this",
"manually",
"and",
"that",
"it",
"is",
"not",
"supported",
"by",
"tweepy",
".",
"It",
"claims",
"to",
"have",
"it",
"but",
"when",
"I",
"tried",
"it",
"crashed",
"with",
"an",
"error",
"."
] |
def api_iter(api_func, user, limit):
"""
Iterates API while error fetching correct. can't believe I have to do this manually and that
it is not supported by tweepy. It claims to have it, but when I tried it crashed with an error.
"""
if limit == 0:
return [] # fast escape when applicable
it = tweepy.Cursor(api_func, id=user).items(limit)
elements = []
while True:
try:
f = it.next()
elements.append(f)
except tweepy.TweepError:
print("got a tweepy error. collected %d/%d so far. waiting 15 minutes..." % (len(elements), limit))
time.sleep(60 * 15 + 10)
continue
except StopIteration:
break
return elements
|
[
"def",
"api_iter",
"(",
"api_func",
",",
"user",
",",
"limit",
")",
":",
"if",
"limit",
"==",
"0",
":",
"return",
"[",
"]",
"# fast escape when applicable",
"it",
"=",
"tweepy",
".",
"Cursor",
"(",
"api_func",
",",
"id",
"=",
"user",
")",
".",
"items",
"(",
"limit",
")",
"elements",
"=",
"[",
"]",
"while",
"True",
":",
"try",
":",
"f",
"=",
"it",
".",
"next",
"(",
")",
"elements",
".",
"append",
"(",
"f",
")",
"except",
"tweepy",
".",
"TweepError",
":",
"print",
"(",
"\"got a tweepy error. collected %d/%d so far. waiting 15 minutes...\"",
"%",
"(",
"len",
"(",
"elements",
")",
",",
"limit",
")",
")",
"time",
".",
"sleep",
"(",
"60",
"*",
"15",
"+",
"10",
")",
"continue",
"except",
"StopIteration",
":",
"break",
"return",
"elements"
] |
https://github.com/karpathy/find-birds/blob/f99b57a918f9fe0ead7f1f69b763d0b4385682cc/common.py#L20-L41
|
|
IronLanguages/ironpython2
|
51fdedeeda15727717fb8268a805f71b06c0b9f1
|
Src/StdLib/Lib/inspect.py
|
python
|
getblock
|
(lines)
|
return lines[:blockfinder.last]
|
Extract the block of code at the top of the given list of lines.
|
Extract the block of code at the top of the given list of lines.
|
[
"Extract",
"the",
"block",
"of",
"code",
"at",
"the",
"top",
"of",
"the",
"given",
"list",
"of",
"lines",
"."
] |
def getblock(lines):
"""Extract the block of code at the top of the given list of lines."""
blockfinder = BlockFinder()
try:
tokenize.tokenize(iter(lines).next, blockfinder.tokeneater)
except (EndOfBlock, IndentationError):
pass
return lines[:blockfinder.last]
|
[
"def",
"getblock",
"(",
"lines",
")",
":",
"blockfinder",
"=",
"BlockFinder",
"(",
")",
"try",
":",
"tokenize",
".",
"tokenize",
"(",
"iter",
"(",
"lines",
")",
".",
"next",
",",
"blockfinder",
".",
"tokeneater",
")",
"except",
"(",
"EndOfBlock",
",",
"IndentationError",
")",
":",
"pass",
"return",
"lines",
"[",
":",
"blockfinder",
".",
"last",
"]"
] |
https://github.com/IronLanguages/ironpython2/blob/51fdedeeda15727717fb8268a805f71b06c0b9f1/Src/StdLib/Lib/inspect.py#L672-L679
|
|
holzschu/Carnets
|
44effb10ddfc6aa5c8b0687582a724ba82c6b547
|
Library/lib/python3.7/site-packages/sympy/sets/fancysets.py
|
python
|
normalize_theta_set
|
(theta)
|
Normalize a Real Set `theta` in the Interval [0, 2*pi). It returns
a normalized value of theta in the Set. For Interval, a maximum of
one cycle [0, 2*pi], is returned i.e. for theta equal to [0, 10*pi],
returned normalized value would be [0, 2*pi). As of now intervals
with end points as non-multiples of `pi` is not supported.
Raises
======
NotImplementedError
The algorithms for Normalizing theta Set are not yet
implemented.
ValueError
The input is not valid, i.e. the input is not a real set.
RuntimeError
It is a bug, please report to the github issue tracker.
Examples
========
>>> from sympy.sets.fancysets import normalize_theta_set
>>> from sympy import Interval, FiniteSet, pi
>>> normalize_theta_set(Interval(9*pi/2, 5*pi))
Interval(pi/2, pi)
>>> normalize_theta_set(Interval(-3*pi/2, pi/2))
Interval.Ropen(0, 2*pi)
>>> normalize_theta_set(Interval(-pi/2, pi/2))
Union(Interval(0, pi/2), Interval.Ropen(3*pi/2, 2*pi))
>>> normalize_theta_set(Interval(-4*pi, 3*pi))
Interval.Ropen(0, 2*pi)
>>> normalize_theta_set(Interval(-3*pi/2, -pi/2))
Interval(pi/2, 3*pi/2)
>>> normalize_theta_set(FiniteSet(0, pi, 3*pi))
FiniteSet(0, pi)
|
Normalize a Real Set `theta` in the Interval [0, 2*pi). It returns
a normalized value of theta in the Set. For Interval, a maximum of
one cycle [0, 2*pi], is returned i.e. for theta equal to [0, 10*pi],
returned normalized value would be [0, 2*pi). As of now intervals
with end points as non-multiples of `pi` is not supported.
|
[
"Normalize",
"a",
"Real",
"Set",
"theta",
"in",
"the",
"Interval",
"[",
"0",
"2",
"*",
"pi",
")",
".",
"It",
"returns",
"a",
"normalized",
"value",
"of",
"theta",
"in",
"the",
"Set",
".",
"For",
"Interval",
"a",
"maximum",
"of",
"one",
"cycle",
"[",
"0",
"2",
"*",
"pi",
"]",
"is",
"returned",
"i",
".",
"e",
".",
"for",
"theta",
"equal",
"to",
"[",
"0",
"10",
"*",
"pi",
"]",
"returned",
"normalized",
"value",
"would",
"be",
"[",
"0",
"2",
"*",
"pi",
")",
".",
"As",
"of",
"now",
"intervals",
"with",
"end",
"points",
"as",
"non",
"-",
"multiples",
"of",
"pi",
"is",
"not",
"supported",
"."
] |
def normalize_theta_set(theta):
"""
Normalize a Real Set `theta` in the Interval [0, 2*pi). It returns
a normalized value of theta in the Set. For Interval, a maximum of
one cycle [0, 2*pi], is returned i.e. for theta equal to [0, 10*pi],
returned normalized value would be [0, 2*pi). As of now intervals
with end points as non-multiples of `pi` is not supported.
Raises
======
NotImplementedError
The algorithms for Normalizing theta Set are not yet
implemented.
ValueError
The input is not valid, i.e. the input is not a real set.
RuntimeError
It is a bug, please report to the github issue tracker.
Examples
========
>>> from sympy.sets.fancysets import normalize_theta_set
>>> from sympy import Interval, FiniteSet, pi
>>> normalize_theta_set(Interval(9*pi/2, 5*pi))
Interval(pi/2, pi)
>>> normalize_theta_set(Interval(-3*pi/2, pi/2))
Interval.Ropen(0, 2*pi)
>>> normalize_theta_set(Interval(-pi/2, pi/2))
Union(Interval(0, pi/2), Interval.Ropen(3*pi/2, 2*pi))
>>> normalize_theta_set(Interval(-4*pi, 3*pi))
Interval.Ropen(0, 2*pi)
>>> normalize_theta_set(Interval(-3*pi/2, -pi/2))
Interval(pi/2, 3*pi/2)
>>> normalize_theta_set(FiniteSet(0, pi, 3*pi))
FiniteSet(0, pi)
"""
from sympy.functions.elementary.trigonometric import _pi_coeff as coeff
if theta.is_Interval:
interval_len = theta.measure
# one complete circle
if interval_len >= 2*S.Pi:
if interval_len == 2*S.Pi and theta.left_open and theta.right_open:
k = coeff(theta.start)
return Union(Interval(0, k*S.Pi, False, True),
Interval(k*S.Pi, 2*S.Pi, True, True))
return Interval(0, 2*S.Pi, False, True)
k_start, k_end = coeff(theta.start), coeff(theta.end)
if k_start is None or k_end is None:
raise NotImplementedError("Normalizing theta without pi as coefficient is "
"not yet implemented")
new_start = k_start*S.Pi
new_end = k_end*S.Pi
if new_start > new_end:
return Union(Interval(S.Zero, new_end, False, theta.right_open),
Interval(new_start, 2*S.Pi, theta.left_open, True))
else:
return Interval(new_start, new_end, theta.left_open, theta.right_open)
elif theta.is_FiniteSet:
new_theta = []
for element in theta:
k = coeff(element)
if k is None:
raise NotImplementedError('Normalizing theta without pi as '
'coefficient, is not Implemented.')
else:
new_theta.append(k*S.Pi)
return FiniteSet(*new_theta)
elif theta.is_Union:
return Union(*[normalize_theta_set(interval) for interval in theta.args])
elif theta.is_subset(S.Reals):
raise NotImplementedError("Normalizing theta when, it is of type %s is not "
"implemented" % type(theta))
else:
raise ValueError(" %s is not a real set" % (theta))
|
[
"def",
"normalize_theta_set",
"(",
"theta",
")",
":",
"from",
"sympy",
".",
"functions",
".",
"elementary",
".",
"trigonometric",
"import",
"_pi_coeff",
"as",
"coeff",
"if",
"theta",
".",
"is_Interval",
":",
"interval_len",
"=",
"theta",
".",
"measure",
"# one complete circle",
"if",
"interval_len",
">=",
"2",
"*",
"S",
".",
"Pi",
":",
"if",
"interval_len",
"==",
"2",
"*",
"S",
".",
"Pi",
"and",
"theta",
".",
"left_open",
"and",
"theta",
".",
"right_open",
":",
"k",
"=",
"coeff",
"(",
"theta",
".",
"start",
")",
"return",
"Union",
"(",
"Interval",
"(",
"0",
",",
"k",
"*",
"S",
".",
"Pi",
",",
"False",
",",
"True",
")",
",",
"Interval",
"(",
"k",
"*",
"S",
".",
"Pi",
",",
"2",
"*",
"S",
".",
"Pi",
",",
"True",
",",
"True",
")",
")",
"return",
"Interval",
"(",
"0",
",",
"2",
"*",
"S",
".",
"Pi",
",",
"False",
",",
"True",
")",
"k_start",
",",
"k_end",
"=",
"coeff",
"(",
"theta",
".",
"start",
")",
",",
"coeff",
"(",
"theta",
".",
"end",
")",
"if",
"k_start",
"is",
"None",
"or",
"k_end",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"\"Normalizing theta without pi as coefficient is \"",
"\"not yet implemented\"",
")",
"new_start",
"=",
"k_start",
"*",
"S",
".",
"Pi",
"new_end",
"=",
"k_end",
"*",
"S",
".",
"Pi",
"if",
"new_start",
">",
"new_end",
":",
"return",
"Union",
"(",
"Interval",
"(",
"S",
".",
"Zero",
",",
"new_end",
",",
"False",
",",
"theta",
".",
"right_open",
")",
",",
"Interval",
"(",
"new_start",
",",
"2",
"*",
"S",
".",
"Pi",
",",
"theta",
".",
"left_open",
",",
"True",
")",
")",
"else",
":",
"return",
"Interval",
"(",
"new_start",
",",
"new_end",
",",
"theta",
".",
"left_open",
",",
"theta",
".",
"right_open",
")",
"elif",
"theta",
".",
"is_FiniteSet",
":",
"new_theta",
"=",
"[",
"]",
"for",
"element",
"in",
"theta",
":",
"k",
"=",
"coeff",
"(",
"element",
")",
"if",
"k",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"'Normalizing theta without pi as '",
"'coefficient, is not Implemented.'",
")",
"else",
":",
"new_theta",
".",
"append",
"(",
"k",
"*",
"S",
".",
"Pi",
")",
"return",
"FiniteSet",
"(",
"*",
"new_theta",
")",
"elif",
"theta",
".",
"is_Union",
":",
"return",
"Union",
"(",
"*",
"[",
"normalize_theta_set",
"(",
"interval",
")",
"for",
"interval",
"in",
"theta",
".",
"args",
"]",
")",
"elif",
"theta",
".",
"is_subset",
"(",
"S",
".",
"Reals",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Normalizing theta when, it is of type %s is not \"",
"\"implemented\"",
"%",
"type",
"(",
"theta",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\" %s is not a real set\"",
"%",
"(",
"theta",
")",
")"
] |
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/sets/fancysets.py#L894-L976
|
||
google-research/bleurt
|
c6f2375c7c178e1480840cf27cb9e2af851394f9
|
bleurt/lib/optimization.py
|
python
|
AdamWeightDecayOptimizer.__init__
|
(self,
learning_rate,
weight_decay_rate=0.0,
beta_1=0.9,
beta_2=0.999,
epsilon=1e-6,
exclude_from_weight_decay=None,
name="AdamWeightDecayOptimizer")
|
Constructs a AdamWeightDecayOptimizer.
|
Constructs a AdamWeightDecayOptimizer.
|
[
"Constructs",
"a",
"AdamWeightDecayOptimizer",
"."
] |
def __init__(self,
learning_rate,
weight_decay_rate=0.0,
beta_1=0.9,
beta_2=0.999,
epsilon=1e-6,
exclude_from_weight_decay=None,
name="AdamWeightDecayOptimizer"):
"""Constructs a AdamWeightDecayOptimizer."""
super(AdamWeightDecayOptimizer, self).__init__(False, name)
self.learning_rate = learning_rate
self.weight_decay_rate = weight_decay_rate
self.beta_1 = beta_1
self.beta_2 = beta_2
self.epsilon = epsilon
self.exclude_from_weight_decay = exclude_from_weight_decay
|
[
"def",
"__init__",
"(",
"self",
",",
"learning_rate",
",",
"weight_decay_rate",
"=",
"0.0",
",",
"beta_1",
"=",
"0.9",
",",
"beta_2",
"=",
"0.999",
",",
"epsilon",
"=",
"1e-6",
",",
"exclude_from_weight_decay",
"=",
"None",
",",
"name",
"=",
"\"AdamWeightDecayOptimizer\"",
")",
":",
"super",
"(",
"AdamWeightDecayOptimizer",
",",
"self",
")",
".",
"__init__",
"(",
"False",
",",
"name",
")",
"self",
".",
"learning_rate",
"=",
"learning_rate",
"self",
".",
"weight_decay_rate",
"=",
"weight_decay_rate",
"self",
".",
"beta_1",
"=",
"beta_1",
"self",
".",
"beta_2",
"=",
"beta_2",
"self",
".",
"epsilon",
"=",
"epsilon",
"self",
".",
"exclude_from_weight_decay",
"=",
"exclude_from_weight_decay"
] |
https://github.com/google-research/bleurt/blob/c6f2375c7c178e1480840cf27cb9e2af851394f9/bleurt/lib/optimization.py#L93-L109
|
||
CityOfZion/neo-python
|
99783bc8310982a5380081ec41a6ee07ba843f3f
|
neo/SmartContract/Contract.py
|
python
|
Contract.CreateSignatureContract
|
(publicKey)
|
return Contract(script, params, pubkey_hash)
|
Create a signature contract.
Args:
publicKey (edcsa.Curve.point): e.g. KeyPair.PublicKey.
Returns:
neo.SmartContract.Contract: a Contract instance.
|
Create a signature contract.
|
[
"Create",
"a",
"signature",
"contract",
"."
] |
def CreateSignatureContract(publicKey):
"""
Create a signature contract.
Args:
publicKey (edcsa.Curve.point): e.g. KeyPair.PublicKey.
Returns:
neo.SmartContract.Contract: a Contract instance.
"""
script = Contract.CreateSignatureRedeemScript(publicKey)
params = b'\x00'
encoded = publicKey.encode_point(True)
pubkey_hash = Crypto.ToScriptHash(encoded, unhex=True)
return Contract(script, params, pubkey_hash)
|
[
"def",
"CreateSignatureContract",
"(",
"publicKey",
")",
":",
"script",
"=",
"Contract",
".",
"CreateSignatureRedeemScript",
"(",
"publicKey",
")",
"params",
"=",
"b'\\x00'",
"encoded",
"=",
"publicKey",
".",
"encode_point",
"(",
"True",
")",
"pubkey_hash",
"=",
"Crypto",
".",
"ToScriptHash",
"(",
"encoded",
",",
"unhex",
"=",
"True",
")",
"return",
"Contract",
"(",
"script",
",",
"params",
",",
"pubkey_hash",
")"
] |
https://github.com/CityOfZion/neo-python/blob/99783bc8310982a5380081ec41a6ee07ba843f3f/neo/SmartContract/Contract.py#L120-L135
|
|
dimagi/commcare-hq
|
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
|
corehq/apps/reports/standard/sms.py
|
python
|
PhoneNumberReport.export_rows
|
(self)
|
return self._get_rows(paginate=False, link_user=False)
|
[] |
def export_rows(self):
return self._get_rows(paginate=False, link_user=False)
|
[
"def",
"export_rows",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_rows",
"(",
"paginate",
"=",
"False",
",",
"link_user",
"=",
"False",
")"
] |
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/reports/standard/sms.py#L1338-L1339
|
|||
selfboot/LeetCode
|
473c0c5451651140d75cbd143309c51cd8fe1cf1
|
Math/07_ReverseInteger.py
|
python
|
Solution.reverse
|
(self, x)
|
return result * negative
|
:type x: int
:rtype: int
|
:type x: int
:rtype: int
|
[
":",
"type",
"x",
":",
"int",
":",
"rtype",
":",
"int"
] |
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
negative = 1
if x < 0:
negative = -1
x = x * -1
result = 0
while x / 10 != 0:
result = (result + x % 10) * 10
x = x / 10
result += x % 10
if abs(result) > 2 ** 31 - 1:
return 0
return result * negative
|
[
"def",
"reverse",
"(",
"self",
",",
"x",
")",
":",
"negative",
"=",
"1",
"if",
"x",
"<",
"0",
":",
"negative",
"=",
"-",
"1",
"x",
"=",
"x",
"*",
"-",
"1",
"result",
"=",
"0",
"while",
"x",
"/",
"10",
"!=",
"0",
":",
"result",
"=",
"(",
"result",
"+",
"x",
"%",
"10",
")",
"*",
"10",
"x",
"=",
"x",
"/",
"10",
"result",
"+=",
"x",
"%",
"10",
"if",
"abs",
"(",
"result",
")",
">",
"2",
"**",
"31",
"-",
"1",
":",
"return",
"0",
"return",
"result",
"*",
"negative"
] |
https://github.com/selfboot/LeetCode/blob/473c0c5451651140d75cbd143309c51cd8fe1cf1/Math/07_ReverseInteger.py#L6-L24
|
|
nosmokingbandit/Watcher3
|
0217e75158b563bdefc8e01c3be7620008cf3977
|
lib/sqlalchemy/orm/events.py
|
python
|
SessionEvents.before_flush
|
(self, session, flush_context, instances)
|
Execute before flush process has started.
:param session: The target :class:`.Session`.
:param flush_context: Internal :class:`.UOWTransaction` object
which handles the details of the flush.
:param instances: Usually ``None``, this is the collection of
objects which can be passed to the :meth:`.Session.flush` method
(note this usage is deprecated).
.. seealso::
:meth:`~.SessionEvents.after_flush`
:meth:`~.SessionEvents.after_flush_postexec`
:ref:`session_persistence_events`
|
Execute before flush process has started.
|
[
"Execute",
"before",
"flush",
"process",
"has",
"started",
"."
] |
def before_flush(self, session, flush_context, instances):
"""Execute before flush process has started.
:param session: The target :class:`.Session`.
:param flush_context: Internal :class:`.UOWTransaction` object
which handles the details of the flush.
:param instances: Usually ``None``, this is the collection of
objects which can be passed to the :meth:`.Session.flush` method
(note this usage is deprecated).
.. seealso::
:meth:`~.SessionEvents.after_flush`
:meth:`~.SessionEvents.after_flush_postexec`
:ref:`session_persistence_events`
"""
|
[
"def",
"before_flush",
"(",
"self",
",",
"session",
",",
"flush_context",
",",
"instances",
")",
":"
] |
https://github.com/nosmokingbandit/Watcher3/blob/0217e75158b563bdefc8e01c3be7620008cf3977/lib/sqlalchemy/orm/events.py#L1373-L1391
|
||
OpenEIT/OpenEIT
|
0448694e8092361ae5ccb45fba81dee543a6244b
|
OpenEIT/backend/bluetooth/build/lib/Adafruit_BluefruitLE/corebluetooth/device.py
|
python
|
CoreBluetoothDevice.is_connected
|
(self)
|
return self._connected.is_set()
|
Return True if the device is connected to the system, otherwise False.
|
Return True if the device is connected to the system, otherwise False.
|
[
"Return",
"True",
"if",
"the",
"device",
"is",
"connected",
"to",
"the",
"system",
"otherwise",
"False",
"."
] |
def is_connected(self):
"""Return True if the device is connected to the system, otherwise False.
"""
return self._connected.is_set()
|
[
"def",
"is_connected",
"(",
"self",
")",
":",
"return",
"self",
".",
"_connected",
".",
"is_set",
"(",
")"
] |
https://github.com/OpenEIT/OpenEIT/blob/0448694e8092361ae5ccb45fba81dee543a6244b/OpenEIT/backend/bluetooth/build/lib/Adafruit_BluefruitLE/corebluetooth/device.py#L181-L184
|
|
OpenMDAO/OpenMDAO-Framework
|
f2e37b7de3edeaaeb2d251b375917adec059db9b
|
openmdao.main/src/openmdao/main/hasparameters.py
|
python
|
ParameterBase._get_scope
|
(self)
|
return self._expreval.scope
|
Return scope of target expression.
|
Return scope of target expression.
|
[
"Return",
"scope",
"of",
"target",
"expression",
"."
] |
def _get_scope(self):
"""Return scope of target expression."""
return self._expreval.scope
|
[
"def",
"_get_scope",
"(",
"self",
")",
":",
"return",
"self",
".",
"_expreval",
".",
"scope"
] |
https://github.com/OpenMDAO/OpenMDAO-Framework/blob/f2e37b7de3edeaaeb2d251b375917adec059db9b/openmdao.main/src/openmdao/main/hasparameters.py#L97-L99
|
|
chris-void/pyway
|
a49c6415e9833e38fa7e5d3399c7e514124b9645
|
ex25.py
|
python
|
print_first_and_last
|
(sentence)
|
Print the first and last words of the sentence.
|
Print the first and last words of the sentence.
|
[
"Print",
"the",
"first",
"and",
"last",
"words",
"of",
"the",
"sentence",
"."
] |
def print_first_and_last(sentence):
"""Print the first and last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
|
[
"def",
"print_first_and_last",
"(",
"sentence",
")",
":",
"words",
"=",
"break_words",
"(",
"sentence",
")",
"print_first_word",
"(",
"words",
")",
"print_last_word",
"(",
"words",
")"
] |
https://github.com/chris-void/pyway/blob/a49c6415e9833e38fa7e5d3399c7e514124b9645/ex25.py#L25-L29
|
||
overviewer/Minecraft-Overviewer
|
7171af587399fee9140eb83fb9b066acd251f57a
|
overviewer_core/observer.py
|
python
|
Observer.start
|
(self, max_value)
|
return self
|
Signals the start of whatever process. Must be called before update
|
Signals the start of whatever process. Must be called before update
|
[
"Signals",
"the",
"start",
"of",
"whatever",
"process",
".",
"Must",
"be",
"called",
"before",
"update"
] |
def start(self, max_value):
"""Signals the start of whatever process. Must be called before update
"""
self._set_max_value(max_value)
self.start_time = time.time()
self.update(0)
return self
|
[
"def",
"start",
"(",
"self",
",",
"max_value",
")",
":",
"self",
".",
"_set_max_value",
"(",
"max_value",
")",
"self",
".",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"update",
"(",
"0",
")",
"return",
"self"
] |
https://github.com/overviewer/Minecraft-Overviewer/blob/7171af587399fee9140eb83fb9b066acd251f57a/overviewer_core/observer.py#L36-L42
|
|
fredrik-johansson/mpmath
|
c11db84b3237bd8fc6721f5a0c5d7c0c98a24dc1
|
mpmath/matrices/linalg.py
|
python
|
LinearAlgebraMethods.lu
|
(ctx, A)
|
return P, L, U
|
A -> P, L, U
LU factorisation of a square matrix A. L is the lower, U the upper part.
P is the permutation matrix indicating the row swaps.
P*A = L*U
If you need efficiency, use the low-level method LU_decomp instead, it's
much more memory efficient.
|
A -> P, L, U
|
[
"A",
"-",
">",
"P",
"L",
"U"
] |
def lu(ctx, A):
"""
A -> P, L, U
LU factorisation of a square matrix A. L is the lower, U the upper part.
P is the permutation matrix indicating the row swaps.
P*A = L*U
If you need efficiency, use the low-level method LU_decomp instead, it's
much more memory efficient.
"""
# get factorization
A, p = ctx.LU_decomp(A)
n = A.rows
L = ctx.matrix(n)
U = ctx.matrix(n)
for i in xrange(n):
for j in xrange(n):
if i > j:
L[i,j] = A[i,j]
elif i == j:
L[i,j] = 1
U[i,j] = A[i,j]
else:
U[i,j] = A[i,j]
# calculate permutation matrix
P = ctx.eye(n)
for k in xrange(len(p)):
ctx.swap_row(P, k, p[k])
return P, L, U
|
[
"def",
"lu",
"(",
"ctx",
",",
"A",
")",
":",
"# get factorization",
"A",
",",
"p",
"=",
"ctx",
".",
"LU_decomp",
"(",
"A",
")",
"n",
"=",
"A",
".",
"rows",
"L",
"=",
"ctx",
".",
"matrix",
"(",
"n",
")",
"U",
"=",
"ctx",
".",
"matrix",
"(",
"n",
")",
"for",
"i",
"in",
"xrange",
"(",
"n",
")",
":",
"for",
"j",
"in",
"xrange",
"(",
"n",
")",
":",
"if",
"i",
">",
"j",
":",
"L",
"[",
"i",
",",
"j",
"]",
"=",
"A",
"[",
"i",
",",
"j",
"]",
"elif",
"i",
"==",
"j",
":",
"L",
"[",
"i",
",",
"j",
"]",
"=",
"1",
"U",
"[",
"i",
",",
"j",
"]",
"=",
"A",
"[",
"i",
",",
"j",
"]",
"else",
":",
"U",
"[",
"i",
",",
"j",
"]",
"=",
"A",
"[",
"i",
",",
"j",
"]",
"# calculate permutation matrix",
"P",
"=",
"ctx",
".",
"eye",
"(",
"n",
")",
"for",
"k",
"in",
"xrange",
"(",
"len",
"(",
"p",
")",
")",
":",
"ctx",
".",
"swap_row",
"(",
"P",
",",
"k",
",",
"p",
"[",
"k",
"]",
")",
"return",
"P",
",",
"L",
",",
"U"
] |
https://github.com/fredrik-johansson/mpmath/blob/c11db84b3237bd8fc6721f5a0c5d7c0c98a24dc1/mpmath/matrices/linalg.py#L251-L281
|
|
saltstack/salt
|
fae5bc757ad0f1716483ce7ae180b451545c2058
|
salt/states/ceph.py
|
python
|
_unchanged
|
(name, msg)
|
return {"name": name, "result": True, "comment": msg, "changes": {}}
|
Utility function: Return structure unchanged
|
Utility function: Return structure unchanged
|
[
"Utility",
"function",
":",
"Return",
"structure",
"unchanged"
] |
def _unchanged(name, msg):
"""
Utility function: Return structure unchanged
"""
return {"name": name, "result": True, "comment": msg, "changes": {}}
|
[
"def",
"_unchanged",
"(",
"name",
",",
"msg",
")",
":",
"return",
"{",
"\"name\"",
":",
"name",
",",
"\"result\"",
":",
"True",
",",
"\"comment\"",
":",
"msg",
",",
"\"changes\"",
":",
"{",
"}",
"}"
] |
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/states/ceph.py#L15-L19
|
|
vertica/vertica-python
|
67323cee6209a6326affbca7dd33f1468a1ad797
|
vertica_python/compat.py
|
python
|
as_bytes
|
(bytes_or_text, encoding='utf-8')
|
Converts either bytes or unicode to `bytes`, using utf-8 encoding for text.
Args:
bytes_or_text: A `bytes`, `bytearray`, `str`, or `unicode` object.
encoding: A string indicating the charset for encoding unicode.
Returns:
A `bytes` object.
Raises:
TypeError: If `bytes_or_text` is not a binary or unicode string.
|
Converts either bytes or unicode to `bytes`, using utf-8 encoding for text.
Args:
bytes_or_text: A `bytes`, `bytearray`, `str`, or `unicode` object.
encoding: A string indicating the charset for encoding unicode.
Returns:
A `bytes` object.
Raises:
TypeError: If `bytes_or_text` is not a binary or unicode string.
|
[
"Converts",
"either",
"bytes",
"or",
"unicode",
"to",
"bytes",
"using",
"utf",
"-",
"8",
"encoding",
"for",
"text",
".",
"Args",
":",
"bytes_or_text",
":",
"A",
"bytes",
"bytearray",
"str",
"or",
"unicode",
"object",
".",
"encoding",
":",
"A",
"string",
"indicating",
"the",
"charset",
"for",
"encoding",
"unicode",
".",
"Returns",
":",
"A",
"bytes",
"object",
".",
"Raises",
":",
"TypeError",
":",
"If",
"bytes_or_text",
"is",
"not",
"a",
"binary",
"or",
"unicode",
"string",
"."
] |
def as_bytes(bytes_or_text, encoding='utf-8'):
"""Converts either bytes or unicode to `bytes`, using utf-8 encoding for text.
Args:
bytes_or_text: A `bytes`, `bytearray`, `str`, or `unicode` object.
encoding: A string indicating the charset for encoding unicode.
Returns:
A `bytes` object.
Raises:
TypeError: If `bytes_or_text` is not a binary or unicode string.
"""
if isinstance(bytes_or_text, _six.text_type):
return bytes_or_text.encode(encoding)
elif isinstance(bytes_or_text, bytearray):
return bytes(bytes_or_text)
elif isinstance(bytes_or_text, bytes):
return bytes_or_text
else:
raise TypeError('Expected binary or unicode string, got %r' %
(bytes_or_text,))
|
[
"def",
"as_bytes",
"(",
"bytes_or_text",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"isinstance",
"(",
"bytes_or_text",
",",
"_six",
".",
"text_type",
")",
":",
"return",
"bytes_or_text",
".",
"encode",
"(",
"encoding",
")",
"elif",
"isinstance",
"(",
"bytes_or_text",
",",
"bytearray",
")",
":",
"return",
"bytes",
"(",
"bytes_or_text",
")",
"elif",
"isinstance",
"(",
"bytes_or_text",
",",
"bytes",
")",
":",
"return",
"bytes_or_text",
"else",
":",
"raise",
"TypeError",
"(",
"'Expected binary or unicode string, got %r'",
"%",
"(",
"bytes_or_text",
",",
")",
")"
] |
https://github.com/vertica/vertica-python/blob/67323cee6209a6326affbca7dd33f1468a1ad797/vertica_python/compat.py#L73-L91
|
||
twilio/twilio-python
|
6e1e811ea57a1edfadd5161ace87397c563f6915
|
twilio/rest/messaging/v1/service/__init__.py
|
python
|
ServiceInstance.fallback_url
|
(self)
|
return self._properties['fallback_url']
|
:returns: The URL that we call using fallback_method if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. This field will be overridden if the `use_inbound_webhook_on_number` field is enabled.
:rtype: unicode
|
:returns: The URL that we call using fallback_method if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. This field will be overridden if the `use_inbound_webhook_on_number` field is enabled.
:rtype: unicode
|
[
":",
"returns",
":",
"The",
"URL",
"that",
"we",
"call",
"using",
"fallback_method",
"if",
"an",
"error",
"occurs",
"while",
"retrieving",
"or",
"executing",
"the",
"TwiML",
"from",
"the",
"Inbound",
"Request",
"URL",
".",
"This",
"field",
"will",
"be",
"overridden",
"if",
"the",
"use_inbound_webhook_on_number",
"field",
"is",
"enabled",
".",
":",
"rtype",
":",
"unicode"
] |
def fallback_url(self):
"""
:returns: The URL that we call using fallback_method if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. This field will be overridden if the `use_inbound_webhook_on_number` field is enabled.
:rtype: unicode
"""
return self._properties['fallback_url']
|
[
"def",
"fallback_url",
"(",
"self",
")",
":",
"return",
"self",
".",
"_properties",
"[",
"'fallback_url'",
"]"
] |
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/messaging/v1/service/__init__.py#L541-L546
|
|
dimagi/commcare-hq
|
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
|
corehq/toggles.py
|
python
|
all_toggles_by_name
|
()
|
return core_toggles
|
[] |
def all_toggles_by_name():
# trick for listing the attributes of the current module.
# http://stackoverflow.com/a/990450/8207
core_toggles = all_toggles_by_name_in_scope(globals())
for module_name in custom_toggle_modules():
module = import_module(module_name)
core_toggles.update(all_toggles_by_name_in_scope(module.__dict__))
return core_toggles
|
[
"def",
"all_toggles_by_name",
"(",
")",
":",
"# trick for listing the attributes of the current module.",
"# http://stackoverflow.com/a/990450/8207",
"core_toggles",
"=",
"all_toggles_by_name_in_scope",
"(",
"globals",
"(",
")",
")",
"for",
"module_name",
"in",
"custom_toggle_modules",
"(",
")",
":",
"module",
"=",
"import_module",
"(",
"module_name",
")",
"core_toggles",
".",
"update",
"(",
"all_toggles_by_name_in_scope",
"(",
"module",
".",
"__dict__",
")",
")",
"return",
"core_toggles"
] |
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/toggles.py#L488-L495
|
|||
natashamjaques/neural_chat
|
ddb977bb4602a67c460d02231e7bbf7b2cb49a97
|
ParlAI/parlai/mturk/tasks/light/light_chats/graph.py
|
python
|
Graph.get_props_from_either
|
(self, id1, id2, prop)
|
return resp1, resp2
|
Try to get ones own prop, fallback to other's prop. Do this for
both provided ids symmetrically
|
Try to get ones own prop, fallback to other's prop. Do this for
both provided ids symmetrically
|
[
"Try",
"to",
"get",
"ones",
"own",
"prop",
"fallback",
"to",
"other",
"s",
"prop",
".",
"Do",
"this",
"for",
"both",
"provided",
"ids",
"symmetrically"
] |
def get_props_from_either(self, id1, id2, prop):
"""Try to get ones own prop, fallback to other's prop. Do this for
both provided ids symmetrically"""
resp1 = self.get_prop(id1, prop, self.get_prop(id2, prop))
resp2 = self.get_prop(id2, prop, self.get_prop(id1, prop))
return resp1, resp2
|
[
"def",
"get_props_from_either",
"(",
"self",
",",
"id1",
",",
"id2",
",",
"prop",
")",
":",
"resp1",
"=",
"self",
".",
"get_prop",
"(",
"id1",
",",
"prop",
",",
"self",
".",
"get_prop",
"(",
"id2",
",",
"prop",
")",
")",
"resp2",
"=",
"self",
".",
"get_prop",
"(",
"id2",
",",
"prop",
",",
"self",
".",
"get_prop",
"(",
"id1",
",",
"prop",
")",
")",
"return",
"resp1",
",",
"resp2"
] |
https://github.com/natashamjaques/neural_chat/blob/ddb977bb4602a67c460d02231e7bbf7b2cb49a97/ParlAI/parlai/mturk/tasks/light/light_chats/graph.py#L3198-L3203
|
|
exodrifter/unity-python
|
bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d
|
Lib/_osx_support.py
|
python
|
customize_compiler
|
(_config_vars)
|
return _config_vars
|
Customize compiler path and configuration variables.
This customization is performed when the first
extension module build is requested
in distutils.sysconfig.customize_compiler).
|
Customize compiler path and configuration variables.
|
[
"Customize",
"compiler",
"path",
"and",
"configuration",
"variables",
"."
] |
def customize_compiler(_config_vars):
"""Customize compiler path and configuration variables.
This customization is performed when the first
extension module build is requested
in distutils.sysconfig.customize_compiler).
"""
# Find a compiler to use for extension module builds
_find_appropriate_compiler(_config_vars)
# Remove ppc arch flags if not supported here
_remove_unsupported_archs(_config_vars)
# Allow user to override all archs with ARCHFLAGS env var
_override_all_archs(_config_vars)
return _config_vars
|
[
"def",
"customize_compiler",
"(",
"_config_vars",
")",
":",
"# Find a compiler to use for extension module builds",
"_find_appropriate_compiler",
"(",
"_config_vars",
")",
"# Remove ppc arch flags if not supported here",
"_remove_unsupported_archs",
"(",
"_config_vars",
")",
"# Allow user to override all archs with ARCHFLAGS env var",
"_override_all_archs",
"(",
"_config_vars",
")",
"return",
"_config_vars"
] |
https://github.com/exodrifter/unity-python/blob/bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d/Lib/_osx_support.py#L409-L426
|
|
galaxyproject/galaxy
|
4c03520f05062e0f4a1b3655dc0b7452fda69943
|
lib/galaxy/config/__init__.py
|
python
|
configure_logging
|
(config)
|
Allow some basic logging configuration to be read from ini file.
This should be able to consume either a galaxy.config.Configuration object
or a simple dictionary of configuration variables.
|
Allow some basic logging configuration to be read from ini file.
|
[
"Allow",
"some",
"basic",
"logging",
"configuration",
"to",
"be",
"read",
"from",
"ini",
"file",
"."
] |
def configure_logging(config):
"""Allow some basic logging configuration to be read from ini file.
This should be able to consume either a galaxy.config.Configuration object
or a simple dictionary of configuration variables.
"""
# Get root logger
logging.addLevelName(LOGLV_TRACE, "TRACE")
# PasteScript will have already configured the logger if the
# 'loggers' section was found in the config file, otherwise we do
# some simple setup using the 'log_*' values from the config.
parser = getattr(config, "global_conf_parser", None)
if parser:
paste_configures_logging = config.global_conf_parser.has_section("loggers")
else:
paste_configures_logging = False
auto_configure_logging = not paste_configures_logging and string_as_bool(config.get("auto_configure_logging", "True"))
if auto_configure_logging:
logging_conf = config.get('logging', None)
if logging_conf is None:
# if using the default logging config, honor the log_level setting
logging_conf = LOGGING_CONFIG_DEFAULT
if config.get('log_level', 'DEBUG') != 'DEBUG':
logging_conf['handlers']['console']['level'] = config.get('log_level', 'DEBUG')
# configure logging with logging dict in config, template *FileHandler handler filenames with the `filename_template` option
for name, conf in logging_conf.get('handlers', {}).items():
if conf['class'].startswith('logging.') and conf['class'].endswith('FileHandler') and 'filename_template' in conf:
conf['filename'] = conf.pop('filename_template').format(**get_stack_facts(config=config))
logging_conf['handlers'][name] = conf
logging.config.dictConfig(logging_conf)
|
[
"def",
"configure_logging",
"(",
"config",
")",
":",
"# Get root logger",
"logging",
".",
"addLevelName",
"(",
"LOGLV_TRACE",
",",
"\"TRACE\"",
")",
"# PasteScript will have already configured the logger if the",
"# 'loggers' section was found in the config file, otherwise we do",
"# some simple setup using the 'log_*' values from the config.",
"parser",
"=",
"getattr",
"(",
"config",
",",
"\"global_conf_parser\"",
",",
"None",
")",
"if",
"parser",
":",
"paste_configures_logging",
"=",
"config",
".",
"global_conf_parser",
".",
"has_section",
"(",
"\"loggers\"",
")",
"else",
":",
"paste_configures_logging",
"=",
"False",
"auto_configure_logging",
"=",
"not",
"paste_configures_logging",
"and",
"string_as_bool",
"(",
"config",
".",
"get",
"(",
"\"auto_configure_logging\"",
",",
"\"True\"",
")",
")",
"if",
"auto_configure_logging",
":",
"logging_conf",
"=",
"config",
".",
"get",
"(",
"'logging'",
",",
"None",
")",
"if",
"logging_conf",
"is",
"None",
":",
"# if using the default logging config, honor the log_level setting",
"logging_conf",
"=",
"LOGGING_CONFIG_DEFAULT",
"if",
"config",
".",
"get",
"(",
"'log_level'",
",",
"'DEBUG'",
")",
"!=",
"'DEBUG'",
":",
"logging_conf",
"[",
"'handlers'",
"]",
"[",
"'console'",
"]",
"[",
"'level'",
"]",
"=",
"config",
".",
"get",
"(",
"'log_level'",
",",
"'DEBUG'",
")",
"# configure logging with logging dict in config, template *FileHandler handler filenames with the `filename_template` option",
"for",
"name",
",",
"conf",
"in",
"logging_conf",
".",
"get",
"(",
"'handlers'",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"if",
"conf",
"[",
"'class'",
"]",
".",
"startswith",
"(",
"'logging.'",
")",
"and",
"conf",
"[",
"'class'",
"]",
".",
"endswith",
"(",
"'FileHandler'",
")",
"and",
"'filename_template'",
"in",
"conf",
":",
"conf",
"[",
"'filename'",
"]",
"=",
"conf",
".",
"pop",
"(",
"'filename_template'",
")",
".",
"format",
"(",
"*",
"*",
"get_stack_facts",
"(",
"config",
"=",
"config",
")",
")",
"logging_conf",
"[",
"'handlers'",
"]",
"[",
"name",
"]",
"=",
"conf",
"logging",
".",
"config",
".",
"dictConfig",
"(",
"logging_conf",
")"
] |
https://github.com/galaxyproject/galaxy/blob/4c03520f05062e0f4a1b3655dc0b7452fda69943/lib/galaxy/config/__init__.py#L1176-L1205
|
||
ashual/scene_generation
|
6f6fe6afffae58da94c0c061e4dcaf273cdb9f44
|
scene_generation/vis.py
|
python
|
draw_scene_graph
|
(objs, triples, vocab=None, **kwargs)
|
return img
|
Use GraphViz to draw a scene graph. If vocab is not passed then we assume
that objs and triples are python lists containing strings for object and
relationship names.
Using this requires that GraphViz is installed. On Ubuntu 16.04 this is easy:
sudo apt-get install graphviz
|
Use GraphViz to draw a scene graph. If vocab is not passed then we assume
that objs and triples are python lists containing strings for object and
relationship names.
|
[
"Use",
"GraphViz",
"to",
"draw",
"a",
"scene",
"graph",
".",
"If",
"vocab",
"is",
"not",
"passed",
"then",
"we",
"assume",
"that",
"objs",
"and",
"triples",
"are",
"python",
"lists",
"containing",
"strings",
"for",
"object",
"and",
"relationship",
"names",
"."
] |
def draw_scene_graph(objs, triples, vocab=None, **kwargs):
"""
Use GraphViz to draw a scene graph. If vocab is not passed then we assume
that objs and triples are python lists containing strings for object and
relationship names.
Using this requires that GraphViz is installed. On Ubuntu 16.04 this is easy:
sudo apt-get install graphviz
"""
output_filename = kwargs.pop('output_filename', 'graph.png')
orientation = kwargs.pop('orientation', 'V')
edge_width = kwargs.pop('edge_width', 6)
arrow_size = kwargs.pop('arrow_size', 1.5)
binary_edge_weight = kwargs.pop('binary_edge_weight', 1.2)
ignore_dummies = kwargs.pop('ignore_dummies', True)
if orientation not in ['V', 'H']:
raise ValueError('Invalid orientation "%s"' % orientation)
rankdir = {'H': 'LR', 'V': 'TD'}[orientation]
if vocab is not None:
# Decode object and relationship names
assert torch.is_tensor(objs)
assert torch.is_tensor(triples)
objs_list, triples_list = [], []
idx_to_obj = ['__image__'] + vocab['my_idx_to_obj']
for i in range(objs.size(0)):
objs_list.append(idx_to_obj[objs[i].item()])
for i in range(triples.size(0)):
s = triples[i, 0].item()
p = vocab['pred_idx_to_name'][triples[i, 1].item()]
o = triples[i, 2].item()
triples_list.append([s, p, o])
objs, triples = objs_list, triples_list
# General setup, and style for object nodes
lines = [
'digraph{',
'graph [size="5,3",ratio="compress",dpi="300",bgcolor="transparent"]',
'rankdir=%s' % rankdir,
'nodesep="0.5"',
'ranksep="0.5"',
'node [shape="box",style="rounded,filled",fontsize="48",color="none"]',
'node [fillcolor="lightpink1"]',
]
# Output nodes for objects
for i, obj in enumerate(objs):
if ignore_dummies and obj == '__image__':
continue
lines.append('%d [label="%s"]' % (i, obj))
# Output relationships
next_node_id = len(objs)
lines.append('node [fillcolor="lightblue1"]')
for s, p, o in triples:
if ignore_dummies and p == '__in_image__':
continue
lines += [
'%d [label="%s"]' % (next_node_id, p),
'%d->%d [penwidth=%f,arrowsize=%f,weight=%f]' % (
s, next_node_id, edge_width, arrow_size, binary_edge_weight),
'%d->%d [penwidth=%f,arrowsize=%f,weight=%f]' % (
next_node_id, o, edge_width, arrow_size, binary_edge_weight)
]
next_node_id += 1
lines.append('}')
# Now it gets slightly hacky. Write the graphviz spec to a temporary
# text file
ff, dot_filename = tempfile.mkstemp()
with open(dot_filename, 'w') as f:
for line in lines:
f.write('%s\n' % line)
os.close(ff)
# Shell out to invoke graphviz; this will save the resulting image to disk,
# so we read it, delete it, then return it.
output_format = os.path.splitext(output_filename)[1][1:]
os.system('dot -T%s %s > %s' % (output_format, dot_filename, output_filename))
os.remove(dot_filename)
img = imread(output_filename)
os.remove(output_filename)
return img
|
[
"def",
"draw_scene_graph",
"(",
"objs",
",",
"triples",
",",
"vocab",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"output_filename",
"=",
"kwargs",
".",
"pop",
"(",
"'output_filename'",
",",
"'graph.png'",
")",
"orientation",
"=",
"kwargs",
".",
"pop",
"(",
"'orientation'",
",",
"'V'",
")",
"edge_width",
"=",
"kwargs",
".",
"pop",
"(",
"'edge_width'",
",",
"6",
")",
"arrow_size",
"=",
"kwargs",
".",
"pop",
"(",
"'arrow_size'",
",",
"1.5",
")",
"binary_edge_weight",
"=",
"kwargs",
".",
"pop",
"(",
"'binary_edge_weight'",
",",
"1.2",
")",
"ignore_dummies",
"=",
"kwargs",
".",
"pop",
"(",
"'ignore_dummies'",
",",
"True",
")",
"if",
"orientation",
"not",
"in",
"[",
"'V'",
",",
"'H'",
"]",
":",
"raise",
"ValueError",
"(",
"'Invalid orientation \"%s\"'",
"%",
"orientation",
")",
"rankdir",
"=",
"{",
"'H'",
":",
"'LR'",
",",
"'V'",
":",
"'TD'",
"}",
"[",
"orientation",
"]",
"if",
"vocab",
"is",
"not",
"None",
":",
"# Decode object and relationship names",
"assert",
"torch",
".",
"is_tensor",
"(",
"objs",
")",
"assert",
"torch",
".",
"is_tensor",
"(",
"triples",
")",
"objs_list",
",",
"triples_list",
"=",
"[",
"]",
",",
"[",
"]",
"idx_to_obj",
"=",
"[",
"'__image__'",
"]",
"+",
"vocab",
"[",
"'my_idx_to_obj'",
"]",
"for",
"i",
"in",
"range",
"(",
"objs",
".",
"size",
"(",
"0",
")",
")",
":",
"objs_list",
".",
"append",
"(",
"idx_to_obj",
"[",
"objs",
"[",
"i",
"]",
".",
"item",
"(",
")",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"triples",
".",
"size",
"(",
"0",
")",
")",
":",
"s",
"=",
"triples",
"[",
"i",
",",
"0",
"]",
".",
"item",
"(",
")",
"p",
"=",
"vocab",
"[",
"'pred_idx_to_name'",
"]",
"[",
"triples",
"[",
"i",
",",
"1",
"]",
".",
"item",
"(",
")",
"]",
"o",
"=",
"triples",
"[",
"i",
",",
"2",
"]",
".",
"item",
"(",
")",
"triples_list",
".",
"append",
"(",
"[",
"s",
",",
"p",
",",
"o",
"]",
")",
"objs",
",",
"triples",
"=",
"objs_list",
",",
"triples_list",
"# General setup, and style for object nodes",
"lines",
"=",
"[",
"'digraph{'",
",",
"'graph [size=\"5,3\",ratio=\"compress\",dpi=\"300\",bgcolor=\"transparent\"]'",
",",
"'rankdir=%s'",
"%",
"rankdir",
",",
"'nodesep=\"0.5\"'",
",",
"'ranksep=\"0.5\"'",
",",
"'node [shape=\"box\",style=\"rounded,filled\",fontsize=\"48\",color=\"none\"]'",
",",
"'node [fillcolor=\"lightpink1\"]'",
",",
"]",
"# Output nodes for objects",
"for",
"i",
",",
"obj",
"in",
"enumerate",
"(",
"objs",
")",
":",
"if",
"ignore_dummies",
"and",
"obj",
"==",
"'__image__'",
":",
"continue",
"lines",
".",
"append",
"(",
"'%d [label=\"%s\"]'",
"%",
"(",
"i",
",",
"obj",
")",
")",
"# Output relationships",
"next_node_id",
"=",
"len",
"(",
"objs",
")",
"lines",
".",
"append",
"(",
"'node [fillcolor=\"lightblue1\"]'",
")",
"for",
"s",
",",
"p",
",",
"o",
"in",
"triples",
":",
"if",
"ignore_dummies",
"and",
"p",
"==",
"'__in_image__'",
":",
"continue",
"lines",
"+=",
"[",
"'%d [label=\"%s\"]'",
"%",
"(",
"next_node_id",
",",
"p",
")",
",",
"'%d->%d [penwidth=%f,arrowsize=%f,weight=%f]'",
"%",
"(",
"s",
",",
"next_node_id",
",",
"edge_width",
",",
"arrow_size",
",",
"binary_edge_weight",
")",
",",
"'%d->%d [penwidth=%f,arrowsize=%f,weight=%f]'",
"%",
"(",
"next_node_id",
",",
"o",
",",
"edge_width",
",",
"arrow_size",
",",
"binary_edge_weight",
")",
"]",
"next_node_id",
"+=",
"1",
"lines",
".",
"append",
"(",
"'}'",
")",
"# Now it gets slightly hacky. Write the graphviz spec to a temporary",
"# text file",
"ff",
",",
"dot_filename",
"=",
"tempfile",
".",
"mkstemp",
"(",
")",
"with",
"open",
"(",
"dot_filename",
",",
"'w'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"lines",
":",
"f",
".",
"write",
"(",
"'%s\\n'",
"%",
"line",
")",
"os",
".",
"close",
"(",
"ff",
")",
"# Shell out to invoke graphviz; this will save the resulting image to disk,",
"# so we read it, delete it, then return it.",
"output_format",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"output_filename",
")",
"[",
"1",
"]",
"[",
"1",
":",
"]",
"os",
".",
"system",
"(",
"'dot -T%s %s > %s'",
"%",
"(",
"output_format",
",",
"dot_filename",
",",
"output_filename",
")",
")",
"os",
".",
"remove",
"(",
"dot_filename",
")",
"img",
"=",
"imread",
"(",
"output_filename",
")",
"os",
".",
"remove",
"(",
"output_filename",
")",
"return",
"img"
] |
https://github.com/ashual/scene_generation/blob/6f6fe6afffae58da94c0c061e4dcaf273cdb9f44/scene_generation/vis.py#L134-L217
|
|
zhl2008/awd-platform
|
0416b31abea29743387b10b3914581fbe8e7da5e
|
web_flaskbb/Python-2.7.9/Lib/posixpath.py
|
python
|
normpath
|
(path)
|
return path or dot
|
Normalize path, eliminating double slashes, etc.
|
Normalize path, eliminating double slashes, etc.
|
[
"Normalize",
"path",
"eliminating",
"double",
"slashes",
"etc",
"."
] |
def normpath(path):
"""Normalize path, eliminating double slashes, etc."""
# Preserve unicode (if path is unicode)
slash, dot = (u'/', u'.') if isinstance(path, _unicode) else ('/', '.')
if path == '':
return dot
initial_slashes = path.startswith('/')
# POSIX allows one or two initial slashes, but treats three or more
# as single slash.
if (initial_slashes and
path.startswith('//') and not path.startswith('///')):
initial_slashes = 2
comps = path.split('/')
new_comps = []
for comp in comps:
if comp in ('', '.'):
continue
if (comp != '..' or (not initial_slashes and not new_comps) or
(new_comps and new_comps[-1] == '..')):
new_comps.append(comp)
elif new_comps:
new_comps.pop()
comps = new_comps
path = slash.join(comps)
if initial_slashes:
path = slash*initial_slashes + path
return path or dot
|
[
"def",
"normpath",
"(",
"path",
")",
":",
"# Preserve unicode (if path is unicode)",
"slash",
",",
"dot",
"=",
"(",
"u'/'",
",",
"u'.'",
")",
"if",
"isinstance",
"(",
"path",
",",
"_unicode",
")",
"else",
"(",
"'/'",
",",
"'.'",
")",
"if",
"path",
"==",
"''",
":",
"return",
"dot",
"initial_slashes",
"=",
"path",
".",
"startswith",
"(",
"'/'",
")",
"# POSIX allows one or two initial slashes, but treats three or more",
"# as single slash.",
"if",
"(",
"initial_slashes",
"and",
"path",
".",
"startswith",
"(",
"'//'",
")",
"and",
"not",
"path",
".",
"startswith",
"(",
"'///'",
")",
")",
":",
"initial_slashes",
"=",
"2",
"comps",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
"new_comps",
"=",
"[",
"]",
"for",
"comp",
"in",
"comps",
":",
"if",
"comp",
"in",
"(",
"''",
",",
"'.'",
")",
":",
"continue",
"if",
"(",
"comp",
"!=",
"'..'",
"or",
"(",
"not",
"initial_slashes",
"and",
"not",
"new_comps",
")",
"or",
"(",
"new_comps",
"and",
"new_comps",
"[",
"-",
"1",
"]",
"==",
"'..'",
")",
")",
":",
"new_comps",
".",
"append",
"(",
"comp",
")",
"elif",
"new_comps",
":",
"new_comps",
".",
"pop",
"(",
")",
"comps",
"=",
"new_comps",
"path",
"=",
"slash",
".",
"join",
"(",
"comps",
")",
"if",
"initial_slashes",
":",
"path",
"=",
"slash",
"*",
"initial_slashes",
"+",
"path",
"return",
"path",
"or",
"dot"
] |
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/posixpath.py#L336-L362
|
|
cbanack/comic-vine-scraper
|
8a7071796c61a9483079ad0e9ade56fcb7596bcd
|
src/py/utils/imagehash.py
|
python
|
hash
|
(image)
|
return __perceptual_hash(image)
|
Returns an image hash for the given .NET Image. The hash values for two
images can be compared by calling:
similarity(hash(image1), hash2(image2)).
The given images are not modified in any way, nor are they Disposed.
|
Returns an image hash for the given .NET Image. The hash values for two
images can be compared by calling:
similarity(hash(image1), hash2(image2)).
The given images are not modified in any way, nor are they Disposed.
|
[
"Returns",
"an",
"image",
"hash",
"for",
"the",
"given",
".",
"NET",
"Image",
".",
"The",
"hash",
"values",
"for",
"two",
"images",
"can",
"be",
"compared",
"by",
"calling",
":",
"similarity",
"(",
"hash",
"(",
"image1",
")",
"hash2",
"(",
"image2",
"))",
".",
"The",
"given",
"images",
"are",
"not",
"modified",
"in",
"any",
"way",
"nor",
"are",
"they",
"Disposed",
"."
] |
def hash(image):
'''
Returns an image hash for the given .NET Image. The hash values for two
images can be compared by calling:
similarity(hash(image1), hash2(image2)).
The given images are not modified in any way, nor are they Disposed.
'''
return __perceptual_hash(image)
|
[
"def",
"hash",
"(",
"image",
")",
":",
"return",
"__perceptual_hash",
"(",
"image",
")"
] |
https://github.com/cbanack/comic-vine-scraper/blob/8a7071796c61a9483079ad0e9ade56fcb7596bcd/src/py/utils/imagehash.py#L20-L29
|
|
w3h/isf
|
6faf0a3df185465ec17369c90ccc16e2a03a1870
|
lib/thirdparty/Crypto/Cipher/PKCS1_v1_5.py
|
python
|
new
|
(key)
|
return PKCS115_Cipher(key)
|
Return a cipher object `PKCS115_Cipher` that can be used to perform PKCS#1 v1.5 encryption or decryption.
:Parameters:
key : RSA key object
The key to use to encrypt or decrypt the message. This is a `Crypto.PublicKey.RSA` object.
Decryption is only possible if *key* is a private RSA key.
|
Return a cipher object `PKCS115_Cipher` that can be used to perform PKCS#1 v1.5 encryption or decryption.
|
[
"Return",
"a",
"cipher",
"object",
"PKCS115_Cipher",
"that",
"can",
"be",
"used",
"to",
"perform",
"PKCS#1",
"v1",
".",
"5",
"encryption",
"or",
"decryption",
"."
] |
def new(key):
"""Return a cipher object `PKCS115_Cipher` that can be used to perform PKCS#1 v1.5 encryption or decryption.
:Parameters:
key : RSA key object
The key to use to encrypt or decrypt the message. This is a `Crypto.PublicKey.RSA` object.
Decryption is only possible if *key* is a private RSA key.
"""
return PKCS115_Cipher(key)
|
[
"def",
"new",
"(",
"key",
")",
":",
"return",
"PKCS115_Cipher",
"(",
"key",
")"
] |
https://github.com/w3h/isf/blob/6faf0a3df185465ec17369c90ccc16e2a03a1870/lib/thirdparty/Crypto/Cipher/PKCS1_v1_5.py#L216-L225
|
|
XiaoMi/minos
|
164454a0804fb7eb7e14052327bdd4d5572c2697
|
build/virtual_bootstrap/virtual_bootstrap.py
|
python
|
Logger.stdout_level_matches
|
(self, level)
|
return self.level_matches(level, self._stdout_level())
|
Returns true if a message at this level will go to stdout
|
Returns true if a message at this level will go to stdout
|
[
"Returns",
"true",
"if",
"a",
"message",
"at",
"this",
"level",
"will",
"go",
"to",
"stdout"
] |
def stdout_level_matches(self, level):
"""Returns true if a message at this level will go to stdout"""
return self.level_matches(level, self._stdout_level())
|
[
"def",
"stdout_level_matches",
"(",
"self",
",",
"level",
")",
":",
"return",
"self",
".",
"level_matches",
"(",
"level",
",",
"self",
".",
"_stdout_level",
"(",
")",
")"
] |
https://github.com/XiaoMi/minos/blob/164454a0804fb7eb7e14052327bdd4d5572c2697/build/virtual_bootstrap/virtual_bootstrap.py#L392-L394
|
|
j4mie/sqlsite
|
f2dadb8db5ed7880f8872b6591d8cb1487f777ea
|
sqlsite/routing.py
|
python
|
search_path
|
(pattern, path)
|
return re.search(regex, path)
|
Given a pattern (ie the contents of the pattern column in the route table) and the
path of an incoming request (without the leading slash), convert the
pattern to a regex and return a match object captured from the path
|
Given a pattern (ie the contents of the pattern column in the route table) and the
path of an incoming request (without the leading slash), convert the
pattern to a regex and return a match object captured from the path
|
[
"Given",
"a",
"pattern",
"(",
"ie",
"the",
"contents",
"of",
"the",
"pattern",
"column",
"in",
"the",
"route",
"table",
")",
"and",
"the",
"path",
"of",
"an",
"incoming",
"request",
"(",
"without",
"the",
"leading",
"slash",
")",
"convert",
"the",
"pattern",
"to",
"a",
"regex",
"and",
"return",
"a",
"match",
"object",
"captured",
"from",
"the",
"path"
] |
def search_path(pattern, path):
"""
Given a pattern (ie the contents of the pattern column in the route table) and the
path of an incoming request (without the leading slash), convert the
pattern to a regex and return a match object captured from the path
"""
regex = pattern_to_regex(pattern)
if regex.endswith("/$"):
regex = regex[:-2] + "/?$"
return re.search(regex, path)
|
[
"def",
"search_path",
"(",
"pattern",
",",
"path",
")",
":",
"regex",
"=",
"pattern_to_regex",
"(",
"pattern",
")",
"if",
"regex",
".",
"endswith",
"(",
"\"/$\"",
")",
":",
"regex",
"=",
"regex",
"[",
":",
"-",
"2",
"]",
"+",
"\"/?$\"",
"return",
"re",
".",
"search",
"(",
"regex",
",",
"path",
")"
] |
https://github.com/j4mie/sqlsite/blob/f2dadb8db5ed7880f8872b6591d8cb1487f777ea/sqlsite/routing.py#L52-L61
|
|
stoq/stoq
|
c26991644d1affcf96bc2e0a0434796cabdf8448
|
stoq/lib/gui/actions/base.py
|
python
|
BaseActions.set_action_enabled
|
(self, action, sensitive)
|
Enables or disables an action
:param action: the action name
:param sensitive: If the action is enabled or disabled
|
Enables or disables an action
|
[
"Enables",
"or",
"disables",
"an",
"action"
] |
def set_action_enabled(self, action, sensitive):
"""Enables or disables an action
:param action: the action name
:param sensitive: If the action is enabled or disabled
"""
action = self._actions[action]
action.set_enabled(bool(sensitive))
|
[
"def",
"set_action_enabled",
"(",
"self",
",",
"action",
",",
"sensitive",
")",
":",
"action",
"=",
"self",
".",
"_actions",
"[",
"action",
"]",
"action",
".",
"set_enabled",
"(",
"bool",
"(",
"sensitive",
")",
")"
] |
https://github.com/stoq/stoq/blob/c26991644d1affcf96bc2e0a0434796cabdf8448/stoq/lib/gui/actions/base.py#L126-L133
|
||
Diamondfan/CTC_pytorch
|
eddd2550224dfe5ac28b6c4d20df5dde7eaf6119
|
my_863_corpus/steps/utils.py
|
python
|
process_map_file
|
(map_file)
|
return char_map, int2phone
|
Input:
map_file : string label和数字的对应关系文件
Output:
char_map : dict 对应关系字典
int2phone : dict 数字到label的对应关系
|
Input:
map_file : string label和数字的对应关系文件
Output:
char_map : dict 对应关系字典
int2phone : dict 数字到label的对应关系
|
[
"Input",
":",
"map_file",
":",
"string",
"label和数字的对应关系文件",
"Output",
":",
"char_map",
":",
"dict",
"对应关系字典",
"int2phone",
":",
"dict",
"数字到label的对应关系"
] |
def process_map_file(map_file):
'''
Input:
map_file : string label和数字的对应关系文件
Output:
char_map : dict 对应关系字典
int2phone : dict 数字到label的对应关系
'''
char_map = dict()
int2phone = dict()
f = open(map_file, 'r')
for line in f.readlines():
char, num = line.strip().split(' ')
char_map[char] = int(num)
int2phone[int(num)] = char
f.close()
int2phone[0] = '#'
return char_map, int2phone
|
[
"def",
"process_map_file",
"(",
"map_file",
")",
":",
"char_map",
"=",
"dict",
"(",
")",
"int2phone",
"=",
"dict",
"(",
")",
"f",
"=",
"open",
"(",
"map_file",
",",
"'r'",
")",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
":",
"char",
",",
"num",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"' '",
")",
"char_map",
"[",
"char",
"]",
"=",
"int",
"(",
"num",
")",
"int2phone",
"[",
"int",
"(",
"num",
")",
"]",
"=",
"char",
"f",
".",
"close",
"(",
")",
"int2phone",
"[",
"0",
"]",
"=",
"'#'",
"return",
"char_map",
",",
"int2phone"
] |
https://github.com/Diamondfan/CTC_pytorch/blob/eddd2550224dfe5ac28b6c4d20df5dde7eaf6119/my_863_corpus/steps/utils.py#L130-L147
|
|
JaniceWuo/MovieRecommend
|
4c86db64ca45598917d304f535413df3bc9fea65
|
movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/pkg_resources/__init__.py
|
python
|
Requirement.__eq__
|
(self, other)
|
return (
isinstance(other, Requirement) and
self.hashCmp == other.hashCmp
)
|
[] |
def __eq__(self, other):
return (
isinstance(other, Requirement) and
self.hashCmp == other.hashCmp
)
|
[
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"return",
"(",
"isinstance",
"(",
"other",
",",
"Requirement",
")",
"and",
"self",
".",
"hashCmp",
"==",
"other",
".",
"hashCmp",
")"
] |
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/pkg_resources/__init__.py#L2891-L2895
|
|||
zhl2008/awd-platform
|
0416b31abea29743387b10b3914581fbe8e7da5e
|
web_hxb2/lib/python3.5/site-packages/pkg_resources/__init__.py
|
python
|
Environment.__getitem__
|
(self, project_name)
|
return self._distmap.get(distribution_key, [])
|
Return a newest-to-oldest list of distributions for `project_name`
Uses case-insensitive `project_name` comparison, assuming all the
project's distributions use their project's name converted to all
lowercase as their key.
|
Return a newest-to-oldest list of distributions for `project_name`
|
[
"Return",
"a",
"newest",
"-",
"to",
"-",
"oldest",
"list",
"of",
"distributions",
"for",
"project_name"
] |
def __getitem__(self, project_name):
"""Return a newest-to-oldest list of distributions for `project_name`
Uses case-insensitive `project_name` comparison, assuming all the
project's distributions use their project's name converted to all
lowercase as their key.
"""
distribution_key = project_name.lower()
return self._distmap.get(distribution_key, [])
|
[
"def",
"__getitem__",
"(",
"self",
",",
"project_name",
")",
":",
"distribution_key",
"=",
"project_name",
".",
"lower",
"(",
")",
"return",
"self",
".",
"_distmap",
".",
"get",
"(",
"distribution_key",
",",
"[",
"]",
")"
] |
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/pkg_resources/__init__.py#L1100-L1109
|
|
wistbean/fxxkpython
|
88e16d79d8dd37236ba6ecd0d0ff11d63143968c
|
vip/qyxuan/projects/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/ipaddress.py
|
python
|
_BaseNetwork.is_loopback
|
(self)
|
return (self.network_address.is_loopback and
self.broadcast_address.is_loopback)
|
Test if the address is a loopback address.
Returns:
A boolean, True if the address is a loopback address as defined in
RFC 2373 2.5.3.
|
Test if the address is a loopback address.
|
[
"Test",
"if",
"the",
"address",
"is",
"a",
"loopback",
"address",
"."
] |
def is_loopback(self):
"""Test if the address is a loopback address.
Returns:
A boolean, True if the address is a loopback address as defined in
RFC 2373 2.5.3.
"""
return (self.network_address.is_loopback and
self.broadcast_address.is_loopback)
|
[
"def",
"is_loopback",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"network_address",
".",
"is_loopback",
"and",
"self",
".",
"broadcast_address",
".",
"is_loopback",
")"
] |
https://github.com/wistbean/fxxkpython/blob/88e16d79d8dd37236ba6ecd0d0ff11d63143968c/vip/qyxuan/projects/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/ipaddress.py#L1180-L1189
|
|
sagemath/sage
|
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
|
src/sage/interfaces/octave.py
|
python
|
Octave.__init__
|
(self, maxread=None, script_subdirectory=None, logfile=None,
server=None, server_tmpdir=None, seed=None, command=None)
|
EXAMPLES::
sage: octave == loads(dumps(octave))
True
|
EXAMPLES::
|
[
"EXAMPLES",
"::"
] |
def __init__(self, maxread=None, script_subdirectory=None, logfile=None,
server=None, server_tmpdir=None, seed=None, command=None):
"""
EXAMPLES::
sage: octave == loads(dumps(octave))
True
"""
if command is None:
command = os.getenv('SAGE_OCTAVE_COMMAND') or 'octave-cli'
if server is None:
server = os.getenv('SAGE_OCTAVE_SERVER') or None
Expect.__init__(self,
name = 'octave',
# We want the prompt sequence to be unique to avoid confusion with syntax error messages containing >>>
prompt = r'octave\:\d+> ',
# We don't want any pagination of output
command = command + " --no-line-editing --silent --eval 'PS2(PS1());more off' --persist",
maxread = maxread,
server = server,
server_tmpdir = server_tmpdir,
script_subdirectory = script_subdirectory,
restart_on_ctrlc = False,
verbose_start = False,
logfile = logfile,
eval_using_file_cutoff=100)
self._seed = seed
|
[
"def",
"__init__",
"(",
"self",
",",
"maxread",
"=",
"None",
",",
"script_subdirectory",
"=",
"None",
",",
"logfile",
"=",
"None",
",",
"server",
"=",
"None",
",",
"server_tmpdir",
"=",
"None",
",",
"seed",
"=",
"None",
",",
"command",
"=",
"None",
")",
":",
"if",
"command",
"is",
"None",
":",
"command",
"=",
"os",
".",
"getenv",
"(",
"'SAGE_OCTAVE_COMMAND'",
")",
"or",
"'octave-cli'",
"if",
"server",
"is",
"None",
":",
"server",
"=",
"os",
".",
"getenv",
"(",
"'SAGE_OCTAVE_SERVER'",
")",
"or",
"None",
"Expect",
".",
"__init__",
"(",
"self",
",",
"name",
"=",
"'octave'",
",",
"# We want the prompt sequence to be unique to avoid confusion with syntax error messages containing >>>",
"prompt",
"=",
"r'octave\\:\\d+> '",
",",
"# We don't want any pagination of output",
"command",
"=",
"command",
"+",
"\" --no-line-editing --silent --eval 'PS2(PS1());more off' --persist\"",
",",
"maxread",
"=",
"maxread",
",",
"server",
"=",
"server",
",",
"server_tmpdir",
"=",
"server_tmpdir",
",",
"script_subdirectory",
"=",
"script_subdirectory",
",",
"restart_on_ctrlc",
"=",
"False",
",",
"verbose_start",
"=",
"False",
",",
"logfile",
"=",
"logfile",
",",
"eval_using_file_cutoff",
"=",
"100",
")",
"self",
".",
"_seed",
"=",
"seed"
] |
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/interfaces/octave.py#L177-L203
|
||
dpressel/mead-baseline
|
9987e6b37fa6525a4ddc187c305e292a718f59a9
|
layers/eight_mile/pytorch/layers.py
|
python
|
MeanPool1D.__init__
|
(self, outsz, batch_first=True)
|
Set up pooling module
:param outsz: The output dim, for dowstream access
:param batch_first: Is this module batch first or time first?
|
Set up pooling module
|
[
"Set",
"up",
"pooling",
"module"
] |
def __init__(self, outsz, batch_first=True):
"""Set up pooling module
:param outsz: The output dim, for dowstream access
:param batch_first: Is this module batch first or time first?
"""
super().__init__()
self.batch_first = batch_first
self.reduction_dim = 1 if self.batch_first else 0
self.output_dim = outsz
self.requires_length = True
|
[
"def",
"__init__",
"(",
"self",
",",
"outsz",
",",
"batch_first",
"=",
"True",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"batch_first",
"=",
"batch_first",
"self",
".",
"reduction_dim",
"=",
"1",
"if",
"self",
".",
"batch_first",
"else",
"0",
"self",
".",
"output_dim",
"=",
"outsz",
"self",
".",
"requires_length",
"=",
"True"
] |
https://github.com/dpressel/mead-baseline/blob/9987e6b37fa6525a4ddc187c305e292a718f59a9/layers/eight_mile/pytorch/layers.py#L241-L251
|
||
inventree/InvenTree
|
4a5e4a88ac3e91d64a21e8cab3708ecbc6e2bd8b
|
InvenTree/plugin/registry.py
|
python
|
PluginsRegistry._activate_plugins
|
(self, force_reload=False)
|
Run integration functions for all plugins
:param force_reload: force reload base apps, defaults to False
:type force_reload: bool, optional
|
Run integration functions for all plugins
|
[
"Run",
"integration",
"functions",
"for",
"all",
"plugins"
] |
def _activate_plugins(self, force_reload=False):
"""
Run integration functions for all plugins
:param force_reload: force reload base apps, defaults to False
:type force_reload: bool, optional
"""
# activate integrations
plugins = self.plugins.items()
logger.info(f'Found {len(plugins)} active plugins')
self.activate_integration_settings(plugins)
self.activate_integration_schedule(plugins)
self.activate_integration_app(plugins, force_reload=force_reload)
|
[
"def",
"_activate_plugins",
"(",
"self",
",",
"force_reload",
"=",
"False",
")",
":",
"# activate integrations",
"plugins",
"=",
"self",
".",
"plugins",
".",
"items",
"(",
")",
"logger",
".",
"info",
"(",
"f'Found {len(plugins)} active plugins'",
")",
"self",
".",
"activate_integration_settings",
"(",
"plugins",
")",
"self",
".",
"activate_integration_schedule",
"(",
"plugins",
")",
"self",
".",
"activate_integration_app",
"(",
"plugins",
",",
"force_reload",
"=",
"force_reload",
")"
] |
https://github.com/inventree/InvenTree/blob/4a5e4a88ac3e91d64a21e8cab3708ecbc6e2bd8b/InvenTree/plugin/registry.py#L256-L269
|
||
google-research/seed_rl
|
66e8890261f09d0355e8bf5f1c5e41968ca9f02b
|
agents/r2d2/learner.py
|
python
|
n_step_bellman_target
|
(rewards, done, q_target, gamma, n_steps)
|
return bellman_target
|
r"""Computes n-step Bellman targets.
See section 2.3 of R2D2 paper (which does not mention the logic around end of
episode).
Args:
rewards: <float32>[time, batch_size] tensor. This is r_t in the equations
below.
done: <bool>[time, batch_size] tensor. This is done_t in the equations
below. done_t should be true if the episode is done just after
experimenting reward r_t.
q_target: <float32>[time, batch_size] tensor. This is Q_target(s_{t+1}, a*)
(where a* is an action chosen by the caller).
gamma: Exponential RL discounting.
n_steps: The number of steps to look ahead for computing the Bellman
targets.
Returns:
y_t targets as <float32>[time, batch_size] tensor.
When n_steps=1, this is just:
$$r_t + gamma * (1 - done_t) * Q_{target}(s_{t+1}, a^*)$$
In the general case, this is:
$$(\sum_{i=0}^{n-1} \gamma ^ {i} * notdone_{t, i-1} * r_{t + i}) +
\gamma ^ n * notdone_{t, n-1} * Q_{target}(s_{t + n}, a^*) $$
where notdone_{t,i} is defined as:
$$notdone_{t,i} = \prod_{k=0}^{k=i}(1 - done_{t+k})$$
The last n_step-1 targets cannot be computed with n_step returns, since we
run out of Q_{target}(s_{t+n}). Instead, they will use n_steps-1, .., 1 step
returns. For those last targets, the last Q_{target}(s_{t}, a^*) is re-used
multiple times.
|
r"""Computes n-step Bellman targets.
|
[
"r",
"Computes",
"n",
"-",
"step",
"Bellman",
"targets",
"."
] |
def n_step_bellman_target(rewards, done, q_target, gamma, n_steps):
r"""Computes n-step Bellman targets.
See section 2.3 of R2D2 paper (which does not mention the logic around end of
episode).
Args:
rewards: <float32>[time, batch_size] tensor. This is r_t in the equations
below.
done: <bool>[time, batch_size] tensor. This is done_t in the equations
below. done_t should be true if the episode is done just after
experimenting reward r_t.
q_target: <float32>[time, batch_size] tensor. This is Q_target(s_{t+1}, a*)
(where a* is an action chosen by the caller).
gamma: Exponential RL discounting.
n_steps: The number of steps to look ahead for computing the Bellman
targets.
Returns:
y_t targets as <float32>[time, batch_size] tensor.
When n_steps=1, this is just:
$$r_t + gamma * (1 - done_t) * Q_{target}(s_{t+1}, a^*)$$
In the general case, this is:
$$(\sum_{i=0}^{n-1} \gamma ^ {i} * notdone_{t, i-1} * r_{t + i}) +
\gamma ^ n * notdone_{t, n-1} * Q_{target}(s_{t + n}, a^*) $$
where notdone_{t,i} is defined as:
$$notdone_{t,i} = \prod_{k=0}^{k=i}(1 - done_{t+k})$$
The last n_step-1 targets cannot be computed with n_step returns, since we
run out of Q_{target}(s_{t+n}). Instead, they will use n_steps-1, .., 1 step
returns. For those last targets, the last Q_{target}(s_{t}, a^*) is re-used
multiple times.
"""
# We append n_steps - 1 times the last q_target. They are divided by gamma **
# k to correct for the fact that they are at a 'fake' indice, and will
# therefore end up being multiplied back by gamma ** k in the loop below.
# We prepend 0s that will be discarded at the first iteration below.
bellman_target = tf.concat(
[tf.zeros_like(q_target[0:1]), q_target] +
[q_target[-1:] / gamma ** k
for k in range(1, n_steps)],
axis=0)
# Pad with n_steps 0s. They will be used to compute the last n_steps-1
# targets (having 0 values is important).
done = tf.concat([done] + [tf.zeros_like(done[0:1])] * n_steps, axis=0)
rewards = tf.concat([rewards] + [tf.zeros_like(rewards[0:1])] * n_steps,
axis=0)
# Iteratively build the n_steps targets. After the i-th iteration (1-based),
# bellman_target is effectively the i-step returns.
for _ in range(n_steps):
rewards = rewards[:-1]
done = done[:-1]
bellman_target = (
rewards + gamma * (1. - tf.cast(done, tf.float32)) * bellman_target[1:])
return bellman_target
|
[
"def",
"n_step_bellman_target",
"(",
"rewards",
",",
"done",
",",
"q_target",
",",
"gamma",
",",
"n_steps",
")",
":",
"# We append n_steps - 1 times the last q_target. They are divided by gamma **",
"# k to correct for the fact that they are at a 'fake' indice, and will",
"# therefore end up being multiplied back by gamma ** k in the loop below.",
"# We prepend 0s that will be discarded at the first iteration below.",
"bellman_target",
"=",
"tf",
".",
"concat",
"(",
"[",
"tf",
".",
"zeros_like",
"(",
"q_target",
"[",
"0",
":",
"1",
"]",
")",
",",
"q_target",
"]",
"+",
"[",
"q_target",
"[",
"-",
"1",
":",
"]",
"/",
"gamma",
"**",
"k",
"for",
"k",
"in",
"range",
"(",
"1",
",",
"n_steps",
")",
"]",
",",
"axis",
"=",
"0",
")",
"# Pad with n_steps 0s. They will be used to compute the last n_steps-1",
"# targets (having 0 values is important).",
"done",
"=",
"tf",
".",
"concat",
"(",
"[",
"done",
"]",
"+",
"[",
"tf",
".",
"zeros_like",
"(",
"done",
"[",
"0",
":",
"1",
"]",
")",
"]",
"*",
"n_steps",
",",
"axis",
"=",
"0",
")",
"rewards",
"=",
"tf",
".",
"concat",
"(",
"[",
"rewards",
"]",
"+",
"[",
"tf",
".",
"zeros_like",
"(",
"rewards",
"[",
"0",
":",
"1",
"]",
")",
"]",
"*",
"n_steps",
",",
"axis",
"=",
"0",
")",
"# Iteratively build the n_steps targets. After the i-th iteration (1-based),",
"# bellman_target is effectively the i-step returns.",
"for",
"_",
"in",
"range",
"(",
"n_steps",
")",
":",
"rewards",
"=",
"rewards",
"[",
":",
"-",
"1",
"]",
"done",
"=",
"done",
"[",
":",
"-",
"1",
"]",
"bellman_target",
"=",
"(",
"rewards",
"+",
"gamma",
"*",
"(",
"1.",
"-",
"tf",
".",
"cast",
"(",
"done",
",",
"tf",
".",
"float32",
")",
")",
"*",
"bellman_target",
"[",
"1",
":",
"]",
")",
"return",
"bellman_target"
] |
https://github.com/google-research/seed_rl/blob/66e8890261f09d0355e8bf5f1c5e41968ca9f02b/agents/r2d2/learner.py#L195-L255
|
|
termius/termius-cli
|
2664d0c70d3d682ad931b885b4965447b156c280
|
termius/cloud/client/cryptor.py
|
python
|
RNCryptor.encrypt
|
(self, data)
|
return self.post_encrypt_data(encrypted_data)
|
Encrypt data.
|
Encrypt data.
|
[
"Encrypt",
"data",
"."
] |
def encrypt(self, data):
"""Encrypt data."""
data = self.pre_encrypt_data(data)
encryption_salt = self.encryption_salt
hmac_salt = self.hmac_salt
hmac_key = self.hmac_key
initialization_vector = self.initialization_vector
cipher_text = self._aes_encrypt(initialization_vector, data)
version = b'\x03'
options = b'\x01'
new_data = b''.join([
version, options,
encryption_salt, hmac_salt,
initialization_vector, cipher_text
])
encrypted_data = new_data + self._hmac(hmac_key, new_data)
return self.post_encrypt_data(encrypted_data)
|
[
"def",
"encrypt",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"self",
".",
"pre_encrypt_data",
"(",
"data",
")",
"encryption_salt",
"=",
"self",
".",
"encryption_salt",
"hmac_salt",
"=",
"self",
".",
"hmac_salt",
"hmac_key",
"=",
"self",
".",
"hmac_key",
"initialization_vector",
"=",
"self",
".",
"initialization_vector",
"cipher_text",
"=",
"self",
".",
"_aes_encrypt",
"(",
"initialization_vector",
",",
"data",
")",
"version",
"=",
"b'\\x03'",
"options",
"=",
"b'\\x01'",
"new_data",
"=",
"b''",
".",
"join",
"(",
"[",
"version",
",",
"options",
",",
"encryption_salt",
",",
"hmac_salt",
",",
"initialization_vector",
",",
"cipher_text",
"]",
")",
"encrypted_data",
"=",
"new_data",
"+",
"self",
".",
"_hmac",
"(",
"hmac_key",
",",
"new_data",
")",
"return",
"self",
".",
"post_encrypt_data",
"(",
"encrypted_data",
")"
] |
https://github.com/termius/termius-cli/blob/2664d0c70d3d682ad931b885b4965447b156c280/termius/cloud/client/cryptor.py#L165-L187
|
|
msracver/Deep-Feature-Flow
|
297293cbe728f817b62c82d3abfbd226300086ef
|
lib/utils/image_processing.py
|
python
|
transform_inverse
|
(im_tensor, pixel_means)
|
return im
|
transform from mxnet im_tensor to ordinary RGB image
im_tensor is limited to one image
:param im_tensor: [batch, channel, height, width]
:param pixel_means: [[[R, G, B pixel means]]]
:return: im [height, width, channel(RGB)]
|
transform from mxnet im_tensor to ordinary RGB image
im_tensor is limited to one image
:param im_tensor: [batch, channel, height, width]
:param pixel_means: [[[R, G, B pixel means]]]
:return: im [height, width, channel(RGB)]
|
[
"transform",
"from",
"mxnet",
"im_tensor",
"to",
"ordinary",
"RGB",
"image",
"im_tensor",
"is",
"limited",
"to",
"one",
"image",
":",
"param",
"im_tensor",
":",
"[",
"batch",
"channel",
"height",
"width",
"]",
":",
"param",
"pixel_means",
":",
"[[[",
"R",
"G",
"B",
"pixel",
"means",
"]]]",
":",
"return",
":",
"im",
"[",
"height",
"width",
"channel",
"(",
"RGB",
")",
"]"
] |
def transform_inverse(im_tensor, pixel_means):
"""
transform from mxnet im_tensor to ordinary RGB image
im_tensor is limited to one image
:param im_tensor: [batch, channel, height, width]
:param pixel_means: [[[R, G, B pixel means]]]
:return: im [height, width, channel(RGB)]
"""
assert im_tensor.shape[0] == 1
im_tensor = im_tensor.copy()
# put channel back
channel_swap = (0, 2, 3, 1)
im_tensor = im_tensor.transpose(channel_swap)
im = im_tensor[0]
assert im.shape[2] == 3
im += pixel_means
im = im.astype(np.uint8)
return im
|
[
"def",
"transform_inverse",
"(",
"im_tensor",
",",
"pixel_means",
")",
":",
"assert",
"im_tensor",
".",
"shape",
"[",
"0",
"]",
"==",
"1",
"im_tensor",
"=",
"im_tensor",
".",
"copy",
"(",
")",
"# put channel back",
"channel_swap",
"=",
"(",
"0",
",",
"2",
",",
"3",
",",
"1",
")",
"im_tensor",
"=",
"im_tensor",
".",
"transpose",
"(",
"channel_swap",
")",
"im",
"=",
"im_tensor",
"[",
"0",
"]",
"assert",
"im",
".",
"shape",
"[",
"2",
"]",
"==",
"3",
"im",
"+=",
"pixel_means",
"im",
"=",
"im",
".",
"astype",
"(",
"np",
".",
"uint8",
")",
"return",
"im"
] |
https://github.com/msracver/Deep-Feature-Flow/blob/297293cbe728f817b62c82d3abfbd226300086ef/lib/utils/image_processing.py#L52-L69
|
|
triaquae/triaquae
|
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
|
TriAquae/models/Ubuntu_12/paramiko/packet.py
|
python
|
Packetizer.set_inbound_cipher
|
(self, block_engine, block_size, mac_engine, mac_size, mac_key)
|
Switch inbound data cipher.
|
Switch inbound data cipher.
|
[
"Switch",
"inbound",
"data",
"cipher",
"."
] |
def set_inbound_cipher(self, block_engine, block_size, mac_engine, mac_size, mac_key):
"""
Switch inbound data cipher.
"""
self.__block_engine_in = block_engine
self.__block_size_in = block_size
self.__mac_engine_in = mac_engine
self.__mac_size_in = mac_size
self.__mac_key_in = mac_key
self.__received_bytes = 0
self.__received_packets = 0
self.__received_bytes_overflow = 0
self.__received_packets_overflow = 0
# wait until the reset happens in both directions before clearing rekey flag
self.__init_count |= 2
if self.__init_count == 3:
self.__init_count = 0
self.__need_rekey = False
|
[
"def",
"set_inbound_cipher",
"(",
"self",
",",
"block_engine",
",",
"block_size",
",",
"mac_engine",
",",
"mac_size",
",",
"mac_key",
")",
":",
"self",
".",
"__block_engine_in",
"=",
"block_engine",
"self",
".",
"__block_size_in",
"=",
"block_size",
"self",
".",
"__mac_engine_in",
"=",
"mac_engine",
"self",
".",
"__mac_size_in",
"=",
"mac_size",
"self",
".",
"__mac_key_in",
"=",
"mac_key",
"self",
".",
"__received_bytes",
"=",
"0",
"self",
".",
"__received_packets",
"=",
"0",
"self",
".",
"__received_bytes_overflow",
"=",
"0",
"self",
".",
"__received_packets_overflow",
"=",
"0",
"# wait until the reset happens in both directions before clearing rekey flag",
"self",
".",
"__init_count",
"|=",
"2",
"if",
"self",
".",
"__init_count",
"==",
"3",
":",
"self",
".",
"__init_count",
"=",
"0",
"self",
".",
"__need_rekey",
"=",
"False"
] |
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Ubuntu_12/paramiko/packet.py#L128-L145
|
||
log2timeline/plaso
|
fe2e316b8c76a0141760c0f2f181d84acb83abc2
|
plaso/cli/tool_options.py
|
python
|
OutputModuleOptions._ParseOutputOptions
|
(self, options)
|
Parses the output options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
|
Parses the output options.
|
[
"Parses",
"the",
"output",
"options",
"."
] |
def _ParseOutputOptions(self, options):
"""Parses the output options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
self._output_dynamic_time = getattr(options, 'dynamic_time', False)
time_zone_string = self.ParseStringOption(options, 'output_time_zone')
if isinstance(time_zone_string, str):
if time_zone_string.lower() == 'list':
self.list_time_zones = True
elif time_zone_string:
try:
pytz.timezone(time_zone_string)
except pytz.UnknownTimeZoneError:
raise errors.BadConfigOption(
'Unknown time zone: {0:s}'.format(time_zone_string))
self._output_time_zone = time_zone_string
|
[
"def",
"_ParseOutputOptions",
"(",
"self",
",",
"options",
")",
":",
"self",
".",
"_output_dynamic_time",
"=",
"getattr",
"(",
"options",
",",
"'dynamic_time'",
",",
"False",
")",
"time_zone_string",
"=",
"self",
".",
"ParseStringOption",
"(",
"options",
",",
"'output_time_zone'",
")",
"if",
"isinstance",
"(",
"time_zone_string",
",",
"str",
")",
":",
"if",
"time_zone_string",
".",
"lower",
"(",
")",
"==",
"'list'",
":",
"self",
".",
"list_time_zones",
"=",
"True",
"elif",
"time_zone_string",
":",
"try",
":",
"pytz",
".",
"timezone",
"(",
"time_zone_string",
")",
"except",
"pytz",
".",
"UnknownTimeZoneError",
":",
"raise",
"errors",
".",
"BadConfigOption",
"(",
"'Unknown time zone: {0:s}'",
".",
"format",
"(",
"time_zone_string",
")",
")",
"self",
".",
"_output_time_zone",
"=",
"time_zone_string"
] |
https://github.com/log2timeline/plaso/blob/fe2e316b8c76a0141760c0f2f181d84acb83abc2/plaso/cli/tool_options.py#L214-L237
|
||
Kjuly/iPokeMon-Server
|
b5e67c67ae248bd092c53fe9e3eee8bf2dba9e3f
|
bottle.py
|
python
|
Bottle.delete
|
(self, path=None, method='DELETE', **options)
|
return self.route(path, method, **options)
|
Equals :meth:`route` with a ``DELETE`` method parameter.
|
Equals :meth:`route` with a ``DELETE`` method parameter.
|
[
"Equals",
":",
"meth",
":",
"route",
"with",
"a",
"DELETE",
"method",
"parameter",
"."
] |
def delete(self, path=None, method='DELETE', **options):
""" Equals :meth:`route` with a ``DELETE`` method parameter. """
return self.route(path, method, **options)
|
[
"def",
"delete",
"(",
"self",
",",
"path",
"=",
"None",
",",
"method",
"=",
"'DELETE'",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"route",
"(",
"path",
",",
"method",
",",
"*",
"*",
"options",
")"
] |
https://github.com/Kjuly/iPokeMon-Server/blob/b5e67c67ae248bd092c53fe9e3eee8bf2dba9e3f/bottle.py#L716-L718
|
|
Komodo/KomodoEdit
|
61edab75dce2bdb03943b387b0608ea36f548e8e
|
src/codeintel/lib/codeintel2/lang_javascript.py
|
python
|
JavaScriptCiler._findInScope
|
(self, name, attrlist=("variables", ), scope=None)
|
return None
|
Find the object of the given name in the given scope
@param name {str} The name of the object to look for
@param attrlist {seq of str} The attributes to look into (e.g.,
"variables", "functions", "classes")
@param scope {JSObject} The scope in which to find the object
@returns {JSObject or None} The found object, an immediate child of the
scope.
|
Find the object of the given name in the given scope
|
[
"Find",
"the",
"object",
"of",
"the",
"given",
"name",
"in",
"the",
"given",
"scope"
] |
def _findInScope(self, name, attrlist=("variables", ), scope=None):
"""Find the object of the given name in the given scope
@param name {str} The name of the object to look for
@param attrlist {seq of str} The attributes to look into (e.g.,
"variables", "functions", "classes")
@param scope {JSObject} The scope in which to find the object
@returns {JSObject or None} The found object, an immediate child of the
scope.
"""
assert scope is not None, "Missing scope"
for attr in attrlist:
namesDict = getattr(scope, attr, None)
if namesDict:
subscope = namesDict.get(name)
if subscope:
log.debug("_findInScope: Found a scope for: %r in %s.%s:",
name, scope.name, attr)
return subscope
# Not found
return None
|
[
"def",
"_findInScope",
"(",
"self",
",",
"name",
",",
"attrlist",
"=",
"(",
"\"variables\"",
",",
")",
",",
"scope",
"=",
"None",
")",
":",
"assert",
"scope",
"is",
"not",
"None",
",",
"\"Missing scope\"",
"for",
"attr",
"in",
"attrlist",
":",
"namesDict",
"=",
"getattr",
"(",
"scope",
",",
"attr",
",",
"None",
")",
"if",
"namesDict",
":",
"subscope",
"=",
"namesDict",
".",
"get",
"(",
"name",
")",
"if",
"subscope",
":",
"log",
".",
"debug",
"(",
"\"_findInScope: Found a scope for: %r in %s.%s:\"",
",",
"name",
",",
"scope",
".",
"name",
",",
"attr",
")",
"return",
"subscope",
"# Not found",
"return",
"None"
] |
https://github.com/Komodo/KomodoEdit/blob/61edab75dce2bdb03943b387b0608ea36f548e8e/src/codeintel/lib/codeintel2/lang_javascript.py#L1968-L1987
|
|
huawei-noah/vega
|
d9f13deede7f2b584e4b1d32ffdb833856129989
|
vega/algorithms/nas/modnas/registry/__init__.py
|
python
|
parse_spec
|
(spec: SPEC_TYPE)
|
Return parsed id and arguments from build spec.
|
Return parsed id and arguments from build spec.
|
[
"Return",
"parsed",
"id",
"and",
"arguments",
"from",
"build",
"spec",
"."
] |
def parse_spec(spec: SPEC_TYPE) -> Any:
"""Return parsed id and arguments from build spec."""
if isinstance(spec, dict):
return spec['type'], spec.get('args', {})
if isinstance(spec, (tuple, list)) and isinstance(spec[0], str):
return spec[0], {} if len(spec) < 2 else spec[1]
if isinstance(spec, str):
return spec, {}
raise ValueError('Invalid build spec: {}'.format(spec))
|
[
"def",
"parse_spec",
"(",
"spec",
":",
"SPEC_TYPE",
")",
"->",
"Any",
":",
"if",
"isinstance",
"(",
"spec",
",",
"dict",
")",
":",
"return",
"spec",
"[",
"'type'",
"]",
",",
"spec",
".",
"get",
"(",
"'args'",
",",
"{",
"}",
")",
"if",
"isinstance",
"(",
"spec",
",",
"(",
"tuple",
",",
"list",
")",
")",
"and",
"isinstance",
"(",
"spec",
"[",
"0",
"]",
",",
"str",
")",
":",
"return",
"spec",
"[",
"0",
"]",
",",
"{",
"}",
"if",
"len",
"(",
"spec",
")",
"<",
"2",
"else",
"spec",
"[",
"1",
"]",
"if",
"isinstance",
"(",
"spec",
",",
"str",
")",
":",
"return",
"spec",
",",
"{",
"}",
"raise",
"ValueError",
"(",
"'Invalid build spec: {}'",
".",
"format",
"(",
"spec",
")",
")"
] |
https://github.com/huawei-noah/vega/blob/d9f13deede7f2b584e4b1d32ffdb833856129989/vega/algorithms/nas/modnas/registry/__init__.py#L45-L53
|
||
linxid/Machine_Learning_Study_Path
|
558e82d13237114bbb8152483977806fc0c222af
|
Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py
|
python
|
TarInfo.create_pax_header
|
(self, info, encoding)
|
return buf + self._create_header(info, USTAR_FORMAT, "ascii", "replace")
|
Return the object as a ustar header block. If it cannot be
represented this way, prepend a pax extended header sequence
with supplement information.
|
Return the object as a ustar header block. If it cannot be
represented this way, prepend a pax extended header sequence
with supplement information.
|
[
"Return",
"the",
"object",
"as",
"a",
"ustar",
"header",
"block",
".",
"If",
"it",
"cannot",
"be",
"represented",
"this",
"way",
"prepend",
"a",
"pax",
"extended",
"header",
"sequence",
"with",
"supplement",
"information",
"."
] |
def create_pax_header(self, info, encoding):
"""Return the object as a ustar header block. If it cannot be
represented this way, prepend a pax extended header sequence
with supplement information.
"""
info["magic"] = POSIX_MAGIC
pax_headers = self.pax_headers.copy()
# Test string fields for values that exceed the field length or cannot
# be represented in ASCII encoding.
for name, hname, length in (
("name", "path", LENGTH_NAME), ("linkname", "linkpath", LENGTH_LINK),
("uname", "uname", 32), ("gname", "gname", 32)):
if hname in pax_headers:
# The pax header has priority.
continue
# Try to encode the string as ASCII.
try:
info[name].encode("ascii", "strict")
except UnicodeEncodeError:
pax_headers[hname] = info[name]
continue
if len(info[name]) > length:
pax_headers[hname] = info[name]
# Test number fields for values that exceed the field limit or values
# that like to be stored as float.
for name, digits in (("uid", 8), ("gid", 8), ("size", 12), ("mtime", 12)):
if name in pax_headers:
# The pax header has priority. Avoid overflow.
info[name] = 0
continue
val = info[name]
if not 0 <= val < 8 ** (digits - 1) or isinstance(val, float):
pax_headers[name] = str(val)
info[name] = 0
# Create a pax extended header if necessary.
if pax_headers:
buf = self._create_pax_generic_header(pax_headers, XHDTYPE, encoding)
else:
buf = b""
return buf + self._create_header(info, USTAR_FORMAT, "ascii", "replace")
|
[
"def",
"create_pax_header",
"(",
"self",
",",
"info",
",",
"encoding",
")",
":",
"info",
"[",
"\"magic\"",
"]",
"=",
"POSIX_MAGIC",
"pax_headers",
"=",
"self",
".",
"pax_headers",
".",
"copy",
"(",
")",
"# Test string fields for values that exceed the field length or cannot",
"# be represented in ASCII encoding.",
"for",
"name",
",",
"hname",
",",
"length",
"in",
"(",
"(",
"\"name\"",
",",
"\"path\"",
",",
"LENGTH_NAME",
")",
",",
"(",
"\"linkname\"",
",",
"\"linkpath\"",
",",
"LENGTH_LINK",
")",
",",
"(",
"\"uname\"",
",",
"\"uname\"",
",",
"32",
")",
",",
"(",
"\"gname\"",
",",
"\"gname\"",
",",
"32",
")",
")",
":",
"if",
"hname",
"in",
"pax_headers",
":",
"# The pax header has priority.",
"continue",
"# Try to encode the string as ASCII.",
"try",
":",
"info",
"[",
"name",
"]",
".",
"encode",
"(",
"\"ascii\"",
",",
"\"strict\"",
")",
"except",
"UnicodeEncodeError",
":",
"pax_headers",
"[",
"hname",
"]",
"=",
"info",
"[",
"name",
"]",
"continue",
"if",
"len",
"(",
"info",
"[",
"name",
"]",
")",
">",
"length",
":",
"pax_headers",
"[",
"hname",
"]",
"=",
"info",
"[",
"name",
"]",
"# Test number fields for values that exceed the field limit or values",
"# that like to be stored as float.",
"for",
"name",
",",
"digits",
"in",
"(",
"(",
"\"uid\"",
",",
"8",
")",
",",
"(",
"\"gid\"",
",",
"8",
")",
",",
"(",
"\"size\"",
",",
"12",
")",
",",
"(",
"\"mtime\"",
",",
"12",
")",
")",
":",
"if",
"name",
"in",
"pax_headers",
":",
"# The pax header has priority. Avoid overflow.",
"info",
"[",
"name",
"]",
"=",
"0",
"continue",
"val",
"=",
"info",
"[",
"name",
"]",
"if",
"not",
"0",
"<=",
"val",
"<",
"8",
"**",
"(",
"digits",
"-",
"1",
")",
"or",
"isinstance",
"(",
"val",
",",
"float",
")",
":",
"pax_headers",
"[",
"name",
"]",
"=",
"str",
"(",
"val",
")",
"info",
"[",
"name",
"]",
"=",
"0",
"# Create a pax extended header if necessary.",
"if",
"pax_headers",
":",
"buf",
"=",
"self",
".",
"_create_pax_generic_header",
"(",
"pax_headers",
",",
"XHDTYPE",
",",
"encoding",
")",
"else",
":",
"buf",
"=",
"b\"\"",
"return",
"buf",
"+",
"self",
".",
"_create_header",
"(",
"info",
",",
"USTAR_FORMAT",
",",
"\"ascii\"",
",",
"\"replace\"",
")"
] |
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L1043-L1090
|
|
Allen7D/mini-shop-server
|
5f3ddd5a4e5e99a1e005f11abc620cefff2493fc
|
app/api/cms/group.py
|
python
|
delete_group
|
(id)
|
return Success(error_code=2)
|
删除权限组
|
删除权限组
|
[
"删除权限组"
] |
def delete_group(id):
'''删除权限组'''
GroupDao.delete_group(id=id)
return Success(error_code=2)
|
[
"def",
"delete_group",
"(",
"id",
")",
":",
"GroupDao",
".",
"delete_group",
"(",
"id",
"=",
"id",
")",
"return",
"Success",
"(",
"error_code",
"=",
"2",
")"
] |
https://github.com/Allen7D/mini-shop-server/blob/5f3ddd5a4e5e99a1e005f11abc620cefff2493fc/app/api/cms/group.py#L66-L69
|
|
home-assistant/core
|
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
|
homeassistant/components/rachio/binary_sensor.py
|
python
|
RachioRainSensor.device_class
|
(self)
|
return BinarySensorDeviceClass.MOISTURE
|
Return the class of this device.
|
Return the class of this device.
|
[
"Return",
"the",
"class",
"of",
"this",
"device",
"."
] |
def device_class(self) -> BinarySensorDeviceClass:
"""Return the class of this device."""
return BinarySensorDeviceClass.MOISTURE
|
[
"def",
"device_class",
"(",
"self",
")",
"->",
"BinarySensorDeviceClass",
":",
"return",
"BinarySensorDeviceClass",
".",
"MOISTURE"
] |
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/rachio/binary_sensor.py#L146-L148
|
|
boston-dynamics/spot-sdk
|
5ffa12e6943a47323c7279d86e30346868755f52
|
python/bosdyn-client/src/bosdyn/client/data_buffer.py
|
python
|
DataBufferClient.add_blob_async
|
(self, data, type_id, channel=None, robot_timestamp=None, write_sync=False,
**kwargs)
|
return self._do_add_blob(self.call_async, data, type_id, channel, robot_timestamp,
write_sync, **kwargs)
|
Async version of add_blob.
|
Async version of add_blob.
|
[
"Async",
"version",
"of",
"add_blob",
"."
] |
def add_blob_async(self, data, type_id, channel=None, robot_timestamp=None, write_sync=False,
**kwargs):
"""Async version of add_blob."""
return self._do_add_blob(self.call_async, data, type_id, channel, robot_timestamp,
write_sync, **kwargs)
|
[
"def",
"add_blob_async",
"(",
"self",
",",
"data",
",",
"type_id",
",",
"channel",
"=",
"None",
",",
"robot_timestamp",
"=",
"None",
",",
"write_sync",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_do_add_blob",
"(",
"self",
".",
"call_async",
",",
"data",
",",
"type_id",
",",
"channel",
",",
"robot_timestamp",
",",
"write_sync",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/boston-dynamics/spot-sdk/blob/5ffa12e6943a47323c7279d86e30346868755f52/python/bosdyn-client/src/bosdyn/client/data_buffer.py#L170-L174
|
|
smart-mobile-software/gitstack
|
d9fee8f414f202143eb6e620529e8e5539a2af56
|
python/Lib/mailbox.py
|
python
|
MaildirMessage.set_flags
|
(self, flags)
|
Set the given flags and unset all others.
|
Set the given flags and unset all others.
|
[
"Set",
"the",
"given",
"flags",
"and",
"unset",
"all",
"others",
"."
] |
def set_flags(self, flags):
"""Set the given flags and unset all others."""
self._info = '2,' + ''.join(sorted(flags))
|
[
"def",
"set_flags",
"(",
"self",
",",
"flags",
")",
":",
"self",
".",
"_info",
"=",
"'2,'",
"+",
"''",
".",
"join",
"(",
"sorted",
"(",
"flags",
")",
")"
] |
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/mailbox.py#L1449-L1451
|
||
ales-tsurko/cells
|
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
|
packaging/macos/python/lib/python3.7/smtplib.py
|
python
|
SMTP.docmd
|
(self, cmd, args="")
|
return self.getreply()
|
Send a command, and return its response code.
|
Send a command, and return its response code.
|
[
"Send",
"a",
"command",
"and",
"return",
"its",
"response",
"code",
"."
] |
def docmd(self, cmd, args=""):
"""Send a command, and return its response code."""
self.putcmd(cmd, args)
return self.getreply()
|
[
"def",
"docmd",
"(",
"self",
",",
"cmd",
",",
"args",
"=",
"\"\"",
")",
":",
"self",
".",
"putcmd",
"(",
"cmd",
",",
"args",
")",
"return",
"self",
".",
"getreply",
"(",
")"
] |
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/smtplib.py#L418-L421
|
|
khanhnamle1994/natural-language-processing
|
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
|
assignment1/.env/lib/python2.7/site-packages/scipy/cluster/vq.py
|
python
|
kmeans2
|
(data, k, iter=10, thresh=1e-5, minit='random',
missing='warn')
|
return _kmeans2(data, clusters, iter, nc, _valid_miss_meth[missing])
|
Classify a set of observations into k clusters using the k-means algorithm.
The algorithm attempts to minimize the Euclidian distance between
observations and centroids. Several initialization methods are
included.
Parameters
----------
data : ndarray
A 'M' by 'N' array of 'M' observations in 'N' dimensions or a length
'M' array of 'M' one-dimensional observations.
k : int or ndarray
The number of clusters to form as well as the number of
centroids to generate. If `minit` initialization string is
'matrix', or if a ndarray is given instead, it is
interpreted as initial cluster to use instead.
iter : int
Number of iterations of the k-means algrithm to run. Note
that this differs in meaning from the iters parameter to
the kmeans function.
thresh : float
(not used yet)
minit : string
Method for initialization. Available methods are 'random',
'points', 'uniform', and 'matrix':
'random': generate k centroids from a Gaussian with mean and
variance estimated from the data.
'points': choose k observations (rows) at random from data for
the initial centroids.
'uniform': generate k observations from the data from a uniform
distribution defined by the data set (unsupported).
'matrix': interpret the k parameter as a k by M (or length k
array for one-dimensional data) array of initial centroids.
Returns
-------
centroid : ndarray
A 'k' by 'N' array of centroids found at the last iteration of
k-means.
label : ndarray
label[i] is the code or index of the centroid the
i'th observation is closest to.
|
Classify a set of observations into k clusters using the k-means algorithm.
|
[
"Classify",
"a",
"set",
"of",
"observations",
"into",
"k",
"clusters",
"using",
"the",
"k",
"-",
"means",
"algorithm",
"."
] |
def kmeans2(data, k, iter=10, thresh=1e-5, minit='random',
missing='warn'):
"""
Classify a set of observations into k clusters using the k-means algorithm.
The algorithm attempts to minimize the Euclidian distance between
observations and centroids. Several initialization methods are
included.
Parameters
----------
data : ndarray
A 'M' by 'N' array of 'M' observations in 'N' dimensions or a length
'M' array of 'M' one-dimensional observations.
k : int or ndarray
The number of clusters to form as well as the number of
centroids to generate. If `minit` initialization string is
'matrix', or if a ndarray is given instead, it is
interpreted as initial cluster to use instead.
iter : int
Number of iterations of the k-means algrithm to run. Note
that this differs in meaning from the iters parameter to
the kmeans function.
thresh : float
(not used yet)
minit : string
Method for initialization. Available methods are 'random',
'points', 'uniform', and 'matrix':
'random': generate k centroids from a Gaussian with mean and
variance estimated from the data.
'points': choose k observations (rows) at random from data for
the initial centroids.
'uniform': generate k observations from the data from a uniform
distribution defined by the data set (unsupported).
'matrix': interpret the k parameter as a k by M (or length k
array for one-dimensional data) array of initial centroids.
Returns
-------
centroid : ndarray
A 'k' by 'N' array of centroids found at the last iteration of
k-means.
label : ndarray
label[i] is the code or index of the centroid the
i'th observation is closest to.
"""
if missing not in _valid_miss_meth:
raise ValueError("Unkown missing method: %s" % str(missing))
# If data is rank 1, then we have 1 dimension problem.
nd = np.ndim(data)
if nd == 1:
d = 1
# raise ValueError("Input of rank 1 not supported yet")
elif nd == 2:
d = data.shape[1]
else:
raise ValueError("Input of rank > 2 not supported")
if np.size(data) < 1:
raise ValueError("Input has 0 items.")
# If k is not a single value, then it should be compatible with data's
# shape
if np.size(k) > 1 or minit == 'matrix':
if not nd == np.ndim(k):
raise ValueError("k is not an int and has not same rank than data")
if d == 1:
nc = len(k)
else:
(nc, dc) = k.shape
if not dc == d:
raise ValueError("k is not an int and has not same rank than\
data")
clusters = k.copy()
else:
try:
nc = int(k)
except TypeError:
raise ValueError("k (%s) could not be converted to an integer " % str(k))
if nc < 1:
raise ValueError("kmeans2 for 0 clusters ? (k was %s)" % str(k))
if not nc == k:
warnings.warn("k was not an integer, was converted.")
try:
init = _valid_init_meth[minit]
except KeyError:
raise ValueError("unknown init method %s" % str(minit))
clusters = init(data, k)
if int(iter) < 1:
raise ValueError("iter = %s is not valid. iter must be a positive integer." % iter)
return _kmeans2(data, clusters, iter, nc, _valid_miss_meth[missing])
|
[
"def",
"kmeans2",
"(",
"data",
",",
"k",
",",
"iter",
"=",
"10",
",",
"thresh",
"=",
"1e-5",
",",
"minit",
"=",
"'random'",
",",
"missing",
"=",
"'warn'",
")",
":",
"if",
"missing",
"not",
"in",
"_valid_miss_meth",
":",
"raise",
"ValueError",
"(",
"\"Unkown missing method: %s\"",
"%",
"str",
"(",
"missing",
")",
")",
"# If data is rank 1, then we have 1 dimension problem.",
"nd",
"=",
"np",
".",
"ndim",
"(",
"data",
")",
"if",
"nd",
"==",
"1",
":",
"d",
"=",
"1",
"# raise ValueError(\"Input of rank 1 not supported yet\")",
"elif",
"nd",
"==",
"2",
":",
"d",
"=",
"data",
".",
"shape",
"[",
"1",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"\"Input of rank > 2 not supported\"",
")",
"if",
"np",
".",
"size",
"(",
"data",
")",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"Input has 0 items.\"",
")",
"# If k is not a single value, then it should be compatible with data's",
"# shape",
"if",
"np",
".",
"size",
"(",
"k",
")",
">",
"1",
"or",
"minit",
"==",
"'matrix'",
":",
"if",
"not",
"nd",
"==",
"np",
".",
"ndim",
"(",
"k",
")",
":",
"raise",
"ValueError",
"(",
"\"k is not an int and has not same rank than data\"",
")",
"if",
"d",
"==",
"1",
":",
"nc",
"=",
"len",
"(",
"k",
")",
"else",
":",
"(",
"nc",
",",
"dc",
")",
"=",
"k",
".",
"shape",
"if",
"not",
"dc",
"==",
"d",
":",
"raise",
"ValueError",
"(",
"\"k is not an int and has not same rank than\\\n data\"",
")",
"clusters",
"=",
"k",
".",
"copy",
"(",
")",
"else",
":",
"try",
":",
"nc",
"=",
"int",
"(",
"k",
")",
"except",
"TypeError",
":",
"raise",
"ValueError",
"(",
"\"k (%s) could not be converted to an integer \"",
"%",
"str",
"(",
"k",
")",
")",
"if",
"nc",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"kmeans2 for 0 clusters ? (k was %s)\"",
"%",
"str",
"(",
"k",
")",
")",
"if",
"not",
"nc",
"==",
"k",
":",
"warnings",
".",
"warn",
"(",
"\"k was not an integer, was converted.\"",
")",
"try",
":",
"init",
"=",
"_valid_init_meth",
"[",
"minit",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"unknown init method %s\"",
"%",
"str",
"(",
"minit",
")",
")",
"clusters",
"=",
"init",
"(",
"data",
",",
"k",
")",
"if",
"int",
"(",
"iter",
")",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"iter = %s is not valid. iter must be a positive integer.\"",
"%",
"iter",
")",
"return",
"_kmeans2",
"(",
"data",
",",
"clusters",
",",
"iter",
",",
"nc",
",",
"_valid_miss_meth",
"[",
"missing",
"]",
")"
] |
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/scipy/cluster/vq.py#L612-L711
|
|
tensorflow/tensor2tensor
|
2a33b152d7835af66a6d20afe7961751047e28dd
|
tensor2tensor/models/research/attention_lm.py
|
python
|
attention_lm_translation_l12
|
()
|
return hparams
|
Version to use for seq2seq.
|
Version to use for seq2seq.
|
[
"Version",
"to",
"use",
"for",
"seq2seq",
"."
] |
def attention_lm_translation_l12():
"""Version to use for seq2seq."""
hparams = attention_lm_translation()
hparams.batch_size = 4096
hparams.num_hidden_layers = 12
return hparams
|
[
"def",
"attention_lm_translation_l12",
"(",
")",
":",
"hparams",
"=",
"attention_lm_translation",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"4096",
"hparams",
".",
"num_hidden_layers",
"=",
"12",
"return",
"hparams"
] |
https://github.com/tensorflow/tensor2tensor/blob/2a33b152d7835af66a6d20afe7961751047e28dd/tensor2tensor/models/research/attention_lm.py#L202-L207
|
|
ztosec/hunter
|
4ee5cca8dc5fc5d7e631e935517bd0f493c30a37
|
SqlmapCelery/model/hunter_model.py
|
python
|
HunterModelService.get_fields_by_where
|
(cls, **kwargs)
|
基础的CURD操作,通用类
To use:
>>> tasks = HunterModelService.__get_fields_by_where(fields=(Task.id, Task.hunter_status), where=(Task.id > 1))
>>> print(tasks)
:param kwargs:
:return:
|
基础的CURD操作,通用类
To use:
>>> tasks = HunterModelService.__get_fields_by_where(fields=(Task.id, Task.hunter_status), where=(Task.id > 1))
>>> print(tasks)
|
[
"基础的CURD操作,通用类",
"To",
"use",
":",
">>>",
"tasks",
"=",
"HunterModelService",
".",
"__get_fields_by_where",
"(",
"fields",
"=",
"(",
"Task",
".",
"id",
"Task",
".",
"hunter_status",
")",
"where",
"=",
"(",
"Task",
".",
"id",
">",
"1",
"))",
">>>",
"print",
"(",
"tasks",
")"
] |
def get_fields_by_where(cls, **kwargs):
"""
基础的CURD操作,通用类
To use:
>>> tasks = HunterModelService.__get_fields_by_where(fields=(Task.id, Task.hunter_status), where=(Task.id > 1))
>>> print(tasks)
:param kwargs:
:return:
"""
# cls = self.__class__
if not kwargs: # 什么都没填
return cls.select().execute()
if "fields" not in kwargs and "where" in kwargs: # 要的结果字段没填
if isinstance(kwargs["where"], tuple):
return cls.select().where(*kwargs["where"]).execute()
return cls.select().where(tuple([kwargs["where"]])).execute()
if "where" not in kwargs and "fields" in kwargs: # 要的结果字段没填
if isinstance(kwargs["fields"], tuple):
return cls.select(*kwargs["fields"]).execute()
return cls.select(kwargs["fields"]).execute()
if "where" in kwargs and "fields" in kwargs: # 两个都填的情况
if isinstance(kwargs["where"], tuple) and isinstance(kwargs["fields"], tuple):
return cls.select(*kwargs["fields"]).where(*kwargs["where"]).execute()
if isinstance(kwargs["where"], tuple) and not isinstance(kwargs["fields"], tuple):
return cls.select(kwargs["fields"]).where(*kwargs["where"]).execute()
if not isinstance(kwargs["where"], tuple) and isinstance(kwargs["fields"], tuple):
return cls.select(*kwargs["fields"]).where(tuple([kwargs["where"]])).execute()
if not isinstance(kwargs["where"], tuple) and not isinstance(kwargs["fields"], tuple):
return cls.select(kwargs["fields"]).where(tuple([kwargs["where"]])).execute()
|
[
"def",
"get_fields_by_where",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"# cls = self.__class__",
"if",
"not",
"kwargs",
":",
"# 什么都没填",
"return",
"cls",
".",
"select",
"(",
")",
".",
"execute",
"(",
")",
"if",
"\"fields\"",
"not",
"in",
"kwargs",
"and",
"\"where\"",
"in",
"kwargs",
":",
"# 要的结果字段没填",
"if",
"isinstance",
"(",
"kwargs",
"[",
"\"where\"",
"]",
",",
"tuple",
")",
":",
"return",
"cls",
".",
"select",
"(",
")",
".",
"where",
"(",
"*",
"kwargs",
"[",
"\"where\"",
"]",
")",
".",
"execute",
"(",
")",
"return",
"cls",
".",
"select",
"(",
")",
".",
"where",
"(",
"tuple",
"(",
"[",
"kwargs",
"[",
"\"where\"",
"]",
"]",
")",
")",
".",
"execute",
"(",
")",
"if",
"\"where\"",
"not",
"in",
"kwargs",
"and",
"\"fields\"",
"in",
"kwargs",
":",
"# 要的结果字段没填",
"if",
"isinstance",
"(",
"kwargs",
"[",
"\"fields\"",
"]",
",",
"tuple",
")",
":",
"return",
"cls",
".",
"select",
"(",
"*",
"kwargs",
"[",
"\"fields\"",
"]",
")",
".",
"execute",
"(",
")",
"return",
"cls",
".",
"select",
"(",
"kwargs",
"[",
"\"fields\"",
"]",
")",
".",
"execute",
"(",
")",
"if",
"\"where\"",
"in",
"kwargs",
"and",
"\"fields\"",
"in",
"kwargs",
":",
"# 两个都填的情况",
"if",
"isinstance",
"(",
"kwargs",
"[",
"\"where\"",
"]",
",",
"tuple",
")",
"and",
"isinstance",
"(",
"kwargs",
"[",
"\"fields\"",
"]",
",",
"tuple",
")",
":",
"return",
"cls",
".",
"select",
"(",
"*",
"kwargs",
"[",
"\"fields\"",
"]",
")",
".",
"where",
"(",
"*",
"kwargs",
"[",
"\"where\"",
"]",
")",
".",
"execute",
"(",
")",
"if",
"isinstance",
"(",
"kwargs",
"[",
"\"where\"",
"]",
",",
"tuple",
")",
"and",
"not",
"isinstance",
"(",
"kwargs",
"[",
"\"fields\"",
"]",
",",
"tuple",
")",
":",
"return",
"cls",
".",
"select",
"(",
"kwargs",
"[",
"\"fields\"",
"]",
")",
".",
"where",
"(",
"*",
"kwargs",
"[",
"\"where\"",
"]",
")",
".",
"execute",
"(",
")",
"if",
"not",
"isinstance",
"(",
"kwargs",
"[",
"\"where\"",
"]",
",",
"tuple",
")",
"and",
"isinstance",
"(",
"kwargs",
"[",
"\"fields\"",
"]",
",",
"tuple",
")",
":",
"return",
"cls",
".",
"select",
"(",
"*",
"kwargs",
"[",
"\"fields\"",
"]",
")",
".",
"where",
"(",
"tuple",
"(",
"[",
"kwargs",
"[",
"\"where\"",
"]",
"]",
")",
")",
".",
"execute",
"(",
")",
"if",
"not",
"isinstance",
"(",
"kwargs",
"[",
"\"where\"",
"]",
",",
"tuple",
")",
"and",
"not",
"isinstance",
"(",
"kwargs",
"[",
"\"fields\"",
"]",
",",
"tuple",
")",
":",
"return",
"cls",
".",
"select",
"(",
"kwargs",
"[",
"\"fields\"",
"]",
")",
".",
"where",
"(",
"tuple",
"(",
"[",
"kwargs",
"[",
"\"where\"",
"]",
"]",
")",
")",
".",
"execute",
"(",
")"
] |
https://github.com/ztosec/hunter/blob/4ee5cca8dc5fc5d7e631e935517bd0f493c30a37/SqlmapCelery/model/hunter_model.py#L132-L167
|
||
IronLanguages/ironpython3
|
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
|
Src/StdLib/Lib/asyncio/base_events.py
|
python
|
BaseEventLoop.call_at
|
(self, when, callback, *args)
|
return timer
|
Like call_later(), but uses an absolute time.
Absolute time corresponds to the event loop's time() method.
|
Like call_later(), but uses an absolute time.
|
[
"Like",
"call_later",
"()",
"but",
"uses",
"an",
"absolute",
"time",
"."
] |
def call_at(self, when, callback, *args):
"""Like call_later(), but uses an absolute time.
Absolute time corresponds to the event loop's time() method.
"""
if (coroutines.iscoroutine(callback)
or coroutines.iscoroutinefunction(callback)):
raise TypeError("coroutines cannot be used with call_at()")
self._check_closed()
if self._debug:
self._check_thread()
timer = events.TimerHandle(when, callback, args, self)
if timer._source_traceback:
del timer._source_traceback[-1]
heapq.heappush(self._scheduled, timer)
timer._scheduled = True
return timer
|
[
"def",
"call_at",
"(",
"self",
",",
"when",
",",
"callback",
",",
"*",
"args",
")",
":",
"if",
"(",
"coroutines",
".",
"iscoroutine",
"(",
"callback",
")",
"or",
"coroutines",
".",
"iscoroutinefunction",
"(",
"callback",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"coroutines cannot be used with call_at()\"",
")",
"self",
".",
"_check_closed",
"(",
")",
"if",
"self",
".",
"_debug",
":",
"self",
".",
"_check_thread",
"(",
")",
"timer",
"=",
"events",
".",
"TimerHandle",
"(",
"when",
",",
"callback",
",",
"args",
",",
"self",
")",
"if",
"timer",
".",
"_source_traceback",
":",
"del",
"timer",
".",
"_source_traceback",
"[",
"-",
"1",
"]",
"heapq",
".",
"heappush",
"(",
"self",
".",
"_scheduled",
",",
"timer",
")",
"timer",
".",
"_scheduled",
"=",
"True",
"return",
"timer"
] |
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/asyncio/base_events.py#L453-L469
|
|
eirannejad/pyRevit
|
49c0b7eb54eb343458ce1365425e6552d0c47d44
|
pyrevitlib/rpw/__revit.py
|
python
|
Revit.open
|
(self, path)
|
Opens New Document
|
Opens New Document
|
[
"Opens",
"New",
"Document"
] |
def open(self, path):
""" Opens New Document """
|
[
"def",
"open",
"(",
"self",
",",
"path",
")",
":"
] |
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/pyrevitlib/rpw/__revit.py#L102-L103
|
||
poppy-project/pypot
|
c5d384fe23eef9f6ec98467f6f76626cdf20afb9
|
pypot/sensor/depth/sonar.py
|
python
|
Sonar.update
|
(self)
|
return self.data
|
[] |
def update(self):
self.ping()
time.sleep(0.065)
self.data = self._filter(self.read())
return self.data
|
[
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"ping",
"(",
")",
"time",
".",
"sleep",
"(",
"0.065",
")",
"self",
".",
"data",
"=",
"self",
".",
"_filter",
"(",
"self",
".",
"read",
"(",
")",
")",
"return",
"self",
".",
"data"
] |
https://github.com/poppy-project/pypot/blob/c5d384fe23eef9f6ec98467f6f76626cdf20afb9/pypot/sensor/depth/sonar.py#L74-L78
|
|||
certbot/certbot
|
30b066f08260b73fc26256b5484a180468b9d0a6
|
certbot-apache/certbot_apache/_internal/parser.py
|
python
|
ApacheParser.save
|
(self, save_files)
|
Saves all changes to the configuration files.
save() is called from ApacheConfigurator to handle the parser specific
tasks of saving.
:param list save_files: list of strings of file paths that we need to save.
|
Saves all changes to the configuration files.
|
[
"Saves",
"all",
"changes",
"to",
"the",
"configuration",
"files",
"."
] |
def save(self, save_files):
"""Saves all changes to the configuration files.
save() is called from ApacheConfigurator to handle the parser specific
tasks of saving.
:param list save_files: list of strings of file paths that we need to save.
"""
self.configurator.save_notes = ""
self.aug.save()
# Force reload if files were modified
# This is needed to recalculate augeas directive span
if save_files:
for sf in save_files:
self.aug.remove("/files/"+sf)
self.aug.load()
|
[
"def",
"save",
"(",
"self",
",",
"save_files",
")",
":",
"self",
".",
"configurator",
".",
"save_notes",
"=",
"\"\"",
"self",
".",
"aug",
".",
"save",
"(",
")",
"# Force reload if files were modified",
"# This is needed to recalculate augeas directive span",
"if",
"save_files",
":",
"for",
"sf",
"in",
"save_files",
":",
"self",
".",
"aug",
".",
"remove",
"(",
"\"/files/\"",
"+",
"sf",
")",
"self",
".",
"aug",
".",
"load",
"(",
")"
] |
https://github.com/certbot/certbot/blob/30b066f08260b73fc26256b5484a180468b9d0a6/certbot-apache/certbot_apache/_internal/parser.py#L181-L198
|
||
zedshaw/lamson
|
8a8ad546ea746b129fa5f069bf9278f87d01473a
|
examples/librelist/app/handlers/bounce.py
|
python
|
force_to_bounce_state
|
(message)
|
[] |
def force_to_bounce_state(message):
# set their admin module state to disabled
name, address = parseaddr(message.bounce.final_recipient)
Router.STATE_STORE.set_all(address, 'BOUNCING')
Router.STATE_STORE.set('app.handlers.bounce', address, 'BOUNCING')
mailinglist.disable_all_subscriptions(message.bounce.final_recipient)
|
[
"def",
"force_to_bounce_state",
"(",
"message",
")",
":",
"# set their admin module state to disabled",
"name",
",",
"address",
"=",
"parseaddr",
"(",
"message",
".",
"bounce",
".",
"final_recipient",
")",
"Router",
".",
"STATE_STORE",
".",
"set_all",
"(",
"address",
",",
"'BOUNCING'",
")",
"Router",
".",
"STATE_STORE",
".",
"set",
"(",
"'app.handlers.bounce'",
",",
"address",
",",
"'BOUNCING'",
")",
"mailinglist",
".",
"disable_all_subscriptions",
"(",
"message",
".",
"bounce",
".",
"final_recipient",
")"
] |
https://github.com/zedshaw/lamson/blob/8a8ad546ea746b129fa5f069bf9278f87d01473a/examples/librelist/app/handlers/bounce.py#L10-L15
|
||||
numba/numba
|
bf480b9e0da858a65508c2b17759a72ee6a44c51
|
numba/cpython/randomimpl.py
|
python
|
randrange_impl_1
|
(context, builder, sig, args)
|
return impl_ret_untracked(context, builder, sig.return_type, res)
|
[] |
def randrange_impl_1(context, builder, sig, args):
stop, = args
start = ir.Constant(stop.type, 0)
step = ir.Constant(stop.type, 1)
res = _randrange_impl(context, builder, start, stop, step, "py")
return impl_ret_untracked(context, builder, sig.return_type, res)
|
[
"def",
"randrange_impl_1",
"(",
"context",
",",
"builder",
",",
"sig",
",",
"args",
")",
":",
"stop",
",",
"=",
"args",
"start",
"=",
"ir",
".",
"Constant",
"(",
"stop",
".",
"type",
",",
"0",
")",
"step",
"=",
"ir",
".",
"Constant",
"(",
"stop",
".",
"type",
",",
"1",
")",
"res",
"=",
"_randrange_impl",
"(",
"context",
",",
"builder",
",",
"start",
",",
"stop",
",",
"step",
",",
"\"py\"",
")",
"return",
"impl_ret_untracked",
"(",
"context",
",",
"builder",
",",
"sig",
".",
"return_type",
",",
"res",
")"
] |
https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/cpython/randomimpl.py#L398-L403
|
|||
hyperledger/aries-cloudagent-python
|
2f36776e99f6053ae92eed8123b5b1b2e891c02a
|
aries_cloudagent/protocols/present_proof/v1_0/routes.py
|
python
|
register
|
(app: web.Application)
|
Register routes.
|
Register routes.
|
[
"Register",
"routes",
"."
] |
async def register(app: web.Application):
"""Register routes."""
app.add_routes(
[
web.get(
"/present-proof/records",
presentation_exchange_list,
allow_head=False,
),
web.get(
"/present-proof/records/{pres_ex_id}",
presentation_exchange_retrieve,
allow_head=False,
),
web.get(
"/present-proof/records/{pres_ex_id}/credentials",
presentation_exchange_credentials_list,
allow_head=False,
),
web.post(
"/present-proof/send-proposal",
presentation_exchange_send_proposal,
),
web.post(
"/present-proof/create-request",
presentation_exchange_create_request,
),
web.post(
"/present-proof/send-request",
presentation_exchange_send_free_request,
),
web.post(
"/present-proof/records/{pres_ex_id}/send-request",
presentation_exchange_send_bound_request,
),
web.post(
"/present-proof/records/{pres_ex_id}/send-presentation",
presentation_exchange_send_presentation,
),
web.post(
"/present-proof/records/{pres_ex_id}/verify-presentation",
presentation_exchange_verify_presentation,
),
web.post(
"/present-proof/records/{pres_ex_id}/problem-report",
presentation_exchange_problem_report,
),
web.delete(
"/present-proof/records/{pres_ex_id}",
presentation_exchange_remove,
),
]
)
|
[
"async",
"def",
"register",
"(",
"app",
":",
"web",
".",
"Application",
")",
":",
"app",
".",
"add_routes",
"(",
"[",
"web",
".",
"get",
"(",
"\"/present-proof/records\"",
",",
"presentation_exchange_list",
",",
"allow_head",
"=",
"False",
",",
")",
",",
"web",
".",
"get",
"(",
"\"/present-proof/records/{pres_ex_id}\"",
",",
"presentation_exchange_retrieve",
",",
"allow_head",
"=",
"False",
",",
")",
",",
"web",
".",
"get",
"(",
"\"/present-proof/records/{pres_ex_id}/credentials\"",
",",
"presentation_exchange_credentials_list",
",",
"allow_head",
"=",
"False",
",",
")",
",",
"web",
".",
"post",
"(",
"\"/present-proof/send-proposal\"",
",",
"presentation_exchange_send_proposal",
",",
")",
",",
"web",
".",
"post",
"(",
"\"/present-proof/create-request\"",
",",
"presentation_exchange_create_request",
",",
")",
",",
"web",
".",
"post",
"(",
"\"/present-proof/send-request\"",
",",
"presentation_exchange_send_free_request",
",",
")",
",",
"web",
".",
"post",
"(",
"\"/present-proof/records/{pres_ex_id}/send-request\"",
",",
"presentation_exchange_send_bound_request",
",",
")",
",",
"web",
".",
"post",
"(",
"\"/present-proof/records/{pres_ex_id}/send-presentation\"",
",",
"presentation_exchange_send_presentation",
",",
")",
",",
"web",
".",
"post",
"(",
"\"/present-proof/records/{pres_ex_id}/verify-presentation\"",
",",
"presentation_exchange_verify_presentation",
",",
")",
",",
"web",
".",
"post",
"(",
"\"/present-proof/records/{pres_ex_id}/problem-report\"",
",",
"presentation_exchange_problem_report",
",",
")",
",",
"web",
".",
"delete",
"(",
"\"/present-proof/records/{pres_ex_id}\"",
",",
"presentation_exchange_remove",
",",
")",
",",
"]",
")"
] |
https://github.com/hyperledger/aries-cloudagent-python/blob/2f36776e99f6053ae92eed8123b5b1b2e891c02a/aries_cloudagent/protocols/present_proof/v1_0/routes.py#L928-L981
|
||
sagemath/sage
|
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
|
src/sage/numerical/interactive_simplex_method.py
|
python
|
LPAbstractDictionary.column_coefficients
|
(self, v)
|
r"""
Return the coefficients of a nonbasic variable.
INPUT:
- ``v`` -- a nonbasic variable of ``self``, can be given as a string, an
actual variable, or an integer interpreted as the index of a variable
OUTPUT:
- a vector of coefficients of a nonbasic variable
EXAMPLES::
sage: A = ([1, 1], [3, 1])
sage: b = (1000, 1500)
sage: c = (10, 5)
sage: P = InteractiveLPProblemStandardForm(A, b, c)
sage: D = P.revised_dictionary()
sage: D.column_coefficients(1)
(1, 3)
|
r"""
Return the coefficients of a nonbasic variable.
|
[
"r",
"Return",
"the",
"coefficients",
"of",
"a",
"nonbasic",
"variable",
"."
] |
def column_coefficients(self, v):
r"""
Return the coefficients of a nonbasic variable.
INPUT:
- ``v`` -- a nonbasic variable of ``self``, can be given as a string, an
actual variable, or an integer interpreted as the index of a variable
OUTPUT:
- a vector of coefficients of a nonbasic variable
EXAMPLES::
sage: A = ([1, 1], [3, 1])
sage: b = (1000, 1500)
sage: c = (10, 5)
sage: P = InteractiveLPProblemStandardForm(A, b, c)
sage: D = P.revised_dictionary()
sage: D.column_coefficients(1)
(1, 3)
"""
|
[
"def",
"column_coefficients",
"(",
"self",
",",
"v",
")",
":"
] |
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/numerical/interactive_simplex_method.py#L2946-L2968
|
||
dimagi/commcare-hq
|
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
|
corehq/apps/app_manager/helpers/validators.py
|
python
|
AdvancedFormValidator.extended_build_validation
|
(self, error_meta, xml_valid, validate_module=True)
|
return errors
|
[] |
def extended_build_validation(self, error_meta, xml_valid, validate_module=True):
errors = []
if xml_valid:
for error in self.check_actions():
error.update(error_meta)
errors.append(error)
module = self.form.get_module()
if validate_module:
errors.extend(module.validator.get_case_errors(
needs_case_type=False,
needs_case_detail=module.requires_case_details(),
needs_referral_detail=False,
))
return errors
|
[
"def",
"extended_build_validation",
"(",
"self",
",",
"error_meta",
",",
"xml_valid",
",",
"validate_module",
"=",
"True",
")",
":",
"errors",
"=",
"[",
"]",
"if",
"xml_valid",
":",
"for",
"error",
"in",
"self",
".",
"check_actions",
"(",
")",
":",
"error",
".",
"update",
"(",
"error_meta",
")",
"errors",
".",
"append",
"(",
"error",
")",
"module",
"=",
"self",
".",
"form",
".",
"get_module",
"(",
")",
"if",
"validate_module",
":",
"errors",
".",
"extend",
"(",
"module",
".",
"validator",
".",
"get_case_errors",
"(",
"needs_case_type",
"=",
"False",
",",
"needs_case_detail",
"=",
"module",
".",
"requires_case_details",
"(",
")",
",",
"needs_referral_detail",
"=",
"False",
",",
")",
")",
"return",
"errors"
] |
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/app_manager/helpers/validators.py#L1028-L1043
|
|||
python/cpython
|
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
|
Lib/importlib/_bootstrap_external.py
|
python
|
SourceFileLoader.path_stats
|
(self, path)
|
return {'mtime': st.st_mtime, 'size': st.st_size}
|
Return the metadata for the path.
|
Return the metadata for the path.
|
[
"Return",
"the",
"metadata",
"for",
"the",
"path",
"."
] |
def path_stats(self, path):
"""Return the metadata for the path."""
st = _path_stat(path)
return {'mtime': st.st_mtime, 'size': st.st_size}
|
[
"def",
"path_stats",
"(",
"self",
",",
"path",
")",
":",
"st",
"=",
"_path_stat",
"(",
"path",
")",
"return",
"{",
"'mtime'",
":",
"st",
".",
"st_mtime",
",",
"'size'",
":",
"st",
".",
"st_size",
"}"
] |
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/importlib/_bootstrap_external.py#L1121-L1124
|
|
BrieflyX/ctf-pwns
|
0eb569d7f407a1bf50d4269ae1572181e4048774
|
heap/heap-trival/mario/release.py
|
python
|
pow_hash
|
(challenge, solution)
|
return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
|
[] |
def pow_hash(challenge, solution):
return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
|
[
"def",
"pow_hash",
"(",
"challenge",
",",
"solution",
")",
":",
"return",
"hashlib",
".",
"sha256",
"(",
"challenge",
".",
"encode",
"(",
"'ascii'",
")",
"+",
"struct",
".",
"pack",
"(",
"'<Q'",
",",
"solution",
")",
")",
".",
"hexdigest",
"(",
")"
] |
https://github.com/BrieflyX/ctf-pwns/blob/0eb569d7f407a1bf50d4269ae1572181e4048774/heap/heap-trival/mario/release.py#L95-L96
|
|||
number5/cloud-init
|
19948dbaf40309355e1a2dbef116efb0ce66245c
|
cloudinit/distros/gentoo.py
|
python
|
convert_resolv_conf
|
(settings)
|
return result
|
Returns a settings string formatted for resolv.conf.
|
Returns a settings string formatted for resolv.conf.
|
[
"Returns",
"a",
"settings",
"string",
"formatted",
"for",
"resolv",
".",
"conf",
"."
] |
def convert_resolv_conf(settings):
"""Returns a settings string formatted for resolv.conf."""
result = ""
if isinstance(settings, list):
for ns in settings:
result += "nameserver %s\n" % ns
return result
|
[
"def",
"convert_resolv_conf",
"(",
"settings",
")",
":",
"result",
"=",
"\"\"",
"if",
"isinstance",
"(",
"settings",
",",
"list",
")",
":",
"for",
"ns",
"in",
"settings",
":",
"result",
"+=",
"\"nameserver %s\\n\"",
"%",
"ns",
"return",
"result"
] |
https://github.com/number5/cloud-init/blob/19948dbaf40309355e1a2dbef116efb0ce66245c/cloudinit/distros/gentoo.py#L239-L245
|
|
AppScale/gts
|
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
|
AppServer/lib/django-1.3/django/template/loader.py
|
python
|
BaseLoader.reset
|
(self)
|
Resets any state maintained by the loader instance (e.g., cached
templates or cached loader modules).
|
Resets any state maintained by the loader instance (e.g., cached
templates or cached loader modules).
|
[
"Resets",
"any",
"state",
"maintained",
"by",
"the",
"loader",
"instance",
"(",
"e",
".",
"g",
".",
"cached",
"templates",
"or",
"cached",
"loader",
"modules",
")",
"."
] |
def reset(self):
"""
Resets any state maintained by the loader instance (e.g., cached
templates or cached loader modules).
"""
pass
|
[
"def",
"reset",
"(",
"self",
")",
":",
"pass"
] |
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.3/django/template/loader.py#L65-L71
|
||
steeve/xbmctorrent
|
e6bcb1037668959e1e3cb5ba8cf3e379c6638da9
|
resources/site-packages/xbmcswift2/listitem.py
|
python
|
ListItem.__init__
|
(self, label=None, label2=None, icon=None, thumbnail=None,
path=None)
|
Defaults are an emtpy string since xbmcgui.ListItem will not
accept None.
|
Defaults are an emtpy string since xbmcgui.ListItem will not
accept None.
|
[
"Defaults",
"are",
"an",
"emtpy",
"string",
"since",
"xbmcgui",
".",
"ListItem",
"will",
"not",
"accept",
"None",
"."
] |
def __init__(self, label=None, label2=None, icon=None, thumbnail=None,
path=None):
'''Defaults are an emtpy string since xbmcgui.ListItem will not
accept None.
'''
kwargs = {
'label': label,
'label2': label2,
'iconImage': icon,
'thumbnailImage': thumbnail,
'path': path,
}
#kwargs = dict((key, val) for key, val in locals().items() if val is
#not None and key != 'self')
kwargs = dict((key, val) for key, val in kwargs.items()
if val is not None)
self._listitem = xbmcgui.ListItem(**kwargs)
# xbmc doesn't make getters available for these properties so we'll
# keep track on our own
self._icon = icon
self._path = path
self._thumbnail = thumbnail
self._context_menu_items = []
self.is_folder = True
self._played = False
|
[
"def",
"__init__",
"(",
"self",
",",
"label",
"=",
"None",
",",
"label2",
"=",
"None",
",",
"icon",
"=",
"None",
",",
"thumbnail",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"'label'",
":",
"label",
",",
"'label2'",
":",
"label2",
",",
"'iconImage'",
":",
"icon",
",",
"'thumbnailImage'",
":",
"thumbnail",
",",
"'path'",
":",
"path",
",",
"}",
"#kwargs = dict((key, val) for key, val in locals().items() if val is",
"#not None and key != 'self')",
"kwargs",
"=",
"dict",
"(",
"(",
"key",
",",
"val",
")",
"for",
"key",
",",
"val",
"in",
"kwargs",
".",
"items",
"(",
")",
"if",
"val",
"is",
"not",
"None",
")",
"self",
".",
"_listitem",
"=",
"xbmcgui",
".",
"ListItem",
"(",
"*",
"*",
"kwargs",
")",
"# xbmc doesn't make getters available for these properties so we'll",
"# keep track on our own",
"self",
".",
"_icon",
"=",
"icon",
"self",
".",
"_path",
"=",
"path",
"self",
".",
"_thumbnail",
"=",
"thumbnail",
"self",
".",
"_context_menu_items",
"=",
"[",
"]",
"self",
".",
"is_folder",
"=",
"True",
"self",
".",
"_played",
"=",
"False"
] |
https://github.com/steeve/xbmctorrent/blob/e6bcb1037668959e1e3cb5ba8cf3e379c6638da9/resources/site-packages/xbmcswift2/listitem.py#L18-L43
|
||
NoGameNoLife00/mybolg
|
afe17ea5bfe405e33766e5682c43a4262232ee12
|
libs/wtforms/ext/appengine/db.py
|
python
|
convert_ReferenceProperty
|
(model, prop, kwargs)
|
return ReferencePropertyField(**kwargs)
|
Returns a form field for a ``db.ReferenceProperty``.
|
Returns a form field for a ``db.ReferenceProperty``.
|
[
"Returns",
"a",
"form",
"field",
"for",
"a",
"db",
".",
"ReferenceProperty",
"."
] |
def convert_ReferenceProperty(model, prop, kwargs):
"""Returns a form field for a ``db.ReferenceProperty``."""
kwargs['reference_class'] = prop.reference_class
kwargs.setdefault('allow_blank', not prop.required)
return ReferencePropertyField(**kwargs)
|
[
"def",
"convert_ReferenceProperty",
"(",
"model",
",",
"prop",
",",
"kwargs",
")",
":",
"kwargs",
"[",
"'reference_class'",
"]",
"=",
"prop",
".",
"reference_class",
"kwargs",
".",
"setdefault",
"(",
"'allow_blank'",
",",
"not",
"prop",
".",
"required",
")",
"return",
"ReferencePropertyField",
"(",
"*",
"*",
"kwargs",
")"
] |
https://github.com/NoGameNoLife00/mybolg/blob/afe17ea5bfe405e33766e5682c43a4262232ee12/libs/wtforms/ext/appengine/db.py#L184-L188
|
|
espnet/espnet
|
ea411f3f627b8f101c211e107d0ff7053344ac80
|
espnet/nets/pytorch_backend/ctc.py
|
python
|
CTC.forced_align
|
(self, h, y, blank_id=0)
|
return output_state_seq
|
forced alignment.
:param torch.Tensor h: hidden state sequence, 2d tensor (T, D)
:param torch.Tensor y: id sequence tensor 1d tensor (L)
:param int y: blank symbol index
:return: best alignment results
:rtype: list
|
forced alignment.
|
[
"forced",
"alignment",
"."
] |
def forced_align(self, h, y, blank_id=0):
"""forced alignment.
:param torch.Tensor h: hidden state sequence, 2d tensor (T, D)
:param torch.Tensor y: id sequence tensor 1d tensor (L)
:param int y: blank symbol index
:return: best alignment results
:rtype: list
"""
def interpolate_blank(label, blank_id=0):
"""Insert blank token between every two label token."""
label = np.expand_dims(label, 1)
blanks = np.zeros((label.shape[0], 1), dtype=np.int64) + blank_id
label = np.concatenate([blanks, label], axis=1)
label = label.reshape(-1)
label = np.append(label, label[0])
return label
lpz = self.log_softmax(h)
lpz = lpz.squeeze(0)
y_int = interpolate_blank(y, blank_id)
logdelta = np.zeros((lpz.size(0), len(y_int))) - 100000000000.0 # log of zero
state_path = (
np.zeros((lpz.size(0), len(y_int)), dtype=np.int16) - 1
) # state path
logdelta[0, 0] = lpz[0][y_int[0]]
logdelta[0, 1] = lpz[0][y_int[1]]
for t in six.moves.range(1, lpz.size(0)):
for s in six.moves.range(len(y_int)):
if y_int[s] == blank_id or s < 2 or y_int[s] == y_int[s - 2]:
candidates = np.array([logdelta[t - 1, s], logdelta[t - 1, s - 1]])
prev_state = [s, s - 1]
else:
candidates = np.array(
[
logdelta[t - 1, s],
logdelta[t - 1, s - 1],
logdelta[t - 1, s - 2],
]
)
prev_state = [s, s - 1, s - 2]
logdelta[t, s] = np.max(candidates) + lpz[t][y_int[s]]
state_path[t, s] = prev_state[np.argmax(candidates)]
state_seq = -1 * np.ones((lpz.size(0), 1), dtype=np.int16)
candidates = np.array(
[logdelta[-1, len(y_int) - 1], logdelta[-1, len(y_int) - 2]]
)
prev_state = [len(y_int) - 1, len(y_int) - 2]
state_seq[-1] = prev_state[np.argmax(candidates)]
for t in six.moves.range(lpz.size(0) - 2, -1, -1):
state_seq[t] = state_path[t + 1, state_seq[t + 1, 0]]
output_state_seq = []
for t in six.moves.range(0, lpz.size(0)):
output_state_seq.append(y_int[state_seq[t, 0]])
return output_state_seq
|
[
"def",
"forced_align",
"(",
"self",
",",
"h",
",",
"y",
",",
"blank_id",
"=",
"0",
")",
":",
"def",
"interpolate_blank",
"(",
"label",
",",
"blank_id",
"=",
"0",
")",
":",
"\"\"\"Insert blank token between every two label token.\"\"\"",
"label",
"=",
"np",
".",
"expand_dims",
"(",
"label",
",",
"1",
")",
"blanks",
"=",
"np",
".",
"zeros",
"(",
"(",
"label",
".",
"shape",
"[",
"0",
"]",
",",
"1",
")",
",",
"dtype",
"=",
"np",
".",
"int64",
")",
"+",
"blank_id",
"label",
"=",
"np",
".",
"concatenate",
"(",
"[",
"blanks",
",",
"label",
"]",
",",
"axis",
"=",
"1",
")",
"label",
"=",
"label",
".",
"reshape",
"(",
"-",
"1",
")",
"label",
"=",
"np",
".",
"append",
"(",
"label",
",",
"label",
"[",
"0",
"]",
")",
"return",
"label",
"lpz",
"=",
"self",
".",
"log_softmax",
"(",
"h",
")",
"lpz",
"=",
"lpz",
".",
"squeeze",
"(",
"0",
")",
"y_int",
"=",
"interpolate_blank",
"(",
"y",
",",
"blank_id",
")",
"logdelta",
"=",
"np",
".",
"zeros",
"(",
"(",
"lpz",
".",
"size",
"(",
"0",
")",
",",
"len",
"(",
"y_int",
")",
")",
")",
"-",
"100000000000.0",
"# log of zero",
"state_path",
"=",
"(",
"np",
".",
"zeros",
"(",
"(",
"lpz",
".",
"size",
"(",
"0",
")",
",",
"len",
"(",
"y_int",
")",
")",
",",
"dtype",
"=",
"np",
".",
"int16",
")",
"-",
"1",
")",
"# state path",
"logdelta",
"[",
"0",
",",
"0",
"]",
"=",
"lpz",
"[",
"0",
"]",
"[",
"y_int",
"[",
"0",
"]",
"]",
"logdelta",
"[",
"0",
",",
"1",
"]",
"=",
"lpz",
"[",
"0",
"]",
"[",
"y_int",
"[",
"1",
"]",
"]",
"for",
"t",
"in",
"six",
".",
"moves",
".",
"range",
"(",
"1",
",",
"lpz",
".",
"size",
"(",
"0",
")",
")",
":",
"for",
"s",
"in",
"six",
".",
"moves",
".",
"range",
"(",
"len",
"(",
"y_int",
")",
")",
":",
"if",
"y_int",
"[",
"s",
"]",
"==",
"blank_id",
"or",
"s",
"<",
"2",
"or",
"y_int",
"[",
"s",
"]",
"==",
"y_int",
"[",
"s",
"-",
"2",
"]",
":",
"candidates",
"=",
"np",
".",
"array",
"(",
"[",
"logdelta",
"[",
"t",
"-",
"1",
",",
"s",
"]",
",",
"logdelta",
"[",
"t",
"-",
"1",
",",
"s",
"-",
"1",
"]",
"]",
")",
"prev_state",
"=",
"[",
"s",
",",
"s",
"-",
"1",
"]",
"else",
":",
"candidates",
"=",
"np",
".",
"array",
"(",
"[",
"logdelta",
"[",
"t",
"-",
"1",
",",
"s",
"]",
",",
"logdelta",
"[",
"t",
"-",
"1",
",",
"s",
"-",
"1",
"]",
",",
"logdelta",
"[",
"t",
"-",
"1",
",",
"s",
"-",
"2",
"]",
",",
"]",
")",
"prev_state",
"=",
"[",
"s",
",",
"s",
"-",
"1",
",",
"s",
"-",
"2",
"]",
"logdelta",
"[",
"t",
",",
"s",
"]",
"=",
"np",
".",
"max",
"(",
"candidates",
")",
"+",
"lpz",
"[",
"t",
"]",
"[",
"y_int",
"[",
"s",
"]",
"]",
"state_path",
"[",
"t",
",",
"s",
"]",
"=",
"prev_state",
"[",
"np",
".",
"argmax",
"(",
"candidates",
")",
"]",
"state_seq",
"=",
"-",
"1",
"*",
"np",
".",
"ones",
"(",
"(",
"lpz",
".",
"size",
"(",
"0",
")",
",",
"1",
")",
",",
"dtype",
"=",
"np",
".",
"int16",
")",
"candidates",
"=",
"np",
".",
"array",
"(",
"[",
"logdelta",
"[",
"-",
"1",
",",
"len",
"(",
"y_int",
")",
"-",
"1",
"]",
",",
"logdelta",
"[",
"-",
"1",
",",
"len",
"(",
"y_int",
")",
"-",
"2",
"]",
"]",
")",
"prev_state",
"=",
"[",
"len",
"(",
"y_int",
")",
"-",
"1",
",",
"len",
"(",
"y_int",
")",
"-",
"2",
"]",
"state_seq",
"[",
"-",
"1",
"]",
"=",
"prev_state",
"[",
"np",
".",
"argmax",
"(",
"candidates",
")",
"]",
"for",
"t",
"in",
"six",
".",
"moves",
".",
"range",
"(",
"lpz",
".",
"size",
"(",
"0",
")",
"-",
"2",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"state_seq",
"[",
"t",
"]",
"=",
"state_path",
"[",
"t",
"+",
"1",
",",
"state_seq",
"[",
"t",
"+",
"1",
",",
"0",
"]",
"]",
"output_state_seq",
"=",
"[",
"]",
"for",
"t",
"in",
"six",
".",
"moves",
".",
"range",
"(",
"0",
",",
"lpz",
".",
"size",
"(",
"0",
")",
")",
":",
"output_state_seq",
".",
"append",
"(",
"y_int",
"[",
"state_seq",
"[",
"t",
",",
"0",
"]",
"]",
")",
"return",
"output_state_seq"
] |
https://github.com/espnet/espnet/blob/ea411f3f627b8f101c211e107d0ff7053344ac80/espnet/nets/pytorch_backend/ctc.py#L180-L243
|
|
PyWavelets/pywt
|
9a72143be347481e2276371efb41ae0266b9c808
|
util/refguide_check.py
|
python
|
short_path
|
(path, cwd=None)
|
return relpath
|
Return relative or absolute path name, whichever is shortest.
|
Return relative or absolute path name, whichever is shortest.
|
[
"Return",
"relative",
"or",
"absolute",
"path",
"name",
"whichever",
"is",
"shortest",
"."
] |
def short_path(path, cwd=None):
"""
Return relative or absolute path name, whichever is shortest.
"""
if not isinstance(path, str):
return path
if cwd is None:
cwd = os.getcwd()
abspath = os.path.abspath(path)
relpath = os.path.relpath(path, cwd)
if len(abspath) <= len(relpath):
return abspath
return relpath
|
[
"def",
"short_path",
"(",
"path",
",",
"cwd",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"return",
"path",
"if",
"cwd",
"is",
"None",
":",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"abspath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"relpath",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"path",
",",
"cwd",
")",
"if",
"len",
"(",
"abspath",
")",
"<=",
"len",
"(",
"relpath",
")",
":",
"return",
"abspath",
"return",
"relpath"
] |
https://github.com/PyWavelets/pywt/blob/9a72143be347481e2276371efb41ae0266b9c808/util/refguide_check.py#L80-L92
|
|
pyopenapi/pyswagger
|
333c4ca08e758cd2194943d9904a3eda3fe43977
|
pyswagger/spec/base.py
|
python
|
BaseObj.resolve
|
(self, ts)
|
return obj
|
resolve a list of tokens to an child object
:param list ts: list of tokens
|
resolve a list of tokens to an child object
|
[
"resolve",
"a",
"list",
"of",
"tokens",
"to",
"an",
"child",
"object"
] |
def resolve(self, ts):
""" resolve a list of tokens to an child object
:param list ts: list of tokens
"""
if isinstance(ts, six.string_types):
ts = [ts]
obj = self
while len(ts) > 0:
t = ts.pop(0)
if issubclass(obj.__class__, BaseObj):
obj = getattr(obj, t)
elif isinstance(obj, list):
obj = obj[int(t)]
elif isinstance(obj, dict):
obj = obj[t]
return obj
|
[
"def",
"resolve",
"(",
"self",
",",
"ts",
")",
":",
"if",
"isinstance",
"(",
"ts",
",",
"six",
".",
"string_types",
")",
":",
"ts",
"=",
"[",
"ts",
"]",
"obj",
"=",
"self",
"while",
"len",
"(",
"ts",
")",
">",
"0",
":",
"t",
"=",
"ts",
".",
"pop",
"(",
"0",
")",
"if",
"issubclass",
"(",
"obj",
".",
"__class__",
",",
"BaseObj",
")",
":",
"obj",
"=",
"getattr",
"(",
"obj",
",",
"t",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"obj",
"=",
"obj",
"[",
"int",
"(",
"t",
")",
"]",
"elif",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"obj",
"=",
"obj",
"[",
"t",
"]",
"return",
"obj"
] |
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/spec/base.py#L259-L278
|
|
caiiiac/Machine-Learning-with-Python
|
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
|
MachineLearning/venv/lib/python3.5/site-packages/pandas/core/dtypes/common.py
|
python
|
is_categorical
|
(arr)
|
return isinstance(arr, ABCCategorical) or is_categorical_dtype(arr)
|
Check whether an array-like is a Categorical instance.
Parameters
----------
arr : array-like
The array-like to check.
Returns
-------
boolean : Whether or not the array-like is of a Categorical instance.
Examples
--------
>>> is_categorical([1, 2, 3])
False
Categoricals, Series Categoricals, and CategoricalIndex will return True.
>>> cat = pd.Categorical([1, 2, 3])
>>> is_categorical(cat)
True
>>> is_categorical(pd.Series(cat))
True
>>> is_categorical(pd.CategoricalIndex([1, 2, 3]))
True
|
Check whether an array-like is a Categorical instance.
|
[
"Check",
"whether",
"an",
"array",
"-",
"like",
"is",
"a",
"Categorical",
"instance",
"."
] |
def is_categorical(arr):
"""
Check whether an array-like is a Categorical instance.
Parameters
----------
arr : array-like
The array-like to check.
Returns
-------
boolean : Whether or not the array-like is of a Categorical instance.
Examples
--------
>>> is_categorical([1, 2, 3])
False
Categoricals, Series Categoricals, and CategoricalIndex will return True.
>>> cat = pd.Categorical([1, 2, 3])
>>> is_categorical(cat)
True
>>> is_categorical(pd.Series(cat))
True
>>> is_categorical(pd.CategoricalIndex([1, 2, 3]))
True
"""
return isinstance(arr, ABCCategorical) or is_categorical_dtype(arr)
|
[
"def",
"is_categorical",
"(",
"arr",
")",
":",
"return",
"isinstance",
"(",
"arr",
",",
"ABCCategorical",
")",
"or",
"is_categorical_dtype",
"(",
"arr",
")"
] |
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/pandas/core/dtypes/common.py#L190-L219
|
|
OptMLGroup/VRP-RL
|
b794fb1e4c4bb70a62cfa54504ee7a247adbc2a0
|
VRP/vrp_utils.py
|
python
|
reward_func
|
(sample_solution)
|
return route_lens_decoded
|
The reward for the VRP task is defined as the
negative value of the route length
Args:
sample_solution : a list tensor of size decode_len of shape [batch_size x input_dim]
demands satisfied: a list tensor of size decode_len of shape [batch_size]
Returns:
rewards: tensor of size [batch_size]
Example:
sample_solution = [[[1,1],[2,2]],[[3,3],[4,4]],[[5,5],[6,6]]]
sourceL = 3
batch_size = 2
input_dim = 2
sample_solution_tilted[ [[5,5]
# [6,6]]
# [[1,1]
# [2,2]]
# [[3,3]
# [4,4]] ]
|
The reward for the VRP task is defined as the
negative value of the route length
|
[
"The",
"reward",
"for",
"the",
"VRP",
"task",
"is",
"defined",
"as",
"the",
"negative",
"value",
"of",
"the",
"route",
"length"
] |
def reward_func(sample_solution):
"""The reward for the VRP task is defined as the
negative value of the route length
Args:
sample_solution : a list tensor of size decode_len of shape [batch_size x input_dim]
demands satisfied: a list tensor of size decode_len of shape [batch_size]
Returns:
rewards: tensor of size [batch_size]
Example:
sample_solution = [[[1,1],[2,2]],[[3,3],[4,4]],[[5,5],[6,6]]]
sourceL = 3
batch_size = 2
input_dim = 2
sample_solution_tilted[ [[5,5]
# [6,6]]
# [[1,1]
# [2,2]]
# [[3,3]
# [4,4]] ]
"""
# make init_solution of shape [sourceL x batch_size x input_dim]
# make sample_solution of shape [sourceL x batch_size x input_dim]
sample_solution = tf.stack(sample_solution,0)
sample_solution_tilted = tf.concat((tf.expand_dims(sample_solution[-1],0),
sample_solution[:-1]),0)
# get the reward based on the route lengths
route_lens_decoded = tf.reduce_sum(tf.pow(tf.reduce_sum(tf.pow(\
(sample_solution_tilted - sample_solution) ,2), 2) , .5), 0)
return route_lens_decoded
|
[
"def",
"reward_func",
"(",
"sample_solution",
")",
":",
"# make init_solution of shape [sourceL x batch_size x input_dim]",
"# make sample_solution of shape [sourceL x batch_size x input_dim]",
"sample_solution",
"=",
"tf",
".",
"stack",
"(",
"sample_solution",
",",
"0",
")",
"sample_solution_tilted",
"=",
"tf",
".",
"concat",
"(",
"(",
"tf",
".",
"expand_dims",
"(",
"sample_solution",
"[",
"-",
"1",
"]",
",",
"0",
")",
",",
"sample_solution",
"[",
":",
"-",
"1",
"]",
")",
",",
"0",
")",
"# get the reward based on the route lengths",
"route_lens_decoded",
"=",
"tf",
".",
"reduce_sum",
"(",
"tf",
".",
"pow",
"(",
"tf",
".",
"reduce_sum",
"(",
"tf",
".",
"pow",
"(",
"(",
"sample_solution_tilted",
"-",
"sample_solution",
")",
",",
"2",
")",
",",
"2",
")",
",",
".5",
")",
",",
"0",
")",
"return",
"route_lens_decoded"
] |
https://github.com/OptMLGroup/VRP-RL/blob/b794fb1e4c4bb70a62cfa54504ee7a247adbc2a0/VRP/vrp_utils.py#L252-L288
|
|
Chaffelson/nipyapi
|
d3b186fd701ce308c2812746d98af9120955e810
|
nipyapi/nifi/models/remote_process_group_status_dto.py
|
python
|
RemoteProcessGroupStatusDTO.transmission_status
|
(self, transmission_status)
|
Sets the transmission_status of this RemoteProcessGroupStatusDTO.
The transmission status of the remote process group.
:param transmission_status: The transmission_status of this RemoteProcessGroupStatusDTO.
:type: str
|
Sets the transmission_status of this RemoteProcessGroupStatusDTO.
The transmission status of the remote process group.
|
[
"Sets",
"the",
"transmission_status",
"of",
"this",
"RemoteProcessGroupStatusDTO",
".",
"The",
"transmission",
"status",
"of",
"the",
"remote",
"process",
"group",
"."
] |
def transmission_status(self, transmission_status):
"""
Sets the transmission_status of this RemoteProcessGroupStatusDTO.
The transmission status of the remote process group.
:param transmission_status: The transmission_status of this RemoteProcessGroupStatusDTO.
:type: str
"""
self._transmission_status = transmission_status
|
[
"def",
"transmission_status",
"(",
"self",
",",
"transmission_status",
")",
":",
"self",
".",
"_transmission_status",
"=",
"transmission_status"
] |
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/remote_process_group_status_dto.py#L195-L204
|
||
zhl2008/awd-platform
|
0416b31abea29743387b10b3914581fbe8e7da5e
|
web_hxb2/lib/python3.5/site-packages/urllib3/packages/ordered_dict.py
|
python
|
OrderedDict.viewitems
|
(self)
|
return ItemsView(self)
|
od.viewitems() -> a set-like object providing a view on od's items
|
od.viewitems() -> a set-like object providing a view on od's items
|
[
"od",
".",
"viewitems",
"()",
"-",
">",
"a",
"set",
"-",
"like",
"object",
"providing",
"a",
"view",
"on",
"od",
"s",
"items"
] |
def viewitems(self):
"od.viewitems() -> a set-like object providing a view on od's items"
return ItemsView(self)
|
[
"def",
"viewitems",
"(",
"self",
")",
":",
"return",
"ItemsView",
"(",
"self",
")"
] |
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/urllib3/packages/ordered_dict.py#L257-L259
|
|
han1057578619/MachineLearning_Zhouzhihua_ProblemSets
|
00935f4216bc2441886a2d2abde5b90100910763
|
ch8--集成学习/8.3-AdaBoost.py
|
python
|
calcMinGiniIndex
|
(a, y, D)
|
return min_gini, min_gini_point
|
计算特征a下样本集y的的基尼指数
:param a: 单一特征值
:param y: 数据样本标签
:param D: 样本权重
:return:
|
计算特征a下样本集y的的基尼指数
:param a: 单一特征值
:param y: 数据样本标签
:param D: 样本权重
:return:
|
[
"计算特征a下样本集y的的基尼指数",
":",
"param",
"a",
":",
"单一特征值",
":",
"param",
"y",
":",
"数据样本标签",
":",
"param",
"D",
":",
"样本权重",
":",
"return",
":"
] |
def calcMinGiniIndex(a, y, D):
'''
计算特征a下样本集y的的基尼指数
:param a: 单一特征值
:param y: 数据样本标签
:param D: 样本权重
:return:
'''
feature = np.sort(a)
total_weight = np.sum(D)
split_points = [(feature[i] + feature[i + 1]) / 2 for i in range(feature.shape[0] - 1)]
min_gini = float('inf')
min_gini_point = None
for i in split_points:
yv1 = y[a <= i]
yv2 = y[a > i]
Dv1 = D[a <= i]
Dv2 = D[a > i]
gini_tmp = (np.sum(Dv1) * gini(yv1, Dv1) + np.sum(Dv2) * gini(yv2, Dv2)) / total_weight
if gini_tmp < min_gini:
min_gini = gini_tmp
min_gini_point = i
return min_gini, min_gini_point
|
[
"def",
"calcMinGiniIndex",
"(",
"a",
",",
"y",
",",
"D",
")",
":",
"feature",
"=",
"np",
".",
"sort",
"(",
"a",
")",
"total_weight",
"=",
"np",
".",
"sum",
"(",
"D",
")",
"split_points",
"=",
"[",
"(",
"feature",
"[",
"i",
"]",
"+",
"feature",
"[",
"i",
"+",
"1",
"]",
")",
"/",
"2",
"for",
"i",
"in",
"range",
"(",
"feature",
".",
"shape",
"[",
"0",
"]",
"-",
"1",
")",
"]",
"min_gini",
"=",
"float",
"(",
"'inf'",
")",
"min_gini_point",
"=",
"None",
"for",
"i",
"in",
"split_points",
":",
"yv1",
"=",
"y",
"[",
"a",
"<=",
"i",
"]",
"yv2",
"=",
"y",
"[",
"a",
">",
"i",
"]",
"Dv1",
"=",
"D",
"[",
"a",
"<=",
"i",
"]",
"Dv2",
"=",
"D",
"[",
"a",
">",
"i",
"]",
"gini_tmp",
"=",
"(",
"np",
".",
"sum",
"(",
"Dv1",
")",
"*",
"gini",
"(",
"yv1",
",",
"Dv1",
")",
"+",
"np",
".",
"sum",
"(",
"Dv2",
")",
"*",
"gini",
"(",
"yv2",
",",
"Dv2",
")",
")",
"/",
"total_weight",
"if",
"gini_tmp",
"<",
"min_gini",
":",
"min_gini",
"=",
"gini_tmp",
"min_gini_point",
"=",
"i",
"return",
"min_gini",
",",
"min_gini_point"
] |
https://github.com/han1057578619/MachineLearning_Zhouzhihua_ProblemSets/blob/00935f4216bc2441886a2d2abde5b90100910763/ch8--集成学习/8.3-AdaBoost.py#L33-L62
|
|
securesystemslab/zippy
|
ff0e84ac99442c2c55fe1d285332cfd4e185e089
|
zippy/benchmarks/src/benchmarks/sympy/sympy/physics/quantum/qft.py
|
python
|
IQFT.omega
|
(self)
|
return exp(-2*pi*I/self.size)
|
[] |
def omega(self):
return exp(-2*pi*I/self.size)
|
[
"def",
"omega",
"(",
"self",
")",
":",
"return",
"exp",
"(",
"-",
"2",
"*",
"pi",
"*",
"I",
"/",
"self",
".",
"size",
")"
] |
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/physics/quantum/qft.py#L211-L212
|
|||
Pymol-Scripts/Pymol-script-repo
|
bcd7bb7812dc6db1595953dfa4471fa15fb68c77
|
modules/pdb2pqr/src/topology.py
|
python
|
TopologyReference.__init__
|
(self, topologyResidue)
|
Initialize with a TopologyResidue object
|
Initialize with a TopologyResidue object
|
[
"Initialize",
"with",
"a",
"TopologyResidue",
"object"
] |
def __init__(self, topologyResidue):
""" Initialize with a TopologyResidue object """
self.topologyResidue = topologyResidue
self.topologyResidue.reference = self
self.atoms = []
self.dihedrals = []
|
[
"def",
"__init__",
"(",
"self",
",",
"topologyResidue",
")",
":",
"self",
".",
"topologyResidue",
"=",
"topologyResidue",
"self",
".",
"topologyResidue",
".",
"reference",
"=",
"self",
"self",
".",
"atoms",
"=",
"[",
"]",
"self",
".",
"dihedrals",
"=",
"[",
"]"
] |
https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/modules/pdb2pqr/src/topology.py#L318-L323
|
||
edisonlz/fastor
|
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
|
base/site-packages/requests/utils.py
|
python
|
dict_to_sequence
|
(d)
|
return d
|
Returns an internal sequence dictionary update.
|
Returns an internal sequence dictionary update.
|
[
"Returns",
"an",
"internal",
"sequence",
"dictionary",
"update",
"."
] |
def dict_to_sequence(d):
"""Returns an internal sequence dictionary update."""
if hasattr(d, 'items'):
d = d.items()
return d
|
[
"def",
"dict_to_sequence",
"(",
"d",
")",
":",
"if",
"hasattr",
"(",
"d",
",",
"'items'",
")",
":",
"d",
"=",
"d",
".",
"items",
"(",
")",
"return",
"d"
] |
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/requests/utils.py#L41-L47
|
|
googleads/google-ads-python
|
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
|
google/ads/googleads/v9/services/services/domain_category_service/client.py
|
python
|
DomainCategoryServiceClientMeta.get_transport_class
|
(
cls, label: str = None,
)
|
return next(iter(cls._transport_registry.values()))
|
Return an appropriate transport class.
Args:
label: The name of the desired transport. If none is
provided, then the first transport in the registry is used.
Returns:
The transport class to use.
|
Return an appropriate transport class.
|
[
"Return",
"an",
"appropriate",
"transport",
"class",
"."
] |
def get_transport_class(
cls, label: str = None,
) -> Type[DomainCategoryServiceTransport]:
"""Return an appropriate transport class.
Args:
label: The name of the desired transport. If none is
provided, then the first transport in the registry is used.
Returns:
The transport class to use.
"""
# If a specific transport is requested, return that one.
if label:
return cls._transport_registry[label]
# No transport is requested; return the default (that is, the first one
# in the dictionary).
return next(iter(cls._transport_registry.values()))
|
[
"def",
"get_transport_class",
"(",
"cls",
",",
"label",
":",
"str",
"=",
"None",
",",
")",
"->",
"Type",
"[",
"DomainCategoryServiceTransport",
"]",
":",
"# If a specific transport is requested, return that one.",
"if",
"label",
":",
"return",
"cls",
".",
"_transport_registry",
"[",
"label",
"]",
"# No transport is requested; return the default (that is, the first one",
"# in the dictionary).",
"return",
"next",
"(",
"iter",
"(",
"cls",
".",
"_transport_registry",
".",
"values",
"(",
")",
")",
")"
] |
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v9/services/services/domain_category_service/client.py#L54-L72
|
|
marchtea/scrapy_doc_chs
|
5ed032cffed0f2c23a188f0b13b0c9ef9e228a22
|
topics/src_used/scrapy-ws.py
|
python
|
cmd_get_spider_stats
|
(args, opts)
|
get-spider-stats <spider> - get stats of a running spider
|
get-spider-stats <spider> - get stats of a running spider
|
[
"get",
"-",
"spider",
"-",
"stats",
"<spider",
">",
"-",
"get",
"stats",
"of",
"a",
"running",
"spider"
] |
def cmd_get_spider_stats(args, opts):
"""get-spider-stats <spider> - get stats of a running spider"""
stats = jsonrpc_call(opts, 'stats', 'get_stats', args[0])
for name, value in stats.items():
print("%-40s %s" % (name, value))
|
[
"def",
"cmd_get_spider_stats",
"(",
"args",
",",
"opts",
")",
":",
"stats",
"=",
"jsonrpc_call",
"(",
"opts",
",",
"'stats'",
",",
"'get_stats'",
",",
"args",
"[",
"0",
"]",
")",
"for",
"name",
",",
"value",
"in",
"stats",
".",
"items",
"(",
")",
":",
"print",
"(",
"\"%-40s %s\"",
"%",
"(",
"name",
",",
"value",
")",
")"
] |
https://github.com/marchtea/scrapy_doc_chs/blob/5ed032cffed0f2c23a188f0b13b0c9ef9e228a22/topics/src_used/scrapy-ws.py#L56-L60
|
||
numenta/nupic
|
b9ebedaf54f49a33de22d8d44dff7c765cdb5548
|
external/linux32/lib/python2.6/site-packages/matplotlib/ticker.py
|
python
|
Base.le
|
(self, x)
|
return d*self._base
|
return the largest multiple of base <= x
|
return the largest multiple of base <= x
|
[
"return",
"the",
"largest",
"multiple",
"of",
"base",
"<",
"=",
"x"
] |
def le(self, x):
'return the largest multiple of base <= x'
d,m = divmod(x, self._base)
if closeto(m/self._base,1): # was closeto(m, self._base)
#looks like floating point error
return (d+1)*self._base
return d*self._base
|
[
"def",
"le",
"(",
"self",
",",
"x",
")",
":",
"d",
",",
"m",
"=",
"divmod",
"(",
"x",
",",
"self",
".",
"_base",
")",
"if",
"closeto",
"(",
"m",
"/",
"self",
".",
"_base",
",",
"1",
")",
":",
"# was closeto(m, self._base)",
"#looks like floating point error",
"return",
"(",
"d",
"+",
"1",
")",
"*",
"self",
".",
"_base",
"return",
"d",
"*",
"self",
".",
"_base"
] |
https://github.com/numenta/nupic/blob/b9ebedaf54f49a33de22d8d44dff7c765cdb5548/external/linux32/lib/python2.6/site-packages/matplotlib/ticker.py#L822-L828
|
|
skylander86/lambda-text-extractor
|
6da52d077a2fc571e38bfe29c33ae68f6443cd5a
|
functions/ocr/pyparsing.py
|
python
|
ParserElement.__call__
|
(self, name=None)
|
Shortcut for C{L{setResultsName}}, with C{listAllMatches=False}.
If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be
passed as C{True}.
If C{name} is omitted, same as calling C{L{copy}}.
Example::
# these are equivalent
userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno")
userdata = Word(alphas)("name") + Word(nums+"-")("socsecno")
|
Shortcut for C{L{setResultsName}}, with C{listAllMatches=False}.
If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be
passed as C{True}.
If C{name} is omitted, same as calling C{L{copy}}.
|
[
"Shortcut",
"for",
"C",
"{",
"L",
"{",
"setResultsName",
"}}",
"with",
"C",
"{",
"listAllMatches",
"=",
"False",
"}",
".",
"If",
"C",
"{",
"name",
"}",
"is",
"given",
"with",
"a",
"trailing",
"C",
"{",
"*",
"}",
"character",
"then",
"C",
"{",
"listAllMatches",
"}",
"will",
"be",
"passed",
"as",
"C",
"{",
"True",
"}",
".",
"If",
"C",
"{",
"name",
"}",
"is",
"omitted",
"same",
"as",
"calling",
"C",
"{",
"L",
"{",
"copy",
"}}",
"."
] |
def __call__(self, name=None):
"""
Shortcut for C{L{setResultsName}}, with C{listAllMatches=False}.
If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be
passed as C{True}.
If C{name} is omitted, same as calling C{L{copy}}.
Example::
# these are equivalent
userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno")
userdata = Word(alphas)("name") + Word(nums+"-")("socsecno")
"""
if name is not None:
return self.setResultsName(name)
else:
return self.copy()
|
[
"def",
"__call__",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"not",
"None",
":",
"return",
"self",
".",
"setResultsName",
"(",
"name",
")",
"else",
":",
"return",
"self",
".",
"copy",
"(",
")"
] |
https://github.com/skylander86/lambda-text-extractor/blob/6da52d077a2fc571e38bfe29c33ae68f6443cd5a/functions/ocr/pyparsing.py#L2004-L2021
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.