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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Source-Python-Dev-Team/Source.Python | d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb | addons/source-python/packages/source-python/memory/manager.py | python | TypeManager.unregister_converter | (self, name) | Unregister a converter. | Unregister a converter. | [
"Unregister",
"a",
"converter",
"."
] | def unregister_converter(self, name):
"""Unregister a converter."""
self.converters.pop(name, None) | [
"def",
"unregister_converter",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"converters",
".",
"pop",
"(",
"name",
",",
"None",
")"
] | https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/source-python/memory/manager.py#L234-L236 | ||
chribsen/simple-machine-learning-examples | dc94e52a4cebdc8bb959ff88b81ff8cfeca25022 | venv/lib/python2.7/site-packages/numpy/ma/timer_comparison.py | python | ModuleTester.test_4 | (self) | Test of take, transpose, inner, outer products. | Test of take, transpose, inner, outer products. | [
"Test",
"of",
"take",
"transpose",
"inner",
"outer",
"products",
"."
] | def test_4(self):
"""
Test of take, transpose, inner, outer products.
"""
x = self.arange(24)
y = np.arange(24)
x[5:6] = self.masked
x = x.reshape(2, 3, 4)
y = y.reshape(2, 3, 4)
assert self.allequal(np.transpose(y, (2, 0, 1)), self.transpose(x, (2, 0, 1)))
assert self.allequal(np.take(y, (2, 0, 1), 1), self.take(x, (2, 0, 1), 1))
assert self.allequal(np.inner(self.filled(x, 0), self.filled(y, 0)),
self.inner(x, y))
assert self.allequal(np.outer(self.filled(x, 0), self.filled(y, 0)),
self.outer(x, y))
y = self.array(['abc', 1, 'def', 2, 3], object)
y[2] = self.masked
t = self.take(y, [0, 3, 4])
assert t[0] == 'abc'
assert t[1] == 2
assert t[2] == 3 | [
"def",
"test_4",
"(",
"self",
")",
":",
"x",
"=",
"self",
".",
"arange",
"(",
"24",
")",
"y",
"=",
"np",
".",
"arange",
"(",
"24",
")",
"x",
"[",
"5",
":",
"6",
"]",
"=",
"self",
".",
"masked",
"x",
"=",
"x",
".",
"reshape",
"(",
"2",
","... | https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/numpy/ma/timer_comparison.py#L215-L236 | ||
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/setuptools/command/build_py.py | python | build_py.build_package_data | (self) | Copy data files into build directory | Copy data files into build directory | [
"Copy",
"data",
"files",
"into",
"build",
"directory"
] | def build_package_data(self):
"""Copy data files into build directory"""
for package, src_dir, build_dir, filenames in self.data_files:
for filename in filenames:
target = os.path.join(build_dir, filename)
self.mkpath(os.path.dirname(target))
srcfile = os.path.join(src_dir, filename)
outf, copied = self.copy_file(srcfile, target)
srcfile = os.path.abspath(srcfile)
if (copied and
srcfile in self.distribution.convert_2to3_doctests):
self.__doctests_2to3.append(outf) | [
"def",
"build_package_data",
"(",
"self",
")",
":",
"for",
"package",
",",
"src_dir",
",",
"build_dir",
",",
"filenames",
"in",
"self",
".",
"data_files",
":",
"for",
"filename",
"in",
"filenames",
":",
"target",
"=",
"os",
".",
"path",
".",
"join",
"(",... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/setuptools/command/build_py.py#L116-L127 | ||
misterch0c/shadowbroker | e3a069bea47a2c1009697941ac214adc6f90aa8d | windows/Resources/Python/Core/Lib/mailbox.py | python | MaildirMessage.set_date | (self, date) | Set delivery date of message, in seconds since the epoch. | Set delivery date of message, in seconds since the epoch. | [
"Set",
"delivery",
"date",
"of",
"message",
"in",
"seconds",
"since",
"the",
"epoch",
"."
] | def set_date(self, date):
"""Set delivery date of message, in seconds since the epoch."""
try:
self._date = float(date)
except ValueError:
raise TypeError("can't convert to float: %s" % date) | [
"def",
"set_date",
"(",
"self",
",",
"date",
")",
":",
"try",
":",
"self",
".",
"_date",
"=",
"float",
"(",
"date",
")",
"except",
"ValueError",
":",
"raise",
"TypeError",
"(",
"\"can't convert to float: %s\"",
"%",
"date",
")"
] | https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/mailbox.py#L1472-L1477 | ||
autotest/autotest | 4614ae5f550cc888267b9a419e4b90deb54f8fae | server/setup.py | python | _get_files | (path) | return flist | Given a path, return all the files in there to package | Given a path, return all the files in there to package | [
"Given",
"a",
"path",
"return",
"all",
"the",
"files",
"in",
"there",
"to",
"package"
] | def _get_files(path):
'''
Given a path, return all the files in there to package
'''
flist = []
for root, _, files in sorted(os.walk(path)):
for name in files:
fullname = os.path.join(root, name)
flist.append(fullname)
return flist | [
"def",
"_get_files",
"(",
"path",
")",
":",
"flist",
"=",
"[",
"]",
"for",
"root",
",",
"_",
",",
"files",
"in",
"sorted",
"(",
"os",
".",
"walk",
"(",
"path",
")",
")",
":",
"for",
"name",
"in",
"files",
":",
"fullname",
"=",
"os",
".",
"path"... | https://github.com/autotest/autotest/blob/4614ae5f550cc888267b9a419e4b90deb54f8fae/server/setup.py#L19-L28 | |
rossant/ipymd | d87c9ebc59d67fe78b0139ee00e0e5307682e303 | ipymd/ext/six.py | python | add_move | (move) | Add an item to six.moves. | Add an item to six.moves. | [
"Add",
"an",
"item",
"to",
"six",
".",
"moves",
"."
] | def add_move(move):
"""Add an item to six.moves."""
setattr(_MovedItems, move.name, move) | [
"def",
"add_move",
"(",
"move",
")",
":",
"setattr",
"(",
"_MovedItems",
",",
"move",
".",
"name",
",",
"move",
")"
] | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/ext/six.py#L469-L471 | ||
wistbean/learn_python3_spider | 73c873f4845f4385f097e5057407d03dd37a117b | stackoverflow/venv/lib/python3.6/site-packages/scrapy/shell.py | python | _request_deferred | (request) | return d | Wrap a request inside a Deferred.
This function is harmful, do not use it until you know what you are doing.
This returns a Deferred whose first pair of callbacks are the request
callback and errback. The Deferred also triggers when the request
callback/errback is executed (ie. when the request is downloaded)
WARNING: Do not call request.replace() until after the deferred is called. | Wrap a request inside a Deferred. | [
"Wrap",
"a",
"request",
"inside",
"a",
"Deferred",
"."
] | def _request_deferred(request):
"""Wrap a request inside a Deferred.
This function is harmful, do not use it until you know what you are doing.
This returns a Deferred whose first pair of callbacks are the request
callback and errback. The Deferred also triggers when the request
callback/errback is executed (ie. when the request is downloaded)
WARNING: Do not call request.replace() until after the deferred is called.
"""
request_callback = request.callback
request_errback = request.errback
def _restore_callbacks(result):
request.callback = request_callback
request.errback = request_errback
return result
d = defer.Deferred()
d.addBoth(_restore_callbacks)
if request.callback:
d.addCallbacks(request.callback, request.errback)
request.callback, request.errback = d.callback, d.errback
return d | [
"def",
"_request_deferred",
"(",
"request",
")",
":",
"request_callback",
"=",
"request",
".",
"callback",
"request_errback",
"=",
"request",
".",
"errback",
"def",
"_restore_callbacks",
"(",
"result",
")",
":",
"request",
".",
"callback",
"=",
"request_callback",... | https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/scrapy/shell.py#L170-L195 | |
GRAAL-Research/domain_adversarial_neural_network | 74eec5e0ae06bd6614bce048abba492c16a633e3 | DANN.py | python | DANN.predict_domain | (self, X) | return np.array(output_layer < .5, dtype=int) | Compute and return the domain predictions for X, i.e., a 1D array of size len(X).
the ith row of the array contains the predicted domain (0 or 1) for the ith example. | Compute and return the domain predictions for X, i.e., a 1D array of size len(X).
the ith row of the array contains the predicted domain (0 or 1) for the ith example. | [
"Compute",
"and",
"return",
"the",
"domain",
"predictions",
"for",
"X",
"i",
".",
"e",
".",
"a",
"1D",
"array",
"of",
"size",
"len",
"(",
"X",
")",
".",
"the",
"ith",
"row",
"of",
"the",
"array",
"contains",
"the",
"predicted",
"domain",
"(",
"0",
... | def predict_domain(self, X):
"""
Compute and return the domain predictions for X, i.e., a 1D array of size len(X).
the ith row of the array contains the predicted domain (0 or 1) for the ith example.
"""
hidden_layer = self.sigmoid(np.dot(self.W, X.T) + self.b[:, np.newaxis])
output_layer = self.sigmoid(np.dot(self.U, hidden_layer) + self.d)
return np.array(output_layer < .5, dtype=int) | [
"def",
"predict_domain",
"(",
"self",
",",
"X",
")",
":",
"hidden_layer",
"=",
"self",
".",
"sigmoid",
"(",
"np",
".",
"dot",
"(",
"self",
".",
"W",
",",
"X",
".",
"T",
")",
"+",
"self",
".",
"b",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
")"... | https://github.com/GRAAL-Research/domain_adversarial_neural_network/blob/74eec5e0ae06bd6614bce048abba492c16a633e3/DANN.py#L203-L210 | |
awslabs/gluon-ts | 066ec3b7f47aa4ee4c061a28f35db7edbad05a98 | src/gluonts/mx/distribution/bijection.py | python | Bijection.log_abs_det_jac | (self, x: Tensor, y: Tensor) | r"""
Receives (x, y) and returns log of the absolute value of the Jacobian
determinant
.. math::
\log |dy/dx|
Note that this is the Jacobian determinant of the forward
transformation x -> y. | r"""
Receives (x, y) and returns log of the absolute value of the Jacobian
determinant | [
"r",
"Receives",
"(",
"x",
"y",
")",
"and",
"returns",
"log",
"of",
"the",
"absolute",
"value",
"of",
"the",
"Jacobian",
"determinant"
] | def log_abs_det_jac(self, x: Tensor, y: Tensor) -> Tensor:
r"""
Receives (x, y) and returns log of the absolute value of the Jacobian
determinant
.. math::
\log |dy/dx|
Note that this is the Jacobian determinant of the forward
transformation x -> y.
"""
raise NotImplementedError | [
"def",
"log_abs_det_jac",
"(",
"self",
",",
"x",
":",
"Tensor",
",",
"y",
":",
"Tensor",
")",
"->",
"Tensor",
":",
"raise",
"NotImplementedError"
] | https://github.com/awslabs/gluon-ts/blob/066ec3b7f47aa4ee4c061a28f35db7edbad05a98/src/gluonts/mx/distribution/bijection.py#L49-L60 | ||
PMEAL/OpenPNM | c9514b858d1361b2090b2f9579280cbcd476c9b0 | openpnm/models/physics/source_terms.py | python | linear | (target, X, A1='', A2='') | return values | r"""
Calculates the rate, as well as slope and intercept of the following
function at the given value of ``X``:
.. math::
r = A_{1} X + A_{2}
Parameters
----------
%(target_blurb)s
X : str
The dictionary key on the target object containing the the quantity
of interest
A1 -> A2 : str
The dictionary keys on the target object containing the coefficients
values to be used in the source term model
Returns
-------
dict
A dictionary containing the following three items:
'rate'
The value of the source term function at the given X.
'S1'
The slope of the source term function at the given X.
'S2'
The intercept of the source term function at the given X.
Notes
-----
The slope and intercept provide a linearized source term equation about the
current value of X as follow:
.. math::
rate = S_{1} X + S_{2} | r"""
Calculates the rate, as well as slope and intercept of the following
function at the given value of ``X``: | [
"r",
"Calculates",
"the",
"rate",
"as",
"well",
"as",
"slope",
"and",
"intercept",
"of",
"the",
"following",
"function",
"at",
"the",
"given",
"value",
"of",
"X",
":"
] | def linear(target, X, A1='', A2=''):
r"""
Calculates the rate, as well as slope and intercept of the following
function at the given value of ``X``:
.. math::
r = A_{1} X + A_{2}
Parameters
----------
%(target_blurb)s
X : str
The dictionary key on the target object containing the the quantity
of interest
A1 -> A2 : str
The dictionary keys on the target object containing the coefficients
values to be used in the source term model
Returns
-------
dict
A dictionary containing the following three items:
'rate'
The value of the source term function at the given X.
'S1'
The slope of the source term function at the given X.
'S2'
The intercept of the source term function at the given X.
Notes
-----
The slope and intercept provide a linearized source term equation about the
current value of X as follow:
.. math::
rate = S_{1} X + S_{2}
"""
A = _parse_args(target=target, key=A1, default=0.0)
B = _parse_args(target=target, key=A2, default=0.0)
X = target[X]
r = A * X + B
S1 = A
S2 = B
values = {'S1': S1, 'S2': S2, 'rate': r}
return values | [
"def",
"linear",
"(",
"target",
",",
"X",
",",
"A1",
"=",
"''",
",",
"A2",
"=",
"''",
")",
":",
"A",
"=",
"_parse_args",
"(",
"target",
"=",
"target",
",",
"key",
"=",
"A1",
",",
"default",
"=",
"0.0",
")",
"B",
"=",
"_parse_args",
"(",
"target... | https://github.com/PMEAL/OpenPNM/blob/c9514b858d1361b2090b2f9579280cbcd476c9b0/openpnm/models/physics/source_terms.py#L165-L212 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/Python-2.7.9/Tools/webchecker/wcgui.py | python | CheckerWindow.go | (self) | [] | def go(self):
if self.__running:
self.__parent.after_idle(self.dosomething)
else:
self.__checking.config(text="Idle")
self.__start.config(state=NORMAL, relief=RAISED)
self.__stop.config(state=DISABLED, relief=RAISED)
self.__step.config(state=NORMAL, relief=RAISED) | [
"def",
"go",
"(",
"self",
")",
":",
"if",
"self",
".",
"__running",
":",
"self",
".",
"__parent",
".",
"after_idle",
"(",
"self",
".",
"dosomething",
")",
"else",
":",
"self",
".",
"__checking",
".",
"config",
"(",
"text",
"=",
"\"Idle\"",
")",
"self... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Tools/webchecker/wcgui.py#L219-L226 | ||||
out0fmemory/GoAgent-Always-Available | c4254984fea633ce3d1893fe5901debd9f22c2a9 | server/lib/google/appengine/ext/ndb/model.py | python | Model._get_or_insert_async | (*args, **kwds) | return internal_tasklet() | Transactionally retrieves an existing entity or creates a new one.
This is the asynchronous version of Model._get_or_insert(). | Transactionally retrieves an existing entity or creates a new one. | [
"Transactionally",
"retrieves",
"an",
"existing",
"entity",
"or",
"creates",
"a",
"new",
"one",
"."
] | def _get_or_insert_async(*args, **kwds):
"""Transactionally retrieves an existing entity or creates a new one.
This is the asynchronous version of Model._get_or_insert().
"""
# NOTE: The signature is really weird here because we want to support
# models with properties named e.g. 'cls' or 'name'.
from . import tasklets
cls, name = args # These must always be positional.
get_arg = cls.__get_arg
app = get_arg(kwds, 'app')
namespace = get_arg(kwds, 'namespace')
parent = get_arg(kwds, 'parent')
context_options = get_arg(kwds, 'context_options')
# (End of super-special argument parsing.)
# TODO: Test the heck out of this, in all sorts of evil scenarios.
if not isinstance(name, basestring):
raise TypeError('name must be a string; received %r' % name)
elif not name:
raise ValueError('name cannot be an empty string.')
key = Key(cls, name, app=app, namespace=namespace, parent=parent)
@tasklets.tasklet
def internal_tasklet():
@tasklets.tasklet
def txn():
ent = yield key.get_async(options=context_options)
if ent is None:
ent = cls(**kwds) # TODO: Use _populate().
ent._key = key
yield ent.put_async(options=context_options)
raise tasklets.Return(ent)
if in_transaction():
# Run txn() in existing transaction.
ent = yield txn()
else:
# Maybe avoid a transaction altogether.
ent = yield key.get_async(options=context_options)
if ent is None:
# Run txn() in new transaction.
ent = yield transaction_async(txn)
raise tasklets.Return(ent)
return internal_tasklet() | [
"def",
"_get_or_insert_async",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"# NOTE: The signature is really weird here because we want to support",
"# models with properties named e.g. 'cls' or 'name'.",
"from",
".",
"import",
"tasklets",
"cls",
",",
"name",
"=",
"ar... | https://github.com/out0fmemory/GoAgent-Always-Available/blob/c4254984fea633ce3d1893fe5901debd9f22c2a9/server/lib/google/appengine/ext/ndb/model.py#L3500-L3543 | |
log2timeline/plaso | fe2e316b8c76a0141760c0f2f181d84acb83abc2 | plaso/multi_process/engine.py | python | MultiProcessEngine._QueryProcessStatus | (self, process) | return process_status | Queries a process to determine its status.
Args:
process (MultiProcessBaseProcess): process to query for its status.
Returns:
dict[str, str]: status values received from the worker process. | Queries a process to determine its status. | [
"Queries",
"a",
"process",
"to",
"determine",
"its",
"status",
"."
] | def _QueryProcessStatus(self, process):
"""Queries a process to determine its status.
Args:
process (MultiProcessBaseProcess): process to query for its status.
Returns:
dict[str, str]: status values received from the worker process.
"""
process_is_alive = process.is_alive()
if process_is_alive:
rpc_client = self._rpc_clients_per_pid.get(process.pid, None)
process_status = rpc_client.CallFunction()
else:
process_status = None
return process_status | [
"def",
"_QueryProcessStatus",
"(",
"self",
",",
"process",
")",
":",
"process_is_alive",
"=",
"process",
".",
"is_alive",
"(",
")",
"if",
"process_is_alive",
":",
"rpc_client",
"=",
"self",
".",
"_rpc_clients_per_pid",
".",
"get",
"(",
"process",
".",
"pid",
... | https://github.com/log2timeline/plaso/blob/fe2e316b8c76a0141760c0f2f181d84acb83abc2/plaso/multi_process/engine.py#L210-L225 | |
web2py/web2py | 095905c4e010a1426c729483d912e270a51b7ba8 | gluon/utils.py | python | initialize_urandom | () | return unpacked_ctokens, have_urandom | This function and the web2py_uuid follow from the following discussion:
`http://groups.google.com/group/web2py-developers/browse_thread/thread/7fd5789a7da3f09`
At startup web2py compute a unique ID that identifies the machine by adding
uuid.getnode() + int(time.time() * 1e3)
This is a 48-bit number. It converts the number into 16 8-bit tokens.
It uses this value to initialize the entropy source ('/dev/urandom') and to seed random.
If os.random() is not supported, it falls back to using random and issues a warning. | This function and the web2py_uuid follow from the following discussion:
`http://groups.google.com/group/web2py-developers/browse_thread/thread/7fd5789a7da3f09` | [
"This",
"function",
"and",
"the",
"web2py_uuid",
"follow",
"from",
"the",
"following",
"discussion",
":",
"http",
":",
"//",
"groups",
".",
"google",
".",
"com",
"/",
"group",
"/",
"web2py",
"-",
"developers",
"/",
"browse_thread",
"/",
"thread",
"/",
"7fd... | def initialize_urandom():
"""
This function and the web2py_uuid follow from the following discussion:
`http://groups.google.com/group/web2py-developers/browse_thread/thread/7fd5789a7da3f09`
At startup web2py compute a unique ID that identifies the machine by adding
uuid.getnode() + int(time.time() * 1e3)
This is a 48-bit number. It converts the number into 16 8-bit tokens.
It uses this value to initialize the entropy source ('/dev/urandom') and to seed random.
If os.random() is not supported, it falls back to using random and issues a warning.
"""
node_id = uuid.getnode()
microseconds = int(time.time() * 1e6)
ctokens = [((node_id + microseconds) >> ((i % 6) * 8)) %
256 for i in range(16)]
random.seed(node_id + microseconds)
try:
os.urandom(1)
have_urandom = True
if sys.platform != 'win32':
try:
# try to add process-specific entropy
frandom = open('/dev/urandom', 'wb')
try:
if PY2:
frandom.write(''.join(chr(t) for t in ctokens))
else:
frandom.write(bytes([]).join(bytes([t]) for t in ctokens))
finally:
frandom.close()
except IOError:
# works anyway
pass
except NotImplementedError:
have_urandom = False
logger.warning(
"""Cryptographically secure session management is not possible on your system because
your system does not provide a cryptographically secure entropy source.
This is not specific to web2py; consider deploying on a different operating system.""")
if PY2:
packed = ''.join(chr(x) for x in ctokens)
else:
packed = bytes([]).join(bytes([x]) for x in ctokens)
unpacked_ctokens = _struct_2_long_long.unpack(packed)
return unpacked_ctokens, have_urandom | [
"def",
"initialize_urandom",
"(",
")",
":",
"node_id",
"=",
"uuid",
".",
"getnode",
"(",
")",
"microseconds",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
"*",
"1e6",
")",
"ctokens",
"=",
"[",
"(",
"(",
"node_id",
"+",
"microseconds",
")",
">>",
... | https://github.com/web2py/web2py/blob/095905c4e010a1426c729483d912e270a51b7ba8/gluon/utils.py#L216-L262 | |
beancount/beancount | cb3526a1af95b3b5be70347470c381b5a86055fe | beancount/query/shell.py | python | DispatchingShell.dispatch | (self, statement) | Dispatch the given statement to a suitable method.
Args:
statement: An instance provided by the parser.
Returns:
Whatever the invoked method happens to return. | Dispatch the given statement to a suitable method. | [
"Dispatch",
"the",
"given",
"statement",
"to",
"a",
"suitable",
"method",
"."
] | def dispatch(self, statement):
"""Dispatch the given statement to a suitable method.
Args:
statement: An instance provided by the parser.
Returns:
Whatever the invoked method happens to return.
"""
try:
method = getattr(self, 'on_{}'.format(type(statement).__name__))
except AttributeError:
print("Internal error: statement '{}' is unsupported.".format(statement),
file=self.outfile)
else:
return method(statement) | [
"def",
"dispatch",
"(",
"self",
",",
"statement",
")",
":",
"try",
":",
"method",
"=",
"getattr",
"(",
"self",
",",
"'on_{}'",
".",
"format",
"(",
"type",
"(",
"statement",
")",
".",
"__name__",
")",
")",
"except",
"AttributeError",
":",
"print",
"(",
... | https://github.com/beancount/beancount/blob/cb3526a1af95b3b5be70347470c381b5a86055fe/beancount/query/shell.py#L237-L251 | ||
twilio/twilio-python | 6e1e811ea57a1edfadd5161ace87397c563f6915 | twilio/rest/insights/v1/call/summary.py | python | CallSummaryInstance.url | (self) | return self._properties['url'] | :returns: The url
:rtype: unicode | :returns: The url
:rtype: unicode | [
":",
"returns",
":",
"The",
"url",
":",
"rtype",
":",
"unicode"
] | def url(self):
"""
:returns: The url
:rtype: unicode
"""
return self._properties['url'] | [
"def",
"url",
"(",
"self",
")",
":",
"return",
"self",
".",
"_properties",
"[",
"'url'",
"]"
] | https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/insights/v1/call/summary.py#L355-L360 | |
keikoproj/minion-manager | c4e89a5c4614f86f0e58acb919bb99cd9122c897 | cloud_provider/aws/asg_mm.py | python | AWSAutoscalinGroupMM.get_instance_info | (self) | return self.instance_info | Returns the instances. | Returns the instances. | [
"Returns",
"the",
"instances",
"."
] | def get_instance_info(self):
""" Returns the instances. """
return self.instance_info | [
"def",
"get_instance_info",
"(",
"self",
")",
":",
"return",
"self",
".",
"instance_info"
] | https://github.com/keikoproj/minion-manager/blob/c4e89a5c4614f86f0e58acb919bb99cd9122c897/cloud_provider/aws/asg_mm.py#L76-L78 | |
khanhnamle1994/natural-language-processing | 01d450d5ac002b0156ef4cf93a07cb508c1bcdc5 | assignment1/.env/lib/python2.7/site-packages/scipy/interpolate/interpolate.py | python | PPoly.from_bernstein_basis | (cls, bp, extrapolate=None) | return cls.construct_fast(c, bp.x, extrapolate) | Construct a piecewise polynomial in the power basis
from a polynomial in Bernstein basis.
Parameters
----------
bp : BPoly
A Bernstein basis polynomial, as created by BPoly
extrapolate : bool, optional
Whether to extrapolate to ouf-of-bounds points based on first
and last intervals, or to return NaNs. Default: True. | Construct a piecewise polynomial in the power basis
from a polynomial in Bernstein basis. | [
"Construct",
"a",
"piecewise",
"polynomial",
"in",
"the",
"power",
"basis",
"from",
"a",
"polynomial",
"in",
"Bernstein",
"basis",
"."
] | def from_bernstein_basis(cls, bp, extrapolate=None):
"""
Construct a piecewise polynomial in the power basis
from a polynomial in Bernstein basis.
Parameters
----------
bp : BPoly
A Bernstein basis polynomial, as created by BPoly
extrapolate : bool, optional
Whether to extrapolate to ouf-of-bounds points based on first
and last intervals, or to return NaNs. Default: True.
"""
dx = np.diff(bp.x)
k = bp.c.shape[0] - 1 # polynomial order
rest = (None,)*(bp.c.ndim-2)
c = np.zeros_like(bp.c)
for a in range(k+1):
factor = (-1)**(a) * comb(k, a) * bp.c[a]
for s in range(a, k+1):
val = comb(k-a, s-a) * (-1)**s
c[k-s] += factor * val / dx[(slice(None),)+rest]**s
if extrapolate is None:
extrapolate = bp.extrapolate
return cls.construct_fast(c, bp.x, extrapolate) | [
"def",
"from_bernstein_basis",
"(",
"cls",
",",
"bp",
",",
"extrapolate",
"=",
"None",
")",
":",
"dx",
"=",
"np",
".",
"diff",
"(",
"bp",
".",
"x",
")",
"k",
"=",
"bp",
".",
"c",
".",
"shape",
"[",
"0",
"]",
"-",
"1",
"# polynomial order",
"rest"... | https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/scipy/interpolate/interpolate.py#L959-L988 | |
yqyao/FCOS_PLUS | 0d20ba34ccc316650d8c30febb2eb40cb6eaae37 | maskrcnn_benchmark/modeling/roi_heads/mask_head/loss.py | python | MaskRCNNLossComputation.__init__ | (self, proposal_matcher, discretization_size) | Arguments:
proposal_matcher (Matcher)
discretization_size (int) | Arguments:
proposal_matcher (Matcher)
discretization_size (int) | [
"Arguments",
":",
"proposal_matcher",
"(",
"Matcher",
")",
"discretization_size",
"(",
"int",
")"
] | def __init__(self, proposal_matcher, discretization_size):
"""
Arguments:
proposal_matcher (Matcher)
discretization_size (int)
"""
self.proposal_matcher = proposal_matcher
self.discretization_size = discretization_size | [
"def",
"__init__",
"(",
"self",
",",
"proposal_matcher",
",",
"discretization_size",
")",
":",
"self",
".",
"proposal_matcher",
"=",
"proposal_matcher",
"self",
".",
"discretization_size",
"=",
"discretization_size"
] | https://github.com/yqyao/FCOS_PLUS/blob/0d20ba34ccc316650d8c30febb2eb40cb6eaae37/maskrcnn_benchmark/modeling/roi_heads/mask_head/loss.py#L46-L53 | ||
oilshell/oil | 94388e7d44a9ad879b12615f6203b38596b5a2d3 | Python-2.7.13/Tools/faqwiz/faqwiz.py | python | FaqWizard.do_recent | (self) | [] | def do_recent(self):
if not self.ui.days:
days = 1
else:
days = float(self.ui.days)
try:
cutoff = now - days * 24 * 3600
except OverflowError:
cutoff = 0
list = []
for file in self.dir.list():
entry = self.dir.open(file)
if not entry:
continue
mtime = entry.getmtime()
if mtime >= cutoff:
list.append((mtime, file))
list.sort()
list.reverse()
self.prologue(T_RECENT)
if days <= 1:
period = "%.2g hours" % (days*24)
else:
period = "%.6g days" % days
if not list:
emit(NO_RECENT, period=period)
elif len(list) == 1:
emit(ONE_RECENT, period=period)
else:
emit(SOME_RECENT, period=period, count=len(list))
self.format_all(map(lambda (mtime, file): file, list), headers=0)
emit(TAIL_RECENT) | [
"def",
"do_recent",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"ui",
".",
"days",
":",
"days",
"=",
"1",
"else",
":",
"days",
"=",
"float",
"(",
"self",
".",
"ui",
".",
"days",
")",
"try",
":",
"cutoff",
"=",
"now",
"-",
"days",
"*",
"2... | https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Tools/faqwiz/faqwiz.py#L550-L581 | ||||
openstack-archive/dragonflow | 4dc36ed6490e2ed53b47dece883cdbd78ea96033 | dragonflow/db/drivers/etcd_db_driver.py | python | _error_catcher | (self) | Catch low-level python exceptions, instead re-raising urllib3
variants, so that low-level exceptions are not leaked in the
high-level api.
On exit, release the connection back to the pool. | Catch low-level python exceptions, instead re-raising urllib3
variants, so that low-level exceptions are not leaked in the
high-level api.
On exit, release the connection back to the pool. | [
"Catch",
"low",
"-",
"level",
"python",
"exceptions",
"instead",
"re",
"-",
"raising",
"urllib3",
"variants",
"so",
"that",
"low",
"-",
"level",
"exceptions",
"are",
"not",
"leaked",
"in",
"the",
"high",
"-",
"level",
"api",
".",
"On",
"exit",
"release",
... | def _error_catcher(self):
"""
Catch low-level python exceptions, instead re-raising urllib3
variants, so that low-level exceptions are not leaked in the
high-level api.
On exit, release the connection back to the pool.
"""
try:
try:
yield
except SocketTimeout:
# FIXME: Ideally we'd like to include the url in the
# ReadTimeoutError but there is yet no clean way to
# get at it from this context.
raise exceptions.ReadTimeoutError(
self._pool, None, 'Read timed out.')
except connection.BaseSSLError as e:
# FIXME: Is there a better way to differentiate between SSLErrors?
if 'read operation timed out' not in str(e): # Defensive:
# This shouldn't happen but just in case we're missing an edge
# case, let's avoid swallowing SSL errors.
raise
raise exceptions.ReadTimeoutError(
self._pool, None, 'Read timed out.')
except connection.HTTPException as e:
# This includes IncompleteRead.
raise exceptions.ProtocolError('Connection broken: %r' % e, e)
except Exception:
# The response may not be closed but we're not going to use it anymore
# so close it now to ensure that the connection is released back to the
# pool.
if self._original_response and not self._original_response.isclosed():
self._original_response.close()
# Before returning the socket, close it. From the server's
# point of view,
# this socket is in the middle of handling an SSL handshake/HTTP
# request so it we were to try and re-use the connection later,
# we'd see undefined behaviour.
#
# Still return the connection to the pool (it will be
# re-established next time it is used).
self._connection.close()
raise
finally:
if self._original_response and self._original_response.isclosed():
self.release_conn() | [
"def",
"_error_catcher",
"(",
"self",
")",
":",
"try",
":",
"try",
":",
"yield",
"except",
"SocketTimeout",
":",
"# FIXME: Ideally we'd like to include the url in the",
"# ReadTimeoutError but there is yet no clean way to",
"# get at it from this context.",
"raise",
"exceptions",... | https://github.com/openstack-archive/dragonflow/blob/4dc36ed6490e2ed53b47dece883cdbd78ea96033/dragonflow/db/drivers/etcd_db_driver.py#L36-L87 | ||
openstack/magnum | fa298eeab19b1d87070d72c7c4fb26cd75b0781e | magnum/api/attr_validator.py | python | validate_federation_hostcluster | (cluster_uuid) | Validate Federation `hostcluster_id` parameter.
If the parameter was not specified raise an
`exceptions.InvalidParameterValue`. If the specified identifier does not
identify any Cluster, raise `exception.ClusterNotFound` | Validate Federation `hostcluster_id` parameter. | [
"Validate",
"Federation",
"hostcluster_id",
"parameter",
"."
] | def validate_federation_hostcluster(cluster_uuid):
"""Validate Federation `hostcluster_id` parameter.
If the parameter was not specified raise an
`exceptions.InvalidParameterValue`. If the specified identifier does not
identify any Cluster, raise `exception.ClusterNotFound`
"""
if cluster_uuid is not None:
api_utils.get_resource('Cluster', cluster_uuid)
else:
raise exception.InvalidParameterValue(
"No hostcluster specified. "
"Please specify a hostcluster_id.") | [
"def",
"validate_federation_hostcluster",
"(",
"cluster_uuid",
")",
":",
"if",
"cluster_uuid",
"is",
"not",
"None",
":",
"api_utils",
".",
"get_resource",
"(",
"'Cluster'",
",",
"cluster_uuid",
")",
"else",
":",
"raise",
"exception",
".",
"InvalidParameterValue",
... | https://github.com/openstack/magnum/blob/fa298eeab19b1d87070d72c7c4fb26cd75b0781e/magnum/api/attr_validator.py#L217-L229 | ||
wanggrun/Adaptively-Connected-Neural-Networks | e27066ef52301bdafa5932f43af8feeb23647edb | tensorpack-installed/tensorpack/graph_builder/training.py | python | SyncMultiGPUParameterServerBuilder.build | (self, get_grad_fn, get_opt_fn) | return train_op | Args:
get_grad_fn (-> [(grad, var)]):
get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer
Returns:
tf.Operation: the training op | Args:
get_grad_fn (-> [(grad, var)]):
get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer | [
"Args",
":",
"get_grad_fn",
"(",
"-",
">",
"[",
"(",
"grad",
"var",
")",
"]",
")",
":",
"get_opt_fn",
"(",
"-",
">",
"tf",
".",
"train",
".",
"Optimizer",
")",
":",
"callable",
"which",
"returns",
"an",
"optimizer"
] | def build(self, get_grad_fn, get_opt_fn):
"""
Args:
get_grad_fn (-> [(grad, var)]):
get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer
Returns:
tf.Operation: the training op
"""
raw_devices = ['/gpu:{}'.format(k) for k in self.towers]
if self.ps_device == 'gpu':
devices = [LeastLoadedDeviceSetter(d, raw_devices) for d in raw_devices]
else:
devices = [tf.train.replica_device_setter(
worker_device=d, ps_device='/cpu:0', ps_tasks=1) for d in raw_devices]
grad_list = DataParallelBuilder.build_on_towers(self.towers, get_grad_fn, devices)
DataParallelBuilder._check_grad_list(grad_list)
# debug tower performance (without update):
# ops = [k[0] for k in grad_list[1]] + [k[0] for k in grad_list[0]]
# self.train_op = tf.group(*ops)
# return
self.grads = aggregate_grads(grad_list, colocation=True)
# grads = grad_list[0]
opt = get_opt_fn()
if self.ps_device == 'cpu':
with tf.device('/cpu:0'):
train_op = opt.apply_gradients(self.grads, name='train_op')
else:
train_op = opt.apply_gradients(self.grads, name='train_op')
return train_op | [
"def",
"build",
"(",
"self",
",",
"get_grad_fn",
",",
"get_opt_fn",
")",
":",
"raw_devices",
"=",
"[",
"'/gpu:{}'",
".",
"format",
"(",
"k",
")",
"for",
"k",
"in",
"self",
".",
"towers",
"]",
"if",
"self",
".",
"ps_device",
"==",
"'gpu'",
":",
"devic... | https://github.com/wanggrun/Adaptively-Connected-Neural-Networks/blob/e27066ef52301bdafa5932f43af8feeb23647edb/tensorpack-installed/tensorpack/graph_builder/training.py#L134-L167 | |
mozilla/kitsune | 7c7cf9baed57aa776547aea744243ccad6ca91fb | kitsune/sumo/redis_utils.py | python | redis_client | (name) | return redis | Get a Redis client.
Uses the name argument to lookup the connection string in the
settings.REDIS_BACKEND dict. | Get a Redis client. | [
"Get",
"a",
"Redis",
"client",
"."
] | def redis_client(name):
"""Get a Redis client.
Uses the name argument to lookup the connection string in the
settings.REDIS_BACKEND dict.
"""
if name not in settings.REDIS_BACKENDS:
raise RedisError("{k} is not defined in settings.REDIS_BACKENDS".format(k=name))
uri = settings.REDIS_BACKENDS[name]
_, server, params = parse_backend_uri(uri)
db = params.pop("db", 1)
try:
db = int(db)
except (ValueError, TypeError):
db = 1
try:
socket_timeout = float(params.pop("socket_timeout"))
except (KeyError, ValueError):
socket_timeout = None
password = params.pop("password", None)
if ":" in server:
host, port = server.split(":")
try:
port = int(port)
except (ValueError, TypeError):
port = 6379
else:
host = server
port = 6379
redis = Redis(
host=host,
port=port,
db=db,
password=password,
socket_timeout=socket_timeout,
decode_responses=True,
)
try:
# Make a cheap call to verify we can connect.
redis.exists("dummy-key")
except ConnectionError:
raise RedisError("Unable to connect to redis backend: {k}".format(k=name))
return redis | [
"def",
"redis_client",
"(",
"name",
")",
":",
"if",
"name",
"not",
"in",
"settings",
".",
"REDIS_BACKENDS",
":",
"raise",
"RedisError",
"(",
"\"{k} is not defined in settings.REDIS_BACKENDS\"",
".",
"format",
"(",
"k",
"=",
"name",
")",
")",
"uri",
"=",
"setti... | https://github.com/mozilla/kitsune/blob/7c7cf9baed57aa776547aea744243ccad6ca91fb/kitsune/sumo/redis_utils.py#L12-L56 | |
CouchPotato/CouchPotatoServer | 7260c12f72447ddb6f062367c6dfbda03ecd4e9c | libs/pytwitter/__init__.py | python | User.SetFriendsCount | (self, count) | Set the friend count for this user.
Args:
count:
The number of users this user has befriended. | Set the friend count for this user. | [
"Set",
"the",
"friend",
"count",
"for",
"this",
"user",
"."
] | def SetFriendsCount(self, count):
'''Set the friend count for this user.
Args:
count:
The number of users this user has befriended.
'''
self._friends_count = count | [
"def",
"SetFriendsCount",
"(",
"self",
",",
"count",
")",
":",
"self",
".",
"_friends_count",
"=",
"count"
] | https://github.com/CouchPotato/CouchPotatoServer/blob/7260c12f72447ddb6f062367c6dfbda03ecd4e9c/libs/pytwitter/__init__.py#L1133-L1140 | ||
bitcraze/crazyflie-lib-python | 876f0dc003b91ba5e4de05daae9d0b79cf600f81 | cflib/crazyflie/high_level_commander.py | python | HighLevelCommander.stop | (self, group_mask=ALL_GROUPS) | stops the current trajectory (turns off the motors)
:param group_mask: Mask for which CFs this should apply to
:return: | stops the current trajectory (turns off the motors) | [
"stops",
"the",
"current",
"trajectory",
"(",
"turns",
"off",
"the",
"motors",
")"
] | def stop(self, group_mask=ALL_GROUPS):
"""
stops the current trajectory (turns off the motors)
:param group_mask: Mask for which CFs this should apply to
:return:
"""
self._send_packet(struct.pack('<BB',
self.COMMAND_STOP,
group_mask)) | [
"def",
"stop",
"(",
"self",
",",
"group_mask",
"=",
"ALL_GROUPS",
")",
":",
"self",
".",
"_send_packet",
"(",
"struct",
".",
"pack",
"(",
"'<BB'",
",",
"self",
".",
"COMMAND_STOP",
",",
"group_mask",
")",
")"
] | https://github.com/bitcraze/crazyflie-lib-python/blob/876f0dc003b91ba5e4de05daae9d0b79cf600f81/cflib/crazyflie/high_level_commander.py#L125-L134 | ||
thinkle/gourmet | 8af29c8ded24528030e5ae2ea3461f61c1e5a575 | gourmet/gtk_extras/pageable_store.py | python | PageableListStore.sort | (self, column, direction=FORWARD) | Add new sort term in direction.
Note -- to remove term we use direction=OFF | Add new sort term in direction. | [
"Add",
"new",
"sort",
"term",
"in",
"direction",
"."
] | def sort (self, column, direction=FORWARD):
"""Add new sort term in direction.
Note -- to remove term we use direction=OFF
"""
assert(direction in (self.FORWARD, self.REVERSE, self.OFF))
self.sort_dict[column]=direction
if direction==self.OFF:
self.parent_list = self.unsorted_parent
return
self.parent_list.sort(key=lambda x: x[column], reverse=(direction == self.REVERSE))
self.update_tree() | [
"def",
"sort",
"(",
"self",
",",
"column",
",",
"direction",
"=",
"FORWARD",
")",
":",
"assert",
"(",
"direction",
"in",
"(",
"self",
".",
"FORWARD",
",",
"self",
".",
"REVERSE",
",",
"self",
".",
"OFF",
")",
")",
"self",
".",
"sort_dict",
"[",
"co... | https://github.com/thinkle/gourmet/blob/8af29c8ded24528030e5ae2ea3461f61c1e5a575/gourmet/gtk_extras/pageable_store.py#L165-L177 | ||
web2py/web2py | 095905c4e010a1426c729483d912e270a51b7ba8 | gluon/contrib/dbg.py | python | Qdb.user_call | (self, frame, argument_list) | This method is called when there is the remote possibility
that we ever need to stop in this function. | This method is called when there is the remote possibility
that we ever need to stop in this function. | [
"This",
"method",
"is",
"called",
"when",
"there",
"is",
"the",
"remote",
"possibility",
"that",
"we",
"ever",
"need",
"to",
"stop",
"in",
"this",
"function",
"."
] | def user_call(self, frame, argument_list):
"""This method is called when there is the remote possibility
that we ever need to stop in this function."""
if self._wait_for_mainpyfile or self._wait_for_breakpoint:
return
if self.stop_here(frame):
self.interaction(frame) | [
"def",
"user_call",
"(",
"self",
",",
"frame",
",",
"argument_list",
")",
":",
"if",
"self",
".",
"_wait_for_mainpyfile",
"or",
"self",
".",
"_wait_for_breakpoint",
":",
"return",
"if",
"self",
".",
"stop_here",
"(",
"frame",
")",
":",
"self",
".",
"intera... | https://github.com/web2py/web2py/blob/095905c4e010a1426c729483d912e270a51b7ba8/gluon/contrib/dbg.py#L121-L127 | ||
debian-calibre/calibre | 020fc81d3936a64b2ac51459ecb796666ab6a051 | src/calibre/ebooks/compression/tcr.py | python | TCRCompressor._free_unused_codes | (self) | Look for codes that do no not appear in the coded text and add them to
the list of free codes. | Look for codes that do no not appear in the coded text and add them to
the list of free codes. | [
"Look",
"for",
"codes",
"that",
"do",
"no",
"not",
"appear",
"in",
"the",
"coded",
"text",
"and",
"add",
"them",
"to",
"the",
"list",
"of",
"free",
"codes",
"."
] | def _free_unused_codes(self):
'''
Look for codes that do no not appear in the coded text and add them to
the list of free codes.
'''
for i in range(256):
if i not in self.unused_codes:
if int_to_byte(i) not in self.coded_txt:
self.unused_codes.add(i) | [
"def",
"_free_unused_codes",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"256",
")",
":",
"if",
"i",
"not",
"in",
"self",
".",
"unused_codes",
":",
"if",
"int_to_byte",
"(",
"i",
")",
"not",
"in",
"self",
".",
"coded_txt",
":",
"self",
"... | https://github.com/debian-calibre/calibre/blob/020fc81d3936a64b2ac51459ecb796666ab6a051/src/calibre/ebooks/compression/tcr.py#L48-L56 | ||
openmc-dev/openmc | 0cf7d9283786677e324bfbdd0984a54d1c86dacc | openmc/tallies.py | python | Tallies.insert | (self, index, item) | Insert tally before index
Parameters
----------
index : int
Index in list
item : openmc.Tally
Tally to insert | Insert tally before index | [
"Insert",
"tally",
"before",
"index"
] | def insert(self, index, item):
"""Insert tally before index
Parameters
----------
index : int
Index in list
item : openmc.Tally
Tally to insert
"""
super().insert(index, item) | [
"def",
"insert",
"(",
"self",
",",
"index",
",",
"item",
")",
":",
"super",
"(",
")",
".",
"insert",
"(",
"index",
",",
"item",
")"
] | https://github.com/openmc-dev/openmc/blob/0cf7d9283786677e324bfbdd0984a54d1c86dacc/openmc/tallies.py#L3041-L3052 | ||
apache/libcloud | 90971e17bfd7b6bb97b2489986472c531cc8e140 | libcloud/compute/drivers/ec2.py | python | BaseEC2NodeDriver.ex_list_route_tables | (self, route_table_ids=None, filters=None) | return self._to_route_tables(response.object) | Describes one or more of a VPC's route tables.
These are used to determine where network traffic is directed.
:param route_table_ids: Returns only route tables matching the
provided route table IDs. If not specified,
a list of all the route tables in the
corresponding region is returned.
:type route_table_ids: ``list``
:param filters: The filters so that the list returned includes
information for certain route tables only.
:type filters: ``dict``
:rtype: ``list`` of :class:`.EC2RouteTable` | Describes one or more of a VPC's route tables.
These are used to determine where network traffic is directed. | [
"Describes",
"one",
"or",
"more",
"of",
"a",
"VPC",
"s",
"route",
"tables",
".",
"These",
"are",
"used",
"to",
"determine",
"where",
"network",
"traffic",
"is",
"directed",
"."
] | def ex_list_route_tables(self, route_table_ids=None, filters=None):
"""
Describes one or more of a VPC's route tables.
These are used to determine where network traffic is directed.
:param route_table_ids: Returns only route tables matching the
provided route table IDs. If not specified,
a list of all the route tables in the
corresponding region is returned.
:type route_table_ids: ``list``
:param filters: The filters so that the list returned includes
information for certain route tables only.
:type filters: ``dict``
:rtype: ``list`` of :class:`.EC2RouteTable`
"""
params = {"Action": "DescribeRouteTables"}
if route_table_ids:
params.update(self._pathlist("RouteTableId", route_table_ids))
if filters:
params.update(self._build_filters(filters))
response = self.connection.request(self.path, params=params)
return self._to_route_tables(response.object) | [
"def",
"ex_list_route_tables",
"(",
"self",
",",
"route_table_ids",
"=",
"None",
",",
"filters",
"=",
"None",
")",
":",
"params",
"=",
"{",
"\"Action\"",
":",
"\"DescribeRouteTables\"",
"}",
"if",
"route_table_ids",
":",
"params",
".",
"update",
"(",
"self",
... | https://github.com/apache/libcloud/blob/90971e17bfd7b6bb97b2489986472c531cc8e140/libcloud/compute/drivers/ec2.py#L4038-L4065 | |
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/lib/django-1.2/django/utils/regex_helper.py | python | flatten_result | (source) | return result, result_args | Turns the given source sequence into a list of reg-exp possibilities and
their arguments. Returns a list of strings and a list of argument lists.
Each of the two lists will be of the same length. | Turns the given source sequence into a list of reg-exp possibilities and
their arguments. Returns a list of strings and a list of argument lists.
Each of the two lists will be of the same length. | [
"Turns",
"the",
"given",
"source",
"sequence",
"into",
"a",
"list",
"of",
"reg",
"-",
"exp",
"possibilities",
"and",
"their",
"arguments",
".",
"Returns",
"a",
"list",
"of",
"strings",
"and",
"a",
"list",
"of",
"argument",
"lists",
".",
"Each",
"of",
"th... | def flatten_result(source):
"""
Turns the given source sequence into a list of reg-exp possibilities and
their arguments. Returns a list of strings and a list of argument lists.
Each of the two lists will be of the same length.
"""
if source is None:
return [u''], [[]]
if isinstance(source, Group):
if source[1] is None:
params = []
else:
params = [source[1]]
return [source[0]], [params]
result = [u'']
result_args = [[]]
pos = last = 0
for pos, elt in enumerate(source):
if isinstance(elt, basestring):
continue
piece = u''.join(source[last:pos])
if isinstance(elt, Group):
piece += elt[0]
param = elt[1]
else:
param = None
last = pos + 1
for i in range(len(result)):
result[i] += piece
if param:
result_args[i].append(param)
if isinstance(elt, (Choice, NonCapture)):
if isinstance(elt, NonCapture):
elt = [elt]
inner_result, inner_args = [], []
for item in elt:
res, args = flatten_result(item)
inner_result.extend(res)
inner_args.extend(args)
new_result = []
new_args = []
for item, args in zip(result, result_args):
for i_item, i_args in zip(inner_result, inner_args):
new_result.append(item + i_item)
new_args.append(args[:] + i_args)
result = new_result
result_args = new_args
if pos >= last:
piece = u''.join(source[last:])
for i in range(len(result)):
result[i] += piece
return result, result_args | [
"def",
"flatten_result",
"(",
"source",
")",
":",
"if",
"source",
"is",
"None",
":",
"return",
"[",
"u''",
"]",
",",
"[",
"[",
"]",
"]",
"if",
"isinstance",
"(",
"source",
",",
"Group",
")",
":",
"if",
"source",
"[",
"1",
"]",
"is",
"None",
":",
... | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.2/django/utils/regex_helper.py#L276-L327 | |
Mindwerks/worldengine | 64dff8eb7824ce46b5b6cb8006bcef21822ef144 | worldengine/draw.py | python | draw_simple_elevation | (world, sea_level, target) | This function can be used on a generic canvas (either an image to save
on disk or a canvas part of a GUI) | This function can be used on a generic canvas (either an image to save
on disk or a canvas part of a GUI) | [
"This",
"function",
"can",
"be",
"used",
"on",
"a",
"generic",
"canvas",
"(",
"either",
"an",
"image",
"to",
"save",
"on",
"disk",
"or",
"a",
"canvas",
"part",
"of",
"a",
"GUI",
")"
] | def draw_simple_elevation(world, sea_level, target):
""" This function can be used on a generic canvas (either an image to save
on disk or a canvas part of a GUI)
"""
e = world.layers['elevation'].data
c = numpy.empty(e.shape, dtype=numpy.float)
has_ocean = not (sea_level is None or world.layers['ocean'].data is None or not world.layers['ocean'].data.any()) # or 'not any ocean'
mask_land = numpy.ma.array(e, mask=world.layers['ocean'].data if has_ocean else False) # only land
min_elev_land = mask_land.min()
max_elev_land = mask_land.max()
elev_delta_land = (max_elev_land - min_elev_land) / 11.0
if has_ocean:
land = numpy.logical_not(world.layers['ocean'].data)
mask_ocean = numpy.ma.array(e, mask=land) # only ocean
min_elev_sea = mask_ocean.min()
max_elev_sea = mask_ocean.max()
elev_delta_sea = max_elev_sea - min_elev_sea
c[world.layers['ocean'].data] = ((e[world.layers['ocean'].data] - min_elev_sea) / elev_delta_sea)
c[land] = ((e[land] - min_elev_land) / elev_delta_land) + 1
else:
c = ((e - min_elev_land) / elev_delta_land) + 1
for y in range(world.height):
for x in range(world.width):
r, g, b = elevation_color(c[y, x], sea_level)
target.set_pixel(x, y, (int(r * 255), int(g * 255),
int(b * 255), 255)) | [
"def",
"draw_simple_elevation",
"(",
"world",
",",
"sea_level",
",",
"target",
")",
":",
"e",
"=",
"world",
".",
"layers",
"[",
"'elevation'",
"]",
".",
"data",
"c",
"=",
"numpy",
".",
"empty",
"(",
"e",
".",
"shape",
",",
"dtype",
"=",
"numpy",
".",... | https://github.com/Mindwerks/worldengine/blob/64dff8eb7824ce46b5b6cb8006bcef21822ef144/worldengine/draw.py#L323-L353 | ||
deepgully/me | f7ad65edc2fe435310c6676bc2e322cfe5d4c8f0 | libs/werkzeug/datastructures.py | python | WWWAuthenticate.set_digest | (self, realm, nonce, qop=('auth',), opaque=None,
algorithm=None, stale=False) | Clear the auth info and enable digest auth. | Clear the auth info and enable digest auth. | [
"Clear",
"the",
"auth",
"info",
"and",
"enable",
"digest",
"auth",
"."
] | def set_digest(self, realm, nonce, qop=('auth',), opaque=None,
algorithm=None, stale=False):
"""Clear the auth info and enable digest auth."""
d = {
'__auth_type__': 'digest',
'realm': realm,
'nonce': nonce,
'qop': dump_header(qop)
}
if stale:
d['stale'] = 'TRUE'
if opaque is not None:
d['opaque'] = opaque
if algorithm is not None:
d['algorithm'] = algorithm
dict.clear(self)
dict.update(self, d)
if self.on_update:
self.on_update(self) | [
"def",
"set_digest",
"(",
"self",
",",
"realm",
",",
"nonce",
",",
"qop",
"=",
"(",
"'auth'",
",",
")",
",",
"opaque",
"=",
"None",
",",
"algorithm",
"=",
"None",
",",
"stale",
"=",
"False",
")",
":",
"d",
"=",
"{",
"'__auth_type__'",
":",
"'digest... | https://github.com/deepgully/me/blob/f7ad65edc2fe435310c6676bc2e322cfe5d4c8f0/libs/werkzeug/datastructures.py#L2335-L2353 | ||
jliljebl/flowblade | 995313a509b80e99eb1ad550d945bdda5995093b | flowblade-trunk/Flowblade/sequence.py | python | Sequence._mute_editable | (self) | [] | def _mute_editable(self):
for i in range(1, len(self.tracks) - 1):
track = self.tracks[i]
track.set("hide", 3) | [
"def",
"_mute_editable",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"self",
".",
"tracks",
")",
"-",
"1",
")",
":",
"track",
"=",
"self",
".",
"tracks",
"[",
"i",
"]",
"track",
".",
"set",
"(",
"\"hide\"",
",",... | https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/sequence.py#L891-L894 | ||||
getsentry/sentry | 83b1f25aac3e08075e0e2495bc29efaf35aca18a | src/sentry/utils/glob.py | python | glob_match | (
value, pat, doublestar=False, ignorecase=False, path_normalize=False, allow_newline=True
) | return sentry_relay.is_glob_match(
value if value is not None else "",
pat,
double_star=doublestar,
case_insensitive=ignorecase,
path_normalize=path_normalize,
allow_newline=allow_newline,
) | A beefed up version of fnmatch.fnmatch | A beefed up version of fnmatch.fnmatch | [
"A",
"beefed",
"up",
"version",
"of",
"fnmatch",
".",
"fnmatch"
] | def glob_match(
value, pat, doublestar=False, ignorecase=False, path_normalize=False, allow_newline=True
):
"""A beefed up version of fnmatch.fnmatch"""
return sentry_relay.is_glob_match(
value if value is not None else "",
pat,
double_star=doublestar,
case_insensitive=ignorecase,
path_normalize=path_normalize,
allow_newline=allow_newline,
) | [
"def",
"glob_match",
"(",
"value",
",",
"pat",
",",
"doublestar",
"=",
"False",
",",
"ignorecase",
"=",
"False",
",",
"path_normalize",
"=",
"False",
",",
"allow_newline",
"=",
"True",
")",
":",
"return",
"sentry_relay",
".",
"is_glob_match",
"(",
"value",
... | https://github.com/getsentry/sentry/blob/83b1f25aac3e08075e0e2495bc29efaf35aca18a/src/sentry/utils/glob.py#L4-L15 | |
Textualize/rich | d39626143036188cb2c9e1619e836540f5b627f8 | rich/jupyter.py | python | print | (*args: Any, **kwargs: Any) | return console.print(*args, **kwargs) | Proxy for Console print. | Proxy for Console print. | [
"Proxy",
"for",
"Console",
"print",
"."
] | def print(*args: Any, **kwargs: Any) -> None:
"""Proxy for Console print."""
console = get_console()
return console.print(*args, **kwargs) | [
"def",
"print",
"(",
"*",
"args",
":",
"Any",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"console",
"=",
"get_console",
"(",
")",
"return",
"console",
".",
"print",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/Textualize/rich/blob/d39626143036188cb2c9e1619e836540f5b627f8/rich/jupyter.py#L89-L92 | |
ales-tsurko/cells | 4cf7e395cd433762bea70cdc863a346f3a6fe1d0 | packaging/macos/python/lib/python3.7/site-packages/pip/_vendor/distlib/util.py | python | zip_dir | (directory) | return result | zip a directory tree into a BytesIO object | zip a directory tree into a BytesIO object | [
"zip",
"a",
"directory",
"tree",
"into",
"a",
"BytesIO",
"object"
] | def zip_dir(directory):
"""zip a directory tree into a BytesIO object"""
result = io.BytesIO()
dlen = len(directory)
with ZipFile(result, "w") as zf:
for root, dirs, files in os.walk(directory):
for name in files:
full = os.path.join(root, name)
rel = root[dlen:]
dest = os.path.join(rel, name)
zf.write(full, dest)
return result | [
"def",
"zip_dir",
"(",
"directory",
")",
":",
"result",
"=",
"io",
".",
"BytesIO",
"(",
")",
"dlen",
"=",
"len",
"(",
"directory",
")",
"with",
"ZipFile",
"(",
"result",
",",
"\"w\"",
")",
"as",
"zf",
":",
"for",
"root",
",",
"dirs",
",",
"files",
... | https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/site-packages/pip/_vendor/distlib/util.py#L1253-L1264 | |
spectacles/CodeComplice | 8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62 | libs/koXMLDatasetInfo.py | python | DatasetHandlerService.createDatasetHandler | (self, publicId, systemId, namespace) | return handler | [] | def createDatasetHandler(self, publicId, systemId, namespace):
dataset = self.resolver.getDataset(publicId, systemId, namespace)
if not dataset:
handler = EmptyDatasetHandler()
else:
handler = DataSetHandler(namespace, dataset)
if namespace:
self.handlers[namespace] = handler
if publicId or systemId:
self.handlers[(publicId, systemId)] = handler
return handler | [
"def",
"createDatasetHandler",
"(",
"self",
",",
"publicId",
",",
"systemId",
",",
"namespace",
")",
":",
"dataset",
"=",
"self",
".",
"resolver",
".",
"getDataset",
"(",
"publicId",
",",
"systemId",
",",
"namespace",
")",
"if",
"not",
"dataset",
":",
"han... | https://github.com/spectacles/CodeComplice/blob/8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62/libs/koXMLDatasetInfo.py#L165-L176 | |||
librahfacebook/Detection | 84504d086634950224716f4de0e4c8a684493c34 | object_detection/utils/config_util.py | python | update_input_reader_config | (configs,
key_name=None,
input_name=None,
field_name=None,
value=None,
path_updater=_update_tf_record_input_path) | Updates specified input reader config field.
Args:
configs: Dictionary of configuration objects. See outputs from
get_configs_from_pipeline_file() or get_configs_from_multiple_files().
key_name: Name of the input config we should update, either
'train_input_config' or 'eval_input_configs'
input_name: String name used to identify input config to update with. Should
be either None or value of the 'name' field in one of the input reader
configs.
field_name: Field name in input_reader_pb2.InputReader.
value: Value used to override existing field value.
path_updater: helper function used to update the input path. Only used when
field_name is "input_path".
Raises:
ValueError: when input field_name is None.
ValueError: when input_name is None and number of eval_input_readers does
not equal to 1. | Updates specified input reader config field. | [
"Updates",
"specified",
"input",
"reader",
"config",
"field",
"."
] | def update_input_reader_config(configs,
key_name=None,
input_name=None,
field_name=None,
value=None,
path_updater=_update_tf_record_input_path):
"""Updates specified input reader config field.
Args:
configs: Dictionary of configuration objects. See outputs from
get_configs_from_pipeline_file() or get_configs_from_multiple_files().
key_name: Name of the input config we should update, either
'train_input_config' or 'eval_input_configs'
input_name: String name used to identify input config to update with. Should
be either None or value of the 'name' field in one of the input reader
configs.
field_name: Field name in input_reader_pb2.InputReader.
value: Value used to override existing field value.
path_updater: helper function used to update the input path. Only used when
field_name is "input_path".
Raises:
ValueError: when input field_name is None.
ValueError: when input_name is None and number of eval_input_readers does
not equal to 1.
"""
if isinstance(configs[key_name], input_reader_pb2.InputReader):
# Updates singular input_config object.
target_input_config = configs[key_name]
if field_name == "input_path":
path_updater(input_config=target_input_config, input_path=value)
else:
setattr(target_input_config, field_name, value)
elif input_name is None and len(configs[key_name]) == 1:
# Updates first (and the only) object of input_config list.
target_input_config = configs[key_name][0]
if field_name == "input_path":
path_updater(input_config=target_input_config, input_path=value)
else:
setattr(target_input_config, field_name, value)
elif input_name is not None and len(configs[key_name]):
# Updates input_config whose name matches input_name.
update_count = 0
for input_config in configs[key_name]:
if input_config.name == input_name:
setattr(input_config, field_name, value)
update_count = update_count + 1
if not update_count:
raise ValueError(
"Input name {} not found when overriding.".format(input_name))
elif update_count > 1:
raise ValueError("Duplicate input name found when overriding.")
else:
key_name = "None" if key_name is None else key_name
input_name = "None" if input_name is None else input_name
field_name = "None" if field_name is None else field_name
raise ValueError("Unknown input config overriding: "
"key_name:{}, input_name:{}, field_name:{}.".format(
key_name, input_name, field_name)) | [
"def",
"update_input_reader_config",
"(",
"configs",
",",
"key_name",
"=",
"None",
",",
"input_name",
"=",
"None",
",",
"field_name",
"=",
"None",
",",
"value",
"=",
"None",
",",
"path_updater",
"=",
"_update_tf_record_input_path",
")",
":",
"if",
"isinstance",
... | https://github.com/librahfacebook/Detection/blob/84504d086634950224716f4de0e4c8a684493c34/object_detection/utils/config_util.py#L581-L639 | ||
truenas/middleware | b11ec47d6340324f5a32287ffb4012e5d709b934 | src/middlewared/middlewared/job.py | python | Job.run | (self, queue) | Run a Job and set state/result accordingly.
This method is supposed to run in a greenlet. | Run a Job and set state/result accordingly.
This method is supposed to run in a greenlet. | [
"Run",
"a",
"Job",
"and",
"set",
"state",
"/",
"result",
"accordingly",
".",
"This",
"method",
"is",
"supposed",
"to",
"run",
"in",
"a",
"greenlet",
"."
] | async def run(self, queue):
"""
Run a Job and set state/result accordingly.
This method is supposed to run in a greenlet.
"""
if self.options["logs"]:
self.logs_path = os.path.join(LOGS_DIR, f"{self.id}.log")
self.start_logging()
try:
if self.aborted:
raise asyncio.CancelledError()
else:
self.set_state('RUNNING')
self.future = asyncio.ensure_future(self.__run_body())
try:
await self.future
except Exception as e:
handled = adapt_exception(e)
if handled is not None:
raise handled
else:
raise
except asyncio.CancelledError:
self.set_state('ABORTED')
except Exception:
self.set_state('FAILED')
self.set_exception(sys.exc_info())
logger.error("Job %r failed", self.method, exc_info=True)
finally:
await self.__close_logs()
await self.__close_pipes()
queue.release_lock(self)
self._finished.set()
if self.options['transient']:
queue.remove(self.id)
else:
self.middleware.send_event('core.get_jobs', 'CHANGED', id=self.id, fields=self.__encode__()) | [
"async",
"def",
"run",
"(",
"self",
",",
"queue",
")",
":",
"if",
"self",
".",
"options",
"[",
"\"logs\"",
"]",
":",
"self",
".",
"logs_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"LOGS_DIR",
",",
"f\"{self.id}.log\"",
")",
"self",
".",
"start_l... | https://github.com/truenas/middleware/blob/b11ec47d6340324f5a32287ffb4012e5d709b934/src/middlewared/middlewared/job.py#L405-L445 | ||
shmilylty/OneForAll | 48591142a641e80f8a64ab215d11d06b696702d7 | brute.py | python | gen_word_subdomains | (expression, path) | return subdomains | Generate subdomains based on word mode
:param str expression: generate subdomains expression
:param str path: path of wordlist
:return set subdomains: list of subdomains | Generate subdomains based on word mode | [
"Generate",
"subdomains",
"based",
"on",
"word",
"mode"
] | def gen_word_subdomains(expression, path):
"""
Generate subdomains based on word mode
:param str expression: generate subdomains expression
:param str path: path of wordlist
:return set subdomains: list of subdomains
"""
subdomains = gen_subdomains(expression, path)
logger.log('DEBUG', f'Dictionary based on word mode size: {len(subdomains)}')
return subdomains | [
"def",
"gen_word_subdomains",
"(",
"expression",
",",
"path",
")",
":",
"subdomains",
"=",
"gen_subdomains",
"(",
"expression",
",",
"path",
")",
"logger",
".",
"log",
"(",
"'DEBUG'",
",",
"f'Dictionary based on word mode size: {len(subdomains)}'",
")",
"return",
"s... | https://github.com/shmilylty/OneForAll/blob/48591142a641e80f8a64ab215d11d06b696702d7/brute.py#L89-L99 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_hxb2/lib/python3.5/site-packages/django/contrib/gis/db/models/aggregates.py | python | Extent3D.__init__ | (self, expression, **extra) | [] | def __init__(self, expression, **extra):
super(Extent3D, self).__init__(expression, output_field=ExtentField(), **extra) | [
"def",
"__init__",
"(",
"self",
",",
"expression",
",",
"*",
"*",
"extra",
")",
":",
"super",
"(",
"Extent3D",
",",
"self",
")",
".",
"__init__",
"(",
"expression",
",",
"output_field",
"=",
"ExtentField",
"(",
")",
",",
"*",
"*",
"extra",
")"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/contrib/gis/db/models/aggregates.py#L56-L57 | ||||
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/unifi/unifi_entity_base.py | python | UniFiBase.async_will_remove_from_hass | (self) | Disconnect object when removed. | Disconnect object when removed. | [
"Disconnect",
"object",
"when",
"removed",
"."
] | async def async_will_remove_from_hass(self) -> None:
"""Disconnect object when removed."""
_LOGGER.debug(
"Removing %s entity %s (%s)",
self.TYPE,
self.entity_id,
self.key,
)
self._item.remove_callback(self.async_update_callback)
self.controller.entities[self.DOMAIN][self.TYPE].remove(self.key) | [
"async",
"def",
"async_will_remove_from_hass",
"(",
"self",
")",
"->",
"None",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Removing %s entity %s (%s)\"",
",",
"self",
".",
"TYPE",
",",
"self",
".",
"entity_id",
",",
"self",
".",
"key",
",",
")",
"self",
".",
"_i... | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/unifi/unifi_entity_base.py#L49-L58 | ||
nltk/nltk | 3f74ac55681667d7ef78b664557487145f51eb02 | nltk/parse/projectivedependencyparser.py | python | ProbabilisticProjectiveDependencyParser.train | (self, graphs) | Trains a ProbabilisticDependencyGrammar based on the list of input
DependencyGraphs. This model is an implementation of Eisner's (1996)
Model C, which derives its statistics from head-word, head-tag,
child-word, and child-tag relationships.
:param graphs: A list of dependency graphs to train from.
:type: list(DependencyGraph) | Trains a ProbabilisticDependencyGrammar based on the list of input
DependencyGraphs. This model is an implementation of Eisner's (1996)
Model C, which derives its statistics from head-word, head-tag,
child-word, and child-tag relationships. | [
"Trains",
"a",
"ProbabilisticDependencyGrammar",
"based",
"on",
"the",
"list",
"of",
"input",
"DependencyGraphs",
".",
"This",
"model",
"is",
"an",
"implementation",
"of",
"Eisner",
"s",
"(",
"1996",
")",
"Model",
"C",
"which",
"derives",
"its",
"statistics",
... | def train(self, graphs):
"""
Trains a ProbabilisticDependencyGrammar based on the list of input
DependencyGraphs. This model is an implementation of Eisner's (1996)
Model C, which derives its statistics from head-word, head-tag,
child-word, and child-tag relationships.
:param graphs: A list of dependency graphs to train from.
:type: list(DependencyGraph)
"""
productions = []
events = defaultdict(int)
tags = {}
for dg in graphs:
for node_index in range(1, len(dg.nodes)):
# children = dg.nodes[node_index]['deps']
children = list(
chain.from_iterable(dg.nodes[node_index]["deps"].values())
)
nr_left_children = dg.left_children(node_index)
nr_right_children = dg.right_children(node_index)
nr_children = nr_left_children + nr_right_children
for child_index in range(
0 - (nr_left_children + 1), nr_right_children + 2
):
head_word = dg.nodes[node_index]["word"]
head_tag = dg.nodes[node_index]["tag"]
if head_word in tags:
tags[head_word].add(head_tag)
else:
tags[head_word] = {head_tag}
child = "STOP"
child_tag = "STOP"
prev_word = "START"
prev_tag = "START"
if child_index < 0:
array_index = child_index + nr_left_children
if array_index >= 0:
child = dg.nodes[children[array_index]]["word"]
child_tag = dg.nodes[children[array_index]]["tag"]
if child_index != -1:
prev_word = dg.nodes[children[array_index + 1]]["word"]
prev_tag = dg.nodes[children[array_index + 1]]["tag"]
if child != "STOP":
productions.append(DependencyProduction(head_word, [child]))
head_event = "(head ({} {}) (mods ({}, {}, {}) left))".format(
child,
child_tag,
prev_tag,
head_word,
head_tag,
)
mod_event = "(mods ({}, {}, {}) left))".format(
prev_tag,
head_word,
head_tag,
)
events[head_event] += 1
events[mod_event] += 1
elif child_index > 0:
array_index = child_index + nr_left_children - 1
if array_index < nr_children:
child = dg.nodes[children[array_index]]["word"]
child_tag = dg.nodes[children[array_index]]["tag"]
if child_index != 1:
prev_word = dg.nodes[children[array_index - 1]]["word"]
prev_tag = dg.nodes[children[array_index - 1]]["tag"]
if child != "STOP":
productions.append(DependencyProduction(head_word, [child]))
head_event = "(head ({} {}) (mods ({}, {}, {}) right))".format(
child,
child_tag,
prev_tag,
head_word,
head_tag,
)
mod_event = "(mods ({}, {}, {}) right))".format(
prev_tag,
head_word,
head_tag,
)
events[head_event] += 1
events[mod_event] += 1
self._grammar = ProbabilisticDependencyGrammar(productions, events, tags) | [
"def",
"train",
"(",
"self",
",",
"graphs",
")",
":",
"productions",
"=",
"[",
"]",
"events",
"=",
"defaultdict",
"(",
"int",
")",
"tags",
"=",
"{",
"}",
"for",
"dg",
"in",
"graphs",
":",
"for",
"node_index",
"in",
"range",
"(",
"1",
",",
"len",
... | https://github.com/nltk/nltk/blob/3f74ac55681667d7ef78b664557487145f51eb02/nltk/parse/projectivedependencyparser.py#L439-L523 | ||
alan-turing-institute/sktime | 79cc513346b1257a6f3fa8e4ed855b5a2a7de716 | sktime/transformations/series/compose.py | python | OptionalPassthrough._transform | (self, X, y=None) | return X | Transform X and return a transformed version.
private _transform containing the core logic, called from transform
Parameters
----------
X : Series or Panel of mtype X_inner_mtype
if X_inner_mtype is list, _transform must support all types in it
Data to be transformed
y : Series or Panel of mtype y_inner_mtype, default=None
Additional data, e.g., labels for transformation
Returns
-------
transformed version of X | Transform X and return a transformed version. | [
"Transform",
"X",
"and",
"return",
"a",
"transformed",
"version",
"."
] | def _transform(self, X, y=None):
"""Transform X and return a transformed version.
private _transform containing the core logic, called from transform
Parameters
----------
X : Series or Panel of mtype X_inner_mtype
if X_inner_mtype is list, _transform must support all types in it
Data to be transformed
y : Series or Panel of mtype y_inner_mtype, default=None
Additional data, e.g., labels for transformation
Returns
-------
transformed version of X
"""
if not self.passthrough:
X = self.transformer_._transform(X, y)
return X | [
"def",
"_transform",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"passthrough",
":",
"X",
"=",
"self",
".",
"transformer_",
".",
"_transform",
"(",
"X",
",",
"y",
")",
"return",
"X"
] | https://github.com/alan-turing-institute/sktime/blob/79cc513346b1257a6f3fa8e4ed855b5a2a7de716/sktime/transformations/series/compose.py#L131-L150 | |
tp4a/teleport | 1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad | server/www/packages/packages-darwin/x64/tornado/web.py | python | RequestHandler._clear_headers_for_304 | (self) | [] | def _clear_headers_for_304(self):
# 304 responses should not contain entity headers (defined in
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.1)
# not explicitly allowed by
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
headers = ["Allow", "Content-Encoding", "Content-Language",
"Content-Length", "Content-MD5", "Content-Range",
"Content-Type", "Last-Modified"]
for h in headers:
self.clear_header(h) | [
"def",
"_clear_headers_for_304",
"(",
"self",
")",
":",
"# 304 responses should not contain entity headers (defined in",
"# http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.1)",
"# not explicitly allowed by",
"# http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5",
"header... | https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/tornado/web.py#L1685-L1694 | ||||
akanimax/msg-stylegan-tf | 41fb4eb29a78d1b8ee5aeaa0719592a28d01bce9 | dnnlib/tflib/optimizer.py | python | Optimizer.get_loss_scaling_var | (self, device: str) | return self._dev_ls_var[device] | Get or create variable representing log2 of the current dynamic loss scaling factor. | Get or create variable representing log2 of the current dynamic loss scaling factor. | [
"Get",
"or",
"create",
"variable",
"representing",
"log2",
"of",
"the",
"current",
"dynamic",
"loss",
"scaling",
"factor",
"."
] | def get_loss_scaling_var(self, device: str) -> Union[tf.Variable, None]:
"""Get or create variable representing log2 of the current dynamic loss scaling factor."""
if not self.use_loss_scaling:
return None
if device not in self._dev_ls_var:
with tfutil.absolute_name_scope(
self.scope + "/LossScalingVars"
), tf.control_dependencies(None):
self._dev_ls_var[device] = tf.Variable(
np.float32(self.loss_scaling_init), name="loss_scaling_var"
)
return self._dev_ls_var[device] | [
"def",
"get_loss_scaling_var",
"(",
"self",
",",
"device",
":",
"str",
")",
"->",
"Union",
"[",
"tf",
".",
"Variable",
",",
"None",
"]",
":",
"if",
"not",
"self",
".",
"use_loss_scaling",
":",
"return",
"None",
"if",
"device",
"not",
"in",
"self",
".",... | https://github.com/akanimax/msg-stylegan-tf/blob/41fb4eb29a78d1b8ee5aeaa0719592a28d01bce9/dnnlib/tflib/optimizer.py#L240-L253 | |
mkeeter/kokopelli | c99b7909e138c42c7d5c99927f5031f021bffd77 | koko/fab/image.py | python | Image.threshold | (self, z) | return out | @brief Thresholds a heightmap at a given depth.
@brief Can only be called on an 8, 16, or 32-bit image.
@param z Z depth (in image units)
@returns Thresholded image (8-bit, single-channel) | [] | def threshold(self, z):
""" @brief Thresholds a heightmap at a given depth.
@brief Can only be called on an 8, 16, or 32-bit image.
@param z Z depth (in image units)
@returns Thresholded image (8-bit, single-channel)
"""
out = self.__class__(self.width, self.height, channels=1, depth=8)
for b in ['xmin','xmax','ymin','ymax']:
setattr(out, b, getattr(self, b))
out.zmin = out.zmax = z
if self.depth == 8: k = int(255*(z-self.zmin) / self.dz)
elif self.depth == 16: k = int(65535*(z-self.zmin) / self.dz)
elif self.depth == 32: k = int(4294967295*(z-self.zmin) / self.dz)
elif self.depth == 'f':
raise ValueError('Cannot take threshold of floating-point image')
out.array = np.array(self.array >= k, dtype=np.uint8)
return out | [
"def",
"threshold",
"(",
"self",
",",
"z",
")",
":",
"out",
"=",
"self",
".",
"__class__",
"(",
"self",
".",
"width",
",",
"self",
".",
"height",
",",
"channels",
"=",
"1",
",",
"depth",
"=",
"8",
")",
"for",
"b",
"in",
"[",
"'xmin'",
",",
"'xm... | https://github.com/mkeeter/kokopelli/blob/c99b7909e138c42c7d5c99927f5031f021bffd77/koko/fab/image.py#L397-L417 | ||
magic282/NQG | 3006ff8b29684adead2eec82c304d81b5907fa74 | seq2seq_pt/s2s/xinit.py | python | xavier_normal | (tensor, gain=1) | return tensor.normal_(0, std) | Fills the input Tensor or Variable with values according to the method described in "Understanding the
difficulty of training deep feedforward neural networks" - Glorot, X. & Bengio, Y. (2010), using a normal
distribution. The resulting tensor will have values sampled from :math:`N(0, std)` where
:math:`std = gain \\times \sqrt{2 / (fan\_in + fan\_out)}`. Also known as Glorot initialisation.
Args:
tensor: an n-dimensional torch.Tensor or autograd.Variable
gain: an optional scaling factor
Examples:
>>> w = torch.Tensor(3, 5)
>>> nn.init.xavier_normal(w) | Fills the input Tensor or Variable with values according to the method described in "Understanding the
difficulty of training deep feedforward neural networks" - Glorot, X. & Bengio, Y. (2010), using a normal
distribution. The resulting tensor will have values sampled from :math:`N(0, std)` where
:math:`std = gain \\times \sqrt{2 / (fan\_in + fan\_out)}`. Also known as Glorot initialisation. | [
"Fills",
"the",
"input",
"Tensor",
"or",
"Variable",
"with",
"values",
"according",
"to",
"the",
"method",
"described",
"in",
"Understanding",
"the",
"difficulty",
"of",
"training",
"deep",
"feedforward",
"neural",
"networks",
"-",
"Glorot",
"X",
".",
"&",
"Be... | def xavier_normal(tensor, gain=1):
"""Fills the input Tensor or Variable with values according to the method described in "Understanding the
difficulty of training deep feedforward neural networks" - Glorot, X. & Bengio, Y. (2010), using a normal
distribution. The resulting tensor will have values sampled from :math:`N(0, std)` where
:math:`std = gain \\times \sqrt{2 / (fan\_in + fan\_out)}`. Also known as Glorot initialisation.
Args:
tensor: an n-dimensional torch.Tensor or autograd.Variable
gain: an optional scaling factor
Examples:
>>> w = torch.Tensor(3, 5)
>>> nn.init.xavier_normal(w)
"""
if isinstance(tensor, Variable):
xavier_normal(tensor.data, gain=gain)
return tensor
fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor)
std = gain * math.sqrt(2.0 / (fan_in + fan_out))
return tensor.normal_(0, std) | [
"def",
"xavier_normal",
"(",
"tensor",
",",
"gain",
"=",
"1",
")",
":",
"if",
"isinstance",
"(",
"tensor",
",",
"Variable",
")",
":",
"xavier_normal",
"(",
"tensor",
".",
"data",
",",
"gain",
"=",
"gain",
")",
"return",
"tensor",
"fan_in",
",",
"fan_ou... | https://github.com/magic282/NQG/blob/3006ff8b29684adead2eec82c304d81b5907fa74/seq2seq_pt/s2s/xinit.py#L203-L223 | |
sydney0zq/PTSNet | 1a9be3eb12216be354a77294cde75f330d278796 | coupled_otn_opn/tracking/maskrcnn/lib/utils/segms.py | python | polys_to_boxes | (polys) | return boxes_from_polys | Convert a list of polygons into an array of tight bounding boxes. | Convert a list of polygons into an array of tight bounding boxes. | [
"Convert",
"a",
"list",
"of",
"polygons",
"into",
"an",
"array",
"of",
"tight",
"bounding",
"boxes",
"."
] | def polys_to_boxes(polys):
"""Convert a list of polygons into an array of tight bounding boxes."""
boxes_from_polys = np.zeros((len(polys), 4), dtype=np.float32)
for i in range(len(polys)):
poly = polys[i]
x0 = min(min(p[::2]) for p in poly)
x1 = max(max(p[::2]) for p in poly)
y0 = min(min(p[1::2]) for p in poly)
y1 = max(max(p[1::2]) for p in poly)
boxes_from_polys[i, :] = [x0, y0, x1, y1]
return boxes_from_polys | [
"def",
"polys_to_boxes",
"(",
"polys",
")",
":",
"boxes_from_polys",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"polys",
")",
",",
"4",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"polys",
")... | https://github.com/sydney0zq/PTSNet/blob/1a9be3eb12216be354a77294cde75f330d278796/coupled_otn_opn/tracking/maskrcnn/lib/utils/segms.py#L120-L131 | |
keiffster/program-y | 8c99b56f8c32f01a7b9887b5daae9465619d0385 | src/programy/services/rest/generic/service.py | python | GenericService.__init__ | (self, configuration) | [] | def __init__(self, configuration):
RESTService.__init__(self, configuration) | [
"def",
"__init__",
"(",
"self",
",",
"configuration",
")",
":",
"RESTService",
".",
"__init__",
"(",
"self",
",",
"configuration",
")"
] | https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/services/rest/generic/service.py#L58-L59 | ||||
blampe/IbPy | cba912d2ecc669b0bf2980357ea7942e49c0825e | ib/ext/ScannerSubscription.py | python | ScannerSubscription.spRatingAbove | (self) | return self.m_spRatingAbove | generated source for method spRatingAbove | generated source for method spRatingAbove | [
"generated",
"source",
"for",
"method",
"spRatingAbove"
] | def spRatingAbove(self):
""" generated source for method spRatingAbove """
return self.m_spRatingAbove | [
"def",
"spRatingAbove",
"(",
"self",
")",
":",
"return",
"self",
".",
"m_spRatingAbove"
] | https://github.com/blampe/IbPy/blob/cba912d2ecc669b0bf2980357ea7942e49c0825e/ib/ext/ScannerSubscription.py#L99-L101 | |
cheshirekow/cmake_format | eff5df1f41c665ea7cac799396042e4f406ef09a | cmakelang/lint/basic_checker.py | python | statement_is_fundef | (node) | return funname in ("function", "macro") | Return true if a statement node is for a function or macro definition. | Return true if a statement node is for a function or macro definition. | [
"Return",
"true",
"if",
"a",
"statement",
"node",
"is",
"for",
"a",
"function",
"or",
"macro",
"definition",
"."
] | def statement_is_fundef(node):
"""Return true if a statement node is for a function or macro definition.
"""
tokens = node.get_semantic_tokens()
if not tokens:
return False
funname = tokens[0].spelling.lower()
return funname in ("function", "macro") | [
"def",
"statement_is_fundef",
"(",
"node",
")",
":",
"tokens",
"=",
"node",
".",
"get_semantic_tokens",
"(",
")",
"if",
"not",
"tokens",
":",
"return",
"False",
"funname",
"=",
"tokens",
"[",
"0",
"]",
".",
"spelling",
".",
"lower",
"(",
")",
"return",
... | https://github.com/cheshirekow/cmake_format/blob/eff5df1f41c665ea7cac799396042e4f406ef09a/cmakelang/lint/basic_checker.py#L71-L78 | |
Gallopsled/pwntools | 1573957cc8b1957399b7cc9bfae0c6f80630d5d4 | pwnlib/context/__init__.py | python | LocalNoarchContext | (function) | return setter | Same as LocalContext, but resets arch to :const:`'none'` by default
Example:
>>> @LocalNoarchContext
... def printArch():
... print(context.arch)
>>> printArch()
none | Same as LocalContext, but resets arch to :const:`'none'` by default | [
"Same",
"as",
"LocalContext",
"but",
"resets",
"arch",
"to",
":",
"const",
":",
"none",
"by",
"default"
] | def LocalNoarchContext(function):
"""
Same as LocalContext, but resets arch to :const:`'none'` by default
Example:
>>> @LocalNoarchContext
... def printArch():
... print(context.arch)
>>> printArch()
none
"""
@functools.wraps(function)
def setter(*a, **kw):
kw.setdefault('arch', 'none')
with context.local(**{k:kw.pop(k) for k,v in tuple(kw.items()) if isinstance(getattr(ContextType, k, None), property)}):
return function(*a, **kw)
return setter | [
"def",
"LocalNoarchContext",
"(",
"function",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"function",
")",
"def",
"setter",
"(",
"*",
"a",
",",
"*",
"*",
"kw",
")",
":",
"kw",
".",
"setdefault",
"(",
"'arch'",
",",
"'none'",
")",
"with",
"context"... | https://github.com/Gallopsled/pwntools/blob/1573957cc8b1957399b7cc9bfae0c6f80630d5d4/pwnlib/context/__init__.py#L1532-L1549 | |
hyperledger/aries-cloudagent-python | 2f36776e99f6053ae92eed8123b5b1b2e891c02a | aries_cloudagent/ledger/base.py | python | BaseLedger.get_revoc_reg_delta | (
self, revoc_reg_id: str, timestamp_from=0, timestamp_to=None
) | Look up a revocation registry delta by ID. | Look up a revocation registry delta by ID. | [
"Look",
"up",
"a",
"revocation",
"registry",
"delta",
"by",
"ID",
"."
] | async def get_revoc_reg_delta(
self, revoc_reg_id: str, timestamp_from=0, timestamp_to=None
) -> Tuple[dict, int]:
"""Look up a revocation registry delta by ID.""" | [
"async",
"def",
"get_revoc_reg_delta",
"(",
"self",
",",
"revoc_reg_id",
":",
"str",
",",
"timestamp_from",
"=",
"0",
",",
"timestamp_to",
"=",
"None",
")",
"->",
"Tuple",
"[",
"dict",
",",
"int",
"]",
":"
] | https://github.com/hyperledger/aries-cloudagent-python/blob/2f36776e99f6053ae92eed8123b5b1b2e891c02a/aries_cloudagent/ledger/base.py#L254-L257 | ||
venth/aws-adfs | 73810a6f60b1a0b1f00921889f163654954fd06f | aws_adfs/account_aliases_fetcher.py | python | account_aliases | (session, username, password, auth_method, saml_response, config) | return accounts | [] | def account_aliases(session, username, password, auth_method, saml_response, config):
alias_response = session.post(
'https://signin.aws.amazon.com/saml',
verify=config.ssl_verification,
headers={
'Accept-Language': 'en',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept': 'text/plain, */*; q=0.01',
},
auth=None,
data={
'SAMLResponse': saml_response,
}
)
logging.debug(u'''Request:
* url: {}
* headers: {}
Response:
* status: {}
* headers: {}
* body: {}
'''.format('https://signin.aws.amazon.com/saml',
alias_response.request.headers,
alias_response.status_code,
alias_response.headers,
alias_response.text))
html_response = ET.fromstring(alias_response.text, ET.HTMLParser())
accounts = {}
account_element_query = './/div[@class="saml-account-name"]'
for account_element in html_response.iterfind(account_element_query):
logging.debug(u'Found SAML account name: {}'.format(account_element.text))
m = _account_alias_pattern.search(account_element.text)
if m is not None:
accounts[m.group(2)] = m.group(1).strip()
if m is None:
m = _account_without_alias_pattern.search(account_element.text)
if m is not None:
accounts[m.group(1)] = m.group(0).strip()
return accounts | [
"def",
"account_aliases",
"(",
"session",
",",
"username",
",",
"password",
",",
"auth_method",
",",
"saml_response",
",",
"config",
")",
":",
"alias_response",
"=",
"session",
".",
"post",
"(",
"'https://signin.aws.amazon.com/saml'",
",",
"verify",
"=",
"config",... | https://github.com/venth/aws-adfs/blob/73810a6f60b1a0b1f00921889f163654954fd06f/aws_adfs/account_aliases_fetcher.py#L11-L55 | |||
steeve/xbmctorrent | e6bcb1037668959e1e3cb5ba8cf3e379c6638da9 | resources/site-packages/xbmcswift2/cli/create.py | python | validate_pluginid | (value) | return all(c in valid for c in value) | Returns True if the provided value is a valid pluglin id | Returns True if the provided value is a valid pluglin id | [
"Returns",
"True",
"if",
"the",
"provided",
"value",
"is",
"a",
"valid",
"pluglin",
"id"
] | def validate_pluginid(value):
'''Returns True if the provided value is a valid pluglin id'''
valid = string.ascii_letters + string.digits + '.'
return all(c in valid for c in value) | [
"def",
"validate_pluginid",
"(",
"value",
")",
":",
"valid",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
"+",
"'.'",
"return",
"all",
"(",
"c",
"in",
"valid",
"for",
"c",
"in",
"value",
")"
] | https://github.com/steeve/xbmctorrent/blob/e6bcb1037668959e1e3cb5ba8cf3e379c6638da9/resources/site-packages/xbmcswift2/cli/create.py#L60-L63 | |
robcarver17/pysystemtrade | b0385705b7135c52d39cb6d2400feece881bcca9 | systems/system_cache.py | python | base_system_cache | (protected=False, not_pickable=False) | return decorate | :param protected: is this protected from casual deletion?
:param not_pickable: can this not be saved using the pickle function (complex objects)
:return: decorator function | [] | def base_system_cache(protected=False, not_pickable=False):
"""
:param protected: is this protected from casual deletion?
:param not_pickable: can this not be saved using the pickle function (complex objects)
:return: decorator function
"""
# this pattern from Beazleys book; function inside function to get
# arguments to wrapper
def decorate(func):
@wraps(func)
# note 'self' as always called from inside system class
def wrapper(self, *args, **kwargs):
system = self
# instrument_classify has to be false, else infinite loop
ans = system.cache.calc_or_cache(
func,
system,
*args,
protected=protected,
not_pickable=not_pickable,
instrument_classify=False,
use_arg_names = False,
**kwargs,
)
return ans
return wrapper
return decorate | [
"def",
"base_system_cache",
"(",
"protected",
"=",
"False",
",",
"not_pickable",
"=",
"False",
")",
":",
"# this pattern from Beazleys book; function inside function to get",
"# arguments to wrapper",
"def",
"decorate",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
... | https://github.com/robcarver17/pysystemtrade/blob/b0385705b7135c52d39cb6d2400feece881bcca9/systems/system_cache.py#L741-L774 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_hxb2/lib/python3.5/site-packages/django/core/serializers/pyyaml.py | python | Deserializer | (stream_or_string, **options) | Deserialize a stream or string of YAML data. | Deserialize a stream or string of YAML data. | [
"Deserialize",
"a",
"stream",
"or",
"string",
"of",
"YAML",
"data",
"."
] | def Deserializer(stream_or_string, **options):
"""
Deserialize a stream or string of YAML data.
"""
if isinstance(stream_or_string, bytes):
stream_or_string = stream_or_string.decode('utf-8')
if isinstance(stream_or_string, six.string_types):
stream = StringIO(stream_or_string)
else:
stream = stream_or_string
try:
for obj in PythonDeserializer(yaml.load(stream, Loader=SafeLoader), **options):
yield obj
except GeneratorExit:
raise
except Exception as e:
# Map to deserializer error
six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2]) | [
"def",
"Deserializer",
"(",
"stream_or_string",
",",
"*",
"*",
"options",
")",
":",
"if",
"isinstance",
"(",
"stream_or_string",
",",
"bytes",
")",
":",
"stream_or_string",
"=",
"stream_or_string",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"isinstance",
"(",
... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/core/serializers/pyyaml.py#L67-L84 | ||
huggingface/transformers | 623b4f7c63f60cce917677ee704d6c93ee960b4b | src/transformers/models/electra/modeling_flax_electra.py | python | FlaxElectraOutput.setup | (self) | [] | def setup(self):
self.dense = nn.Dense(
self.config.hidden_size,
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
dtype=self.dtype,
)
self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype) | [
"def",
"setup",
"(",
"self",
")",
":",
"self",
".",
"dense",
"=",
"nn",
".",
"Dense",
"(",
"self",
".",
"config",
".",
"hidden_size",
",",
"kernel_init",
"=",
"jax",
".",
"nn",
".",
"initializers",
".",
"normal",
"(",
"self",
".",
"config",
".",
"i... | https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/electra/modeling_flax_electra.py#L354-L361 | ||||
ales-tsurko/cells | 4cf7e395cd433762bea70cdc863a346f3a6fe1d0 | packaging/macos/python/lib/python3.7/site-packages/pip/_vendor/pyparsing.py | python | originalTextFor | (expr, asString=True) | return matchExpr | Helper to return the original, untokenized text for a given
expression. Useful to restore the parsed fields of an HTML start
tag into the raw tag text itself, or to revert separate tokens with
intervening whitespace back to the original matching input text. By
default, returns astring containing the original parsed text.
If the optional ``asString`` argument is passed as
``False``, then the return value is
a :class:`ParseResults` containing any results names that
were originally matched, and a single token containing the original
matched text from the input string. So if the expression passed to
:class:`originalTextFor` contains expressions with defined
results names, you must set ``asString`` to ``False`` if you
want to preserve those results name values.
Example::
src = "this is test <b> bold <i>text</i> </b> normal text "
for tag in ("b","i"):
opener,closer = makeHTMLTags(tag)
patt = originalTextFor(opener + SkipTo(closer) + closer)
print(patt.searchString(src)[0])
prints::
['<b> bold <i>text</i> </b>']
['<i>text</i>'] | Helper to return the original, untokenized text for a given
expression. Useful to restore the parsed fields of an HTML start
tag into the raw tag text itself, or to revert separate tokens with
intervening whitespace back to the original matching input text. By
default, returns astring containing the original parsed text. | [
"Helper",
"to",
"return",
"the",
"original",
"untokenized",
"text",
"for",
"a",
"given",
"expression",
".",
"Useful",
"to",
"restore",
"the",
"parsed",
"fields",
"of",
"an",
"HTML",
"start",
"tag",
"into",
"the",
"raw",
"tag",
"text",
"itself",
"or",
"to",... | def originalTextFor(expr, asString=True):
"""Helper to return the original, untokenized text for a given
expression. Useful to restore the parsed fields of an HTML start
tag into the raw tag text itself, or to revert separate tokens with
intervening whitespace back to the original matching input text. By
default, returns astring containing the original parsed text.
If the optional ``asString`` argument is passed as
``False``, then the return value is
a :class:`ParseResults` containing any results names that
were originally matched, and a single token containing the original
matched text from the input string. So if the expression passed to
:class:`originalTextFor` contains expressions with defined
results names, you must set ``asString`` to ``False`` if you
want to preserve those results name values.
Example::
src = "this is test <b> bold <i>text</i> </b> normal text "
for tag in ("b","i"):
opener,closer = makeHTMLTags(tag)
patt = originalTextFor(opener + SkipTo(closer) + closer)
print(patt.searchString(src)[0])
prints::
['<b> bold <i>text</i> </b>']
['<i>text</i>']
"""
locMarker = Empty().setParseAction(lambda s,loc,t: loc)
endlocMarker = locMarker.copy()
endlocMarker.callPreparse = False
matchExpr = locMarker("_original_start") + expr + endlocMarker("_original_end")
if asString:
extractText = lambda s,l,t: s[t._original_start:t._original_end]
else:
def extractText(s,l,t):
t[:] = [s[t.pop('_original_start'):t.pop('_original_end')]]
matchExpr.setParseAction(extractText)
matchExpr.ignoreExprs = expr.ignoreExprs
return matchExpr | [
"def",
"originalTextFor",
"(",
"expr",
",",
"asString",
"=",
"True",
")",
":",
"locMarker",
"=",
"Empty",
"(",
")",
".",
"setParseAction",
"(",
"lambda",
"s",
",",
"loc",
",",
"t",
":",
"loc",
")",
"endlocMarker",
"=",
"locMarker",
".",
"copy",
"(",
... | https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/site-packages/pip/_vendor/pyparsing.py#L5173-L5213 | |
bert-nmt/bert-nmt | fcb616d28091ac23c9c16f30e6870fe90b8576d6 | fairseq/optim/fairseq_optimizer.py | python | FairseqOptimizer.optimizer | (self) | return self._optimizer | Return a torch.optim.optimizer.Optimizer instance. | Return a torch.optim.optimizer.Optimizer instance. | [
"Return",
"a",
"torch",
".",
"optim",
".",
"optimizer",
".",
"Optimizer",
"instance",
"."
] | def optimizer(self):
"""Return a torch.optim.optimizer.Optimizer instance."""
if not hasattr(self, '_optimizer'):
raise NotImplementedError
if not isinstance(self._optimizer, torch.optim.Optimizer):
raise ValueError('_optimizer must be an instance of torch.optim.Optimizer')
return self._optimizer | [
"def",
"optimizer",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_optimizer'",
")",
":",
"raise",
"NotImplementedError",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_optimizer",
",",
"torch",
".",
"optim",
".",
"Optimizer",
")",
"... | https://github.com/bert-nmt/bert-nmt/blob/fcb616d28091ac23c9c16f30e6870fe90b8576d6/fairseq/optim/fairseq_optimizer.py#L26-L32 | |
cuthbertLab/music21 | bd30d4663e52955ed922c10fdf541419d8c67671 | music21/analysis/metrical.py | python | thomassenMelodicAccent | (streamIn) | adds a attribute melodicAccent to each note of a :class:`~music21.stream.Stream` object
according to the method postulated in Joseph M. Thomassen, "Melodic accent: Experiments and
a tentative model," ''Journal of the Acoustical Society of America'', Vol. 71, No. 6 (1982) pp.
1598-1605; with, Erratum, ''Journal of the Acoustical Society of America'', Vol. 73,
No. 1 (1983) p.373, and in David Huron and Matthew Royal,
"What is melodic accent? Converging evidence
from musical practice." ''Music Perception'', Vol. 13, No. 4 (1996) pp. 489-516.
Similar to the humdrum melac_ tool.
.. _melac: https://www.humdrum.org/Humdrum/commands/melac.html
Takes in a Stream of :class:`~music21.note.Note` objects (use `.flatten().notes` to get it, or
better `.flatten().getElementsByClass('Note')` to filter out chords) and adds the attribute to
each. Note that Huron and Royal's work suggests that melodic accent has a correlation
with metrical accent only for solo works/passages; even treble passages do not have a
strong correlation. (Gregorian chants were found to have a strong ''negative'' correlation
between melodic accent and syllable onsets)
Following Huron's lead, we assign a `melodicAccent` of 1.0 to the first note in a piece
and take the accent marker of the first interval alone to the second note and
of the last interval alone to be the accent of the last note.
Example from Thomassen, figure 5:
>>> s = converter.parse('tinynotation: 7/4 c4 c c d e d d')
>>> analysis.metrical.thomassenMelodicAccent(s.flatten().notes)
>>> for n in s.flatten().notes:
... (n.pitch.nameWithOctave, n.melodicAccent)
('C4', 1.0)
('C4', 0.0)
('C4', 0.0)
('D4', 0.33)
('E4', 0.5561)
('D4', 0.17)
('D4', 0.0) | adds a attribute melodicAccent to each note of a :class:`~music21.stream.Stream` object
according to the method postulated in Joseph M. Thomassen, "Melodic accent: Experiments and
a tentative model," ''Journal of the Acoustical Society of America'', Vol. 71, No. 6 (1982) pp.
1598-1605; with, Erratum, ''Journal of the Acoustical Society of America'', Vol. 73,
No. 1 (1983) p.373, and in David Huron and Matthew Royal,
"What is melodic accent? Converging evidence
from musical practice." ''Music Perception'', Vol. 13, No. 4 (1996) pp. 489-516. | [
"adds",
"a",
"attribute",
"melodicAccent",
"to",
"each",
"note",
"of",
"a",
":",
"class",
":",
"~music21",
".",
"stream",
".",
"Stream",
"object",
"according",
"to",
"the",
"method",
"postulated",
"in",
"Joseph",
"M",
".",
"Thomassen",
"Melodic",
"accent",
... | def thomassenMelodicAccent(streamIn):
'''
adds a attribute melodicAccent to each note of a :class:`~music21.stream.Stream` object
according to the method postulated in Joseph M. Thomassen, "Melodic accent: Experiments and
a tentative model," ''Journal of the Acoustical Society of America'', Vol. 71, No. 6 (1982) pp.
1598-1605; with, Erratum, ''Journal of the Acoustical Society of America'', Vol. 73,
No. 1 (1983) p.373, and in David Huron and Matthew Royal,
"What is melodic accent? Converging evidence
from musical practice." ''Music Perception'', Vol. 13, No. 4 (1996) pp. 489-516.
Similar to the humdrum melac_ tool.
.. _melac: https://www.humdrum.org/Humdrum/commands/melac.html
Takes in a Stream of :class:`~music21.note.Note` objects (use `.flatten().notes` to get it, or
better `.flatten().getElementsByClass('Note')` to filter out chords) and adds the attribute to
each. Note that Huron and Royal's work suggests that melodic accent has a correlation
with metrical accent only for solo works/passages; even treble passages do not have a
strong correlation. (Gregorian chants were found to have a strong ''negative'' correlation
between melodic accent and syllable onsets)
Following Huron's lead, we assign a `melodicAccent` of 1.0 to the first note in a piece
and take the accent marker of the first interval alone to the second note and
of the last interval alone to be the accent of the last note.
Example from Thomassen, figure 5:
>>> s = converter.parse('tinynotation: 7/4 c4 c c d e d d')
>>> analysis.metrical.thomassenMelodicAccent(s.flatten().notes)
>>> for n in s.flatten().notes:
... (n.pitch.nameWithOctave, n.melodicAccent)
('C4', 1.0)
('C4', 0.0)
('C4', 0.0)
('D4', 0.33)
('E4', 0.5561)
('D4', 0.17)
('D4', 0.0)
'''
# we use .ps instead of Intervals for speed, since
# we just need perceived contours
maxNotes = len(streamIn) - 1
p2Accent = 1.0
for i, n in enumerate(streamIn):
if i == 0:
n.melodicAccent = 1.0
continue
elif i == maxNotes:
n.melodicAccent = p2Accent
continue
lastPs = streamIn[i - 1].pitch.ps
thisPs = n.pitch.ps
nextPs = streamIn[i + 1].pitch.ps
if lastPs == thisPs and thisPs == nextPs:
thisAccent = 0.0
nextAccent = 0.0
elif lastPs != thisPs and thisPs == nextPs:
thisAccent = 1.0
nextAccent = 0.0
elif lastPs == thisPs and thisPs != nextPs:
thisAccent = 0.0
nextAccent = 1.0
elif lastPs < thisPs and thisPs > nextPs:
thisAccent = 0.83
nextAccent = 0.17
elif lastPs > thisPs and thisPs < nextPs:
thisAccent = 0.71
nextAccent = 0.29
elif lastPs < thisPs < nextPs:
thisAccent = 0.33
nextAccent = 0.67
elif lastPs > thisPs > nextPs:
thisAccent = 0.5
nextAccent = 0.5
else: # pragma: no cover # should not happen
thisAccent = 0.0
nextAccent = 0.0
n.melodicAccent = thisAccent * p2Accent
p2Accent = nextAccent | [
"def",
"thomassenMelodicAccent",
"(",
"streamIn",
")",
":",
"# we use .ps instead of Intervals for speed, since",
"# we just need perceived contours",
"maxNotes",
"=",
"len",
"(",
"streamIn",
")",
"-",
"1",
"p2Accent",
"=",
"1.0",
"for",
"i",
",",
"n",
"in",
"enumerat... | https://github.com/cuthbertLab/music21/blob/bd30d4663e52955ed922c10fdf541419d8c67671/music21/analysis/metrical.py#L74-L157 | ||
joschabach/micropsi2 | 74a2642d20da9da1d64acc5e4c11aeabee192a27 | micropsi_server/bottle.py | python | Router.build | (self, _name, *anons, **query) | Build an URL by filling the wildcards in a rule. | Build an URL by filling the wildcards in a rule. | [
"Build",
"an",
"URL",
"by",
"filling",
"the",
"wildcards",
"in",
"a",
"rule",
"."
] | def build(self, _name, *anons, **query):
''' Build an URL by filling the wildcards in a rule. '''
builder = self.builder.get(_name)
if not builder: raise RouteBuildError("No route with that name.", _name)
try:
for i, value in enumerate(anons): query['anon%d'%i] = value
url = ''.join([f(query.pop(n)) if n else f for (n,f) in builder])
return url if not query else url+'?'+urlencode(query)
except KeyError:
raise RouteBuildError('Missing URL argument: %r' % _e().args[0]) | [
"def",
"build",
"(",
"self",
",",
"_name",
",",
"*",
"anons",
",",
"*",
"*",
"query",
")",
":",
"builder",
"=",
"self",
".",
"builder",
".",
"get",
"(",
"_name",
")",
"if",
"not",
"builder",
":",
"raise",
"RouteBuildError",
"(",
"\"No route with that n... | https://github.com/joschabach/micropsi2/blob/74a2642d20da9da1d64acc5e4c11aeabee192a27/micropsi_server/bottle.py#L400-L409 | ||
jgilhutton/PyxieWPS | ba590343a73db98f898bda8b56b43928ac90947f | pyxiewps-EN-swearing-version.py | python | help | () | Help information | Help information | [
"Help",
"information"
] | def help():
"""
Help information
"""
print
print ' Examples:'
print
print "\tpyxiewps -p -t 6 -c 7 -P -o file.txt -f"
print "\tpyxiewps --use-pixie --time 6 --channel 7 --prompt --output file.txt"
print "\tpyxiewps -m STATIC"
print "\tpyxiewps --mode DRIVE"
print
print ' Individual options:'
print
print '\t-p --use-pixie Once all the data is captured with reaver [False]'
print '\t the script tries to get the WPS pin with pixiewps.'
print '\t-a --airodump-time [time] Airodump spends this amount of time enumerating APs [3]'
print '\t-t --time [time] Set the time used to get the hex data from the AP. [6]'
print '\t-c --channel [channel] Set the listening channel to enumerate the WPS-active APs.'
print '\t If not set, all channels are listened.'
print '\t-P --prompt If more than one WPS-active AP is found, ask the user [False]'
print '\t the target to attack.'
print '\t-o --output [file] Outputs all the data into a file.'
print '\t-f --pass If the WPS pin is found, the script uses reaver again to retrieve'
print '\t the WPA password of the AP.'
print '\t-q --quiet Doesn\'t print the AP information. Will print the WPS pin and pass if found.'
print '\t-F --forever Runs the program on a While loop so the user can scan and attack a hole'
print '\t zone without having to execute the program over and over again.'
print '\t-A --again Target is attacked again in case of success without prompting the user.'
print '\t-s --signal [-NUMBER] APs with RSSI lower than NUMBER will be ignored [-100]'
print '\t A value of "-50" will ignore APs with RSSI between'
print '\t -100 and -51 and will attack APs which RSSI goes from -50 to 0'
print '\t-M --max-aps [number] Max amount of APs to be attacked.'
print '\t-m --mode [mode] Set the mode preset. Any preset option can be override'
print '\t by giving its argument and value on the commandline.'
print '\t i.e: "-m DRIVE -t 10"'
print
print ' Available modes:'
print
print '\tWALK:'
print '\t\t[-p] [-f] [-a 4] [-t 8] [-F] [-M 2]'
print '\t\tTries to get the WPS pin'
print '\t\t4 seconds will be used to enumerate the APs'
print '\t\t8 seconds will be used to fetch the AP information'
print '\t\tWill try to get the password'
print '\t\tThe program will run in a while loop.'
print '\t\tA max amount of 2 APs will be attacked'
print '\t\tAP won\'t be atacked again if failed once'
print '\tDRIVE:'
print '\t\t[-p] [-t 10] [-F] [-M 1]'
print '\t\tTries to get the WPS pin'
print '\t\t3 seconds will be used to enumerate the APs'
print '\t\t10 seconds will be used to fetch the AP information'
print '\t\tWon\'t try to get the password'
print '\t\tThe program will run in a while loop.'
print '\t\tOnly one AP will be attacked'
print '\t\tAP won\'t be atacked again if failed once'
print '\tSTATIC:'
print '\t\t[-p] [-f] [-a 5] [-t 10] [-P] [-O]'
print '\t\tTries to get the WPS pin'
print '\t\t5 seconds will be used to enumerate the APs'
print '\t\t10 seconds will be used to fetch the AP information'
print '\t\tWill try to get the password'
print '\t\tThe program will run only once'
print '\t\tUser will be prompted for an AP to attack'
print '\t\tAP will be atacked again if failed once'
exit() | [
"def",
"help",
"(",
")",
":",
"print",
"print",
"' Examples:'",
"print",
"print",
"\"\\tpyxiewps -p -t 6 -c 7 -P -o file.txt -f\"",
"print",
"\"\\tpyxiewps --use-pixie --time 6 --channel 7 --prompt --output file.txt\"",
"print",
"\"\\tpyxiewps -m STATIC\"",
"print",
"\"\\tpyxiewps -... | https://github.com/jgilhutton/PyxieWPS/blob/ba590343a73db98f898bda8b56b43928ac90947f/pyxiewps-EN-swearing-version.py#L175-L242 | ||
orakaro/rainbowstream | 96141fac10675e0775d703f65a59c4477a48c57e | rainbowstream/rainbow.py | python | urlopen | () | Open url | Open url | [
"Open",
"url"
] | def urlopen():
"""
Open url
"""
t = Twitter(auth=authen())
try:
if not g['stuff'].isdigit():
return
tid = c['tweet_dict'][int(g['stuff'])]
tweet = t.statuses.show(id=tid)
urls = tweet['entities']['urls']
if not urls:
printNicely(light_magenta('No url here @.@!'))
return
else:
for url in urls:
expanded_url = url['expanded_url']
webbrowser.open(expanded_url)
except:
debug_option()
printNicely(red('Sorry I can\'t open url in this tweet.')) | [
"def",
"urlopen",
"(",
")",
":",
"t",
"=",
"Twitter",
"(",
"auth",
"=",
"authen",
"(",
")",
")",
"try",
":",
"if",
"not",
"g",
"[",
"'stuff'",
"]",
".",
"isdigit",
"(",
")",
":",
"return",
"tid",
"=",
"c",
"[",
"'tweet_dict'",
"]",
"[",
"int",
... | https://github.com/orakaro/rainbowstream/blob/96141fac10675e0775d703f65a59c4477a48c57e/rainbowstream/rainbow.py#L836-L856 | ||
MaurizioFD/RecSys2019_DeepLearning_Evaluation | 0fb6b7f5c396f8525316ed66cf9c9fdb03a5fa9b | Conferences/SIGIR/CMN_our_interface/Pinterest/PinterestICCVReader.py | python | Dataset_NeuralCollaborativeFiltering.load_rating_file_as_matrix | (self, filename) | return mat | Read .rating file and Return dok matrix.
The first line of .rating file is: num_users\t num_items | Read .rating file and Return dok matrix.
The first line of .rating file is: num_users\t num_items | [
"Read",
".",
"rating",
"file",
"and",
"Return",
"dok",
"matrix",
".",
"The",
"first",
"line",
"of",
".",
"rating",
"file",
"is",
":",
"num_users",
"\\",
"t",
"num_items"
] | def load_rating_file_as_matrix(self, filename):
'''
Read .rating file and Return dok matrix.
The first line of .rating file is: num_users\t num_items
'''
# Get number of users and items
num_users, num_items = 0, 0
with open(filename, "r") as f:
line = f.readline()
while line != None and line != "":
arr = line.split("\t")
u, i = int(arr[0]), int(arr[1])
num_users = max(num_users, u)
num_items = max(num_items, i)
line = f.readline()
# Construct matrix
mat = sps.dok_matrix((num_users+1, num_items+1), dtype=np.float32)
with open(filename, "r") as f:
line = f.readline()
while line != None and line != "":
arr = line.split("\t")
user, item, rating = int(arr[0]), int(arr[1]), float(arr[2])
if (rating > 0):
mat[user, item] = 1.0
line = f.readline()
return mat | [
"def",
"load_rating_file_as_matrix",
"(",
"self",
",",
"filename",
")",
":",
"# Get number of users and items",
"num_users",
",",
"num_items",
"=",
"0",
",",
"0",
"with",
"open",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"f",
":",
"line",
"=",
"f",
".",
"r... | https://github.com/MaurizioFD/RecSys2019_DeepLearning_Evaluation/blob/0fb6b7f5c396f8525316ed66cf9c9fdb03a5fa9b/Conferences/SIGIR/CMN_our_interface/Pinterest/PinterestICCVReader.py#L155-L180 | |
iclavera/learning_to_adapt | bd7d99ba402521c96631e7d09714128f549db0f1 | learning_to_adapt/mujoco_py/mjtypes.py | python | MjvGeomWrapper.category | (self, value) | [] | def category(self, value):
self._wrapped.contents.category = value | [
"def",
"category",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_wrapped",
".",
"contents",
".",
"category",
"=",
"value"
] | https://github.com/iclavera/learning_to_adapt/blob/bd7d99ba402521c96631e7d09714128f549db0f1/learning_to_adapt/mujoco_py/mjtypes.py#L1526-L1527 | ||||
caiiiac/Machine-Learning-with-Python | 1a26c4467da41ca4ebc3d5bd789ea942ef79422f | MachineLearning/venv/lib/python3.5/site-packages/scipy/io/matlab/mio4.py | python | VarReader4.read_full_array | (self, hdr) | return self.read_sub_array(hdr) | Full (rather than sparse) matrix getter
Read matrix (array) can be real or complex
Parameters
----------
hdr : ``VarHeader4`` instance
Returns
-------
arr : ndarray
complex array if ``hdr.is_complex`` is True, otherwise a real
numeric array | Full (rather than sparse) matrix getter | [
"Full",
"(",
"rather",
"than",
"sparse",
")",
"matrix",
"getter"
] | def read_full_array(self, hdr):
''' Full (rather than sparse) matrix getter
Read matrix (array) can be real or complex
Parameters
----------
hdr : ``VarHeader4`` instance
Returns
-------
arr : ndarray
complex array if ``hdr.is_complex`` is True, otherwise a real
numeric array
'''
if hdr.is_complex:
# avoid array copy to save memory
res = self.read_sub_array(hdr, copy=False)
res_j = self.read_sub_array(hdr, copy=False)
return res + (res_j * 1j)
return self.read_sub_array(hdr) | [
"def",
"read_full_array",
"(",
"self",
",",
"hdr",
")",
":",
"if",
"hdr",
".",
"is_complex",
":",
"# avoid array copy to save memory",
"res",
"=",
"self",
".",
"read_sub_array",
"(",
"hdr",
",",
"copy",
"=",
"False",
")",
"res_j",
"=",
"self",
".",
"read_s... | https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/scipy/io/matlab/mio4.py#L187-L207 | |
mesalock-linux/mesapy | ed546d59a21b36feb93e2309d5c6b75aa0ad95c9 | pypy/interpreter/baseobjspace.py | python | ObjSpace.unpackiterable | (self, w_iterable, expected_length=-1) | Unpack an iterable into a real (interpreter-level) list.
Raise an OperationError(w_ValueError) if the length is wrong. | Unpack an iterable into a real (interpreter-level) list. | [
"Unpack",
"an",
"iterable",
"into",
"a",
"real",
"(",
"interpreter",
"-",
"level",
")",
"list",
"."
] | def unpackiterable(self, w_iterable, expected_length=-1):
"""Unpack an iterable into a real (interpreter-level) list.
Raise an OperationError(w_ValueError) if the length is wrong."""
w_iterator = self.iter(w_iterable)
if expected_length == -1:
if self.is_generator(w_iterator):
# special hack for speed
lst_w = []
w_iterator.unpack_into(lst_w)
return lst_w
return self._unpackiterable_unknown_length(w_iterator, w_iterable)
else:
lst_w = self._unpackiterable_known_length(w_iterator,
expected_length)
return lst_w[:] | [
"def",
"unpackiterable",
"(",
"self",
",",
"w_iterable",
",",
"expected_length",
"=",
"-",
"1",
")",
":",
"w_iterator",
"=",
"self",
".",
"iter",
"(",
"w_iterable",
")",
"if",
"expected_length",
"==",
"-",
"1",
":",
"if",
"self",
".",
"is_generator",
"("... | https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/pypy/interpreter/baseobjspace.py#L912-L927 | ||
sfepy/sfepy | 02ec7bb2ab39ee1dfe1eb4cd509f0ffb7dcc8b25 | sfepy/discrete/problem.py | python | Problem.get_tss_functions | (self, state0, update_bcs=True, update_materials=True,
save_results=True,
step_hook=None, post_process_hook=None) | return init_fun, prestep_fun, poststep_fun | Get the problem-dependent functions required by the time-stepping
solver during the solution process.
Parameters
----------
state0 : State
The state holding the problem variables.
update_bcs : bool, optional
If True, update the boundary conditions in each `prestep_fun` call.
update_materials : bool, optional
If True, update the values of material parameters in each
`prestep_fun` call.
save_results : bool, optional
If True, save the results in each `poststep_fun` call.
step_hook : callable, optional
The optional user-defined function that is called in each
`poststep_fun` call before saving the results.
post_process_hook : callable, optional
The optional user-defined function that is passed in each
`poststep_fun` to :func:`Problem.save_state()`.
Returns
-------
init_fun : callable
The initialization function called before the actual time-stepping.
prestep_fun : callable
The function called in each time (sub-)step prior to the nonlinear
solver call.
poststep_fun : callable
The function called at the end of each time step. | Get the problem-dependent functions required by the time-stepping
solver during the solution process. | [
"Get",
"the",
"problem",
"-",
"dependent",
"functions",
"required",
"by",
"the",
"time",
"-",
"stepping",
"solver",
"during",
"the",
"solution",
"process",
"."
] | def get_tss_functions(self, state0, update_bcs=True, update_materials=True,
save_results=True,
step_hook=None, post_process_hook=None):
"""
Get the problem-dependent functions required by the time-stepping
solver during the solution process.
Parameters
----------
state0 : State
The state holding the problem variables.
update_bcs : bool, optional
If True, update the boundary conditions in each `prestep_fun` call.
update_materials : bool, optional
If True, update the values of material parameters in each
`prestep_fun` call.
save_results : bool, optional
If True, save the results in each `poststep_fun` call.
step_hook : callable, optional
The optional user-defined function that is called in each
`poststep_fun` call before saving the results.
post_process_hook : callable, optional
The optional user-defined function that is passed in each
`poststep_fun` to :func:`Problem.save_state()`.
Returns
-------
init_fun : callable
The initialization function called before the actual time-stepping.
prestep_fun : callable
The function called in each time (sub-)step prior to the nonlinear
solver call.
poststep_fun : callable
The function called at the end of each time step.
"""
is_save = make_is_save(self.conf.options)
def init_fun(ts, vec0):
if not ts.is_quasistatic:
self.init_time(ts)
is_save.reset(ts)
restart_filename = self.conf.options.get('load_restart', None)
if restart_filename is not None:
self.load_restart(restart_filename, state=state0, ts=ts)
self.advance(ts)
ts.advance()
state = self.create_state()
vec0 = state.get_vec(self.active_only)
return vec0
def prestep_fun(ts, vec):
if update_bcs:
self.time_update(ts)
state = state0.copy()
state.set_vec(vec, self.active_only)
state.apply_ebc()
if update_materials:
self.update_materials(verbose=self.conf.get('verbose', True))
def poststep_fun(ts, vec):
state = state0.copy(preserve_caches=True)
state.set_vec(vec, self.active_only)
if step_hook is not None:
step_hook(self, ts, state)
restart_filename = self.get_restart_filename(ts=ts)
if restart_filename is not None:
self.save_restart(restart_filename, state, ts=ts)
if save_results and is_save(ts):
if not isinstance(self.get_solver(), StationarySolver):
suffix = ts.suffix % ts.step
else:
suffix = None
filename = self.get_output_name(suffix=suffix)
self.save_state(filename, state,
post_process_hook=post_process_hook,
file_per_var=None,
ts=ts,
file_format=self.file_format)
self.advance(ts)
return init_fun, prestep_fun, poststep_fun | [
"def",
"get_tss_functions",
"(",
"self",
",",
"state0",
",",
"update_bcs",
"=",
"True",
",",
"update_materials",
"=",
"True",
",",
"save_results",
"=",
"True",
",",
"step_hook",
"=",
"None",
",",
"post_process_hook",
"=",
"None",
")",
":",
"is_save",
"=",
... | https://github.com/sfepy/sfepy/blob/02ec7bb2ab39ee1dfe1eb4cd509f0ffb7dcc8b25/sfepy/discrete/problem.py#L1200-L1289 | |
morganstanley/treadmill | f18267c665baf6def4374d21170198f63ff1cde4 | lib/python/treadmill/scheduler/__init__.py | python | zero_capacity | () | return np.zeros(DIMENSION_COUNT) | Returns zero capacity vector. | Returns zero capacity vector. | [
"Returns",
"zero",
"capacity",
"vector",
"."
] | def zero_capacity():
"""Returns zero capacity vector.
"""
assert DIMENSION_COUNT is not None, 'Dimension count not set.'
return np.zeros(DIMENSION_COUNT) | [
"def",
"zero_capacity",
"(",
")",
":",
"assert",
"DIMENSION_COUNT",
"is",
"not",
"None",
",",
"'Dimension count not set.'",
"return",
"np",
".",
"zeros",
"(",
"DIMENSION_COUNT",
")"
] | https://github.com/morganstanley/treadmill/blob/f18267c665baf6def4374d21170198f63ff1cde4/lib/python/treadmill/scheduler/__init__.py#L60-L64 | |
wikimedia/pywikibot | 81a01ffaec7271bf5b4b170f85a80388420a4e78 | pywikibot/page/__init__.py | python | BaseLink.fromPage | (cls, page) | return cls(title, namespace=page.namespace(), site=page.site) | Create a BaseLink to a Page.
:param page: target pywikibot.page.Page
:type page: pywikibot.page.Page
:rtype: pywikibot.page.BaseLink | Create a BaseLink to a Page. | [
"Create",
"a",
"BaseLink",
"to",
"a",
"Page",
"."
] | def fromPage(cls, page):
"""
Create a BaseLink to a Page.
:param page: target pywikibot.page.Page
:type page: pywikibot.page.Page
:rtype: pywikibot.page.BaseLink
"""
title = page.title(with_ns=False,
allow_interwiki=False,
with_section=False)
return cls(title, namespace=page.namespace(), site=page.site) | [
"def",
"fromPage",
"(",
"cls",
",",
"page",
")",
":",
"title",
"=",
"page",
".",
"title",
"(",
"with_ns",
"=",
"False",
",",
"allow_interwiki",
"=",
"False",
",",
"with_section",
"=",
"False",
")",
"return",
"cls",
"(",
"title",
",",
"namespace",
"=",
... | https://github.com/wikimedia/pywikibot/blob/81a01ffaec7271bf5b4b170f85a80388420a4e78/pywikibot/page/__init__.py#L5219-L5232 | |
google-research/language | 61fa7260ac7d690d11ef72ca863e45a37c0bdc80 | language/bert_extraction/steal_bert_classifier/models/run_classifier.py | python | MnliProcessor.get_train_examples | (self, data_dir) | return self._create_examples(
self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") | See base class. | See base class. | [
"See",
"base",
"class",
"."
] | def get_train_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") | [
"def",
"get_train_examples",
"(",
"self",
",",
"data_dir",
")",
":",
"return",
"self",
".",
"_create_examples",
"(",
"self",
".",
"_read_tsv",
"(",
"os",
".",
"path",
".",
"join",
"(",
"data_dir",
",",
"\"train.tsv\"",
")",
")",
",",
"\"train\"",
")"
] | https://github.com/google-research/language/blob/61fa7260ac7d690d11ef72ca863e45a37c0bdc80/language/bert_extraction/steal_bert_classifier/models/run_classifier.py#L267-L270 | |
IntelLabs/coach | dea46ae0d22b0a0cd30b9fc138a4a2642e1b9d9d | rl_coach/core_types.py | python | Episode.is_empty | (self) | return self.length() == 0 | Check if the episode is empty
:return: A boolean value determining if the episode is empty or not | Check if the episode is empty | [
"Check",
"if",
"the",
"episode",
"is",
"empty"
] | def is_empty(self) -> bool:
"""
Check if the episode is empty
:return: A boolean value determining if the episode is empty or not
"""
return self.length() == 0 | [
"def",
"is_empty",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"length",
"(",
")",
"==",
"0"
] | https://github.com/IntelLabs/coach/blob/dea46ae0d22b0a0cd30b9fc138a4a2642e1b9d9d/rl_coach/core_types.py#L727-L733 | |
Germey/CookiesPool | baf1989fcbe56634907ce9c923d74a022740ee87 | cookiespool/api.py | python | add | (name, username, password) | return result | 添加用户, 访问地址如 /weibo/add/user/password | 添加用户, 访问地址如 /weibo/add/user/password | [
"添加用户",
"访问地址如",
"/",
"weibo",
"/",
"add",
"/",
"user",
"/",
"password"
] | def add(name, username, password):
"""
添加用户, 访问地址如 /weibo/add/user/password
"""
g = get_conn()
result = getattr(g, name + '_account').set(username, password)
return result | [
"def",
"add",
"(",
"name",
",",
"username",
",",
"password",
")",
":",
"g",
"=",
"get_conn",
"(",
")",
"result",
"=",
"getattr",
"(",
"g",
",",
"name",
"+",
"'_account'",
")",
".",
"set",
"(",
"username",
",",
"password",
")",
"return",
"result"
] | https://github.com/Germey/CookiesPool/blob/baf1989fcbe56634907ce9c923d74a022740ee87/cookiespool/api.py#L40-L46 | |
SCons/scons | 309f0234d1d9cc76955818be47c5c722f577dac6 | SCons/cpp.py | python | FunctionEvaluator.__call__ | (self, *values) | return eval(statement, globals(), localvars) | Evaluates the expansion of a #define macro function called
with the specified values. | Evaluates the expansion of a #define macro function called
with the specified values. | [
"Evaluates",
"the",
"expansion",
"of",
"a",
"#define",
"macro",
"function",
"called",
"with",
"the",
"specified",
"values",
"."
] | def __call__(self, *values):
"""
Evaluates the expansion of a #define macro function called
with the specified values.
"""
if len(self.args) != len(values):
raise ValueError("Incorrect number of arguments to `%s'" % self.name)
# Create a dictionary that maps the macro arguments to the
# corresponding values in this "call." We'll use this when we
# eval() the expansion so that arguments will get expanded to
# the right values.
args = self.args
localvars = {k: v for k, v in zip(args, values)}
parts = [s if s in args else repr(s) for s in self.expansion]
statement = ' + '.join(parts)
return eval(statement, globals(), localvars) | [
"def",
"__call__",
"(",
"self",
",",
"*",
"values",
")",
":",
"if",
"len",
"(",
"self",
".",
"args",
")",
"!=",
"len",
"(",
"values",
")",
":",
"raise",
"ValueError",
"(",
"\"Incorrect number of arguments to `%s'\"",
"%",
"self",
".",
"name",
")",
"# Cre... | https://github.com/SCons/scons/blob/309f0234d1d9cc76955818be47c5c722f577dac6/SCons/cpp.py#L197-L213 | |
eBay/accelerator | 218d9a5e4451ac72b9e65df6c5b32e37d25136c8 | accelerator/standard_methods/a_dataset_sort.py | python | prepare | (job, params) | return dw, ds_list, sort_idx | [] | def prepare(job, params):
if options.trigger_column:
assert options.sort_across_slices, 'trigger_column is meaningless without sort_across_slices'
assert options.trigger_column in options.sort_columns, 'can only trigger on a column that is sorted on'
d = datasets.source
ds_list = d.chain(stop_ds={datasets.previous: 'source'})
if options.sort_across_slices:
sort_idx, sort_extra = sort(partial(ds_list.iterate, None))
total = len(sort_idx)
per_slice = [total // params.slices] * params.slices
extra = total % params.slices
if extra:
# spread the left over length over pseudo-randomly selected slices
# (using the start of sort_idx to select slices).
# this will always select the first slices if data is already sorted
# but at least it's deterministic.
selector = sorted(range(min(params.slices, total)), key=sort_idx.__getitem__)
for sliceno in selector[:extra]:
per_slice[sliceno] += 1
# Switch to tracking what line the slices end at
slice_end = []
end = 0
for cnt in per_slice:
end += cnt
slice_end.append(end)
if options.trigger_column:
# extra definitely changed value last to simplify loop
sort_extra.append(object())
sort_idx.append(-1)
# move slice_end counts around to only switch when trigger_column changes
def fixup_fwd(cnt):
trigger_v = sort_extra[sort_idx[cnt - 1]]
while trigger_v == sort_extra[sort_idx[cnt]]:
cnt += 1
return cnt
def fixup_bck(cnt, min_cnt):
trigger_v = sort_extra[sort_idx[cnt - 1]]
while cnt > min_cnt and trigger_v == sort_extra[sort_idx[cnt]]:
cnt -= 1
return cnt
with status('Adjusting for trigger_column'):
prev = 0
for sliceno, cnt in enumerate(slice_end[:-1]):
if cnt:
cnt = max(cnt, prev)
choosen = fwd = fixup_fwd(cnt)
bck = fixup_bck(cnt, prev)
# This could be smarter
if (cnt - bck) <= (fwd < cnt):
choosen = bck
prev = slice_end[sliceno] = choosen
# and now switch sort_idx to be per slice
sort_idx = [
sort_idx[start:end]
for start, end in zip([0] + slice_end, slice_end)
]
assert sum(len(part) for part in sort_idx) == total # all rows used
if not options.trigger_column:
assert len(set(len(part) for part in sort_idx)) < 3 # only 1 or 2 lengths possible
else:
sort_idx = None
if options.sort_across_slices:
hashlabel = None
else:
hashlabel = d.hashlabel
if len(ds_list) == 1:
filename = d.filename
else:
filename = None
dw = job.datasetwriter(
columns=d.columns,
caption=params.caption,
hashlabel=hashlabel,
filename=filename,
previous=datasets.previous,
copy_mode=True,
)
return dw, ds_list, sort_idx | [
"def",
"prepare",
"(",
"job",
",",
"params",
")",
":",
"if",
"options",
".",
"trigger_column",
":",
"assert",
"options",
".",
"sort_across_slices",
",",
"'trigger_column is meaningless without sort_across_slices'",
"assert",
"options",
".",
"trigger_column",
"in",
"op... | https://github.com/eBay/accelerator/blob/218d9a5e4451ac72b9e65df6c5b32e37d25136c8/accelerator/standard_methods/a_dataset_sort.py#L126-L203 | |||
openstack/python-keystoneclient | 100253d52e0c62dffffddb6f046ad660a9bce1a9 | keystoneclient/v2_0/tokens.py | python | TokenManager.validate | (self, token) | return self._get('/tokens/%s' % base.getid(token), 'access') | Validate a token.
:param token: Token to be validated.
:rtype: :py:class:`.Token` | Validate a token. | [
"Validate",
"a",
"token",
"."
] | def validate(self, token):
"""Validate a token.
:param token: Token to be validated.
:rtype: :py:class:`.Token`
"""
return self._get('/tokens/%s' % base.getid(token), 'access') | [
"def",
"validate",
"(",
"self",
",",
"token",
")",
":",
"return",
"self",
".",
"_get",
"(",
"'/tokens/%s'",
"%",
"base",
".",
"getid",
"(",
"token",
")",
",",
"'access'",
")"
] | https://github.com/openstack/python-keystoneclient/blob/100253d52e0c62dffffddb6f046ad660a9bce1a9/keystoneclient/v2_0/tokens.py#L77-L85 | |
nlloyd/SubliminalCollaborator | 5c619e17ddbe8acb9eea8996ec038169ddcd50a1 | libs/twisted/web/static.py | python | File.render_GET | (self, request) | return server.NOT_DONE_YET | Begin sending the contents of this L{File} (or a subset of the
contents, based on the 'range' header) to the given request. | Begin sending the contents of this L{File} (or a subset of the
contents, based on the 'range' header) to the given request. | [
"Begin",
"sending",
"the",
"contents",
"of",
"this",
"L",
"{",
"File",
"}",
"(",
"or",
"a",
"subset",
"of",
"the",
"contents",
"based",
"on",
"the",
"range",
"header",
")",
"to",
"the",
"given",
"request",
"."
] | def render_GET(self, request):
"""
Begin sending the contents of this L{File} (or a subset of the
contents, based on the 'range' header) to the given request.
"""
self.restat(False)
if self.type is None:
self.type, self.encoding = getTypeAndEncoding(self.basename(),
self.contentTypes,
self.contentEncodings,
self.defaultType)
if not self.exists():
return self.childNotFound.render(request)
if self.isdir():
return self.redirect(request)
request.setHeader('accept-ranges', 'bytes')
try:
fileForReading = self.openForReading()
except IOError, e:
import errno
if e[0] == errno.EACCES:
return resource.ForbiddenResource().render(request)
else:
raise
if request.setLastModified(self.getmtime()) is http.CACHED:
return ''
producer = self.makeProducer(request, fileForReading)
if request.method == 'HEAD':
return ''
producer.start()
# and make sure the connection doesn't get closed
return server.NOT_DONE_YET | [
"def",
"render_GET",
"(",
"self",
",",
"request",
")",
":",
"self",
".",
"restat",
"(",
"False",
")",
"if",
"self",
".",
"type",
"is",
"None",
":",
"self",
".",
"type",
",",
"self",
".",
"encoding",
"=",
"getTypeAndEncoding",
"(",
"self",
".",
"basen... | https://github.com/nlloyd/SubliminalCollaborator/blob/5c619e17ddbe8acb9eea8996ec038169ddcd50a1/libs/twisted/web/static.py#L593-L634 | |
jimmyleaf/ocr_tensorflow_cnn | aedd35bc49366c4a02a8068ec37b611a50d60db8 | genIDCard.py | python | put_chinese_text.draw_text | (self, image, pos, text, text_size, text_color) | return img | draw chinese(or not) text with ttf
:param image: image(numpy.ndarray) to draw text
:param pos: where to draw text
:param text: the context, for chinese should be unicode type
:param text_size: text size
:param text_color:text color
:return: image | draw chinese(or not) text with ttf
:param image: image(numpy.ndarray) to draw text
:param pos: where to draw text
:param text: the context, for chinese should be unicode type
:param text_size: text size
:param text_color:text color
:return: image | [
"draw",
"chinese",
"(",
"or",
"not",
")",
"text",
"with",
"ttf",
":",
"param",
"image",
":",
"image",
"(",
"numpy",
".",
"ndarray",
")",
"to",
"draw",
"text",
":",
"param",
"pos",
":",
"where",
"to",
"draw",
"text",
":",
"param",
"text",
":",
"the"... | def draw_text(self, image, pos, text, text_size, text_color):
'''
draw chinese(or not) text with ttf
:param image: image(numpy.ndarray) to draw text
:param pos: where to draw text
:param text: the context, for chinese should be unicode type
:param text_size: text size
:param text_color:text color
:return: image
'''
self._face.set_char_size(text_size * 64)
metrics = self._face.size
ascender = metrics.ascender/64.0
#descender = metrics.descender/64.0
#height = metrics.height/64.0
#linegap = height - ascender + descender
ypos = int(ascender)
if not isinstance(text, unicode):
text = text.decode('utf-8')
img = self.draw_string(image, pos[0], pos[1]+ypos, text, text_color)
return img | [
"def",
"draw_text",
"(",
"self",
",",
"image",
",",
"pos",
",",
"text",
",",
"text_size",
",",
"text_color",
")",
":",
"self",
".",
"_face",
".",
"set_char_size",
"(",
"text_size",
"*",
"64",
")",
"metrics",
"=",
"self",
".",
"_face",
".",
"size",
"a... | https://github.com/jimmyleaf/ocr_tensorflow_cnn/blob/aedd35bc49366c4a02a8068ec37b611a50d60db8/genIDCard.py#L18-L40 | |
matrix-org/synapse | 8e57584a5859a9002759963eb546d523d2498a01 | synapse/federation/transport/client.py | python | TransportLayerClient.send_knock_v1 | (
self,
destination: str,
room_id: str,
event_id: str,
content: JsonDict,
) | return await self.client.put_json(
destination=destination, path=path, data=content
) | Sends a signed knock membership event to a remote server. This is the second
step for knocking after make_knock.
Args:
destination: The remote homeserver.
room_id: The ID of the room to knock on.
event_id: The ID of the knock membership event that we're sending.
content: The knock membership event that we're sending. Note that this is not the
`content` field of the membership event, but the entire signed membership event
itself represented as a JSON dict.
Returns:
The remote homeserver can optionally return some state from the room. The response
dictionary is in the form:
{"knock_state_events": [<state event dict>, ...]}
The list of state events may be empty. | Sends a signed knock membership event to a remote server. This is the second
step for knocking after make_knock. | [
"Sends",
"a",
"signed",
"knock",
"membership",
"event",
"to",
"a",
"remote",
"server",
".",
"This",
"is",
"the",
"second",
"step",
"for",
"knocking",
"after",
"make_knock",
"."
] | async def send_knock_v1(
self,
destination: str,
room_id: str,
event_id: str,
content: JsonDict,
) -> JsonDict:
"""
Sends a signed knock membership event to a remote server. This is the second
step for knocking after make_knock.
Args:
destination: The remote homeserver.
room_id: The ID of the room to knock on.
event_id: The ID of the knock membership event that we're sending.
content: The knock membership event that we're sending. Note that this is not the
`content` field of the membership event, but the entire signed membership event
itself represented as a JSON dict.
Returns:
The remote homeserver can optionally return some state from the room. The response
dictionary is in the form:
{"knock_state_events": [<state event dict>, ...]}
The list of state events may be empty.
"""
path = _create_v1_path("/send_knock/%s/%s", room_id, event_id)
return await self.client.put_json(
destination=destination, path=path, data=content
) | [
"async",
"def",
"send_knock_v1",
"(",
"self",
",",
"destination",
":",
"str",
",",
"room_id",
":",
"str",
",",
"event_id",
":",
"str",
",",
"content",
":",
"JsonDict",
",",
")",
"->",
"JsonDict",
":",
"path",
"=",
"_create_v1_path",
"(",
"\"/send_knock/%s/... | https://github.com/matrix-org/synapse/blob/8e57584a5859a9002759963eb546d523d2498a01/synapse/federation/transport/client.py#L393-L424 | |
gepd/Deviot | 150caea06108369b30210eb287a580fcff4904af | platformio/project_recognition.py | python | ProjectRecognition.get_temp_project_path | (self) | return temp | Temp Project Path
Path of project in a temporal folder, this folder
do not neccessarilly exits
Returns:
[str] -- temp_path/project_name/ | Temp Project Path | [
"Temp",
"Project",
"Path"
] | def get_temp_project_path(self):
"""Temp Project Path
Path of project in a temporal folder, this folder
do not neccessarilly exits
Returns:
[str] -- temp_path/project_name/
"""
file_name = self.get_file_name(ext=False)
if(not file_name):
return None
ext = self.get_file_extension()
if(ext and ext != 'ino'):
from glob import glob
project_path = self.get_project_path()
project_path = os.path.join(project_path, '*')
project_path = glob(project_path)
for file in project_path:
if(file.endswith('ino')):
file_name = self.get_file_name(custom_path=file, ext=False)
break
temp = self.get_temp_path(file_name)
return temp | [
"def",
"get_temp_project_path",
"(",
"self",
")",
":",
"file_name",
"=",
"self",
".",
"get_file_name",
"(",
"ext",
"=",
"False",
")",
"if",
"(",
"not",
"file_name",
")",
":",
"return",
"None",
"ext",
"=",
"self",
".",
"get_file_extension",
"(",
")",
"if"... | https://github.com/gepd/Deviot/blob/150caea06108369b30210eb287a580fcff4904af/platformio/project_recognition.py#L75-L104 | |
fake-name/ReadableWebProxy | ed5c7abe38706acc2684a1e6cd80242a03c5f010 | WebMirror/management/rss_parser_funcs/feed_parse_extractTrackestWordpressCom.py | python | extractTrackestWordpressCom | (item) | return False | Parser for 'trackest.wordpress.com' | Parser for 'trackest.wordpress.com' | [
"Parser",
"for",
"trackest",
".",
"wordpress",
".",
"com"
] | def extractTrackestWordpressCom(item):
'''
Parser for 'trackest.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('Legend of Fu Yao Chapter Update', 'Legend of Fu Yao', 'translated'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False | [
"def",
"extractTrackestWordpressCom",
"(",
"item",
")",
":",
"vol",
",",
"chp",
",",
"frag",
",",
"postfix",
"=",
"extractVolChapterFragmentPostfix",
"(",
"item",
"[",
"'title'",
"]",
")",
"if",
"not",
"(",
"chp",
"or",
"vol",
")",
"or",
"\"preview\"",
"in... | https://github.com/fake-name/ReadableWebProxy/blob/ed5c7abe38706acc2684a1e6cd80242a03c5f010/WebMirror/management/rss_parser_funcs/feed_parse_extractTrackestWordpressCom.py#L1-L19 | |
meetbill/zabbix_manager | 739e5b51facf19cc6bda2b50f29108f831cf833e | ZabbixTool/lib_zabbix/w_lib/mylib/xlwt/Worksheet.py | python | Worksheet.get_merged_ranges | (self) | return self.__merged_ranges | [] | def get_merged_ranges(self):
return self.__merged_ranges | [
"def",
"get_merged_ranges",
"(",
"self",
")",
":",
"return",
"self",
".",
"__merged_ranges"
] | https://github.com/meetbill/zabbix_manager/blob/739e5b51facf19cc6bda2b50f29108f831cf833e/ZabbixTool/lib_zabbix/w_lib/mylib/xlwt/Worksheet.py#L241-L242 | |||
Chaffelson/nipyapi | d3b186fd701ce308c2812746d98af9120955e810 | nipyapi/nifi/models/process_group_dto.py | python | ProcessGroupDTO.parameter_context | (self, parameter_context) | Sets the parameter_context of this ProcessGroupDTO.
The Parameter Context that this Process Group is bound to.
:param parameter_context: The parameter_context of this ProcessGroupDTO.
:type: ParameterContextReferenceEntity | Sets the parameter_context of this ProcessGroupDTO.
The Parameter Context that this Process Group is bound to. | [
"Sets",
"the",
"parameter_context",
"of",
"this",
"ProcessGroupDTO",
".",
"The",
"Parameter",
"Context",
"that",
"this",
"Process",
"Group",
"is",
"bound",
"to",
"."
] | def parameter_context(self, parameter_context):
"""
Sets the parameter_context of this ProcessGroupDTO.
The Parameter Context that this Process Group is bound to.
:param parameter_context: The parameter_context of this ProcessGroupDTO.
:type: ParameterContextReferenceEntity
"""
self._parameter_context = parameter_context | [
"def",
"parameter_context",
"(",
"self",
",",
"parameter_context",
")",
":",
"self",
".",
"_parameter_context",
"=",
"parameter_context"
] | https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/process_group_dto.py#L402-L411 | ||
WerWolv/EdiZon_CheatsConfigsAndScripts | d16d36c7509c01dca770f402babd83ff2e9ae6e7 | Scripts/lib/python3.5/imp.py | python | source_from_cache | (path) | return util.source_from_cache(path) | **DEPRECATED**
Given the path to a .pyc. file, return the path to its .py file.
The .pyc file does not need to exist; this simply returns the path to
the .py file calculated to correspond to the .pyc file. If path does
not conform to PEP 3147 format, ValueError will be raised. If
sys.implementation.cache_tag is None then NotImplementedError is raised. | **DEPRECATED** | [
"**",
"DEPRECATED",
"**"
] | def source_from_cache(path):
"""**DEPRECATED**
Given the path to a .pyc. file, return the path to its .py file.
The .pyc file does not need to exist; this simply returns the path to
the .py file calculated to correspond to the .pyc file. If path does
not conform to PEP 3147 format, ValueError will be raised. If
sys.implementation.cache_tag is None then NotImplementedError is raised.
"""
return util.source_from_cache(path) | [
"def",
"source_from_cache",
"(",
"path",
")",
":",
"return",
"util",
".",
"source_from_cache",
"(",
"path",
")"
] | https://github.com/WerWolv/EdiZon_CheatsConfigsAndScripts/blob/d16d36c7509c01dca770f402babd83ff2e9ae6e7/Scripts/lib/python3.5/imp.py#L91-L102 | |
leancloud/satori | 701caccbd4fe45765001ca60435c0cb499477c03 | satori-rules/plugin/libs/redis/client.py | python | StrictRedis.decr | (self, name, amount=1) | return self.execute_command('DECRBY', name, amount) | Decrements the value of ``key`` by ``amount``. If no key exists,
the value will be initialized as 0 - ``amount`` | Decrements the value of ``key`` by ``amount``. If no key exists,
the value will be initialized as 0 - ``amount`` | [
"Decrements",
"the",
"value",
"of",
"key",
"by",
"amount",
".",
"If",
"no",
"key",
"exists",
"the",
"value",
"will",
"be",
"initialized",
"as",
"0",
"-",
"amount"
] | def decr(self, name, amount=1):
"""
Decrements the value of ``key`` by ``amount``. If no key exists,
the value will be initialized as 0 - ``amount``
"""
return self.execute_command('DECRBY', name, amount) | [
"def",
"decr",
"(",
"self",
",",
"name",
",",
"amount",
"=",
"1",
")",
":",
"return",
"self",
".",
"execute_command",
"(",
"'DECRBY'",
",",
"name",
",",
"amount",
")"
] | https://github.com/leancloud/satori/blob/701caccbd4fe45765001ca60435c0cb499477c03/satori-rules/plugin/libs/redis/client.py#L832-L837 | |
tensorflow/graphics | 86997957324bfbdd85848daae989b4c02588faa0 | tensorflow_graphics/io/exr.py | python | write_exr | (filename, values, channel_names) | Writes the values in a multi-channel ndarray into an EXR file.
Args:
filename: The filename of the output file
values: A numpy ndarray with shape [height, width, channels]
channel_names: A list of strings with length = channels
Raises:
TypeError: If the numpy array has an unsupported type.
ValueError: If the length of the array and the length of the channel names
list do not match. | Writes the values in a multi-channel ndarray into an EXR file. | [
"Writes",
"the",
"values",
"in",
"a",
"multi",
"-",
"channel",
"ndarray",
"into",
"an",
"EXR",
"file",
"."
] | def write_exr(filename, values, channel_names):
"""Writes the values in a multi-channel ndarray into an EXR file.
Args:
filename: The filename of the output file
values: A numpy ndarray with shape [height, width, channels]
channel_names: A list of strings with length = channels
Raises:
TypeError: If the numpy array has an unsupported type.
ValueError: If the length of the array and the length of the channel names
list do not match.
"""
if values.shape[-1] != len(channel_names):
raise ValueError(
'Number of channels in values does not match channel names (%d, %d)' %
(values.shape[-1], len(channel_names)))
header = OpenEXR.Header(values.shape[1], values.shape[0])
try:
exr_channel_type = Imath.PixelType(_np_to_exr[values.dtype.type])
except KeyError:
raise TypeError('Unsupported numpy type: %s' % str(values.dtype))
header['channels'] = {
n: Imath.Channel(exr_channel_type) for n in channel_names
}
channel_data = [values[..., i] for i in range(values.shape[-1])]
exr = OpenEXR.OutputFile(filename, header)
exr.writePixels(
dict((n, d.tobytes()) for n, d in zip(channel_names, channel_data)))
exr.close() | [
"def",
"write_exr",
"(",
"filename",
",",
"values",
",",
"channel_names",
")",
":",
"if",
"values",
".",
"shape",
"[",
"-",
"1",
"]",
"!=",
"len",
"(",
"channel_names",
")",
":",
"raise",
"ValueError",
"(",
"'Number of channels in values does not match channel n... | https://github.com/tensorflow/graphics/blob/86997957324bfbdd85848daae989b4c02588faa0/tensorflow_graphics/io/exr.py#L114-L143 | ||
wbond/oscrypto | d40c62577706682a0f6da5616ad09964f1c9137d | oscrypto/_win/symmetric.py | python | _bcrypt_decrypt | (cipher, key, data, iv, padding) | Decrypts AES/RC4/RC2/3DES/DES ciphertext via CNG
:param cipher:
A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key",
"rc2", "rc4"
:param key:
The encryption key - a byte string 5-16 bytes long
:param data:
The ciphertext - a byte string
:param iv:
The initialization vector - a byte string - unused for RC4
:param padding:
Boolean, if padding should be used - unused for RC4
:raises:
ValueError - when any of the parameters contain an invalid value
TypeError - when any of the parameters are of the wrong type
OSError - when an error is returned by the OS crypto library
:return:
A byte string of the plaintext | Decrypts AES/RC4/RC2/3DES/DES ciphertext via CNG | [
"Decrypts",
"AES",
"/",
"RC4",
"/",
"RC2",
"/",
"3DES",
"/",
"DES",
"ciphertext",
"via",
"CNG"
] | def _bcrypt_decrypt(cipher, key, data, iv, padding):
"""
Decrypts AES/RC4/RC2/3DES/DES ciphertext via CNG
:param cipher:
A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key",
"rc2", "rc4"
:param key:
The encryption key - a byte string 5-16 bytes long
:param data:
The ciphertext - a byte string
:param iv:
The initialization vector - a byte string - unused for RC4
:param padding:
Boolean, if padding should be used - unused for RC4
:raises:
ValueError - when any of the parameters contain an invalid value
TypeError - when any of the parameters are of the wrong type
OSError - when an error is returned by the OS crypto library
:return:
A byte string of the plaintext
"""
key_handle = None
try:
key_handle = _bcrypt_create_key_handle(cipher, key)
if iv is None:
iv_len = 0
else:
iv_len = len(iv)
flags = 0
if padding is True:
flags = BcryptConst.BCRYPT_BLOCK_PADDING
out_len = new(bcrypt, 'ULONG *')
res = bcrypt.BCryptDecrypt(
key_handle,
data,
len(data),
null(),
null(),
0,
null(),
0,
out_len,
flags
)
handle_error(res)
buffer_len = deref(out_len)
buffer = buffer_from_bytes(buffer_len)
iv_buffer = buffer_from_bytes(iv) if iv else null()
res = bcrypt.BCryptDecrypt(
key_handle,
data,
len(data),
null(),
iv_buffer,
iv_len,
buffer,
buffer_len,
out_len,
flags
)
handle_error(res)
return bytes_from_buffer(buffer, deref(out_len))
finally:
if key_handle:
bcrypt.BCryptDestroyKey(key_handle) | [
"def",
"_bcrypt_decrypt",
"(",
"cipher",
",",
"key",
",",
"data",
",",
"iv",
",",
"padding",
")",
":",
"key_handle",
"=",
"None",
"try",
":",
"key_handle",
"=",
"_bcrypt_create_key_handle",
"(",
"cipher",
",",
"key",
")",
"if",
"iv",
"is",
"None",
":",
... | https://github.com/wbond/oscrypto/blob/d40c62577706682a0f6da5616ad09964f1c9137d/oscrypto/_win/symmetric.py#L1086-L1166 | ||
openhatch/oh-mainline | ce29352a034e1223141dcc2f317030bbc3359a51 | vendor/packages/python-openid/openid/association.py | python | Association.getMessageSignature | (self, message) | return oidutil.toBase64(self.sign(pairs)) | Return the signature of a message.
If I am not a sign-all association, the message must have a
signed list.
@return: the signature, base64 encoded
@rtype: str
@raises ValueError: If there is no signed list and I am not a sign-all
type of association. | Return the signature of a message. | [
"Return",
"the",
"signature",
"of",
"a",
"message",
"."
] | def getMessageSignature(self, message):
"""Return the signature of a message.
If I am not a sign-all association, the message must have a
signed list.
@return: the signature, base64 encoded
@rtype: str
@raises ValueError: If there is no signed list and I am not a sign-all
type of association.
"""
pairs = self._makePairs(message)
return oidutil.toBase64(self.sign(pairs)) | [
"def",
"getMessageSignature",
"(",
"self",
",",
"message",
")",
":",
"pairs",
"=",
"self",
".",
"_makePairs",
"(",
"message",
")",
"return",
"oidutil",
".",
"toBase64",
"(",
"self",
".",
"sign",
"(",
"pairs",
")",
")"
] | https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/python-openid/openid/association.py#L482-L496 | |
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/lib-python/3/xml/etree/ElementPath.py | python | findtext | (elem, path, default=None, namespaces=None) | [] | def findtext(elem, path, default=None, namespaces=None):
try:
elem = next(iterfind(elem, path, namespaces))
return elem.text or ""
except StopIteration:
return default | [
"def",
"findtext",
"(",
"elem",
",",
"path",
",",
"default",
"=",
"None",
",",
"namespaces",
"=",
"None",
")",
":",
"try",
":",
"elem",
"=",
"next",
"(",
"iterfind",
"(",
"elem",
",",
"path",
",",
"namespaces",
")",
")",
"return",
"elem",
".",
"tex... | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/xml/etree/ElementPath.py#L298-L303 | ||||
Calysto/calysto_scheme | 15bf81987870bcae1264e5a0a06feb9a8ee12b8b | calysto_scheme/scheme.py | python | literal_q_hat | (asexp) | return (((asexp).car) is (atom_tag)) and ((number_q(untag_atom_hat(asexp))) or (boolean_q(untag_atom_hat(asexp))) or (((untag_atom_hat(asexp)) is symbol_emptylist)) or (char_q(untag_atom_hat(asexp))) or (string_q(untag_atom_hat(asexp)))) | [] | def literal_q_hat(asexp):
return (((asexp).car) is (atom_tag)) and ((number_q(untag_atom_hat(asexp))) or (boolean_q(untag_atom_hat(asexp))) or (((untag_atom_hat(asexp)) is symbol_emptylist)) or (char_q(untag_atom_hat(asexp))) or (string_q(untag_atom_hat(asexp)))) | [
"def",
"literal_q_hat",
"(",
"asexp",
")",
":",
"return",
"(",
"(",
"(",
"asexp",
")",
".",
"car",
")",
"is",
"(",
"atom_tag",
")",
")",
"and",
"(",
"(",
"number_q",
"(",
"untag_atom_hat",
"(",
"asexp",
")",
")",
")",
"or",
"(",
"boolean_q",
"(",
... | https://github.com/Calysto/calysto_scheme/blob/15bf81987870bcae1264e5a0a06feb9a8ee12b8b/calysto_scheme/scheme.py#L6838-L6839 | |||
UFAL-DSG/tgen | 3c43c0e29faa7ea3857a6e490d9c28a8daafc7d0 | tgen/cluster.py | python | Job.__try_command | (self, cmd) | return output | \
Try to run a command and return its output. If the command fails,
throw a RuntimeError. | \
Try to run a command and return its output. If the command fails,
throw a RuntimeError. | [
"\\",
"Try",
"to",
"run",
"a",
"command",
"and",
"return",
"its",
"output",
".",
"If",
"the",
"command",
"fails",
"throw",
"a",
"RuntimeError",
"."
] | def __try_command(self, cmd):
"""\
Try to run a command and return its output. If the command fails,
throw a RuntimeError.
"""
status, output = subprocess.getstatusoutput(cmd)
if status != 0:
raise RuntimeError('Command \'' + cmd + '\' failed. Status: ' +
str(status) + ', Output: ' + output)
return output | [
"def",
"__try_command",
"(",
"self",
",",
"cmd",
")",
":",
"status",
",",
"output",
"=",
"subprocess",
".",
"getstatusoutput",
"(",
"cmd",
")",
"if",
"status",
"!=",
"0",
":",
"raise",
"RuntimeError",
"(",
"'Command \\''",
"+",
"cmd",
"+",
"'\\' failed. St... | https://github.com/UFAL-DSG/tgen/blob/3c43c0e29faa7ea3857a6e490d9c28a8daafc7d0/tgen/cluster.py#L374-L383 | |
rembo10/headphones | b3199605be1ebc83a7a8feab6b1e99b64014187c | lib/cherrypy/wsgiserver/wsgiserver2.py | python | WSGIPathInfoDispatcher.__call__ | (self, environ, start_response) | return [''] | [] | def __call__(self, environ, start_response):
path = environ["PATH_INFO"] or "/"
for p, app in self.apps:
# The apps list should be sorted by length, descending.
if path.startswith(p + "/") or path == p:
environ = environ.copy()
environ["SCRIPT_NAME"] = environ["SCRIPT_NAME"] + p
environ["PATH_INFO"] = path[len(p):]
return app(environ, start_response)
start_response('404 Not Found', [('Content-Type', 'text/plain'),
('Content-Length', '0')])
return [''] | [
"def",
"__call__",
"(",
"self",
",",
"environ",
",",
"start_response",
")",
":",
"path",
"=",
"environ",
"[",
"\"PATH_INFO\"",
"]",
"or",
"\"/\"",
"for",
"p",
",",
"app",
"in",
"self",
".",
"apps",
":",
"# The apps list should be sorted by length, descending.",
... | https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/cherrypy/wsgiserver/wsgiserver2.py#L2471-L2483 | |||
fake-name/ReadableWebProxy | ed5c7abe38706acc2684a1e6cd80242a03c5f010 | WebMirror/management/rss_parser_funcs/feed_parse_extractLazyNanaseruTranslation.py | python | extractLazyNanaseruTranslation | (item) | return False | Parser for 'Lazy Nanaseru Translation' | Parser for 'Lazy Nanaseru Translation' | [
"Parser",
"for",
"Lazy",
"Nanaseru",
"Translation"
] | def extractLazyNanaseruTranslation(item):
"""
Parser for 'Lazy Nanaseru Translation'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'WATTT' in item['tags']:
return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag, postfix=postfix)
return False | [
"def",
"extractLazyNanaseruTranslation",
"(",
"item",
")",
":",
"vol",
",",
"chp",
",",
"frag",
",",
"postfix",
"=",
"extractVolChapterFragmentPostfix",
"(",
"item",
"[",
"'title'",
"]",
")",
"if",
"not",
"(",
"chp",
"or",
"vol",
")",
"or",
"'preview'",
"i... | https://github.com/fake-name/ReadableWebProxy/blob/ed5c7abe38706acc2684a1e6cd80242a03c5f010/WebMirror/management/rss_parser_funcs/feed_parse_extractLazyNanaseruTranslation.py#L1-L10 | |
raveberry/raveberry | df0186c94b238b57de86d3fd5c595dcd08a7c708 | backend/core/musiq/playlist_provider.py | python | PlaylistProvider.persist | (self, session_key: str, archive: bool = True) | [] | def persist(self, session_key: str, archive: bool = True) -> None:
if self.is_radio():
return
assert self.id
if self.title is None:
logging.warning("Persisting a playlist with no title (id %s)", self.id)
self.title = ""
with transaction.atomic():
queryset = ArchivedPlaylist.objects.filter(list_id=self.id)
if queryset.count() == 0:
initial_counter = 1 if archive else 0
archived_playlist = ArchivedPlaylist.objects.create(
list_id=self.id, title=self.title, counter=initial_counter
)
for index, url in enumerate(self.urls):
PlaylistEntry.objects.create(
playlist=archived_playlist, index=index, url=url
)
else:
if archive:
queryset.update(counter=F("counter") + 1)
archived_playlist = queryset.get()
if archive:
ArchivedPlaylistQuery.objects.get_or_create(
playlist=archived_playlist, query=self.query
)
if storage.get("logging_enabled") and session_key:
RequestLog.objects.create(
playlist=archived_playlist, session_key=session_key
) | [
"def",
"persist",
"(",
"self",
",",
"session_key",
":",
"str",
",",
"archive",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"if",
"self",
".",
"is_radio",
"(",
")",
":",
"return",
"assert",
"self",
".",
"id",
"if",
"self",
".",
"title",
"is",
... | https://github.com/raveberry/raveberry/blob/df0186c94b238b57de86d3fd5c595dcd08a7c708/backend/core/musiq/playlist_provider.py#L150-L183 | ||||
pythonarcade/arcade | 1ee3eb1900683213e8e8df93943327c2ea784564 | doc/tutorials/pymunk_platformer/pymunk_demo_platformer_02.py | python | GameWindow.setup | (self) | Set up everything with the game | Set up everything with the game | [
"Set",
"up",
"everything",
"with",
"the",
"game"
] | def setup(self):
""" Set up everything with the game """
pass | [
"def",
"setup",
"(",
"self",
")",
":",
"pass"
] | https://github.com/pythonarcade/arcade/blob/1ee3eb1900683213e8e8df93943327c2ea784564/doc/tutorials/pymunk_platformer/pymunk_demo_platformer_02.py#L38-L40 | ||
demisto/content | 5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07 | Packs/DigitalGuardian/Integrations/DigitalGuardian/DigitalGuardian.py | python | check_componentlist_entry | () | Does the componentlist_entry exist in the component list identified by componentlist_name
Sets DigitalGuardian.Componentlist.Found flag. | Does the componentlist_entry exist in the component list identified by componentlist_name | [
"Does",
"the",
"componentlist_entry",
"exist",
"in",
"the",
"component",
"list",
"identified",
"by",
"componentlist_name"
] | def check_componentlist_entry():
"""
Does the componentlist_entry exist in the component list identified by componentlist_name
Sets DigitalGuardian.Componentlist.Found flag.
"""
componentlist_name = demisto.args().get('componentlist_name', None)
componentlist_entry = demisto.args().get('componentlist_entry', None)
if componentlist_name is None or componentlist_entry is None:
return_error('Please provide both componentlist_name and componentlist_entry')
componentlist = None
list_id = get_list_id(componentlist_name, 'component_list')
if list_id:
full_url = ARC_URL + '/lists/'
r = requests.get(url=full_url + list_id + '/values?limit=100000', headers=CLIENT_HEADERS, verify=VERIFY_CERT)
json_text = json.loads(r.text)
if 200 <= r.status_code <= 299:
for jText in json_text:
if str(jText['content_value']).lower() == componentlist_entry.lower():
componentlist = jText['content_value']
else:
return_error(f'Unable to find componentlist named {componentlist_name}, {r.status_code}')
if componentlist:
return_outputs(readable_output='Componentlist found', outputs={
'DigitalGuardian.Componentlist.Found': True}, raw_response='Componentlist entry not found')
else:
return_outputs(readable_output='Componentlist not found', outputs={
'DigitalGuardian.Componentlist.Found': False}, raw_response='Componentlist entry not found') | [
"def",
"check_componentlist_entry",
"(",
")",
":",
"componentlist_name",
"=",
"demisto",
".",
"args",
"(",
")",
".",
"get",
"(",
"'componentlist_name'",
",",
"None",
")",
"componentlist_entry",
"=",
"demisto",
".",
"args",
"(",
")",
".",
"get",
"(",
"'compon... | https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/DigitalGuardian/Integrations/DigitalGuardian/DigitalGuardian.py#L162-L192 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.