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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/pytables.py | python | IndexCol.maybe_set_size | (self, min_itemsize=None) | maybe set a string col itemsize:
min_itemsize can be an integer or a dict with this columns name
with an integer size | maybe set a string col itemsize:
min_itemsize can be an integer or a dict with this columns name
with an integer size | [
"maybe",
"set",
"a",
"string",
"col",
"itemsize",
":",
"min_itemsize",
"can",
"be",
"an",
"integer",
"or",
"a",
"dict",
"with",
"this",
"columns",
"name",
"with",
"an",
"integer",
"size"
] | def maybe_set_size(self, min_itemsize=None):
""" maybe set a string col itemsize:
min_itemsize can be an integer or a dict with this columns name
with an integer size """
if _ensure_decoded(self.kind) == "string":
if isinstance(min_itemsize, dict):
min_itemsize = min_itemsize.get(self.name)
if min_itemsize is not None and self.typ.itemsize < min_itemsize:
self.typ = _tables().StringCol(itemsize=min_itemsize, pos=self.pos) | [
"def",
"maybe_set_size",
"(",
"self",
",",
"min_itemsize",
"=",
"None",
")",
":",
"if",
"_ensure_decoded",
"(",
"self",
".",
"kind",
")",
"==",
"\"string\"",
":",
"if",
"isinstance",
"(",
"min_itemsize",
",",
"dict",
")",
":",
"min_itemsize",
"=",
"min_itemsize",
".",
"get",
"(",
"self",
".",
"name",
")",
"if",
"min_itemsize",
"is",
"not",
"None",
"and",
"self",
".",
"typ",
".",
"itemsize",
"<",
"min_itemsize",
":",
"self",
".",
"typ",
"=",
"_tables",
"(",
")",
".",
"StringCol",
"(",
"itemsize",
"=",
"min_itemsize",
",",
"pos",
"=",
"self",
".",
"pos",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/pytables.py#L2002-L2012 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/utils/data_utils.py | python | validate_file | (fpath, file_hash, algorithm='auto', chunk_size=65535) | Validates a file against a sha256 or md5 hash.
Args:
fpath: path to the file being validated
file_hash: The expected hash string of the file.
The sha256 and md5 hash algorithms are both supported.
algorithm: Hash algorithm, one of 'auto', 'sha256', or 'md5'.
The default 'auto' detects the hash algorithm in use.
chunk_size: Bytes to read at a time, important for large files.
Returns:
Whether the file is valid | Validates a file against a sha256 or md5 hash. | [
"Validates",
"a",
"file",
"against",
"a",
"sha256",
"or",
"md5",
"hash",
"."
] | def validate_file(fpath, file_hash, algorithm='auto', chunk_size=65535):
"""Validates a file against a sha256 or md5 hash.
Args:
fpath: path to the file being validated
file_hash: The expected hash string of the file.
The sha256 and md5 hash algorithms are both supported.
algorithm: Hash algorithm, one of 'auto', 'sha256', or 'md5'.
The default 'auto' detects the hash algorithm in use.
chunk_size: Bytes to read at a time, important for large files.
Returns:
Whether the file is valid
"""
hasher = _resolve_hasher(algorithm, file_hash)
if str(_hash_file(fpath, hasher, chunk_size)) == str(file_hash):
return True
else:
return False | [
"def",
"validate_file",
"(",
"fpath",
",",
"file_hash",
",",
"algorithm",
"=",
"'auto'",
",",
"chunk_size",
"=",
"65535",
")",
":",
"hasher",
"=",
"_resolve_hasher",
"(",
"algorithm",
",",
"file_hash",
")",
"if",
"str",
"(",
"_hash_file",
"(",
"fpath",
",",
"hasher",
",",
"chunk_size",
")",
")",
"==",
"str",
"(",
"file_hash",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/utils/data_utils.py#L328-L347 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/dirichlet.py | python | Dirichlet.mode | (self, name="mode") | Mode of the distribution.
Note that the mode for the Beta distribution is only defined
when `alpha > 1`. This returns the mode when `alpha > 1`,
and NaN otherwise. If `self.allow_nan_stats` is `False`, an exception
will be raised rather than returning `NaN`.
Args:
name: The name for this op.
Returns:
Mode of the Dirichlet distribution. | Mode of the distribution. | [
"Mode",
"of",
"the",
"distribution",
"."
] | def mode(self, name="mode"):
"""Mode of the distribution.
Note that the mode for the Beta distribution is only defined
when `alpha > 1`. This returns the mode when `alpha > 1`,
and NaN otherwise. If `self.allow_nan_stats` is `False`, an exception
will be raised rather than returning `NaN`.
Args:
name: The name for this op.
Returns:
Mode of the Dirichlet distribution.
"""
with ops.name_scope(self.name):
with ops.op_scope([self._alpha, self._alpha_0], name):
one = constant_op.constant(1, self.dtype)
mode = (self._alpha - 1)/ (
array_ops.expand_dims(self._alpha_0, -1) - math_ops.cast(
self.event_shape()[0], self.dtype))
if self.allow_nan_stats:
return math_ops.select(
math_ops.greater(self._alpha, 1),
mode,
(constant_op.constant(float("NaN"), dtype=self.dtype) *
array_ops.ones_like(self._alpha, dtype=self.dtype)))
else:
return control_flow_ops.with_dependencies([
check_ops.assert_less(
one, self._alpha,
message="mode not defined for components of alpha <= 1")
], mode) | [
"def",
"mode",
"(",
"self",
",",
"name",
"=",
"\"mode\"",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"self",
".",
"name",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"self",
".",
"_alpha",
",",
"self",
".",
"_alpha_0",
"]",
",",
"name",
")",
":",
"one",
"=",
"constant_op",
".",
"constant",
"(",
"1",
",",
"self",
".",
"dtype",
")",
"mode",
"=",
"(",
"self",
".",
"_alpha",
"-",
"1",
")",
"/",
"(",
"array_ops",
".",
"expand_dims",
"(",
"self",
".",
"_alpha_0",
",",
"-",
"1",
")",
"-",
"math_ops",
".",
"cast",
"(",
"self",
".",
"event_shape",
"(",
")",
"[",
"0",
"]",
",",
"self",
".",
"dtype",
")",
")",
"if",
"self",
".",
"allow_nan_stats",
":",
"return",
"math_ops",
".",
"select",
"(",
"math_ops",
".",
"greater",
"(",
"self",
".",
"_alpha",
",",
"1",
")",
",",
"mode",
",",
"(",
"constant_op",
".",
"constant",
"(",
"float",
"(",
"\"NaN\"",
")",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
"*",
"array_ops",
".",
"ones_like",
"(",
"self",
".",
"_alpha",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
")",
")",
"else",
":",
"return",
"control_flow_ops",
".",
"with_dependencies",
"(",
"[",
"check_ops",
".",
"assert_less",
"(",
"one",
",",
"self",
".",
"_alpha",
",",
"message",
"=",
"\"mode not defined for components of alpha <= 1\"",
")",
"]",
",",
"mode",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/dirichlet.py#L258-L290 | ||
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/gyp/pylib/gyp/xcodeproj_file.py | python | SourceTreeAndPathFromPath | (input_path) | return (source_tree, output_path) | Given input_path, returns a tuple with sourceTree and path values.
Examples:
input_path (source_tree, output_path)
'$(VAR)/path' ('VAR', 'path')
'$(VAR)' ('VAR', None)
'path' (None, 'path') | Given input_path, returns a tuple with sourceTree and path values. | [
"Given",
"input_path",
"returns",
"a",
"tuple",
"with",
"sourceTree",
"and",
"path",
"values",
"."
] | def SourceTreeAndPathFromPath(input_path):
"""Given input_path, returns a tuple with sourceTree and path values.
Examples:
input_path (source_tree, output_path)
'$(VAR)/path' ('VAR', 'path')
'$(VAR)' ('VAR', None)
'path' (None, 'path')
"""
source_group_match = _path_leading_variable.match(input_path)
if source_group_match:
source_tree = source_group_match.group(1)
output_path = source_group_match.group(3) # This may be None.
else:
source_tree = None
output_path = input_path
return (source_tree, output_path) | [
"def",
"SourceTreeAndPathFromPath",
"(",
"input_path",
")",
":",
"source_group_match",
"=",
"_path_leading_variable",
".",
"match",
"(",
"input_path",
")",
"if",
"source_group_match",
":",
"source_tree",
"=",
"source_group_match",
".",
"group",
"(",
"1",
")",
"output_path",
"=",
"source_group_match",
".",
"group",
"(",
"3",
")",
"# This may be None.",
"else",
":",
"source_tree",
"=",
"None",
"output_path",
"=",
"input_path",
"return",
"(",
"source_tree",
",",
"output_path",
")"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/xcodeproj_file.py#L175-L193 | |
trailofbits/llvm-sanitizer-tutorial | d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99 | llvm/bindings/python/llvm/object.py | python | Section.address | (self) | return lib.LLVMGetSectionAddress(self) | The address of this section, in long bytes. | The address of this section, in long bytes. | [
"The",
"address",
"of",
"this",
"section",
"in",
"long",
"bytes",
"."
] | def address(self):
"""The address of this section, in long bytes."""
if self.expired:
raise Exception('Section instance has expired.')
return lib.LLVMGetSectionAddress(self) | [
"def",
"address",
"(",
"self",
")",
":",
"if",
"self",
".",
"expired",
":",
"raise",
"Exception",
"(",
"'Section instance has expired.'",
")",
"return",
"lib",
".",
"LLVMGetSectionAddress",
"(",
"self",
")"
] | https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/bindings/python/llvm/object.py#L225-L230 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/distutils/fancy_getopt.py | python | FancyGetopt.set_negative_aliases | (self, negative_alias) | Set the negative aliases for this option parser.
'negative_alias' should be a dictionary mapping option names to
option names, both the key and value must already be defined
in the option table. | Set the negative aliases for this option parser.
'negative_alias' should be a dictionary mapping option names to
option names, both the key and value must already be defined
in the option table. | [
"Set",
"the",
"negative",
"aliases",
"for",
"this",
"option",
"parser",
".",
"negative_alias",
"should",
"be",
"a",
"dictionary",
"mapping",
"option",
"names",
"to",
"option",
"names",
"both",
"the",
"key",
"and",
"value",
"must",
"already",
"be",
"defined",
"in",
"the",
"option",
"table",
"."
] | def set_negative_aliases (self, negative_alias):
"""Set the negative aliases for this option parser.
'negative_alias' should be a dictionary mapping option names to
option names, both the key and value must already be defined
in the option table."""
self._check_alias_dict(negative_alias, "negative alias")
self.negative_alias = negative_alias | [
"def",
"set_negative_aliases",
"(",
"self",
",",
"negative_alias",
")",
":",
"self",
".",
"_check_alias_dict",
"(",
"negative_alias",
",",
"\"negative alias\"",
")",
"self",
".",
"negative_alias",
"=",
"negative_alias"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/distutils/fancy_getopt.py#L138-L144 | ||
tensorflow/deepmath | b5b721f54de1d5d6a02d78f5da5995237f9995f9 | deepmath/deephol/action_generator.py | python | ActionGenerator.step | (self, node: proof_search_tree.ProofSearchNode,
premises: proof_assistant_pb2.PremiseSet) | return ret | Generates a list of possible ApplyTactic argument strings from a goal.
Args:
node: state of the proof search, starting at current goal.
premises: Specification of the selection of premises that can be used for
tactic parameters. Currently we are supporting only a single
DatabaseSection.
Returns:
List of string arugments for HolLight.ApplyTactic function, along with
scores (Suggestion). | Generates a list of possible ApplyTactic argument strings from a goal. | [
"Generates",
"a",
"list",
"of",
"possible",
"ApplyTactic",
"argument",
"strings",
"from",
"a",
"goal",
"."
] | def step(self, node: proof_search_tree.ProofSearchNode,
premises: proof_assistant_pb2.PremiseSet) -> List[Suggestion]:
"""Generates a list of possible ApplyTactic argument strings from a goal.
Args:
node: state of the proof search, starting at current goal.
premises: Specification of the selection of premises that can be used for
tactic parameters. Currently we are supporting only a single
DatabaseSection.
Returns:
List of string arugments for HolLight.ApplyTactic function, along with
scores (Suggestion).
"""
assert not premises.reference_sets, ('Premise reference sets are not '
'supported.')
assert len(premises.sections) == 1, ('Premise set must have exactly one '
'section.')
# TODO(szegedy): If the premise is not specified, we want the whole
# database to be used. Not sure if -1 or len(database.theorems) would do
# that or not. Assertion will certainly fail before that.
# Also we don't have checks on this use case.
assert premises.sections[0].HasField('before_premise'), ('Premise is '
'required.')
fp = premises.sections[0].before_premise
thm_number = self.thm_index_by_fingerprint.get(fp)
assert thm_number is not None
assert theorem_fingerprint.Fingerprint(
self.theorem_database.theorems[thm_number]) == fp
thm_names = self.thm_names[:thm_number]
tf.logging.debug(thm_names)
# TODO(smloos): update predictor api to accept theorems directly
proof_state = predictions.ProofState(
goal=str(normalization_lib.normalize(node.goal).conclusion))
proof_state_emb = self.predictor.proof_state_embedding(proof_state)
proof_state_enc = self.predictor.proof_state_encoding(proof_state_emb)
tf.logging.debug(proof_state_enc)
tactic_scores = self._compute_tactic_scores(proof_state_enc)
empty_emb = self.predictor.thm_embedding('')
empty_emb_batch = np.reshape(empty_emb, [1, empty_emb.shape[0]])
enumerated_tactics = enumerate(self.tactics)
if self.options.asm_meson_only:
enumerated_tactics = [
v for v in enumerated_tactics if str(v[1].name) == 'ASM_MESON_TAC'
]
assert enumerated_tactics, (
'action generator option asm_meson_only requires ASM_MESON_TAC.')
ranked_closest = self.compute_closest(node.goal, thm_number)
if ranked_closest:
tf.logging.info(
'Cosine closest picked:\n%s', '\n'.join(
['%s: %.6f' % (name, score) for score, name in ranked_closest]))
ret = []
thm_scores = None
# TODO(smloos): This computes parameters for all tactics. It should cut off
# based on the prover BFS options.
for tactic_id, tactic in enumerated_tactics:
if (thm_scores is None or self.model_architecture ==
deephol_pb2.ProverOptions.PARAMETERS_CONDITIONED_ON_TAC):
thm_scores = self._get_theorem_scores(proof_state_enc, thm_number,
tactic_id)
tf.logging.debug(thm_scores)
no_params_score = self.predictor.batch_thm_scores(
proof_state_enc, empty_emb_batch, tactic_id)[0]
tf.logging.info('Theorem score for empty theorem: %f0.2',
no_params_score)
thm_ranked = sorted(
zip(thm_scores, self.thm_names),
reverse=True)[:self.options.max_theorem_parameters]
pass_no_arguments = thm_ranked[-1][0] < no_params_score
thm_ranked = self.add_similar(thm_ranked, ranked_closest)
tf.logging.info('thm_ranked: %s', str(thm_ranked))
tactic_str = str(tactic.name)
try:
tactic_params = _compute_parameter_string(
list(tactic.parameter_types), pass_no_arguments, thm_ranked)
for params_str in tactic_params:
ret.append(
Suggestion(
string=tactic_str + params_str,
score=tactic_scores[tactic_id]))
except ValueError as e:
tf.logging.warning('Failed to compute parameters for tactic %s: %s',
tactic.name, str(e))
return ret | [
"def",
"step",
"(",
"self",
",",
"node",
":",
"proof_search_tree",
".",
"ProofSearchNode",
",",
"premises",
":",
"proof_assistant_pb2",
".",
"PremiseSet",
")",
"->",
"List",
"[",
"Suggestion",
"]",
":",
"assert",
"not",
"premises",
".",
"reference_sets",
",",
"(",
"'Premise reference sets are not '",
"'supported.'",
")",
"assert",
"len",
"(",
"premises",
".",
"sections",
")",
"==",
"1",
",",
"(",
"'Premise set must have exactly one '",
"'section.'",
")",
"# TODO(szegedy): If the premise is not specified, we want the whole",
"# database to be used. Not sure if -1 or len(database.theorems) would do",
"# that or not. Assertion will certainly fail before that.",
"# Also we don't have checks on this use case.",
"assert",
"premises",
".",
"sections",
"[",
"0",
"]",
".",
"HasField",
"(",
"'before_premise'",
")",
",",
"(",
"'Premise is '",
"'required.'",
")",
"fp",
"=",
"premises",
".",
"sections",
"[",
"0",
"]",
".",
"before_premise",
"thm_number",
"=",
"self",
".",
"thm_index_by_fingerprint",
".",
"get",
"(",
"fp",
")",
"assert",
"thm_number",
"is",
"not",
"None",
"assert",
"theorem_fingerprint",
".",
"Fingerprint",
"(",
"self",
".",
"theorem_database",
".",
"theorems",
"[",
"thm_number",
"]",
")",
"==",
"fp",
"thm_names",
"=",
"self",
".",
"thm_names",
"[",
":",
"thm_number",
"]",
"tf",
".",
"logging",
".",
"debug",
"(",
"thm_names",
")",
"# TODO(smloos): update predictor api to accept theorems directly",
"proof_state",
"=",
"predictions",
".",
"ProofState",
"(",
"goal",
"=",
"str",
"(",
"normalization_lib",
".",
"normalize",
"(",
"node",
".",
"goal",
")",
".",
"conclusion",
")",
")",
"proof_state_emb",
"=",
"self",
".",
"predictor",
".",
"proof_state_embedding",
"(",
"proof_state",
")",
"proof_state_enc",
"=",
"self",
".",
"predictor",
".",
"proof_state_encoding",
"(",
"proof_state_emb",
")",
"tf",
".",
"logging",
".",
"debug",
"(",
"proof_state_enc",
")",
"tactic_scores",
"=",
"self",
".",
"_compute_tactic_scores",
"(",
"proof_state_enc",
")",
"empty_emb",
"=",
"self",
".",
"predictor",
".",
"thm_embedding",
"(",
"''",
")",
"empty_emb_batch",
"=",
"np",
".",
"reshape",
"(",
"empty_emb",
",",
"[",
"1",
",",
"empty_emb",
".",
"shape",
"[",
"0",
"]",
"]",
")",
"enumerated_tactics",
"=",
"enumerate",
"(",
"self",
".",
"tactics",
")",
"if",
"self",
".",
"options",
".",
"asm_meson_only",
":",
"enumerated_tactics",
"=",
"[",
"v",
"for",
"v",
"in",
"enumerated_tactics",
"if",
"str",
"(",
"v",
"[",
"1",
"]",
".",
"name",
")",
"==",
"'ASM_MESON_TAC'",
"]",
"assert",
"enumerated_tactics",
",",
"(",
"'action generator option asm_meson_only requires ASM_MESON_TAC.'",
")",
"ranked_closest",
"=",
"self",
".",
"compute_closest",
"(",
"node",
".",
"goal",
",",
"thm_number",
")",
"if",
"ranked_closest",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"'Cosine closest picked:\\n%s'",
",",
"'\\n'",
".",
"join",
"(",
"[",
"'%s: %.6f'",
"%",
"(",
"name",
",",
"score",
")",
"for",
"score",
",",
"name",
"in",
"ranked_closest",
"]",
")",
")",
"ret",
"=",
"[",
"]",
"thm_scores",
"=",
"None",
"# TODO(smloos): This computes parameters for all tactics. It should cut off",
"# based on the prover BFS options.",
"for",
"tactic_id",
",",
"tactic",
"in",
"enumerated_tactics",
":",
"if",
"(",
"thm_scores",
"is",
"None",
"or",
"self",
".",
"model_architecture",
"==",
"deephol_pb2",
".",
"ProverOptions",
".",
"PARAMETERS_CONDITIONED_ON_TAC",
")",
":",
"thm_scores",
"=",
"self",
".",
"_get_theorem_scores",
"(",
"proof_state_enc",
",",
"thm_number",
",",
"tactic_id",
")",
"tf",
".",
"logging",
".",
"debug",
"(",
"thm_scores",
")",
"no_params_score",
"=",
"self",
".",
"predictor",
".",
"batch_thm_scores",
"(",
"proof_state_enc",
",",
"empty_emb_batch",
",",
"tactic_id",
")",
"[",
"0",
"]",
"tf",
".",
"logging",
".",
"info",
"(",
"'Theorem score for empty theorem: %f0.2'",
",",
"no_params_score",
")",
"thm_ranked",
"=",
"sorted",
"(",
"zip",
"(",
"thm_scores",
",",
"self",
".",
"thm_names",
")",
",",
"reverse",
"=",
"True",
")",
"[",
":",
"self",
".",
"options",
".",
"max_theorem_parameters",
"]",
"pass_no_arguments",
"=",
"thm_ranked",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"<",
"no_params_score",
"thm_ranked",
"=",
"self",
".",
"add_similar",
"(",
"thm_ranked",
",",
"ranked_closest",
")",
"tf",
".",
"logging",
".",
"info",
"(",
"'thm_ranked: %s'",
",",
"str",
"(",
"thm_ranked",
")",
")",
"tactic_str",
"=",
"str",
"(",
"tactic",
".",
"name",
")",
"try",
":",
"tactic_params",
"=",
"_compute_parameter_string",
"(",
"list",
"(",
"tactic",
".",
"parameter_types",
")",
",",
"pass_no_arguments",
",",
"thm_ranked",
")",
"for",
"params_str",
"in",
"tactic_params",
":",
"ret",
".",
"append",
"(",
"Suggestion",
"(",
"string",
"=",
"tactic_str",
"+",
"params_str",
",",
"score",
"=",
"tactic_scores",
"[",
"tactic_id",
"]",
")",
")",
"except",
"ValueError",
"as",
"e",
":",
"tf",
".",
"logging",
".",
"warning",
"(",
"'Failed to compute parameters for tactic %s: %s'",
",",
"tactic",
".",
"name",
",",
"str",
"(",
"e",
")",
")",
"return",
"ret"
] | https://github.com/tensorflow/deepmath/blob/b5b721f54de1d5d6a02d78f5da5995237f9995f9/deepmath/deephol/action_generator.py#L264-L354 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBExpressionOptions.GetTrapExceptions | (self) | return _lldb.SBExpressionOptions_GetTrapExceptions(self) | GetTrapExceptions(self) -> bool | GetTrapExceptions(self) -> bool | [
"GetTrapExceptions",
"(",
"self",
")",
"-",
">",
"bool"
] | def GetTrapExceptions(self):
"""GetTrapExceptions(self) -> bool"""
return _lldb.SBExpressionOptions_GetTrapExceptions(self) | [
"def",
"GetTrapExceptions",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBExpressionOptions_GetTrapExceptions",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L4163-L4165 | |
indutny/candor | 48e7260618f5091c80a3416828e2808cad3ea22e | tools/gyp/pylib/gyp/generator/scons.py | python | TargetFilename | (target, build_file=None, output_suffix='') | return output_file | Returns the .scons file name for the specified target. | Returns the .scons file name for the specified target. | [
"Returns",
"the",
".",
"scons",
"file",
"name",
"for",
"the",
"specified",
"target",
"."
] | def TargetFilename(target, build_file=None, output_suffix=''):
"""Returns the .scons file name for the specified target.
"""
if build_file is None:
build_file, target = gyp.common.ParseQualifiedTarget(target)[:2]
output_file = os.path.join(os.path.dirname(build_file),
target + output_suffix + '.scons')
return output_file | [
"def",
"TargetFilename",
"(",
"target",
",",
"build_file",
"=",
"None",
",",
"output_suffix",
"=",
"''",
")",
":",
"if",
"build_file",
"is",
"None",
":",
"build_file",
",",
"target",
"=",
"gyp",
".",
"common",
".",
"ParseQualifiedTarget",
"(",
"target",
")",
"[",
":",
"2",
"]",
"output_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"build_file",
")",
",",
"target",
"+",
"output_suffix",
"+",
"'.scons'",
")",
"return",
"output_file"
] | https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/generator/scons.py#L953-L960 | |
NVIDIAGameWorks/kaolin | e5148d05e9c1e2ce92a07881ce3593b1c5c3f166 | kaolin/metrics/tetmesh.py | python | amips | (tet_vertices, inverse_offset_matrix) | return amips_energy | r"""Compute the AMIPS (Advanced MIPS) loss as devised by *Fu et al.* in
`Computing Locally Injective Mappings by Advanced MIPS. \
<https://www.microsoft.com/en-us/research/publication/computing-locally-injective-mappings-advanced-mips/>`_
ACM Transactions on Graphics (TOG) - Proceedings of ACM SIGGRAPH 2015.
The Jacobian can be derived as: :math:`J = (g(x) - g(x_0)) / (x - x_0)`
Only components where the determinant of the Jacobian is positive, are included in the calculation of AMIPS.
This is because the AMIPS Loss is only defined for tetrahedrons whose determinant of the Jacobian is positive.
Args:
tet_vertices (torch.Tensor):
Batched tetrahedrons, of shape
:math:`(\text{batch_size}, \text{num_tetrahedrons}, 4, 3)`.
inverse_offset_matrix (torch.LongTensor):
The inverse of the offset matrix is of shape
:math:`(\text{batch_size}, \text{num_tetrahedrons}, 3, 3)`.
Refer to :func:`kaolin.ops.mesh.tetmesh.inverse_vertices_offset`.
Returns:
(torch.Tensor):
AMIPS loss for each mesh, of shape :math:`(\text{batch_size})`.
Example:
>>> tet_vertices = torch.tensor([[[[1.7000, 2.3000, 4.4500],
... [3.4800, 0.2000, 5.3000],
... [4.9000, 9.4500, 6.4500],
... [6.2000, 8.5000, 7.1000]],
... [[-1.3750, 1.4500, 3.2500],
... [4.9000, 1.8000, 2.7000],
... [3.6000, 1.9000, 2.3000],
... [1.5500, 1.3500, 2.9000]]],
... [[[1.7000, 2.3000, 4.4500],
... [3.4800, 0.2000, 5.3000],
... [4.9000, 9.4500, 6.4500],
... [6.2000, 8.5000, 7.1000]],
... [[-1.3750, 1.4500, 3.2500],
... [4.9000, 1.8000, 2.7000],
... [3.6000, 1.9000, 2.3000],
... [1.5500, 1.3500, 2.9000]]]])
>>> inverse_offset_matrix = torch.tensor([[[[ -1.1561, -1.1512, -1.9049],
... [1.5138, 1.0108, 3.4302],
... [1.6538, 1.0346, 4.2223]],
... [[ 2.9020, -1.0995, -1.8744],
... [ 1.1554, 1.1519, 1.7780],
... [-0.0766, 1.6350, 1.1064]]],
... [[[-0.9969, 1.4321, -0.3075],
... [-1.3414, 1.5795, -1.6571],
... [-0.1775, -0.4349, 1.1772]],
... [[-1.1077, -1.2441, 1.8037],
... [-0.5722, 0.1755, -2.4364],
... [-0.5263, 1.5765, 1.5607]]]])
>>> amips(tet_vertices, inverse_offset_matrix)
tensor([[13042.3408],
[ 2376.2517]]) | r"""Compute the AMIPS (Advanced MIPS) loss as devised by *Fu et al.* in
`Computing Locally Injective Mappings by Advanced MIPS. \
<https://www.microsoft.com/en-us/research/publication/computing-locally-injective-mappings-advanced-mips/>`_
ACM Transactions on Graphics (TOG) - Proceedings of ACM SIGGRAPH 2015. | [
"r",
"Compute",
"the",
"AMIPS",
"(",
"Advanced",
"MIPS",
")",
"loss",
"as",
"devised",
"by",
"*",
"Fu",
"et",
"al",
".",
"*",
"in",
"Computing",
"Locally",
"Injective",
"Mappings",
"by",
"Advanced",
"MIPS",
".",
"\\",
"<https",
":",
"//",
"www",
".",
"microsoft",
".",
"com",
"/",
"en",
"-",
"us",
"/",
"research",
"/",
"publication",
"/",
"computing",
"-",
"locally",
"-",
"injective",
"-",
"mappings",
"-",
"advanced",
"-",
"mips",
"/",
">",
"_",
"ACM",
"Transactions",
"on",
"Graphics",
"(",
"TOG",
")",
"-",
"Proceedings",
"of",
"ACM",
"SIGGRAPH",
"2015",
"."
] | def amips(tet_vertices, inverse_offset_matrix):
r"""Compute the AMIPS (Advanced MIPS) loss as devised by *Fu et al.* in
`Computing Locally Injective Mappings by Advanced MIPS. \
<https://www.microsoft.com/en-us/research/publication/computing-locally-injective-mappings-advanced-mips/>`_
ACM Transactions on Graphics (TOG) - Proceedings of ACM SIGGRAPH 2015.
The Jacobian can be derived as: :math:`J = (g(x) - g(x_0)) / (x - x_0)`
Only components where the determinant of the Jacobian is positive, are included in the calculation of AMIPS.
This is because the AMIPS Loss is only defined for tetrahedrons whose determinant of the Jacobian is positive.
Args:
tet_vertices (torch.Tensor):
Batched tetrahedrons, of shape
:math:`(\text{batch_size}, \text{num_tetrahedrons}, 4, 3)`.
inverse_offset_matrix (torch.LongTensor):
The inverse of the offset matrix is of shape
:math:`(\text{batch_size}, \text{num_tetrahedrons}, 3, 3)`.
Refer to :func:`kaolin.ops.mesh.tetmesh.inverse_vertices_offset`.
Returns:
(torch.Tensor):
AMIPS loss for each mesh, of shape :math:`(\text{batch_size})`.
Example:
>>> tet_vertices = torch.tensor([[[[1.7000, 2.3000, 4.4500],
... [3.4800, 0.2000, 5.3000],
... [4.9000, 9.4500, 6.4500],
... [6.2000, 8.5000, 7.1000]],
... [[-1.3750, 1.4500, 3.2500],
... [4.9000, 1.8000, 2.7000],
... [3.6000, 1.9000, 2.3000],
... [1.5500, 1.3500, 2.9000]]],
... [[[1.7000, 2.3000, 4.4500],
... [3.4800, 0.2000, 5.3000],
... [4.9000, 9.4500, 6.4500],
... [6.2000, 8.5000, 7.1000]],
... [[-1.3750, 1.4500, 3.2500],
... [4.9000, 1.8000, 2.7000],
... [3.6000, 1.9000, 2.3000],
... [1.5500, 1.3500, 2.9000]]]])
>>> inverse_offset_matrix = torch.tensor([[[[ -1.1561, -1.1512, -1.9049],
... [1.5138, 1.0108, 3.4302],
... [1.6538, 1.0346, 4.2223]],
... [[ 2.9020, -1.0995, -1.8744],
... [ 1.1554, 1.1519, 1.7780],
... [-0.0766, 1.6350, 1.1064]]],
... [[[-0.9969, 1.4321, -0.3075],
... [-1.3414, 1.5795, -1.6571],
... [-0.1775, -0.4349, 1.1772]],
... [[-1.1077, -1.2441, 1.8037],
... [-0.5722, 0.1755, -2.4364],
... [-0.5263, 1.5765, 1.5607]]]])
>>> amips(tet_vertices, inverse_offset_matrix)
tensor([[13042.3408],
[ 2376.2517]])
"""
_validate_tet_vertices(tet_vertices)
# split the tensor
A, B, C, D = torch.split(tet_vertices, split_size_or_sections=1, dim=2)
# compute the offset matrix of the tetrahedrons w.r.t. vertex A.
offset_matrix = torch.cat([B - A, C - A, D - A], dim=2)
# compute the Jacobian for each tetrahedron - the Jacobian represents the unique 3D deformation that transforms the
# tetrahedron t into a regular tetrahedron.
jacobian = torch.matmul(offset_matrix, inverse_offset_matrix)
# compute determinant of Jacobian
j_det = torch.det(jacobian)
# compute the trace of J * J.T
jacobian_squared = torch.matmul(jacobian, torch.transpose(jacobian, -2, -1))
trace = torch.diagonal(jacobian_squared, dim1=-2, dim2=-1).sum(-1)
# compute the determinant of the Jacobian to the 2/3
EPS = 1e-10
denominator = torch.pow(torch.pow(j_det, 2) + EPS, 1 / 3)
# compute amips energy for positive tetrahedrons whose determinant of their Jacobian is positive
amips_energy = torch.mean(torch.div(trace, denominator) * (j_det >= 0).float(),
dim=1, keepdim=True)
return amips_energy | [
"def",
"amips",
"(",
"tet_vertices",
",",
"inverse_offset_matrix",
")",
":",
"_validate_tet_vertices",
"(",
"tet_vertices",
")",
"# split the tensor",
"A",
",",
"B",
",",
"C",
",",
"D",
"=",
"torch",
".",
"split",
"(",
"tet_vertices",
",",
"split_size_or_sections",
"=",
"1",
",",
"dim",
"=",
"2",
")",
"# compute the offset matrix of the tetrahedrons w.r.t. vertex A.",
"offset_matrix",
"=",
"torch",
".",
"cat",
"(",
"[",
"B",
"-",
"A",
",",
"C",
"-",
"A",
",",
"D",
"-",
"A",
"]",
",",
"dim",
"=",
"2",
")",
"# compute the Jacobian for each tetrahedron - the Jacobian represents the unique 3D deformation that transforms the",
"# tetrahedron t into a regular tetrahedron.",
"jacobian",
"=",
"torch",
".",
"matmul",
"(",
"offset_matrix",
",",
"inverse_offset_matrix",
")",
"# compute determinant of Jacobian",
"j_det",
"=",
"torch",
".",
"det",
"(",
"jacobian",
")",
"# compute the trace of J * J.T",
"jacobian_squared",
"=",
"torch",
".",
"matmul",
"(",
"jacobian",
",",
"torch",
".",
"transpose",
"(",
"jacobian",
",",
"-",
"2",
",",
"-",
"1",
")",
")",
"trace",
"=",
"torch",
".",
"diagonal",
"(",
"jacobian_squared",
",",
"dim1",
"=",
"-",
"2",
",",
"dim2",
"=",
"-",
"1",
")",
".",
"sum",
"(",
"-",
"1",
")",
"# compute the determinant of the Jacobian to the 2/3",
"EPS",
"=",
"1e-10",
"denominator",
"=",
"torch",
".",
"pow",
"(",
"torch",
".",
"pow",
"(",
"j_det",
",",
"2",
")",
"+",
"EPS",
",",
"1",
"/",
"3",
")",
"# compute amips energy for positive tetrahedrons whose determinant of their Jacobian is positive",
"amips_energy",
"=",
"torch",
".",
"mean",
"(",
"torch",
".",
"div",
"(",
"trace",
",",
"denominator",
")",
"*",
"(",
"j_det",
">=",
"0",
")",
".",
"float",
"(",
")",
",",
"dim",
"=",
"1",
",",
"keepdim",
"=",
"True",
")",
"return",
"amips_energy"
] | https://github.com/NVIDIAGameWorks/kaolin/blob/e5148d05e9c1e2ce92a07881ce3593b1c5c3f166/kaolin/metrics/tetmesh.py#L112-L195 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_gdi.py | python | Font.GetNoAntiAliasing | (*args, **kwargs) | return _gdi_.Font_GetNoAntiAliasing(*args, **kwargs) | GetNoAntiAliasing(self) -> bool | GetNoAntiAliasing(self) -> bool | [
"GetNoAntiAliasing",
"(",
"self",
")",
"-",
">",
"bool"
] | def GetNoAntiAliasing(*args, **kwargs):
"""GetNoAntiAliasing(self) -> bool"""
return _gdi_.Font_GetNoAntiAliasing(*args, **kwargs) | [
"def",
"GetNoAntiAliasing",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Font_GetNoAntiAliasing",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L2433-L2435 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | benchmarks/distributed/rpc/rl/launcher.py | python | main | () | r"""
Runs rpc benchmark once if no argument has multiple entries, and otherwise once for each of the multiple entries.
Multiple entries is indicated by comma separated values, and may only be done for a single argument.
Results are printed as well as saved to output file. In case of multiple entries for a single argument,
the plot repo can be used to benchmark results on the y axis with each entry on the x axis. | r"""
Runs rpc benchmark once if no argument has multiple entries, and otherwise once for each of the multiple entries.
Multiple entries is indicated by comma separated values, and may only be done for a single argument.
Results are printed as well as saved to output file. In case of multiple entries for a single argument,
the plot repo can be used to benchmark results on the y axis with each entry on the x axis. | [
"r",
"Runs",
"rpc",
"benchmark",
"once",
"if",
"no",
"argument",
"has",
"multiple",
"entries",
"and",
"otherwise",
"once",
"for",
"each",
"of",
"the",
"multiple",
"entries",
".",
"Multiple",
"entries",
"is",
"indicated",
"by",
"comma",
"separated",
"values",
"and",
"may",
"only",
"be",
"done",
"for",
"a",
"single",
"argument",
".",
"Results",
"are",
"printed",
"as",
"well",
"as",
"saved",
"to",
"output",
"file",
".",
"In",
"case",
"of",
"multiple",
"entries",
"for",
"a",
"single",
"argument",
"the",
"plot",
"repo",
"can",
"be",
"used",
"to",
"benchmark",
"results",
"on",
"the",
"y",
"axis",
"with",
"each",
"entry",
"on",
"the",
"x",
"axis",
"."
] | def main():
r"""
Runs rpc benchmark once if no argument has multiple entries, and otherwise once for each of the multiple entries.
Multiple entries is indicated by comma separated values, and may only be done for a single argument.
Results are printed as well as saved to output file. In case of multiple entries for a single argument,
the plot repo can be used to benchmark results on the y axis with each entry on the x axis.
"""
find_graph_variable(args)
# run once if no x axis variables
x_axis_variables = args[args['x_axis_name']] if args.get('x_axis_name') else [None]
ctx = mp.get_context('spawn')
queue = ctx.SimpleQueue()
benchmark_runs = []
for i, x_axis_variable in enumerate(x_axis_variables): # run benchmark for every x axis variable
if len(x_axis_variables) > 1:
args[args['x_axis_name']] = x_axis_variable # set x axis variable for this benchmark iteration
processes = []
start_time = time.time()
for rank in range(args['world_size']):
prc = ctx.Process(
target=run_worker,
args=(
rank, args['world_size'], args['master_addr'], args['master_port'],
args['batch'], args['state_size'], args['nlayers'],
args['out_features'], queue
)
)
prc.start()
processes.append(prc)
benchmark_run_results = queue.get()
for process in processes:
process.join()
print(f"Time taken benchmark run {i} -, {time.time() - start_time}")
if args.get('x_axis_name'):
# save x axis value was for this iteration in the results
benchmark_run_results[args['x_axis_name']] = x_axis_variable
benchmark_runs.append(benchmark_run_results)
report = args
report['benchmark_results'] = benchmark_runs
if args.get('x_axis_name'):
# x_axis_name was variable so dont save a constant in the report for that variable
del report[args['x_axis_name']]
with open(args['output_file_path'], 'w') as f:
json.dump(report, f)
print_benchmark_results(report) | [
"def",
"main",
"(",
")",
":",
"find_graph_variable",
"(",
"args",
")",
"# run once if no x axis variables",
"x_axis_variables",
"=",
"args",
"[",
"args",
"[",
"'x_axis_name'",
"]",
"]",
"if",
"args",
".",
"get",
"(",
"'x_axis_name'",
")",
"else",
"[",
"None",
"]",
"ctx",
"=",
"mp",
".",
"get_context",
"(",
"'spawn'",
")",
"queue",
"=",
"ctx",
".",
"SimpleQueue",
"(",
")",
"benchmark_runs",
"=",
"[",
"]",
"for",
"i",
",",
"x_axis_variable",
"in",
"enumerate",
"(",
"x_axis_variables",
")",
":",
"# run benchmark for every x axis variable",
"if",
"len",
"(",
"x_axis_variables",
")",
">",
"1",
":",
"args",
"[",
"args",
"[",
"'x_axis_name'",
"]",
"]",
"=",
"x_axis_variable",
"# set x axis variable for this benchmark iteration",
"processes",
"=",
"[",
"]",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"for",
"rank",
"in",
"range",
"(",
"args",
"[",
"'world_size'",
"]",
")",
":",
"prc",
"=",
"ctx",
".",
"Process",
"(",
"target",
"=",
"run_worker",
",",
"args",
"=",
"(",
"rank",
",",
"args",
"[",
"'world_size'",
"]",
",",
"args",
"[",
"'master_addr'",
"]",
",",
"args",
"[",
"'master_port'",
"]",
",",
"args",
"[",
"'batch'",
"]",
",",
"args",
"[",
"'state_size'",
"]",
",",
"args",
"[",
"'nlayers'",
"]",
",",
"args",
"[",
"'out_features'",
"]",
",",
"queue",
")",
")",
"prc",
".",
"start",
"(",
")",
"processes",
".",
"append",
"(",
"prc",
")",
"benchmark_run_results",
"=",
"queue",
".",
"get",
"(",
")",
"for",
"process",
"in",
"processes",
":",
"process",
".",
"join",
"(",
")",
"print",
"(",
"f\"Time taken benchmark run {i} -, {time.time() - start_time}\"",
")",
"if",
"args",
".",
"get",
"(",
"'x_axis_name'",
")",
":",
"# save x axis value was for this iteration in the results",
"benchmark_run_results",
"[",
"args",
"[",
"'x_axis_name'",
"]",
"]",
"=",
"x_axis_variable",
"benchmark_runs",
".",
"append",
"(",
"benchmark_run_results",
")",
"report",
"=",
"args",
"report",
"[",
"'benchmark_results'",
"]",
"=",
"benchmark_runs",
"if",
"args",
".",
"get",
"(",
"'x_axis_name'",
")",
":",
"# x_axis_name was variable so dont save a constant in the report for that variable",
"del",
"report",
"[",
"args",
"[",
"'x_axis_name'",
"]",
"]",
"with",
"open",
"(",
"args",
"[",
"'output_file_path'",
"]",
",",
"'w'",
")",
"as",
"f",
":",
"json",
".",
"dump",
"(",
"report",
",",
"f",
")",
"print_benchmark_results",
"(",
"report",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/benchmarks/distributed/rpc/rl/launcher.py#L164-L210 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | SettableHeaderColumn.SetFlags | (*args, **kwargs) | return _core_.SettableHeaderColumn_SetFlags(*args, **kwargs) | SetFlags(self, int flags) | SetFlags(self, int flags) | [
"SetFlags",
"(",
"self",
"int",
"flags",
")"
] | def SetFlags(*args, **kwargs):
"""SetFlags(self, int flags)"""
return _core_.SettableHeaderColumn_SetFlags(*args, **kwargs) | [
"def",
"SetFlags",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"SettableHeaderColumn_SetFlags",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L16480-L16482 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/logging/config.py | python | stopListening | () | Stop the listening server which was created with a call to listen(). | Stop the listening server which was created with a call to listen(). | [
"Stop",
"the",
"listening",
"server",
"which",
"was",
"created",
"with",
"a",
"call",
"to",
"listen",
"()",
"."
] | def stopListening():
"""
Stop the listening server which was created with a call to listen().
"""
global _listener
if _listener:
logging._acquireLock()
_listener.abort = 1
_listener = None
logging._releaseLock() | [
"def",
"stopListening",
"(",
")",
":",
"global",
"_listener",
"if",
"_listener",
":",
"logging",
".",
"_acquireLock",
"(",
")",
"_listener",
".",
"abort",
"=",
"1",
"_listener",
"=",
"None",
"logging",
".",
"_releaseLock",
"(",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/logging/config.py#L371-L380 | ||
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | qa/tasks/kclient.py | python | task | (ctx, config) | Mount/unmount a ``kernel`` client.
The config is optional and defaults to mounting on all clients. If
a config is given, it is expected to be a list of clients to do
this operation on. This lets you e.g. set up one client with
``ceph-fuse`` and another with ``kclient``.
``brxnet`` should be a Private IPv4 Address range, default range is
[192.168.0.0/16]
Example that mounts all clients::
tasks:
- ceph:
- kclient:
- interactive:
- brxnet: [192.168.0.0/16]
Example that uses both ``kclient` and ``ceph-fuse``::
tasks:
- ceph:
- ceph-fuse: [client.0]
- kclient: [client.1]
- interactive:
Pass a dictionary instead of lists to specify per-client config:
tasks:
-kclient:
client.0:
debug: true
mntopts: ["nowsync"]
:param ctx: Context
:param config: Configuration | Mount/unmount a ``kernel`` client. | [
"Mount",
"/",
"unmount",
"a",
"kernel",
"client",
"."
] | def task(ctx, config):
"""
Mount/unmount a ``kernel`` client.
The config is optional and defaults to mounting on all clients. If
a config is given, it is expected to be a list of clients to do
this operation on. This lets you e.g. set up one client with
``ceph-fuse`` and another with ``kclient``.
``brxnet`` should be a Private IPv4 Address range, default range is
[192.168.0.0/16]
Example that mounts all clients::
tasks:
- ceph:
- kclient:
- interactive:
- brxnet: [192.168.0.0/16]
Example that uses both ``kclient` and ``ceph-fuse``::
tasks:
- ceph:
- ceph-fuse: [client.0]
- kclient: [client.1]
- interactive:
Pass a dictionary instead of lists to specify per-client config:
tasks:
-kclient:
client.0:
debug: true
mntopts: ["nowsync"]
:param ctx: Context
:param config: Configuration
"""
log.info('Mounting kernel clients...')
if config is None:
ids = misc.all_roles_of_type(ctx.cluster, 'client')
client_roles = [f'client.{id_}' for id_ in ids]
config = dict([r, dict()] for r in client_roles)
elif isinstance(config, list):
client_roles = config
config = dict([r, dict()] for r in client_roles)
elif isinstance(config, dict):
client_roles = filter(lambda x: 'client.' in x, config.keys())
else:
raise ValueError(f"Invalid config object: {config} ({config.__class__})")
log.info(f"config is {config}")
clients = list(misc.get_clients(ctx=ctx, roles=client_roles))
test_dir = misc.get_testdir(ctx)
for id_, remote in clients:
KernelMount.cleanup_stale_netnses_and_bridge(remote)
mounts = {}
overrides = ctx.config.get('overrides', {}).get('kclient', {})
top_overrides = dict(filter(lambda x: 'client.' not in x[0], overrides.items()))
for id_, remote in clients:
entity = f"client.{id_}"
client_config = config.get(entity)
if client_config is None:
client_config = {}
# top level overrides
deep_merge(client_config, top_overrides)
# mount specific overrides
client_config_overrides = overrides.get(entity)
deep_merge(client_config, client_config_overrides)
log.info(f"{entity} config is {client_config}")
cephfs_name = client_config.get("cephfs_name")
if config.get("disabled", False) or not client_config.get('mounted', True):
continue
kernel_mount = KernelMount(
ctx=ctx,
test_dir=test_dir,
client_id=id_,
client_remote=remote,
brxnet=ctx.teuthology_config.get('brxnet', None),
client_config=client_config,
cephfs_name=cephfs_name)
mounts[id_] = kernel_mount
if client_config.get('debug', False):
remote.run(args=["sudo", "bash", "-c", "echo 'module ceph +p' > /sys/kernel/debug/dynamic_debug/control"])
remote.run(args=["sudo", "bash", "-c", "echo 'module libceph +p' > /sys/kernel/debug/dynamic_debug/control"])
kernel_mount.mount(mntopts=client_config.get('mntopts', []))
def umount_all():
log.info('Unmounting kernel clients...')
forced = False
for mount in mounts.values():
if mount.is_mounted():
try:
mount.umount()
except (CommandFailedError, MaxWhileTries):
log.warning("Ordinary umount failed, forcing...")
forced = True
mount.umount_wait(force=True)
for id_, remote in clients:
KernelMount.cleanup_stale_netnses_and_bridge(remote)
return forced
ctx.mounts = mounts
try:
yield mounts
except:
umount_all() # ignore forced retval, we are already in error handling
finally:
forced = umount_all()
if forced:
# The context managers within the kclient manager worked (i.e.
# the test workload passed) but for some reason we couldn't
# umount, so turn this into a test failure.
raise RuntimeError("Kernel mounts did not umount cleanly") | [
"def",
"task",
"(",
"ctx",
",",
"config",
")",
":",
"log",
".",
"info",
"(",
"'Mounting kernel clients...'",
")",
"if",
"config",
"is",
"None",
":",
"ids",
"=",
"misc",
".",
"all_roles_of_type",
"(",
"ctx",
".",
"cluster",
",",
"'client'",
")",
"client_roles",
"=",
"[",
"f'client.{id_}'",
"for",
"id_",
"in",
"ids",
"]",
"config",
"=",
"dict",
"(",
"[",
"r",
",",
"dict",
"(",
")",
"]",
"for",
"r",
"in",
"client_roles",
")",
"elif",
"isinstance",
"(",
"config",
",",
"list",
")",
":",
"client_roles",
"=",
"config",
"config",
"=",
"dict",
"(",
"[",
"r",
",",
"dict",
"(",
")",
"]",
"for",
"r",
"in",
"client_roles",
")",
"elif",
"isinstance",
"(",
"config",
",",
"dict",
")",
":",
"client_roles",
"=",
"filter",
"(",
"lambda",
"x",
":",
"'client.'",
"in",
"x",
",",
"config",
".",
"keys",
"(",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"f\"Invalid config object: {config} ({config.__class__})\"",
")",
"log",
".",
"info",
"(",
"f\"config is {config}\"",
")",
"clients",
"=",
"list",
"(",
"misc",
".",
"get_clients",
"(",
"ctx",
"=",
"ctx",
",",
"roles",
"=",
"client_roles",
")",
")",
"test_dir",
"=",
"misc",
".",
"get_testdir",
"(",
"ctx",
")",
"for",
"id_",
",",
"remote",
"in",
"clients",
":",
"KernelMount",
".",
"cleanup_stale_netnses_and_bridge",
"(",
"remote",
")",
"mounts",
"=",
"{",
"}",
"overrides",
"=",
"ctx",
".",
"config",
".",
"get",
"(",
"'overrides'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'kclient'",
",",
"{",
"}",
")",
"top_overrides",
"=",
"dict",
"(",
"filter",
"(",
"lambda",
"x",
":",
"'client.'",
"not",
"in",
"x",
"[",
"0",
"]",
",",
"overrides",
".",
"items",
"(",
")",
")",
")",
"for",
"id_",
",",
"remote",
"in",
"clients",
":",
"entity",
"=",
"f\"client.{id_}\"",
"client_config",
"=",
"config",
".",
"get",
"(",
"entity",
")",
"if",
"client_config",
"is",
"None",
":",
"client_config",
"=",
"{",
"}",
"# top level overrides",
"deep_merge",
"(",
"client_config",
",",
"top_overrides",
")",
"# mount specific overrides",
"client_config_overrides",
"=",
"overrides",
".",
"get",
"(",
"entity",
")",
"deep_merge",
"(",
"client_config",
",",
"client_config_overrides",
")",
"log",
".",
"info",
"(",
"f\"{entity} config is {client_config}\"",
")",
"cephfs_name",
"=",
"client_config",
".",
"get",
"(",
"\"cephfs_name\"",
")",
"if",
"config",
".",
"get",
"(",
"\"disabled\"",
",",
"False",
")",
"or",
"not",
"client_config",
".",
"get",
"(",
"'mounted'",
",",
"True",
")",
":",
"continue",
"kernel_mount",
"=",
"KernelMount",
"(",
"ctx",
"=",
"ctx",
",",
"test_dir",
"=",
"test_dir",
",",
"client_id",
"=",
"id_",
",",
"client_remote",
"=",
"remote",
",",
"brxnet",
"=",
"ctx",
".",
"teuthology_config",
".",
"get",
"(",
"'brxnet'",
",",
"None",
")",
",",
"client_config",
"=",
"client_config",
",",
"cephfs_name",
"=",
"cephfs_name",
")",
"mounts",
"[",
"id_",
"]",
"=",
"kernel_mount",
"if",
"client_config",
".",
"get",
"(",
"'debug'",
",",
"False",
")",
":",
"remote",
".",
"run",
"(",
"args",
"=",
"[",
"\"sudo\"",
",",
"\"bash\"",
",",
"\"-c\"",
",",
"\"echo 'module ceph +p' > /sys/kernel/debug/dynamic_debug/control\"",
"]",
")",
"remote",
".",
"run",
"(",
"args",
"=",
"[",
"\"sudo\"",
",",
"\"bash\"",
",",
"\"-c\"",
",",
"\"echo 'module libceph +p' > /sys/kernel/debug/dynamic_debug/control\"",
"]",
")",
"kernel_mount",
".",
"mount",
"(",
"mntopts",
"=",
"client_config",
".",
"get",
"(",
"'mntopts'",
",",
"[",
"]",
")",
")",
"def",
"umount_all",
"(",
")",
":",
"log",
".",
"info",
"(",
"'Unmounting kernel clients...'",
")",
"forced",
"=",
"False",
"for",
"mount",
"in",
"mounts",
".",
"values",
"(",
")",
":",
"if",
"mount",
".",
"is_mounted",
"(",
")",
":",
"try",
":",
"mount",
".",
"umount",
"(",
")",
"except",
"(",
"CommandFailedError",
",",
"MaxWhileTries",
")",
":",
"log",
".",
"warning",
"(",
"\"Ordinary umount failed, forcing...\"",
")",
"forced",
"=",
"True",
"mount",
".",
"umount_wait",
"(",
"force",
"=",
"True",
")",
"for",
"id_",
",",
"remote",
"in",
"clients",
":",
"KernelMount",
".",
"cleanup_stale_netnses_and_bridge",
"(",
"remote",
")",
"return",
"forced",
"ctx",
".",
"mounts",
"=",
"mounts",
"try",
":",
"yield",
"mounts",
"except",
":",
"umount_all",
"(",
")",
"# ignore forced retval, we are already in error handling",
"finally",
":",
"forced",
"=",
"umount_all",
"(",
")",
"if",
"forced",
":",
"# The context managers within the kclient manager worked (i.e.",
"# the test workload passed) but for some reason we couldn't",
"# umount, so turn this into a test failure.",
"raise",
"RuntimeError",
"(",
"\"Kernel mounts did not umount cleanly\"",
")"
] | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/kclient.py#L16-L144 | ||
bigartm/bigartm | 47e37f982de87aa67bfd475ff1f39da696b181b3 | 3rdparty/protobuf-3.0.0/python/google/protobuf/internal/containers.py | python | BaseContainer.__getitem__ | (self, key) | return self._values[key] | Retrieves item by the specified key. | Retrieves item by the specified key. | [
"Retrieves",
"item",
"by",
"the",
"specified",
"key",
"."
] | def __getitem__(self, key):
"""Retrieves item by the specified key."""
return self._values[key] | [
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"return",
"self",
".",
"_values",
"[",
"key",
"]"
] | https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/python/google/protobuf/internal/containers.py#L202-L204 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/framework/tensor_shape.py | python | TensorShape.__bool__ | (self) | return self._dims is not None | Returns True if this shape contains non-zero information. | Returns True if this shape contains non-zero information. | [
"Returns",
"True",
"if",
"this",
"shape",
"contains",
"non",
"-",
"zero",
"information",
"."
] | def __bool__(self):
"""Returns True if this shape contains non-zero information."""
return self._dims is not None | [
"def",
"__bool__",
"(",
"self",
")",
":",
"return",
"self",
".",
"_dims",
"is",
"not",
"None"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/framework/tensor_shape.py#L481-L483 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/estimator.py | python | Estimator.__init__ | (self,
model_fn=None,
model_dir=None,
config=None,
params=None) | Constructs an Estimator instance.
Args:
model_fn: Model function, takes features and targets tensors or dicts of
tensors and returns predictions and loss tensors.
Supports next three signatures for the function:
* `(features, targets) -> (predictions, loss, train_op)`
* `(features, targets, mode) -> (predictions, loss, train_op)`
* `(features, targets, mode, params) -> (predictions, loss, train_op)`
Where
* `features` are single `Tensor` or `dict` of `Tensor`s
(depending on data passed to `fit`),
* `targets` are `Tensor` or `dict` of `Tensor`s (for multi-head
models). If mode is `ModeKeys.INFER`, `targets=None` will be
passed. If the `model_fn`'s signature does not accept
`mode`, the `model_fn` must still be able to handle
`targets=None`.
* `mode` represents if this training, evaluation or
prediction. See `ModeKeys`.
* `params` is a `dict` of hyperparameters. Will receive what
is passed to Estimator in `params` parameter. This allows
to configure Estimators from hyper parameter tunning.
model_dir: Directory to save model parameters, graph and etc. This can
also be used to load checkpoints from the directory into a estimator to
continue training a previously saved model.
config: Configuration object.
params: `dict` of hyper parameters that will be passed into `model_fn`.
Keys are names of parameters, values are basic python types.
Raises:
ValueError: parameters of `model_fn` don't match `params`. | Constructs an Estimator instance. | [
"Constructs",
"an",
"Estimator",
"instance",
"."
] | def __init__(self,
model_fn=None,
model_dir=None,
config=None,
params=None):
"""Constructs an Estimator instance.
Args:
model_fn: Model function, takes features and targets tensors or dicts of
tensors and returns predictions and loss tensors.
Supports next three signatures for the function:
* `(features, targets) -> (predictions, loss, train_op)`
* `(features, targets, mode) -> (predictions, loss, train_op)`
* `(features, targets, mode, params) -> (predictions, loss, train_op)`
Where
* `features` are single `Tensor` or `dict` of `Tensor`s
(depending on data passed to `fit`),
* `targets` are `Tensor` or `dict` of `Tensor`s (for multi-head
models). If mode is `ModeKeys.INFER`, `targets=None` will be
passed. If the `model_fn`'s signature does not accept
`mode`, the `model_fn` must still be able to handle
`targets=None`.
* `mode` represents if this training, evaluation or
prediction. See `ModeKeys`.
* `params` is a `dict` of hyperparameters. Will receive what
is passed to Estimator in `params` parameter. This allows
to configure Estimators from hyper parameter tunning.
model_dir: Directory to save model parameters, graph and etc. This can
also be used to load checkpoints from the directory into a estimator to
continue training a previously saved model.
config: Configuration object.
params: `dict` of hyper parameters that will be passed into `model_fn`.
Keys are names of parameters, values are basic python types.
Raises:
ValueError: parameters of `model_fn` don't match `params`.
"""
super(Estimator, self).__init__(model_dir=model_dir, config=config)
if model_fn is not None:
# Check number of arguments of the given function matches requirements.
model_fn_args = _get_arguments(model_fn)
if params is not None and 'params' not in model_fn_args:
raise ValueError('Estimator\'s model_fn (%s) has less than 4 '
'arguments, but not None params (%s) are passed.' %
(model_fn, params))
if params is None and 'params' in model_fn_args:
logging.warning('Estimator\'s model_fn (%s) has includes params '
'argument, but params are not passed to Estimator.',
model_fn)
self._model_fn = model_fn
self.params = params | [
"def",
"__init__",
"(",
"self",
",",
"model_fn",
"=",
"None",
",",
"model_dir",
"=",
"None",
",",
"config",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"super",
"(",
"Estimator",
",",
"self",
")",
".",
"__init__",
"(",
"model_dir",
"=",
"model_dir",
",",
"config",
"=",
"config",
")",
"if",
"model_fn",
"is",
"not",
"None",
":",
"# Check number of arguments of the given function matches requirements.",
"model_fn_args",
"=",
"_get_arguments",
"(",
"model_fn",
")",
"if",
"params",
"is",
"not",
"None",
"and",
"'params'",
"not",
"in",
"model_fn_args",
":",
"raise",
"ValueError",
"(",
"'Estimator\\'s model_fn (%s) has less than 4 '",
"'arguments, but not None params (%s) are passed.'",
"%",
"(",
"model_fn",
",",
"params",
")",
")",
"if",
"params",
"is",
"None",
"and",
"'params'",
"in",
"model_fn_args",
":",
"logging",
".",
"warning",
"(",
"'Estimator\\'s model_fn (%s) has includes params '",
"'argument, but params are not passed to Estimator.'",
",",
"model_fn",
")",
"self",
".",
"_model_fn",
"=",
"model_fn",
"self",
".",
"params",
"=",
"params"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/estimator.py#L669-L723 | ||
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/gyp/msvs_emulation.py | python | MsvsSettings.AdjustLibraries | (libraries) | return [lib + '.lib' if not lib.lower().endswith('.lib') else lib for lib in libs] | Strip -l from library if it's specified with that. | Strip -l from library if it's specified with that. | [
"Strip",
"-",
"l",
"from",
"library",
"if",
"it",
"s",
"specified",
"with",
"that",
"."
] | def AdjustLibraries(libraries):
"""Strip -l from library if it's specified with that."""
libs = [lib[2:] if lib.startswith('-l') else lib for lib in libraries]
return [lib + '.lib' if not lib.lower().endswith('.lib') else lib for lib in libs] | [
"def",
"AdjustLibraries",
"(",
"libraries",
")",
":",
"libs",
"=",
"[",
"lib",
"[",
"2",
":",
"]",
"if",
"lib",
".",
"startswith",
"(",
"'-l'",
")",
"else",
"lib",
"for",
"lib",
"in",
"libraries",
"]",
"return",
"[",
"lib",
"+",
"'.lib'",
"if",
"not",
"lib",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.lib'",
")",
"else",
"lib",
"for",
"lib",
"in",
"libs",
"]"
] | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/msvs_emulation.py#L251-L254 | |
luliyucoordinate/Leetcode | 96afcdc54807d1d184e881a075d1dbf3371e31fb | src/0162-Find-Peak-Element/0162.py | python | Solution.findPeakElement | (self, nums) | return l | :type nums: List[int]
:rtype: int | :type nums: List[int]
:rtype: int | [
":",
"type",
"nums",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"int"
] | def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l, r = 0, len(nums)-1
while l < r:
mid = (l + r)//2
if nums[mid] <= nums[mid+1]:
l = mid + 1
else:
r = mid
return l | [
"def",
"findPeakElement",
"(",
"self",
",",
"nums",
")",
":",
"l",
",",
"r",
"=",
"0",
",",
"len",
"(",
"nums",
")",
"-",
"1",
"while",
"l",
"<",
"r",
":",
"mid",
"=",
"(",
"l",
"+",
"r",
")",
"//",
"2",
"if",
"nums",
"[",
"mid",
"]",
"<=",
"nums",
"[",
"mid",
"+",
"1",
"]",
":",
"l",
"=",
"mid",
"+",
"1",
"else",
":",
"r",
"=",
"mid",
"return",
"l"
] | https://github.com/luliyucoordinate/Leetcode/blob/96afcdc54807d1d184e881a075d1dbf3371e31fb/src/0162-Find-Peak-Element/0162.py#L2-L15 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_controls.py | python | SpinButton.GetClassDefaultAttributes | (*args, **kwargs) | return _controls_.SpinButton_GetClassDefaultAttributes(*args, **kwargs) | GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this. | GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes | [
"GetClassDefaultAttributes",
"(",
"int",
"variant",
"=",
"WINDOW_VARIANT_NORMAL",
")",
"-",
">",
"VisualAttributes"
] | def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.SpinButton_GetClassDefaultAttributes(*args, **kwargs) | [
"def",
"GetClassDefaultAttributes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"SpinButton_GetClassDefaultAttributes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L2286-L2301 | |
dmtcp/dmtcp | 48a23686e1ce6784829b783ced9c62a14d620507 | util/cpplint.py | python | RemoveMultiLineCommentsFromRange | (lines, begin, end) | Clears a range of lines for multi-line comments. | Clears a range of lines for multi-line comments. | [
"Clears",
"a",
"range",
"of",
"lines",
"for",
"multi",
"-",
"line",
"comments",
"."
] | def RemoveMultiLineCommentsFromRange(lines, begin, end):
"""Clears a range of lines for multi-line comments."""
# Having // dummy comments makes the lines non-empty, so we will not get
# unnecessary blank line warnings later in the code.
for i in range(begin, end):
lines[i] = '/**/' | [
"def",
"RemoveMultiLineCommentsFromRange",
"(",
"lines",
",",
"begin",
",",
"end",
")",
":",
"# Having // dummy comments makes the lines non-empty, so we will not get",
"# unnecessary blank line warnings later in the code.",
"for",
"i",
"in",
"range",
"(",
"begin",
",",
"end",
")",
":",
"lines",
"[",
"i",
"]",
"=",
"'/**/'"
] | https://github.com/dmtcp/dmtcp/blob/48a23686e1ce6784829b783ced9c62a14d620507/util/cpplint.py#L1357-L1362 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/functools.py | python | _lt_from_le | (self, other, NotImplemented=NotImplemented) | return op_result and self != other | Return a < b. Computed by @total_ordering from (a <= b) and (a != b). | Return a < b. Computed by | [
"Return",
"a",
"<",
"b",
".",
"Computed",
"by"
] | def _lt_from_le(self, other, NotImplemented=NotImplemented):
'Return a < b. Computed by @total_ordering from (a <= b) and (a != b).'
op_result = self.__le__(other)
if op_result is NotImplemented:
return op_result
return op_result and self != other | [
"def",
"_lt_from_le",
"(",
"self",
",",
"other",
",",
"NotImplemented",
"=",
"NotImplemented",
")",
":",
"op_result",
"=",
"self",
".",
"__le__",
"(",
"other",
")",
"if",
"op_result",
"is",
"NotImplemented",
":",
"return",
"op_result",
"return",
"op_result",
"and",
"self",
"!=",
"other"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/functools.py#L117-L122 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython-genutils/ipython_genutils/encoding.py | python | get_stream_enc | (stream, default=None) | Return the given stream's encoding or a default.
There are cases where ``sys.std*`` might not actually be a stream, so
check for the encoding attribute prior to returning it, and return
a default if it doesn't exist or evaluates as False. ``default``
is None if not provided. | Return the given stream's encoding or a default. | [
"Return",
"the",
"given",
"stream",
"s",
"encoding",
"or",
"a",
"default",
"."
] | def get_stream_enc(stream, default=None):
"""Return the given stream's encoding or a default.
There are cases where ``sys.std*`` might not actually be a stream, so
check for the encoding attribute prior to returning it, and return
a default if it doesn't exist or evaluates as False. ``default``
is None if not provided.
"""
if not hasattr(stream, 'encoding') or not stream.encoding:
return default
else:
return stream.encoding | [
"def",
"get_stream_enc",
"(",
"stream",
",",
"default",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"stream",
",",
"'encoding'",
")",
"or",
"not",
"stream",
".",
"encoding",
":",
"return",
"default",
"else",
":",
"return",
"stream",
".",
"encoding"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython-genutils/ipython_genutils/encoding.py#L21-L32 | ||
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | Alignment/MillePedeAlignmentAlgorithm/scripts/mps_alisetup.py | python | SetupAlignment._check_iov_definition | (self) | return problematic_gt_inputs | Check consistency of input alignment payloads and IOV definition.
Returns a dictionary with the information needed to override possibly
problematic input taken from the global tag. | Check consistency of input alignment payloads and IOV definition.
Returns a dictionary with the information needed to override possibly
problematic input taken from the global tag. | [
"Check",
"consistency",
"of",
"input",
"alignment",
"payloads",
"and",
"IOV",
"definition",
".",
"Returns",
"a",
"dictionary",
"with",
"the",
"information",
"needed",
"to",
"override",
"possibly",
"problematic",
"input",
"taken",
"from",
"the",
"global",
"tag",
"."
] | def _check_iov_definition(self):
"""
Check consistency of input alignment payloads and IOV definition.
Returns a dictionary with the information needed to override possibly
problematic input taken from the global tag.
"""
print("Checking consistency of IOV definition...")
iovs = mps_tools.make_unique_runranges(self._cms_process.AlignmentProducer)
inputs = {
"TrackerAlignmentRcd": None,
"TrackerSurfaceDeformationRcd": None,
"TrackerAlignmentErrorExtendedRcd": None,
}
for condition in self._cms_process.GlobalTag.toGet.value():
if condition.record.value() in inputs:
inputs[condition.record.value()] = {
"tag": condition.tag.value(),
"connect": ("pro"
if not condition.hasParameter("connect")
else condition.connect.value())
}
inputs_from_gt = [record for record in inputs if inputs[record] is None]
inputs.update(
mps_tools.get_tags(self._cms_process.GlobalTag.globaltag.value(),
inputs_from_gt))
if int(self._first_run) != iovs[0]: # simple consistency check
if iovs[0] == 1 and len(iovs) == 1:
print("Single IOV output detected in configuration and", end=' ')
print("'FirstRunForStartGeometry' is not 1.")
print("Creating single IOV output from input conditions in run", end=' ')
print(self._first_run+".")
for inp in inputs: inputs[inp]["problematic"] = True
else:
print("Value of 'FirstRunForStartGeometry' has to match first", end=' ')
print("defined output IOV:", end=' ')
print(self._first_run, "!=", iovs[0])
sys.exit(1)
for inp in inputs.values():
inp["iovs"] = mps_tools.get_iovs(inp["connect"], inp["tag"])
# check consistency of input with output
problematic_gt_inputs = {}
input_indices = {key: len(value["iovs"]) -1
for key,value in inputs.items()}
for iov in reversed(iovs):
for inp in inputs:
if inputs[inp].pop("problematic", False):
problematic_gt_inputs[inp] = inputs[inp]
if inp in problematic_gt_inputs: continue
if input_indices[inp] < 0:
print("First output IOV boundary at run", iov, end=' ')
print("is before the first input IOV boundary at", end=' ')
print(inputs[inp]["iovs"][0], "for '"+inp+"'.")
print("Please check your run range selection.")
sys.exit(1)
input_iov = inputs[inp]["iovs"][input_indices[inp]]
if iov < input_iov:
if inp in inputs_from_gt:
problematic_gt_inputs[inp] = inputs[inp]
print("Found problematic input taken from global tag.")
print("Input IOV boundary at run",input_iov, end=' ')
print("for '"+inp+"' is within output IOV starting", end=' ')
print("with run", str(iov)+".")
print("Deriving an alignment with coarse IOV", end=' ')
print("granularity starting from finer granularity", end=' ')
print("leads to wrong results.")
print("A single IOV input using the IOV of", end=' ')
print("'FirstRunForStartGeometry' ("+self._first_run+")", end=' ')
print("is automatically created and used.")
continue
print("Found input IOV boundary at run",input_iov, end=' ')
print("for '"+inp+"' which is within output IOV starting", end=' ')
print("with run", str(iov)+".")
print("Deriving an alignment with coarse IOV granularity", end=' ')
print("starting from finer granularity leads to wrong", end=' ')
print("results.")
print("Please check your run range selection.")
sys.exit(1)
elif iov == input_iov:
input_indices[inp] -= 1
# check consistency of 'TrackerAlignmentRcd' with other inputs
input_indices = {key: len(value["iovs"]) -1
for key,value in inputs.items()
if (key != "TrackerAlignmentRcd")
and (inp not in problematic_gt_inputs)}
for iov in reversed(inputs["TrackerAlignmentRcd"]["iovs"]):
for inp in input_indices:
input_iov = inputs[inp]["iovs"][input_indices[inp]]
if iov < input_iov:
print("Found input IOV boundary at run",input_iov, end=' ')
print("for '"+inp+"' which is within 'TrackerAlignmentRcd'", end=' ')
print("IOV starting with run", str(iov)+".")
print("Deriving an alignment with inconsistent IOV boundaries", end=' ')
print("leads to wrong results.")
print("Please check your input IOVs.")
sys.exit(1)
elif iov == input_iov:
input_indices[inp] -= 1
print(" -> IOV consistency check successful.")
print("="*75)
return problematic_gt_inputs | [
"def",
"_check_iov_definition",
"(",
"self",
")",
":",
"print",
"(",
"\"Checking consistency of IOV definition...\"",
")",
"iovs",
"=",
"mps_tools",
".",
"make_unique_runranges",
"(",
"self",
".",
"_cms_process",
".",
"AlignmentProducer",
")",
"inputs",
"=",
"{",
"\"TrackerAlignmentRcd\"",
":",
"None",
",",
"\"TrackerSurfaceDeformationRcd\"",
":",
"None",
",",
"\"TrackerAlignmentErrorExtendedRcd\"",
":",
"None",
",",
"}",
"for",
"condition",
"in",
"self",
".",
"_cms_process",
".",
"GlobalTag",
".",
"toGet",
".",
"value",
"(",
")",
":",
"if",
"condition",
".",
"record",
".",
"value",
"(",
")",
"in",
"inputs",
":",
"inputs",
"[",
"condition",
".",
"record",
".",
"value",
"(",
")",
"]",
"=",
"{",
"\"tag\"",
":",
"condition",
".",
"tag",
".",
"value",
"(",
")",
",",
"\"connect\"",
":",
"(",
"\"pro\"",
"if",
"not",
"condition",
".",
"hasParameter",
"(",
"\"connect\"",
")",
"else",
"condition",
".",
"connect",
".",
"value",
"(",
")",
")",
"}",
"inputs_from_gt",
"=",
"[",
"record",
"for",
"record",
"in",
"inputs",
"if",
"inputs",
"[",
"record",
"]",
"is",
"None",
"]",
"inputs",
".",
"update",
"(",
"mps_tools",
".",
"get_tags",
"(",
"self",
".",
"_cms_process",
".",
"GlobalTag",
".",
"globaltag",
".",
"value",
"(",
")",
",",
"inputs_from_gt",
")",
")",
"if",
"int",
"(",
"self",
".",
"_first_run",
")",
"!=",
"iovs",
"[",
"0",
"]",
":",
"# simple consistency check",
"if",
"iovs",
"[",
"0",
"]",
"==",
"1",
"and",
"len",
"(",
"iovs",
")",
"==",
"1",
":",
"print",
"(",
"\"Single IOV output detected in configuration and\"",
",",
"end",
"=",
"' '",
")",
"print",
"(",
"\"'FirstRunForStartGeometry' is not 1.\"",
")",
"print",
"(",
"\"Creating single IOV output from input conditions in run\"",
",",
"end",
"=",
"' '",
")",
"print",
"(",
"self",
".",
"_first_run",
"+",
"\".\"",
")",
"for",
"inp",
"in",
"inputs",
":",
"inputs",
"[",
"inp",
"]",
"[",
"\"problematic\"",
"]",
"=",
"True",
"else",
":",
"print",
"(",
"\"Value of 'FirstRunForStartGeometry' has to match first\"",
",",
"end",
"=",
"' '",
")",
"print",
"(",
"\"defined output IOV:\"",
",",
"end",
"=",
"' '",
")",
"print",
"(",
"self",
".",
"_first_run",
",",
"\"!=\"",
",",
"iovs",
"[",
"0",
"]",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"for",
"inp",
"in",
"inputs",
".",
"values",
"(",
")",
":",
"inp",
"[",
"\"iovs\"",
"]",
"=",
"mps_tools",
".",
"get_iovs",
"(",
"inp",
"[",
"\"connect\"",
"]",
",",
"inp",
"[",
"\"tag\"",
"]",
")",
"# check consistency of input with output",
"problematic_gt_inputs",
"=",
"{",
"}",
"input_indices",
"=",
"{",
"key",
":",
"len",
"(",
"value",
"[",
"\"iovs\"",
"]",
")",
"-",
"1",
"for",
"key",
",",
"value",
"in",
"inputs",
".",
"items",
"(",
")",
"}",
"for",
"iov",
"in",
"reversed",
"(",
"iovs",
")",
":",
"for",
"inp",
"in",
"inputs",
":",
"if",
"inputs",
"[",
"inp",
"]",
".",
"pop",
"(",
"\"problematic\"",
",",
"False",
")",
":",
"problematic_gt_inputs",
"[",
"inp",
"]",
"=",
"inputs",
"[",
"inp",
"]",
"if",
"inp",
"in",
"problematic_gt_inputs",
":",
"continue",
"if",
"input_indices",
"[",
"inp",
"]",
"<",
"0",
":",
"print",
"(",
"\"First output IOV boundary at run\"",
",",
"iov",
",",
"end",
"=",
"' '",
")",
"print",
"(",
"\"is before the first input IOV boundary at\"",
",",
"end",
"=",
"' '",
")",
"print",
"(",
"inputs",
"[",
"inp",
"]",
"[",
"\"iovs\"",
"]",
"[",
"0",
"]",
",",
"\"for '\"",
"+",
"inp",
"+",
"\"'.\"",
")",
"print",
"(",
"\"Please check your run range selection.\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"input_iov",
"=",
"inputs",
"[",
"inp",
"]",
"[",
"\"iovs\"",
"]",
"[",
"input_indices",
"[",
"inp",
"]",
"]",
"if",
"iov",
"<",
"input_iov",
":",
"if",
"inp",
"in",
"inputs_from_gt",
":",
"problematic_gt_inputs",
"[",
"inp",
"]",
"=",
"inputs",
"[",
"inp",
"]",
"print",
"(",
"\"Found problematic input taken from global tag.\"",
")",
"print",
"(",
"\"Input IOV boundary at run\"",
",",
"input_iov",
",",
"end",
"=",
"' '",
")",
"print",
"(",
"\"for '\"",
"+",
"inp",
"+",
"\"' is within output IOV starting\"",
",",
"end",
"=",
"' '",
")",
"print",
"(",
"\"with run\"",
",",
"str",
"(",
"iov",
")",
"+",
"\".\"",
")",
"print",
"(",
"\"Deriving an alignment with coarse IOV\"",
",",
"end",
"=",
"' '",
")",
"print",
"(",
"\"granularity starting from finer granularity\"",
",",
"end",
"=",
"' '",
")",
"print",
"(",
"\"leads to wrong results.\"",
")",
"print",
"(",
"\"A single IOV input using the IOV of\"",
",",
"end",
"=",
"' '",
")",
"print",
"(",
"\"'FirstRunForStartGeometry' (\"",
"+",
"self",
".",
"_first_run",
"+",
"\")\"",
",",
"end",
"=",
"' '",
")",
"print",
"(",
"\"is automatically created and used.\"",
")",
"continue",
"print",
"(",
"\"Found input IOV boundary at run\"",
",",
"input_iov",
",",
"end",
"=",
"' '",
")",
"print",
"(",
"\"for '\"",
"+",
"inp",
"+",
"\"' which is within output IOV starting\"",
",",
"end",
"=",
"' '",
")",
"print",
"(",
"\"with run\"",
",",
"str",
"(",
"iov",
")",
"+",
"\".\"",
")",
"print",
"(",
"\"Deriving an alignment with coarse IOV granularity\"",
",",
"end",
"=",
"' '",
")",
"print",
"(",
"\"starting from finer granularity leads to wrong\"",
",",
"end",
"=",
"' '",
")",
"print",
"(",
"\"results.\"",
")",
"print",
"(",
"\"Please check your run range selection.\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"elif",
"iov",
"==",
"input_iov",
":",
"input_indices",
"[",
"inp",
"]",
"-=",
"1",
"# check consistency of 'TrackerAlignmentRcd' with other inputs",
"input_indices",
"=",
"{",
"key",
":",
"len",
"(",
"value",
"[",
"\"iovs\"",
"]",
")",
"-",
"1",
"for",
"key",
",",
"value",
"in",
"inputs",
".",
"items",
"(",
")",
"if",
"(",
"key",
"!=",
"\"TrackerAlignmentRcd\"",
")",
"and",
"(",
"inp",
"not",
"in",
"problematic_gt_inputs",
")",
"}",
"for",
"iov",
"in",
"reversed",
"(",
"inputs",
"[",
"\"TrackerAlignmentRcd\"",
"]",
"[",
"\"iovs\"",
"]",
")",
":",
"for",
"inp",
"in",
"input_indices",
":",
"input_iov",
"=",
"inputs",
"[",
"inp",
"]",
"[",
"\"iovs\"",
"]",
"[",
"input_indices",
"[",
"inp",
"]",
"]",
"if",
"iov",
"<",
"input_iov",
":",
"print",
"(",
"\"Found input IOV boundary at run\"",
",",
"input_iov",
",",
"end",
"=",
"' '",
")",
"print",
"(",
"\"for '\"",
"+",
"inp",
"+",
"\"' which is within 'TrackerAlignmentRcd'\"",
",",
"end",
"=",
"' '",
")",
"print",
"(",
"\"IOV starting with run\"",
",",
"str",
"(",
"iov",
")",
"+",
"\".\"",
")",
"print",
"(",
"\"Deriving an alignment with inconsistent IOV boundaries\"",
",",
"end",
"=",
"' '",
")",
"print",
"(",
"\"leads to wrong results.\"",
")",
"print",
"(",
"\"Please check your input IOVs.\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"elif",
"iov",
"==",
"input_iov",
":",
"input_indices",
"[",
"inp",
"]",
"-=",
"1",
"print",
"(",
"\" -> IOV consistency check successful.\"",
")",
"print",
"(",
"\"=\"",
"*",
"75",
")",
"return",
"problematic_gt_inputs"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Alignment/MillePedeAlignmentAlgorithm/scripts/mps_alisetup.py#L531-L640 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/perspective.py | python | PerspectiveManager.SetAutoPerspective | (self) | Set the current perspective management into automatic mode
@postcondition: window is set into | Set the current perspective management into automatic mode
@postcondition: window is set into | [
"Set",
"the",
"current",
"perspective",
"management",
"into",
"automatic",
"mode",
"@postcondition",
":",
"window",
"is",
"set",
"into"
] | def SetAutoPerspective(self):
"""Set the current perspective management into automatic mode
@postcondition: window is set into
"""
self._currview = AUTO_PERSPECTIVE
self.UpdateAutoPerspective() | [
"def",
"SetAutoPerspective",
"(",
"self",
")",
":",
"self",
".",
"_currview",
"=",
"AUTO_PERSPECTIVE",
"self",
".",
"UpdateAutoPerspective",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/perspective.py#L339-L345 | ||
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | gr-fft/python/fft/logpwrfft.py | python | _logpwrfft_base.set_vec_rate | (self, vec_rate) | Set the vector rate on stream decimator.
Args:
vec_rate: the new vector rate | Set the vector rate on stream decimator. | [
"Set",
"the",
"vector",
"rate",
"on",
"stream",
"decimator",
"."
] | def set_vec_rate(self, vec_rate):
"""
Set the vector rate on stream decimator.
Args:
vec_rate: the new vector rate
"""
self._sd.set_vec_rate(vec_rate) | [
"def",
"set_vec_rate",
"(",
"self",
",",
"vec_rate",
")",
":",
"self",
".",
"_sd",
".",
"set_vec_rate",
"(",
"vec_rate",
")"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-fft/python/fft/logpwrfft.py#L85-L92 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/jinja2/environment.py | python | Environment.lex | (self, source, name=None, filename=None) | Lex the given sourcecode and return a generator that yields
tokens as tuples in the form ``(lineno, token_type, value)``.
This can be useful for :ref:`extension development <writing-extensions>`
and debugging templates.
This does not perform preprocessing. If you want the preprocessing
of the extensions to be applied you have to filter source through
the :meth:`preprocess` method. | Lex the given sourcecode and return a generator that yields
tokens as tuples in the form ``(lineno, token_type, value)``.
This can be useful for :ref:`extension development <writing-extensions>`
and debugging templates. | [
"Lex",
"the",
"given",
"sourcecode",
"and",
"return",
"a",
"generator",
"that",
"yields",
"tokens",
"as",
"tuples",
"in",
"the",
"form",
"(",
"lineno",
"token_type",
"value",
")",
".",
"This",
"can",
"be",
"useful",
"for",
":",
"ref",
":",
"extension",
"development",
"<writing",
"-",
"extensions",
">",
"and",
"debugging",
"templates",
"."
] | def lex(self, source, name=None, filename=None):
"""Lex the given sourcecode and return a generator that yields
tokens as tuples in the form ``(lineno, token_type, value)``.
This can be useful for :ref:`extension development <writing-extensions>`
and debugging templates.
This does not perform preprocessing. If you want the preprocessing
of the extensions to be applied you have to filter source through
the :meth:`preprocess` method.
"""
source = text_type(source)
try:
return self.lexer.tokeniter(source, name, filename)
except TemplateSyntaxError:
exc_info = sys.exc_info()
self.handle_exception(exc_info, source_hint=source) | [
"def",
"lex",
"(",
"self",
",",
"source",
",",
"name",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"source",
"=",
"text_type",
"(",
"source",
")",
"try",
":",
"return",
"self",
".",
"lexer",
".",
"tokeniter",
"(",
"source",
",",
"name",
",",
"filename",
")",
"except",
"TemplateSyntaxError",
":",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"self",
".",
"handle_exception",
"(",
"exc_info",
",",
"source_hint",
"=",
"source",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/jinja2/environment.py#L499-L514 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tix.py | python | Grid.edit_apply | (self) | If any cell is being edited, de-highlight the cell and applies
the changes. | If any cell is being edited, de-highlight the cell and applies
the changes. | [
"If",
"any",
"cell",
"is",
"being",
"edited",
"de",
"-",
"highlight",
"the",
"cell",
"and",
"applies",
"the",
"changes",
"."
] | def edit_apply(self):
"""If any cell is being edited, de-highlight the cell and applies
the changes."""
self.tk.call(self, 'edit', 'apply') | [
"def",
"edit_apply",
"(",
"self",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
",",
"'edit'",
",",
"'apply'",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tix.py#L1846-L1849 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/_vendor/pyparsing.py | python | ParseBaseException._from_exception | (cls, pe) | return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement) | internal factory method to simplify creating one type of ParseException
from another - avoids having __init__ signature conflicts among subclasses | internal factory method to simplify creating one type of ParseException
from another - avoids having __init__ signature conflicts among subclasses | [
"internal",
"factory",
"method",
"to",
"simplify",
"creating",
"one",
"type",
"of",
"ParseException",
"from",
"another",
"-",
"avoids",
"having",
"__init__",
"signature",
"conflicts",
"among",
"subclasses"
] | def _from_exception(cls, pe):
"""
internal factory method to simplify creating one type of ParseException
from another - avoids having __init__ signature conflicts among subclasses
"""
return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement) | [
"def",
"_from_exception",
"(",
"cls",
",",
"pe",
")",
":",
"return",
"cls",
"(",
"pe",
".",
"pstr",
",",
"pe",
".",
"loc",
",",
"pe",
".",
"msg",
",",
"pe",
".",
"parserElement",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/_vendor/pyparsing.py#L221-L226 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/categorical.py | python | Categorical._get_codes | (self) | return v | Get the codes.
Returns
-------
codes : integer array view
A non writable view of the `codes` array. | Get the codes. | [
"Get",
"the",
"codes",
"."
] | def _get_codes(self):
"""
Get the codes.
Returns
-------
codes : integer array view
A non writable view of the `codes` array.
"""
v = self._codes.view()
v.flags.writeable = False
return v | [
"def",
"_get_codes",
"(",
"self",
")",
":",
"v",
"=",
"self",
".",
"_codes",
".",
"view",
"(",
")",
"v",
".",
"flags",
".",
"writeable",
"=",
"False",
"return",
"v"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/categorical.py#L662-L673 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/aui.py | python | AuiPaneInfo.IsResizable | (*args, **kwargs) | return _aui.AuiPaneInfo_IsResizable(*args, **kwargs) | IsResizable(self) -> bool | IsResizable(self) -> bool | [
"IsResizable",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsResizable(*args, **kwargs):
"""IsResizable(self) -> bool"""
return _aui.AuiPaneInfo_IsResizable(*args, **kwargs) | [
"def",
"IsResizable",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiPaneInfo_IsResizable",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L245-L247 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/sipdistutils.py | python | build_ext._get_sip_output_list | (self, sbf) | Parse the sbf file specified to extract the name of the generated source
files. Make them absolute assuming they reside in the temp directory. | Parse the sbf file specified to extract the name of the generated source
files. Make them absolute assuming they reside in the temp directory. | [
"Parse",
"the",
"sbf",
"file",
"specified",
"to",
"extract",
"the",
"name",
"of",
"the",
"generated",
"source",
"files",
".",
"Make",
"them",
"absolute",
"assuming",
"they",
"reside",
"in",
"the",
"temp",
"directory",
"."
] | def _get_sip_output_list(self, sbf):
"""
Parse the sbf file specified to extract the name of the generated source
files. Make them absolute assuming they reside in the temp directory.
"""
for L in open(sbf).readlines():
key, value = L.split("=", 1)
if key.strip() == "sources":
out = []
for o in value.split():
out.append(os.path.join(self._sip_output_dir(), o))
return out
raise RuntimeError("cannot parse SIP-generated '%s'" % sbf) | [
"def",
"_get_sip_output_list",
"(",
"self",
",",
"sbf",
")",
":",
"for",
"L",
"in",
"open",
"(",
"sbf",
")",
".",
"readlines",
"(",
")",
":",
"key",
",",
"value",
"=",
"L",
".",
"split",
"(",
"\"=\"",
",",
"1",
")",
"if",
"key",
".",
"strip",
"(",
")",
"==",
"\"sources\"",
":",
"out",
"=",
"[",
"]",
"for",
"o",
"in",
"value",
".",
"split",
"(",
")",
":",
"out",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_sip_output_dir",
"(",
")",
",",
"o",
")",
")",
"return",
"out",
"raise",
"RuntimeError",
"(",
"\"cannot parse SIP-generated '%s'\"",
"%",
"sbf",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/sipdistutils.py#L53-L66 | ||
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | clang/bindings/python/clang/cindex.py | python | Cursor.is_scoped_enum | (self) | return conf.lib.clang_EnumDecl_isScoped(self) | Returns True if the cursor refers to a scoped enum declaration. | Returns True if the cursor refers to a scoped enum declaration. | [
"Returns",
"True",
"if",
"the",
"cursor",
"refers",
"to",
"a",
"scoped",
"enum",
"declaration",
"."
] | def is_scoped_enum(self):
"""Returns True if the cursor refers to a scoped enum declaration.
"""
return conf.lib.clang_EnumDecl_isScoped(self) | [
"def",
"is_scoped_enum",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_EnumDecl_isScoped",
"(",
"self",
")"
] | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/clang/bindings/python/clang/cindex.py#L1506-L1509 | |
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | gnuradio-runtime/python/gnuradio/gr/qa_random.py | python | test_random.test_006_xoroshiro128p_reproducibility | (self) | Make sure two RNGs with the same seed yield the same
sequence | Make sure two RNGs with the same seed yield the same
sequence | [
"Make",
"sure",
"two",
"RNGs",
"with",
"the",
"same",
"seed",
"yield",
"the",
"same",
"sequence"
] | def test_006_xoroshiro128p_reproducibility(self):
"""
Make sure two RNGs with the same seed yield the same
sequence
"""
seed = 123456
N = 10000
rng1 = gr.xoroshiro128p_prng(123456)
rng2 = gr.xoroshiro128p_prng(123456)
self.assertSequenceEqual(
tuple(rng1() for _ in range(N)),
tuple(rng2() for _ in range(N))) | [
"def",
"test_006_xoroshiro128p_reproducibility",
"(",
"self",
")",
":",
"seed",
"=",
"123456",
"N",
"=",
"10000",
"rng1",
"=",
"gr",
".",
"xoroshiro128p_prng",
"(",
"123456",
")",
"rng2",
"=",
"gr",
".",
"xoroshiro128p_prng",
"(",
"123456",
")",
"self",
".",
"assertSequenceEqual",
"(",
"tuple",
"(",
"rng1",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"N",
")",
")",
",",
"tuple",
"(",
"rng2",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"N",
")",
")",
")"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gnuradio-runtime/python/gnuradio/gr/qa_random.py#L77-L88 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/dataset.py | python | BoxPSDataset.end_pass | (self, need_save_delta) | End Pass
Notify BoxPS that current pass ended
Examples:
.. code-block:: python
import paddle.fluid as fluid
dataset = fluid.DatasetFactory().create_dataset("BoxPSDataset")
dataset.end_pass(True) | End Pass
Notify BoxPS that current pass ended
Examples:
.. code-block:: python | [
"End",
"Pass",
"Notify",
"BoxPS",
"that",
"current",
"pass",
"ended",
"Examples",
":",
"..",
"code",
"-",
"block",
"::",
"python"
] | def end_pass(self, need_save_delta):
"""
End Pass
Notify BoxPS that current pass ended
Examples:
.. code-block:: python
import paddle.fluid as fluid
dataset = fluid.DatasetFactory().create_dataset("BoxPSDataset")
dataset.end_pass(True)
"""
self.boxps.end_pass(need_save_delta) | [
"def",
"end_pass",
"(",
"self",
",",
"need_save_delta",
")",
":",
"self",
".",
"boxps",
".",
"end_pass",
"(",
"need_save_delta",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/dataset.py#L1214-L1225 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/jinja2/ext.py | python | babel_extract | (fileobj, keywords, comment_tags, options) | Babel extraction method for Jinja templates.
.. versionchanged:: 2.3
Basic support for translation comments was added. If `comment_tags`
is now set to a list of keywords for extraction, the extractor will
try to find the best preceeding comment that begins with one of the
keywords. For best results, make sure to not have more than one
gettext call in one line of code and the matching comment in the
same line or the line before.
.. versionchanged:: 2.5.1
The `newstyle_gettext` flag can be set to `True` to enable newstyle
gettext calls.
.. versionchanged:: 2.7
A `silent` option can now be provided. If set to `False` template
syntax errors are propagated instead of being ignored.
:param fileobj: the file-like object the messages should be extracted from
:param keywords: a list of keywords (i.e. function names) that should be
recognized as translation functions
:param comment_tags: a list of translator tags to search for and include
in the results.
:param options: a dictionary of additional options (optional)
:return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
(comments will be empty currently) | Babel extraction method for Jinja templates. | [
"Babel",
"extraction",
"method",
"for",
"Jinja",
"templates",
"."
] | def babel_extract(fileobj, keywords, comment_tags, options):
"""Babel extraction method for Jinja templates.
.. versionchanged:: 2.3
Basic support for translation comments was added. If `comment_tags`
is now set to a list of keywords for extraction, the extractor will
try to find the best preceeding comment that begins with one of the
keywords. For best results, make sure to not have more than one
gettext call in one line of code and the matching comment in the
same line or the line before.
.. versionchanged:: 2.5.1
The `newstyle_gettext` flag can be set to `True` to enable newstyle
gettext calls.
.. versionchanged:: 2.7
A `silent` option can now be provided. If set to `False` template
syntax errors are propagated instead of being ignored.
:param fileobj: the file-like object the messages should be extracted from
:param keywords: a list of keywords (i.e. function names) that should be
recognized as translation functions
:param comment_tags: a list of translator tags to search for and include
in the results.
:param options: a dictionary of additional options (optional)
:return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
(comments will be empty currently)
"""
extensions = set()
for extension in options.get('extensions', '').split(','):
extension = extension.strip()
if not extension:
continue
extensions.add(import_string(extension))
if InternationalizationExtension not in extensions:
extensions.add(InternationalizationExtension)
def getbool(options, key, default=False):
return options.get(key, str(default)).lower() in \
('1', 'on', 'yes', 'true')
silent = getbool(options, 'silent', True)
environment = Environment(
options.get('block_start_string', BLOCK_START_STRING),
options.get('block_end_string', BLOCK_END_STRING),
options.get('variable_start_string', VARIABLE_START_STRING),
options.get('variable_end_string', VARIABLE_END_STRING),
options.get('comment_start_string', COMMENT_START_STRING),
options.get('comment_end_string', COMMENT_END_STRING),
options.get('line_statement_prefix') or LINE_STATEMENT_PREFIX,
options.get('line_comment_prefix') or LINE_COMMENT_PREFIX,
getbool(options, 'trim_blocks', TRIM_BLOCKS),
getbool(options, 'lstrip_blocks', LSTRIP_BLOCKS),
NEWLINE_SEQUENCE,
getbool(options, 'keep_trailing_newline', KEEP_TRAILING_NEWLINE),
frozenset(extensions),
cache_size=0,
auto_reload=False
)
if getbool(options, 'newstyle_gettext'):
environment.newstyle_gettext = True
source = fileobj.read().decode(options.get('encoding', 'utf-8'))
try:
node = environment.parse(source)
tokens = list(environment.lex(environment.preprocess(source)))
except TemplateSyntaxError as e:
if not silent:
raise
# skip templates with syntax errors
return
finder = _CommentFinder(tokens, comment_tags)
for lineno, func, message in extract_from_ast(node, keywords):
yield lineno, func, message, finder.find_comments(lineno) | [
"def",
"babel_extract",
"(",
"fileobj",
",",
"keywords",
",",
"comment_tags",
",",
"options",
")",
":",
"extensions",
"=",
"set",
"(",
")",
"for",
"extension",
"in",
"options",
".",
"get",
"(",
"'extensions'",
",",
"''",
")",
".",
"split",
"(",
"','",
")",
":",
"extension",
"=",
"extension",
".",
"strip",
"(",
")",
"if",
"not",
"extension",
":",
"continue",
"extensions",
".",
"add",
"(",
"import_string",
"(",
"extension",
")",
")",
"if",
"InternationalizationExtension",
"not",
"in",
"extensions",
":",
"extensions",
".",
"add",
"(",
"InternationalizationExtension",
")",
"def",
"getbool",
"(",
"options",
",",
"key",
",",
"default",
"=",
"False",
")",
":",
"return",
"options",
".",
"get",
"(",
"key",
",",
"str",
"(",
"default",
")",
")",
".",
"lower",
"(",
")",
"in",
"(",
"'1'",
",",
"'on'",
",",
"'yes'",
",",
"'true'",
")",
"silent",
"=",
"getbool",
"(",
"options",
",",
"'silent'",
",",
"True",
")",
"environment",
"=",
"Environment",
"(",
"options",
".",
"get",
"(",
"'block_start_string'",
",",
"BLOCK_START_STRING",
")",
",",
"options",
".",
"get",
"(",
"'block_end_string'",
",",
"BLOCK_END_STRING",
")",
",",
"options",
".",
"get",
"(",
"'variable_start_string'",
",",
"VARIABLE_START_STRING",
")",
",",
"options",
".",
"get",
"(",
"'variable_end_string'",
",",
"VARIABLE_END_STRING",
")",
",",
"options",
".",
"get",
"(",
"'comment_start_string'",
",",
"COMMENT_START_STRING",
")",
",",
"options",
".",
"get",
"(",
"'comment_end_string'",
",",
"COMMENT_END_STRING",
")",
",",
"options",
".",
"get",
"(",
"'line_statement_prefix'",
")",
"or",
"LINE_STATEMENT_PREFIX",
",",
"options",
".",
"get",
"(",
"'line_comment_prefix'",
")",
"or",
"LINE_COMMENT_PREFIX",
",",
"getbool",
"(",
"options",
",",
"'trim_blocks'",
",",
"TRIM_BLOCKS",
")",
",",
"getbool",
"(",
"options",
",",
"'lstrip_blocks'",
",",
"LSTRIP_BLOCKS",
")",
",",
"NEWLINE_SEQUENCE",
",",
"getbool",
"(",
"options",
",",
"'keep_trailing_newline'",
",",
"KEEP_TRAILING_NEWLINE",
")",
",",
"frozenset",
"(",
"extensions",
")",
",",
"cache_size",
"=",
"0",
",",
"auto_reload",
"=",
"False",
")",
"if",
"getbool",
"(",
"options",
",",
"'newstyle_gettext'",
")",
":",
"environment",
".",
"newstyle_gettext",
"=",
"True",
"source",
"=",
"fileobj",
".",
"read",
"(",
")",
".",
"decode",
"(",
"options",
".",
"get",
"(",
"'encoding'",
",",
"'utf-8'",
")",
")",
"try",
":",
"node",
"=",
"environment",
".",
"parse",
"(",
"source",
")",
"tokens",
"=",
"list",
"(",
"environment",
".",
"lex",
"(",
"environment",
".",
"preprocess",
"(",
"source",
")",
")",
")",
"except",
"TemplateSyntaxError",
"as",
"e",
":",
"if",
"not",
"silent",
":",
"raise",
"# skip templates with syntax errors",
"return",
"finder",
"=",
"_CommentFinder",
"(",
"tokens",
",",
"comment_tags",
")",
"for",
"lineno",
",",
"func",
",",
"message",
"in",
"extract_from_ast",
"(",
"node",
",",
"keywords",
")",
":",
"yield",
"lineno",
",",
"func",
",",
"message",
",",
"finder",
".",
"find_comments",
"(",
"lineno",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/jinja2/ext.py#L553-L628 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/pyparse.py | python | Parser.set_lo | (self, lo) | Throw away the start of the string.
Intended to be called with the result of find_good_parse_start(). | Throw away the start of the string. | [
"Throw",
"away",
"the",
"start",
"of",
"the",
"string",
"."
] | def set_lo(self, lo):
""" Throw away the start of the string.
Intended to be called with the result of find_good_parse_start().
"""
assert lo == 0 or self.code[lo-1] == '\n'
if lo > 0:
self.code = self.code[lo:] | [
"def",
"set_lo",
"(",
"self",
",",
"lo",
")",
":",
"assert",
"lo",
"==",
"0",
"or",
"self",
".",
"code",
"[",
"lo",
"-",
"1",
"]",
"==",
"'\\n'",
"if",
"lo",
">",
"0",
":",
"self",
".",
"code",
"=",
"self",
".",
"code",
"[",
"lo",
":",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/pyparse.py#L192-L199 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/math_grad.py | python | _SegmentMinOrMaxGrad | (op, grad, is_sorted) | Gradient for SegmentMin and (unsorted) SegmentMax. They share similar code. | Gradient for SegmentMin and (unsorted) SegmentMax. They share similar code. | [
"Gradient",
"for",
"SegmentMin",
"and",
"(",
"unsorted",
")",
"SegmentMax",
".",
"They",
"share",
"similar",
"code",
"."
] | def _SegmentMinOrMaxGrad(op, grad, is_sorted):
"""Gradient for SegmentMin and (unsorted) SegmentMax. They share similar code."""
zeros = array_ops.zeros(array_ops.shape(op.inputs[0]),
dtype=op.inputs[0].dtype)
# Get the number of selected (minimum or maximum) elements in each segment.
gathered_outputs = array_ops.gather(op.outputs[0], op.inputs[1])
is_selected = math_ops.equal(op.inputs[0], gathered_outputs)
if is_sorted:
num_selected = math_ops.segment_sum(math_ops.cast(is_selected, grad.dtype),
op.inputs[1])
else:
num_selected = math_ops.unsorted_segment_sum(math_ops.cast(is_selected, grad.dtype),
op.inputs[1], op.inputs[2])
# Compute the gradient for each segment. The gradient for the ith segment is
# divided evenly among the selected elements in that segment.
weighted_grads = math_ops.div(grad, num_selected)
gathered_grads = array_ops.gather(weighted_grads, op.inputs[1])
if is_sorted:
return array_ops.where(is_selected, gathered_grads, zeros), None
else:
return array_ops.where(is_selected, gathered_grads, zeros), None, None | [
"def",
"_SegmentMinOrMaxGrad",
"(",
"op",
",",
"grad",
",",
"is_sorted",
")",
":",
"zeros",
"=",
"array_ops",
".",
"zeros",
"(",
"array_ops",
".",
"shape",
"(",
"op",
".",
"inputs",
"[",
"0",
"]",
")",
",",
"dtype",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
".",
"dtype",
")",
"# Get the number of selected (minimum or maximum) elements in each segment.",
"gathered_outputs",
"=",
"array_ops",
".",
"gather",
"(",
"op",
".",
"outputs",
"[",
"0",
"]",
",",
"op",
".",
"inputs",
"[",
"1",
"]",
")",
"is_selected",
"=",
"math_ops",
".",
"equal",
"(",
"op",
".",
"inputs",
"[",
"0",
"]",
",",
"gathered_outputs",
")",
"if",
"is_sorted",
":",
"num_selected",
"=",
"math_ops",
".",
"segment_sum",
"(",
"math_ops",
".",
"cast",
"(",
"is_selected",
",",
"grad",
".",
"dtype",
")",
",",
"op",
".",
"inputs",
"[",
"1",
"]",
")",
"else",
":",
"num_selected",
"=",
"math_ops",
".",
"unsorted_segment_sum",
"(",
"math_ops",
".",
"cast",
"(",
"is_selected",
",",
"grad",
".",
"dtype",
")",
",",
"op",
".",
"inputs",
"[",
"1",
"]",
",",
"op",
".",
"inputs",
"[",
"2",
"]",
")",
"# Compute the gradient for each segment. The gradient for the ith segment is",
"# divided evenly among the selected elements in that segment.",
"weighted_grads",
"=",
"math_ops",
".",
"div",
"(",
"grad",
",",
"num_selected",
")",
"gathered_grads",
"=",
"array_ops",
".",
"gather",
"(",
"weighted_grads",
",",
"op",
".",
"inputs",
"[",
"1",
"]",
")",
"if",
"is_sorted",
":",
"return",
"array_ops",
".",
"where",
"(",
"is_selected",
",",
"gathered_grads",
",",
"zeros",
")",
",",
"None",
"else",
":",
"return",
"array_ops",
".",
"where",
"(",
"is_selected",
",",
"gathered_grads",
",",
"zeros",
")",
",",
"None",
",",
"None"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/math_grad.py#L193-L216 | ||
PaddlePaddle/PaddleOCR | b756bf5f8c90142e0d89d3db0163965c686b6ffe | ppocr/utils/e2e_utils/extract_textpoint_slow.py | python | softmax | (logits) | return dist | logits: N x d | logits: N x d | [
"logits",
":",
"N",
"x",
"d"
] | def softmax(logits):
"""
logits: N x d
"""
max_value = np.max(logits, axis=1, keepdims=True)
exp = np.exp(logits - max_value)
exp_sum = np.sum(exp, axis=1, keepdims=True)
dist = exp / exp_sum
return dist | [
"def",
"softmax",
"(",
"logits",
")",
":",
"max_value",
"=",
"np",
".",
"max",
"(",
"logits",
",",
"axis",
"=",
"1",
",",
"keepdims",
"=",
"True",
")",
"exp",
"=",
"np",
".",
"exp",
"(",
"logits",
"-",
"max_value",
")",
"exp_sum",
"=",
"np",
".",
"sum",
"(",
"exp",
",",
"axis",
"=",
"1",
",",
"keepdims",
"=",
"True",
")",
"dist",
"=",
"exp",
"/",
"exp_sum",
"return",
"dist"
] | https://github.com/PaddlePaddle/PaddleOCR/blob/b756bf5f8c90142e0d89d3db0163965c686b6ffe/ppocr/utils/e2e_utils/extract_textpoint_slow.py#L96-L104 | |
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | lldb/third_party/Python/module/pexpect-4.6/pexpect/utils.py | python | split_command_line | (command_line) | return arg_list | This splits a command line into a list of arguments. It splits arguments
on spaces, but handles embedded quotes, doublequotes, and escaped
characters. It's impossible to do this with a regular expression, so I
wrote a little state machine to parse the command line. | This splits a command line into a list of arguments. It splits arguments
on spaces, but handles embedded quotes, doublequotes, and escaped
characters. It's impossible to do this with a regular expression, so I
wrote a little state machine to parse the command line. | [
"This",
"splits",
"a",
"command",
"line",
"into",
"a",
"list",
"of",
"arguments",
".",
"It",
"splits",
"arguments",
"on",
"spaces",
"but",
"handles",
"embedded",
"quotes",
"doublequotes",
"and",
"escaped",
"characters",
".",
"It",
"s",
"impossible",
"to",
"do",
"this",
"with",
"a",
"regular",
"expression",
"so",
"I",
"wrote",
"a",
"little",
"state",
"machine",
"to",
"parse",
"the",
"command",
"line",
"."
] | def split_command_line(command_line):
'''This splits a command line into a list of arguments. It splits arguments
on spaces, but handles embedded quotes, doublequotes, and escaped
characters. It's impossible to do this with a regular expression, so I
wrote a little state machine to parse the command line. '''
arg_list = []
arg = ''
# Constants to name the states we can be in.
state_basic = 0
state_esc = 1
state_singlequote = 2
state_doublequote = 3
# The state when consuming whitespace between commands.
state_whitespace = 4
state = state_basic
for c in command_line:
if state == state_basic or state == state_whitespace:
if c == '\\':
# Escape the next character
state = state_esc
elif c == r"'":
# Handle single quote
state = state_singlequote
elif c == r'"':
# Handle double quote
state = state_doublequote
elif c.isspace():
# Add arg to arg_list if we aren't in the middle of whitespace.
if state == state_whitespace:
# Do nothing.
None
else:
arg_list.append(arg)
arg = ''
state = state_whitespace
else:
arg = arg + c
state = state_basic
elif state == state_esc:
arg = arg + c
state = state_basic
elif state == state_singlequote:
if c == r"'":
state = state_basic
else:
arg = arg + c
elif state == state_doublequote:
if c == r'"':
state = state_basic
else:
arg = arg + c
if arg != '':
arg_list.append(arg)
return arg_list | [
"def",
"split_command_line",
"(",
"command_line",
")",
":",
"arg_list",
"=",
"[",
"]",
"arg",
"=",
"''",
"# Constants to name the states we can be in.",
"state_basic",
"=",
"0",
"state_esc",
"=",
"1",
"state_singlequote",
"=",
"2",
"state_doublequote",
"=",
"3",
"# The state when consuming whitespace between commands.",
"state_whitespace",
"=",
"4",
"state",
"=",
"state_basic",
"for",
"c",
"in",
"command_line",
":",
"if",
"state",
"==",
"state_basic",
"or",
"state",
"==",
"state_whitespace",
":",
"if",
"c",
"==",
"'\\\\'",
":",
"# Escape the next character",
"state",
"=",
"state_esc",
"elif",
"c",
"==",
"r\"'\"",
":",
"# Handle single quote",
"state",
"=",
"state_singlequote",
"elif",
"c",
"==",
"r'\"'",
":",
"# Handle double quote",
"state",
"=",
"state_doublequote",
"elif",
"c",
".",
"isspace",
"(",
")",
":",
"# Add arg to arg_list if we aren't in the middle of whitespace.",
"if",
"state",
"==",
"state_whitespace",
":",
"# Do nothing.",
"None",
"else",
":",
"arg_list",
".",
"append",
"(",
"arg",
")",
"arg",
"=",
"''",
"state",
"=",
"state_whitespace",
"else",
":",
"arg",
"=",
"arg",
"+",
"c",
"state",
"=",
"state_basic",
"elif",
"state",
"==",
"state_esc",
":",
"arg",
"=",
"arg",
"+",
"c",
"state",
"=",
"state_basic",
"elif",
"state",
"==",
"state_singlequote",
":",
"if",
"c",
"==",
"r\"'\"",
":",
"state",
"=",
"state_basic",
"else",
":",
"arg",
"=",
"arg",
"+",
"c",
"elif",
"state",
"==",
"state_doublequote",
":",
"if",
"c",
"==",
"r'\"'",
":",
"state",
"=",
"state_basic",
"else",
":",
"arg",
"=",
"arg",
"+",
"c",
"if",
"arg",
"!=",
"''",
":",
"arg_list",
".",
"append",
"(",
"arg",
")",
"return",
"arg_list"
] | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/lldb/third_party/Python/module/pexpect-4.6/pexpect/utils.py#L69-L127 | |
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | tools/i-pi/ipi/utils/prng.py | python | Random.g | (self) | return self.rng.standard_normal() | Interface to the standard standard_normal() function.
Returns:
A pseudo-random number from a normal Gaussian distribution. | Interface to the standard standard_normal() function. | [
"Interface",
"to",
"the",
"standard",
"standard_normal",
"()",
"function",
"."
] | def g(self):
"""Interface to the standard standard_normal() function.
Returns:
A pseudo-random number from a normal Gaussian distribution.
"""
return self.rng.standard_normal() | [
"def",
"g",
"(",
"self",
")",
":",
"return",
"self",
".",
"rng",
".",
"standard_normal",
"(",
")"
] | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/utils/prng.py#L95-L102 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Explorer/Web_Browser_Suite.py | python | Web_Browser_Suite_Events.GetWindowInfo | (self, _object, _attributes={}, **_arguments) | GetWindowInfo: Returns a window info record (URL/Title) for the specified window.
Required argument: Window Identifier of the window
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: | GetWindowInfo: Returns a window info record (URL/Title) for the specified window.
Required argument: Window Identifier of the window
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: | [
"GetWindowInfo",
":",
"Returns",
"a",
"window",
"info",
"record",
"(",
"URL",
"/",
"Title",
")",
"for",
"the",
"specified",
"window",
".",
"Required",
"argument",
":",
"Window",
"Identifier",
"of",
"the",
"window",
"Keyword",
"argument",
"_attributes",
":",
"AppleEvent",
"attribute",
"dictionary",
"Returns",
":"
] | def GetWindowInfo(self, _object, _attributes={}, **_arguments):
"""GetWindowInfo: Returns a window info record (URL/Title) for the specified window.
Required argument: Window Identifier of the window
Keyword argument _attributes: AppleEvent attribute dictionary
Returns:
"""
_code = 'WWW!'
_subcode = 'WNFO'
if _arguments: raise TypeError, 'No optional args expected'
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.get('errn', 0):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----'] | [
"def",
"GetWindowInfo",
"(",
"self",
",",
"_object",
",",
"_attributes",
"=",
"{",
"}",
",",
"*",
"*",
"_arguments",
")",
":",
"_code",
"=",
"'WWW!'",
"_subcode",
"=",
"'WNFO'",
"if",
"_arguments",
":",
"raise",
"TypeError",
",",
"'No optional args expected'",
"_arguments",
"[",
"'----'",
"]",
"=",
"_object",
"_reply",
",",
"_arguments",
",",
"_attributes",
"=",
"self",
".",
"send",
"(",
"_code",
",",
"_subcode",
",",
"_arguments",
",",
"_attributes",
")",
"if",
"_arguments",
".",
"get",
"(",
"'errn'",
",",
"0",
")",
":",
"raise",
"aetools",
".",
"Error",
",",
"aetools",
".",
"decodeerror",
"(",
"_arguments",
")",
"# XXXX Optionally decode result",
"if",
"_arguments",
".",
"has_key",
"(",
"'----'",
")",
":",
"return",
"_arguments",
"[",
"'----'",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Explorer/Web_Browser_Suite.py#L83-L102 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | tools/fast_nvcc/fast_nvcc.py | python | fast_nvcc_warn | (warning: str) | Warn the user about something regarding fast_nvcc. | Warn the user about something regarding fast_nvcc. | [
"Warn",
"the",
"user",
"about",
"something",
"regarding",
"fast_nvcc",
"."
] | def fast_nvcc_warn(warning: str) -> None:
"""
Warn the user about something regarding fast_nvcc.
"""
print(f'warning (fast_nvcc): {warning}', file=sys.stderr) | [
"def",
"fast_nvcc_warn",
"(",
"warning",
":",
"str",
")",
"->",
"None",
":",
"print",
"(",
"f'warning (fast_nvcc): {warning}'",
",",
"file",
"=",
"sys",
".",
"stderr",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/tools/fast_nvcc/fast_nvcc.py#L84-L88 | ||
xiaohaoChen/rrc_detection | 4f2b110cd122da7f55e8533275a9b4809a88785a | scripts/cpp_lint.py | python | _NestingState.UpdatePreprocessor | (self, line) | Update preprocessor stack.
We need to handle preprocessors due to classes like this:
#ifdef SWIG
struct ResultDetailsPageElementExtensionPoint {
#else
struct ResultDetailsPageElementExtensionPoint : public Extension {
#endif
We make the following assumptions (good enough for most files):
- Preprocessor condition evaluates to true from #if up to first
#else/#elif/#endif.
- Preprocessor condition evaluates to false from #else/#elif up
to #endif. We still perform lint checks on these lines, but
these do not affect nesting stack.
Args:
line: current line to check. | Update preprocessor stack. | [
"Update",
"preprocessor",
"stack",
"."
] | def UpdatePreprocessor(self, line):
"""Update preprocessor stack.
We need to handle preprocessors due to classes like this:
#ifdef SWIG
struct ResultDetailsPageElementExtensionPoint {
#else
struct ResultDetailsPageElementExtensionPoint : public Extension {
#endif
We make the following assumptions (good enough for most files):
- Preprocessor condition evaluates to true from #if up to first
#else/#elif/#endif.
- Preprocessor condition evaluates to false from #else/#elif up
to #endif. We still perform lint checks on these lines, but
these do not affect nesting stack.
Args:
line: current line to check.
"""
if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):
# Beginning of #if block, save the nesting stack here. The saved
# stack will allow us to restore the parsing state in the #else case.
self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))
elif Match(r'^\s*#\s*(else|elif)\b', line):
# Beginning of #else block
if self.pp_stack:
if not self.pp_stack[-1].seen_else:
# This is the first #else or #elif block. Remember the
# whole nesting stack up to this point. This is what we
# keep after the #endif.
self.pp_stack[-1].seen_else = True
self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
# Restore the stack to how it was before the #if
self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
else:
# TODO(unknown): unexpected #else, issue warning?
pass
elif Match(r'^\s*#\s*endif\b', line):
# End of #if or #else blocks.
if self.pp_stack:
# If we saw an #else, we will need to restore the nesting
# stack to its former state before the #else, otherwise we
# will just continue from where we left off.
if self.pp_stack[-1].seen_else:
# Here we can just use a shallow copy since we are the last
# reference to it.
self.stack = self.pp_stack[-1].stack_before_else
# Drop the corresponding #if
self.pp_stack.pop()
else:
# TODO(unknown): unexpected #endif, issue warning?
pass | [
"def",
"UpdatePreprocessor",
"(",
"self",
",",
"line",
")",
":",
"if",
"Match",
"(",
"r'^\\s*#\\s*(if|ifdef|ifndef)\\b'",
",",
"line",
")",
":",
"# Beginning of #if block, save the nesting stack here. The saved",
"# stack will allow us to restore the parsing state in the #else case.",
"self",
".",
"pp_stack",
".",
"append",
"(",
"_PreprocessorInfo",
"(",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"stack",
")",
")",
")",
"elif",
"Match",
"(",
"r'^\\s*#\\s*(else|elif)\\b'",
",",
"line",
")",
":",
"# Beginning of #else block",
"if",
"self",
".",
"pp_stack",
":",
"if",
"not",
"self",
".",
"pp_stack",
"[",
"-",
"1",
"]",
".",
"seen_else",
":",
"# This is the first #else or #elif block. Remember the",
"# whole nesting stack up to this point. This is what we",
"# keep after the #endif.",
"self",
".",
"pp_stack",
"[",
"-",
"1",
"]",
".",
"seen_else",
"=",
"True",
"self",
".",
"pp_stack",
"[",
"-",
"1",
"]",
".",
"stack_before_else",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"stack",
")",
"# Restore the stack to how it was before the #if",
"self",
".",
"stack",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"pp_stack",
"[",
"-",
"1",
"]",
".",
"stack_before_if",
")",
"else",
":",
"# TODO(unknown): unexpected #else, issue warning?",
"pass",
"elif",
"Match",
"(",
"r'^\\s*#\\s*endif\\b'",
",",
"line",
")",
":",
"# End of #if or #else blocks.",
"if",
"self",
".",
"pp_stack",
":",
"# If we saw an #else, we will need to restore the nesting",
"# stack to its former state before the #else, otherwise we",
"# will just continue from where we left off.",
"if",
"self",
".",
"pp_stack",
"[",
"-",
"1",
"]",
".",
"seen_else",
":",
"# Here we can just use a shallow copy since we are the last",
"# reference to it.",
"self",
".",
"stack",
"=",
"self",
".",
"pp_stack",
"[",
"-",
"1",
"]",
".",
"stack_before_else",
"# Drop the corresponding #if",
"self",
".",
"pp_stack",
".",
"pop",
"(",
")",
"else",
":",
"# TODO(unknown): unexpected #endif, issue warning?",
"pass"
] | https://github.com/xiaohaoChen/rrc_detection/blob/4f2b110cd122da7f55e8533275a9b4809a88785a/scripts/cpp_lint.py#L1952-L2006 | ||
epam/Indigo | 30e40b4b1eb9bae0207435a26cfcb81ddcc42be1 | api/python/indigo/__init__.py | python | IndigoObject.at | (self, index) | return self.dispatcher.IndigoObject(
self.dispatcher,
self.dispatcher._checkResult(Indigo._lib.indigoAt(self.id, index)),
) | Loader method returns element by index
Args:
index (int): element index
Returns:
IndigoObject: element object | Loader method returns element by index | [
"Loader",
"method",
"returns",
"element",
"by",
"index"
] | def at(self, index):
"""Loader method returns element by index
Args:
index (int): element index
Returns:
IndigoObject: element object
"""
self.dispatcher._setSessionId()
return self.dispatcher.IndigoObject(
self.dispatcher,
self.dispatcher._checkResult(Indigo._lib.indigoAt(self.id, index)),
) | [
"def",
"at",
"(",
"self",
",",
"index",
")",
":",
"self",
".",
"dispatcher",
".",
"_setSessionId",
"(",
")",
"return",
"self",
".",
"dispatcher",
".",
"IndigoObject",
"(",
"self",
".",
"dispatcher",
",",
"self",
".",
"dispatcher",
".",
"_checkResult",
"(",
"Indigo",
".",
"_lib",
".",
"indigoAt",
"(",
"self",
".",
"id",
",",
"index",
")",
")",
",",
")"
] | https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/api/python/indigo/__init__.py#L3760-L3773 | |
google/iree | 1224bbdbe65b0d1fdf40e7324f60f68beeaf7c76 | integrations/tensorflow/iree-dialects/python/iree/compiler/dialects/iree_pydm/rtl/modules/macros.py | python | cmpnz_i32 | (stage: ImportStage, value: ir.Value) | return d.ApplyCompareOp(d.BoolType.get(), ir.StringAttr.get("ne"), value_i32,
zero).result | Promotes a numeric value to i32 and compares it to zero.
Returns True if not zero.
This should not be needed in the fullness of time but works around type
inference limitations in low level code. | Promotes a numeric value to i32 and compares it to zero. | [
"Promotes",
"a",
"numeric",
"value",
"to",
"i32",
"and",
"compares",
"it",
"to",
"zero",
"."
] | def cmpnz_i32(stage: ImportStage, value: ir.Value) -> ir.Value:
"""Promotes a numeric value to i32 and compares it to zero.
Returns True if not zero.
This should not be needed in the fullness of time but works around type
inference limitations in low level code.
"""
value_i32 = _unbox_i32(stage, value)
zero = _constant_i32(0)
return d.ApplyCompareOp(d.BoolType.get(), ir.StringAttr.get("ne"), value_i32,
zero).result | [
"def",
"cmpnz_i32",
"(",
"stage",
":",
"ImportStage",
",",
"value",
":",
"ir",
".",
"Value",
")",
"->",
"ir",
".",
"Value",
":",
"value_i32",
"=",
"_unbox_i32",
"(",
"stage",
",",
"value",
")",
"zero",
"=",
"_constant_i32",
"(",
"0",
")",
"return",
"d",
".",
"ApplyCompareOp",
"(",
"d",
".",
"BoolType",
".",
"get",
"(",
")",
",",
"ir",
".",
"StringAttr",
".",
"get",
"(",
"\"ne\"",
")",
",",
"value_i32",
",",
"zero",
")",
".",
"result"
] | https://github.com/google/iree/blob/1224bbdbe65b0d1fdf40e7324f60f68beeaf7c76/integrations/tensorflow/iree-dialects/python/iree/compiler/dialects/iree_pydm/rtl/modules/macros.py#L117-L127 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/mindrecord/tools/mnist_to_mr.py | python | MnistToMR._mnist_test_iterator | (self) | get data from mnist test data and label file.
Yields:
data (dict of list): mnist data list which contains dict. | get data from mnist test data and label file. | [
"get",
"data",
"from",
"mnist",
"test",
"data",
"and",
"label",
"file",
"."
] | def _mnist_test_iterator(self):
"""
get data from mnist test data and label file.
Yields:
data (dict of list): mnist data list which contains dict.
"""
test_data = self._extract_images(self.test_data_filename_)
test_labels = self._extract_labels(self.test_labels_filename_)
for data, label in zip(test_data, test_labels):
_, img = cv2.imencode(".jpeg", data)
yield {"label": int(label), "data": img.tobytes()} | [
"def",
"_mnist_test_iterator",
"(",
"self",
")",
":",
"test_data",
"=",
"self",
".",
"_extract_images",
"(",
"self",
".",
"test_data_filename_",
")",
"test_labels",
"=",
"self",
".",
"_extract_labels",
"(",
"self",
".",
"test_labels_filename_",
")",
"for",
"data",
",",
"label",
"in",
"zip",
"(",
"test_data",
",",
"test_labels",
")",
":",
"_",
",",
"img",
"=",
"cv2",
".",
"imencode",
"(",
"\".jpeg\"",
",",
"data",
")",
"yield",
"{",
"\"label\"",
":",
"int",
"(",
"label",
")",
",",
"\"data\"",
":",
"img",
".",
"tobytes",
"(",
")",
"}"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/mindrecord/tools/mnist_to_mr.py#L113-L124 | ||
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/v8/third_party/jinja2/runtime.py | python | Context.get_exported | (self) | return dict((k, self.vars[k]) for k in self.exported_vars) | Get a new dict with the exported variables. | Get a new dict with the exported variables. | [
"Get",
"a",
"new",
"dict",
"with",
"the",
"exported",
"variables",
"."
] | def get_exported(self):
"""Get a new dict with the exported variables."""
return dict((k, self.vars[k]) for k in self.exported_vars) | [
"def",
"get_exported",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"(",
"k",
",",
"self",
".",
"vars",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"self",
".",
"exported_vars",
")"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/v8/third_party/jinja2/runtime.py#L219-L221 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_gdi.py | python | Locale_GetInfo | (*args, **kwargs) | return _gdi_.Locale_GetInfo(*args, **kwargs) | Locale_GetInfo(int index, int cat=LOCALE_CAT_DEFAULT) -> String | Locale_GetInfo(int index, int cat=LOCALE_CAT_DEFAULT) -> String | [
"Locale_GetInfo",
"(",
"int",
"index",
"int",
"cat",
"=",
"LOCALE_CAT_DEFAULT",
")",
"-",
">",
"String"
] | def Locale_GetInfo(*args, **kwargs):
"""Locale_GetInfo(int index, int cat=LOCALE_CAT_DEFAULT) -> String"""
return _gdi_.Locale_GetInfo(*args, **kwargs) | [
"def",
"Locale_GetInfo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Locale_GetInfo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L3205-L3207 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftguitools/gui_lines.py | python | Line.removeTemporaryObject | (self) | Remove temporary object created. | Remove temporary object created. | [
"Remove",
"temporary",
"object",
"created",
"."
] | def removeTemporaryObject(self):
"""Remove temporary object created."""
if self.obj:
try:
old = self.obj.Name
except ReferenceError:
# object already deleted, for some reason
pass
else:
todo.ToDo.delay(self.doc.removeObject, old)
self.obj = None | [
"def",
"removeTemporaryObject",
"(",
"self",
")",
":",
"if",
"self",
".",
"obj",
":",
"try",
":",
"old",
"=",
"self",
".",
"obj",
".",
"Name",
"except",
"ReferenceError",
":",
"# object already deleted, for some reason",
"pass",
"else",
":",
"todo",
".",
"ToDo",
".",
"delay",
"(",
"self",
".",
"doc",
".",
"removeObject",
",",
"old",
")",
"self",
".",
"obj",
"=",
"None"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_lines.py#L195-L205 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/telemetry/telemetry/core/platform/__init__.py | python | Platform.LaunchApplication | (self, application, parameters=None,
elevate_privilege=False) | return self._platform_backend.LaunchApplication(
application, parameters, elevate_privilege=elevate_privilege) | Launches the given |application| with a list of |parameters| on the OS.
Set |elevate_privilege| to launch the application with root or admin rights.
Returns:
A popen style process handle for host platforms. | Launches the given |application| with a list of |parameters| on the OS. | [
"Launches",
"the",
"given",
"|application|",
"with",
"a",
"list",
"of",
"|parameters|",
"on",
"the",
"OS",
"."
] | def LaunchApplication(self, application, parameters=None,
elevate_privilege=False):
""""Launches the given |application| with a list of |parameters| on the OS.
Set |elevate_privilege| to launch the application with root or admin rights.
Returns:
A popen style process handle for host platforms.
"""
return self._platform_backend.LaunchApplication(
application, parameters, elevate_privilege=elevate_privilege) | [
"def",
"LaunchApplication",
"(",
"self",
",",
"application",
",",
"parameters",
"=",
"None",
",",
"elevate_privilege",
"=",
"False",
")",
":",
"return",
"self",
".",
"_platform_backend",
".",
"LaunchApplication",
"(",
"application",
",",
"parameters",
",",
"elevate_privilege",
"=",
"elevate_privilege",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/telemetry/core/platform/__init__.py#L109-L119 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/grid.py | python | GridEditorCreatedEvent.SetRow | (*args, **kwargs) | return _grid.GridEditorCreatedEvent_SetRow(*args, **kwargs) | SetRow(self, int row) | SetRow(self, int row) | [
"SetRow",
"(",
"self",
"int",
"row",
")"
] | def SetRow(*args, **kwargs):
"""SetRow(self, int row)"""
return _grid.GridEditorCreatedEvent_SetRow(*args, **kwargs) | [
"def",
"SetRow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"GridEditorCreatedEvent_SetRow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L2479-L2481 | |
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | contrib/src/sceneeditor/seParticles.py | python | Particles.getEmitter | (self) | return self.emitter | getEmitter() | getEmitter() | [
"getEmitter",
"()"
] | def getEmitter(self):
"""getEmitter()"""
return self.emitter | [
"def",
"getEmitter",
"(",
"self",
")",
":",
"return",
"self",
".",
"emitter"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/contrib/src/sceneeditor/seParticles.py#L196-L198 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/defchararray.py | python | chararray.upper | (self) | return asarray(upper(self)) | Return an array with the elements of `self` converted to
uppercase.
See also
--------
char.upper | Return an array with the elements of `self` converted to
uppercase. | [
"Return",
"an",
"array",
"with",
"the",
"elements",
"of",
"self",
"converted",
"to",
"uppercase",
"."
] | def upper(self):
"""
Return an array with the elements of `self` converted to
uppercase.
See also
--------
char.upper
"""
return asarray(upper(self)) | [
"def",
"upper",
"(",
"self",
")",
":",
"return",
"asarray",
"(",
"upper",
"(",
"self",
")",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/defchararray.py#L2427-L2437 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/internals/blocks.py | python | CategoricalBlock.concat_same_type | (self, to_concat, placement=None) | return make_block(
values, placement=placement or slice(0, len(values), 1),
ndim=self.ndim) | Concatenate list of single blocks of the same type.
Note that this CategoricalBlock._concat_same_type *may* not
return a CategoricalBlock. When the categories in `to_concat`
differ, this will return an object ndarray.
If / when we decide we don't like that behavior:
1. Change Categorical._concat_same_type to use union_categoricals
2. Delete this method. | Concatenate list of single blocks of the same type. | [
"Concatenate",
"list",
"of",
"single",
"blocks",
"of",
"the",
"same",
"type",
"."
] | def concat_same_type(self, to_concat, placement=None):
"""
Concatenate list of single blocks of the same type.
Note that this CategoricalBlock._concat_same_type *may* not
return a CategoricalBlock. When the categories in `to_concat`
differ, this will return an object ndarray.
If / when we decide we don't like that behavior:
1. Change Categorical._concat_same_type to use union_categoricals
2. Delete this method.
"""
values = self._concatenator([blk.values for blk in to_concat],
axis=self.ndim - 1)
# not using self.make_block_same_class as values can be object dtype
return make_block(
values, placement=placement or slice(0, len(values), 1),
ndim=self.ndim) | [
"def",
"concat_same_type",
"(",
"self",
",",
"to_concat",
",",
"placement",
"=",
"None",
")",
":",
"values",
"=",
"self",
".",
"_concatenator",
"(",
"[",
"blk",
".",
"values",
"for",
"blk",
"in",
"to_concat",
"]",
",",
"axis",
"=",
"self",
".",
"ndim",
"-",
"1",
")",
"# not using self.make_block_same_class as values can be object dtype",
"return",
"make_block",
"(",
"values",
",",
"placement",
"=",
"placement",
"or",
"slice",
"(",
"0",
",",
"len",
"(",
"values",
")",
",",
"1",
")",
",",
"ndim",
"=",
"self",
".",
"ndim",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/internals/blocks.py#L2983-L3001 | |
gem5/gem5 | 141cc37c2d4b93959d4c249b8f7e6a8b2ef75338 | util/minorview/model.py | python | BlobVisualData.get_inst | (self) | return None | Get an instruction Id (if any) from this data | Get an instruction Id (if any) from this data | [
"Get",
"an",
"instruction",
"Id",
"(",
"if",
"any",
")",
"from",
"this",
"data"
] | def get_inst(self):
"""Get an instruction Id (if any) from this data"""
return None | [
"def",
"get_inst",
"(",
"self",
")",
":",
"return",
"None"
] | https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/util/minorview/model.py#L68-L70 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pydecimal.py | python | Context.copy_negate | (self, a) | return a.copy_negate() | Returns a copy of the operand with the sign inverted.
>>> ExtendedContext.copy_negate(Decimal('101.5'))
Decimal('-101.5')
>>> ExtendedContext.copy_negate(Decimal('-101.5'))
Decimal('101.5')
>>> ExtendedContext.copy_negate(1)
Decimal('-1') | Returns a copy of the operand with the sign inverted. | [
"Returns",
"a",
"copy",
"of",
"the",
"operand",
"with",
"the",
"sign",
"inverted",
"."
] | def copy_negate(self, a):
"""Returns a copy of the operand with the sign inverted.
>>> ExtendedContext.copy_negate(Decimal('101.5'))
Decimal('-101.5')
>>> ExtendedContext.copy_negate(Decimal('-101.5'))
Decimal('101.5')
>>> ExtendedContext.copy_negate(1)
Decimal('-1')
"""
a = _convert_other(a, raiseit=True)
return a.copy_negate() | [
"def",
"copy_negate",
"(",
"self",
",",
"a",
")",
":",
"a",
"=",
"_convert_other",
"(",
"a",
",",
"raiseit",
"=",
"True",
")",
"return",
"a",
".",
"copy_negate",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pydecimal.py#L4321-L4332 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_gdi.py | python | GraphicsContext.CreateMatrix | (*args, **kwargs) | return _gdi_.GraphicsContext_CreateMatrix(*args, **kwargs) | CreateMatrix(self, Double a=1.0, Double b=0.0, Double c=0.0, Double d=1.0,
Double tx=0.0, Double ty=0.0) -> GraphicsMatrix
Creates a native affine transformation matrix from the passed in
values. The defaults result in an identity matrix. | CreateMatrix(self, Double a=1.0, Double b=0.0, Double c=0.0, Double d=1.0,
Double tx=0.0, Double ty=0.0) -> GraphicsMatrix | [
"CreateMatrix",
"(",
"self",
"Double",
"a",
"=",
"1",
".",
"0",
"Double",
"b",
"=",
"0",
".",
"0",
"Double",
"c",
"=",
"0",
".",
"0",
"Double",
"d",
"=",
"1",
".",
"0",
"Double",
"tx",
"=",
"0",
".",
"0",
"Double",
"ty",
"=",
"0",
".",
"0",
")",
"-",
">",
"GraphicsMatrix"
] | def CreateMatrix(*args, **kwargs):
"""
CreateMatrix(self, Double a=1.0, Double b=0.0, Double c=0.0, Double d=1.0,
Double tx=0.0, Double ty=0.0) -> GraphicsMatrix
Creates a native affine transformation matrix from the passed in
values. The defaults result in an identity matrix.
"""
return _gdi_.GraphicsContext_CreateMatrix(*args, **kwargs) | [
"def",
"CreateMatrix",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"GraphicsContext_CreateMatrix",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L6308-L6316 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/presenter/DrillPresenter.py | python | DrillPresenter.onSaveAs | (self) | Triggered when the user selects the "save as" function. This methods
will open a dialog to select the file even if one has previously been
used. | Triggered when the user selects the "save as" function. This methods
will open a dialog to select the file even if one has previously been
used. | [
"Triggered",
"when",
"the",
"user",
"selects",
"the",
"save",
"as",
"function",
".",
"This",
"methods",
"will",
"open",
"a",
"dialog",
"to",
"select",
"the",
"file",
"even",
"if",
"one",
"has",
"previously",
"been",
"used",
"."
] | def onSaveAs(self):
"""
Triggered when the user selects the "save as" function. This methods
will open a dialog to select the file even if one has previously been
used.
"""
filename = QFileDialog.getSaveFileName(self.view, 'Save rundex',
'./*.mrd',
"Rundex (*.mrd);;All (*)")
if not filename[0]:
return
self.model.setIOFile(filename[0])
self.view.setWindowTitle(os.path.split(filename[0])[1] + " [*]")
self.model.setVisualSettings(self.view.getVisualSettings())
self.model.exportRundexData()
self.view.setWindowModified(False) | [
"def",
"onSaveAs",
"(",
"self",
")",
":",
"filename",
"=",
"QFileDialog",
".",
"getSaveFileName",
"(",
"self",
".",
"view",
",",
"'Save rundex'",
",",
"'./*.mrd'",
",",
"\"Rundex (*.mrd);;All (*)\"",
")",
"if",
"not",
"filename",
"[",
"0",
"]",
":",
"return",
"self",
".",
"model",
".",
"setIOFile",
"(",
"filename",
"[",
"0",
"]",
")",
"self",
".",
"view",
".",
"setWindowTitle",
"(",
"os",
".",
"path",
".",
"split",
"(",
"filename",
"[",
"0",
"]",
")",
"[",
"1",
"]",
"+",
"\" [*]\"",
")",
"self",
".",
"model",
".",
"setVisualSettings",
"(",
"self",
".",
"view",
".",
"getVisualSettings",
"(",
")",
")",
"self",
".",
"model",
".",
"exportRundexData",
"(",
")",
"self",
".",
"view",
".",
"setWindowModified",
"(",
"False",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/presenter/DrillPresenter.py#L359-L374 | ||
epam/Indigo | 30e40b4b1eb9bae0207435a26cfcb81ddcc42be1 | api/python/indigo/inchi.py | python | IndigoInchi.getWarning | (self) | return self.indigo._checkResultString(
self._lib.indigoInchiGetWarning()
) | Returns warning message
Returns:
str: warning string | Returns warning message | [
"Returns",
"warning",
"message"
] | def getWarning(self):
"""Returns warning message
Returns:
str: warning string
"""
self.indigo._setSessionId()
return self.indigo._checkResultString(
self._lib.indigoInchiGetWarning()
) | [
"def",
"getWarning",
"(",
"self",
")",
":",
"self",
".",
"indigo",
".",
"_setSessionId",
"(",
")",
"return",
"self",
".",
"indigo",
".",
"_checkResultString",
"(",
"self",
".",
"_lib",
".",
"indigoInchiGetWarning",
"(",
")",
")"
] | https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/api/python/indigo/inchi.py#L133-L142 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/vpc/__init__.py | python | VPCConnection.delete_vpc | (self, vpc_id, dry_run=False) | return self.get_status('DeleteVpc', params) | Delete a Virtual Private Cloud.
:type vpc_id: str
:param vpc_id: The ID of the vpc to be deleted.
:type dry_run: bool
:param dry_run: Set to True if the operation should not actually run.
:rtype: bool
:return: True if successful | Delete a Virtual Private Cloud. | [
"Delete",
"a",
"Virtual",
"Private",
"Cloud",
"."
] | def delete_vpc(self, vpc_id, dry_run=False):
"""
Delete a Virtual Private Cloud.
:type vpc_id: str
:param vpc_id: The ID of the vpc to be deleted.
:type dry_run: bool
:param dry_run: Set to True if the operation should not actually run.
:rtype: bool
:return: True if successful
"""
params = {'VpcId': vpc_id}
if dry_run:
params['DryRun'] = 'true'
return self.get_status('DeleteVpc', params) | [
"def",
"delete_vpc",
"(",
"self",
",",
"vpc_id",
",",
"dry_run",
"=",
"False",
")",
":",
"params",
"=",
"{",
"'VpcId'",
":",
"vpc_id",
"}",
"if",
"dry_run",
":",
"params",
"[",
"'DryRun'",
"]",
"=",
"'true'",
"return",
"self",
".",
"get_status",
"(",
"'DeleteVpc'",
",",
"params",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/vpc/__init__.py#L137-L153 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AzCodeGenerator/bin/windows/jinja_extensions/template.py | python | toUuid | (fullClassName) | return uuid.uuid5(uuid.NAMESPACE_URL, str(fullClassName)) | Convert strings to Uuid | Convert strings to Uuid | [
"Convert",
"strings",
"to",
"Uuid"
] | def toUuid(fullClassName):
"""
Convert strings to Uuid
"""
return uuid.uuid5(uuid.NAMESPACE_URL, str(fullClassName)) | [
"def",
"toUuid",
"(",
"fullClassName",
")",
":",
"return",
"uuid",
".",
"uuid5",
"(",
"uuid",
".",
"NAMESPACE_URL",
",",
"str",
"(",
"fullClassName",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AzCodeGenerator/bin/windows/jinja_extensions/template.py#L18-L22 | |
kevinlin311tw/Caffe-DeepBinaryCode | 9eaa7662be47d49f475ecbeea2bd51be105270d2 | scripts/cpp_lint.py | python | IsBlankLine | (line) | return not line or line.isspace() | Returns true if the given line is blank.
We consider a line to be blank if the line is empty or consists of
only white spaces.
Args:
line: A line of a string.
Returns:
True, if the given line is blank. | Returns true if the given line is blank. | [
"Returns",
"true",
"if",
"the",
"given",
"line",
"is",
"blank",
"."
] | def IsBlankLine(line):
"""Returns true if the given line is blank.
We consider a line to be blank if the line is empty or consists of
only white spaces.
Args:
line: A line of a string.
Returns:
True, if the given line is blank.
"""
return not line or line.isspace() | [
"def",
"IsBlankLine",
"(",
"line",
")",
":",
"return",
"not",
"line",
"or",
"line",
".",
"isspace",
"(",
")"
] | https://github.com/kevinlin311tw/Caffe-DeepBinaryCode/blob/9eaa7662be47d49f475ecbeea2bd51be105270d2/scripts/cpp_lint.py#L2369-L2381 | |
ValveSoftware/source-sdk-2013 | 0d8dceea4310fde5706b3ce1c70609d72a38efdf | sp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py | python | _AddEqualsMethod | (message_descriptor, cls) | Helper for _AddMessageMethods(). | Helper for _AddMessageMethods(). | [
"Helper",
"for",
"_AddMessageMethods",
"()",
"."
] | def _AddEqualsMethod(message_descriptor, cls):
"""Helper for _AddMessageMethods()."""
def __eq__(self, other):
if (not isinstance(other, message_mod.Message) or
other.DESCRIPTOR != self.DESCRIPTOR):
return False
if self is other:
return True
return self.ListFields() == other.ListFields()
cls.__eq__ = __eq__ | [
"def",
"_AddEqualsMethod",
"(",
"message_descriptor",
",",
"cls",
")",
":",
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"other",
",",
"message_mod",
".",
"Message",
")",
"or",
"other",
".",
"DESCRIPTOR",
"!=",
"self",
".",
"DESCRIPTOR",
")",
":",
"return",
"False",
"if",
"self",
"is",
"other",
":",
"return",
"True",
"return",
"self",
".",
"ListFields",
"(",
")",
"==",
"other",
".",
"ListFields",
"(",
")",
"cls",
".",
"__eq__",
"=",
"__eq__"
] | https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/sp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py#L716-L728 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextCtrl.GetLineState | (*args, **kwargs) | return _stc.StyledTextCtrl_GetLineState(*args, **kwargs) | GetLineState(self, int line) -> int
Retrieve the extra styling information for a line. | GetLineState(self, int line) -> int | [
"GetLineState",
"(",
"self",
"int",
"line",
")",
"-",
">",
"int"
] | def GetLineState(*args, **kwargs):
"""
GetLineState(self, int line) -> int
Retrieve the extra styling information for a line.
"""
return _stc.StyledTextCtrl_GetLineState(*args, **kwargs) | [
"def",
"GetLineState",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_GetLineState",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L2971-L2977 | |
apache/incubator-weex | 5c25f0b59f7ac90703c363e7261f60bd06356dbe | weex_core/tools/cpplint.py | python | _FunctionState.Begin | (self, function_name) | Start analyzing function body.
Args:
function_name: The name of the function being tracked. | Start analyzing function body. | [
"Start",
"analyzing",
"function",
"body",
"."
] | def Begin(self, function_name):
"""Start analyzing function body.
Args:
function_name: The name of the function being tracked.
"""
self.in_a_function = True
self.lines_in_function = 0
self.current_function = function_name | [
"def",
"Begin",
"(",
"self",
",",
"function_name",
")",
":",
"self",
".",
"in_a_function",
"=",
"True",
"self",
".",
"lines_in_function",
"=",
"0",
"self",
".",
"current_function",
"=",
"function_name"
] | https://github.com/apache/incubator-weex/blob/5c25f0b59f7ac90703c363e7261f60bd06356dbe/weex_core/tools/cpplint.py#L1044-L1052 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/distributions/python/ops/bijectors/fill_triangular.py | python | FillTriangular.__init__ | (self,
upper=False,
validate_args=False,
name="fill_triangular") | Instantiates the `FillTriangular` bijector.
Args:
upper: Python `bool` representing whether output matrix should be upper
triangular (`True`) or lower triangular (`False`, default).
validate_args: Python `bool` indicating whether arguments should be
checked for correctness.
name: Python `str` name given to ops managed by this object. | Instantiates the `FillTriangular` bijector. | [
"Instantiates",
"the",
"FillTriangular",
"bijector",
"."
] | def __init__(self,
upper=False,
validate_args=False,
name="fill_triangular"):
"""Instantiates the `FillTriangular` bijector.
Args:
upper: Python `bool` representing whether output matrix should be upper
triangular (`True`) or lower triangular (`False`, default).
validate_args: Python `bool` indicating whether arguments should be
checked for correctness.
name: Python `str` name given to ops managed by this object.
"""
self._upper = upper
super(FillTriangular, self).__init__(
forward_min_event_ndims=1,
inverse_min_event_ndims=2,
validate_args=validate_args,
name=name) | [
"def",
"__init__",
"(",
"self",
",",
"upper",
"=",
"False",
",",
"validate_args",
"=",
"False",
",",
"name",
"=",
"\"fill_triangular\"",
")",
":",
"self",
".",
"_upper",
"=",
"upper",
"super",
"(",
"FillTriangular",
",",
"self",
")",
".",
"__init__",
"(",
"forward_min_event_ndims",
"=",
"1",
",",
"inverse_min_event_ndims",
"=",
"2",
",",
"validate_args",
"=",
"validate_args",
",",
"name",
"=",
"name",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/distributions/python/ops/bijectors/fill_triangular.py#L76-L94 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANS/SANSSingleReduction2.py | python | SANSSingleReduction._get_output_workspace_name | (self, state, reduction_mode=None, data_type=None,
can=False, sample=False, transmission=False, fitted=False) | Get the output names for the sliced workspaces (within the group workspaces, which are already named).
:param state: a SANS state object
:param reduction_mode: an optional ReductionMode enum: "HAB", "LAB", "Merged", or "All"
:param data_type: an optional DataType enum: "Sample" or "Can"
:param can: optional bool. If true then creating name for a can workspace
:param sample: optional bool. If true then creating name for a sample workspace. Sample and can cannot both be
true
:param transmission: optional bool. If true then creating name for a transmission workspace
:param fitted: optional bool. If true then workspace is a fitted transmission workspace, otherwise unfitted
:return: name of the workspace | Get the output names for the sliced workspaces (within the group workspaces, which are already named). | [
"Get",
"the",
"output",
"names",
"for",
"the",
"sliced",
"workspaces",
"(",
"within",
"the",
"group",
"workspaces",
"which",
"are",
"already",
"named",
")",
"."
] | def _get_output_workspace_name(self, state, reduction_mode=None, data_type=None,
can=False, sample=False, transmission=False, fitted=False):
"""
Get the output names for the sliced workspaces (within the group workspaces, which are already named).
:param state: a SANS state object
:param reduction_mode: an optional ReductionMode enum: "HAB", "LAB", "Merged", or "All"
:param data_type: an optional DataType enum: "Sample" or "Can"
:param can: optional bool. If true then creating name for a can workspace
:param sample: optional bool. If true then creating name for a sample workspace. Sample and can cannot both be
true
:param transmission: optional bool. If true then creating name for a transmission workspace
:param fitted: optional bool. If true then workspace is a fitted transmission workspace, otherwise unfitted
:return: name of the workspace
"""
_multi = {"event_slice": True,
"period": self.getProperty("Period").value,
"wavelength_range": self.getProperty("WavelengthRange").value}
if not transmission:
_suffix = ""
if can:
if reduction_mode == ReductionMode.HAB:
_suffix = "_hab_can"
elif reduction_mode == ReductionMode.LAB:
_suffix = "_lab_can"
elif sample:
if reduction_mode == ReductionMode.HAB:
_suffix = "_hab_sample"
elif reduction_mode == ReductionMode.LAB:
_suffix = "_lab_sample"
return get_output_name(state, reduction_mode, True, suffix=_suffix, multi_reduction_type=_multi)[0]
else:
return get_transmission_output_name(state, data_type, _multi, fitted)[0] | [
"def",
"_get_output_workspace_name",
"(",
"self",
",",
"state",
",",
"reduction_mode",
"=",
"None",
",",
"data_type",
"=",
"None",
",",
"can",
"=",
"False",
",",
"sample",
"=",
"False",
",",
"transmission",
"=",
"False",
",",
"fitted",
"=",
"False",
")",
":",
"_multi",
"=",
"{",
"\"event_slice\"",
":",
"True",
",",
"\"period\"",
":",
"self",
".",
"getProperty",
"(",
"\"Period\"",
")",
".",
"value",
",",
"\"wavelength_range\"",
":",
"self",
".",
"getProperty",
"(",
"\"WavelengthRange\"",
")",
".",
"value",
"}",
"if",
"not",
"transmission",
":",
"_suffix",
"=",
"\"\"",
"if",
"can",
":",
"if",
"reduction_mode",
"==",
"ReductionMode",
".",
"HAB",
":",
"_suffix",
"=",
"\"_hab_can\"",
"elif",
"reduction_mode",
"==",
"ReductionMode",
".",
"LAB",
":",
"_suffix",
"=",
"\"_lab_can\"",
"elif",
"sample",
":",
"if",
"reduction_mode",
"==",
"ReductionMode",
".",
"HAB",
":",
"_suffix",
"=",
"\"_hab_sample\"",
"elif",
"reduction_mode",
"==",
"ReductionMode",
".",
"LAB",
":",
"_suffix",
"=",
"\"_lab_sample\"",
"return",
"get_output_name",
"(",
"state",
",",
"reduction_mode",
",",
"True",
",",
"suffix",
"=",
"_suffix",
",",
"multi_reduction_type",
"=",
"_multi",
")",
"[",
"0",
"]",
"else",
":",
"return",
"get_transmission_output_name",
"(",
"state",
",",
"data_type",
",",
"_multi",
",",
"fitted",
")",
"[",
"0",
"]"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANS/SANSSingleReduction2.py#L491-L524 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/resource_variable_ops.py | python | _UnreadVariable.op | (self) | return self._parent_op | The op for this variable. | The op for this variable. | [
"The",
"op",
"for",
"this",
"variable",
"."
] | def op(self):
"""The op for this variable."""
return self._parent_op | [
"def",
"op",
"(",
"self",
")",
":",
"return",
"self",
".",
"_parent_op"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/resource_variable_ops.py#L1849-L1851 | |
scribusproject/scribus | 41ec7c775a060912cf251682a8b1437f753f80f4 | codegen/cheetah/Cheetah/Parser.py | python | _LowLevelParser.matchExpressionPlaceholderStart | (self) | return self.expressionPlaceholderStartRE.match(self.src(), self.pos()) | includes the enclosure and cache token | includes the enclosure and cache token | [
"includes",
"the",
"enclosure",
"and",
"cache",
"token"
] | def matchExpressionPlaceholderStart(self):
"""includes the enclosure and cache token"""
return self.expressionPlaceholderStartRE.match(self.src(), self.pos()) | [
"def",
"matchExpressionPlaceholderStart",
"(",
"self",
")",
":",
"return",
"self",
".",
"expressionPlaceholderStartRE",
".",
"match",
"(",
"self",
".",
"src",
"(",
")",
",",
"self",
".",
"pos",
"(",
")",
")"
] | https://github.com/scribusproject/scribus/blob/41ec7c775a060912cf251682a8b1437f753f80f4/codegen/cheetah/Cheetah/Parser.py#L796-L798 | |
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | lldb/examples/python/mach_o.py | python | TerminalColors.underline | (self, on=True) | return '' | Enable or disable underline depending on the "on" parameter. | Enable or disable underline depending on the "on" parameter. | [
"Enable",
"or",
"disable",
"underline",
"depending",
"on",
"the",
"on",
"parameter",
"."
] | def underline(self, on=True):
'''Enable or disable underline depending on the "on" parameter.'''
if self.enabled:
if on:
return "\x1b[4m"
else:
return "\x1b[24m"
return '' | [
"def",
"underline",
"(",
"self",
",",
"on",
"=",
"True",
")",
":",
"if",
"self",
".",
"enabled",
":",
"if",
"on",
":",
"return",
"\"\\x1b[4m\"",
"else",
":",
"return",
"\"\\x1b[24m\"",
"return",
"''"
] | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/lldb/examples/python/mach_o.py#L244-L251 | |
Kitware/VTK | 5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8 | Wrapping/Python/vtkmodules/numpy_interface/dataset_adapter.py | python | DataSetAttributes.GetArray | (self, idx) | return array | Given an index or name, returns a VTKArray. | Given an index or name, returns a VTKArray. | [
"Given",
"an",
"index",
"or",
"name",
"returns",
"a",
"VTKArray",
"."
] | def GetArray(self, idx):
"Given an index or name, returns a VTKArray."
if isinstance(idx, int) and idx >= self.VTKObject.GetNumberOfArrays():
raise IndexError("array index out of range")
vtkarray = self.VTKObject.GetArray(idx)
if not vtkarray:
vtkarray = self.VTKObject.GetAbstractArray(idx)
if vtkarray:
return vtkarray
return NoneArray
array = vtkDataArrayToVTKArray(vtkarray, self.DataSet)
array.Association = self.Association
return array | [
"def",
"GetArray",
"(",
"self",
",",
"idx",
")",
":",
"if",
"isinstance",
"(",
"idx",
",",
"int",
")",
"and",
"idx",
">=",
"self",
".",
"VTKObject",
".",
"GetNumberOfArrays",
"(",
")",
":",
"raise",
"IndexError",
"(",
"\"array index out of range\"",
")",
"vtkarray",
"=",
"self",
".",
"VTKObject",
".",
"GetArray",
"(",
"idx",
")",
"if",
"not",
"vtkarray",
":",
"vtkarray",
"=",
"self",
".",
"VTKObject",
".",
"GetAbstractArray",
"(",
"idx",
")",
"if",
"vtkarray",
":",
"return",
"vtkarray",
"return",
"NoneArray",
"array",
"=",
"vtkDataArrayToVTKArray",
"(",
"vtkarray",
",",
"self",
".",
"DataSet",
")",
"array",
".",
"Association",
"=",
"self",
".",
"Association",
"return",
"array"
] | https://github.com/Kitware/VTK/blob/5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8/Wrapping/Python/vtkmodules/numpy_interface/dataset_adapter.py#L645-L657 | |
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/plugins/db_manager/db_plugins/plugin.py | python | Database.prepareMenuMoveTableToSchemaActionSlot | (self, item, menu, mainWindow) | populate menu with schemas | populate menu with schemas | [
"populate",
"menu",
"with",
"schemas"
] | def prepareMenuMoveTableToSchemaActionSlot(self, item, menu, mainWindow):
""" populate menu with schemas """
def slot(x):
return lambda: mainWindow.invokeCallback(self.moveTableToSchemaActionSlot, x)
menu.clear()
for schema in self.schemas():
menu.addAction(schema.name, slot(schema)) | [
"def",
"prepareMenuMoveTableToSchemaActionSlot",
"(",
"self",
",",
"item",
",",
"menu",
",",
"mainWindow",
")",
":",
"def",
"slot",
"(",
"x",
")",
":",
"return",
"lambda",
":",
"mainWindow",
".",
"invokeCallback",
"(",
"self",
".",
"moveTableToSchemaActionSlot",
",",
"x",
")",
"menu",
".",
"clear",
"(",
")",
"for",
"schema",
"in",
"self",
".",
"schemas",
"(",
")",
":",
"menu",
".",
"addAction",
"(",
"schema",
".",
"name",
",",
"slot",
"(",
"schema",
")",
")"
] | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/db_manager/db_plugins/plugin.py#L532-L540 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/frame.py | python | DataFrame.isin | (self, values) | Whether each element in the DataFrame is contained in values.
Parameters
----------
values : iterable, Series, DataFrame or dict
The result will only be true at a location if all the
labels match. If `values` is a Series, that's the index. If
`values` is a dict, the keys must be the column names,
which must match. If `values` is a DataFrame,
then both the index and column labels must match.
Returns
-------
DataFrame
DataFrame of booleans showing whether each element in the DataFrame
is contained in values.
See Also
--------
DataFrame.eq: Equality test for DataFrame.
Series.isin: Equivalent method on Series.
Series.str.contains: Test if pattern or regex is contained within a
string of a Series or Index.
Examples
--------
>>> df = pd.DataFrame({'num_legs': [2, 4], 'num_wings': [2, 0]},
... index=['falcon', 'dog'])
>>> df
num_legs num_wings
falcon 2 2
dog 4 0
When ``values`` is a list check whether every value in the DataFrame
is present in the list (which animals have 0 or 2 legs or wings)
>>> df.isin([0, 2])
num_legs num_wings
falcon True True
dog False True
When ``values`` is a dict, we can pass values to check for each
column separately:
>>> df.isin({'num_wings': [0, 3]})
num_legs num_wings
falcon False False
dog False True
When ``values`` is a Series or DataFrame the index and column must
match. Note that 'falcon' does not match based on the number of legs
in df2.
>>> other = pd.DataFrame({'num_legs': [8, 2],'num_wings': [0, 2]},
... index=['spider', 'falcon'])
>>> df.isin(other)
num_legs num_wings
falcon True True
dog False False | Whether each element in the DataFrame is contained in values. | [
"Whether",
"each",
"element",
"in",
"the",
"DataFrame",
"is",
"contained",
"in",
"values",
"."
] | def isin(self, values):
"""
Whether each element in the DataFrame is contained in values.
Parameters
----------
values : iterable, Series, DataFrame or dict
The result will only be true at a location if all the
labels match. If `values` is a Series, that's the index. If
`values` is a dict, the keys must be the column names,
which must match. If `values` is a DataFrame,
then both the index and column labels must match.
Returns
-------
DataFrame
DataFrame of booleans showing whether each element in the DataFrame
is contained in values.
See Also
--------
DataFrame.eq: Equality test for DataFrame.
Series.isin: Equivalent method on Series.
Series.str.contains: Test if pattern or regex is contained within a
string of a Series or Index.
Examples
--------
>>> df = pd.DataFrame({'num_legs': [2, 4], 'num_wings': [2, 0]},
... index=['falcon', 'dog'])
>>> df
num_legs num_wings
falcon 2 2
dog 4 0
When ``values`` is a list check whether every value in the DataFrame
is present in the list (which animals have 0 or 2 legs or wings)
>>> df.isin([0, 2])
num_legs num_wings
falcon True True
dog False True
When ``values`` is a dict, we can pass values to check for each
column separately:
>>> df.isin({'num_wings': [0, 3]})
num_legs num_wings
falcon False False
dog False True
When ``values`` is a Series or DataFrame the index and column must
match. Note that 'falcon' does not match based on the number of legs
in df2.
>>> other = pd.DataFrame({'num_legs': [8, 2],'num_wings': [0, 2]},
... index=['spider', 'falcon'])
>>> df.isin(other)
num_legs num_wings
falcon True True
dog False False
"""
if isinstance(values, dict):
from pandas.core.reshape.concat import concat
values = collections.defaultdict(list, values)
return concat((self.iloc[:, [i]].isin(values[col])
for i, col in enumerate(self.columns)), axis=1)
elif isinstance(values, Series):
if not values.index.is_unique:
raise ValueError("cannot compute isin with "
"a duplicate axis.")
return self.eq(values.reindex_like(self), axis='index')
elif isinstance(values, DataFrame):
if not (values.columns.is_unique and values.index.is_unique):
raise ValueError("cannot compute isin with "
"a duplicate axis.")
return self.eq(values.reindex_like(self))
else:
if not is_list_like(values):
raise TypeError("only list-like or dict-like objects are "
"allowed to be passed to DataFrame.isin(), "
"you passed a "
"{0!r}".format(type(values).__name__))
return DataFrame(
algorithms.isin(self.values.ravel(),
values).reshape(self.shape), self.index,
self.columns) | [
"def",
"isin",
"(",
"self",
",",
"values",
")",
":",
"if",
"isinstance",
"(",
"values",
",",
"dict",
")",
":",
"from",
"pandas",
".",
"core",
".",
"reshape",
".",
"concat",
"import",
"concat",
"values",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
",",
"values",
")",
"return",
"concat",
"(",
"(",
"self",
".",
"iloc",
"[",
":",
",",
"[",
"i",
"]",
"]",
".",
"isin",
"(",
"values",
"[",
"col",
"]",
")",
"for",
"i",
",",
"col",
"in",
"enumerate",
"(",
"self",
".",
"columns",
")",
")",
",",
"axis",
"=",
"1",
")",
"elif",
"isinstance",
"(",
"values",
",",
"Series",
")",
":",
"if",
"not",
"values",
".",
"index",
".",
"is_unique",
":",
"raise",
"ValueError",
"(",
"\"cannot compute isin with \"",
"\"a duplicate axis.\"",
")",
"return",
"self",
".",
"eq",
"(",
"values",
".",
"reindex_like",
"(",
"self",
")",
",",
"axis",
"=",
"'index'",
")",
"elif",
"isinstance",
"(",
"values",
",",
"DataFrame",
")",
":",
"if",
"not",
"(",
"values",
".",
"columns",
".",
"is_unique",
"and",
"values",
".",
"index",
".",
"is_unique",
")",
":",
"raise",
"ValueError",
"(",
"\"cannot compute isin with \"",
"\"a duplicate axis.\"",
")",
"return",
"self",
".",
"eq",
"(",
"values",
".",
"reindex_like",
"(",
"self",
")",
")",
"else",
":",
"if",
"not",
"is_list_like",
"(",
"values",
")",
":",
"raise",
"TypeError",
"(",
"\"only list-like or dict-like objects are \"",
"\"allowed to be passed to DataFrame.isin(), \"",
"\"you passed a \"",
"\"{0!r}\"",
".",
"format",
"(",
"type",
"(",
"values",
")",
".",
"__name__",
")",
")",
"return",
"DataFrame",
"(",
"algorithms",
".",
"isin",
"(",
"self",
".",
"values",
".",
"ravel",
"(",
")",
",",
"values",
")",
".",
"reshape",
"(",
"self",
".",
"shape",
")",
",",
"self",
".",
"index",
",",
"self",
".",
"columns",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/frame.py#L7857-L7944 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tkinter/tix.py | python | Grid.move_row | (self, from_, to, offset) | Moves the range of rows from position FROM through TO by
the distance indicated by OFFSET.
For example, move_row(2, 4, 1) moves the rows 2,3,4 to rows 3,4,5. | Moves the range of rows from position FROM through TO by
the distance indicated by OFFSET.
For example, move_row(2, 4, 1) moves the rows 2,3,4 to rows 3,4,5. | [
"Moves",
"the",
"range",
"of",
"rows",
"from",
"position",
"FROM",
"through",
"TO",
"by",
"the",
"distance",
"indicated",
"by",
"OFFSET",
".",
"For",
"example",
"move_row",
"(",
"2",
"4",
"1",
")",
"moves",
"the",
"rows",
"2",
"3",
"4",
"to",
"rows",
"3",
"4",
"5",
"."
] | def move_row(self, from_, to, offset):
"""Moves the range of rows from position FROM through TO by
the distance indicated by OFFSET.
For example, move_row(2, 4, 1) moves the rows 2,3,4 to rows 3,4,5."""
self.tk.call(self, 'move', 'row', from_, to, offset) | [
"def",
"move_row",
"(",
"self",
",",
"from_",
",",
"to",
",",
"offset",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
",",
"'move'",
",",
"'row'",
",",
"from_",
",",
"to",
",",
"offset",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/tix.py#L1861-L1865 | ||
chipsalliance/verible | aa14e0074ff89945bf65eecfb9ef78684d996058 | third_party/py/dataclasses/dataclasses/__init__.py | python | astuple | (obj, *, tuple_factory=tuple) | return _astuple_inner(obj, tuple_factory) | Return the fields of a dataclass instance as a new tuple of field values.
Example usage::
@dataclass
class C:
x: int
y: int
c = C(1, 2)
assert astuple(c) == (1, 2)
If given, 'tuple_factory' will be used instead of built-in tuple.
The function applies recursively to field values that are
dataclass instances. This will also look into built-in containers:
tuples, lists, and dicts. | Return the fields of a dataclass instance as a new tuple of field values. | [
"Return",
"the",
"fields",
"of",
"a",
"dataclass",
"instance",
"as",
"a",
"new",
"tuple",
"of",
"field",
"values",
"."
] | def astuple(obj, *, tuple_factory=tuple):
"""Return the fields of a dataclass instance as a new tuple of field values.
Example usage::
@dataclass
class C:
x: int
y: int
c = C(1, 2)
assert astuple(c) == (1, 2)
If given, 'tuple_factory' will be used instead of built-in tuple.
The function applies recursively to field values that are
dataclass instances. This will also look into built-in containers:
tuples, lists, and dicts.
"""
if not _is_dataclass_instance(obj):
raise TypeError("astuple() should be called on dataclass instances")
return _astuple_inner(obj, tuple_factory) | [
"def",
"astuple",
"(",
"obj",
",",
"*",
",",
"tuple_factory",
"=",
"tuple",
")",
":",
"if",
"not",
"_is_dataclass_instance",
"(",
"obj",
")",
":",
"raise",
"TypeError",
"(",
"\"astuple() should be called on dataclass instances\"",
")",
"return",
"_astuple_inner",
"(",
"obj",
",",
"tuple_factory",
")"
] | https://github.com/chipsalliance/verible/blob/aa14e0074ff89945bf65eecfb9ef78684d996058/third_party/py/dataclasses/dataclasses/__init__.py#L925-L946 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib2to3/pytree.py | python | Base.next_sibling | (self) | The node immediately following the invocant in their parent's children
list. If the invocant does not have a next sibling, it is None | The node immediately following the invocant in their parent's children
list. If the invocant does not have a next sibling, it is None | [
"The",
"node",
"immediately",
"following",
"the",
"invocant",
"in",
"their",
"parent",
"s",
"children",
"list",
".",
"If",
"the",
"invocant",
"does",
"not",
"have",
"a",
"next",
"sibling",
"it",
"is",
"None"
] | def next_sibling(self):
"""
The node immediately following the invocant in their parent's children
list. If the invocant does not have a next sibling, it is None
"""
if self.parent is None:
return None
# Can't use index(); we need to test by identity
for i, child in enumerate(self.parent.children):
if child is self:
try:
return self.parent.children[i+1]
except IndexError:
return None | [
"def",
"next_sibling",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
"is",
"None",
":",
"return",
"None",
"# Can't use index(); we need to test by identity",
"for",
"i",
",",
"child",
"in",
"enumerate",
"(",
"self",
".",
"parent",
".",
"children",
")",
":",
"if",
"child",
"is",
"self",
":",
"try",
":",
"return",
"self",
".",
"parent",
".",
"children",
"[",
"i",
"+",
"1",
"]",
"except",
"IndexError",
":",
"return",
"None"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib2to3/pytree.py#L183-L197 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/sparse/base.py | python | spmatrix.tolil | (self, copy=False) | return self.tocsr(copy=False).tolil(copy=copy) | Convert this matrix to LInked List format.
With copy=False, the data/indices may be shared between this matrix and
the resultant lil_matrix. | Convert this matrix to LInked List format. | [
"Convert",
"this",
"matrix",
"to",
"LInked",
"List",
"format",
"."
] | def tolil(self, copy=False):
"""Convert this matrix to LInked List format.
With copy=False, the data/indices may be shared between this matrix and
the resultant lil_matrix.
"""
return self.tocsr(copy=False).tolil(copy=copy) | [
"def",
"tolil",
"(",
"self",
",",
"copy",
"=",
"False",
")",
":",
"return",
"self",
".",
"tocsr",
"(",
"copy",
"=",
"False",
")",
".",
"tolil",
"(",
"copy",
"=",
"copy",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/sparse/base.py#L908-L914 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | TextAttr.HasURL | (*args, **kwargs) | return _controls_.TextAttr_HasURL(*args, **kwargs) | HasURL(self) -> bool | HasURL(self) -> bool | [
"HasURL",
"(",
"self",
")",
"-",
">",
"bool"
] | def HasURL(*args, **kwargs):
"""HasURL(self) -> bool"""
return _controls_.TextAttr_HasURL(*args, **kwargs) | [
"def",
"HasURL",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TextAttr_HasURL",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L1868-L1870 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/external/bazel_tools/tools/android/incremental_install.py | python | Adb.Pull | (self, remote) | Invoke 'adb pull'.
Args:
remote: The path to the remote file to pull.
Returns:
The contents of a file or None if the file didn't exist. | Invoke 'adb pull'. | [
"Invoke",
"adb",
"pull",
"."
] | def Pull(self, remote):
"""Invoke 'adb pull'.
Args:
remote: The path to the remote file to pull.
Returns:
The contents of a file or None if the file didn't exist.
"""
local = self._CreateLocalFile()
try:
self._Exec(["pull", remote, local])
with file(local) as f:
return f.read()
except (AdbError, IOError):
return None | [
"def",
"Pull",
"(",
"self",
",",
"remote",
")",
":",
"local",
"=",
"self",
".",
"_CreateLocalFile",
"(",
")",
"try",
":",
"self",
".",
"_Exec",
"(",
"[",
"\"pull\"",
",",
"remote",
",",
"local",
"]",
")",
"with",
"file",
"(",
"local",
")",
"as",
"f",
":",
"return",
"f",
".",
"read",
"(",
")",
"except",
"(",
"AdbError",
",",
"IOError",
")",
":",
"return",
"None"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/external/bazel_tools/tools/android/incremental_install.py#L205-L220 | ||
apiaryio/drafter | 4634ebd07f6c6f257cc656598ccd535492fdfb55 | tools/gyp/pylib/gyp/MSVSSettings.py | python | FixVCMacroSlashes | (s) | return s | Replace macros which have excessive following slashes.
These macros are known to have a built-in trailing slash. Furthermore, many
scripts hiccup on processing paths with extra slashes in the middle.
This list is probably not exhaustive. Add as needed. | Replace macros which have excessive following slashes. | [
"Replace",
"macros",
"which",
"have",
"excessive",
"following",
"slashes",
"."
] | def FixVCMacroSlashes(s):
"""Replace macros which have excessive following slashes.
These macros are known to have a built-in trailing slash. Furthermore, many
scripts hiccup on processing paths with extra slashes in the middle.
This list is probably not exhaustive. Add as needed.
"""
if '$' in s:
s = fix_vc_macro_slashes_regex.sub(r'\1', s)
return s | [
"def",
"FixVCMacroSlashes",
"(",
"s",
")",
":",
"if",
"'$'",
"in",
"s",
":",
"s",
"=",
"fix_vc_macro_slashes_regex",
".",
"sub",
"(",
"r'\\1'",
",",
"s",
")",
"return",
"s"
] | https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/MSVSSettings.py#L406-L416 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/hyperlink.py | python | HyperLinkCtrl.SetLinkCursor | (self, cur=wx.CURSOR_HAND) | Sets link cursor properties.
:param `cur`: an integer representing a :class:`StockCursor` constant. | Sets link cursor properties. | [
"Sets",
"link",
"cursor",
"properties",
"."
] | def SetLinkCursor(self, cur=wx.CURSOR_HAND):
"""
Sets link cursor properties.
:param `cur`: an integer representing a :class:`StockCursor` constant.
"""
self._CursorHand = wx.StockCursor(cur) | [
"def",
"SetLinkCursor",
"(",
"self",
",",
"cur",
"=",
"wx",
".",
"CURSOR_HAND",
")",
":",
"self",
".",
"_CursorHand",
"=",
"wx",
".",
"StockCursor",
"(",
"cur",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/hyperlink.py#L502-L509 | ||
apiaryio/drafter | 4634ebd07f6c6f257cc656598ccd535492fdfb55 | tools/gyp/pylib/gyp/xcodeproj_file.py | python | XCConfigurationList.DefaultConfiguration | (self) | return self.ConfigurationNamed(self._properties['defaultConfigurationName']) | Convenience accessor to obtain the default XCBuildConfiguration. | Convenience accessor to obtain the default XCBuildConfiguration. | [
"Convenience",
"accessor",
"to",
"obtain",
"the",
"default",
"XCBuildConfiguration",
"."
] | def DefaultConfiguration(self):
"""Convenience accessor to obtain the default XCBuildConfiguration."""
return self.ConfigurationNamed(self._properties['defaultConfigurationName']) | [
"def",
"DefaultConfiguration",
"(",
"self",
")",
":",
"return",
"self",
".",
"ConfigurationNamed",
"(",
"self",
".",
"_properties",
"[",
"'defaultConfigurationName'",
"]",
")"
] | https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/xcodeproj_file.py#L1613-L1615 | |
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Tool/GettextCommon.py | python | RPaths.__call__ | (self, nodes, *args, **kw) | return rpaths | Return nodes' paths (strings) relative to current working directory.
**Arguments**:
- *nodes* ([`SCons.Node.FS.Base`]) - list of nodes.
- *args* - currently unused.
- *kw* - currently unused.
**Returns**:
- Tuple of strings, which represent paths relative to current working
directory (for given environment). | Return nodes' paths (strings) relative to current working directory. | [
"Return",
"nodes",
"paths",
"(",
"strings",
")",
"relative",
"to",
"current",
"working",
"directory",
"."
] | def __call__(self, nodes, *args, **kw):
""" Return nodes' paths (strings) relative to current working directory.
**Arguments**:
- *nodes* ([`SCons.Node.FS.Base`]) - list of nodes.
- *args* - currently unused.
- *kw* - currently unused.
**Returns**:
- Tuple of strings, which represent paths relative to current working
directory (for given environment).
"""
import os
import SCons.Node.FS
rpaths = ()
cwd = self.env.fs.getcwd().get_abspath()
for node in nodes:
rpath = None
if isinstance(node, SCons.Node.FS.Base):
rpath = os.path.relpath(node.get_abspath(), cwd)
# FIXME: Other types possible here?
if rpath is not None:
rpaths += (rpath,)
return rpaths | [
"def",
"__call__",
"(",
"self",
",",
"nodes",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"import",
"os",
"import",
"SCons",
".",
"Node",
".",
"FS",
"rpaths",
"=",
"(",
")",
"cwd",
"=",
"self",
".",
"env",
".",
"fs",
".",
"getcwd",
"(",
")",
".",
"get_abspath",
"(",
")",
"for",
"node",
"in",
"nodes",
":",
"rpath",
"=",
"None",
"if",
"isinstance",
"(",
"node",
",",
"SCons",
".",
"Node",
".",
"FS",
".",
"Base",
")",
":",
"rpath",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"node",
".",
"get_abspath",
"(",
")",
",",
"cwd",
")",
"# FIXME: Other types possible here?",
"if",
"rpath",
"is",
"not",
"None",
":",
"rpaths",
"+=",
"(",
"rpath",
",",
")",
"return",
"rpaths"
] | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Tool/GettextCommon.py#L331-L356 | |
apache/qpid-proton | 6bcdfebb55ea3554bc29b1901422532db331a591 | python/proton/_reactor.py | python | EventInjector.close | (self) | Request that this EventInjector be closed. Existing events
will be dispatched on the container's event dispatch thread,
then this will be removed from the set of interest. | Request that this EventInjector be closed. Existing events
will be dispatched on the container's event dispatch thread,
then this will be removed from the set of interest. | [
"Request",
"that",
"this",
"EventInjector",
"be",
"closed",
".",
"Existing",
"events",
"will",
"be",
"dispatched",
"on",
"the",
"container",
"s",
"event",
"dispatch",
"thread",
"then",
"this",
"will",
"be",
"removed",
"from",
"the",
"set",
"of",
"interest",
"."
] | def close(self) -> None:
"""
Request that this EventInjector be closed. Existing events
will be dispatched on the container's event dispatch thread,
then this will be removed from the set of interest.
"""
self._closed = True
os.write(self.pipe[1], b"!") | [
"def",
"close",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_closed",
"=",
"True",
"os",
".",
"write",
"(",
"self",
".",
"pipe",
"[",
"1",
"]",
",",
"b\"!\"",
")"
] | https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_reactor.py#L434-L441 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/feature_selection/_univariate_selection.py | python | _BaseFilter.fit | (self, X, y) | return self | Run score function on (X, y) and get the appropriate features.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The training input samples.
y : array-like of shape (n_samples,)
The target values (class labels in classification, real numbers in
regression).
Returns
-------
self : object | Run score function on (X, y) and get the appropriate features. | [
"Run",
"score",
"function",
"on",
"(",
"X",
"y",
")",
"and",
"get",
"the",
"appropriate",
"features",
"."
] | def fit(self, X, y):
"""Run score function on (X, y) and get the appropriate features.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The training input samples.
y : array-like of shape (n_samples,)
The target values (class labels in classification, real numbers in
regression).
Returns
-------
self : object
"""
X, y = check_X_y(X, y, ['csr', 'csc'], multi_output=True)
if not callable(self.score_func):
raise TypeError("The score function should be a callable, %s (%s) "
"was passed."
% (self.score_func, type(self.score_func)))
self._check_params(X, y)
score_func_ret = self.score_func(X, y)
if isinstance(score_func_ret, (list, tuple)):
self.scores_, self.pvalues_ = score_func_ret
self.pvalues_ = np.asarray(self.pvalues_)
else:
self.scores_ = score_func_ret
self.pvalues_ = None
self.scores_ = np.asarray(self.scores_)
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"X",
",",
"y",
"=",
"check_X_y",
"(",
"X",
",",
"y",
",",
"[",
"'csr'",
",",
"'csc'",
"]",
",",
"multi_output",
"=",
"True",
")",
"if",
"not",
"callable",
"(",
"self",
".",
"score_func",
")",
":",
"raise",
"TypeError",
"(",
"\"The score function should be a callable, %s (%s) \"",
"\"was passed.\"",
"%",
"(",
"self",
".",
"score_func",
",",
"type",
"(",
"self",
".",
"score_func",
")",
")",
")",
"self",
".",
"_check_params",
"(",
"X",
",",
"y",
")",
"score_func_ret",
"=",
"self",
".",
"score_func",
"(",
"X",
",",
"y",
")",
"if",
"isinstance",
"(",
"score_func_ret",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"self",
".",
"scores_",
",",
"self",
".",
"pvalues_",
"=",
"score_func_ret",
"self",
".",
"pvalues_",
"=",
"np",
".",
"asarray",
"(",
"self",
".",
"pvalues_",
")",
"else",
":",
"self",
".",
"scores_",
"=",
"score_func_ret",
"self",
".",
"pvalues_",
"=",
"None",
"self",
".",
"scores_",
"=",
"np",
".",
"asarray",
"(",
"self",
".",
"scores_",
")",
"return",
"self"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/feature_selection/_univariate_selection.py#L325-L359 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | GenericDirCtrl.GetDefaultPath | (*args, **kwargs) | return _controls_.GenericDirCtrl_GetDefaultPath(*args, **kwargs) | GetDefaultPath(self) -> String | GetDefaultPath(self) -> String | [
"GetDefaultPath",
"(",
"self",
")",
"-",
">",
"String"
] | def GetDefaultPath(*args, **kwargs):
"""GetDefaultPath(self) -> String"""
return _controls_.GenericDirCtrl_GetDefaultPath(*args, **kwargs) | [
"def",
"GetDefaultPath",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"GenericDirCtrl_GetDefaultPath",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L5673-L5675 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/process_mask.py | python | RegionOfInterest.lower_left_corner | (self) | return self._lowerLeftCorner | get lower left corner position
:return: 2-tuple | get lower left corner position
:return: 2-tuple | [
"get",
"lower",
"left",
"corner",
"position",
":",
"return",
":",
"2",
"-",
"tuple"
] | def lower_left_corner(self):
"""
get lower left corner position
:return: 2-tuple
"""
if self._lowerLeftCorner is None:
raise RuntimeError('lower left not set')
return self._lowerLeftCorner | [
"def",
"lower_left_corner",
"(",
"self",
")",
":",
"if",
"self",
".",
"_lowerLeftCorner",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'lower left not set'",
")",
"return",
"self",
".",
"_lowerLeftCorner"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/process_mask.py#L137-L145 | |
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | buildscripts/cpplint.py | python | GetIndentLevel | (line) | Return the number of leading spaces in line.
Args:
line: A string to check.
Returns:
An integer count of leading spaces, possibly zero. | Return the number of leading spaces in line. | [
"Return",
"the",
"number",
"of",
"leading",
"spaces",
"in",
"line",
"."
] | def GetIndentLevel(line):
"""Return the number of leading spaces in line.
Args:
line: A string to check.
Returns:
An integer count of leading spaces, possibly zero.
"""
indent = Match(r'^( *)\S', line)
if indent:
return len(indent.group(1))
else:
return 0 | [
"def",
"GetIndentLevel",
"(",
"line",
")",
":",
"indent",
"=",
"Match",
"(",
"r'^( *)\\S'",
",",
"line",
")",
"if",
"indent",
":",
"return",
"len",
"(",
"indent",
".",
"group",
"(",
"1",
")",
")",
"else",
":",
"return",
"0"
] | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/buildscripts/cpplint.py#L1681-L1694 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/htmllib.py | python | HTMLParser.handle_image | (self, src, alt, *args) | This method is called to handle images.
The default implementation simply passes the alt value to the
handle_data() method. | This method is called to handle images. | [
"This",
"method",
"is",
"called",
"to",
"handle",
"images",
"."
] | def handle_image(self, src, alt, *args):
"""This method is called to handle images.
The default implementation simply passes the alt value to the
handle_data() method.
"""
self.handle_data(alt) | [
"def",
"handle_image",
"(",
"self",
",",
"src",
",",
"alt",
",",
"*",
"args",
")",
":",
"self",
".",
"handle_data",
"(",
"alt",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/htmllib.py#L128-L135 | ||
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/atoms/elementwise/ceil.py | python | floor.is_incr | (self, idx) | return True | Is the composition non-decreasing in argument idx? | Is the composition non-decreasing in argument idx? | [
"Is",
"the",
"composition",
"non",
"-",
"decreasing",
"in",
"argument",
"idx?"
] | def is_incr(self, idx) -> bool:
"""Is the composition non-decreasing in argument idx?
"""
return True | [
"def",
"is_incr",
"(",
"self",
",",
"idx",
")",
"->",
"bool",
":",
"return",
"True"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/elementwise/ceil.py#L154-L157 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TBPGraph.GetNodes | (self) | return _snap.TBPGraph_GetNodes(self) | GetNodes(TBPGraph self) -> int
Parameters:
self: TBPGraph const * | GetNodes(TBPGraph self) -> int | [
"GetNodes",
"(",
"TBPGraph",
"self",
")",
"-",
">",
"int"
] | def GetNodes(self):
"""
GetNodes(TBPGraph self) -> int
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_GetNodes(self) | [
"def",
"GetNodes",
"(",
"self",
")",
":",
"return",
"_snap",
".",
"TBPGraph_GetNodes",
"(",
"self",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L4894-L4902 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | media/tools/constrained_network_server/cns.py | python | ConstrainedNetworkServer.__init__ | (self, options, port_allocator) | Sets up initial state for the CNS.
Args:
options: optparse based class returned by ParseArgs()
port_allocator: A port allocator instance. | Sets up initial state for the CNS. | [
"Sets",
"up",
"initial",
"state",
"for",
"the",
"CNS",
"."
] | def __init__(self, options, port_allocator):
"""Sets up initial state for the CNS.
Args:
options: optparse based class returned by ParseArgs()
port_allocator: A port allocator instance.
"""
self._options = options
self._port_allocator = port_allocator | [
"def",
"__init__",
"(",
"self",
",",
"options",
",",
"port_allocator",
")",
":",
"self",
".",
"_options",
"=",
"options",
"self",
".",
"_port_allocator",
"=",
"port_allocator"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/media/tools/constrained_network_server/cns.py#L176-L184 | ||
neoml-lib/neoml | a0d370fba05269a1b2258cef126f77bbd2054a3e | NeoML/Python/neoml/Dnn/Dnn.py | python | Dnn.load | (self, path) | Loads the network from file.
:param path: The full path to the location from where the network should be loaded.
:type path: str | Loads the network from file.
:param path: The full path to the location from where the network should be loaded.
:type path: str | [
"Loads",
"the",
"network",
"from",
"file",
".",
":",
"param",
"path",
":",
"The",
"full",
"path",
"to",
"the",
"location",
"from",
"where",
"the",
"network",
"should",
"be",
"loaded",
".",
":",
"type",
"path",
":",
"str"
] | def load(self, path):
"""Loads the network from file.
:param path: The full path to the location from where the network should be loaded.
:type path: str
"""
self._load(str(path)) | [
"def",
"load",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"_load",
"(",
"str",
"(",
"path",
")",
")"
] | https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/Dnn.py#L54-L60 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py3/prompt_toolkit/output/vt100.py | python | Vt100_Output.write | (self, data: str) | Write text to output.
(Removes vt100 escape codes. -- used for safely writing text.) | Write text to output.
(Removes vt100 escape codes. -- used for safely writing text.) | [
"Write",
"text",
"to",
"output",
".",
"(",
"Removes",
"vt100",
"escape",
"codes",
".",
"--",
"used",
"for",
"safely",
"writing",
"text",
".",
")"
] | def write(self, data: str) -> None:
"""
Write text to output.
(Removes vt100 escape codes. -- used for safely writing text.)
"""
self._buffer.append(data.replace("\x1b", "?")) | [
"def",
"write",
"(",
"self",
",",
"data",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"_buffer",
".",
"append",
"(",
"data",
".",
"replace",
"(",
"\"\\x1b\"",
",",
"\"?\"",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/output/vt100.py#L517-L522 | ||
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/showbase/PhasedObject.py | python | PhasedObject.setAlias | (self, phase, alias) | Map an alias to a phase number.
phase must be >= 0 and alias must be a string
of characters suitable for python variable names.
The mapping must be one-to-one. | Map an alias to a phase number. | [
"Map",
"an",
"alias",
"to",
"a",
"phase",
"number",
"."
] | def setAlias(self, phase, alias):
"""
Map an alias to a phase number.
phase must be >= 0 and alias must be a string
of characters suitable for python variable names.
The mapping must be one-to-one.
"""
assert isinstance(phase,int) and phase >= 0
assert isinstance(alias,str)
self.phaseAliasMap[phase] = alias
self.aliasPhaseMap[alias] = phase | [
"def",
"setAlias",
"(",
"self",
",",
"phase",
",",
"alias",
")",
":",
"assert",
"isinstance",
"(",
"phase",
",",
"int",
")",
"and",
"phase",
">=",
"0",
"assert",
"isinstance",
"(",
"alias",
",",
"str",
")",
"self",
".",
"phaseAliasMap",
"[",
"phase",
"]",
"=",
"alias",
"self",
".",
"aliasPhaseMap",
"[",
"alias",
"]",
"=",
"phase"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/showbase/PhasedObject.py#L52-L65 | ||
apple/swift-clang | d7403439fc6641751840b723e7165fb02f52db95 | bindings/python/clang/cindex.py | python | Cursor.get_bitfield_width | (self) | return conf.lib.clang_getFieldDeclBitWidth(self) | Retrieve the width of a bitfield. | Retrieve the width of a bitfield. | [
"Retrieve",
"the",
"width",
"of",
"a",
"bitfield",
"."
] | def get_bitfield_width(self):
"""
Retrieve the width of a bitfield.
"""
return conf.lib.clang_getFieldDeclBitWidth(self) | [
"def",
"get_bitfield_width",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getFieldDeclBitWidth",
"(",
"self",
")"
] | https://github.com/apple/swift-clang/blob/d7403439fc6641751840b723e7165fb02f52db95/bindings/python/clang/cindex.py#L1881-L1885 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/util.py | python | GetResources | (resource) | Returns a list of resource directories from a given toplevel config dir
@param resource: config directory name
@return: list of resource directory that exist under the given resource path | Returns a list of resource directories from a given toplevel config dir
@param resource: config directory name
@return: list of resource directory that exist under the given resource path | [
"Returns",
"a",
"list",
"of",
"resource",
"directories",
"from",
"a",
"given",
"toplevel",
"config",
"dir",
"@param",
"resource",
":",
"config",
"directory",
"name",
"@return",
":",
"list",
"of",
"resource",
"directory",
"that",
"exist",
"under",
"the",
"given",
"resource",
"path"
] | def GetResources(resource):
"""Returns a list of resource directories from a given toplevel config dir
@param resource: config directory name
@return: list of resource directory that exist under the given resource path
"""
rec_dir = ResolvConfigDir(resource)
if os.path.exists(rec_dir):
rec_lst = [ rec.title() for rec in os.listdir(rec_dir)
if os.path.isdir(rec_dir + rec) and rec[0] != u"." ]
return rec_lst
else:
return -1 | [
"def",
"GetResources",
"(",
"resource",
")",
":",
"rec_dir",
"=",
"ResolvConfigDir",
"(",
"resource",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"rec_dir",
")",
":",
"rec_lst",
"=",
"[",
"rec",
".",
"title",
"(",
")",
"for",
"rec",
"in",
"os",
".",
"listdir",
"(",
"rec_dir",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"rec_dir",
"+",
"rec",
")",
"and",
"rec",
"[",
"0",
"]",
"!=",
"u\".\"",
"]",
"return",
"rec_lst",
"else",
":",
"return",
"-",
"1"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/util.py#L614-L626 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/data_flow_ops.py | python | StagingArea.clear | (self, name=None) | return gen_data_flow_ops.stage_clear(name=name, shared_name=self._name,
dtypes=self._dtypes, capacity=self._capacity,
memory_limit=self._memory_limit) | Clears the staging area.
Args:
name: A name for the operation (optional)
Returns:
The created op | Clears the staging area. | [
"Clears",
"the",
"staging",
"area",
"."
] | def clear(self, name=None):
"""Clears the staging area.
Args:
name: A name for the operation (optional)
Returns:
The created op
"""
if name is None:
name = "%s_clear" % self._name
return gen_data_flow_ops.stage_clear(name=name, shared_name=self._name,
dtypes=self._dtypes, capacity=self._capacity,
memory_limit=self._memory_limit) | [
"def",
"clear",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"\"%s_clear\"",
"%",
"self",
".",
"_name",
"return",
"gen_data_flow_ops",
".",
"stage_clear",
"(",
"name",
"=",
"name",
",",
"shared_name",
"=",
"self",
".",
"_name",
",",
"dtypes",
"=",
"self",
".",
"_dtypes",
",",
"capacity",
"=",
"self",
".",
"_capacity",
",",
"memory_limit",
"=",
"self",
".",
"_memory_limit",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/data_flow_ops.py#L1763-L1777 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.