nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/ao/quantization/fx/qconfig_utils.py | python | check_is_valid_convert_custom_config_dict | (convert_custom_config_dict: Optional[Dict[str, Any]] = None) | r""" Checks if the given convert_custom_config_dict has the correct keys
Args:
`convert_custom_config_dict`: dictionary for custom configurations for
convert function | r""" Checks if the given convert_custom_config_dict has the correct keys | [
"r",
"Checks",
"if",
"the",
"given",
"convert_custom_config_dict",
"has",
"the",
"correct",
"keys"
] | def check_is_valid_convert_custom_config_dict(convert_custom_config_dict: Optional[Dict[str, Any]] = None) -> None:
r""" Checks if the given convert_custom_config_dict has the correct keys
Args:
`convert_custom_config_dict`: dictionary for custom configurations for
convert function
"""
if not convert_custom_config_dict:
return
convert_custom_config_dict_allowed_keys = {"additional_object_mapping",
"observed_to_quantized_custom_module_class",
"preserved_attributes"}
check_is_valid_config_dict(convert_custom_config_dict,
convert_custom_config_dict_allowed_keys, "convert_custom_config_dict") | [
"def",
"check_is_valid_convert_custom_config_dict",
"(",
"convert_custom_config_dict",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
"=",
"None",
")",
"->",
"None",
":",
"if",
"not",
"convert_custom_config_dict",
":",
"return",
"convert_custom_config_dict_allowed_keys",
"=",
"{",
"\"additional_object_mapping\"",
",",
"\"observed_to_quantized_custom_module_class\"",
",",
"\"preserved_attributes\"",
"}",
"check_is_valid_config_dict",
"(",
"convert_custom_config_dict",
",",
"convert_custom_config_dict_allowed_keys",
",",
"\"convert_custom_config_dict\"",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/ao/quantization/fx/qconfig_utils.py#L227-L241 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/external/bazel_tools/tools/android/incremental_install.py | python | ConvertNativeLibs | (args) | return native_libs | Converts the --native_libs command line argument to an arch -> libs map. | Converts the --native_libs command line argument to an arch -> libs map. | [
"Converts",
"the",
"--",
"native_libs",
"command",
"line",
"argument",
"to",
"an",
"arch",
"-",
">",
"libs",
"map",
"."
] | def ConvertNativeLibs(args):
"""Converts the --native_libs command line argument to an arch -> libs map."""
native_libs = {}
if args is not None:
for native_lib in args:
abi, path = native_lib.split(":")
if abi not in native_libs:
native_libs[abi] = set()
native_libs[abi].add(path)
return native_libs | [
"def",
"ConvertNativeLibs",
"(",
"args",
")",
":",
"native_libs",
"=",
"{",
"}",
"if",
"args",
"is",
"not",
"None",
":",
"for",
"native_lib",
"in",
"args",
":",
"abi",
",",
"path",
"=",
"native_lib",
".",
"split",
"(",
"\":\"",
")",
"if",
"abi",
"not",
"in",
"native_libs",
":",
"native_libs",
"[",
"abi",
"]",
"=",
"set",
"(",
")",
"native_libs",
"[",
"abi",
"]",
".",
"add",
"(",
"path",
")",
"return",
"native_libs"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/external/bazel_tools/tools/android/incremental_install.py#L473-L484 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/oauthlib/oauth1/rfc5849/endpoints/request_token.py | python | RequestTokenEndpoint.validate_request_token_request | (self, request) | return v, request | Validate a request token request.
:param request: An oauthlib.common.Request object.
:raises: OAuth1Error if the request is invalid.
:returns: A tuple of 2 elements.
1. The validation result (True or False).
2. The request object. | Validate a request token request. | [
"Validate",
"a",
"request",
"token",
"request",
"."
] | def validate_request_token_request(self, request):
"""Validate a request token request.
:param request: An oauthlib.common.Request object.
:raises: OAuth1Error if the request is invalid.
:returns: A tuple of 2 elements.
1. The validation result (True or False).
2. The request object.
"""
self._check_transport_security(request)
self._check_mandatory_parameters(request)
if request.realm:
request.realms = request.realm.split(' ')
else:
request.realms = self.request_validator.get_default_realms(
request.client_key, request)
if not self.request_validator.check_realms(request.realms):
raise errors.InvalidRequestError(
description='Invalid realm %s. Allowed are %r.' % (
request.realms, self.request_validator.realms))
if not request.redirect_uri:
raise errors.InvalidRequestError(
description='Missing callback URI.')
if not self.request_validator.validate_timestamp_and_nonce(
request.client_key, request.timestamp, request.nonce, request,
request_token=request.resource_owner_key):
return False, request
# The server SHOULD return a 401 (Unauthorized) status code when
# receiving a request with invalid client credentials.
# Note: This is postponed in order to avoid timing attacks, instead
# a dummy client is assigned and used to maintain near constant
# time request verification.
#
# Note that early exit would enable client enumeration
valid_client = self.request_validator.validate_client_key(
request.client_key, request)
if not valid_client:
request.client_key = self.request_validator.dummy_client
# Note that `realm`_ is only used in authorization headers and how
# it should be interepreted is not included in the OAuth spec.
# However they could be seen as a scope or realm to which the
# client has access and as such every client should be checked
# to ensure it is authorized access to that scope or realm.
# .. _`realm`: https://tools.ietf.org/html/rfc2617#section-1.2
#
# Note that early exit would enable client realm access enumeration.
#
# The require_realm indicates this is the first step in the OAuth
# workflow where a client requests access to a specific realm.
# This first step (obtaining request token) need not require a realm
# and can then be identified by checking the require_resource_owner
# flag and abscence of realm.
#
# Clients obtaining an access token will not supply a realm and it will
# not be checked. Instead the previously requested realm should be
# transferred from the request token to the access token.
#
# Access to protected resources will always validate the realm but note
# that the realm is now tied to the access token and not provided by
# the client.
valid_realm = self.request_validator.validate_requested_realms(
request.client_key, request.realms, request)
# Callback is normally never required, except for requests for
# a Temporary Credential as described in `Section 2.1`_
# .._`Section 2.1`: https://tools.ietf.org/html/rfc5849#section-2.1
valid_redirect = self.request_validator.validate_redirect_uri(
request.client_key, request.redirect_uri, request)
if not request.redirect_uri:
raise NotImplementedError('Redirect URI must either be provided '
'or set to a default during validation.')
valid_signature = self._check_signature(request)
# log the results to the validator_log
# this lets us handle internal reporting and analysis
request.validator_log['client'] = valid_client
request.validator_log['realm'] = valid_realm
request.validator_log['callback'] = valid_redirect
request.validator_log['signature'] = valid_signature
# We delay checking validity until the very end, using dummy values for
# calculations and fetching secrets/keys to ensure the flow of every
# request remains almost identical regardless of whether valid values
# have been supplied. This ensures near constant time execution and
# prevents malicious users from guessing sensitive information
v = all((valid_client, valid_realm, valid_redirect, valid_signature))
if not v:
log.info("[Failure] request verification failed.")
log.info("Valid client: %s.", valid_client)
log.info("Valid realm: %s.", valid_realm)
log.info("Valid callback: %s.", valid_redirect)
log.info("Valid signature: %s.", valid_signature)
return v, request | [
"def",
"validate_request_token_request",
"(",
"self",
",",
"request",
")",
":",
"self",
".",
"_check_transport_security",
"(",
"request",
")",
"self",
".",
"_check_mandatory_parameters",
"(",
"request",
")",
"if",
"request",
".",
"realm",
":",
"request",
".",
"realms",
"=",
"request",
".",
"realm",
".",
"split",
"(",
"' '",
")",
"else",
":",
"request",
".",
"realms",
"=",
"self",
".",
"request_validator",
".",
"get_default_realms",
"(",
"request",
".",
"client_key",
",",
"request",
")",
"if",
"not",
"self",
".",
"request_validator",
".",
"check_realms",
"(",
"request",
".",
"realms",
")",
":",
"raise",
"errors",
".",
"InvalidRequestError",
"(",
"description",
"=",
"'Invalid realm %s. Allowed are %r.'",
"%",
"(",
"request",
".",
"realms",
",",
"self",
".",
"request_validator",
".",
"realms",
")",
")",
"if",
"not",
"request",
".",
"redirect_uri",
":",
"raise",
"errors",
".",
"InvalidRequestError",
"(",
"description",
"=",
"'Missing callback URI.'",
")",
"if",
"not",
"self",
".",
"request_validator",
".",
"validate_timestamp_and_nonce",
"(",
"request",
".",
"client_key",
",",
"request",
".",
"timestamp",
",",
"request",
".",
"nonce",
",",
"request",
",",
"request_token",
"=",
"request",
".",
"resource_owner_key",
")",
":",
"return",
"False",
",",
"request",
"# The server SHOULD return a 401 (Unauthorized) status code when",
"# receiving a request with invalid client credentials.",
"# Note: This is postponed in order to avoid timing attacks, instead",
"# a dummy client is assigned and used to maintain near constant",
"# time request verification.",
"#",
"# Note that early exit would enable client enumeration",
"valid_client",
"=",
"self",
".",
"request_validator",
".",
"validate_client_key",
"(",
"request",
".",
"client_key",
",",
"request",
")",
"if",
"not",
"valid_client",
":",
"request",
".",
"client_key",
"=",
"self",
".",
"request_validator",
".",
"dummy_client",
"# Note that `realm`_ is only used in authorization headers and how",
"# it should be interepreted is not included in the OAuth spec.",
"# However they could be seen as a scope or realm to which the",
"# client has access and as such every client should be checked",
"# to ensure it is authorized access to that scope or realm.",
"# .. _`realm`: https://tools.ietf.org/html/rfc2617#section-1.2",
"#",
"# Note that early exit would enable client realm access enumeration.",
"#",
"# The require_realm indicates this is the first step in the OAuth",
"# workflow where a client requests access to a specific realm.",
"# This first step (obtaining request token) need not require a realm",
"# and can then be identified by checking the require_resource_owner",
"# flag and abscence of realm.",
"#",
"# Clients obtaining an access token will not supply a realm and it will",
"# not be checked. Instead the previously requested realm should be",
"# transferred from the request token to the access token.",
"#",
"# Access to protected resources will always validate the realm but note",
"# that the realm is now tied to the access token and not provided by",
"# the client.",
"valid_realm",
"=",
"self",
".",
"request_validator",
".",
"validate_requested_realms",
"(",
"request",
".",
"client_key",
",",
"request",
".",
"realms",
",",
"request",
")",
"# Callback is normally never required, except for requests for",
"# a Temporary Credential as described in `Section 2.1`_",
"# .._`Section 2.1`: https://tools.ietf.org/html/rfc5849#section-2.1",
"valid_redirect",
"=",
"self",
".",
"request_validator",
".",
"validate_redirect_uri",
"(",
"request",
".",
"client_key",
",",
"request",
".",
"redirect_uri",
",",
"request",
")",
"if",
"not",
"request",
".",
"redirect_uri",
":",
"raise",
"NotImplementedError",
"(",
"'Redirect URI must either be provided '",
"'or set to a default during validation.'",
")",
"valid_signature",
"=",
"self",
".",
"_check_signature",
"(",
"request",
")",
"# log the results to the validator_log",
"# this lets us handle internal reporting and analysis",
"request",
".",
"validator_log",
"[",
"'client'",
"]",
"=",
"valid_client",
"request",
".",
"validator_log",
"[",
"'realm'",
"]",
"=",
"valid_realm",
"request",
".",
"validator_log",
"[",
"'callback'",
"]",
"=",
"valid_redirect",
"request",
".",
"validator_log",
"[",
"'signature'",
"]",
"=",
"valid_signature",
"# We delay checking validity until the very end, using dummy values for",
"# calculations and fetching secrets/keys to ensure the flow of every",
"# request remains almost identical regardless of whether valid values",
"# have been supplied. This ensures near constant time execution and",
"# prevents malicious users from guessing sensitive information",
"v",
"=",
"all",
"(",
"(",
"valid_client",
",",
"valid_realm",
",",
"valid_redirect",
",",
"valid_signature",
")",
")",
"if",
"not",
"v",
":",
"log",
".",
"info",
"(",
"\"[Failure] request verification failed.\"",
")",
"log",
".",
"info",
"(",
"\"Valid client: %s.\"",
",",
"valid_client",
")",
"log",
".",
"info",
"(",
"\"Valid realm: %s.\"",
",",
"valid_realm",
")",
"log",
".",
"info",
"(",
"\"Valid callback: %s.\"",
",",
"valid_redirect",
")",
"log",
".",
"info",
"(",
"\"Valid signature: %s.\"",
",",
"valid_signature",
")",
"return",
"v",
",",
"request"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/oauthlib/oauth1/rfc5849/endpoints/request_token.py#L111-L209 | |
GJDuck/LowFat | ecf6a0f0fa1b73a27a626cf493cc39e477b6faea | llvm-4.0.0.src/projects/compiler-rt/lib/sanitizer_common/scripts/cpplint.py | python | ProcessFileData | (filename, file_extension, lines, error,
extra_check_functions=[]) | Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error | Performs lint checks and reports any errors to the given error function. | [
"Performs",
"lint",
"checks",
"and",
"reports",
"any",
"errors",
"to",
"the",
"given",
"error",
"function",
"."
] | def ProcessFileData(filename, file_extension, lines, error,
extra_check_functions=[]):
"""Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
lines = (['// marker so line numbers and indices both start at 1'] + lines +
['// marker so line numbers end in a known way'])
include_state = _IncludeState()
function_state = _FunctionState()
nesting_state = _NestingState()
ResetNolintSuppressions()
CheckForCopyright(filename, lines, error)
if file_extension == 'h':
CheckForHeaderGuard(filename, lines, error)
RemoveMultiLineComments(filename, lines, error)
clean_lines = CleansedLines(lines)
for line in xrange(clean_lines.NumLines()):
ProcessLine(filename, file_extension, clean_lines, line,
include_state, function_state, nesting_state, error,
extra_check_functions)
nesting_state.CheckClassFinished(filename, error)
CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
# We check here rather than inside ProcessLine so that we see raw
# lines rather than "cleaned" lines.
CheckForUnicodeReplacementCharacters(filename, lines, error)
CheckForNewlineAtEOF(filename, lines, error) | [
"def",
"ProcessFileData",
"(",
"filename",
",",
"file_extension",
",",
"lines",
",",
"error",
",",
"extra_check_functions",
"=",
"[",
"]",
")",
":",
"lines",
"=",
"(",
"[",
"'// marker so line numbers and indices both start at 1'",
"]",
"+",
"lines",
"+",
"[",
"'// marker so line numbers end in a known way'",
"]",
")",
"include_state",
"=",
"_IncludeState",
"(",
")",
"function_state",
"=",
"_FunctionState",
"(",
")",
"nesting_state",
"=",
"_NestingState",
"(",
")",
"ResetNolintSuppressions",
"(",
")",
"CheckForCopyright",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"if",
"file_extension",
"==",
"'h'",
":",
"CheckForHeaderGuard",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"RemoveMultiLineComments",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"clean_lines",
"=",
"CleansedLines",
"(",
"lines",
")",
"for",
"line",
"in",
"xrange",
"(",
"clean_lines",
".",
"NumLines",
"(",
")",
")",
":",
"ProcessLine",
"(",
"filename",
",",
"file_extension",
",",
"clean_lines",
",",
"line",
",",
"include_state",
",",
"function_state",
",",
"nesting_state",
",",
"error",
",",
"extra_check_functions",
")",
"nesting_state",
".",
"CheckClassFinished",
"(",
"filename",
",",
"error",
")",
"CheckForIncludeWhatYouUse",
"(",
"filename",
",",
"clean_lines",
",",
"include_state",
",",
"error",
")",
"# We check here rather than inside ProcessLine so that we see raw",
"# lines rather than \"cleaned\" lines.",
"CheckForUnicodeReplacementCharacters",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"CheckForNewlineAtEOF",
"(",
"filename",
",",
"lines",
",",
"error",
")"
] | https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/projects/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L3814-L3857 | ||
IfcOpenShell/IfcOpenShell | 2c2954b11a9c9d581bef03240836d4567e69ad0b | src/ifcopenshell-python/ifcopenshell/file.py | python | file.by_id | (self, id) | return self[id] | Return an IFC entity instance filtered by IFC ID.
:param id: STEP numerical identifier
:type id: int
:returns: An ifcopenshell.entity_instance.entity_instance
:rtype: ifcopenshell.entity_instance.entity_instance | Return an IFC entity instance filtered by IFC ID. | [
"Return",
"an",
"IFC",
"entity",
"instance",
"filtered",
"by",
"IFC",
"ID",
"."
] | def by_id(self, id):
"""Return an IFC entity instance filtered by IFC ID.
:param id: STEP numerical identifier
:type id: int
:returns: An ifcopenshell.entity_instance.entity_instance
:rtype: ifcopenshell.entity_instance.entity_instance
"""
return self[id] | [
"def",
"by_id",
"(",
"self",
",",
"id",
")",
":",
"return",
"self",
"[",
"id",
"]"
] | https://github.com/IfcOpenShell/IfcOpenShell/blob/2c2954b11a9c9d581bef03240836d4567e69ad0b/src/ifcopenshell-python/ifcopenshell/file.py#L310-L318 | |
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/osr.py | python | SpatialReference.IsLocal | (self, *args) | return _osr.SpatialReference_IsLocal(self, *args) | r"""IsLocal(SpatialReference self) -> int | r"""IsLocal(SpatialReference self) -> int | [
"r",
"IsLocal",
"(",
"SpatialReference",
"self",
")",
"-",
">",
"int"
] | def IsLocal(self, *args):
r"""IsLocal(SpatialReference self) -> int"""
return _osr.SpatialReference_IsLocal(self, *args) | [
"def",
"IsLocal",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_osr",
".",
"SpatialReference_IsLocal",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/osr.py#L366-L368 | |
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_envs/agents/utility.py | python | save_config | (config, logdir=None) | return config | Save a new configuration by name.
If a logging directory is specified, is will be created and the configuration
will be stored there. Otherwise, a log message will be printed.
Args:
config: Configuration object.
logdir: Location for writing summaries and checkpoints if specified.
Returns:
Configuration object. | Save a new configuration by name. | [
"Save",
"a",
"new",
"configuration",
"by",
"name",
"."
] | def save_config(config, logdir=None):
"""Save a new configuration by name.
If a logging directory is specified, is will be created and the configuration
will be stored there. Otherwise, a log message will be printed.
Args:
config: Configuration object.
logdir: Location for writing summaries and checkpoints if specified.
Returns:
Configuration object.
"""
if logdir:
with config.unlocked:
config.logdir = logdir
message = 'Start a new run and write summaries and checkpoints to {}.'
tf.logging.info(message.format(config.logdir))
tf.gfile.MakeDirs(config.logdir)
config_path = os.path.join(config.logdir, 'config.yaml')
with tf.gfile.GFile(config_path, 'w') as file_:
yaml.dump(config, file_, default_flow_style=False)
else:
message = ('Start a new run without storing summaries and checkpoints since no '
'logging directory was specified.')
tf.logging.info(message)
return config | [
"def",
"save_config",
"(",
"config",
",",
"logdir",
"=",
"None",
")",
":",
"if",
"logdir",
":",
"with",
"config",
".",
"unlocked",
":",
"config",
".",
"logdir",
"=",
"logdir",
"message",
"=",
"'Start a new run and write summaries and checkpoints to {}.'",
"tf",
".",
"logging",
".",
"info",
"(",
"message",
".",
"format",
"(",
"config",
".",
"logdir",
")",
")",
"tf",
".",
"gfile",
".",
"MakeDirs",
"(",
"config",
".",
"logdir",
")",
"config_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config",
".",
"logdir",
",",
"'config.yaml'",
")",
"with",
"tf",
".",
"gfile",
".",
"GFile",
"(",
"config_path",
",",
"'w'",
")",
"as",
"file_",
":",
"yaml",
".",
"dump",
"(",
"config",
",",
"file_",
",",
"default_flow_style",
"=",
"False",
")",
"else",
":",
"message",
"=",
"(",
"'Start a new run without storing summaries and checkpoints since no '",
"'logging directory was specified.'",
")",
"tf",
".",
"logging",
".",
"info",
"(",
"message",
")",
"return",
"config"
] | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/agents/utility.py#L129-L155 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | LayoutAlgorithm.LayoutWindow | (*args, **kwargs) | return _windows_.LayoutAlgorithm_LayoutWindow(*args, **kwargs) | LayoutWindow(self, Window parent, Window mainWindow=None) -> bool | LayoutWindow(self, Window parent, Window mainWindow=None) -> bool | [
"LayoutWindow",
"(",
"self",
"Window",
"parent",
"Window",
"mainWindow",
"=",
"None",
")",
"-",
">",
"bool"
] | def LayoutWindow(*args, **kwargs):
"""LayoutWindow(self, Window parent, Window mainWindow=None) -> bool"""
return _windows_.LayoutAlgorithm_LayoutWindow(*args, **kwargs) | [
"def",
"LayoutWindow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"LayoutAlgorithm_LayoutWindow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L2101-L2103 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/ops/__init__.py | python | should_reindex_frame_op | (
left: DataFrame, right, op, axis, default_axis, fill_value, level
) | return False | Check if this is an operation between DataFrames that will need to reindex. | Check if this is an operation between DataFrames that will need to reindex. | [
"Check",
"if",
"this",
"is",
"an",
"operation",
"between",
"DataFrames",
"that",
"will",
"need",
"to",
"reindex",
"."
] | def should_reindex_frame_op(
left: DataFrame, right, op, axis, default_axis, fill_value, level
) -> bool:
"""
Check if this is an operation between DataFrames that will need to reindex.
"""
assert isinstance(left, ABCDataFrame)
if op is operator.pow or op is roperator.rpow:
# GH#32685 pow has special semantics for operating with null values
return False
if not isinstance(right, ABCDataFrame):
return False
if fill_value is None and level is None and axis is default_axis:
# TODO: any other cases we should handle here?
# Intersection is always unique so we have to check the unique columns
left_uniques = left.columns.unique()
right_uniques = right.columns.unique()
cols = left_uniques.intersection(right_uniques)
if len(cols) and not (cols.equals(left_uniques) and cols.equals(right_uniques)):
# TODO: is there a shortcut available when len(cols) == 0?
return True
return False | [
"def",
"should_reindex_frame_op",
"(",
"left",
":",
"DataFrame",
",",
"right",
",",
"op",
",",
"axis",
",",
"default_axis",
",",
"fill_value",
",",
"level",
")",
"->",
"bool",
":",
"assert",
"isinstance",
"(",
"left",
",",
"ABCDataFrame",
")",
"if",
"op",
"is",
"operator",
".",
"pow",
"or",
"op",
"is",
"roperator",
".",
"rpow",
":",
"# GH#32685 pow has special semantics for operating with null values",
"return",
"False",
"if",
"not",
"isinstance",
"(",
"right",
",",
"ABCDataFrame",
")",
":",
"return",
"False",
"if",
"fill_value",
"is",
"None",
"and",
"level",
"is",
"None",
"and",
"axis",
"is",
"default_axis",
":",
"# TODO: any other cases we should handle here?",
"# Intersection is always unique so we have to check the unique columns",
"left_uniques",
"=",
"left",
".",
"columns",
".",
"unique",
"(",
")",
"right_uniques",
"=",
"right",
".",
"columns",
".",
"unique",
"(",
")",
"cols",
"=",
"left_uniques",
".",
"intersection",
"(",
"right_uniques",
")",
"if",
"len",
"(",
"cols",
")",
"and",
"not",
"(",
"cols",
".",
"equals",
"(",
"left_uniques",
")",
"and",
"cols",
".",
"equals",
"(",
"right_uniques",
")",
")",
":",
"# TODO: is there a shortcut available when len(cols) == 0?",
"return",
"True",
"return",
"False"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/ops/__init__.py#L314-L340 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/stc.py | python | StyledTextCtrl.SelectionIsRectangle | (*args, **kwargs) | return _stc.StyledTextCtrl_SelectionIsRectangle(*args, **kwargs) | SelectionIsRectangle(self) -> bool
Is the selection rectangular? The alternative is the more common stream selection. | SelectionIsRectangle(self) -> bool | [
"SelectionIsRectangle",
"(",
"self",
")",
"-",
">",
"bool"
] | def SelectionIsRectangle(*args, **kwargs):
"""
SelectionIsRectangle(self) -> bool
Is the selection rectangular? The alternative is the more common stream selection.
"""
return _stc.StyledTextCtrl_SelectionIsRectangle(*args, **kwargs) | [
"def",
"SelectionIsRectangle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_SelectionIsRectangle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L4964-L4970 | |
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/showutil/TexMemWatcher.py | python | TexMemWatcher.unplaceTexture | (self, tr) | Removes the texture from its place on the canvas. | Removes the texture from its place on the canvas. | [
"Removes",
"the",
"texture",
"from",
"its",
"place",
"on",
"the",
"canvas",
"."
] | def unplaceTexture(self, tr):
""" Removes the texture from its place on the canvas. """
if tr.placements:
for tp in tr.placements:
tp.clearBitmasks(self.bitmasks)
if not tp.overflowed:
self.placedQSize -= tp.area
assert self.placedQSize >= 0
del self.texPlacements[tp]
tr.placements = []
tr.clearCard(self)
if not tr.overflowed:
self.placedSize -= tr.size
assert self.placedSize >= 0
tr.overflowed = 0 | [
"def",
"unplaceTexture",
"(",
"self",
",",
"tr",
")",
":",
"if",
"tr",
".",
"placements",
":",
"for",
"tp",
"in",
"tr",
".",
"placements",
":",
"tp",
".",
"clearBitmasks",
"(",
"self",
".",
"bitmasks",
")",
"if",
"not",
"tp",
".",
"overflowed",
":",
"self",
".",
"placedQSize",
"-=",
"tp",
".",
"area",
"assert",
"self",
".",
"placedQSize",
">=",
"0",
"del",
"self",
".",
"texPlacements",
"[",
"tp",
"]",
"tr",
".",
"placements",
"=",
"[",
"]",
"tr",
".",
"clearCard",
"(",
"self",
")",
"if",
"not",
"tr",
".",
"overflowed",
":",
"self",
".",
"placedSize",
"-=",
"tr",
".",
"size",
"assert",
"self",
".",
"placedSize",
">=",
"0",
"tr",
".",
"overflowed",
"=",
"0"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/showutil/TexMemWatcher.py#L756-L770 | ||
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | v8_7_5/tools/stats-viewer.py | python | ChromeCounterCollection.__init__ | (self, data) | Create a new instance.
Args:
data: the shared data access object | Create a new instance. | [
"Create",
"a",
"new",
"instance",
"."
] | def __init__(self, data):
"""Create a new instance.
Args:
data: the shared data access object
"""
self.data = data
self.max_counters = data.IntAt(8)
self.max_threads = data.IntAt(12)
self.counter_names_offset = \
self._HEADER_SIZE + self.max_threads * (self._THREAD_NAME_SIZE + 2 * 4)
self.counter_values_offset = \
self.counter_names_offset + self.max_counters * self._COUNTER_NAME_SIZE | [
"def",
"__init__",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"data",
"=",
"data",
"self",
".",
"max_counters",
"=",
"data",
".",
"IntAt",
"(",
"8",
")",
"self",
".",
"max_threads",
"=",
"data",
".",
"IntAt",
"(",
"12",
")",
"self",
".",
"counter_names_offset",
"=",
"self",
".",
"_HEADER_SIZE",
"+",
"self",
".",
"max_threads",
"*",
"(",
"self",
".",
"_THREAD_NAME_SIZE",
"+",
"2",
"*",
"4",
")",
"self",
".",
"counter_values_offset",
"=",
"self",
".",
"counter_names_offset",
"+",
"self",
".",
"max_counters",
"*",
"self",
".",
"_COUNTER_NAME_SIZE"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/v8_7_5/tools/stats-viewer.py#L425-L437 | ||
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | bindings/python/cntk/learners/__init__.py | python | momentum_as_time_constant_schedule | (momentum, epoch_size=None) | Create a momentum schedule in a minibatch-size agnostic way
(using the same semantics as :func:`training_parameter_schedule`
with `unit=UnitType.sample`).
Deprecated:: 2.2
This is for legacy API.
In this legacy API,::
#assume the desired minibatch size invariant constant momentum rate is: momentum_rate
momentum_time_constant = -minibatch_size/np.log(momentum_rate)
momentum = momentum_as_time_constant_schedule(momentum_time_constant)
The equivalent code in the latest API, ::
momentum = momentum_schedule(momentum_rate, minibatch_size = minibatch_size)
Args:
momentum (float or list): see parameter ``schedule`` in
:func:`training_parameter_schedule`.
epoch_size (int): see parameter ``epoch_size`` in
:func:`training_parameter_schedule`.
CNTK specifies momentum in a minibatch-size agnostic way as the time
constant (in samples) of a unit-gain 1st-order IIR filter. The value
specifies the number of samples after which a gradient has an effect of
1/e=37%.
If you want to specify the momentum per N samples (or per minibatch),
use :func:`momentum_schedule`.
Examples:
>>> # Use a fixed momentum of 1100 for all samples
>>> m = momentum_as_time_constant_schedule(1100)
>>> # Use the time constant 1100 for the first 1000 samples,
>>> # then 1500 for the remaining ones
>>> m = momentum_as_time_constant_schedule([1100, 1500], 1000)
Returns:
momentum as time constant schedule | Create a momentum schedule in a minibatch-size agnostic way
(using the same semantics as :func:`training_parameter_schedule`
with `unit=UnitType.sample`). | [
"Create",
"a",
"momentum",
"schedule",
"in",
"a",
"minibatch",
"-",
"size",
"agnostic",
"way",
"(",
"using",
"the",
"same",
"semantics",
"as",
":",
"func",
":",
"training_parameter_schedule",
"with",
"unit",
"=",
"UnitType",
".",
"sample",
")",
"."
] | def momentum_as_time_constant_schedule(momentum, epoch_size=None):
'''
Create a momentum schedule in a minibatch-size agnostic way
(using the same semantics as :func:`training_parameter_schedule`
with `unit=UnitType.sample`).
Deprecated:: 2.2
This is for legacy API.
In this legacy API,::
#assume the desired minibatch size invariant constant momentum rate is: momentum_rate
momentum_time_constant = -minibatch_size/np.log(momentum_rate)
momentum = momentum_as_time_constant_schedule(momentum_time_constant)
The equivalent code in the latest API, ::
momentum = momentum_schedule(momentum_rate, minibatch_size = minibatch_size)
Args:
momentum (float or list): see parameter ``schedule`` in
:func:`training_parameter_schedule`.
epoch_size (int): see parameter ``epoch_size`` in
:func:`training_parameter_schedule`.
CNTK specifies momentum in a minibatch-size agnostic way as the time
constant (in samples) of a unit-gain 1st-order IIR filter. The value
specifies the number of samples after which a gradient has an effect of
1/e=37%.
If you want to specify the momentum per N samples (or per minibatch),
use :func:`momentum_schedule`.
Examples:
>>> # Use a fixed momentum of 1100 for all samples
>>> m = momentum_as_time_constant_schedule(1100)
>>> # Use the time constant 1100 for the first 1000 samples,
>>> # then 1500 for the remaining ones
>>> m = momentum_as_time_constant_schedule([1100, 1500], 1000)
Returns:
momentum as time constant schedule
'''
if isinstance(momentum, (cntk_py.training_double_parameter_schedule)):
#the legacy momentum as time constant schedule: the ref minibatch size is always 1, so it is specified by definition
momentum.is_minibatch_size_explicitly_specified = True
return momentum
if isinstance(momentum, (int, float)):
if epoch_size is not None:
warnings.warn('When providing the schedule as a number, epoch_size is ignored', RuntimeWarning)
momentum = cntk_py.momentum_as_time_constant_schedule(momentum)
momentum.is_minibatch_size_explicitly_specified = True
return momentum
epoch_size = epoch_size if epoch_size is not None else cntk_py.training_double_parameter_schedule.full_data_sweep
if isinstance(momentum, list):
momentum = _prepare_training_parameter_list(momentum)
args = [momentum, epoch_size, 1] #momentum constant schedule's reference minibatch size is always per sample
momentum = cntk_py.training_double_parameter_schedule(*args)
momentum = cntk_py.momentum_as_time_constant_schedule(momentum)
momentum.is_minibatch_size_explicitly_specified = True
return momentum
raise ValueError(
'momentum must be either a float or a list, not %s' % type(momentum)) | [
"def",
"momentum_as_time_constant_schedule",
"(",
"momentum",
",",
"epoch_size",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"momentum",
",",
"(",
"cntk_py",
".",
"training_double_parameter_schedule",
")",
")",
":",
"#the legacy momentum as time constant schedule: the ref minibatch size is always 1, so it is specified by definition",
"momentum",
".",
"is_minibatch_size_explicitly_specified",
"=",
"True",
"return",
"momentum",
"if",
"isinstance",
"(",
"momentum",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"if",
"epoch_size",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"'When providing the schedule as a number, epoch_size is ignored'",
",",
"RuntimeWarning",
")",
"momentum",
"=",
"cntk_py",
".",
"momentum_as_time_constant_schedule",
"(",
"momentum",
")",
"momentum",
".",
"is_minibatch_size_explicitly_specified",
"=",
"True",
"return",
"momentum",
"epoch_size",
"=",
"epoch_size",
"if",
"epoch_size",
"is",
"not",
"None",
"else",
"cntk_py",
".",
"training_double_parameter_schedule",
".",
"full_data_sweep",
"if",
"isinstance",
"(",
"momentum",
",",
"list",
")",
":",
"momentum",
"=",
"_prepare_training_parameter_list",
"(",
"momentum",
")",
"args",
"=",
"[",
"momentum",
",",
"epoch_size",
",",
"1",
"]",
"#momentum constant schedule's reference minibatch size is always per sample",
"momentum",
"=",
"cntk_py",
".",
"training_double_parameter_schedule",
"(",
"*",
"args",
")",
"momentum",
"=",
"cntk_py",
".",
"momentum_as_time_constant_schedule",
"(",
"momentum",
")",
"momentum",
".",
"is_minibatch_size_explicitly_specified",
"=",
"True",
"return",
"momentum",
"raise",
"ValueError",
"(",
"'momentum must be either a float or a list, not %s'",
"%",
"type",
"(",
"momentum",
")",
")"
] | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/learners/__init__.py#L471-L537 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/dynamic_lr.py | python | natural_exp_decay_lr | (learning_rate, decay_rate, total_step, step_per_epoch, decay_epoch, is_stair=False) | return lr | r"""
Calculates learning rate base on natural exponential decay function.
For the i-th step, the formula of computing decayed_learning_rate[i] is:
.. math::
decayed\_learning\_rate[i] = learning\_rate * e^{-decay\_rate * current\_epoch}
Where :math:`current\_epoch=floor(\frac{i}{step\_per\_epoch})`.
Args:
learning_rate (float): The initial value of learning rate.
decay_rate (float): The decay rate.
total_step (int): The total number of steps.
step_per_epoch (int): The number of steps in per epoch.
decay_epoch (int): A value used to calculate decayed learning rate.
is_stair (bool): If true, learning rate is decayed once every `decay_epoch` times. Default: False.
Returns:
list[float]. The size of list is `total_step`.
Examples:
>>> import mindspore.nn as nn
>>>
>>> learning_rate = 0.1
>>> decay_rate = 0.9
>>> total_step = 6
>>> step_per_epoch = 2
>>> decay_epoch = 2
>>> output = nn.natural_exp_decay_lr(learning_rate, decay_rate, total_step, step_per_epoch, decay_epoch, True)
>>> print(output)
[0.1, 0.1, 0.1, 0.1, 0.016529888822158657, 0.016529888822158657] | r"""
Calculates learning rate base on natural exponential decay function. | [
"r",
"Calculates",
"learning",
"rate",
"base",
"on",
"natural",
"exponential",
"decay",
"function",
"."
] | def natural_exp_decay_lr(learning_rate, decay_rate, total_step, step_per_epoch, decay_epoch, is_stair=False):
r"""
Calculates learning rate base on natural exponential decay function.
For the i-th step, the formula of computing decayed_learning_rate[i] is:
.. math::
decayed\_learning\_rate[i] = learning\_rate * e^{-decay\_rate * current\_epoch}
Where :math:`current\_epoch=floor(\frac{i}{step\_per\_epoch})`.
Args:
learning_rate (float): The initial value of learning rate.
decay_rate (float): The decay rate.
total_step (int): The total number of steps.
step_per_epoch (int): The number of steps in per epoch.
decay_epoch (int): A value used to calculate decayed learning rate.
is_stair (bool): If true, learning rate is decayed once every `decay_epoch` times. Default: False.
Returns:
list[float]. The size of list is `total_step`.
Examples:
>>> import mindspore.nn as nn
>>>
>>> learning_rate = 0.1
>>> decay_rate = 0.9
>>> total_step = 6
>>> step_per_epoch = 2
>>> decay_epoch = 2
>>> output = nn.natural_exp_decay_lr(learning_rate, decay_rate, total_step, step_per_epoch, decay_epoch, True)
>>> print(output)
[0.1, 0.1, 0.1, 0.1, 0.016529888822158657, 0.016529888822158657]
"""
_check_inputs(learning_rate, decay_rate, total_step, step_per_epoch, decay_epoch, is_stair)
function = lambda x, y: x
if is_stair:
function = lambda x, y: math.floor(x / y) * y
lr = []
for i in range(total_step):
lr.append(learning_rate * math.e ** (-decay_rate * function(math.floor(i / step_per_epoch), decay_epoch)))
return lr | [
"def",
"natural_exp_decay_lr",
"(",
"learning_rate",
",",
"decay_rate",
",",
"total_step",
",",
"step_per_epoch",
",",
"decay_epoch",
",",
"is_stair",
"=",
"False",
")",
":",
"_check_inputs",
"(",
"learning_rate",
",",
"decay_rate",
",",
"total_step",
",",
"step_per_epoch",
",",
"decay_epoch",
",",
"is_stair",
")",
"function",
"=",
"lambda",
"x",
",",
"y",
":",
"x",
"if",
"is_stair",
":",
"function",
"=",
"lambda",
"x",
",",
"y",
":",
"math",
".",
"floor",
"(",
"x",
"/",
"y",
")",
"*",
"y",
"lr",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"total_step",
")",
":",
"lr",
".",
"append",
"(",
"learning_rate",
"*",
"math",
".",
"e",
"**",
"(",
"-",
"decay_rate",
"*",
"function",
"(",
"math",
".",
"floor",
"(",
"i",
"/",
"step_per_epoch",
")",
",",
"decay_epoch",
")",
")",
")",
"return",
"lr"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/dynamic_lr.py#L129-L172 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/debug/wrappers/framework.py | python | NonInteractiveDebugWrapperSession.on_session_init | (self, request) | return OnSessionInitResponse(OnSessionInitAction.PROCEED) | See doc of BaseDebugWrapperSession.on_run_start. | See doc of BaseDebugWrapperSession.on_run_start. | [
"See",
"doc",
"of",
"BaseDebugWrapperSession",
".",
"on_run_start",
"."
] | def on_session_init(self, request):
"""See doc of BaseDebugWrapperSession.on_run_start."""
return OnSessionInitResponse(OnSessionInitAction.PROCEED) | [
"def",
"on_session_init",
"(",
"self",
",",
"request",
")",
":",
"return",
"OnSessionInitResponse",
"(",
"OnSessionInitAction",
".",
"PROCEED",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/debug/wrappers/framework.py#L920-L923 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/logging/__init__.py | python | FileHandler.emit | (self, record) | Emit a record.
If the stream was not opened because 'delay' was specified in the
constructor, open it before calling the superclass's emit. | Emit a record. | [
"Emit",
"a",
"record",
"."
] | def emit(self, record):
"""
Emit a record.
If the stream was not opened because 'delay' was specified in the
constructor, open it before calling the superclass's emit.
"""
if self.stream is None:
self.stream = self._open()
StreamHandler.emit(self, record) | [
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"if",
"self",
".",
"stream",
"is",
"None",
":",
"self",
".",
"stream",
"=",
"self",
".",
"_open",
"(",
")",
"StreamHandler",
".",
"emit",
"(",
"self",
",",
"record",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/logging/__init__.py#L1178-L1187 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py | python | Distribution._filter_extras | (dm) | return dm | Given a mapping of extras to dependencies, strip off
environment markers and filter out any dependencies
not matching the markers. | Given a mapping of extras to dependencies, strip off
environment markers and filter out any dependencies
not matching the markers. | [
"Given",
"a",
"mapping",
"of",
"extras",
"to",
"dependencies",
"strip",
"off",
"environment",
"markers",
"and",
"filter",
"out",
"any",
"dependencies",
"not",
"matching",
"the",
"markers",
"."
] | def _filter_extras(dm):
"""
Given a mapping of extras to dependencies, strip off
environment markers and filter out any dependencies
not matching the markers.
"""
for extra in list(filter(None, dm)):
new_extra = extra
reqs = dm.pop(extra)
new_extra, _, marker = extra.partition(':')
fails_marker = marker and (
invalid_marker(marker)
or not evaluate_marker(marker)
)
if fails_marker:
reqs = []
new_extra = safe_extra(new_extra) or None
dm.setdefault(new_extra, []).extend(reqs)
return dm | [
"def",
"_filter_extras",
"(",
"dm",
")",
":",
"for",
"extra",
"in",
"list",
"(",
"filter",
"(",
"None",
",",
"dm",
")",
")",
":",
"new_extra",
"=",
"extra",
"reqs",
"=",
"dm",
".",
"pop",
"(",
"extra",
")",
"new_extra",
",",
"_",
",",
"marker",
"=",
"extra",
".",
"partition",
"(",
"':'",
")",
"fails_marker",
"=",
"marker",
"and",
"(",
"invalid_marker",
"(",
"marker",
")",
"or",
"not",
"evaluate_marker",
"(",
"marker",
")",
")",
"if",
"fails_marker",
":",
"reqs",
"=",
"[",
"]",
"new_extra",
"=",
"safe_extra",
"(",
"new_extra",
")",
"or",
"None",
"dm",
".",
"setdefault",
"(",
"new_extra",
",",
"[",
"]",
")",
".",
"extend",
"(",
"reqs",
")",
"return",
"dm"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py#L2706-L2725 | |
Jittor/jittor | e9aca0444c2bdc8e2389d99122954cd0903eec46 | python/jittor/__init__.py | python | rand_like | (x, dtype=None) | return jt.random(x.shape, x.dtype) | samples random values from standard uniform distribution with the same shape as x.
:param x: reference variable.
:type x: jt.Var
:param dtype: if None, the dtype of the output is the same as x.
Otherwise, use the specified dtype. Defaults to None.
:type dtype: str, optional
Example:
>>> x = jt.zeros((2, 3))
>>> jt.rand_like(x)
jt.Var([[0.6164821 0.21476883 0.61959815]
[0.58626485 0.35345772 0.5638483 ]], dtype=float32) | samples random values from standard uniform distribution with the same shape as x.
:param x: reference variable.
:type x: jt.Var
:param dtype: if None, the dtype of the output is the same as x.
Otherwise, use the specified dtype. Defaults to None.
:type dtype: str, optional
Example:
>>> x = jt.zeros((2, 3))
>>> jt.rand_like(x)
jt.Var([[0.6164821 0.21476883 0.61959815]
[0.58626485 0.35345772 0.5638483 ]], dtype=float32) | [
"samples",
"random",
"values",
"from",
"standard",
"uniform",
"distribution",
"with",
"the",
"same",
"shape",
"as",
"x",
".",
":",
"param",
"x",
":",
"reference",
"variable",
".",
":",
"type",
"x",
":",
"jt",
".",
"Var",
":",
"param",
"dtype",
":",
"if",
"None",
"the",
"dtype",
"of",
"the",
"output",
"is",
"the",
"same",
"as",
"x",
".",
"Otherwise",
"use",
"the",
"specified",
"dtype",
".",
"Defaults",
"to",
"None",
".",
":",
"type",
"dtype",
":",
"str",
"optional",
"Example",
":",
">>>",
"x",
"=",
"jt",
".",
"zeros",
"((",
"2",
"3",
"))",
">>>",
"jt",
".",
"rand_like",
"(",
"x",
")",
"jt",
".",
"Var",
"(",
"[[",
"0",
".",
"6164821",
"0",
".",
"21476883",
"0",
".",
"61959815",
"]",
"[",
"0",
".",
"58626485",
"0",
".",
"35345772",
"0",
".",
"5638483",
"]]",
"dtype",
"=",
"float32",
")"
] | def rand_like(x, dtype=None) -> Var:
''' samples random values from standard uniform distribution with the same shape as x.
:param x: reference variable.
:type x: jt.Var
:param dtype: if None, the dtype of the output is the same as x.
Otherwise, use the specified dtype. Defaults to None.
:type dtype: str, optional
Example:
>>> x = jt.zeros((2, 3))
>>> jt.rand_like(x)
jt.Var([[0.6164821 0.21476883 0.61959815]
[0.58626485 0.35345772 0.5638483 ]], dtype=float32)
'''
if dtype is None: dtype = x.dtype
return jt.random(x.shape, x.dtype) | [
"def",
"rand_like",
"(",
"x",
",",
"dtype",
"=",
"None",
")",
"->",
"Var",
":",
"if",
"dtype",
"is",
"None",
":",
"dtype",
"=",
"x",
".",
"dtype",
"return",
"jt",
".",
"random",
"(",
"x",
".",
"shape",
",",
"x",
".",
"dtype",
")"
] | https://github.com/Jittor/jittor/blob/e9aca0444c2bdc8e2389d99122954cd0903eec46/python/jittor/__init__.py#L536-L554 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/reader/decorator.py | python | compose | (*readers, **kwargs) | return reader | Creates a data reader whose output is the combination of input readers.
If input readers output following data entries:
(1, 2) 3 (4, 5)
The composed reader will output:
(1, 2, 3, 4, 5)
Args:
readers (Reader|list of Reader): readers that will be composed together.
check_alignment(bool, optional): Indicates whether the input readers are checked for
alignment. If True, whether input readers are aligned
correctly will be checked, else alignment will not be checkout and trailing outputs
will be discarded. Defaults to True.
Returns:
the new data reader (Reader).
Raises:
ComposeNotAligned: outputs of readers are not aligned. This will not raise if check_alignment is set to False.
Examples:
.. code-block:: python
import paddle.fluid as fluid
def reader_creator_10(dur):
def reader():
for i in range(10):
yield i
return reader
reader = fluid.io.compose(reader_creator_10(0), reader_creator_10(0)) | Creates a data reader whose output is the combination of input readers. | [
"Creates",
"a",
"data",
"reader",
"whose",
"output",
"is",
"the",
"combination",
"of",
"input",
"readers",
"."
] | def compose(*readers, **kwargs):
"""
Creates a data reader whose output is the combination of input readers.
If input readers output following data entries:
(1, 2) 3 (4, 5)
The composed reader will output:
(1, 2, 3, 4, 5)
Args:
readers (Reader|list of Reader): readers that will be composed together.
check_alignment(bool, optional): Indicates whether the input readers are checked for
alignment. If True, whether input readers are aligned
correctly will be checked, else alignment will not be checkout and trailing outputs
will be discarded. Defaults to True.
Returns:
the new data reader (Reader).
Raises:
ComposeNotAligned: outputs of readers are not aligned. This will not raise if check_alignment is set to False.
Examples:
.. code-block:: python
import paddle.fluid as fluid
def reader_creator_10(dur):
def reader():
for i in range(10):
yield i
return reader
reader = fluid.io.compose(reader_creator_10(0), reader_creator_10(0))
"""
check_alignment = kwargs.pop('check_alignment', True)
def make_tuple(x):
if isinstance(x, tuple):
return x
else:
return (x, )
def reader():
rs = []
for r in readers:
rs.append(r())
if not check_alignment:
for outputs in zip(*rs):
yield sum(list(map(make_tuple, outputs)), ())
else:
for outputs in zip_longest(*rs):
for o in outputs:
if o is None:
# None will be not be present if compose is aligned
raise ComposeNotAligned(
"outputs of readers are not aligned.")
yield sum(list(map(make_tuple, outputs)), ())
return reader | [
"def",
"compose",
"(",
"*",
"readers",
",",
"*",
"*",
"kwargs",
")",
":",
"check_alignment",
"=",
"kwargs",
".",
"pop",
"(",
"'check_alignment'",
",",
"True",
")",
"def",
"make_tuple",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"tuple",
")",
":",
"return",
"x",
"else",
":",
"return",
"(",
"x",
",",
")",
"def",
"reader",
"(",
")",
":",
"rs",
"=",
"[",
"]",
"for",
"r",
"in",
"readers",
":",
"rs",
".",
"append",
"(",
"r",
"(",
")",
")",
"if",
"not",
"check_alignment",
":",
"for",
"outputs",
"in",
"zip",
"(",
"*",
"rs",
")",
":",
"yield",
"sum",
"(",
"list",
"(",
"map",
"(",
"make_tuple",
",",
"outputs",
")",
")",
",",
"(",
")",
")",
"else",
":",
"for",
"outputs",
"in",
"zip_longest",
"(",
"*",
"rs",
")",
":",
"for",
"o",
"in",
"outputs",
":",
"if",
"o",
"is",
"None",
":",
"# None will be not be present if compose is aligned",
"raise",
"ComposeNotAligned",
"(",
"\"outputs of readers are not aligned.\"",
")",
"yield",
"sum",
"(",
"list",
"(",
"map",
"(",
"make_tuple",
",",
"outputs",
")",
")",
",",
"(",
")",
")",
"return",
"reader"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/reader/decorator.py#L248-L305 | |
rodeofx/OpenWalter | 6116fbe3f04f1146c854afbfbdbe944feaee647e | walter/katana/WalterIn/walterVariantsMenu.py | python | WalterVariantsToolbar._buildControlWidget | (self, layout) | Called when FormWidget needs a container for control widgets. | Called when FormWidget needs a container for control widgets. | [
"Called",
"when",
"FormWidget",
"needs",
"a",
"container",
"for",
"control",
"widgets",
"."
] | def _buildControlWidget(self, layout):
"""Called when FormWidget needs a container for control widgets."""
self.variantsMenu = VariantsMenu(self)
action = QtGui.QAction("Variants", self)
action.triggered.connect(self.__showVariantsMenu)
self.__variantButton = ToolbarButton(
"Variants", self, IconManager.GetPixmap('Icons/plug24.png'),
None, None, None, False, False, None, None, None, None,
action)
layout.addWidget(self.__variantButton)
self.__registerEventsHandler() | [
"def",
"_buildControlWidget",
"(",
"self",
",",
"layout",
")",
":",
"self",
".",
"variantsMenu",
"=",
"VariantsMenu",
"(",
"self",
")",
"action",
"=",
"QtGui",
".",
"QAction",
"(",
"\"Variants\"",
",",
"self",
")",
"action",
".",
"triggered",
".",
"connect",
"(",
"self",
".",
"__showVariantsMenu",
")",
"self",
".",
"__variantButton",
"=",
"ToolbarButton",
"(",
"\"Variants\"",
",",
"self",
",",
"IconManager",
".",
"GetPixmap",
"(",
"'Icons/plug24.png'",
")",
",",
"None",
",",
"None",
",",
"None",
",",
"False",
",",
"False",
",",
"None",
",",
"None",
",",
"None",
",",
"None",
",",
"action",
")",
"layout",
".",
"addWidget",
"(",
"self",
".",
"__variantButton",
")",
"self",
".",
"__registerEventsHandler",
"(",
")"
] | https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/katana/WalterIn/walterVariantsMenu.py#L99-L113 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | media/webrtc/trunk/tools/gyp/pylib/gyp/generator/scons.py | python | GenerateSConscript | (output_filename, spec, build_file, build_file_data) | Generates a SConscript file for a specific target.
This generates a SConscript file suitable for building any or all of
the target's configurations.
A SConscript file may be called multiple times to generate targets for
multiple configurations. Consequently, it needs to be ready to build
the target for any requested configuration, and therefore contains
information about the settings for all configurations (generated into
the SConscript file at gyp configuration time) as well as logic for
selecting (at SCons build time) the specific configuration being built.
The general outline of a generated SConscript file is:
-- Header
-- Import 'env'. This contains a $CONFIG_NAME construction
variable that specifies what configuration to build
(e.g. Debug, Release).
-- Configurations. This is a dictionary with settings for
the different configurations (Debug, Release) under which this
target can be built. The values in the dictionary are themselves
dictionaries specifying what construction variables should added
to the local copy of the imported construction environment
(Append), should be removed (FilterOut), and should outright
replace the imported values (Replace).
-- Clone the imported construction environment and update
with the proper configuration settings.
-- Initialize the lists of the targets' input files and prerequisites.
-- Target-specific actions and rules. These come after the
input file and prerequisite initializations because the
outputs of the actions and rules may affect the input file
list (process_outputs_as_sources) and get added to the list of
prerequisites (so that they're guaranteed to be executed before
building the target).
-- Call the Builder for the target itself.
-- Arrange for any copies to be made into installation directories.
-- Set up the {name} Alias (phony Node) for the target as the
primary handle for building all of the target's pieces.
-- Use env.Require() to make sure the prerequisites (explicitly
specified, but also including the actions and rules) are built
before the target itself.
-- Return the {name} Alias to the calling SConstruct file
so it can be added to the list of default targets. | Generates a SConscript file for a specific target. | [
"Generates",
"a",
"SConscript",
"file",
"for",
"a",
"specific",
"target",
"."
] | def GenerateSConscript(output_filename, spec, build_file, build_file_data):
"""
Generates a SConscript file for a specific target.
This generates a SConscript file suitable for building any or all of
the target's configurations.
A SConscript file may be called multiple times to generate targets for
multiple configurations. Consequently, it needs to be ready to build
the target for any requested configuration, and therefore contains
information about the settings for all configurations (generated into
the SConscript file at gyp configuration time) as well as logic for
selecting (at SCons build time) the specific configuration being built.
The general outline of a generated SConscript file is:
-- Header
-- Import 'env'. This contains a $CONFIG_NAME construction
variable that specifies what configuration to build
(e.g. Debug, Release).
-- Configurations. This is a dictionary with settings for
the different configurations (Debug, Release) under which this
target can be built. The values in the dictionary are themselves
dictionaries specifying what construction variables should added
to the local copy of the imported construction environment
(Append), should be removed (FilterOut), and should outright
replace the imported values (Replace).
-- Clone the imported construction environment and update
with the proper configuration settings.
-- Initialize the lists of the targets' input files and prerequisites.
-- Target-specific actions and rules. These come after the
input file and prerequisite initializations because the
outputs of the actions and rules may affect the input file
list (process_outputs_as_sources) and get added to the list of
prerequisites (so that they're guaranteed to be executed before
building the target).
-- Call the Builder for the target itself.
-- Arrange for any copies to be made into installation directories.
-- Set up the {name} Alias (phony Node) for the target as the
primary handle for building all of the target's pieces.
-- Use env.Require() to make sure the prerequisites (explicitly
specified, but also including the actions and rules) are built
before the target itself.
-- Return the {name} Alias to the calling SConstruct file
so it can be added to the list of default targets.
"""
scons_target = SCons.Target(spec)
gyp_dir = os.path.dirname(output_filename)
if not gyp_dir:
gyp_dir = '.'
gyp_dir = os.path.abspath(gyp_dir)
output_dir = os.path.dirname(output_filename)
src_dir = build_file_data['_DEPTH']
src_dir_rel = gyp.common.RelativePath(src_dir, output_dir)
subdir = gyp.common.RelativePath(os.path.dirname(build_file), src_dir)
src_subdir = '$SRC_DIR/' + subdir
src_subdir_ = src_subdir + '/'
component_name = os.path.splitext(os.path.basename(build_file))[0]
target_name = spec['target_name']
if not os.path.exists(gyp_dir):
os.makedirs(gyp_dir)
fp = open(output_filename, 'w')
fp.write(header)
fp.write('\nimport os\n')
fp.write('\nImport("env")\n')
#
fp.write('\n')
fp.write('env = env.Clone(COMPONENT_NAME=%s,\n' % repr(component_name))
fp.write(' TARGET_NAME=%s)\n' % repr(target_name))
#
for config in spec['configurations'].itervalues():
if config.get('scons_line_length'):
fp.write(_spawn_hack)
break
#
indent = ' ' * 12
fp.write('\n')
fp.write('configurations = {\n')
for config_name, config in spec['configurations'].iteritems():
fp.write(' \'%s\' : {\n' % config_name)
fp.write(' \'Append\' : dict(\n')
GenerateConfig(fp, config, indent, src_subdir)
libraries = spec.get('libraries')
if libraries:
WriteList(fp,
map(repr, libraries),
prefix=indent,
preamble='%sLIBS = [\n ' % indent,
postamble='\n%s],\n' % indent)
fp.write(' ),\n')
fp.write(' \'FilterOut\' : dict(\n' )
for key, var in config.get('scons_remove', {}).iteritems():
fp.write(' %s = %s,\n' % (key, repr(var)))
fp.write(' ),\n')
fp.write(' \'Replace\' : dict(\n' )
scons_settings = config.get('scons_variable_settings', {})
for key in sorted(scons_settings.keys()):
val = pprint.pformat(scons_settings[key])
fp.write(' %s = %s,\n' % (key, val))
if 'c++' in spec.get('link_languages', []):
fp.write(' %s = %s,\n' % ('LINK', repr('$CXX')))
if config.get('scons_line_length'):
fp.write(' SPAWN = gyp_spawn,\n')
fp.write(' ),\n')
fp.write(' \'ImportExternal\' : [\n' )
for var in config.get('scons_import_variables', []):
fp.write(' %s,\n' % repr(var))
fp.write(' ],\n')
fp.write(' \'PropagateExternal\' : [\n' )
for var in config.get('scons_propagate_variables', []):
fp.write(' %s,\n' % repr(var))
fp.write(' ],\n')
fp.write(' },\n')
fp.write('}\n')
fp.write('\n'
'config = configurations[env[\'CONFIG_NAME\']]\n'
'env.Append(**config[\'Append\'])\n'
'env.FilterOut(**config[\'FilterOut\'])\n'
'env.Replace(**config[\'Replace\'])\n')
fp.write('\n'
'# Scons forces -fPIC for SHCCFLAGS on some platforms.\n'
'# Disable that so we can control it from cflags in gyp.\n'
'# Note that Scons itself is inconsistent with its -fPIC\n'
'# setting. SHCCFLAGS forces -fPIC, and SHCFLAGS does not.\n'
'# This will make SHCCFLAGS consistent with SHCFLAGS.\n'
'env[\'SHCCFLAGS\'] = [\'$CCFLAGS\']\n')
fp.write('\n'
'for _var in config[\'ImportExternal\']:\n'
' if _var in ARGUMENTS:\n'
' env[_var] = ARGUMENTS[_var]\n'
' elif _var in os.environ:\n'
' env[_var] = os.environ[_var]\n'
'for _var in config[\'PropagateExternal\']:\n'
' if _var in ARGUMENTS:\n'
' env[_var] = ARGUMENTS[_var]\n'
' elif _var in os.environ:\n'
' env[\'ENV\'][_var] = os.environ[_var]\n')
fp.write('\n'
"env['ENV']['LD_LIBRARY_PATH'] = env.subst('$LIB_DIR')\n")
#
#fp.write("\nif env.has_key('CPPPATH'):\n")
#fp.write(" env['CPPPATH'] = map(env.Dir, env['CPPPATH'])\n")
variants = spec.get('variants', {})
for setting in sorted(variants.keys()):
if_fmt = 'if ARGUMENTS.get(%s) not in (None, \'0\'):\n'
fp.write('\n')
fp.write(if_fmt % repr(setting.upper()))
fp.write(' env.AppendUnique(\n')
GenerateConfig(fp, variants[setting], indent, src_subdir)
fp.write(' )\n')
#
scons_target.write_input_files(fp)
fp.write('\n')
fp.write('target_files = []\n')
prerequisites = spec.get('scons_prerequisites', [])
fp.write('prerequisites = %s\n' % pprint.pformat(prerequisites))
actions = spec.get('actions', [])
for action in actions:
a = ['cd', src_subdir, '&&'] + action['action']
message = action.get('message')
if message:
message = repr(message)
inputs = [FixPath(f, src_subdir_) for f in action.get('inputs', [])]
outputs = [FixPath(f, src_subdir_) for f in action.get('outputs', [])]
if outputs:
template = _command_template
else:
template = _alias_template
fp.write(template % {
'inputs' : pprint.pformat(inputs),
'outputs' : pprint.pformat(outputs),
'action' : pprint.pformat(a),
'message' : message,
'target_name': target_name,
})
if int(action.get('process_outputs_as_sources', 0)):
fp.write('input_files.extend(_outputs)\n')
fp.write('prerequisites.extend(_outputs)\n')
fp.write('target_files.extend(_outputs)\n')
rules = spec.get('rules', [])
for rule in rules:
name = re.sub('[^a-zA-Z0-9_]', '_', rule['rule_name'])
message = rule.get('message')
if message:
message = repr(message)
if int(rule.get('process_outputs_as_sources', 0)):
poas_line = '_processed_input_files.extend(_generated)'
else:
poas_line = '_processed_input_files.append(infile)'
inputs = [FixPath(f, src_subdir_) for f in rule.get('inputs', [])]
outputs = [FixPath(f, src_subdir_) for f in rule.get('outputs', [])]
# Skip a rule with no action and no inputs.
if 'action' not in rule and not rule.get('rule_sources', []):
continue
a = ['cd', src_subdir, '&&'] + rule['action']
fp.write(_rule_template % {
'inputs' : pprint.pformat(inputs),
'outputs' : pprint.pformat(outputs),
'action' : pprint.pformat(a),
'extension' : rule['extension'],
'name' : name,
'message' : message,
'process_outputs_as_sources_line' : poas_line,
'src_dir' : src_subdir_,
})
scons_target.write_target(fp, src_subdir)
copies = spec.get('copies', [])
if copies:
fp.write(_copy_action_template)
for copy in copies:
destdir = None
files = None
try:
destdir = copy['destination']
except KeyError, e:
gyp.common.ExceptionAppend(
e,
"Required 'destination' key missing for 'copies' in %s." % build_file)
raise
try:
files = copy['files']
except KeyError, e:
gyp.common.ExceptionAppend(
e, "Required 'files' key missing for 'copies' in %s." % build_file)
raise
if not files:
# TODO: should probably add a (suppressible) warning;
# a null file list may be unintentional.
continue
if not destdir:
raise Exception(
"Required 'destination' key is empty for 'copies' in %s." % build_file)
fmt = ('\n'
'_outputs = env.Command(%s,\n'
' %s,\n'
' GYPCopy(\'$TARGET\', \'$SOURCE\'))\n')
for f in copy['files']:
# Remove trailing separators so basename() acts like Unix basename and
# always returns the last element, whether a file or dir. Without this,
# only the contents, not the directory itself, are copied (and nothing
# might be copied if dest already exists, since scons thinks nothing needs
# to be done).
dest = os.path.join(destdir, os.path.basename(f.rstrip(os.sep)))
f = FixPath(f, src_subdir_)
dest = FixPath(dest, src_subdir_)
fp.write(fmt % (repr(dest), repr(f)))
fp.write('target_files.extend(_outputs)\n')
run_as = spec.get('run_as')
if run_as:
action = run_as.get('action', [])
working_directory = run_as.get('working_directory')
if not working_directory:
working_directory = gyp_dir
else:
if not os.path.isabs(working_directory):
working_directory = os.path.normpath(os.path.join(gyp_dir,
working_directory))
if run_as.get('environment'):
for (key, val) in run_as.get('environment').iteritems():
action = ['%s="%s"' % (key, val)] + action
action = ['cd', '"%s"' % working_directory, '&&'] + action
fp.write(_run_as_template % {
'action' : pprint.pformat(action),
'message' : run_as.get('message', ''),
})
fmt = "\ngyp_target = env.Alias('%s', target_files)\n"
fp.write(fmt % target_name)
dependencies = spec.get('scons_dependencies', [])
if dependencies:
WriteList(fp, dependencies, preamble='dependencies = [\n ',
postamble='\n]\n')
fp.write('env.Requires(target_files, dependencies)\n')
fp.write('env.Requires(gyp_target, dependencies)\n')
fp.write('for prerequisite in prerequisites:\n')
fp.write(' env.Requires(prerequisite, dependencies)\n')
fp.write('env.Requires(gyp_target, prerequisites)\n')
if run_as:
fp.write(_run_as_template_suffix % {
'target_name': target_name,
})
fp.write('Return("gyp_target")\n')
fp.close() | [
"def",
"GenerateSConscript",
"(",
"output_filename",
",",
"spec",
",",
"build_file",
",",
"build_file_data",
")",
":",
"scons_target",
"=",
"SCons",
".",
"Target",
"(",
"spec",
")",
"gyp_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"output_filename",
")",
"if",
"not",
"gyp_dir",
":",
"gyp_dir",
"=",
"'.'",
"gyp_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"gyp_dir",
")",
"output_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"output_filename",
")",
"src_dir",
"=",
"build_file_data",
"[",
"'_DEPTH'",
"]",
"src_dir_rel",
"=",
"gyp",
".",
"common",
".",
"RelativePath",
"(",
"src_dir",
",",
"output_dir",
")",
"subdir",
"=",
"gyp",
".",
"common",
".",
"RelativePath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"build_file",
")",
",",
"src_dir",
")",
"src_subdir",
"=",
"'$SRC_DIR/'",
"+",
"subdir",
"src_subdir_",
"=",
"src_subdir",
"+",
"'/'",
"component_name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"build_file",
")",
")",
"[",
"0",
"]",
"target_name",
"=",
"spec",
"[",
"'target_name'",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"gyp_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"gyp_dir",
")",
"fp",
"=",
"open",
"(",
"output_filename",
",",
"'w'",
")",
"fp",
".",
"write",
"(",
"header",
")",
"fp",
".",
"write",
"(",
"'\\nimport os\\n'",
")",
"fp",
".",
"write",
"(",
"'\\nImport(\"env\")\\n'",
")",
"#",
"fp",
".",
"write",
"(",
"'\\n'",
")",
"fp",
".",
"write",
"(",
"'env = env.Clone(COMPONENT_NAME=%s,\\n'",
"%",
"repr",
"(",
"component_name",
")",
")",
"fp",
".",
"write",
"(",
"' TARGET_NAME=%s)\\n'",
"%",
"repr",
"(",
"target_name",
")",
")",
"#",
"for",
"config",
"in",
"spec",
"[",
"'configurations'",
"]",
".",
"itervalues",
"(",
")",
":",
"if",
"config",
".",
"get",
"(",
"'scons_line_length'",
")",
":",
"fp",
".",
"write",
"(",
"_spawn_hack",
")",
"break",
"#",
"indent",
"=",
"' '",
"*",
"12",
"fp",
".",
"write",
"(",
"'\\n'",
")",
"fp",
".",
"write",
"(",
"'configurations = {\\n'",
")",
"for",
"config_name",
",",
"config",
"in",
"spec",
"[",
"'configurations'",
"]",
".",
"iteritems",
"(",
")",
":",
"fp",
".",
"write",
"(",
"' \\'%s\\' : {\\n'",
"%",
"config_name",
")",
"fp",
".",
"write",
"(",
"' \\'Append\\' : dict(\\n'",
")",
"GenerateConfig",
"(",
"fp",
",",
"config",
",",
"indent",
",",
"src_subdir",
")",
"libraries",
"=",
"spec",
".",
"get",
"(",
"'libraries'",
")",
"if",
"libraries",
":",
"WriteList",
"(",
"fp",
",",
"map",
"(",
"repr",
",",
"libraries",
")",
",",
"prefix",
"=",
"indent",
",",
"preamble",
"=",
"'%sLIBS = [\\n '",
"%",
"indent",
",",
"postamble",
"=",
"'\\n%s],\\n'",
"%",
"indent",
")",
"fp",
".",
"write",
"(",
"' ),\\n'",
")",
"fp",
".",
"write",
"(",
"' \\'FilterOut\\' : dict(\\n'",
")",
"for",
"key",
",",
"var",
"in",
"config",
".",
"get",
"(",
"'scons_remove'",
",",
"{",
"}",
")",
".",
"iteritems",
"(",
")",
":",
"fp",
".",
"write",
"(",
"' %s = %s,\\n'",
"%",
"(",
"key",
",",
"repr",
"(",
"var",
")",
")",
")",
"fp",
".",
"write",
"(",
"' ),\\n'",
")",
"fp",
".",
"write",
"(",
"' \\'Replace\\' : dict(\\n'",
")",
"scons_settings",
"=",
"config",
".",
"get",
"(",
"'scons_variable_settings'",
",",
"{",
"}",
")",
"for",
"key",
"in",
"sorted",
"(",
"scons_settings",
".",
"keys",
"(",
")",
")",
":",
"val",
"=",
"pprint",
".",
"pformat",
"(",
"scons_settings",
"[",
"key",
"]",
")",
"fp",
".",
"write",
"(",
"' %s = %s,\\n'",
"%",
"(",
"key",
",",
"val",
")",
")",
"if",
"'c++'",
"in",
"spec",
".",
"get",
"(",
"'link_languages'",
",",
"[",
"]",
")",
":",
"fp",
".",
"write",
"(",
"' %s = %s,\\n'",
"%",
"(",
"'LINK'",
",",
"repr",
"(",
"'$CXX'",
")",
")",
")",
"if",
"config",
".",
"get",
"(",
"'scons_line_length'",
")",
":",
"fp",
".",
"write",
"(",
"' SPAWN = gyp_spawn,\\n'",
")",
"fp",
".",
"write",
"(",
"' ),\\n'",
")",
"fp",
".",
"write",
"(",
"' \\'ImportExternal\\' : [\\n'",
")",
"for",
"var",
"in",
"config",
".",
"get",
"(",
"'scons_import_variables'",
",",
"[",
"]",
")",
":",
"fp",
".",
"write",
"(",
"' %s,\\n'",
"%",
"repr",
"(",
"var",
")",
")",
"fp",
".",
"write",
"(",
"' ],\\n'",
")",
"fp",
".",
"write",
"(",
"' \\'PropagateExternal\\' : [\\n'",
")",
"for",
"var",
"in",
"config",
".",
"get",
"(",
"'scons_propagate_variables'",
",",
"[",
"]",
")",
":",
"fp",
".",
"write",
"(",
"' %s,\\n'",
"%",
"repr",
"(",
"var",
")",
")",
"fp",
".",
"write",
"(",
"' ],\\n'",
")",
"fp",
".",
"write",
"(",
"' },\\n'",
")",
"fp",
".",
"write",
"(",
"'}\\n'",
")",
"fp",
".",
"write",
"(",
"'\\n'",
"'config = configurations[env[\\'CONFIG_NAME\\']]\\n'",
"'env.Append(**config[\\'Append\\'])\\n'",
"'env.FilterOut(**config[\\'FilterOut\\'])\\n'",
"'env.Replace(**config[\\'Replace\\'])\\n'",
")",
"fp",
".",
"write",
"(",
"'\\n'",
"'# Scons forces -fPIC for SHCCFLAGS on some platforms.\\n'",
"'# Disable that so we can control it from cflags in gyp.\\n'",
"'# Note that Scons itself is inconsistent with its -fPIC\\n'",
"'# setting. SHCCFLAGS forces -fPIC, and SHCFLAGS does not.\\n'",
"'# This will make SHCCFLAGS consistent with SHCFLAGS.\\n'",
"'env[\\'SHCCFLAGS\\'] = [\\'$CCFLAGS\\']\\n'",
")",
"fp",
".",
"write",
"(",
"'\\n'",
"'for _var in config[\\'ImportExternal\\']:\\n'",
"' if _var in ARGUMENTS:\\n'",
"' env[_var] = ARGUMENTS[_var]\\n'",
"' elif _var in os.environ:\\n'",
"' env[_var] = os.environ[_var]\\n'",
"'for _var in config[\\'PropagateExternal\\']:\\n'",
"' if _var in ARGUMENTS:\\n'",
"' env[_var] = ARGUMENTS[_var]\\n'",
"' elif _var in os.environ:\\n'",
"' env[\\'ENV\\'][_var] = os.environ[_var]\\n'",
")",
"fp",
".",
"write",
"(",
"'\\n'",
"\"env['ENV']['LD_LIBRARY_PATH'] = env.subst('$LIB_DIR')\\n\"",
")",
"#",
"#fp.write(\"\\nif env.has_key('CPPPATH'):\\n\")",
"#fp.write(\" env['CPPPATH'] = map(env.Dir, env['CPPPATH'])\\n\")",
"variants",
"=",
"spec",
".",
"get",
"(",
"'variants'",
",",
"{",
"}",
")",
"for",
"setting",
"in",
"sorted",
"(",
"variants",
".",
"keys",
"(",
")",
")",
":",
"if_fmt",
"=",
"'if ARGUMENTS.get(%s) not in (None, \\'0\\'):\\n'",
"fp",
".",
"write",
"(",
"'\\n'",
")",
"fp",
".",
"write",
"(",
"if_fmt",
"%",
"repr",
"(",
"setting",
".",
"upper",
"(",
")",
")",
")",
"fp",
".",
"write",
"(",
"' env.AppendUnique(\\n'",
")",
"GenerateConfig",
"(",
"fp",
",",
"variants",
"[",
"setting",
"]",
",",
"indent",
",",
"src_subdir",
")",
"fp",
".",
"write",
"(",
"' )\\n'",
")",
"#",
"scons_target",
".",
"write_input_files",
"(",
"fp",
")",
"fp",
".",
"write",
"(",
"'\\n'",
")",
"fp",
".",
"write",
"(",
"'target_files = []\\n'",
")",
"prerequisites",
"=",
"spec",
".",
"get",
"(",
"'scons_prerequisites'",
",",
"[",
"]",
")",
"fp",
".",
"write",
"(",
"'prerequisites = %s\\n'",
"%",
"pprint",
".",
"pformat",
"(",
"prerequisites",
")",
")",
"actions",
"=",
"spec",
".",
"get",
"(",
"'actions'",
",",
"[",
"]",
")",
"for",
"action",
"in",
"actions",
":",
"a",
"=",
"[",
"'cd'",
",",
"src_subdir",
",",
"'&&'",
"]",
"+",
"action",
"[",
"'action'",
"]",
"message",
"=",
"action",
".",
"get",
"(",
"'message'",
")",
"if",
"message",
":",
"message",
"=",
"repr",
"(",
"message",
")",
"inputs",
"=",
"[",
"FixPath",
"(",
"f",
",",
"src_subdir_",
")",
"for",
"f",
"in",
"action",
".",
"get",
"(",
"'inputs'",
",",
"[",
"]",
")",
"]",
"outputs",
"=",
"[",
"FixPath",
"(",
"f",
",",
"src_subdir_",
")",
"for",
"f",
"in",
"action",
".",
"get",
"(",
"'outputs'",
",",
"[",
"]",
")",
"]",
"if",
"outputs",
":",
"template",
"=",
"_command_template",
"else",
":",
"template",
"=",
"_alias_template",
"fp",
".",
"write",
"(",
"template",
"%",
"{",
"'inputs'",
":",
"pprint",
".",
"pformat",
"(",
"inputs",
")",
",",
"'outputs'",
":",
"pprint",
".",
"pformat",
"(",
"outputs",
")",
",",
"'action'",
":",
"pprint",
".",
"pformat",
"(",
"a",
")",
",",
"'message'",
":",
"message",
",",
"'target_name'",
":",
"target_name",
",",
"}",
")",
"if",
"int",
"(",
"action",
".",
"get",
"(",
"'process_outputs_as_sources'",
",",
"0",
")",
")",
":",
"fp",
".",
"write",
"(",
"'input_files.extend(_outputs)\\n'",
")",
"fp",
".",
"write",
"(",
"'prerequisites.extend(_outputs)\\n'",
")",
"fp",
".",
"write",
"(",
"'target_files.extend(_outputs)\\n'",
")",
"rules",
"=",
"spec",
".",
"get",
"(",
"'rules'",
",",
"[",
"]",
")",
"for",
"rule",
"in",
"rules",
":",
"name",
"=",
"re",
".",
"sub",
"(",
"'[^a-zA-Z0-9_]'",
",",
"'_'",
",",
"rule",
"[",
"'rule_name'",
"]",
")",
"message",
"=",
"rule",
".",
"get",
"(",
"'message'",
")",
"if",
"message",
":",
"message",
"=",
"repr",
"(",
"message",
")",
"if",
"int",
"(",
"rule",
".",
"get",
"(",
"'process_outputs_as_sources'",
",",
"0",
")",
")",
":",
"poas_line",
"=",
"'_processed_input_files.extend(_generated)'",
"else",
":",
"poas_line",
"=",
"'_processed_input_files.append(infile)'",
"inputs",
"=",
"[",
"FixPath",
"(",
"f",
",",
"src_subdir_",
")",
"for",
"f",
"in",
"rule",
".",
"get",
"(",
"'inputs'",
",",
"[",
"]",
")",
"]",
"outputs",
"=",
"[",
"FixPath",
"(",
"f",
",",
"src_subdir_",
")",
"for",
"f",
"in",
"rule",
".",
"get",
"(",
"'outputs'",
",",
"[",
"]",
")",
"]",
"# Skip a rule with no action and no inputs.",
"if",
"'action'",
"not",
"in",
"rule",
"and",
"not",
"rule",
".",
"get",
"(",
"'rule_sources'",
",",
"[",
"]",
")",
":",
"continue",
"a",
"=",
"[",
"'cd'",
",",
"src_subdir",
",",
"'&&'",
"]",
"+",
"rule",
"[",
"'action'",
"]",
"fp",
".",
"write",
"(",
"_rule_template",
"%",
"{",
"'inputs'",
":",
"pprint",
".",
"pformat",
"(",
"inputs",
")",
",",
"'outputs'",
":",
"pprint",
".",
"pformat",
"(",
"outputs",
")",
",",
"'action'",
":",
"pprint",
".",
"pformat",
"(",
"a",
")",
",",
"'extension'",
":",
"rule",
"[",
"'extension'",
"]",
",",
"'name'",
":",
"name",
",",
"'message'",
":",
"message",
",",
"'process_outputs_as_sources_line'",
":",
"poas_line",
",",
"'src_dir'",
":",
"src_subdir_",
",",
"}",
")",
"scons_target",
".",
"write_target",
"(",
"fp",
",",
"src_subdir",
")",
"copies",
"=",
"spec",
".",
"get",
"(",
"'copies'",
",",
"[",
"]",
")",
"if",
"copies",
":",
"fp",
".",
"write",
"(",
"_copy_action_template",
")",
"for",
"copy",
"in",
"copies",
":",
"destdir",
"=",
"None",
"files",
"=",
"None",
"try",
":",
"destdir",
"=",
"copy",
"[",
"'destination'",
"]",
"except",
"KeyError",
",",
"e",
":",
"gyp",
".",
"common",
".",
"ExceptionAppend",
"(",
"e",
",",
"\"Required 'destination' key missing for 'copies' in %s.\"",
"%",
"build_file",
")",
"raise",
"try",
":",
"files",
"=",
"copy",
"[",
"'files'",
"]",
"except",
"KeyError",
",",
"e",
":",
"gyp",
".",
"common",
".",
"ExceptionAppend",
"(",
"e",
",",
"\"Required 'files' key missing for 'copies' in %s.\"",
"%",
"build_file",
")",
"raise",
"if",
"not",
"files",
":",
"# TODO: should probably add a (suppressible) warning;",
"# a null file list may be unintentional.",
"continue",
"if",
"not",
"destdir",
":",
"raise",
"Exception",
"(",
"\"Required 'destination' key is empty for 'copies' in %s.\"",
"%",
"build_file",
")",
"fmt",
"=",
"(",
"'\\n'",
"'_outputs = env.Command(%s,\\n'",
"' %s,\\n'",
"' GYPCopy(\\'$TARGET\\', \\'$SOURCE\\'))\\n'",
")",
"for",
"f",
"in",
"copy",
"[",
"'files'",
"]",
":",
"# Remove trailing separators so basename() acts like Unix basename and",
"# always returns the last element, whether a file or dir. Without this,",
"# only the contents, not the directory itself, are copied (and nothing",
"# might be copied if dest already exists, since scons thinks nothing needs",
"# to be done).",
"dest",
"=",
"os",
".",
"path",
".",
"join",
"(",
"destdir",
",",
"os",
".",
"path",
".",
"basename",
"(",
"f",
".",
"rstrip",
"(",
"os",
".",
"sep",
")",
")",
")",
"f",
"=",
"FixPath",
"(",
"f",
",",
"src_subdir_",
")",
"dest",
"=",
"FixPath",
"(",
"dest",
",",
"src_subdir_",
")",
"fp",
".",
"write",
"(",
"fmt",
"%",
"(",
"repr",
"(",
"dest",
")",
",",
"repr",
"(",
"f",
")",
")",
")",
"fp",
".",
"write",
"(",
"'target_files.extend(_outputs)\\n'",
")",
"run_as",
"=",
"spec",
".",
"get",
"(",
"'run_as'",
")",
"if",
"run_as",
":",
"action",
"=",
"run_as",
".",
"get",
"(",
"'action'",
",",
"[",
"]",
")",
"working_directory",
"=",
"run_as",
".",
"get",
"(",
"'working_directory'",
")",
"if",
"not",
"working_directory",
":",
"working_directory",
"=",
"gyp_dir",
"else",
":",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"working_directory",
")",
":",
"working_directory",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"gyp_dir",
",",
"working_directory",
")",
")",
"if",
"run_as",
".",
"get",
"(",
"'environment'",
")",
":",
"for",
"(",
"key",
",",
"val",
")",
"in",
"run_as",
".",
"get",
"(",
"'environment'",
")",
".",
"iteritems",
"(",
")",
":",
"action",
"=",
"[",
"'%s=\"%s\"'",
"%",
"(",
"key",
",",
"val",
")",
"]",
"+",
"action",
"action",
"=",
"[",
"'cd'",
",",
"'\"%s\"'",
"%",
"working_directory",
",",
"'&&'",
"]",
"+",
"action",
"fp",
".",
"write",
"(",
"_run_as_template",
"%",
"{",
"'action'",
":",
"pprint",
".",
"pformat",
"(",
"action",
")",
",",
"'message'",
":",
"run_as",
".",
"get",
"(",
"'message'",
",",
"''",
")",
",",
"}",
")",
"fmt",
"=",
"\"\\ngyp_target = env.Alias('%s', target_files)\\n\"",
"fp",
".",
"write",
"(",
"fmt",
"%",
"target_name",
")",
"dependencies",
"=",
"spec",
".",
"get",
"(",
"'scons_dependencies'",
",",
"[",
"]",
")",
"if",
"dependencies",
":",
"WriteList",
"(",
"fp",
",",
"dependencies",
",",
"preamble",
"=",
"'dependencies = [\\n '",
",",
"postamble",
"=",
"'\\n]\\n'",
")",
"fp",
".",
"write",
"(",
"'env.Requires(target_files, dependencies)\\n'",
")",
"fp",
".",
"write",
"(",
"'env.Requires(gyp_target, dependencies)\\n'",
")",
"fp",
".",
"write",
"(",
"'for prerequisite in prerequisites:\\n'",
")",
"fp",
".",
"write",
"(",
"' env.Requires(prerequisite, dependencies)\\n'",
")",
"fp",
".",
"write",
"(",
"'env.Requires(gyp_target, prerequisites)\\n'",
")",
"if",
"run_as",
":",
"fp",
".",
"write",
"(",
"_run_as_template_suffix",
"%",
"{",
"'target_name'",
":",
"target_name",
",",
"}",
")",
"fp",
".",
"write",
"(",
"'Return(\"gyp_target\")\\n'",
")",
"fp",
".",
"close",
"(",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/scons.py#L251-L575 | ||
facebook/fbthrift | fb9c8562aba04c4fd9b17716eb5d970cc88a75bb | thrift/lib/py/util/randomizer.py | python | BaseRandomizer.flatten_constraints | (self, constraints) | return flattened | Return a single constraint dictionary by combining default
constraints with overriding constraints. | Return a single constraint dictionary by combining default
constraints with overriding constraints. | [
"Return",
"a",
"single",
"constraint",
"dictionary",
"by",
"combining",
"default",
"constraints",
"with",
"overriding",
"constraints",
"."
] | def flatten_constraints(self, constraints):
"""Return a single constraint dictionary by combining default
constraints with overriding constraints."""
cls = self.__class__
flattened = {}
deep_dict_update(flattened, cls.default_constraints)
# Put the default constraints of the whole stack
deep_dict_update(flattened, self.state.default_constraints)
type_name = self.type_name
for type_constraints in self.state.type_constraint_stacks[type_name]:
deep_dict_update(flattened, type_constraints)
deep_dict_update(flattened, constraints)
return flattened | [
"def",
"flatten_constraints",
"(",
"self",
",",
"constraints",
")",
":",
"cls",
"=",
"self",
".",
"__class__",
"flattened",
"=",
"{",
"}",
"deep_dict_update",
"(",
"flattened",
",",
"cls",
".",
"default_constraints",
")",
"# Put the default constraints of the whole stack",
"deep_dict_update",
"(",
"flattened",
",",
"self",
".",
"state",
".",
"default_constraints",
")",
"type_name",
"=",
"self",
".",
"type_name",
"for",
"type_constraints",
"in",
"self",
".",
"state",
".",
"type_constraint_stacks",
"[",
"type_name",
"]",
":",
"deep_dict_update",
"(",
"flattened",
",",
"type_constraints",
")",
"deep_dict_update",
"(",
"flattened",
",",
"constraints",
")",
"return",
"flattened"
] | https://github.com/facebook/fbthrift/blob/fb9c8562aba04c4fd9b17716eb5d970cc88a75bb/thrift/lib/py/util/randomizer.py#L126-L143 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/nn_ops.py | python | _calc_dilation2d_flops | (graph, node) | return ops.OpStats("flops", (output_count * filter_height * filter_width * 2)) | Calculates the compute resources needed for Dilation2D. | Calculates the compute resources needed for Dilation2D. | [
"Calculates",
"the",
"compute",
"resources",
"needed",
"for",
"Dilation2D",
"."
] | def _calc_dilation2d_flops(graph, node):
"""Calculates the compute resources needed for Dilation2D."""
input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0])
input_shape.assert_is_fully_defined()
filter_shape = graph_util.tensor_shape_from_node_def_name(graph,
node.input[1])
filter_shape.assert_is_fully_defined()
output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name)
output_shape.assert_is_fully_defined()
filter_height = int(filter_shape[0])
filter_width = int(filter_shape[1])
output_count = np.prod(output_shape.as_list())
return ops.OpStats("flops", (output_count * filter_height * filter_width * 2)) | [
"def",
"_calc_dilation2d_flops",
"(",
"graph",
",",
"node",
")",
":",
"input_shape",
"=",
"graph_util",
".",
"tensor_shape_from_node_def_name",
"(",
"graph",
",",
"node",
".",
"input",
"[",
"0",
"]",
")",
"input_shape",
".",
"assert_is_fully_defined",
"(",
")",
"filter_shape",
"=",
"graph_util",
".",
"tensor_shape_from_node_def_name",
"(",
"graph",
",",
"node",
".",
"input",
"[",
"1",
"]",
")",
"filter_shape",
".",
"assert_is_fully_defined",
"(",
")",
"output_shape",
"=",
"graph_util",
".",
"tensor_shape_from_node_def_name",
"(",
"graph",
",",
"node",
".",
"name",
")",
"output_shape",
".",
"assert_is_fully_defined",
"(",
")",
"filter_height",
"=",
"int",
"(",
"filter_shape",
"[",
"0",
"]",
")",
"filter_width",
"=",
"int",
"(",
"filter_shape",
"[",
"1",
"]",
")",
"output_count",
"=",
"np",
".",
"prod",
"(",
"output_shape",
".",
"as_list",
"(",
")",
")",
"return",
"ops",
".",
"OpStats",
"(",
"\"flops\"",
",",
"(",
"output_count",
"*",
"filter_height",
"*",
"filter_width",
"*",
"2",
")",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/nn_ops.py#L1261-L1273 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | .github/github_org_control/github_api.py | python | GithubOrgApi.remove_users | (self, users) | Removes users from GitHub organization | Removes users from GitHub organization | [
"Removes",
"users",
"from",
"GitHub",
"organization"
] | def remove_users(self, users):
"""Removes users from GitHub organization"""
if not isinstance(users, typing.Iterable):
users = [users]
print(f"\nRemove {len(users)} users:")
dry_run = self._cfg.DRY_RUN
if not dry_run and len(users) > self._cfg.MAX_MEMBERS_TO_REMOVE:
print(
"WARNING: Review is required for removing members more than "
f"{self._cfg.MAX_MEMBERS_TO_REMOVE}"
)
# TODO: Add notification
dry_run = True
for user in users:
member = self.get_github_user_by_email(user) if isinstance(user, str) else user
print(f'{member.login} - "{member.name}" - {member.email} - ', end="")
try:
if is_user_ignored(member):
print("Ignored")
continue
if dry_run:
print("Dry run")
continue
self.github_org.remove_from_membership(member)
print("OK")
except GithubException as exc:
print(f'FAIL: {exc.data["errors"][0]["message"]}') | [
"def",
"remove_users",
"(",
"self",
",",
"users",
")",
":",
"if",
"not",
"isinstance",
"(",
"users",
",",
"typing",
".",
"Iterable",
")",
":",
"users",
"=",
"[",
"users",
"]",
"print",
"(",
"f\"\\nRemove {len(users)} users:\"",
")",
"dry_run",
"=",
"self",
".",
"_cfg",
".",
"DRY_RUN",
"if",
"not",
"dry_run",
"and",
"len",
"(",
"users",
")",
">",
"self",
".",
"_cfg",
".",
"MAX_MEMBERS_TO_REMOVE",
":",
"print",
"(",
"\"WARNING: Review is required for removing members more than \"",
"f\"{self._cfg.MAX_MEMBERS_TO_REMOVE}\"",
")",
"# TODO: Add notification",
"dry_run",
"=",
"True",
"for",
"user",
"in",
"users",
":",
"member",
"=",
"self",
".",
"get_github_user_by_email",
"(",
"user",
")",
"if",
"isinstance",
"(",
"user",
",",
"str",
")",
"else",
"user",
"print",
"(",
"f'{member.login} - \"{member.name}\" - {member.email} - '",
",",
"end",
"=",
"\"\"",
")",
"try",
":",
"if",
"is_user_ignored",
"(",
"member",
")",
":",
"print",
"(",
"\"Ignored\"",
")",
"continue",
"if",
"dry_run",
":",
"print",
"(",
"\"Dry run\"",
")",
"continue",
"self",
".",
"github_org",
".",
"remove_from_membership",
"(",
"member",
")",
"print",
"(",
"\"OK\"",
")",
"except",
"GithubException",
"as",
"exc",
":",
"print",
"(",
"f'FAIL: {exc.data[\"errors\"][0][\"message\"]}'",
")"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/.github/github_org_control/github_api.py#L342-L370 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/string_ops.py | python | _StringJoinShape | (op) | return [base_shape] | Shape function for the StringJoin op. | Shape function for the StringJoin op. | [
"Shape",
"function",
"for",
"the",
"StringJoin",
"op",
"."
] | def _StringJoinShape(op):
"""Shape function for the StringJoin op."""
input_shapes = [x.get_shape() for x in op.inputs]
# First check if all inputs are scalars. In the next section
# we may have *some* scalars and we will be broadcasting them
if all([s.ndims == 0 for s in input_shapes]):
return [tensor_shape.scalar()]
base_shape = tensor_shape.unknown_shape()
for shape in input_shapes:
if shape.ndims != 0:
base_shape = base_shape.merge_with(shape)
return [base_shape] | [
"def",
"_StringJoinShape",
"(",
"op",
")",
":",
"input_shapes",
"=",
"[",
"x",
".",
"get_shape",
"(",
")",
"for",
"x",
"in",
"op",
".",
"inputs",
"]",
"# First check if all inputs are scalars. In the next section",
"# we may have *some* scalars and we will be broadcasting them",
"if",
"all",
"(",
"[",
"s",
".",
"ndims",
"==",
"0",
"for",
"s",
"in",
"input_shapes",
"]",
")",
":",
"return",
"[",
"tensor_shape",
".",
"scalar",
"(",
")",
"]",
"base_shape",
"=",
"tensor_shape",
".",
"unknown_shape",
"(",
")",
"for",
"shape",
"in",
"input_shapes",
":",
"if",
"shape",
".",
"ndims",
"!=",
"0",
":",
"base_shape",
"=",
"base_shape",
".",
"merge_with",
"(",
"shape",
")",
"return",
"[",
"base_shape",
"]"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/string_ops.py#L114-L127 | |
giuspen/cherrytree | 84712f206478fcf9acf30174009ad28c648c6344 | pygtk2/modules/core.py | python | CherryTree.nodes_add_from_html_folder | (self, action) | Add Nodes from HTML File(s) in Selected Folder | Add Nodes from HTML File(s) in Selected Folder | [
"Add",
"Nodes",
"from",
"HTML",
"File",
"(",
"s",
")",
"in",
"Selected",
"Folder"
] | def nodes_add_from_html_folder(self, action):
"""Add Nodes from HTML File(s) in Selected Folder"""
folderpath = support.dialog_folder_select(curr_folder=self.pick_dir_import, parent=self.window)
if not folderpath: return
self.pick_dir_import = os.path.dirname(folderpath)
html = imports.HTMLHandler(self)
cherrytree_string = html.get_cherrytree_xml(folderpath=folderpath)
self.nodes_add_from_cherrytree_data(cherrytree_string) | [
"def",
"nodes_add_from_html_folder",
"(",
"self",
",",
"action",
")",
":",
"folderpath",
"=",
"support",
".",
"dialog_folder_select",
"(",
"curr_folder",
"=",
"self",
".",
"pick_dir_import",
",",
"parent",
"=",
"self",
".",
"window",
")",
"if",
"not",
"folderpath",
":",
"return",
"self",
".",
"pick_dir_import",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"folderpath",
")",
"html",
"=",
"imports",
".",
"HTMLHandler",
"(",
"self",
")",
"cherrytree_string",
"=",
"html",
".",
"get_cherrytree_xml",
"(",
"folderpath",
"=",
"folderpath",
")",
"self",
".",
"nodes_add_from_cherrytree_data",
"(",
"cherrytree_string",
")"
] | https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/core.py#L1006-L1013 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/utils/stats.py | python | _weighted_percentile | (array, sample_weight, percentile=50) | return array[sorted_idx[percentile_idx]] | Compute the weighted ``percentile`` of ``array`` with ``sample_weight``. | Compute the weighted ``percentile`` of ``array`` with ``sample_weight``. | [
"Compute",
"the",
"weighted",
"percentile",
"of",
"array",
"with",
"sample_weight",
"."
] | def _weighted_percentile(array, sample_weight, percentile=50):
"""Compute the weighted ``percentile`` of ``array`` with ``sample_weight``. """
sorted_idx = np.argsort(array)
# Find index of median prediction for each sample
weight_cdf = sample_weight[sorted_idx].cumsum()
percentile_idx = np.searchsorted(
weight_cdf, (percentile / 100.) * weight_cdf[-1])
return array[sorted_idx[percentile_idx]] | [
"def",
"_weighted_percentile",
"(",
"array",
",",
"sample_weight",
",",
"percentile",
"=",
"50",
")",
":",
"sorted_idx",
"=",
"np",
".",
"argsort",
"(",
"array",
")",
"# Find index of median prediction for each sample",
"weight_cdf",
"=",
"sample_weight",
"[",
"sorted_idx",
"]",
".",
"cumsum",
"(",
")",
"percentile_idx",
"=",
"np",
".",
"searchsorted",
"(",
"weight_cdf",
",",
"(",
"percentile",
"/",
"100.",
")",
"*",
"weight_cdf",
"[",
"-",
"1",
"]",
")",
"return",
"array",
"[",
"sorted_idx",
"[",
"percentile_idx",
"]",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/utils/stats.py#L51-L59 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/kvstore/kvstore.py | python | KVStore.pull | (self, key, out=None, priority=0, ignore_sparse=True) | Pulls a single value or a sequence of values from the store.
This function returns immediately after adding an operator to the engine.
Subsequent attempts to read from the `out` variable will be blocked until the
pull operation completes.
`pull` is executed asynchronously after all previous `pull` calls and only
the last `push` call for the same input key(s) are finished.
The returned values are guaranteed to be the latest values in the store.
pull with `RowSparseNDArray` is not supported for dist kvstore.
Please use ``row_sparse_pull`` instead.
Parameters
----------
key : str, int, or sequence of str or int
Keys.
out: NDArray or list of NDArray or list of list of NDArray
Values corresponding to the keys.
priority : int, optional
The priority of the pull operation.
Higher priority pull operations are likely to be executed before
other pull actions.
ignore_sparse: bool, optional, default True
Whether to ignore sparse arrays in the request.
Examples
--------
>>> # pull a single key-value pair
>>> shape = (2,3)
>>> a = mx.nd.zeros(shape)
>>> kv.pull('3', out=a)
>>> print a.asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]]
>>> # pull into multiple devices
>>> b = [mx.nd.ones(shape, gpu) for gpu in gpus]
>>> kv.pull('3', out=b)
>>> print b[1].asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]]
>>> # pull a list of key-value pairs.
>>> # On single device
>>> keys = ['5', '7', '9']
>>> b = [mx.nd.zeros(shape)]*len(keys)
>>> kv.pull(keys, out=b)
>>> print b[1].asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]]
>>> # On multiple devices
>>> keys = ['6', '8', '10']
>>> b = [[mx.nd.ones(shape, gpu) for gpu in gpus]] * len(keys)
>>> kv.pull(keys, out=b)
>>> print b[1][1].asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]] | Pulls a single value or a sequence of values from the store. | [
"Pulls",
"a",
"single",
"value",
"or",
"a",
"sequence",
"of",
"values",
"from",
"the",
"store",
"."
] | def pull(self, key, out=None, priority=0, ignore_sparse=True):
""" Pulls a single value or a sequence of values from the store.
This function returns immediately after adding an operator to the engine.
Subsequent attempts to read from the `out` variable will be blocked until the
pull operation completes.
`pull` is executed asynchronously after all previous `pull` calls and only
the last `push` call for the same input key(s) are finished.
The returned values are guaranteed to be the latest values in the store.
pull with `RowSparseNDArray` is not supported for dist kvstore.
Please use ``row_sparse_pull`` instead.
Parameters
----------
key : str, int, or sequence of str or int
Keys.
out: NDArray or list of NDArray or list of list of NDArray
Values corresponding to the keys.
priority : int, optional
The priority of the pull operation.
Higher priority pull operations are likely to be executed before
other pull actions.
ignore_sparse: bool, optional, default True
Whether to ignore sparse arrays in the request.
Examples
--------
>>> # pull a single key-value pair
>>> shape = (2,3)
>>> a = mx.nd.zeros(shape)
>>> kv.pull('3', out=a)
>>> print a.asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]]
>>> # pull into multiple devices
>>> b = [mx.nd.ones(shape, gpu) for gpu in gpus]
>>> kv.pull('3', out=b)
>>> print b[1].asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]]
>>> # pull a list of key-value pairs.
>>> # On single device
>>> keys = ['5', '7', '9']
>>> b = [mx.nd.zeros(shape)]*len(keys)
>>> kv.pull(keys, out=b)
>>> print b[1].asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]]
>>> # On multiple devices
>>> keys = ['6', '8', '10']
>>> b = [[mx.nd.ones(shape, gpu) for gpu in gpus]] * len(keys)
>>> kv.pull(keys, out=b)
>>> print b[1][1].asnumpy()
[[ 2. 2. 2.]
[ 2. 2. 2.]]
"""
assert(out is not None)
ckeys, cvals, use_str_keys = _ctype_key_value(key, out)
if use_str_keys:
check_call(_LIB.MXKVStorePullWithSparseEx(self.handle, mx_uint(len(ckeys)), ckeys,
cvals, ctypes.c_int(priority),
ctypes.c_bool(ignore_sparse)))
else:
check_call(_LIB.MXKVStorePullWithSparse(self.handle, mx_uint(len(ckeys)), ckeys,
cvals, ctypes.c_int(priority),
ctypes.c_bool(ignore_sparse))) | [
"def",
"pull",
"(",
"self",
",",
"key",
",",
"out",
"=",
"None",
",",
"priority",
"=",
"0",
",",
"ignore_sparse",
"=",
"True",
")",
":",
"assert",
"(",
"out",
"is",
"not",
"None",
")",
"ckeys",
",",
"cvals",
",",
"use_str_keys",
"=",
"_ctype_key_value",
"(",
"key",
",",
"out",
")",
"if",
"use_str_keys",
":",
"check_call",
"(",
"_LIB",
".",
"MXKVStorePullWithSparseEx",
"(",
"self",
".",
"handle",
",",
"mx_uint",
"(",
"len",
"(",
"ckeys",
")",
")",
",",
"ckeys",
",",
"cvals",
",",
"ctypes",
".",
"c_int",
"(",
"priority",
")",
",",
"ctypes",
".",
"c_bool",
"(",
"ignore_sparse",
")",
")",
")",
"else",
":",
"check_call",
"(",
"_LIB",
".",
"MXKVStorePullWithSparse",
"(",
"self",
".",
"handle",
",",
"mx_uint",
"(",
"len",
"(",
"ckeys",
")",
")",
",",
"ckeys",
",",
"cvals",
",",
"ctypes",
".",
"c_int",
"(",
"priority",
")",
",",
"ctypes",
".",
"c_bool",
"(",
"ignore_sparse",
")",
")",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/kvstore/kvstore.py#L265-L338 | ||
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/fuchsia/binary_sizes.py | python | GetCompressedSize | (file_path) | return int(math.ceil(blob_bytes / BLOBFS_BLOCK_SIZE)) * BLOBFS_BLOCK_SIZE | Measures file size after blobfs compression. | Measures file size after blobfs compression. | [
"Measures",
"file",
"size",
"after",
"blobfs",
"compression",
"."
] | def GetCompressedSize(file_path):
"""Measures file size after blobfs compression."""
compressor_path = GetHostToolPathFromPlatform('blobfs-compression')
try:
temp_dir = tempfile.mkdtemp()
compressed_file_path = os.path.join(temp_dir, os.path.basename(file_path))
compressor_cmd = [
compressor_path,
'--source_file=%s' % file_path,
'--compressed_file=%s' % compressed_file_path
]
proc = subprocess.Popen(compressor_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
proc.wait()
compressor_output = proc.stdout.read().decode('utf-8')
if proc.returncode != 0:
print(compressor_output, file=sys.stderr)
raise Exception('Error while running %s' % compressor_path)
finally:
shutil.rmtree(temp_dir)
# Match a compressed bytes total from blobfs-compression output like
# Wrote 360830 bytes (40% compression)
blobfs_compressed_bytes_re = r'Wrote\s+(?P<bytes>\d+)\s+bytes'
match = re.search(blobfs_compressed_bytes_re, compressor_output)
if not match:
print(compressor_output, file=sys.stderr)
raise Exception('Could not get compressed bytes for %s' % file_path)
# Round the compressed file size up to an integer number of blobfs blocks.
BLOBFS_BLOCK_SIZE = 8192 # Fuchsia's blobfs file system uses 8KiB blocks.
blob_bytes = int(match.group('bytes'))
return int(math.ceil(blob_bytes / BLOBFS_BLOCK_SIZE)) * BLOBFS_BLOCK_SIZE | [
"def",
"GetCompressedSize",
"(",
"file_path",
")",
":",
"compressor_path",
"=",
"GetHostToolPathFromPlatform",
"(",
"'blobfs-compression'",
")",
"try",
":",
"temp_dir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"compressed_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"temp_dir",
",",
"os",
".",
"path",
".",
"basename",
"(",
"file_path",
")",
")",
"compressor_cmd",
"=",
"[",
"compressor_path",
",",
"'--source_file=%s'",
"%",
"file_path",
",",
"'--compressed_file=%s'",
"%",
"compressed_file_path",
"]",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"compressor_cmd",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"proc",
".",
"wait",
"(",
")",
"compressor_output",
"=",
"proc",
".",
"stdout",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"proc",
".",
"returncode",
"!=",
"0",
":",
"print",
"(",
"compressor_output",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"raise",
"Exception",
"(",
"'Error while running %s'",
"%",
"compressor_path",
")",
"finally",
":",
"shutil",
".",
"rmtree",
"(",
"temp_dir",
")",
"# Match a compressed bytes total from blobfs-compression output like",
"# Wrote 360830 bytes (40% compression)",
"blobfs_compressed_bytes_re",
"=",
"r'Wrote\\s+(?P<bytes>\\d+)\\s+bytes'",
"match",
"=",
"re",
".",
"search",
"(",
"blobfs_compressed_bytes_re",
",",
"compressor_output",
")",
"if",
"not",
"match",
":",
"print",
"(",
"compressor_output",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"raise",
"Exception",
"(",
"'Could not get compressed bytes for %s'",
"%",
"file_path",
")",
"# Round the compressed file size up to an integer number of blobfs blocks.",
"BLOBFS_BLOCK_SIZE",
"=",
"8192",
"# Fuchsia's blobfs file system uses 8KiB blocks.",
"blob_bytes",
"=",
"int",
"(",
"match",
".",
"group",
"(",
"'bytes'",
")",
")",
"return",
"int",
"(",
"math",
".",
"ceil",
"(",
"blob_bytes",
"/",
"BLOBFS_BLOCK_SIZE",
")",
")",
"*",
"BLOBFS_BLOCK_SIZE"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/fuchsia/binary_sizes.py#L240-L275 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Canvas.insert | (self, *args) | Insert TEXT in item TAGORID at position POS. ARGS must
be TAGORID POS TEXT. | Insert TEXT in item TAGORID at position POS. ARGS must
be TAGORID POS TEXT. | [
"Insert",
"TEXT",
"in",
"item",
"TAGORID",
"at",
"position",
"POS",
".",
"ARGS",
"must",
"be",
"TAGORID",
"POS",
"TEXT",
"."
] | def insert(self, *args):
"""Insert TEXT in item TAGORID at position POS. ARGS must
be TAGORID POS TEXT."""
self.tk.call((self._w, 'insert') + args) | [
"def",
"insert",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"(",
"self",
".",
"_w",
",",
"'insert'",
")",
"+",
"args",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2334-L2337 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/supertooltip.py | python | ToolTipWindowBase.MakeWindowTransparent | (self, amount) | Makes the :class:`SuperToolTip` window transparent.
:param `amount`: the alpha channel value.
:note: This method is available only on Windows and requires Mark Hammond's
pywin32 package. | Makes the :class:`SuperToolTip` window transparent. | [
"Makes",
"the",
":",
"class",
":",
"SuperToolTip",
"window",
"transparent",
"."
] | def MakeWindowTransparent(self, amount):
"""
Makes the :class:`SuperToolTip` window transparent.
:param `amount`: the alpha channel value.
:note: This method is available only on Windows and requires Mark Hammond's
pywin32 package.
"""
if not _libimported:
# No way, only Windows XP with Mark Hammond's win32all
return
# this API call is not in all SDKs, only the newer ones, so
# we will runtime bind this
if wx.Platform != "__WXMSW__":
return
hwnd = self.GetHandle()
if not hasattr(self, "_winlib"):
self._winlib = win32api.LoadLibrary("user32")
pSetLayeredWindowAttributes = win32api.GetProcAddress(self._winlib,
"SetLayeredWindowAttributes")
if pSetLayeredWindowAttributes == None:
return
exstyle = win32api.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
if 0 == (exstyle & 0x80000):
win32api.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, exstyle | 0x80000)
winxpgui.SetLayeredWindowAttributes(hwnd, 0, amount, 2) | [
"def",
"MakeWindowTransparent",
"(",
"self",
",",
"amount",
")",
":",
"if",
"not",
"_libimported",
":",
"# No way, only Windows XP with Mark Hammond's win32all",
"return",
"# this API call is not in all SDKs, only the newer ones, so",
"# we will runtime bind this",
"if",
"wx",
".",
"Platform",
"!=",
"\"__WXMSW__\"",
":",
"return",
"hwnd",
"=",
"self",
".",
"GetHandle",
"(",
")",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_winlib\"",
")",
":",
"self",
".",
"_winlib",
"=",
"win32api",
".",
"LoadLibrary",
"(",
"\"user32\"",
")",
"pSetLayeredWindowAttributes",
"=",
"win32api",
".",
"GetProcAddress",
"(",
"self",
".",
"_winlib",
",",
"\"SetLayeredWindowAttributes\"",
")",
"if",
"pSetLayeredWindowAttributes",
"==",
"None",
":",
"return",
"exstyle",
"=",
"win32api",
".",
"GetWindowLong",
"(",
"hwnd",
",",
"win32con",
".",
"GWL_EXSTYLE",
")",
"if",
"0",
"==",
"(",
"exstyle",
"&",
"0x80000",
")",
":",
"win32api",
".",
"SetWindowLong",
"(",
"hwnd",
",",
"win32con",
".",
"GWL_EXSTYLE",
",",
"exstyle",
"|",
"0x80000",
")",
"winxpgui",
".",
"SetLayeredWindowAttributes",
"(",
"hwnd",
",",
"0",
",",
"amount",
",",
"2",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/supertooltip.py#L637-L671 | ||
epam/Indigo | 30e40b4b1eb9bae0207435a26cfcb81ddcc42be1 | api/python/indigo/__init__.py | python | IndigoObject.clone | (self) | return self.dispatcher.IndigoObject(
self.dispatcher,
self.dispatcher._checkResult(Indigo._lib.indigoClone(self.id)),
) | Clones IndigoObject
Returns:
IndigoObject: cloned object | Clones IndigoObject | [
"Clones",
"IndigoObject"
] | def clone(self):
"""Clones IndigoObject
Returns:
IndigoObject: cloned object
"""
self.dispatcher._setSessionId()
return self.dispatcher.IndigoObject(
self.dispatcher,
self.dispatcher._checkResult(Indigo._lib.indigoClone(self.id)),
) | [
"def",
"clone",
"(",
"self",
")",
":",
"self",
".",
"dispatcher",
".",
"_setSessionId",
"(",
")",
"return",
"self",
".",
"dispatcher",
".",
"IndigoObject",
"(",
"self",
".",
"dispatcher",
",",
"self",
".",
"dispatcher",
".",
"_checkResult",
"(",
"Indigo",
".",
"_lib",
".",
"indigoClone",
"(",
"self",
".",
"id",
")",
")",
",",
")"
] | https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/api/python/indigo/__init__.py#L205-L215 | |
baidu/bigflow | 449245016c0df7d1252e85581e588bfc60cefad3 | bigflow_python/python/bigflow/rpc/requests.py | python | suspend | (pipeline_id, logical_plan_message, commit_args=None) | return None, res.status | Send the rpc command to the other end to suspend the logical plan
Args:
Raises:
error.BigflowRPCException: if any error happened | Send the rpc command to the other end to suspend the logical plan | [
"Send",
"the",
"rpc",
"command",
"to",
"the",
"other",
"end",
"to",
"suspend",
"the",
"logical",
"plan"
] | def suspend(pipeline_id, logical_plan_message, commit_args=None):
"""
Send the rpc command to the other end to suspend the logical plan
Args:
Raises:
error.BigflowRPCException: if any error happened
"""
request = service_pb2.SuspendRequest()
request.pipeline_id = pipeline_id
request.logical_plan.CopyFrom(logical_plan_message)
if commit_args is not None:
request.hadoop_commit_args.extend(commit_args)
response = _service.request(request, "suspend")
import google.protobuf.json_format as json_format
res = json_format.Parse(response, service_pb2.VoidResponse())
return None, res.status | [
"def",
"suspend",
"(",
"pipeline_id",
",",
"logical_plan_message",
",",
"commit_args",
"=",
"None",
")",
":",
"request",
"=",
"service_pb2",
".",
"SuspendRequest",
"(",
")",
"request",
".",
"pipeline_id",
"=",
"pipeline_id",
"request",
".",
"logical_plan",
".",
"CopyFrom",
"(",
"logical_plan_message",
")",
"if",
"commit_args",
"is",
"not",
"None",
":",
"request",
".",
"hadoop_commit_args",
".",
"extend",
"(",
"commit_args",
")",
"response",
"=",
"_service",
".",
"request",
"(",
"request",
",",
"\"suspend\"",
")",
"import",
"google",
".",
"protobuf",
".",
"json_format",
"as",
"json_format",
"res",
"=",
"json_format",
".",
"Parse",
"(",
"response",
",",
"service_pb2",
".",
"VoidResponse",
"(",
")",
")",
"return",
"None",
",",
"res",
".",
"status"
] | https://github.com/baidu/bigflow/blob/449245016c0df7d1252e85581e588bfc60cefad3/bigflow_python/python/bigflow/rpc/requests.py#L117-L138 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/idlelib/tooltip.py | python | OnHoverTooltipBase._show_event | (self, event=None) | event handler to display the tooltip | event handler to display the tooltip | [
"event",
"handler",
"to",
"display",
"the",
"tooltip"
] | def _show_event(self, event=None):
"""event handler to display the tooltip"""
if self.hover_delay:
self.schedule()
else:
self.showtip() | [
"def",
"_show_event",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"if",
"self",
".",
"hover_delay",
":",
"self",
".",
"schedule",
"(",
")",
"else",
":",
"self",
".",
"showtip",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/tooltip.py#L112-L117 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/dataview.py | python | DataViewRenderer.FinishEditing | (*args, **kwargs) | return _dataview.DataViewRenderer_FinishEditing(*args, **kwargs) | FinishEditing(self) -> bool | FinishEditing(self) -> bool | [
"FinishEditing",
"(",
"self",
")",
"-",
">",
"bool"
] | def FinishEditing(*args, **kwargs):
"""FinishEditing(self) -> bool"""
return _dataview.DataViewRenderer_FinishEditing(*args, **kwargs) | [
"def",
"FinishEditing",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewRenderer_FinishEditing",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/dataview.py#L1229-L1231 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/math_ops.py | python | _calc_mat_mul_flops | (graph, node) | return ops.OpStats("flops", (k * output_count * 2)) | Calculates the compute resources needed for MatMul. | Calculates the compute resources needed for MatMul. | [
"Calculates",
"the",
"compute",
"resources",
"needed",
"for",
"MatMul",
"."
] | def _calc_mat_mul_flops(graph, node):
"""Calculates the compute resources needed for MatMul."""
transpose_a = node.attr["transpose_a"].b
a_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0])
a_shape.assert_is_fully_defined()
if transpose_a:
k = int(a_shape[0])
else:
k = int(a_shape[1])
output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name)
output_shape.assert_is_fully_defined()
output_count = np.prod(output_shape.as_list())
return ops.OpStats("flops", (k * output_count * 2)) | [
"def",
"_calc_mat_mul_flops",
"(",
"graph",
",",
"node",
")",
":",
"transpose_a",
"=",
"node",
".",
"attr",
"[",
"\"transpose_a\"",
"]",
".",
"b",
"a_shape",
"=",
"graph_util",
".",
"tensor_shape_from_node_def_name",
"(",
"graph",
",",
"node",
".",
"input",
"[",
"0",
"]",
")",
"a_shape",
".",
"assert_is_fully_defined",
"(",
")",
"if",
"transpose_a",
":",
"k",
"=",
"int",
"(",
"a_shape",
"[",
"0",
"]",
")",
"else",
":",
"k",
"=",
"int",
"(",
"a_shape",
"[",
"1",
"]",
")",
"output_shape",
"=",
"graph_util",
".",
"tensor_shape_from_node_def_name",
"(",
"graph",
",",
"node",
".",
"name",
")",
"output_shape",
".",
"assert_is_fully_defined",
"(",
")",
"output_count",
"=",
"np",
".",
"prod",
"(",
"output_shape",
".",
"as_list",
"(",
")",
")",
"return",
"ops",
".",
"OpStats",
"(",
"\"flops\"",
",",
"(",
"k",
"*",
"output_count",
"*",
"2",
")",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/math_ops.py#L1362-L1374 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/genericpath.py | python | isdir | (s) | return stat.S_ISDIR(st.st_mode) | Return true if the pathname refers to an existing directory. | Return true if the pathname refers to an existing directory. | [
"Return",
"true",
"if",
"the",
"pathname",
"refers",
"to",
"an",
"existing",
"directory",
"."
] | def isdir(s):
"""Return true if the pathname refers to an existing directory."""
try:
st = os.stat(s)
except os.error:
return False
return stat.S_ISDIR(st.st_mode) | [
"def",
"isdir",
"(",
"s",
")",
":",
"try",
":",
"st",
"=",
"os",
".",
"stat",
"(",
"s",
")",
"except",
"os",
".",
"error",
":",
"return",
"False",
"return",
"stat",
".",
"S_ISDIR",
"(",
"st",
".",
"st_mode",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/genericpath.py#L38-L44 | |
facebook/mysql-5.6 | 65a650660ec7b4d627d1b738f397252ff4706207 | arcanist/lint/cpp_linter/cpplint.py | python | CheckCStyleCast | (filename, linenum, line, raw_line, cast_type, pattern,
error) | return True | Checks for a C-style cast by looking for the pattern.
Args:
filename: The name of the current file.
linenum: The number of the line to check.
line: The line of code to check.
raw_line: The raw line of code to check, with comments.
cast_type: The string for the C++ cast to recommend. This is either
reinterpret_cast, static_cast, or const_cast, depending.
pattern: The regular expression used to find C-style casts.
error: The function to call with any errors found.
Returns:
True if an error was emitted.
False otherwise. | Checks for a C-style cast by looking for the pattern. | [
"Checks",
"for",
"a",
"C",
"-",
"style",
"cast",
"by",
"looking",
"for",
"the",
"pattern",
"."
] | def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern,
error):
"""Checks for a C-style cast by looking for the pattern.
Args:
filename: The name of the current file.
linenum: The number of the line to check.
line: The line of code to check.
raw_line: The raw line of code to check, with comments.
cast_type: The string for the C++ cast to recommend. This is either
reinterpret_cast, static_cast, or const_cast, depending.
pattern: The regular expression used to find C-style casts.
error: The function to call with any errors found.
Returns:
True if an error was emitted.
False otherwise.
"""
match = Search(pattern, line)
if not match:
return False
# Exclude lines with sizeof, since sizeof looks like a cast.
sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1])
if sizeof_match:
return False
# operator++(int) and operator--(int)
if (line[0:match.start(1) - 1].endswith(' operator++') or
line[0:match.start(1) - 1].endswith(' operator--')):
return False
# A single unnamed argument for a function tends to look like old
# style cast. If we see those, don't issue warnings for deprecated
# casts, instead issue warnings for unnamed arguments where
# appropriate.
#
# These are things that we want warnings for, since the style guide
# explicitly require all parameters to be named:
# Function(int);
# Function(int) {
# ConstMember(int) const;
# ConstMember(int) const {
# ExceptionMember(int) throw (...);
# ExceptionMember(int) throw (...) {
# PureVirtual(int) = 0;
#
# These are functions of some sort, where the compiler would be fine
# if they had named parameters, but people often omit those
# identifiers to reduce clutter:
# (FunctionPointer)(int);
# (FunctionPointer)(int) = value;
# Function((function_pointer_arg)(int))
# <TemplateArgument(int)>;
# <(FunctionPointerTemplateArgument)(int)>;
remainder = line[match.end(0):]
if Match(r'^\s*(?:;|const\b|throw\b|=|>|\{|\))', remainder):
# Looks like an unnamed parameter.
# Don't warn on any kind of template arguments.
if Match(r'^\s*>', remainder):
return False
# Don't warn on assignments to function pointers, but keep warnings for
# unnamed parameters to pure virtual functions. Note that this pattern
# will also pass on assignments of "0" to function pointers, but the
# preferred values for those would be "nullptr" or "NULL".
matched_zero = Match(r'^\s=\s*(\S+)\s*;', remainder)
if matched_zero and matched_zero.group(1) != '0':
return False
# Don't warn on function pointer declarations. For this we need
# to check what came before the "(type)" string.
if Match(r'.*\)\s*$', line[0:match.start(0)]):
return False
# Don't warn if the parameter is named with block comments, e.g.:
# Function(int /*unused_param*/);
if '/*' in raw_line:
return False
# Passed all filters, issue warning here.
error(filename, linenum, 'readability/function', 3,
'All parameters should be named in a function')
return True
# At this point, all that should be left is actual casts.
error(filename, linenum, 'readability/casting', 4,
'Using C-style cast. Use %s<%s>(...) instead' %
(cast_type, match.group(1)))
return True | [
"def",
"CheckCStyleCast",
"(",
"filename",
",",
"linenum",
",",
"line",
",",
"raw_line",
",",
"cast_type",
",",
"pattern",
",",
"error",
")",
":",
"match",
"=",
"Search",
"(",
"pattern",
",",
"line",
")",
"if",
"not",
"match",
":",
"return",
"False",
"# Exclude lines with sizeof, since sizeof looks like a cast.",
"sizeof_match",
"=",
"Match",
"(",
"r'.*sizeof\\s*$'",
",",
"line",
"[",
"0",
":",
"match",
".",
"start",
"(",
"1",
")",
"-",
"1",
"]",
")",
"if",
"sizeof_match",
":",
"return",
"False",
"# operator++(int) and operator--(int)",
"if",
"(",
"line",
"[",
"0",
":",
"match",
".",
"start",
"(",
"1",
")",
"-",
"1",
"]",
".",
"endswith",
"(",
"' operator++'",
")",
"or",
"line",
"[",
"0",
":",
"match",
".",
"start",
"(",
"1",
")",
"-",
"1",
"]",
".",
"endswith",
"(",
"' operator--'",
")",
")",
":",
"return",
"False",
"# A single unnamed argument for a function tends to look like old",
"# style cast. If we see those, don't issue warnings for deprecated",
"# casts, instead issue warnings for unnamed arguments where",
"# appropriate.",
"#",
"# These are things that we want warnings for, since the style guide",
"# explicitly require all parameters to be named:",
"# Function(int);",
"# Function(int) {",
"# ConstMember(int) const;",
"# ConstMember(int) const {",
"# ExceptionMember(int) throw (...);",
"# ExceptionMember(int) throw (...) {",
"# PureVirtual(int) = 0;",
"#",
"# These are functions of some sort, where the compiler would be fine",
"# if they had named parameters, but people often omit those",
"# identifiers to reduce clutter:",
"# (FunctionPointer)(int);",
"# (FunctionPointer)(int) = value;",
"# Function((function_pointer_arg)(int))",
"# <TemplateArgument(int)>;",
"# <(FunctionPointerTemplateArgument)(int)>;",
"remainder",
"=",
"line",
"[",
"match",
".",
"end",
"(",
"0",
")",
":",
"]",
"if",
"Match",
"(",
"r'^\\s*(?:;|const\\b|throw\\b|=|>|\\{|\\))'",
",",
"remainder",
")",
":",
"# Looks like an unnamed parameter.",
"# Don't warn on any kind of template arguments.",
"if",
"Match",
"(",
"r'^\\s*>'",
",",
"remainder",
")",
":",
"return",
"False",
"# Don't warn on assignments to function pointers, but keep warnings for",
"# unnamed parameters to pure virtual functions. Note that this pattern",
"# will also pass on assignments of \"0\" to function pointers, but the",
"# preferred values for those would be \"nullptr\" or \"NULL\".",
"matched_zero",
"=",
"Match",
"(",
"r'^\\s=\\s*(\\S+)\\s*;'",
",",
"remainder",
")",
"if",
"matched_zero",
"and",
"matched_zero",
".",
"group",
"(",
"1",
")",
"!=",
"'0'",
":",
"return",
"False",
"# Don't warn on function pointer declarations. For this we need",
"# to check what came before the \"(type)\" string.",
"if",
"Match",
"(",
"r'.*\\)\\s*$'",
",",
"line",
"[",
"0",
":",
"match",
".",
"start",
"(",
"0",
")",
"]",
")",
":",
"return",
"False",
"# Don't warn if the parameter is named with block comments, e.g.:",
"# Function(int /*unused_param*/);",
"if",
"'/*'",
"in",
"raw_line",
":",
"return",
"False",
"# Passed all filters, issue warning here.",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/function'",
",",
"3",
",",
"'All parameters should be named in a function'",
")",
"return",
"True",
"# At this point, all that should be left is actual casts.",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/casting'",
",",
"4",
",",
"'Using C-style cast. Use %s<%s>(...) instead'",
"%",
"(",
"cast_type",
",",
"match",
".",
"group",
"(",
"1",
")",
")",
")",
"return",
"True"
] | https://github.com/facebook/mysql-5.6/blob/65a650660ec7b4d627d1b738f397252ff4706207/arcanist/lint/cpp_linter/cpplint.py#L4152-L4243 | |
plaidml/plaidml | f3c6681db21460e5fdc11ae651d6d7b6c27f8262 | mlperf/models/base_model_r34.py | python | Loss._loc_vec | (self, loc) | return torch.cat((gxy, gwh), dim=1).contiguous() | Generate Location Vectors | Generate Location Vectors | [
"Generate",
"Location",
"Vectors"
] | def _loc_vec(self, loc):
"""
Generate Location Vectors
"""
gxy = self.scale_xy * (loc[:, :2, :] - self.dboxes[:, :2, :]) / self.dboxes[:, 2:,]
gwh = self.scale_wh * (loc[:, 2:, :] / self.dboxes[:, 2:, :]).log()
return torch.cat((gxy, gwh), dim=1).contiguous() | [
"def",
"_loc_vec",
"(",
"self",
",",
"loc",
")",
":",
"gxy",
"=",
"self",
".",
"scale_xy",
"*",
"(",
"loc",
"[",
":",
",",
":",
"2",
",",
":",
"]",
"-",
"self",
".",
"dboxes",
"[",
":",
",",
":",
"2",
",",
":",
"]",
")",
"/",
"self",
".",
"dboxes",
"[",
":",
",",
"2",
":",
",",
"]",
"gwh",
"=",
"self",
".",
"scale_wh",
"*",
"(",
"loc",
"[",
":",
",",
"2",
":",
",",
":",
"]",
"/",
"self",
".",
"dboxes",
"[",
":",
",",
"2",
":",
",",
":",
"]",
")",
".",
"log",
"(",
")",
"return",
"torch",
".",
"cat",
"(",
"(",
"gxy",
",",
"gwh",
")",
",",
"dim",
"=",
"1",
")",
".",
"contiguous",
"(",
")"
] | https://github.com/plaidml/plaidml/blob/f3c6681db21460e5fdc11ae651d6d7b6c27f8262/mlperf/models/base_model_r34.py#L164-L171 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/configHandler.py | python | IdleConf.GetExtensionBindings | (self,extensionName) | return extBinds | Returns a dictionary of all the event bindings for a particular
extension. The configurable keybindings are returned as they exist in
the dictionary returned by GetCurrentKeySet; that is, where re-used
keybindings are disabled. | Returns a dictionary of all the event bindings for a particular
extension. The configurable keybindings are returned as they exist in
the dictionary returned by GetCurrentKeySet; that is, where re-used
keybindings are disabled. | [
"Returns",
"a",
"dictionary",
"of",
"all",
"the",
"event",
"bindings",
"for",
"a",
"particular",
"extension",
".",
"The",
"configurable",
"keybindings",
"are",
"returned",
"as",
"they",
"exist",
"in",
"the",
"dictionary",
"returned",
"by",
"GetCurrentKeySet",
";",
"that",
"is",
"where",
"re",
"-",
"used",
"keybindings",
"are",
"disabled",
"."
] | def GetExtensionBindings(self,extensionName):
"""
Returns a dictionary of all the event bindings for a particular
extension. The configurable keybindings are returned as they exist in
the dictionary returned by GetCurrentKeySet; that is, where re-used
keybindings are disabled.
"""
bindsName=extensionName+'_bindings'
extBinds=self.GetExtensionKeys(extensionName)
#add the non-configurable bindings
if self.defaultCfg['extensions'].has_section(bindsName):
eventNames=self.defaultCfg['extensions'].GetOptionList(bindsName)
for eventName in eventNames:
binding=self.GetOption('extensions',bindsName,
eventName,default='').split()
event='<<'+eventName+'>>'
extBinds[event]=binding
return extBinds | [
"def",
"GetExtensionBindings",
"(",
"self",
",",
"extensionName",
")",
":",
"bindsName",
"=",
"extensionName",
"+",
"'_bindings'",
"extBinds",
"=",
"self",
".",
"GetExtensionKeys",
"(",
"extensionName",
")",
"#add the non-configurable bindings",
"if",
"self",
".",
"defaultCfg",
"[",
"'extensions'",
"]",
".",
"has_section",
"(",
"bindsName",
")",
":",
"eventNames",
"=",
"self",
".",
"defaultCfg",
"[",
"'extensions'",
"]",
".",
"GetOptionList",
"(",
"bindsName",
")",
"for",
"eventName",
"in",
"eventNames",
":",
"binding",
"=",
"self",
".",
"GetOption",
"(",
"'extensions'",
",",
"bindsName",
",",
"eventName",
",",
"default",
"=",
"''",
")",
".",
"split",
"(",
")",
"event",
"=",
"'<<'",
"+",
"eventName",
"+",
"'>>'",
"extBinds",
"[",
"event",
"]",
"=",
"binding",
"return",
"extBinds"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/configHandler.py#L495-L513 | |
flexflow/FlexFlow | 581fad8ba8d10a16a3102ee2b406b0319586df24 | python/flexflow/core/flexflow_cffi.py | python | FFModel.identity | (self, input, name=None) | return Tensor(handle, owner_op_type=OpType.IDENTITY) | Identity function.
:param input: the input Tensor.
:type input: Tensor
:param name: the name of the layer. Default is None.
:type name: string
:returns: Tensor -- the output tensor. | Identity function.
:param input: the input Tensor.
:type input: Tensor
:param name: the name of the layer. Default is None.
:type name: string | [
"Identity",
"function",
".",
":",
"param",
"input",
":",
"the",
"input",
"Tensor",
".",
":",
"type",
"input",
":",
"Tensor",
":",
"param",
"name",
":",
"the",
"name",
"of",
"the",
"layer",
".",
"Default",
"is",
"None",
".",
":",
"type",
"name",
":",
"string"
] | def identity(self, input, name=None):
"""Identity function.
:param input: the input Tensor.
:type input: Tensor
:param name: the name of the layer. Default is None.
:type name: string
:returns: Tensor -- the output tensor.
"""
c_name = get_c_name(name)
handle = ffc.flexflow_model_add_identity(self.handle, input.handle, c_name)
self.add_layer(OpType.IDENTITY, name)
return Tensor(handle, owner_op_type=OpType.IDENTITY) | [
"def",
"identity",
"(",
"self",
",",
"input",
",",
"name",
"=",
"None",
")",
":",
"c_name",
"=",
"get_c_name",
"(",
"name",
")",
"handle",
"=",
"ffc",
".",
"flexflow_model_add_identity",
"(",
"self",
".",
"handle",
",",
"input",
".",
"handle",
",",
"c_name",
")",
"self",
".",
"add_layer",
"(",
"OpType",
".",
"IDENTITY",
",",
"name",
")",
"return",
"Tensor",
"(",
"handle",
",",
"owner_op_type",
"=",
"OpType",
".",
"IDENTITY",
")"
] | https://github.com/flexflow/FlexFlow/blob/581fad8ba8d10a16a3102ee2b406b0319586df24/python/flexflow/core/flexflow_cffi.py#L1541-L1555 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/util/tf_inspect.py | python | stack | (context=1) | return _inspect.stack(context)[1:] | TFDecorator-aware replacement for inspect.stack. | TFDecorator-aware replacement for inspect.stack. | [
"TFDecorator",
"-",
"aware",
"replacement",
"for",
"inspect",
".",
"stack",
"."
] | def stack(context=1):
"""TFDecorator-aware replacement for inspect.stack."""
return _inspect.stack(context)[1:] | [
"def",
"stack",
"(",
"context",
"=",
"1",
")",
":",
"return",
"_inspect",
".",
"stack",
"(",
"context",
")",
"[",
"1",
":",
"]"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/util/tf_inspect.py#L405-L407 | |
cathywu/Sentiment-Analysis | eb501fd1375c0c3f3ab430f963255f1bb858e659 | PyML-0.7.9/PyML/datagen/toydata.py | python | noisyData | () | Creates two populations, usually linearly-separable, but with
vastly different variance. Simulates a problem where one
population has significantly more noise than another. Data are
output in a CSV format suitable for creating a PyML VectorDataSet
(labelsColumn=1). | Creates two populations, usually linearly-separable, but with
vastly different variance. Simulates a problem where one
population has significantly more noise than another. Data are
output in a CSV format suitable for creating a PyML VectorDataSet
(labelsColumn=1). | [
"Creates",
"two",
"populations",
"usually",
"linearly",
"-",
"separable",
"but",
"with",
"vastly",
"different",
"variance",
".",
"Simulates",
"a",
"problem",
"where",
"one",
"population",
"has",
"significantly",
"more",
"noise",
"than",
"another",
".",
"Data",
"are",
"output",
"in",
"a",
"CSV",
"format",
"suitable",
"for",
"creating",
"a",
"PyML",
"VectorDataSet",
"(",
"labelsColumn",
"=",
"1",
")",
"."
] | def noisyData() :
"""
Creates two populations, usually linearly-separable, but with
vastly different variance. Simulates a problem where one
population has significantly more noise than another. Data are
output in a CSV format suitable for creating a PyML VectorDataSet
(labelsColumn=1).
"""
pid = 0
for label in [-1,1] :
if label < 0 :
X,Y = gaussCloud(-0.5, 0.0, sigma=0.05, n=20)
else :
X,Y = gaussCloud(0.3, 0.0, sigma=0.25, n=20)
for i in xrange(len(X)) :
pid += 1
print "%(p)d,%(l)d,%(x)f,%(y)f" % {'p':pid, 'l':label, 'x':X[i], 'y':Y[i]} | [
"def",
"noisyData",
"(",
")",
":",
"pid",
"=",
"0",
"for",
"label",
"in",
"[",
"-",
"1",
",",
"1",
"]",
":",
"if",
"label",
"<",
"0",
":",
"X",
",",
"Y",
"=",
"gaussCloud",
"(",
"-",
"0.5",
",",
"0.0",
",",
"sigma",
"=",
"0.05",
",",
"n",
"=",
"20",
")",
"else",
":",
"X",
",",
"Y",
"=",
"gaussCloud",
"(",
"0.3",
",",
"0.0",
",",
"sigma",
"=",
"0.25",
",",
"n",
"=",
"20",
")",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"X",
")",
")",
":",
"pid",
"+=",
"1",
"print",
"\"%(p)d,%(l)d,%(x)f,%(y)f\"",
"%",
"{",
"'p'",
":",
"pid",
",",
"'l'",
":",
"label",
",",
"'x'",
":",
"X",
"[",
"i",
"]",
",",
"'y'",
":",
"Y",
"[",
"i",
"]",
"}"
] | https://github.com/cathywu/Sentiment-Analysis/blob/eb501fd1375c0c3f3ab430f963255f1bb858e659/PyML-0.7.9/PyML/datagen/toydata.py#L83-L99 | ||
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSUserFile.py | python | Writer.AddDebugSettings | (self, config_name, command, environment = {},
working_directory="") | Adds a DebugSettings node to the user file for a particular config.
Args:
command: command line to run. First element in the list is the
executable. All elements of the command will be quoted if
necessary.
working_directory: other files which may trigger the rule. (optional) | Adds a DebugSettings node to the user file for a particular config. | [
"Adds",
"a",
"DebugSettings",
"node",
"to",
"the",
"user",
"file",
"for",
"a",
"particular",
"config",
"."
] | def AddDebugSettings(self, config_name, command, environment = {},
working_directory=""):
"""Adds a DebugSettings node to the user file for a particular config.
Args:
command: command line to run. First element in the list is the
executable. All elements of the command will be quoted if
necessary.
working_directory: other files which may trigger the rule. (optional)
"""
command = _QuoteWin32CommandLineArgs(command)
abs_command = _FindCommandInPath(command[0])
if environment and isinstance(environment, dict):
env_list = ['%s="%s"' % (key, val)
for (key,val) in environment.iteritems()]
environment = ' '.join(env_list)
else:
environment = ''
n_cmd = ['DebugSettings',
{'Command': abs_command,
'WorkingDirectory': working_directory,
'CommandArguments': " ".join(command[1:]),
'RemoteMachine': socket.gethostname(),
'Environment': environment,
'EnvironmentMerge': 'true',
# Currently these are all "dummy" values that we're just setting
# in the default manner that MSVS does it. We could use some of
# these to add additional capabilities, I suppose, but they might
# not have parity with other platforms then.
'Attach': 'false',
'DebuggerType': '3', # 'auto' debugger
'Remote': '1',
'RemoteCommand': '',
'HttpUrl': '',
'PDBPath': '',
'SQLDebugging': '',
'DebuggerFlavor': '0',
'MPIRunCommand': '',
'MPIRunArguments': '',
'MPIRunWorkingDirectory': '',
'ApplicationCommand': '',
'ApplicationArguments': '',
'ShimCommand': '',
'MPIAcceptMode': '',
'MPIAcceptFilter': ''
}]
# Find the config, and add it if it doesn't exist.
if config_name not in self.configurations:
self.AddConfig(config_name)
# Add the DebugSettings onto the appropriate config.
self.configurations[config_name].append(n_cmd) | [
"def",
"AddDebugSettings",
"(",
"self",
",",
"config_name",
",",
"command",
",",
"environment",
"=",
"{",
"}",
",",
"working_directory",
"=",
"\"\"",
")",
":",
"command",
"=",
"_QuoteWin32CommandLineArgs",
"(",
"command",
")",
"abs_command",
"=",
"_FindCommandInPath",
"(",
"command",
"[",
"0",
"]",
")",
"if",
"environment",
"and",
"isinstance",
"(",
"environment",
",",
"dict",
")",
":",
"env_list",
"=",
"[",
"'%s=\"%s\"'",
"%",
"(",
"key",
",",
"val",
")",
"for",
"(",
"key",
",",
"val",
")",
"in",
"environment",
".",
"iteritems",
"(",
")",
"]",
"environment",
"=",
"' '",
".",
"join",
"(",
"env_list",
")",
"else",
":",
"environment",
"=",
"''",
"n_cmd",
"=",
"[",
"'DebugSettings'",
",",
"{",
"'Command'",
":",
"abs_command",
",",
"'WorkingDirectory'",
":",
"working_directory",
",",
"'CommandArguments'",
":",
"\" \"",
".",
"join",
"(",
"command",
"[",
"1",
":",
"]",
")",
",",
"'RemoteMachine'",
":",
"socket",
".",
"gethostname",
"(",
")",
",",
"'Environment'",
":",
"environment",
",",
"'EnvironmentMerge'",
":",
"'true'",
",",
"# Currently these are all \"dummy\" values that we're just setting",
"# in the default manner that MSVS does it. We could use some of",
"# these to add additional capabilities, I suppose, but they might",
"# not have parity with other platforms then.",
"'Attach'",
":",
"'false'",
",",
"'DebuggerType'",
":",
"'3'",
",",
"# 'auto' debugger",
"'Remote'",
":",
"'1'",
",",
"'RemoteCommand'",
":",
"''",
",",
"'HttpUrl'",
":",
"''",
",",
"'PDBPath'",
":",
"''",
",",
"'SQLDebugging'",
":",
"''",
",",
"'DebuggerFlavor'",
":",
"'0'",
",",
"'MPIRunCommand'",
":",
"''",
",",
"'MPIRunArguments'",
":",
"''",
",",
"'MPIRunWorkingDirectory'",
":",
"''",
",",
"'ApplicationCommand'",
":",
"''",
",",
"'ApplicationArguments'",
":",
"''",
",",
"'ShimCommand'",
":",
"''",
",",
"'MPIAcceptMode'",
":",
"''",
",",
"'MPIAcceptFilter'",
":",
"''",
"}",
"]",
"# Find the config, and add it if it doesn't exist.",
"if",
"config_name",
"not",
"in",
"self",
".",
"configurations",
":",
"self",
".",
"AddConfig",
"(",
"config_name",
")",
"# Add the DebugSettings onto the appropriate config.",
"self",
".",
"configurations",
"[",
"config_name",
"]",
".",
"append",
"(",
"n_cmd",
")"
] | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSUserFile.py#L78-L133 | ||
microsoft/EdgeML | ef9f8a77f096acbdeb941014791f8eda1c1bc35b | examples/pytorch/DROCC/main_timeseries.py | python | adjust_learning_rate | (epoch, total_epochs, only_ce_epochs, learning_rate, optimizer) | return optimizer | Adjust learning rate during training.
Parameters
----------
epoch: Current training epoch.
total_epochs: Total number of epochs for training.
only_ce_epochs: Number of epochs for initial pretraining.
learning_rate: Initial learning rate for training. | Adjust learning rate during training. | [
"Adjust",
"learning",
"rate",
"during",
"training",
"."
] | def adjust_learning_rate(epoch, total_epochs, only_ce_epochs, learning_rate, optimizer):
"""Adjust learning rate during training.
Parameters
----------
epoch: Current training epoch.
total_epochs: Total number of epochs for training.
only_ce_epochs: Number of epochs for initial pretraining.
learning_rate: Initial learning rate for training.
"""
#We dont want to consider the only ce
#based epochs for the lr scheduler
epoch = epoch - only_ce_epochs
drocc_epochs = total_epochs - only_ce_epochs
# lr = learning_rate
if epoch <= drocc_epochs:
lr = learning_rate * 0.1
if epoch <= 0.50 * drocc_epochs:
lr = learning_rate
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return optimizer | [
"def",
"adjust_learning_rate",
"(",
"epoch",
",",
"total_epochs",
",",
"only_ce_epochs",
",",
"learning_rate",
",",
"optimizer",
")",
":",
"#We dont want to consider the only ce ",
"#based epochs for the lr scheduler",
"epoch",
"=",
"epoch",
"-",
"only_ce_epochs",
"drocc_epochs",
"=",
"total_epochs",
"-",
"only_ce_epochs",
"# lr = learning_rate",
"if",
"epoch",
"<=",
"drocc_epochs",
":",
"lr",
"=",
"learning_rate",
"*",
"0.1",
"if",
"epoch",
"<=",
"0.50",
"*",
"drocc_epochs",
":",
"lr",
"=",
"learning_rate",
"for",
"param_group",
"in",
"optimizer",
".",
"param_groups",
":",
"param_group",
"[",
"'lr'",
"]",
"=",
"lr",
"return",
"optimizer"
] | https://github.com/microsoft/EdgeML/blob/ef9f8a77f096acbdeb941014791f8eda1c1bc35b/examples/pytorch/DROCC/main_timeseries.py#L54-L76 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/turtle.py | python | TurtleScreen.screensize | (self, canvwidth=None, canvheight=None, bg=None) | return self._resize(canvwidth, canvheight, bg) | Resize the canvas the turtles are drawing on.
Optional arguments:
canvwidth -- positive integer, new width of canvas in pixels
canvheight -- positive integer, new height of canvas in pixels
bg -- colorstring or color-tuple, new backgroundcolor
If no arguments are given, return current (canvaswidth, canvasheight)
Do not alter the drawing window. To observe hidden parts of
the canvas use the scrollbars. (Can make visible those parts
of a drawing, which were outside the canvas before!)
Example (for a Turtle instance named turtle):
>>> turtle.screensize(2000,1500)
>>> # e. g. to search for an erroneously escaped turtle ;-) | Resize the canvas the turtles are drawing on. | [
"Resize",
"the",
"canvas",
"the",
"turtles",
"are",
"drawing",
"on",
"."
] | def screensize(self, canvwidth=None, canvheight=None, bg=None):
"""Resize the canvas the turtles are drawing on.
Optional arguments:
canvwidth -- positive integer, new width of canvas in pixels
canvheight -- positive integer, new height of canvas in pixels
bg -- colorstring or color-tuple, new backgroundcolor
If no arguments are given, return current (canvaswidth, canvasheight)
Do not alter the drawing window. To observe hidden parts of
the canvas use the scrollbars. (Can make visible those parts
of a drawing, which were outside the canvas before!)
Example (for a Turtle instance named turtle):
>>> turtle.screensize(2000,1500)
>>> # e. g. to search for an erroneously escaped turtle ;-)
"""
return self._resize(canvwidth, canvheight, bg) | [
"def",
"screensize",
"(",
"self",
",",
"canvwidth",
"=",
"None",
",",
"canvheight",
"=",
"None",
",",
"bg",
"=",
"None",
")",
":",
"return",
"self",
".",
"_resize",
"(",
"canvwidth",
",",
"canvheight",
",",
"bg",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/turtle.py#L1402-L1419 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32/scripts/regsetup.py | python | LocatePythonCore | (searchPaths) | return installPath, [libPath, corePath] | Locate and validate the core Python directories. Returns a list
of paths that should be used as the core (ie, un-named) portion of
the Python path. | Locate and validate the core Python directories. Returns a list
of paths that should be used as the core (ie, un-named) portion of
the Python path. | [
"Locate",
"and",
"validate",
"the",
"core",
"Python",
"directories",
".",
"Returns",
"a",
"list",
"of",
"paths",
"that",
"should",
"be",
"used",
"as",
"the",
"core",
"(",
"ie",
"un",
"-",
"named",
")",
"portion",
"of",
"the",
"Python",
"path",
"."
] | def LocatePythonCore(searchPaths):
"""Locate and validate the core Python directories. Returns a list
of paths that should be used as the core (ie, un-named) portion of
the Python path.
"""
import os, regutil
currentPath = regutil.GetRegisteredNamedPath(None)
if currentPath:
presearchPaths = currentPath.split(";")
else:
presearchPaths = [os.path.abspath(".")]
libPath = None
for path in presearchPaths:
if FileExists(os.path.join(path, "os.py")):
libPath = path
break
if libPath is None and searchPaths is not None:
libPath = LocatePath("os.py", searchPaths)
if libPath is None:
raise error("The core Python library could not be located.")
corePath = None
suffix = IsDebug()
for path in presearchPaths:
if FileExists(os.path.join(path, "unicodedata%s.pyd" % suffix)):
corePath = path
break
if corePath is None and searchPaths is not None:
corePath = LocatePath("unicodedata%s.pyd" % suffix, searchPaths)
if corePath is None:
raise error("The core Python path could not be located.")
installPath = os.path.abspath(os.path.join(libPath, ".."))
return installPath, [libPath, corePath] | [
"def",
"LocatePythonCore",
"(",
"searchPaths",
")",
":",
"import",
"os",
",",
"regutil",
"currentPath",
"=",
"regutil",
".",
"GetRegisteredNamedPath",
"(",
"None",
")",
"if",
"currentPath",
":",
"presearchPaths",
"=",
"currentPath",
".",
"split",
"(",
"\";\"",
")",
"else",
":",
"presearchPaths",
"=",
"[",
"os",
".",
"path",
".",
"abspath",
"(",
"\".\"",
")",
"]",
"libPath",
"=",
"None",
"for",
"path",
"in",
"presearchPaths",
":",
"if",
"FileExists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"os.py\"",
")",
")",
":",
"libPath",
"=",
"path",
"break",
"if",
"libPath",
"is",
"None",
"and",
"searchPaths",
"is",
"not",
"None",
":",
"libPath",
"=",
"LocatePath",
"(",
"\"os.py\"",
",",
"searchPaths",
")",
"if",
"libPath",
"is",
"None",
":",
"raise",
"error",
"(",
"\"The core Python library could not be located.\"",
")",
"corePath",
"=",
"None",
"suffix",
"=",
"IsDebug",
"(",
")",
"for",
"path",
"in",
"presearchPaths",
":",
"if",
"FileExists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"unicodedata%s.pyd\"",
"%",
"suffix",
")",
")",
":",
"corePath",
"=",
"path",
"break",
"if",
"corePath",
"is",
"None",
"and",
"searchPaths",
"is",
"not",
"None",
":",
"corePath",
"=",
"LocatePath",
"(",
"\"unicodedata%s.pyd\"",
"%",
"suffix",
",",
"searchPaths",
")",
"if",
"corePath",
"is",
"None",
":",
"raise",
"error",
"(",
"\"The core Python path could not be located.\"",
")",
"installPath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"libPath",
",",
"\"..\"",
")",
")",
"return",
"installPath",
",",
"[",
"libPath",
",",
"corePath",
"]"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32/scripts/regsetup.py#L201-L234 | |
jsupancic/deep_hand_pose | 22cbeae1a8410ff5d37c060c7315719d0a5d608f | scripts/cpp_lint.py | python | CheckSpacingForFunctionCall | (filename, line, linenum, error) | Checks for the correctness of various spacing around function calls.
Args:
filename: The name of the current file.
line: The text of the line to check.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks for the correctness of various spacing around function calls. | [
"Checks",
"for",
"the",
"correctness",
"of",
"various",
"spacing",
"around",
"function",
"calls",
"."
] | def CheckSpacingForFunctionCall(filename, line, linenum, error):
"""Checks for the correctness of various spacing around function calls.
Args:
filename: The name of the current file.
line: The text of the line to check.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Since function calls often occur inside if/for/while/switch
# expressions - which have their own, more liberal conventions - we
# first see if we should be looking inside such an expression for a
# function call, to which we can apply more strict standards.
fncall = line # if there's no control flow construct, look at whole line
for pattern in (r'\bif\s*\((.*)\)\s*{',
r'\bfor\s*\((.*)\)\s*{',
r'\bwhile\s*\((.*)\)\s*[{;]',
r'\bswitch\s*\((.*)\)\s*{'):
match = Search(pattern, line)
if match:
fncall = match.group(1) # look inside the parens for function calls
break
# Except in if/for/while/switch, there should never be space
# immediately inside parens (eg "f( 3, 4 )"). We make an exception
# for nested parens ( (a+b) + c ). Likewise, there should never be
# a space before a ( when it's a function argument. I assume it's a
# function argument when the char before the whitespace is legal in
# a function name (alnum + _) and we're not starting a macro. Also ignore
# pointers and references to arrays and functions coz they're too tricky:
# we use a very simple way to recognize these:
# " (something)(maybe-something)" or
# " (something)(maybe-something," or
# " (something)[something]"
# Note that we assume the contents of [] to be short enough that
# they'll never need to wrap.
if ( # Ignore control structures.
not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',
fncall) and
# Ignore pointers/references to functions.
not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
# Ignore pointers/references to arrays.
not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
error(filename, linenum, 'whitespace/parens', 4,
'Extra space after ( in function call')
elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
error(filename, linenum, 'whitespace/parens', 2,
'Extra space after (')
if (Search(r'\w\s+\(', fncall) and
not Search(r'#\s*define|typedef', fncall) and
not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall)):
error(filename, linenum, 'whitespace/parens', 4,
'Extra space before ( in function call')
# If the ) is followed only by a newline or a { + newline, assume it's
# part of a control statement (if/while/etc), and don't complain
if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
# If the closing parenthesis is preceded by only whitespaces,
# try to give a more descriptive error message.
if Search(r'^\s+\)', fncall):
error(filename, linenum, 'whitespace/parens', 2,
'Closing ) should be moved to the previous line')
else:
error(filename, linenum, 'whitespace/parens', 2,
'Extra space before )') | [
"def",
"CheckSpacingForFunctionCall",
"(",
"filename",
",",
"line",
",",
"linenum",
",",
"error",
")",
":",
"# Since function calls often occur inside if/for/while/switch",
"# expressions - which have their own, more liberal conventions - we",
"# first see if we should be looking inside such an expression for a",
"# function call, to which we can apply more strict standards.",
"fncall",
"=",
"line",
"# if there's no control flow construct, look at whole line",
"for",
"pattern",
"in",
"(",
"r'\\bif\\s*\\((.*)\\)\\s*{'",
",",
"r'\\bfor\\s*\\((.*)\\)\\s*{'",
",",
"r'\\bwhile\\s*\\((.*)\\)\\s*[{;]'",
",",
"r'\\bswitch\\s*\\((.*)\\)\\s*{'",
")",
":",
"match",
"=",
"Search",
"(",
"pattern",
",",
"line",
")",
"if",
"match",
":",
"fncall",
"=",
"match",
".",
"group",
"(",
"1",
")",
"# look inside the parens for function calls",
"break",
"# Except in if/for/while/switch, there should never be space",
"# immediately inside parens (eg \"f( 3, 4 )\"). We make an exception",
"# for nested parens ( (a+b) + c ). Likewise, there should never be",
"# a space before a ( when it's a function argument. I assume it's a",
"# function argument when the char before the whitespace is legal in",
"# a function name (alnum + _) and we're not starting a macro. Also ignore",
"# pointers and references to arrays and functions coz they're too tricky:",
"# we use a very simple way to recognize these:",
"# \" (something)(maybe-something)\" or",
"# \" (something)(maybe-something,\" or",
"# \" (something)[something]\"",
"# Note that we assume the contents of [] to be short enough that",
"# they'll never need to wrap.",
"if",
"(",
"# Ignore control structures.",
"not",
"Search",
"(",
"r'\\b(if|for|while|switch|return|new|delete|catch|sizeof)\\b'",
",",
"fncall",
")",
"and",
"# Ignore pointers/references to functions.",
"not",
"Search",
"(",
"r' \\([^)]+\\)\\([^)]*(\\)|,$)'",
",",
"fncall",
")",
"and",
"# Ignore pointers/references to arrays.",
"not",
"Search",
"(",
"r' \\([^)]+\\)\\[[^\\]]+\\]'",
",",
"fncall",
")",
")",
":",
"if",
"Search",
"(",
"r'\\w\\s*\\(\\s(?!\\s*\\\\$)'",
",",
"fncall",
")",
":",
"# a ( used for a fn call",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"4",
",",
"'Extra space after ( in function call'",
")",
"elif",
"Search",
"(",
"r'\\(\\s+(?!(\\s*\\\\)|\\()'",
",",
"fncall",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"2",
",",
"'Extra space after ('",
")",
"if",
"(",
"Search",
"(",
"r'\\w\\s+\\('",
",",
"fncall",
")",
"and",
"not",
"Search",
"(",
"r'#\\s*define|typedef'",
",",
"fncall",
")",
"and",
"not",
"Search",
"(",
"r'\\w\\s+\\((\\w+::)*\\*\\w+\\)\\('",
",",
"fncall",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"4",
",",
"'Extra space before ( in function call'",
")",
"# If the ) is followed only by a newline or a { + newline, assume it's",
"# part of a control statement (if/while/etc), and don't complain",
"if",
"Search",
"(",
"r'[^)]\\s+\\)\\s*[^{\\s]'",
",",
"fncall",
")",
":",
"# If the closing parenthesis is preceded by only whitespaces,",
"# try to give a more descriptive error message.",
"if",
"Search",
"(",
"r'^\\s+\\)'",
",",
"fncall",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"2",
",",
"'Closing ) should be moved to the previous line'",
")",
"else",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"2",
",",
"'Extra space before )'",
")"
] | https://github.com/jsupancic/deep_hand_pose/blob/22cbeae1a8410ff5d37c060c7315719d0a5d608f/scripts/cpp_lint.py#L2301-L2366 | ||
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | v8_4_5/PRESUBMIT.py | python | _CommonChecks | (input_api, output_api) | return results | Checks common to both upload and commit. | Checks common to both upload and commit. | [
"Checks",
"common",
"to",
"both",
"upload",
"and",
"commit",
"."
] | def _CommonChecks(input_api, output_api):
"""Checks common to both upload and commit."""
results = []
results.extend(input_api.canned_checks.CheckOwners(
input_api, output_api, source_file_filter=None))
results.extend(input_api.canned_checks.CheckPatchFormatted(
input_api, output_api))
results.extend(_V8PresubmitChecks(input_api, output_api))
results.extend(_CheckUnwantedDependencies(input_api, output_api))
results.extend(
_CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api))
return results | [
"def",
"_CommonChecks",
"(",
"input_api",
",",
"output_api",
")",
":",
"results",
"=",
"[",
"]",
"results",
".",
"extend",
"(",
"input_api",
".",
"canned_checks",
".",
"CheckOwners",
"(",
"input_api",
",",
"output_api",
",",
"source_file_filter",
"=",
"None",
")",
")",
"results",
".",
"extend",
"(",
"input_api",
".",
"canned_checks",
".",
"CheckPatchFormatted",
"(",
"input_api",
",",
"output_api",
")",
")",
"results",
".",
"extend",
"(",
"_V8PresubmitChecks",
"(",
"input_api",
",",
"output_api",
")",
")",
"results",
".",
"extend",
"(",
"_CheckUnwantedDependencies",
"(",
"input_api",
",",
"output_api",
")",
")",
"results",
".",
"extend",
"(",
"_CheckNoProductionCodeUsingTestOnlyFunctions",
"(",
"input_api",
",",
"output_api",
")",
")",
"return",
"results"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/v8_4_5/PRESUBMIT.py#L187-L198 | |
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/tools/gyp/pylib/gyp/ordered_dict.py | python | OrderedDict.keys | (self) | return list(self) | od.keys() -> list of keys in od | od.keys() -> list of keys in od | [
"od",
".",
"keys",
"()",
"-",
">",
"list",
"of",
"keys",
"in",
"od"
] | def keys(self):
'od.keys() -> list of keys in od'
return list(self) | [
"def",
"keys",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
")"
] | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/ordered_dict.py#L143-L145 | |
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/boost_1.75.0/tools/build/src/build/property.py | python | PropertyMap.insert | (self, properties, value) | Associate value with properties. | Associate value with properties. | [
"Associate",
"value",
"with",
"properties",
"."
] | def insert (self, properties, value):
""" Associate value with properties.
"""
assert is_iterable_typed(properties, basestring)
assert isinstance(value, basestring)
self.__properties.append(properties)
self.__values.append(value) | [
"def",
"insert",
"(",
"self",
",",
"properties",
",",
"value",
")",
":",
"assert",
"is_iterable_typed",
"(",
"properties",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"value",
",",
"basestring",
")",
"self",
".",
"__properties",
".",
"append",
"(",
"properties",
")",
"self",
".",
"__values",
".",
"append",
"(",
"value",
")"
] | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/boost_1.75.0/tools/build/src/build/property.py#L590-L596 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/dataset/engine/datasets.py | python | Schema.from_json | (self, json_obj) | Get schema file from JSON object.
Args:
json_obj(dictionary): Object of JSON parsed.
Raises:
RuntimeError: if there is unknown item in the object.
RuntimeError: if dataset type is missing in the object.
RuntimeError: if columns are missing in the object. | Get schema file from JSON object. | [
"Get",
"schema",
"file",
"from",
"JSON",
"object",
"."
] | def from_json(self, json_obj):
"""
Get schema file from JSON object.
Args:
json_obj(dictionary): Object of JSON parsed.
Raises:
RuntimeError: if there is unknown item in the object.
RuntimeError: if dataset type is missing in the object.
RuntimeError: if columns are missing in the object.
"""
self.cpp_schema.from_string(json.dumps(json_obj, indent=2)) | [
"def",
"from_json",
"(",
"self",
",",
"json_obj",
")",
":",
"self",
".",
"cpp_schema",
".",
"from_string",
"(",
"json",
".",
"dumps",
"(",
"json_obj",
",",
"indent",
"=",
"2",
")",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/engine/datasets.py#L6360-L6372 | ||
perilouswithadollarsign/cstrike15_src | f82112a2388b841d72cb62ca48ab1846dfcc11c8 | thirdparty/protobuf-2.5.0/python/google/protobuf/descriptor_pool.py | python | DescriptorPool.FindMessageTypeByName | (self, full_name) | return self._descriptors[full_name] | Loads the named descriptor from the pool.
Args:
full_name: The full name of the descriptor to load.
Returns:
The descriptor for the named type. | Loads the named descriptor from the pool. | [
"Loads",
"the",
"named",
"descriptor",
"from",
"the",
"pool",
"."
] | def FindMessageTypeByName(self, full_name):
"""Loads the named descriptor from the pool.
Args:
full_name: The full name of the descriptor to load.
Returns:
The descriptor for the named type.
"""
full_name = full_name.lstrip('.') # fix inconsistent qualified name formats
if full_name not in self._descriptors:
self.FindFileContainingSymbol(full_name)
return self._descriptors[full_name] | [
"def",
"FindMessageTypeByName",
"(",
"self",
",",
"full_name",
")",
":",
"full_name",
"=",
"full_name",
".",
"lstrip",
"(",
"'.'",
")",
"# fix inconsistent qualified name formats",
"if",
"full_name",
"not",
"in",
"self",
".",
"_descriptors",
":",
"self",
".",
"FindFileContainingSymbol",
"(",
"full_name",
")",
"return",
"self",
".",
"_descriptors",
"[",
"full_name",
"]"
] | https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/google/protobuf/descriptor_pool.py#L140-L153 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/PyShell.py | python | PyShell.endexecuting | (self) | Helper for ModifiedInterpreter | Helper for ModifiedInterpreter | [
"Helper",
"for",
"ModifiedInterpreter"
] | def endexecuting(self):
"Helper for ModifiedInterpreter"
self.executing = 0
self.canceled = 0
self.showprompt() | [
"def",
"endexecuting",
"(",
"self",
")",
":",
"self",
".",
"executing",
"=",
"0",
"self",
".",
"canceled",
"=",
"0",
"self",
".",
"showprompt",
"(",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/PyShell.py#L972-L976 | ||
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | pygimli/physics/ert/ertModelling.py | python | ERTModelling.createJacobian | (self, mod) | return self._core.createJacobian(mod) | Compute Jacobian matrix and store but not return. | Compute Jacobian matrix and store but not return. | [
"Compute",
"Jacobian",
"matrix",
"and",
"store",
"but",
"not",
"return",
"."
] | def createJacobian(self, mod):
"""Compute Jacobian matrix and store but not return."""
# ensure the mesh is initialized
self.mesh()
if self.complex():
if self._conjImag:
pg.warn("Flipping imaginary part for jacobian calc")
mod = self.flipImagPart(mod)
self._core.createJacobian(mod)
self._J = pg.utils.squeezeComplex(self._core.jacobian(),
conj=self._conjImag
)
self.setJacobian(self._J)
# pg._r("create Jacobian", self, self._J)
return self._J
return self._core.createJacobian(mod) | [
"def",
"createJacobian",
"(",
"self",
",",
"mod",
")",
":",
"# ensure the mesh is initialized",
"self",
".",
"mesh",
"(",
")",
"if",
"self",
".",
"complex",
"(",
")",
":",
"if",
"self",
".",
"_conjImag",
":",
"pg",
".",
"warn",
"(",
"\"Flipping imaginary part for jacobian calc\"",
")",
"mod",
"=",
"self",
".",
"flipImagPart",
"(",
"mod",
")",
"self",
".",
"_core",
".",
"createJacobian",
"(",
"mod",
")",
"self",
".",
"_J",
"=",
"pg",
".",
"utils",
".",
"squeezeComplex",
"(",
"self",
".",
"_core",
".",
"jacobian",
"(",
")",
",",
"conj",
"=",
"self",
".",
"_conjImag",
")",
"self",
".",
"setJacobian",
"(",
"self",
".",
"_J",
")",
"# pg._r(\"create Jacobian\", self, self._J)",
"return",
"self",
".",
"_J",
"return",
"self",
".",
"_core",
".",
"createJacobian",
"(",
"mod",
")"
] | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/ert/ertModelling.py#L156-L173 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/security/fuzzing/python_fuzzing.py | python | FuzzingHelper.get_random_numeric_tensor | (self,
dtype=None,
min_size=_MIN_SIZE,
max_size=_MAX_SIZE,
min_val=_MIN_INT,
max_val=_MAX_INT) | return tf.random.uniform(
shape=shape, minval=min_val, maxval=max_val, dtype=dtype, seed=seed) | Return a tensor of random shape and values.
Generated tensors are capped at dimension sizes of 8, as 2^32 bytes of
requested memory crashes the fuzzer (see b/34190148).
Returns only type that tf.random.uniform can generate. If you need a
different type, consider using tf.cast.
Args:
dtype: Type of tensor, must of one of the following types: float16,
float32, float64, int32, or int64
min_size: Minimum size of returned tensor
max_size: Maximum size of returned tensor
min_val: Minimum value in returned tensor
max_val: Maximum value in returned tensor
Returns:
Tensor of random shape filled with uniformly random numeric values. | Return a tensor of random shape and values. | [
"Return",
"a",
"tensor",
"of",
"random",
"shape",
"and",
"values",
"."
] | def get_random_numeric_tensor(self,
dtype=None,
min_size=_MIN_SIZE,
max_size=_MAX_SIZE,
min_val=_MIN_INT,
max_val=_MAX_INT):
"""Return a tensor of random shape and values.
Generated tensors are capped at dimension sizes of 8, as 2^32 bytes of
requested memory crashes the fuzzer (see b/34190148).
Returns only type that tf.random.uniform can generate. If you need a
different type, consider using tf.cast.
Args:
dtype: Type of tensor, must of one of the following types: float16,
float32, float64, int32, or int64
min_size: Minimum size of returned tensor
max_size: Maximum size of returned tensor
min_val: Minimum value in returned tensor
max_val: Maximum value in returned tensor
Returns:
Tensor of random shape filled with uniformly random numeric values.
"""
# Max shape can be 8 in length and randomized from 0-8 without running into
# an OOM error.
if max_size > 8:
raise tf.errors.InvalidArgumentError(
None, None,
'Given size of {} will result in an OOM error'.format(max_size))
seed = self.get_int()
shape = self.get_int_list(
min_length=min_size,
max_length=max_size,
min_int=min_size,
max_int=max_size)
if dtype is None:
dtype = self.get_tf_dtype(allowed_set=_TF_RANDOM_DTYPES)
elif dtype not in _TF_RANDOM_DTYPES:
raise tf.errors.InvalidArgumentError(
None, None,
'Given dtype {} is not accepted in get_random_numeric_tensor'.format(
dtype))
return tf.random.uniform(
shape=shape, minval=min_val, maxval=max_val, dtype=dtype, seed=seed) | [
"def",
"get_random_numeric_tensor",
"(",
"self",
",",
"dtype",
"=",
"None",
",",
"min_size",
"=",
"_MIN_SIZE",
",",
"max_size",
"=",
"_MAX_SIZE",
",",
"min_val",
"=",
"_MIN_INT",
",",
"max_val",
"=",
"_MAX_INT",
")",
":",
"# Max shape can be 8 in length and randomized from 0-8 without running into",
"# an OOM error.",
"if",
"max_size",
">",
"8",
":",
"raise",
"tf",
".",
"errors",
".",
"InvalidArgumentError",
"(",
"None",
",",
"None",
",",
"'Given size of {} will result in an OOM error'",
".",
"format",
"(",
"max_size",
")",
")",
"seed",
"=",
"self",
".",
"get_int",
"(",
")",
"shape",
"=",
"self",
".",
"get_int_list",
"(",
"min_length",
"=",
"min_size",
",",
"max_length",
"=",
"max_size",
",",
"min_int",
"=",
"min_size",
",",
"max_int",
"=",
"max_size",
")",
"if",
"dtype",
"is",
"None",
":",
"dtype",
"=",
"self",
".",
"get_tf_dtype",
"(",
"allowed_set",
"=",
"_TF_RANDOM_DTYPES",
")",
"elif",
"dtype",
"not",
"in",
"_TF_RANDOM_DTYPES",
":",
"raise",
"tf",
".",
"errors",
".",
"InvalidArgumentError",
"(",
"None",
",",
"None",
",",
"'Given dtype {} is not accepted in get_random_numeric_tensor'",
".",
"format",
"(",
"dtype",
")",
")",
"return",
"tf",
".",
"random",
".",
"uniform",
"(",
"shape",
"=",
"shape",
",",
"minval",
"=",
"min_val",
",",
"maxval",
"=",
"max_val",
",",
"dtype",
"=",
"dtype",
",",
"seed",
"=",
"seed",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/security/fuzzing/python_fuzzing.py#L169-L216 | |
KratosMultiphysics/Kratos | 0000833054ed0503424eb28205d6508d9ca6cbbc | applications/MultilevelMonteCarloApplication/external_libraries/XMC/xmc/classDefs_solverWrapper/oscillator.py | python | VanDerPol.trajectory | (self, forcing: Optional[List[float]] = None) | return x.tolist() | Trajectory of the oscillator, with given forcing.
Solves the oscillator problem with forward Euler scheme and uniform temporal mesh.
:param forcing: list of values of external forcing, as discretised on :py:attr:`~.VanDerPol.mesh` (must have same length). If `None`, no forcing is applied.
:return: values of position at times of :py:attr:`~.VanDerPol.mesh`. | Trajectory of the oscillator, with given forcing. | [
"Trajectory",
"of",
"the",
"oscillator",
"with",
"given",
"forcing",
"."
] | def trajectory(self, forcing: Optional[List[float]] = None) -> List[float]:
"""Trajectory of the oscillator, with given forcing.
Solves the oscillator problem with forward Euler scheme and uniform temporal mesh.
:param forcing: list of values of external forcing, as discretised on :py:attr:`~.VanDerPol.mesh` (must have same length). If `None`, no forcing is applied.
:return: values of position at times of :py:attr:`~.VanDerPol.mesh`.
"""
# Shorthands
dt = self.timestep
nb_dt = self._numberTimesteps()
damping = self.damping
# Process optional input argument
if forcing:
forcing_factor = self.forcingAmplitude * np.sqrt(dt)
else:
forcing_factor = 0
forcing = np.zeros(nb_dt)
x = np.zeros(nb_dt)
dx = np.zeros(len(x))
# Initialize
x[0], dx[0] = self.initial
# Solve iteratively
for n in range(nb_dt - 1):
x[n + 1] = x[n] + dt * dx[n]
dx[n + 1] = (
dx[n]
+ dt * (damping * dx[n] * (1 - x[n] ** 2) - x[n])
+ forcing_factor * forcing[n]
)
return x.tolist() | [
"def",
"trajectory",
"(",
"self",
",",
"forcing",
":",
"Optional",
"[",
"List",
"[",
"float",
"]",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"float",
"]",
":",
"# Shorthands",
"dt",
"=",
"self",
".",
"timestep",
"nb_dt",
"=",
"self",
".",
"_numberTimesteps",
"(",
")",
"damping",
"=",
"self",
".",
"damping",
"# Process optional input argument",
"if",
"forcing",
":",
"forcing_factor",
"=",
"self",
".",
"forcingAmplitude",
"*",
"np",
".",
"sqrt",
"(",
"dt",
")",
"else",
":",
"forcing_factor",
"=",
"0",
"forcing",
"=",
"np",
".",
"zeros",
"(",
"nb_dt",
")",
"x",
"=",
"np",
".",
"zeros",
"(",
"nb_dt",
")",
"dx",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"x",
")",
")",
"# Initialize",
"x",
"[",
"0",
"]",
",",
"dx",
"[",
"0",
"]",
"=",
"self",
".",
"initial",
"# Solve iteratively",
"for",
"n",
"in",
"range",
"(",
"nb_dt",
"-",
"1",
")",
":",
"x",
"[",
"n",
"+",
"1",
"]",
"=",
"x",
"[",
"n",
"]",
"+",
"dt",
"*",
"dx",
"[",
"n",
"]",
"dx",
"[",
"n",
"+",
"1",
"]",
"=",
"(",
"dx",
"[",
"n",
"]",
"+",
"dt",
"*",
"(",
"damping",
"*",
"dx",
"[",
"n",
"]",
"*",
"(",
"1",
"-",
"x",
"[",
"n",
"]",
"**",
"2",
")",
"-",
"x",
"[",
"n",
"]",
")",
"+",
"forcing_factor",
"*",
"forcing",
"[",
"n",
"]",
")",
"return",
"x",
".",
"tolist",
"(",
")"
] | https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/MultilevelMonteCarloApplication/external_libraries/XMC/xmc/classDefs_solverWrapper/oscillator.py#L145-L177 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/cookielib.py | python | CookiePolicy.path_return_ok | (self, path, request) | return True | Return false if cookies should not be returned, given cookie path. | Return false if cookies should not be returned, given cookie path. | [
"Return",
"false",
"if",
"cookies",
"should",
"not",
"be",
"returned",
"given",
"cookie",
"path",
"."
] | def path_return_ok(self, path, request):
"""Return false if cookies should not be returned, given cookie path.
"""
return True | [
"def",
"path_return_ok",
"(",
"self",
",",
"path",
",",
"request",
")",
":",
"return",
"True"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/cookielib.py#L832-L835 | |
mysql/mysql-workbench | 2f35f9034f015cbcd22139a60e1baa2e3e8e795c | modules/db.generic/db_generic_re_grt.py | python | GenericReverseEngineering.find_datatype_object | (cls, catalog, datatype_name) | return (False, None) | Finds the datatype object corresponding to the given datatype name.
Returns: a tuple of the form (is_simple_datatype, datatype) where:
is_simple_datatype: True if the datatype was found among the simple datatypes for
its corresponding RDBMS
datatype: The actual datatype object. None if not found | Finds the datatype object corresponding to the given datatype name. | [
"Finds",
"the",
"datatype",
"object",
"corresponding",
"to",
"the",
"given",
"datatype",
"name",
"."
] | def find_datatype_object(cls, catalog, datatype_name):
''' Finds the datatype object corresponding to the given datatype name.
Returns: a tuple of the form (is_simple_datatype, datatype) where:
is_simple_datatype: True if the datatype was found among the simple datatypes for
its corresponding RDBMS
datatype: The actual datatype object. None if not found
'''
simple_types = cls._rdbms.simpleDatatypes
user_types = catalog.userDatatypes
for simple_type in simple_types:
if datatype_name == simple_type.name or datatype_name in simple_type.synonyms:
return (True, simple_type)
for user_type in user_types:
if datatype_name == user_type.name:
return (False, user_type)
return (False, None) | [
"def",
"find_datatype_object",
"(",
"cls",
",",
"catalog",
",",
"datatype_name",
")",
":",
"simple_types",
"=",
"cls",
".",
"_rdbms",
".",
"simpleDatatypes",
"user_types",
"=",
"catalog",
".",
"userDatatypes",
"for",
"simple_type",
"in",
"simple_types",
":",
"if",
"datatype_name",
"==",
"simple_type",
".",
"name",
"or",
"datatype_name",
"in",
"simple_type",
".",
"synonyms",
":",
"return",
"(",
"True",
",",
"simple_type",
")",
"for",
"user_type",
"in",
"user_types",
":",
"if",
"datatype_name",
"==",
"user_type",
".",
"name",
":",
"return",
"(",
"False",
",",
"user_type",
")",
"return",
"(",
"False",
",",
"None",
")"
] | https://github.com/mysql/mysql-workbench/blob/2f35f9034f015cbcd22139a60e1baa2e3e8e795c/modules/db.generic/db_generic_re_grt.py#L48-L64 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py3/IPython/core/inputtransformer2.py | python | HelpEnd.find | (cls, tokens_by_line) | Find the first help command (foo?) in the cell. | Find the first help command (foo?) in the cell. | [
"Find",
"the",
"first",
"help",
"command",
"(",
"foo?",
")",
"in",
"the",
"cell",
"."
] | def find(cls, tokens_by_line):
"""Find the first help command (foo?) in the cell.
"""
for line in tokens_by_line:
# Last token is NEWLINE; look at last but one
if len(line) > 2 and line[-2].string == '?':
# Find the first token that's not INDENT/DEDENT
ix = 0
while line[ix].type in {tokenize.INDENT, tokenize.DEDENT}:
ix += 1
return cls(line[ix].start, line[-2].start) | [
"def",
"find",
"(",
"cls",
",",
"tokens_by_line",
")",
":",
"for",
"line",
"in",
"tokens_by_line",
":",
"# Last token is NEWLINE; look at last but one",
"if",
"len",
"(",
"line",
")",
">",
"2",
"and",
"line",
"[",
"-",
"2",
"]",
".",
"string",
"==",
"'?'",
":",
"# Find the first token that's not INDENT/DEDENT",
"ix",
"=",
"0",
"while",
"line",
"[",
"ix",
"]",
".",
"type",
"in",
"{",
"tokenize",
".",
"INDENT",
",",
"tokenize",
".",
"DEDENT",
"}",
":",
"ix",
"+=",
"1",
"return",
"cls",
"(",
"line",
"[",
"ix",
"]",
".",
"start",
",",
"line",
"[",
"-",
"2",
"]",
".",
"start",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/inputtransformer2.py#L432-L442 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/propgrid.py | python | PropertyGrid.GetSortFunction | (*args, **kwargs) | return _propgrid.PropertyGrid_GetSortFunction(*args, **kwargs) | GetSortFunction(self) -> PGSortCallback | GetSortFunction(self) -> PGSortCallback | [
"GetSortFunction",
"(",
"self",
")",
"-",
">",
"PGSortCallback"
] | def GetSortFunction(*args, **kwargs):
"""GetSortFunction(self) -> PGSortCallback"""
return _propgrid.PropertyGrid_GetSortFunction(*args, **kwargs) | [
"def",
"GetSortFunction",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGrid_GetSortFunction",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L2284-L2286 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/training/saver.py | python | _get_saver_or_default | () | return saver | Returns the saver from SAVERS collection, or creates a default one.
This method is used by other members of the training module, such as
`Scaffold`, or `CheckpointSaverHook`.
Returns:
`Saver`.
Raises:
RuntimeError: If the SAVERS collection already has more than one items. | Returns the saver from SAVERS collection, or creates a default one. | [
"Returns",
"the",
"saver",
"from",
"SAVERS",
"collection",
"or",
"creates",
"a",
"default",
"one",
"."
] | def _get_saver_or_default():
"""Returns the saver from SAVERS collection, or creates a default one.
This method is used by other members of the training module, such as
`Scaffold`, or `CheckpointSaverHook`.
Returns:
`Saver`.
Raises:
RuntimeError: If the SAVERS collection already has more than one items.
"""
collection_key = ops.GraphKeys.SAVERS
savers = ops.get_collection(collection_key)
if savers:
if len(savers) > 1:
raise RuntimeError(
"More than one item in collection {}. "
"Please indicate which one to use by passing it to the constructor."
.format(collection_key))
return savers[0]
saver = Saver(sharded=True, allow_empty=True)
if saver is not None:
ops.add_to_collection(collection_key, saver)
return saver | [
"def",
"_get_saver_or_default",
"(",
")",
":",
"collection_key",
"=",
"ops",
".",
"GraphKeys",
".",
"SAVERS",
"savers",
"=",
"ops",
".",
"get_collection",
"(",
"collection_key",
")",
"if",
"savers",
":",
"if",
"len",
"(",
"savers",
")",
">",
"1",
":",
"raise",
"RuntimeError",
"(",
"\"More than one item in collection {}. \"",
"\"Please indicate which one to use by passing it to the constructor.\"",
".",
"format",
"(",
"collection_key",
")",
")",
"return",
"savers",
"[",
"0",
"]",
"saver",
"=",
"Saver",
"(",
"sharded",
"=",
"True",
",",
"allow_empty",
"=",
"True",
")",
"if",
"saver",
"is",
"not",
"None",
":",
"ops",
".",
"add_to_collection",
"(",
"collection_key",
",",
"saver",
")",
"return",
"saver"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/training/saver.py#L614-L638 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/asyncio/base_events.py | python | BaseEventLoop._make_write_pipe_transport | (self, pipe, protocol, waiter=None,
extra=None) | Create write pipe transport. | Create write pipe transport. | [
"Create",
"write",
"pipe",
"transport",
"."
] | def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
extra=None):
"""Create write pipe transport."""
raise NotImplementedError | [
"def",
"_make_write_pipe_transport",
"(",
"self",
",",
"pipe",
",",
"protocol",
",",
"waiter",
"=",
"None",
",",
"extra",
"=",
"None",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/asyncio/base_events.py#L453-L456 | ||
intel/ros_object_analytics | eb0208edbb6da67e5d5c4092fd2964a2c8d9838e | object_analytics_visualization/scripts/marker_publisher.py | python | ObjectItem.min_text | (self) | return text | Build text marker to hold min text | Build text marker to hold min text | [
"Build",
"text",
"marker",
"to",
"hold",
"min",
"text"
] | def min_text(self):
"""Build text marker to hold min text
"""
text = Marker()
text.header = self._header
text.type = Marker.TEXT_VIEW_FACING
text.action = Marker.ADD
text.scale.z = 0.05
text.color = self.GREEN
text.pose = deepcopy(self.POSE)
text.pose.position = deepcopy(self._p1)
text.text = "Min[{:.2f} {:.2f} {:.2f}]".format(self._p1.x, self._p1.y, self._p1.z)
return text | [
"def",
"min_text",
"(",
"self",
")",
":",
"text",
"=",
"Marker",
"(",
")",
"text",
".",
"header",
"=",
"self",
".",
"_header",
"text",
".",
"type",
"=",
"Marker",
".",
"TEXT_VIEW_FACING",
"text",
".",
"action",
"=",
"Marker",
".",
"ADD",
"text",
".",
"scale",
".",
"z",
"=",
"0.05",
"text",
".",
"color",
"=",
"self",
".",
"GREEN",
"text",
".",
"pose",
"=",
"deepcopy",
"(",
"self",
".",
"POSE",
")",
"text",
".",
"pose",
".",
"position",
"=",
"deepcopy",
"(",
"self",
".",
"_p1",
")",
"text",
".",
"text",
"=",
"\"Min[{:.2f} {:.2f} {:.2f}]\"",
".",
"format",
"(",
"self",
".",
"_p1",
".",
"x",
",",
"self",
".",
"_p1",
".",
"y",
",",
"self",
".",
"_p1",
".",
"z",
")",
"return",
"text"
] | https://github.com/intel/ros_object_analytics/blob/eb0208edbb6da67e5d5c4092fd2964a2c8d9838e/object_analytics_visualization/scripts/marker_publisher.py#L129-L141 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/dataset/engine/validators.py | python | check_gnn_get_all_nodes | (method) | return new_method | A wrapper that wraps a parameter checker around the GNN `get_all_nodes` function. | A wrapper that wraps a parameter checker around the GNN `get_all_nodes` function. | [
"A",
"wrapper",
"that",
"wraps",
"a",
"parameter",
"checker",
"around",
"the",
"GNN",
"get_all_nodes",
"function",
"."
] | def check_gnn_get_all_nodes(method):
"""A wrapper that wraps a parameter checker around the GNN `get_all_nodes` function."""
@wraps(method)
def new_method(self, *args, **kwargs):
[node_type], _ = parse_user_args(method, *args, **kwargs)
type_check(node_type, (int,), "node_type")
return method(self, *args, **kwargs)
return new_method | [
"def",
"check_gnn_get_all_nodes",
"(",
"method",
")",
":",
"@",
"wraps",
"(",
"method",
")",
"def",
"new_method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"[",
"node_type",
"]",
",",
"_",
"=",
"parse_user_args",
"(",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"type_check",
"(",
"node_type",
",",
"(",
"int",
",",
")",
",",
"\"node_type\"",
")",
"return",
"method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"new_method"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/engine/validators.py#L1589-L1599 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib2to3/pytree.py | python | WildcardPattern.match | (self, node, results=None) | return self.match_seq([node], results) | Does this pattern exactly match a node? | Does this pattern exactly match a node? | [
"Does",
"this",
"pattern",
"exactly",
"match",
"a",
"node?"
] | def match(self, node, results=None):
"""Does this pattern exactly match a node?"""
return self.match_seq([node], results) | [
"def",
"match",
"(",
"self",
",",
"node",
",",
"results",
"=",
"None",
")",
":",
"return",
"self",
".",
"match_seq",
"(",
"[",
"node",
"]",
",",
"results",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib2to3/pytree.py#L707-L709 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/build/pymake/pymake/parserdata.py | python | parsecommandlineargs | (args) | return stmts, r, ' '.join(overrides) | Given a set of arguments from a command-line invocation of make,
parse out the variable definitions and return (stmts, arglist, overridestr) | Given a set of arguments from a command-line invocation of make,
parse out the variable definitions and return (stmts, arglist, overridestr) | [
"Given",
"a",
"set",
"of",
"arguments",
"from",
"a",
"command",
"-",
"line",
"invocation",
"of",
"make",
"parse",
"out",
"the",
"variable",
"definitions",
"and",
"return",
"(",
"stmts",
"arglist",
"overridestr",
")"
] | def parsecommandlineargs(args):
"""
Given a set of arguments from a command-line invocation of make,
parse out the variable definitions and return (stmts, arglist, overridestr)
"""
overrides = []
stmts = StatementList()
r = []
for i in xrange(0, len(args)):
a = args[i]
vname, t, val = util.strpartition(a, ':=')
if t == '':
vname, t, val = util.strpartition(a, '=')
if t != '':
overrides.append(_flagescape.sub(r'\\\1', a))
vname = vname.strip()
vnameexp = data.Expansion.fromstring(vname, "Command-line argument")
stmts.append(ExportDirective(vnameexp, concurrent_set=True))
stmts.append(SetVariable(vnameexp, token=t,
value=val, valueloc=Location('<command-line>', i, len(vname) + len(t)),
targetexp=None, source=data.Variables.SOURCE_COMMANDLINE))
else:
r.append(data.stripdotslash(a))
return stmts, r, ' '.join(overrides) | [
"def",
"parsecommandlineargs",
"(",
"args",
")",
":",
"overrides",
"=",
"[",
"]",
"stmts",
"=",
"StatementList",
"(",
")",
"r",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"args",
")",
")",
":",
"a",
"=",
"args",
"[",
"i",
"]",
"vname",
",",
"t",
",",
"val",
"=",
"util",
".",
"strpartition",
"(",
"a",
",",
"':='",
")",
"if",
"t",
"==",
"''",
":",
"vname",
",",
"t",
",",
"val",
"=",
"util",
".",
"strpartition",
"(",
"a",
",",
"'='",
")",
"if",
"t",
"!=",
"''",
":",
"overrides",
".",
"append",
"(",
"_flagescape",
".",
"sub",
"(",
"r'\\\\\\1'",
",",
"a",
")",
")",
"vname",
"=",
"vname",
".",
"strip",
"(",
")",
"vnameexp",
"=",
"data",
".",
"Expansion",
".",
"fromstring",
"(",
"vname",
",",
"\"Command-line argument\"",
")",
"stmts",
".",
"append",
"(",
"ExportDirective",
"(",
"vnameexp",
",",
"concurrent_set",
"=",
"True",
")",
")",
"stmts",
".",
"append",
"(",
"SetVariable",
"(",
"vnameexp",
",",
"token",
"=",
"t",
",",
"value",
"=",
"val",
",",
"valueloc",
"=",
"Location",
"(",
"'<command-line>'",
",",
"i",
",",
"len",
"(",
"vname",
")",
"+",
"len",
"(",
"t",
")",
")",
",",
"targetexp",
"=",
"None",
",",
"source",
"=",
"data",
".",
"Variables",
".",
"SOURCE_COMMANDLINE",
")",
")",
"else",
":",
"r",
".",
"append",
"(",
"data",
".",
"stripdotslash",
"(",
"a",
")",
")",
"return",
"stmts",
",",
"r",
",",
"' '",
".",
"join",
"(",
"overrides",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/build/pymake/pymake/parserdata.py#L70-L98 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/champagne-tower.py | python | Solution.champagneTower | (self, poured, query_row, query_glass) | return min(result[query_glass], 1) | :type poured: int
:type query_row: int
:type query_glass: int
:rtype: float | :type poured: int
:type query_row: int
:type query_glass: int
:rtype: float | [
":",
"type",
"poured",
":",
"int",
":",
"type",
"query_row",
":",
"int",
":",
"type",
"query_glass",
":",
"int",
":",
"rtype",
":",
"float"
] | def champagneTower(self, poured, query_row, query_glass):
"""
:type poured: int
:type query_row: int
:type query_glass: int
:rtype: float
"""
result = [poured] + [0] * query_row
for i in xrange(1, query_row+1):
for j in reversed(xrange(i+1)):
result[j] = max(result[j]-1, 0)/2.0 + \
max(result[j-1]-1, 0)/2.0
return min(result[query_glass], 1) | [
"def",
"champagneTower",
"(",
"self",
",",
"poured",
",",
"query_row",
",",
"query_glass",
")",
":",
"result",
"=",
"[",
"poured",
"]",
"+",
"[",
"0",
"]",
"*",
"query_row",
"for",
"i",
"in",
"xrange",
"(",
"1",
",",
"query_row",
"+",
"1",
")",
":",
"for",
"j",
"in",
"reversed",
"(",
"xrange",
"(",
"i",
"+",
"1",
")",
")",
":",
"result",
"[",
"j",
"]",
"=",
"max",
"(",
"result",
"[",
"j",
"]",
"-",
"1",
",",
"0",
")",
"/",
"2.0",
"+",
"max",
"(",
"result",
"[",
"j",
"-",
"1",
"]",
"-",
"1",
",",
"0",
")",
"/",
"2.0",
"return",
"min",
"(",
"result",
"[",
"query_glass",
"]",
",",
"1",
")"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/champagne-tower.py#L5-L17 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/package_index.py | python | PackageIndex.prescan | (self) | Scan urls scheduled for prescanning (e.g. --find-links) | Scan urls scheduled for prescanning (e.g. --find-links) | [
"Scan",
"urls",
"scheduled",
"for",
"prescanning",
"(",
"e",
".",
"g",
".",
"--",
"find",
"-",
"links",
")"
] | def prescan(self):
"""Scan urls scheduled for prescanning (e.g. --find-links)"""
if self.to_scan:
list(map(self.scan_url, self.to_scan))
self.to_scan = None | [
"def",
"prescan",
"(",
"self",
")",
":",
"if",
"self",
".",
"to_scan",
":",
"list",
"(",
"map",
"(",
"self",
".",
"scan_url",
",",
"self",
".",
"to_scan",
")",
")",
"self",
".",
"to_scan",
"=",
"None"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/package_index.py#L531-L535 | ||
DLR-SC/tigl | d1c5901e948e33d10b1f9659ff3e22c4717b455f | thirdparty/nsiqcppstyle/nsiqcppstyle_checker.py | python | CppLexerNavigator.GetPrevTokenSkipWhiteSpaceAndComment | (self) | return self.GetPrevToken(True, True) | Get Previous Token skip whitespace and comment.
This method changes the current lex position. | Get Previous Token skip whitespace and comment.
This method changes the current lex position. | [
"Get",
"Previous",
"Token",
"skip",
"whitespace",
"and",
"comment",
".",
"This",
"method",
"changes",
"the",
"current",
"lex",
"position",
"."
] | def GetPrevTokenSkipWhiteSpaceAndComment(self):
"""
Get Previous Token skip whitespace and comment.
This method changes the current lex position.
"""
return self.GetPrevToken(True, True) | [
"def",
"GetPrevTokenSkipWhiteSpaceAndComment",
"(",
"self",
")",
":",
"return",
"self",
".",
"GetPrevToken",
"(",
"True",
",",
"True",
")"
] | https://github.com/DLR-SC/tigl/blob/d1c5901e948e33d10b1f9659ff3e22c4717b455f/thirdparty/nsiqcppstyle/nsiqcppstyle_checker.py#L523-L528 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/signal/windows/windows.py | python | _extend | (M, sym) | Extend window by 1 sample if needed for DFT-even symmetry | Extend window by 1 sample if needed for DFT-even symmetry | [
"Extend",
"window",
"by",
"1",
"sample",
"if",
"needed",
"for",
"DFT",
"-",
"even",
"symmetry"
] | def _extend(M, sym):
"""Extend window by 1 sample if needed for DFT-even symmetry"""
if not sym:
return M + 1, True
else:
return M, False | [
"def",
"_extend",
"(",
"M",
",",
"sym",
")",
":",
"if",
"not",
"sym",
":",
"return",
"M",
"+",
"1",
",",
"True",
"else",
":",
"return",
"M",
",",
"False"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/signal/windows/windows.py#L26-L31 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Path/PathScripts/PathEngraveGui.py | python | TaskPanelOpPage.taskPanelBaseGeometryPage | (self, obj, features) | return TaskPanelBaseGeometryPage(obj, features) | taskPanelBaseGeometryPage(obj, features) ... return page for adding base geometries. | taskPanelBaseGeometryPage(obj, features) ... return page for adding base geometries. | [
"taskPanelBaseGeometryPage",
"(",
"obj",
"features",
")",
"...",
"return",
"page",
"for",
"adding",
"base",
"geometries",
"."
] | def taskPanelBaseGeometryPage(self, obj, features):
"""taskPanelBaseGeometryPage(obj, features) ... return page for adding base geometries."""
return TaskPanelBaseGeometryPage(obj, features) | [
"def",
"taskPanelBaseGeometryPage",
"(",
"self",
",",
"obj",
",",
"features",
")",
":",
"return",
"TaskPanelBaseGeometryPage",
"(",
"obj",
",",
"features",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathEngraveGui.py#L162-L164 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/thumbnailctrl.py | python | GetMondrianImage | () | return wx.ImageFromStream(stream) | Returns a default image placeholder as a :class:`Image`. | Returns a default image placeholder as a :class:`Image`. | [
"Returns",
"a",
"default",
"image",
"placeholder",
"as",
"a",
":",
"class",
":",
"Image",
"."
] | def GetMondrianImage():
""" Returns a default image placeholder as a :class:`Image`. """
stream = cStringIO.StringIO(GetMondrianData())
return wx.ImageFromStream(stream) | [
"def",
"GetMondrianImage",
"(",
")",
":",
"stream",
"=",
"cStringIO",
".",
"StringIO",
"(",
"GetMondrianData",
"(",
")",
")",
"return",
"wx",
".",
"ImageFromStream",
"(",
"stream",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/thumbnailctrl.py#L196-L200 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/bintrees/bintrees/treemixin.py | python | TreeMixin.pop | (self, key, *args) | T.pop(k[,d]) -> v, remove specified key and return the corresponding value
If key is not found, d is returned if given, otherwise KeyError is raised | T.pop(k[,d]) -> v, remove specified key and return the corresponding value
If key is not found, d is returned if given, otherwise KeyError is raised | [
"T",
".",
"pop",
"(",
"k",
"[",
"d",
"]",
")",
"-",
">",
"v",
"remove",
"specified",
"key",
"and",
"return",
"the",
"corresponding",
"value",
"If",
"key",
"is",
"not",
"found",
"d",
"is",
"returned",
"if",
"given",
"otherwise",
"KeyError",
"is",
"raised"
] | def pop(self, key, *args):
""" T.pop(k[,d]) -> v, remove specified key and return the corresponding value
If key is not found, d is returned if given, otherwise KeyError is raised
"""
if len(args) > 1:
raise TypeError("pop expected at most 2 arguments, got %d" % (1 + len(args)))
try:
value = self.get_value(key)
self.remove(key)
return value
except KeyError:
if len(args) == 0:
raise
else:
return args[0] | [
"def",
"pop",
"(",
"self",
",",
"key",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"1",
":",
"raise",
"TypeError",
"(",
"\"pop expected at most 2 arguments, got %d\"",
"%",
"(",
"1",
"+",
"len",
"(",
"args",
")",
")",
")",
"try",
":",
"value",
"=",
"self",
".",
"get_value",
"(",
"key",
")",
"self",
".",
"remove",
"(",
"key",
")",
"return",
"value",
"except",
"KeyError",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"raise",
"else",
":",
"return",
"args",
"[",
"0",
"]"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/bintrees/bintrees/treemixin.py#L409-L423 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/distribute/distribute_lib.py | python | _require_strategy_scope_extended | (extended) | Verify in a `distribution_strategy.scope()` in this thread. | Verify in a `distribution_strategy.scope()` in this thread. | [
"Verify",
"in",
"a",
"distribution_strategy",
".",
"scope",
"()",
"in",
"this",
"thread",
"."
] | def _require_strategy_scope_extended(extended):
"""Verify in a `distribution_strategy.scope()` in this thread."""
context = _get_per_thread_mode()
if context.strategy.extended is extended: return
# Report error.
strategy = extended._container_strategy() # pylint: disable=protected-access
_wrong_strategy_scope(strategy, context) | [
"def",
"_require_strategy_scope_extended",
"(",
"extended",
")",
":",
"context",
"=",
"_get_per_thread_mode",
"(",
")",
"if",
"context",
".",
"strategy",
".",
"extended",
"is",
"extended",
":",
"return",
"# Report error.",
"strategy",
"=",
"extended",
".",
"_container_strategy",
"(",
")",
"# pylint: disable=protected-access",
"_wrong_strategy_scope",
"(",
"strategy",
",",
"context",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/distribute_lib.py#L349-L355 | ||
quarnster/SublimeClang | 6823e7f0904e60680ac9f898108e301582ec5505 | internals/clang/cindex.py | python | Type.is_restrict_qualified | (self) | return Type_is_restrict_qualified(self) | Determine whether a Type has the "restrict" qualifier set,
without looking through typedefs that may have added
"restrict" at a different level. | Determine whether a Type has the "restrict" qualifier set,
without looking through typedefs that may have added
"restrict" at a different level. | [
"Determine",
"whether",
"a",
"Type",
"has",
"the",
"restrict",
"qualifier",
"set",
"without",
"looking",
"through",
"typedefs",
"that",
"may",
"have",
"added",
"restrict",
"at",
"a",
"different",
"level",
"."
] | def is_restrict_qualified(self):
"""
Determine whether a Type has the "restrict" qualifier set,
without looking through typedefs that may have added
"restrict" at a different level.
"""
return Type_is_restrict_qualified(self) | [
"def",
"is_restrict_qualified",
"(",
"self",
")",
":",
"return",
"Type_is_restrict_qualified",
"(",
"self",
")"
] | https://github.com/quarnster/SublimeClang/blob/6823e7f0904e60680ac9f898108e301582ec5505/internals/clang/cindex.py#L1485-L1491 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/rnn_cell.py | python | GRUCell.__call__ | (self, inputs, state, scope=None) | return new_h, new_h | Gated recurrent unit (GRU) with nunits cells. | Gated recurrent unit (GRU) with nunits cells. | [
"Gated",
"recurrent",
"unit",
"(",
"GRU",
")",
"with",
"nunits",
"cells",
"."
] | def __call__(self, inputs, state, scope=None):
"""Gated recurrent unit (GRU) with nunits cells."""
with vs.variable_scope(scope or type(self).__name__): # "GRUCell"
with vs.variable_scope("Gates"): # Reset gate and update gate.
# We start with bias of 1.0 to not reset and not update.
r, u = array_ops.split(1, 2, _linear([inputs, state],
2 * self._num_units, True, 1.0))
r, u = sigmoid(r), sigmoid(u)
with vs.variable_scope("Candidate"):
c = self._activation(_linear([inputs, r * state],
self._num_units, True))
new_h = u * state + (1 - u) * c
return new_h, new_h | [
"def",
"__call__",
"(",
"self",
",",
"inputs",
",",
"state",
",",
"scope",
"=",
"None",
")",
":",
"with",
"vs",
".",
"variable_scope",
"(",
"scope",
"or",
"type",
"(",
"self",
")",
".",
"__name__",
")",
":",
"# \"GRUCell\"",
"with",
"vs",
".",
"variable_scope",
"(",
"\"Gates\"",
")",
":",
"# Reset gate and update gate.",
"# We start with bias of 1.0 to not reset and not update.",
"r",
",",
"u",
"=",
"array_ops",
".",
"split",
"(",
"1",
",",
"2",
",",
"_linear",
"(",
"[",
"inputs",
",",
"state",
"]",
",",
"2",
"*",
"self",
".",
"_num_units",
",",
"True",
",",
"1.0",
")",
")",
"r",
",",
"u",
"=",
"sigmoid",
"(",
"r",
")",
",",
"sigmoid",
"(",
"u",
")",
"with",
"vs",
".",
"variable_scope",
"(",
"\"Candidate\"",
")",
":",
"c",
"=",
"self",
".",
"_activation",
"(",
"_linear",
"(",
"[",
"inputs",
",",
"r",
"*",
"state",
"]",
",",
"self",
".",
"_num_units",
",",
"True",
")",
")",
"new_h",
"=",
"u",
"*",
"state",
"+",
"(",
"1",
"-",
"u",
")",
"*",
"c",
"return",
"new_h",
",",
"new_h"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/rnn_cell.py#L220-L232 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/linear_optimizer/python/ops/sdca_ops.py | python | SdcaModel._l1_loss | (self) | Computes the (un-normalized) l1 loss of the model. | Computes the (un-normalized) l1 loss of the model. | [
"Computes",
"the",
"(",
"un",
"-",
"normalized",
")",
"l1",
"loss",
"of",
"the",
"model",
"."
] | def _l1_loss(self):
"""Computes the (un-normalized) l1 loss of the model."""
with name_scope('l1_loss'):
sum = 0.0
for name in ['sparse_features_weights', 'dense_features_weights']:
for weights in self._convert_n_to_tensor(self._variables[name]):
sum += math_ops.reduce_sum(math_ops.abs(weights))
# SDCA L1 regularization cost is: l1 * sum(|weights|)
return self._options['symmetric_l1_regularization'] * sum | [
"def",
"_l1_loss",
"(",
"self",
")",
":",
"with",
"name_scope",
"(",
"'l1_loss'",
")",
":",
"sum",
"=",
"0.0",
"for",
"name",
"in",
"[",
"'sparse_features_weights'",
",",
"'dense_features_weights'",
"]",
":",
"for",
"weights",
"in",
"self",
".",
"_convert_n_to_tensor",
"(",
"self",
".",
"_variables",
"[",
"name",
"]",
")",
":",
"sum",
"+=",
"math_ops",
".",
"reduce_sum",
"(",
"math_ops",
".",
"abs",
"(",
"weights",
")",
")",
"# SDCA L1 regularization cost is: l1 * sum(|weights|)",
"return",
"self",
".",
"_options",
"[",
"'symmetric_l1_regularization'",
"]",
"*",
"sum"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/linear_optimizer/python/ops/sdca_ops.py#L398-L406 | ||
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/oldnumeric/ma.py | python | zeros | (shape, dtype=float) | return array(numeric.zeros(shape, dtype)) | zeros(n, dtype=float) =
an array of all zeros of the given length or shape. | zeros(n, dtype=float) =
an array of all zeros of the given length or shape. | [
"zeros",
"(",
"n",
"dtype",
"=",
"float",
")",
"=",
"an",
"array",
"of",
"all",
"zeros",
"of",
"the",
"given",
"length",
"or",
"shape",
"."
] | def zeros (shape, dtype=float):
"""zeros(n, dtype=float) =
an array of all zeros of the given length or shape."""
return array(numeric.zeros(shape, dtype)) | [
"def",
"zeros",
"(",
"shape",
",",
"dtype",
"=",
"float",
")",
":",
"return",
"array",
"(",
"numeric",
".",
"zeros",
"(",
"shape",
",",
"dtype",
")",
")"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/oldnumeric/ma.py#L1552-L1555 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/coremltools_wrap/coremltools/coremltools/models/model.py | python | MLModel.save | (self, filename) | Save the model to a .mlmodel format.
Parameters
----------
filename: str
Target filename for the model.
See Also
--------
coremltools.utils.load_model
Examples
--------
>>> model.save('my_model_file.mlmodel')
>>> loaded_model = MLModel('my_model_file.mlmodel') | Save the model to a .mlmodel format. | [
"Save",
"the",
"model",
"to",
"a",
".",
"mlmodel",
"format",
"."
] | def save(self, filename):
"""
Save the model to a .mlmodel format.
Parameters
----------
filename: str
Target filename for the model.
See Also
--------
coremltools.utils.load_model
Examples
--------
>>> model.save('my_model_file.mlmodel')
>>> loaded_model = MLModel('my_model_file.mlmodel')
"""
filename = _os.path.expanduser(filename)
_save_spec(self._spec, filename) | [
"def",
"save",
"(",
"self",
",",
"filename",
")",
":",
"filename",
"=",
"_os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
"_save_spec",
"(",
"self",
".",
"_spec",
",",
"filename",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/models/model.py#L266-L285 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/linecache.py | python | updatecache | (filename, module_globals=None) | return lines | Update a cache entry and return its list of lines.
If something's wrong, print a message, discard the cache entry,
and return an empty list. | Update a cache entry and return its list of lines.
If something's wrong, print a message, discard the cache entry,
and return an empty list. | [
"Update",
"a",
"cache",
"entry",
"and",
"return",
"its",
"list",
"of",
"lines",
".",
"If",
"something",
"s",
"wrong",
"print",
"a",
"message",
"discard",
"the",
"cache",
"entry",
"and",
"return",
"an",
"empty",
"list",
"."
] | def updatecache(filename, module_globals=None):
"""Update a cache entry and return its list of lines.
If something's wrong, print a message, discard the cache entry,
and return an empty list."""
if filename in cache:
if len(cache[filename]) != 1:
cache.pop(filename, None)
if not filename or (filename.startswith('<') and filename.endswith('>')):
return []
fullname = filename
try:
stat = os.stat(fullname)
except OSError:
basename = filename
# Realise a lazy loader based lookup if there is one
# otherwise try to lookup right now.
if lazycache(filename, module_globals):
try:
data = cache[filename][0]()
except (ImportError, OSError):
pass
else:
if data is None:
# No luck, the PEP302 loader cannot find the source
# for this module.
return []
cache[filename] = (
len(data), None,
[line+'\n' for line in data.splitlines()], fullname
)
return cache[filename][2]
# Try looking through the module search path, which is only useful
# when handling a relative filename.
if os.path.isabs(filename):
return []
for dirname in sys.path:
try:
fullname = os.path.join(dirname, basename)
except (TypeError, AttributeError):
# Not sufficiently string-like to do anything useful with.
continue
try:
stat = os.stat(fullname)
break
except OSError:
pass
else:
return []
try:
with tokenize.open(fullname) as fp:
lines = fp.readlines()
except OSError:
return []
if lines and not lines[-1].endswith('\n'):
lines[-1] += '\n'
size, mtime = stat.st_size, stat.st_mtime
cache[filename] = size, mtime, lines, fullname
return lines | [
"def",
"updatecache",
"(",
"filename",
",",
"module_globals",
"=",
"None",
")",
":",
"if",
"filename",
"in",
"cache",
":",
"if",
"len",
"(",
"cache",
"[",
"filename",
"]",
")",
"!=",
"1",
":",
"cache",
".",
"pop",
"(",
"filename",
",",
"None",
")",
"if",
"not",
"filename",
"or",
"(",
"filename",
".",
"startswith",
"(",
"'<'",
")",
"and",
"filename",
".",
"endswith",
"(",
"'>'",
")",
")",
":",
"return",
"[",
"]",
"fullname",
"=",
"filename",
"try",
":",
"stat",
"=",
"os",
".",
"stat",
"(",
"fullname",
")",
"except",
"OSError",
":",
"basename",
"=",
"filename",
"# Realise a lazy loader based lookup if there is one",
"# otherwise try to lookup right now.",
"if",
"lazycache",
"(",
"filename",
",",
"module_globals",
")",
":",
"try",
":",
"data",
"=",
"cache",
"[",
"filename",
"]",
"[",
"0",
"]",
"(",
")",
"except",
"(",
"ImportError",
",",
"OSError",
")",
":",
"pass",
"else",
":",
"if",
"data",
"is",
"None",
":",
"# No luck, the PEP302 loader cannot find the source",
"# for this module.",
"return",
"[",
"]",
"cache",
"[",
"filename",
"]",
"=",
"(",
"len",
"(",
"data",
")",
",",
"None",
",",
"[",
"line",
"+",
"'\\n'",
"for",
"line",
"in",
"data",
".",
"splitlines",
"(",
")",
"]",
",",
"fullname",
")",
"return",
"cache",
"[",
"filename",
"]",
"[",
"2",
"]",
"# Try looking through the module search path, which is only useful",
"# when handling a relative filename.",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"filename",
")",
":",
"return",
"[",
"]",
"for",
"dirname",
"in",
"sys",
".",
"path",
":",
"try",
":",
"fullname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"basename",
")",
"except",
"(",
"TypeError",
",",
"AttributeError",
")",
":",
"# Not sufficiently string-like to do anything useful with.",
"continue",
"try",
":",
"stat",
"=",
"os",
".",
"stat",
"(",
"fullname",
")",
"break",
"except",
"OSError",
":",
"pass",
"else",
":",
"return",
"[",
"]",
"try",
":",
"with",
"tokenize",
".",
"open",
"(",
"fullname",
")",
"as",
"fp",
":",
"lines",
"=",
"fp",
".",
"readlines",
"(",
")",
"except",
"OSError",
":",
"return",
"[",
"]",
"if",
"lines",
"and",
"not",
"lines",
"[",
"-",
"1",
"]",
".",
"endswith",
"(",
"'\\n'",
")",
":",
"lines",
"[",
"-",
"1",
"]",
"+=",
"'\\n'",
"size",
",",
"mtime",
"=",
"stat",
".",
"st_size",
",",
"stat",
".",
"st_mtime",
"cache",
"[",
"filename",
"]",
"=",
"size",
",",
"mtime",
",",
"lines",
",",
"fullname",
"return",
"lines"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/linecache.py#L82-L144 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/training/python/training/training.py | python | clip_gradient_norms_fn | (max_norm) | return clip_norms | Returns a `transform_grads_fn` function for gradient clipping. | Returns a `transform_grads_fn` function for gradient clipping. | [
"Returns",
"a",
"transform_grads_fn",
"function",
"for",
"gradient",
"clipping",
"."
] | def clip_gradient_norms_fn(max_norm):
"""Returns a `transform_grads_fn` function for gradient clipping."""
def clip_norms(gradients_to_variables):
return clip_gradient_norms(gradients_to_variables, max_norm)
return clip_norms | [
"def",
"clip_gradient_norms_fn",
"(",
"max_norm",
")",
":",
"def",
"clip_norms",
"(",
"gradients_to_variables",
")",
":",
"return",
"clip_gradient_norms",
"(",
"gradients_to_variables",
",",
"max_norm",
")",
"return",
"clip_norms"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/training/python/training/training.py#L320-L324 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/distributions/dirichlet_multinomial.py | python | DirichletMultinomial._maybe_assert_valid_sample | (self, counts) | return control_flow_ops.with_dependencies([
check_ops.assert_equal(
self.total_count, math_ops.reduce_sum(counts, -1),
message="counts last-dimension must sum to `self.total_count`"),
], counts) | Check counts for proper shape, values, then return tensor version. | Check counts for proper shape, values, then return tensor version. | [
"Check",
"counts",
"for",
"proper",
"shape",
"values",
"then",
"return",
"tensor",
"version",
"."
] | def _maybe_assert_valid_sample(self, counts):
"""Check counts for proper shape, values, then return tensor version."""
if not self.validate_args:
return counts
counts = distribution_util.embed_check_nonnegative_integer_form(counts)
return control_flow_ops.with_dependencies([
check_ops.assert_equal(
self.total_count, math_ops.reduce_sum(counts, -1),
message="counts last-dimension must sum to `self.total_count`"),
], counts) | [
"def",
"_maybe_assert_valid_sample",
"(",
"self",
",",
"counts",
")",
":",
"if",
"not",
"self",
".",
"validate_args",
":",
"return",
"counts",
"counts",
"=",
"distribution_util",
".",
"embed_check_nonnegative_integer_form",
"(",
"counts",
")",
"return",
"control_flow_ops",
".",
"with_dependencies",
"(",
"[",
"check_ops",
".",
"assert_equal",
"(",
"self",
".",
"total_count",
",",
"math_ops",
".",
"reduce_sum",
"(",
"counts",
",",
"-",
"1",
")",
",",
"message",
"=",
"\"counts last-dimension must sum to `self.total_count`\"",
")",
",",
"]",
",",
"counts",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/distributions/dirichlet_multinomial.py#L334-L343 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/gyp/pylib/gyp/msvs_emulation.py | python | _FindDirectXInstallation | () | return dxsdk_dir | Try to find an installation location for the DirectX SDK. Check for the
standard environment variable, and if that doesn't exist, try to find
via the registry. May return None if not found in either location. | Try to find an installation location for the DirectX SDK. Check for the
standard environment variable, and if that doesn't exist, try to find
via the registry. May return None if not found in either location. | [
"Try",
"to",
"find",
"an",
"installation",
"location",
"for",
"the",
"DirectX",
"SDK",
".",
"Check",
"for",
"the",
"standard",
"environment",
"variable",
"and",
"if",
"that",
"doesn",
"t",
"exist",
"try",
"to",
"find",
"via",
"the",
"registry",
".",
"May",
"return",
"None",
"if",
"not",
"found",
"in",
"either",
"location",
"."
] | def _FindDirectXInstallation():
"""Try to find an installation location for the DirectX SDK. Check for the
standard environment variable, and if that doesn't exist, try to find
via the registry. May return None if not found in either location."""
# Return previously calculated value, if there is one
if hasattr(_FindDirectXInstallation, 'dxsdk_dir'):
return _FindDirectXInstallation.dxsdk_dir
dxsdk_dir = os.environ.get('DXSDK_DIR')
if not dxsdk_dir:
# Setup params to pass to and attempt to launch reg.exe.
cmd = ['reg.exe', 'query', r'HKLM\Software\Microsoft\DirectX', '/s']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = p.communicate()[0]
if PY3:
stdout = stdout.decode('utf-8')
for line in stdout.splitlines():
if 'InstallPath' in line:
dxsdk_dir = line.split(' ')[3] + "\\"
# Cache return value
_FindDirectXInstallation.dxsdk_dir = dxsdk_dir
return dxsdk_dir | [
"def",
"_FindDirectXInstallation",
"(",
")",
":",
"# Return previously calculated value, if there is one",
"if",
"hasattr",
"(",
"_FindDirectXInstallation",
",",
"'dxsdk_dir'",
")",
":",
"return",
"_FindDirectXInstallation",
".",
"dxsdk_dir",
"dxsdk_dir",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'DXSDK_DIR'",
")",
"if",
"not",
"dxsdk_dir",
":",
"# Setup params to pass to and attempt to launch reg.exe.",
"cmd",
"=",
"[",
"'reg.exe'",
",",
"'query'",
",",
"r'HKLM\\Software\\Microsoft\\DirectX'",
",",
"'/s'",
"]",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"stdout",
"=",
"p",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
"if",
"PY3",
":",
"stdout",
"=",
"stdout",
".",
"decode",
"(",
"'utf-8'",
")",
"for",
"line",
"in",
"stdout",
".",
"splitlines",
"(",
")",
":",
"if",
"'InstallPath'",
"in",
"line",
":",
"dxsdk_dir",
"=",
"line",
".",
"split",
"(",
"' '",
")",
"[",
"3",
"]",
"+",
"\"\\\\\"",
"# Cache return value",
"_FindDirectXInstallation",
".",
"dxsdk_dir",
"=",
"dxsdk_dir",
"return",
"dxsdk_dir"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/msvs_emulation.py#L121-L143 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/masked/numctrl.py | python | NumCtrl.SetValue | (self, value) | Sets the value of the control to the value specified.
The resulting actual value of the control may be altered to
conform with the bounds set on the control if limited,
or colored if not limited but the value is out-of-bounds.
A ValueError exception will be raised if an invalid value
is specified. | Sets the value of the control to the value specified.
The resulting actual value of the control may be altered to
conform with the bounds set on the control if limited,
or colored if not limited but the value is out-of-bounds.
A ValueError exception will be raised if an invalid value
is specified. | [
"Sets",
"the",
"value",
"of",
"the",
"control",
"to",
"the",
"value",
"specified",
".",
"The",
"resulting",
"actual",
"value",
"of",
"the",
"control",
"may",
"be",
"altered",
"to",
"conform",
"with",
"the",
"bounds",
"set",
"on",
"the",
"control",
"if",
"limited",
"or",
"colored",
"if",
"not",
"limited",
"but",
"the",
"value",
"is",
"out",
"-",
"of",
"-",
"bounds",
".",
"A",
"ValueError",
"exception",
"will",
"be",
"raised",
"if",
"an",
"invalid",
"value",
"is",
"specified",
"."
] | def SetValue(self, value):
"""
Sets the value of the control to the value specified.
The resulting actual value of the control may be altered to
conform with the bounds set on the control if limited,
or colored if not limited but the value is out-of-bounds.
A ValueError exception will be raised if an invalid value
is specified.
"""
## dbg('NumCtrl::SetValue(%s)' % value, indent=1)
BaseMaskedTextCtrl.SetValue( self, self._toGUI(value) ) | [
"def",
"SetValue",
"(",
"self",
",",
"value",
")",
":",
"## dbg('NumCtrl::SetValue(%s)' % value, indent=1)",
"BaseMaskedTextCtrl",
".",
"SetValue",
"(",
"self",
",",
"self",
".",
"_toGUI",
"(",
"value",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/masked/numctrl.py#L1271-L1281 | ||
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/gdal.py | python | GetLastErrorMsg | (*args) | return _gdal.GetLastErrorMsg(*args) | r"""GetLastErrorMsg() -> char const * | r"""GetLastErrorMsg() -> char const * | [
"r",
"GetLastErrorMsg",
"()",
"-",
">",
"char",
"const",
"*"
] | def GetLastErrorMsg(*args):
r"""GetLastErrorMsg() -> char const *"""
return _gdal.GetLastErrorMsg(*args) | [
"def",
"GetLastErrorMsg",
"(",
"*",
"args",
")",
":",
"return",
"_gdal",
".",
"GetLastErrorMsg",
"(",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L1558-L1560 | |
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | bindings/python/cntk/train/distributed.py | python | Communicator.barrier | (self) | Sync point to make sure all workers reach the same state. | Sync point to make sure all workers reach the same state. | [
"Sync",
"point",
"to",
"make",
"sure",
"all",
"workers",
"reach",
"the",
"same",
"state",
"."
] | def barrier(self):
'''
Sync point to make sure all workers reach the same state.
'''
super(Communicator, self).barrier() | [
"def",
"barrier",
"(",
"self",
")",
":",
"super",
"(",
"Communicator",
",",
"self",
")",
".",
"barrier",
"(",
")"
] | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/train/distributed.py#L67-L71 | ||
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exodus3.in.py | python | exodus.put_side_set_names | (self, names) | store a list of all side set names ordered by side set *INDEX*;
(see `exodus.get_ids` for explanation of the
difference between side set *ID* and side set *INDEX*)
>>> exo.put_side_set_names(side_set_names)
Parameters
----------
<list<string>> side_set_names | store a list of all side set names ordered by side set *INDEX*;
(see `exodus.get_ids` for explanation of the
difference between side set *ID* and side set *INDEX*) | [
"store",
"a",
"list",
"of",
"all",
"side",
"set",
"names",
"ordered",
"by",
"side",
"set",
"*",
"INDEX",
"*",
";",
"(",
"see",
"exodus",
".",
"get_ids",
"for",
"explanation",
"of",
"the",
"difference",
"between",
"side",
"set",
"*",
"ID",
"*",
"and",
"side",
"set",
"*",
"INDEX",
"*",
")"
] | def put_side_set_names(self, names):
"""
store a list of all side set names ordered by side set *INDEX*;
(see `exodus.get_ids` for explanation of the
difference between side set *ID* and side set *INDEX*)
>>> exo.put_side_set_names(side_set_names)
Parameters
----------
<list<string>> side_set_names
"""
self.__ex_put_names('EX_SIDE_SET', names) | [
"def",
"put_side_set_names",
"(",
"self",
",",
"names",
")",
":",
"self",
".",
"__ex_put_names",
"(",
"'EX_SIDE_SET'",
",",
"names",
")"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exodus3.in.py#L3795-L3807 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/eager/python/metrics_impl.py | python | Metric.result | (self) | Computes and returns a final value for the metric. | Computes and returns a final value for the metric. | [
"Computes",
"and",
"returns",
"a",
"final",
"value",
"for",
"the",
"metric",
"."
] | def result(self): # TODO(josh11b): Add an optional summary_writer parameter.
"""Computes and returns a final value for the metric."""
raise NotImplementedError("Metrics must define a result() member function") | [
"def",
"result",
"(",
"self",
")",
":",
"# TODO(josh11b): Add an optional summary_writer parameter.",
"raise",
"NotImplementedError",
"(",
"\"Metrics must define a result() member function\"",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/eager/python/metrics_impl.py#L213-L215 | ||
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/examples/jpsro.py | python | get_game | (game_name) | return pyspiel.load_game_as_turn_based(game_name, game_kwargs) | Returns the game. | Returns the game. | [
"Returns",
"the",
"game",
"."
] | def get_game(game_name):
"""Returns the game."""
if game_name == "kuhn_poker_2p":
game_name = "kuhn_poker"
game_kwargs = {"players": int(2)}
elif game_name == "kuhn_poker_3p":
game_name = "kuhn_poker"
game_kwargs = {"players": int(3)}
elif game_name == "kuhn_poker_4p":
game_name = "kuhn_poker"
game_kwargs = {"players": int(4)}
elif game_name == "leduc_poker_2p":
game_name = "leduc_poker"
game_kwargs = {"players": int(2)}
elif game_name == "leduc_poker_3p":
game_name = "leduc_poker"
game_kwargs = {"players": int(3)}
elif game_name == "leduc_poker_4p":
game_name = "leduc_poker"
game_kwargs = {"players": int(4)}
elif game_name == "trade_comm_2p_2i":
game_name = "trade_comm"
game_kwargs = {"num_items": int(2)}
elif game_name == "trade_comm_2p_3i":
game_name = "trade_comm"
game_kwargs = {"num_items": int(3)}
elif game_name == "trade_comm_2p_4i":
game_name = "trade_comm"
game_kwargs = {"num_items": int(4)}
elif game_name == "trade_comm_2p_5i":
game_name = "trade_comm"
game_kwargs = {"num_items": int(5)}
elif game_name == "tiny_bridge_2p":
game_name = "tiny_bridge_2p"
game_kwargs = {}
elif game_name == "tiny_bridge_4p":
game_name = "tiny_bridge_4p"
game_kwargs = {} # Too big game.
elif game_name == "sheriff_2p_1r":
game_name = "sheriff"
game_kwargs = {"num_rounds": int(1)}
elif game_name == "sheriff_2p_2r":
game_name = "sheriff"
game_kwargs = {"num_rounds": int(2)}
elif game_name == "sheriff_2p_3r":
game_name = "sheriff"
game_kwargs = {"num_rounds": int(3)}
elif game_name == "sheriff_2p_gabriele":
game_name = "sheriff"
game_kwargs = {
"item_penalty": float(1.0),
"item_value": float(5.0),
"max_bribe": int(2),
"max_items": int(10),
"num_rounds": int(2),
"sheriff_penalty": float(1.0),
}
elif game_name == "goofspiel_2p_3c_total":
game_name = "goofspiel"
game_kwargs = {
"players": int(2),
"returns_type": "total_points",
"num_cards": int(3)}
elif game_name == "goofspiel_2p_4c_total":
game_name = "goofspiel"
game_kwargs = {
"players": int(2),
"returns_type": "total_points",
"num_cards": int(4)}
elif game_name == "goofspiel_2p_5c_total":
game_name = "goofspiel"
game_kwargs = {
"players": int(2),
"returns_type": "total_points",
"num_cards": int(5)}
else:
raise ValueError("Unrecognised game: %s" % game_name)
return pyspiel.load_game_as_turn_based(game_name, game_kwargs) | [
"def",
"get_game",
"(",
"game_name",
")",
":",
"if",
"game_name",
"==",
"\"kuhn_poker_2p\"",
":",
"game_name",
"=",
"\"kuhn_poker\"",
"game_kwargs",
"=",
"{",
"\"players\"",
":",
"int",
"(",
"2",
")",
"}",
"elif",
"game_name",
"==",
"\"kuhn_poker_3p\"",
":",
"game_name",
"=",
"\"kuhn_poker\"",
"game_kwargs",
"=",
"{",
"\"players\"",
":",
"int",
"(",
"3",
")",
"}",
"elif",
"game_name",
"==",
"\"kuhn_poker_4p\"",
":",
"game_name",
"=",
"\"kuhn_poker\"",
"game_kwargs",
"=",
"{",
"\"players\"",
":",
"int",
"(",
"4",
")",
"}",
"elif",
"game_name",
"==",
"\"leduc_poker_2p\"",
":",
"game_name",
"=",
"\"leduc_poker\"",
"game_kwargs",
"=",
"{",
"\"players\"",
":",
"int",
"(",
"2",
")",
"}",
"elif",
"game_name",
"==",
"\"leduc_poker_3p\"",
":",
"game_name",
"=",
"\"leduc_poker\"",
"game_kwargs",
"=",
"{",
"\"players\"",
":",
"int",
"(",
"3",
")",
"}",
"elif",
"game_name",
"==",
"\"leduc_poker_4p\"",
":",
"game_name",
"=",
"\"leduc_poker\"",
"game_kwargs",
"=",
"{",
"\"players\"",
":",
"int",
"(",
"4",
")",
"}",
"elif",
"game_name",
"==",
"\"trade_comm_2p_2i\"",
":",
"game_name",
"=",
"\"trade_comm\"",
"game_kwargs",
"=",
"{",
"\"num_items\"",
":",
"int",
"(",
"2",
")",
"}",
"elif",
"game_name",
"==",
"\"trade_comm_2p_3i\"",
":",
"game_name",
"=",
"\"trade_comm\"",
"game_kwargs",
"=",
"{",
"\"num_items\"",
":",
"int",
"(",
"3",
")",
"}",
"elif",
"game_name",
"==",
"\"trade_comm_2p_4i\"",
":",
"game_name",
"=",
"\"trade_comm\"",
"game_kwargs",
"=",
"{",
"\"num_items\"",
":",
"int",
"(",
"4",
")",
"}",
"elif",
"game_name",
"==",
"\"trade_comm_2p_5i\"",
":",
"game_name",
"=",
"\"trade_comm\"",
"game_kwargs",
"=",
"{",
"\"num_items\"",
":",
"int",
"(",
"5",
")",
"}",
"elif",
"game_name",
"==",
"\"tiny_bridge_2p\"",
":",
"game_name",
"=",
"\"tiny_bridge_2p\"",
"game_kwargs",
"=",
"{",
"}",
"elif",
"game_name",
"==",
"\"tiny_bridge_4p\"",
":",
"game_name",
"=",
"\"tiny_bridge_4p\"",
"game_kwargs",
"=",
"{",
"}",
"# Too big game.",
"elif",
"game_name",
"==",
"\"sheriff_2p_1r\"",
":",
"game_name",
"=",
"\"sheriff\"",
"game_kwargs",
"=",
"{",
"\"num_rounds\"",
":",
"int",
"(",
"1",
")",
"}",
"elif",
"game_name",
"==",
"\"sheriff_2p_2r\"",
":",
"game_name",
"=",
"\"sheriff\"",
"game_kwargs",
"=",
"{",
"\"num_rounds\"",
":",
"int",
"(",
"2",
")",
"}",
"elif",
"game_name",
"==",
"\"sheriff_2p_3r\"",
":",
"game_name",
"=",
"\"sheriff\"",
"game_kwargs",
"=",
"{",
"\"num_rounds\"",
":",
"int",
"(",
"3",
")",
"}",
"elif",
"game_name",
"==",
"\"sheriff_2p_gabriele\"",
":",
"game_name",
"=",
"\"sheriff\"",
"game_kwargs",
"=",
"{",
"\"item_penalty\"",
":",
"float",
"(",
"1.0",
")",
",",
"\"item_value\"",
":",
"float",
"(",
"5.0",
")",
",",
"\"max_bribe\"",
":",
"int",
"(",
"2",
")",
",",
"\"max_items\"",
":",
"int",
"(",
"10",
")",
",",
"\"num_rounds\"",
":",
"int",
"(",
"2",
")",
",",
"\"sheriff_penalty\"",
":",
"float",
"(",
"1.0",
")",
",",
"}",
"elif",
"game_name",
"==",
"\"goofspiel_2p_3c_total\"",
":",
"game_name",
"=",
"\"goofspiel\"",
"game_kwargs",
"=",
"{",
"\"players\"",
":",
"int",
"(",
"2",
")",
",",
"\"returns_type\"",
":",
"\"total_points\"",
",",
"\"num_cards\"",
":",
"int",
"(",
"3",
")",
"}",
"elif",
"game_name",
"==",
"\"goofspiel_2p_4c_total\"",
":",
"game_name",
"=",
"\"goofspiel\"",
"game_kwargs",
"=",
"{",
"\"players\"",
":",
"int",
"(",
"2",
")",
",",
"\"returns_type\"",
":",
"\"total_points\"",
",",
"\"num_cards\"",
":",
"int",
"(",
"4",
")",
"}",
"elif",
"game_name",
"==",
"\"goofspiel_2p_5c_total\"",
":",
"game_name",
"=",
"\"goofspiel\"",
"game_kwargs",
"=",
"{",
"\"players\"",
":",
"int",
"(",
"2",
")",
",",
"\"returns_type\"",
":",
"\"total_points\"",
",",
"\"num_cards\"",
":",
"int",
"(",
"5",
")",
"}",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unrecognised game: %s\"",
"%",
"game_name",
")",
"return",
"pyspiel",
".",
"load_game_as_turn_based",
"(",
"game_name",
",",
"game_kwargs",
")"
] | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/examples/jpsro.py#L110-L195 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/arrays/datetimelike.py | python | DatetimeLikeArrayMixin._maybe_mask_results | (
self, result: np.ndarray, fill_value=iNaT, convert=None
) | return result | Parameters
----------
result : np.ndarray
fill_value : object, default iNaT
convert : str, dtype or None
Returns
-------
result : ndarray with values replace by the fill_value
mask the result if needed, convert to the provided dtype if its not
None
This is an internal routine. | Parameters
----------
result : np.ndarray
fill_value : object, default iNaT
convert : str, dtype or None | [
"Parameters",
"----------",
"result",
":",
"np",
".",
"ndarray",
"fill_value",
":",
"object",
"default",
"iNaT",
"convert",
":",
"str",
"dtype",
"or",
"None"
] | def _maybe_mask_results(
self, result: np.ndarray, fill_value=iNaT, convert=None
) -> np.ndarray:
"""
Parameters
----------
result : np.ndarray
fill_value : object, default iNaT
convert : str, dtype or None
Returns
-------
result : ndarray with values replace by the fill_value
mask the result if needed, convert to the provided dtype if its not
None
This is an internal routine.
"""
if self._hasnans:
if convert:
result = result.astype(convert)
if fill_value is None:
fill_value = np.nan
np.putmask(result, self._isnan, fill_value)
return result | [
"def",
"_maybe_mask_results",
"(",
"self",
",",
"result",
":",
"np",
".",
"ndarray",
",",
"fill_value",
"=",
"iNaT",
",",
"convert",
"=",
"None",
")",
"->",
"np",
".",
"ndarray",
":",
"if",
"self",
".",
"_hasnans",
":",
"if",
"convert",
":",
"result",
"=",
"result",
".",
"astype",
"(",
"convert",
")",
"if",
"fill_value",
"is",
"None",
":",
"fill_value",
"=",
"np",
".",
"nan",
"np",
".",
"putmask",
"(",
"result",
",",
"self",
".",
"_isnan",
",",
"fill_value",
")",
"return",
"result"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/arrays/datetimelike.py#L850-L875 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | Brush.SetStipple | (*args, **kwargs) | return _gdi_.Brush_SetStipple(*args, **kwargs) | SetStipple(self, Bitmap stipple)
Sets the stipple `wx.Bitmap`. | SetStipple(self, Bitmap stipple) | [
"SetStipple",
"(",
"self",
"Bitmap",
"stipple",
")"
] | def SetStipple(*args, **kwargs):
"""
SetStipple(self, Bitmap stipple)
Sets the stipple `wx.Bitmap`.
"""
return _gdi_.Brush_SetStipple(*args, **kwargs) | [
"def",
"SetStipple",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Brush_SetStipple",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L537-L543 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/valgrind/tsan_analyze.py | python | TsanAnalyzer.__init__ | (self, use_gdb=False) | Reads in a set of files. | Reads in a set of files. | [
"Reads",
"in",
"a",
"set",
"of",
"files",
"."
] | def __init__(self, use_gdb=False):
'''Reads in a set of files.'''
self._use_gdb = use_gdb
self._cur_testcase = None | [
"def",
"__init__",
"(",
"self",
",",
"use_gdb",
"=",
"False",
")",
":",
"self",
".",
"_use_gdb",
"=",
"use_gdb",
"self",
".",
"_cur_testcase",
"=",
"None"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/valgrind/tsan_analyze.py#L62-L66 | ||
priyankchheda/algorithms | c361aa9071573fa9966d5b02d05e524815abcf2b | graph/connected_components.py | python | main | () | operational function | operational function | [
"operational",
"function"
] | def main():
""" operational function """
graph = {
'1': ['2', '3'],
'2': ['3', '1'],
'3': ['1', '2', '4'],
'4': ['3'],
'5': ['7', '6'],
'6': ['5'],
'7': ['5'],
'8': [],
'9': [],
}
print(find_components(graph)) | [
"def",
"main",
"(",
")",
":",
"graph",
"=",
"{",
"'1'",
":",
"[",
"'2'",
",",
"'3'",
"]",
",",
"'2'",
":",
"[",
"'3'",
",",
"'1'",
"]",
",",
"'3'",
":",
"[",
"'1'",
",",
"'2'",
",",
"'4'",
"]",
",",
"'4'",
":",
"[",
"'3'",
"]",
",",
"'5'",
":",
"[",
"'7'",
",",
"'6'",
"]",
",",
"'6'",
":",
"[",
"'5'",
"]",
",",
"'7'",
":",
"[",
"'5'",
"]",
",",
"'8'",
":",
"[",
"]",
",",
"'9'",
":",
"[",
"]",
",",
"}",
"print",
"(",
"find_components",
"(",
"graph",
")",
")"
] | https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/graph/connected_components.py#L25-L39 | ||
PixarAnimationStudios/USD | faed18ce62c8736b02413635b584a2f637156bad | pxr/usd/usd/usdGenSchema.py | python | _GetTokensPrefix | (layer) | return _GetLibMetadata(layer).get('tokensPrefix',
_GetLibPrefix(layer)) | Return the tokensPrefix defined in layer. | Return the tokensPrefix defined in layer. | [
"Return",
"the",
"tokensPrefix",
"defined",
"in",
"layer",
"."
] | def _GetTokensPrefix(layer):
""" Return the tokensPrefix defined in layer."""
return _GetLibMetadata(layer).get('tokensPrefix',
_GetLibPrefix(layer)) | [
"def",
"_GetTokensPrefix",
"(",
"layer",
")",
":",
"return",
"_GetLibMetadata",
"(",
"layer",
")",
".",
"get",
"(",
"'tokensPrefix'",
",",
"_GetLibPrefix",
"(",
"layer",
")",
")"
] | https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usd/usd/usdGenSchema.py#L214-L218 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/learn/python/learn/ops/seq2seq_ops.py | python | rnn_seq2seq | (encoder_inputs,
decoder_inputs,
encoder_cell,
decoder_cell=None,
dtype=dtypes.float32,
scope=None) | RNN Sequence to Sequence model.
Args:
encoder_inputs: List of tensors, inputs for encoder.
decoder_inputs: List of tensors, inputs for decoder.
encoder_cell: RNN cell to use for encoder.
decoder_cell: RNN cell to use for decoder, if None encoder_cell is used.
dtype: Type to initialize encoder state with.
scope: Scope to use, if None new will be produced.
Returns:
List of tensors for outputs and states for training and sampling sub-graphs. | RNN Sequence to Sequence model. | [
"RNN",
"Sequence",
"to",
"Sequence",
"model",
"."
] | def rnn_seq2seq(encoder_inputs,
decoder_inputs,
encoder_cell,
decoder_cell=None,
dtype=dtypes.float32,
scope=None):
"""RNN Sequence to Sequence model.
Args:
encoder_inputs: List of tensors, inputs for encoder.
decoder_inputs: List of tensors, inputs for decoder.
encoder_cell: RNN cell to use for encoder.
decoder_cell: RNN cell to use for decoder, if None encoder_cell is used.
dtype: Type to initialize encoder state with.
scope: Scope to use, if None new will be produced.
Returns:
List of tensors for outputs and states for training and sampling sub-graphs.
"""
with vs.variable_scope(scope or "rnn_seq2seq"):
_, last_enc_state = rnn.static_rnn(
encoder_cell, encoder_inputs, dtype=dtype)
return rnn_decoder(decoder_inputs, last_enc_state, decoder_cell or
encoder_cell) | [
"def",
"rnn_seq2seq",
"(",
"encoder_inputs",
",",
"decoder_inputs",
",",
"encoder_cell",
",",
"decoder_cell",
"=",
"None",
",",
"dtype",
"=",
"dtypes",
".",
"float32",
",",
"scope",
"=",
"None",
")",
":",
"with",
"vs",
".",
"variable_scope",
"(",
"scope",
"or",
"\"rnn_seq2seq\"",
")",
":",
"_",
",",
"last_enc_state",
"=",
"rnn",
".",
"static_rnn",
"(",
"encoder_cell",
",",
"encoder_inputs",
",",
"dtype",
"=",
"dtype",
")",
"return",
"rnn_decoder",
"(",
"decoder_inputs",
",",
"last_enc_state",
",",
"decoder_cell",
"or",
"encoder_cell",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/ops/seq2seq_ops.py#L126-L149 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | python/psutil/psutil/_psmswindows.py | python | virtual_memory | () | return nt_virtmem_info(total, avail, percent, used, free) | System virtual memory as a namedtuple. | System virtual memory as a namedtuple. | [
"System",
"virtual",
"memory",
"as",
"a",
"namedtuple",
"."
] | def virtual_memory():
"""System virtual memory as a namedtuple."""
mem = _psutil_mswindows.get_virtual_mem()
totphys, availphys, totpagef, availpagef, totvirt, freevirt = mem
#
total = totphys
avail = availphys
free = availphys
used = total - avail
percent = usage_percent((total - avail), total, _round=1)
return nt_virtmem_info(total, avail, percent, used, free) | [
"def",
"virtual_memory",
"(",
")",
":",
"mem",
"=",
"_psutil_mswindows",
".",
"get_virtual_mem",
"(",
")",
"totphys",
",",
"availphys",
",",
"totpagef",
",",
"availpagef",
",",
"totvirt",
",",
"freevirt",
"=",
"mem",
"#",
"total",
"=",
"totphys",
"avail",
"=",
"availphys",
"free",
"=",
"availphys",
"used",
"=",
"total",
"-",
"avail",
"percent",
"=",
"usage_percent",
"(",
"(",
"total",
"-",
"avail",
")",
",",
"total",
",",
"_round",
"=",
"1",
")",
"return",
"nt_virtmem_info",
"(",
"total",
",",
"avail",
",",
"percent",
",",
"used",
",",
"free",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/psutil/psutil/_psmswindows.py#L105-L115 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/markdown/extensions/footnotes.py | python | FootnotePreprocessor.detectTabbed | (self, lines) | return items, i | Find indented text and remove indent before further proccesing.
Keyword arguments:
* lines: an array of strings
Returns: a list of post processed items and the index of last line. | Find indented text and remove indent before further proccesing. | [
"Find",
"indented",
"text",
"and",
"remove",
"indent",
"before",
"further",
"proccesing",
"."
] | def detectTabbed(self, lines):
""" Find indented text and remove indent before further proccesing.
Keyword arguments:
* lines: an array of strings
Returns: a list of post processed items and the index of last line.
"""
items = []
blank_line = False # have we encountered a blank line yet?
i = 0 # to keep track of where we are
def detab(line):
match = TABBED_RE.match(line)
if match:
return match.group(4)
for line in lines:
if line.strip(): # Non-blank line
detabbed_line = detab(line)
if detabbed_line:
items.append(detabbed_line)
i += 1
continue
elif not blank_line and not DEF_RE.match(line):
# not tabbed but still part of first par.
items.append(line)
i += 1
continue
else:
return items, i+1
else: # Blank line: _maybe_ we are done.
blank_line = True
i += 1 # advance
# Find the next non-blank line
for j in range(i, len(lines)):
if lines[j].strip():
next_line = lines[j]; break
else:
break # There is no more text; we are done.
# Check if the next non-blank line is tabbed
if detab(next_line): # Yes, more work to do.
items.append("")
continue
else:
break # No, we are done.
else:
i += 1
return items, i | [
"def",
"detectTabbed",
"(",
"self",
",",
"lines",
")",
":",
"items",
"=",
"[",
"]",
"blank_line",
"=",
"False",
"# have we encountered a blank line yet?",
"i",
"=",
"0",
"# to keep track of where we are",
"def",
"detab",
"(",
"line",
")",
":",
"match",
"=",
"TABBED_RE",
".",
"match",
"(",
"line",
")",
"if",
"match",
":",
"return",
"match",
".",
"group",
"(",
"4",
")",
"for",
"line",
"in",
"lines",
":",
"if",
"line",
".",
"strip",
"(",
")",
":",
"# Non-blank line",
"detabbed_line",
"=",
"detab",
"(",
"line",
")",
"if",
"detabbed_line",
":",
"items",
".",
"append",
"(",
"detabbed_line",
")",
"i",
"+=",
"1",
"continue",
"elif",
"not",
"blank_line",
"and",
"not",
"DEF_RE",
".",
"match",
"(",
"line",
")",
":",
"# not tabbed but still part of first par.",
"items",
".",
"append",
"(",
"line",
")",
"i",
"+=",
"1",
"continue",
"else",
":",
"return",
"items",
",",
"i",
"+",
"1",
"else",
":",
"# Blank line: _maybe_ we are done.",
"blank_line",
"=",
"True",
"i",
"+=",
"1",
"# advance",
"# Find the next non-blank line",
"for",
"j",
"in",
"range",
"(",
"i",
",",
"len",
"(",
"lines",
")",
")",
":",
"if",
"lines",
"[",
"j",
"]",
".",
"strip",
"(",
")",
":",
"next_line",
"=",
"lines",
"[",
"j",
"]",
"break",
"else",
":",
"break",
"# There is no more text; we are done.",
"# Check if the next non-blank line is tabbed",
"if",
"detab",
"(",
"next_line",
")",
":",
"# Yes, more work to do.",
"items",
".",
"append",
"(",
"\"\"",
")",
"continue",
"else",
":",
"break",
"# No, we are done.",
"else",
":",
"i",
"+=",
"1",
"return",
"items",
",",
"i"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/markdown/extensions/footnotes.py#L231-L285 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | DC.GetTextForeground | (*args, **kwargs) | return _gdi_.DC_GetTextForeground(*args, **kwargs) | GetTextForeground(self) -> Colour
Gets the current text foreground colour | GetTextForeground(self) -> Colour | [
"GetTextForeground",
"(",
"self",
")",
"-",
">",
"Colour"
] | def GetTextForeground(*args, **kwargs):
"""
GetTextForeground(self) -> Colour
Gets the current text foreground colour
"""
return _gdi_.DC_GetTextForeground(*args, **kwargs) | [
"def",
"GetTextForeground",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"DC_GetTextForeground",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L4369-L4375 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/calendar.py | python | CalendarDateAttr.SetMark | (*args, **kwargs) | return _calendar.CalendarDateAttr_SetMark(*args, **kwargs) | SetMark(CalendarDateAttr m) | SetMark(CalendarDateAttr m) | [
"SetMark",
"(",
"CalendarDateAttr",
"m",
")"
] | def SetMark(*args, **kwargs):
"""SetMark(CalendarDateAttr m)"""
return _calendar.CalendarDateAttr_SetMark(*args, **kwargs) | [
"def",
"SetMark",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_calendar",
".",
"CalendarDateAttr_SetMark",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/calendar.py#L171-L173 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.