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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_utils/filter_plugins/oo_filters.py | python | lib_utils_oo_random_word | (length, source='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') | return ''.join(random.choice(source) for i in range(length)) | Generates a random string of given length from a set of alphanumeric characters.
The default source uses [a-z][A-Z][0-9]
Ex:
- lib_utils_oo_random_word(3) => aB9
- lib_utils_oo_random_word(4, source='012') => 0123 | Generates a random string of given length from a set of alphanumeric characters.
The default source uses [a-z][A-Z][0-9]
Ex:
- lib_utils_oo_random_word(3) => aB9
- lib_utils_oo_random_word(4, source='012') => 0123 | [
"Generates",
"a",
"random",
"string",
"of",
"given",
"length",
"from",
"a",
"set",
"of",
"alphanumeric",
"characters",
".",
"The",
"default",
"source",
"uses",
"[",
"a",
"-",
"z",
"]",
"[",
"A",
"-",
"Z",
"]",
"[",
"0",
"-",
"9",
"]",
"Ex",
":",
... | def lib_utils_oo_random_word(length, source='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""Generates a random string of given length from a set of alphanumeric characters.
The default source uses [a-z][A-Z][0-9]
Ex:
- lib_utils_oo_random_word(3) => aB9
- lib_utils_oo_random_word(4, source='012') => 0123
"""
return ''.join(random.choice(source) for i in range(length)) | [
"def",
"lib_utils_oo_random_word",
"(",
"length",
",",
"source",
"=",
"'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'",
")",
":",
"return",
"''",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"source",
")",
"for",
"i",
"in",
"range",
"(",
"leng... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_utils/filter_plugins/oo_filters.py#L549-L556 | |
oilshell/oil | 94388e7d44a9ad879b12615f6203b38596b5a2d3 | Python-2.7.13/Lib/lib-tk/turtle.py | python | __methodDict | (cls, _dict) | helper function for Scrolled Canvas | helper function for Scrolled Canvas | [
"helper",
"function",
"for",
"Scrolled",
"Canvas"
] | def __methodDict(cls, _dict):
"""helper function for Scrolled Canvas"""
baseList = list(cls.__bases__)
baseList.reverse()
for _super in baseList:
__methodDict(_super, _dict)
for key, value in cls.__dict__.items():
if type(value) == types.FunctionType:
_dict[key] = value | [
"def",
"__methodDict",
"(",
"cls",
",",
"_dict",
")",
":",
"baseList",
"=",
"list",
"(",
"cls",
".",
"__bases__",
")",
"baseList",
".",
"reverse",
"(",
")",
"for",
"_super",
"in",
"baseList",
":",
"__methodDict",
"(",
"_super",
",",
"_dict",
")",
"for"... | https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/lib-tk/turtle.py#L308-L316 | ||
jminardi/mecode | e8efbf6b8e03964d682e74b9e7d2a6d0b72ccb74 | mecode/printer.py | python | Printer.connect | (self, s=None) | Instantiate a Serial object using the stored port and baudrate.
Parameters
----------
s : serial.Serial
If a serial object is passed in then it will be used instead of
creating a new one. | Instantiate a Serial object using the stored port and baudrate. | [
"Instantiate",
"a",
"Serial",
"object",
"using",
"the",
"stored",
"port",
"and",
"baudrate",
"."
] | def connect(self, s=None):
""" Instantiate a Serial object using the stored port and baudrate.
Parameters
----------
s : serial.Serial
If a serial object is passed in then it will be used instead of
creating a new one.
"""
with self._connection_lock:
if s is None:
self.s = serial.Serial(self.port, self.baudrate, timeout=3)
else:
self.s = s
self._owns_serial = False
self._ok_received.set()
self._current_line_idx = 0
self._buffer = []
self.responses = []
self.sentlines = []
self._disconnect_pending = False
self._start_read_thread()
if s is None:
while len(self.responses) == 0:
sleep(0.01) # wait until the start message is recieved.
self.responses = []
logger.debug('Connected to {}'.format(self.s)) | [
"def",
"connect",
"(",
"self",
",",
"s",
"=",
"None",
")",
":",
"with",
"self",
".",
"_connection_lock",
":",
"if",
"s",
"is",
"None",
":",
"self",
".",
"s",
"=",
"serial",
".",
"Serial",
"(",
"self",
".",
"port",
",",
"self",
".",
"baudrate",
",... | https://github.com/jminardi/mecode/blob/e8efbf6b8e03964d682e74b9e7d2a6d0b72ccb74/mecode/printer.py#L126-L153 | ||
facebookresearch/ParlAI | e4d59c30eef44f1f67105961b82a83fd28d7d78b | parlai/utils/safety.py | python | OffensiveStringMatcher.__contains__ | (self, key) | return self.contains_offensive_language(key) | Determine if text contains any offensive words in the filter. | Determine if text contains any offensive words in the filter. | [
"Determine",
"if",
"text",
"contains",
"any",
"offensive",
"words",
"in",
"the",
"filter",
"."
] | def __contains__(self, key):
"""
Determine if text contains any offensive words in the filter.
"""
return self.contains_offensive_language(key) | [
"def",
"__contains__",
"(",
"self",
",",
"key",
")",
":",
"return",
"self",
".",
"contains_offensive_language",
"(",
"key",
")"
] | https://github.com/facebookresearch/ParlAI/blob/e4d59c30eef44f1f67105961b82a83fd28d7d78b/parlai/utils/safety.py#L273-L277 | |
SteveDoyle2/pyNastran | eda651ac2d4883d95a34951f8a002ff94f642a1a | pyNastran/dev/bdf_vectorized/cards/elements/shell/pcomp_helper.py | python | PCOMPi.update | (self, pid_map, mid_map) | maps = {
'node' : nid_map,
'property' : pid_map,
} | maps = {
'node' : nid_map,
'property' : pid_map,
} | [
"maps",
"=",
"{",
"node",
":",
"nid_map",
"property",
":",
"pid_map",
"}"
] | def update(self, pid_map, mid_map):
"""
maps = {
'node' : nid_map,
'property' : pid_map,
}
"""
pid2 = pid_map[self.pid]
mids2 = [mid_map[mid] if mid != 0 else 0 for mid in self.mids]
self.pid = pid2
self.mids = mids2 | [
"def",
"update",
"(",
"self",
",",
"pid_map",
",",
"mid_map",
")",
":",
"pid2",
"=",
"pid_map",
"[",
"self",
".",
"pid",
"]",
"mids2",
"=",
"[",
"mid_map",
"[",
"mid",
"]",
"if",
"mid",
"!=",
"0",
"else",
"0",
"for",
"mid",
"in",
"self",
".",
"... | https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/dev/bdf_vectorized/cards/elements/shell/pcomp_helper.py#L659-L669 | ||
Den1al/JSShell | 7940a125ac2da48e9f22160ec54e56e6b1b89f2b | web/__init__.py | python | start_api_server | () | Starts the web server | Starts the web server | [
"Starts",
"the",
"web",
"server"
] | def start_api_server() -> None:
""" Starts the web server """
domain_name = config.get('DOMAIN', '')
lets_encrypt_base_path = f'/etc/letsencrypt/live/{domain_name}/'
app.run(
host=config.get('HOST', 'localhost'),
port=config.get('PORT', 5000),
debug=config.get('DEBUG', False),
ssl_context=(
lets_encrypt_base_path + 'cert.pem',
lets_encrypt_base_path + 'privkey.pem'
)
) | [
"def",
"start_api_server",
"(",
")",
"->",
"None",
":",
"domain_name",
"=",
"config",
".",
"get",
"(",
"'DOMAIN'",
",",
"''",
")",
"lets_encrypt_base_path",
"=",
"f'/etc/letsencrypt/live/{domain_name}/'",
"app",
".",
"run",
"(",
"host",
"=",
"config",
".",
"ge... | https://github.com/Den1al/JSShell/blob/7940a125ac2da48e9f22160ec54e56e6b1b89f2b/web/__init__.py#L24-L38 | ||
Kozea/cairocffi | 2473d1bb82a52ca781edec595a95951509db2969 | cairocffi/surfaces.py | python | Surface.flush | (self) | Do any pending drawing for the surface
and also restore any temporary modifications
cairo has made to the surface's state.
This method must be called before switching
from drawing on the surface with cairo
to drawing on it directly with native APIs.
If the surface doesn't support direct access,
then this method does nothing. | Do any pending drawing for the surface
and also restore any temporary modifications
cairo has made to the surface's state.
This method must be called before switching
from drawing on the surface with cairo
to drawing on it directly with native APIs.
If the surface doesn't support direct access,
then this method does nothing. | [
"Do",
"any",
"pending",
"drawing",
"for",
"the",
"surface",
"and",
"also",
"restore",
"any",
"temporary",
"modifications",
"cairo",
"has",
"made",
"to",
"the",
"surface",
"s",
"state",
".",
"This",
"method",
"must",
"be",
"called",
"before",
"switching",
"fr... | def flush(self):
"""Do any pending drawing for the surface
and also restore any temporary modifications
cairo has made to the surface's state.
This method must be called before switching
from drawing on the surface with cairo
to drawing on it directly with native APIs.
If the surface doesn't support direct access,
then this method does nothing.
"""
cairo.cairo_surface_flush(self._pointer)
self._check_status() | [
"def",
"flush",
"(",
"self",
")",
":",
"cairo",
".",
"cairo_surface_flush",
"(",
"self",
".",
"_pointer",
")",
"self",
".",
"_check_status",
"(",
")"
] | https://github.com/Kozea/cairocffi/blob/2473d1bb82a52ca781edec595a95951509db2969/cairocffi/surfaces.py#L609-L621 | ||
n1nj4sec/pupy | a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39 | pupy/library_patches/umsgpack.py | python | _pack_array | (obj, fp, options) | [] | def _pack_array(obj, fp, options):
if len(obj) <= 15:
fp.write(struct.pack("B", 0x90 | len(obj)))
elif len(obj) <= 2**16 - 1:
fp.write(b"\xdc" + struct.pack(">H", len(obj)))
elif len(obj) <= 2**32 - 1:
fp.write(b"\xdd" + struct.pack(">I", len(obj)))
else:
raise UnsupportedTypeException("huge array")
for e in obj:
pack(e, fp, **options) | [
"def",
"_pack_array",
"(",
"obj",
",",
"fp",
",",
"options",
")",
":",
"if",
"len",
"(",
"obj",
")",
"<=",
"15",
":",
"fp",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"\"B\"",
",",
"0x90",
"|",
"len",
"(",
"obj",
")",
")",
")",
"elif",
"l... | https://github.com/n1nj4sec/pupy/blob/a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39/pupy/library_patches/umsgpack.py#L351-L362 | ||||
JiYou/openstack | 8607dd488bde0905044b303eb6e52bdea6806923 | packages/source/cinder/cinder/quota.py | python | DbQuotaDriver.rollback | (self, context, reservations, project_id=None) | Roll back reservations.
:param context: The request context, for access checks.
:param reservations: A list of the reservation UUIDs, as
returned by the reserve() method.
:param project_id: Specify the project_id if current context
is admin and admin wants to impact on
common user's tenant. | Roll back reservations. | [
"Roll",
"back",
"reservations",
"."
] | def rollback(self, context, reservations, project_id=None):
"""Roll back reservations.
:param context: The request context, for access checks.
:param reservations: A list of the reservation UUIDs, as
returned by the reserve() method.
:param project_id: Specify the project_id if current context
is admin and admin wants to impact on
common user's tenant.
"""
# If project_id is None, then we use the project_id in context
if project_id is None:
project_id = context.project_id
db.reservation_rollback(context, reservations, project_id=project_id) | [
"def",
"rollback",
"(",
"self",
",",
"context",
",",
"reservations",
",",
"project_id",
"=",
"None",
")",
":",
"# If project_id is None, then we use the project_id in context",
"if",
"project_id",
"is",
"None",
":",
"project_id",
"=",
"context",
".",
"project_id",
"... | https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/cinder/cinder/quota.py#L343-L357 | ||
w3h/isf | 6faf0a3df185465ec17369c90ccc16e2a03a1870 | lib/thirdparty/scapy/utils.py | python | PcapReader_metaclass.__new__ | (cls, name, bases, dct) | return newcls | The `alternative` class attribute is declared in the PcapNg
variant, and set here to the Pcap variant. | The `alternative` class attribute is declared in the PcapNg
variant, and set here to the Pcap variant. | [
"The",
"alternative",
"class",
"attribute",
"is",
"declared",
"in",
"the",
"PcapNg",
"variant",
"and",
"set",
"here",
"to",
"the",
"Pcap",
"variant",
"."
] | def __new__(cls, name, bases, dct):
"""The `alternative` class attribute is declared in the PcapNg
variant, and set here to the Pcap variant.
"""
newcls = super(PcapReader_metaclass, cls).__new__(cls, name, bases, dct)
if 'alternative' in dct:
dct['alternative'].alternative = newcls
return newcls | [
"def",
"__new__",
"(",
"cls",
",",
"name",
",",
"bases",
",",
"dct",
")",
":",
"newcls",
"=",
"super",
"(",
"PcapReader_metaclass",
",",
"cls",
")",
".",
"__new__",
"(",
"cls",
",",
"name",
",",
"bases",
",",
"dct",
")",
"if",
"'alternative'",
"in",
... | https://github.com/w3h/isf/blob/6faf0a3df185465ec17369c90ccc16e2a03a1870/lib/thirdparty/scapy/utils.py#L567-L575 | |
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/schemes/toric/morphism.py | python | SchemeMorphism_fan_toric_variety.is_birational | (self) | return self.fan_morphism().is_birational() | r"""
Check if ``self`` is birational.
See
:meth:`~sage.geometry.fan_morphism.FanMorphism.is_birational`
for fan morphisms for a description of the toric algorithm.
OUTPUT:
Boolean. Whether ``self`` is birational.
EXAMPLES::
sage: dP8 = toric_varieties.dP8()
sage: P2 = toric_varieties.P2()
sage: dP8.hom(identity_matrix(2), P2).is_birational()
True
sage: X = toric_varieties.A(2)
sage: Y = ToricVariety(Fan([Cone([(1,0), (1,1)])]))
sage: m = identity_matrix(2)
sage: f = Y.hom(m, X)
sage: f.is_birational()
True | r"""
Check if ``self`` is birational. | [
"r",
"Check",
"if",
"self",
"is",
"birational",
"."
] | def is_birational(self):
r"""
Check if ``self`` is birational.
See
:meth:`~sage.geometry.fan_morphism.FanMorphism.is_birational`
for fan morphisms for a description of the toric algorithm.
OUTPUT:
Boolean. Whether ``self`` is birational.
EXAMPLES::
sage: dP8 = toric_varieties.dP8()
sage: P2 = toric_varieties.P2()
sage: dP8.hom(identity_matrix(2), P2).is_birational()
True
sage: X = toric_varieties.A(2)
sage: Y = ToricVariety(Fan([Cone([(1,0), (1,1)])]))
sage: m = identity_matrix(2)
sage: f = Y.hom(m, X)
sage: f.is_birational()
True
"""
return self.fan_morphism().is_birational() | [
"def",
"is_birational",
"(",
"self",
")",
":",
"return",
"self",
".",
"fan_morphism",
"(",
")",
".",
"is_birational",
"(",
")"
] | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/schemes/toric/morphism.py#L1241-L1267 | |
cdhigh/KindleEar | 7c4ecf9625239f12a829210d1760b863ef5a23aa | lib/sendgrid/helpers/mail/ganalytics.py | python | Ganalytics.utm_campaign | (self) | return self._utm_campaign | The name of the campaign.
:rtype: string | The name of the campaign. | [
"The",
"name",
"of",
"the",
"campaign",
"."
] | def utm_campaign(self):
"""The name of the campaign.
:rtype: string
"""
return self._utm_campaign | [
"def",
"utm_campaign",
"(",
"self",
")",
":",
"return",
"self",
".",
"_utm_campaign"
] | https://github.com/cdhigh/KindleEar/blob/7c4ecf9625239f12a829210d1760b863ef5a23aa/lib/sendgrid/helpers/mail/ganalytics.py#L113-L118 | |
pexpect/pexpect | 2be6c4d1aa2b9b522636342c2fd54b73c058060d | pexpect/spawnbase.py | python | SpawnBase.expect | (self, pattern, timeout=-1, searchwindowsize=-1, async_=False, **kw) | return self.expect_list(compiled_pattern_list,
timeout, searchwindowsize, async_) | This seeks through the stream until a pattern is matched. The
pattern is overloaded and may take several types. The pattern can be a
StringType, EOF, a compiled re, or a list of any of those types.
Strings will be compiled to re types. This returns the index into the
pattern list. If the pattern was not a list this returns index 0 on a
successful match. This may raise exceptions for EOF or TIMEOUT. To
avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern
list. That will cause expect to match an EOF or TIMEOUT condition
instead of raising an exception.
If you pass a list of patterns and more than one matches, the first
match in the stream is chosen. If more than one pattern matches at that
point, the leftmost in the pattern list is chosen. For example::
# the input is 'foobar'
index = p.expect(['bar', 'foo', 'foobar'])
# returns 1('foo') even though 'foobar' is a "better" match
Please note, however, that buffering can affect this behavior, since
input arrives in unpredictable chunks. For example::
# the input is 'foobar'
index = p.expect(['foobar', 'foo'])
# returns 0('foobar') if all input is available at once,
# but returns 1('foo') if parts of the final 'bar' arrive late
When a match is found for the given pattern, the class instance
attribute *match* becomes an re.MatchObject result. Should an EOF
or TIMEOUT pattern match, then the match attribute will be an instance
of that exception class. The pairing before and after class
instance attributes are views of the data preceding and following
the matching pattern. On general exception, class attribute
*before* is all data received up to the exception, while *match* and
*after* attributes are value None.
When the keyword argument timeout is -1 (default), then TIMEOUT will
raise after the default value specified by the class timeout
attribute. When None, TIMEOUT will not be raised and may block
indefinitely until match.
When the keyword argument searchwindowsize is -1 (default), then the
value specified by the class maxread attribute is used.
A list entry may be EOF or TIMEOUT instead of a string. This will
catch these exceptions and return the index of the list entry instead
of raising the exception. The attribute 'after' will be set to the
exception type. The attribute 'match' will be None. This allows you to
write code like this::
index = p.expect(['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
if index == 0:
do_something()
elif index == 1:
do_something_else()
elif index == 2:
do_some_other_thing()
elif index == 3:
do_something_completely_different()
instead of code like this::
try:
index = p.expect(['good', 'bad'])
if index == 0:
do_something()
elif index == 1:
do_something_else()
except EOF:
do_some_other_thing()
except TIMEOUT:
do_something_completely_different()
These two forms are equivalent. It all depends on what you want. You
can also just expect the EOF if you are waiting for all output of a
child to finish. For example::
p = pexpect.spawn('/bin/ls')
p.expect(pexpect.EOF)
print p.before
If you are trying to optimize for speed then see expect_list().
On Python 3.4, or Python 3.3 with asyncio installed, passing
``async_=True`` will make this return an :mod:`asyncio` coroutine,
which you can yield from to get the same result that this method would
normally give directly. So, inside a coroutine, you can replace this code::
index = p.expect(patterns)
With this non-blocking form::
index = yield from p.expect(patterns, async_=True) | This seeks through the stream until a pattern is matched. The
pattern is overloaded and may take several types. The pattern can be a
StringType, EOF, a compiled re, or a list of any of those types.
Strings will be compiled to re types. This returns the index into the
pattern list. If the pattern was not a list this returns index 0 on a
successful match. This may raise exceptions for EOF or TIMEOUT. To
avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern
list. That will cause expect to match an EOF or TIMEOUT condition
instead of raising an exception. | [
"This",
"seeks",
"through",
"the",
"stream",
"until",
"a",
"pattern",
"is",
"matched",
".",
"The",
"pattern",
"is",
"overloaded",
"and",
"may",
"take",
"several",
"types",
".",
"The",
"pattern",
"can",
"be",
"a",
"StringType",
"EOF",
"a",
"compiled",
"re",... | def expect(self, pattern, timeout=-1, searchwindowsize=-1, async_=False, **kw):
'''This seeks through the stream until a pattern is matched. The
pattern is overloaded and may take several types. The pattern can be a
StringType, EOF, a compiled re, or a list of any of those types.
Strings will be compiled to re types. This returns the index into the
pattern list. If the pattern was not a list this returns index 0 on a
successful match. This may raise exceptions for EOF or TIMEOUT. To
avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern
list. That will cause expect to match an EOF or TIMEOUT condition
instead of raising an exception.
If you pass a list of patterns and more than one matches, the first
match in the stream is chosen. If more than one pattern matches at that
point, the leftmost in the pattern list is chosen. For example::
# the input is 'foobar'
index = p.expect(['bar', 'foo', 'foobar'])
# returns 1('foo') even though 'foobar' is a "better" match
Please note, however, that buffering can affect this behavior, since
input arrives in unpredictable chunks. For example::
# the input is 'foobar'
index = p.expect(['foobar', 'foo'])
# returns 0('foobar') if all input is available at once,
# but returns 1('foo') if parts of the final 'bar' arrive late
When a match is found for the given pattern, the class instance
attribute *match* becomes an re.MatchObject result. Should an EOF
or TIMEOUT pattern match, then the match attribute will be an instance
of that exception class. The pairing before and after class
instance attributes are views of the data preceding and following
the matching pattern. On general exception, class attribute
*before* is all data received up to the exception, while *match* and
*after* attributes are value None.
When the keyword argument timeout is -1 (default), then TIMEOUT will
raise after the default value specified by the class timeout
attribute. When None, TIMEOUT will not be raised and may block
indefinitely until match.
When the keyword argument searchwindowsize is -1 (default), then the
value specified by the class maxread attribute is used.
A list entry may be EOF or TIMEOUT instead of a string. This will
catch these exceptions and return the index of the list entry instead
of raising the exception. The attribute 'after' will be set to the
exception type. The attribute 'match' will be None. This allows you to
write code like this::
index = p.expect(['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
if index == 0:
do_something()
elif index == 1:
do_something_else()
elif index == 2:
do_some_other_thing()
elif index == 3:
do_something_completely_different()
instead of code like this::
try:
index = p.expect(['good', 'bad'])
if index == 0:
do_something()
elif index == 1:
do_something_else()
except EOF:
do_some_other_thing()
except TIMEOUT:
do_something_completely_different()
These two forms are equivalent. It all depends on what you want. You
can also just expect the EOF if you are waiting for all output of a
child to finish. For example::
p = pexpect.spawn('/bin/ls')
p.expect(pexpect.EOF)
print p.before
If you are trying to optimize for speed then see expect_list().
On Python 3.4, or Python 3.3 with asyncio installed, passing
``async_=True`` will make this return an :mod:`asyncio` coroutine,
which you can yield from to get the same result that this method would
normally give directly. So, inside a coroutine, you can replace this code::
index = p.expect(patterns)
With this non-blocking form::
index = yield from p.expect(patterns, async_=True)
'''
if 'async' in kw:
async_ = kw.pop('async')
if kw:
raise TypeError("Unknown keyword arguments: {}".format(kw))
compiled_pattern_list = self.compile_pattern_list(pattern)
return self.expect_list(compiled_pattern_list,
timeout, searchwindowsize, async_) | [
"def",
"expect",
"(",
"self",
",",
"pattern",
",",
"timeout",
"=",
"-",
"1",
",",
"searchwindowsize",
"=",
"-",
"1",
",",
"async_",
"=",
"False",
",",
"*",
"*",
"kw",
")",
":",
"if",
"'async'",
"in",
"kw",
":",
"async_",
"=",
"kw",
".",
"pop",
... | https://github.com/pexpect/pexpect/blob/2be6c4d1aa2b9b522636342c2fd54b73c058060d/pexpect/spawnbase.py#L243-L344 | |
closeio/tasktiger | 754f3e90e4f759666910081b6bcd07d515c85a22 | tasktiger/redis_scripts.py | python | RedisScripts.can_replicate_commands | (self) | return self._can_replicate_commands | Whether Redis supports single command replication. | Whether Redis supports single command replication. | [
"Whether",
"Redis",
"supports",
"single",
"command",
"replication",
"."
] | def can_replicate_commands(self):
"""
Whether Redis supports single command replication.
"""
if not hasattr(self, '_can_replicate_commands'):
info = self.redis.info('server')
version_info = info['redis_version'].split('.')
major, minor = int(version_info[0]), int(version_info[1])
result = major > 3 or major == 3 and minor >= 2
self._can_replicate_commands = result
return self._can_replicate_commands | [
"def",
"can_replicate_commands",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_can_replicate_commands'",
")",
":",
"info",
"=",
"self",
".",
"redis",
".",
"info",
"(",
"'server'",
")",
"version_info",
"=",
"info",
"[",
"'redis_version'"... | https://github.com/closeio/tasktiger/blob/754f3e90e4f759666910081b6bcd07d515c85a22/tasktiger/redis_scripts.py#L317-L327 | |
angr/angr | 4b04d56ace135018083d36d9083805be8146688b | angr/analyses/identifier/functions/atoi.py | python | atoi.gen_input_output_pair | (self) | return TestData(test_input, test_output, return_val, max_steps) | [] | def gen_input_output_pair(self):
num = random.randint(-(2**26), 2**26-1)
if not self.allows_negative:
num = abs(num)
s = str(num)
test_input = [s]
test_output = [s]
return_val = num
max_steps = 20
return TestData(test_input, test_output, return_val, max_steps) | [
"def",
"gen_input_output_pair",
"(",
"self",
")",
":",
"num",
"=",
"random",
".",
"randint",
"(",
"-",
"(",
"2",
"**",
"26",
")",
",",
"2",
"**",
"26",
"-",
"1",
")",
"if",
"not",
"self",
".",
"allows_negative",
":",
"num",
"=",
"abs",
"(",
"num"... | https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/analyses/identifier/functions/atoi.py#L31-L42 | |||
trakt/Plex-Trakt-Scrobbler | aeb0bfbe62fad4b06c164f1b95581da7f35dce0b | Trakttv.bundle/Contents/Libraries/Shared/OpenSSL/rand.py | python | add | (buffer, entropy) | Mix bytes from *string* into the PRNG state.
The *entropy* argument is (the lower bound of) an estimate of how much
randomness is contained in *string*, measured in bytes.
For more information, see e.g. :rfc:`1750`.
:param buffer: Buffer with random data.
:param entropy: The entropy (in bytes) measurement of the buffer.
:return: :obj:`None` | Mix bytes from *string* into the PRNG state. | [
"Mix",
"bytes",
"from",
"*",
"string",
"*",
"into",
"the",
"PRNG",
"state",
"."
] | def add(buffer, entropy):
"""
Mix bytes from *string* into the PRNG state.
The *entropy* argument is (the lower bound of) an estimate of how much
randomness is contained in *string*, measured in bytes.
For more information, see e.g. :rfc:`1750`.
:param buffer: Buffer with random data.
:param entropy: The entropy (in bytes) measurement of the buffer.
:return: :obj:`None`
"""
if not isinstance(buffer, _builtin_bytes):
raise TypeError("buffer must be a byte string")
if not isinstance(entropy, int):
raise TypeError("entropy must be an integer")
# TODO Nothing tests this call actually being made, or made properly.
_lib.RAND_add(buffer, len(buffer), entropy) | [
"def",
"add",
"(",
"buffer",
",",
"entropy",
")",
":",
"if",
"not",
"isinstance",
"(",
"buffer",
",",
"_builtin_bytes",
")",
":",
"raise",
"TypeError",
"(",
"\"buffer must be a byte string\"",
")",
"if",
"not",
"isinstance",
"(",
"entropy",
",",
"int",
")",
... | https://github.com/trakt/Plex-Trakt-Scrobbler/blob/aeb0bfbe62fad4b06c164f1b95581da7f35dce0b/Trakttv.bundle/Contents/Libraries/Shared/OpenSSL/rand.py#L67-L88 | ||
RaRe-Technologies/smart_open | 59d3a6079b523c030c78a3935622cf94405ce052 | smart_open/s3.py | python | Reader.readable | (self) | return True | Return True if the stream can be read from. | Return True if the stream can be read from. | [
"Return",
"True",
"if",
"the",
"stream",
"can",
"be",
"read",
"from",
"."
] | def readable(self):
"""Return True if the stream can be read from."""
return True | [
"def",
"readable",
"(",
"self",
")",
":",
"return",
"True"
] | https://github.com/RaRe-Technologies/smart_open/blob/59d3a6079b523c030c78a3935622cf94405ce052/smart_open/s3.py#L584-L586 | |
ales-tsurko/cells | 4cf7e395cd433762bea70cdc863a346f3a6fe1d0 | packaging/macos/python/lib/python3.7/site-packages/pip/_vendor/urllib3/packages/rfc3986/validators.py | python | ensure_one_of | (allowed_values, uri, attribute) | Assert that the uri's attribute is one of the allowed values. | Assert that the uri's attribute is one of the allowed values. | [
"Assert",
"that",
"the",
"uri",
"s",
"attribute",
"is",
"one",
"of",
"the",
"allowed",
"values",
"."
] | def ensure_one_of(allowed_values, uri, attribute):
"""Assert that the uri's attribute is one of the allowed values."""
value = getattr(uri, attribute)
if value is not None and allowed_values and value not in allowed_values:
raise exceptions.UnpermittedComponentError(
attribute, value, allowed_values,
) | [
"def",
"ensure_one_of",
"(",
"allowed_values",
",",
"uri",
",",
"attribute",
")",
":",
"value",
"=",
"getattr",
"(",
"uri",
",",
"attribute",
")",
"if",
"value",
"is",
"not",
"None",
"and",
"allowed_values",
"and",
"value",
"not",
"in",
"allowed_values",
"... | https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/site-packages/pip/_vendor/urllib3/packages/rfc3986/validators.py#L254-L260 | ||
oracle/graalpython | 577e02da9755d916056184ec441c26e00b70145c | graalpython/lib-python/3/tkinter/ttk.py | python | Treeview.tag_bind | (self, tagname, sequence=None, callback=None) | Bind a callback for the given event sequence to the tag tagname.
When an event is delivered to an item, the callbacks for each
of the item's tags option are called. | Bind a callback for the given event sequence to the tag tagname.
When an event is delivered to an item, the callbacks for each
of the item's tags option are called. | [
"Bind",
"a",
"callback",
"for",
"the",
"given",
"event",
"sequence",
"to",
"the",
"tag",
"tagname",
".",
"When",
"an",
"event",
"is",
"delivered",
"to",
"an",
"item",
"the",
"callbacks",
"for",
"each",
"of",
"the",
"item",
"s",
"tags",
"option",
"are",
... | def tag_bind(self, tagname, sequence=None, callback=None):
"""Bind a callback for the given event sequence to the tag tagname.
When an event is delivered to an item, the callbacks for each
of the item's tags option are called."""
self._bind((self._w, "tag", "bind", tagname), sequence, callback, add=0) | [
"def",
"tag_bind",
"(",
"self",
",",
"tagname",
",",
"sequence",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"self",
".",
"_bind",
"(",
"(",
"self",
".",
"_w",
",",
"\"tag\"",
",",
"\"bind\"",
",",
"tagname",
")",
",",
"sequence",
",",
"ca... | https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/tkinter/ttk.py#L1472-L1476 | ||
tp4a/teleport | 1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad | server/www/packages/packages-darwin/x64/PIL/PcfFontFile.py | python | PcfFontFile._load_properties | (self) | return properties | [] | def _load_properties(self):
#
# font properties
properties = {}
fp, format, i16, i32 = self._getformat(PCF_PROPERTIES)
nprops = i32(fp.read(4))
# read property description
p = []
for i in range(nprops):
p.append((i32(fp.read(4)), i8(fp.read(1)), i32(fp.read(4))))
if nprops & 3:
fp.seek(4 - (nprops & 3), 1) # pad
data = fp.read(i32(fp.read(4)))
for k, s, v in p:
k = sz(data, k)
if s:
v = sz(data, v)
properties[k] = v
return properties | [
"def",
"_load_properties",
"(",
"self",
")",
":",
"#",
"# font properties",
"properties",
"=",
"{",
"}",
"fp",
",",
"format",
",",
"i16",
",",
"i32",
"=",
"self",
".",
"_getformat",
"(",
"PCF_PROPERTIES",
")",
"nprops",
"=",
"i32",
"(",
"fp",
".",
"rea... | https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/PIL/PcfFontFile.py#L104-L130 | |||
renerocksai/sublimeless_zk | 6738375c0e371f0c2fde0aa9e539242cfd2b4777 | patches/PyInstaller/depend/bindepend.py | python | getImports | (pth) | Forwards to the correct getImports implementation for the platform. | Forwards to the correct getImports implementation for the platform. | [
"Forwards",
"to",
"the",
"correct",
"getImports",
"implementation",
"for",
"the",
"platform",
"."
] | def getImports(pth):
"""
Forwards to the correct getImports implementation for the platform.
"""
if is_win or is_cygwin:
if pth.lower().endswith(".manifest"):
return []
try:
return _getImports_pe(pth)
except Exception as exception:
# Assemblies can pull in files which aren't necessarily PE,
# but are still needed by the assembly. Any additional binary
# dependencies should already have been handled by
# selectAssemblies in that case, so just warn, return an empty
# list and continue.
logger.warning('Can not get binary dependencies for file: %s', pth,
exc_info=1)
return []
elif is_darwin:
return _getImports_macholib(pth)
else:
return _getImports_ldd(pth) | [
"def",
"getImports",
"(",
"pth",
")",
":",
"if",
"is_win",
"or",
"is_cygwin",
":",
"if",
"pth",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"\".manifest\"",
")",
":",
"return",
"[",
"]",
"try",
":",
"return",
"_getImports_pe",
"(",
"pth",
")",
"exc... | https://github.com/renerocksai/sublimeless_zk/blob/6738375c0e371f0c2fde0aa9e539242cfd2b4777/patches/PyInstaller/depend/bindepend.py#L713-L734 | ||
PaddlePaddle/PaddleX | 2bab73f81ab54e328204e7871e6ae4a82e719f5d | paddlex/ppcls/arch/backbone/model_zoo/efficientnet.py | python | ProjectConvNorm.__init__ | (self,
input_channels,
block_args,
padding_type,
name=None,
model_name=None,
cur_stage=None) | [] | def __init__(self,
input_channels,
block_args,
padding_type,
name=None,
model_name=None,
cur_stage=None):
super(ProjectConvNorm, self).__init__()
final_oup = block_args.output_filters
self._conv = ConvBNLayer(
input_channels,
1,
final_oup,
bn_act=None,
padding_type=padding_type,
name=name,
conv_name=name + "_project_conv",
bn_name="_bn2",
model_name=model_name,
cur_stage=cur_stage) | [
"def",
"__init__",
"(",
"self",
",",
"input_channels",
",",
"block_args",
",",
"padding_type",
",",
"name",
"=",
"None",
",",
"model_name",
"=",
"None",
",",
"cur_stage",
"=",
"None",
")",
":",
"super",
"(",
"ProjectConvNorm",
",",
"self",
")",
".",
"__i... | https://github.com/PaddlePaddle/PaddleX/blob/2bab73f81ab54e328204e7871e6ae4a82e719f5d/paddlex/ppcls/arch/backbone/model_zoo/efficientnet.py#L486-L507 | ||||
Runbook/runbook | 7b68622f75ef09f654046f0394540025f3ee7445 | src/web/monitors.py | python | Monitor.count | (self, uid, rdb) | return result | This will return the numerical count of monitors by user id | This will return the numerical count of monitors by user id | [
"This",
"will",
"return",
"the",
"numerical",
"count",
"of",
"monitors",
"by",
"user",
"id"
] | def count(self, uid, rdb):
''' This will return the numerical count of monitors by user id '''
result = r.table('monitors').filter({'uid': uid}).count().run(rdb)
return result | [
"def",
"count",
"(",
"self",
",",
"uid",
",",
"rdb",
")",
":",
"result",
"=",
"r",
".",
"table",
"(",
"'monitors'",
")",
".",
"filter",
"(",
"{",
"'uid'",
":",
"uid",
"}",
")",
".",
"count",
"(",
")",
".",
"run",
"(",
"rdb",
")",
"return",
"r... | https://github.com/Runbook/runbook/blob/7b68622f75ef09f654046f0394540025f3ee7445/src/web/monitors.py#L232-L235 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/Python-2.7.9/Tools/pynche/pyColorChooser.py | python | Chooser.__init__ | (self,
master = None,
databasefile = None,
initfile = None,
ignore = None,
wantspec = None) | [] | def __init__(self,
master = None,
databasefile = None,
initfile = None,
ignore = None,
wantspec = None):
self.__master = master
self.__databasefile = databasefile
self.__initfile = initfile or os.path.expanduser('~/.pynche')
self.__ignore = ignore
self.__pw = None
self.__wantspec = wantspec | [
"def",
"__init__",
"(",
"self",
",",
"master",
"=",
"None",
",",
"databasefile",
"=",
"None",
",",
"initfile",
"=",
"None",
",",
"ignore",
"=",
"None",
",",
"wantspec",
"=",
"None",
")",
":",
"self",
".",
"__master",
"=",
"master",
"self",
".",
"__da... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Tools/pynche/pyColorChooser.py#L12-L23 | ||||
ifwe/digsby | f5fe00244744aa131e07f09348d10563f3d8fa99 | digsby/devplugins/irc/ircclient.py | python | IRCClient.NICK | (self, none, new_nick, origin) | An IRC buddy has changed his or her nickname.
We must be careful to replace the buddy's name, and also the hash
key for the buddy. | An IRC buddy has changed his or her nickname. | [
"An",
"IRC",
"buddy",
"has",
"changed",
"his",
"or",
"her",
"nickname",
"."
] | def NICK(self, none, new_nick, origin):
'''
An IRC buddy has changed his or her nickname.
We must be careful to replace the buddy's name, and also the hash
key for the buddy.
'''
old_nick = _origin_user(origin)
if not old_nick: return
buddy = self.buddies.pop(old_nick)
buddy.name = new_nick
self.buddies[new_nick] = buddy | [
"def",
"NICK",
"(",
"self",
",",
"none",
",",
"new_nick",
",",
"origin",
")",
":",
"old_nick",
"=",
"_origin_user",
"(",
"origin",
")",
"if",
"not",
"old_nick",
":",
"return",
"buddy",
"=",
"self",
".",
"buddies",
".",
"pop",
"(",
"old_nick",
")",
"b... | https://github.com/ifwe/digsby/blob/f5fe00244744aa131e07f09348d10563f3d8fa99/digsby/devplugins/irc/ircclient.py#L264-L276 | ||
brutasse/graphite-api | 0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff | graphite_api/functions.py | python | sortByMaxima | (requestContext, seriesList) | return list(sorted(seriesList, key=max)) | Takes one metric or a wildcard seriesList.
Sorts the list of metrics by the maximum value across the time period
specified. Useful with the &areaMode=all parameter, to keep the
lowest value lines visible.
Example::
&target=sortByMaxima(server*.instance*.memory.free) | Takes one metric or a wildcard seriesList. | [
"Takes",
"one",
"metric",
"or",
"a",
"wildcard",
"seriesList",
"."
] | def sortByMaxima(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList.
Sorts the list of metrics by the maximum value across the time period
specified. Useful with the &areaMode=all parameter, to keep the
lowest value lines visible.
Example::
&target=sortByMaxima(server*.instance*.memory.free)
"""
return list(sorted(seriesList, key=max)) | [
"def",
"sortByMaxima",
"(",
"requestContext",
",",
"seriesList",
")",
":",
"return",
"list",
"(",
"sorted",
"(",
"seriesList",
",",
"key",
"=",
"max",
")",
")"
] | https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L2554-L2567 | |
nschaetti/EchoTorch | cba209c49e0fda73172d2e853b85c747f9f5117e | echotorch/base_tensors.py | python | BaseTensor.short | (self) | return self | r"""To short (int16) :class:`BaseTensor` (no copy)
:return: The :class:`BaseTensor` with data casted to char
:rtype: :class:`BaseTensor` | r"""To short (int16) :class:`BaseTensor` (no copy) | [
"r",
"To",
"short",
"(",
"int16",
")",
":",
"class",
":",
"BaseTensor",
"(",
"no",
"copy",
")"
] | def short(self) -> 'BaseTensor':
r"""To short (int16) :class:`BaseTensor` (no copy)
:return: The :class:`BaseTensor` with data casted to char
:rtype: :class:`BaseTensor`
"""
self._tensor = self._tensor.char()
return self | [
"def",
"short",
"(",
"self",
")",
"->",
"'BaseTensor'",
":",
"self",
".",
"_tensor",
"=",
"self",
".",
"_tensor",
".",
"char",
"(",
")",
"return",
"self"
] | https://github.com/nschaetti/EchoTorch/blob/cba209c49e0fda73172d2e853b85c747f9f5117e/echotorch/base_tensors.py#L171-L178 | |
bert-nmt/bert-nmt | fcb616d28091ac23c9c16f30e6870fe90b8576d6 | bert/tokenization.py | python | BertTokenizer.__len__ | (self) | return len(self.vocab) | Returns the number of symbols in the dictionary | Returns the number of symbols in the dictionary | [
"Returns",
"the",
"number",
"of",
"symbols",
"in",
"the",
"dictionary"
] | def __len__(self):
"""Returns the number of symbols in the dictionary"""
return len(self.vocab) | [
"def",
"__len__",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"vocab",
")"
] | https://github.com/bert-nmt/bert-nmt/blob/fcb616d28091ac23c9c16f30e6870fe90b8576d6/bert/tokenization.py#L127-L129 | |
batiste/django-page-cms | 8ba3fa07ecc4aab1013db457ff50a1ebe1ac4d06 | pages/views.py | python | Details.resolve_redirection | (self, request, context) | Check for redirections. | Check for redirections. | [
"Check",
"for",
"redirections",
"."
] | def resolve_redirection(self, request, context):
"""Check for redirections."""
current_page = context['current_page']
lang = context['lang']
if current_page.redirect_to_url:
return HttpResponsePermanentRedirect(current_page.redirect_to_url)
if current_page.redirect_to:
return HttpResponsePermanentRedirect(
current_page.redirect_to.get_url_path(lang)) | [
"def",
"resolve_redirection",
"(",
"self",
",",
"request",
",",
"context",
")",
":",
"current_page",
"=",
"context",
"[",
"'current_page'",
"]",
"lang",
"=",
"context",
"[",
"'lang'",
"]",
"if",
"current_page",
".",
"redirect_to_url",
":",
"return",
"HttpRespo... | https://github.com/batiste/django-page-cms/blob/8ba3fa07ecc4aab1013db457ff50a1ebe1ac4d06/pages/views.py#L134-L143 | ||
huggingface/transformers | 623b4f7c63f60cce917677ee704d6c93ee960b4b | src/transformers/utils/dummy_pt_objects.py | python | DistilBertForSequenceClassification.__init__ | (self, *args, **kwargs) | [] | def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"]) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"requires_backends",
"(",
"self",
",",
"[",
"\"torch\"",
"]",
")"
] | https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/utils/dummy_pt_objects.py#L1826-L1827 | ||||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_vendored_deps/library/oc_pvc.py | python | PersistentVolumeClaim.add_access_mode | (self, inc_mode) | return True | add an access_mode | add an access_mode | [
"add",
"an",
"access_mode"
] | def add_access_mode(self, inc_mode):
''' add an access_mode'''
if self.access_modes:
self.access_modes.append(inc_mode)
else:
self.put(PersistentVolumeClaim.access_modes_path, [inc_mode])
return True | [
"def",
"add_access_mode",
"(",
"self",
",",
"inc_mode",
")",
":",
"if",
"self",
".",
"access_modes",
":",
"self",
".",
"access_modes",
".",
"append",
"(",
"inc_mode",
")",
"else",
":",
"self",
".",
"put",
"(",
"PersistentVolumeClaim",
".",
"access_modes_path... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_vendored_deps/library/oc_pvc.py#L1648-L1655 | |
Source-Python-Dev-Team/Source.Python | d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb | addons/source-python/Python3/_pydecimal.py | python | Decimal.__neg__ | (self, context=None) | return ans._fix(context) | Returns a copy with the sign switched.
Rounds, if it has reason. | Returns a copy with the sign switched. | [
"Returns",
"a",
"copy",
"with",
"the",
"sign",
"switched",
"."
] | def __neg__(self, context=None):
"""Returns a copy with the sign switched.
Rounds, if it has reason.
"""
if self._is_special:
ans = self._check_nans(context=context)
if ans:
return ans
if context is None:
context = getcontext()
if not self and context.rounding != ROUND_FLOOR:
# -Decimal('0') is Decimal('0'), not Decimal('-0'), except
# in ROUND_FLOOR rounding mode.
ans = self.copy_abs()
else:
ans = self.copy_negate()
return ans._fix(context) | [
"def",
"__neg__",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"if",
"self",
".",
"_is_special",
":",
"ans",
"=",
"self",
".",
"_check_nans",
"(",
"context",
"=",
"context",
")",
"if",
"ans",
":",
"return",
"ans",
"if",
"context",
"is",
"None"... | https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/_pydecimal.py#L1129-L1149 | |
pantsbuild/pex | 473c6ac732ed4bc338b4b20a9ec930d1d722c9b4 | pex/vendor/_vendored/pip/pip/_vendor/distlib/_backport/tarfile.py | python | TarFile.taropen | (cls, name, mode="r", fileobj=None, **kwargs) | return cls(name, mode, fileobj, **kwargs) | Open uncompressed tar archive name for reading or writing. | Open uncompressed tar archive name for reading or writing. | [
"Open",
"uncompressed",
"tar",
"archive",
"name",
"for",
"reading",
"or",
"writing",
"."
] | def taropen(cls, name, mode="r", fileobj=None, **kwargs):
"""Open uncompressed tar archive name for reading or writing.
"""
if len(mode) > 1 or mode not in "raw":
raise ValueError("mode must be 'r', 'a' or 'w'")
return cls(name, mode, fileobj, **kwargs) | [
"def",
"taropen",
"(",
"cls",
",",
"name",
",",
"mode",
"=",
"\"r\"",
",",
"fileobj",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"mode",
")",
">",
"1",
"or",
"mode",
"not",
"in",
"\"raw\"",
":",
"raise",
"ValueError",
"(",
... | https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/pip/pip/_vendor/distlib/_backport/tarfile.py#L1790-L1795 | |
smicallef/spiderfoot | fd4bf9394c9ab3ecc90adc3115c56349fb23165b | modules/sfp_commoncrawl.py | python | sfp_commoncrawl.watchedEvents | (self) | return ["INTERNET_NAME"] | [] | def watchedEvents(self):
return ["INTERNET_NAME"] | [
"def",
"watchedEvents",
"(",
"self",
")",
":",
"return",
"[",
"\"INTERNET_NAME\"",
"]"
] | https://github.com/smicallef/spiderfoot/blob/fd4bf9394c9ab3ecc90adc3115c56349fb23165b/modules/sfp_commoncrawl.py#L124-L125 | |||
meetbill/zabbix_manager | 739e5b51facf19cc6bda2b50f29108f831cf833e | ZabbixTool/lib_zabbix/w_lib/colorclass/core.py | python | ColorStr.isalnum | (self) | return self.value_no_colors.isalnum() | Return True if all characters in string are alphanumeric and there is at least one character in it. | Return True if all characters in string are alphanumeric and there is at least one character in it. | [
"Return",
"True",
"if",
"all",
"characters",
"in",
"string",
"are",
"alphanumeric",
"and",
"there",
"is",
"at",
"least",
"one",
"character",
"in",
"it",
"."
] | def isalnum(self):
"""Return True if all characters in string are alphanumeric and there is at least one character in it."""
return self.value_no_colors.isalnum() | [
"def",
"isalnum",
"(",
"self",
")",
":",
"return",
"self",
".",
"value_no_colors",
".",
"isalnum",
"(",
")"
] | https://github.com/meetbill/zabbix_manager/blob/739e5b51facf19cc6bda2b50f29108f831cf833e/ZabbixTool/lib_zabbix/w_lib/colorclass/core.py#L198-L200 | |
GalSim-developers/GalSim | a05d4ec3b8d8574f99d3b0606ad882cbba53f345 | galsim/download_cosmos.py | python | download_cosmos | (args, logger) | The main script given the ArgParsed args and a logger | The main script given the ArgParsed args and a logger | [
"The",
"main",
"script",
"given",
"the",
"ArgParsed",
"args",
"and",
"a",
"logger"
] | def download_cosmos(args, logger):
"""The main script given the ArgParsed args and a logger
"""
# Give diagnostic about GalSim version
logger.debug("GalSim version: %s",version)
logger.debug("This download script is: %s",__file__)
logger.info("Type %s -h to see command line options.\n",script_name)
# Some definitions:
# share_dir is the base galsim share directory, e.g. /usr/local/share/galsim/
# url is the url from which we will download the tarball.
# target is the full path of the downloaded tarball
# target_dir is where we will put the downloaded file, usually == share_dir.
# link_dir is the directory where this would normally have been unpacked.
# unpack_dir is the directory that the tarball will unpack into.
url, target, target_dir, link_dir, unpack_dir, do_link = get_names(args, logger)
meta = get_meta(url, args, logger)
# Check if the file already exists and if it is the right size
do_download = check_existing(target, unpack_dir, meta, args, logger)
# Download the tarball
download(do_download, url, target, meta, args, logger)
# Unpack the tarball
do_unpack = check_unpack(do_download, unpack_dir, target, args)
unpack(do_unpack, target, target_dir, unpack_dir, meta, args, logger)
# Remove the tarball
do_remove = check_remove(do_unpack, target, args)
remove_tarball(do_remove, target, logger)
# If we are downloading to an alternate directory, we (usually) link to it from share/galsim
make_link(do_link, unpack_dir, link_dir, args, logger) | [
"def",
"download_cosmos",
"(",
"args",
",",
"logger",
")",
":",
"# Give diagnostic about GalSim version",
"logger",
".",
"debug",
"(",
"\"GalSim version: %s\"",
",",
"version",
")",
"logger",
".",
"debug",
"(",
"\"This download script is: %s\"",
",",
"__file__",
")",
... | https://github.com/GalSim-developers/GalSim/blob/a05d4ec3b8d8574f99d3b0606ad882cbba53f345/galsim/download_cosmos.py#L397-L432 | ||
dulwich/dulwich | 1f66817d712e3563ce1ff53b1218491a2eae39da | dulwich/porcelain.py | python | upload_pack | (path=".", inf=None, outf=None) | return 0 | Upload a pack file after negotiating its contents using smart protocol.
Args:
path: Path to the repository
inf: Input stream to communicate with client
outf: Output stream to communicate with client | Upload a pack file after negotiating its contents using smart protocol. | [
"Upload",
"a",
"pack",
"file",
"after",
"negotiating",
"its",
"contents",
"using",
"smart",
"protocol",
"."
] | def upload_pack(path=".", inf=None, outf=None):
"""Upload a pack file after negotiating its contents using smart protocol.
Args:
path: Path to the repository
inf: Input stream to communicate with client
outf: Output stream to communicate with client
"""
if outf is None:
outf = getattr(sys.stdout, "buffer", sys.stdout)
if inf is None:
inf = getattr(sys.stdin, "buffer", sys.stdin)
path = os.path.expanduser(path)
backend = FileSystemBackend(path)
def send_fn(data):
outf.write(data)
outf.flush()
proto = Protocol(inf.read, send_fn)
handler = UploadPackHandler(backend, [path], proto)
# FIXME: Catch exceptions and write a single-line summary to outf.
handler.handle()
return 0 | [
"def",
"upload_pack",
"(",
"path",
"=",
"\".\"",
",",
"inf",
"=",
"None",
",",
"outf",
"=",
"None",
")",
":",
"if",
"outf",
"is",
"None",
":",
"outf",
"=",
"getattr",
"(",
"sys",
".",
"stdout",
",",
"\"buffer\"",
",",
"sys",
".",
"stdout",
")",
"... | https://github.com/dulwich/dulwich/blob/1f66817d712e3563ce1ff53b1218491a2eae39da/dulwich/porcelain.py#L1340-L1363 | |
JiYou/openstack | 8607dd488bde0905044b303eb6e52bdea6806923 | packages/source/nova/nova/scheduler/filters/retry_filter.py | python | RetryFilter.host_passes | (self, host_state, filter_properties) | return passes | Skip nodes that have already been attempted. | Skip nodes that have already been attempted. | [
"Skip",
"nodes",
"that",
"have",
"already",
"been",
"attempted",
"."
] | def host_passes(self, host_state, filter_properties):
"""Skip nodes that have already been attempted."""
retry = filter_properties.get('retry', None)
if not retry:
# Re-scheduling is disabled
LOG.debug("Re-scheduling is disabled")
return True
hosts = retry.get('hosts', [])
host = [host_state.host, host_state.nodename]
passes = host not in hosts
pass_msg = "passes" if passes else "fails"
LOG.debug(_("Host %(host)s %(pass_msg)s. Previously tried hosts: "
"%(hosts)s") % locals())
# Host passes if it's not in the list of previously attempted hosts:
return passes | [
"def",
"host_passes",
"(",
"self",
",",
"host_state",
",",
"filter_properties",
")",
":",
"retry",
"=",
"filter_properties",
".",
"get",
"(",
"'retry'",
",",
"None",
")",
"if",
"not",
"retry",
":",
"# Re-scheduling is disabled",
"LOG",
".",
"debug",
"(",
"\"... | https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/nova/nova/scheduler/filters/retry_filter.py#L27-L45 | |
omz/PythonistaAppTemplate | f560f93f8876d82a21d108977f90583df08d55af | PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/core/containers.py | python | Dict.items | (self) | return self._dict.items() | D.items() -> list of D's (key, value) pairs, as 2-tuples | D.items() -> list of D's (key, value) pairs, as 2-tuples | [
"D",
".",
"items",
"()",
"-",
">",
"list",
"of",
"D",
"s",
"(",
"key",
"value",
")",
"pairs",
"as",
"2",
"-",
"tuples"
] | def items(self):
'''D.items() -> list of D's (key, value) pairs, as 2-tuples'''
return self._dict.items() | [
"def",
"items",
"(",
"self",
")",
":",
"return",
"self",
".",
"_dict",
".",
"items",
"(",
")"
] | https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/core/containers.py#L222-L224 | |
Netflix/vmaf | e768a2be57116c76bf33be7f8ee3566d8b774664 | python/vmaf/tools/misc.py | python | dedup_value_in_dict | (d) | return d_ | >>> dedup_value_in_dict({'a': 1, 'b': 1, 'c': 2}) == {'a': 1, 'c': 2}
True | >>> dedup_value_in_dict({'a': 1, 'b': 1, 'c': 2}) == {'a': 1, 'c': 2}
True | [
">>>",
"dedup_value_in_dict",
"(",
"{",
"a",
":",
"1",
"b",
":",
"1",
"c",
":",
"2",
"}",
")",
"==",
"{",
"a",
":",
"1",
"c",
":",
"2",
"}",
"True"
] | def dedup_value_in_dict(d):
"""
>>> dedup_value_in_dict({'a': 1, 'b': 1, 'c': 2}) == {'a': 1, 'c': 2}
True
"""
reversed_d = dict()
keys = sorted(d.keys())
for key in keys:
value = d[key]
if value not in reversed_d:
reversed_d[value] = key
d_ = dict()
for value, key in reversed_d.items():
d_[key] = value
return d_ | [
"def",
"dedup_value_in_dict",
"(",
"d",
")",
":",
"reversed_d",
"=",
"dict",
"(",
")",
"keys",
"=",
"sorted",
"(",
"d",
".",
"keys",
"(",
")",
")",
"for",
"key",
"in",
"keys",
":",
"value",
"=",
"d",
"[",
"key",
"]",
"if",
"value",
"not",
"in",
... | https://github.com/Netflix/vmaf/blob/e768a2be57116c76bf33be7f8ee3566d8b774664/python/vmaf/tools/misc.py#L491-L505 | |
hirofumi0810/tensorflow_end2end_speech_recognition | 65b9728089d5e92b25b92384a67419d970399a64 | models/attention/attention_seq2seq.py | python | AttentionSeq2Seq._encode | (self, inputs, inputs_seq_len, keep_prob_encoder) | return EncoderOutput(outputs=outputs,
final_state=final_state,
seq_len=inputs_seq_len) | Encode input features.
Args:
inputs (placeholder): A tensor of size`[B, T, input_size]`
inputs_seq_len (placeholder): A tensor of size` [B]`
keep_prob_encoder (placeholder, float): A probability to keep nodes
in the hidden-hidden connection
Returns:
encoder_outputs (namedtuple): A namedtuple of
`(outputs, final_state, seq_len)`
outputs: Encoder states, a tensor of size
`[B, T, num_units (num_proj)]` (always batch-major)
final_state: A final hidden state of the encoder
seq_len: equivalent to inputs_seq_len | Encode input features.
Args:
inputs (placeholder): A tensor of size`[B, T, input_size]`
inputs_seq_len (placeholder): A tensor of size` [B]`
keep_prob_encoder (placeholder, float): A probability to keep nodes
in the hidden-hidden connection
Returns:
encoder_outputs (namedtuple): A namedtuple of
`(outputs, final_state, seq_len)`
outputs: Encoder states, a tensor of size
`[B, T, num_units (num_proj)]` (always batch-major)
final_state: A final hidden state of the encoder
seq_len: equivalent to inputs_seq_len | [
"Encode",
"input",
"features",
".",
"Args",
":",
"inputs",
"(",
"placeholder",
")",
":",
"A",
"tensor",
"of",
"size",
"[",
"B",
"T",
"input_size",
"]",
"inputs_seq_len",
"(",
"placeholder",
")",
":",
"A",
"tensor",
"of",
"size",
"[",
"B",
"]",
"keep_pr... | def _encode(self, inputs, inputs_seq_len, keep_prob_encoder):
"""Encode input features.
Args:
inputs (placeholder): A tensor of size`[B, T, input_size]`
inputs_seq_len (placeholder): A tensor of size` [B]`
keep_prob_encoder (placeholder, float): A probability to keep nodes
in the hidden-hidden connection
Returns:
encoder_outputs (namedtuple): A namedtuple of
`(outputs, final_state, seq_len)`
outputs: Encoder states, a tensor of size
`[B, T, num_units (num_proj)]` (always batch-major)
final_state: A final hidden state of the encoder
seq_len: equivalent to inputs_seq_len
"""
# Define encoder
if self.encoder_type in ['blstm', 'lstm']:
self.encoder = load_encoder(self.encoder_type)(
num_units=self.encoder_num_units,
num_proj=None, # TODO: add the projection layer
num_layers=self.encoder_num_layers,
lstm_impl=self.lstm_impl,
use_peephole=self.use_peephole,
parameter_init=self.parameter_init,
clip_activation=self.clip_activation_encoder,
time_major=self.time_major)
else:
# TODO: add other encoders
raise NotImplementedError
outputs, final_state = self.encoder(
inputs=inputs,
inputs_seq_len=inputs_seq_len,
keep_prob=keep_prob_encoder,
is_training=True)
# TODO: fix this
if self.time_major:
# Convert from time-major to batch-major
outputs = tf.transpose(outputs, [1, 0, 2])
return EncoderOutput(outputs=outputs,
final_state=final_state,
seq_len=inputs_seq_len) | [
"def",
"_encode",
"(",
"self",
",",
"inputs",
",",
"inputs_seq_len",
",",
"keep_prob_encoder",
")",
":",
"# Define encoder",
"if",
"self",
".",
"encoder_type",
"in",
"[",
"'blstm'",
",",
"'lstm'",
"]",
":",
"self",
".",
"encoder",
"=",
"load_encoder",
"(",
... | https://github.com/hirofumi0810/tensorflow_end2end_speech_recognition/blob/65b9728089d5e92b25b92384a67419d970399a64/models/attention/attention_seq2seq.py#L279-L322 | |
gem/oq-engine | 1bdb88f3914e390abcbd285600bfd39477aae47c | openquake/hazardlib/gsim/ameri_2017.py | python | _get_magnitude_scaling_term | (C, mag) | Returns the magnitude scaling term of the GMPE described in
equation 3 | Returns the magnitude scaling term of the GMPE described in
equation 3 | [
"Returns",
"the",
"magnitude",
"scaling",
"term",
"of",
"the",
"GMPE",
"described",
"in",
"equation",
"3"
] | def _get_magnitude_scaling_term(C, mag):
"""
Returns the magnitude scaling term of the GMPE described in
equation 3
"""
dmag = mag - CONSTS["Mh"]
if mag <= CONSTS["Mh"]:
return C["b1"] * dmag + C["b2"] * (dmag ** 2.0)
else:
return C["b3"] * dmag | [
"def",
"_get_magnitude_scaling_term",
"(",
"C",
",",
"mag",
")",
":",
"dmag",
"=",
"mag",
"-",
"CONSTS",
"[",
"\"Mh\"",
"]",
"if",
"mag",
"<=",
"CONSTS",
"[",
"\"Mh\"",
"]",
":",
"return",
"C",
"[",
"\"b1\"",
"]",
"*",
"dmag",
"+",
"C",
"[",
"\"b2\... | https://github.com/gem/oq-engine/blob/1bdb88f3914e390abcbd285600bfd39477aae47c/openquake/hazardlib/gsim/ameri_2017.py#L76-L85 | ||
tylertreat/BigQuery-Python | 40aaf694afbc37875ed18b66bce9fbc1ffdb7765 | bigquery/client.py | python | BigQueryClient._recurse_on_row | (self, col_dict, nested_value) | return row_value | Apply the schema specified by the given dict to the nested value by
recursing on it.
Parameters
----------
col_dict : dict
The schema to apply to the nested value.
nested_value : A value nested in a BigQuery row.
Returns
-------
Union[dict, list]
``dict`` or ``list`` of ``dict`` objects from applied schema. | Apply the schema specified by the given dict to the nested value by
recursing on it. | [
"Apply",
"the",
"schema",
"specified",
"by",
"the",
"given",
"dict",
"to",
"the",
"nested",
"value",
"by",
"recursing",
"on",
"it",
"."
] | def _recurse_on_row(self, col_dict, nested_value):
"""Apply the schema specified by the given dict to the nested value by
recursing on it.
Parameters
----------
col_dict : dict
The schema to apply to the nested value.
nested_value : A value nested in a BigQuery row.
Returns
-------
Union[dict, list]
``dict`` or ``list`` of ``dict`` objects from applied schema.
"""
row_value = None
# Multiple nested records
if col_dict['mode'] == 'REPEATED' and isinstance(nested_value, list):
row_value = [self._transform_row(record['v'], col_dict['fields'])
for record in nested_value]
# A single nested record
else:
row_value = self._transform_row(nested_value, col_dict['fields'])
return row_value | [
"def",
"_recurse_on_row",
"(",
"self",
",",
"col_dict",
",",
"nested_value",
")",
":",
"row_value",
"=",
"None",
"# Multiple nested records",
"if",
"col_dict",
"[",
"'mode'",
"]",
"==",
"'REPEATED'",
"and",
"isinstance",
"(",
"nested_value",
",",
"list",
")",
... | https://github.com/tylertreat/BigQuery-Python/blob/40aaf694afbc37875ed18b66bce9fbc1ffdb7765/bigquery/client.py#L1713-L1740 | |
artefactual/archivematica | 4f4605453d5a8796f6a739fa9664921bdb3418f2 | src/MCPClient/lib/ensure_no_mutable_globals.py | python | analyze_module | (module_name) | return global2modules_funcs_2 | Analyze module ``module_name`` by importing it and returning a dict that
documents the mutable globals that are accessed by any of its functions or
methods. | Analyze module ``module_name`` by importing it and returning a dict that
documents the mutable globals that are accessed by any of its functions or
methods. | [
"Analyze",
"module",
"module_name",
"by",
"importing",
"it",
"and",
"returning",
"a",
"dict",
"that",
"documents",
"the",
"mutable",
"globals",
"that",
"are",
"accessed",
"by",
"any",
"of",
"its",
"functions",
"or",
"methods",
"."
] | def analyze_module(module_name):
"""Analyze module ``module_name`` by importing it and returning a dict that
documents the mutable globals that are accessed by any of its functions or
methods.
"""
global2modules_funcs_2 = {}
module = importlib.import_module("clientScripts." + module_name)
for attr in dir(module):
val = getattr(module, attr)
if attr.startswith("__"):
continue
if six.PY2 and isinstance(val, (types.TypeType, types.ClassType)):
for class_attr in dir(val):
global2modules_funcs_2 = collect_globals(
"{}.{}".format(attr, class_attr),
getattr(val, class_attr),
module,
module_name,
global2modules_funcs_2,
)
elif isinstance(val, types.FunctionType):
global2modules_funcs_2 = collect_globals(
attr, val, module, module_name, global2modules_funcs_2
)
return global2modules_funcs_2 | [
"def",
"analyze_module",
"(",
"module_name",
")",
":",
"global2modules_funcs_2",
"=",
"{",
"}",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"\"clientScripts.\"",
"+",
"module_name",
")",
"for",
"attr",
"in",
"dir",
"(",
"module",
")",
":",
"val",
... | https://github.com/artefactual/archivematica/blob/4f4605453d5a8796f6a739fa9664921bdb3418f2/src/MCPClient/lib/ensure_no_mutable_globals.py#L111-L135 | |
entropy1337/infernal-twin | 10995cd03312e39a48ade0f114ebb0ae3a711bb8 | Modules/build/pip/build/lib.linux-i686-2.7/pip/vcs/__init__.py | python | VersionControl.get_url | (self, location) | Return the url used at location
Used in get_info or check_destination | Return the url used at location
Used in get_info or check_destination | [
"Return",
"the",
"url",
"used",
"at",
"location",
"Used",
"in",
"get_info",
"or",
"check_destination"
] | def get_url(self, location):
"""
Return the url used at location
Used in get_info or check_destination
"""
raise NotImplementedError | [
"def",
"get_url",
"(",
"self",
",",
"location",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/entropy1337/infernal-twin/blob/10995cd03312e39a48ade0f114ebb0ae3a711bb8/Modules/build/pip/build/lib.linux-i686-2.7/pip/vcs/__init__.py#L287-L292 | ||
pantsbuild/pex | 473c6ac732ed4bc338b4b20a9ec930d1d722c9b4 | pex/vendor/_vendored/pip/pip/_vendor/ipaddress.py | python | _BaseNetwork.num_addresses | (self) | return int(self.broadcast_address) - int(self.network_address) + 1 | Number of hosts in the current subnet. | Number of hosts in the current subnet. | [
"Number",
"of",
"hosts",
"in",
"the",
"current",
"subnet",
"."
] | def num_addresses(self):
"""Number of hosts in the current subnet."""
return int(self.broadcast_address) - int(self.network_address) + 1 | [
"def",
"num_addresses",
"(",
"self",
")",
":",
"return",
"int",
"(",
"self",
".",
"broadcast_address",
")",
"-",
"int",
"(",
"self",
".",
"network_address",
")",
"+",
"1"
] | https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/pip/pip/_vendor/ipaddress.py#L847-L849 | |
adobe/brackets-shell | c180d7ea812759ba50d25ab0685434c345343008 | gyp/pylib/gyp/xml_fix.py | python | _Replacement_write_data | (writer, data, is_attrib=False) | Writes datachars to writer. | Writes datachars to writer. | [
"Writes",
"datachars",
"to",
"writer",
"."
] | def _Replacement_write_data(writer, data, is_attrib=False):
"""Writes datachars to writer."""
data = data.replace("&", "&").replace("<", "<")
data = data.replace("\"", """).replace(">", ">")
if is_attrib:
data = data.replace(
"\r", "
").replace(
"\n", "
").replace(
"\t", "	")
writer.write(data) | [
"def",
"_Replacement_write_data",
"(",
"writer",
",",
"data",
",",
"is_attrib",
"=",
"False",
")",
":",
"data",
"=",
"data",
".",
"replace",
"(",
"\"&\"",
",",
"\"&\"",
")",
".",
"replace",
"(",
"\"<\"",
",",
"\"<\"",
")",
"data",
"=",
"data",
"... | https://github.com/adobe/brackets-shell/blob/c180d7ea812759ba50d25ab0685434c345343008/gyp/pylib/gyp/xml_fix.py#L16-L25 | ||
Source-Python-Dev-Team/Source.Python | d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb | addons/source-python/packages/source-python/plugins/instance.py | python | Plugin._unload | (self) | Actually unload the plugin. | Actually unload the plugin. | [
"Actually",
"unload",
"the",
"plugin",
"."
] | def _unload(self):
"""Actually unload the plugin."""
if hasattr(self.module, 'unload'):
self.module.unload()
self.module = None | [
"def",
"_unload",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"module",
",",
"'unload'",
")",
":",
"self",
".",
"module",
".",
"unload",
"(",
")",
"self",
".",
"module",
"=",
"None"
] | https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/source-python/plugins/instance.py#L78-L83 | ||
aneisch/home-assistant-config | 86e381fde9609cb8871c439c433c12989e4e225d | custom_components/alexa_media/notify.py | python | AlexaNotificationService.convert | (self, names, type_="entities", filter_matches=False) | return devices | Return a list of converted Alexa devices based on names.
Names may be matched either by serialNumber, accountName, or
Homeassistant entity_id and can return any of the above plus entities
Parameters
----------
names : list(string)
A list of names to convert
type_ : string
The type to return entities, entity_ids, serialnumbers, names
filter_matches : bool
Whether non-matching items are removed from the returned list.
Returns
-------
list(string)
List of home assistant entity_ids | Return a list of converted Alexa devices based on names. | [
"Return",
"a",
"list",
"of",
"converted",
"Alexa",
"devices",
"based",
"on",
"names",
"."
] | def convert(self, names, type_="entities", filter_matches=False):
"""Return a list of converted Alexa devices based on names.
Names may be matched either by serialNumber, accountName, or
Homeassistant entity_id and can return any of the above plus entities
Parameters
----------
names : list(string)
A list of names to convert
type_ : string
The type to return entities, entity_ids, serialnumbers, names
filter_matches : bool
Whether non-matching items are removed from the returned list.
Returns
-------
list(string)
List of home assistant entity_ids
"""
devices = []
if isinstance(names, str):
names = [names]
for item in names:
matched = False
for alexa in self.devices:
# _LOGGER.debug(
# "Testing item: %s against (%s, %s, %s, %s)",
# item,
# alexa,
# alexa.name,
# hide_serial(alexa.unique_id),
# alexa.entity_id,
# )
if item in (
alexa,
alexa.name,
alexa.unique_id,
alexa.entity_id,
alexa.device_serial_number,
):
if type_ == "entities":
converted = alexa
elif type_ == "serialnumbers":
converted = alexa.device_serial_number
elif type_ == "names":
converted = alexa.name
elif type_ == "entity_ids":
converted = alexa.entity_id
devices.append(converted)
matched = True
# _LOGGER.debug("Converting: %s to (%s): %s", item, type_, converted)
if not filter_matches and not matched:
devices.append(item)
return devices | [
"def",
"convert",
"(",
"self",
",",
"names",
",",
"type_",
"=",
"\"entities\"",
",",
"filter_matches",
"=",
"False",
")",
":",
"devices",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"names",
",",
"str",
")",
":",
"names",
"=",
"[",
"names",
"]",
"for",
... | https://github.com/aneisch/home-assistant-config/blob/86e381fde9609cb8871c439c433c12989e4e225d/custom_components/alexa_media/notify.py#L85-L140 | |
tp4a/teleport | 1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad | server/www/packages/packages-windows/x86/pyasn1/codec/ber/encoder.py | python | IntegerEncoder.encodeValue | (self, value, asn1Spec, encodeFun, **options) | return to_bytes(int(value), signed=True), False, True | [] | def encodeValue(self, value, asn1Spec, encodeFun, **options):
if value == 0:
if LOG:
LOG('encoding %spayload for zero INTEGER' % (
self.supportCompactZero and 'no ' or ''
))
# de-facto way to encode zero
if self.supportCompactZero:
return (), False, False
else:
return (0,), False, False
return to_bytes(int(value), signed=True), False, True | [
"def",
"encodeValue",
"(",
"self",
",",
"value",
",",
"asn1Spec",
",",
"encodeFun",
",",
"*",
"*",
"options",
")",
":",
"if",
"value",
"==",
"0",
":",
"if",
"LOG",
":",
"LOG",
"(",
"'encoding %spayload for zero INTEGER'",
"%",
"(",
"self",
".",
"supportC... | https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/pyasn1/codec/ber/encoder.py#L171-L184 | |||
miguelgrinberg/api-pycon2014 | 9a1e036d0851b93545b1d0bd0309d61cc01f3d89 | api/rate_limit.py | python | FakeRedis.execute | (self) | return [self.v[self.last_key]] | [] | def execute(self):
return [self.v[self.last_key]] | [
"def",
"execute",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"v",
"[",
"self",
".",
"last_key",
"]",
"]"
] | https://github.com/miguelgrinberg/api-pycon2014/blob/9a1e036d0851b93545b1d0bd0309d61cc01f3d89/api/rate_limit.py#L26-L27 | |||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/openshift_facts/library/openshift_facts.py | python | normalize_gce_facts | (metadata, facts) | return facts | Normalize gce facts
Args:
metadata (dict): provider metadata
facts (dict): facts to update
Returns:
dict: the result of adding the normalized metadata to the provided
facts dict | Normalize gce facts | [
"Normalize",
"gce",
"facts"
] | def normalize_gce_facts(metadata, facts):
""" Normalize gce facts
Args:
metadata (dict): provider metadata
facts (dict): facts to update
Returns:
dict: the result of adding the normalized metadata to the provided
facts dict
"""
for interface in metadata['instance']['networkInterfaces']:
int_info = dict(ips=[interface['ip']], network_type='gce')
int_info['public_ips'] = [ac['externalIp'] for ac
in interface['accessConfigs']]
int_info['public_ips'].extend(interface['forwardedIps'])
_, _, network_id = interface['network'].rpartition('/')
int_info['network_id'] = network_id
facts['network']['interfaces'].append(int_info)
_, _, zone = metadata['instance']['zone'].rpartition('/')
facts['zone'] = zone
# GCE currently only supports a single interface
facts['network']['ip'] = facts['network']['interfaces'][0]['ips'][0]
pub_ip = facts['network']['interfaces'][0]['public_ips'][0]
facts['network']['public_ip'] = pub_ip
# Split instance hostname from GCE metadata to use the short instance name
facts['network']['hostname'] = metadata['instance']['hostname'].split('.')[0]
# TODO: attempt to resolve public_hostname
facts['network']['public_hostname'] = facts['network']['public_ip']
return facts | [
"def",
"normalize_gce_facts",
"(",
"metadata",
",",
"facts",
")",
":",
"for",
"interface",
"in",
"metadata",
"[",
"'instance'",
"]",
"[",
"'networkInterfaces'",
"]",
":",
"int_info",
"=",
"dict",
"(",
"ips",
"=",
"[",
"interface",
"[",
"'ip'",
"]",
"]",
... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/openshift_facts/library/openshift_facts.py#L206-L237 | |
dropbox/dropbox-sdk-python | 015437429be224732990041164a21a0501235db1 | dropbox/team_log.py | python | EventType.is_member_transfer_account_contents | (self) | return self._tag == 'member_transfer_account_contents' | Check if the union tag is ``member_transfer_account_contents``.
:rtype: bool | Check if the union tag is ``member_transfer_account_contents``. | [
"Check",
"if",
"the",
"union",
"tag",
"is",
"member_transfer_account_contents",
"."
] | def is_member_transfer_account_contents(self):
"""
Check if the union tag is ``member_transfer_account_contents``.
:rtype: bool
"""
return self._tag == 'member_transfer_account_contents' | [
"def",
"is_member_transfer_account_contents",
"(",
"self",
")",
":",
"return",
"self",
".",
"_tag",
"==",
"'member_transfer_account_contents'"
] | https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/team_log.py#L29609-L29615 | |
EmpireProject/EmPyre | c73854ed9d90d2bba1717d3fe6df758d18c20b8f | lib/common/agents.py | python | Agents.get_agent_ids | (self) | return results | Return all IDs of active agents from the database. | Return all IDs of active agents from the database. | [
"Return",
"all",
"IDs",
"of",
"active",
"agents",
"from",
"the",
"database",
"."
] | def get_agent_ids(self):
"""
Return all IDs of active agents from the database.
"""
cur = self.conn.cursor()
cur.execute("SELECT session_id FROM agents")
results = cur.fetchall()
cur.close()
# make sure names all ascii encoded
results = [r[0].encode('ascii', 'ignore') for r in results]
return results | [
"def",
"get_agent_ids",
"(",
"self",
")",
":",
"cur",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"cur",
".",
"execute",
"(",
"\"SELECT session_id FROM agents\"",
")",
"results",
"=",
"cur",
".",
"fetchall",
"(",
")",
"cur",
".",
"close",
"(",
"... | https://github.com/EmpireProject/EmPyre/blob/c73854ed9d90d2bba1717d3fe6df758d18c20b8f/lib/common/agents.py#L316-L327 | |
googleads/googleads-python-lib | b3b42a6deedbe6eaa1c9b30183a9eae3f9e9a7ee | examples/adwords/v201809/advanced_operations/add_dynamic_search_ads_campaign.py | python | _CreateCampaign | (client, budget) | return campaign_id | Creates the campaign.
Args:
client: an AdWordsClient instance.
budget: a zeep.objects.Budget representation of a created budget.
Returns:
An integer campaign ID. | Creates the campaign. | [
"Creates",
"the",
"campaign",
"."
] | def _CreateCampaign(client, budget):
"""Creates the campaign.
Args:
client: an AdWordsClient instance.
budget: a zeep.objects.Budget representation of a created budget.
Returns:
An integer campaign ID.
"""
campaign_service = client.GetService('CampaignService')
operations = [{
'operator': 'ADD',
'operand': {
'name': 'Interplanetary Cruise #%d' % uuid.uuid4(),
# Recommendation: Set the campaign to PAUSED when creating it to
# prevent the ads from immediately serving. Set to ENABLED once you've
# added targeting and the ads are ready to serve.
'status': 'PAUSED',
'advertisingChannelType': 'SEARCH',
'biddingStrategyConfiguration': {
'biddingStrategyType': 'MANUAL_CPC',
},
'budget': budget,
# Required: Set the campaign's Dynamic Search Ad settings.
'settings': [{
'xsi_type': 'DynamicSearchAdsSetting',
# Required: Set the domain name and language.
'domainName': 'example.com',
'languageCode': 'en'
}],
# Optional: Set the start date.
'startDate': (datetime.datetime.now() +
datetime.timedelta(1)).strftime('%Y%m%d'),
# Optional: Set the end date.
'endDate': (datetime.datetime.now() +
datetime.timedelta(365)).strftime('%Y%m%d'),
}
}]
campaign = campaign_service.mutate(operations)['value'][0]
campaign_id = campaign['id']
print('Campaign with ID "%d" and name "%s" was added.' % (
campaign_id, campaign['name']))
return campaign_id | [
"def",
"_CreateCampaign",
"(",
"client",
",",
"budget",
")",
":",
"campaign_service",
"=",
"client",
".",
"GetService",
"(",
"'CampaignService'",
")",
"operations",
"=",
"[",
"{",
"'operator'",
":",
"'ADD'",
",",
"'operand'",
":",
"{",
"'name'",
":",
"'Inter... | https://github.com/googleads/googleads-python-lib/blob/b3b42a6deedbe6eaa1c9b30183a9eae3f9e9a7ee/examples/adwords/v201809/advanced_operations/add_dynamic_search_ads_campaign.py#L74-L121 | |
nerdvegas/rez | d392c65bf63b4bca8106f938cec49144ba54e770 | src/rez/package_repository.py | python | PackageRepository.ignore_package | (self, pkg_name, pkg_version, allow_missing=False) | Ignore the given package.
Ignoring a package makes it invisible to further resolves.
Args:
pkg_name (str): Package name
pkg_version(`Version`): Package version
allow_missing (bool): if True, allow for ignoring a package that
does not exist. This is useful when you want to copy a package
to a repo and you don't want it visible until the copy is
completed.
Returns:
int:
* -1: Package not found
* 0: Nothing was done, package already ignored
* 1: Package was ignored | Ignore the given package. | [
"Ignore",
"the",
"given",
"package",
"."
] | def ignore_package(self, pkg_name, pkg_version, allow_missing=False):
"""Ignore the given package.
Ignoring a package makes it invisible to further resolves.
Args:
pkg_name (str): Package name
pkg_version(`Version`): Package version
allow_missing (bool): if True, allow for ignoring a package that
does not exist. This is useful when you want to copy a package
to a repo and you don't want it visible until the copy is
completed.
Returns:
int:
* -1: Package not found
* 0: Nothing was done, package already ignored
* 1: Package was ignored
"""
raise NotImplementedError | [
"def",
"ignore_package",
"(",
"self",
",",
"pkg_name",
",",
"pkg_version",
",",
"allow_missing",
"=",
"False",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/nerdvegas/rez/blob/d392c65bf63b4bca8106f938cec49144ba54e770/src/rez/package_repository.py#L232-L251 | ||
marinho/geraldo | 868ebdce67176d9b6205cddc92476f642c783fff | geraldo/base.py | python | GeraldoObject.find_by_type | (self, typ) | return found | Find child by informed type (and raises an exception if doesn't
find).
Attributes:
* typ - class type to find | Find child by informed type (and raises an exception if doesn't
find).
Attributes:
* typ - class type to find | [
"Find",
"child",
"by",
"informed",
"type",
"(",
"and",
"raises",
"an",
"exception",
"if",
"doesn",
"t",
"find",
")",
".",
"Attributes",
":",
"*",
"typ",
"-",
"class",
"type",
"to",
"find"
] | def find_by_type(self, typ):
"""Find child by informed type (and raises an exception if doesn't
find).
Attributes:
* typ - class type to find
"""
found = []
# Get object children
children = self.get_children()
for child in children:
# Child with the type it is searching for
if isinstance(child, typ):
found.append(child)
# Search on child's children
try:
ch_found = child.find_by_type(typ)
except ObjectNotFound:
ch_found = []
found.extend(ch_found)
# Cleans using a set
found = list(set(found))
return found | [
"def",
"find_by_type",
"(",
"self",
",",
"typ",
")",
":",
"found",
"=",
"[",
"]",
"# Get object children",
"children",
"=",
"self",
".",
"get_children",
"(",
")",
"for",
"child",
"in",
"children",
":",
"# Child with the type it is searching for",
"if",
"isinstan... | https://github.com/marinho/geraldo/blob/868ebdce67176d9b6205cddc92476f642c783fff/geraldo/base.py#L89-L118 | |
dgilland/cacheout | 8395e5028a5d3324d62d99d5349ba813d94d22e2 | src/cacheout/manager.py | python | CacheManager.configure | (self, name: t.Hashable, **options: t.Any) | Configure cache identified by `name`.
Note:
If no cache has been configured for `name`, then it will be created.
Args:
name: Cache name identifier.
**options: Cache options. | Configure cache identified by `name`. | [
"Configure",
"cache",
"identified",
"by",
"name",
"."
] | def configure(self, name: t.Hashable, **options: t.Any) -> None:
"""
Configure cache identified by `name`.
Note:
If no cache has been configured for `name`, then it will be created.
Args:
name: Cache name identifier.
**options: Cache options.
"""
try:
cache = self[name]
cache.configure(**options)
except KeyError:
self.register(name, self._create_cache(**options)) | [
"def",
"configure",
"(",
"self",
",",
"name",
":",
"t",
".",
"Hashable",
",",
"*",
"*",
"options",
":",
"t",
".",
"Any",
")",
"->",
"None",
":",
"try",
":",
"cache",
"=",
"self",
"[",
"name",
"]",
"cache",
".",
"configure",
"(",
"*",
"*",
"opti... | https://github.com/dgilland/cacheout/blob/8395e5028a5d3324d62d99d5349ba813d94d22e2/src/cacheout/manager.py#L83-L98 | ||
rigetti/pyquil | 36987ecb78d5dc85d299dd62395b7669a1cedd5a | pyquil/paulis.py | python | PauliTerm.__init__ | (
self,
op: str,
index: Optional[PauliTargetDesignator],
coefficient: ExpressionDesignator = 1.0,
) | Create a new Pauli Term with a Pauli operator at a particular index and a leading
coefficient.
:param op: The Pauli operator as a string "X", "Y", "Z", or "I"
:param index: The qubit index that that operator is applied to.
:param coefficient: The coefficient multiplying the operator, e.g. 1.5 * Z_1 | Create a new Pauli Term with a Pauli operator at a particular index and a leading
coefficient. | [
"Create",
"a",
"new",
"Pauli",
"Term",
"with",
"a",
"Pauli",
"operator",
"at",
"a",
"particular",
"index",
"and",
"a",
"leading",
"coefficient",
"."
] | def __init__(
self,
op: str,
index: Optional[PauliTargetDesignator],
coefficient: ExpressionDesignator = 1.0,
):
"""Create a new Pauli Term with a Pauli operator at a particular index and a leading
coefficient.
:param op: The Pauli operator as a string "X", "Y", "Z", or "I"
:param index: The qubit index that that operator is applied to.
:param coefficient: The coefficient multiplying the operator, e.g. 1.5 * Z_1
"""
if op not in PAULI_OPS:
raise ValueError(f"{op} is not a valid Pauli operator")
self._ops: Dict[PauliTargetDesignator, str] = OrderedDict()
if op != "I":
if not _valid_qubit(index):
raise ValueError(f"{index} is not a valid qubit")
assert index is not None
self._ops[index] = op
if isinstance(coefficient, Number):
self.coefficient: Union[complex, Expression] = complex(coefficient)
else:
self.coefficient = coefficient | [
"def",
"__init__",
"(",
"self",
",",
"op",
":",
"str",
",",
"index",
":",
"Optional",
"[",
"PauliTargetDesignator",
"]",
",",
"coefficient",
":",
"ExpressionDesignator",
"=",
"1.0",
",",
")",
":",
"if",
"op",
"not",
"in",
"PAULI_OPS",
":",
"raise",
"Valu... | https://github.com/rigetti/pyquil/blob/36987ecb78d5dc85d299dd62395b7669a1cedd5a/pyquil/paulis.py#L134-L160 | ||
omz/PythonistaAppTemplate | f560f93f8876d82a21d108977f90583df08d55af | PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/numpy/distutils/misc_util.py | python | njoin | (*path) | return minrelpath(joined) | Join two or more pathname components +
- convert a /-separated pathname to one using the OS's path separator.
- resolve `..` and `.` from path.
Either passing n arguments as in njoin('a','b'), or a sequence
of n names as in njoin(['a','b']) is handled, or a mixture of such arguments. | Join two or more pathname components +
- convert a /-separated pathname to one using the OS's path separator.
- resolve `..` and `.` from path. | [
"Join",
"two",
"or",
"more",
"pathname",
"components",
"+",
"-",
"convert",
"a",
"/",
"-",
"separated",
"pathname",
"to",
"one",
"using",
"the",
"OS",
"s",
"path",
"separator",
".",
"-",
"resolve",
"..",
"and",
".",
"from",
"path",
"."
] | def njoin(*path):
"""Join two or more pathname components +
- convert a /-separated pathname to one using the OS's path separator.
- resolve `..` and `.` from path.
Either passing n arguments as in njoin('a','b'), or a sequence
of n names as in njoin(['a','b']) is handled, or a mixture of such arguments.
"""
paths = []
for p in path:
if is_sequence(p):
# njoin(['a', 'b'], 'c')
paths.append(njoin(*p))
else:
assert is_string(p)
paths.append(p)
path = paths
if not path:
# njoin()
joined = ''
else:
# njoin('a', 'b')
joined = os.path.join(*path)
if os.path.sep != '/':
joined = joined.replace('/', os.path.sep)
return minrelpath(joined) | [
"def",
"njoin",
"(",
"*",
"path",
")",
":",
"paths",
"=",
"[",
"]",
"for",
"p",
"in",
"path",
":",
"if",
"is_sequence",
"(",
"p",
")",
":",
"# njoin(['a', 'b'], 'c')",
"paths",
".",
"append",
"(",
"njoin",
"(",
"*",
"p",
")",
")",
"else",
":",
"a... | https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/numpy/distutils/misc_util.py#L123-L148 | |
cmhungsteve/TA3N | 423ef3396d70d9d9261530d5b0c5589c4bc2fc15 | utils/utils.py | python | plot_confusion_matrix | (path, cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues) | This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`. | This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`. | [
"This",
"function",
"prints",
"and",
"plots",
"the",
"confusion",
"matrix",
".",
"Normalization",
"can",
"be",
"applied",
"by",
"setting",
"normalize",
"=",
"True",
"."
] | def plot_confusion_matrix(path, cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
num_classlabels = cm.sum(axis=1) # count the number of true labels for all the classes
np.putmask(num_classlabels, num_classlabels == 0, 1) # avoid zero division
if normalize:
cm = cm.astype('float') / num_classlabels[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
plt.figure(figsize=(13, 10))
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=90)
plt.yticks(tick_marks, classes)
factor = 100 if normalize else 1
fmt = '.0f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j]*factor, fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.savefig(path) | [
"def",
"plot_confusion_matrix",
"(",
"path",
",",
"cm",
",",
"classes",
",",
"normalize",
"=",
"False",
",",
"title",
"=",
"'Confusion matrix'",
",",
"cmap",
"=",
"plt",
".",
"cm",
".",
"Blues",
")",
":",
"num_classlabels",
"=",
"cm",
".",
"sum",
"(",
... | https://github.com/cmhungsteve/TA3N/blob/423ef3396d70d9d9261530d5b0c5589c4bc2fc15/utils/utils.py#L13-L50 | ||
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/states/boto_lambda.py | python | __virtual__ | () | return (False, "boto_lambda module could not be loaded") | Only load if boto is available. | Only load if boto is available. | [
"Only",
"load",
"if",
"boto",
"is",
"available",
"."
] | def __virtual__():
"""
Only load if boto is available.
"""
if "boto_lambda.function_exists" in __salt__:
return "boto_lambda"
return (False, "boto_lambda module could not be loaded") | [
"def",
"__virtual__",
"(",
")",
":",
"if",
"\"boto_lambda.function_exists\"",
"in",
"__salt__",
":",
"return",
"\"boto_lambda\"",
"return",
"(",
"False",
",",
"\"boto_lambda module could not be loaded\"",
")"
] | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/states/boto_lambda.py#L76-L82 | |
tensorflow/models | 6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3 | official/vision/beta/ops/augment.py | python | _clip_bbox | (min_y, min_x, max_y, max_x) | return min_y, min_x, max_y, max_x | Clip bounding box coordinates between 0 and 1.
Args:
min_y: Normalized bbox coordinate of type float between 0 and 1.
min_x: Normalized bbox coordinate of type float between 0 and 1.
max_y: Normalized bbox coordinate of type float between 0 and 1.
max_x: Normalized bbox coordinate of type float between 0 and 1.
Returns:
Clipped coordinate values between 0 and 1. | Clip bounding box coordinates between 0 and 1. | [
"Clip",
"bounding",
"box",
"coordinates",
"between",
"0",
"and",
"1",
"."
] | def _clip_bbox(min_y, min_x, max_y, max_x):
"""Clip bounding box coordinates between 0 and 1.
Args:
min_y: Normalized bbox coordinate of type float between 0 and 1.
min_x: Normalized bbox coordinate of type float between 0 and 1.
max_y: Normalized bbox coordinate of type float between 0 and 1.
max_x: Normalized bbox coordinate of type float between 0 and 1.
Returns:
Clipped coordinate values between 0 and 1.
"""
min_y = tf.clip_by_value(min_y, 0.0, 1.0)
min_x = tf.clip_by_value(min_x, 0.0, 1.0)
max_y = tf.clip_by_value(max_y, 0.0, 1.0)
max_x = tf.clip_by_value(max_x, 0.0, 1.0)
return min_y, min_x, max_y, max_x | [
"def",
"_clip_bbox",
"(",
"min_y",
",",
"min_x",
",",
"max_y",
",",
"max_x",
")",
":",
"min_y",
"=",
"tf",
".",
"clip_by_value",
"(",
"min_y",
",",
"0.0",
",",
"1.0",
")",
"min_x",
"=",
"tf",
".",
"clip_by_value",
"(",
"min_x",
",",
"0.0",
",",
"1.... | https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/official/vision/beta/ops/augment.py#L945-L961 | |
fortharris/Pcode | 147962d160a834c219e12cb456abc130826468e4 | Extensions/EditorWindow/EditorWindow.py | python | EditorWindow.saveUiState | (self) | [] | def saveUiState(self):
name = self.projectPathDict["root"]
settings = QtCore.QSettings("Clean Code Inc.", "Pcode")
settings.beginGroup(name)
settings.setValue('hsplitter', self.hSplitter.saveState())
settings.setValue('vsplitter', self.vSplitter.saveState())
settings.setValue('sidesplitter', self.sideSplitter.saveState())
settings.setValue('writepad', self.writePad.geometry())
settings.endGroup() | [
"def",
"saveUiState",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"projectPathDict",
"[",
"\"root\"",
"]",
"settings",
"=",
"QtCore",
".",
"QSettings",
"(",
"\"Clean Code Inc.\"",
",",
"\"Pcode\"",
")",
"settings",
".",
"beginGroup",
"(",
"name",
")",
... | https://github.com/fortharris/Pcode/blob/147962d160a834c219e12cb456abc130826468e4/Extensions/EditorWindow/EditorWindow.py#L663-L671 | ||||
inkandswitch/livebook | 93c8d467734787366ad084fc3566bf5cbe249c51 | public/pypyjs/modules/decimal.py | python | Decimal.copy_sign | (self, other) | return _dec_from_triple(other._sign, self._int,
self._exp, self._is_special) | Returns self with the sign of other. | Returns self with the sign of other. | [
"Returns",
"self",
"with",
"the",
"sign",
"of",
"other",
"."
] | def copy_sign(self, other):
"""Returns self with the sign of other."""
other = _convert_other(other, raiseit=True)
return _dec_from_triple(other._sign, self._int,
self._exp, self._is_special) | [
"def",
"copy_sign",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"_convert_other",
"(",
"other",
",",
"raiseit",
"=",
"True",
")",
"return",
"_dec_from_triple",
"(",
"other",
".",
"_sign",
",",
"self",
".",
"_int",
",",
"self",
".",
"_exp",
",",
... | https://github.com/inkandswitch/livebook/blob/93c8d467734787366ad084fc3566bf5cbe249c51/public/pypyjs/modules/decimal.py#L2925-L2929 | |
DeepPavlov/convai | 54d921f99606960941ece4865a396925dfc264f4 | 2017/solutions/kaib/ParlAI/parlai/agents/seq2seq_v2/beam.py | python | Beam.__init__ | (self, size, vocab, cuda=False) | Initialize params. | Initialize params. | [
"Initialize",
"params",
"."
] | def __init__(self, size, vocab, cuda=False):
"""Initialize params."""
## vocab = self.dict.tok2ind
self.size = size
self.done = False
self.pad = vocab['__NULL__']
self.bos = vocab['__START__']
self.eos = vocab['__END__']
self.unk = vocab['__UNK__']
self.tt = torch.cuda if cuda else torch
# The score for each translation on the beam.
self.scores = self.tt.FloatTensor(size).zero_()
self.score_mask = self.tt.FloatTensor(size).fill_(1)
# The backpointers at each time-step.
self.prevKs = []
# The outputs at each time-step.
self.nextYs = [self.tt.LongTensor(size).fill_(self.pad)]
self.nextYs[0][0] = self.bos
# The attentions (matrix) for each time.
self.attn = []
# The 'done' for each translation on the beam.
self.doneYs = [False]*size
self.active_idx_list = list(range(self.size))
self.active_idx = self.tt.LongTensor(self.active_idx_list)
# Generating unk token or not
self.gen_unk = False | [
"def",
"__init__",
"(",
"self",
",",
"size",
",",
"vocab",
",",
"cuda",
"=",
"False",
")",
":",
"## vocab = self.dict.tok2ind",
"self",
".",
"size",
"=",
"size",
"self",
".",
"done",
"=",
"False",
"self",
".",
"pad",
"=",
"vocab",
"[",
"'__NULL__'",
"]... | https://github.com/DeepPavlov/convai/blob/54d921f99606960941ece4865a396925dfc264f4/2017/solutions/kaib/ParlAI/parlai/agents/seq2seq_v2/beam.py#L26-L58 | ||
lebigot/uncertainties | 210d6d9a4ffe174a92b9f5fa230ca9b8dca58000 | uncertainties/core.py | python | ge_on_aff_funcs | (self, y_with_uncert) | return (gt_on_aff_funcs(self, y_with_uncert)
or eq_on_aff_funcs(self, y_with_uncert)) | __ge__ operator, assuming that both self and y_with_uncert are
AffineScalarFunc objects. | __ge__ operator, assuming that both self and y_with_uncert are
AffineScalarFunc objects. | [
"__ge__",
"operator",
"assuming",
"that",
"both",
"self",
"and",
"y_with_uncert",
"are",
"AffineScalarFunc",
"objects",
"."
] | def ge_on_aff_funcs(self, y_with_uncert):
"""
__ge__ operator, assuming that both self and y_with_uncert are
AffineScalarFunc objects.
"""
return (gt_on_aff_funcs(self, y_with_uncert)
or eq_on_aff_funcs(self, y_with_uncert)) | [
"def",
"ge_on_aff_funcs",
"(",
"self",
",",
"y_with_uncert",
")",
":",
"return",
"(",
"gt_on_aff_funcs",
"(",
"self",
",",
"y_with_uncert",
")",
"or",
"eq_on_aff_funcs",
"(",
"self",
",",
"y_with_uncert",
")",
")"
] | https://github.com/lebigot/uncertainties/blob/210d6d9a4ffe174a92b9f5fa230ca9b8dca58000/uncertainties/core.py#L848-L855 | |
phimpme/phimpme-generator | ba6d11190b9016238f27672e1ad55e6a875b74a0 | Phimpme/site-packages/coverage/control.py | python | coverage.use_cache | (self, usecache) | Control the use of a data file (incorrectly called a cache).
`usecache` is true or false, whether to read and write data on disk. | Control the use of a data file (incorrectly called a cache). | [
"Control",
"the",
"use",
"of",
"a",
"data",
"file",
"(",
"incorrectly",
"called",
"a",
"cache",
")",
"."
] | def use_cache(self, usecache):
"""Control the use of a data file (incorrectly called a cache).
`usecache` is true or false, whether to read and write data on disk.
"""
self.data.usefile(usecache) | [
"def",
"use_cache",
"(",
"self",
",",
"usecache",
")",
":",
"self",
".",
"data",
".",
"usefile",
"(",
"usecache",
")"
] | https://github.com/phimpme/phimpme-generator/blob/ba6d11190b9016238f27672e1ad55e6a875b74a0/Phimpme/site-packages/coverage/control.py#L350-L356 | ||
yiranran/Audio-driven-TalkingFace-HeadPose | d062a00a46a5d0ebb4bf66751e7a9af92ee418e8 | render-to-video/models/memory_seq_model.py | python | MemorySeqModel.backward_mem | (self) | [] | def backward_mem(self):
#print(self.image_paths)
resnet_feature = self.netmem(self.resnet_input)
self.loss_mem = self.netmem.unsupervised_loss(resnet_feature, self.real_B_feat, self.opt.iden_thres)
self.loss_mem.backward() | [
"def",
"backward_mem",
"(",
"self",
")",
":",
"#print(self.image_paths)",
"resnet_feature",
"=",
"self",
".",
"netmem",
"(",
"self",
".",
"resnet_input",
")",
"self",
".",
"loss_mem",
"=",
"self",
".",
"netmem",
".",
"unsupervised_loss",
"(",
"resnet_feature",
... | https://github.com/yiranran/Audio-driven-TalkingFace-HeadPose/blob/d062a00a46a5d0ebb4bf66751e7a9af92ee418e8/render-to-video/models/memory_seq_model.py#L126-L130 | ||||
behave/behave | e6364fe3d62c2befe34bc56471cfb317a218cd01 | behave/__main__.py | python | run_behave | (config, runner_class=None) | return return_code | Run behave with configuration (and optional runner class).
:param config: Configuration object for behave.
:param runner_class: Runner class to use or none (use Runner class).
:return: 0, if successful. Non-zero on failure.
.. note:: BEST EFFORT, not intended for multi-threaded usage. | Run behave with configuration (and optional runner class). | [
"Run",
"behave",
"with",
"configuration",
"(",
"and",
"optional",
"runner",
"class",
")",
"."
] | def run_behave(config, runner_class=None):
"""Run behave with configuration (and optional runner class).
:param config: Configuration object for behave.
:param runner_class: Runner class to use or none (use Runner class).
:return: 0, if successful. Non-zero on failure.
.. note:: BEST EFFORT, not intended for multi-threaded usage.
"""
# pylint: disable=too-many-branches, too-many-statements, too-many-return-statements
if runner_class is None:
runner_class = Runner
if config.version:
print("behave " + BEHAVE_VERSION)
return 0
if config.tags_help:
print(TAG_HELP)
return 0
if config.lang_list:
print_language_list()
return 0
if config.lang_help:
print_language_help(config)
return 0
if not config.format:
config.format = [config.default_format]
elif config.format and "format" in config.defaults:
# -- CASE: Formatter are specified in behave configuration file.
# Check if formatter are provided on command-line, too.
if len(config.format) == len(config.defaults["format"]):
# -- NO FORMATTER on command-line: Add default formatter.
config.format.append(config.default_format)
if "help" in config.format:
print_formatters("Available formatters:")
return 0
if len(config.outputs) > len(config.format):
print("CONFIG-ERROR: More outfiles (%d) than formatters (%d)." % \
(len(config.outputs), len(config.format)))
return 1
# -- MAIN PART:
failed = True
try:
reset_runtime()
runner = runner_class(config)
failed = runner.run()
except ParserError as e:
print(u"ParserError: %s" % e)
except ConfigError as e:
print(u"ConfigError: %s" % e)
except FileNotFoundError as e:
print(u"FileNotFoundError: %s" % e)
except InvalidFileLocationError as e:
print(u"InvalidFileLocationError: %s" % e)
except InvalidFilenameError as e:
print(u"InvalidFilenameError: %s" % e)
except ConstraintError as e:
print(u"ConstraintError: %s" % e)
except Exception as e:
# -- DIAGNOSTICS:
text = _text(e)
print(u"Exception %s: %s" % (e.__class__.__name__, text))
raise
if config.show_snippets and runner.undefined_steps:
print_undefined_step_snippets(runner.undefined_steps,
colored=config.color)
return_code = 0
if failed:
return_code = 1
return return_code | [
"def",
"run_behave",
"(",
"config",
",",
"runner_class",
"=",
"None",
")",
":",
"# pylint: disable=too-many-branches, too-many-statements, too-many-return-statements",
"if",
"runner_class",
"is",
"None",
":",
"runner_class",
"=",
"Runner",
"if",
"config",
".",
"version",
... | https://github.com/behave/behave/blob/e6364fe3d62c2befe34bc56471cfb317a218cd01/behave/__main__.py#L52-L129 | |
saleor/saleor | 2221bdf61b037c660ffc2d1efa484d8efe8172f5 | saleor/graphql/product/bulk_mutations/products.py | python | ProductVariantBulkCreate.add_indexes_to_errors | (cls, index, error, error_dict) | Append errors with index in params to mutation error dict. | Append errors with index in params to mutation error dict. | [
"Append",
"errors",
"with",
"index",
"in",
"params",
"to",
"mutation",
"error",
"dict",
"."
] | def add_indexes_to_errors(cls, index, error, error_dict):
"""Append errors with index in params to mutation error dict."""
for key, value in error.error_dict.items():
for e in value:
if e.params:
e.params["index"] = index
else:
e.params = {"index": index}
error_dict[key].extend(value) | [
"def",
"add_indexes_to_errors",
"(",
"cls",
",",
"index",
",",
"error",
",",
"error_dict",
")",
":",
"for",
"key",
",",
"value",
"in",
"error",
".",
"error_dict",
".",
"items",
"(",
")",
":",
"for",
"e",
"in",
"value",
":",
"if",
"e",
".",
"params",
... | https://github.com/saleor/saleor/blob/2221bdf61b037c660ffc2d1efa484d8efe8172f5/saleor/graphql/product/bulk_mutations/products.py#L377-L385 | ||
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/modular/modform_hecketriangle/abstract_ring.py | python | FormsRing_abstract.E4 | (self) | r"""
Return the normalized Eisenstein series of weight `4`.
It lies in a (holomorphic) extension of the graded ring of ``self``.
In case ``has_reduce_hom`` is ``True`` it is given as an element of
the corresponding space of homogeneous elements.
It is equal to ``f_rho^(n-2)``.
NOTE:
If ``n=infinity`` the situation is different, there we have:
``f_rho=1`` (since that's the limit as ``n`` goes to infinity)
and the polynomial variable ``x`` refers to ``E4`` instead of
``f_rho``. In that case ``E4`` has exactly one simple zero
at the cusp ``-1``. Also note that ``E4`` is the limit of ``f_rho^n``.
EXAMPLES::
sage: from sage.modular.modform_hecketriangle.graded_ring import QuasiMeromorphicModularFormsRing, ModularFormsRing, CuspFormsRing
sage: MR = ModularFormsRing(n=7)
sage: E4 = MR.E4()
sage: E4 in MR
True
sage: CuspFormsRing(n=7).E4() == E4
True
sage: E4
f_rho^5
sage: QuasiMeromorphicModularFormsRing(n=7).E4() == QuasiMeromorphicModularFormsRing(n=7)(E4)
True
sage: from sage.modular.modform_hecketriangle.space import ModularForms, CuspForms
sage: MF = ModularForms(n=5, k=4)
sage: E4 = MF.E4()
sage: E4 in MF
True
sage: ModularFormsRing(n=5, red_hom=True).E4() == E4
True
sage: CuspForms(n=5, k=12).E4() == E4
True
sage: MF.disp_prec(3)
sage: E4
1 + 21/(100*d)*q + 483/(32000*d^2)*q^2 + O(q^3)
sage: from sage.modular.modform_hecketriangle.series_constructor import MFSeriesConstructor as MFC
sage: MF = ModularForms(n=5)
sage: d = MF.get_d()
sage: q = MF.get_q()
sage: ModularForms(n=5, k=4).E4().q_expansion(prec=5) == MFC(group=5, prec=7).E4_ZZ()(q/d).add_bigoh(5)
True
sage: ModularForms(n=infinity, k=4).E4().q_expansion(prec=5) == MFC(group=infinity, prec=7).E4_ZZ()(q/d).add_bigoh(5)
True
sage: ModularForms(n=5, k=4).E4().q_expansion(fix_d=1, prec=5) == MFC(group=5, prec=7).E4_ZZ().add_bigoh(5)
True
sage: ModularForms(n=infinity, k=4).E4().q_expansion(fix_d=1, prec=5) == MFC(group=infinity, prec=7).E4_ZZ().add_bigoh(5)
True
sage: ModularForms(n=infinity, k=4).E4()
1 + 16*q + 112*q^2 + 448*q^3 + 1136*q^4 + O(q^5)
sage: ModularForms(k=4).f_rho() == ModularForms(k=4).E4()
True
sage: ModularForms(k=4).E4()
1 + 240*q + 2160*q^2 + 6720*q^3 + 17520*q^4 + O(q^5) | r"""
Return the normalized Eisenstein series of weight `4`. | [
"r",
"Return",
"the",
"normalized",
"Eisenstein",
"series",
"of",
"weight",
"4",
"."
] | def E4(self):
r"""
Return the normalized Eisenstein series of weight `4`.
It lies in a (holomorphic) extension of the graded ring of ``self``.
In case ``has_reduce_hom`` is ``True`` it is given as an element of
the corresponding space of homogeneous elements.
It is equal to ``f_rho^(n-2)``.
NOTE:
If ``n=infinity`` the situation is different, there we have:
``f_rho=1`` (since that's the limit as ``n`` goes to infinity)
and the polynomial variable ``x`` refers to ``E4`` instead of
``f_rho``. In that case ``E4`` has exactly one simple zero
at the cusp ``-1``. Also note that ``E4`` is the limit of ``f_rho^n``.
EXAMPLES::
sage: from sage.modular.modform_hecketriangle.graded_ring import QuasiMeromorphicModularFormsRing, ModularFormsRing, CuspFormsRing
sage: MR = ModularFormsRing(n=7)
sage: E4 = MR.E4()
sage: E4 in MR
True
sage: CuspFormsRing(n=7).E4() == E4
True
sage: E4
f_rho^5
sage: QuasiMeromorphicModularFormsRing(n=7).E4() == QuasiMeromorphicModularFormsRing(n=7)(E4)
True
sage: from sage.modular.modform_hecketriangle.space import ModularForms, CuspForms
sage: MF = ModularForms(n=5, k=4)
sage: E4 = MF.E4()
sage: E4 in MF
True
sage: ModularFormsRing(n=5, red_hom=True).E4() == E4
True
sage: CuspForms(n=5, k=12).E4() == E4
True
sage: MF.disp_prec(3)
sage: E4
1 + 21/(100*d)*q + 483/(32000*d^2)*q^2 + O(q^3)
sage: from sage.modular.modform_hecketriangle.series_constructor import MFSeriesConstructor as MFC
sage: MF = ModularForms(n=5)
sage: d = MF.get_d()
sage: q = MF.get_q()
sage: ModularForms(n=5, k=4).E4().q_expansion(prec=5) == MFC(group=5, prec=7).E4_ZZ()(q/d).add_bigoh(5)
True
sage: ModularForms(n=infinity, k=4).E4().q_expansion(prec=5) == MFC(group=infinity, prec=7).E4_ZZ()(q/d).add_bigoh(5)
True
sage: ModularForms(n=5, k=4).E4().q_expansion(fix_d=1, prec=5) == MFC(group=5, prec=7).E4_ZZ().add_bigoh(5)
True
sage: ModularForms(n=infinity, k=4).E4().q_expansion(fix_d=1, prec=5) == MFC(group=infinity, prec=7).E4_ZZ().add_bigoh(5)
True
sage: ModularForms(n=infinity, k=4).E4()
1 + 16*q + 112*q^2 + 448*q^3 + 1136*q^4 + O(q^5)
sage: ModularForms(k=4).f_rho() == ModularForms(k=4).E4()
True
sage: ModularForms(k=4).E4()
1 + 240*q + 2160*q^2 + 6720*q^3 + 17520*q^4 + O(q^5)
"""
(x,y,z,d) = self._pol_ring.gens()
if (self.hecke_n() == infinity):
return self.extend_type("holo", ring=True)(x).reduce()
else:
return self.extend_type("holo", ring=True)(x**(self._group.n()-2)).reduce() | [
"def",
"E4",
"(",
"self",
")",
":",
"(",
"x",
",",
"y",
",",
"z",
",",
"d",
")",
"=",
"self",
".",
"_pol_ring",
".",
"gens",
"(",
")",
"if",
"(",
"self",
".",
"hecke_n",
"(",
")",
"==",
"infinity",
")",
":",
"return",
"self",
".",
"extend_typ... | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/modular/modform_hecketriangle/abstract_ring.py#L1530-L1602 | ||
B16f00t/whapa | b843f1d3fd15578025dcca21d5f1cf094e2978bf | whapa-gui.py | python | Whapa.on_focusout_out_whachat | (self, event) | Function that's called every time the focus is lost | Function that's called every time the focus is lost | [
"Function",
"that",
"s",
"called",
"every",
"time",
"the",
"focus",
"is",
"lost"
] | def on_focusout_out_whachat(self, event):
"""Function that's called every time the focus is lost"""
if self.entry_whachat_te.get() == '':
self.entry_whachat_te.insert(0, "dd-mm-yyyy HH:MM")
self.entry_whachat_te.config(fg='grey') | [
"def",
"on_focusout_out_whachat",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"entry_whachat_te",
".",
"get",
"(",
")",
"==",
"''",
":",
"self",
".",
"entry_whachat_te",
".",
"insert",
"(",
"0",
",",
"\"dd-mm-yyyy HH:MM\"",
")",
"self",
".",
... | https://github.com/B16f00t/whapa/blob/b843f1d3fd15578025dcca21d5f1cf094e2978bf/whapa-gui.py#L743-L747 | ||
ShivamSarodia/ShivyC | e7d72eff237e1ef49ec70333497348baf86be425 | shivyc/lexer.py | python | match_number_string | (token_repr) | return token_str if token_str.isdigit() else None | Return a string that represents the given constant number.
token_repr - List of Tagged characters.
returns (str, or None) - String representation of the number. | Return a string that represents the given constant number. | [
"Return",
"a",
"string",
"that",
"represents",
"the",
"given",
"constant",
"number",
"."
] | def match_number_string(token_repr):
"""Return a string that represents the given constant number.
token_repr - List of Tagged characters.
returns (str, or None) - String representation of the number.
"""
token_str = chunk_to_str(token_repr)
return token_str if token_str.isdigit() else None | [
"def",
"match_number_string",
"(",
"token_repr",
")",
":",
"token_str",
"=",
"chunk_to_str",
"(",
"token_repr",
")",
"return",
"token_str",
"if",
"token_str",
".",
"isdigit",
"(",
")",
"else",
"None"
] | https://github.com/ShivamSarodia/ShivyC/blob/e7d72eff237e1ef49ec70333497348baf86be425/shivyc/lexer.py#L439-L447 | |
makehumancommunity/makehuman | 8006cf2cc851624619485658bb933a4244bbfd7c | makehuman/shared/animation.py | python | VertexBoneWeights.__init__ | (self, data, vertexCount=None, rootBone="root") | Note: specifiying vertexCount is just for speeding up loading, if not
specified, vertexCount will be calculated automatically (taking a little
longer to load). | Note: specifiying vertexCount is just for speeding up loading, if not
specified, vertexCount will be calculated automatically (taking a little
longer to load). | [
"Note",
":",
"specifiying",
"vertexCount",
"is",
"just",
"for",
"speeding",
"up",
"loading",
"if",
"not",
"specified",
"vertexCount",
"will",
"be",
"calculated",
"automatically",
"(",
"taking",
"a",
"little",
"longer",
"to",
"load",
")",
"."
] | def __init__(self, data, vertexCount=None, rootBone="root"):
"""
Note: specifiying vertexCount is just for speeding up loading, if not
specified, vertexCount will be calculated automatically (taking a little
longer to load).
"""
self._vertexCount = None # The number of vertices that are mapped
self._wCounts = None # Per vertex, the number of weights attached
self._nWeights = None # The maximum number of weights per vertex
self.rootBone = rootBone
self._data = self._build_vertex_weights_data(data, vertexCount, rootBone)
self._calculate_num_weights()
self._compiled = {}
self.name = ""
self.version = ""
self.license = makehuman.getAssetLicense()
self.description = "" | [
"def",
"__init__",
"(",
"self",
",",
"data",
",",
"vertexCount",
"=",
"None",
",",
"rootBone",
"=",
"\"root\"",
")",
":",
"self",
".",
"_vertexCount",
"=",
"None",
"# The number of vertices that are mapped",
"self",
".",
"_wCounts",
"=",
"None",
"# Per vertex, t... | https://github.com/makehumancommunity/makehuman/blob/8006cf2cc851624619485658bb933a4244bbfd7c/makehuman/shared/animation.py#L498-L518 | ||
open-cogsci/OpenSesame | c4a3641b097a80a76937edbd8c365f036bcc9705 | libqtopensesame/items/experiment.py | python | experiment.notify | (self, msg, title=None, icon=None) | Presents a default notification dialog.
Arguments:
msg -- The message to be shown.
Keyword arguments:
title -- A title message or None for default title. (default=None)
icon -- A custom icon or None for default icon. (default=None) | Presents a default notification dialog. | [
"Presents",
"a",
"default",
"notification",
"dialog",
"."
] | def notify(self, msg, title=None, icon=None):
"""
Presents a default notification dialog.
Arguments:
msg -- The message to be shown.
Keyword arguments:
title -- A title message or None for default title. (default=None)
icon -- A custom icon or None for default icon. (default=None)
"""
from libqtopensesame.dialogs.notification import notification
nd = notification(self.main_window, msg=safe_decode(msg), title=title,
icon=icon)
nd.show() | [
"def",
"notify",
"(",
"self",
",",
"msg",
",",
"title",
"=",
"None",
",",
"icon",
"=",
"None",
")",
":",
"from",
"libqtopensesame",
".",
"dialogs",
".",
"notification",
"import",
"notification",
"nd",
"=",
"notification",
"(",
"self",
".",
"main_window",
... | https://github.com/open-cogsci/OpenSesame/blob/c4a3641b097a80a76937edbd8c365f036bcc9705/libqtopensesame/items/experiment.py#L211-L227 | ||
TencentCloud/tencentcloud-sdk-python | 3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2 | tencentcloud/cdn/v20180606/models.py | python | ScdnAclConfig.__init__ | (self) | r"""
:param Switch: 是否开启,on | off
:type Switch: str
:param ScriptData: 新版本请使用AdvancedScriptData
注意:此字段可能返回 null,表示取不到有效值。
:type ScriptData: list of ScdnAclGroup
:param ErrorPage: 错误页面配置
注意:此字段可能返回 null,表示取不到有效值。
:type ErrorPage: :class:`tencentcloud.cdn.v20180606.models.ScdnErrorPage`
:param AdvancedScriptData: Acl规则组,switch为on时必填
注意:此字段可能返回 null,表示取不到有效值。
:type AdvancedScriptData: list of AdvancedScdnAclGroup | r"""
:param Switch: 是否开启,on | off
:type Switch: str
:param ScriptData: 新版本请使用AdvancedScriptData
注意:此字段可能返回 null,表示取不到有效值。
:type ScriptData: list of ScdnAclGroup
:param ErrorPage: 错误页面配置
注意:此字段可能返回 null,表示取不到有效值。
:type ErrorPage: :class:`tencentcloud.cdn.v20180606.models.ScdnErrorPage`
:param AdvancedScriptData: Acl规则组,switch为on时必填
注意:此字段可能返回 null,表示取不到有效值。
:type AdvancedScriptData: list of AdvancedScdnAclGroup | [
"r",
":",
"param",
"Switch",
":",
"是否开启,on",
"|",
"off",
":",
"type",
"Switch",
":",
"str",
":",
"param",
"ScriptData",
":",
"新版本请使用AdvancedScriptData",
"注意:此字段可能返回",
"null,表示取不到有效值。",
":",
"type",
"ScriptData",
":",
"list",
"of",
"ScdnAclGroup",
":",
"param",... | def __init__(self):
r"""
:param Switch: 是否开启,on | off
:type Switch: str
:param ScriptData: 新版本请使用AdvancedScriptData
注意:此字段可能返回 null,表示取不到有效值。
:type ScriptData: list of ScdnAclGroup
:param ErrorPage: 错误页面配置
注意:此字段可能返回 null,表示取不到有效值。
:type ErrorPage: :class:`tencentcloud.cdn.v20180606.models.ScdnErrorPage`
:param AdvancedScriptData: Acl规则组,switch为on时必填
注意:此字段可能返回 null,表示取不到有效值。
:type AdvancedScriptData: list of AdvancedScdnAclGroup
"""
self.Switch = None
self.ScriptData = None
self.ErrorPage = None
self.AdvancedScriptData = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"Switch",
"=",
"None",
"self",
".",
"ScriptData",
"=",
"None",
"self",
".",
"ErrorPage",
"=",
"None",
"self",
".",
"AdvancedScriptData",
"=",
"None"
] | https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cdn/v20180606/models.py#L11806-L11823 | ||
chadmv/cmt | 1b1a9a4fb154d1d10e73373cf899e4d83c95a6a1 | scripts/cmt/dge.py | python | DGParser.max | (self, x, y) | return self.condition(x, y, self.conditionals.index(">="), x, y) | [] | def max(self, x, y):
return self.condition(x, y, self.conditionals.index(">="), x, y) | [
"def",
"max",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"return",
"self",
".",
"condition",
"(",
"x",
",",
"y",
",",
"self",
".",
"conditionals",
".",
"index",
"(",
"\">=\"",
")",
",",
"x",
",",
"y",
")"
] | https://github.com/chadmv/cmt/blob/1b1a9a4fb154d1d10e73373cf899e4d83c95a6a1/scripts/cmt/dge.py#L594-L595 | |||
libertysoft3/saidit | 271c7d03adb369f82921d811360b00812e42da24 | r2/r2/controllers/front.py | python | FrontController.GET_spamlisting | (self, location, only, num, after, reverse, count,
timeout) | return EditReddit(content=panes,
location=location,
nav_menus=menus,
extension_handling=extension_handling).render() | Return a listing of posts relevant to moderators.
* reports: Things that have been reported.
* spam: Things that have been marked as spam or otherwise removed.
* modqueue: Things requiring moderator review, such as reported things
and items caught by the spam filter.
* unmoderated: Things that have yet to be approved/removed by a mod.
* edited: Things that have been edited recently.
Requires the "posts" moderator permission for the subreddit. | Return a listing of posts relevant to moderators. | [
"Return",
"a",
"listing",
"of",
"posts",
"relevant",
"to",
"moderators",
"."
] | def GET_spamlisting(self, location, only, num, after, reverse, count,
timeout):
"""Return a listing of posts relevant to moderators.
* reports: Things that have been reported.
* spam: Things that have been marked as spam or otherwise removed.
* modqueue: Things requiring moderator review, such as reported things
and items caught by the spam filter.
* unmoderated: Things that have yet to be approved/removed by a mod.
* edited: Things that have been edited recently.
Requires the "posts" moderator permission for the subreddit.
"""
c.allow_styles = True
c.profilepage = True
panes = PaneStack()
# We clone and modify this when a user clicks 'reply' on a comment.
replyBox = UserText(item=None, display=False, cloneable=True,
creating=True, post_form='comment')
panes.append(replyBox)
spamlisting = self._make_spamlisting(location, only, num, after,
reverse, count)
panes.append(spamlisting)
extension_handling = "private" if c.user.pref_private_feeds else False
if location in ('reports', 'spam', 'modqueue', 'edited'):
buttons = [
QueryButton(_('posts and comments'), None, query_param='only'),
QueryButton(_('posts'), 'links', query_param='only'),
QueryButton(_('comments'), 'comments', query_param='only'),
]
menus = [NavMenu(buttons, base_path=request.path, title=_('show'),
type='lightdrop')]
else:
menus = None
return EditReddit(content=panes,
location=location,
nav_menus=menus,
extension_handling=extension_handling).render() | [
"def",
"GET_spamlisting",
"(",
"self",
",",
"location",
",",
"only",
",",
"num",
",",
"after",
",",
"reverse",
",",
"count",
",",
"timeout",
")",
":",
"c",
".",
"allow_styles",
"=",
"True",
"c",
".",
"profilepage",
"=",
"True",
"panes",
"=",
"PaneStack... | https://github.com/libertysoft3/saidit/blob/271c7d03adb369f82921d811360b00812e42da24/r2/r2/controllers/front.py#L853-L895 | |
bwohlberg/sporco | df67462abcf83af6ab1961bcb0d51b87a66483fa | sporco/admm/tvl1.py | python | TVL1Denoise.xstep | (self) | r"""Minimise Augmented Lagrangian with respect to
:math:`\mathbf{x}`. | r"""Minimise Augmented Lagrangian with respect to
:math:`\mathbf{x}`. | [
"r",
"Minimise",
"Augmented",
"Lagrangian",
"with",
"respect",
"to",
":",
"math",
":",
"\\",
"mathbf",
"{",
"x",
"}",
"."
] | def xstep(self):
r"""Minimise Augmented Lagrangian with respect to
:math:`\mathbf{x}`.
"""
ngsit = 0
gsrrs = np.inf
YU = self.Y - self.U
SYU = self.S + YU[..., -1]
YU[..., -1] = 0.0
ATYU = self.cnst_AT(YU)
while gsrrs > self.opt['GSTol'] and ngsit < self.opt['MaxGSIter']:
self.X = self.GaussSeidelStep(
SYU, self.X, ATYU, 1.0, self.lcw, 1.0)
gsrrs = rrs(
self.cnst_AT(self.cnst_A(self.X)),
self.cnst_AT(self.cnst_c() - self.cnst_B(self.Y) - self.U)
)
ngsit += 1
self.xs = (ngsit, gsrrs) | [
"def",
"xstep",
"(",
"self",
")",
":",
"ngsit",
"=",
"0",
"gsrrs",
"=",
"np",
".",
"inf",
"YU",
"=",
"self",
".",
"Y",
"-",
"self",
".",
"U",
"SYU",
"=",
"self",
".",
"S",
"+",
"YU",
"[",
"...",
",",
"-",
"1",
"]",
"YU",
"[",
"...",
",",
... | https://github.com/bwohlberg/sporco/blob/df67462abcf83af6ab1961bcb0d51b87a66483fa/sporco/admm/tvl1.py#L240-L260 | ||
PaddlePaddle/PaddleSeg | 8a9196177c9e4b0187f90cbc6a6bc38a652eba73 | contrib/Matting/utils.py | python | get_image_list | (image_path) | return image_list, image_dir | Get image list | Get image list | [
"Get",
"image",
"list"
] | def get_image_list(image_path):
"""Get image list"""
valid_suffix = [
'.JPEG', '.jpeg', '.JPG', '.jpg', '.BMP', '.bmp', '.PNG', '.png'
]
image_list = []
image_dir = None
if os.path.isfile(image_path):
if os.path.splitext(image_path)[-1] in valid_suffix:
image_list.append(image_path)
else:
image_dir = os.path.dirname(image_path)
with open(image_path, 'r') as f:
for line in f:
line = line.strip()
if len(line.split()) > 1:
raise RuntimeError(
'There should be only one image path per line in `image_path` file. Wrong line: {}'
.format(line))
image_list.append(os.path.join(image_dir, line))
elif os.path.isdir(image_path):
image_dir = image_path
for root, dirs, files in os.walk(image_path):
for f in files:
if '.ipynb_checkpoints' in root:
continue
if os.path.splitext(f)[-1] in valid_suffix:
image_list.append(os.path.join(root, f))
image_list.sort()
else:
raise FileNotFoundError(
'`image_path` is not found. it should be an image file or a directory including images'
)
if len(image_list) == 0:
raise RuntimeError('There are not image file in `image_path`')
return image_list, image_dir | [
"def",
"get_image_list",
"(",
"image_path",
")",
":",
"valid_suffix",
"=",
"[",
"'.JPEG'",
",",
"'.jpeg'",
",",
"'.JPG'",
",",
"'.jpg'",
",",
"'.BMP'",
",",
"'.bmp'",
",",
"'.PNG'",
",",
"'.png'",
"]",
"image_list",
"=",
"[",
"]",
"image_dir",
"=",
"None... | https://github.com/PaddlePaddle/PaddleSeg/blob/8a9196177c9e4b0187f90cbc6a6bc38a652eba73/contrib/Matting/utils.py#L27-L64 | |
zeropointdynamics/zelos | 0c5bd57b4bab56c23c27dc5301ba1a42ee054726 | src/zelos/network/base_socket.py | python | BaseSocket.shutdown | (self, how: int) | Shut down part of the socket connection.
Args:
how: the part of the connection to shutdown | Shut down part of the socket connection. | [
"Shut",
"down",
"part",
"of",
"the",
"socket",
"connection",
"."
] | def shutdown(self, how: int):
"""
Shut down part of the socket connection.
Args:
how: the part of the connection to shutdown
"""
pass | [
"def",
"shutdown",
"(",
"self",
",",
"how",
":",
"int",
")",
":",
"pass"
] | https://github.com/zeropointdynamics/zelos/blob/0c5bd57b4bab56c23c27dc5301ba1a42ee054726/src/zelos/network/base_socket.py#L272-L279 | ||
allenai/scitldr | da87c05acdc99dad5f3d75c661a482700fa16e1a | scripts/cal-rouge.py | python | _get_rouge | (pred, data) | return rouge_author_score, rouge_multi_max, rouge_multi_mean | given a prediction (pred) and a data object, calculate rouge scores
pred: str
data: {'target': str, '': ...}
returns (author rouge score, multi-target rouge score (by max), multi-target rouge score (by mean)) | given a prediction (pred) and a data object, calculate rouge scores
pred: str
data: {'target': str, '': ...} | [
"given",
"a",
"prediction",
"(",
"pred",
")",
"and",
"a",
"data",
"object",
"calculate",
"rouge",
"scores",
"pred",
":",
"str",
"data",
":",
"{",
"target",
":",
"str",
":",
"...",
"}"
] | def _get_rouge(pred, data):
""" given a prediction (pred) and a data object, calculate rouge scores
pred: str
data: {'target': str, '': ...}
returns (author rouge score, multi-target rouge score (by max), multi-target rouge score (by mean))
"""
rouge_author_score = {}
rouge_multi_mean = defaultdict(list)
with tempfile.TemporaryDirectory() as td:
cand_file = os.path.join(td, 'cand')
max_curr_rouge = -1000
author_rouge_f1 = 0
curr_rouge = {}
with open(cand_file, 'w') as fh:
fh.write(pred.strip())
if not isinstance(data['target'], list): # handle single target
data['target'] = [data['target']]
log_file = os.path.join(td, 'rouge.log')
for i, gold_tldr in enumerate(data['target']):
gold_file = os.path.join(td, 'gold')
with open(gold_file, 'w') as fh:
fh.write(gold_tldr.strip())
files2rouge.run(cand_file, gold_file, ignore_empty=True, saveto=log_file)
rouge_score = Path(log_file).read_text()
rouge_score = filter_rouge(rouge_score)
if max_curr_rouge < rouge_score['rouge-1']:
curr_rouge = rouge_score
max_curr_rouge = rouge_score['rouge-1']
if i == 0:
rouge_author_score = rouge_score
author_rouge_f1 = rouge_score['rouge-1']
for k, v in rouge_score.items():
rouge_multi_mean[k].append(v)
for k, v in rouge_multi_mean.items():
rouge_multi_mean[k] = sum(v) / len(v)
rouge_multi_max = curr_rouge
return rouge_author_score, rouge_multi_max, rouge_multi_mean | [
"def",
"_get_rouge",
"(",
"pred",
",",
"data",
")",
":",
"rouge_author_score",
"=",
"{",
"}",
"rouge_multi_mean",
"=",
"defaultdict",
"(",
"list",
")",
"with",
"tempfile",
".",
"TemporaryDirectory",
"(",
")",
"as",
"td",
":",
"cand_file",
"=",
"os",
".",
... | https://github.com/allenai/scitldr/blob/da87c05acdc99dad5f3d75c661a482700fa16e1a/scripts/cal-rouge.py#L50-L87 | |
rll/rllab | ba78e4c16dc492982e648f117875b22af3965579 | rllab/mujoco_py/glfw.py | python | set_monitor_callback | (cbfun) | Sets the monitor configuration callback.
Wrapper for:
GLFWmonitorfun glfwSetMonitorCallback(GLFWmonitorfun cbfun); | Sets the monitor configuration callback. | [
"Sets",
"the",
"monitor",
"configuration",
"callback",
"."
] | def set_monitor_callback(cbfun):
'''
Sets the monitor configuration callback.
Wrapper for:
GLFWmonitorfun glfwSetMonitorCallback(GLFWmonitorfun cbfun);
'''
global _monitor_callback
previous_callback = _monitor_callback
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWmonitorfun(cbfun)
_monitor_callback = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetMonitorCallback(cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0] | [
"def",
"set_monitor_callback",
"(",
"cbfun",
")",
":",
"global",
"_monitor_callback",
"previous_callback",
"=",
"_monitor_callback",
"if",
"cbfun",
"is",
"None",
":",
"cbfun",
"=",
"0",
"c_cbfun",
"=",
"_GLFWmonitorfun",
"(",
"cbfun",
")",
"_monitor_callback",
"="... | https://github.com/rll/rllab/blob/ba78e4c16dc492982e648f117875b22af3965579/rllab/mujoco_py/glfw.py#L671-L687 | ||
pillone/usntssearch | 24b5e5bc4b6af2589d95121c4d523dc58cb34273 | NZBmegasearch/requests/packages/urllib3/util.py | python | split_first | (s, delims) | return s[:min_idx], s[min_idx+1:], min_delim | Given a string and an iterable of delimiters, split on the first found
delimiter. Return two split parts and the matched delimiter.
If not found, then the first part is the full input string.
Example: ::
>>> split_first('foo/bar?baz', '?/=')
('foo', 'bar?baz', '/')
>>> split_first('foo/bar?baz', '123')
('foo/bar?baz', '', None)
Scales linearly with number of delims. Not ideal for large number of delims. | Given a string and an iterable of delimiters, split on the first found
delimiter. Return two split parts and the matched delimiter. | [
"Given",
"a",
"string",
"and",
"an",
"iterable",
"of",
"delimiters",
"split",
"on",
"the",
"first",
"found",
"delimiter",
".",
"Return",
"two",
"split",
"parts",
"and",
"the",
"matched",
"delimiter",
"."
] | def split_first(s, delims):
"""
Given a string and an iterable of delimiters, split on the first found
delimiter. Return two split parts and the matched delimiter.
If not found, then the first part is the full input string.
Example: ::
>>> split_first('foo/bar?baz', '?/=')
('foo', 'bar?baz', '/')
>>> split_first('foo/bar?baz', '123')
('foo/bar?baz', '', None)
Scales linearly with number of delims. Not ideal for large number of delims.
"""
min_idx = None
min_delim = None
for d in delims:
idx = s.find(d)
if idx < 0:
continue
if min_idx is None or idx < min_idx:
min_idx = idx
min_delim = d
if min_idx is None or min_idx < 0:
return s, '', None
return s[:min_idx], s[min_idx+1:], min_delim | [
"def",
"split_first",
"(",
"s",
",",
"delims",
")",
":",
"min_idx",
"=",
"None",
"min_delim",
"=",
"None",
"for",
"d",
"in",
"delims",
":",
"idx",
"=",
"s",
".",
"find",
"(",
"d",
")",
"if",
"idx",
"<",
"0",
":",
"continue",
"if",
"min_idx",
"is"... | https://github.com/pillone/usntssearch/blob/24b5e5bc4b6af2589d95121c4d523dc58cb34273/NZBmegasearch/requests/packages/urllib3/util.py#L63-L93 | |
axcore/tartube | 36dd493642923fe8b9190a41db596c30c043ae90 | tartube/mainapp.py | python | TartubeApp.clone_download_options_from_window | (self, data_list) | Called by config.OptionsEditWin.on_clone_options_clicked().
(Not called by self.apply_download_options(), which can handle its own
cloning).
Clones youtube-dl download options from the General Options manager
into the specified download options manager.
This function is designed to be called from one particular place. For
general cloning, call self.clone_download_options() instead.
Args:
data_list (list): List of values supplied by the dialogue window.
The first is the edit window for the download options object
(which must be reset). The second value is the download options
manager object, into which new options will be cloned. | Called by config.OptionsEditWin.on_clone_options_clicked(). | [
"Called",
"by",
"config",
".",
"OptionsEditWin",
".",
"on_clone_options_clicked",
"()",
"."
] | def clone_download_options_from_window(self, data_list):
"""Called by config.OptionsEditWin.on_clone_options_clicked().
(Not called by self.apply_download_options(), which can handle its own
cloning).
Clones youtube-dl download options from the General Options manager
into the specified download options manager.
This function is designed to be called from one particular place. For
general cloning, call self.clone_download_options() instead.
Args:
data_list (list): List of values supplied by the dialogue window.
The first is the edit window for the download options object
(which must be reset). The second value is the download options
manager object, into which new options will be cloned.
"""
if DEBUG_FUNC_FLAG:
utils.debug_time('app 15230 clone_download_options_from_window')
edit_win_obj = data_list.pop(0)
options_obj = data_list.pop(0)
# Clone values from the general download options manager
options_obj.clone_options(self.general_options_obj)
# Reset the edit window to display the new (cloned) values
edit_win_obj.reset_with_new_edit_obj(options_obj) | [
"def",
"clone_download_options_from_window",
"(",
"self",
",",
"data_list",
")",
":",
"if",
"DEBUG_FUNC_FLAG",
":",
"utils",
".",
"debug_time",
"(",
"'app 15230 clone_download_options_from_window'",
")",
"edit_win_obj",
"=",
"data_list",
".",
"pop",
"(",
"0",
")",
"... | https://github.com/axcore/tartube/blob/36dd493642923fe8b9190a41db596c30c043ae90/tartube/mainapp.py#L19070-L19101 | ||
CoinCheung/BiSeNet | f9231b7c971413e6ebdfcd961fbea53417b18851 | old/fp16/model.py | python | SpatialPath.get_params | (self) | return wd_params, nowd_params | [] | def get_params(self):
wd_params, nowd_params = [], []
for name, module in self.named_modules():
if isinstance(module, nn.Linear) or isinstance(module, nn.Conv2d):
wd_params.append(module.weight)
if not module.bias is None:
nowd_params.append(module.bias)
elif isinstance(module, nn.modules.batchnorm._BatchNorm):
nowd_params += list(module.parameters())
return wd_params, nowd_params | [
"def",
"get_params",
"(",
"self",
")",
":",
"wd_params",
",",
"nowd_params",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"name",
",",
"module",
"in",
"self",
".",
"named_modules",
"(",
")",
":",
"if",
"isinstance",
"(",
"module",
",",
"nn",
".",
"Linear",
... | https://github.com/CoinCheung/BiSeNet/blob/f9231b7c971413e6ebdfcd961fbea53417b18851/old/fp16/model.py#L171-L180 | |||
rajeshmajumdar/BruteXSS | ed08d0561a46d6553627ba7a26fd23fd792383e0 | mechanize/_beautifulsoup.py | python | Tag._getAttrMap | (self) | return self.attrMap | Initializes a map representation of this tag's attributes,
if not already initialized. | Initializes a map representation of this tag's attributes,
if not already initialized. | [
"Initializes",
"a",
"map",
"representation",
"of",
"this",
"tag",
"s",
"attributes",
"if",
"not",
"already",
"initialized",
"."
] | def _getAttrMap(self):
"""Initializes a map representation of this tag's attributes,
if not already initialized."""
if not getattr(self, 'attrMap'):
self.attrMap = {}
for (key, value) in self.attrs:
self.attrMap[key] = value
return self.attrMap | [
"def",
"_getAttrMap",
"(",
"self",
")",
":",
"if",
"not",
"getattr",
"(",
"self",
",",
"'attrMap'",
")",
":",
"self",
".",
"attrMap",
"=",
"{",
"}",
"for",
"(",
"key",
",",
"value",
")",
"in",
"self",
".",
"attrs",
":",
"self",
".",
"attrMap",
"[... | https://github.com/rajeshmajumdar/BruteXSS/blob/ed08d0561a46d6553627ba7a26fd23fd792383e0/mechanize/_beautifulsoup.py#L508-L515 | |
XKNX/xknx | 1deeeb3dc0978aebacf14492a84e1f1eaf0970ed | xknx/exceptions/exception.py | python | CouldNotParseAddress.__str__ | (self) | return f'<CouldNotParseAddress address="{self.address}" />' | Return object as readable string. | Return object as readable string. | [
"Return",
"object",
"as",
"readable",
"string",
"."
] | def __str__(self) -> str:
"""Return object as readable string."""
return f'<CouldNotParseAddress address="{self.address}" />' | [
"def",
"__str__",
"(",
"self",
")",
"->",
"str",
":",
"return",
"f'<CouldNotParseAddress address=\"{self.address}\" />'"
] | https://github.com/XKNX/xknx/blob/1deeeb3dc0978aebacf14492a84e1f1eaf0970ed/xknx/exceptions/exception.py#L110-L112 | |
xiepaup/dbatools | 8549f2571aaee6a39f5c6f32179ac9c5d301a9aa | mysqlTools/mysql_utilities/mysql/utilities/command/rpl_admin.py | python | RplCommands._report | (self, message, level=logging.INFO, print_msg=True) | Log message if logging is on
This method will log the message presented if the log is turned on.
Specifically, if options['log_file'] is not None. It will also
print the message to stdout.
message[in] message to be printed
level[in] level of message to log. Default = INFO
print_msg[in] if True, print the message to stdout. Default = True | Log message if logging is on | [
"Log",
"message",
"if",
"logging",
"is",
"on"
] | def _report(self, message, level=logging.INFO, print_msg=True):
"""Log message if logging is on
This method will log the message presented if the log is turned on.
Specifically, if options['log_file'] is not None. It will also
print the message to stdout.
message[in] message to be printed
level[in] level of message to log. Default = INFO
print_msg[in] if True, print the message to stdout. Default = True
"""
# First, print the message.
if print_msg and not self.quiet:
print message
# Now log message if logging turned on
if self.logging:
logging.log(int(level), message.strip("#").strip(' ')) | [
"def",
"_report",
"(",
"self",
",",
"message",
",",
"level",
"=",
"logging",
".",
"INFO",
",",
"print_msg",
"=",
"True",
")",
":",
"# First, print the message.",
"if",
"print_msg",
"and",
"not",
"self",
".",
"quiet",
":",
"print",
"message",
"# Now log messa... | https://github.com/xiepaup/dbatools/blob/8549f2571aaee6a39f5c6f32179ac9c5d301a9aa/mysqlTools/mysql_utilities/mysql/utilities/command/rpl_admin.py#L175-L191 | ||
JaniceWuo/MovieRecommend | 4c86db64ca45598917d304f535413df3bc9fea65 | movierecommend/venv1/Lib/site-packages/django/contrib/postgres/fields/ranges.py | python | RangeField.model | (self, model) | [] | def model(self, model):
self.__dict__['model'] = model
self.base_field.model = model | [
"def",
"model",
"(",
"self",
",",
"model",
")",
":",
"self",
".",
"__dict__",
"[",
"'model'",
"]",
"=",
"model",
"self",
".",
"base_field",
".",
"model",
"=",
"model"
] | https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/contrib/postgres/fields/ranges.py#L34-L36 | ||||
zetaops/ulakbus | bcc05abf17bbd6dbeec93809e4ad30885e94e83e | ulakbus/views/bap/bap_firma_kayit.py | python | BapFirmaKayit.uygunluk_kontrolleri | (self, form) | return True, '', '' | Firma kaydında girilen bilgiler kontrol edilir. Örneğin, formda girilen vergi numarası ve
vergi dairesine ait veritabanında kayıt bulunması ya da girilen firma e-postasının
sistemde bulunması gibi durumlar kontrol edilir. Bu durumlara özel uyarı mesajları üretilir.
Args:
form(form): Firma kayıt başvurusu formu.
Returns:
bool, hata mesajı, hatanın bulunduğu form field listesi | Firma kaydında girilen bilgiler kontrol edilir. Örneğin, formda girilen vergi numarası ve
vergi dairesine ait veritabanında kayıt bulunması ya da girilen firma e-postasının
sistemde bulunması gibi durumlar kontrol edilir. Bu durumlara özel uyarı mesajları üretilir.
Args:
form(form): Firma kayıt başvurusu formu.
Returns:
bool, hata mesajı, hatanın bulunduğu form field listesi | [
"Firma",
"kaydında",
"girilen",
"bilgiler",
"kontrol",
"edilir",
".",
"Örneğin",
"formda",
"girilen",
"vergi",
"numarası",
"ve",
"vergi",
"dairesine",
"ait",
"veritabanında",
"kayıt",
"bulunması",
"ya",
"da",
"girilen",
"firma",
"e",
"-",
"postasının",
"sistemde",... | def uygunluk_kontrolleri(self, form):
"""
Firma kaydında girilen bilgiler kontrol edilir. Örneğin, formda girilen vergi numarası ve
vergi dairesine ait veritabanında kayıt bulunması ya da girilen firma e-postasının
sistemde bulunması gibi durumlar kontrol edilir. Bu durumlara özel uyarı mesajları üretilir.
Args:
form(form): Firma kayıt başvurusu formu.
Returns:
bool, hata mesajı, hatanın bulunduğu form field listesi
"""
vergi_daireleri = catalog_data_manager.get_all_as_dict('vergi_daireleri')
vergi_dairesi = vergi_daireleri[form['vergi_dairesi']]
giris_bilgileri = {
'vergi_no': (BAPFirma,
{'vergi_no': form['vergi_no'], 'vergi_dairesi': form['vergi_dairesi']},
vergi_dairesi, 'vergi_dairesi'),
'e_posta': (BAPFirma, {'e_posta': form['e_posta']}, 'firma e-postasına', ''),
'k_adi': (User, {'username': form['k_adi']}, 'yetkili kullanıcı adına', ''),
'yetkili_e_posta': (User, {'e_mail': form['yetkili_e_posta']}, 'yetkili e-postasına', '')}
for key, bilgiler in giris_bilgileri.items():
model, query, msg, additional = bilgiler
try:
obj = model.objects.get(**query)
error_msg = vergi_no_msg if key == 'vergi_no' else mevcut_bilgi_msg
field_list = [key, additional] if key == 'vergi_no' else [key]
self.current.task_data['vergi_no_hatasi'] = (key == 'vergi_no')
if self.current.task_data['vergi_no_hatasi']:
self.current.task_data['firma_key'] = obj.key
return False, error_msg.format(form[key], msg), field_list
except ObjectDoesNotExist:
pass
return True, '', '' | [
"def",
"uygunluk_kontrolleri",
"(",
"self",
",",
"form",
")",
":",
"vergi_daireleri",
"=",
"catalog_data_manager",
".",
"get_all_as_dict",
"(",
"'vergi_daireleri'",
")",
"vergi_dairesi",
"=",
"vergi_daireleri",
"[",
"form",
"[",
"'vergi_dairesi'",
"]",
"]",
"giris_b... | https://github.com/zetaops/ulakbus/blob/bcc05abf17bbd6dbeec93809e4ad30885e94e83e/ulakbus/views/bap/bap_firma_kayit.py#L258-L295 | |
mschwager/gitem | d40a1c9ba27270f043440372ccfe0cd18c83706c | lib/gitem/api.py | python | Api.call | (self, method, url, params=None) | return response | Make a Github developer API call | Make a Github developer API call | [
"Make",
"a",
"Github",
"developer",
"API",
"call"
] | def call(self, method, url, params=None):
"""
Make a Github developer API call
"""
if params is None:
params = {}
if self.oauth2_token:
params["access_token"] = self.oauth2_token
response = self.requester(method, url, params=params, headers=self.headers)
if not response.ok:
raise ApiCallException(response.status_code, response.json())
return response | [
"def",
"call",
"(",
"self",
",",
"method",
",",
"url",
",",
"params",
"=",
"None",
")",
":",
"if",
"params",
"is",
"None",
":",
"params",
"=",
"{",
"}",
"if",
"self",
".",
"oauth2_token",
":",
"params",
"[",
"\"access_token\"",
"]",
"=",
"self",
".... | https://github.com/mschwager/gitem/blob/d40a1c9ba27270f043440372ccfe0cd18c83706c/lib/gitem/api.py#L85-L100 | |
HelloRicky123/Siamese-RPN | 08625aa8828aea5d63cb8b301c7ec4e300cb047b | lib/visual.py | python | visual.denormalize | (self, img) | return img | [] | def denormalize(self, img):
img = img.cpu().detach().numpy().transpose(1, 2, 0)
img = np.clip(img, 0, 255).astype(np.uint8)
return img | [
"def",
"denormalize",
"(",
"self",
",",
"img",
")",
":",
"img",
"=",
"img",
".",
"cpu",
"(",
")",
".",
"detach",
"(",
")",
".",
"numpy",
"(",
")",
".",
"transpose",
"(",
"1",
",",
"2",
",",
"0",
")",
"img",
"=",
"np",
".",
"clip",
"(",
"img... | https://github.com/HelloRicky123/Siamese-RPN/blob/08625aa8828aea5d63cb8b301c7ec4e300cb047b/lib/visual.py#L16-L19 | |||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.9.40/roles/openshift_health_checker/callback_plugins/zz_failure_summary.py | python | failure_summary | (failures, playbook) | return u'\n'.join(summary) | Return a summary of failed tasks, including details on health checks. | Return a summary of failed tasks, including details on health checks. | [
"Return",
"a",
"summary",
"of",
"failed",
"tasks",
"including",
"details",
"on",
"health",
"checks",
"."
] | def failure_summary(failures, playbook):
"""Return a summary of failed tasks, including details on health checks."""
if not failures:
return u''
# NOTE: because we don't have access to task_vars from callback plugins, we
# store the playbook context in the task result when the
# openshift_health_check action plugin is used, and we use this context to
# customize the error message.
# pylint: disable=protected-access; Ansible gives us no sufficient public
# API on TaskResult objects.
context = next((
context for context in
(failure._result.get('playbook_context') for failure in failures)
if context
), None)
failures = [failure_to_dict(failure) for failure in failures]
failures = deduplicate_failures(failures)
summary = [u'', u'', u'Failure summary:', u'']
width = len(str(len(failures)))
initial_indent_format = u' {{:>{width}}}. '.format(width=width)
initial_indent_len = len(initial_indent_format.format(0))
subsequent_indent = u' ' * initial_indent_len
subsequent_extra_indent = u' ' * (initial_indent_len + 10)
for i, failure in enumerate(failures, 1):
entries = format_failure(failure)
summary.append(u'\n{}{}'.format(initial_indent_format.format(i), entries[0]))
for entry in entries[1:]:
if PY2:
entry = entry.decode('utf8')
entry = entry.replace(u'\n', u'\n' + subsequent_extra_indent)
indented = u'{}{}'.format(subsequent_indent, entry)
summary.append(indented)
failed_checks = set()
for failure in failures:
failed_checks.update(name for name, message in failure['checks'])
if failed_checks:
summary.append(check_failure_footer(failed_checks, context, playbook))
return u'\n'.join(summary) | [
"def",
"failure_summary",
"(",
"failures",
",",
"playbook",
")",
":",
"if",
"not",
"failures",
":",
"return",
"u''",
"# NOTE: because we don't have access to task_vars from callback plugins, we",
"# store the playbook context in the task result when the",
"# openshift_health_check ac... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/openshift_health_checker/callback_plugins/zz_failure_summary.py#L57-L101 | |
geopandas/geopandas | 8e7133aef9e6c0d2465e07e92d954e95dedd3881 | geopandas/geodataframe.py | python | GeoDataFrame.__xor__ | (self, other) | return self.geometry.symmetric_difference(other) | Implement ^ operator as for builtin set type | Implement ^ operator as for builtin set type | [
"Implement",
"^",
"operator",
"as",
"for",
"builtin",
"set",
"type"
] | def __xor__(self, other):
"""Implement ^ operator as for builtin set type"""
warnings.warn(
"'^' operator will be deprecated. Use the 'symmetric_difference' "
"method instead.",
DeprecationWarning,
stacklevel=2,
)
return self.geometry.symmetric_difference(other) | [
"def",
"__xor__",
"(",
"self",
",",
"other",
")",
":",
"warnings",
".",
"warn",
"(",
"\"'^' operator will be deprecated. Use the 'symmetric_difference' \"",
"\"method instead.\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
",",
")",
"return",
"self",
".",... | https://github.com/geopandas/geopandas/blob/8e7133aef9e6c0d2465e07e92d954e95dedd3881/geopandas/geodataframe.py#L1839-L1847 | |
zhaoolee/StarsAndClown | b2d4039cad2f9232b691e5976f787b49a0a2c113 | node_modules/npmi/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/ninja_syntax.py | python | Writer._line | (self, text, indent=0) | Write 'text' word-wrapped at self.width characters. | Write 'text' word-wrapped at self.width characters. | [
"Write",
"text",
"word",
"-",
"wrapped",
"at",
"self",
".",
"width",
"characters",
"."
] | def _line(self, text, indent=0):
"""Write 'text' word-wrapped at self.width characters."""
leading_space = ' ' * indent
while len(leading_space) + len(text) > self.width:
# The text is too wide; wrap if possible.
# Find the rightmost space that would obey our width constraint and
# that's not an escaped space.
available_space = self.width - len(leading_space) - len(' $')
space = available_space
while True:
space = text.rfind(' ', 0, space)
if space < 0 or \
self._count_dollars_before_index(text, space) % 2 == 0:
break
if space < 0:
# No such space; just use the first unescaped space we can find.
space = available_space - 1
while True:
space = text.find(' ', space + 1)
if space < 0 or \
self._count_dollars_before_index(text, space) % 2 == 0:
break
if space < 0:
# Give up on breaking.
break
self.output.write(leading_space + text[0:space] + ' $\n')
text = text[space+1:]
# Subsequent lines are continuations, so indent them.
leading_space = ' ' * (indent+2)
self.output.write(leading_space + text + '\n') | [
"def",
"_line",
"(",
"self",
",",
"text",
",",
"indent",
"=",
"0",
")",
":",
"leading_space",
"=",
"' '",
"*",
"indent",
"while",
"len",
"(",
"leading_space",
")",
"+",
"len",
"(",
"text",
")",
">",
"self",
".",
"width",
":",
"# The text is too wide; ... | https://github.com/zhaoolee/StarsAndClown/blob/b2d4039cad2f9232b691e5976f787b49a0a2c113/node_modules/npmi/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/ninja_syntax.py#L111-L145 | ||
santhoshkolloju/Abstractive-Summarization-With-Transfer-Learning | 97ff2ae3ba9f2d478e174444c4e0f5349f28c319 | texar_repo/examples/bert/utils/data_utils.py | python | DataProcessor.get_dev_examples | (self, data_dir) | Gets a collection of `InputExample`s for the dev set. | Gets a collection of `InputExample`s for the dev set. | [
"Gets",
"a",
"collection",
"of",
"InputExample",
"s",
"for",
"the",
"dev",
"set",
"."
] | def get_dev_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the dev set."""
raise NotImplementedError() | [
"def",
"get_dev_examples",
"(",
"self",
",",
"data_dir",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/santhoshkolloju/Abstractive-Summarization-With-Transfer-Learning/blob/97ff2ae3ba9f2d478e174444c4e0f5349f28c319/texar_repo/examples/bert/utils/data_utils.py#L65-L67 | ||
ElementAI/baal | 1108f2667d14f8e43562266ea085c72086f6abd6 | baal/bayesian/dropout.py | python | MCDropoutModule.__init__ | (self, module: torch.nn.Module) | Create a module that with all dropout layers patched.
Args:
module (torch.nn.Module):
A fully specified neural network. | Create a module that with all dropout layers patched. | [
"Create",
"a",
"module",
"that",
"with",
"all",
"dropout",
"layers",
"patched",
"."
] | def __init__(self, module: torch.nn.Module):
"""Create a module that with all dropout layers patched.
Args:
module (torch.nn.Module):
A fully specified neural network.
"""
super().__init__()
self.parent_module = module
_patch_dropout_layers(self.parent_module) | [
"def",
"__init__",
"(",
"self",
",",
"module",
":",
"torch",
".",
"nn",
".",
"Module",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"parent_module",
"=",
"module",
"_patch_dropout_layers",
"(",
"self",
".",
"parent_module",
")"
] | https://github.com/ElementAI/baal/blob/1108f2667d14f8e43562266ea085c72086f6abd6/baal/bayesian/dropout.py#L138-L147 | ||
cloud-custodian/cloud-custodian | 1ce1deb2d0f0832d6eb8839ef74b4c9e397128de | c7n/resources/rds.py | python | _get_available_engine_upgrades | (client, major=False) | return results | Returns all extant rds engine upgrades.
As a nested mapping of engine type to known versions
and their upgrades.
Defaults to minor upgrades, but configurable to major.
Example::
>>> _get_available_engine_upgrades(client)
{
'oracle-se2': {'12.1.0.2.v2': '12.1.0.2.v5',
'12.1.0.2.v3': '12.1.0.2.v5'},
'postgres': {'9.3.1': '9.3.14',
'9.3.10': '9.3.14',
'9.3.12': '9.3.14',
'9.3.2': '9.3.14'}
} | Returns all extant rds engine upgrades. | [
"Returns",
"all",
"extant",
"rds",
"engine",
"upgrades",
"."
] | def _get_available_engine_upgrades(client, major=False):
"""Returns all extant rds engine upgrades.
As a nested mapping of engine type to known versions
and their upgrades.
Defaults to minor upgrades, but configurable to major.
Example::
>>> _get_available_engine_upgrades(client)
{
'oracle-se2': {'12.1.0.2.v2': '12.1.0.2.v5',
'12.1.0.2.v3': '12.1.0.2.v5'},
'postgres': {'9.3.1': '9.3.14',
'9.3.10': '9.3.14',
'9.3.12': '9.3.14',
'9.3.2': '9.3.14'}
}
"""
results = {}
paginator = client.get_paginator('describe_db_engine_versions')
for page in paginator.paginate():
engine_versions = page['DBEngineVersions']
for v in engine_versions:
if not v['Engine'] in results:
results[v['Engine']] = {}
if 'ValidUpgradeTarget' not in v or len(v['ValidUpgradeTarget']) == 0:
continue
for t in v['ValidUpgradeTarget']:
if not major and t['IsMajorVersionUpgrade']:
continue
if LooseVersion(t['EngineVersion']) > LooseVersion(
results[v['Engine']].get(v['EngineVersion'], '0.0.0')):
results[v['Engine']][v['EngineVersion']] = t['EngineVersion']
return results | [
"def",
"_get_available_engine_upgrades",
"(",
"client",
",",
"major",
"=",
"False",
")",
":",
"results",
"=",
"{",
"}",
"paginator",
"=",
"client",
".",
"get_paginator",
"(",
"'describe_db_engine_versions'",
")",
"for",
"page",
"in",
"paginator",
".",
"paginate"... | https://github.com/cloud-custodian/cloud-custodian/blob/1ce1deb2d0f0832d6eb8839ef74b4c9e397128de/c7n/resources/rds.py#L196-L231 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.