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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/apps/accounting/forms.py | python | SuppressInvoiceForm.suppress_invoice | (self) | [] | def suppress_invoice(self):
self.invoice.is_hidden_to_ops = True
self.invoice.save() | [
"def",
"suppress_invoice",
"(",
"self",
")",
":",
"self",
".",
"invoice",
".",
"is_hidden_to_ops",
"=",
"True",
"self",
".",
"invoice",
".",
"save",
"(",
")"
] | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/accounting/forms.py#L2666-L2668 | ||||
openstack/barbican | a9d2b133c8dc3307974f119f9a2b23a4ba82e8ce | barbican/plugin/resources.py | python | _generate_symmetric_key | (
generate_plugin, key_spec, secret_model, project_model, content_type) | return secret_metadata | [] | def _generate_symmetric_key(
generate_plugin, key_spec, secret_model, project_model, content_type):
if isinstance(generate_plugin, store_crypto.StoreCryptoAdapterPlugin):
context = store_crypto.StoreCryptoContext(
project_model,
secret_model=secret_model,
content_type=content_type)
secret_metadata = generate_plugin.generate_symmetric_key(
key_spec, context)
else:
secret_metadata = generate_plugin.generate_symmetric_key(key_spec)
return secret_metadata | [
"def",
"_generate_symmetric_key",
"(",
"generate_plugin",
",",
"key_spec",
",",
"secret_model",
",",
"project_model",
",",
"content_type",
")",
":",
"if",
"isinstance",
"(",
"generate_plugin",
",",
"store_crypto",
".",
"StoreCryptoAdapterPlugin",
")",
":",
"context",
... | https://github.com/openstack/barbican/blob/a9d2b133c8dc3307974f119f9a2b23a4ba82e8ce/barbican/plugin/resources.py#L285-L296 | |||
NVIDIA/DeepLearningExamples | 589604d49e016cd9ef4525f7abcc9c7b826cfc5e | TensorFlow/Detection/SSD/models/research/object_detection/box_coders/mean_stddev_box_coder.py | python | MeanStddevBoxCoder._encode | (self, boxes, anchors) | return (box_corners - means) / self._stddev | Encode a box collection with respect to anchor collection.
Args:
boxes: BoxList holding N boxes to be encoded.
anchors: BoxList of N anchors.
Returns:
a tensor representing N anchor-encoded boxes
Raises:
ValueError: if the anchors still have deprecated stddev field. | Encode a box collection with respect to anchor collection. | [
"Encode",
"a",
"box",
"collection",
"with",
"respect",
"to",
"anchor",
"collection",
"."
] | def _encode(self, boxes, anchors):
"""Encode a box collection with respect to anchor collection.
Args:
boxes: BoxList holding N boxes to be encoded.
anchors: BoxList of N anchors.
Returns:
a tensor representing N anchor-encoded boxes
Raises:
ValueError: if the anchors still have deprecated stddev field.
"""
box_corners = boxes.get()
if anchors.has_field('stddev'):
raise ValueError("'stddev' is a parameter of MeanStddevBoxCoder and "
"should not be specified in the box list.")
means = anchors.get()
return (box_corners - means) / self._stddev | [
"def",
"_encode",
"(",
"self",
",",
"boxes",
",",
"anchors",
")",
":",
"box_corners",
"=",
"boxes",
".",
"get",
"(",
")",
"if",
"anchors",
".",
"has_field",
"(",
"'stddev'",
")",
":",
"raise",
"ValueError",
"(",
"\"'stddev' is a parameter of MeanStddevBoxCoder... | https://github.com/NVIDIA/DeepLearningExamples/blob/589604d49e016cd9ef4525f7abcc9c7b826cfc5e/TensorFlow/Detection/SSD/models/research/object_detection/box_coders/mean_stddev_box_coder.py#L40-L58 | |
deepgram/kur | fd0c120e50815c1e5be64e5dde964dcd47234556 | kur/containers/operators/for_loop.py | python | ForLoop.__init__ | (self, *args, **kwargs) | Create a new for loop. | Create a new for loop. | [
"Create",
"a",
"new",
"for",
"loop",
"."
] | def __init__(self, *args, **kwargs):
""" Create a new for loop.
"""
super().__init__(*args, **kwargs)
self.limit = None
self.index = None | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"limit",
"=",
"None",
"self",
".",
"index",
"=",
"None"
] | https://github.com/deepgram/kur/blob/fd0c120e50815c1e5be64e5dde964dcd47234556/kur/containers/operators/for_loop.py#L48-L53 | ||
Qiskit/qiskit-terra | b66030e3b9192efdd3eb95cf25c6545fe0a13da4 | qiskit/opflow/state_fns/cvar_measurement.py | python | CVaRMeasurement.traverse | (
self, convert_fn: Callable, coeff: Optional[Union[complex, ParameterExpression]] = None
) | return self | r"""
Apply the convert_fn to the internal primitive if the primitive is an Operator (as in
the case of ``OperatorStateFn``). Otherwise do nothing. Used by converters.
Args:
convert_fn: The function to apply to the internal OperatorBase.
coeff: A coefficient to multiply by after applying convert_fn.
If it is None, self.coeff is used instead.
Returns:
The converted StateFn. | r"""
Apply the convert_fn to the internal primitive if the primitive is an Operator (as in
the case of ``OperatorStateFn``). Otherwise do nothing. Used by converters. | [
"r",
"Apply",
"the",
"convert_fn",
"to",
"the",
"internal",
"primitive",
"if",
"the",
"primitive",
"is",
"an",
"Operator",
"(",
"as",
"in",
"the",
"case",
"of",
"OperatorStateFn",
")",
".",
"Otherwise",
"do",
"nothing",
".",
"Used",
"by",
"converters",
"."... | def traverse(
self, convert_fn: Callable, coeff: Optional[Union[complex, ParameterExpression]] = None
) -> OperatorBase:
r"""
Apply the convert_fn to the internal primitive if the primitive is an Operator (as in
the case of ``OperatorStateFn``). Otherwise do nothing. Used by converters.
Args:
convert_fn: The function to apply to the internal OperatorBase.
coeff: A coefficient to multiply by after applying convert_fn.
If it is None, self.coeff is used instead.
Returns:
The converted StateFn.
"""
if coeff is None:
coeff = self.coeff
if isinstance(self.primitive, OperatorBase):
return self.__class__(convert_fn(self.primitive), coeff=coeff, alpha=self._alpha)
return self | [
"def",
"traverse",
"(",
"self",
",",
"convert_fn",
":",
"Callable",
",",
"coeff",
":",
"Optional",
"[",
"Union",
"[",
"complex",
",",
"ParameterExpression",
"]",
"]",
"=",
"None",
")",
"->",
"OperatorBase",
":",
"if",
"coeff",
"is",
"None",
":",
"coeff",... | https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/opflow/state_fns/cvar_measurement.py#L323-L343 | |
yt-project/yt | dc7b24f9b266703db4c843e329c6c8644d47b824 | yt/data_objects/derived_quantities.py | python | SampleAtMaxFieldValues.reduce_intermediate | (self, values) | return [val[i] for val in values] | [] | def reduce_intermediate(self, values):
i = self._func(values[0]) # ma is values[0]
return [val[i] for val in values] | [
"def",
"reduce_intermediate",
"(",
"self",
",",
"values",
")",
":",
"i",
"=",
"self",
".",
"_func",
"(",
"values",
"[",
"0",
"]",
")",
"# ma is values[0]",
"return",
"[",
"val",
"[",
"i",
"]",
"for",
"val",
"in",
"values",
"]"
] | https://github.com/yt-project/yt/blob/dc7b24f9b266703db4c843e329c6c8644d47b824/yt/data_objects/derived_quantities.py#L669-L671 | |||
4shadoww/hakkuframework | 409a11fc3819d251f86faa3473439f8c19066a21 | lib/urllib3/contrib/securetransport.py | python | WrappedSocket._custom_validate | (self, verify, trust_bundle) | Called when we have set custom validation. We do this in two cases:
first, when cert validation is entirely disabled; and second, when
using a custom trust DB.
Raises an SSLError if the connection is not trusted. | Called when we have set custom validation. We do this in two cases:
first, when cert validation is entirely disabled; and second, when
using a custom trust DB.
Raises an SSLError if the connection is not trusted. | [
"Called",
"when",
"we",
"have",
"set",
"custom",
"validation",
".",
"We",
"do",
"this",
"in",
"two",
"cases",
":",
"first",
"when",
"cert",
"validation",
"is",
"entirely",
"disabled",
";",
"and",
"second",
"when",
"using",
"a",
"custom",
"trust",
"DB",
"... | def _custom_validate(self, verify, trust_bundle):
"""
Called when we have set custom validation. We do this in two cases:
first, when cert validation is entirely disabled; and second, when
using a custom trust DB.
Raises an SSLError if the connection is not trusted.
"""
# If we disabled cert validation, just say: cool.
if not verify:
return
successes = (
SecurityConst.kSecTrustResultUnspecified,
SecurityConst.kSecTrustResultProceed,
)
try:
trust_result = self._evaluate_trust(trust_bundle)
if trust_result in successes:
return
reason = "error code: %d" % (trust_result,)
except Exception as e:
# Do not trust on error
reason = "exception: %r" % (e,)
# SecureTransport does not send an alert nor shuts down the connection.
rec = _build_tls_unknown_ca_alert(self.version())
self.socket.sendall(rec)
# close the connection immediately
# l_onoff = 1, activate linger
# l_linger = 0, linger for 0 seoncds
opts = struct.pack("ii", 1, 0)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, opts)
self.close()
raise ssl.SSLError("certificate verify failed, %s" % reason) | [
"def",
"_custom_validate",
"(",
"self",
",",
"verify",
",",
"trust_bundle",
")",
":",
"# If we disabled cert validation, just say: cool.",
"if",
"not",
"verify",
":",
"return",
"successes",
"=",
"(",
"SecurityConst",
".",
"kSecTrustResultUnspecified",
",",
"SecurityCons... | https://github.com/4shadoww/hakkuframework/blob/409a11fc3819d251f86faa3473439f8c19066a21/lib/urllib3/contrib/securetransport.py#L399-L432 | ||
ewels/MultiQC | 9b953261d3d684c24eef1827a5ce6718c847a5af | multiqc/modules/biscuit/biscuit.py | python | MultiqcModule.parse_logs_covdist_q40_base_botgc | (self, f, fn) | return self.parse_logs_covdist_all_base(f, fn) | Handled by parse_logs_covdist_all_base() | Handled by parse_logs_covdist_all_base() | [
"Handled",
"by",
"parse_logs_covdist_all_base",
"()"
] | def parse_logs_covdist_q40_base_botgc(self, f, fn):
"""Handled by parse_logs_covdist_all_base()"""
return self.parse_logs_covdist_all_base(f, fn) | [
"def",
"parse_logs_covdist_q40_base_botgc",
"(",
"self",
",",
"f",
",",
"fn",
")",
":",
"return",
"self",
".",
"parse_logs_covdist_all_base",
"(",
"f",
",",
"fn",
")"
] | https://github.com/ewels/MultiQC/blob/9b953261d3d684c24eef1827a5ce6718c847a5af/multiqc/modules/biscuit/biscuit.py#L865-L867 | |
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/full/bdb.py | python | user_exception | (self, frame, exc_info) | Called when we stop on an exception. | Called when we stop on an exception. | [
"Called",
"when",
"we",
"stop",
"on",
"an",
"exception",
"."
] | def user_exception(self, frame, exc_info):
"""Called when we stop on an exception."""
pass | [
"def",
"user_exception",
"(",
"self",
",",
"frame",
",",
"exc_info",
")",
":",
"pass"
] | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/bdb.py#L271-L273 | ||
openstack/cinder | 23494a6d6c51451688191e1847a458f1d3cdcaa5 | cinder/volume/drivers/ibm/ibm_storage/xiv_proxy.py | python | XIVProxy._update_consistencygroup | (self, context, group,
add_volumes=None, remove_volumes=None) | return model_update, None, None | Updates a consistency group. | Updates a consistency group. | [
"Updates",
"a",
"consistency",
"group",
"."
] | def _update_consistencygroup(self, context, group,
add_volumes=None, remove_volumes=None):
"""Updates a consistency group."""
cgname = self._cg_name_from_group(group)
LOG.info("Updating consistency group %(name)s.", {'name': cgname})
model_update = {'status': fields.GroupStatus.AVAILABLE}
add_volumes_update = []
if add_volumes:
for volume in add_volumes:
try:
self._call_xiv_xcli(
"cg_add_vol", vol=volume['name'], cg=cgname)
except errors.XCLIError as e:
error = (_("Failed adding volume %(vol)s to "
"consistency group %(cg)s: %(err)s")
% {'vol': volume['name'],
'cg': cgname,
'err':
self._get_code_and_status_or_message(e)})
LOG.error(error)
self._cleanup_consistencygroup_update(
context, group, add_volumes_update, None)
raise self._get_exception()(error)
add_volumes_update.append({'name': volume['name']})
remove_volumes_update = []
if remove_volumes:
for volume in remove_volumes:
try:
self._call_xiv_xcli(
"cg_remove_vol", vol=volume['name'])
except (errors.VolumeNotInConsGroup,
errors.VolumeBadNameError) as e:
# ignore the error if the volume exists in storage but
# not in cg, or the volume does not exist in the storage
details = self._get_code_and_status_or_message(e)
LOG.debug(details)
except errors.XCLIError as e:
error = (_("Failed removing volume %(vol)s from "
"consistency group %(cg)s: %(err)s")
% {'vol': volume['name'],
'cg': cgname,
'err':
self._get_code_and_status_or_message(e)})
LOG.error(error)
self._cleanup_consistencygroup_update(
context, group, add_volumes_update,
remove_volumes_update)
raise self._get_exception()(error)
remove_volumes_update.append({'name': volume['name']})
return model_update, None, None | [
"def",
"_update_consistencygroup",
"(",
"self",
",",
"context",
",",
"group",
",",
"add_volumes",
"=",
"None",
",",
"remove_volumes",
"=",
"None",
")",
":",
"cgname",
"=",
"self",
".",
"_cg_name_from_group",
"(",
"group",
")",
"LOG",
".",
"info",
"(",
"\"U... | https://github.com/openstack/cinder/blob/23494a6d6c51451688191e1847a458f1d3cdcaa5/cinder/volume/drivers/ibm/ibm_storage/xiv_proxy.py#L2078-L2131 | |
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AdminServer/appscale/admin/routing/haproxy.py | python | HAProxy.__init__ | (self, instance, config_location, stats_socket) | Creates a new HAProxy operator. | Creates a new HAProxy operator. | [
"Creates",
"a",
"new",
"HAProxy",
"operator",
"."
] | def __init__(self, instance, config_location, stats_socket):
""" Creates a new HAProxy operator. """
self.connect_timeout_ms = self.DEFAULT_CONNECT_TIMEOUT * 1000
self.client_timeout_ms = self.DEFAULT_CLIENT_TIMEOUT * 1000
self.server_timeout_ms = self.DEFAULT_SERVER_TIMEOUT * 1000
self.blocks = {}
self.reload_future = None
self._instance = instance
self._config_location = config_location
self._stats_socket = stats_socket
# Given the arbitrary base of the monotonic clock, it doesn't make sense
# for outside functions to access this attribute.
self._last_reload = monotonic.monotonic() | [
"def",
"__init__",
"(",
"self",
",",
"instance",
",",
"config_location",
",",
"stats_socket",
")",
":",
"self",
".",
"connect_timeout_ms",
"=",
"self",
".",
"DEFAULT_CONNECT_TIMEOUT",
"*",
"1000",
"self",
".",
"client_timeout_ms",
"=",
"self",
".",
"DEFAULT_CLIE... | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AdminServer/appscale/admin/routing/haproxy.py#L114-L128 | ||
entropy1337/infernal-twin | 10995cd03312e39a48ade0f114ebb0ae3a711bb8 | Modules/build/pip/build/lib.linux-i686-2.7/pip/_vendor/pkg_resources/__init__.py | python | WorkingSet.subscribe | (self, callback) | Invoke `callback` for all distributions (including existing ones) | Invoke `callback` for all distributions (including existing ones) | [
"Invoke",
"callback",
"for",
"all",
"distributions",
"(",
"including",
"existing",
"ones",
")"
] | def subscribe(self, callback):
"""Invoke `callback` for all distributions (including existing ones)"""
if callback in self.callbacks:
return
self.callbacks.append(callback)
for dist in self:
callback(dist) | [
"def",
"subscribe",
"(",
"self",
",",
"callback",
")",
":",
"if",
"callback",
"in",
"self",
".",
"callbacks",
":",
"return",
"self",
".",
"callbacks",
".",
"append",
"(",
"callback",
")",
"for",
"dist",
"in",
"self",
":",
"callback",
"(",
"dist",
")"
] | https://github.com/entropy1337/infernal-twin/blob/10995cd03312e39a48ade0f114ebb0ae3a711bb8/Modules/build/pip/build/lib.linux-i686-2.7/pip/_vendor/pkg_resources/__init__.py#L953-L959 | ||
Eugeny/reconfigure | ff1115dede4b80222a2618d0e7657cafa36a2573 | reconfigure/items/squid.py | python | HTTPPortData.template | (self) | return Node(
'line',
PropertyNode('name', 'http_port'),
Node('arguments', PropertyNode('1', '3128'))
) | [] | def template(self):
return Node(
'line',
PropertyNode('name', 'http_port'),
Node('arguments', PropertyNode('1', '3128'))
) | [
"def",
"template",
"(",
"self",
")",
":",
"return",
"Node",
"(",
"'line'",
",",
"PropertyNode",
"(",
"'name'",
",",
"'http_port'",
")",
",",
"Node",
"(",
"'arguments'",
",",
"PropertyNode",
"(",
"'1'",
",",
"'3128'",
")",
")",
")"
] | https://github.com/Eugeny/reconfigure/blob/ff1115dede4b80222a2618d0e7657cafa36a2573/reconfigure/items/squid.py#L39-L44 | |||
DevTable/gantryd | eb348113f0f73a0be45a45f7a5626ad2b5dd30ba | runtime/component.py | python | Component.lookupExportedComponentLink | (self, link_name) | Looks up the exported component link with the given name and returns it or None if none. | Looks up the exported component link with the given name and returns it or None if none. | [
"Looks",
"up",
"the",
"exported",
"component",
"link",
"with",
"the",
"given",
"name",
"and",
"returns",
"it",
"or",
"None",
"if",
"none",
"."
] | def lookupExportedComponentLink(self, link_name):
""" Looks up the exported component link with the given name and returns it or None if none. """
pass | [
"def",
"lookupExportedComponentLink",
"(",
"self",
",",
"link_name",
")",
":",
"pass"
] | https://github.com/DevTable/gantryd/blob/eb348113f0f73a0be45a45f7a5626ad2b5dd30ba/runtime/component.py#L37-L39 | ||
deepmind/dm_control | 806a10e896e7c887635328bfa8352604ad0fedae | dm_control/autowrap/codegen_util.py | python | recursive_dict_lookup | (key, try_dict, max_depth=10) | return key | Recursively map dictionary keys to values. | Recursively map dictionary keys to values. | [
"Recursively",
"map",
"dictionary",
"keys",
"to",
"values",
"."
] | def recursive_dict_lookup(key, try_dict, max_depth=10):
"""Recursively map dictionary keys to values."""
if max_depth < 0:
raise KeyError("Maximum recursion depth exceeded")
while key in try_dict:
key = try_dict[key]
return recursive_dict_lookup(key, try_dict, max_depth - 1)
return key | [
"def",
"recursive_dict_lookup",
"(",
"key",
",",
"try_dict",
",",
"max_depth",
"=",
"10",
")",
":",
"if",
"max_depth",
"<",
"0",
":",
"raise",
"KeyError",
"(",
"\"Maximum recursion depth exceeded\"",
")",
"while",
"key",
"in",
"try_dict",
":",
"key",
"=",
"t... | https://github.com/deepmind/dm_control/blob/806a10e896e7c887635328bfa8352604ad0fedae/dm_control/autowrap/codegen_util.py#L137-L144 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/celery/app/amqp.py | python | Queues.deselect | (self, exclude) | Deselect queues so that they won't be consumed from.
Arguments:
exclude (Sequence[str], str): Names of queues to avoid
consuming from. | Deselect queues so that they won't be consumed from. | [
"Deselect",
"queues",
"so",
"that",
"they",
"won",
"t",
"be",
"consumed",
"from",
"."
] | def deselect(self, exclude):
"""Deselect queues so that they won't be consumed from.
Arguments:
exclude (Sequence[str], str): Names of queues to avoid
consuming from.
"""
if exclude:
exclude = maybe_list(exclude)
if self._consume_from is None:
# using selection
return self.select(k for k in self if k not in exclude)
# using all queues
for queue in exclude:
self._consume_from.pop(queue, None) | [
"def",
"deselect",
"(",
"self",
",",
"exclude",
")",
":",
"if",
"exclude",
":",
"exclude",
"=",
"maybe_list",
"(",
"exclude",
")",
"if",
"self",
".",
"_consume_from",
"is",
"None",
":",
"# using selection",
"return",
"self",
".",
"select",
"(",
"k",
"for... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/celery/app/amqp.py#L191-L205 | ||
googleads/google-ads-python | 2a1d6062221f6aad1992a6bcca0e7e4a93d2db86 | examples/remarketing/add_customer_match_user_list.py | python | _build_offline_user_data_job_operations | (client) | return [
user_data_with_email_address_operation,
user_data_with_physical_address_operation,
] | Builds and returns two sample offline user data job operations.
Args:
client: The Google Ads client.
Returns:
A list containing the operations. | Builds and returns two sample offline user data job operations. | [
"Builds",
"and",
"returns",
"two",
"sample",
"offline",
"user",
"data",
"job",
"operations",
"."
] | def _build_offline_user_data_job_operations(client):
"""Builds and returns two sample offline user data job operations.
Args:
client: The Google Ads client.
Returns:
A list containing the operations.
"""
# Creates a first user data based on an email address.
user_data_with_email_address_operation = client.get_type(
"OfflineUserDataJobOperation"
)
user_data_with_email_address = user_data_with_email_address_operation.create
user_identifier_with_hashed_email = client.get_type("UserIdentifier")
# Hash normalized email addresses based on SHA-256 hashing algorithm.
user_identifier_with_hashed_email.hashed_email = _normalize_and_hash(
"customer@example.com"
)
user_data_with_email_address.user_identifiers.append(
user_identifier_with_hashed_email
)
# Creates a second user data based on a physical address.
user_data_with_physical_address_operation = client.get_type(
"OfflineUserDataJobOperation"
)
user_data_with_physical_address = (
user_data_with_physical_address_operation.create
)
user_identifier_with_address = client.get_type("UserIdentifier")
# First and last name must be normalized and hashed.
user_identifier_with_address.address_info.hashed_first_name = _normalize_and_hash(
"John"
)
user_identifier_with_address.address_info.hashed_last_name = _normalize_and_hash(
"Doe"
)
# Country and zip codes are sent in plain text.
user_identifier_with_address.address_info.country_code = "US"
user_identifier_with_address.address_info.postal_code = "10011"
user_data_with_physical_address.user_identifiers.append(
user_identifier_with_address
)
return [
user_data_with_email_address_operation,
user_data_with_physical_address_operation,
] | [
"def",
"_build_offline_user_data_job_operations",
"(",
"client",
")",
":",
"# Creates a first user data based on an email address.",
"user_data_with_email_address_operation",
"=",
"client",
".",
"get_type",
"(",
"\"OfflineUserDataJobOperation\"",
")",
"user_data_with_email_address",
... | https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/examples/remarketing/add_customer_match_user_list.py#L193-L241 | |
kubernetes-client/python | 47b9da9de2d02b2b7a34fbe05afb44afd130d73a | kubernetes/client/models/v1_json_schema_props.py | python | V1JSONSchemaProps.max_properties | (self) | return self._max_properties | Gets the max_properties of this V1JSONSchemaProps. # noqa: E501
:return: The max_properties of this V1JSONSchemaProps. # noqa: E501
:rtype: int | Gets the max_properties of this V1JSONSchemaProps. # noqa: E501 | [
"Gets",
"the",
"max_properties",
"of",
"this",
"V1JSONSchemaProps",
".",
"#",
"noqa",
":",
"E501"
] | def max_properties(self):
"""Gets the max_properties of this V1JSONSchemaProps. # noqa: E501
:return: The max_properties of this V1JSONSchemaProps. # noqa: E501
:rtype: int
"""
return self._max_properties | [
"def",
"max_properties",
"(",
"self",
")",
":",
"return",
"self",
".",
"_max_properties"
] | https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_json_schema_props.py#L698-L705 | |
robinhood/faust | 01b4c0ad8390221db71751d80001b0fd879291e2 | faust/app/base.py | python | App.commit | (self, topics: TPorTopicSet) | return await self.topics.commit(topics) | Commit offset for acked messages in specified topics'.
Warning:
This will commit acked messages in **all topics**
if the topics argument is passed in as :const:`None`. | Commit offset for acked messages in specified topics'. | [
"Commit",
"offset",
"for",
"acked",
"messages",
"in",
"specified",
"topics",
"."
] | async def commit(self, topics: TPorTopicSet) -> bool:
"""Commit offset for acked messages in specified topics'.
Warning:
This will commit acked messages in **all topics**
if the topics argument is passed in as :const:`None`.
"""
return await self.topics.commit(topics) | [
"async",
"def",
"commit",
"(",
"self",
",",
"topics",
":",
"TPorTopicSet",
")",
"->",
"bool",
":",
"return",
"await",
"self",
".",
"topics",
".",
"commit",
"(",
"topics",
")"
] | https://github.com/robinhood/faust/blob/01b4c0ad8390221db71751d80001b0fd879291e2/faust/app/base.py#L1456-L1463 | |
jliljebl/flowblade | 995313a509b80e99eb1ad550d945bdda5995093b | flowblade-trunk/Flowblade/editorwindow.py | python | EditorWindow.connect_player | (self, mltplayer) | [] | def connect_player(self, mltplayer):
# Buttons
# NOTE: ORDER OF CALLBACKS IS THE SAME AS ORDER OF BUTTONS FROM LEFT TO RIGHT
# Jul-2016 - SvdB - For play/pause button
if editorpersistance.prefs.play_pause == False:
# ------------------------------timeline_start_end_button
if (editorpersistance.prefs.timeline_start_end is True):
pressed_callback_funcs = [monitorevent.start_pressed, # go to start
monitorevent.end_pressed, # go to end
monitorevent.prev_pressed,
monitorevent.next_pressed,
monitorevent.play_pressed,
monitorevent.stop_pressed,
monitorevent.mark_in_pressed,
monitorevent.mark_out_pressed,
monitorevent.marks_clear_pressed,
monitorevent.to_mark_in_pressed,
monitorevent.to_mark_out_pressed]
else:
pressed_callback_funcs = [monitorevent.prev_pressed,
monitorevent.next_pressed,
monitorevent.play_pressed,
monitorevent.stop_pressed,
monitorevent.mark_in_pressed,
monitorevent.mark_out_pressed,
monitorevent.marks_clear_pressed,
monitorevent.to_mark_in_pressed,
monitorevent.to_mark_out_pressed]
else:
if (editorpersistance.prefs.timeline_start_end is True):
pressed_callback_funcs = [monitorevent.start_pressed, # go to start
monitorevent.end_pressed, # go to end
monitorevent.prev_pressed,
monitorevent.next_pressed,
monitorevent.play_pressed,
monitorevent.mark_in_pressed,
monitorevent.mark_out_pressed,
monitorevent.marks_clear_pressed,
monitorevent.to_mark_in_pressed,
monitorevent.to_mark_out_pressed]
else:
pressed_callback_funcs = [monitorevent.prev_pressed,
monitorevent.next_pressed,
monitorevent.play_pressed,
monitorevent.mark_in_pressed,
monitorevent.mark_out_pressed,
monitorevent.marks_clear_pressed,
monitorevent.to_mark_in_pressed,
monitorevent.to_mark_out_pressed]
self.player_buttons.set_callbacks(pressed_callback_funcs)
# Monitor position bar
self.pos_bar.set_listener(mltplayer.seek_position_normalized) | [
"def",
"connect_player",
"(",
"self",
",",
"mltplayer",
")",
":",
"# Buttons",
"# NOTE: ORDER OF CALLBACKS IS THE SAME AS ORDER OF BUTTONS FROM LEFT TO RIGHT",
"# Jul-2016 - SvdB - For play/pause button",
"if",
"editorpersistance",
".",
"prefs",
".",
"play_pause",
"==",
"False",
... | https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/editorwindow.py#L1432-L1485 | ||||
yt-project/yt | dc7b24f9b266703db4c843e329c6c8644d47b824 | yt/frontends/fits/data_structures.py | python | EventsFITSDataset.__init__ | (
self,
filename,
storage_filename=None,
suppress_astropy_warnings=True,
reblock=1,
parameters=None,
units_override=None,
unit_system="cgs",
) | [] | def __init__(
self,
filename,
storage_filename=None,
suppress_astropy_warnings=True,
reblock=1,
parameters=None,
units_override=None,
unit_system="cgs",
):
self.reblock = reblock
super().__init__(
filename,
nprocs=1,
storage_filename=storage_filename,
parameters=parameters,
suppress_astropy_warnings=suppress_astropy_warnings,
units_override=units_override,
unit_system=unit_system,
) | [
"def",
"__init__",
"(",
"self",
",",
"filename",
",",
"storage_filename",
"=",
"None",
",",
"suppress_astropy_warnings",
"=",
"True",
",",
"reblock",
"=",
"1",
",",
"parameters",
"=",
"None",
",",
"units_override",
"=",
"None",
",",
"unit_system",
"=",
"\"cg... | https://github.com/yt-project/yt/blob/dc7b24f9b266703db4c843e329c6c8644d47b824/yt/frontends/fits/data_structures.py#L849-L868 | ||||
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/client/ssh/wrapper/state.py | python | run_request | (name="default", **kwargs) | return {} | .. versionadded:: 2017.7.3
Execute the pending state request
CLI Example:
.. code-block:: bash
salt '*' state.run_request | .. versionadded:: 2017.7.3 | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"3"
] | def run_request(name="default", **kwargs):
"""
.. versionadded:: 2017.7.3
Execute the pending state request
CLI Example:
.. code-block:: bash
salt '*' state.run_request
"""
req = check_request()
if name not in req:
return {}
n_req = req[name]
if "mods" not in n_req or "kwargs" not in n_req:
return {}
req[name]["kwargs"].update(kwargs)
if "test" in n_req["kwargs"]:
n_req["kwargs"].pop("test")
if req:
ret = apply_(n_req["mods"], **n_req["kwargs"])
try:
os.remove(os.path.join(__opts__["cachedir"], "req_state.p"))
except OSError:
pass
return ret
return {} | [
"def",
"run_request",
"(",
"name",
"=",
"\"default\"",
",",
"*",
"*",
"kwargs",
")",
":",
"req",
"=",
"check_request",
"(",
")",
"if",
"name",
"not",
"in",
"req",
":",
"return",
"{",
"}",
"n_req",
"=",
"req",
"[",
"name",
"]",
"if",
"\"mods\"",
"no... | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/client/ssh/wrapper/state.py#L616-L644 | |
jiangxinyang227/NLP-Project | b11f67d8962f40e17990b4fc4551b0ea5496881c | multi_label_classifier/models/base.py | python | BaseModel.build_model | (self) | 创建模型
:return: | 创建模型
:return: | [
"创建模型",
":",
"return",
":"
] | def build_model(self):
"""
创建模型
:return:
"""
raise NotImplementedError | [
"def",
"build_model",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/jiangxinyang227/NLP-Project/blob/b11f67d8962f40e17990b4fc4551b0ea5496881c/multi_label_classifier/models/base.py#L88-L93 | ||
mchristopher/PokemonGo-DesktopMap | ec37575f2776ee7d64456e2a1f6b6b78830b4fe0 | app/pywin/Lib/abc.py | python | ABCMeta._dump_registry | (cls, file=None) | Debug helper to print the ABC registry. | Debug helper to print the ABC registry. | [
"Debug",
"helper",
"to",
"print",
"the",
"ABC",
"registry",
"."
] | def _dump_registry(cls, file=None):
"""Debug helper to print the ABC registry."""
print >> file, "Class: %s.%s" % (cls.__module__, cls.__name__)
print >> file, "Inv.counter: %s" % ABCMeta._abc_invalidation_counter
for name in sorted(cls.__dict__.keys()):
if name.startswith("_abc_"):
value = getattr(cls, name)
print >> file, "%s: %r" % (name, value) | [
"def",
"_dump_registry",
"(",
"cls",
",",
"file",
"=",
"None",
")",
":",
"print",
">>",
"file",
",",
"\"Class: %s.%s\"",
"%",
"(",
"cls",
".",
"__module__",
",",
"cls",
".",
"__name__",
")",
"print",
">>",
"file",
",",
"\"Inv.counter: %s\"",
"%",
"ABCMet... | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/ec37575f2776ee7d64456e2a1f6b6b78830b4fe0/app/pywin/Lib/abc.py#L119-L126 | ||
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/apps/aggregate_ucrs/column_specs.py | python | SecondaryColumnAdapter.create_index | (self) | return False | [] | def create_index(self):
return False | [
"def",
"create_index",
"(",
"self",
")",
":",
"return",
"False"
] | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/aggregate_ucrs/column_specs.py#L289-L290 | |||
openstack/nova | b49b7663e1c3073917d5844b81d38db8e86d05c4 | nova/virt/vmwareapi/driver.py | python | VMwareVCDriver.instance_exists | (self, instance) | return self._vmops.instance_exists(instance) | Efficient override of base instance_exists method. | Efficient override of base instance_exists method. | [
"Efficient",
"override",
"of",
"base",
"instance_exists",
"method",
"."
] | def instance_exists(self, instance):
"""Efficient override of base instance_exists method."""
return self._vmops.instance_exists(instance) | [
"def",
"instance_exists",
"(",
"self",
",",
"instance",
")",
":",
"return",
"self",
".",
"_vmops",
".",
"instance_exists",
"(",
"instance",
")"
] | https://github.com/openstack/nova/blob/b49b7663e1c3073917d5844b81d38db8e86d05c4/nova/virt/vmwareapi/driver.py#L710-L712 | |
google/turbinia | 4559d4af9267762a8995cfc415099a80a22ee4d3 | turbinia/workers/strings.py | python | StringsAsciiTask.run | (self, evidence, result) | return result | Run strings binary.
Args:
evidence (Evidence object): The evidence we will process.
result (TurbiniaTaskResult): The object to place task results into.
Returns:
TurbiniaTaskResult object. | Run strings binary. | [
"Run",
"strings",
"binary",
"."
] | def run(self, evidence, result):
"""Run strings binary.
Args:
evidence (Evidence object): The evidence we will process.
result (TurbiniaTaskResult): The object to place task results into.
Returns:
TurbiniaTaskResult object.
"""
# Create a path that we can write the new file to.
base_name = os.path.basename(evidence.device_path)
output_file_path = os.path.join(
self.output_dir, '{0:s}.ascii'.format(base_name))
# Create the new Evidence object that will be generated by this Task.
output_evidence = TextFile(source_path=output_file_path)
# Generate the command we want to run.
cmd = 'strings -a -t d {0:s} > {1:s}'.format(
evidence.device_path, output_file_path)
# Add a log line to the result that will be returned.
result.log('Running strings as [{0:s}]'.format(cmd))
# Actually execute the binary
self.execute(
cmd, result, new_evidence=[output_evidence], close=True, shell=True)
return result | [
"def",
"run",
"(",
"self",
",",
"evidence",
",",
"result",
")",
":",
"# Create a path that we can write the new file to.",
"base_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"evidence",
".",
"device_path",
")",
"output_file_path",
"=",
"os",
".",
"path",... | https://github.com/google/turbinia/blob/4559d4af9267762a8995cfc415099a80a22ee4d3/turbinia/workers/strings.py#L31-L57 | |
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/mailbox.py | python | MaildirMessage.__init__ | (self, message=None) | Initialize a MaildirMessage instance. | Initialize a MaildirMessage instance. | [
"Initialize",
"a",
"MaildirMessage",
"instance",
"."
] | def __init__(self, message=None):
"""Initialize a MaildirMessage instance."""
self._subdir = 'new'
self._info = ''
self._date = time.time()
Message.__init__(self, message) | [
"def",
"__init__",
"(",
"self",
",",
"message",
"=",
"None",
")",
":",
"self",
".",
"_subdir",
"=",
"'new'",
"self",
".",
"_info",
"=",
"''",
"self",
".",
"_date",
"=",
"time",
".",
"time",
"(",
")",
"Message",
".",
"__init__",
"(",
"self",
",",
... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/mailbox.py#L1528-L1533 | ||
kuri65536/python-for-android | 26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891 | python-build/python-libs/gdata/build/lib/gdata/apps/service.py | python | AppsService.GetGeneratorFromLinkFinder | (self, link_finder, func) | returns a generator for pagination | returns a generator for pagination | [
"returns",
"a",
"generator",
"for",
"pagination"
] | def GetGeneratorFromLinkFinder(self, link_finder, func):
"""returns a generator for pagination"""
yield link_finder
next = link_finder.GetNextLink()
while next is not None:
next_feed = func(str(self.Get(next.href)))
yield next_feed
next = next_feed.GetNextLink() | [
"def",
"GetGeneratorFromLinkFinder",
"(",
"self",
",",
"link_finder",
",",
"func",
")",
":",
"yield",
"link_finder",
"next",
"=",
"link_finder",
".",
"GetNextLink",
"(",
")",
"while",
"next",
"is",
"not",
"None",
":",
"next_feed",
"=",
"func",
"(",
"str",
... | https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-build/python-libs/gdata/build/lib/gdata/apps/service.py#L107-L114 | ||
JaniceWuo/MovieRecommend | 4c86db64ca45598917d304f535413df3bc9fea65 | movierecommend/venv1/Lib/site-packages/django/contrib/admin/filters.py | python | BooleanFieldListFilter.expected_parameters | (self) | return [self.lookup_kwarg, self.lookup_kwarg2] | [] | def expected_parameters(self):
return [self.lookup_kwarg, self.lookup_kwarg2] | [
"def",
"expected_parameters",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"lookup_kwarg",
",",
"self",
".",
"lookup_kwarg2",
"]"
] | https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/contrib/admin/filters.py#L242-L243 | |||
apple/ccs-calendarserver | 13c706b985fb728b9aab42dc0fef85aae21921c3 | txweb2/dav/resource.py | python | DAVResource.authorize | (self, request, privileges, recurse=False) | return d | See L{IDAVResource.authorize}. | See L{IDAVResource.authorize}. | [
"See",
"L",
"{",
"IDAVResource",
".",
"authorize",
"}",
"."
] | def authorize(self, request, privileges, recurse=False):
"""
See L{IDAVResource.authorize}.
"""
def whenAuthenticated(result):
privilegeCheck = self.checkPrivileges(request, privileges, recurse)
return privilegeCheck.addErrback(whenAccessDenied)
def whenAccessDenied(f):
f.trap(AccessDeniedError)
# If we were unauthenticated to start with (no
# Authorization header from client) then we should return
# an unauthorized response instead to force the client to
# login if it can.
# We're not adding the headers here because this response
# class is supposed to be a FORBIDDEN status code and
# "Authorization will not help" according to RFC2616
def translateError(response):
return Failure(HTTPError(response))
if request.authnUser == None:
return UnauthorizedResponse.makeResponse(
request.credentialFactories,
request.remoteAddr).addCallback(translateError)
else:
return translateError(
NeedPrivilegesResponse(request.uri, f.value.errors))
d = self.authenticate(request)
d.addCallback(whenAuthenticated)
return d | [
"def",
"authorize",
"(",
"self",
",",
"request",
",",
"privileges",
",",
"recurse",
"=",
"False",
")",
":",
"def",
"whenAuthenticated",
"(",
"result",
")",
":",
"privilegeCheck",
"=",
"self",
".",
"checkPrivileges",
"(",
"request",
",",
"privileges",
",",
... | https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txweb2/dav/resource.py#L916-L949 | |
huanghoujing/person-reid-triplet-loss-baseline | a1c2bd20180cfaf225782717aeaaab461798abec | script/experiment/train.py | python | main | () | [] | def main():
cfg = Config()
# Redirect logs to both console and file.
if cfg.log_to_file:
ReDirectSTD(cfg.stdout_file, 'stdout', False)
ReDirectSTD(cfg.stderr_file, 'stderr', False)
# Lazily create SummaryWriter
writer = None
TVT, TMO = set_devices(cfg.sys_device_ids)
if cfg.seed is not None:
set_seed(cfg.seed)
# Dump the configurations to log.
import pprint
print('-' * 60)
print('cfg.__dict__')
pprint.pprint(cfg.__dict__)
print('-' * 60)
###########
# Dataset #
###########
if not cfg.only_test:
train_set = create_dataset(**cfg.train_set_kwargs)
# The combined dataset does not provide val set currently.
val_set = None if cfg.dataset == 'combined' else create_dataset(**cfg.val_set_kwargs)
test_sets = []
test_set_names = []
if cfg.dataset == 'combined':
for name in ['market1501', 'cuhk03', 'duke']:
cfg.test_set_kwargs['name'] = name
test_sets.append(create_dataset(**cfg.test_set_kwargs))
test_set_names.append(name)
else:
test_sets.append(create_dataset(**cfg.test_set_kwargs))
test_set_names.append(cfg.dataset)
###########
# Models #
###########
model = Model(last_conv_stride=cfg.last_conv_stride)
# Model wrapper
model_w = DataParallel(model)
#############################
# Criteria and Optimizers #
#############################
tri_loss = TripletLoss(margin=cfg.margin)
optimizer = optim.Adam(model.parameters(),
lr=cfg.base_lr,
weight_decay=cfg.weight_decay)
# Bind them together just to save some codes in the following usage.
modules_optims = [model, optimizer]
################################
# May Resume Models and Optims #
################################
if cfg.resume:
resume_ep, scores = load_ckpt(modules_optims, cfg.ckpt_file)
# May Transfer Models and Optims to Specified Device. Transferring optimizer
# is to cope with the case when you load the checkpoint to a new device.
TMO(modules_optims)
########
# Test #
########
def test(load_model_weight=False):
if load_model_weight:
if cfg.model_weight_file != '':
map_location = (lambda storage, loc: storage)
sd = torch.load(cfg.model_weight_file, map_location=map_location)
load_state_dict(model, sd)
print('Loaded model weights from {}'.format(cfg.model_weight_file))
else:
load_ckpt(modules_optims, cfg.ckpt_file)
for test_set, name in zip(test_sets, test_set_names):
test_set.set_feat_func(ExtractFeature(model_w, TVT))
print('\n=========> Test on dataset: {} <=========\n'.format(name))
test_set.eval(
normalize_feat=cfg.normalize_feature,
verbose=True)
def validate():
if val_set.extract_feat_func is None:
val_set.set_feat_func(ExtractFeature(model_w, TVT))
print('\n=========> Test on validation set <=========\n')
mAP, cmc_scores, _, _ = val_set.eval(
normalize_feat=cfg.normalize_feature,
to_re_rank=False,
verbose=False)
print()
return mAP, cmc_scores[0]
if cfg.only_test:
test(load_model_weight=True)
return
############
# Training #
############
start_ep = resume_ep if cfg.resume else 0
for ep in range(start_ep, cfg.total_epochs):
# Adjust Learning Rate
if cfg.lr_decay_type == 'exp':
adjust_lr_exp(
optimizer,
cfg.base_lr,
ep + 1,
cfg.total_epochs,
cfg.exp_decay_at_epoch)
else:
adjust_lr_staircase(
optimizer,
cfg.base_lr,
ep + 1,
cfg.staircase_decay_at_epochs,
cfg.staircase_decay_multiply_factor)
may_set_mode(modules_optims, 'train')
# For recording precision, satisfying margin, etc
prec_meter = AverageMeter()
sm_meter = AverageMeter()
dist_ap_meter = AverageMeter()
dist_an_meter = AverageMeter()
loss_meter = AverageMeter()
ep_st = time.time()
step = 0
epoch_done = False
while not epoch_done:
step += 1
step_st = time.time()
ims, im_names, labels, mirrored, epoch_done = train_set.next_batch()
ims_var = Variable(TVT(torch.from_numpy(ims).float()))
labels_t = TVT(torch.from_numpy(labels).long())
feat = model_w(ims_var)
loss, p_inds, n_inds, dist_ap, dist_an, dist_mat = global_loss(
tri_loss, feat, labels_t,
normalize_feature=cfg.normalize_feature)
optimizer.zero_grad()
loss.backward()
optimizer.step()
############
# Step Log #
############
# precision
prec = (dist_an > dist_ap).data.float().mean()
# the proportion of triplets that satisfy margin
sm = (dist_an > dist_ap + cfg.margin).data.float().mean()
# average (anchor, positive) distance
d_ap = dist_ap.data.mean()
# average (anchor, negative) distance
d_an = dist_an.data.mean()
prec_meter.update(prec)
sm_meter.update(sm)
dist_ap_meter.update(d_ap)
dist_an_meter.update(d_an)
loss_meter.update(to_scalar(loss))
if step % cfg.steps_per_log == 0:
time_log = '\tStep {}/Ep {}, {:.2f}s'.format(
step, ep + 1, time.time() - step_st, )
tri_log = (', prec {:.2%}, sm {:.2%}, '
'd_ap {:.4f}, d_an {:.4f}, '
'loss {:.4f}'.format(
prec_meter.val, sm_meter.val,
dist_ap_meter.val, dist_an_meter.val,
loss_meter.val, ))
log = time_log + tri_log
print(log)
#############
# Epoch Log #
#############
time_log = 'Ep {}, {:.2f}s'.format(ep + 1, time.time() - ep_st)
tri_log = (', prec {:.2%}, sm {:.2%}, '
'd_ap {:.4f}, d_an {:.4f}, '
'loss {:.4f}'.format(
prec_meter.avg, sm_meter.avg,
dist_ap_meter.avg, dist_an_meter.avg,
loss_meter.avg, ))
log = time_log + tri_log
print(log)
##########################
# Test on Validation Set #
##########################
mAP, Rank1 = 0, 0
if ((ep + 1) % cfg.epochs_per_val == 0) and (val_set is not None):
mAP, Rank1 = validate()
# Log to TensorBoard
if cfg.log_to_file:
if writer is None:
writer = SummaryWriter(log_dir=osp.join(cfg.exp_dir, 'tensorboard'))
writer.add_scalars(
'val scores',
dict(mAP=mAP,
Rank1=Rank1),
ep)
writer.add_scalars(
'loss',
dict(loss=loss_meter.avg, ),
ep)
writer.add_scalars(
'precision',
dict(precision=prec_meter.avg, ),
ep)
writer.add_scalars(
'satisfy_margin',
dict(satisfy_margin=sm_meter.avg, ),
ep)
writer.add_scalars(
'average_distance',
dict(dist_ap=dist_ap_meter.avg,
dist_an=dist_an_meter.avg, ),
ep)
# save ckpt
if cfg.log_to_file:
save_ckpt(modules_optims, ep + 1, 0, cfg.ckpt_file)
########
# Test #
########
test(load_model_weight=False) | [
"def",
"main",
"(",
")",
":",
"cfg",
"=",
"Config",
"(",
")",
"# Redirect logs to both console and file.",
"if",
"cfg",
".",
"log_to_file",
":",
"ReDirectSTD",
"(",
"cfg",
".",
"stdout_file",
",",
"'stdout'",
",",
"False",
")",
"ReDirectSTD",
"(",
"cfg",
"."... | https://github.com/huanghoujing/person-reid-triplet-loss-baseline/blob/a1c2bd20180cfaf225782717aeaaab461798abec/script/experiment/train.py#L295-L554 | ||||
nipy/nipype | cd4c34d935a43812d1756482fdc4034844e485b8 | nipype/interfaces/base/traits_extension.py | python | _recurse_on_path_traits | (func, thistrait, value, cwd) | return value | Run func recursively on BasePath-derived traits. | Run func recursively on BasePath-derived traits. | [
"Run",
"func",
"recursively",
"on",
"BasePath",
"-",
"derived",
"traits",
"."
] | def _recurse_on_path_traits(func, thistrait, value, cwd):
"""Run func recursively on BasePath-derived traits."""
if thistrait.is_trait_type(BasePath):
value = func(value, cwd)
elif thistrait.is_trait_type(traits.List):
(innertrait,) = thistrait.inner_traits
if not isinstance(value, (list, tuple)):
return _recurse_on_path_traits(func, innertrait, value, cwd)
value = [_recurse_on_path_traits(func, innertrait, v, cwd) for v in value]
elif isinstance(value, dict) and thistrait.is_trait_type(traits.Dict):
_, innertrait = thistrait.inner_traits
value = {
k: _recurse_on_path_traits(func, innertrait, v, cwd)
for k, v in value.items()
}
elif isinstance(value, tuple) and thistrait.is_trait_type(traits.Tuple):
value = tuple(
[
_recurse_on_path_traits(func, subtrait, v, cwd)
for subtrait, v in zip(thistrait.handler.types, value)
]
)
elif thistrait.is_trait_type(traits.TraitCompound):
is_str = [
isinstance(f, (traits.String, traits.BaseStr, traits.BaseBytes, Str))
for f in thistrait.handler.handlers
]
if (
any(is_str)
and isinstance(value, (bytes, str))
and not value.startswith("/")
):
return value
for subtrait in thistrait.handler.handlers:
try:
sb_instance = subtrait()
except TypeError:
return value
else:
value = _recurse_on_path_traits(func, sb_instance, value, cwd)
return value | [
"def",
"_recurse_on_path_traits",
"(",
"func",
",",
"thistrait",
",",
"value",
",",
"cwd",
")",
":",
"if",
"thistrait",
".",
"is_trait_type",
"(",
"BasePath",
")",
":",
"value",
"=",
"func",
"(",
"value",
",",
"cwd",
")",
"elif",
"thistrait",
".",
"is_tr... | https://github.com/nipy/nipype/blob/cd4c34d935a43812d1756482fdc4034844e485b8/nipype/interfaces/base/traits_extension.py#L548-L591 | |
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/lib/django-1.5/django/contrib/messages/api.py | python | get_level | (request) | return storage.level | Returns the minimum level of messages to be recorded.
The default level is the ``MESSAGE_LEVEL`` setting. If this is not found,
the ``INFO`` level is used. | Returns the minimum level of messages to be recorded. | [
"Returns",
"the",
"minimum",
"level",
"of",
"messages",
"to",
"be",
"recorded",
"."
] | def get_level(request):
"""
Returns the minimum level of messages to be recorded.
The default level is the ``MESSAGE_LEVEL`` setting. If this is not found,
the ``INFO`` level is used.
"""
if hasattr(request, '_messages'):
storage = request._messages
else:
storage = default_storage(request)
return storage.level | [
"def",
"get_level",
"(",
"request",
")",
":",
"if",
"hasattr",
"(",
"request",
",",
"'_messages'",
")",
":",
"storage",
"=",
"request",
".",
"_messages",
"else",
":",
"storage",
"=",
"default_storage",
"(",
"request",
")",
"return",
"storage",
".",
"level"... | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.5/django/contrib/messages/api.py#L37-L48 | |
ClusterLabs/pcs | 1f225199e02c8d20456bb386f4c913c3ff21ac78 | pcs/lib/cib/tag.py | python | _validate_reference_ids_are_resources | (
resources_section: _Element,
idref_list: Iterable[str],
) | return report_list | Validate that ids are resources.
resources_section -- element resources
idref_list -- reference ids to validate | Validate that ids are resources. | [
"Validate",
"that",
"ids",
"are",
"resources",
"."
] | def _validate_reference_ids_are_resources(
resources_section: _Element,
idref_list: Iterable[str],
) -> ReportItemList:
"""
Validate that ids are resources.
resources_section -- element resources
idref_list -- reference ids to validate
"""
dummy_resources, report_list = find_resources(resources_section, idref_list)
return report_list | [
"def",
"_validate_reference_ids_are_resources",
"(",
"resources_section",
":",
"_Element",
",",
"idref_list",
":",
"Iterable",
"[",
"str",
"]",
",",
")",
"->",
"ReportItemList",
":",
"dummy_resources",
",",
"report_list",
"=",
"find_resources",
"(",
"resources_section... | https://github.com/ClusterLabs/pcs/blob/1f225199e02c8d20456bb386f4c913c3ff21ac78/pcs/lib/cib/tag.py#L108-L119 | |
buke/GreenOdoo | 3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df | runtime/python/lib/python2.7/random.py | python | Random.gauss | (self, mu, sigma) | return mu + z*sigma | Gaussian distribution.
mu is the mean, and sigma is the standard deviation. This is
slightly faster than the normalvariate() function.
Not thread-safe without a lock around calls. | Gaussian distribution. | [
"Gaussian",
"distribution",
"."
] | def gauss(self, mu, sigma):
"""Gaussian distribution.
mu is the mean, and sigma is the standard deviation. This is
slightly faster than the normalvariate() function.
Not thread-safe without a lock around calls.
"""
# When x and y are two variables from [0, 1), uniformly
# distributed, then
#
# cos(2*pi*x)*sqrt(-2*log(1-y))
# sin(2*pi*x)*sqrt(-2*log(1-y))
#
# are two *independent* variables with normal distribution
# (mu = 0, sigma = 1).
# (Lambert Meertens)
# (corrected version; bug discovered by Mike Miller, fixed by LM)
# Multithreading note: When two threads call this function
# simultaneously, it is possible that they will receive the
# same return value. The window is very small though. To
# avoid this, you have to use a lock around all calls. (I
# didn't want to slow this down in the serial case by using a
# lock here.)
random = self.random
z = self.gauss_next
self.gauss_next = None
if z is None:
x2pi = random() * TWOPI
g2rad = _sqrt(-2.0 * _log(1.0 - random()))
z = _cos(x2pi) * g2rad
self.gauss_next = _sin(x2pi) * g2rad
return mu + z*sigma | [
"def",
"gauss",
"(",
"self",
",",
"mu",
",",
"sigma",
")",
":",
"# When x and y are two variables from [0, 1), uniformly",
"# distributed, then",
"#",
"# cos(2*pi*x)*sqrt(-2*log(1-y))",
"# sin(2*pi*x)*sqrt(-2*log(1-y))",
"#",
"# are two *independent* variables with normal distr... | https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/random.py#L556-L593 | |
Epistimio/orion | 732e739d99561020dbe620760acf062ade746006 | src/orion/core/io/experiment_branch_builder.py | python | ExperimentBranchBuilder.set_cli_change_type | (self, change_type) | Set cli change type
Parameters
----------
change_type: string
One of the types defined in ``orion.core.evc.adapters.CommandLineChange.types``.
Raises
------
ValueError
If change_type is not in ``orion.core.evc.adapters.CommandLineChange.types``.
RuntimeError
If there is no cli conflict left to resolve. | Set cli change type | [
"Set",
"cli",
"change",
"type"
] | def set_cli_change_type(self, change_type):
"""Set cli change type
Parameters
----------
change_type: string
One of the types defined in ``orion.core.evc.adapters.CommandLineChange.types``.
Raises
------
ValueError
If change_type is not in ``orion.core.evc.adapters.CommandLineChange.types``.
RuntimeError
If there is no cli conflict left to resolve.
"""
cli_conflicts = self.conflicts.get_remaining([conflicts.CommandLineConflict])
if not cli_conflicts:
raise RuntimeError("No command line conflicts to solve")
self.conflicts.try_resolve(cli_conflicts[0], change_type) | [
"def",
"set_cli_change_type",
"(",
"self",
",",
"change_type",
")",
":",
"cli_conflicts",
"=",
"self",
".",
"conflicts",
".",
"get_remaining",
"(",
"[",
"conflicts",
".",
"CommandLineConflict",
"]",
")",
"if",
"not",
"cli_conflicts",
":",
"raise",
"RuntimeError"... | https://github.com/Epistimio/orion/blob/732e739d99561020dbe620760acf062ade746006/src/orion/core/io/experiment_branch_builder.py#L161-L181 | ||
openai/mujoco-worldgen | 39f52b1b47aed499925a6a214b58bdbdb4e2f75e | mujoco_worldgen/util/types.py | python | maybe | (arg_type) | return Derived | Helper for @accepts and @returns decorator. Maybe means optionally None.
Example:
@accepts(maybe(int), str, maybe(dict))
def foo(a, b, c):
# a - can be int or None
# b - must be str
# c - can be dict or None
See: https://wiki.haskell.org/Maybe | Helper for | [
"Helper",
"for"
] | def maybe(arg_type):
'''
Helper for @accepts and @returns decorator. Maybe means optionally None.
Example:
@accepts(maybe(int), str, maybe(dict))
def foo(a, b, c):
# a - can be int or None
# b - must be str
# c - can be dict or None
See: https://wiki.haskell.org/Maybe
'''
class Derived(metaclass=Maybe):
maybe_type = arg_type
return Derived | [
"def",
"maybe",
"(",
"arg_type",
")",
":",
"class",
"Derived",
"(",
"metaclass",
"=",
"Maybe",
")",
":",
"maybe_type",
"=",
"arg_type",
"return",
"Derived"
] | https://github.com/openai/mujoco-worldgen/blob/39f52b1b47aed499925a6a214b58bdbdb4e2f75e/mujoco_worldgen/util/types.py#L103-L116 | |
catalyst-team/catalyst | 678dc06eda1848242df010b7f34adb572def2598 | catalyst/contrib/data/dataset.py | python | NumpyDataset.__init__ | (
self,
numpy_data: np.ndarray,
numpy_key: str = "features",
dict_transform: Optional[Callable] = None,
) | General purpose dataset class to use with `numpy_data`.
Args:
numpy_data: numpy data
(for example path to embeddings, features, etc.)
numpy_key: key to use for output dictionary
dict_transform: transforms to use on dict.
(for example normalize vector, etc) | General purpose dataset class to use with `numpy_data`. | [
"General",
"purpose",
"dataset",
"class",
"to",
"use",
"with",
"numpy_data",
"."
] | def __init__(
self,
numpy_data: np.ndarray,
numpy_key: str = "features",
dict_transform: Optional[Callable] = None,
):
"""
General purpose dataset class to use with `numpy_data`.
Args:
numpy_data: numpy data
(for example path to embeddings, features, etc.)
numpy_key: key to use for output dictionary
dict_transform: transforms to use on dict.
(for example normalize vector, etc)
"""
super().__init__()
self.data = numpy_data
self.key = numpy_key
self.dict_transform = dict_transform if dict_transform is not None else lambda x: x | [
"def",
"__init__",
"(",
"self",
",",
"numpy_data",
":",
"np",
".",
"ndarray",
",",
"numpy_key",
":",
"str",
"=",
"\"features\"",
",",
"dict_transform",
":",
"Optional",
"[",
"Callable",
"]",
"=",
"None",
",",
")",
":",
"super",
"(",
")",
".",
"__init__... | https://github.com/catalyst-team/catalyst/blob/678dc06eda1848242df010b7f34adb572def2598/catalyst/contrib/data/dataset.py#L101-L120 | ||
earl/beanstalkc | 70c2ffc41cc84b0a1ae557e470e1db89b7b61023 | beanstalkc.py | python | Connection._read_response | (self) | return response[0], response[1:] | [] | def _read_response(self):
line = SocketError.wrap(self._socket_file.readline)
if not line:
raise SocketError()
response = line.split()
return response[0], response[1:] | [
"def",
"_read_response",
"(",
"self",
")",
":",
"line",
"=",
"SocketError",
".",
"wrap",
"(",
"self",
".",
"_socket_file",
".",
"readline",
")",
"if",
"not",
"line",
":",
"raise",
"SocketError",
"(",
")",
"response",
"=",
"line",
".",
"split",
"(",
")"... | https://github.com/earl/beanstalkc/blob/70c2ffc41cc84b0a1ae557e470e1db89b7b61023/beanstalkc.py#L105-L110 | |||
oilshell/oil | 94388e7d44a9ad879b12615f6203b38596b5a2d3 | Python-2.7.13/Lib/logging/handlers.py | python | SMTPHandler.emit | (self, record) | Emit a record.
Format the record and send it to the specified addressees. | Emit a record. | [
"Emit",
"a",
"record",
"."
] | def emit(self, record):
"""
Emit a record.
Format the record and send it to the specified addressees.
"""
try:
import smtplib
from email.utils import formatdate
port = self.mailport
if not port:
port = smtplib.SMTP_PORT
smtp = smtplib.SMTP(self.mailhost, port, timeout=self._timeout)
msg = self.format(record)
msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
self.fromaddr,
",".join(self.toaddrs),
self.getSubject(record),
formatdate(), msg)
if self.username:
if self.secure is not None:
smtp.ehlo()
smtp.starttls(*self.secure)
smtp.ehlo()
smtp.login(self.username, self.password)
smtp.sendmail(self.fromaddr, self.toaddrs, msg)
smtp.quit()
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record) | [
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"try",
":",
"import",
"smtplib",
"from",
"email",
".",
"utils",
"import",
"formatdate",
"port",
"=",
"self",
".",
"mailport",
"if",
"not",
"port",
":",
"port",
"=",
"smtplib",
".",
"SMTP_PORT",
"smtp... | https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/logging/handlers.py#L918-L948 | ||
smart-mobile-software/gitstack | d9fee8f414f202143eb6e620529e8e5539a2af56 | python/Lib/lib-tk/Tkinter.py | python | Menu.add | (self, itemType, cnf={}, **kw) | Internal function. | Internal function. | [
"Internal",
"function",
"."
] | def add(self, itemType, cnf={}, **kw):
"""Internal function."""
self.tk.call((self._w, 'add', itemType) +
self._options(cnf, kw)) | [
"def",
"add",
"(",
"self",
",",
"itemType",
",",
"cnf",
"=",
"{",
"}",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"(",
"self",
".",
"_w",
",",
"'add'",
",",
"itemType",
")",
"+",
"self",
".",
"_options",
"(",
"cnf",
... | https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/lib-tk/Tkinter.py#L2609-L2612 | ||
IronLanguages/ironpython2 | 51fdedeeda15727717fb8268a805f71b06c0b9f1 | Src/StdLib/Lib/pickle.py | python | _keep_alive | (x, memo) | Keeps a reference to the object x in the memo.
Because we remember objects by their id, we have
to assure that possibly temporary objects are kept
alive by referencing them.
We store a reference at the id of the memo, which should
normally not be used unless someone tries to deepcopy
the memo itself... | Keeps a reference to the object x in the memo. | [
"Keeps",
"a",
"reference",
"to",
"the",
"object",
"x",
"in",
"the",
"memo",
"."
] | def _keep_alive(x, memo):
"""Keeps a reference to the object x in the memo.
Because we remember objects by their id, we have
to assure that possibly temporary objects are kept
alive by referencing them.
We store a reference at the id of the memo, which should
normally not be used unless someone tries to deepcopy
the memo itself...
"""
try:
memo[id(memo)].append(x)
except KeyError:
# aha, this is the first one :-)
memo[id(memo)]=[x] | [
"def",
"_keep_alive",
"(",
"x",
",",
"memo",
")",
":",
"try",
":",
"memo",
"[",
"id",
"(",
"memo",
")",
"]",
".",
"append",
"(",
"x",
")",
"except",
"KeyError",
":",
"# aha, this is the first one :-)",
"memo",
"[",
"id",
"(",
"memo",
")",
"]",
"=",
... | https://github.com/IronLanguages/ironpython2/blob/51fdedeeda15727717fb8268a805f71b06c0b9f1/Src/StdLib/Lib/pickle.py#L783-L797 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/Python-2.7.9/Lib/plat-freebsd8/IN.py | python | IN6_IS_ADDR_MC_SITELOCAL | (a) | return | [] | def IN6_IS_ADDR_MC_SITELOCAL(a): return | [
"def",
"IN6_IS_ADDR_MC_SITELOCAL",
"(",
"a",
")",
":",
"return"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/plat-freebsd8/IN.py#L453-L453 | |||
dji-sdk/Tello-Python | 693776d65b691525773adf4f320f034946fb15b2 | Tello_Video_With_Pose_Recognition/tello.py | python | Tello.set_abort_flag | (self) | Sets self.abort_flag to True.
Used by the timer in Tello.send_command() to indicate to that a response
timeout has occurred. | Sets self.abort_flag to True. | [
"Sets",
"self",
".",
"abort_flag",
"to",
"True",
"."
] | def set_abort_flag(self):
"""
Sets self.abort_flag to True.
Used by the timer in Tello.send_command() to indicate to that a response
timeout has occurred.
"""
self.abort_flag = True | [
"def",
"set_abort_flag",
"(",
"self",
")",
":",
"self",
".",
"abort_flag",
"=",
"True"
] | https://github.com/dji-sdk/Tello-Python/blob/693776d65b691525773adf4f320f034946fb15b2/Tello_Video_With_Pose_Recognition/tello.py#L164-L174 | ||
pantsbuild/pex | 473c6ac732ed4bc338b4b20a9ec930d1d722c9b4 | pex/vendor/_vendored/setuptools/setuptools/extension.py | python | Extension._convert_pyx_sources_to_lang | (self) | Replace sources with .pyx extensions to sources with the target
language extension. This mechanism allows language authors to supply
pre-converted sources but to prefer the .pyx sources. | Replace sources with .pyx extensions to sources with the target
language extension. This mechanism allows language authors to supply
pre-converted sources but to prefer the .pyx sources. | [
"Replace",
"sources",
"with",
".",
"pyx",
"extensions",
"to",
"sources",
"with",
"the",
"target",
"language",
"extension",
".",
"This",
"mechanism",
"allows",
"language",
"authors",
"to",
"supply",
"pre",
"-",
"converted",
"sources",
"but",
"to",
"prefer",
"th... | def _convert_pyx_sources_to_lang(self):
"""
Replace sources with .pyx extensions to sources with the target
language extension. This mechanism allows language authors to supply
pre-converted sources but to prefer the .pyx sources.
"""
if _have_cython():
# the build has Cython, so allow it to compile the .pyx files
return
lang = self.language or ''
target_ext = '.cpp' if lang.lower() == 'c++' else '.c'
sub = functools.partial(re.sub, '.pyx$', target_ext)
self.sources = list(map(sub, self.sources)) | [
"def",
"_convert_pyx_sources_to_lang",
"(",
"self",
")",
":",
"if",
"_have_cython",
"(",
")",
":",
"# the build has Cython, so allow it to compile the .pyx files",
"return",
"lang",
"=",
"self",
".",
"language",
"or",
"''",
"target_ext",
"=",
"'.cpp'",
"if",
"lang",
... | https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/setuptools/setuptools/extension.py#L45-L57 | ||
dreikanter/wp2md | 84e960f8bf5980e51a093414d2140dc37b722ccc | wp2md/html2text.py | python | HTML2Text.previousIndex | (self, attrs) | returns the index of certain set of attributes (of a link) in the
self.a list
If the set of attributes is not found, returns None | returns the index of certain set of attributes (of a link) in the
self.a list | [
"returns",
"the",
"index",
"of",
"certain",
"set",
"of",
"attributes",
"(",
"of",
"a",
"link",
")",
"in",
"the",
"self",
".",
"a",
"list"
] | def previousIndex(self, attrs):
""" returns the index of certain set of attributes (of a link) in the
self.a list
If the set of attributes is not found, returns None
"""
if not has_key(attrs, 'href'): return None
i = -1
for a in self.a:
i += 1
match = 0
if has_key(a, 'href') and a['href'] == attrs['href']:
if has_key(a, 'title') or has_key(attrs, 'title'):
if (has_key(a, 'title') and has_key(attrs, 'title') and
a['title'] == attrs['title']):
match = True
else:
match = True
if match: return i | [
"def",
"previousIndex",
"(",
"self",
",",
"attrs",
")",
":",
"if",
"not",
"has_key",
"(",
"attrs",
",",
"'href'",
")",
":",
"return",
"None",
"i",
"=",
"-",
"1",
"for",
"a",
"in",
"self",
".",
"a",
":",
"i",
"+=",
"1",
"match",
"=",
"0",
"if",
... | https://github.com/dreikanter/wp2md/blob/84e960f8bf5980e51a093414d2140dc37b722ccc/wp2md/html2text.py#L296-L317 | ||
stamparm/hontel | 2bedc3ba55d5a78c292f0fef471862f78f153b11 | thirdparty/telnetsrv/telnetsrvlib.py | python | TelnetHandlerBase.getc | (self, block=True) | Return one character from the input queue | Return one character from the input queue | [
"Return",
"one",
"character",
"from",
"the",
"input",
"queue"
] | def getc(self, block=True):
"""Return one character from the input queue"""
# This is very different between green threads and real threads.
raise NotImplementedError("Please Implement the getc method") | [
"def",
"getc",
"(",
"self",
",",
"block",
"=",
"True",
")",
":",
"# This is very different between green threads and real threads.",
"raise",
"NotImplementedError",
"(",
"\"Please Implement the getc method\"",
")"
] | https://github.com/stamparm/hontel/blob/2bedc3ba55d5a78c292f0fef471862f78f153b11/thirdparty/telnetsrv/telnetsrvlib.py#L771-L774 | ||
eyaltrabelsi/pandas-log | 5ea73d91856cee28096bdd0272dead2a639b137d | pandas_log/patched_logs_functions.py | python | log_join | (
output_df,
input_df,
other,
on=None,
how="left",
lsuffix="",
rsuffix="",
sort=False,
**kwargs,
) | return logs, tips | [] | def log_join(
output_df,
input_df,
other,
on=None,
how="left",
lsuffix="",
rsuffix="",
sort=False,
**kwargs,
):
logs = []
tips = ""
merged = input_df.original_merge(
other, "outer", on, input_df.index, other.index, indicator=True
)
logs.append(
JOIN_TYPE_MSG.format(how=how, **merged._merge.value_counts().to_dict())
)
logs.append(get_filter_rows_logs(input_df, output_df))
if not is_same_cols(input_df, output_df):
logs.append(
JOIN_NEW_COLS_MSG.format(
num_new_columns=num_new_columns(input_df, output_df),
new_columns=str_new_columns(input_df, output_df),
)
)
logs = "\n".join(logs)
return logs, tips | [
"def",
"log_join",
"(",
"output_df",
",",
"input_df",
",",
"other",
",",
"on",
"=",
"None",
",",
"how",
"=",
"\"left\"",
",",
"lsuffix",
"=",
"\"\"",
",",
"rsuffix",
"=",
"\"\"",
",",
"sort",
"=",
"False",
",",
"*",
"*",
"kwargs",
",",
")",
":",
... | https://github.com/eyaltrabelsi/pandas-log/blob/5ea73d91856cee28096bdd0272dead2a639b137d/pandas_log/patched_logs_functions.py#L408-L437 | |||
midgetspy/Sick-Beard | 171a607e41b7347a74cc815f6ecce7968d9acccf | cherrypy/lib/reprconf.py | python | modules | (modulePath) | return mod | Load a module and retrieve a reference to that module. | Load a module and retrieve a reference to that module. | [
"Load",
"a",
"module",
"and",
"retrieve",
"a",
"reference",
"to",
"that",
"module",
"."
] | def modules(modulePath):
"""Load a module and retrieve a reference to that module."""
try:
mod = sys.modules[modulePath]
if mod is None:
raise KeyError()
except KeyError:
# The last [''] is important.
mod = __import__(modulePath, globals(), locals(), [''])
return mod | [
"def",
"modules",
"(",
"modulePath",
")",
":",
"try",
":",
"mod",
"=",
"sys",
".",
"modules",
"[",
"modulePath",
"]",
"if",
"mod",
"is",
"None",
":",
"raise",
"KeyError",
"(",
")",
"except",
"KeyError",
":",
"# The last [''] is important.",
"mod",
"=",
"... | https://github.com/midgetspy/Sick-Beard/blob/171a607e41b7347a74cc815f6ecce7968d9acccf/cherrypy/lib/reprconf.py#L315-L324 | |
lightforever/mlcomp | c78fdb77ec9c4ec8ff11beea50b90cab20903ad9 | mlcomp/contrib/segmentation/deeplabv3/backbone/mobilenet.py | python | InvertedResidual.__init__ | (self, inp, oup, stride, dilation, expand_ratio, BatchNorm) | [] | def __init__(self, inp, oup, stride, dilation, expand_ratio, BatchNorm):
super(InvertedResidual, self).__init__()
self.stride = stride
assert stride in [1, 2]
hidden_dim = round(inp * expand_ratio)
self.use_res_connect = self.stride == 1 and inp == oup
self.kernel_size = 3
self.dilation = dilation
if expand_ratio == 1:
self.conv = nn.Sequential(
# dw
nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 0, dilation,
groups=hidden_dim, bias=False),
BatchNorm(hidden_dim),
nn.ReLU6(inplace=True),
# pw-linear
nn.Conv2d(hidden_dim, oup, 1, 1, 0, 1, 1, bias=False),
BatchNorm(oup),
)
else:
self.conv = nn.Sequential(
# pw
nn.Conv2d(inp, hidden_dim, 1, 1, 0, 1, bias=False),
BatchNorm(hidden_dim),
nn.ReLU6(inplace=True),
# dw
nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 0, dilation,
groups=hidden_dim, bias=False),
BatchNorm(hidden_dim),
nn.ReLU6(inplace=True),
# pw-linear
nn.Conv2d(hidden_dim, oup, 1, 1, 0, 1, bias=False),
BatchNorm(oup),
) | [
"def",
"__init__",
"(",
"self",
",",
"inp",
",",
"oup",
",",
"stride",
",",
"dilation",
",",
"expand_ratio",
",",
"BatchNorm",
")",
":",
"super",
"(",
"InvertedResidual",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"stride",
"=",
"stride"... | https://github.com/lightforever/mlcomp/blob/c78fdb77ec9c4ec8ff11beea50b90cab20903ad9/mlcomp/contrib/segmentation/deeplabv3/backbone/mobilenet.py#L25-L60 | ||||
oilshell/oil | 94388e7d44a9ad879b12615f6203b38596b5a2d3 | Python-2.7.13/Lib/distutils/unixccompiler.py | python | UnixCCompiler.library_dir_option | (self, dir) | return "-L" + dir | [] | def library_dir_option(self, dir):
return "-L" + dir | [
"def",
"library_dir_option",
"(",
"self",
",",
"dir",
")",
":",
"return",
"\"-L\"",
"+",
"dir"
] | https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/distutils/unixccompiler.py#L210-L211 | |||
hhursev/recipe-scrapers | 478b9ddb0dda02b17b14f299eea729bef8131aa9 | recipe_scrapers/bakingmischeif.py | python | BakingMischeif.total_time | (self) | return self.schema.total_time() | [] | def total_time(self):
return self.schema.total_time() | [
"def",
"total_time",
"(",
"self",
")",
":",
"return",
"self",
".",
"schema",
".",
"total_time",
"(",
")"
] | https://github.com/hhursev/recipe-scrapers/blob/478b9ddb0dda02b17b14f299eea729bef8131aa9/recipe_scrapers/bakingmischeif.py#L15-L16 | |||
pantsbuild/pex | 473c6ac732ed4bc338b4b20a9ec930d1d722c9b4 | pex/vendor/_vendored/setuptools/setuptools/sandbox.py | python | _needs_hiding | (mod_name) | return bool(pattern.match(mod_name)) | >>> _needs_hiding('setuptools')
True
>>> _needs_hiding('pkg_resources')
True
>>> _needs_hiding('setuptools_plugin')
False
>>> _needs_hiding('setuptools.__init__')
True
>>> _needs_hiding('distutils')
True
>>> _needs_hiding('os')
False
>>> _needs_hiding('Cython')
True | >>> _needs_hiding('setuptools')
True
>>> _needs_hiding('pkg_resources')
True
>>> _needs_hiding('setuptools_plugin')
False
>>> _needs_hiding('setuptools.__init__')
True
>>> _needs_hiding('distutils')
True
>>> _needs_hiding('os')
False
>>> _needs_hiding('Cython')
True | [
">>>",
"_needs_hiding",
"(",
"setuptools",
")",
"True",
">>>",
"_needs_hiding",
"(",
"pkg_resources",
")",
"True",
">>>",
"_needs_hiding",
"(",
"setuptools_plugin",
")",
"False",
">>>",
"_needs_hiding",
"(",
"setuptools",
".",
"__init__",
")",
"True",
">>>",
"_n... | def _needs_hiding(mod_name):
"""
>>> _needs_hiding('setuptools')
True
>>> _needs_hiding('pkg_resources')
True
>>> _needs_hiding('setuptools_plugin')
False
>>> _needs_hiding('setuptools.__init__')
True
>>> _needs_hiding('distutils')
True
>>> _needs_hiding('os')
False
>>> _needs_hiding('Cython')
True
"""
pattern = re.compile(r'(setuptools|pkg_resources|distutils|Cython)(\.|$)')
return bool(pattern.match(mod_name)) | [
"def",
"_needs_hiding",
"(",
"mod_name",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r'(setuptools|pkg_resources|distutils|Cython)(\\.|$)'",
")",
"return",
"bool",
"(",
"pattern",
".",
"match",
"(",
"mod_name",
")",
")"
] | https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/setuptools/setuptools/sandbox.py#L222-L240 | |
jliljebl/flowblade | 995313a509b80e99eb1ad550d945bdda5995093b | flowblade-trunk/Flowblade/tools/batchrendering.py | python | QueueRunnerThread.abort | (self) | [] | def abort(self):
render_thread.shutdown()
# It may be that 'aborted' and 'running' could combined into single flag, but whatevaar
self.aborted = True
self.running = False
self.thread_running = False
batch_window.reload_queue() | [
"def",
"abort",
"(",
"self",
")",
":",
"render_thread",
".",
"shutdown",
"(",
")",
"# It may be that 'aborted' and 'running' could combined into single flag, but whatevaar",
"self",
".",
"aborted",
"=",
"True",
"self",
".",
"running",
"=",
"False",
"self",
".",
"threa... | https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/tools/batchrendering.py#L204-L211 | ||||
HRanWang/Spatial-Re-Scaling | 982448bf83e236288c545a64a96c38cc9548163b | reid/datasets/__init__.py | python | create | (name, root, *args, **kwargs) | return __factory[name](root, *args, **kwargs) | Create a dataset instance.
Parameters
----------
name : str
The dataset name. Can be one of 'market', 'duke'.
root : str
The path to the dataset directory. | Create a dataset instance. | [
"Create",
"a",
"dataset",
"instance",
"."
] | def create(name, root, *args, **kwargs):
"""
Create a dataset instance.
Parameters
----------
name : str
The dataset name. Can be one of 'market', 'duke'.
root : str
The path to the dataset directory.
"""
if name not in __factory:
raise KeyError("Unknown dataset:", name)
return __factory[name](root, *args, **kwargs) | [
"def",
"create",
"(",
"name",
",",
"root",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"name",
"not",
"in",
"__factory",
":",
"raise",
"KeyError",
"(",
"\"Unknown dataset:\"",
",",
"name",
")",
"return",
"__factory",
"[",
"name",
"]",
... | https://github.com/HRanWang/Spatial-Re-Scaling/blob/982448bf83e236288c545a64a96c38cc9548163b/reid/datasets/__init__.py#L16-L29 | |
CouchPotato/CouchPotatoServer | 7260c12f72447ddb6f062367c6dfbda03ecd4e9c | libs/requests/packages/urllib3/connectionpool.py | python | HTTPConnectionPool.close | (self) | Close all pooled connections and disable the pool. | Close all pooled connections and disable the pool. | [
"Close",
"all",
"pooled",
"connections",
"and",
"disable",
"the",
"pool",
"."
] | def close(self):
"""
Close all pooled connections and disable the pool.
"""
# Disable access to the pool
old_pool, self.pool = self.pool, None
try:
while True:
conn = old_pool.get(block=False)
if conn:
conn.close()
except Empty:
pass | [
"def",
"close",
"(",
"self",
")",
":",
"# Disable access to the pool",
"old_pool",
",",
"self",
".",
"pool",
"=",
"self",
".",
"pool",
",",
"None",
"try",
":",
"while",
"True",
":",
"conn",
"=",
"old_pool",
".",
"get",
"(",
"block",
"=",
"False",
")",
... | https://github.com/CouchPotato/CouchPotatoServer/blob/7260c12f72447ddb6f062367c6dfbda03ecd4e9c/libs/requests/packages/urllib3/connectionpool.py#L386-L400 | ||
pwnieexpress/pwn_plug_sources | 1a23324f5dc2c3de20f9c810269b6a29b2758cad | src/voiper/sulley/impacket/dcerpc/winreg.py | python | WINREGRespDeleteValue.get_header_size | (self) | return WINREGRespDeleteValue.__SIZE | [] | def get_header_size(self):
return WINREGRespDeleteValue.__SIZE | [
"def",
"get_header_size",
"(",
"self",
")",
":",
"return",
"WINREGRespDeleteValue",
".",
"__SIZE"
] | https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/voiper/sulley/impacket/dcerpc/winreg.py#L147-L148 | |||
Source-Python-Dev-Team/Source.Python | d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb | addons/source-python/Python3/multiprocessing/context.py | python | BaseContext.Value | (self, typecode_or_type, *args, lock=True) | return Value(typecode_or_type, *args, lock=lock,
ctx=self.get_context()) | Returns a synchronized shared object | Returns a synchronized shared object | [
"Returns",
"a",
"synchronized",
"shared",
"object"
] | def Value(self, typecode_or_type, *args, lock=True):
'''Returns a synchronized shared object'''
from .sharedctypes import Value
return Value(typecode_or_type, *args, lock=lock,
ctx=self.get_context()) | [
"def",
"Value",
"(",
"self",
",",
"typecode_or_type",
",",
"*",
"args",
",",
"lock",
"=",
"True",
")",
":",
"from",
".",
"sharedctypes",
"import",
"Value",
"return",
"Value",
"(",
"typecode_or_type",
",",
"*",
"args",
",",
"lock",
"=",
"lock",
",",
"ct... | https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/multiprocessing/context.py#L131-L135 | |
mrlesmithjr/Ansible | d44f0dc0d942bdf3bf7334b307e6048f0ee16e36 | roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/setuptools/package_index.py | python | ContentChecker.is_valid | (self) | return True | Check the hash. Return False if validation fails. | Check the hash. Return False if validation fails. | [
"Check",
"the",
"hash",
".",
"Return",
"False",
"if",
"validation",
"fails",
"."
] | def is_valid(self):
"""
Check the hash. Return False if validation fails.
"""
return True | [
"def",
"is_valid",
"(",
"self",
")",
":",
"return",
"True"
] | https://github.com/mrlesmithjr/Ansible/blob/d44f0dc0d942bdf3bf7334b307e6048f0ee16e36/roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/setuptools/package_index.py#L242-L246 | |
keiffster/program-y | 8c99b56f8c32f01a7b9887b5daae9465619d0385 | src/programy/dialog/question.py | python | Question.properties | (self, properties) | [] | def properties(self, properties):
self._properties = dict(properties) | [
"def",
"properties",
"(",
"self",
",",
"properties",
")",
":",
"self",
".",
"_properties",
"=",
"dict",
"(",
"properties",
")"
] | https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/dialog/question.py#L87-L88 | ||||
RedTeamOperations/PivotSuite | 9078d1ede1f076d30b6d72ca14e05ddf991f51f4 | pivot_suite/ntlm_auth/session_security.py | python | SessionSecurity.unwrap | (self, message, signature) | return message | [MS-NLMP] v28.0 2016-07-14
3.4.7 GSS_UnwrapEx()
Emulates the GSS_Unwrap() implementation to unseal messages and verify the signature
sent matches what has been computed locally. Will throw an Exception if the signature
doesn't match
@param message: The message data received from the server
@param signature: The signature of the message
@return message: The message that has been unsealed if flags are set | [MS-NLMP] v28.0 2016-07-14 | [
"[",
"MS",
"-",
"NLMP",
"]",
"v28",
".",
"0",
"2016",
"-",
"07",
"-",
"14"
] | def unwrap(self, message, signature):
"""
[MS-NLMP] v28.0 2016-07-14
3.4.7 GSS_UnwrapEx()
Emulates the GSS_Unwrap() implementation to unseal messages and verify the signature
sent matches what has been computed locally. Will throw an Exception if the signature
doesn't match
@param message: The message data received from the server
@param signature: The signature of the message
@return message: The message that has been unsealed if flags are set
"""
if self.negotiate_flags & NegotiateFlags.NTLMSSP_NEGOTIATE_SEAL:
message = self._unseal_message(message)
self._verify_signature(message, signature)
elif self.negotiate_flags & NegotiateFlags.NTLMSSP_NEGOTIATE_SIGN:
self._verify_signature(message, signature)
return message | [
"def",
"unwrap",
"(",
"self",
",",
"message",
",",
"signature",
")",
":",
"if",
"self",
".",
"negotiate_flags",
"&",
"NegotiateFlags",
".",
"NTLMSSP_NEGOTIATE_SEAL",
":",
"message",
"=",
"self",
".",
"_unseal_message",
"(",
"message",
")",
"self",
".",
"_ver... | https://github.com/RedTeamOperations/PivotSuite/blob/9078d1ede1f076d30b6d72ca14e05ddf991f51f4/pivot_suite/ntlm_auth/session_security.py#L137-L157 | |
rwth-i6/returnn | f2d718a197a280b0d5f0fd91a7fcb8658560dddb | returnn/config.py | python | Config.set | (self, key, value) | :type key: str
:type value: list[str] | str | int | float | bool | dict | None | :type key: str
:type value: list[str] | str | int | float | bool | dict | None | [
":",
"type",
"key",
":",
"str",
":",
"type",
"value",
":",
"list",
"[",
"str",
"]",
"|",
"str",
"|",
"int",
"|",
"float",
"|",
"bool",
"|",
"dict",
"|",
"None"
] | def set(self, key, value):
"""
:type key: str
:type value: list[str] | str | int | float | bool | dict | None
"""
self.typed_dict[key] = value | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"typed_dict",
"[",
"key",
"]",
"=",
"value"
] | https://github.com/rwth-i6/returnn/blob/f2d718a197a280b0d5f0fd91a7fcb8658560dddb/returnn/config.py#L265-L270 | ||
Source-Python-Dev-Team/Source.Python | d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb | addons/source-python/Python3/asyncio/base_events.py | python | BaseEventLoop.set_exception_handler | (self, handler) | Set handler as the new event loop exception handler.
If handler is None, the default exception handler will
be set.
If handler is a callable object, it should have a
signature matching '(loop, context)', where 'loop'
will be a reference to the active event loop, 'context'
will be a dict object (see `call_exception_handler()`
documentation for details about context). | Set handler as the new event loop exception handler. | [
"Set",
"handler",
"as",
"the",
"new",
"event",
"loop",
"exception",
"handler",
"."
] | def set_exception_handler(self, handler):
"""Set handler as the new event loop exception handler.
If handler is None, the default exception handler will
be set.
If handler is a callable object, it should have a
signature matching '(loop, context)', where 'loop'
will be a reference to the active event loop, 'context'
will be a dict object (see `call_exception_handler()`
documentation for details about context).
"""
if handler is not None and not callable(handler):
raise TypeError('A callable object or None is expected, '
'got {!r}'.format(handler))
self._exception_handler = handler | [
"def",
"set_exception_handler",
"(",
"self",
",",
"handler",
")",
":",
"if",
"handler",
"is",
"not",
"None",
"and",
"not",
"callable",
"(",
"handler",
")",
":",
"raise",
"TypeError",
"(",
"'A callable object or None is expected, '",
"'got {!r}'",
".",
"format",
... | https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/asyncio/base_events.py#L1200-L1215 | ||
nltk/nltk | 3f74ac55681667d7ef78b664557487145f51eb02 | nltk/inference/discourse.py | python | ReadingCommand.process_thread | (self, sentence_readings) | return sentence_readings | This method should be used to handle dependencies between readings such
as resolving anaphora.
:param sentence_readings: readings to process
:type sentence_readings: list(Expression)
:return: the list of readings after processing
:rtype: list(Expression) | This method should be used to handle dependencies between readings such
as resolving anaphora. | [
"This",
"method",
"should",
"be",
"used",
"to",
"handle",
"dependencies",
"between",
"readings",
"such",
"as",
"resolving",
"anaphora",
"."
] | def process_thread(self, sentence_readings):
"""
This method should be used to handle dependencies between readings such
as resolving anaphora.
:param sentence_readings: readings to process
:type sentence_readings: list(Expression)
:return: the list of readings after processing
:rtype: list(Expression)
"""
return sentence_readings | [
"def",
"process_thread",
"(",
"self",
",",
"sentence_readings",
")",
":",
"return",
"sentence_readings"
] | https://github.com/nltk/nltk/blob/3f74ac55681667d7ef78b664557487145f51eb02/nltk/inference/discourse.py#L70-L80 | |
linhaow/TextClassify | aa479ae0941c008602631c50124d8c07d159bfb1 | pytorch_transformers/modeling_openai.py | python | OpenAIGPTPreTrainedModel.init_weights | (self, module) | Initialize the weights. | Initialize the weights. | [
"Initialize",
"the",
"weights",
"."
] | def init_weights(self, module):
""" Initialize the weights.
"""
if isinstance(module, (nn.Linear, nn.Embedding, Conv1D)):
# Slightly different from the TF version which uses truncated_normal for initialization
# cf https://github.com/pytorch/pytorch/pull/5617
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if isinstance(module, (nn.Linear, Conv1D)) and module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0) | [
"def",
"init_weights",
"(",
"self",
",",
"module",
")",
":",
"if",
"isinstance",
"(",
"module",
",",
"(",
"nn",
".",
"Linear",
",",
"nn",
".",
"Embedding",
",",
"Conv1D",
")",
")",
":",
"# Slightly different from the TF version which uses truncated_normal for init... | https://github.com/linhaow/TextClassify/blob/aa479ae0941c008602631c50124d8c07d159bfb1/pytorch_transformers/modeling_openai.py#L369-L380 | ||
Jajcus/pyxmpp2 | 59e5fd7c8837991ac265dc6aad23a6bd256768a7 | pyxmpp2/error.py | python | ErrorElement.__init__ | (self, element_or_cond, text = None, language = None) | Initialize an StanzaErrorElement object.
:Parameters:
- `element_or_cond`: XML <error/> element to decode or an error
condition name or element.
- `text`: optional description to override the default one
- `language`: RFC 3066 language tag for the description
:Types:
- `element_or_cond`: :etree:`ElementTree.Element` or `unicode`
- `text`: `unicode`
- `language`: `unicode` | Initialize an StanzaErrorElement object. | [
"Initialize",
"an",
"StanzaErrorElement",
"object",
"."
] | def __init__(self, element_or_cond, text = None, language = None):
"""Initialize an StanzaErrorElement object.
:Parameters:
- `element_or_cond`: XML <error/> element to decode or an error
condition name or element.
- `text`: optional description to override the default one
- `language`: RFC 3066 language tag for the description
:Types:
- `element_or_cond`: :etree:`ElementTree.Element` or `unicode`
- `text`: `unicode`
- `language`: `unicode`
"""
self.text = None
self.custom_condition = []
self.language = language
if isinstance(element_or_cond, basestring):
self.condition = ElementTree.Element(self.cond_qname_prefix
+ element_or_cond)
elif not isinstance(element_or_cond, ElementClass):
raise TypeError, "Element or unicode string expected"
else:
self._from_xml(element_or_cond)
if text:
self.text = text | [
"def",
"__init__",
"(",
"self",
",",
"element_or_cond",
",",
"text",
"=",
"None",
",",
"language",
"=",
"None",
")",
":",
"self",
".",
"text",
"=",
"None",
"self",
".",
"custom_condition",
"=",
"[",
"]",
"self",
".",
"language",
"=",
"language",
"if",
... | https://github.com/Jajcus/pyxmpp2/blob/59e5fd7c8837991ac265dc6aad23a6bd256768a7/pyxmpp2/error.py#L205-L230 | ||
openstack/cinder | 23494a6d6c51451688191e1847a458f1d3cdcaa5 | cinder/volume/drivers/dell_emc/vnx/client.py | python | Client.delete_lun | (self, name, force=False, snap_copy=False) | Deletes a LUN or mount point. | Deletes a LUN or mount point. | [
"Deletes",
"a",
"LUN",
"or",
"mount",
"point",
"."
] | def delete_lun(self, name, force=False, snap_copy=False):
"""Deletes a LUN or mount point."""
lun = self.get_lun(name=name)
try:
# Do not delete the snapshots of the lun.
lun.delete(force_detach=True, detach_from_sg=force)
if snap_copy:
snap = self.vnx.get_snap(name=snap_copy)
snap.delete()
except storops_ex.VNXLunNotFoundError as ex:
LOG.info("LUN %(name)s is already deleted. This message can "
"be safely ignored. Message: %(msg)s",
{'name': name, 'msg': ex.message}) | [
"def",
"delete_lun",
"(",
"self",
",",
"name",
",",
"force",
"=",
"False",
",",
"snap_copy",
"=",
"False",
")",
":",
"lun",
"=",
"self",
".",
"get_lun",
"(",
"name",
"=",
"name",
")",
"try",
":",
"# Do not delete the snapshots of the lun.",
"lun",
".",
"... | https://github.com/openstack/cinder/blob/23494a6d6c51451688191e1847a458f1d3cdcaa5/cinder/volume/drivers/dell_emc/vnx/client.py#L144-L156 | ||
nicolashahn/diffimg | b82f0bb416f100f9105ccccf1995872b29302461 | diffimg/diff.py | python | diff | (
im1_file, im2_file, delete_diff_file=False, diff_img_file=None, ignore_alpha=False
) | return diff_ratio | Calculate the difference between two images by comparing channel values at the pixel
level. If the images are different sizes, the second will be resized to match the
first.
`delete_diff_file`: removes the diff image after ratio found
`diff_img_file`: filename to store diff image
`ignore_alpha`: ignore the alpha channel for ratio calculation, and set the diff
image's alpha to fully opaque | Calculate the difference between two images by comparing channel values at the pixel
level. If the images are different sizes, the second will be resized to match the
first. | [
"Calculate",
"the",
"difference",
"between",
"two",
"images",
"by",
"comparing",
"channel",
"values",
"at",
"the",
"pixel",
"level",
".",
"If",
"the",
"images",
"are",
"different",
"sizes",
"the",
"second",
"will",
"be",
"resized",
"to",
"match",
"the",
"fir... | def diff(
im1_file, im2_file, delete_diff_file=False, diff_img_file=None, ignore_alpha=False
):
"""
Calculate the difference between two images by comparing channel values at the pixel
level. If the images are different sizes, the second will be resized to match the
first.
`delete_diff_file`: removes the diff image after ratio found
`diff_img_file`: filename to store diff image
`ignore_alpha`: ignore the alpha channel for ratio calculation, and set the diff
image's alpha to fully opaque
"""
if not diff_img_file:
diff_img_file = DIFF_IMG_FILE
im1 = Image.open(im1_file)
im2 = Image.open(im2_file)
# Ensure we have the same color channels (RGBA vs RGB)
if im1.mode != im2.mode:
raise ValueError(
(
"Differing color modes:\n {}: {}\n {}: {}\n"
"Ensure image color modes are the same."
).format(im1_file, im1.mode, im2_file, im2.mode)
)
# Coerce 2nd dimensions to same as 1st
im2 = im2.resize((im1.width, im1.height))
# Generate diff image in memory.
diff_img = ImageChops.difference(im1, im2)
if ignore_alpha:
diff_img.putalpha(256)
if not delete_diff_file:
if "." not in diff_img_file:
extension = "png"
else:
extension = diff_img_file.split(".")[-1]
if extension in ("jpg", "jpeg"):
# For some reason, save() thinks "jpg" is invalid
# This doesn't affect the image's saved filename
extension = "jpeg"
diff_img = diff_img.convert("RGB")
diff_img.save(diff_img_file, extension)
# Calculate difference as a ratio.
stat = ImageStat.Stat(diff_img)
# stat.mean can be [r,g,b] or [r,g,b,a].
removed_channels = 1 if ignore_alpha and len(stat.mean) == 4 else 0
num_channels = len(stat.mean) - removed_channels
sum_channel_values = sum(stat.mean[:num_channels])
max_all_channels = num_channels * 255
diff_ratio = sum_channel_values / max_all_channels
return diff_ratio | [
"def",
"diff",
"(",
"im1_file",
",",
"im2_file",
",",
"delete_diff_file",
"=",
"False",
",",
"diff_img_file",
"=",
"None",
",",
"ignore_alpha",
"=",
"False",
")",
":",
"if",
"not",
"diff_img_file",
":",
"diff_img_file",
"=",
"DIFF_IMG_FILE",
"im1",
"=",
"Ima... | https://github.com/nicolashahn/diffimg/blob/b82f0bb416f100f9105ccccf1995872b29302461/diffimg/diff.py#L12-L70 | |
couchbase/couchbase-python-client | 58ccfd42af320bde6b733acf094fd5a4cf34e0ad | txcouchbase/cluster.py | python | BatchedRowMixin.on_error | (self, ex) | Reimplemented from :meth:`~AsyncViewBase.on_error` | Reimplemented from :meth:`~AsyncViewBase.on_error` | [
"Reimplemented",
"from",
":",
"meth",
":",
"~AsyncViewBase",
".",
"on_error"
] | def on_error(self, ex):
"""
Reimplemented from :meth:`~AsyncViewBase.on_error`
"""
if self._d:
self._d.errback()
self._d = None | [
"def",
"on_error",
"(",
"self",
",",
"ex",
")",
":",
"if",
"self",
".",
"_d",
":",
"self",
".",
"_d",
".",
"errback",
"(",
")",
"self",
".",
"_d",
"=",
"None"
] | https://github.com/couchbase/couchbase-python-client/blob/58ccfd42af320bde6b733acf094fd5a4cf34e0ad/txcouchbase/cluster.py#L78-L84 | ||
google/grr | 8ad8a4d2c5a93c92729206b7771af19d92d4f915 | grr/server/grr_response_server/bin/config_updater_util.py | python | FleetspeakConfig._WriteDisabled | (self, config) | [] | def _WriteDisabled(self, config):
config.Set("Server.fleetspeak_enabled", False)
config.Set("Client.fleetspeak_enabled", False)
config.Set("ClientBuilder.fleetspeak_bundled", False)
config.Set("Server.fleetspeak_server", "")
if self._IsFleetspeakPresent():
with open(self._ConfigPath("disabled"), "w") as f:
f.write("The existence of this file disables the "
"fleetspeak-server.service systemd unit.\n") | [
"def",
"_WriteDisabled",
"(",
"self",
",",
"config",
")",
":",
"config",
".",
"Set",
"(",
"\"Server.fleetspeak_enabled\"",
",",
"False",
")",
"config",
".",
"Set",
"(",
"\"Client.fleetspeak_enabled\"",
",",
"False",
")",
"config",
".",
"Set",
"(",
"\"ClientBui... | https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/server/grr_response_server/bin/config_updater_util.py#L438-L448 | ||||
rowliny/DiffHelper | ab3a96f58f9579d0023aed9ebd785f4edf26f8af | Tool/SitePackages/nltk/sem/drt.py | python | DrsDrawer._get_centered_top | (self, top, full_height, item_height) | return top + (full_height - item_height) / 2 | Get the y-coordinate of the point that a figure should start at if
its height is 'item_height' and it needs to be centered in an area that
starts at 'top' and is 'full_height' tall. | Get the y-coordinate of the point that a figure should start at if
its height is 'item_height' and it needs to be centered in an area that
starts at 'top' and is 'full_height' tall. | [
"Get",
"the",
"y",
"-",
"coordinate",
"of",
"the",
"point",
"that",
"a",
"figure",
"should",
"start",
"at",
"if",
"its",
"height",
"is",
"item_height",
"and",
"it",
"needs",
"to",
"be",
"centered",
"in",
"an",
"area",
"that",
"starts",
"at",
"top",
"an... | def _get_centered_top(self, top, full_height, item_height):
"""Get the y-coordinate of the point that a figure should start at if
its height is 'item_height' and it needs to be centered in an area that
starts at 'top' and is 'full_height' tall."""
return top + (full_height - item_height) / 2 | [
"def",
"_get_centered_top",
"(",
"self",
",",
"top",
",",
"full_height",
",",
"item_height",
")",
":",
"return",
"top",
"+",
"(",
"full_height",
"-",
"item_height",
")",
"/",
"2"
] | https://github.com/rowliny/DiffHelper/blob/ab3a96f58f9579d0023aed9ebd785f4edf26f8af/Tool/SitePackages/nltk/sem/drt.py#L1387-L1391 | |
vstinner/python-ptrace | a715d0f9bef4060022bfb6d25e25e148b2bd5f54 | ptrace/debugger/parse_expr.py | python | parseExpression | (process, text) | return value | Parse an expression. Syntax:
- "10": decimal number
- "0x10": hexadecimal number
- "eax": register value
- "a+b", "a-b", "a*b", "a/b", "a**b", "a<<b", "a>>b": operators
>>> from ptrace.mockup import FakeProcess
>>> process = FakeProcess()
>>> parseExpression(process, "1+1")
2
>>> process.setreg("eax", 3)
>>> parseExpression(process, "eax*0x10")
48 | Parse an expression. Syntax:
- "10": decimal number
- "0x10": hexadecimal number
- "eax": register value
- "a+b", "a-b", "a*b", "a/b", "a**b", "a<<b", "a>>b": operators | [
"Parse",
"an",
"expression",
".",
"Syntax",
":",
"-",
"10",
":",
"decimal",
"number",
"-",
"0x10",
":",
"hexadecimal",
"number",
"-",
"eax",
":",
"register",
"value",
"-",
"a",
"+",
"b",
"a",
"-",
"b",
"a",
"*",
"b",
"a",
"/",
"b",
"a",
"**",
"... | def parseExpression(process, text):
"""
Parse an expression. Syntax:
- "10": decimal number
- "0x10": hexadecimal number
- "eax": register value
- "a+b", "a-b", "a*b", "a/b", "a**b", "a<<b", "a>>b": operators
>>> from ptrace.mockup import FakeProcess
>>> process = FakeProcess()
>>> parseExpression(process, "1+1")
2
>>> process.setreg("eax", 3)
>>> parseExpression(process, "eax*0x10")
48
"""
# Remove spaces and convert to lower case
text = text.strip()
orig_text = text
if " " in text:
raise ValueError("Space are forbidden: %r" % text)
text = text.lower()
def readRegister(regs):
name = regs.group(1)
value = process.getreg(name)
return str(value)
# Replace hexadecimal by decimal
text = HEXADECIMAL_REGEX.sub(replaceHexadecimal, text)
# Replace registers by their value
text = REGISTER_REGEX.sub(readRegister, text)
# Reject invalid characters
if not EXPR_REGEX.match(text):
raise ValueError("Invalid expression: %r" % orig_text)
# Use integer division (a//b) instead of float division (a/b)
text = text.replace("/", "//")
# Finally, evaluate the expression
try:
value = eval(text)
except SyntaxError:
raise ValueError("Invalid expression: %r" % orig_text)
return value | [
"def",
"parseExpression",
"(",
"process",
",",
"text",
")",
":",
"# Remove spaces and convert to lower case",
"text",
"=",
"text",
".",
"strip",
"(",
")",
"orig_text",
"=",
"text",
"if",
"\" \"",
"in",
"text",
":",
"raise",
"ValueError",
"(",
"\"Space are forbid... | https://github.com/vstinner/python-ptrace/blob/a715d0f9bef4060022bfb6d25e25e148b2bd5f54/ptrace/debugger/parse_expr.py#L30-L76 | |
MDAnalysis/mdanalysis | 3488df3cdb0c29ed41c4fb94efe334b541e31b21 | package/MDAnalysis/lib/transformations.py | python | Arcball.setconstrain | (self, constrain) | Set state of constrain to axis mode. | Set state of constrain to axis mode. | [
"Set",
"state",
"of",
"constrain",
"to",
"axis",
"mode",
"."
] | def setconstrain(self, constrain):
"""Set state of constrain to axis mode."""
self._constrain = constrain is True | [
"def",
"setconstrain",
"(",
"self",
",",
"constrain",
")",
":",
"self",
".",
"_constrain",
"=",
"constrain",
"is",
"True"
] | https://github.com/MDAnalysis/mdanalysis/blob/3488df3cdb0c29ed41c4fb94efe334b541e31b21/package/MDAnalysis/lib/transformations.py#L1538-L1540 | ||
ipython/ipykernel | 0ab288fe42f3155c7c7d9257c9be8cf093d175e0 | ipykernel/zmqshell.py | python | ZMQInteractiveShell.set_next_input | (self, text, replace=False) | Send the specified text to the frontend to be presented at the next
input cell. | Send the specified text to the frontend to be presented at the next
input cell. | [
"Send",
"the",
"specified",
"text",
"to",
"the",
"frontend",
"to",
"be",
"presented",
"at",
"the",
"next",
"input",
"cell",
"."
] | def set_next_input(self, text, replace=False):
"""Send the specified text to the frontend to be presented at the next
input cell."""
payload = dict(
source='set_next_input',
text=text,
replace=replace,
)
self.payload_manager.write_payload(payload) | [
"def",
"set_next_input",
"(",
"self",
",",
"text",
",",
"replace",
"=",
"False",
")",
":",
"payload",
"=",
"dict",
"(",
"source",
"=",
"'set_next_input'",
",",
"text",
"=",
"text",
",",
"replace",
"=",
"replace",
",",
")",
"self",
".",
"payload_manager",... | https://github.com/ipython/ipykernel/blob/0ab288fe42f3155c7c7d9257c9be8cf093d175e0/ipykernel/zmqshell.py#L564-L572 | ||
cloudinary/pycloudinary | a61a9687c8933f23574c38e27f201358e540ee64 | cloudinary/cache/responsive_breakpoints_cache.py | python | ResponsiveBreakpointsCache.get | (self, public_id, **options) | return self._cache_adapter.get(public_id, *params) | Retrieve the breakpoints of a particular derived resource identified by the public_id and options
:param public_id: The public ID of the resource
:param options: The public ID of the resource
:return: Array of responsive breakpoints, None if not found | Retrieve the breakpoints of a particular derived resource identified by the public_id and options | [
"Retrieve",
"the",
"breakpoints",
"of",
"a",
"particular",
"derived",
"resource",
"identified",
"by",
"the",
"public_id",
"and",
"options"
] | def get(self, public_id, **options):
"""
Retrieve the breakpoints of a particular derived resource identified by the public_id and options
:param public_id: The public ID of the resource
:param options: The public ID of the resource
:return: Array of responsive breakpoints, None if not found
"""
params = self._options_to_parameters(**options)
return self._cache_adapter.get(public_id, *params) | [
"def",
"get",
"(",
"self",
",",
"public_id",
",",
"*",
"*",
"options",
")",
":",
"params",
"=",
"self",
".",
"_options_to_parameters",
"(",
"*",
"*",
"options",
")",
"return",
"self",
".",
"_cache_adapter",
".",
"get",
"(",
"public_id",
",",
"*",
"para... | https://github.com/cloudinary/pycloudinary/blob/a61a9687c8933f23574c38e27f201358e540ee64/cloudinary/cache/responsive_breakpoints_cache.py#L69-L80 | |
lad1337/XDM | 0c1b7009fe00f06f102a6f67c793478f515e7efe | site-packages/guessit_new/containers.py | python | PropertiesContainer.register_canonical_properties | (self, name, *canonical_forms, **property_params) | return properties | Register properties from their canonical forms.
:param name: name of the property (releaseGroup, ...)
:type name: string
:param canonical_forms: values of the property ('ESiR', 'WAF', 'SEPTiC', ...)
:type canonical_forms: varargs of strings | Register properties from their canonical forms. | [
"Register",
"properties",
"from",
"their",
"canonical",
"forms",
"."
] | def register_canonical_properties(self, name, *canonical_forms, **property_params):
"""Register properties from their canonical forms.
:param name: name of the property (releaseGroup, ...)
:type name: string
:param canonical_forms: values of the property ('ESiR', 'WAF', 'SEPTiC', ...)
:type canonical_forms: varargs of strings
"""
properties = []
for canonical_form in canonical_forms:
params = dict(property_params)
params['canonical_form'] = canonical_form
properties.extend(self.register_property(name, canonical_form, **property_params))
return properties | [
"def",
"register_canonical_properties",
"(",
"self",
",",
"name",
",",
"*",
"canonical_forms",
",",
"*",
"*",
"property_params",
")",
":",
"properties",
"=",
"[",
"]",
"for",
"canonical_form",
"in",
"canonical_forms",
":",
"params",
"=",
"dict",
"(",
"property... | https://github.com/lad1337/XDM/blob/0c1b7009fe00f06f102a6f67c793478f515e7efe/site-packages/guessit_new/containers.py#L270-L283 | |
facebookresearch/pycls | 8c79a8e2adfffa7cae3a88aace28ef45e52aa7e5 | pycls/sweep/plotting.py | python | plot_models | (sweeps, names, n_models, reverse=False) | return fig | Plots model visualization for up to n_models per sweep. | Plots model visualization for up to n_models per sweep. | [
"Plots",
"model",
"visualization",
"for",
"up",
"to",
"n_models",
"per",
"sweep",
"."
] | def plot_models(sweeps, names, n_models, reverse=False):
"""Plots model visualization for up to n_models per sweep."""
ms = [min(n_models, len(sweep)) for sweep in sweeps]
m, n = max(ms), len(sweeps)
fig, axes = fig_make(m, n, False, sharex=True, sharey=True)
sweeps = [sort_sweep(sweep, "error", reverse)[0] for sweep in sweeps]
for i, j in [(i, j) for j in range(n) for i in range(ms[j])]:
ax, sweep, color = axes[i][j], [sweeps[j][i]], get_color(j)
metrics = ["error", "flops", "params", "acts", "epoch_fw_bw", "resolution"]
vals = [get_vals(sweep, m)[0] for m in metrics]
label = "e = {:.2f}%, f = {:.2f}B\n".format(*vals[0:2])
label += "p = {:.2f}M, a = {:.2f}M\n".format(*vals[2:4])
label += "t = {0:.0f}s, r = ${1:d} \\times {1:d}$\n".format(*vals[4:6])
model_type = get_vals(sweep, "cfg.MODEL.TYPE")[0]
if model_type == "regnet":
metrics = ["GROUP_W", "BOT_MUL", "WA", "W0", "WM", "DEPTH"]
vals = [get_vals(sweep, "cfg.REGNET." + m)[0] for m in metrics]
ws, ds, _, _, _, ws_cont = regnet.generate_regnet(*vals[2:])
label += "$d_i = {:s}$\n$w_i = {:s}$\n".format(str(ds), str(ws))
label += "$g={:d}$, $b={:g}$, $w_a={:.1f}$\n".format(*vals[:3])
label += "$w_0={:d}$, $w_m={:.3f}$".format(*vals[3:5])
ax.plot(ws_cont, ":", c=color)
elif model_type == "anynet":
metrics = ["anynet_ds", "anynet_ws", "anynet_gs", "anynet_bs"]
ds, ws, gs, bs = [get_vals(sweep, m)[0] for m in metrics]
label += "$d_i = {:s}$\n$w_i = {:s}$\n".format(str(ds), str(ws))
label += "$g_i = {:s}$\n$b_i = {:s}$".format(str(gs), str(bs))
elif model_type == "effnet":
metrics = ["effnet_ds", "effnet_ws", "effnet_ss", "effnet_bs"]
ds, ws, ss, bs = [get_vals(sweep, m)[0] for m in metrics]
label += "$d_i = {:s}$\n$w_i = {:s}$\n".format(str(ds), str(ws))
label += "$s_i = {:s}$\n$b_i = {:s}$".format(str(ss), str(bs))
else:
raise AssertionError("Unknown model type" + model_type)
ws_all = [w for ws in [[w] * d for d, w in zip(ds, ws)] for w in ws]
ds_cum = np.cumsum([0] + ds[0:-1])
ax.plot(ws_all, "o-", c=color, markersize=plt.rcParams["lines.markersize"] - 1)
ax.plot(ds_cum, ws, "o", c="k", fillstyle="none", label=label)
ax.legend(loc="lower right", markerscale=0, handletextpad=0, handlelength=0)
for i, j in [(i, j) for i in range(m) for j in range(n)]:
ax = axes[i][j]
ax.set_xlabel("block index" if i == m - 1 else "")
ax.set_ylabel("width" if j == 0 else "")
ax.set_yscale("log", base=2)
ax.yaxis.set_major_formatter(ticker.ScalarFormatter())
ax.xaxis.set_major_locator(ticker.MaxNLocator(integer=True))
fig_legend(fig, n, names, styles="-")
return fig | [
"def",
"plot_models",
"(",
"sweeps",
",",
"names",
",",
"n_models",
",",
"reverse",
"=",
"False",
")",
":",
"ms",
"=",
"[",
"min",
"(",
"n_models",
",",
"len",
"(",
"sweep",
")",
")",
"for",
"sweep",
"in",
"sweeps",
"]",
"m",
",",
"n",
"=",
"max"... | https://github.com/facebookresearch/pycls/blob/8c79a8e2adfffa7cae3a88aace28ef45e52aa7e5/pycls/sweep/plotting.py#L234-L281 | |
pyqteval/evlal_win | ce7fc77ac5cdf864cd6aa9b04b5329501f8f4c92 | Clicked_Controller/requests/models.py | python | Response.is_redirect | (self) | return ('location' in self.headers and self.status_code in REDIRECT_STATI) | True if this Response is a well-formed HTTP redirect that could have
been processed automatically (by :meth:`Session.resolve_redirects`). | True if this Response is a well-formed HTTP redirect that could have
been processed automatically (by :meth:`Session.resolve_redirects`). | [
"True",
"if",
"this",
"Response",
"is",
"a",
"well",
"-",
"formed",
"HTTP",
"redirect",
"that",
"could",
"have",
"been",
"processed",
"automatically",
"(",
"by",
":",
"meth",
":",
"Session",
".",
"resolve_redirects",
")",
"."
] | def is_redirect(self):
"""True if this Response is a well-formed HTTP redirect that could have
been processed automatically (by :meth:`Session.resolve_redirects`).
"""
return ('location' in self.headers and self.status_code in REDIRECT_STATI) | [
"def",
"is_redirect",
"(",
"self",
")",
":",
"return",
"(",
"'location'",
"in",
"self",
".",
"headers",
"and",
"self",
".",
"status_code",
"in",
"REDIRECT_STATI",
")"
] | https://github.com/pyqteval/evlal_win/blob/ce7fc77ac5cdf864cd6aa9b04b5329501f8f4c92/Clicked_Controller/requests/models.py#L633-L637 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/Python-2.7.9/Lib/idlelib/rpc.py | python | _getmethods | (obj, methods) | [] | def _getmethods(obj, methods):
# Helper to get a list of methods from an object
# Adds names to dictionary argument 'methods'
for name in dir(obj):
attr = getattr(obj, name)
if hasattr(attr, '__call__'):
methods[name] = 1
if type(obj) == types.InstanceType:
_getmethods(obj.__class__, methods)
if type(obj) == types.ClassType:
for super in obj.__bases__:
_getmethods(super, methods) | [
"def",
"_getmethods",
"(",
"obj",
",",
"methods",
")",
":",
"# Helper to get a list of methods from an object",
"# Adds names to dictionary argument 'methods'",
"for",
"name",
"in",
"dir",
"(",
"obj",
")",
":",
"attr",
"=",
"getattr",
"(",
"obj",
",",
"name",
")",
... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/idlelib/rpc.py#L568-L579 | ||||
krintoxi/NoobSec-Toolkit | 38738541cbc03cedb9a3b3ed13b629f781ad64f6 | NoobSecToolkit /tools/inject/thirdparty/gprof2dot/gprof2dot.py | python | XmlParser.match_element_end | (self, name) | return self.token.type == XML_ELEMENT_END and self.token.name_or_data == name | [] | def match_element_end(self, name):
return self.token.type == XML_ELEMENT_END and self.token.name_or_data == name | [
"def",
"match_element_end",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"token",
".",
"type",
"==",
"XML_ELEMENT_END",
"and",
"self",
".",
"token",
".",
"name_or_data",
"==",
"name"
] | https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit /tools/inject/thirdparty/gprof2dot/gprof2dot.py#L740-L741 | |||
oracle/graalpython | 577e02da9755d916056184ec441c26e00b70145c | graalpython/lib-python/3/tkinter/__init__.py | python | Text.dump | (self, index1, index2=None, command=None, **kw) | Return the contents of the widget between index1 and index2.
The type of contents returned in filtered based on the keyword
parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
given and true, then the corresponding items are returned. The result
is a list of triples of the form (key, value, index). If none of the
keywords are true then 'all' is used by default.
If the 'command' argument is given, it is called once for each element
of the list of triples, with the values of each triple serving as the
arguments to the function. In this case the list is not returned. | Return the contents of the widget between index1 and index2. | [
"Return",
"the",
"contents",
"of",
"the",
"widget",
"between",
"index1",
"and",
"index2",
"."
] | def dump(self, index1, index2=None, command=None, **kw):
"""Return the contents of the widget between index1 and index2.
The type of contents returned in filtered based on the keyword
parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
given and true, then the corresponding items are returned. The result
is a list of triples of the form (key, value, index). If none of the
keywords are true then 'all' is used by default.
If the 'command' argument is given, it is called once for each element
of the list of triples, with the values of each triple serving as the
arguments to the function. In this case the list is not returned."""
args = []
func_name = None
result = None
if not command:
# Never call the dump command without the -command flag, since the
# output could involve Tcl quoting and would be a pain to parse
# right. Instead just set the command to build a list of triples
# as if we had done the parsing.
result = []
def append_triple(key, value, index, result=result):
result.append((key, value, index))
command = append_triple
try:
if not isinstance(command, str):
func_name = command = self._register(command)
args += ["-command", command]
for key in kw:
if kw[key]: args.append("-" + key)
args.append(index1)
if index2:
args.append(index2)
self.tk.call(self._w, "dump", *args)
return result
finally:
if func_name:
self.deletecommand(func_name) | [
"def",
"dump",
"(",
"self",
",",
"index1",
",",
"index2",
"=",
"None",
",",
"command",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"args",
"=",
"[",
"]",
"func_name",
"=",
"None",
"result",
"=",
"None",
"if",
"not",
"command",
":",
"# Never call th... | https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/tkinter/__init__.py#L3605-L3642 | ||
Source-Python-Dev-Team/Source.Python | d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb | addons/source-python/packages/site-packages/sqlalchemy/orm/attributes.py | python | AttributeImpl.set_committed_value | (self, state, dict_, value) | return value | set an attribute value on the given instance and 'commit' it. | set an attribute value on the given instance and 'commit' it. | [
"set",
"an",
"attribute",
"value",
"on",
"the",
"given",
"instance",
"and",
"commit",
"it",
"."
] | def set_committed_value(self, state, dict_, value):
"""set an attribute value on the given instance and 'commit' it."""
dict_[self.key] = value
state._commit(dict_, [self.key])
return value | [
"def",
"set_committed_value",
"(",
"self",
",",
"state",
",",
"dict_",
",",
"value",
")",
":",
"dict_",
"[",
"self",
".",
"key",
"]",
"=",
"value",
"state",
".",
"_commit",
"(",
"dict_",
",",
"[",
"self",
".",
"key",
"]",
")",
"return",
"value"
] | https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/site-packages/sqlalchemy/orm/attributes.py#L634-L639 | |
slackapi/python-slack-sdk | 2dee6656ffacb7de0c29bb2a6c2b51ec6b5dbce7 | slack_sdk/web/client.py | python | WebClient.admin_emoji_add | (
self,
*,
name: str,
url: str,
**kwargs,
) | return self.api_call("admin.emoji.add", http_verb="GET", params=kwargs) | Add an emoji.
https://api.slack.com/methods/admin.emoji.add | Add an emoji.
https://api.slack.com/methods/admin.emoji.add | [
"Add",
"an",
"emoji",
".",
"https",
":",
"//",
"api",
".",
"slack",
".",
"com",
"/",
"methods",
"/",
"admin",
".",
"emoji",
".",
"add"
] | def admin_emoji_add(
self,
*,
name: str,
url: str,
**kwargs,
) -> SlackResponse:
"""Add an emoji.
https://api.slack.com/methods/admin.emoji.add
"""
kwargs.update({"name": name, "url": url})
return self.api_call("admin.emoji.add", http_verb="GET", params=kwargs) | [
"def",
"admin_emoji_add",
"(",
"self",
",",
"*",
",",
"name",
":",
"str",
",",
"url",
":",
"str",
",",
"*",
"*",
"kwargs",
",",
")",
"->",
"SlackResponse",
":",
"kwargs",
".",
"update",
"(",
"{",
"\"name\"",
":",
"name",
",",
"\"url\"",
":",
"url",... | https://github.com/slackapi/python-slack-sdk/blob/2dee6656ffacb7de0c29bb2a6c2b51ec6b5dbce7/slack_sdk/web/client.py#L808-L819 | |
modelop/hadrian | 7c63e539d79e6e3cad959792d313dfc8b0c523ea | titus/titus/pfaast.py | python | SymbolTable.getLocal | (self, name) | Get a symbol's type specifically from *this* scope.
:type name: string
:param name: name of the symbol
:rtype: titus.datatype.AvroType or ``None``
:return: the symbol's type if defined in *this* scope, ``None`` otherwise | Get a symbol's type specifically from *this* scope. | [
"Get",
"a",
"symbol",
"s",
"type",
"specifically",
"from",
"*",
"this",
"*",
"scope",
"."
] | def getLocal(self, name):
"""Get a symbol's type specifically from *this* scope.
:type name: string
:param name: name of the symbol
:rtype: titus.datatype.AvroType or ``None``
:return: the symbol's type if defined in *this* scope, ``None`` otherwise
"""
if name in self.symbols:
return self.symbols[name]
else:
return None | [
"def",
"getLocal",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"symbols",
":",
"return",
"self",
".",
"symbols",
"[",
"name",
"]",
"else",
":",
"return",
"None"
] | https://github.com/modelop/hadrian/blob/7c63e539d79e6e3cad959792d313dfc8b0c523ea/titus/titus/pfaast.py#L141-L152 | ||
pwnieexpress/pwn_plug_sources | 1a23324f5dc2c3de20f9c810269b6a29b2758cad | src/metagoofil/hachoir_core/tools.py | python | humanFrequency | (hertz) | return u"%s %s" % (hertz, unit) | Convert a frequency in hertz to human classic representation.
It uses the values: 1 KHz is 1000 Hz, 1 MHz is 1000 KMhz, etc.
The result is an unicode string.
>>> humanFrequency(790)
u'790 Hz'
>>> humanFrequency(629469)
u'629.5 kHz' | Convert a frequency in hertz to human classic representation.
It uses the values: 1 KHz is 1000 Hz, 1 MHz is 1000 KMhz, etc.
The result is an unicode string. | [
"Convert",
"a",
"frequency",
"in",
"hertz",
"to",
"human",
"classic",
"representation",
".",
"It",
"uses",
"the",
"values",
":",
"1",
"KHz",
"is",
"1000",
"Hz",
"1",
"MHz",
"is",
"1000",
"KMhz",
"etc",
".",
"The",
"result",
"is",
"an",
"unicode",
"stri... | def humanFrequency(hertz):
"""
Convert a frequency in hertz to human classic representation.
It uses the values: 1 KHz is 1000 Hz, 1 MHz is 1000 KMhz, etc.
The result is an unicode string.
>>> humanFrequency(790)
u'790 Hz'
>>> humanFrequency(629469)
u'629.5 kHz'
"""
divisor = 1000
if hertz < divisor:
return u"%u Hz" % hertz
units = [u"kHz", u"MHz", u"GHz", u"THz"]
hertz = float(hertz)
for unit in units:
hertz = hertz / divisor
if hertz < divisor:
return u"%.1f %s" % (hertz, unit)
return u"%s %s" % (hertz, unit) | [
"def",
"humanFrequency",
"(",
"hertz",
")",
":",
"divisor",
"=",
"1000",
"if",
"hertz",
"<",
"divisor",
":",
"return",
"u\"%u Hz\"",
"%",
"hertz",
"units",
"=",
"[",
"u\"kHz\"",
",",
"u\"MHz\"",
",",
"u\"GHz\"",
",",
"u\"THz\"",
"]",
"hertz",
"=",
"float... | https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/metagoofil/hachoir_core/tools.py#L220-L240 | |
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/lib/django-1.3/django/contrib/gis/geos/geometry.py | python | GEOSGeometry.intersection | (self, other) | return self._topology(capi.geos_intersection(self.ptr, other.ptr)) | Returns a Geometry representing the points shared by this Geometry and other. | Returns a Geometry representing the points shared by this Geometry and other. | [
"Returns",
"a",
"Geometry",
"representing",
"the",
"points",
"shared",
"by",
"this",
"Geometry",
"and",
"other",
"."
] | def intersection(self, other):
"Returns a Geometry representing the points shared by this Geometry and other."
return self._topology(capi.geos_intersection(self.ptr, other.ptr)) | [
"def",
"intersection",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"_topology",
"(",
"capi",
".",
"geos_intersection",
"(",
"self",
".",
"ptr",
",",
"other",
".",
"ptr",
")",
")"
] | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.3/django/contrib/gis/geos/geometry.py#L586-L588 | |
IronLanguages/ironpython3 | 7a7bb2a872eeab0d1009fc8a6e24dca43f65b693 | Src/StdLib/Lib/pydoc.py | python | HTMLDoc.docdata | (self, object, name=None, mod=None, cl=None) | return self._docdescriptor(name, object, mod) | Produce html documentation for a data descriptor. | Produce html documentation for a data descriptor. | [
"Produce",
"html",
"documentation",
"for",
"a",
"data",
"descriptor",
"."
] | def docdata(self, object, name=None, mod=None, cl=None):
"""Produce html documentation for a data descriptor."""
return self._docdescriptor(name, object, mod) | [
"def",
"docdata",
"(",
"self",
",",
"object",
",",
"name",
"=",
"None",
",",
"mod",
"=",
"None",
",",
"cl",
"=",
"None",
")",
":",
"return",
"self",
".",
"_docdescriptor",
"(",
"name",
",",
"object",
",",
"mod",
")"
] | https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/pydoc.py#L992-L994 | |
zzzeek/sqlalchemy | fc5c54fcd4d868c2a4c7ac19668d72f506fe821e | examples/space_invaders/space_invaders.py | python | GlyphCoordinate.blank | (self, window) | Render a blank box for this glyph's position and size. | Render a blank box for this glyph's position and size. | [
"Render",
"a",
"blank",
"box",
"for",
"this",
"glyph",
"s",
"position",
"and",
"size",
"."
] | def blank(self, window):
"""Render a blank box for this glyph's position and size."""
glyph = self.glyph
x = min(max(self.x, 0), MAX_X)
width = min(glyph.width, MAX_X - x) or 1
for y_a in xrange(self.y, self.y + glyph.height):
y = y_a
window.addstr(y + VERT_PADDING, x + HORIZ_PADDING, " " * width)
if self.label:
self._render_label(window, True) | [
"def",
"blank",
"(",
"self",
",",
"window",
")",
":",
"glyph",
"=",
"self",
".",
"glyph",
"x",
"=",
"min",
"(",
"max",
"(",
"self",
".",
"x",
",",
"0",
")",
",",
"MAX_X",
")",
"width",
"=",
"min",
"(",
"glyph",
".",
"width",
",",
"MAX_X",
"-"... | https://github.com/zzzeek/sqlalchemy/blob/fc5c54fcd4d868c2a4c7ac19668d72f506fe821e/examples/space_invaders/space_invaders.py#L187-L198 | ||
Kwpolska/python-project-template | a5896fd5a38273d7efd44e55b2336b14f89491e1 | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/__main__.py | python | main | () | Main routine of {{ cookiecutter.project_name }}. | Main routine of {{ cookiecutter.project_name }}. | [
"Main",
"routine",
"of",
"{{",
"cookiecutter",
".",
"project_name",
"}}",
"."
] | def main():
"""Main routine of {{ cookiecutter.project_name }}."""
print("Hello, world!")
print("This is {{ cookiecutter.project_name }}.")
print("You should customize __main__.py to your liking (or delete it).") | [
"def",
"main",
"(",
")",
":",
"print",
"(",
"\"Hello, world!\"",
")",
"print",
"(",
"\"This is {{ cookiecutter.project_name }}.\"",
")",
"print",
"(",
"\"You should customize __main__.py to your liking (or delete it).\"",
")"
] | https://github.com/Kwpolska/python-project-template/blob/a5896fd5a38273d7efd44e55b2336b14f89491e1/{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/__main__.py#L17-L21 | ||
daler/pybedtools | ffe0d4bd2f32a0a5fc0cea049ee73773c4d57573 | pybedtools/contrib/long_range_interaction.py | python | cis_trans_interactions | (iterator, n, extra, verbose=True) | return df | Converts the output from `tag_bedpe` into a pandas DataFrame containing
information about regions that contact each other in cis (same fragment) or
trans (different fragments).
For example, given a BEDPE file representing 3D interactions in the genome,
we want to identify which transcription start sites are connected to distal
regions containing a peak.
>>> bedpe = pybedtools.example_bedtool('test_bedpe.bed')
>>> print(bedpe) # doctest: +NORMALIZE_WHITESPACE
chr1 1 10 chr1 50 90 pair1 5 + - x1
chr1 2 15 chr1 200 210 pair2 1 + + y1
<BLANKLINE>
>>> tsses = pybedtools.example_bedtool('test_tsses.bed')
>>> print(tsses) # doctest: +NORMALIZE_WHITESPACE
chr1 5 6 gene1
chr1 60 61 gene2
chr1 88 89 gene3
<BLANKLINE>
>>> peaks = pybedtools.example_bedtool('test_peaks.bed')
>>> print(peaks) # doctest: +NORMALIZE_WHITESPACE
chr1 3 4 peak1 50 .
<BLANKLINE>
Here's what the tracks look like. Note that pair1 is evidence of
a gene1-gene2 interaction and a gene1-gene3 interaction::
TRACKS:
1 2 / 5 6 / 8 9 / 20
0123456789012345678901 / 2345678901234567890123 / 012345678901234 / 0123456789
pair1 |||||||||------------ / --------|||||||||||||| / ||||||||||||||| /
pair2 |||||||||||||------- / ---------------------- / --------------- / ||||||||||
tsses 1 / 2 / 3
peaks 1
>>> from collections import OrderedDict
>>> queries = OrderedDict()
>>> queries['tss'] = tsses
>>> queries['pk'] = peaks
>>> iterator, n, extra = tag_bedpe(bedpe, queries)
>>> for (label, group1, group2) in iterator:
... group1 = sorted(group1, key=lambda x: str(x))
... group2 = sorted(group2, key=lambda x: str(x))
... for i in group1:
... print(i, end='') # doctest: +NORMALIZE_WHITESPACE
... for i in group2:
... print(i, end='') # doctest: +NORMALIZE_WHITESPACE
chr1 1 10 pair1 5 + x1 pk chr1 3 4 peak1 50 . 1
chr1 1 10 pair1 5 + x1 tss chr1 5 6 gene1 1
chr1 50 90 pair1 5 - x1 tss chr1 60 61 gene2 1
chr1 50 90 pair1 5 - x1 tss chr1 88 89 gene3 1
chr1 2 15 pair2 1 + y1 pk chr1 3 4 peak1 50 . 1
chr1 2 15 pair2 1 + y1 tss chr1 5 6 gene1 1
chr1 200 210 pair2 1 + y1 . . -1 -1 . 0
Now we run the same thing, but now aggregate it. Note that each piece of
interaction evidence has its own line. The first line shows that pair1 has
gene1 and peak1 in the same fragment, and that they are connected to gene2.
The second line shows again that gene1 and peak1 are in the same fragmet
and that they are also connected to gene3:
>>> import pandas; pandas.set_option('display.max_columns', 10)
>>> iterator, n, extra = tag_bedpe(bedpe, {'tss': tsses, 'pk': peaks})
>>> df = cis_trans_interactions(iterator, n, extra)
>>> print(df.sort_values(list(df.columns)).reset_index(drop=True))
target_label target_name cis_label cis_name distal_label distal_name label
0 pk peak1 tss gene1 . . pair2
1 pk peak1 tss gene1 tss gene2 pair1
2 pk peak1 tss gene1 tss gene3 pair1
3 tss gene1 pk peak1 . . pair2
4 tss gene1 pk peak1 tss gene2 pair1
5 tss gene1 pk peak1 tss gene3 pair1
6 tss gene2 tss gene3 pk peak1 pair1
7 tss gene2 tss gene3 tss gene1 pair1
8 tss gene3 tss gene2 pk peak1 pair1
9 tss gene3 tss gene2 tss gene1 pair1
If we only care about genes:
>>> print((df[df.target_label == 'tss']).sort_values(list(df.columns)).reset_index(drop=True))
target_label target_name cis_label cis_name distal_label distal_name label
0 tss gene1 pk peak1 . . pair2
1 tss gene1 pk peak1 tss gene2 pair1
2 tss gene1 pk peak1 tss gene3 pair1
3 tss gene2 tss gene3 pk peak1 pair1
4 tss gene2 tss gene3 tss gene1 pair1
5 tss gene3 tss gene2 pk peak1 pair1
6 tss gene3 tss gene2 tss gene1 pair1
Note that in pair2, there is no evidence of interaction between gene1 and
gene2.
What interacts distally with gene2's TSS?
>>> assert set(df.loc[df.target_name == 'gene2', 'distal_name']).difference('.') == set([u'gene1', u'peak1']) | Converts the output from `tag_bedpe` into a pandas DataFrame containing
information about regions that contact each other in cis (same fragment) or
trans (different fragments). | [
"Converts",
"the",
"output",
"from",
"tag_bedpe",
"into",
"a",
"pandas",
"DataFrame",
"containing",
"information",
"about",
"regions",
"that",
"contact",
"each",
"other",
"in",
"cis",
"(",
"same",
"fragment",
")",
"or",
"trans",
"(",
"different",
"fragments",
... | def cis_trans_interactions(iterator, n, extra, verbose=True):
"""
Converts the output from `tag_bedpe` into a pandas DataFrame containing
information about regions that contact each other in cis (same fragment) or
trans (different fragments).
For example, given a BEDPE file representing 3D interactions in the genome,
we want to identify which transcription start sites are connected to distal
regions containing a peak.
>>> bedpe = pybedtools.example_bedtool('test_bedpe.bed')
>>> print(bedpe) # doctest: +NORMALIZE_WHITESPACE
chr1 1 10 chr1 50 90 pair1 5 + - x1
chr1 2 15 chr1 200 210 pair2 1 + + y1
<BLANKLINE>
>>> tsses = pybedtools.example_bedtool('test_tsses.bed')
>>> print(tsses) # doctest: +NORMALIZE_WHITESPACE
chr1 5 6 gene1
chr1 60 61 gene2
chr1 88 89 gene3
<BLANKLINE>
>>> peaks = pybedtools.example_bedtool('test_peaks.bed')
>>> print(peaks) # doctest: +NORMALIZE_WHITESPACE
chr1 3 4 peak1 50 .
<BLANKLINE>
Here's what the tracks look like. Note that pair1 is evidence of
a gene1-gene2 interaction and a gene1-gene3 interaction::
TRACKS:
1 2 / 5 6 / 8 9 / 20
0123456789012345678901 / 2345678901234567890123 / 012345678901234 / 0123456789
pair1 |||||||||------------ / --------|||||||||||||| / ||||||||||||||| /
pair2 |||||||||||||------- / ---------------------- / --------------- / ||||||||||
tsses 1 / 2 / 3
peaks 1
>>> from collections import OrderedDict
>>> queries = OrderedDict()
>>> queries['tss'] = tsses
>>> queries['pk'] = peaks
>>> iterator, n, extra = tag_bedpe(bedpe, queries)
>>> for (label, group1, group2) in iterator:
... group1 = sorted(group1, key=lambda x: str(x))
... group2 = sorted(group2, key=lambda x: str(x))
... for i in group1:
... print(i, end='') # doctest: +NORMALIZE_WHITESPACE
... for i in group2:
... print(i, end='') # doctest: +NORMALIZE_WHITESPACE
chr1 1 10 pair1 5 + x1 pk chr1 3 4 peak1 50 . 1
chr1 1 10 pair1 5 + x1 tss chr1 5 6 gene1 1
chr1 50 90 pair1 5 - x1 tss chr1 60 61 gene2 1
chr1 50 90 pair1 5 - x1 tss chr1 88 89 gene3 1
chr1 2 15 pair2 1 + y1 pk chr1 3 4 peak1 50 . 1
chr1 2 15 pair2 1 + y1 tss chr1 5 6 gene1 1
chr1 200 210 pair2 1 + y1 . . -1 -1 . 0
Now we run the same thing, but now aggregate it. Note that each piece of
interaction evidence has its own line. The first line shows that pair1 has
gene1 and peak1 in the same fragment, and that they are connected to gene2.
The second line shows again that gene1 and peak1 are in the same fragmet
and that they are also connected to gene3:
>>> import pandas; pandas.set_option('display.max_columns', 10)
>>> iterator, n, extra = tag_bedpe(bedpe, {'tss': tsses, 'pk': peaks})
>>> df = cis_trans_interactions(iterator, n, extra)
>>> print(df.sort_values(list(df.columns)).reset_index(drop=True))
target_label target_name cis_label cis_name distal_label distal_name label
0 pk peak1 tss gene1 . . pair2
1 pk peak1 tss gene1 tss gene2 pair1
2 pk peak1 tss gene1 tss gene3 pair1
3 tss gene1 pk peak1 . . pair2
4 tss gene1 pk peak1 tss gene2 pair1
5 tss gene1 pk peak1 tss gene3 pair1
6 tss gene2 tss gene3 pk peak1 pair1
7 tss gene2 tss gene3 tss gene1 pair1
8 tss gene3 tss gene2 pk peak1 pair1
9 tss gene3 tss gene2 tss gene1 pair1
If we only care about genes:
>>> print((df[df.target_label == 'tss']).sort_values(list(df.columns)).reset_index(drop=True))
target_label target_name cis_label cis_name distal_label distal_name label
0 tss gene1 pk peak1 . . pair2
1 tss gene1 pk peak1 tss gene2 pair1
2 tss gene1 pk peak1 tss gene3 pair1
3 tss gene2 tss gene3 pk peak1 pair1
4 tss gene2 tss gene3 tss gene1 pair1
5 tss gene3 tss gene2 pk peak1 pair1
6 tss gene3 tss gene2 tss gene1 pair1
Note that in pair2, there is no evidence of interaction between gene1 and
gene2.
What interacts distally with gene2's TSS?
>>> assert set(df.loc[df.target_name == 'gene2', 'distal_name']).difference('.') == set([u'gene1', u'peak1'])
"""
try:
import pandas
except ImportError:
raise ImportError("pandas must be installed to use this function")
c = 0
lines = []
for label, end1_hits, end2_hits in iterator:
c += 1
if c % 1000 == 0:
print("%d (%.1f%%)\r" % (c, c / float(n) * 100), end="")
sys.stdout.flush()
# end1_hits has the full lines of all intersections with end1
end1_hits = list(end1_hits)
end2_hits = list(end2_hits)
def get_name_hits(f):
"""
Returns the key (from which file the interval came) and the name
(of the individual feature).
"""
# this is the "name" reported if there was no hit.
if f[6 + extra] == ".":
return (".", ".")
interval = pybedtools.create_interval_from_list(f[7 + extra :])
return [f[6 + extra], interval.name]
names1 = set(six.moves.map(tuple, six.moves.map(get_name_hits, end1_hits)))
names2 = set(six.moves.map(tuple, six.moves.map(get_name_hits, end2_hits)))
for cis, others in [(names1, names2), (names2, names1)]:
for target in cis:
if target == (".", "."):
continue
non_targets = set(cis).difference([target])
if len(non_targets) == 0:
non_targets = [(".", ".")]
for non_target in non_targets:
for other in others:
line = []
line.extend(target)
line.extend(non_target)
line.extend(other)
line.append(label)
lines.append(line)
df = pandas.DataFrame(
lines,
columns=[
"target_label",
"target_name",
"cis_label",
"cis_name",
"distal_label",
"distal_name",
"label",
],
)
df = df.drop_duplicates()
return df | [
"def",
"cis_trans_interactions",
"(",
"iterator",
",",
"n",
",",
"extra",
",",
"verbose",
"=",
"True",
")",
":",
"try",
":",
"import",
"pandas",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"\"pandas must be installed to use this function\"",
")",
"c... | https://github.com/daler/pybedtools/blob/ffe0d4bd2f32a0a5fc0cea049ee73773c4d57573/pybedtools/contrib/long_range_interaction.py#L245-L408 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/whoosh/codec/plaintext.py | python | PlainTermsReader._find_term | (self, fieldname, btext) | return False | [] | def _find_term(self, fieldname, btext):
self._find_field(fieldname)
for t in self._iter_btexts():
if t == btext:
return True
elif t > btext:
break
return False | [
"def",
"_find_term",
"(",
"self",
",",
"fieldname",
",",
"btext",
")",
":",
"self",
".",
"_find_field",
"(",
"fieldname",
")",
"for",
"t",
"in",
"self",
".",
"_iter_btexts",
"(",
")",
":",
"if",
"t",
"==",
"btext",
":",
"return",
"True",
"elif",
"t",... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/whoosh/codec/plaintext.py#L371-L378 | |||
microsoft/nni | 31f11f51249660930824e888af0d4e022823285c | examples/trials/network_morphism/cifar10/cifar10_keras.py | python | SendMetrics.on_epoch_end | (self, epoch, logs=None) | Run on end of each epoch | Run on end of each epoch | [
"Run",
"on",
"end",
"of",
"each",
"epoch"
] | def on_epoch_end(self, epoch, logs=None):
"""
Run on end of each epoch
"""
if logs is None:
logs = dict()
logger.debug(logs)
# TensorFlow 2.0 API reference claims the key is `val_acc`, but in fact it's `val_accuracy`
if 'val_acc' in logs:
nni.report_intermediate_result(logs['val_acc'])
else:
nni.report_intermediate_result(logs['val_accuracy']) | [
"def",
"on_epoch_end",
"(",
"self",
",",
"epoch",
",",
"logs",
"=",
"None",
")",
":",
"if",
"logs",
"is",
"None",
":",
"logs",
"=",
"dict",
"(",
")",
"logger",
".",
"debug",
"(",
"logs",
")",
"# TensorFlow 2.0 API reference claims the key is `val_acc`, but in ... | https://github.com/microsoft/nni/blob/31f11f51249660930824e888af0d4e022823285c/examples/trials/network_morphism/cifar10/cifar10_keras.py#L148-L159 | ||
IntelPython/sdc | 1ebf55c00ef38dfbd401a70b3945e352a5a38b87 | sdc/extensions/indexes/multi_index_helpers.py | python | _multi_index_create_level_ovld | (index_data, name) | return _multi_index_create_level_impl | [] | def _multi_index_create_level_ovld(index_data, name):
def _multi_index_create_level_impl(index_data, name):
index = fix_df_index(index_data)
return sdc_indexes_rename(index, name)
return _multi_index_create_level_impl | [
"def",
"_multi_index_create_level_ovld",
"(",
"index_data",
",",
"name",
")",
":",
"def",
"_multi_index_create_level_impl",
"(",
"index_data",
",",
"name",
")",
":",
"index",
"=",
"fix_df_index",
"(",
"index_data",
")",
"return",
"sdc_indexes_rename",
"(",
"index",
... | https://github.com/IntelPython/sdc/blob/1ebf55c00ef38dfbd401a70b3945e352a5a38b87/sdc/extensions/indexes/multi_index_helpers.py#L170-L175 | |||
spectacles/CodeComplice | 8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62 | libs/codeintel2/buffer.py | python | ImplicitBuffer.__init__ | (self, lang, mgr, accessor, env=None, path=None,
encoding=None) | [] | def __init__(self, lang, mgr, accessor, env=None, path=None,
encoding=None):
self.lang = lang
Buffer.__init__(self, mgr, accessor, env=env, path=path,
encoding=encoding) | [
"def",
"__init__",
"(",
"self",
",",
"lang",
",",
"mgr",
",",
"accessor",
",",
"env",
"=",
"None",
",",
"path",
"=",
"None",
",",
"encoding",
"=",
"None",
")",
":",
"self",
".",
"lang",
"=",
"lang",
"Buffer",
".",
"__init__",
"(",
"self",
",",
"m... | https://github.com/spectacles/CodeComplice/blob/8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62/libs/codeintel2/buffer.py#L669-L673 | ||||
pgmpy/pgmpy | 24279929a28082ea994c52f3d165ca63fc56b02b | pgmpy/readwrite/XMLBeliefNetwork.py | python | XBNReader.get_distributions | (self) | return distribution | Returns a dictionary of name and its distribution. Distribution is a ndarray.
The ndarray is stored in the standard way such that the rightmost variable
changes most often. Consider a CPD of variable 'd' which has parents 'b' and
'c' (distribution['CONDSET'] = ['b', 'c'])
| d_0 d_1
---------------------------
b_0, c_0 | 0.8 0.2
b_0, c_1 | 0.9 0.1
b_1, c_0 | 0.7 0.3
b_1, c_1 | 0.05 0.95
The value of distribution['d']['DPIS'] for the above example will be:
array([[ 0.8 , 0.2 ], [ 0.9 , 0.1 ], [ 0.7 , 0.3 ], [ 0.05, 0.95]])
Examples
--------
>>> reader = XBNReader('xbn_test.xml')
>>> reader.get_distributions()
{'a': {'TYPE': 'discrete', 'DPIS': array([[ 0.2, 0.8]])},
'e': {'TYPE': 'discrete', 'DPIS': array([[ 0.8, 0.2],
[ 0.6, 0.4]]), 'CONDSET': ['c'], 'CARDINALITY': [2]},
'b': {'TYPE': 'discrete', 'DPIS': array([[ 0.8, 0.2],
[ 0.2, 0.8]]), 'CONDSET': ['a'], 'CARDINALITY': [2]},
'c': {'TYPE': 'discrete', 'DPIS': array([[ 0.2 , 0.8 ],
[ 0.05, 0.95]]), 'CONDSET': ['a'], 'CARDINALITY': [2]},
'd': {'TYPE': 'discrete', 'DPIS': array([[ 0.8 , 0.2 ],
[ 0.9 , 0.1 ],
[ 0.7 , 0.3 ],
[ 0.05, 0.95]]), 'CONDSET': ['b', 'c']}, 'CARDINALITY': [2, 2]} | Returns a dictionary of name and its distribution. Distribution is a ndarray. | [
"Returns",
"a",
"dictionary",
"of",
"name",
"and",
"its",
"distribution",
".",
"Distribution",
"is",
"a",
"ndarray",
"."
] | def get_distributions(self):
"""
Returns a dictionary of name and its distribution. Distribution is a ndarray.
The ndarray is stored in the standard way such that the rightmost variable
changes most often. Consider a CPD of variable 'd' which has parents 'b' and
'c' (distribution['CONDSET'] = ['b', 'c'])
| d_0 d_1
---------------------------
b_0, c_0 | 0.8 0.2
b_0, c_1 | 0.9 0.1
b_1, c_0 | 0.7 0.3
b_1, c_1 | 0.05 0.95
The value of distribution['d']['DPIS'] for the above example will be:
array([[ 0.8 , 0.2 ], [ 0.9 , 0.1 ], [ 0.7 , 0.3 ], [ 0.05, 0.95]])
Examples
--------
>>> reader = XBNReader('xbn_test.xml')
>>> reader.get_distributions()
{'a': {'TYPE': 'discrete', 'DPIS': array([[ 0.2, 0.8]])},
'e': {'TYPE': 'discrete', 'DPIS': array([[ 0.8, 0.2],
[ 0.6, 0.4]]), 'CONDSET': ['c'], 'CARDINALITY': [2]},
'b': {'TYPE': 'discrete', 'DPIS': array([[ 0.8, 0.2],
[ 0.2, 0.8]]), 'CONDSET': ['a'], 'CARDINALITY': [2]},
'c': {'TYPE': 'discrete', 'DPIS': array([[ 0.2 , 0.8 ],
[ 0.05, 0.95]]), 'CONDSET': ['a'], 'CARDINALITY': [2]},
'd': {'TYPE': 'discrete', 'DPIS': array([[ 0.8 , 0.2 ],
[ 0.9 , 0.1 ],
[ 0.7 , 0.3 ],
[ 0.05, 0.95]]), 'CONDSET': ['b', 'c']}, 'CARDINALITY': [2, 2]}
"""
distribution = {}
for dist in self.bnmodel.find("DISTRIBUTIONS"):
variable_name = dist.find("PRIVATE").get("NAME")
distribution[variable_name] = {"TYPE": dist.get("TYPE")}
if dist.find("CONDSET") is not None:
distribution[variable_name]["CONDSET"] = [
var.get("NAME") for var in dist.find("CONDSET").findall("CONDELEM")
]
distribution[variable_name]["CARDINALITY"] = np.array(
[
len(
set(
np.array(
[
list(map(int, dpi.get("INDEXES").split()))
for dpi in dist.find("DPIS")
]
)[:, i]
)
)
for i in range(len(distribution[variable_name]["CONDSET"]))
]
)
distribution[variable_name]["DPIS"] = np.array(
[list(map(float, dpi.text.split())) for dpi in dist.find("DPIS")]
).transpose()
return distribution | [
"def",
"get_distributions",
"(",
"self",
")",
":",
"distribution",
"=",
"{",
"}",
"for",
"dist",
"in",
"self",
".",
"bnmodel",
".",
"find",
"(",
"\"DISTRIBUTIONS\"",
")",
":",
"variable_name",
"=",
"dist",
".",
"find",
"(",
"\"PRIVATE\"",
")",
".",
"get"... | https://github.com/pgmpy/pgmpy/blob/24279929a28082ea994c52f3d165ca63fc56b02b/pgmpy/readwrite/XMLBeliefNetwork.py#L147-L208 | |
TengXiaoDai/DistributedCrawling | f5c2439e6ce68dd9b49bde084d76473ff9ed4963 | Lib/site-packages/pip/vcs/subversion.py | python | Subversion.get_info | (self, location) | return url, match.group(1) | Returns (url, revision), where both are strings | Returns (url, revision), where both are strings | [
"Returns",
"(",
"url",
"revision",
")",
"where",
"both",
"are",
"strings"
] | def get_info(self, location):
"""Returns (url, revision), where both are strings"""
assert not location.rstrip('/').endswith(self.dirname), \
'Bad directory: %s' % location
output = self.run_command(
['info', location],
show_stdout=False,
extra_environ={'LANG': 'C'},
)
match = _svn_url_re.search(output)
if not match:
logger.warning(
'Cannot determine URL of svn checkout %s',
display_path(location),
)
logger.debug('Output that cannot be parsed: \n%s', output)
return None, None
url = match.group(1).strip()
match = _svn_revision_re.search(output)
if not match:
logger.warning(
'Cannot determine revision of svn checkout %s',
display_path(location),
)
logger.debug('Output that cannot be parsed: \n%s', output)
return url, None
return url, match.group(1) | [
"def",
"get_info",
"(",
"self",
",",
"location",
")",
":",
"assert",
"not",
"location",
".",
"rstrip",
"(",
"'/'",
")",
".",
"endswith",
"(",
"self",
".",
"dirname",
")",
",",
"'Bad directory: %s'",
"%",
"location",
"output",
"=",
"self",
".",
"run_comma... | https://github.com/TengXiaoDai/DistributedCrawling/blob/f5c2439e6ce68dd9b49bde084d76473ff9ed4963/Lib/site-packages/pip/vcs/subversion.py#L31-L57 | |
pwnieexpress/pwn_plug_sources | 1a23324f5dc2c3de20f9c810269b6a29b2758cad | src/metagoofil/pdfminer/pdfinterp.py | python | PDFPageInterpreter.do_EI | (self, obj) | return | [] | def do_EI(self, obj):
if 'W' in obj and 'H' in obj:
iobjid = str(id(obj))
self.device.begin_figure(iobjid, (0,0,1,1), MATRIX_IDENTITY)
self.device.render_image(iobjid, obj)
self.device.end_figure(iobjid)
return | [
"def",
"do_EI",
"(",
"self",
",",
"obj",
")",
":",
"if",
"'W'",
"in",
"obj",
"and",
"'H'",
"in",
"obj",
":",
"iobjid",
"=",
"str",
"(",
"id",
"(",
"obj",
")",
")",
"self",
".",
"device",
".",
"begin_figure",
"(",
"iobjid",
",",
"(",
"0",
",",
... | https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/metagoofil/pdfminer/pdfinterp.py#L704-L710 | |||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/setuptools/command/build_py.py | python | build_py.__getattr__ | (self, attr) | return orig.build_py.__getattr__(self, attr) | lazily compute data files | lazily compute data files | [
"lazily",
"compute",
"data",
"files"
] | def __getattr__(self, attr):
"lazily compute data files"
if attr == 'data_files':
self.data_files = self._get_data_files()
return self.data_files
return orig.build_py.__getattr__(self, attr) | [
"def",
"__getattr__",
"(",
"self",
",",
"attr",
")",
":",
"if",
"attr",
"==",
"'data_files'",
":",
"self",
".",
"data_files",
"=",
"self",
".",
"_get_data_files",
"(",
")",
"return",
"self",
".",
"data_files",
"return",
"orig",
".",
"build_py",
".",
"__g... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/setuptools/command/build_py.py#L63-L68 | |
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/networkx/algorithms/cluster.py | python | generalized_degree | (G, nodes=None) | return {v: gd for v, d, t, gd in _triangles_and_degree_iter(G, nodes)} | r""" Compute the generalized degree for nodes.
For each node, the generalized degree shows how many edges of given
triangle multiplicity the node is connected to. The triangle multiplicity
of an edge is the number of triangles an edge participates in. The
generalized degree of node :math:`i` can be written as a vector
:math:`\mathbf{k}_i=(k_i^{(0)}, \dotsc, k_i^{(N-2)})` where
:math:`k_i^{(j)}` is the number of edges attached to node :math:`i` that
participate in :math:`j` triangles.
Parameters
----------
G : graph
nodes : container of nodes, optional (default=all nodes in G)
Compute the generalized degree for nodes in this container.
Returns
-------
out : Counter, or dictionary of Counters
Generalized degree of specified nodes. The Counter is keyed by edge
triangle multiplicity.
Examples
--------
>>> G=nx.complete_graph(5)
>>> print(nx.generalized_degree(G,0))
Counter({3: 4})
>>> print(nx.generalized_degree(G))
{0: Counter({3: 4}), 1: Counter({3: 4}), 2: Counter({3: 4}), 3: Counter({3: 4}), 4: Counter({3: 4})}
To recover the number of triangles attached to a node:
>>> k1 = nx.generalized_degree(G,0)
>>> sum([k*v for k,v in k1.items()])/2 == nx.triangles(G,0)
True
Notes
-----
In a network of N nodes, the highest triangle multiplicty an edge can have
is N-2.
The return value does not include a `zero` entry if no edges of a
particular triangle multiplicity are present.
The number of triangles node :math:`i` is attached to can be recovered from
the generalized degree :math:`\mathbf{k}_i=(k_i^{(0)}, \dotsc,
k_i^{(N-2)})` by :math:`(k_i^{(1)}+2k_i^{(2)}+\dotsc +(N-2)k_i^{(N-2)})/2`.
References
----------
.. [1] Networks with arbitrary edge multiplicities by V. Zlatić,
D. Garlaschelli and G. Caldarelli, EPL (Europhysics Letters),
Volume 97, Number 2 (2012).
https://iopscience.iop.org/article/10.1209/0295-5075/97/28005 | r""" Compute the generalized degree for nodes. | [
"r",
"Compute",
"the",
"generalized",
"degree",
"for",
"nodes",
"."
] | def generalized_degree(G, nodes=None):
r""" Compute the generalized degree for nodes.
For each node, the generalized degree shows how many edges of given
triangle multiplicity the node is connected to. The triangle multiplicity
of an edge is the number of triangles an edge participates in. The
generalized degree of node :math:`i` can be written as a vector
:math:`\mathbf{k}_i=(k_i^{(0)}, \dotsc, k_i^{(N-2)})` where
:math:`k_i^{(j)}` is the number of edges attached to node :math:`i` that
participate in :math:`j` triangles.
Parameters
----------
G : graph
nodes : container of nodes, optional (default=all nodes in G)
Compute the generalized degree for nodes in this container.
Returns
-------
out : Counter, or dictionary of Counters
Generalized degree of specified nodes. The Counter is keyed by edge
triangle multiplicity.
Examples
--------
>>> G=nx.complete_graph(5)
>>> print(nx.generalized_degree(G,0))
Counter({3: 4})
>>> print(nx.generalized_degree(G))
{0: Counter({3: 4}), 1: Counter({3: 4}), 2: Counter({3: 4}), 3: Counter({3: 4}), 4: Counter({3: 4})}
To recover the number of triangles attached to a node:
>>> k1 = nx.generalized_degree(G,0)
>>> sum([k*v for k,v in k1.items()])/2 == nx.triangles(G,0)
True
Notes
-----
In a network of N nodes, the highest triangle multiplicty an edge can have
is N-2.
The return value does not include a `zero` entry if no edges of a
particular triangle multiplicity are present.
The number of triangles node :math:`i` is attached to can be recovered from
the generalized degree :math:`\mathbf{k}_i=(k_i^{(0)}, \dotsc,
k_i^{(N-2)})` by :math:`(k_i^{(1)}+2k_i^{(2)}+\dotsc +(N-2)k_i^{(N-2)})/2`.
References
----------
.. [1] Networks with arbitrary edge multiplicities by V. Zlatić,
D. Garlaschelli and G. Caldarelli, EPL (Europhysics Letters),
Volume 97, Number 2 (2012).
https://iopscience.iop.org/article/10.1209/0295-5075/97/28005
"""
if nodes in G:
return next(_triangles_and_degree_iter(G, nodes))[3]
return {v: gd for v, d, t, gd in _triangles_and_degree_iter(G, nodes)} | [
"def",
"generalized_degree",
"(",
"G",
",",
"nodes",
"=",
"None",
")",
":",
"if",
"nodes",
"in",
"G",
":",
"return",
"next",
"(",
"_triangles_and_degree_iter",
"(",
"G",
",",
"nodes",
")",
")",
"[",
"3",
"]",
"return",
"{",
"v",
":",
"gd",
"for",
"... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/networkx/algorithms/cluster.py#L480-L539 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.