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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lemonhu/NER-BERT-pytorch | 5f7577b78020dc5867cc3a4dbb7a2db44bae1fc8 | metrics.py | python | start_of_chunk | (prev_tag, tag, prev_type, type_) | return chunk_start | Checks if a chunk started between the previous and current word.
Args:
prev_tag: previous chunk tag.
tag: current chunk tag.
prev_type: previous type.
type_: current type.
Returns:
chunk_start: boolean. | Checks if a chunk started between the previous and current word. | [
"Checks",
"if",
"a",
"chunk",
"started",
"between",
"the",
"previous",
"and",
"current",
"word",
"."
] | def start_of_chunk(prev_tag, tag, prev_type, type_):
"""Checks if a chunk started between the previous and current word.
Args:
prev_tag: previous chunk tag.
tag: current chunk tag.
prev_type: previous type.
type_: current type.
Returns:
chunk_start: boolean.
"""
chunk_start = False
if tag == 'B': chunk_start = True
if tag == 'S': chunk_start = True
if prev_tag == 'E' and tag == 'E': chunk_start = True
if prev_tag == 'E' and tag == 'I': chunk_start = True
if prev_tag == 'S' and tag == 'E': chunk_start = True
if prev_tag == 'S' and tag == 'I': chunk_start = True
if prev_tag == 'O' and tag == 'E': chunk_start = True
if prev_tag == 'O' and tag == 'I': chunk_start = True
if tag != 'O' and tag != '.' and prev_type != type_:
chunk_start = True
return chunk_start | [
"def",
"start_of_chunk",
"(",
"prev_tag",
",",
"tag",
",",
"prev_type",
",",
"type_",
")",
":",
"chunk_start",
"=",
"False",
"if",
"tag",
"==",
"'B'",
":",
"chunk_start",
"=",
"True",
"if",
"tag",
"==",
"'S'",
":",
"chunk_start",
"=",
"True",
"if",
"pr... | https://github.com/lemonhu/NER-BERT-pytorch/blob/5f7577b78020dc5867cc3a4dbb7a2db44bae1fc8/metrics.py#L87-L114 | |
bastula/dicompyler | 2643e0ee145cb7c699b3d36e3e4f07ac9dc7b1f2 | dicompyler/baseplugins/quickopen.py | python | plugin.OnImportPrefsChange | (self, topic, msg) | When the import preferences change, update the values. | When the import preferences change, update the values. | [
"When",
"the",
"import",
"preferences",
"change",
"update",
"the",
"values",
"."
] | def OnImportPrefsChange(self, topic, msg):
"""When the import preferences change, update the values."""
topic = topic.split('.')
if (topic[1] == 'import_location'):
self.path = str(msg)
elif (topic[1] == 'import_location_setting'):
self.import_location_setting = msg | [
"def",
"OnImportPrefsChange",
"(",
"self",
",",
"topic",
",",
"msg",
")",
":",
"topic",
"=",
"topic",
".",
"split",
"(",
"'.'",
")",
"if",
"(",
"topic",
"[",
"1",
"]",
"==",
"'import_location'",
")",
":",
"self",
".",
"path",
"=",
"str",
"(",
"msg"... | https://github.com/bastula/dicompyler/blob/2643e0ee145cb7c699b3d36e3e4f07ac9dc7b1f2/dicompyler/baseplugins/quickopen.py#L49-L55 | ||
syb7573330/im2avatar | f4636d35f622f2f1f3915a2a8f3307f3ee104928 | utils/tf_utils.py | python | avg_pool3d | (inputs,
kernel_size,
scope,
stride=[2, 2, 2],
padding='VALID') | 3D avg pooling.
Args:
inputs: 5-D tensor BxDxHxWxC
kernel_size: a list of 3 ints
stride: a list of 3 ints
Returns:
Variable tensor | 3D avg pooling. | [
"3D",
"avg",
"pooling",
"."
] | def avg_pool3d(inputs,
kernel_size,
scope,
stride=[2, 2, 2],
padding='VALID'):
""" 3D avg pooling.
Args:
inputs: 5-D tensor BxDxHxWxC
kernel_size: a list of 3 ints
stride: a list of 3 ints
Returns:
Variable tensor
"""
with tf.variable_scope(scope) as sc:
kernel_d, kernel_h, kernel_w = kernel_size
stride_d, stride_h, stride_w = stride
outputs = tf.nn.avg_pool3d(inputs,
ksize=[1, kernel_d, kernel_h, kernel_w, 1],
strides=[1, stride_d, stride_h, stride_w, 1],
padding=padding,
name=sc.name)
return outputs | [
"def",
"avg_pool3d",
"(",
"inputs",
",",
"kernel_size",
",",
"scope",
",",
"stride",
"=",
"[",
"2",
",",
"2",
",",
"2",
"]",
",",
"padding",
"=",
"'VALID'",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"scope",
")",
"as",
"sc",
":",
"kernel_... | https://github.com/syb7573330/im2avatar/blob/f4636d35f622f2f1f3915a2a8f3307f3ee104928/utils/tf_utils.py#L502-L525 | ||
sahana/eden | 1696fa50e90ce967df69f66b571af45356cc18da | modules/s3/s3aaa.py | python | AuthS3.s3_register_onaccept | (self, form) | Sets session.auth.user for authorstamp, etc, and approves user
(to set registration groups, such as AUTHENTICATED, link to Person)
Designed to be called when a user is created through:
- registration via OAuth, LDAP, etc | Sets session.auth.user for authorstamp, etc, and approves user
(to set registration groups, such as AUTHENTICATED, link to Person) | [
"Sets",
"session",
".",
"auth",
".",
"user",
"for",
"authorstamp",
"etc",
"and",
"approves",
"user",
"(",
"to",
"set",
"registration",
"groups",
"such",
"as",
"AUTHENTICATED",
"link",
"to",
"Person",
")"
] | def s3_register_onaccept(self, form):
"""
Sets session.auth.user for authorstamp, etc, and approves user
(to set registration groups, such as AUTHENTICATED, link to Person)
Designed to be called when a user is created through:
- registration via OAuth, LDAP, etc
"""
user = form.vars
current.session.auth = Storage(user = user)
self.s3_approve_user(user) | [
"def",
"s3_register_onaccept",
"(",
"self",
",",
"form",
")",
":",
"user",
"=",
"form",
".",
"vars",
"current",
".",
"session",
".",
"auth",
"=",
"Storage",
"(",
"user",
"=",
"user",
")",
"self",
".",
"s3_approve_user",
"(",
"user",
")"
] | https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3/s3aaa.py#L2527-L2538 | ||
replit-archive/empythoned | 977ec10ced29a3541a4973dc2b59910805695752 | cpython/Lib/compiler/symbols.py | python | SymbolVisitor.visitAssign | (self, node, scope) | Propagate assignment flag down to child nodes.
The Assign node doesn't itself contains the variables being
assigned to. Instead, the children in node.nodes are visited
with the assign flag set to true. When the names occur in
those nodes, they are marked as defs.
Some names that occur in an assignment target are not bound by
the assignment, e.g. a name occurring inside a slice. The
visitor handles these nodes specially; they do not propagate
the assign flag to their children. | Propagate assignment flag down to child nodes. | [
"Propagate",
"assignment",
"flag",
"down",
"to",
"child",
"nodes",
"."
] | def visitAssign(self, node, scope):
"""Propagate assignment flag down to child nodes.
The Assign node doesn't itself contains the variables being
assigned to. Instead, the children in node.nodes are visited
with the assign flag set to true. When the names occur in
those nodes, they are marked as defs.
Some names that occur in an assignment target are not bound by
the assignment, e.g. a name occurring inside a slice. The
visitor handles these nodes specially; they do not propagate
the assign flag to their children.
"""
for n in node.nodes:
self.visit(n, scope, 1)
self.visit(node.expr, scope) | [
"def",
"visitAssign",
"(",
"self",
",",
"node",
",",
"scope",
")",
":",
"for",
"n",
"in",
"node",
".",
"nodes",
":",
"self",
".",
"visit",
"(",
"n",
",",
"scope",
",",
"1",
")",
"self",
".",
"visit",
"(",
"node",
".",
"expr",
",",
"scope",
")"
... | https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/cpython/Lib/compiler/symbols.py#L347-L362 | ||
tendenci/tendenci | 0f2c348cc0e7d41bc56f50b00ce05544b083bf1d | tendenci/apps/articles/models.py | python | Article.has_google_publisher | (self) | return self.contributor_type == self.CONTRIBUTOR_PUBLISHER | [] | def has_google_publisher(self):
return self.contributor_type == self.CONTRIBUTOR_PUBLISHER | [
"def",
"has_google_publisher",
"(",
"self",
")",
":",
"return",
"self",
".",
"contributor_type",
"==",
"self",
".",
"CONTRIBUTOR_PUBLISHER"
] | https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/articles/models.py#L154-L155 | |||
google/coursebuilder-core | 08f809db3226d9269e30d5edd0edd33bd22041f4 | coursebuilder/controllers/utils.py | python | BaseHandler.render | (self, template_file, additional_dirs=None, save_location=True) | Renders a template. | Renders a template. | [
"Renders",
"a",
"template",
"."
] | def render(self, template_file, additional_dirs=None, save_location=True):
"""Renders a template."""
prefs = models.StudentPreferencesDAO.load_or_default()
courses.Course.set_current(self.get_course())
models.MemcacheManager.begin_readonly()
try:
template = self.get_template(
template_file, additional_dirs=additional_dirs, prefs=prefs)
self.response.out.write(template.render(self.template_value))
finally:
models.MemcacheManager.end_readonly()
courses.Course.clear_current()
# If the page displayed successfully, save the location for registered
# students so future visits to the course's base URL sends the student
# to the most-recently-visited page.
# TODO(psimakov): method called render() must not have mutations
if save_location and self.request.method == 'GET':
user = self.get_user()
if user:
student = models.Student.get_enrolled_student_by_user(user)
if student:
prefs.last_location = self.request.path_qs
models.StudentPreferencesDAO.save(prefs) | [
"def",
"render",
"(",
"self",
",",
"template_file",
",",
"additional_dirs",
"=",
"None",
",",
"save_location",
"=",
"True",
")",
":",
"prefs",
"=",
"models",
".",
"StudentPreferencesDAO",
".",
"load_or_default",
"(",
")",
"courses",
".",
"Course",
".",
"set_... | https://github.com/google/coursebuilder-core/blob/08f809db3226d9269e30d5edd0edd33bd22041f4/coursebuilder/controllers/utils.py#L1086-L1110 | ||
berkerpeksag/github-badge | a9a2a4ef1a2a35be6cf4328bbd3c736080dd4af7 | packages/requests/packages/oauthlib/oauth2/draft25/parameters.py | python | prepare_grant_uri | (uri, client_id, response_type, redirect_uri=None,
scope=None, state=None, **kwargs) | return add_params_to_uri(uri, params) | Prepare the authorization grant request URI.
The client constructs the request URI by adding the following
parameters to the query component of the authorization endpoint URI
using the "application/x-www-form-urlencoded" format as defined by
[W3C.REC-html401-19991224]:
response_type
REQUIRED. Value MUST be set to "code".
client_id
REQUIRED. The client identifier as described in `Section 2.2`_.
redirect_uri
OPTIONAL. As described in `Section 3.1.2`_.
scope
OPTIONAL. The scope of the access request as described by
`Section 3.3`_.
state
RECOMMENDED. An opaque value used by the client to maintain
state between the request and callback. The authorization
server includes this value when redirecting the user-agent back
to the client. The parameter SHOULD be used for preventing
cross-site request forgery as described in `Section 10.12`_.
GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1
Host: server.example.com
.. _`W3C.REC-html401-19991224`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#ref-W3C.REC-html401-19991224
.. _`Section 2.2`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-2.2
.. _`Section 3.1.2`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-3.1.2
.. _`Section 3.3`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-3.3
.. _`section 10.12`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-10.12 | Prepare the authorization grant request URI. | [
"Prepare",
"the",
"authorization",
"grant",
"request",
"URI",
"."
] | def prepare_grant_uri(uri, client_id, response_type, redirect_uri=None,
scope=None, state=None, **kwargs):
"""Prepare the authorization grant request URI.
The client constructs the request URI by adding the following
parameters to the query component of the authorization endpoint URI
using the "application/x-www-form-urlencoded" format as defined by
[W3C.REC-html401-19991224]:
response_type
REQUIRED. Value MUST be set to "code".
client_id
REQUIRED. The client identifier as described in `Section 2.2`_.
redirect_uri
OPTIONAL. As described in `Section 3.1.2`_.
scope
OPTIONAL. The scope of the access request as described by
`Section 3.3`_.
state
RECOMMENDED. An opaque value used by the client to maintain
state between the request and callback. The authorization
server includes this value when redirecting the user-agent back
to the client. The parameter SHOULD be used for preventing
cross-site request forgery as described in `Section 10.12`_.
GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1
Host: server.example.com
.. _`W3C.REC-html401-19991224`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#ref-W3C.REC-html401-19991224
.. _`Section 2.2`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-2.2
.. _`Section 3.1.2`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-3.1.2
.. _`Section 3.3`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-3.3
.. _`section 10.12`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-10.12
"""
params = [((u'response_type', response_type)),
((u'client_id', client_id))]
if redirect_uri:
params.append((u'redirect_uri', redirect_uri))
if scope:
params.append((u'scope', scope))
if state:
params.append((u'state', state))
for k in kwargs:
params.append((unicode(k), kwargs[k]))
return add_params_to_uri(uri, params) | [
"def",
"prepare_grant_uri",
"(",
"uri",
",",
"client_id",
",",
"response_type",
",",
"redirect_uri",
"=",
"None",
",",
"scope",
"=",
"None",
",",
"state",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"[",
"(",
"(",
"u'response_type'",
... | https://github.com/berkerpeksag/github-badge/blob/a9a2a4ef1a2a35be6cf4328bbd3c736080dd4af7/packages/requests/packages/oauthlib/oauth2/draft25/parameters.py#L15-L63 | |
coleifer/huey | b7aebe442514fa9cca376265dce371ae42a17535 | huey/consumer.py | python | Consumer.start | (self) | Start all consumer processes and register signal handlers. | Start all consumer processes and register signal handlers. | [
"Start",
"all",
"consumer",
"processes",
"and",
"register",
"signal",
"handlers",
"."
] | def start(self):
"""
Start all consumer processes and register signal handlers.
"""
if self.huey.immediate:
raise ConfigurationError(
'Consumer cannot be run with Huey instances where immediate '
'is enabled. Please check your configuration and ensure that '
'"huey.immediate = False".')
# Log startup message.
self._logger.info('Huey consumer started with %s %s, PID %s at %s',
self.workers, self.worker_type, os.getpid(),
self.huey._get_timestamp())
self._logger.info('Scheduler runs every %s second(s).',
self.scheduler_interval)
self._logger.info('Periodic tasks are %s.',
'enabled' if self.periodic else 'disabled')
msg = ['The following commands are available:']
for command in self.huey._registry._registry:
msg.append('+ %s' % command)
self._logger.info('\n'.join(msg))
# Start the scheduler and workers.
self.scheduler.start()
for _, worker_process in self.worker_threads:
worker_process.start()
# Finally set the signal handlers for main process.
self._set_signal_handlers() | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"huey",
".",
"immediate",
":",
"raise",
"ConfigurationError",
"(",
"'Consumer cannot be run with Huey instances where immediate '",
"'is enabled. Please check your configuration and ensure that '",
"'\"huey.immediate = Fal... | https://github.com/coleifer/huey/blob/b7aebe442514fa9cca376265dce371ae42a17535/huey/consumer.py#L365-L396 | ||
whyliam/whyliam.workflows.youdao | 2dfa7f1de56419dab1c2e70c1a27e5e13ba25a5c | urllib3/packages/rfc3986/_mixin.py | python | URIMixin.scheme_is_valid | (self, require=False) | return validators.scheme_is_valid(self.scheme, require) | Determine if the scheme component is valid.
.. deprecated:: 1.1.0
Use the :class:`~rfc3986.validators.Validator` object instead.
:param str require: Set to ``True`` to require the presence of this
component.
:returns: ``True`` if the scheme is valid. ``False`` otherwise.
:rtype: bool | Determine if the scheme component is valid. | [
"Determine",
"if",
"the",
"scheme",
"component",
"is",
"valid",
"."
] | def scheme_is_valid(self, require=False):
"""Determine if the scheme component is valid.
.. deprecated:: 1.1.0
Use the :class:`~rfc3986.validators.Validator` object instead.
:param str require: Set to ``True`` to require the presence of this
component.
:returns: ``True`` if the scheme is valid. ``False`` otherwise.
:rtype: bool
"""
warnings.warn(
"Please use rfc3986.validators.Validator instead. "
"This method will be eventually removed.",
DeprecationWarning,
)
return validators.scheme_is_valid(self.scheme, require) | [
"def",
"scheme_is_valid",
"(",
"self",
",",
"require",
"=",
"False",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Please use rfc3986.validators.Validator instead. \"",
"\"This method will be eventually removed.\"",
",",
"DeprecationWarning",
",",
")",
"return",
"validators",
... | https://github.com/whyliam/whyliam.workflows.youdao/blob/2dfa7f1de56419dab1c2e70c1a27e5e13ba25a5c/urllib3/packages/rfc3986/_mixin.py#L158-L175 | |
agoragames/leaderboard-python | 4bc028164c259c3a31c7e6ccb2a8ecb83cfb1da2 | leaderboard/leaderboard.py | python | Leaderboard.total_members_in_score_range | (self, min_score, max_score) | return self.total_members_in_score_range_in(
self.leaderboard_name, min_score, max_score) | Retrieve the total members in a given score range from the leaderboard.
@param min_score [float] Minimum score.
@param max_score [float] Maximum score.
@return the total members in a given score range from the leaderboard. | Retrieve the total members in a given score range from the leaderboard. | [
"Retrieve",
"the",
"total",
"members",
"in",
"a",
"given",
"score",
"range",
"from",
"the",
"leaderboard",
"."
] | def total_members_in_score_range(self, min_score, max_score):
'''
Retrieve the total members in a given score range from the leaderboard.
@param min_score [float] Minimum score.
@param max_score [float] Maximum score.
@return the total members in a given score range from the leaderboard.
'''
return self.total_members_in_score_range_in(
self.leaderboard_name, min_score, max_score) | [
"def",
"total_members_in_score_range",
"(",
"self",
",",
"min_score",
",",
"max_score",
")",
":",
"return",
"self",
".",
"total_members_in_score_range_in",
"(",
"self",
".",
"leaderboard_name",
",",
"min_score",
",",
"max_score",
")"
] | https://github.com/agoragames/leaderboard-python/blob/4bc028164c259c3a31c7e6ccb2a8ecb83cfb1da2/leaderboard/leaderboard.py#L392-L401 | |
Fuyukai/Kyoukai | 44d47f4b0ece1c509fc5116275982df63ca09438 | kyoukai/backends/http2.py | python | H2KyoukaiProtocol.close | (self, error_code: int=0) | Called to terminate the connection for some reason.
This will close the underlying transport. | Called to terminate the connection for some reason. | [
"Called",
"to",
"terminate",
"the",
"connection",
"for",
"some",
"reason",
"."
] | def close(self, error_code: int=0):
"""
Called to terminate the connection for some reason.
This will close the underlying transport.
"""
# Send a GOAWAY frame.
self.conn.close_connection(error_code)
self.raw_write(self.conn.data_to_send())
self.transport.close() | [
"def",
"close",
"(",
"self",
",",
"error_code",
":",
"int",
"=",
"0",
")",
":",
"# Send a GOAWAY frame.",
"self",
".",
"conn",
".",
"close_connection",
"(",
"error_code",
")",
"self",
".",
"raw_write",
"(",
"self",
".",
"conn",
".",
"data_to_send",
"(",
... | https://github.com/Fuyukai/Kyoukai/blob/44d47f4b0ece1c509fc5116275982df63ca09438/kyoukai/backends/http2.py#L532-L542 | ||
pypa/pipenv | b21baade71a86ab3ee1429f71fbc14d4f95fb75d | pipenv/patched/notpip/_vendor/urllib3/util/ssltransport.py | python | SSLTransport.send | (self, data, flags=0) | return response | [] | def send(self, data, flags=0):
if flags != 0:
raise ValueError("non-zero flags not allowed in calls to send")
response = self._ssl_io_loop(self.sslobj.write, data)
return response | [
"def",
"send",
"(",
"self",
",",
"data",
",",
"flags",
"=",
"0",
")",
":",
"if",
"flags",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"\"non-zero flags not allowed in calls to send\"",
")",
"response",
"=",
"self",
".",
"_ssl_io_loop",
"(",
"self",
".",
"s... | https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/patched/notpip/_vendor/urllib3/util/ssltransport.py#L99-L103 | |||
fake-name/ReadableWebProxy | ed5c7abe38706acc2684a1e6cd80242a03c5f010 | amqpstorm/base.py | python | Stateful.exceptions | (self) | return self._exceptions | Stores all exceptions thrown by this instance.
This is useful for troubleshooting, and is used internally
to check the health of the connection.
:rtype: list | Stores all exceptions thrown by this instance. | [
"Stores",
"all",
"exceptions",
"thrown",
"by",
"this",
"instance",
"."
] | def exceptions(self):
"""Stores all exceptions thrown by this instance.
This is useful for troubleshooting, and is used internally
to check the health of the connection.
:rtype: list
"""
return self._exceptions | [
"def",
"exceptions",
"(",
"self",
")",
":",
"return",
"self",
".",
"_exceptions"
] | https://github.com/fake-name/ReadableWebProxy/blob/ed5c7abe38706acc2684a1e6cd80242a03c5f010/amqpstorm/base.py#L85-L93 | |
rwightman/pytorch-image-models | ccfeb06936549f19c453b7f1f27e8e632cfbe1c2 | timm/models/efficientnet.py | python | efficientnet_em | (pretrained=False, **kwargs) | return model | EfficientNet-Edge-Medium. | EfficientNet-Edge-Medium. | [
"EfficientNet",
"-",
"Edge",
"-",
"Medium",
"."
] | def efficientnet_em(pretrained=False, **kwargs):
""" EfficientNet-Edge-Medium. """
model = _gen_efficientnet_edge(
'efficientnet_em', channel_multiplier=1.0, depth_multiplier=1.1, pretrained=pretrained, **kwargs)
return model | [
"def",
"efficientnet_em",
"(",
"pretrained",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"model",
"=",
"_gen_efficientnet_edge",
"(",
"'efficientnet_em'",
",",
"channel_multiplier",
"=",
"1.0",
",",
"depth_multiplier",
"=",
"1.1",
",",
"pretrained",
"=",
... | https://github.com/rwightman/pytorch-image-models/blob/ccfeb06936549f19c453b7f1f27e8e632cfbe1c2/timm/models/efficientnet.py#L1458-L1462 | |
pypa/setuptools | 9f37366aab9cd8f6baa23e6a77cfdb8daf97757e | setuptools/_vendor/pyparsing.py | python | dictOf | ( key, value ) | return Dict( ZeroOrMore( Group ( key + value ) ) ) | Helper to easily and clearly define a dictionary by specifying the respective patterns
for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens
in the proper order. The key pattern can include delimiting markers or punctuation,
as long as they are suppressed, thereby leaving the significant key text. The value
pattern can include named results, so that the C{Dict} results can include named token
fields.
Example::
text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
print(OneOrMore(attr_expr).parseString(text).dump())
attr_label = label
attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)
# similar to Dict, but simpler call format
result = dictOf(attr_label, attr_value).parseString(text)
print(result.dump())
print(result['shape'])
print(result.shape) # object attribute access works too
print(result.asDict())
prints::
[['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
- color: light blue
- posn: upper left
- shape: SQUARE
- texture: burlap
SQUARE
SQUARE
{'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'} | Helper to easily and clearly define a dictionary by specifying the respective patterns
for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens
in the proper order. The key pattern can include delimiting markers or punctuation,
as long as they are suppressed, thereby leaving the significant key text. The value
pattern can include named results, so that the C{Dict} results can include named token
fields. | [
"Helper",
"to",
"easily",
"and",
"clearly",
"define",
"a",
"dictionary",
"by",
"specifying",
"the",
"respective",
"patterns",
"for",
"the",
"key",
"and",
"value",
".",
"Takes",
"care",
"of",
"defining",
"the",
"C",
"{",
"L",
"{",
"Dict",
"}}",
"C",
"{",
... | def dictOf( key, value ):
"""
Helper to easily and clearly define a dictionary by specifying the respective patterns
for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens
in the proper order. The key pattern can include delimiting markers or punctuation,
as long as they are suppressed, thereby leaving the significant key text. The value
pattern can include named results, so that the C{Dict} results can include named token
fields.
Example::
text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
print(OneOrMore(attr_expr).parseString(text).dump())
attr_label = label
attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)
# similar to Dict, but simpler call format
result = dictOf(attr_label, attr_value).parseString(text)
print(result.dump())
print(result['shape'])
print(result.shape) # object attribute access works too
print(result.asDict())
prints::
[['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
- color: light blue
- posn: upper left
- shape: SQUARE
- texture: burlap
SQUARE
SQUARE
{'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'}
"""
return Dict( ZeroOrMore( Group ( key + value ) ) ) | [
"def",
"dictOf",
"(",
"key",
",",
"value",
")",
":",
"return",
"Dict",
"(",
"ZeroOrMore",
"(",
"Group",
"(",
"key",
"+",
"value",
")",
")",
")"
] | https://github.com/pypa/setuptools/blob/9f37366aab9cd8f6baa23e6a77cfdb8daf97757e/setuptools/_vendor/pyparsing.py#L4646-L4679 | |
anki/vector-python-sdk | d61fdb07c6278deba750f987b20441fff2df865f | anki_vector/opengl/opengl_viewer.py | python | _OpenGLViewController.initialize | (self) | Sets up the OpenGL window and binds input callbacks to it | Sets up the OpenGL window and binds input callbacks to it | [
"Sets",
"up",
"the",
"OpenGL",
"window",
"and",
"binds",
"input",
"callbacks",
"to",
"it"
] | def initialize(self):
"""Sets up the OpenGL window and binds input callbacks to it
"""
glutKeyboardFunc(self._on_key_down)
glutSpecialFunc(self._on_special_key_down)
# [Keyboard/Special]Up methods aren't supported on some old GLUT implementations
has_keyboard_up = False
has_special_up = False
try:
if bool(glutKeyboardUpFunc):
glutKeyboardUpFunc(self._on_key_up)
has_keyboard_up = True
if bool(glutSpecialUpFunc):
glutSpecialUpFunc(self._on_special_key_up)
has_special_up = True
except NullFunctionError:
# Methods aren't available on this GLUT version
pass
if not has_keyboard_up or not has_special_up:
# Warn on old GLUT implementations that don't implement much of the interface.
self._logger.warning("Warning: Old GLUT implementation detected - keyboard remote control of Vector disabled."
"We recommend installing freeglut. %s", _glut_install_instructions())
self._is_keyboard_control_enabled = False
else:
self._is_keyboard_control_enabled = True
try:
GLUT_BITMAP_9_BY_15
except NameError:
self._logger.warning("Warning: GLUT font not detected. Help message will be unavailable.")
glutMouseFunc(self._on_mouse_button)
glutMotionFunc(self._on_mouse_move)
glutPassiveMotionFunc(self._on_mouse_move)
glutIdleFunc(self._idle)
glutVisibilityFunc(self._visible) | [
"def",
"initialize",
"(",
"self",
")",
":",
"glutKeyboardFunc",
"(",
"self",
".",
"_on_key_down",
")",
"glutSpecialFunc",
"(",
"self",
".",
"_on_special_key_down",
")",
"# [Keyboard/Special]Up methods aren't supported on some old GLUT implementations",
"has_keyboard_up",
"=",... | https://github.com/anki/vector-python-sdk/blob/d61fdb07c6278deba750f987b20441fff2df865f/anki_vector/opengl/opengl_viewer.py#L179-L218 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/Python-2.7.9/Demo/parser/unparse.py | python | Unparser._Compare | (self, t) | [] | def _Compare(self, t):
self.write("(")
self.dispatch(t.left)
for o, e in zip(t.ops, t.comparators):
self.write(" " + self.cmpops[o.__class__.__name__] + " ")
self.dispatch(e)
self.write(")") | [
"def",
"_Compare",
"(",
"self",
",",
"t",
")",
":",
"self",
".",
"write",
"(",
"\"(\"",
")",
"self",
".",
"dispatch",
"(",
"t",
".",
"left",
")",
"for",
"o",
",",
"e",
"in",
"zip",
"(",
"t",
".",
"ops",
",",
"t",
".",
"comparators",
")",
":",... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Demo/parser/unparse.py#L452-L458 | ||||
twilio/twilio-python | 6e1e811ea57a1edfadd5161ace87397c563f6915 | twilio/rest/ip_messaging/v1/service/user/__init__.py | python | UserPage.__repr__ | (self) | return '<Twilio.IpMessaging.V1.UserPage>' | Provide a friendly representation
:returns: Machine friendly representation
:rtype: str | Provide a friendly representation | [
"Provide",
"a",
"friendly",
"representation"
] | def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.IpMessaging.V1.UserPage>' | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"'<Twilio.IpMessaging.V1.UserPage>'"
] | https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/ip_messaging/v1/service/user/__init__.py#L198-L205 | |
SciTools/iris | a12d0b15bab3377b23a148e891270b13a0419c38 | lib/iris/util.py | python | rolling_window | (a, window=1, step=1, axis=-1) | return rw | Make an ndarray with a rolling window of the last dimension
Args:
* a : array_like
Array to add rolling window to
Kwargs:
* window : int
Size of rolling window
* step : int
Size of step between rolling windows
* axis : int
Axis to take the rolling window over
Returns:
Array that is a view of the original array with an added dimension
of the size of the given window at axis + 1.
Examples::
>>> x = np.arange(10).reshape((2, 5))
>>> rolling_window(x, 3)
array([[[0, 1, 2], [1, 2, 3], [2, 3, 4]],
[[5, 6, 7], [6, 7, 8], [7, 8, 9]]])
Calculate rolling mean of last dimension::
>>> np.mean(rolling_window(x, 3), -1)
array([[ 1., 2., 3.],
[ 6., 7., 8.]]) | Make an ndarray with a rolling window of the last dimension | [
"Make",
"an",
"ndarray",
"with",
"a",
"rolling",
"window",
"of",
"the",
"last",
"dimension"
] | def rolling_window(a, window=1, step=1, axis=-1):
"""
Make an ndarray with a rolling window of the last dimension
Args:
* a : array_like
Array to add rolling window to
Kwargs:
* window : int
Size of rolling window
* step : int
Size of step between rolling windows
* axis : int
Axis to take the rolling window over
Returns:
Array that is a view of the original array with an added dimension
of the size of the given window at axis + 1.
Examples::
>>> x = np.arange(10).reshape((2, 5))
>>> rolling_window(x, 3)
array([[[0, 1, 2], [1, 2, 3], [2, 3, 4]],
[[5, 6, 7], [6, 7, 8], [7, 8, 9]]])
Calculate rolling mean of last dimension::
>>> np.mean(rolling_window(x, 3), -1)
array([[ 1., 2., 3.],
[ 6., 7., 8.]])
"""
# NOTE: The implementation of this function originates from
# https://github.com/numpy/numpy/pull/31#issuecomment-1304851 04/08/2011
if window < 1:
raise ValueError("`window` must be at least 1.")
if window > a.shape[axis]:
raise ValueError("`window` is too long.")
if step < 1:
raise ValueError("`step` must be at least 1.")
axis = axis % a.ndim
num_windows = (a.shape[axis] - window + step) // step
shape = a.shape[:axis] + (num_windows, window) + a.shape[axis + 1 :]
strides = (
a.strides[:axis]
+ (step * a.strides[axis], a.strides[axis])
+ a.strides[axis + 1 :]
)
rw = np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
if ma.isMaskedArray(a):
mask = ma.getmaskarray(a)
strides = (
mask.strides[:axis]
+ (step * mask.strides[axis], mask.strides[axis])
+ mask.strides[axis + 1 :]
)
rw = ma.array(
rw,
mask=np.lib.stride_tricks.as_strided(
mask, shape=shape, strides=strides
),
)
return rw | [
"def",
"rolling_window",
"(",
"a",
",",
"window",
"=",
"1",
",",
"step",
"=",
"1",
",",
"axis",
"=",
"-",
"1",
")",
":",
"# NOTE: The implementation of this function originates from",
"# https://github.com/numpy/numpy/pull/31#issuecomment-1304851 04/08/2011",
"if",
"windo... | https://github.com/SciTools/iris/blob/a12d0b15bab3377b23a148e891270b13a0419c38/lib/iris/util.py#L272-L339 | |
kanzure/nanoengineer | 874e4c9f8a9190f093625b267f9767e19f82e6c4 | cad/src/graphics/rendering/mdl/writemdlfile.py | python | writemdlfile | (part, glpane, filename) | return | write the given part into a new MDL file with the given name,
using glpane.displayMode | write the given part into a new MDL file with the given name,
using glpane.displayMode | [
"write",
"the",
"given",
"part",
"into",
"a",
"new",
"MDL",
"file",
"with",
"the",
"given",
"name",
"using",
"glpane",
".",
"displayMode"
] | def writemdlfile(part, glpane, filename): #bruce 050927 replaced assy argument with part and glpane args, added docstring
"""
write the given part into a new MDL file with the given name,
using glpane.displayMode
"""
alist = [] #bruce 050325 changed assy.alist to localvar alist
natoms = 0
# Specular values keyed by atom color
# Only Carbon, Hydrogen and Silicon supported here
specValues = {(117,117,117):((183, 183, 183), 16, 44), \
(256,256,256):((183, 183, 183), 15, 44), \
(111,93,133):((187,176,200), 16, 44)}
# Determine the number of visible atoms in the part.
# Invisible atoms are drawn. Hidden atoms are not drawn.
# This is a bug to be fixed in the future. Will require work in chunk/chem.writemdl, too.
# writepov may have this problem, too.
# Mark [04-12-05]
# To test this, we need to get a copy of Animation Master.
# Mark [05-01-14]
for mol in part.molecules:
if (not mol.hidden) and (mol.display != diINVISIBLE): natoms += len(mol.atoms) #bruce 050421 disp->display (bugfix?)
f = open(filename, 'w');
# Write the header
f.write(mdlheader)
# Write atoms with spline coordinates
f.write("Splines=%d\n"%(13*natoms))
part.topnode.writemdl(alist, f, glpane.displayMode)
#bruce 050421 changed assy.tree to assy.part.topnode to fix an assy/part bug
#bruce 050927 changed assy.part -> new part arg
# Write the GROUP information
# Currently, each atom is
f.write("[ENDMESH]\n[GROUPS]\n")
atomindex = 0
for mol in part.molecules:
col = mol.color # Color of molecule
for a in mol.atoms.values():
# Begin GROUP record for this atom.
f.write("[GROUP]\nName=Atom%d\nCount=80\n"%atomindex)
# Write atom mesh IDs
for j in range(80):
f.write("%d\n"%(98-j+atomindex*80))
# Write Pivot record for this atom.
# print "a.pos = ", a.posn()
xyz=a.posn()
n=(float(xyz[0]), float(xyz[1]), float(xyz[2]))
f.write("Pivot= %f %f %f\n" % n)
# Add DiffuseColor record for this atom.
color = col or a.element.color
# if this was color = a.drawing_color() it would mess up the specularity lookup below;
# could be fixed somehow... [bruce 070417 comment]
rgb=map(int,A(color)*255) # rgb = 3-tuple of int
color=(int(rgb[0]), int(rgb[1]), int(rgb[2]))
f.write("DiffuseColor=%d %d %d\n"%color)
# Added specularity per John Burch's request
# Specular values keyed by atom color
(specColor, specSize, specIntensity) = \
specValues.get(color, ((183,183,183),16,44))
f.write("SpecularColor=%d %d %d\n"%specColor)
f.write("SpecularSize=%d\n"%specSize)
f.write("SpecularIntensity=%d\n"%specIntensity)
# End the group for this atom.
f.write("[ENDGROUP]\n")
atomindex += 1
# ENDGROUPS
f.write("[ENDGROUPS]\n")
# Write the footer and close
fpos = f.tell()
f.write(mdlfooter)
f.write("FileInfoPos=%d\n"%fpos)
f.close()
return | [
"def",
"writemdlfile",
"(",
"part",
",",
"glpane",
",",
"filename",
")",
":",
"#bruce 050927 replaced assy argument with part and glpane args, added docstring",
"alist",
"=",
"[",
"]",
"#bruce 050325 changed assy.alist to localvar alist",
"natoms",
"=",
"0",
"# Specular values ... | https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/graphics/rendering/mdl/writemdlfile.py#L28-L115 | |
pyparallel/pyparallel | 11e8c6072d48c8f13641925d17b147bf36ee0ba3 | Lib/datetime.py | python | date.year | (self) | return self._year | year (1-9999) | year (1-9999) | [
"year",
"(",
"1",
"-",
"9999",
")"
] | def year(self):
"""year (1-9999)"""
return self._year | [
"def",
"year",
"(",
"self",
")",
":",
"return",
"self",
".",
"_year"
] | https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/datetime.py#L744-L746 | |
IBM/lale | b4d6829c143a4735b06083a0e6c70d2cca244162 | lale/operators.py | python | make_union | (*orig_steps) | return make_union_no_concat(*orig_steps) >> ConcatFeatures() | [] | def make_union(*orig_steps): # type: ignore
from lale.lib.lale import ConcatFeatures
return make_union_no_concat(*orig_steps) >> ConcatFeatures() | [
"def",
"make_union",
"(",
"*",
"orig_steps",
")",
":",
"# type: ignore",
"from",
"lale",
".",
"lib",
".",
"lale",
"import",
"ConcatFeatures",
"return",
"make_union_no_concat",
"(",
"*",
"orig_steps",
")",
">>",
"ConcatFeatures",
"(",
")"
] | https://github.com/IBM/lale/blob/b4d6829c143a4735b06083a0e6c70d2cca244162/lale/operators.py#L5403-L5406 | |||
PaddlePaddle/PaddleX | 2bab73f81ab54e328204e7871e6ae4a82e719f5d | static/paddlex_restful/restful/project/evaluate/detection.py | python | DetEvaluator.__init__ | (self, model_path, overlap_thresh=0.5, score_threshold=0.3) | [] | def __init__(self, model_path, overlap_thresh=0.5, score_threshold=0.3):
self.model_path = model_path
self.overlap_thresh = overlap_thresh if overlap_thresh is not None else .5
self.score_threshold = score_threshold if score_threshold is not None else .3 | [
"def",
"__init__",
"(",
"self",
",",
"model_path",
",",
"overlap_thresh",
"=",
"0.5",
",",
"score_threshold",
"=",
"0.3",
")",
":",
"self",
".",
"model_path",
"=",
"model_path",
"self",
".",
"overlap_thresh",
"=",
"overlap_thresh",
"if",
"overlap_thresh",
"is"... | https://github.com/PaddlePaddle/PaddleX/blob/2bab73f81ab54e328204e7871e6ae4a82e719f5d/static/paddlex_restful/restful/project/evaluate/detection.py#L406-L409 | ||||
aws/sagemaker-python-sdk | 9d259b316f7f43838c16f35c10e98a110b56735b | src/sagemaker/local/image.py | python | _delete_tree | (path) | Makes a call to `shutil.rmtree` for the given path.
Args:
path: | Makes a call to `shutil.rmtree` for the given path. | [
"Makes",
"a",
"call",
"to",
"shutil",
".",
"rmtree",
"for",
"the",
"given",
"path",
"."
] | def _delete_tree(path):
"""Makes a call to `shutil.rmtree` for the given path.
Args:
path:
"""
try:
shutil.rmtree(path)
except OSError as exc:
# on Linux, when docker writes to any mounted volume, it uses the container's user. In most
# cases this is root. When the container exits and we try to delete them we can't because
# root owns those files. We expect this to happen, so we handle EACCESS. Any other error
# we will raise the exception up.
if exc.errno == errno.EACCES:
logger.warning("Failed to delete: %s Please remove it manually.", path)
else:
logger.error("Failed to delete: %s", path)
raise | [
"def",
"_delete_tree",
"(",
"path",
")",
":",
"try",
":",
"shutil",
".",
"rmtree",
"(",
"path",
")",
"except",
"OSError",
"as",
"exc",
":",
"# on Linux, when docker writes to any mounted volume, it uses the container's user. In most",
"# cases this is root. When the container... | https://github.com/aws/sagemaker-python-sdk/blob/9d259b316f7f43838c16f35c10e98a110b56735b/src/sagemaker/local/image.py#L952-L969 | ||
scikit-learn/scikit-learn | 1d1aadd0711b87d2a11c80aad15df6f8cf156712 | sklearn/manifold/_t_sne.py | python | TSNE._tsne | (
self,
P,
degrees_of_freedom,
n_samples,
X_embedded,
neighbors=None,
skip_num_points=0,
) | return X_embedded | Runs t-SNE. | Runs t-SNE. | [
"Runs",
"t",
"-",
"SNE",
"."
] | def _tsne(
self,
P,
degrees_of_freedom,
n_samples,
X_embedded,
neighbors=None,
skip_num_points=0,
):
"""Runs t-SNE."""
# t-SNE minimizes the Kullback-Leiber divergence of the Gaussians P
# and the Student's t-distributions Q. The optimization algorithm that
# we use is batch gradient descent with two stages:
# * initial optimization with early exaggeration and momentum at 0.5
# * final optimization with momentum at 0.8
params = X_embedded.ravel()
opt_args = {
"it": 0,
"n_iter_check": self._N_ITER_CHECK,
"min_grad_norm": self.min_grad_norm,
"learning_rate": self._learning_rate,
"verbose": self.verbose,
"kwargs": dict(skip_num_points=skip_num_points),
"args": [P, degrees_of_freedom, n_samples, self.n_components],
"n_iter_without_progress": self._EXPLORATION_N_ITER,
"n_iter": self._EXPLORATION_N_ITER,
"momentum": 0.5,
}
if self.method == "barnes_hut":
obj_func = _kl_divergence_bh
opt_args["kwargs"]["angle"] = self.angle
# Repeat verbose argument for _kl_divergence_bh
opt_args["kwargs"]["verbose"] = self.verbose
# Get the number of threads for gradient computation here to
# avoid recomputing it at each iteration.
opt_args["kwargs"]["num_threads"] = _openmp_effective_n_threads()
else:
obj_func = _kl_divergence
# Learning schedule (part 1): do 250 iteration with lower momentum but
# higher learning rate controlled via the early exaggeration parameter
P *= self.early_exaggeration
params, kl_divergence, it = _gradient_descent(obj_func, params, **opt_args)
if self.verbose:
print(
"[t-SNE] KL divergence after %d iterations with early exaggeration: %f"
% (it + 1, kl_divergence)
)
# Learning schedule (part 2): disable early exaggeration and finish
# optimization with a higher momentum at 0.8
P /= self.early_exaggeration
remaining = self.n_iter - self._EXPLORATION_N_ITER
if it < self._EXPLORATION_N_ITER or remaining > 0:
opt_args["n_iter"] = self.n_iter
opt_args["it"] = it + 1
opt_args["momentum"] = 0.8
opt_args["n_iter_without_progress"] = self.n_iter_without_progress
params, kl_divergence, it = _gradient_descent(obj_func, params, **opt_args)
# Save the final number of iterations
self.n_iter_ = it
if self.verbose:
print(
"[t-SNE] KL divergence after %d iterations: %f"
% (it + 1, kl_divergence)
)
X_embedded = params.reshape(n_samples, self.n_components)
self.kl_divergence_ = kl_divergence
return X_embedded | [
"def",
"_tsne",
"(",
"self",
",",
"P",
",",
"degrees_of_freedom",
",",
"n_samples",
",",
"X_embedded",
",",
"neighbors",
"=",
"None",
",",
"skip_num_points",
"=",
"0",
",",
")",
":",
"# t-SNE minimizes the Kullback-Leiber divergence of the Gaussians P",
"# and the Stu... | https://github.com/scikit-learn/scikit-learn/blob/1d1aadd0711b87d2a11c80aad15df6f8cf156712/sklearn/manifold/_t_sne.py#L1015-L1088 | |
codelv/enaml-native | 04c3a015bcd649f374c5ecd98fcddba5e4fbdbdc | src/enamlnative/android/android_wifi.py | python | WifiManager.__del__ | (self) | Remove any receivers before destroying | Remove any receivers before destroying | [
"Remove",
"any",
"receivers",
"before",
"destroying"
] | def __del__(self):
""" Remove any receivers before destroying """
app = AndroidApplication.instance()
activity = app.widget
for r in self._receivers:
activity.unregisterReceiver(r)
super(WifiManager, self).__del__() | [
"def",
"__del__",
"(",
"self",
")",
":",
"app",
"=",
"AndroidApplication",
".",
"instance",
"(",
")",
"activity",
"=",
"app",
".",
"widget",
"for",
"r",
"in",
"self",
".",
"_receivers",
":",
"activity",
".",
"unregisterReceiver",
"(",
"r",
")",
"super",
... | https://github.com/codelv/enaml-native/blob/04c3a015bcd649f374c5ecd98fcddba5e4fbdbdc/src/enamlnative/android/android_wifi.py#L419-L425 | ||
deepfakes/faceswap | 09c7d8aca3c608d1afad941ea78e9fd9b64d9219 | lib/gui/custom_widgets.py | python | PopupProgress.progress_bar | (self) | return self._progress_bar | :class:`tkinter.ttk.Progressbar`: The progress bar object within the pop up window. | :class:`tkinter.ttk.Progressbar`: The progress bar object within the pop up window. | [
":",
"class",
":",
"tkinter",
".",
"ttk",
".",
"Progressbar",
":",
"The",
"progress",
"bar",
"object",
"within",
"the",
"pop",
"up",
"window",
"."
] | def progress_bar(self):
""" :class:`tkinter.ttk.Progressbar`: The progress bar object within the pop up window. """
return self._progress_bar | [
"def",
"progress_bar",
"(",
"self",
")",
":",
"return",
"self",
".",
"_progress_bar"
] | https://github.com/deepfakes/faceswap/blob/09c7d8aca3c608d1afad941ea78e9fd9b64d9219/lib/gui/custom_widgets.py#L827-L829 | |
ctxis/canape | 5f0e03424577296bcc60c2008a60a98ec5307e4b | CANAPE.Scripting/Lib/SimpleHTTPServer.py | python | SimpleHTTPRequestHandler.guess_type | (self, path) | Guess the type of a file.
Argument is a PATH (a filename).
Return value is a string of the form type/subtype,
usable for a MIME Content-type header.
The default implementation looks the file's extension
up in the table self.extensions_map, using application/octet-stream
as a default; however it would be permissible (if
slow) to look inside the data to make a better guess. | Guess the type of a file. | [
"Guess",
"the",
"type",
"of",
"a",
"file",
"."
] | def guess_type(self, path):
"""Guess the type of a file.
Argument is a PATH (a filename).
Return value is a string of the form type/subtype,
usable for a MIME Content-type header.
The default implementation looks the file's extension
up in the table self.extensions_map, using application/octet-stream
as a default; however it would be permissible (if
slow) to look inside the data to make a better guess.
"""
base, ext = posixpath.splitext(path)
if ext in self.extensions_map:
return self.extensions_map[ext]
ext = ext.lower()
if ext in self.extensions_map:
return self.extensions_map[ext]
else:
return self.extensions_map[''] | [
"def",
"guess_type",
"(",
"self",
",",
"path",
")",
":",
"base",
",",
"ext",
"=",
"posixpath",
".",
"splitext",
"(",
"path",
")",
"if",
"ext",
"in",
"self",
".",
"extensions_map",
":",
"return",
"self",
".",
"extensions_map",
"[",
"ext",
"]",
"ext",
... | https://github.com/ctxis/canape/blob/5f0e03424577296bcc60c2008a60a98ec5307e4b/CANAPE.Scripting/Lib/SimpleHTTPServer.py#L179-L201 | ||
leo-editor/leo-editor | 383d6776d135ef17d73d935a2f0ecb3ac0e99494 | leo/core/format-code.py | python | formatController.underline | (self,s,p) | return '%s\n%s\n\n' % (p.h.strip(),ch*n) | Return the underlining string to be used at the given level for string s. | Return the underlining string to be used at the given level for string s. | [
"Return",
"the",
"underlining",
"string",
"to",
"be",
"used",
"at",
"the",
"given",
"level",
"for",
"string",
"s",
"."
] | def underline (self,s,p):
'''Return the underlining string to be used at the given level for string s.'''
trace = False and not g.unitTesting
# The user is responsible for top-level overlining.
u = self.getOption('underline_characters') # '''#=+*^~"'`-:><_'''
level = max(0,p.level()-self.topLevel)
level = min(level+1,len(u)-1) # Reserve the first character for explicit titles.
ch = u [level]
if trace: g.trace(self.topLevel,p.level(),level,repr(ch),p.h)
n = max(4,len(g.toEncodedString(s,encoding=self.encoding,reportErrors=False)))
return '%s\n%s\n\n' % (p.h.strip(),ch*n) | [
"def",
"underline",
"(",
"self",
",",
"s",
",",
"p",
")",
":",
"trace",
"=",
"False",
"and",
"not",
"g",
".",
"unitTesting",
"# The user is responsible for top-level overlining.",
"u",
"=",
"self",
".",
"getOption",
"(",
"'underline_characters'",
")",
"# '''#=+... | https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/core/format-code.py#L339-L352 | |
studioimaginaire/phue | 8ea25484176c3055a30469361977d4bc83ca2a83 | phue.py | python | Light.brightness | (self) | return self._brightness | Get or set the brightness of the light [0-254].
0 is not off | Get or set the brightness of the light [0-254]. | [
"Get",
"or",
"set",
"the",
"brightness",
"of",
"the",
"light",
"[",
"0",
"-",
"254",
"]",
"."
] | def brightness(self):
'''Get or set the brightness of the light [0-254].
0 is not off'''
self._brightness = self._get('bri')
return self._brightness | [
"def",
"brightness",
"(",
"self",
")",
":",
"self",
".",
"_brightness",
"=",
"self",
".",
"_get",
"(",
"'bri'",
")",
"return",
"self",
".",
"_brightness"
] | https://github.com/studioimaginaire/phue/blob/8ea25484176c3055a30469361977d4bc83ca2a83/phue.py#L189-L195 | |
replit-archive/empythoned | 977ec10ced29a3541a4973dc2b59910805695752 | dist/lib/python2.7/mhlib.py | python | Folder.__init__ | (self, mh, name) | Constructor. | Constructor. | [
"Constructor",
"."
] | def __init__(self, mh, name):
"""Constructor."""
self.mh = mh
self.name = name
if not os.path.isdir(self.getfullname()):
raise Error, 'no folder %s' % name | [
"def",
"__init__",
"(",
"self",
",",
"mh",
",",
"name",
")",
":",
"self",
".",
"mh",
"=",
"mh",
"self",
".",
"name",
"=",
"name",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"getfullname",
"(",
")",
")",
":",
"raise",
"Error... | https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/dist/lib/python2.7/mhlib.py#L245-L250 | ||
mpescimoro/wi-finder | d19c22d662d60da9f51795cad5cbb7042142a2b8 | nmap/nmap.py | python | PortScannerAsync.wait | (self, timeout=None) | return | Wait for the current scan process to finish, or timeout
:param timeout: default = None, wait timeout seconds | Wait for the current scan process to finish, or timeout | [
"Wait",
"for",
"the",
"current",
"scan",
"process",
"to",
"finish",
"or",
"timeout"
] | def wait(self, timeout=None):
"""
Wait for the current scan process to finish, or timeout
:param timeout: default = None, wait timeout seconds
"""
assert type(timeout) in (int, type(None)), 'Wrong type for [timeout], should be an int or None [was {0}]'.format(type(timeout))
self._process.join(timeout)
return | [
"def",
"wait",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"assert",
"type",
"(",
"timeout",
")",
"in",
"(",
"int",
",",
"type",
"(",
"None",
")",
")",
",",
"'Wrong type for [timeout], should be an int or None [was {0}]'",
".",
"format",
"(",
"type",... | https://github.com/mpescimoro/wi-finder/blob/d19c22d662d60da9f51795cad5cbb7042142a2b8/nmap/nmap.py#L771-L782 | |
apache/superset | 3d829fc3c838358dd8c798ecaeefd34c502edca0 | superset/datasets/api.py | python | DatasetRestApi.refresh | (self, pk: int) | Refresh a Dataset
---
put:
description: >-
Refreshes and updates columns of a dataset
parameters:
- in: path
schema:
type: integer
name: pk
responses:
200:
description: Dataset delete
content:
application/json:
schema:
type: object
properties:
message:
type: string
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500' | Refresh a Dataset
---
put:
description: >-
Refreshes and updates columns of a dataset
parameters:
- in: path
schema:
type: integer
name: pk
responses:
200:
description: Dataset delete
content:
application/json:
schema:
type: object
properties:
message:
type: string
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500' | [
"Refresh",
"a",
"Dataset",
"---",
"put",
":",
"description",
":",
">",
"-",
"Refreshes",
"and",
"updates",
"columns",
"of",
"a",
"dataset",
"parameters",
":",
"-",
"in",
":",
"path",
"schema",
":",
"type",
":",
"integer",
"name",
":",
"pk",
"responses",
... | def refresh(self, pk: int) -> Response:
"""Refresh a Dataset
---
put:
description: >-
Refreshes and updates columns of a dataset
parameters:
- in: path
schema:
type: integer
name: pk
responses:
200:
description: Dataset delete
content:
application/json:
schema:
type: object
properties:
message:
type: string
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
try:
RefreshDatasetCommand(g.user, pk).run()
return self.response(200, message="OK")
except DatasetNotFoundError:
return self.response_404()
except DatasetForbiddenError:
return self.response_403()
except DatasetRefreshFailedError as ex:
logger.error(
"Error refreshing dataset %s: %s",
self.__class__.__name__,
str(ex),
exc_info=True,
)
return self.response_422(message=str(ex)) | [
"def",
"refresh",
"(",
"self",
",",
"pk",
":",
"int",
")",
"->",
"Response",
":",
"try",
":",
"RefreshDatasetCommand",
"(",
"g",
".",
"user",
",",
"pk",
")",
".",
"run",
"(",
")",
"return",
"self",
".",
"response",
"(",
"200",
",",
"message",
"=",
... | https://github.com/apache/superset/blob/3d829fc3c838358dd8c798ecaeefd34c502edca0/superset/datasets/api.py#L503-L549 | ||
FederatedAI/FATE | 32540492623568ecd1afcb367360133616e02fa3 | python/federatedml/param/base_param.py | python | BaseParam._range | (value, ranges) | return in_range | [] | def _range(value, ranges):
in_range = False
for left_limit, right_limit in ranges:
if (
left_limit - consts.FLOAT_ZERO
<= value
<= right_limit + consts.FLOAT_ZERO
):
in_range = True
break
return in_range | [
"def",
"_range",
"(",
"value",
",",
"ranges",
")",
":",
"in_range",
"=",
"False",
"for",
"left_limit",
",",
"right_limit",
"in",
"ranges",
":",
"if",
"(",
"left_limit",
"-",
"consts",
".",
"FLOAT_ZERO",
"<=",
"value",
"<=",
"right_limit",
"+",
"consts",
... | https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/federatedml/param/base_param.py#L345-L356 | |||
sabnzbd/sabnzbd | 52d21e94d3cc6e30764a833fe2a256783d1a8931 | builder/package.py | python | patch_version_file | (release_name) | Patch in the Git commit hash, but only when this is
an unmodified checkout | Patch in the Git commit hash, but only when this is
an unmodified checkout | [
"Patch",
"in",
"the",
"Git",
"commit",
"hash",
"but",
"only",
"when",
"this",
"is",
"an",
"unmodified",
"checkout"
] | def patch_version_file(release_name):
"""Patch in the Git commit hash, but only when this is
an unmodified checkout
"""
git_output = run_git_command(["log", "-1"])
for line in git_output.split("\n"):
if "commit " in line:
commit = line.split(" ")[1].strip()
break
else:
raise TypeError("Commit hash not found")
with open(VERSION_FILE, "r") as ver:
version_file = ver.read()
version_file = re.sub(r'__baseline__\s*=\s*"[^"]*"', '__baseline__ = "%s"' % commit, version_file)
version_file = re.sub(r'__version__\s*=\s*"[^"]*"', '__version__ = "%s"' % release_name, version_file)
with open(VERSION_FILE, "w") as ver:
ver.write(version_file) | [
"def",
"patch_version_file",
"(",
"release_name",
")",
":",
"git_output",
"=",
"run_git_command",
"(",
"[",
"\"log\"",
",",
"\"-1\"",
"]",
")",
"for",
"line",
"in",
"git_output",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"if",
"\"commit \"",
"in",
"line",
":... | https://github.com/sabnzbd/sabnzbd/blob/52d21e94d3cc6e30764a833fe2a256783d1a8931/builder/package.py#L95-L114 | ||
pystitch/stitch | 09a16da2f2af2be6a960e2338de488c8de2c2271 | stitch/stitch.py | python | is_executable | (block, lang, attrs) | return (is_code_block(block) and attrs.get('eval') is not False and
lang is not None) | Return whether a block should be executed.
Must be a code_block, and must not have ``eval=False`` in the block
arguments, and ``lang`` (kernel_name) must not be None. | Return whether a block should be executed.
Must be a code_block, and must not have ``eval=False`` in the block
arguments, and ``lang`` (kernel_name) must not be None. | [
"Return",
"whether",
"a",
"block",
"should",
"be",
"executed",
".",
"Must",
"be",
"a",
"code_block",
"and",
"must",
"not",
"have",
"eval",
"=",
"False",
"in",
"the",
"block",
"arguments",
"and",
"lang",
"(",
"kernel_name",
")",
"must",
"not",
"be",
"None... | def is_executable(block, lang, attrs):
"""
Return whether a block should be executed.
Must be a code_block, and must not have ``eval=False`` in the block
arguments, and ``lang`` (kernel_name) must not be None.
"""
return (is_code_block(block) and attrs.get('eval') is not False and
lang is not None) | [
"def",
"is_executable",
"(",
"block",
",",
"lang",
",",
"attrs",
")",
":",
"return",
"(",
"is_code_block",
"(",
"block",
")",
"and",
"attrs",
".",
"get",
"(",
"'eval'",
")",
"is",
"not",
"False",
"and",
"lang",
"is",
"not",
"None",
")"
] | https://github.com/pystitch/stitch/blob/09a16da2f2af2be6a960e2338de488c8de2c2271/stitch/stitch.py#L567-L574 | |
yt-project/yt | dc7b24f9b266703db4c843e329c6c8644d47b824 | yt/data_objects/construction_data_containers.py | python | YTProj.plot | (self, fields=None) | return pw | [] | def plot(self, fields=None):
if hasattr(self.data_source, "left_edge") and hasattr(
self.data_source, "right_edge"
):
left_edge = self.data_source.left_edge
right_edge = self.data_source.right_edge
center = (left_edge + right_edge) / 2.0
width = right_edge - left_edge
xax = self.ds.coordinates.x_axis[self.axis]
yax = self.ds.coordinates.y_axis[self.axis]
lx, rx = left_edge[xax], right_edge[xax]
ly, ry = left_edge[yax], right_edge[yax]
width = (rx - lx), (ry - ly)
else:
width = self.ds.domain_width
center = self.ds.domain_center
pw = self._get_pw(fields, center, width, "native", "Projection")
try:
pw.show()
except YTNotInsideNotebook:
pass
return pw | [
"def",
"plot",
"(",
"self",
",",
"fields",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"data_source",
",",
"\"left_edge\"",
")",
"and",
"hasattr",
"(",
"self",
".",
"data_source",
",",
"\"right_edge\"",
")",
":",
"left_edge",
"=",
"self",
... | https://github.com/yt-project/yt/blob/dc7b24f9b266703db4c843e329c6c8644d47b824/yt/data_objects/construction_data_containers.py#L313-L334 | |||
josephwilk/semanticpy | 60af3f190fd44e5c76717c3a126cdc9201624cb5 | semanticpy/porter_stemmer.py | python | PorterStemmer.ends | (self, s) | return 1 | ends(s) is TRUE <=> k0,...k ends with the string s. | ends(s) is TRUE <=> k0,...k ends with the string s. | [
"ends",
"(",
"s",
")",
"is",
"TRUE",
"<",
"=",
">",
"k0",
"...",
"k",
"ends",
"with",
"the",
"string",
"s",
"."
] | def ends(self, s):
"""ends(s) is TRUE <=> k0,...k ends with the string s."""
length = len(s)
if s[length - 1] != self.b[self.k]: # tiny speed-up
return 0
if length > (self.k - self.k0 + 1):
return 0
if self.b[self.k-length+1:self.k+1] != s:
return 0
self.j = self.k - length
return 1 | [
"def",
"ends",
"(",
"self",
",",
"s",
")",
":",
"length",
"=",
"len",
"(",
"s",
")",
"if",
"s",
"[",
"length",
"-",
"1",
"]",
"!=",
"self",
".",
"b",
"[",
"self",
".",
"k",
"]",
":",
"# tiny speed-up",
"return",
"0",
"if",
"length",
">",
"(",... | https://github.com/josephwilk/semanticpy/blob/60af3f190fd44e5c76717c3a126cdc9201624cb5/semanticpy/porter_stemmer.py#L130-L140 | |
karanchahal/distiller | a17ec06cbeafcdd2aea19d7c7663033c951392f5 | distill_archive/research_seed/baselines/rkd_baseline/rkd_baseline_trainer.py | python | main | (hparams) | [] | def main(hparams):
# init module
teacher_base = create_cnn_model(hparams.teacher_model, feature_maps=True, dataset=hparams.dataset)
# Loading from checkpoint
teacher_base = load_model_chk(teacher_base, hparams.path_to_teacher)
# Train Teacher Embedding
trained_teacher_with_embed = RKD_Cifar(student_base=teacher_base, hparams=hparams)
logger = TestTubeLogger(
save_dir=hparams.save_dir,
version=hparams.version # An existing version with a saved checkpoint
)
# most basic trainer, uses good defaults
if hparams.gpus > 1:
dist = 'ddp'
else:
dist = None
# most basic trainer, uses good defaults
trainer = Trainer(
max_nb_epochs=hparams.epochs,
gpus=hparams.gpus,
nb_gpu_nodes=hparams.nodes,
early_stop_callback=None,
logger=logger,
default_save_path=hparams.save_dir,
distributed_backend=dist,
)
trainer.fit(trained_teacher_with_embed) | [
"def",
"main",
"(",
"hparams",
")",
":",
"# init module",
"teacher_base",
"=",
"create_cnn_model",
"(",
"hparams",
".",
"teacher_model",
",",
"feature_maps",
"=",
"True",
",",
"dataset",
"=",
"hparams",
".",
"dataset",
")",
"# Loading from checkpoint",
"teacher_ba... | https://github.com/karanchahal/distiller/blob/a17ec06cbeafcdd2aea19d7c7663033c951392f5/distill_archive/research_seed/baselines/rkd_baseline/rkd_baseline_trainer.py#L11-L43 | ||||
edisonlz/fastor | 342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3 | base/site-packages/flup/server/ajp.py | python | WSGIServer.run | (self) | return ret | Main loop. Call this after instantiating WSGIServer. SIGHUP, SIGINT,
SIGQUIT, SIGTERM cause it to cleanup and return. (If a SIGHUP
is caught, this method returns True. Returns False otherwise.) | Main loop. Call this after instantiating WSGIServer. SIGHUP, SIGINT,
SIGQUIT, SIGTERM cause it to cleanup and return. (If a SIGHUP
is caught, this method returns True. Returns False otherwise.) | [
"Main",
"loop",
".",
"Call",
"this",
"after",
"instantiating",
"WSGIServer",
".",
"SIGHUP",
"SIGINT",
"SIGQUIT",
"SIGTERM",
"cause",
"it",
"to",
"cleanup",
"and",
"return",
".",
"(",
"If",
"a",
"SIGHUP",
"is",
"caught",
"this",
"method",
"returns",
"True",
... | def run(self):
"""
Main loop. Call this after instantiating WSGIServer. SIGHUP, SIGINT,
SIGQUIT, SIGTERM cause it to cleanup and return. (If a SIGHUP
is caught, this method returns True. Returns False otherwise.)
"""
self.logger.info('%s starting up', self.__class__.__name__)
try:
sock = self._setupSocket()
except socket.error, e:
self.logger.error('Failed to bind socket (%s), exiting', e[1])
return False
ret = ThreadedServer.run(self, sock)
self._cleanupSocket(sock)
# AJP connections are more or less persistent. .shutdown() will
# not return until the web server lets go. So don't bother calling
# it...
#self.shutdown()
self.logger.info('%s shutting down%s', self.__class__.__name__,
self._hupReceived and ' (reload requested)' or '')
return ret | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'%s starting up'",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
"try",
":",
"sock",
"=",
"self",
".",
"_setupSocket",
"(",
")",
"except",
"socket",
".",
"error",
"... | https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/flup/server/ajp.py#L148-L173 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_hxb2/lib/python3.5/site-packages/wagtail_bak/wagtailcore/models.py | python | PagePermissionTester.can_delete | (self) | [] | def can_delete(self):
if not self.user.is_active:
return False
if self.page_is_root: # root node is not a page and can never be deleted, even by superusers
return False
if self.user.is_superuser:
# superusers require no further checks
return True
# if the user does not have bulk_delete permission, they may only delete leaf pages
if 'bulk_delete' not in self.permissions and not self.page.is_leaf():
return False
if 'edit' in self.permissions:
# if the user does not have publish permission, we also need to confirm that there
# are no published pages here
if 'publish' not in self.permissions:
pages_to_delete = self.page.get_descendants(inclusive=True)
if pages_to_delete.live().exists():
return False
return True
elif 'add' in self.permissions:
pages_to_delete = self.page.get_descendants(inclusive=True)
if 'publish' in self.permissions:
# we don't care about live state, but all pages must be owned by this user
# (i.e. eliminating pages owned by this user must give us the empty set)
return not pages_to_delete.exclude(owner=self.user).exists()
else:
# all pages must be owned by this user and non-live
# (i.e. eliminating non-live pages owned by this user must give us the empty set)
return not pages_to_delete.exclude(live=False, owner=self.user).exists()
else:
return False | [
"def",
"can_delete",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"user",
".",
"is_active",
":",
"return",
"False",
"if",
"self",
".",
"page_is_root",
":",
"# root node is not a page and can never be deleted, even by superusers",
"return",
"False",
"if",
"self",... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/wagtail_bak/wagtailcore/models.py#L1741-L1777 | ||||
SteveDoyle2/pyNastran | eda651ac2d4883d95a34951f8a002ff94f642a1a | pyNastran/dev/bdf_vectorized/cards/elements/shell/ctria6.py | python | CTRIA6._mass_area_normal | (self, element_id=None, xyz_cid0=None,
calculate_mass=True, calculate_area=True,
calculate_normal=True) | return massi, A, normal | Gets the mass, area, and normals of the CTRIA6s on a per
element basis.
Parameters
----------
element_id : (nelements, ) int ndarray; default=None -> all
the elements to consider
:param node_ids: the GRIDs as an (N, ) NDARRAY (or None)
:param xyz_cid0: the GRIDs as an (N, 3) NDARRAY in CORD2R=0 (or None)
calculate_mass : bool; default=True
should the mass be calculated
calculate_area : bool; default=True
should the area be calculated
calculate_normal : bool; default=True
should the normals be calculated | Gets the mass, area, and normals of the CTRIA6s on a per
element basis. | [
"Gets",
"the",
"mass",
"area",
"and",
"normals",
"of",
"the",
"CTRIA6s",
"on",
"a",
"per",
"element",
"basis",
"."
] | def _mass_area_normal(self, element_id=None, xyz_cid0=None,
calculate_mass=True, calculate_area=True,
calculate_normal=True):
"""
Gets the mass, area, and normals of the CTRIA6s on a per
element basis.
Parameters
----------
element_id : (nelements, ) int ndarray; default=None -> all
the elements to consider
:param node_ids: the GRIDs as an (N, ) NDARRAY (or None)
:param xyz_cid0: the GRIDs as an (N, 3) NDARRAY in CORD2R=0 (or None)
calculate_mass : bool; default=True
should the mass be calculated
calculate_area : bool; default=True
should the area be calculated
calculate_normal : bool; default=True
should the normals be calculated
"""
if element_id is None:
element_id = self.element_id
property_id = self.property_id
i = None
else:
i = searchsorted(self.element_id, element_id)
property_id = self.property_id[i]
n1, n2, n3 = self._node_locations(xyz_cid0)
if calculate_mass:
calculate_area = True
normal, A = _ctria3_normal_A(n1, n2, n3, calculate_area=calculate_area, normalize=True)
massi = None
if calculate_mass:
mpa = self.model.properties_shell.get_mass_per_area(property_id)
assert mpa is not None
#massi = rho * A * t + nsm
massi = mpa * A
return massi, A, normal | [
"def",
"_mass_area_normal",
"(",
"self",
",",
"element_id",
"=",
"None",
",",
"xyz_cid0",
"=",
"None",
",",
"calculate_mass",
"=",
"True",
",",
"calculate_area",
"=",
"True",
",",
"calculate_normal",
"=",
"True",
")",
":",
"if",
"element_id",
"is",
"None",
... | https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/dev/bdf_vectorized/cards/elements/shell/ctria6.py#L126-L167 | |
pymedusa/Medusa | 1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38 | ext/boto/regioninfo.py | python | RegionInfo.connect | (self, **kw_params) | Connect to this Region's endpoint. Returns an connection
object pointing to the endpoint associated with this region.
You may pass any of the arguments accepted by the connection
class's constructor as keyword arguments and they will be
passed along to the connection object.
:rtype: Connection object
:return: The connection to this regions endpoint | Connect to this Region's endpoint. Returns an connection
object pointing to the endpoint associated with this region.
You may pass any of the arguments accepted by the connection
class's constructor as keyword arguments and they will be
passed along to the connection object. | [
"Connect",
"to",
"this",
"Region",
"s",
"endpoint",
".",
"Returns",
"an",
"connection",
"object",
"pointing",
"to",
"the",
"endpoint",
"associated",
"with",
"this",
"region",
".",
"You",
"may",
"pass",
"any",
"of",
"the",
"arguments",
"accepted",
"by",
"the"... | def connect(self, **kw_params):
"""
Connect to this Region's endpoint. Returns an connection
object pointing to the endpoint associated with this region.
You may pass any of the arguments accepted by the connection
class's constructor as keyword arguments and they will be
passed along to the connection object.
:rtype: Connection object
:return: The connection to this regions endpoint
"""
if self.connection_cls:
return self.connection_cls(region=self, **kw_params) | [
"def",
"connect",
"(",
"self",
",",
"*",
"*",
"kw_params",
")",
":",
"if",
"self",
".",
"connection_cls",
":",
"return",
"self",
".",
"connection_cls",
"(",
"region",
"=",
"self",
",",
"*",
"*",
"kw_params",
")"
] | https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/boto/regioninfo.py#L278-L290 | ||
MarcusOlivecrona/REINVENT | 752935c29d46868d1aa040c0cd9c8d2169c9150a | data_structs.py | python | Vocabulary.tokenize | (self, smiles) | return tokenized | Takes a SMILES and return a list of characters/tokens | Takes a SMILES and return a list of characters/tokens | [
"Takes",
"a",
"SMILES",
"and",
"return",
"a",
"list",
"of",
"characters",
"/",
"tokens"
] | def tokenize(self, smiles):
"""Takes a SMILES and return a list of characters/tokens"""
regex = '(\[[^\[\]]{1,6}\])'
smiles = replace_halogen(smiles)
char_list = re.split(regex, smiles)
tokenized = []
for char in char_list:
if char.startswith('['):
tokenized.append(char)
else:
chars = [unit for unit in char]
[tokenized.append(unit) for unit in chars]
tokenized.append('EOS')
return tokenized | [
"def",
"tokenize",
"(",
"self",
",",
"smiles",
")",
":",
"regex",
"=",
"'(\\[[^\\[\\]]{1,6}\\])'",
"smiles",
"=",
"replace_halogen",
"(",
"smiles",
")",
"char_list",
"=",
"re",
".",
"split",
"(",
"regex",
",",
"smiles",
")",
"tokenized",
"=",
"[",
"]",
"... | https://github.com/MarcusOlivecrona/REINVENT/blob/752935c29d46868d1aa040c0cd9c8d2169c9150a/data_structs.py#L42-L55 | |
shiweibsw/Translation-Tools | 2fbbf902364e557fa7017f9a74a8797b7440c077 | venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/colorama/initialise.py | python | wrap_stream | (stream, convert, strip, autoreset, wrap) | return stream | [] | def wrap_stream(stream, convert, strip, autoreset, wrap):
if wrap:
wrapper = AnsiToWin32(stream,
convert=convert, strip=strip, autoreset=autoreset)
if wrapper.should_wrap():
stream = wrapper.stream
return stream | [
"def",
"wrap_stream",
"(",
"stream",
",",
"convert",
",",
"strip",
",",
"autoreset",
",",
"wrap",
")",
":",
"if",
"wrap",
":",
"wrapper",
"=",
"AnsiToWin32",
"(",
"stream",
",",
"convert",
"=",
"convert",
",",
"strip",
"=",
"strip",
",",
"autoreset",
"... | https://github.com/shiweibsw/Translation-Tools/blob/2fbbf902364e557fa7017f9a74a8797b7440c077/venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/colorama/initialise.py#L74-L80 | |||
OpenTreeMap/otm-core | 06600b85880136da46f0a18f9e447aa80b1a8d32 | opentreemap/treemap/search.py | python | create_filter | (instance, filterstr, mapping) | return q | A filter is a string that must be valid json and conform to
the following grammar:
literal = json literal | GMT date string in 'YYYY-MM-DD HH:MM:SS'
model = 'plot' | 'tree' | 'species'
value-property = 'MIN'
| 'MAX'
| 'EXCLUSIVE'
| 'IN'
| 'IS'
| 'IN_BOUNDARY'
| 'LIKE'
| 'ISNULL'
combinator = 'AND' | 'OR'
predicate = { model.field: literal }
| { model.field: { (value-property: literal)* }}
filter = predicate
| [combinator, filter*, literal?]
mapping allows for the developer to search focussed on a
particular object group
Returns a Q object that can be applied to a model of your choice | A filter is a string that must be valid json and conform to
the following grammar:
literal = json literal | GMT date string in 'YYYY-MM-DD HH:MM:SS'
model = 'plot' | 'tree' | 'species'
value-property = 'MIN'
| 'MAX'
| 'EXCLUSIVE'
| 'IN'
| 'IS'
| 'IN_BOUNDARY'
| 'LIKE'
| 'ISNULL'
combinator = 'AND' | 'OR'
predicate = { model.field: literal }
| { model.field: { (value-property: literal)* }}
filter = predicate
| [combinator, filter*, literal?] | [
"A",
"filter",
"is",
"a",
"string",
"that",
"must",
"be",
"valid",
"json",
"and",
"conform",
"to",
"the",
"following",
"grammar",
":",
"literal",
"=",
"json",
"literal",
"|",
"GMT",
"date",
"string",
"in",
"YYYY",
"-",
"MM",
"-",
"DD",
"HH",
":",
"MM... | def create_filter(instance, filterstr, mapping):
"""
A filter is a string that must be valid json and conform to
the following grammar:
literal = json literal | GMT date string in 'YYYY-MM-DD HH:MM:SS'
model = 'plot' | 'tree' | 'species'
value-property = 'MIN'
| 'MAX'
| 'EXCLUSIVE'
| 'IN'
| 'IS'
| 'IN_BOUNDARY'
| 'LIKE'
| 'ISNULL'
combinator = 'AND' | 'OR'
predicate = { model.field: literal }
| { model.field: { (value-property: literal)* }}
filter = predicate
| [combinator, filter*, literal?]
mapping allows for the developer to search focussed on a
particular object group
Returns a Q object that can be applied to a model of your choice
"""
if filterstr is not None and filterstr != '':
query = loads(filterstr)
convert_filter_units(instance, query)
q = _parse_filter(query, mapping)
else:
q = FilterContext()
if instance:
q = q & FilterContext(instance=instance)
return q | [
"def",
"create_filter",
"(",
"instance",
",",
"filterstr",
",",
"mapping",
")",
":",
"if",
"filterstr",
"is",
"not",
"None",
"and",
"filterstr",
"!=",
"''",
":",
"query",
"=",
"loads",
"(",
"filterstr",
")",
"convert_filter_units",
"(",
"instance",
",",
"q... | https://github.com/OpenTreeMap/otm-core/blob/06600b85880136da46f0a18f9e447aa80b1a8d32/opentreemap/treemap/search.py#L166-L201 | |
deepmind/dm_control | 806a10e896e7c887635328bfa8352604ad0fedae | dm_control/viewer/renderer.py | python | SceneCamera.zoom_to_scene | (self) | Zooms in on the entire scene. | Zooms in on the entire scene. | [
"Zooms",
"in",
"on",
"the",
"entire",
"scene",
"."
] | def zoom_to_scene(self):
"""Zooms in on the entire scene."""
self.look_at(self._model.stat.center[:],
self._zoom_factor * self._model.stat.extent)
self.settings = self._settings | [
"def",
"zoom_to_scene",
"(",
"self",
")",
":",
"self",
".",
"look_at",
"(",
"self",
".",
"_model",
".",
"stat",
".",
"center",
"[",
":",
"]",
",",
"self",
".",
"_zoom_factor",
"*",
"self",
".",
"_model",
".",
"stat",
".",
"extent",
")",
"self",
"."... | https://github.com/deepmind/dm_control/blob/806a10e896e7c887635328bfa8352604ad0fedae/dm_control/viewer/renderer.py#L503-L508 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/alembic/runtime/migration.py | python | MigrationStep.upgrade_from_script | (cls, revision_map, script) | return RevisionStep(revision_map, script, True) | [] | def upgrade_from_script(cls, revision_map, script):
return RevisionStep(revision_map, script, True) | [
"def",
"upgrade_from_script",
"(",
"cls",
",",
"revision_map",
",",
"script",
")",
":",
"return",
"RevisionStep",
"(",
"revision_map",
",",
"script",
",",
"True",
")"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/alembic/runtime/migration.py#L676-L677 | |||
ljean/modbus-tk | 1159c71794071ae67f73f86fa14dd71c989b4859 | modbus_tk/pymodbusclient.py | python | PyModbusClientTCP.open | (self) | return True | [] | def open(self):
self.client.open()
return True | [
"def",
"open",
"(",
"self",
")",
":",
"self",
".",
"client",
".",
"open",
"(",
")",
"return",
"True"
] | https://github.com/ljean/modbus-tk/blob/1159c71794071ae67f73f86fa14dd71c989b4859/modbus_tk/pymodbusclient.py#L10-L12 | |||
Map-A-Droid/MAD | 81375b5c9ccc5ca3161eb487aa81469d40ded221 | mapadroid/data_manager/__init__.py | python | DataManager.fix_routecalc_on_boot | (self) | [] | def fix_routecalc_on_boot(self) -> None:
rc_sql = "IFNULL(id.`routecalc`, IFNULL(iv.`routecalc`, IFNULL(mon.`routecalc`, " \
"IFNULL(ps.`routecalc`, ra.`routecalc`))))"
sql = "SELECT a.`area_id`, a.`instance_id` AS 'ain', rc.`routecalc_id`, rc.`instance_id` AS 'rcin'\n"\
"FROM (\n"\
" SELECT sa.`area_id`, sa.`instance_id`, %s AS 'routecalc'\n"\
" FROM `settings_area` sa\n"\
" LEFT JOIN `settings_area_idle` id ON id.`area_id` = sa.`area_id`\n"\
" LEFT JOIN `settings_area_iv_mitm` iv ON iv.`area_id` = sa.`area_id`\n"\
" LEFT JOIN `settings_area_mon_mitm` mon ON mon.`area_id` = sa.`area_id`\n"\
" LEFT JOIN `settings_area_pokestops` ps ON ps.`area_id` = sa.`area_id`\n"\
" LEFT JOIN `settings_area_raids_mitm` ra ON ra.`area_id` = sa.`area_id`\n"\
") a\n"\
"INNER JOIN `settings_routecalc` rc ON rc.`routecalc_id` = a.`routecalc`\n"\
"WHERE a.`instance_id` != rc.`instance_id`" % (rc_sql,)
bad_entries = self.dbc.autofetch_all(sql)
if bad_entries:
logger.info('Routecalcs with mis-matched IDs present. {}', bad_entries)
for entry in bad_entries:
update = {
'instance_id': entry['ain']
}
where = {
'routecalc_id': entry['routecalc_id']
}
self.dbc.autoexec_update('settings_routecalc', update, where_keyvals=where) | [
"def",
"fix_routecalc_on_boot",
"(",
"self",
")",
"->",
"None",
":",
"rc_sql",
"=",
"\"IFNULL(id.`routecalc`, IFNULL(iv.`routecalc`, IFNULL(mon.`routecalc`, \"",
"\"IFNULL(ps.`routecalc`, ra.`routecalc`))))\"",
"sql",
"=",
"\"SELECT a.`area_id`, a.`instance_id` AS 'ain', rc.`routecalc_id... | https://github.com/Map-A-Droid/MAD/blob/81375b5c9ccc5ca3161eb487aa81469d40ded221/mapadroid/data_manager/__init__.py#L37-L62 | ||||
JaniceWuo/MovieRecommend | 4c86db64ca45598917d304f535413df3bc9fea65 | movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/requests/models.py | python | PreparedRequest.prepare_content_length | (self, body) | [] | def prepare_content_length(self, body):
if hasattr(body, 'seek') and hasattr(body, 'tell'):
curr_pos = body.tell()
body.seek(0, 2)
end_pos = body.tell()
self.headers['Content-Length'] = builtin_str(max(0, end_pos - curr_pos))
body.seek(curr_pos, 0)
elif body is not None:
l = super_len(body)
if l:
self.headers['Content-Length'] = builtin_str(l)
elif (self.method not in ('GET', 'HEAD')) and (self.headers.get('Content-Length') is None):
self.headers['Content-Length'] = '0' | [
"def",
"prepare_content_length",
"(",
"self",
",",
"body",
")",
":",
"if",
"hasattr",
"(",
"body",
",",
"'seek'",
")",
"and",
"hasattr",
"(",
"body",
",",
"'tell'",
")",
":",
"curr_pos",
"=",
"body",
".",
"tell",
"(",
")",
"body",
".",
"seek",
"(",
... | https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/requests/models.py#L472-L484 | ||||
graphql-python/graphql-core | 9ea9c3705d6826322027d9bb539d37c5b25f7af9 | src/graphql/utilities/separate_operations.py | python | separate_operations | (document_ast: DocumentNode) | return separated_document_asts | Separate operations in a given AST document.
This function accepts a single AST document which may contain many operations and
fragments and returns a collection of AST documents each of which contains a single
operation as well the fragment definitions it refers to. | Separate operations in a given AST document. | [
"Separate",
"operations",
"in",
"a",
"given",
"AST",
"document",
"."
] | def separate_operations(document_ast: DocumentNode) -> Dict[str, DocumentNode]:
"""Separate operations in a given AST document.
This function accepts a single AST document which may contain many operations and
fragments and returns a collection of AST documents each of which contains a single
operation as well the fragment definitions it refers to.
"""
operations: List[OperationDefinitionNode] = []
dep_graph: DepGraph = {}
# Populate metadata and build a dependency graph.
for definition_node in document_ast.definitions:
if isinstance(definition_node, OperationDefinitionNode):
operations.append(definition_node)
elif isinstance(
definition_node, FragmentDefinitionNode
): # pragma: no cover else
dep_graph[definition_node.name.value] = collect_dependencies(
definition_node.selection_set
)
# For each operation, produce a new synthesized AST which includes only what is
# necessary for completing that operation.
separated_document_asts: Dict[str, DocumentNode] = {}
for operation in operations:
dependencies: Set[str] = set()
for fragment_name in collect_dependencies(operation.selection_set):
collect_transitive_dependencies(dependencies, dep_graph, fragment_name)
# Provides the empty string for anonymous operations.
operation_name = operation.name.value if operation.name else ""
# The list of definition nodes to be included for this operation, sorted
# to retain the same order as the original document.
separated_document_asts[operation_name] = DocumentNode(
definitions=[
node
for node in document_ast.definitions
if node is operation
or (
isinstance(node, FragmentDefinitionNode)
and node.name.value in dependencies
)
]
)
return separated_document_asts | [
"def",
"separate_operations",
"(",
"document_ast",
":",
"DocumentNode",
")",
"->",
"Dict",
"[",
"str",
",",
"DocumentNode",
"]",
":",
"operations",
":",
"List",
"[",
"OperationDefinitionNode",
"]",
"=",
"[",
"]",
"dep_graph",
":",
"DepGraph",
"=",
"{",
"}",
... | https://github.com/graphql-python/graphql-core/blob/9ea9c3705d6826322027d9bb539d37c5b25f7af9/src/graphql/utilities/separate_operations.py#L19-L66 | |
nasa-jpl-memex/memex-explorer | d2910496238359b3676b4467721017fc82f0b324 | source/base/views.py | python | AddProjectView.get_success_url | (self) | return self.object.get_absolute_url() | [] | def get_success_url(self):
return self.object.get_absolute_url() | [
"def",
"get_success_url",
"(",
"self",
")",
":",
"return",
"self",
".",
"object",
".",
"get_absolute_url",
"(",
")"
] | https://github.com/nasa-jpl-memex/memex-explorer/blob/d2910496238359b3676b4467721017fc82f0b324/source/base/views.py#L97-L98 | |||
witherst/MayaNodeInterface | 30d35bd199cb864b0ae2b21e7ce3dc75c690837d | ui/nodeWidgetsModule.py | python | AbstractAttrObject.setupWidget | (self) | Abstract. This function is called AS SOON AS THE NODE IS CREATED IN THE SCENE, regardless of
if it is connected to another node. | Abstract. This function is called AS SOON AS THE NODE IS CREATED IN THE SCENE, regardless of
if it is connected to another node. | [
"Abstract",
".",
"This",
"function",
"is",
"called",
"AS",
"SOON",
"AS",
"THE",
"NODE",
"IS",
"CREATED",
"IN",
"THE",
"SCENE",
"regardless",
"of",
"if",
"it",
"is",
"connected",
"to",
"another",
"node",
"."
] | def setupWidget(self):
"""
Abstract. This function is called AS SOON AS THE NODE IS CREATED IN THE SCENE, regardless of
if it is connected to another node.
"""
pass | [
"def",
"setupWidget",
"(",
"self",
")",
":",
"pass"
] | https://github.com/witherst/MayaNodeInterface/blob/30d35bd199cb864b0ae2b21e7ce3dc75c690837d/ui/nodeWidgetsModule.py#L159-L164 | ||
XX-net/XX-Net | a9898cfcf0084195fb7e69b6bc834e59aecdf14f | python3.8.2/Lib/OpenSSL/_util.py | python | make_assert | (error) | return openssl_assert | Create an assert function that uses :func:`exception_from_error_queue` to
raise an exception wrapped by *error*. | Create an assert function that uses :func:`exception_from_error_queue` to
raise an exception wrapped by *error*. | [
"Create",
"an",
"assert",
"function",
"that",
"uses",
":",
"func",
":",
"exception_from_error_queue",
"to",
"raise",
"an",
"exception",
"wrapped",
"by",
"*",
"error",
"*",
"."
] | def make_assert(error):
"""
Create an assert function that uses :func:`exception_from_error_queue` to
raise an exception wrapped by *error*.
"""
def openssl_assert(ok):
"""
If *ok* is not True, retrieve the error from OpenSSL and raise it.
"""
if ok is not True:
exception_from_error_queue(error)
return openssl_assert | [
"def",
"make_assert",
"(",
"error",
")",
":",
"def",
"openssl_assert",
"(",
"ok",
")",
":",
"\"\"\"\n If *ok* is not True, retrieve the error from OpenSSL and raise it.\n \"\"\"",
"if",
"ok",
"is",
"not",
"True",
":",
"exception_from_error_queue",
"(",
"error"... | https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/OpenSSL/_util.py#L57-L69 | |
samuelclay/NewsBlur | 2c45209df01a1566ea105e04d499367f32ac9ad2 | apps/rss_feeds/management/commands/calculate_scores.py | python | daemonize | () | Detach from the terminal and continue as a daemon. | Detach from the terminal and continue as a daemon. | [
"Detach",
"from",
"the",
"terminal",
"and",
"continue",
"as",
"a",
"daemon",
"."
] | def daemonize():
"""
Detach from the terminal and continue as a daemon.
"""
# swiped from twisted/scripts/twistd.py
# See http://www.erlenstar.demon.co.uk/unix/faq_toc.html#TOC16
if os.fork(): # launch child and...
os._exit(0) # kill off parent
os.setsid()
if os.fork(): # launch child and...
os._exit(0) # kill off parent again.
os.umask(0o77)
null = os.open("/dev/null", os.O_RDWR)
for i in range(3):
try:
os.dup2(null, i)
except OSError as e:
if e.errno != errno.EBADF:
raise
os.close(null) | [
"def",
"daemonize",
"(",
")",
":",
"# swiped from twisted/scripts/twistd.py",
"# See http://www.erlenstar.demon.co.uk/unix/faq_toc.html#TOC16",
"if",
"os",
".",
"fork",
"(",
")",
":",
"# launch child and...",
"os",
".",
"_exit",
"(",
"0",
")",
"# kill off parent",
"os",
... | https://github.com/samuelclay/NewsBlur/blob/2c45209df01a1566ea105e04d499367f32ac9ad2/apps/rss_feeds/management/commands/calculate_scores.py#L48-L67 | ||
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/kaiterra/air_quality.py | python | KaiterraAirQuality.air_quality_index_level | (self) | return self._data("aqi_level") | Return the Air Quality Index level. | Return the Air Quality Index level. | [
"Return",
"the",
"Air",
"Quality",
"Index",
"level",
"."
] | def air_quality_index_level(self):
"""Return the Air Quality Index level."""
return self._data("aqi_level") | [
"def",
"air_quality_index_level",
"(",
"self",
")",
":",
"return",
"self",
".",
"_data",
"(",
"\"aqi_level\"",
")"
] | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/kaiterra/air_quality.py#L74-L76 | |
jcmgray/quimb | a54b22c61534be8acbc9efe4da97fb5c7f12057d | quimb/linalg/slepc_linalg.py | python | mfn_multiply_slepc | (mat, vec,
fntype='exp',
MFNType='AUTO',
comm=None,
isherm=False) | return all_out | Compute the action of ``func(mat) @ vec``.
Parameters
----------
mat : operator
Operator to compute function action of.
vec : vector-like
Vector to compute matrix function action on.
func : {'exp', 'sqrt', 'log'}, optional
Function to use.
MFNType : {'krylov', 'expokit'}, optional
Method of computing the matrix function action, 'expokit' is only
available for func='exp'.
comm : mpi4py.MPI.Comm instance, optional
The mpi communicator.
isherm : bool, optional
If `mat` is known to be hermitian, this might speed things up in
some circumstances.
Returns
-------
fvec : array
The vector output of ``func(mat) @ vec``. | Compute the action of ``func(mat) @ vec``. | [
"Compute",
"the",
"action",
"of",
"func",
"(",
"mat",
")",
"@",
"vec",
"."
] | def mfn_multiply_slepc(mat, vec,
fntype='exp',
MFNType='AUTO',
comm=None,
isherm=False):
"""Compute the action of ``func(mat) @ vec``.
Parameters
----------
mat : operator
Operator to compute function action of.
vec : vector-like
Vector to compute matrix function action on.
func : {'exp', 'sqrt', 'log'}, optional
Function to use.
MFNType : {'krylov', 'expokit'}, optional
Method of computing the matrix function action, 'expokit' is only
available for func='exp'.
comm : mpi4py.MPI.Comm instance, optional
The mpi communicator.
isherm : bool, optional
If `mat` is known to be hermitian, this might speed things up in
some circumstances.
Returns
-------
fvec : array
The vector output of ``func(mat) @ vec``.
"""
SLEPc, comm = get_slepc(comm=comm)
mat = convert_mat_to_petsc(mat, comm=comm)
if isherm:
mat.setOption(mat.Option.HERMITIAN, True)
vec = convert_vec_to_petsc(vec, comm=comm)
out = new_petsc_vec(vec.size, comm=comm)
if MFNType.upper() == 'AUTO':
if (fntype == 'exp') and (vec.size <= 2**16):
MFNType = 'EXPOKIT'
else:
MFNType = 'KRYLOV'
# set up the matrix function options and objects
mfn = SLEPc.MFN().create(comm=comm)
mfn.setType(getattr(SLEPc.MFN.Type, MFNType.upper()))
mfn_fn = mfn.getFN()
mfn_fn.setType(getattr(SLEPc.FN.Type, fntype.upper()))
mfn_fn.setScale(1.0, 1.0)
mfn.setFromOptions()
mfn.setOperator(mat)
# 'solve' / perform the matrix function
mfn.solve(vec, out)
# --> gather the (distributed) petsc vector to a numpy matrix on master
all_out = gather_petsc_array(out, comm=comm, out_shape=(-1, 1))
mfn.destroy()
return all_out | [
"def",
"mfn_multiply_slepc",
"(",
"mat",
",",
"vec",
",",
"fntype",
"=",
"'exp'",
",",
"MFNType",
"=",
"'AUTO'",
",",
"comm",
"=",
"None",
",",
"isherm",
"=",
"False",
")",
":",
"SLEPc",
",",
"comm",
"=",
"get_slepc",
"(",
"comm",
"=",
"comm",
")",
... | https://github.com/jcmgray/quimb/blob/a54b22c61534be8acbc9efe4da97fb5c7f12057d/quimb/linalg/slepc_linalg.py#L687-L748 | |
beetbox/beets | 2fea53c34dd505ba391cb345424e0613901c8025 | beetsplug/bpd/__init__.py | python | Server._listall | (self, basepath, node, info=False) | Helper function for recursive listing. If info, show
tracks' complete info; otherwise, just show items' paths. | Helper function for recursive listing. If info, show
tracks' complete info; otherwise, just show items' paths. | [
"Helper",
"function",
"for",
"recursive",
"listing",
".",
"If",
"info",
"show",
"tracks",
"complete",
"info",
";",
"otherwise",
"just",
"show",
"items",
"paths",
"."
] | def _listall(self, basepath, node, info=False):
"""Helper function for recursive listing. If info, show
tracks' complete info; otherwise, just show items' paths.
"""
if isinstance(node, int):
# List a single file.
if info:
item = self.lib.get_item(node)
yield self._item_info(item)
else:
yield 'file: ' + basepath
else:
# List a directory. Recurse into both directories and files.
for name, itemid in sorted(node.files.items()):
newpath = self._path_join(basepath, name)
# "yield from"
yield from self._listall(newpath, itemid, info)
for name, subdir in sorted(node.dirs.items()):
newpath = self._path_join(basepath, name)
yield 'directory: ' + newpath
yield from self._listall(newpath, subdir, info) | [
"def",
"_listall",
"(",
"self",
",",
"basepath",
",",
"node",
",",
"info",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"int",
")",
":",
"# List a single file.",
"if",
"info",
":",
"item",
"=",
"self",
".",
"lib",
".",
"get_item",
"(... | https://github.com/beetbox/beets/blob/2fea53c34dd505ba391cb345424e0613901c8025/beetsplug/bpd/__init__.py#L1219-L1239 | ||
StepNeverStop/RLs | 25cc97c96cbb19fe859c9387b7547cbada2c89f2 | rls/nn/layers.py | python | NoisyLinear.scale_noise | (size: int) | return x.sign().mul(x.abs().sqrt()) | Set scale to make noise (factorized gaussian noise). | Set scale to make noise (factorized gaussian noise). | [
"Set",
"scale",
"to",
"make",
"noise",
"(",
"factorized",
"gaussian",
"noise",
")",
"."
] | def scale_noise(size: int) -> th.Tensor:
"""Set scale to make noise (factorized gaussian noise)."""
x = th.randn(size)
return x.sign().mul(x.abs().sqrt()) | [
"def",
"scale_noise",
"(",
"size",
":",
"int",
")",
"->",
"th",
".",
"Tensor",
":",
"x",
"=",
"th",
".",
"randn",
"(",
"size",
")",
"return",
"x",
".",
"sign",
"(",
")",
".",
"mul",
"(",
"x",
".",
"abs",
"(",
")",
".",
"sqrt",
"(",
")",
")"... | https://github.com/StepNeverStop/RLs/blob/25cc97c96cbb19fe859c9387b7547cbada2c89f2/rls/nn/layers.py#L92-L96 | |
kuri65536/python-for-android | 26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891 | python-modules/twisted/twisted/web/resource.py | python | Resource.__init__ | (self) | Initialize. | Initialize. | [
"Initialize",
"."
] | def __init__(self):
"""Initialize.
"""
self.children = {} | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"children",
"=",
"{",
"}"
] | https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-modules/twisted/twisted/web/resource.py#L81-L84 | ||
IronLanguages/ironpython3 | 7a7bb2a872eeab0d1009fc8a6e24dca43f65b693 | Src/StdLib/Lib/tkinter/tix.py | python | Grid.info_bbox | (self, x, y) | return self.tk.call(self, 'info', 'bbox', x, y) | [] | def info_bbox(self, x, y):
# This seems to always return '', at least for 'text' displayitems
return self.tk.call(self, 'info', 'bbox', x, y) | [
"def",
"info_bbox",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"# This seems to always return '', at least for 'text' displayitems",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"self",
",",
"'info'",
",",
"'bbox'",
",",
"x",
",",
"y",
")"
] | https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/tkinter/tix.py#L1849-L1851 | |||
TensorSpeech/TensorflowTTS | 34358d82a4c91fd70344872f8ea8a405ea84aedb | tensorflow_tts/utils/griffin_lim.py | python | TFGriffinLim.call | (self, mel_spec, n_iter=32) | return tf.signal.inverse_stft(
mel_to_linear * phase,
frame_length=self.ds_config["win_length"] or self.ds_config["fft_size"],
frame_step=self.ds_config["hop_size"],
fft_length=self.ds_config["fft_size"],
window_fn=tf.signal.inverse_stft_window_fn(self.ds_config["hop_size"]),
) | Apply GL algorithm to batched mel spectrograms.
Args:
mel_spec (tf.Tensor): normalized mel spectrogram.
n_iter (int): number of iterations to run GL algorithm.
Returns:
(tf.Tensor): reconstructed signal from GL algorithm. | Apply GL algorithm to batched mel spectrograms.
Args:
mel_spec (tf.Tensor): normalized mel spectrogram.
n_iter (int): number of iterations to run GL algorithm.
Returns:
(tf.Tensor): reconstructed signal from GL algorithm. | [
"Apply",
"GL",
"algorithm",
"to",
"batched",
"mel",
"spectrograms",
".",
"Args",
":",
"mel_spec",
"(",
"tf",
".",
"Tensor",
")",
":",
"normalized",
"mel",
"spectrogram",
".",
"n_iter",
"(",
"int",
")",
":",
"number",
"of",
"iterations",
"to",
"run",
"GL"... | def call(self, mel_spec, n_iter=32):
"""Apply GL algorithm to batched mel spectrograms.
Args:
mel_spec (tf.Tensor): normalized mel spectrogram.
n_iter (int): number of iterations to run GL algorithm.
Returns:
(tf.Tensor): reconstructed signal from GL algorithm.
"""
# de-normalize mel spectogram
if self.normalized:
mel_spec = tf.math.pow(
10.0, mel_spec * self.scaler.scale_ + self.scaler.mean_
)
else:
mel_spec = tf.math.pow(
10.0, mel_spec
) # TODO @dathudeptrai check if its ok without it wavs were too quiet
inverse_mel = tf.linalg.pinv(self.mel_basis)
# [:, num_mels] @ [fft_size // 2 + 1, num_mels].T
mel_to_linear = tf.linalg.matmul(mel_spec, inverse_mel, transpose_b=True)
mel_to_linear = tf.cast(tf.math.maximum(1e-10, mel_to_linear), tf.complex64)
init_phase = tf.cast(
tf.random.uniform(tf.shape(mel_to_linear), maxval=1), tf.complex64
)
phase = tf.math.exp(2j * np.pi * init_phase)
for _ in tf.range(n_iter):
inverse = tf.signal.inverse_stft(
mel_to_linear * phase,
frame_length=self.ds_config["win_length"] or self.ds_config["fft_size"],
frame_step=self.ds_config["hop_size"],
fft_length=self.ds_config["fft_size"],
window_fn=tf.signal.inverse_stft_window_fn(self.ds_config["hop_size"]),
)
phase = tf.signal.stft(
inverse,
self.ds_config["win_length"] or self.ds_config["fft_size"],
self.ds_config["hop_size"],
self.ds_config["fft_size"],
)
phase /= tf.cast(tf.maximum(1e-10, tf.abs(phase)), tf.complex64)
return tf.signal.inverse_stft(
mel_to_linear * phase,
frame_length=self.ds_config["win_length"] or self.ds_config["fft_size"],
frame_step=self.ds_config["hop_size"],
fft_length=self.ds_config["fft_size"],
window_fn=tf.signal.inverse_stft_window_fn(self.ds_config["hop_size"]),
) | [
"def",
"call",
"(",
"self",
",",
"mel_spec",
",",
"n_iter",
"=",
"32",
")",
":",
"# de-normalize mel spectogram",
"if",
"self",
".",
"normalized",
":",
"mel_spec",
"=",
"tf",
".",
"math",
".",
"pow",
"(",
"10.0",
",",
"mel_spec",
"*",
"self",
".",
"sca... | https://github.com/TensorSpeech/TensorflowTTS/blob/34358d82a4c91fd70344872f8ea8a405ea84aedb/tensorflow_tts/utils/griffin_lim.py#L117-L166 | |
axcore/tartube | 36dd493642923fe8b9190a41db596c30c043ae90 | tartube/mainwin.py | python | MainWin.on_progress_list_dl_last | (self, menu_item, download_item_obj) | Called from a callback in self.progress_list_popup_menu().
Moves the selected media data object to the bottom of the
downloads.DownloadList, so it is assigned to the last available worker.
Args:
menu_item (Gtk.MenuItem): The menu item that was clicked
download_item_obj (downloads.DownloadItem): The download item
object for the selected media data object | Called from a callback in self.progress_list_popup_menu(). | [
"Called",
"from",
"a",
"callback",
"in",
"self",
".",
"progress_list_popup_menu",
"()",
"."
] | def on_progress_list_dl_last(self, menu_item, download_item_obj):
"""Called from a callback in self.progress_list_popup_menu().
Moves the selected media data object to the bottom of the
downloads.DownloadList, so it is assigned to the last available worker.
Args:
menu_item (Gtk.MenuItem): The menu item that was clicked
download_item_obj (downloads.DownloadItem): The download item
object for the selected media data object
"""
if DEBUG_FUNC_FLAG:
utils.debug_time('mwn 15308 on_progress_list_dl_last')
# Check that, since the popup menu was created, the media data object
# hasn't been assigned a worker
for this_worker_obj in self.app_obj.download_manager_obj.worker_list:
if this_worker_obj.running_flag \
and this_worker_obj.download_item_obj == download_item_obj \
and this_worker_obj.downloader_obj is not None:
return
# Assign this media data object to the last available worker
download_list_obj = self.app_obj.download_manager_obj.download_list_obj
download_list_obj.move_item_to_bottom(download_item_obj)
# Change the row's icon to show that it will be checked/downloaded
# last
# (Because of the way the Progress List has been set up, borrowing from
# the design in youtube-dl-gui, reordering the rows in the list is
# not practial)
tree_path = Gtk.TreePath(
self.progress_list_row_dict[download_item_obj.item_id],
)
self.progress_list_liststore.set(
self.progress_list_liststore.get_iter(tree_path),
2,
self.pixbuf_dict['arrow_down_small'],
) | [
"def",
"on_progress_list_dl_last",
"(",
"self",
",",
"menu_item",
",",
"download_item_obj",
")",
":",
"if",
"DEBUG_FUNC_FLAG",
":",
"utils",
".",
"debug_time",
"(",
"'mwn 15308 on_progress_list_dl_last'",
")",
"# Check that, since the popup menu was created, the media data obje... | https://github.com/axcore/tartube/blob/36dd493642923fe8b9190a41db596c30c043ae90/tartube/mainwin.py#L16768-L16812 | ||
llSourcell/AI_Artist | 3038c06c2e389b9c919c881c9a169efe2fd7810e | lib/python2.7/site-packages/pip/_vendor/pyparsing.py | python | ZeroOrMore.__init__ | ( self, expr, stopOn=None) | [] | def __init__( self, expr, stopOn=None):
super(ZeroOrMore,self).__init__(expr, stopOn=stopOn)
self.mayReturnEmpty = True | [
"def",
"__init__",
"(",
"self",
",",
"expr",
",",
"stopOn",
"=",
"None",
")",
":",
"super",
"(",
"ZeroOrMore",
",",
"self",
")",
".",
"__init__",
"(",
"expr",
",",
"stopOn",
"=",
"stopOn",
")",
"self",
".",
"mayReturnEmpty",
"=",
"True"
] | https://github.com/llSourcell/AI_Artist/blob/3038c06c2e389b9c919c881c9a169efe2fd7810e/lib/python2.7/site-packages/pip/_vendor/pyparsing.py#L2882-L2884 | ||||
jonathf/chaospy | f1a1ba52b87285afdb65ceaf7f8a3a27907bf25e | chaospy/quadrature/genz_keister.py | python | genz_keister | (order, dist=None, rule=24) | return nodes, weights | Create Genz-Keister quadrature nodes and weights.
Args:
order (int, Sequence[int]):
The order of the quadrature.
dist (Optional[chaospy.Distribution]):
The distribution which density will be used as weight function.
If omitted, standard Gaussian is assumed.
rule (int, Sequence[int]):
The Genz-Keister rule name. Supported rules are 16, 18, 22 and 24.
Returns:
(numpy.ndarray, numpy.ndarray):
Genz-Keister quadrature abscissas and weights.
Examples:
>>> genz_keister(0)
(array([[0.]]), array([1.]))
>>> genz_keister(1) # doctest: +NORMALIZE_WHITESPACE
(array([[-1.73205081, 0. , 1.73205081]]),
array([0.16666667, 0.66666667, 0.16666667])) | Create Genz-Keister quadrature nodes and weights. | [
"Create",
"Genz",
"-",
"Keister",
"quadrature",
"nodes",
"and",
"weights",
"."
] | def genz_keister(order, dist=None, rule=24):
"""
Create Genz-Keister quadrature nodes and weights.
Args:
order (int, Sequence[int]):
The order of the quadrature.
dist (Optional[chaospy.Distribution]):
The distribution which density will be used as weight function.
If omitted, standard Gaussian is assumed.
rule (int, Sequence[int]):
The Genz-Keister rule name. Supported rules are 16, 18, 22 and 24.
Returns:
(numpy.ndarray, numpy.ndarray):
Genz-Keister quadrature abscissas and weights.
Examples:
>>> genz_keister(0)
(array([[0.]]), array([1.]))
>>> genz_keister(1) # doctest: +NORMALIZE_WHITESPACE
(array([[-1.73205081, 0. , 1.73205081]]),
array([0.16666667, 0.66666667, 0.16666667]))
"""
shape = (1,) if dist is None else (len(dist),)
order = numpy.broadcast_to(order, shape)
rule = numpy.broadcast_to(rule, shape)
nodes, weights = zip(*[_genz_keister(order_, rule_)
for order_, rule_ in zip(order, rule)])
nodes, weights = combine_quadrature(nodes, weights)
if dist is not None:
nodes = dist.inv(scipy.special.ndtr(nodes))
return nodes, weights | [
"def",
"genz_keister",
"(",
"order",
",",
"dist",
"=",
"None",
",",
"rule",
"=",
"24",
")",
":",
"shape",
"=",
"(",
"1",
",",
")",
"if",
"dist",
"is",
"None",
"else",
"(",
"len",
"(",
"dist",
")",
",",
")",
"order",
"=",
"numpy",
".",
"broadcas... | https://github.com/jonathf/chaospy/blob/f1a1ba52b87285afdb65ceaf7f8a3a27907bf25e/chaospy/quadrature/genz_keister.py#L251-L284 | |
JimmXinu/FanFicFare | bc149a2deb2636320fe50a3e374af6eef8f61889 | included_dependencies/urllib3/util/retry.py | python | _RetryMeta.DEFAULT_METHOD_WHITELIST | (cls) | return cls.DEFAULT_ALLOWED_METHODS | [] | def DEFAULT_METHOD_WHITELIST(cls):
warnings.warn(
"Using 'Retry.DEFAULT_METHOD_WHITELIST' is deprecated and "
"will be removed in v2.0. Use 'Retry.DEFAULT_ALLOWED_METHODS' instead",
DeprecationWarning,
)
return cls.DEFAULT_ALLOWED_METHODS | [
"def",
"DEFAULT_METHOD_WHITELIST",
"(",
"cls",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Using 'Retry.DEFAULT_METHOD_WHITELIST' is deprecated and \"",
"\"will be removed in v2.0. Use 'Retry.DEFAULT_ALLOWED_METHODS' instead\"",
",",
"DeprecationWarning",
",",
")",
"return",
"cls",
... | https://github.com/JimmXinu/FanFicFare/blob/bc149a2deb2636320fe50a3e374af6eef8f61889/included_dependencies/urllib3/util/retry.py#L37-L43 | |||
spyder-ide/spyder | 55da47c032dfcf519600f67f8b30eab467f965e7 | spyder/plugins/editor/widgets/status.py | python | VCSStatus.process_git_data | (self, worker, output, error) | Receive data from git and update gui. | Receive data from git and update gui. | [
"Receive",
"data",
"from",
"git",
"and",
"update",
"gui",
"."
] | def process_git_data(self, worker, output, error):
"""Receive data from git and update gui."""
branches, branch, files_modified = output
text = branch if branch else ''
if len(files_modified):
text = text + ' [{}]'.format(len(files_modified))
self.setVisible(bool(branch))
self.set_value(text)
self._git_is_working = False
if self._git_job_queue:
self.update_vcs(*self._git_job_queue) | [
"def",
"process_git_data",
"(",
"self",
",",
"worker",
",",
"output",
",",
"error",
")",
":",
"branches",
",",
"branch",
",",
"files_modified",
"=",
"output",
"text",
"=",
"branch",
"if",
"branch",
"else",
"''",
"if",
"len",
"(",
"files_modified",
")",
"... | https://github.com/spyder-ide/spyder/blob/55da47c032dfcf519600f67f8b30eab467f965e7/spyder/plugins/editor/widgets/status.py#L118-L130 | ||
iopsgroup/imoocc | de810eb6d4c1697b7139305925a5b0ba21225f3f | scanhosts/modules/paramiko_old/proxy.py | python | ProxyCommand.send | (self, content) | return len(content) | Write the content received from the SSH client to the standard
input of the forked command.
@param content: string to be sent to the forked command
@type content: str | Write the content received from the SSH client to the standard
input of the forked command. | [
"Write",
"the",
"content",
"received",
"from",
"the",
"SSH",
"client",
"to",
"the",
"standard",
"input",
"of",
"the",
"forked",
"command",
"."
] | def send(self, content):
"""
Write the content received from the SSH client to the standard
input of the forked command.
@param content: string to be sent to the forked command
@type content: str
"""
try:
self.process.stdin.write(content)
except IOError, e:
# There was a problem with the child process. It probably
# died and we can't proceed. The best option here is to
# raise an exception informing the user that the informed
# ProxyCommand is not working.
raise BadProxyCommand(' '.join(self.cmd), e.strerror)
return len(content) | [
"def",
"send",
"(",
"self",
",",
"content",
")",
":",
"try",
":",
"self",
".",
"process",
".",
"stdin",
".",
"write",
"(",
"content",
")",
"except",
"IOError",
",",
"e",
":",
"# There was a problem with the child process. It probably",
"# died and we can't proceed... | https://github.com/iopsgroup/imoocc/blob/de810eb6d4c1697b7139305925a5b0ba21225f3f/scanhosts/modules/paramiko_old/proxy.py#L52-L68 | |
mongodb/pymodm | be1c7b079df4954ef7e79e46f1b4a9ac9510766c | pymodm/files.py | python | File.open | (self, mode='rb') | Open this file or seek to the beginning if already open. | Open this file or seek to the beginning if already open. | [
"Open",
"this",
"file",
"or",
"seek",
"to",
"the",
"beginning",
"if",
"already",
"open",
"."
] | def open(self, mode='rb'):
"""Open this file or seek to the beginning if already open."""
if self.closed:
self.file = open(self.file.name, mode)
else:
self.file.seek(0) | [
"def",
"open",
"(",
"self",
",",
"mode",
"=",
"'rb'",
")",
":",
"if",
"self",
".",
"closed",
":",
"self",
".",
"file",
"=",
"open",
"(",
"self",
".",
"file",
".",
"name",
",",
"mode",
")",
"else",
":",
"self",
".",
"file",
".",
"seek",
"(",
"... | https://github.com/mongodb/pymodm/blob/be1c7b079df4954ef7e79e46f1b4a9ac9510766c/pymodm/files.py#L175-L180 | ||
DxCx/plugin.video.9anime | 34358c2f701e5ddf19d3276926374a16f63f7b6a | resources/lib/ui/js2py/legecy_translators/nodevisitor.py | python | js_not | (a) | return a+'.neg()' | [] | def js_not(a):
return a+'.neg()' | [
"def",
"js_not",
"(",
"a",
")",
":",
"return",
"a",
"+",
"'.neg()'"
] | https://github.com/DxCx/plugin.video.9anime/blob/34358c2f701e5ddf19d3276926374a16f63f7b6a/resources/lib/ui/js2py/legecy_translators/nodevisitor.py#L373-L374 | |||
SCSSoftware/BlenderTools | 96f323d3bdf2d8cb8ed7f882dcdf036277a802dd | addon/io_scs_tools/properties/object.py | python | ObjectAnimationInventoryItem.anim_range_update | (self, context) | If start or end frame are changed frame range in scene should be adopted to new values
together with FPS reset. | If start or end frame are changed frame range in scene should be adopted to new values
together with FPS reset. | [
"If",
"start",
"or",
"end",
"frame",
"are",
"changed",
"frame",
"range",
"in",
"scene",
"should",
"be",
"adopted",
"to",
"new",
"values",
"together",
"with",
"FPS",
"reset",
"."
] | def anim_range_update(self, context):
"""If start or end frame are changed frame range in scene should be adopted to new values
together with FPS reset.
"""
active_object = context.active_object
if active_object and active_object.type == "ARMATURE" and active_object.animation_data:
action = active_object.animation_data.action
if action:
_animation_utils.set_frame_range(context.scene, self.anim_start, self.anim_end)
_animation_utils.set_fps_for_preview(
context.scene,
self.length,
self.anim_start,
self.anim_end,
) | [
"def",
"anim_range_update",
"(",
"self",
",",
"context",
")",
":",
"active_object",
"=",
"context",
".",
"active_object",
"if",
"active_object",
"and",
"active_object",
".",
"type",
"==",
"\"ARMATURE\"",
"and",
"active_object",
".",
"animation_data",
":",
"action"... | https://github.com/SCSSoftware/BlenderTools/blob/96f323d3bdf2d8cb8ed7f882dcdf036277a802dd/addon/io_scs_tools/properties/object.py#L195-L211 | ||
hellofresh/eks-rolling-update | 70306efbf8d9a6c587d8f82af60d995827122537 | eksrollup/lib/aws.py | python | get_asg_tag | (tags, tag_name) | return result | Returns a tag on a list of asg tags | Returns a tag on a list of asg tags | [
"Returns",
"a",
"tag",
"on",
"a",
"list",
"of",
"asg",
"tags"
] | def get_asg_tag(tags, tag_name):
"""
Returns a tag on a list of asg tags
"""
result = {}
for tag in tags:
for key, val in tag.items():
if val == tag_name:
result = tag
return result | [
"def",
"get_asg_tag",
"(",
"tags",
",",
"tag_name",
")",
":",
"result",
"=",
"{",
"}",
"for",
"tag",
"in",
"tags",
":",
"for",
"key",
",",
"val",
"in",
"tag",
".",
"items",
"(",
")",
":",
"if",
"val",
"==",
"tag_name",
":",
"result",
"=",
"tag",
... | https://github.com/hellofresh/eks-rolling-update/blob/70306efbf8d9a6c587d8f82af60d995827122537/eksrollup/lib/aws.py#L412-L421 | |
hzlzh/AlfredWorkflow.com | 7055f14f6922c80ea5943839eb0caff11ae57255 | Sources/Workflows/nuomituangou/alp/request/requests/packages/urllib3/packages/ordered_dict.py | python | OrderedDict.viewitems | (self) | return ItemsView(self) | od.viewitems() -> a set-like object providing a view on od's items | od.viewitems() -> a set-like object providing a view on od's items | [
"od",
".",
"viewitems",
"()",
"-",
">",
"a",
"set",
"-",
"like",
"object",
"providing",
"a",
"view",
"on",
"od",
"s",
"items"
] | def viewitems(self):
"od.viewitems() -> a set-like object providing a view on od's items"
return ItemsView(self) | [
"def",
"viewitems",
"(",
"self",
")",
":",
"return",
"ItemsView",
"(",
"self",
")"
] | https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/nuomituangou/alp/request/requests/packages/urllib3/packages/ordered_dict.py#L258-L260 | |
DamnWidget/anaconda | a9998fb362320f907d5ccbc6fcf5b62baca677c0 | commands/vagrant.py | python | AnacondaVagrantBase.print_status | (self, edit: sublime.Edit) | Print the vagrant command output string into a Sublime Text panel | Print the vagrant command output string into a Sublime Text panel | [
"Print",
"the",
"vagrant",
"command",
"output",
"string",
"into",
"a",
"Sublime",
"Text",
"panel"
] | def print_status(self, edit: sublime.Edit) -> None:
"""Print the vagrant command output string into a Sublime Text panel
"""
vagrant_panel = self.view.window().create_output_panel(
'anaconda_vagrant'
)
vagrant_panel.set_read_only(False)
region = sublime.Region(0, vagrant_panel.size())
vagrant_panel.erase(edit, region)
vagrant_panel.insert(edit, 0, self.data.decode('utf8'))
self.data = None
vagrant_panel.set_read_only(True)
vagrant_panel.show(0)
self.view.window().run_command(
'show_panel', {'panel': 'output.anaconda_vagrant'}
) | [
"def",
"print_status",
"(",
"self",
",",
"edit",
":",
"sublime",
".",
"Edit",
")",
"->",
"None",
":",
"vagrant_panel",
"=",
"self",
".",
"view",
".",
"window",
"(",
")",
".",
"create_output_panel",
"(",
"'anaconda_vagrant'",
")",
"vagrant_panel",
".",
"set... | https://github.com/DamnWidget/anaconda/blob/a9998fb362320f907d5ccbc6fcf5b62baca677c0/commands/vagrant.py#L34-L51 | ||
igraph/python-igraph | e9f83e8af08f24ea025596e745917197d8b44d94 | src/igraph/drawing/__init__.py | python | Plot.mark_dirty | (self) | Marks the plot as dirty (should be redrawn) | Marks the plot as dirty (should be redrawn) | [
"Marks",
"the",
"plot",
"as",
"dirty",
"(",
"should",
"be",
"redrawn",
")"
] | def mark_dirty(self):
"""Marks the plot as dirty (should be redrawn)"""
self._is_dirty = True | [
"def",
"mark_dirty",
"(",
"self",
")",
":",
"self",
".",
"_is_dirty",
"=",
"True"
] | https://github.com/igraph/python-igraph/blob/e9f83e8af08f24ea025596e745917197d8b44d94/src/igraph/drawing/__init__.py#L253-L255 | ||
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/lib-python/3/multiprocessing/sharedctypes.py | python | copy | (obj) | return new_obj | [] | def copy(obj):
new_obj = _new_value(type(obj))
ctypes.pointer(new_obj)[0] = obj
return new_obj | [
"def",
"copy",
"(",
"obj",
")",
":",
"new_obj",
"=",
"_new_value",
"(",
"type",
"(",
"obj",
")",
")",
"ctypes",
".",
"pointer",
"(",
"new_obj",
")",
"[",
"0",
"]",
"=",
"obj",
"return",
"new_obj"
] | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/multiprocessing/sharedctypes.py#L121-L124 | |||
stoq/stoq | c26991644d1affcf96bc2e0a0434796cabdf8448 | stoqlib/domain/payment/payment.py | python | Payment.is_cancelled | (self) | return self.status == Payment.STATUS_CANCELLED | Check if the payment was cancelled.
:returns: ``True`` if the payment was cancelled | Check if the payment was cancelled. | [
"Check",
"if",
"the",
"payment",
"was",
"cancelled",
"."
] | def is_cancelled(self):
"""Check if the payment was cancelled.
:returns: ``True`` if the payment was cancelled
"""
return self.status == Payment.STATUS_CANCELLED | [
"def",
"is_cancelled",
"(",
"self",
")",
":",
"return",
"self",
".",
"status",
"==",
"Payment",
".",
"STATUS_CANCELLED"
] | https://github.com/stoq/stoq/blob/c26991644d1affcf96bc2e0a0434796cabdf8448/stoqlib/domain/payment/payment.py#L598-L603 | |
Pymol-Scripts/Pymol-script-repo | bcd7bb7812dc6db1595953dfa4471fa15fb68c77 | modules/pdb2pqr/src/aa.py | python | Amino.addDihedralAngle | (self, value) | Add the value to the list of chiangles
Parameters
value: The value to be added (float) | Add the value to the list of chiangles | [
"Add",
"the",
"value",
"to",
"the",
"list",
"of",
"chiangles"
] | def addDihedralAngle(self, value):
"""
Add the value to the list of chiangles
Parameters
value: The value to be added (float)
"""
self.dihedrals.append(value) | [
"def",
"addDihedralAngle",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"dihedrals",
".",
"append",
"(",
"value",
")"
] | https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/modules/pdb2pqr/src/aa.py#L140-L147 | ||
kuri65536/python-for-android | 26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891 | python3-alpha/python-libs/gdata/youtube/service.py | python | YouTubeService.GetFormUploadToken | (self, video_entry, uri=YOUTUBE_UPLOAD_TOKEN_URI) | return (post_url, youtube_token) | Receives a YouTube Token and a YouTube PostUrl from a YouTubeVideoEntry.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to upload (meta-data only).
uri: An optional string representing the URI from where to fetch the
token information. Defaults to the YOUTUBE_UPLOADTOKEN_URI.
Returns:
A tuple containing the URL to which to post your video file, along
with the youtube token that must be included with your upload in the
form of: (post_url, youtube_token). | Receives a YouTube Token and a YouTube PostUrl from a YouTubeVideoEntry. | [
"Receives",
"a",
"YouTube",
"Token",
"and",
"a",
"YouTube",
"PostUrl",
"from",
"a",
"YouTubeVideoEntry",
"."
] | def GetFormUploadToken(self, video_entry, uri=YOUTUBE_UPLOAD_TOKEN_URI):
"""Receives a YouTube Token and a YouTube PostUrl from a YouTubeVideoEntry.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to upload (meta-data only).
uri: An optional string representing the URI from where to fetch the
token information. Defaults to the YOUTUBE_UPLOADTOKEN_URI.
Returns:
A tuple containing the URL to which to post your video file, along
with the youtube token that must be included with your upload in the
form of: (post_url, youtube_token).
"""
try:
response = self.Post(video_entry, uri)
except gdata.service.RequestError as e:
raise YouTubeError(e.args[0])
tree = ElementTree.fromstring(response)
for child in tree:
if child.tag == 'url':
post_url = child.text
elif child.tag == 'token':
youtube_token = child.text
return (post_url, youtube_token) | [
"def",
"GetFormUploadToken",
"(",
"self",
",",
"video_entry",
",",
"uri",
"=",
"YOUTUBE_UPLOAD_TOKEN_URI",
")",
":",
"try",
":",
"response",
"=",
"self",
".",
"Post",
"(",
"video_entry",
",",
"uri",
")",
"except",
"gdata",
".",
"service",
".",
"RequestError"... | https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python3-alpha/python-libs/gdata/youtube/service.py#L700-L727 | |
andresriancho/w3af | cd22e5252243a87aaa6d0ddea47cf58dacfe00a9 | w3af/plugins/attack/db/sqlmap/thirdparty/beautifulsoup/beautifulsoup.py | python | ResultSet.__init__ | (self, source) | [] | def __init__(self, source):
list.__init__([])
self.source = source | [
"def",
"__init__",
"(",
"self",
",",
"source",
")",
":",
"list",
".",
"__init__",
"(",
"[",
"]",
")",
"self",
".",
"source",
"=",
"source"
] | https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/plugins/attack/db/sqlmap/thirdparty/beautifulsoup/beautifulsoup.py#L1016-L1018 | ||||
googleads/google-ads-python | 2a1d6062221f6aad1992a6bcca0e7e4a93d2db86 | google/ads/googleads/v9/services/services/asset_service/client.py | python | AssetServiceClient.common_billing_account_path | (billing_account: str,) | return "billingAccounts/{billing_account}".format(
billing_account=billing_account,
) | Return a fully-qualified billing_account string. | Return a fully-qualified billing_account string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"billing_account",
"string",
"."
] | def common_billing_account_path(billing_account: str,) -> str:
"""Return a fully-qualified billing_account string."""
return "billingAccounts/{billing_account}".format(
billing_account=billing_account,
) | [
"def",
"common_billing_account_path",
"(",
"billing_account",
":",
"str",
",",
")",
"->",
"str",
":",
"return",
"\"billingAccounts/{billing_account}\"",
".",
"format",
"(",
"billing_account",
"=",
"billing_account",
",",
")"
] | https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v9/services/services/asset_service/client.py#L212-L216 | |
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/manifolds/section_module.py | python | SectionModule.vector_bundle | (self) | return self._vbundle | r"""
Return the overlying vector bundle on which the section module is
defined.
EXAMPLES::
sage: M = Manifold(3, 'M', structure='top')
sage: E = M.vector_bundle(2, 'E')
sage: C0 = E.section_module(); C0
Module C^0(M;E) of sections on the 3-dimensional topological
manifold M with values in the real vector bundle E of rank 2
sage: C0.vector_bundle()
Topological real vector bundle E -> M of rank 2 over the base space
3-dimensional topological manifold M
sage: E is C0.vector_bundle()
True | r"""
Return the overlying vector bundle on which the section module is
defined. | [
"r",
"Return",
"the",
"overlying",
"vector",
"bundle",
"on",
"which",
"the",
"section",
"module",
"is",
"defined",
"."
] | def vector_bundle(self):
r"""
Return the overlying vector bundle on which the section module is
defined.
EXAMPLES::
sage: M = Manifold(3, 'M', structure='top')
sage: E = M.vector_bundle(2, 'E')
sage: C0 = E.section_module(); C0
Module C^0(M;E) of sections on the 3-dimensional topological
manifold M with values in the real vector bundle E of rank 2
sage: C0.vector_bundle()
Topological real vector bundle E -> M of rank 2 over the base space
3-dimensional topological manifold M
sage: E is C0.vector_bundle()
True
"""
return self._vbundle | [
"def",
"vector_bundle",
"(",
"self",
")",
":",
"return",
"self",
".",
"_vbundle"
] | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/manifolds/section_module.py#L378-L397 | |
quodlibet/quodlibet | e3099c89f7aa6524380795d325cc14630031886c | quodlibet/qltk/pluginwin.py | python | PluginWindow.unfilter | (self) | Clears all filters applied to the list | Clears all filters applied to the list | [
"Clears",
"all",
"filters",
"applied",
"to",
"the",
"list"
] | def unfilter(self):
"""Clears all filters applied to the list"""
self._enabled_combo.set_active(0)
self._type_combo.set_active(0)
self._filter_entry.set_text(u"") | [
"def",
"unfilter",
"(",
"self",
")",
":",
"self",
".",
"_enabled_combo",
".",
"set_active",
"(",
"0",
")",
"self",
".",
"_type_combo",
".",
"set_active",
"(",
"0",
")",
"self",
".",
"_filter_entry",
".",
"set_text",
"(",
"u\"\"",
")"
] | https://github.com/quodlibet/quodlibet/blob/e3099c89f7aa6524380795d325cc14630031886c/quodlibet/qltk/pluginwin.py#L519-L524 | ||
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/tradfri/__init__.py | python | async_setup | (hass: HomeAssistant, config: ConfigType) | return True | Set up the Tradfri component. | Set up the Tradfri component. | [
"Set",
"up",
"the",
"Tradfri",
"component",
"."
] | async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the Tradfri component."""
if (conf := config.get(DOMAIN)) is None:
return True
configured_hosts = [
entry.data.get("host") for entry in hass.config_entries.async_entries(DOMAIN)
]
host = conf.get(CONF_HOST)
import_groups = conf[CONF_ALLOW_TRADFRI_GROUPS]
if host is None or host in configured_hosts:
return True
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data={CONF_HOST: host, CONF_IMPORT_GROUPS: import_groups},
)
)
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
":",
"HomeAssistant",
",",
"config",
":",
"ConfigType",
")",
"->",
"bool",
":",
"if",
"(",
"conf",
":=",
"config",
".",
"get",
"(",
"DOMAIN",
")",
")",
"is",
"None",
":",
"return",
"True",
"configured_hosts",
... | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/tradfri/__init__.py#L61-L84 | |
prody/ProDy | b24bbf58aa8fffe463c8548ae50e3955910e5b7f | prody/ensemble/conformation.py | python | Conformation.numAtoms | (self) | return self._ensemble.numAtoms() | Returns number of atoms. | Returns number of atoms. | [
"Returns",
"number",
"of",
"atoms",
"."
] | def numAtoms(self):
"""Returns number of atoms."""
return self._ensemble.numAtoms() | [
"def",
"numAtoms",
"(",
"self",
")",
":",
"return",
"self",
".",
"_ensemble",
".",
"numAtoms",
"(",
")"
] | https://github.com/prody/ProDy/blob/b24bbf58aa8fffe463c8548ae50e3955910e5b7f/prody/ensemble/conformation.py#L35-L38 | |
awslabs/autogluon | 7309118f2ab1c9519f25acf61a283a95af95842b | core/src/autogluon/core/utils/utils.py | python | get_gpu_count_mxnet | () | return num_gpus | [] | def get_gpu_count_mxnet():
try:
import mxnet
num_gpus = mxnet.context.num_gpus()
except Exception:
num_gpus = 0
return num_gpus | [
"def",
"get_gpu_count_mxnet",
"(",
")",
":",
"try",
":",
"import",
"mxnet",
"num_gpus",
"=",
"mxnet",
".",
"context",
".",
"num_gpus",
"(",
")",
"except",
"Exception",
":",
"num_gpus",
"=",
"0",
"return",
"num_gpus"
] | https://github.com/awslabs/autogluon/blob/7309118f2ab1c9519f25acf61a283a95af95842b/core/src/autogluon/core/utils/utils.py#L54-L60 | |||
ninja-ide/ninja-ide | 87d91131bd19fdc3dcfd91eb97ad1e41c49c60c0 | ninja_ide/dependencies/pycodestyle.py | python | read_config | (options, args, arglist, parser) | return options | Read and parse configurations.
If a config file is specified on the command line with the "--config"
option, then only it is used for configuration.
Otherwise, the user configuration (~/.config/pycodestyle) and any local
configurations in the current directory or above will be merged together
(in that order) using the read method of ConfigParser. | Read and parse configurations. | [
"Read",
"and",
"parse",
"configurations",
"."
] | def read_config(options, args, arglist, parser):
"""Read and parse configurations.
If a config file is specified on the command line with the "--config"
option, then only it is used for configuration.
Otherwise, the user configuration (~/.config/pycodestyle) and any local
configurations in the current directory or above will be merged together
(in that order) using the read method of ConfigParser.
"""
config = RawConfigParser()
cli_conf = options.config
local_dir = os.curdir
if USER_CONFIG and os.path.isfile(USER_CONFIG):
if options.verbose:
print('user configuration: %s' % USER_CONFIG)
config.read(USER_CONFIG)
parent = tail = args and os.path.abspath(os.path.commonprefix(args))
while tail:
if config.read(os.path.join(parent, fn) for fn in PROJECT_CONFIG):
local_dir = parent
if options.verbose:
print('local configuration: in %s' % parent)
break
(parent, tail) = os.path.split(parent)
if cli_conf and os.path.isfile(cli_conf):
if options.verbose:
print('cli configuration: %s' % cli_conf)
config.read(cli_conf)
pycodestyle_section = None
if config.has_section(parser.prog):
pycodestyle_section = parser.prog
elif config.has_section('pep8'):
pycodestyle_section = 'pep8' # Deprecated
warnings.warn('[pep8] section is deprecated. Use [pycodestyle].')
if pycodestyle_section:
option_list = dict([(o.dest, o.type or o.action)
for o in parser.option_list])
# First, read the default values
(new_options, __) = parser.parse_args([])
# Second, parse the configuration
for opt in config.options(pycodestyle_section):
if opt.replace('_', '-') not in parser.config_options:
print(" unknown option '%s' ignored" % opt)
continue
if options.verbose > 1:
print(" %s = %s" % (opt,
config.get(pycodestyle_section, opt)))
normalized_opt = opt.replace('-', '_')
opt_type = option_list[normalized_opt]
if opt_type in ('int', 'count'):
value = config.getint(pycodestyle_section, opt)
elif opt_type in ('store_true', 'store_false'):
value = config.getboolean(pycodestyle_section, opt)
else:
value = config.get(pycodestyle_section, opt)
if normalized_opt == 'exclude':
value = normalize_paths(value, local_dir)
setattr(new_options, normalized_opt, value)
# Third, overwrite with the command-line options
(options, __) = parser.parse_args(arglist, values=new_options)
options.doctest = options.testsuite = False
return options | [
"def",
"read_config",
"(",
"options",
",",
"args",
",",
"arglist",
",",
"parser",
")",
":",
"config",
"=",
"RawConfigParser",
"(",
")",
"cli_conf",
"=",
"options",
".",
"config",
"local_dir",
"=",
"os",
".",
"curdir",
"if",
"USER_CONFIG",
"and",
"os",
".... | https://github.com/ninja-ide/ninja-ide/blob/87d91131bd19fdc3dcfd91eb97ad1e41c49c60c0/ninja_ide/dependencies/pycodestyle.py#L2148-L2220 | |
nlloyd/SubliminalCollaborator | 5c619e17ddbe8acb9eea8996ec038169ddcd50a1 | libs/zope/interface/interfaces.py | python | IInterfaceDeclaration.classImplements | (class_, *interfaces) | Declare additional interfaces implemented for instances of a class
The arguments after the class are one or more interfaces or
interface specifications (IDeclaration objects).
The interfaces given (including the interfaces in the
specifications) are added to any interfaces previously
declared.
Consider the following example::
class C(A, B):
...
classImplements(C, I1, I2)
Instances of ``C`` provide ``I1``, ``I2``, and whatever interfaces
instances of ``A`` and ``B`` provide. | Declare additional interfaces implemented for instances of a class | [
"Declare",
"additional",
"interfaces",
"implemented",
"for",
"instances",
"of",
"a",
"class"
] | def classImplements(class_, *interfaces):
"""Declare additional interfaces implemented for instances of a class
The arguments after the class are one or more interfaces or
interface specifications (IDeclaration objects).
The interfaces given (including the interfaces in the
specifications) are added to any interfaces previously
declared.
Consider the following example::
class C(A, B):
...
classImplements(C, I1, I2)
Instances of ``C`` provide ``I1``, ``I2``, and whatever interfaces
instances of ``A`` and ``B`` provide.
""" | [
"def",
"classImplements",
"(",
"class_",
",",
"*",
"interfaces",
")",
":"
] | https://github.com/nlloyd/SubliminalCollaborator/blob/5c619e17ddbe8acb9eea8996ec038169ddcd50a1/libs/zope/interface/interfaces.py#L401-L421 | ||
out0fmemory/GoAgent-Always-Available | c4254984fea633ce3d1893fe5901debd9f22c2a9 | server/lib/google/appengine/datastore/datastore_query.py | python | Batch.skipped_results | (self) | return self._skipped_results | The number of results skipped because of an offset in the request.
An offset is satisfied before any results are returned. The start_cursor
points to the position in the query before the skipped results. | The number of results skipped because of an offset in the request. | [
"The",
"number",
"of",
"results",
"skipped",
"because",
"of",
"an",
"offset",
"in",
"the",
"request",
"."
] | def skipped_results(self):
"""The number of results skipped because of an offset in the request.
An offset is satisfied before any results are returned. The start_cursor
points to the position in the query before the skipped results.
"""
return self._skipped_results | [
"def",
"skipped_results",
"(",
"self",
")",
":",
"return",
"self",
".",
"_skipped_results"
] | https://github.com/out0fmemory/GoAgent-Always-Available/blob/c4254984fea633ce3d1893fe5901debd9f22c2a9/server/lib/google/appengine/datastore/datastore_query.py#L2663-L2669 | |
SCSSoftware/BlenderTools | 96f323d3bdf2d8cb8ed7f882dcdf036277a802dd | addon/io_scs_tools/internals/shaders/eut2/dif_anim/anim_blend_factor_ng.py | python | __create_node_group__ | () | Creates add env group.
Inputs: Fresnel Scale, Fresnel Bias, Normal Vector, View Vector, Apply Fresnel,
Reflection Texture Color, Base Texture Alpha, Env Factor Color and Specular Color
Outputs: Environment Addition Color | Creates add env group. | [
"Creates",
"add",
"env",
"group",
"."
] | def __create_node_group__():
"""Creates add env group.
Inputs: Fresnel Scale, Fresnel Bias, Normal Vector, View Vector, Apply Fresnel,
Reflection Texture Color, Base Texture Alpha, Env Factor Color and Specular Color
Outputs: Environment Addition Color
"""
start_pos_x = 0
start_pos_y = 0
pos_x_shift = 185
blend_fac_g = bpy.data.node_groups.new(type="ShaderNodeTree", name=BLEND_FACTOR_G)
# inputs defining
blend_fac_g.inputs.new("NodeSocketFloat", "Speed")
input_n = blend_fac_g.nodes.new("NodeGroupInput")
input_n.location = (start_pos_x - pos_x_shift, start_pos_y)
# outputs defining
blend_fac_g.outputs.new("NodeSocketColor", "Factor")
output_n = blend_fac_g.nodes.new("NodeGroupOutput")
output_n.location = (start_pos_x + pos_x_shift * 9, start_pos_y)
# node creation
anim_time_n = blend_fac_g.nodes.new("ShaderNodeValue")
anim_time_n.name = anim_time_n.label = _ANIM_TIME_NODE
anim_time_n.location = (start_pos_x, start_pos_y + 200)
equation_nodes = []
for i, name in enumerate(("(Time*Speed)", "((Time*Speed)/3)", "((Time*Speed)/3)*2", "((Time*Speed)/3)*2*3.14159",
"sin(((Time*Speed)/3)*2*3.14159)", "sin(((Time*Speed)/3)*2*3.14159)/2",
"sin(((Time*Speed)/3)*2*3.14159)/2+0.5")):
# node creation
equation_nodes.append(blend_fac_g.nodes.new("ShaderNodeMath"))
equation_nodes[i].name = equation_nodes[i].label = name
equation_nodes[i].location = (start_pos_x + pos_x_shift * (1 + i), start_pos_y)
# links creation and settings
if i == 0:
equation_nodes[i].operation = "MULTIPLY"
blend_fac_g.links.new(equation_nodes[i].inputs[0], anim_time_n.outputs[0])
blend_fac_g.links.new(equation_nodes[i].inputs[1], input_n.outputs['Speed'])
elif i == 1:
equation_nodes[i].operation = "DIVIDE"
equation_nodes[i].inputs[1].default_value = 3.0
blend_fac_g.links.new(equation_nodes[i].inputs[0], equation_nodes[i - 1].outputs[0])
elif i == 2:
equation_nodes[i].operation = "MULTIPLY"
equation_nodes[i].inputs[1].default_value = 2.0
blend_fac_g.links.new(equation_nodes[i].inputs[0], equation_nodes[i - 1].outputs[0])
elif i == 3:
equation_nodes[i].operation = "MULTIPLY"
equation_nodes[i].inputs[1].default_value = 3.14159
blend_fac_g.links.new(equation_nodes[i].inputs[0], equation_nodes[i - 1].outputs[0])
elif i == 4:
equation_nodes[i].operation = "SINE"
equation_nodes[i].inputs[1].default_value = 0.0
blend_fac_g.links.new(equation_nodes[i].inputs[0], equation_nodes[i - 1].outputs[0])
elif i == 5:
equation_nodes[i].operation = "DIVIDE"
equation_nodes[i].inputs[1].default_value = 2.0
blend_fac_g.links.new(equation_nodes[i].inputs[0], equation_nodes[i - 1].outputs[0])
elif i == 6:
equation_nodes[i].operation = "ADD"
equation_nodes[i].inputs[1].default_value = 0.5
blend_fac_g.links.new(equation_nodes[i].inputs[0], equation_nodes[i - 1].outputs[0])
# output
blend_fac_g.links.new(output_n.inputs['Factor'], equation_nodes[i].outputs[0]) | [
"def",
"__create_node_group__",
"(",
")",
":",
"start_pos_x",
"=",
"0",
"start_pos_y",
"=",
"0",
"pos_x_shift",
"=",
"185",
"blend_fac_g",
"=",
"bpy",
".",
"data",
".",
"node_groups",
".",
"new",
"(",
"type",
"=",
"\"ShaderNodeTree\"",
",",
"name",
"=",
"B... | https://github.com/SCSSoftware/BlenderTools/blob/96f323d3bdf2d8cb8ed7f882dcdf036277a802dd/addon/io_scs_tools/internals/shaders/eut2/dif_anim/anim_blend_factor_ng.py#L56-L141 | ||
jakewaldron/PlexEmail | 8e560407a87f58e02d1f1e8048dacb9be6e35c03 | scripts/cloudinary/poster/encode.py | python | multipart_yielder.next | (self) | return advance_iterator(self) | generator function to yield multipart/form-data representation
of parameters | generator function to yield multipart/form-data representation
of parameters | [
"generator",
"function",
"to",
"yield",
"multipart",
"/",
"form",
"-",
"data",
"representation",
"of",
"parameters"
] | def next(self):
"""generator function to yield multipart/form-data representation
of parameters"""
if self.param_iter is not None:
try:
block = advance_iterator(self.param_iter)
self.current += len(block)
if self.cb:
self.cb(self.p, self.current, self.total)
return block
except StopIteration:
self.p = None
self.param_iter = None
if self.i is None:
raise StopIteration
elif self.i >= len(self.params):
self.param_iter = None
self.p = None
self.i = None
block = to_bytes("--%s--\r\n" % self.boundary)
self.current += len(block)
if self.cb:
self.cb(self.p, self.current, self.total)
return block
self.p = self.params[self.i]
self.param_iter = self.p.iter_encode(self.boundary)
self.i += 1
return advance_iterator(self) | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"param_iter",
"is",
"not",
"None",
":",
"try",
":",
"block",
"=",
"advance_iterator",
"(",
"self",
".",
"param_iter",
")",
"self",
".",
"current",
"+=",
"len",
"(",
"block",
")",
"if",
"self",
... | https://github.com/jakewaldron/PlexEmail/blob/8e560407a87f58e02d1f1e8048dacb9be6e35c03/scripts/cloudinary/poster/encode.py#L356-L385 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/Python-2.7.9/Lib/smtpd.py | python | SMTPChannel.__init__ | (self, server, conn, addr) | [] | def __init__(self, server, conn, addr):
asynchat.async_chat.__init__(self, conn)
self.__server = server
self.__conn = conn
self.__addr = addr
self.__line = []
self.__state = self.COMMAND
self.__greeting = 0
self.__mailfrom = None
self.__rcpttos = []
self.__data = ''
self.__fqdn = socket.getfqdn()
try:
self.__peer = conn.getpeername()
except socket.error, err:
# a race condition may occur if the other end is closing
# before we can get the peername
self.close()
if err[0] != errno.ENOTCONN:
raise
return
print >> DEBUGSTREAM, 'Peer:', repr(self.__peer)
self.push('220 %s %s' % (self.__fqdn, __version__))
self.set_terminator('\r\n') | [
"def",
"__init__",
"(",
"self",
",",
"server",
",",
"conn",
",",
"addr",
")",
":",
"asynchat",
".",
"async_chat",
".",
"__init__",
"(",
"self",
",",
"conn",
")",
"self",
".",
"__server",
"=",
"server",
"self",
".",
"__conn",
"=",
"conn",
"self",
".",... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/smtpd.py#L109-L132 | ||||
ifwe/digsby | f5fe00244744aa131e07f09348d10563f3d8fa99 | digsby/src/common/Buddy.py | python | Buddy.buddy_icon | (self) | return get_buddy_icon(self, 32, False) | Returns a 32 pixel version of this buddy's icon (or the generic
replacement icon for buddies without icons). | Returns a 32 pixel version of this buddy's icon (or the generic
replacement icon for buddies without icons). | [
"Returns",
"a",
"32",
"pixel",
"version",
"of",
"this",
"buddy",
"s",
"icon",
"(",
"or",
"the",
"generic",
"replacement",
"icon",
"for",
"buddies",
"without",
"icons",
")",
"."
] | def buddy_icon(self):
'''
Returns a 32 pixel version of this buddy's icon (or the generic
replacement icon for buddies without icons).
'''
from gui.buddylist.renderers import get_buddy_icon
return get_buddy_icon(self, 32, False) | [
"def",
"buddy_icon",
"(",
"self",
")",
":",
"from",
"gui",
".",
"buddylist",
".",
"renderers",
"import",
"get_buddy_icon",
"return",
"get_buddy_icon",
"(",
"self",
",",
"32",
",",
"False",
")"
] | https://github.com/ifwe/digsby/blob/f5fe00244744aa131e07f09348d10563f3d8fa99/digsby/src/common/Buddy.py#L631-L638 | |
sympy/sympy | d822fcba181155b85ff2b29fe525adbafb22b448 | sympy/assumptions/refine.py | python | refine_re | (expr, assumptions) | return _refine_reim(expr, assumptions) | Handler for real part.
Examples
========
>>> from sympy.assumptions.refine import refine_re
>>> from sympy import Q, re
>>> from sympy.abc import x
>>> refine_re(re(x), Q.real(x))
x
>>> refine_re(re(x), Q.imaginary(x))
0 | Handler for real part. | [
"Handler",
"for",
"real",
"part",
"."
] | def refine_re(expr, assumptions):
"""
Handler for real part.
Examples
========
>>> from sympy.assumptions.refine import refine_re
>>> from sympy import Q, re
>>> from sympy.abc import x
>>> refine_re(re(x), Q.real(x))
x
>>> refine_re(re(x), Q.imaginary(x))
0
"""
arg = expr.args[0]
if ask(Q.real(arg), assumptions):
return arg
if ask(Q.imaginary(arg), assumptions):
return S.Zero
return _refine_reim(expr, assumptions) | [
"def",
"refine_re",
"(",
"expr",
",",
"assumptions",
")",
":",
"arg",
"=",
"expr",
".",
"args",
"[",
"0",
"]",
"if",
"ask",
"(",
"Q",
".",
"real",
"(",
"arg",
")",
",",
"assumptions",
")",
":",
"return",
"arg",
"if",
"ask",
"(",
"Q",
".",
"imag... | https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/assumptions/refine.py#L253-L273 | |
idanr1986/cuckoo-droid | 1350274639473d3d2b0ac740cae133ca53ab7444 | analyzer/android/lib/api/androguard/dvm.py | python | AnnotationsDirectoryItem.get_class_annotations_off | (self) | return self.class_annotations_off | Return the offset from the start of the file to the annotations made directly on the class,
or 0 if the class has no direct annotations
:rtype: int | Return the offset from the start of the file to the annotations made directly on the class,
or 0 if the class has no direct annotations | [
"Return",
"the",
"offset",
"from",
"the",
"start",
"of",
"the",
"file",
"to",
"the",
"annotations",
"made",
"directly",
"on",
"the",
"class",
"or",
"0",
"if",
"the",
"class",
"has",
"no",
"direct",
"annotations"
] | def get_class_annotations_off(self) :
"""
Return the offset from the start of the file to the annotations made directly on the class,
or 0 if the class has no direct annotations
:rtype: int
"""
return self.class_annotations_off | [
"def",
"get_class_annotations_off",
"(",
"self",
")",
":",
"return",
"self",
".",
"class_annotations_off"
] | https://github.com/idanr1986/cuckoo-droid/blob/1350274639473d3d2b0ac740cae133ca53ab7444/analyzer/android/lib/api/androguard/dvm.py#L898-L905 | |
pbugnion/gmaps | 9f37193e6daf6b7020481d15f7461a76cb3fc14e | gmaps/directions.py | python | directions_layer | (
start, end, waypoints=None, avoid_ferries=False,
travel_mode=DEFAULT_TRAVEL_MODE,
avoid_highways=False, avoid_tolls=False, optimize_waypoints=False,
show_markers=True, show_route=True, stroke_color=DEFAULT_STROKE_COLOR,
stroke_weight=6.0, stroke_opacity=0.6) | return Directions(**kwargs) | Create a directions layer.
Add this layer to a :class:`gmaps.Figure` instance to draw
directions on the map.
:Examples:
{examples}
{params}
:returns:
A :class:`gmaps.Directions` widget. | Create a directions layer. | [
"Create",
"a",
"directions",
"layer",
"."
] | def directions_layer(
start, end, waypoints=None, avoid_ferries=False,
travel_mode=DEFAULT_TRAVEL_MODE,
avoid_highways=False, avoid_tolls=False, optimize_waypoints=False,
show_markers=True, show_route=True, stroke_color=DEFAULT_STROKE_COLOR,
stroke_weight=6.0, stroke_opacity=0.6):
"""
Create a directions layer.
Add this layer to a :class:`gmaps.Figure` instance to draw
directions on the map.
:Examples:
{examples}
{params}
:returns:
A :class:`gmaps.Directions` widget.
"""
kwargs = {
'start': start,
'end': end,
'waypoints': waypoints,
'travel_mode': travel_mode,
'avoid_ferries': avoid_ferries,
'avoid_highways': avoid_highways,
'avoid_tolls': avoid_tolls,
'optimize_waypoints': optimize_waypoints,
'show_markers': show_markers,
'show_route': show_route,
'stroke_color': stroke_color,
'stroke_weight': stroke_weight,
'stroke_opacity': stroke_opacity
}
return Directions(**kwargs) | [
"def",
"directions_layer",
"(",
"start",
",",
"end",
",",
"waypoints",
"=",
"None",
",",
"avoid_ferries",
"=",
"False",
",",
"travel_mode",
"=",
"DEFAULT_TRAVEL_MODE",
",",
"avoid_highways",
"=",
"False",
",",
"avoid_tolls",
"=",
"False",
",",
"optimize_waypoint... | https://github.com/pbugnion/gmaps/blob/9f37193e6daf6b7020481d15f7461a76cb3fc14e/gmaps/directions.py#L246-L282 | |
TencentCloud/tencentcloud-sdk-python | 3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2 | tencentcloud/cvm/v20170312/models.py | python | EnhancedService.__init__ | (self) | r"""
:param SecurityService: 开启云安全服务。若不指定该参数,则默认开启云安全服务。
:type SecurityService: :class:`tencentcloud.cvm.v20170312.models.RunSecurityServiceEnabled`
:param MonitorService: 开启云监控服务。若不指定该参数,则默认开启云监控服务。
:type MonitorService: :class:`tencentcloud.cvm.v20170312.models.RunMonitorServiceEnabled`
:param AutomationService: 开启云自动化助手服务。若不指定该参数,则默认不开启云自动化助手服务。
:type AutomationService: :class:`tencentcloud.cvm.v20170312.models.RunAutomationServiceEnabled` | r"""
:param SecurityService: 开启云安全服务。若不指定该参数,则默认开启云安全服务。
:type SecurityService: :class:`tencentcloud.cvm.v20170312.models.RunSecurityServiceEnabled`
:param MonitorService: 开启云监控服务。若不指定该参数,则默认开启云监控服务。
:type MonitorService: :class:`tencentcloud.cvm.v20170312.models.RunMonitorServiceEnabled`
:param AutomationService: 开启云自动化助手服务。若不指定该参数,则默认不开启云自动化助手服务。
:type AutomationService: :class:`tencentcloud.cvm.v20170312.models.RunAutomationServiceEnabled` | [
"r",
":",
"param",
"SecurityService",
":",
"开启云安全服务。若不指定该参数,则默认开启云安全服务。",
":",
"type",
"SecurityService",
":",
":",
"class",
":",
"tencentcloud",
".",
"cvm",
".",
"v20170312",
".",
"models",
".",
"RunSecurityServiceEnabled",
":",
"param",
"MonitorService",
":",
"开... | def __init__(self):
r"""
:param SecurityService: 开启云安全服务。若不指定该参数,则默认开启云安全服务。
:type SecurityService: :class:`tencentcloud.cvm.v20170312.models.RunSecurityServiceEnabled`
:param MonitorService: 开启云监控服务。若不指定该参数,则默认开启云监控服务。
:type MonitorService: :class:`tencentcloud.cvm.v20170312.models.RunMonitorServiceEnabled`
:param AutomationService: 开启云自动化助手服务。若不指定该参数,则默认不开启云自动化助手服务。
:type AutomationService: :class:`tencentcloud.cvm.v20170312.models.RunAutomationServiceEnabled`
"""
self.SecurityService = None
self.MonitorService = None
self.AutomationService = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"SecurityService",
"=",
"None",
"self",
".",
"MonitorService",
"=",
"None",
"self",
".",
"AutomationService",
"=",
"None"
] | https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cvm/v20170312/models.py#L2947-L2958 | ||
StackStorm/st2 | 85ae05b73af422efd3097c9c05351f7f1cc8369e | st2common/st2common/content/utils.py | python | get_pack_resource_file_abs_path | (pack_ref, resource_type, file_path) | return result | Retrieve full absolute path to the pack resource file.
Note: This function also takes care of sanitizing ``file_name`` argument
preventing directory traversal and similar attacks.
:param pack_ref: Pack reference (needs to be the same as directory on disk).
:type pack_ref: ``str``
:param resource_type: Pack resource type (e.g. action, sensor, etc.).
:type resource_type: ``str``
:pack file_path: Resource file path relative to the pack directory (e.g. my_file.py or
directory/my_file.py)
:type file_path: ``str``
:rtype: ``str`` | Retrieve full absolute path to the pack resource file. | [
"Retrieve",
"full",
"absolute",
"path",
"to",
"the",
"pack",
"resource",
"file",
"."
] | def get_pack_resource_file_abs_path(pack_ref, resource_type, file_path):
"""
Retrieve full absolute path to the pack resource file.
Note: This function also takes care of sanitizing ``file_name`` argument
preventing directory traversal and similar attacks.
:param pack_ref: Pack reference (needs to be the same as directory on disk).
:type pack_ref: ``str``
:param resource_type: Pack resource type (e.g. action, sensor, etc.).
:type resource_type: ``str``
:pack file_path: Resource file path relative to the pack directory (e.g. my_file.py or
directory/my_file.py)
:type file_path: ``str``
:rtype: ``str``
"""
path_components = []
if resource_type == "action":
path_components.append("actions/")
elif resource_type == "sensor":
path_components.append("sensors/")
elif resource_type == "rule":
path_components.append("rules/")
else:
raise ValueError("Invalid resource type: %s" % (resource_type))
path_components.append(file_path)
file_path = os.path.join(*path_components) # pylint: disable=E1120
result = get_pack_file_abs_path(
pack_ref=pack_ref, file_path=file_path, resource_type=resource_type
)
return result | [
"def",
"get_pack_resource_file_abs_path",
"(",
"pack_ref",
",",
"resource_type",
",",
"file_path",
")",
":",
"path_components",
"=",
"[",
"]",
"if",
"resource_type",
"==",
"\"action\"",
":",
"path_components",
".",
"append",
"(",
"\"actions/\"",
")",
"elif",
"reso... | https://github.com/StackStorm/st2/blob/85ae05b73af422efd3097c9c05351f7f1cc8369e/st2common/st2common/content/utils.py#L318-L352 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.