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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/EnggCalibrate.py | python | EnggCalibrate._focus_run | (self, ws, vanadium_ws, bank, indices, prog) | return mantid.EnggFocus(InputWorkspace=ws, Bank=bank, SpectrumNumbers=indices, StoreInADS=False,
startProgress=0.3, endProgress=0.6, **engg_focus_params) | Focuses the input workspace by running EnggFocus as a child algorithm, which will produce a
single spectrum workspace.
@param ws :: workspace to focus
@param vanadium_ws :: workspace with Vanadium run for corrections
@param bank :: the focusing will be applied on the detectors of this bank
@param indices :: list of indices to consider, as an alternative to bank (bank and indices are
mutually exclusive)
@return focused (summed) workspace | Focuses the input workspace by running EnggFocus as a child algorithm, which will produce a
single spectrum workspace. | [
"Focuses",
"the",
"input",
"workspace",
"by",
"running",
"EnggFocus",
"as",
"a",
"child",
"algorithm",
"which",
"will",
"produce",
"a",
"single",
"spectrum",
"workspace",
"."
] | def _focus_run(self, ws, vanadium_ws, bank, indices, prog):
"""
Focuses the input workspace by running EnggFocus as a child algorithm, which will produce a
single spectrum workspace.
@param ws :: workspace to focus
@param vanadium_ws :: workspace with Vanadium run for corrections
@param bank :: the focusing will be applied on the detectors of this bank
@param indices :: list of indices to consider, as an alternative to bank (bank and indices are
mutually exclusive)
@return focused (summed) workspace
"""
prog.report("Initialising EnggFocus")
engg_focus_params = dict()
detector_positions = self.getProperty('DetectorPositions').value
if detector_positions:
engg_focus_params["DetectorPositions"] = detector_positions
if vanadium_ws:
engg_focus_params["VanadiumWorkspace"] = vanadium_ws
van_integration_ws = self.getProperty('VanIntegrationWorkspace').value
if van_integration_ws:
engg_focus_params["VanIntegrationWorkspace"] = van_integration_ws
van_curves_ws = self.getProperty('VanCurvesWorkspace').value
if van_curves_ws:
engg_focus_params['VanCurvesWorkspace'] = van_curves_ws
prog.report("Running EnggFocus")
return mantid.EnggFocus(InputWorkspace=ws, Bank=bank, SpectrumNumbers=indices, StoreInADS=False,
startProgress=0.3, endProgress=0.6, **engg_focus_params) | [
"def",
"_focus_run",
"(",
"self",
",",
"ws",
",",
"vanadium_ws",
",",
"bank",
",",
"indices",
",",
"prog",
")",
":",
"prog",
".",
"report",
"(",
"\"Initialising EnggFocus\"",
")",
"engg_focus_params",
"=",
"dict",
"(",
")",
"detector_positions",
"=",
"self",
".",
"getProperty",
"(",
"'DetectorPositions'",
")",
".",
"value",
"if",
"detector_positions",
":",
"engg_focus_params",
"[",
"\"DetectorPositions\"",
"]",
"=",
"detector_positions",
"if",
"vanadium_ws",
":",
"engg_focus_params",
"[",
"\"VanadiumWorkspace\"",
"]",
"=",
"vanadium_ws",
"van_integration_ws",
"=",
"self",
".",
"getProperty",
"(",
"'VanIntegrationWorkspace'",
")",
".",
"value",
"if",
"van_integration_ws",
":",
"engg_focus_params",
"[",
"\"VanIntegrationWorkspace\"",
"]",
"=",
"van_integration_ws",
"van_curves_ws",
"=",
"self",
".",
"getProperty",
"(",
"'VanCurvesWorkspace'",
")",
".",
"value",
"if",
"van_curves_ws",
":",
"engg_focus_params",
"[",
"'VanCurvesWorkspace'",
"]",
"=",
"van_curves_ws",
"prog",
".",
"report",
"(",
"\"Running EnggFocus\"",
")",
"return",
"mantid",
".",
"EnggFocus",
"(",
"InputWorkspace",
"=",
"ws",
",",
"Bank",
"=",
"bank",
",",
"SpectrumNumbers",
"=",
"indices",
",",
"StoreInADS",
"=",
"False",
",",
"startProgress",
"=",
"0.3",
",",
"endProgress",
"=",
"0.6",
",",
"*",
"*",
"engg_focus_params",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/EnggCalibrate.py#L197-L231 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/peakprocesshelper.py | python | PeakProcessRecord.get_intensity | (self, algorithm_type, lorentz_corrected) | return intensity, std_dev | get the integrated intensity with specified integration algorithm and whether
the result should be corrected by Lorentz correction factor
:param algorithm_type:
:param lorentz_corrected:
:return: | get the integrated intensity with specified integration algorithm and whether
the result should be corrected by Lorentz correction factor
:param algorithm_type:
:param lorentz_corrected:
:return: | [
"get",
"the",
"integrated",
"intensity",
"with",
"specified",
"integration",
"algorithm",
"and",
"whether",
"the",
"result",
"should",
"be",
"corrected",
"by",
"Lorentz",
"correction",
"factor",
":",
"param",
"algorithm_type",
":",
":",
"param",
"lorentz_corrected",
":",
":",
"return",
":"
] | def get_intensity(self, algorithm_type, lorentz_corrected):
"""
get the integrated intensity with specified integration algorithm and whether
the result should be corrected by Lorentz correction factor
:param algorithm_type:
:param lorentz_corrected:
:return:
"""
# check
if self._integrationDict is None and self._myIntensity is None:
raise RuntimeError('PeakInfo of Exp {0} Scan {1} ({2} | {3}) has not integrated setup.'
''.format(self._myExpNumber, self._myScanNumber, self._fingerPrint, hex(id(self))))
elif self._myIntensity is not None:
# return ZERO intensity due to previously found error
return self._myIntensity, 0.
try:
if algorithm_type == 0 or algorithm_type.startswith('simple'):
# simple
intensity = self._integrationDict['simple intensity']
std_dev = self._integrationDict['simple error']
elif algorithm_type == 1 or algorithm_type.count('mixed') > 0:
# intensity 2: mixed simple and gaussian
intensity = self._integrationDict['intensity 2']
std_dev = self._integrationDict['error 2']
elif algorithm_type == 2 or algorithm_type.count('gauss') > 0:
# gaussian
intensity = self._integrationDict['gauss intensity']
std_dev = self._integrationDict['gauss error']
else:
raise RuntimeError('Type {0} not supported yet.')
except KeyError as key_err:
err_msg = 'Some key(s) does not exist in dictionary with keys {0}. FYI: {1}' \
''.format(self._integrationDict.keys(), key_err)
raise RuntimeError(err_msg)
if intensity is None:
intensity = 0.
std_dev = 0.
elif lorentz_corrected:
intensity *= self._lorenzFactor
std_dev *= self._lorenzFactor
return intensity, std_dev | [
"def",
"get_intensity",
"(",
"self",
",",
"algorithm_type",
",",
"lorentz_corrected",
")",
":",
"# check",
"if",
"self",
".",
"_integrationDict",
"is",
"None",
"and",
"self",
".",
"_myIntensity",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'PeakInfo of Exp {0} Scan {1} ({2} | {3}) has not integrated setup.'",
"''",
".",
"format",
"(",
"self",
".",
"_myExpNumber",
",",
"self",
".",
"_myScanNumber",
",",
"self",
".",
"_fingerPrint",
",",
"hex",
"(",
"id",
"(",
"self",
")",
")",
")",
")",
"elif",
"self",
".",
"_myIntensity",
"is",
"not",
"None",
":",
"# return ZERO intensity due to previously found error",
"return",
"self",
".",
"_myIntensity",
",",
"0.",
"try",
":",
"if",
"algorithm_type",
"==",
"0",
"or",
"algorithm_type",
".",
"startswith",
"(",
"'simple'",
")",
":",
"# simple",
"intensity",
"=",
"self",
".",
"_integrationDict",
"[",
"'simple intensity'",
"]",
"std_dev",
"=",
"self",
".",
"_integrationDict",
"[",
"'simple error'",
"]",
"elif",
"algorithm_type",
"==",
"1",
"or",
"algorithm_type",
".",
"count",
"(",
"'mixed'",
")",
">",
"0",
":",
"# intensity 2: mixed simple and gaussian",
"intensity",
"=",
"self",
".",
"_integrationDict",
"[",
"'intensity 2'",
"]",
"std_dev",
"=",
"self",
".",
"_integrationDict",
"[",
"'error 2'",
"]",
"elif",
"algorithm_type",
"==",
"2",
"or",
"algorithm_type",
".",
"count",
"(",
"'gauss'",
")",
">",
"0",
":",
"# gaussian",
"intensity",
"=",
"self",
".",
"_integrationDict",
"[",
"'gauss intensity'",
"]",
"std_dev",
"=",
"self",
".",
"_integrationDict",
"[",
"'gauss error'",
"]",
"else",
":",
"raise",
"RuntimeError",
"(",
"'Type {0} not supported yet.'",
")",
"except",
"KeyError",
"as",
"key_err",
":",
"err_msg",
"=",
"'Some key(s) does not exist in dictionary with keys {0}. FYI: {1}'",
"''",
".",
"format",
"(",
"self",
".",
"_integrationDict",
".",
"keys",
"(",
")",
",",
"key_err",
")",
"raise",
"RuntimeError",
"(",
"err_msg",
")",
"if",
"intensity",
"is",
"None",
":",
"intensity",
"=",
"0.",
"std_dev",
"=",
"0.",
"elif",
"lorentz_corrected",
":",
"intensity",
"*=",
"self",
".",
"_lorenzFactor",
"std_dev",
"*=",
"self",
".",
"_lorenzFactor",
"return",
"intensity",
",",
"std_dev"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/peakprocesshelper.py#L222-L265 | |
coinapi/coinapi-sdk | 854f21e7f69ea8599ae35c5403565cf299d8b795 | oeml-sdk/python/openapi_client/rest.py | python | RESTResponse.getheaders | (self) | return self.urllib3_response.getheaders() | Returns a dictionary of the response headers. | Returns a dictionary of the response headers. | [
"Returns",
"a",
"dictionary",
"of",
"the",
"response",
"headers",
"."
] | def getheaders(self):
"""Returns a dictionary of the response headers."""
return self.urllib3_response.getheaders() | [
"def",
"getheaders",
"(",
"self",
")",
":",
"return",
"self",
".",
"urllib3_response",
".",
"getheaders",
"(",
")"
] | https://github.com/coinapi/coinapi-sdk/blob/854f21e7f69ea8599ae35c5403565cf299d8b795/oeml-sdk/python/openapi_client/rest.py#L37-L39 | |
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | compiler-rt/lib/sanitizer_common/scripts/cpplint.py | python | ProcessConfigOverrides | (filename) | return True | Loads the configuration files and processes the config overrides.
Args:
filename: The name of the file being processed by the linter.
Returns:
False if the current |filename| should not be processed further. | Loads the configuration files and processes the config overrides. | [
"Loads",
"the",
"configuration",
"files",
"and",
"processes",
"the",
"config",
"overrides",
"."
] | def ProcessConfigOverrides(filename):
""" Loads the configuration files and processes the config overrides.
Args:
filename: The name of the file being processed by the linter.
Returns:
False if the current |filename| should not be processed further.
"""
abs_filename = os.path.abspath(filename)
cfg_filters = []
keep_looking = True
while keep_looking:
abs_path, base_name = os.path.split(abs_filename)
if not base_name:
break # Reached the root directory.
cfg_file = os.path.join(abs_path, "CPPLINT.cfg")
abs_filename = abs_path
if not os.path.isfile(cfg_file):
continue
try:
with open(cfg_file) as file_handle:
for line in file_handle:
line, _, _ = line.partition('#') # Remove comments.
if not line.strip():
continue
name, _, val = line.partition('=')
name = name.strip()
val = val.strip()
if name == 'set noparent':
keep_looking = False
elif name == 'filter':
cfg_filters.append(val)
elif name == 'exclude_files':
# When matching exclude_files pattern, use the base_name of
# the current file name or the directory name we are processing.
# For example, if we are checking for lint errors in /foo/bar/baz.cc
# and we found the .cfg file at /foo/CPPLINT.cfg, then the config
# file's "exclude_files" filter is meant to be checked against "bar"
# and not "baz" nor "bar/baz.cc".
if base_name:
pattern = re.compile(val)
if pattern.match(base_name):
if _cpplint_state.quiet:
# Suppress "Ignoring file" warning when using --quiet.
return False
sys.stderr.write('Ignoring "%s": file excluded by "%s". '
'File path component "%s" matches '
'pattern "%s"\n' %
(filename, cfg_file, base_name, val))
return False
elif name == 'linelength':
global _line_length
try:
_line_length = int(val)
except ValueError:
sys.stderr.write('Line length must be numeric.')
elif name == 'root':
global _root
# root directories are specified relative to CPPLINT.cfg dir.
_root = os.path.join(os.path.dirname(cfg_file), val)
elif name == 'headers':
ProcessHppHeadersOption(val)
else:
sys.stderr.write(
'Invalid configuration option (%s) in file %s\n' %
(name, cfg_file))
except IOError:
sys.stderr.write(
"Skipping config file '%s': Can't open for reading\n" % cfg_file)
keep_looking = False
# Apply all the accumulated filters in reverse order (top-level directory
# config options having the least priority).
for filter in reversed(cfg_filters):
_AddFilters(filter)
return True | [
"def",
"ProcessConfigOverrides",
"(",
"filename",
")",
":",
"abs_filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
"cfg_filters",
"=",
"[",
"]",
"keep_looking",
"=",
"True",
"while",
"keep_looking",
":",
"abs_path",
",",
"base_name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"abs_filename",
")",
"if",
"not",
"base_name",
":",
"break",
"# Reached the root directory.",
"cfg_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"abs_path",
",",
"\"CPPLINT.cfg\"",
")",
"abs_filename",
"=",
"abs_path",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"cfg_file",
")",
":",
"continue",
"try",
":",
"with",
"open",
"(",
"cfg_file",
")",
"as",
"file_handle",
":",
"for",
"line",
"in",
"file_handle",
":",
"line",
",",
"_",
",",
"_",
"=",
"line",
".",
"partition",
"(",
"'#'",
")",
"# Remove comments.",
"if",
"not",
"line",
".",
"strip",
"(",
")",
":",
"continue",
"name",
",",
"_",
",",
"val",
"=",
"line",
".",
"partition",
"(",
"'='",
")",
"name",
"=",
"name",
".",
"strip",
"(",
")",
"val",
"=",
"val",
".",
"strip",
"(",
")",
"if",
"name",
"==",
"'set noparent'",
":",
"keep_looking",
"=",
"False",
"elif",
"name",
"==",
"'filter'",
":",
"cfg_filters",
".",
"append",
"(",
"val",
")",
"elif",
"name",
"==",
"'exclude_files'",
":",
"# When matching exclude_files pattern, use the base_name of",
"# the current file name or the directory name we are processing.",
"# For example, if we are checking for lint errors in /foo/bar/baz.cc",
"# and we found the .cfg file at /foo/CPPLINT.cfg, then the config",
"# file's \"exclude_files\" filter is meant to be checked against \"bar\"",
"# and not \"baz\" nor \"bar/baz.cc\".",
"if",
"base_name",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"val",
")",
"if",
"pattern",
".",
"match",
"(",
"base_name",
")",
":",
"if",
"_cpplint_state",
".",
"quiet",
":",
"# Suppress \"Ignoring file\" warning when using --quiet.",
"return",
"False",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Ignoring \"%s\": file excluded by \"%s\". '",
"'File path component \"%s\" matches '",
"'pattern \"%s\"\\n'",
"%",
"(",
"filename",
",",
"cfg_file",
",",
"base_name",
",",
"val",
")",
")",
"return",
"False",
"elif",
"name",
"==",
"'linelength'",
":",
"global",
"_line_length",
"try",
":",
"_line_length",
"=",
"int",
"(",
"val",
")",
"except",
"ValueError",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Line length must be numeric.'",
")",
"elif",
"name",
"==",
"'root'",
":",
"global",
"_root",
"# root directories are specified relative to CPPLINT.cfg dir.",
"_root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"cfg_file",
")",
",",
"val",
")",
"elif",
"name",
"==",
"'headers'",
":",
"ProcessHppHeadersOption",
"(",
"val",
")",
"else",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Invalid configuration option (%s) in file %s\\n'",
"%",
"(",
"name",
",",
"cfg_file",
")",
")",
"except",
"IOError",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Skipping config file '%s': Can't open for reading\\n\"",
"%",
"cfg_file",
")",
"keep_looking",
"=",
"False",
"# Apply all the accumulated filters in reverse order (top-level directory",
"# config options having the least priority).",
"for",
"filter",
"in",
"reversed",
"(",
"cfg_filters",
")",
":",
"_AddFilters",
"(",
"filter",
")",
"return",
"True"
] | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L5946-L6028 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/logging/handlers.py | python | QueueListener.start | (self) | Start the listener.
This starts up a background thread to monitor the queue for
LogRecords to process. | Start the listener. | [
"Start",
"the",
"listener",
"."
] | def start(self):
"""
Start the listener.
This starts up a background thread to monitor the queue for
LogRecords to process.
"""
self._thread = t = threading.Thread(target=self._monitor)
t.daemon = True
t.start() | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_thread",
"=",
"t",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"_monitor",
")",
"t",
".",
"daemon",
"=",
"True",
"t",
".",
"start",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/logging/handlers.py#L1429-L1438 | ||
baidu/AnyQ | d94d450d2aaa5f7ed73424b10aa4539835b97527 | tools/common/nlp_algo.py | python | character_similarity | (str_a, str_b) | return min(matching_degree / len(set1), matching_degree / len(set2)) | Calculate character similarity
Returns: character similarity score | Calculate character similarity
Returns: character similarity score | [
"Calculate",
"character",
"similarity",
"Returns",
":",
"character",
"similarity",
"score"
] | def character_similarity(str_a, str_b):
"""
Calculate character similarity
Returns: character similarity score
"""
set1 = set(str_a.decode('utf8'))
set2 = set(str_b.decode('utf8'))
matching_degree = float(len(set1 & set2))
return min(matching_degree / len(set1), matching_degree / len(set2)) | [
"def",
"character_similarity",
"(",
"str_a",
",",
"str_b",
")",
":",
"set1",
"=",
"set",
"(",
"str_a",
".",
"decode",
"(",
"'utf8'",
")",
")",
"set2",
"=",
"set",
"(",
"str_b",
".",
"decode",
"(",
"'utf8'",
")",
")",
"matching_degree",
"=",
"float",
"(",
"len",
"(",
"set1",
"&",
"set2",
")",
")",
"return",
"min",
"(",
"matching_degree",
"/",
"len",
"(",
"set1",
")",
",",
"matching_degree",
"/",
"len",
"(",
"set2",
")",
")"
] | https://github.com/baidu/AnyQ/blob/d94d450d2aaa5f7ed73424b10aa4539835b97527/tools/common/nlp_algo.py#L120-L128 | |
gwaldron/osgearth | 4c521857d59a69743e4a9cedba00afe570f984e8 | src/third_party/tinygltf/deps/cpplint.py | python | _CppLintState.PrintErrorCounts | (self) | Print a summary of errors by category, and the total. | Print a summary of errors by category, and the total. | [
"Print",
"a",
"summary",
"of",
"errors",
"by",
"category",
"and",
"the",
"total",
"."
] | def PrintErrorCounts(self):
"""Print a summary of errors by category, and the total."""
for category, count in self.errors_by_category.iteritems():
sys.stderr.write('Category \'%s\' errors found: %d\n' %
(category, count))
sys.stderr.write('Total errors found: %d\n' % self.error_count) | [
"def",
"PrintErrorCounts",
"(",
"self",
")",
":",
"for",
"category",
",",
"count",
"in",
"self",
".",
"errors_by_category",
".",
"iteritems",
"(",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Category \\'%s\\' errors found: %d\\n'",
"%",
"(",
"category",
",",
"count",
")",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Total errors found: %d\\n'",
"%",
"self",
".",
"error_count",
")"
] | https://github.com/gwaldron/osgearth/blob/4c521857d59a69743e4a9cedba00afe570f984e8/src/third_party/tinygltf/deps/cpplint.py#L841-L846 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py | python | _ExtensionDict.__init__ | (self, extended_message) | extended_message: Message instance for which we are the Extensions dict. | extended_message: Message instance for which we are the Extensions dict. | [
"extended_message",
":",
"Message",
"instance",
"for",
"which",
"we",
"are",
"the",
"Extensions",
"dict",
"."
] | def __init__(self, extended_message):
"""extended_message: Message instance for which we are the Extensions dict.
"""
self._extended_message = extended_message | [
"def",
"__init__",
"(",
"self",
",",
"extended_message",
")",
":",
"self",
".",
"_extended_message",
"=",
"extended_message"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L1435-L1439 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/control/robotinterfaceutils.py | python | _JointInterfaceEmulatorData._getSegment | (self,t) | return (p,u) | Returns the index and interpolation parameter for the
segment at time t.
Running time is O(log n) time where n is the number of segments. | Returns the index and interpolation parameter for the
segment at time t. | [
"Returns",
"the",
"index",
"and",
"interpolation",
"parameter",
"for",
"the",
"segment",
"at",
"time",
"t",
"."
] | def _getSegment(self,t):
"""Returns the index and interpolation parameter for the
segment at time t.
Running time is O(log n) time where n is the number of segments.
"""
if len(self.trajectoryTimes)==0:
raise ValueError("Empty trajectory")
if len(self.trajectoryTimes)==1:
return (-1,0)
if t >= self.trajectoryTimes[-1]:
return (len(self.trajectoryTimes)-1,0)
if t <= self.trajectoryTimes[0]:
return (0,0)
i = bisect.bisect_right(self.trajectoryTimes,t)
p=i-1
assert i > 0 and i < len(self.trajectoryTimes),"Invalid time index "+str(t)+" in "+str(self.trajectoryTimes)
u=(t-self.trajectoryTimes[p])/(self.trajectoryTimes[i]-self.trajectoryTimes[p])
if i==0:
return (-1,0)
assert u >= 0 and u <= 1
return (p,u) | [
"def",
"_getSegment",
"(",
"self",
",",
"t",
")",
":",
"if",
"len",
"(",
"self",
".",
"trajectoryTimes",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"Empty trajectory\"",
")",
"if",
"len",
"(",
"self",
".",
"trajectoryTimes",
")",
"==",
"1",
":",
"return",
"(",
"-",
"1",
",",
"0",
")",
"if",
"t",
">=",
"self",
".",
"trajectoryTimes",
"[",
"-",
"1",
"]",
":",
"return",
"(",
"len",
"(",
"self",
".",
"trajectoryTimes",
")",
"-",
"1",
",",
"0",
")",
"if",
"t",
"<=",
"self",
".",
"trajectoryTimes",
"[",
"0",
"]",
":",
"return",
"(",
"0",
",",
"0",
")",
"i",
"=",
"bisect",
".",
"bisect_right",
"(",
"self",
".",
"trajectoryTimes",
",",
"t",
")",
"p",
"=",
"i",
"-",
"1",
"assert",
"i",
">",
"0",
"and",
"i",
"<",
"len",
"(",
"self",
".",
"trajectoryTimes",
")",
",",
"\"Invalid time index \"",
"+",
"str",
"(",
"t",
")",
"+",
"\" in \"",
"+",
"str",
"(",
"self",
".",
"trajectoryTimes",
")",
"u",
"=",
"(",
"t",
"-",
"self",
".",
"trajectoryTimes",
"[",
"p",
"]",
")",
"/",
"(",
"self",
".",
"trajectoryTimes",
"[",
"i",
"]",
"-",
"self",
".",
"trajectoryTimes",
"[",
"p",
"]",
")",
"if",
"i",
"==",
"0",
":",
"return",
"(",
"-",
"1",
",",
"0",
")",
"assert",
"u",
">=",
"0",
"and",
"u",
"<=",
"1",
"return",
"(",
"p",
",",
"u",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/control/robotinterfaceutils.py#L3894-L3915 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/control/motion_generation.py | python | VelocityBoundedMotionGeneration.setVelocity | (self,vtarget,duration=1,append=False) | Sets a velocity command to vtarget. Moves along this
speed for duration seconds and then stops. | Sets a velocity command to vtarget. Moves along this
speed for duration seconds and then stops. | [
"Sets",
"a",
"velocity",
"command",
"to",
"vtarget",
".",
"Moves",
"along",
"this",
"speed",
"for",
"duration",
"seconds",
"and",
"then",
"stops",
"."
] | def setVelocity(self,vtarget,duration=1,append=False):
"""Sets a velocity command to vtarget. Moves along this
speed for duration seconds and then stops.
"""
assert len(vtarget) == len(self.x)
assert duration >= 0
self._trim(append)
xlast = self.milestones[-1]
self.times.append(self.times[-1]+duration)
self.milestones.append(vectorops.madd(xlast,vtarget,duration)) | [
"def",
"setVelocity",
"(",
"self",
",",
"vtarget",
",",
"duration",
"=",
"1",
",",
"append",
"=",
"False",
")",
":",
"assert",
"len",
"(",
"vtarget",
")",
"==",
"len",
"(",
"self",
".",
"x",
")",
"assert",
"duration",
">=",
"0",
"self",
".",
"_trim",
"(",
"append",
")",
"xlast",
"=",
"self",
".",
"milestones",
"[",
"-",
"1",
"]",
"self",
".",
"times",
".",
"append",
"(",
"self",
".",
"times",
"[",
"-",
"1",
"]",
"+",
"duration",
")",
"self",
".",
"milestones",
".",
"append",
"(",
"vectorops",
".",
"madd",
"(",
"xlast",
",",
"vtarget",
",",
"duration",
")",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/control/motion_generation.py#L99-L108 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/chigger/filters/TubeFilter.py | python | TubeFilter.update | (self, **kwargs) | Computes the contour levels for the vtkContourFilter. | Computes the contour levels for the vtkContourFilter. | [
"Computes",
"the",
"contour",
"levels",
"for",
"the",
"vtkContourFilter",
"."
] | def update(self, **kwargs):
"""
Computes the contour levels for the vtkContourFilter.
"""
super(TubeFilter, self).update(**kwargs)
if self.isOptionValid('radius'):
self._vtkfilter.SetRadius(self.getOption('radius'))
if self.isOptionValid('normalized_radius'):
if self.isOptionValid('radius'):
mooseutils.mooseWarning("The 'radius' and 'normalized_radius' options are both "
"set, the 'radius is being used.'")
else:
self._vtkfilter.SetRadius(utils.compute_distance(self._source) *
self.getOption('normalized_radius'))
if self.isOptionValid('sides'):
self._vtkfilter.SetNumberOfSides(self.getOption('sides'))
if self.isOptionValid('caps'):
self._vtkfilter.SetCapping(self.getOption('caps')) | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"TubeFilter",
",",
"self",
")",
".",
"update",
"(",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"isOptionValid",
"(",
"'radius'",
")",
":",
"self",
".",
"_vtkfilter",
".",
"SetRadius",
"(",
"self",
".",
"getOption",
"(",
"'radius'",
")",
")",
"if",
"self",
".",
"isOptionValid",
"(",
"'normalized_radius'",
")",
":",
"if",
"self",
".",
"isOptionValid",
"(",
"'radius'",
")",
":",
"mooseutils",
".",
"mooseWarning",
"(",
"\"The 'radius' and 'normalized_radius' options are both \"",
"\"set, the 'radius is being used.'\"",
")",
"else",
":",
"self",
".",
"_vtkfilter",
".",
"SetRadius",
"(",
"utils",
".",
"compute_distance",
"(",
"self",
".",
"_source",
")",
"*",
"self",
".",
"getOption",
"(",
"'normalized_radius'",
")",
")",
"if",
"self",
".",
"isOptionValid",
"(",
"'sides'",
")",
":",
"self",
".",
"_vtkfilter",
".",
"SetNumberOfSides",
"(",
"self",
".",
"getOption",
"(",
"'sides'",
")",
")",
"if",
"self",
".",
"isOptionValid",
"(",
"'caps'",
")",
":",
"self",
".",
"_vtkfilter",
".",
"SetCapping",
"(",
"self",
".",
"getOption",
"(",
"'caps'",
")",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/chigger/filters/TubeFilter.py#L36-L57 | ||
dartsim/dart | 495c82120c836005f2d136d4a50c8cc997fb879b | tools/cpplint.py | python | Error | (filename, linenum, category, confidence, message) | Logs the fact we've found a lint error.
We log where the error was found, and also our confidence in the error,
that is, how certain we are this is a legitimate style regression, and
not a misidentification or a use that's sometimes justified.
False positives can be suppressed by the use of
"cpplint(category)" comments on the offending line. These are
parsed into _error_suppressions.
Args:
filename: The name of the file containing the error.
linenum: The number of the line containing the error.
category: A string used to describe the "category" this bug
falls under: "whitespace", say, or "runtime". Categories
may have a hierarchy separated by slashes: "whitespace/indent".
confidence: A number from 1-5 representing a confidence score for
the error, with 5 meaning that we are certain of the problem,
and 1 meaning that it could be a legitimate construct.
message: The error message. | Logs the fact we've found a lint error. | [
"Logs",
"the",
"fact",
"we",
"ve",
"found",
"a",
"lint",
"error",
"."
] | def Error(filename, linenum, category, confidence, message):
"""Logs the fact we've found a lint error.
We log where the error was found, and also our confidence in the error,
that is, how certain we are this is a legitimate style regression, and
not a misidentification or a use that's sometimes justified.
False positives can be suppressed by the use of
"cpplint(category)" comments on the offending line. These are
parsed into _error_suppressions.
Args:
filename: The name of the file containing the error.
linenum: The number of the line containing the error.
category: A string used to describe the "category" this bug
falls under: "whitespace", say, or "runtime". Categories
may have a hierarchy separated by slashes: "whitespace/indent".
confidence: A number from 1-5 representing a confidence score for
the error, with 5 meaning that we are certain of the problem,
and 1 meaning that it could be a legitimate construct.
message: The error message.
"""
if _ShouldPrintError(category, confidence, linenum):
_cpplint_state.IncrementErrorCount(category)
if _cpplint_state.output_format == 'vs7':
sys.stderr.write('%s(%s): %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence))
elif _cpplint_state.output_format == 'eclipse':
sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence))
else:
sys.stderr.write('%s:%s: %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence)) | [
"def",
"Error",
"(",
"filename",
",",
"linenum",
",",
"category",
",",
"confidence",
",",
"message",
")",
":",
"if",
"_ShouldPrintError",
"(",
"category",
",",
"confidence",
",",
"linenum",
")",
":",
"_cpplint_state",
".",
"IncrementErrorCount",
"(",
"category",
")",
"if",
"_cpplint_state",
".",
"output_format",
"==",
"'vs7'",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'%s(%s): %s [%s] [%d]\\n'",
"%",
"(",
"filename",
",",
"linenum",
",",
"message",
",",
"category",
",",
"confidence",
")",
")",
"elif",
"_cpplint_state",
".",
"output_format",
"==",
"'eclipse'",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'%s:%s: warning: %s [%s] [%d]\\n'",
"%",
"(",
"filename",
",",
"linenum",
",",
"message",
",",
"category",
",",
"confidence",
")",
")",
"else",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'%s:%s: %s [%s] [%d]\\n'",
"%",
"(",
"filename",
",",
"linenum",
",",
"message",
",",
"category",
",",
"confidence",
")",
")"
] | https://github.com/dartsim/dart/blob/495c82120c836005f2d136d4a50c8cc997fb879b/tools/cpplint.py#L965-L997 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py2/pkg_resources/_vendor/pyparsing.py | python | pyparsing_common.stripHTMLTags | (s, l, tokens) | return pyparsing_common._html_stripper.transformString(tokens[0]) | Parse action to remove HTML tags from web page HTML source
Example::
# strip HTML links from normal text
text = '<td>More info at the <a href="http://pyparsing.wikispaces.com">pyparsing</a> wiki page</td>'
td,td_end = makeHTMLTags("TD")
table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)("body") + td_end
print(table_text.parseString(text).body) # -> 'More info at the pyparsing wiki page' | Parse action to remove HTML tags from web page HTML source | [
"Parse",
"action",
"to",
"remove",
"HTML",
"tags",
"from",
"web",
"page",
"HTML",
"source"
] | def stripHTMLTags(s, l, tokens):
"""
Parse action to remove HTML tags from web page HTML source
Example::
# strip HTML links from normal text
text = '<td>More info at the <a href="http://pyparsing.wikispaces.com">pyparsing</a> wiki page</td>'
td,td_end = makeHTMLTags("TD")
table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)("body") + td_end
print(table_text.parseString(text).body) # -> 'More info at the pyparsing wiki page'
"""
return pyparsing_common._html_stripper.transformString(tokens[0]) | [
"def",
"stripHTMLTags",
"(",
"s",
",",
"l",
",",
"tokens",
")",
":",
"return",
"pyparsing_common",
".",
"_html_stripper",
".",
"transformString",
"(",
"tokens",
"[",
"0",
"]",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/pkg_resources/_vendor/pyparsing.py#L5647-L5659 | |
s5z/zsim | fb4d6e0475a25cffd23f0687ede2d43d96b4a99f | misc/cpplint.py | python | CheckForNonStandardConstructs | (filename, clean_lines, linenum,
nesting_state, error) | Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message | Logs an error if we see certain non-ANSI constructs ignored by gcc-2. | [
"Logs",
"an",
"error",
"if",
"we",
"see",
"certain",
"non",
"-",
"ANSI",
"constructs",
"ignored",
"by",
"gcc",
"-",
"2",
"."
] | def CheckForNonStandardConstructs(filename, clean_lines, linenum,
nesting_state, error):
"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
"""
# Remove comments from the line, but leave in strings for now.
line = clean_lines.lines[linenum]
if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
error(filename, linenum, 'runtime/printf_format', 3,
'%q in format strings is deprecated. Use %ll instead.')
if Search(r'printf\s*\(.*".*%\d+\$', line):
error(filename, linenum, 'runtime/printf_format', 2,
'%N$ formats are unconventional. Try rewriting to avoid them.')
# Remove escaped backslashes before looking for undefined escapes.
line = line.replace('\\\\', '')
if Search(r'("|\').*\\(%|\[|\(|{)', line):
error(filename, linenum, 'build/printf_format', 3,
'%, [, (, and { are undefined character escapes. Unescape them.')
# For the rest, work with both comments and strings removed.
line = clean_lines.elided[linenum]
if Search(r'\b(const|volatile|void|char|short|int|long'
r'|float|double|signed|unsigned'
r'|schar|u?int8|u?int16|u?int32|u?int64)'
r'\s+(register|static|extern|typedef)\b',
line):
error(filename, linenum, 'build/storage_class', 5,
'Storage class (static, extern, typedef, etc) should be first.')
if Match(r'\s*#\s*endif\s*[^/\s]+', line):
error(filename, linenum, 'build/endif_comment', 5,
'Uncommented text after #endif is non-standard. Use a comment.')
if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
error(filename, linenum, 'build/forward_decl', 5,
'Inner-style forward declarations are invalid. Remove this line.')
if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
line):
error(filename, linenum, 'build/deprecated', 3,
'>? and <? (max and min) operators are non-standard and deprecated.')
if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
# TODO(unknown): Could it be expanded safely to arbitrary references,
# without triggering too many false positives? The first
# attempt triggered 5 warnings for mostly benign code in the regtest, hence
# the restriction.
# Here's the original regexp, for the reference:
# type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
# r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
error(filename, linenum, 'runtime/member_string_references', 2,
'const string& members are dangerous. It is much better to use '
'alternatives, such as pointers or simple constants.')
# Everything else in this function operates on class declarations.
# Return early if the top of the nesting stack is not a class, or if
# the class head is not completed yet.
classinfo = nesting_state.InnermostClass()
if not classinfo or not classinfo.seen_open_brace:
return
# The class may have been declared with namespace or classname qualifiers.
# The constructor and destructor will not have those qualifiers.
base_classname = classinfo.name.split('::')[-1]
# Look for single-argument constructors that aren't marked explicit.
# Technically a valid construct, but against style.
args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)'
% re.escape(base_classname),
line)
if (args and
args.group(1) != 'void' and
not Match(r'(const\s+)?%s\s*(?:<\w+>\s*)?&' % re.escape(base_classname),
args.group(1).strip())):
error(filename, linenum, 'runtime/explicit', 5,
'Single-argument constructors should be marked explicit.') | [
"def",
"CheckForNonStandardConstructs",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"# Remove comments from the line, but leave in strings for now.",
"line",
"=",
"clean_lines",
".",
"lines",
"[",
"linenum",
"]",
"if",
"Search",
"(",
"r'printf\\s*\\(.*\".*%[-+ ]?\\d*q'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf_format'",
",",
"3",
",",
"'%q in format strings is deprecated. Use %ll instead.'",
")",
"if",
"Search",
"(",
"r'printf\\s*\\(.*\".*%\\d+\\$'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf_format'",
",",
"2",
",",
"'%N$ formats are unconventional. Try rewriting to avoid them.'",
")",
"# Remove escaped backslashes before looking for undefined escapes.",
"line",
"=",
"line",
".",
"replace",
"(",
"'\\\\\\\\'",
",",
"''",
")",
"if",
"Search",
"(",
"r'(\"|\\').*\\\\(%|\\[|\\(|{)'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/printf_format'",
",",
"3",
",",
"'%, [, (, and { are undefined character escapes. Unescape them.'",
")",
"# For the rest, work with both comments and strings removed.",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"Search",
"(",
"r'\\b(const|volatile|void|char|short|int|long'",
"r'|float|double|signed|unsigned'",
"r'|schar|u?int8|u?int16|u?int32|u?int64)'",
"r'\\s+(register|static|extern|typedef)\\b'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/storage_class'",
",",
"5",
",",
"'Storage class (static, extern, typedef, etc) should be first.'",
")",
"if",
"Match",
"(",
"r'\\s*#\\s*endif\\s*[^/\\s]+'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/endif_comment'",
",",
"5",
",",
"'Uncommented text after #endif is non-standard. Use a comment.'",
")",
"if",
"Match",
"(",
"r'\\s*class\\s+(\\w+\\s*::\\s*)+\\w+\\s*;'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/forward_decl'",
",",
"5",
",",
"'Inner-style forward declarations are invalid. Remove this line.'",
")",
"if",
"Search",
"(",
"r'(\\w+|[+-]?\\d+(\\.\\d*)?)\\s*(<|>)\\?=?\\s*(\\w+|[+-]?\\d+)(\\.\\d*)?'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/deprecated'",
",",
"3",
",",
"'>? and <? (max and min) operators are non-standard and deprecated.'",
")",
"if",
"Search",
"(",
"r'^\\s*const\\s*string\\s*&\\s*\\w+\\s*;'",
",",
"line",
")",
":",
"# TODO(unknown): Could it be expanded safely to arbitrary references,",
"# without triggering too many false positives? The first",
"# attempt triggered 5 warnings for mostly benign code in the regtest, hence",
"# the restriction.",
"# Here's the original regexp, for the reference:",
"# type_name = r'\\w+((\\s*::\\s*\\w+)|(\\s*<\\s*\\w+?\\s*>))?'",
"# r'\\s*const\\s*' + type_name + '\\s*&\\s*\\w+\\s*;'",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/member_string_references'",
",",
"2",
",",
"'const string& members are dangerous. It is much better to use '",
"'alternatives, such as pointers or simple constants.'",
")",
"# Everything else in this function operates on class declarations.",
"# Return early if the top of the nesting stack is not a class, or if",
"# the class head is not completed yet.",
"classinfo",
"=",
"nesting_state",
".",
"InnermostClass",
"(",
")",
"if",
"not",
"classinfo",
"or",
"not",
"classinfo",
".",
"seen_open_brace",
":",
"return",
"# The class may have been declared with namespace or classname qualifiers.",
"# The constructor and destructor will not have those qualifiers.",
"base_classname",
"=",
"classinfo",
".",
"name",
".",
"split",
"(",
"'::'",
")",
"[",
"-",
"1",
"]",
"# Look for single-argument constructors that aren't marked explicit.",
"# Technically a valid construct, but against style.",
"args",
"=",
"Match",
"(",
"r'\\s+(?:inline\\s+)?%s\\s*\\(([^,()]+)\\)'",
"%",
"re",
".",
"escape",
"(",
"base_classname",
")",
",",
"line",
")",
"if",
"(",
"args",
"and",
"args",
".",
"group",
"(",
"1",
")",
"!=",
"'void'",
"and",
"not",
"Match",
"(",
"r'(const\\s+)?%s\\s*(?:<\\w+>\\s*)?&'",
"%",
"re",
".",
"escape",
"(",
"base_classname",
")",
",",
"args",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/explicit'",
",",
"5",
",",
"'Single-argument constructors should be marked explicit.'",
")"
] | https://github.com/s5z/zsim/blob/fb4d6e0475a25cffd23f0687ede2d43d96b4a99f/misc/cpplint.py#L1748-L1852 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_menu.py | python | IterateMenuItems | (menu) | Recursively walk and yield menu items as the are found. Only menu
items are yielded, not submenus or separators.
@param menu: menu to iterate | Recursively walk and yield menu items as the are found. Only menu
items are yielded, not submenus or separators.
@param menu: menu to iterate | [
"Recursively",
"walk",
"and",
"yield",
"menu",
"items",
"as",
"the",
"are",
"found",
".",
"Only",
"menu",
"items",
"are",
"yielded",
"not",
"submenus",
"or",
"separators",
".",
"@param",
"menu",
":",
"menu",
"to",
"iterate"
] | def IterateMenuItems(menu):
"""Recursively walk and yield menu items as the are found. Only menu
items are yielded, not submenus or separators.
@param menu: menu to iterate
"""
for item in menu.GetMenuItems():
if item.IsSubMenu():
for subitem in IterateMenuItems(item.GetSubMenu()):
yield subitem
if not item.IsSeparator():
yield item
else:
continue | [
"def",
"IterateMenuItems",
"(",
"menu",
")",
":",
"for",
"item",
"in",
"menu",
".",
"GetMenuItems",
"(",
")",
":",
"if",
"item",
".",
"IsSubMenu",
"(",
")",
":",
"for",
"subitem",
"in",
"IterateMenuItems",
"(",
"item",
".",
"GetSubMenu",
"(",
")",
")",
":",
"yield",
"subitem",
"if",
"not",
"item",
".",
"IsSeparator",
"(",
")",
":",
"yield",
"item",
"else",
":",
"continue"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_menu.py#L1162-L1175 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/dirichlet.py | python | Dirichlet.prob | (self, x, name="prob") | return super(Dirichlet, self).prob(x, name=name) | `P[x]`, computed for every batch member.
Args:
x: Non-negative tensor with dtype `dtype` and whose shape can
be broadcast with `self.alpha`. For fixed leading dimensions, the last
dimension represents x for the corresponding Dirichlet distribution in
`self.alpha` and `self.beta`. `x` is only legal if it sums up to one.
name: Name to give this Op, defaults to "prob".
Returns:
Probabilities for each record, shape `[N1,...,Nm]`. | `P[x]`, computed for every batch member. | [
"P",
"[",
"x",
"]",
"computed",
"for",
"every",
"batch",
"member",
"."
] | def prob(self, x, name="prob"):
"""`P[x]`, computed for every batch member.
Args:
x: Non-negative tensor with dtype `dtype` and whose shape can
be broadcast with `self.alpha`. For fixed leading dimensions, the last
dimension represents x for the corresponding Dirichlet distribution in
`self.alpha` and `self.beta`. `x` is only legal if it sums up to one.
name: Name to give this Op, defaults to "prob".
Returns:
Probabilities for each record, shape `[N1,...,Nm]`.
"""
return super(Dirichlet, self).prob(x, name=name) | [
"def",
"prob",
"(",
"self",
",",
"x",
",",
"name",
"=",
"\"prob\"",
")",
":",
"return",
"super",
"(",
"Dirichlet",
",",
"self",
")",
".",
"prob",
"(",
"x",
",",
"name",
"=",
"name",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/dirichlet.py#L342-L355 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py | python | Metrowerks_Shell_Suite_Events.Save_Error_Window_As | (self, _object, _attributes={}, **_arguments) | Save Error Window As: Saves the Errors & Warnings window as a text file
Required argument: Destination file for Save Message Window As
Keyword argument _attributes: AppleEvent attribute dictionary | Save Error Window As: Saves the Errors & Warnings window as a text file
Required argument: Destination file for Save Message Window As
Keyword argument _attributes: AppleEvent attribute dictionary | [
"Save",
"Error",
"Window",
"As",
":",
"Saves",
"the",
"Errors",
"&",
"Warnings",
"window",
"as",
"a",
"text",
"file",
"Required",
"argument",
":",
"Destination",
"file",
"for",
"Save",
"Message",
"Window",
"As",
"Keyword",
"argument",
"_attributes",
":",
"AppleEvent",
"attribute",
"dictionary"
] | def Save_Error_Window_As(self, _object, _attributes={}, **_arguments):
"""Save Error Window As: Saves the Errors & Warnings window as a text file
Required argument: Destination file for Save Message Window As
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'MMPR'
_subcode = 'SvMs'
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",
"Save_Error_Window_As",
"(",
"self",
",",
"_object",
",",
"_attributes",
"=",
"{",
"}",
",",
"*",
"*",
"_arguments",
")",
":",
"_code",
"=",
"'MMPR'",
"_subcode",
"=",
"'SvMs'",
"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-v7a/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py#L584-L602 | ||
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | clang-tools-extra/clangd/quality/CompletionModelCodegen.py | python | if_greater_node | (n, label, next_label) | return "%s: if (E.get%s() >= %s /*%s*/) goto %s;" % (
label, n['feature'], order_encode(threshold), threshold, next_label) | Returns code snippet for a if_greater node.
Jumps to true_label if the Example feature (NUMBER) is greater than the threshold.
Comparing integers is much faster than comparing floats. Assuming floating points
are represented as IEEE 754, it order-encodes the floats to integers before comparing them.
Control falls through if condition is evaluated to false. | Returns code snippet for a if_greater node.
Jumps to true_label if the Example feature (NUMBER) is greater than the threshold.
Comparing integers is much faster than comparing floats. Assuming floating points
are represented as IEEE 754, it order-encodes the floats to integers before comparing them.
Control falls through if condition is evaluated to false. | [
"Returns",
"code",
"snippet",
"for",
"a",
"if_greater",
"node",
".",
"Jumps",
"to",
"true_label",
"if",
"the",
"Example",
"feature",
"(",
"NUMBER",
")",
"is",
"greater",
"than",
"the",
"threshold",
".",
"Comparing",
"integers",
"is",
"much",
"faster",
"than",
"comparing",
"floats",
".",
"Assuming",
"floating",
"points",
"are",
"represented",
"as",
"IEEE",
"754",
"it",
"order",
"-",
"encodes",
"the",
"floats",
"to",
"integers",
"before",
"comparing",
"them",
".",
"Control",
"falls",
"through",
"if",
"condition",
"is",
"evaluated",
"to",
"false",
"."
] | def if_greater_node(n, label, next_label):
"""Returns code snippet for a if_greater node.
Jumps to true_label if the Example feature (NUMBER) is greater than the threshold.
Comparing integers is much faster than comparing floats. Assuming floating points
are represented as IEEE 754, it order-encodes the floats to integers before comparing them.
Control falls through if condition is evaluated to false."""
threshold = n["threshold"]
return "%s: if (E.get%s() >= %s /*%s*/) goto %s;" % (
label, n['feature'], order_encode(threshold), threshold, next_label) | [
"def",
"if_greater_node",
"(",
"n",
",",
"label",
",",
"next_label",
")",
":",
"threshold",
"=",
"n",
"[",
"\"threshold\"",
"]",
"return",
"\"%s: if (E.get%s() >= %s /*%s*/) goto %s;\"",
"%",
"(",
"label",
",",
"n",
"[",
"'feature'",
"]",
",",
"order_encode",
"(",
"threshold",
")",
",",
"threshold",
",",
"next_label",
")"
] | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/clang-tools-extra/clangd/quality/CompletionModelCodegen.py#L46-L54 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/common-code/Utils/cgf_utils/role_utils.py | python | get_access_control_role_name | (stack_arn, logical_role_name) | return role_name | Generates a role name based on a stack name and a logical role name.
Args:
stack_arn - The arn of the stack.
logical_role_name: Appended to the stack name to construct the actual role name. | Generates a role name based on a stack name and a logical role name. | [
"Generates",
"a",
"role",
"name",
"based",
"on",
"a",
"stack",
"name",
"and",
"a",
"logical",
"role",
"name",
"."
] | def get_access_control_role_name(stack_arn, logical_role_name):
"""Generates a role name based on a stack name and a logical role name.
Args:
stack_arn - The arn of the stack.
logical_role_name: Appended to the stack name to construct the actual role name.
"""
# Expecting stack names like: {project-name}-{deployment-name}-{resource-group-name}-{random-stuff}.
# In practice role names are truncated to the max allowable length.
stack_name = aws_utils.get_stack_name_from_stack_arn(stack_arn)
role_name = sanitize_role_name(stack_name + '-' + logical_role_name)
return role_name | [
"def",
"get_access_control_role_name",
"(",
"stack_arn",
",",
"logical_role_name",
")",
":",
"# Expecting stack names like: {project-name}-{deployment-name}-{resource-group-name}-{random-stuff}.",
"# In practice role names are truncated to the max allowable length.",
"stack_name",
"=",
"aws_utils",
".",
"get_stack_name_from_stack_arn",
"(",
"stack_arn",
")",
"role_name",
"=",
"sanitize_role_name",
"(",
"stack_name",
"+",
"'-'",
"+",
"logical_role_name",
")",
"return",
"role_name"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/Utils/cgf_utils/role_utils.py#L200-L216 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/sorting.py | python | _nanargminmax | (values, mask, func) | return non_nan_idx[func(non_nans)] | See nanargminmax.__doc__. | See nanargminmax.__doc__. | [
"See",
"nanargminmax",
".",
"__doc__",
"."
] | def _nanargminmax(values, mask, func) -> int:
"""
See nanargminmax.__doc__.
"""
idx = np.arange(values.shape[0])
non_nans = values[~mask]
non_nan_idx = idx[~mask]
return non_nan_idx[func(non_nans)] | [
"def",
"_nanargminmax",
"(",
"values",
",",
"mask",
",",
"func",
")",
"->",
"int",
":",
"idx",
"=",
"np",
".",
"arange",
"(",
"values",
".",
"shape",
"[",
"0",
"]",
")",
"non_nans",
"=",
"values",
"[",
"~",
"mask",
"]",
"non_nan_idx",
"=",
"idx",
"[",
"~",
"mask",
"]",
"return",
"non_nan_idx",
"[",
"func",
"(",
"non_nans",
")",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/sorting.py#L450-L458 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py | python | register_finder | (importer_type, distribution_finder) | Register `distribution_finder` to find distributions in sys.path items
`importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
handler), and `distribution_finder` is a callable that, passed a path
item and the importer instance, yields ``Distribution`` instances found on
that path item. See ``pkg_resources.find_on_path`` for an example. | Register `distribution_finder` to find distributions in sys.path items | [
"Register",
"distribution_finder",
"to",
"find",
"distributions",
"in",
"sys",
".",
"path",
"items"
] | def register_finder(importer_type, distribution_finder):
"""Register `distribution_finder` to find distributions in sys.path items
`importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
handler), and `distribution_finder` is a callable that, passed a path
item and the importer instance, yields ``Distribution`` instances found on
that path item. See ``pkg_resources.find_on_path`` for an example."""
_distribution_finders[importer_type] = distribution_finder | [
"def",
"register_finder",
"(",
"importer_type",
",",
"distribution_finder",
")",
":",
"_distribution_finders",
"[",
"importer_type",
"]",
"=",
"distribution_finder"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py#L1957-L1964 | ||
geemaple/leetcode | 68bc5032e1ee52c22ef2f2e608053484c487af54 | leetcode/98.validate-binary-search-tree.py | python | Solution2.isValidBST | (self, root) | return self.helper(root) | :type root: TreeNode
:rtype: bool | :type root: TreeNode
:rtype: bool | [
":",
"type",
"root",
":",
"TreeNode",
":",
"rtype",
":",
"bool"
] | def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.helper(root) | [
"def",
"isValidBST",
"(",
"self",
",",
"root",
")",
":",
"return",
"self",
".",
"helper",
"(",
"root",
")"
] | https://github.com/geemaple/leetcode/blob/68bc5032e1ee52c22ef2f2e608053484c487af54/leetcode/98.validate-binary-search-tree.py#L85-L90 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | SimGeneral/Configuration/python/LumiToRun.py | python | lumi_to_run | (runs, events_in_sample, events_per_job) | return tuple(pairs) | Print tuple for use in firstLuminosityBlockForEachRun | Print tuple for use in firstLuminosityBlockForEachRun | [
"Print",
"tuple",
"for",
"use",
"in",
"firstLuminosityBlockForEachRun"
] | def lumi_to_run(runs, events_in_sample, events_per_job):
'''Print tuple for use in firstLuminosityBlockForEachRun'''
n_iovs = len(runs)
n_lumis = events_in_sample // events_per_job
if n_lumis % n_iovs != 0:
raise Exception('n_lumis should be evenly divisible by n_iovs.')
pairs = []
for i, run in enumerate(runs):
pairs.append((run, 1 + i*n_lumis//n_iovs))
return tuple(pairs) | [
"def",
"lumi_to_run",
"(",
"runs",
",",
"events_in_sample",
",",
"events_per_job",
")",
":",
"n_iovs",
"=",
"len",
"(",
"runs",
")",
"n_lumis",
"=",
"events_in_sample",
"//",
"events_per_job",
"if",
"n_lumis",
"%",
"n_iovs",
"!=",
"0",
":",
"raise",
"Exception",
"(",
"'n_lumis should be evenly divisible by n_iovs.'",
")",
"pairs",
"=",
"[",
"]",
"for",
"i",
",",
"run",
"in",
"enumerate",
"(",
"runs",
")",
":",
"pairs",
".",
"append",
"(",
"(",
"run",
",",
"1",
"+",
"i",
"*",
"n_lumis",
"//",
"n_iovs",
")",
")",
"return",
"tuple",
"(",
"pairs",
")"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/SimGeneral/Configuration/python/LumiToRun.py#L1-L10 | |
freeorion/freeorion | c266a40eccd3a99a17de8fe57c36ef6ba3771665 | default/python/AI/ShipDesignAI.py | python | ShipDesignCache.print_best_designs | (self, print_diff_only: bool = True) | Print the best designs that were previously found.
:param print_diff_only: Print only changes to cache since last print | Print the best designs that were previously found. | [
"Print",
"the",
"best",
"designs",
"that",
"were",
"previously",
"found",
"."
] | def print_best_designs(self, print_diff_only: bool = True):
"""Print the best designs that were previously found.
:param print_diff_only: Print only changes to cache since last print
"""
debug("Currently cached best designs:")
if print_diff_only:
print_dict = {}
recursive_dict_diff(self.best_designs, self.last_printed, print_dict, diff_level_threshold=1)
else:
print_dict = self.best_designs
for classname in print_dict:
debug(classname)
cache_name = print_dict[classname]
for consider_fleet in cache_name:
debug(4 * " " + str(consider_fleet))
cache_upkeep = cache_name[consider_fleet]
for req_tuple in cache_upkeep:
debug(8 * " " + str(req_tuple))
cache_reqs = cache_upkeep[req_tuple]
for tech_tuple in cache_reqs:
debug(12 * " " + str(tech_tuple) + " # relevant tech upgrades")
cache_techs = cache_reqs[tech_tuple]
for species_tuple in cache_techs:
debug(16 * " " + str(species_tuple) + " # relevant species stats")
cache_species = cache_techs[species_tuple]
for av_parts in cache_species:
debug(20 * " " + str(av_parts))
cache_parts = cache_species[av_parts]
for hullname in sorted(cache_parts, reverse=True, key=lambda x: cache_parts[x][0]):
debug(24 * " " + hullname + ":" + str(cache_parts[hullname]))
self.last_printed = copy.deepcopy(self.best_designs) | [
"def",
"print_best_designs",
"(",
"self",
",",
"print_diff_only",
":",
"bool",
"=",
"True",
")",
":",
"debug",
"(",
"\"Currently cached best designs:\"",
")",
"if",
"print_diff_only",
":",
"print_dict",
"=",
"{",
"}",
"recursive_dict_diff",
"(",
"self",
".",
"best_designs",
",",
"self",
".",
"last_printed",
",",
"print_dict",
",",
"diff_level_threshold",
"=",
"1",
")",
"else",
":",
"print_dict",
"=",
"self",
".",
"best_designs",
"for",
"classname",
"in",
"print_dict",
":",
"debug",
"(",
"classname",
")",
"cache_name",
"=",
"print_dict",
"[",
"classname",
"]",
"for",
"consider_fleet",
"in",
"cache_name",
":",
"debug",
"(",
"4",
"*",
"\" \"",
"+",
"str",
"(",
"consider_fleet",
")",
")",
"cache_upkeep",
"=",
"cache_name",
"[",
"consider_fleet",
"]",
"for",
"req_tuple",
"in",
"cache_upkeep",
":",
"debug",
"(",
"8",
"*",
"\" \"",
"+",
"str",
"(",
"req_tuple",
")",
")",
"cache_reqs",
"=",
"cache_upkeep",
"[",
"req_tuple",
"]",
"for",
"tech_tuple",
"in",
"cache_reqs",
":",
"debug",
"(",
"12",
"*",
"\" \"",
"+",
"str",
"(",
"tech_tuple",
")",
"+",
"\" # relevant tech upgrades\"",
")",
"cache_techs",
"=",
"cache_reqs",
"[",
"tech_tuple",
"]",
"for",
"species_tuple",
"in",
"cache_techs",
":",
"debug",
"(",
"16",
"*",
"\" \"",
"+",
"str",
"(",
"species_tuple",
")",
"+",
"\" # relevant species stats\"",
")",
"cache_species",
"=",
"cache_techs",
"[",
"species_tuple",
"]",
"for",
"av_parts",
"in",
"cache_species",
":",
"debug",
"(",
"20",
"*",
"\" \"",
"+",
"str",
"(",
"av_parts",
")",
")",
"cache_parts",
"=",
"cache_species",
"[",
"av_parts",
"]",
"for",
"hullname",
"in",
"sorted",
"(",
"cache_parts",
",",
"reverse",
"=",
"True",
",",
"key",
"=",
"lambda",
"x",
":",
"cache_parts",
"[",
"x",
"]",
"[",
"0",
"]",
")",
":",
"debug",
"(",
"24",
"*",
"\" \"",
"+",
"hullname",
"+",
"\":\"",
"+",
"str",
"(",
"cache_parts",
"[",
"hullname",
"]",
")",
")",
"self",
".",
"last_printed",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"best_designs",
")"
] | https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/AI/ShipDesignAI.py#L211-L242 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py | python | Misc.winfo_ismapped | (self) | return self.tk.getint(
self.tk.call('winfo', 'ismapped', self._w)) | Return true if this widget is mapped. | Return true if this widget is mapped. | [
"Return",
"true",
"if",
"this",
"widget",
"is",
"mapped",
"."
] | def winfo_ismapped(self):
"""Return true if this widget is mapped."""
return self.tk.getint(
self.tk.call('winfo', 'ismapped', self._w)) | [
"def",
"winfo_ismapped",
"(",
"self",
")",
":",
"return",
"self",
".",
"tk",
".",
"getint",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"'winfo'",
",",
"'ismapped'",
",",
"self",
".",
"_w",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py#L1008-L1011 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/formats/style.py | python | Styler.render | (self, **kwargs) | return self.template.render(**d) | Render the built up styles to HTML.
Parameters
----------
**kwargs
Any additional keyword arguments are passed
through to ``self.template.render``.
This is useful when you need to provide
additional variables for a custom template.
Returns
-------
rendered : str
The rendered HTML.
Notes
-----
``Styler`` objects have defined the ``_repr_html_`` method
which automatically calls ``self.render()`` when it's the
last item in a Notebook cell. When calling ``Styler.render()``
directly, wrap the result in ``IPython.display.HTML`` to view
the rendered HTML in the notebook.
Pandas uses the following keys in render. Arguments passed
in ``**kwargs`` take precedence, so think carefully if you want
to override them:
* head
* cellstyle
* body
* uuid
* precision
* table_styles
* caption
* table_attributes | Render the built up styles to HTML. | [
"Render",
"the",
"built",
"up",
"styles",
"to",
"HTML",
"."
] | def render(self, **kwargs):
"""
Render the built up styles to HTML.
Parameters
----------
**kwargs
Any additional keyword arguments are passed
through to ``self.template.render``.
This is useful when you need to provide
additional variables for a custom template.
Returns
-------
rendered : str
The rendered HTML.
Notes
-----
``Styler`` objects have defined the ``_repr_html_`` method
which automatically calls ``self.render()`` when it's the
last item in a Notebook cell. When calling ``Styler.render()``
directly, wrap the result in ``IPython.display.HTML`` to view
the rendered HTML in the notebook.
Pandas uses the following keys in render. Arguments passed
in ``**kwargs`` take precedence, so think carefully if you want
to override them:
* head
* cellstyle
* body
* uuid
* precision
* table_styles
* caption
* table_attributes
"""
self._compute()
# TODO: namespace all the pandas keys
d = self._translate()
# filter out empty styles, every cell will have a class
# but the list of props may just be [['', '']].
# so we have the neested anys below
trimmed = [x for x in d["cellstyle"] if any(any(y) for y in x["props"])]
d["cellstyle"] = trimmed
d.update(kwargs)
return self.template.render(**d) | [
"def",
"render",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_compute",
"(",
")",
"# TODO: namespace all the pandas keys",
"d",
"=",
"self",
".",
"_translate",
"(",
")",
"# filter out empty styles, every cell will have a class",
"# but the list of props may just be [['', '']].",
"# so we have the neested anys below",
"trimmed",
"=",
"[",
"x",
"for",
"x",
"in",
"d",
"[",
"\"cellstyle\"",
"]",
"if",
"any",
"(",
"any",
"(",
"y",
")",
"for",
"y",
"in",
"x",
"[",
"\"props\"",
"]",
")",
"]",
"d",
"[",
"\"cellstyle\"",
"]",
"=",
"trimmed",
"d",
".",
"update",
"(",
"kwargs",
")",
"return",
"self",
".",
"template",
".",
"render",
"(",
"*",
"*",
"d",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/formats/style.py#L499-L546 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/distributed/distributed_c10d.py | python | destroy_process_group | (group=None) | Destroy a given process group, and deinitialize the distributed package
Args:
group (ProcessGroup, optional): The process group to be destroyed, if
group.WORLD is given, all process
groups including the default one will
be destroyed. | Destroy a given process group, and deinitialize the distributed package | [
"Destroy",
"a",
"given",
"process",
"group",
"and",
"deinitialize",
"the",
"distributed",
"package"
] | def destroy_process_group(group=None):
"""
Destroy a given process group, and deinitialize the distributed package
Args:
group (ProcessGroup, optional): The process group to be destroyed, if
group.WORLD is given, all process
groups including the default one will
be destroyed.
"""
global _pg_map
global _pg_names
global _pg_group_ranks
global _default_pg_init_method
global _group_count
if group == GroupMember.NON_GROUP_MEMBER:
return
if group is None:
pg = GroupMember.WORLD
else:
pg = group
assert pg is not None
if _pg_map.get(pg, None) is None:
raise RuntimeError("Invalid process group specified")
if group is None or group == GroupMember.WORLD:
_update_default_pg(None)
_default_pg_init_method = None
_pg_map.clear()
_pg_names.clear()
_pg_group_ranks.clear()
# when process group doesn't have an explicit name (only WORLD (default)
# process group can have an explicit name), we use global _group_counter
# to generate the name. We need to reset the counter on destruction to
# allow consistent value to be generated when we re-create process
# groups after some trainers recover from failure
#
# We only reset this when WORLD is being destroyed because if this
# process group is in good state, we aren't dealing with failures.
_group_count = 0
else:
del _pg_map[pg]
del _pg_names[pg]
del _pg_group_ranks[pg] | [
"def",
"destroy_process_group",
"(",
"group",
"=",
"None",
")",
":",
"global",
"_pg_map",
"global",
"_pg_names",
"global",
"_pg_group_ranks",
"global",
"_default_pg_init_method",
"global",
"_group_count",
"if",
"group",
"==",
"GroupMember",
".",
"NON_GROUP_MEMBER",
":",
"return",
"if",
"group",
"is",
"None",
":",
"pg",
"=",
"GroupMember",
".",
"WORLD",
"else",
":",
"pg",
"=",
"group",
"assert",
"pg",
"is",
"not",
"None",
"if",
"_pg_map",
".",
"get",
"(",
"pg",
",",
"None",
")",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Invalid process group specified\"",
")",
"if",
"group",
"is",
"None",
"or",
"group",
"==",
"GroupMember",
".",
"WORLD",
":",
"_update_default_pg",
"(",
"None",
")",
"_default_pg_init_method",
"=",
"None",
"_pg_map",
".",
"clear",
"(",
")",
"_pg_names",
".",
"clear",
"(",
")",
"_pg_group_ranks",
".",
"clear",
"(",
")",
"# when process group doesn't have an explicit name (only WORLD (default)",
"# process group can have an explicit name), we use global _group_counter",
"# to generate the name. We need to reset the counter on destruction to",
"# allow consistent value to be generated when we re-create process",
"# groups after some trainers recover from failure",
"#",
"# We only reset this when WORLD is being destroyed because if this",
"# process group is in good state, we aren't dealing with failures.",
"_group_count",
"=",
"0",
"else",
":",
"del",
"_pg_map",
"[",
"pg",
"]",
"del",
"_pg_names",
"[",
"pg",
"]",
"del",
"_pg_group_ranks",
"[",
"pg",
"]"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/distributed_c10d.py#L773-L820 | ||
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Tool/msvs.py | python | _GenerateV7DSW.PrintSolution | (self) | Writes a solution file | Writes a solution file | [
"Writes",
"a",
"solution",
"file"
] | def PrintSolution(self):
"""Writes a solution file"""
self.file.write('Microsoft Visual Studio Solution File, Format Version %s\n' % self.versionstr)
if self.version_num >= 14.2:
# Visual Studio 2019 is considered to be version 16.
self.file.write('# Visual Studio 16\n')
elif self.version_num > 14.0:
# Visual Studio 2015 and 2017 are both considered to be version 15.
self.file.write('# Visual Studio 15\n')
elif self.version_num >= 12.0:
self.file.write('# Visual Studio 14\n')
elif self.version_num >= 11.0:
self.file.write('# Visual Studio 11\n')
elif self.version_num >= 10.0:
self.file.write('# Visual Studio 2010\n')
elif self.version_num >= 9.0:
self.file.write('# Visual Studio 2008\n')
elif self.version_num >= 8.0:
self.file.write('# Visual Studio 2005\n')
for dspinfo in self.dspfiles_info:
name = dspinfo['NAME']
base, suffix = SCons.Util.splitext(name)
if suffix == '.vcproj':
name = base
self.file.write('Project("%s") = "%s", "%s", "%s"\n'
% (external_makefile_guid, name, dspinfo['SLN_RELATIVE_FILE_PATH'], dspinfo['GUID']))
if 7.1 <= self.version_num < 8.0:
self.file.write('\tProjectSection(ProjectDependencies) = postProject\n'
'\tEndProjectSection\n')
self.file.write('EndProject\n')
self.file.write('Global\n')
env = self.env
if 'MSVS_SCC_PROVIDER' in env:
scc_number_of_projects = len(self.dspfiles) + 1
slnguid = self.slnguid
scc_provider = env.get('MSVS_SCC_PROVIDER', '').replace(' ', r'\u0020')
scc_project_name = env.get('MSVS_SCC_PROJECT_NAME', '').replace(' ', r'\u0020')
scc_connection_root = env.get('MSVS_SCC_CONNECTION_ROOT', os.curdir)
scc_local_path = os.path.relpath(scc_connection_root, self.dsw_folder_path).replace('\\', '\\\\')
self.file.write('\tGlobalSection(SourceCodeControl) = preSolution\n'
'\t\tSccNumberOfProjects = %(scc_number_of_projects)d\n'
'\t\tSccProjectName0 = %(scc_project_name)s\n'
'\t\tSccLocalPath0 = %(scc_local_path)s\n'
'\t\tSccProvider0 = %(scc_provider)s\n'
'\t\tCanCheckoutShared = true\n' % locals())
sln_relative_path_from_scc = os.path.relpath(self.dsw_folder_path, scc_connection_root)
if sln_relative_path_from_scc != os.curdir:
self.file.write('\t\tSccProjectFilePathRelativizedFromConnection0 = %s\\\\\n'
% sln_relative_path_from_scc.replace('\\', '\\\\'))
if self.version_num < 8.0:
# When present, SolutionUniqueID is automatically removed by VS 2005
# TODO: check for Visual Studio versions newer than 2005
self.file.write('\t\tSolutionUniqueID = %s\n' % slnguid)
for dspinfo in self.dspfiles_info:
i = self.dspfiles_info.index(dspinfo) + 1
dsp_relative_file_path = dspinfo['SLN_RELATIVE_FILE_PATH'].replace('\\', '\\\\')
dsp_scc_relative_folder_path = os.path.relpath(dspinfo['FOLDER_PATH'], scc_connection_root).replace('\\', '\\\\')
self.file.write('\t\tSccProjectUniqueName%(i)s = %(dsp_relative_file_path)s\n'
'\t\tSccLocalPath%(i)d = %(scc_local_path)s\n'
'\t\tCanCheckoutShared = true\n'
'\t\tSccProjectFilePathRelativizedFromConnection%(i)s = %(dsp_scc_relative_folder_path)s\\\\\n'
% locals())
self.file.write('\tEndGlobalSection\n')
if self.version_num >= 8.0:
self.file.write('\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\n')
else:
self.file.write('\tGlobalSection(SolutionConfiguration) = preSolution\n')
confkeys = sorted(self.configs.keys())
cnt = 0
for name in confkeys:
variant = self.configs[name].variant
platform = self.configs[name].platform
if self.version_num >= 8.0:
self.file.write('\t\t%s|%s = %s|%s\n' % (variant, platform, variant, platform))
else:
self.file.write('\t\tConfigName.%d = %s\n' % (cnt, variant))
cnt = cnt + 1
self.file.write('\tEndGlobalSection\n')
if self.version_num <= 7.1:
self.file.write('\tGlobalSection(ProjectDependencies) = postSolution\n'
'\tEndGlobalSection\n')
if self.version_num >= 8.0:
self.file.write('\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\n')
else:
self.file.write('\tGlobalSection(ProjectConfiguration) = postSolution\n')
for name in confkeys:
variant = self.configs[name].variant
platform = self.configs[name].platform
if self.version_num >= 8.0:
for dspinfo in self.dspfiles_info:
guid = dspinfo['GUID']
self.file.write('\t\t%s.%s|%s.ActiveCfg = %s|%s\n'
'\t\t%s.%s|%s.Build.0 = %s|%s\n' % (guid,variant,platform,variant,platform,guid,variant,platform,variant,platform))
else:
for dspinfo in self.dspfiles_info:
guid = dspinfo['GUID']
self.file.write('\t\t%s.%s.ActiveCfg = %s|%s\n'
'\t\t%s.%s.Build.0 = %s|%s\n' %(guid,variant,variant,platform,guid,variant,variant,platform))
self.file.write('\tEndGlobalSection\n')
if self.version_num >= 8.0:
self.file.write('\tGlobalSection(SolutionProperties) = preSolution\n'
'\t\tHideSolutionNode = FALSE\n'
'\tEndGlobalSection\n')
else:
self.file.write('\tGlobalSection(ExtensibilityGlobals) = postSolution\n'
'\tEndGlobalSection\n'
'\tGlobalSection(ExtensibilityAddIns) = postSolution\n'
'\tEndGlobalSection\n')
self.file.write('EndGlobal\n')
if self.nokeep == 0:
pdata = pickle.dumps(self.configs,PICKLE_PROTOCOL)
pdata = base64.b64encode(pdata).decode()
self.file.write(pdata)
self.file.write('\n') | [
"def",
"PrintSolution",
"(",
"self",
")",
":",
"self",
".",
"file",
".",
"write",
"(",
"'Microsoft Visual Studio Solution File, Format Version %s\\n'",
"%",
"self",
".",
"versionstr",
")",
"if",
"self",
".",
"version_num",
">=",
"14.2",
":",
"# Visual Studio 2019 is considered to be version 16.",
"self",
".",
"file",
".",
"write",
"(",
"'# Visual Studio 16\\n'",
")",
"elif",
"self",
".",
"version_num",
">",
"14.0",
":",
"# Visual Studio 2015 and 2017 are both considered to be version 15.",
"self",
".",
"file",
".",
"write",
"(",
"'# Visual Studio 15\\n'",
")",
"elif",
"self",
".",
"version_num",
">=",
"12.0",
":",
"self",
".",
"file",
".",
"write",
"(",
"'# Visual Studio 14\\n'",
")",
"elif",
"self",
".",
"version_num",
">=",
"11.0",
":",
"self",
".",
"file",
".",
"write",
"(",
"'# Visual Studio 11\\n'",
")",
"elif",
"self",
".",
"version_num",
">=",
"10.0",
":",
"self",
".",
"file",
".",
"write",
"(",
"'# Visual Studio 2010\\n'",
")",
"elif",
"self",
".",
"version_num",
">=",
"9.0",
":",
"self",
".",
"file",
".",
"write",
"(",
"'# Visual Studio 2008\\n'",
")",
"elif",
"self",
".",
"version_num",
">=",
"8.0",
":",
"self",
".",
"file",
".",
"write",
"(",
"'# Visual Studio 2005\\n'",
")",
"for",
"dspinfo",
"in",
"self",
".",
"dspfiles_info",
":",
"name",
"=",
"dspinfo",
"[",
"'NAME'",
"]",
"base",
",",
"suffix",
"=",
"SCons",
".",
"Util",
".",
"splitext",
"(",
"name",
")",
"if",
"suffix",
"==",
"'.vcproj'",
":",
"name",
"=",
"base",
"self",
".",
"file",
".",
"write",
"(",
"'Project(\"%s\") = \"%s\", \"%s\", \"%s\"\\n'",
"%",
"(",
"external_makefile_guid",
",",
"name",
",",
"dspinfo",
"[",
"'SLN_RELATIVE_FILE_PATH'",
"]",
",",
"dspinfo",
"[",
"'GUID'",
"]",
")",
")",
"if",
"7.1",
"<=",
"self",
".",
"version_num",
"<",
"8.0",
":",
"self",
".",
"file",
".",
"write",
"(",
"'\\tProjectSection(ProjectDependencies) = postProject\\n'",
"'\\tEndProjectSection\\n'",
")",
"self",
".",
"file",
".",
"write",
"(",
"'EndProject\\n'",
")",
"self",
".",
"file",
".",
"write",
"(",
"'Global\\n'",
")",
"env",
"=",
"self",
".",
"env",
"if",
"'MSVS_SCC_PROVIDER'",
"in",
"env",
":",
"scc_number_of_projects",
"=",
"len",
"(",
"self",
".",
"dspfiles",
")",
"+",
"1",
"slnguid",
"=",
"self",
".",
"slnguid",
"scc_provider",
"=",
"env",
".",
"get",
"(",
"'MSVS_SCC_PROVIDER'",
",",
"''",
")",
".",
"replace",
"(",
"' '",
",",
"r'\\u0020'",
")",
"scc_project_name",
"=",
"env",
".",
"get",
"(",
"'MSVS_SCC_PROJECT_NAME'",
",",
"''",
")",
".",
"replace",
"(",
"' '",
",",
"r'\\u0020'",
")",
"scc_connection_root",
"=",
"env",
".",
"get",
"(",
"'MSVS_SCC_CONNECTION_ROOT'",
",",
"os",
".",
"curdir",
")",
"scc_local_path",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"scc_connection_root",
",",
"self",
".",
"dsw_folder_path",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'\\\\\\\\'",
")",
"self",
".",
"file",
".",
"write",
"(",
"'\\tGlobalSection(SourceCodeControl) = preSolution\\n'",
"'\\t\\tSccNumberOfProjects = %(scc_number_of_projects)d\\n'",
"'\\t\\tSccProjectName0 = %(scc_project_name)s\\n'",
"'\\t\\tSccLocalPath0 = %(scc_local_path)s\\n'",
"'\\t\\tSccProvider0 = %(scc_provider)s\\n'",
"'\\t\\tCanCheckoutShared = true\\n'",
"%",
"locals",
"(",
")",
")",
"sln_relative_path_from_scc",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"self",
".",
"dsw_folder_path",
",",
"scc_connection_root",
")",
"if",
"sln_relative_path_from_scc",
"!=",
"os",
".",
"curdir",
":",
"self",
".",
"file",
".",
"write",
"(",
"'\\t\\tSccProjectFilePathRelativizedFromConnection0 = %s\\\\\\\\\\n'",
"%",
"sln_relative_path_from_scc",
".",
"replace",
"(",
"'\\\\'",
",",
"'\\\\\\\\'",
")",
")",
"if",
"self",
".",
"version_num",
"<",
"8.0",
":",
"# When present, SolutionUniqueID is automatically removed by VS 2005",
"# TODO: check for Visual Studio versions newer than 2005",
"self",
".",
"file",
".",
"write",
"(",
"'\\t\\tSolutionUniqueID = %s\\n'",
"%",
"slnguid",
")",
"for",
"dspinfo",
"in",
"self",
".",
"dspfiles_info",
":",
"i",
"=",
"self",
".",
"dspfiles_info",
".",
"index",
"(",
"dspinfo",
")",
"+",
"1",
"dsp_relative_file_path",
"=",
"dspinfo",
"[",
"'SLN_RELATIVE_FILE_PATH'",
"]",
".",
"replace",
"(",
"'\\\\'",
",",
"'\\\\\\\\'",
")",
"dsp_scc_relative_folder_path",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"dspinfo",
"[",
"'FOLDER_PATH'",
"]",
",",
"scc_connection_root",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'\\\\\\\\'",
")",
"self",
".",
"file",
".",
"write",
"(",
"'\\t\\tSccProjectUniqueName%(i)s = %(dsp_relative_file_path)s\\n'",
"'\\t\\tSccLocalPath%(i)d = %(scc_local_path)s\\n'",
"'\\t\\tCanCheckoutShared = true\\n'",
"'\\t\\tSccProjectFilePathRelativizedFromConnection%(i)s = %(dsp_scc_relative_folder_path)s\\\\\\\\\\n'",
"%",
"locals",
"(",
")",
")",
"self",
".",
"file",
".",
"write",
"(",
"'\\tEndGlobalSection\\n'",
")",
"if",
"self",
".",
"version_num",
">=",
"8.0",
":",
"self",
".",
"file",
".",
"write",
"(",
"'\\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\\n'",
")",
"else",
":",
"self",
".",
"file",
".",
"write",
"(",
"'\\tGlobalSection(SolutionConfiguration) = preSolution\\n'",
")",
"confkeys",
"=",
"sorted",
"(",
"self",
".",
"configs",
".",
"keys",
"(",
")",
")",
"cnt",
"=",
"0",
"for",
"name",
"in",
"confkeys",
":",
"variant",
"=",
"self",
".",
"configs",
"[",
"name",
"]",
".",
"variant",
"platform",
"=",
"self",
".",
"configs",
"[",
"name",
"]",
".",
"platform",
"if",
"self",
".",
"version_num",
">=",
"8.0",
":",
"self",
".",
"file",
".",
"write",
"(",
"'\\t\\t%s|%s = %s|%s\\n'",
"%",
"(",
"variant",
",",
"platform",
",",
"variant",
",",
"platform",
")",
")",
"else",
":",
"self",
".",
"file",
".",
"write",
"(",
"'\\t\\tConfigName.%d = %s\\n'",
"%",
"(",
"cnt",
",",
"variant",
")",
")",
"cnt",
"=",
"cnt",
"+",
"1",
"self",
".",
"file",
".",
"write",
"(",
"'\\tEndGlobalSection\\n'",
")",
"if",
"self",
".",
"version_num",
"<=",
"7.1",
":",
"self",
".",
"file",
".",
"write",
"(",
"'\\tGlobalSection(ProjectDependencies) = postSolution\\n'",
"'\\tEndGlobalSection\\n'",
")",
"if",
"self",
".",
"version_num",
">=",
"8.0",
":",
"self",
".",
"file",
".",
"write",
"(",
"'\\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\\n'",
")",
"else",
":",
"self",
".",
"file",
".",
"write",
"(",
"'\\tGlobalSection(ProjectConfiguration) = postSolution\\n'",
")",
"for",
"name",
"in",
"confkeys",
":",
"variant",
"=",
"self",
".",
"configs",
"[",
"name",
"]",
".",
"variant",
"platform",
"=",
"self",
".",
"configs",
"[",
"name",
"]",
".",
"platform",
"if",
"self",
".",
"version_num",
">=",
"8.0",
":",
"for",
"dspinfo",
"in",
"self",
".",
"dspfiles_info",
":",
"guid",
"=",
"dspinfo",
"[",
"'GUID'",
"]",
"self",
".",
"file",
".",
"write",
"(",
"'\\t\\t%s.%s|%s.ActiveCfg = %s|%s\\n'",
"'\\t\\t%s.%s|%s.Build.0 = %s|%s\\n'",
"%",
"(",
"guid",
",",
"variant",
",",
"platform",
",",
"variant",
",",
"platform",
",",
"guid",
",",
"variant",
",",
"platform",
",",
"variant",
",",
"platform",
")",
")",
"else",
":",
"for",
"dspinfo",
"in",
"self",
".",
"dspfiles_info",
":",
"guid",
"=",
"dspinfo",
"[",
"'GUID'",
"]",
"self",
".",
"file",
".",
"write",
"(",
"'\\t\\t%s.%s.ActiveCfg = %s|%s\\n'",
"'\\t\\t%s.%s.Build.0 = %s|%s\\n'",
"%",
"(",
"guid",
",",
"variant",
",",
"variant",
",",
"platform",
",",
"guid",
",",
"variant",
",",
"variant",
",",
"platform",
")",
")",
"self",
".",
"file",
".",
"write",
"(",
"'\\tEndGlobalSection\\n'",
")",
"if",
"self",
".",
"version_num",
">=",
"8.0",
":",
"self",
".",
"file",
".",
"write",
"(",
"'\\tGlobalSection(SolutionProperties) = preSolution\\n'",
"'\\t\\tHideSolutionNode = FALSE\\n'",
"'\\tEndGlobalSection\\n'",
")",
"else",
":",
"self",
".",
"file",
".",
"write",
"(",
"'\\tGlobalSection(ExtensibilityGlobals) = postSolution\\n'",
"'\\tEndGlobalSection\\n'",
"'\\tGlobalSection(ExtensibilityAddIns) = postSolution\\n'",
"'\\tEndGlobalSection\\n'",
")",
"self",
".",
"file",
".",
"write",
"(",
"'EndGlobal\\n'",
")",
"if",
"self",
".",
"nokeep",
"==",
"0",
":",
"pdata",
"=",
"pickle",
".",
"dumps",
"(",
"self",
".",
"configs",
",",
"PICKLE_PROTOCOL",
")",
"pdata",
"=",
"base64",
".",
"b64encode",
"(",
"pdata",
")",
".",
"decode",
"(",
")",
"self",
".",
"file",
".",
"write",
"(",
"pdata",
")",
"self",
".",
"file",
".",
"write",
"(",
"'\\n'",
")"
] | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Tool/msvs.py#L1605-L1725 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/cond_v2.py | python | _create_dummy_input | (func_graph, template_tensor) | Creates tensors in func_graph to represent template_tensors.
Args:
func_graph: FuncGraph.
template_tensor: a tensor in the outer graph.
Returns:
A tensor in func_graph. | Creates tensors in func_graph to represent template_tensors. | [
"Creates",
"tensors",
"in",
"func_graph",
"to",
"represent",
"template_tensors",
"."
] | def _create_dummy_input(func_graph, template_tensor):
"""Creates tensors in func_graph to represent template_tensors.
Args:
func_graph: FuncGraph.
template_tensor: a tensor in the outer graph.
Returns:
A tensor in func_graph.
"""
with func_graph.as_default():
return array_ops.placeholder(
template_tensor.dtype, shape=template_tensor.shape) | [
"def",
"_create_dummy_input",
"(",
"func_graph",
",",
"template_tensor",
")",
":",
"with",
"func_graph",
".",
"as_default",
"(",
")",
":",
"return",
"array_ops",
".",
"placeholder",
"(",
"template_tensor",
".",
"dtype",
",",
"shape",
"=",
"template_tensor",
".",
"shape",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/cond_v2.py#L662-L674 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/gslib/wildcard_iterator.py | python | FileWildcardIterator.IterAll | (self, bucket_listing_fields=None, expand_top_level_buckets=False) | Iterates over the wildcard, yielding BucketListingRefs.
Args:
bucket_listing_fields: Ignored; filesystems don't have buckets.
expand_top_level_buckets: Ignored; filesystems don't have buckets.
Yields:
BucketListingRefs of type OBJECT (file) or PREFIX (directory),
or empty iterator if no matches. | Iterates over the wildcard, yielding BucketListingRefs. | [
"Iterates",
"over",
"the",
"wildcard",
"yielding",
"BucketListingRefs",
"."
] | def IterAll(self, bucket_listing_fields=None, expand_top_level_buckets=False):
"""Iterates over the wildcard, yielding BucketListingRefs.
Args:
bucket_listing_fields: Ignored; filesystems don't have buckets.
expand_top_level_buckets: Ignored; filesystems don't have buckets.
Yields:
BucketListingRefs of type OBJECT (file) or PREFIX (directory),
or empty iterator if no matches.
"""
for bucket_listing_ref in self.__iter__():
yield bucket_listing_ref | [
"def",
"IterAll",
"(",
"self",
",",
"bucket_listing_fields",
"=",
"None",
",",
"expand_top_level_buckets",
"=",
"False",
")",
":",
"for",
"bucket_listing_ref",
"in",
"self",
".",
"__iter__",
"(",
")",
":",
"yield",
"bucket_listing_ref"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/wildcard_iterator.py#L592-L604 | ||
bristolcrypto/SPDZ-2 | 721abfae849625a02ea49aabc534f9cf41ca643f | Compiler/program.py | python | Program.schedule_wait | (self, tape) | Schedule the end of a thread. | Schedule the end of a thread. | [
"Schedule",
"the",
"end",
"of",
"a",
"thread",
"."
] | def schedule_wait(self, tape):
""" Schedule the end of a thread. """
if self.schedule[-1][0] == 'stop':
self.schedule[-1][1].append((tape, None))
else:
self.schedule.append(('stop', [(tape, None)]))
self.finalize_tape(tape)
self.update_req(tape) | [
"def",
"schedule_wait",
"(",
"self",
",",
"tape",
")",
":",
"if",
"self",
".",
"schedule",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"==",
"'stop'",
":",
"self",
".",
"schedule",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
".",
"append",
"(",
"(",
"tape",
",",
"None",
")",
")",
"else",
":",
"self",
".",
"schedule",
".",
"append",
"(",
"(",
"'stop'",
",",
"[",
"(",
"tape",
",",
"None",
")",
"]",
")",
")",
"self",
".",
"finalize_tape",
"(",
"tape",
")",
"self",
".",
"update_req",
"(",
"tape",
")"
] | https://github.com/bristolcrypto/SPDZ-2/blob/721abfae849625a02ea49aabc534f9cf41ca643f/Compiler/program.py#L273-L280 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/plot_widget/plotting_canvas/plotting_canvas_presenter.py | python | PlottingCanvasPresenter.plot_workspaces | (self, workspace_names: List[str], workspace_indices: List[int], hold_on: bool,
autoscale: bool) | Plots the input workspace names and indices in the figure window
If hold_on is True the existing workspaces plotted in the figure are kept | Plots the input workspace names and indices in the figure window
If hold_on is True the existing workspaces plotted in the figure are kept | [
"Plots",
"the",
"input",
"workspace",
"names",
"and",
"indices",
"in",
"the",
"figure",
"window",
"If",
"hold_on",
"is",
"True",
"the",
"existing",
"workspaces",
"plotted",
"in",
"the",
"figure",
"are",
"kept"
] | def plot_workspaces(self, workspace_names: List[str], workspace_indices: List[int], hold_on: bool,
autoscale: bool):
"""Plots the input workspace names and indices in the figure window
If hold_on is True the existing workspaces plotted in the figure are kept"""
# Create workspace information named tuple from input list
workspace_plot_info = self._model.create_workspace_plot_information(workspace_names, workspace_indices,
self._options_presenter.get_errors())
if not hold_on:
# Remove data which is currently plotted and not in the new workspace_plot_info
workspaces_info_to_remove = [plot_info for plot_info in self._view.plotted_workspace_information
if plot_info not in workspace_plot_info]
self._view.remove_workspace_info_from_plot(workspaces_info_to_remove)
# Add workspace info which is currently not plotted
workspace_info_to_add = [plot_info for plot_info in workspace_plot_info if plot_info
not in self._view.plotted_workspace_information]
self._view.add_workspaces_to_plot(workspace_info_to_add)
# check if to force autoscale
if self._options_presenter.autoscale:
autoscale = True
self._set_axes_limits_and_titles(autoscale) | [
"def",
"plot_workspaces",
"(",
"self",
",",
"workspace_names",
":",
"List",
"[",
"str",
"]",
",",
"workspace_indices",
":",
"List",
"[",
"int",
"]",
",",
"hold_on",
":",
"bool",
",",
"autoscale",
":",
"bool",
")",
":",
"# Create workspace information named tuple from input list",
"workspace_plot_info",
"=",
"self",
".",
"_model",
".",
"create_workspace_plot_information",
"(",
"workspace_names",
",",
"workspace_indices",
",",
"self",
".",
"_options_presenter",
".",
"get_errors",
"(",
")",
")",
"if",
"not",
"hold_on",
":",
"# Remove data which is currently plotted and not in the new workspace_plot_info",
"workspaces_info_to_remove",
"=",
"[",
"plot_info",
"for",
"plot_info",
"in",
"self",
".",
"_view",
".",
"plotted_workspace_information",
"if",
"plot_info",
"not",
"in",
"workspace_plot_info",
"]",
"self",
".",
"_view",
".",
"remove_workspace_info_from_plot",
"(",
"workspaces_info_to_remove",
")",
"# Add workspace info which is currently not plotted",
"workspace_info_to_add",
"=",
"[",
"plot_info",
"for",
"plot_info",
"in",
"workspace_plot_info",
"if",
"plot_info",
"not",
"in",
"self",
".",
"_view",
".",
"plotted_workspace_information",
"]",
"self",
".",
"_view",
".",
"add_workspaces_to_plot",
"(",
"workspace_info_to_add",
")",
"# check if to force autoscale",
"if",
"self",
".",
"_options_presenter",
".",
"autoscale",
":",
"autoscale",
"=",
"True",
"self",
".",
"_set_axes_limits_and_titles",
"(",
"autoscale",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/plot_widget/plotting_canvas/plotting_canvas_presenter.py#L116-L137 | ||
NVIDIA/DALI | bf16cc86ba8f091b145f91962f21fe1b6aff243d | docs/examples/use_cases/tensorflow/efficientdet/hparams_config.py | python | default_detection_configs | () | return h | Returns a default detection configs. | Returns a default detection configs. | [
"Returns",
"a",
"default",
"detection",
"configs",
"."
] | def default_detection_configs():
"""Returns a default detection configs."""
h = Config()
# model name.
h.name = "efficientdet-d1"
# activation type: see activation_fn in utils.py.
h.act_type = "swish"
# input preprocessing parameters
h.image_size = 640 # An integer or a string WxH such as 640x320.
h.target_size = None
h.input_rand_hflip = True
h.jitter_min = 0.1
h.jitter_max = 2.0
h.grid_mask = False
# dataset specific parameters
h.num_classes = 91 # 1+ actual classes, 0 is reserved for background.
h.skip_crowd_during_training = True
h.label_map = "coco" # a dict or a string of 'coco', 'voc', 'waymo'.
h.max_instances_per_image = 100 # Default to 100 for COCO.
# model architecture
h.min_level = 3
h.max_level = 7
h.num_scales = 3
# ratio w/h: 2.0 means w=1.4, h=0.7. Can be computed with k-mean per dataset.
h.aspect_ratios = [1.0, 2.0, 0.5] # [[0.7, 1.4], [1.0, 1.0], [1.4, 0.7]]
h.anchor_scale = 4.0
# optimization
h.momentum = 0.9
h.optimizer = "sgd" # can be 'adam' or 'sgd'.
h.learning_rate = 0.08 # 0.008 for adam.
h.lr_warmup_init = 0.008 # 0.0008 for adam.
h.lr_warmup_epoch = 1.0
h.first_lr_drop_epoch = 200.0
h.second_lr_drop_epoch = 250.0
h.poly_lr_power = 0.9
h.clip_gradients_norm = 10.0
h.data_format = "channels_last"
# classification loss
h.label_smoothing = 0.0 # 0.1 is a good default
# Behold the focal loss parameters
h.alpha = 0.25
h.gamma = 1.5
# localization loss
h.delta = 0.1 # regularization parameter of huber loss.
# total loss = box_loss * box_loss_weight + iou_loss * iou_loss_weight
h.box_loss_weight = 50.0
h.iou_loss_type = None
h.iou_loss_weight = 1.0
# regularization l2 loss.
h.weight_decay = 4e-5
# For detection.
h.box_class_repeats = 3
h.fpn_cell_repeats = 3
h.fpn_num_filters = 88
h.separable_conv = True
h.apply_bn_for_resampling = True
h.conv_after_downsample = False
h.conv_bn_act_pattern = False
h.drop_remainder = True # drop remainder for the final batch eval.
# For post-processing nms, must be a dict.
h.nms_configs = {
"method": "gaussian",
"iou_thresh": None, # use the default value based on method.
"score_thresh": 0.0,
"sigma": None,
"max_nms_inputs": 0,
"max_output_size": 100,
}
# version.
h.fpn_name = None
h.fpn_weight_method = None
h.fpn_config = None
# No stochastic depth in default.
h.survival_prob = None
h.lr_decay_method = "cosine"
h.backbone_name = "efficientnet-b1"
h.backbone_config = None
h.var_freeze_expr = None
# A temporary flag to switch between legacy and keras models.
h.positives_momentum = None
h.grad_checkpoint = False
return h | [
"def",
"default_detection_configs",
"(",
")",
":",
"h",
"=",
"Config",
"(",
")",
"# model name.",
"h",
".",
"name",
"=",
"\"efficientdet-d1\"",
"# activation type: see activation_fn in utils.py.",
"h",
".",
"act_type",
"=",
"\"swish\"",
"# input preprocessing parameters",
"h",
".",
"image_size",
"=",
"640",
"# An integer or a string WxH such as 640x320.",
"h",
".",
"target_size",
"=",
"None",
"h",
".",
"input_rand_hflip",
"=",
"True",
"h",
".",
"jitter_min",
"=",
"0.1",
"h",
".",
"jitter_max",
"=",
"2.0",
"h",
".",
"grid_mask",
"=",
"False",
"# dataset specific parameters",
"h",
".",
"num_classes",
"=",
"91",
"# 1+ actual classes, 0 is reserved for background.",
"h",
".",
"skip_crowd_during_training",
"=",
"True",
"h",
".",
"label_map",
"=",
"\"coco\"",
"# a dict or a string of 'coco', 'voc', 'waymo'.",
"h",
".",
"max_instances_per_image",
"=",
"100",
"# Default to 100 for COCO.",
"# model architecture",
"h",
".",
"min_level",
"=",
"3",
"h",
".",
"max_level",
"=",
"7",
"h",
".",
"num_scales",
"=",
"3",
"# ratio w/h: 2.0 means w=1.4, h=0.7. Can be computed with k-mean per dataset.",
"h",
".",
"aspect_ratios",
"=",
"[",
"1.0",
",",
"2.0",
",",
"0.5",
"]",
"# [[0.7, 1.4], [1.0, 1.0], [1.4, 0.7]]",
"h",
".",
"anchor_scale",
"=",
"4.0",
"# optimization",
"h",
".",
"momentum",
"=",
"0.9",
"h",
".",
"optimizer",
"=",
"\"sgd\"",
"# can be 'adam' or 'sgd'.",
"h",
".",
"learning_rate",
"=",
"0.08",
"# 0.008 for adam.",
"h",
".",
"lr_warmup_init",
"=",
"0.008",
"# 0.0008 for adam.",
"h",
".",
"lr_warmup_epoch",
"=",
"1.0",
"h",
".",
"first_lr_drop_epoch",
"=",
"200.0",
"h",
".",
"second_lr_drop_epoch",
"=",
"250.0",
"h",
".",
"poly_lr_power",
"=",
"0.9",
"h",
".",
"clip_gradients_norm",
"=",
"10.0",
"h",
".",
"data_format",
"=",
"\"channels_last\"",
"# classification loss",
"h",
".",
"label_smoothing",
"=",
"0.0",
"# 0.1 is a good default",
"# Behold the focal loss parameters",
"h",
".",
"alpha",
"=",
"0.25",
"h",
".",
"gamma",
"=",
"1.5",
"# localization loss",
"h",
".",
"delta",
"=",
"0.1",
"# regularization parameter of huber loss.",
"# total loss = box_loss * box_loss_weight + iou_loss * iou_loss_weight",
"h",
".",
"box_loss_weight",
"=",
"50.0",
"h",
".",
"iou_loss_type",
"=",
"None",
"h",
".",
"iou_loss_weight",
"=",
"1.0",
"# regularization l2 loss.",
"h",
".",
"weight_decay",
"=",
"4e-5",
"# For detection.",
"h",
".",
"box_class_repeats",
"=",
"3",
"h",
".",
"fpn_cell_repeats",
"=",
"3",
"h",
".",
"fpn_num_filters",
"=",
"88",
"h",
".",
"separable_conv",
"=",
"True",
"h",
".",
"apply_bn_for_resampling",
"=",
"True",
"h",
".",
"conv_after_downsample",
"=",
"False",
"h",
".",
"conv_bn_act_pattern",
"=",
"False",
"h",
".",
"drop_remainder",
"=",
"True",
"# drop remainder for the final batch eval.",
"# For post-processing nms, must be a dict.",
"h",
".",
"nms_configs",
"=",
"{",
"\"method\"",
":",
"\"gaussian\"",
",",
"\"iou_thresh\"",
":",
"None",
",",
"# use the default value based on method.",
"\"score_thresh\"",
":",
"0.0",
",",
"\"sigma\"",
":",
"None",
",",
"\"max_nms_inputs\"",
":",
"0",
",",
"\"max_output_size\"",
":",
"100",
",",
"}",
"# version.",
"h",
".",
"fpn_name",
"=",
"None",
"h",
".",
"fpn_weight_method",
"=",
"None",
"h",
".",
"fpn_config",
"=",
"None",
"# No stochastic depth in default.",
"h",
".",
"survival_prob",
"=",
"None",
"h",
".",
"lr_decay_method",
"=",
"\"cosine\"",
"h",
".",
"backbone_name",
"=",
"\"efficientnet-b1\"",
"h",
".",
"backbone_config",
"=",
"None",
"h",
".",
"var_freeze_expr",
"=",
"None",
"# A temporary flag to switch between legacy and keras models.",
"h",
".",
"positives_momentum",
"=",
"None",
"h",
".",
"grad_checkpoint",
"=",
"False",
"return",
"h"
] | https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/docs/examples/use_cases/tensorflow/efficientdet/hparams_config.py#L175-L273 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/cudnn_rnn/python/ops/cudnn_rnn_ops.py | python | CudnnOpaqueParamsSaveable._cudnn_to_tf_biases | (self, *biases) | r"""Stitching cudnn canonical biases to generate tf canonical biases. | r"""Stitching cudnn canonical biases to generate tf canonical biases. | [
"r",
"Stitching",
"cudnn",
"canonical",
"biases",
"to",
"generate",
"tf",
"canonical",
"biases",
"."
] | def _cudnn_to_tf_biases(self, *biases):
r"""Stitching cudnn canonical biases to generate tf canonical biases."""
raise NotImplementedError("Abstract method") | [
"def",
"_cudnn_to_tf_biases",
"(",
"self",
",",
"*",
"biases",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Abstract method\"",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/cudnn_rnn/python/ops/cudnn_rnn_ops.py#L432-L434 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexers.py | python | is_list_like_indexer | (key) | return is_list_like(key) and not (isinstance(key, tuple) and type(key) is not tuple) | Check if we have a list-like indexer that is *not* a NamedTuple.
Parameters
----------
key : object
Returns
-------
bool | Check if we have a list-like indexer that is *not* a NamedTuple. | [
"Check",
"if",
"we",
"have",
"a",
"list",
"-",
"like",
"indexer",
"that",
"is",
"*",
"not",
"*",
"a",
"NamedTuple",
"."
] | def is_list_like_indexer(key) -> bool:
"""
Check if we have a list-like indexer that is *not* a NamedTuple.
Parameters
----------
key : object
Returns
-------
bool
"""
# allow a list_like, but exclude NamedTuples which can be indexers
return is_list_like(key) and not (isinstance(key, tuple) and type(key) is not tuple) | [
"def",
"is_list_like_indexer",
"(",
"key",
")",
"->",
"bool",
":",
"# allow a list_like, but exclude NamedTuples which can be indexers",
"return",
"is_list_like",
"(",
"key",
")",
"and",
"not",
"(",
"isinstance",
"(",
"key",
",",
"tuple",
")",
"and",
"type",
"(",
"key",
")",
"is",
"not",
"tuple",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexers.py#L23-L36 | |
CanalTP/navitia | cb84ce9859070187e708818b058e6a7e0b7f891b | source/navitiacommon/navitiacommon/ratelimit.py | python | RateLimiter.acquire | (self, key, block=True) | Tests whether we can make a request, or if we are currently being limited
key - key to track what to rate limit
block - Whether to wait until we can make the request | Tests whether we can make a request, or if we are currently being limited
key - key to track what to rate limit
block - Whether to wait until we can make the request | [
"Tests",
"whether",
"we",
"can",
"make",
"a",
"request",
"or",
"if",
"we",
"are",
"currently",
"being",
"limited",
"key",
"-",
"key",
"to",
"track",
"what",
"to",
"rate",
"limit",
"block",
"-",
"Whether",
"to",
"wait",
"until",
"we",
"can",
"make",
"the",
"request"
] | def acquire(self, key, block=True):
"""
Tests whether we can make a request, or if we are currently being limited
key - key to track what to rate limit
block - Whether to wait until we can make the request
"""
if block:
while True:
success, wait = self._make_ping(key)
if success:
return True
self.log.debug('blocking acquire sleeping for %.1fs', wait)
time.sleep(wait)
else:
success, wait = self._make_ping(key)
return success | [
"def",
"acquire",
"(",
"self",
",",
"key",
",",
"block",
"=",
"True",
")",
":",
"if",
"block",
":",
"while",
"True",
":",
"success",
",",
"wait",
"=",
"self",
".",
"_make_ping",
"(",
"key",
")",
"if",
"success",
":",
"return",
"True",
"self",
".",
"log",
".",
"debug",
"(",
"'blocking acquire sleeping for %.1fs'",
",",
"wait",
")",
"time",
".",
"sleep",
"(",
"wait",
")",
"else",
":",
"success",
",",
"wait",
"=",
"self",
".",
"_make_ping",
"(",
"key",
")",
"return",
"success"
] | https://github.com/CanalTP/navitia/blob/cb84ce9859070187e708818b058e6a7e0b7f891b/source/navitiacommon/navitiacommon/ratelimit.py#L161-L176 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | PreTreeCtrl | (*args, **kwargs) | return val | PreTreeCtrl() -> TreeCtrl | PreTreeCtrl() -> TreeCtrl | [
"PreTreeCtrl",
"()",
"-",
">",
"TreeCtrl"
] | def PreTreeCtrl(*args, **kwargs):
"""PreTreeCtrl() -> TreeCtrl"""
val = _controls_.new_PreTreeCtrl(*args, **kwargs)
return val | [
"def",
"PreTreeCtrl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"val",
"=",
"_controls_",
".",
"new_PreTreeCtrl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"val"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L5593-L5596 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/cpplint.py | python | CheckForIncludeWhatYouUse | (filename, clean_lines, include_state, error,
io=codecs) | Reports for missing stl includes.
This function will output warnings to make sure you are including the headers
necessary for the stl containers and functions that you use. We only give one
reason to include a header. For example, if you use both equal_to<> and
less<> in a .h file, only one (the latter in the file) of these will be
reported as a reason to include the <functional>.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
include_state: An _IncludeState instance.
error: The function to call with any errors found.
io: The IO factory to use to read the header file. Provided for unittest
injection. | Reports for missing stl includes. | [
"Reports",
"for",
"missing",
"stl",
"includes",
"."
] | def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
io=codecs):
"""Reports for missing stl includes.
This function will output warnings to make sure you are including the headers
necessary for the stl containers and functions that you use. We only give one
reason to include a header. For example, if you use both equal_to<> and
less<> in a .h file, only one (the latter in the file) of these will be
reported as a reason to include the <functional>.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
include_state: An _IncludeState instance.
error: The function to call with any errors found.
io: The IO factory to use to read the header file. Provided for unittest
injection.
"""
required = {} # A map of header name to linenumber and the template entity.
# Example of required: { '<functional>': (1219, 'less<>') }
for linenum in xrange(clean_lines.NumLines()):
line = clean_lines.elided[linenum]
if not line or line[0] == '#':
continue
# String is special -- it is a non-templatized type in STL.
matched = _RE_PATTERN_STRING.search(line)
if matched:
# Don't warn about strings in non-STL namespaces:
# (We check only the first match per line; good enough.)
prefix = line[:matched.start()]
if prefix.endswith('std::') or not prefix.endswith('::'):
required['<string>'] = (linenum, 'string')
for pattern, template, header in _re_pattern_headers_maybe_templates:
if pattern.search(line):
required[header] = (linenum, template)
# The following function is just a speed up, no semantics are changed.
if not '<' in line: # Reduces the cpu time usage by skipping lines.
continue
for pattern, template, header in _re_pattern_templates:
if pattern.search(line):
required[header] = (linenum, template)
# The policy is that if you #include something in foo.h you don't need to
# include it again in foo.cc. Here, we will look at possible includes.
# Let's flatten the include_state include_list and copy it into a dictionary.
include_dict = dict([item for sublist in include_state.include_list
for item in sublist])
# Did we find the header for this file (if any) and successfully load it?
header_found = False
# Use the absolute path so that matching works properly.
abs_filename = FileInfo(filename).FullName()
# For Emacs's flymake.
# If cpplint is invoked from Emacs's flymake, a temporary file is generated
# by flymake and that file name might end with '_flymake.cc'. In that case,
# restore original file name here so that the corresponding header file can be
# found.
# e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
# instead of 'foo_flymake.h'
abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
# include_dict is modified during iteration, so we iterate over a copy of
# the keys.
header_keys = list(include_dict.keys())
for header in header_keys:
(same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
fullpath = common_path + header
if same_module and UpdateIncludeState(fullpath, include_dict, io):
header_found = True
# If we can't find the header file for a .cc, assume it's because we don't
# know where to look. In that case we'll give up as we're not sure they
# didn't include it in the .h file.
# TODO(unknown): Do a better job of finding .h files so we are confident that
# not having the .h file means there isn't one.
if not header_found:
for extension in GetNonHeaderExtensions():
if filename.endswith('.' + extension):
return
# All the lines have been processed, report the errors found.
for required_header_unstripped in sorted(required, key=required.__getitem__):
template = required[required_header_unstripped][1]
if required_header_unstripped.strip('<>"') not in include_dict:
error(filename, required[required_header_unstripped][0],
'build/include_what_you_use', 4,
'Add #include ' + required_header_unstripped + ' for ' + template) | [
"def",
"CheckForIncludeWhatYouUse",
"(",
"filename",
",",
"clean_lines",
",",
"include_state",
",",
"error",
",",
"io",
"=",
"codecs",
")",
":",
"required",
"=",
"{",
"}",
"# A map of header name to linenumber and the template entity.",
"# Example of required: { '<functional>': (1219, 'less<>') }",
"for",
"linenum",
"in",
"xrange",
"(",
"clean_lines",
".",
"NumLines",
"(",
")",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"not",
"line",
"or",
"line",
"[",
"0",
"]",
"==",
"'#'",
":",
"continue",
"# String is special -- it is a non-templatized type in STL.",
"matched",
"=",
"_RE_PATTERN_STRING",
".",
"search",
"(",
"line",
")",
"if",
"matched",
":",
"# Don't warn about strings in non-STL namespaces:",
"# (We check only the first match per line; good enough.)",
"prefix",
"=",
"line",
"[",
":",
"matched",
".",
"start",
"(",
")",
"]",
"if",
"prefix",
".",
"endswith",
"(",
"'std::'",
")",
"or",
"not",
"prefix",
".",
"endswith",
"(",
"'::'",
")",
":",
"required",
"[",
"'<string>'",
"]",
"=",
"(",
"linenum",
",",
"'string'",
")",
"for",
"pattern",
",",
"template",
",",
"header",
"in",
"_re_pattern_headers_maybe_templates",
":",
"if",
"pattern",
".",
"search",
"(",
"line",
")",
":",
"required",
"[",
"header",
"]",
"=",
"(",
"linenum",
",",
"template",
")",
"# The following function is just a speed up, no semantics are changed.",
"if",
"not",
"'<'",
"in",
"line",
":",
"# Reduces the cpu time usage by skipping lines.",
"continue",
"for",
"pattern",
",",
"template",
",",
"header",
"in",
"_re_pattern_templates",
":",
"if",
"pattern",
".",
"search",
"(",
"line",
")",
":",
"required",
"[",
"header",
"]",
"=",
"(",
"linenum",
",",
"template",
")",
"# The policy is that if you #include something in foo.h you don't need to",
"# include it again in foo.cc. Here, we will look at possible includes.",
"# Let's flatten the include_state include_list and copy it into a dictionary.",
"include_dict",
"=",
"dict",
"(",
"[",
"item",
"for",
"sublist",
"in",
"include_state",
".",
"include_list",
"for",
"item",
"in",
"sublist",
"]",
")",
"# Did we find the header for this file (if any) and successfully load it?",
"header_found",
"=",
"False",
"# Use the absolute path so that matching works properly.",
"abs_filename",
"=",
"FileInfo",
"(",
"filename",
")",
".",
"FullName",
"(",
")",
"# For Emacs's flymake.",
"# If cpplint is invoked from Emacs's flymake, a temporary file is generated",
"# by flymake and that file name might end with '_flymake.cc'. In that case,",
"# restore original file name here so that the corresponding header file can be",
"# found.",
"# e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'",
"# instead of 'foo_flymake.h'",
"abs_filename",
"=",
"re",
".",
"sub",
"(",
"r'_flymake\\.cc$'",
",",
"'.cc'",
",",
"abs_filename",
")",
"# include_dict is modified during iteration, so we iterate over a copy of",
"# the keys.",
"header_keys",
"=",
"list",
"(",
"include_dict",
".",
"keys",
"(",
")",
")",
"for",
"header",
"in",
"header_keys",
":",
"(",
"same_module",
",",
"common_path",
")",
"=",
"FilesBelongToSameModule",
"(",
"abs_filename",
",",
"header",
")",
"fullpath",
"=",
"common_path",
"+",
"header",
"if",
"same_module",
"and",
"UpdateIncludeState",
"(",
"fullpath",
",",
"include_dict",
",",
"io",
")",
":",
"header_found",
"=",
"True",
"# If we can't find the header file for a .cc, assume it's because we don't",
"# know where to look. In that case we'll give up as we're not sure they",
"# didn't include it in the .h file.",
"# TODO(unknown): Do a better job of finding .h files so we are confident that",
"# not having the .h file means there isn't one.",
"if",
"not",
"header_found",
":",
"for",
"extension",
"in",
"GetNonHeaderExtensions",
"(",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"'.'",
"+",
"extension",
")",
":",
"return",
"# All the lines have been processed, report the errors found.",
"for",
"required_header_unstripped",
"in",
"sorted",
"(",
"required",
",",
"key",
"=",
"required",
".",
"__getitem__",
")",
":",
"template",
"=",
"required",
"[",
"required_header_unstripped",
"]",
"[",
"1",
"]",
"if",
"required_header_unstripped",
".",
"strip",
"(",
"'<>\"'",
")",
"not",
"in",
"include_dict",
":",
"error",
"(",
"filename",
",",
"required",
"[",
"required_header_unstripped",
"]",
"[",
"0",
"]",
",",
"'build/include_what_you_use'",
",",
"4",
",",
"'Add #include '",
"+",
"required_header_unstripped",
"+",
"' for '",
"+",
"template",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/cpplint.py#L5698-L5791 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/array_ops.py | python | parallel_stack | (values, name="parallel_stack") | Stacks a list of rank-`R` tensors into one rank-`(R+1)` tensor in parallel.
Requires that the shape of inputs be known at graph construction time.
Packs the list of tensors in `values` into a tensor with rank one higher than
each tensor in `values`, by packing them along the first dimension.
Given a list of length `N` of tensors of shape `(A, B, C)`; the `output`
tensor will have the shape `(N, A, B, C)`.
For example:
```python
x = tf.constant([1, 4])
y = tf.constant([2, 5])
z = tf.constant([3, 6])
tf.parallel_stack([x, y, z]) # [[1, 4], [2, 5], [3, 6]]
```
The difference between `stack` and `parallel_stack` is that `stack` requires
all the inputs be computed before the operation will begin but doesn't require
that the input shapes be known during graph construction.
`parallel_stack` will copy pieces of the input into the output as they become
available, in some situations this can provide a performance benefit.
Unlike `stack`, `parallel_stack` does NOT support backpropagation.
This is the opposite of unstack. The numpy equivalent is
tf.parallel_stack([x, y, z]) = np.asarray([x, y, z])
Args:
values: A list of `Tensor` objects with the same shape and type.
name: A name for this operation (optional).
Returns:
output: A stacked `Tensor` with the same type as `values`. | Stacks a list of rank-`R` tensors into one rank-`(R+1)` tensor in parallel. | [
"Stacks",
"a",
"list",
"of",
"rank",
"-",
"R",
"tensors",
"into",
"one",
"rank",
"-",
"(",
"R",
"+",
"1",
")",
"tensor",
"in",
"parallel",
"."
] | def parallel_stack(values, name="parallel_stack"):
"""Stacks a list of rank-`R` tensors into one rank-`(R+1)` tensor in parallel.
Requires that the shape of inputs be known at graph construction time.
Packs the list of tensors in `values` into a tensor with rank one higher than
each tensor in `values`, by packing them along the first dimension.
Given a list of length `N` of tensors of shape `(A, B, C)`; the `output`
tensor will have the shape `(N, A, B, C)`.
For example:
```python
x = tf.constant([1, 4])
y = tf.constant([2, 5])
z = tf.constant([3, 6])
tf.parallel_stack([x, y, z]) # [[1, 4], [2, 5], [3, 6]]
```
The difference between `stack` and `parallel_stack` is that `stack` requires
all the inputs be computed before the operation will begin but doesn't require
that the input shapes be known during graph construction.
`parallel_stack` will copy pieces of the input into the output as they become
available, in some situations this can provide a performance benefit.
Unlike `stack`, `parallel_stack` does NOT support backpropagation.
This is the opposite of unstack. The numpy equivalent is
tf.parallel_stack([x, y, z]) = np.asarray([x, y, z])
Args:
values: A list of `Tensor` objects with the same shape and type.
name: A name for this operation (optional).
Returns:
output: A stacked `Tensor` with the same type as `values`.
"""
with ops.name_scope(name):
value_t = ops.convert_to_tensor(values[0])
value_shape = ops.convert_to_tensor(value_t).get_shape()
output_shape = tensor_shape.TensorShape([len(values)])
output_shape = output_shape.concatenate(value_shape)
# expand_dims converts concat to stack.
return gen_array_ops.parallel_concat(
[expand_dims(value, 0) for value in values], shape=output_shape) | [
"def",
"parallel_stack",
"(",
"values",
",",
"name",
"=",
"\"parallel_stack\"",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
")",
":",
"value_t",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"values",
"[",
"0",
"]",
")",
"value_shape",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"value_t",
")",
".",
"get_shape",
"(",
")",
"output_shape",
"=",
"tensor_shape",
".",
"TensorShape",
"(",
"[",
"len",
"(",
"values",
")",
"]",
")",
"output_shape",
"=",
"output_shape",
".",
"concatenate",
"(",
"value_shape",
")",
"# expand_dims converts concat to stack.",
"return",
"gen_array_ops",
".",
"parallel_concat",
"(",
"[",
"expand_dims",
"(",
"value",
",",
"0",
")",
"for",
"value",
"in",
"values",
"]",
",",
"shape",
"=",
"output_shape",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/array_ops.py#L1049-L1096 | ||
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | src/pybind/mgr/orchestrator/_interface.py | python | Orchestrator.apply_drivegroups | (self, specs: List[DriveGroupSpec]) | Update OSD cluster | Update OSD cluster | [
"Update",
"OSD",
"cluster"
] | def apply_drivegroups(self, specs: List[DriveGroupSpec]) -> OrchResult[List[str]]:
""" Update OSD cluster """
raise NotImplementedError() | [
"def",
"apply_drivegroups",
"(",
"self",
",",
"specs",
":",
"List",
"[",
"DriveGroupSpec",
"]",
")",
"->",
"OrchResult",
"[",
"List",
"[",
"str",
"]",
"]",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/orchestrator/_interface.py#L541-L543 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/model/coordinates.py | python | Group.setController | (self,controller) | return | Given a robotController, sets this group to contain all sensed
and commanded frames. | Given a robotController, sets this group to contain all sensed
and commanded frames. | [
"Given",
"a",
"robotController",
"sets",
"this",
"group",
"to",
"contain",
"all",
"sensed",
"and",
"commanded",
"frames",
"."
] | def setController(self,controller):
"""Given a robotController, sets this group to contain all sensed
and commanded frames."""
root = self.frames['root']
robot = controller.robot()
robot.setConfig(controller.getCommandedConfig())
for i in xrange(robot.numLinks()):
if p >= 0:
Fp = self.frames[robotModel.link(p).getName()+"_commanded"]
else:
Fp = root
f = self.addFrame(robot.link(i).getName()+"_commanded",worldCoordinates=robot.link(i).getTransform(),parent=Fp)
f._data = (controller,i,'commanded')
robot.setConfig(controller.getSensedConfig())
for i in xrange(robot.numLinks()):
if p >= 0:
Fp = self.frames[robotModel.link(p).getName()+"_commanded"]
else:
Fp = root
f = self.addFrame(robot.link(i).getName()+"_sensed",worldCoordinates=robot.link(i).getTransform(),parent=Fp)
f._data = (controller,i,'sensed')
return | [
"def",
"setController",
"(",
"self",
",",
"controller",
")",
":",
"root",
"=",
"self",
".",
"frames",
"[",
"'root'",
"]",
"robot",
"=",
"controller",
".",
"robot",
"(",
")",
"robot",
".",
"setConfig",
"(",
"controller",
".",
"getCommandedConfig",
"(",
")",
")",
"for",
"i",
"in",
"xrange",
"(",
"robot",
".",
"numLinks",
"(",
")",
")",
":",
"if",
"p",
">=",
"0",
":",
"Fp",
"=",
"self",
".",
"frames",
"[",
"robotModel",
".",
"link",
"(",
"p",
")",
".",
"getName",
"(",
")",
"+",
"\"_commanded\"",
"]",
"else",
":",
"Fp",
"=",
"root",
"f",
"=",
"self",
".",
"addFrame",
"(",
"robot",
".",
"link",
"(",
"i",
")",
".",
"getName",
"(",
")",
"+",
"\"_commanded\"",
",",
"worldCoordinates",
"=",
"robot",
".",
"link",
"(",
"i",
")",
".",
"getTransform",
"(",
")",
",",
"parent",
"=",
"Fp",
")",
"f",
".",
"_data",
"=",
"(",
"controller",
",",
"i",
",",
"'commanded'",
")",
"robot",
".",
"setConfig",
"(",
"controller",
".",
"getSensedConfig",
"(",
")",
")",
"for",
"i",
"in",
"xrange",
"(",
"robot",
".",
"numLinks",
"(",
")",
")",
":",
"if",
"p",
">=",
"0",
":",
"Fp",
"=",
"self",
".",
"frames",
"[",
"robotModel",
".",
"link",
"(",
"p",
")",
".",
"getName",
"(",
")",
"+",
"\"_commanded\"",
"]",
"else",
":",
"Fp",
"=",
"root",
"f",
"=",
"self",
".",
"addFrame",
"(",
"robot",
".",
"link",
"(",
"i",
")",
".",
"getName",
"(",
")",
"+",
"\"_sensed\"",
",",
"worldCoordinates",
"=",
"robot",
".",
"link",
"(",
"i",
")",
".",
"getTransform",
"(",
")",
",",
"parent",
"=",
"Fp",
")",
"f",
".",
"_data",
"=",
"(",
"controller",
",",
"i",
",",
"'sensed'",
")",
"return"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/model/coordinates.py#L272-L293 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/distribute/coordinator/cluster_coordinator.py | python | _CoordinatedClosureQueue.put | (self, closure) | Put a closure into the queue for later execution.
If `mark_failed` was called before `put`, the error from the first
invocation of `mark_failed` will be raised.
Args:
closure: The `Closure` to put into the queue. | Put a closure into the queue for later execution. | [
"Put",
"a",
"closure",
"into",
"the",
"queue",
"for",
"later",
"execution",
"."
] | def put(self, closure):
"""Put a closure into the queue for later execution.
If `mark_failed` was called before `put`, the error from the first
invocation of `mark_failed` will be raised.
Args:
closure: The `Closure` to put into the queue.
"""
with self._put_wait_lock, self._queue_lock:
self._queue_free_slot_condition.wait_for(lambda: not self._queue.full())
self._queue.put(closure, block=False)
self._raise_if_error()
self._closures_queued_condition.notify() | [
"def",
"put",
"(",
"self",
",",
"closure",
")",
":",
"with",
"self",
".",
"_put_wait_lock",
",",
"self",
".",
"_queue_lock",
":",
"self",
".",
"_queue_free_slot_condition",
".",
"wait_for",
"(",
"lambda",
":",
"not",
"self",
".",
"_queue",
".",
"full",
"(",
")",
")",
"self",
".",
"_queue",
".",
"put",
"(",
"closure",
",",
"block",
"=",
"False",
")",
"self",
".",
"_raise_if_error",
"(",
")",
"self",
".",
"_closures_queued_condition",
".",
"notify",
"(",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/coordinator/cluster_coordinator.py#L376-L389 | ||
lyxok1/Tiny-DSOD | 94d15450699bea0dd3720e75e2d273e476174fba | python/caffe/pycaffe.py | python | _Net_params | (self) | return self._params_dict | An OrderedDict (bottom to top, i.e., input to output) of network
parameters indexed by name; each is a list of multiple blobs (e.g.,
weights and biases) | An OrderedDict (bottom to top, i.e., input to output) of network
parameters indexed by name; each is a list of multiple blobs (e.g.,
weights and biases) | [
"An",
"OrderedDict",
"(",
"bottom",
"to",
"top",
"i",
".",
"e",
".",
"input",
"to",
"output",
")",
"of",
"network",
"parameters",
"indexed",
"by",
"name",
";",
"each",
"is",
"a",
"list",
"of",
"multiple",
"blobs",
"(",
"e",
".",
"g",
".",
"weights",
"and",
"biases",
")"
] | def _Net_params(self):
"""
An OrderedDict (bottom to top, i.e., input to output) of network
parameters indexed by name; each is a list of multiple blobs (e.g.,
weights and biases)
"""
if not hasattr(self, '_params_dict'):
self._params_dict = OrderedDict([(name, lr.blobs)
for name, lr in zip(
self._layer_names, self.layers)
if len(lr.blobs) > 0])
return self._params_dict | [
"def",
"_Net_params",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_params_dict'",
")",
":",
"self",
".",
"_params_dict",
"=",
"OrderedDict",
"(",
"[",
"(",
"name",
",",
"lr",
".",
"blobs",
")",
"for",
"name",
",",
"lr",
"in",
"zip",
"(",
"self",
".",
"_layer_names",
",",
"self",
".",
"layers",
")",
"if",
"len",
"(",
"lr",
".",
"blobs",
")",
">",
"0",
"]",
")",
"return",
"self",
".",
"_params_dict"
] | https://github.com/lyxok1/Tiny-DSOD/blob/94d15450699bea0dd3720e75e2d273e476174fba/python/caffe/pycaffe.py#L48-L59 | |
InsightSoftwareConsortium/ITK | 87acfce9a93d928311c38bc371b666b515b9f19d | Modules/ThirdParty/pygccxml/src/pygccxml/declarations/matchers.py | python | matcher_base_t.__invert__ | (self) | return not_matcher_t(self) | not-operator (~) | not-operator (~) | [
"not",
"-",
"operator",
"(",
"~",
")"
] | def __invert__(self):
"""not-operator (~)"""
return not_matcher_t(self) | [
"def",
"__invert__",
"(",
"self",
")",
":",
"return",
"not_matcher_t",
"(",
"self",
")"
] | https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/matchers.py#L28-L30 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/xrc.py | python | XmlResource.LoadFile | (*args, **kwargs) | return _xrc.XmlResource_LoadFile(*args, **kwargs) | LoadFile(self, String file) -> bool | LoadFile(self, String file) -> bool | [
"LoadFile",
"(",
"self",
"String",
"file",
")",
"-",
">",
"bool"
] | def LoadFile(*args, **kwargs):
"""LoadFile(self, String file) -> bool"""
return _xrc.XmlResource_LoadFile(*args, **kwargs) | [
"def",
"LoadFile",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_xrc",
".",
"XmlResource_LoadFile",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/xrc.py#L90-L92 | |
goldeneye-source/ges-code | 2630cd8ef3d015af53c72ec2e19fc1f7e7fe8d9d | thirdparty/protobuf-2.3.0/python/mox.py | python | UnorderedGroup.AddMethod | (self, mock_method) | Add a method to this group.
Args:
mock_method: A mock method to be added to this group. | Add a method to this group. | [
"Add",
"a",
"method",
"to",
"this",
"group",
"."
] | def AddMethod(self, mock_method):
"""Add a method to this group.
Args:
mock_method: A mock method to be added to this group.
"""
self._methods.append(mock_method) | [
"def",
"AddMethod",
"(",
"self",
",",
"mock_method",
")",
":",
"self",
".",
"_methods",
".",
"append",
"(",
"mock_method",
")"
] | https://github.com/goldeneye-source/ges-code/blob/2630cd8ef3d015af53c72ec2e19fc1f7e7fe8d9d/thirdparty/protobuf-2.3.0/python/mox.py#L1214-L1221 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/aui.py | python | PyAuiTabArt.GetNormalFont | (*args, **kwargs) | return _aui.PyAuiTabArt_GetNormalFont(*args, **kwargs) | GetNormalFont(self) -> Font | GetNormalFont(self) -> Font | [
"GetNormalFont",
"(",
"self",
")",
"-",
">",
"Font"
] | def GetNormalFont(*args, **kwargs):
"""GetNormalFont(self) -> Font"""
return _aui.PyAuiTabArt_GetNormalFont(*args, **kwargs) | [
"def",
"GetNormalFont",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"PyAuiTabArt_GetNormalFont",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L2435-L2437 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | Menu.InsertSeparator | (*args, **kwargs) | return _core_.Menu_InsertSeparator(*args, **kwargs) | InsertSeparator(self, size_t pos) -> MenuItem | InsertSeparator(self, size_t pos) -> MenuItem | [
"InsertSeparator",
"(",
"self",
"size_t",
"pos",
")",
"-",
">",
"MenuItem"
] | def InsertSeparator(*args, **kwargs):
"""InsertSeparator(self, size_t pos) -> MenuItem"""
return _core_.Menu_InsertSeparator(*args, **kwargs) | [
"def",
"InsertSeparator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Menu_InsertSeparator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L12056-L12058 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/composite/multitype_ops/add_impl.py | python | _tensor_add_scalar | (x, y) | return F.add(x, y) | Tensor is added to number.
Args:
x (Tensor): x
y (Number): The dtype is same as x.
Returns:
Tensor, has the same dtype as x. | Tensor is added to number. | [
"Tensor",
"is",
"added",
"to",
"number",
"."
] | def _tensor_add_scalar(x, y):
"""
Tensor is added to number.
Args:
x (Tensor): x
y (Number): The dtype is same as x.
Returns:
Tensor, has the same dtype as x.
"""
return F.add(x, y) | [
"def",
"_tensor_add_scalar",
"(",
"x",
",",
"y",
")",
":",
"return",
"F",
".",
"add",
"(",
"x",
",",
"y",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/composite/multitype_ops/add_impl.py#L105-L116 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/StringIO.py | python | StringIO.flush | (self) | Flush the internal buffer | Flush the internal buffer | [
"Flush",
"the",
"internal",
"buffer"
] | def flush(self):
"""Flush the internal buffer
"""
_complain_ifclosed(self.closed) | [
"def",
"flush",
"(",
"self",
")",
":",
"_complain_ifclosed",
"(",
"self",
".",
"closed",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/StringIO.py#L253-L256 | ||
microsoft/clang | 86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5 | utils/check_cfc/check_cfc.py | python | flip_dash_g | (args) | Search for -g in args. If it exists then return args without. If not then
add it. | Search for -g in args. If it exists then return args without. If not then
add it. | [
"Search",
"for",
"-",
"g",
"in",
"args",
".",
"If",
"it",
"exists",
"then",
"return",
"args",
"without",
".",
"If",
"not",
"then",
"add",
"it",
"."
] | def flip_dash_g(args):
"""Search for -g in args. If it exists then return args without. If not then
add it."""
if '-g' in args:
# Return args without any -g
return [x for x in args if x != '-g']
else:
# No -g, add one
return args + ['-g'] | [
"def",
"flip_dash_g",
"(",
"args",
")",
":",
"if",
"'-g'",
"in",
"args",
":",
"# Return args without any -g",
"return",
"[",
"x",
"for",
"x",
"in",
"args",
"if",
"x",
"!=",
"'-g'",
"]",
"else",
":",
"# No -g, add one",
"return",
"args",
"+",
"[",
"'-g'",
"]"
] | https://github.com/microsoft/clang/blob/86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5/utils/check_cfc/check_cfc.py#L108-L116 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/difflib.py | python | Differ._qformat | (self, aline, bline, atags, btags) | r"""
Format "?" output and deal with leading tabs.
Example:
>>> d = Differ()
>>> results = d._qformat('\tabcDefghiJkl\n', '\tabcdefGhijkl\n',
... ' ^ ^ ^ ', ' ^ ^ ^ ')
>>> for line in results: print repr(line)
...
'- \tabcDefghiJkl\n'
'? \t ^ ^ ^\n'
'+ \tabcdefGhijkl\n'
'? \t ^ ^ ^\n' | r"""
Format "?" output and deal with leading tabs. | [
"r",
"Format",
"?",
"output",
"and",
"deal",
"with",
"leading",
"tabs",
"."
] | def _qformat(self, aline, bline, atags, btags):
r"""
Format "?" output and deal with leading tabs.
Example:
>>> d = Differ()
>>> results = d._qformat('\tabcDefghiJkl\n', '\tabcdefGhijkl\n',
... ' ^ ^ ^ ', ' ^ ^ ^ ')
>>> for line in results: print repr(line)
...
'- \tabcDefghiJkl\n'
'? \t ^ ^ ^\n'
'+ \tabcdefGhijkl\n'
'? \t ^ ^ ^\n'
"""
# Can hurt, but will probably help most of the time.
common = min(_count_leading(aline, "\t"),
_count_leading(bline, "\t"))
common = min(common, _count_leading(atags[:common], " "))
common = min(common, _count_leading(btags[:common], " "))
atags = atags[common:].rstrip()
btags = btags[common:].rstrip()
yield "- " + aline
if atags:
yield "? %s%s\n" % ("\t" * common, atags)
yield "+ " + bline
if btags:
yield "? %s%s\n" % ("\t" * common, btags) | [
"def",
"_qformat",
"(",
"self",
",",
"aline",
",",
"bline",
",",
"atags",
",",
"btags",
")",
":",
"# Can hurt, but will probably help most of the time.",
"common",
"=",
"min",
"(",
"_count_leading",
"(",
"aline",
",",
"\"\\t\"",
")",
",",
"_count_leading",
"(",
"bline",
",",
"\"\\t\"",
")",
")",
"common",
"=",
"min",
"(",
"common",
",",
"_count_leading",
"(",
"atags",
"[",
":",
"common",
"]",
",",
"\" \"",
")",
")",
"common",
"=",
"min",
"(",
"common",
",",
"_count_leading",
"(",
"btags",
"[",
":",
"common",
"]",
",",
"\" \"",
")",
")",
"atags",
"=",
"atags",
"[",
"common",
":",
"]",
".",
"rstrip",
"(",
")",
"btags",
"=",
"btags",
"[",
"common",
":",
"]",
".",
"rstrip",
"(",
")",
"yield",
"\"- \"",
"+",
"aline",
"if",
"atags",
":",
"yield",
"\"? %s%s\\n\"",
"%",
"(",
"\"\\t\"",
"*",
"common",
",",
"atags",
")",
"yield",
"\"+ \"",
"+",
"bline",
"if",
"btags",
":",
"yield",
"\"? %s%s\\n\"",
"%",
"(",
"\"\\t\"",
"*",
"common",
",",
"btags",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/difflib.py#L1056-L1087 | ||
CGRU/cgru | 1881a4128530e3d31ac6c25314c18314fc50c2c7 | afanasy/python/af.py | python | Job.setMaxRunTasksPerHost | (self, value) | Missing DocString
:param value:
:return: | Missing DocString | [
"Missing",
"DocString"
] | def setMaxRunTasksPerHost(self, value):
"""Missing DocString
:param value:
:return:
"""
if value >= 0:
self.data["max_running_tasks_per_host"] = int(value) | [
"def",
"setMaxRunTasksPerHost",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
">=",
"0",
":",
"self",
".",
"data",
"[",
"\"max_running_tasks_per_host\"",
"]",
"=",
"int",
"(",
"value",
")"
] | https://github.com/CGRU/cgru/blob/1881a4128530e3d31ac6c25314c18314fc50c2c7/afanasy/python/af.py#L781-L788 | ||
nyuwireless-unipd/ns3-mmwave | 4ff9e87e8079764e04cbeccd8e85bff15ae16fb3 | utils/grid.py | python | Timeline.get_range | (self, name) | return timeline | ! Get range
@param self this object
@param name name
@return the range | ! Get range | [
"!",
"Get",
"range"
] | def get_range(self, name):
"""! Get range
@param self this object
@param name name
@return the range
"""
for range in self.ranges:
if range.name == name:
return range
timeline = TimelineDataRange(name)
self.ranges.append(timeline)
return timeline | [
"def",
"get_range",
"(",
"self",
",",
"name",
")",
":",
"for",
"range",
"in",
"self",
".",
"ranges",
":",
"if",
"range",
".",
"name",
"==",
"name",
":",
"return",
"range",
"timeline",
"=",
"TimelineDataRange",
"(",
"name",
")",
"self",
".",
"ranges",
".",
"append",
"(",
"timeline",
")",
"return",
"timeline"
] | https://github.com/nyuwireless-unipd/ns3-mmwave/blob/4ff9e87e8079764e04cbeccd8e85bff15ae16fb3/utils/grid.py#L284-L295 | |
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/plugins/grassprovider/ext/r_series_interp.py | python | checkParameterValuesBeforeExecuting | (alg, parameters, context) | return True, None | Verify if we have the right parameters | Verify if we have the right parameters | [
"Verify",
"if",
"we",
"have",
"the",
"right",
"parameters"
] | def checkParameterValuesBeforeExecuting(alg, parameters, context):
""" Verify if we have the right parameters """
datapos = alg.parameterAsDouble(parameters, 'datapos', context)
infile = alg.parameterAsString(parameters, 'infile', context)
output = alg.parameterAsString(parameters, 'output', context)
outfile = alg.parameterAsString(parameters, 'outfile', context)
if datapos and infile:
return False, alg.tr("You need to set either inline data positions or an input data positions file!")
if output and outfile:
return False, alg.tr("You need to set either sampling data positions or an output sampling data positions file!")
if not (datapos or infile or output or outfile):
return False, alg.tr("You need to set input and output data positions parameters!")
return True, None | [
"def",
"checkParameterValuesBeforeExecuting",
"(",
"alg",
",",
"parameters",
",",
"context",
")",
":",
"datapos",
"=",
"alg",
".",
"parameterAsDouble",
"(",
"parameters",
",",
"'datapos'",
",",
"context",
")",
"infile",
"=",
"alg",
".",
"parameterAsString",
"(",
"parameters",
",",
"'infile'",
",",
"context",
")",
"output",
"=",
"alg",
".",
"parameterAsString",
"(",
"parameters",
",",
"'output'",
",",
"context",
")",
"outfile",
"=",
"alg",
".",
"parameterAsString",
"(",
"parameters",
",",
"'outfile'",
",",
"context",
")",
"if",
"datapos",
"and",
"infile",
":",
"return",
"False",
",",
"alg",
".",
"tr",
"(",
"\"You need to set either inline data positions or an input data positions file!\"",
")",
"if",
"output",
"and",
"outfile",
":",
"return",
"False",
",",
"alg",
".",
"tr",
"(",
"\"You need to set either sampling data positions or an output sampling data positions file!\"",
")",
"if",
"not",
"(",
"datapos",
"or",
"infile",
"or",
"output",
"or",
"outfile",
")",
":",
"return",
"False",
",",
"alg",
".",
"tr",
"(",
"\"You need to set input and output data positions parameters!\"",
")",
"return",
"True",
",",
"None"
] | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/grassprovider/ext/r_series_interp.py#L28-L41 | |
ZhouWeikuan/DouDiZhu | 0d84ff6c0bc54dba6ae37955de9ae9307513dc99 | code/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py | python | TokenKind.from_value | (value) | return result | Obtain a registered TokenKind instance from its value. | Obtain a registered TokenKind instance from its value. | [
"Obtain",
"a",
"registered",
"TokenKind",
"instance",
"from",
"its",
"value",
"."
] | def from_value(value):
"""Obtain a registered TokenKind instance from its value."""
result = TokenKind._value_map.get(value, None)
if result is None:
raise ValueError('Unknown TokenKind: %d' % value)
return result | [
"def",
"from_value",
"(",
"value",
")",
":",
"result",
"=",
"TokenKind",
".",
"_value_map",
".",
"get",
"(",
"value",
",",
"None",
")",
"if",
"result",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Unknown TokenKind: %d'",
"%",
"value",
")",
"return",
"result"
] | https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L565-L572 | |
giuspen/cherrytree | 84712f206478fcf9acf30174009ad28c648c6344 | pygtk2/modules/findreplace.py | python | FindReplace.find_again | (self) | Continue the previous search (a_node/in_selected_node/in_all_nodes) | Continue the previous search (a_node/in_selected_node/in_all_nodes) | [
"Continue",
"the",
"previous",
"search",
"(",
"a_node",
"/",
"in_selected_node",
"/",
"in_all_nodes",
")"
] | def find_again(self):
"""Continue the previous search (a_node/in_selected_node/in_all_nodes)"""
self.from_find_iterated = True
if self.curr_find[0] == None: support.dialog_warning(_("No Previous Search Was Performed During This Session"), self.dad.window)
elif self.curr_find[0] == "in_selected_node": self.find_in_selected_node()
elif self.curr_find[0] == "in_all_nodes": self.find_in_all_nodes(None)
elif self.curr_find[0] == "in_sel_nod_n_sub": self.find_in_all_nodes(self.dad.curr_tree_iter)
elif self.curr_find[0] == "a_node": self.find_a_node()
self.from_find_iterated = False | [
"def",
"find_again",
"(",
"self",
")",
":",
"self",
".",
"from_find_iterated",
"=",
"True",
"if",
"self",
".",
"curr_find",
"[",
"0",
"]",
"==",
"None",
":",
"support",
".",
"dialog_warning",
"(",
"_",
"(",
"\"No Previous Search Was Performed During This Session\"",
")",
",",
"self",
".",
"dad",
".",
"window",
")",
"elif",
"self",
".",
"curr_find",
"[",
"0",
"]",
"==",
"\"in_selected_node\"",
":",
"self",
".",
"find_in_selected_node",
"(",
")",
"elif",
"self",
".",
"curr_find",
"[",
"0",
"]",
"==",
"\"in_all_nodes\"",
":",
"self",
".",
"find_in_all_nodes",
"(",
"None",
")",
"elif",
"self",
".",
"curr_find",
"[",
"0",
"]",
"==",
"\"in_sel_nod_n_sub\"",
":",
"self",
".",
"find_in_all_nodes",
"(",
"self",
".",
"dad",
".",
"curr_tree_iter",
")",
"elif",
"self",
".",
"curr_find",
"[",
"0",
"]",
"==",
"\"a_node\"",
":",
"self",
".",
"find_a_node",
"(",
")",
"self",
".",
"from_find_iterated",
"=",
"False"
] | https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/findreplace.py#L867-L875 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/cookies.py | python | RequestsCookieJar.items | (self) | return list(self.iteritems()) | Dict-like items() that returns a list of name-value tuples from the
jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a
vanilla python dict of key value pairs.
.. seealso:: keys() and values(). | Dict-like items() that returns a list of name-value tuples from the
jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a
vanilla python dict of key value pairs. | [
"Dict",
"-",
"like",
"items",
"()",
"that",
"returns",
"a",
"list",
"of",
"name",
"-",
"value",
"tuples",
"from",
"the",
"jar",
".",
"Allows",
"client",
"-",
"code",
"to",
"call",
"dict",
"(",
"RequestsCookieJar",
")",
"and",
"get",
"a",
"vanilla",
"python",
"dict",
"of",
"key",
"value",
"pairs",
"."
] | def items(self):
"""Dict-like items() that returns a list of name-value tuples from the
jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a
vanilla python dict of key value pairs.
.. seealso:: keys() and values().
"""
return list(self.iteritems()) | [
"def",
"items",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
".",
"iteritems",
"(",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/cookies.py#L261-L268 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/win_unicode_console/win_unicode_console/tokenize_open.py | python | open | (filename) | Open a file in read only mode using the encoding detected by
detect_encoding(). | Open a file in read only mode using the encoding detected by
detect_encoding(). | [
"Open",
"a",
"file",
"in",
"read",
"only",
"mode",
"using",
"the",
"encoding",
"detected",
"by",
"detect_encoding",
"()",
"."
] | def open(filename):
"""Open a file in read only mode using the encoding detected by
detect_encoding().
"""
buffer = _builtin_open(filename, 'rb')
try:
encoding, lines = detect_encoding(buffer.readline)
buffer.seek(0)
text = TextIOWrapper(buffer, encoding, line_buffering=True)
text.mode = 'r'
return text
except:
buffer.close()
raise | [
"def",
"open",
"(",
"filename",
")",
":",
"buffer",
"=",
"_builtin_open",
"(",
"filename",
",",
"'rb'",
")",
"try",
":",
"encoding",
",",
"lines",
"=",
"detect_encoding",
"(",
"buffer",
".",
"readline",
")",
"buffer",
".",
"seek",
"(",
"0",
")",
"text",
"=",
"TextIOWrapper",
"(",
"buffer",
",",
"encoding",
",",
"line_buffering",
"=",
"True",
")",
"text",
".",
"mode",
"=",
"'r'",
"return",
"text",
"except",
":",
"buffer",
".",
"close",
"(",
")",
"raise"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/win_unicode_console/win_unicode_console/tokenize_open.py#L128-L141 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | TextAttrDimensions.Reset | (*args, **kwargs) | return _richtext.TextAttrDimensions_Reset(*args, **kwargs) | Reset(self) | Reset(self) | [
"Reset",
"(",
"self",
")"
] | def Reset(*args, **kwargs):
"""Reset(self)"""
return _richtext.TextAttrDimensions_Reset(*args, **kwargs) | [
"def",
"Reset",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"TextAttrDimensions_Reset",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L205-L207 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/distributed/elastic/metrics/api.py | python | put_metric | (metric_name: str, metric_value: int, metric_group: str = "torchelastic") | Publishes a metric data point.
Usage
::
put_metric("metric_name", 1)
put_metric("metric_name", 1, "metric_group_name") | Publishes a metric data point. | [
"Publishes",
"a",
"metric",
"data",
"point",
"."
] | def put_metric(metric_name: str, metric_value: int, metric_group: str = "torchelastic"):
"""
Publishes a metric data point.
Usage
::
put_metric("metric_name", 1)
put_metric("metric_name", 1, "metric_group_name")
"""
getStream(metric_group).add_value(metric_name, metric_value) | [
"def",
"put_metric",
"(",
"metric_name",
":",
"str",
",",
"metric_value",
":",
"int",
",",
"metric_group",
":",
"str",
"=",
"\"torchelastic\"",
")",
":",
"getStream",
"(",
"metric_group",
")",
".",
"add_value",
"(",
"metric_name",
",",
"metric_value",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/elastic/metrics/api.py#L178-L190 | ||
apache/arrow | af33dd1157eb8d7d9bfac25ebf61445b793b7943 | dev/archery/archery/utils/maven.py | python | MavenDefinition.build | (self, build_dir, force=False, cmd_kwargs=None, **kwargs) | return MavenBuild(build_dir, definition=self, **kwargs) | Invoke maven into a build directory.
Parameters
----------
build_dir : str
Directory in which the Maven build will be instantiated.
force : bool
not used now | Invoke maven into a build directory. | [
"Invoke",
"maven",
"into",
"a",
"build",
"directory",
"."
] | def build(self, build_dir, force=False, cmd_kwargs=None, **kwargs):
""" Invoke maven into a build directory.
Parameters
----------
build_dir : str
Directory in which the Maven build will be instantiated.
force : bool
not used now
"""
if os.path.exists(build_dir):
# Extra safety to ensure we're deleting a build folder.
if not MavenBuild.is_build_dir(build_dir):
raise FileExistsError(
"{} is not a maven build".format(build_dir)
)
cmd_kwargs = cmd_kwargs if cmd_kwargs else {}
assert MavenBuild.is_build_dir(build_dir)
maven(*self.build_arguments, cwd=build_dir, env=self.env, **cmd_kwargs)
return MavenBuild(build_dir, definition=self, **kwargs) | [
"def",
"build",
"(",
"self",
",",
"build_dir",
",",
"force",
"=",
"False",
",",
"cmd_kwargs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"build_dir",
")",
":",
"# Extra safety to ensure we're deleting a build folder.",
"if",
"not",
"MavenBuild",
".",
"is_build_dir",
"(",
"build_dir",
")",
":",
"raise",
"FileExistsError",
"(",
"\"{} is not a maven build\"",
".",
"format",
"(",
"build_dir",
")",
")",
"cmd_kwargs",
"=",
"cmd_kwargs",
"if",
"cmd_kwargs",
"else",
"{",
"}",
"assert",
"MavenBuild",
".",
"is_build_dir",
"(",
"build_dir",
")",
"maven",
"(",
"*",
"self",
".",
"build_arguments",
",",
"cwd",
"=",
"build_dir",
",",
"env",
"=",
"self",
".",
"env",
",",
"*",
"*",
"cmd_kwargs",
")",
"return",
"MavenBuild",
"(",
"build_dir",
",",
"definition",
"=",
"self",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/dev/archery/archery/utils/maven.py#L74-L94 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | mainloop | (n=0) | Run the main loop of Tcl. | Run the main loop of Tcl. | [
"Run",
"the",
"main",
"loop",
"of",
"Tcl",
"."
] | def mainloop(n=0):
"""Run the main loop of Tcl."""
_default_root.tk.mainloop(n) | [
"def",
"mainloop",
"(",
"n",
"=",
"0",
")",
":",
"_default_root",
".",
"tk",
".",
"mainloop",
"(",
"n",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L359-L361 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/stc.py | python | StyledTextCtrl.SetTextUTF8 | (self, text) | Replace the contents of the document with the UTF8 text given.
Works 'natively' in a unicode build of wxPython, and will also
work in an ansi build if the UTF8 text is compatible with the
current encoding. | Replace the contents of the document with the UTF8 text given.
Works 'natively' in a unicode build of wxPython, and will also
work in an ansi build if the UTF8 text is compatible with the
current encoding. | [
"Replace",
"the",
"contents",
"of",
"the",
"document",
"with",
"the",
"UTF8",
"text",
"given",
".",
"Works",
"natively",
"in",
"a",
"unicode",
"build",
"of",
"wxPython",
"and",
"will",
"also",
"work",
"in",
"an",
"ansi",
"build",
"if",
"the",
"UTF8",
"text",
"is",
"compatible",
"with",
"the",
"current",
"encoding",
"."
] | def SetTextUTF8(self, text):
"""
Replace the contents of the document with the UTF8 text given.
Works 'natively' in a unicode build of wxPython, and will also
work in an ansi build if the UTF8 text is compatible with the
current encoding.
"""
if not wx.USE_UNICODE:
u = text.decode('utf-8')
text = u.encode(wx.GetDefaultPyEncoding())
self.SetTextRaw(text) | [
"def",
"SetTextUTF8",
"(",
"self",
",",
"text",
")",
":",
"if",
"not",
"wx",
".",
"USE_UNICODE",
":",
"u",
"=",
"text",
".",
"decode",
"(",
"'utf-8'",
")",
"text",
"=",
"u",
".",
"encode",
"(",
"wx",
".",
"GetDefaultPyEncoding",
"(",
")",
")",
"self",
".",
"SetTextRaw",
"(",
"text",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L6856-L6866 | ||
geemaple/leetcode | 68bc5032e1ee52c22ef2f2e608053484c487af54 | leetcode/438.find-all-anagrams-in-a-string.py | python | Solution.findAnagrams | (self, s, p) | return res | :type s: str
:type p: str
:rtype: List[int] | :type s: str
:type p: str
:rtype: List[int] | [
":",
"type",
"s",
":",
"str",
":",
"type",
"p",
":",
"str",
":",
"rtype",
":",
"List",
"[",
"int",
"]"
] | def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
size = len(p)
left = size
counting = {}
res = []
for c in p:
counting[c] = counting.get(c, 0) + 1
back = 0
for i in range(len(s)):
if s[i] in counting:
counting[s[i]] -= 1
if counting[s[i]] >= 0:
left -= 1
if i - back + 1 == size:
if left == 0:
res.append(back)
if s[back] in counting:
counting[s[back]] += 1
if counting[s[back]] > 0:
left += 1
back += 1
return res | [
"def",
"findAnagrams",
"(",
"self",
",",
"s",
",",
"p",
")",
":",
"size",
"=",
"len",
"(",
"p",
")",
"left",
"=",
"size",
"counting",
"=",
"{",
"}",
"res",
"=",
"[",
"]",
"for",
"c",
"in",
"p",
":",
"counting",
"[",
"c",
"]",
"=",
"counting",
".",
"get",
"(",
"c",
",",
"0",
")",
"+",
"1",
"back",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"s",
")",
")",
":",
"if",
"s",
"[",
"i",
"]",
"in",
"counting",
":",
"counting",
"[",
"s",
"[",
"i",
"]",
"]",
"-=",
"1",
"if",
"counting",
"[",
"s",
"[",
"i",
"]",
"]",
">=",
"0",
":",
"left",
"-=",
"1",
"if",
"i",
"-",
"back",
"+",
"1",
"==",
"size",
":",
"if",
"left",
"==",
"0",
":",
"res",
".",
"append",
"(",
"back",
")",
"if",
"s",
"[",
"back",
"]",
"in",
"counting",
":",
"counting",
"[",
"s",
"[",
"back",
"]",
"]",
"+=",
"1",
"if",
"counting",
"[",
"s",
"[",
"back",
"]",
"]",
">",
"0",
":",
"left",
"+=",
"1",
"back",
"+=",
"1",
"return",
"res"
] | https://github.com/geemaple/leetcode/blob/68bc5032e1ee52c22ef2f2e608053484c487af54/leetcode/438.find-all-anagrams-in-a-string.py#L2-L34 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py | python | Misc.image_names | (self) | return self.tk.splitlist(self.tk.call('image', 'names')) | Return a list of all existing image names. | Return a list of all existing image names. | [
"Return",
"a",
"list",
"of",
"all",
"existing",
"image",
"names",
"."
] | def image_names(self):
"""Return a list of all existing image names."""
return self.tk.splitlist(self.tk.call('image', 'names')) | [
"def",
"image_names",
"(",
"self",
")",
":",
"return",
"self",
".",
"tk",
".",
"splitlist",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"'image'",
",",
"'names'",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py#L1683-L1685 | |
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/xcode_emulation.py | python | XcodeSettings.GetCflags | (self, configname, arch=None) | return cflags | Returns flags that need to be added to .c, .cc, .m, and .mm
compilations. | Returns flags that need to be added to .c, .cc, .m, and .mm
compilations. | [
"Returns",
"flags",
"that",
"need",
"to",
"be",
"added",
"to",
".",
"c",
".",
"cc",
".",
"m",
"and",
".",
"mm",
"compilations",
"."
] | def GetCflags(self, configname, arch=None):
"""Returns flags that need to be added to .c, .cc, .m, and .mm
compilations."""
# This functions (and the similar ones below) do not offer complete
# emulation of all xcode_settings keys. They're implemented on demand.
self.configname = configname
cflags = []
sdk_root = self._SdkPath()
if 'SDKROOT' in self._Settings() and sdk_root:
cflags.append('-isysroot %s' % sdk_root)
if self._Test('CLANG_WARN_CONSTANT_CONVERSION', 'YES', default='NO'):
cflags.append('-Wconstant-conversion')
if self._Test('GCC_CHAR_IS_UNSIGNED_CHAR', 'YES', default='NO'):
cflags.append('-funsigned-char')
if self._Test('GCC_CW_ASM_SYNTAX', 'YES', default='YES'):
cflags.append('-fasm-blocks')
if 'GCC_DYNAMIC_NO_PIC' in self._Settings():
if self._Settings()['GCC_DYNAMIC_NO_PIC'] == 'YES':
cflags.append('-mdynamic-no-pic')
else:
pass
# TODO: In this case, it depends on the target. xcode passes
# mdynamic-no-pic by default for executable and possibly static lib
# according to mento
if self._Test('GCC_ENABLE_PASCAL_STRINGS', 'YES', default='YES'):
cflags.append('-mpascal-strings')
self._Appendf(cflags, 'GCC_OPTIMIZATION_LEVEL', '-O%s', default='s')
if self._Test('GCC_GENERATE_DEBUGGING_SYMBOLS', 'YES', default='YES'):
dbg_format = self._Settings().get('DEBUG_INFORMATION_FORMAT', 'dwarf')
if dbg_format == 'dwarf':
cflags.append('-gdwarf-2')
elif dbg_format == 'stabs':
raise NotImplementedError('stabs debug format is not supported yet.')
elif dbg_format == 'dwarf-with-dsym':
cflags.append('-gdwarf-2')
else:
raise NotImplementedError('Unknown debug format %s' % dbg_format)
if self._Settings().get('GCC_STRICT_ALIASING') == 'YES':
cflags.append('-fstrict-aliasing')
elif self._Settings().get('GCC_STRICT_ALIASING') == 'NO':
cflags.append('-fno-strict-aliasing')
if self._Test('GCC_SYMBOLS_PRIVATE_EXTERN', 'YES', default='NO'):
cflags.append('-fvisibility=hidden')
if self._Test('GCC_TREAT_WARNINGS_AS_ERRORS', 'YES', default='NO'):
cflags.append('-Werror')
if self._Test('GCC_WARN_ABOUT_MISSING_NEWLINE', 'YES', default='NO'):
cflags.append('-Wnewline-eof')
# In Xcode, this is only activated when GCC_COMPILER_VERSION is clang or
# llvm-gcc. It also requires a fairly recent libtool, and
# if the system clang isn't used, DYLD_LIBRARY_PATH needs to contain the
# path to the libLTO.dylib that matches the used clang.
if self._Test('LLVM_LTO', 'YES', default='NO'):
cflags.append('-flto')
self._AppendPlatformVersionMinFlags(cflags)
# TODO:
if self._Test('COPY_PHASE_STRIP', 'YES', default='NO'):
self._WarnUnimplemented('COPY_PHASE_STRIP')
self._WarnUnimplemented('GCC_DEBUGGING_SYMBOLS')
self._WarnUnimplemented('GCC_ENABLE_OBJC_EXCEPTIONS')
# TODO: This is exported correctly, but assigning to it is not supported.
self._WarnUnimplemented('MACH_O_TYPE')
self._WarnUnimplemented('PRODUCT_TYPE')
if arch is not None:
archs = [arch]
else:
assert self.configname
archs = self.GetActiveArchs(self.configname)
if len(archs) != 1:
# TODO: Supporting fat binaries will be annoying.
self._WarnUnimplemented('ARCHS')
archs = ['i386']
cflags.append('-arch ' + archs[0])
if archs[0] in ('i386', 'x86_64'):
if self._Test('GCC_ENABLE_SSE3_EXTENSIONS', 'YES', default='NO'):
cflags.append('-msse3')
if self._Test('GCC_ENABLE_SUPPLEMENTAL_SSE3_INSTRUCTIONS', 'YES',
default='NO'):
cflags.append('-mssse3') # Note 3rd 's'.
if self._Test('GCC_ENABLE_SSE41_EXTENSIONS', 'YES', default='NO'):
cflags.append('-msse4.1')
if self._Test('GCC_ENABLE_SSE42_EXTENSIONS', 'YES', default='NO'):
cflags.append('-msse4.2')
cflags += self._Settings().get('WARNING_CFLAGS', [])
if sdk_root:
framework_root = sdk_root
else:
framework_root = ''
config = self.spec['configurations'][self.configname]
framework_dirs = config.get('mac_framework_dirs', [])
for directory in framework_dirs:
cflags.append('-F' + directory.replace('$(SDKROOT)', framework_root))
self.configname = None
return cflags | [
"def",
"GetCflags",
"(",
"self",
",",
"configname",
",",
"arch",
"=",
"None",
")",
":",
"# This functions (and the similar ones below) do not offer complete",
"# emulation of all xcode_settings keys. They're implemented on demand.",
"self",
".",
"configname",
"=",
"configname",
"cflags",
"=",
"[",
"]",
"sdk_root",
"=",
"self",
".",
"_SdkPath",
"(",
")",
"if",
"'SDKROOT'",
"in",
"self",
".",
"_Settings",
"(",
")",
"and",
"sdk_root",
":",
"cflags",
".",
"append",
"(",
"'-isysroot %s'",
"%",
"sdk_root",
")",
"if",
"self",
".",
"_Test",
"(",
"'CLANG_WARN_CONSTANT_CONVERSION'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"cflags",
".",
"append",
"(",
"'-Wconstant-conversion'",
")",
"if",
"self",
".",
"_Test",
"(",
"'GCC_CHAR_IS_UNSIGNED_CHAR'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"cflags",
".",
"append",
"(",
"'-funsigned-char'",
")",
"if",
"self",
".",
"_Test",
"(",
"'GCC_CW_ASM_SYNTAX'",
",",
"'YES'",
",",
"default",
"=",
"'YES'",
")",
":",
"cflags",
".",
"append",
"(",
"'-fasm-blocks'",
")",
"if",
"'GCC_DYNAMIC_NO_PIC'",
"in",
"self",
".",
"_Settings",
"(",
")",
":",
"if",
"self",
".",
"_Settings",
"(",
")",
"[",
"'GCC_DYNAMIC_NO_PIC'",
"]",
"==",
"'YES'",
":",
"cflags",
".",
"append",
"(",
"'-mdynamic-no-pic'",
")",
"else",
":",
"pass",
"# TODO: In this case, it depends on the target. xcode passes",
"# mdynamic-no-pic by default for executable and possibly static lib",
"# according to mento",
"if",
"self",
".",
"_Test",
"(",
"'GCC_ENABLE_PASCAL_STRINGS'",
",",
"'YES'",
",",
"default",
"=",
"'YES'",
")",
":",
"cflags",
".",
"append",
"(",
"'-mpascal-strings'",
")",
"self",
".",
"_Appendf",
"(",
"cflags",
",",
"'GCC_OPTIMIZATION_LEVEL'",
",",
"'-O%s'",
",",
"default",
"=",
"'s'",
")",
"if",
"self",
".",
"_Test",
"(",
"'GCC_GENERATE_DEBUGGING_SYMBOLS'",
",",
"'YES'",
",",
"default",
"=",
"'YES'",
")",
":",
"dbg_format",
"=",
"self",
".",
"_Settings",
"(",
")",
".",
"get",
"(",
"'DEBUG_INFORMATION_FORMAT'",
",",
"'dwarf'",
")",
"if",
"dbg_format",
"==",
"'dwarf'",
":",
"cflags",
".",
"append",
"(",
"'-gdwarf-2'",
")",
"elif",
"dbg_format",
"==",
"'stabs'",
":",
"raise",
"NotImplementedError",
"(",
"'stabs debug format is not supported yet.'",
")",
"elif",
"dbg_format",
"==",
"'dwarf-with-dsym'",
":",
"cflags",
".",
"append",
"(",
"'-gdwarf-2'",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"'Unknown debug format %s'",
"%",
"dbg_format",
")",
"if",
"self",
".",
"_Settings",
"(",
")",
".",
"get",
"(",
"'GCC_STRICT_ALIASING'",
")",
"==",
"'YES'",
":",
"cflags",
".",
"append",
"(",
"'-fstrict-aliasing'",
")",
"elif",
"self",
".",
"_Settings",
"(",
")",
".",
"get",
"(",
"'GCC_STRICT_ALIASING'",
")",
"==",
"'NO'",
":",
"cflags",
".",
"append",
"(",
"'-fno-strict-aliasing'",
")",
"if",
"self",
".",
"_Test",
"(",
"'GCC_SYMBOLS_PRIVATE_EXTERN'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"cflags",
".",
"append",
"(",
"'-fvisibility=hidden'",
")",
"if",
"self",
".",
"_Test",
"(",
"'GCC_TREAT_WARNINGS_AS_ERRORS'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"cflags",
".",
"append",
"(",
"'-Werror'",
")",
"if",
"self",
".",
"_Test",
"(",
"'GCC_WARN_ABOUT_MISSING_NEWLINE'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"cflags",
".",
"append",
"(",
"'-Wnewline-eof'",
")",
"# In Xcode, this is only activated when GCC_COMPILER_VERSION is clang or",
"# llvm-gcc. It also requires a fairly recent libtool, and",
"# if the system clang isn't used, DYLD_LIBRARY_PATH needs to contain the",
"# path to the libLTO.dylib that matches the used clang.",
"if",
"self",
".",
"_Test",
"(",
"'LLVM_LTO'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"cflags",
".",
"append",
"(",
"'-flto'",
")",
"self",
".",
"_AppendPlatformVersionMinFlags",
"(",
"cflags",
")",
"# TODO:",
"if",
"self",
".",
"_Test",
"(",
"'COPY_PHASE_STRIP'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"self",
".",
"_WarnUnimplemented",
"(",
"'COPY_PHASE_STRIP'",
")",
"self",
".",
"_WarnUnimplemented",
"(",
"'GCC_DEBUGGING_SYMBOLS'",
")",
"self",
".",
"_WarnUnimplemented",
"(",
"'GCC_ENABLE_OBJC_EXCEPTIONS'",
")",
"# TODO: This is exported correctly, but assigning to it is not supported.",
"self",
".",
"_WarnUnimplemented",
"(",
"'MACH_O_TYPE'",
")",
"self",
".",
"_WarnUnimplemented",
"(",
"'PRODUCT_TYPE'",
")",
"if",
"arch",
"is",
"not",
"None",
":",
"archs",
"=",
"[",
"arch",
"]",
"else",
":",
"assert",
"self",
".",
"configname",
"archs",
"=",
"self",
".",
"GetActiveArchs",
"(",
"self",
".",
"configname",
")",
"if",
"len",
"(",
"archs",
")",
"!=",
"1",
":",
"# TODO: Supporting fat binaries will be annoying.",
"self",
".",
"_WarnUnimplemented",
"(",
"'ARCHS'",
")",
"archs",
"=",
"[",
"'i386'",
"]",
"cflags",
".",
"append",
"(",
"'-arch '",
"+",
"archs",
"[",
"0",
"]",
")",
"if",
"archs",
"[",
"0",
"]",
"in",
"(",
"'i386'",
",",
"'x86_64'",
")",
":",
"if",
"self",
".",
"_Test",
"(",
"'GCC_ENABLE_SSE3_EXTENSIONS'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"cflags",
".",
"append",
"(",
"'-msse3'",
")",
"if",
"self",
".",
"_Test",
"(",
"'GCC_ENABLE_SUPPLEMENTAL_SSE3_INSTRUCTIONS'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"cflags",
".",
"append",
"(",
"'-mssse3'",
")",
"# Note 3rd 's'.",
"if",
"self",
".",
"_Test",
"(",
"'GCC_ENABLE_SSE41_EXTENSIONS'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"cflags",
".",
"append",
"(",
"'-msse4.1'",
")",
"if",
"self",
".",
"_Test",
"(",
"'GCC_ENABLE_SSE42_EXTENSIONS'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"cflags",
".",
"append",
"(",
"'-msse4.2'",
")",
"cflags",
"+=",
"self",
".",
"_Settings",
"(",
")",
".",
"get",
"(",
"'WARNING_CFLAGS'",
",",
"[",
"]",
")",
"if",
"sdk_root",
":",
"framework_root",
"=",
"sdk_root",
"else",
":",
"framework_root",
"=",
"''",
"config",
"=",
"self",
".",
"spec",
"[",
"'configurations'",
"]",
"[",
"self",
".",
"configname",
"]",
"framework_dirs",
"=",
"config",
".",
"get",
"(",
"'mac_framework_dirs'",
",",
"[",
"]",
")",
"for",
"directory",
"in",
"framework_dirs",
":",
"cflags",
".",
"append",
"(",
"'-F'",
"+",
"directory",
".",
"replace",
"(",
"'$(SDKROOT)'",
",",
"framework_root",
")",
")",
"self",
".",
"configname",
"=",
"None",
"return",
"cflags"
] | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/xcode_emulation.py#L467-L581 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/math/vectorops.py | python | cross | (a,b) | Cross product between a 3-vector or a 2-vector | Cross product between a 3-vector or a 2-vector | [
"Cross",
"product",
"between",
"a",
"3",
"-",
"vector",
"or",
"a",
"2",
"-",
"vector"
] | def cross(a,b):
"""Cross product between a 3-vector or a 2-vector"""
if len(a)!=len(b):
raise RuntimeError('Vector dimensions not equal')
if len(a)==3:
return (a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0])
elif len(a)==2:
return a[0]*b[1]-a[1]*b[0]
else:
raise RuntimeError('Vectors must be 2D or 3D') | [
"def",
"cross",
"(",
"a",
",",
"b",
")",
":",
"if",
"len",
"(",
"a",
")",
"!=",
"len",
"(",
"b",
")",
":",
"raise",
"RuntimeError",
"(",
"'Vector dimensions not equal'",
")",
"if",
"len",
"(",
"a",
")",
"==",
"3",
":",
"return",
"(",
"a",
"[",
"1",
"]",
"*",
"b",
"[",
"2",
"]",
"-",
"a",
"[",
"2",
"]",
"*",
"b",
"[",
"1",
"]",
",",
"a",
"[",
"2",
"]",
"*",
"b",
"[",
"0",
"]",
"-",
"a",
"[",
"0",
"]",
"*",
"b",
"[",
"2",
"]",
",",
"a",
"[",
"0",
"]",
"*",
"b",
"[",
"1",
"]",
"-",
"a",
"[",
"1",
"]",
"*",
"b",
"[",
"0",
"]",
")",
"elif",
"len",
"(",
"a",
")",
"==",
"2",
":",
"return",
"a",
"[",
"0",
"]",
"*",
"b",
"[",
"1",
"]",
"-",
"a",
"[",
"1",
"]",
"*",
"b",
"[",
"0",
"]",
"else",
":",
"raise",
"RuntimeError",
"(",
"'Vectors must be 2D or 3D'",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/math/vectorops.py#L104-L113 | ||
milvus-io/milvus | 3b1030de2b6c39e3512833e97f6044d63eb24237 | internal/core/build-support/cpplint.py | python | _CppLintState.BackupFilters | (self) | Saves the current filter list to backup storage. | Saves the current filter list to backup storage. | [
"Saves",
"the",
"current",
"filter",
"list",
"to",
"backup",
"storage",
"."
] | def BackupFilters(self):
""" Saves the current filter list to backup storage."""
self._filters_backup = self.filters[:] | [
"def",
"BackupFilters",
"(",
"self",
")",
":",
"self",
".",
"_filters_backup",
"=",
"self",
".",
"filters",
"[",
":",
"]"
] | https://github.com/milvus-io/milvus/blob/3b1030de2b6c39e3512833e97f6044d63eb24237/internal/core/build-support/cpplint.py#L1322-L1324 | ||
lawy623/SVS | b7c7ae367c82a4797ff4a896a2ff304f02e7f724 | caffe/scripts/cpp_lint.py | python | CheckSpacingForFunctionCall | (filename, line, linenum, error) | Checks for the correctness of various spacing around function calls.
Args:
filename: The name of the current file.
line: The text of the line to check.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks for the correctness of various spacing around function calls. | [
"Checks",
"for",
"the",
"correctness",
"of",
"various",
"spacing",
"around",
"function",
"calls",
"."
] | def CheckSpacingForFunctionCall(filename, line, linenum, error):
"""Checks for the correctness of various spacing around function calls.
Args:
filename: The name of the current file.
line: The text of the line to check.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Since function calls often occur inside if/for/while/switch
# expressions - which have their own, more liberal conventions - we
# first see if we should be looking inside such an expression for a
# function call, to which we can apply more strict standards.
fncall = line # if there's no control flow construct, look at whole line
for pattern in (r'\bif\s*\((.*)\)\s*{',
r'\bfor\s*\((.*)\)\s*{',
r'\bwhile\s*\((.*)\)\s*[{;]',
r'\bswitch\s*\((.*)\)\s*{'):
match = Search(pattern, line)
if match:
fncall = match.group(1) # look inside the parens for function calls
break
# Except in if/for/while/switch, there should never be space
# immediately inside parens (eg "f( 3, 4 )"). We make an exception
# for nested parens ( (a+b) + c ). Likewise, there should never be
# a space before a ( when it's a function argument. I assume it's a
# function argument when the char before the whitespace is legal in
# a function name (alnum + _) and we're not starting a macro. Also ignore
# pointers and references to arrays and functions coz they're too tricky:
# we use a very simple way to recognize these:
# " (something)(maybe-something)" or
# " (something)(maybe-something," or
# " (something)[something]"
# Note that we assume the contents of [] to be short enough that
# they'll never need to wrap.
if ( # Ignore control structures.
not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',
fncall) and
# Ignore pointers/references to functions.
not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
# Ignore pointers/references to arrays.
not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
error(filename, linenum, 'whitespace/parens', 4,
'Extra space after ( in function call')
elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
error(filename, linenum, 'whitespace/parens', 2,
'Extra space after (')
if (Search(r'\w\s+\(', fncall) and
not Search(r'#\s*define|typedef', fncall) and
not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall)):
error(filename, linenum, 'whitespace/parens', 4,
'Extra space before ( in function call')
# If the ) is followed only by a newline or a { + newline, assume it's
# part of a control statement (if/while/etc), and don't complain
if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
# If the closing parenthesis is preceded by only whitespaces,
# try to give a more descriptive error message.
if Search(r'^\s+\)', fncall):
error(filename, linenum, 'whitespace/parens', 2,
'Closing ) should be moved to the previous line')
else:
error(filename, linenum, 'whitespace/parens', 2,
'Extra space before )') | [
"def",
"CheckSpacingForFunctionCall",
"(",
"filename",
",",
"line",
",",
"linenum",
",",
"error",
")",
":",
"# Since function calls often occur inside if/for/while/switch",
"# expressions - which have their own, more liberal conventions - we",
"# first see if we should be looking inside such an expression for a",
"# function call, to which we can apply more strict standards.",
"fncall",
"=",
"line",
"# if there's no control flow construct, look at whole line",
"for",
"pattern",
"in",
"(",
"r'\\bif\\s*\\((.*)\\)\\s*{'",
",",
"r'\\bfor\\s*\\((.*)\\)\\s*{'",
",",
"r'\\bwhile\\s*\\((.*)\\)\\s*[{;]'",
",",
"r'\\bswitch\\s*\\((.*)\\)\\s*{'",
")",
":",
"match",
"=",
"Search",
"(",
"pattern",
",",
"line",
")",
"if",
"match",
":",
"fncall",
"=",
"match",
".",
"group",
"(",
"1",
")",
"# look inside the parens for function calls",
"break",
"# Except in if/for/while/switch, there should never be space",
"# immediately inside parens (eg \"f( 3, 4 )\"). We make an exception",
"# for nested parens ( (a+b) + c ). Likewise, there should never be",
"# a space before a ( when it's a function argument. I assume it's a",
"# function argument when the char before the whitespace is legal in",
"# a function name (alnum + _) and we're not starting a macro. Also ignore",
"# pointers and references to arrays and functions coz they're too tricky:",
"# we use a very simple way to recognize these:",
"# \" (something)(maybe-something)\" or",
"# \" (something)(maybe-something,\" or",
"# \" (something)[something]\"",
"# Note that we assume the contents of [] to be short enough that",
"# they'll never need to wrap.",
"if",
"(",
"# Ignore control structures.",
"not",
"Search",
"(",
"r'\\b(if|for|while|switch|return|new|delete|catch|sizeof)\\b'",
",",
"fncall",
")",
"and",
"# Ignore pointers/references to functions.",
"not",
"Search",
"(",
"r' \\([^)]+\\)\\([^)]*(\\)|,$)'",
",",
"fncall",
")",
"and",
"# Ignore pointers/references to arrays.",
"not",
"Search",
"(",
"r' \\([^)]+\\)\\[[^\\]]+\\]'",
",",
"fncall",
")",
")",
":",
"if",
"Search",
"(",
"r'\\w\\s*\\(\\s(?!\\s*\\\\$)'",
",",
"fncall",
")",
":",
"# a ( used for a fn call",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"4",
",",
"'Extra space after ( in function call'",
")",
"elif",
"Search",
"(",
"r'\\(\\s+(?!(\\s*\\\\)|\\()'",
",",
"fncall",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"2",
",",
"'Extra space after ('",
")",
"if",
"(",
"Search",
"(",
"r'\\w\\s+\\('",
",",
"fncall",
")",
"and",
"not",
"Search",
"(",
"r'#\\s*define|typedef'",
",",
"fncall",
")",
"and",
"not",
"Search",
"(",
"r'\\w\\s+\\((\\w+::)*\\*\\w+\\)\\('",
",",
"fncall",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"4",
",",
"'Extra space before ( in function call'",
")",
"# If the ) is followed only by a newline or a { + newline, assume it's",
"# part of a control statement (if/while/etc), and don't complain",
"if",
"Search",
"(",
"r'[^)]\\s+\\)\\s*[^{\\s]'",
",",
"fncall",
")",
":",
"# If the closing parenthesis is preceded by only whitespaces,",
"# try to give a more descriptive error message.",
"if",
"Search",
"(",
"r'^\\s+\\)'",
",",
"fncall",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"2",
",",
"'Closing ) should be moved to the previous line'",
")",
"else",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"2",
",",
"'Extra space before )'",
")"
] | https://github.com/lawy623/SVS/blob/b7c7ae367c82a4797ff4a896a2ff304f02e7f724/caffe/scripts/cpp_lint.py#L2301-L2366 | ||
cocos-creator/engine-native | 984c4c9f5838253313b44ccd429bd8fac4ec8a6a | tools/bindings-generator/clang/cindex.py | python | CompilationDatabase.fromDirectory | (buildDir) | return cdb | Builds a CompilationDatabase from the database found in buildDir | Builds a CompilationDatabase from the database found in buildDir | [
"Builds",
"a",
"CompilationDatabase",
"from",
"the",
"database",
"found",
"in",
"buildDir"
] | def fromDirectory(buildDir):
"""Builds a CompilationDatabase from the database found in buildDir"""
errorCode = c_uint()
try:
cdb = conf.lib.clang_CompilationDatabase_fromDirectory(fspath(buildDir),
byref(errorCode))
except CompilationDatabaseError as e:
raise CompilationDatabaseError(int(errorCode.value),
"CompilationDatabase loading failed")
return cdb | [
"def",
"fromDirectory",
"(",
"buildDir",
")",
":",
"errorCode",
"=",
"c_uint",
"(",
")",
"try",
":",
"cdb",
"=",
"conf",
".",
"lib",
".",
"clang_CompilationDatabase_fromDirectory",
"(",
"fspath",
"(",
"buildDir",
")",
",",
"byref",
"(",
"errorCode",
")",
")",
"except",
"CompilationDatabaseError",
"as",
"e",
":",
"raise",
"CompilationDatabaseError",
"(",
"int",
"(",
"errorCode",
".",
"value",
")",
",",
"\"CompilationDatabase loading failed\"",
")",
"return",
"cdb"
] | https://github.com/cocos-creator/engine-native/blob/984c4c9f5838253313b44ccd429bd8fac4ec8a6a/tools/bindings-generator/clang/cindex.py#L3245-L3254 | |
google/google-api-cpp-client | 3df15df632bef43eb320645ac3329d872aabf5ad | prepare_dependencies.py | python | PackageInstaller.MaybeTweakAfterUnpackage | (self) | Extra stuff to do after unpackaging an archive. | Extra stuff to do after unpackaging an archive. | [
"Extra",
"stuff",
"to",
"do",
"after",
"unpackaging",
"an",
"archive",
"."
] | def MaybeTweakAfterUnpackage(self):
"""Extra stuff to do after unpackaging an archive."""
config = self._config
if config.compiler == VS_COMPILER and self._vc_upgrade_from_project_path:
proj_dir = os.path.split(self._vc_project_path)[0]
marker = os.path.join(proj_dir, '_upgraded_vc')
if os.path.exists(self._vc_project_path) and config.force:
if self._vc_upgrade_from_project_path != self._vc_project_path:
os.unlink(self._vc_project_path)
if os.path.exists(marker):
os.unlink(marker)
if (not os.path.exists(self._vc_project_path)
or self._vc_project_path == self._vc_upgrade_from_project_path):
self.UpgradeVisualStudio(self._vc_upgrade_from_project_path,
self._vc_project_path)
open(marker, 'w').close() | [
"def",
"MaybeTweakAfterUnpackage",
"(",
"self",
")",
":",
"config",
"=",
"self",
".",
"_config",
"if",
"config",
".",
"compiler",
"==",
"VS_COMPILER",
"and",
"self",
".",
"_vc_upgrade_from_project_path",
":",
"proj_dir",
"=",
"os",
".",
"path",
".",
"split",
"(",
"self",
".",
"_vc_project_path",
")",
"[",
"0",
"]",
"marker",
"=",
"os",
".",
"path",
".",
"join",
"(",
"proj_dir",
",",
"'_upgraded_vc'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_vc_project_path",
")",
"and",
"config",
".",
"force",
":",
"if",
"self",
".",
"_vc_upgrade_from_project_path",
"!=",
"self",
".",
"_vc_project_path",
":",
"os",
".",
"unlink",
"(",
"self",
".",
"_vc_project_path",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"marker",
")",
":",
"os",
".",
"unlink",
"(",
"marker",
")",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_vc_project_path",
")",
"or",
"self",
".",
"_vc_project_path",
"==",
"self",
".",
"_vc_upgrade_from_project_path",
")",
":",
"self",
".",
"UpgradeVisualStudio",
"(",
"self",
".",
"_vc_upgrade_from_project_path",
",",
"self",
".",
"_vc_project_path",
")",
"open",
"(",
"marker",
",",
"'w'",
")",
".",
"close",
"(",
")"
] | https://github.com/google/google-api-cpp-client/blob/3df15df632bef43eb320645ac3329d872aabf5ad/prepare_dependencies.py#L324-L339 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/botocore/credentials.py | python | AssumeRoleCredentialFetcher._assume_role_kwargs | (self) | return assume_role_kwargs | Get the arguments for assume role based on current configuration. | Get the arguments for assume role based on current configuration. | [
"Get",
"the",
"arguments",
"for",
"assume",
"role",
"based",
"on",
"current",
"configuration",
"."
] | def _assume_role_kwargs(self):
"""Get the arguments for assume role based on current configuration."""
assume_role_kwargs = self._assume_kwargs
mfa_serial = assume_role_kwargs.get('SerialNumber')
if mfa_serial is not None:
prompt = 'Enter MFA code for %s: ' % mfa_serial
token_code = self._mfa_prompter(prompt)
assume_role_kwargs = deepcopy(assume_role_kwargs)
assume_role_kwargs['TokenCode'] = token_code
return assume_role_kwargs | [
"def",
"_assume_role_kwargs",
"(",
"self",
")",
":",
"assume_role_kwargs",
"=",
"self",
".",
"_assume_kwargs",
"mfa_serial",
"=",
"assume_role_kwargs",
".",
"get",
"(",
"'SerialNumber'",
")",
"if",
"mfa_serial",
"is",
"not",
"None",
":",
"prompt",
"=",
"'Enter MFA code for %s: '",
"%",
"mfa_serial",
"token_code",
"=",
"self",
".",
"_mfa_prompter",
"(",
"prompt",
")",
"assume_role_kwargs",
"=",
"deepcopy",
"(",
"assume_role_kwargs",
")",
"assume_role_kwargs",
"[",
"'TokenCode'",
"]",
"=",
"token_code",
"return",
"assume_role_kwargs"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/credentials.py#L689-L701 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | utils/lui/lldbutil.py | python | state_type_to_str | (enum) | Returns the stateType string given an enum. | Returns the stateType string given an enum. | [
"Returns",
"the",
"stateType",
"string",
"given",
"an",
"enum",
"."
] | def state_type_to_str(enum):
"""Returns the stateType string given an enum."""
if enum == lldb.eStateInvalid:
return "invalid"
elif enum == lldb.eStateUnloaded:
return "unloaded"
elif enum == lldb.eStateConnected:
return "connected"
elif enum == lldb.eStateAttaching:
return "attaching"
elif enum == lldb.eStateLaunching:
return "launching"
elif enum == lldb.eStateStopped:
return "stopped"
elif enum == lldb.eStateRunning:
return "running"
elif enum == lldb.eStateStepping:
return "stepping"
elif enum == lldb.eStateCrashed:
return "crashed"
elif enum == lldb.eStateDetached:
return "detached"
elif enum == lldb.eStateExited:
return "exited"
elif enum == lldb.eStateSuspended:
return "suspended"
else:
raise Exception("Unknown StateType enum") | [
"def",
"state_type_to_str",
"(",
"enum",
")",
":",
"if",
"enum",
"==",
"lldb",
".",
"eStateInvalid",
":",
"return",
"\"invalid\"",
"elif",
"enum",
"==",
"lldb",
".",
"eStateUnloaded",
":",
"return",
"\"unloaded\"",
"elif",
"enum",
"==",
"lldb",
".",
"eStateConnected",
":",
"return",
"\"connected\"",
"elif",
"enum",
"==",
"lldb",
".",
"eStateAttaching",
":",
"return",
"\"attaching\"",
"elif",
"enum",
"==",
"lldb",
".",
"eStateLaunching",
":",
"return",
"\"launching\"",
"elif",
"enum",
"==",
"lldb",
".",
"eStateStopped",
":",
"return",
"\"stopped\"",
"elif",
"enum",
"==",
"lldb",
".",
"eStateRunning",
":",
"return",
"\"running\"",
"elif",
"enum",
"==",
"lldb",
".",
"eStateStepping",
":",
"return",
"\"stepping\"",
"elif",
"enum",
"==",
"lldb",
".",
"eStateCrashed",
":",
"return",
"\"crashed\"",
"elif",
"enum",
"==",
"lldb",
".",
"eStateDetached",
":",
"return",
"\"detached\"",
"elif",
"enum",
"==",
"lldb",
".",
"eStateExited",
":",
"return",
"\"exited\"",
"elif",
"enum",
"==",
"lldb",
".",
"eStateSuspended",
":",
"return",
"\"suspended\"",
"else",
":",
"raise",
"Exception",
"(",
"\"Unknown StateType enum\"",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/utils/lui/lldbutil.py#L153-L180 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/stc.py | python | StyledTextCtrl.InsertTextUTF8 | (self, pos, text) | Insert UTF8 encoded text at a position. Works 'natively' in a
unicode build of wxPython, and will also work in an ansi build if
the UTF8 text is compatible with the current encoding. | Insert UTF8 encoded text at a position. Works 'natively' in a
unicode build of wxPython, and will also work in an ansi build if
the UTF8 text is compatible with the current encoding. | [
"Insert",
"UTF8",
"encoded",
"text",
"at",
"a",
"position",
".",
"Works",
"natively",
"in",
"a",
"unicode",
"build",
"of",
"wxPython",
"and",
"will",
"also",
"work",
"in",
"an",
"ansi",
"build",
"if",
"the",
"UTF8",
"text",
"is",
"compatible",
"with",
"the",
"current",
"encoding",
"."
] | def InsertTextUTF8(self, pos, text):
"""
Insert UTF8 encoded text at a position. Works 'natively' in a
unicode build of wxPython, and will also work in an ansi build if
the UTF8 text is compatible with the current encoding.
"""
if not wx.USE_UNICODE:
u = text.decode('utf-8')
text = u.encode(wx.GetDefaultPyEncoding())
self.InsertTextRaw(pos, text) | [
"def",
"InsertTextUTF8",
"(",
"self",
",",
"pos",
",",
"text",
")",
":",
"if",
"not",
"wx",
".",
"USE_UNICODE",
":",
"u",
"=",
"text",
".",
"decode",
"(",
"'utf-8'",
")",
"text",
"=",
"u",
".",
"encode",
"(",
"wx",
".",
"GetDefaultPyEncoding",
"(",
")",
")",
"self",
".",
"InsertTextRaw",
"(",
"pos",
",",
"text",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L6791-L6800 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/_vendor/pyparsing.py | python | ParserElement.parseWithTabs | ( self ) | return self | Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string.
Must be called before C{parseString} when the input grammar contains elements that
match C{<TAB>} characters. | Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string.
Must be called before C{parseString} when the input grammar contains elements that
match C{<TAB>} characters. | [
"Overrides",
"default",
"behavior",
"to",
"expand",
"C",
"{",
"<TAB",
">",
"}",
"s",
"to",
"spaces",
"before",
"parsing",
"the",
"input",
"string",
".",
"Must",
"be",
"called",
"before",
"C",
"{",
"parseString",
"}",
"when",
"the",
"input",
"grammar",
"contains",
"elements",
"that",
"match",
"C",
"{",
"<TAB",
">",
"}",
"characters",
"."
] | def parseWithTabs( self ):
"""
Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string.
Must be called before C{parseString} when the input grammar contains elements that
match C{<TAB>} characters.
"""
self.keepTabs = True
return self | [
"def",
"parseWithTabs",
"(",
"self",
")",
":",
"self",
".",
"keepTabs",
"=",
"True",
"return",
"self"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/_vendor/pyparsing.py#L2070-L2077 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/valid-square.py | python | Solution.validSquare | (self, p1, p2, p3, p4) | return 0 not in lookup and len(lookup) == 2 | :type p1: List[int]
:type p2: List[int]
:type p3: List[int]
:type p4: List[int]
:rtype: bool | :type p1: List[int]
:type p2: List[int]
:type p3: List[int]
:type p4: List[int]
:rtype: bool | [
":",
"type",
"p1",
":",
"List",
"[",
"int",
"]",
":",
"type",
"p2",
":",
"List",
"[",
"int",
"]",
":",
"type",
"p3",
":",
"List",
"[",
"int",
"]",
":",
"type",
"p4",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"bool"
] | def validSquare(self, p1, p2, p3, p4):
"""
:type p1: List[int]
:type p2: List[int]
:type p3: List[int]
:type p4: List[int]
:rtype: bool
"""
def dist(p1, p2):
return (p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2
lookup = set([dist(p1, p2), dist(p1, p3),\
dist(p1, p4), dist(p2, p3),\
dist(p2, p4), dist(p3, p4)])
return 0 not in lookup and len(lookup) == 2 | [
"def",
"validSquare",
"(",
"self",
",",
"p1",
",",
"p2",
",",
"p3",
",",
"p4",
")",
":",
"def",
"dist",
"(",
"p1",
",",
"p2",
")",
":",
"return",
"(",
"p1",
"[",
"0",
"]",
"-",
"p2",
"[",
"0",
"]",
")",
"**",
"2",
"+",
"(",
"p1",
"[",
"1",
"]",
"-",
"p2",
"[",
"1",
"]",
")",
"**",
"2",
"lookup",
"=",
"set",
"(",
"[",
"dist",
"(",
"p1",
",",
"p2",
")",
",",
"dist",
"(",
"p1",
",",
"p3",
")",
",",
"dist",
"(",
"p1",
",",
"p4",
")",
",",
"dist",
"(",
"p2",
",",
"p3",
")",
",",
"dist",
"(",
"p2",
",",
"p4",
")",
",",
"dist",
"(",
"p3",
",",
"p4",
")",
"]",
")",
"return",
"0",
"not",
"in",
"lookup",
"and",
"len",
"(",
"lookup",
")",
"==",
"2"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/valid-square.py#L5-L19 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/grit/grit/gather/chrome_html.py | python | ChromeHtml.Parse | (self) | Parses and inlines the represented file. | Parses and inlines the represented file. | [
"Parses",
"and",
"inlines",
"the",
"represented",
"file",
"."
] | def Parse(self):
"""Parses and inlines the represented file."""
filename = self.GetInputPath()
if self.filename_expansion_function:
filename = self.filename_expansion_function(filename)
# Hack: some unit tests supply an absolute path and no root node.
if not os.path.isabs(filename):
filename = self.grd_node.ToRealPath(filename)
if self.flatten_html_:
self.inlined_text_ = html_inline.InlineToString(
filename,
self.grd_node,
allow_external_script = self.allow_external_script_,
strip_whitespace=True,
preprocess_only = self.preprocess_only_,
rewrite_function=lambda fp, t, d: ProcessImageSets(
fp, t, self.scale_factors_, d,
filename_expansion_function=self.filename_expansion_function),
filename_expansion_function=self.filename_expansion_function)
else:
distribution = html_inline.GetDistribution()
self.inlined_text_ = ProcessImageSets(
os.path.dirname(filename),
util.ReadFile(filename, 'utf-8'),
self.scale_factors_,
distribution,
filename_expansion_function=self.filename_expansion_function) | [
"def",
"Parse",
"(",
"self",
")",
":",
"filename",
"=",
"self",
".",
"GetInputPath",
"(",
")",
"if",
"self",
".",
"filename_expansion_function",
":",
"filename",
"=",
"self",
".",
"filename_expansion_function",
"(",
"filename",
")",
"# Hack: some unit tests supply an absolute path and no root node.",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"filename",
")",
":",
"filename",
"=",
"self",
".",
"grd_node",
".",
"ToRealPath",
"(",
"filename",
")",
"if",
"self",
".",
"flatten_html_",
":",
"self",
".",
"inlined_text_",
"=",
"html_inline",
".",
"InlineToString",
"(",
"filename",
",",
"self",
".",
"grd_node",
",",
"allow_external_script",
"=",
"self",
".",
"allow_external_script_",
",",
"strip_whitespace",
"=",
"True",
",",
"preprocess_only",
"=",
"self",
".",
"preprocess_only_",
",",
"rewrite_function",
"=",
"lambda",
"fp",
",",
"t",
",",
"d",
":",
"ProcessImageSets",
"(",
"fp",
",",
"t",
",",
"self",
".",
"scale_factors_",
",",
"d",
",",
"filename_expansion_function",
"=",
"self",
".",
"filename_expansion_function",
")",
",",
"filename_expansion_function",
"=",
"self",
".",
"filename_expansion_function",
")",
"else",
":",
"distribution",
"=",
"html_inline",
".",
"GetDistribution",
"(",
")",
"self",
".",
"inlined_text_",
"=",
"ProcessImageSets",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
",",
"util",
".",
"ReadFile",
"(",
"filename",
",",
"'utf-8'",
")",
",",
"self",
".",
"scale_factors_",
",",
"distribution",
",",
"filename_expansion_function",
"=",
"self",
".",
"filename_expansion_function",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/gather/chrome_html.py#L338-L365 | ||
shedskin/shedskin | ae88dbca7b1d9671cd8be448cb0b497122758936 | examples/c64/cpu.py | python | CPU.RTS | (self, opcode = 0x60) | return from subroutine | return from subroutine | [
"return",
"from",
"subroutine"
] | def RTS(self, opcode = 0x60):
""" return from subroutine """
PC = (self.stack_pop(2))
self.set_PC(PC + 1) | [
"def",
"RTS",
"(",
"self",
",",
"opcode",
"=",
"0x60",
")",
":",
"PC",
"=",
"(",
"self",
".",
"stack_pop",
"(",
"2",
")",
")",
"self",
".",
"set_PC",
"(",
"PC",
"+",
"1",
")"
] | https://github.com/shedskin/shedskin/blob/ae88dbca7b1d9671cd8be448cb0b497122758936/examples/c64/cpu.py#L1719-L1722 | ||
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/convert/entity_object/export/formats/bltable_metadata.py | python | BlendtableMetadata._get_table_with | (self) | return left | Get the width of the blending table. | Get the width of the blending table. | [
"Get",
"the",
"width",
"of",
"the",
"blending",
"table",
"."
] | def _get_table_with(self):
"""
Get the width of the blending table.
"""
table_size = len(self.blendtable)
# Newton's method
left = table_size
right = (left + 1) // 2
while right < left:
left = right
right = (left + table_size // left) // 2
return left | [
"def",
"_get_table_with",
"(",
"self",
")",
":",
"table_size",
"=",
"len",
"(",
"self",
".",
"blendtable",
")",
"# Newton's method",
"left",
"=",
"table_size",
"right",
"=",
"(",
"left",
"+",
"1",
")",
"//",
"2",
"while",
"right",
"<",
"left",
":",
"left",
"=",
"right",
"right",
"=",
"(",
"left",
"+",
"table_size",
"//",
"left",
")",
"//",
"2",
"return",
"left"
] | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/entity_object/export/formats/bltable_metadata.py#L77-L90 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/configHandler.py | python | IdleConf.GetExtensionKeys | (self,extensionName) | return extKeys | returns a dictionary of the configurable keybindings for a particular
extension,as they exist in the dictionary returned by GetCurrentKeySet;
that is, where previously used bindings are disabled. | returns a dictionary of the configurable keybindings for a particular
extension,as they exist in the dictionary returned by GetCurrentKeySet;
that is, where previously used bindings are disabled. | [
"returns",
"a",
"dictionary",
"of",
"the",
"configurable",
"keybindings",
"for",
"a",
"particular",
"extension",
"as",
"they",
"exist",
"in",
"the",
"dictionary",
"returned",
"by",
"GetCurrentKeySet",
";",
"that",
"is",
"where",
"previously",
"used",
"bindings",
"are",
"disabled",
"."
] | def GetExtensionKeys(self,extensionName):
"""
returns a dictionary of the configurable keybindings for a particular
extension,as they exist in the dictionary returned by GetCurrentKeySet;
that is, where previously used bindings are disabled.
"""
keysName=extensionName+'_cfgBindings'
activeKeys=self.GetCurrentKeySet()
extKeys={}
if self.defaultCfg['extensions'].has_section(keysName):
eventNames=self.defaultCfg['extensions'].GetOptionList(keysName)
for eventName in eventNames:
event='<<'+eventName+'>>'
binding=activeKeys[event]
extKeys[event]=binding
return extKeys | [
"def",
"GetExtensionKeys",
"(",
"self",
",",
"extensionName",
")",
":",
"keysName",
"=",
"extensionName",
"+",
"'_cfgBindings'",
"activeKeys",
"=",
"self",
".",
"GetCurrentKeySet",
"(",
")",
"extKeys",
"=",
"{",
"}",
"if",
"self",
".",
"defaultCfg",
"[",
"'extensions'",
"]",
".",
"has_section",
"(",
"keysName",
")",
":",
"eventNames",
"=",
"self",
".",
"defaultCfg",
"[",
"'extensions'",
"]",
".",
"GetOptionList",
"(",
"keysName",
")",
"for",
"eventName",
"in",
"eventNames",
":",
"event",
"=",
"'<<'",
"+",
"eventName",
"+",
"'>>'",
"binding",
"=",
"activeKeys",
"[",
"event",
"]",
"extKeys",
"[",
"event",
"]",
"=",
"binding",
"return",
"extKeys"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/configHandler.py#L461-L476 | |
fluffos/fluffos | bf54d5d4acef4de49dbed7d184849a7b7b354156 | src/thirdparty/libevent/event_rpcgen.py | python | Struct.EntryTagName | (self, entry) | return name.upper() | Creates the name inside an enumeration for distinguishing data
types. | Creates the name inside an enumeration for distinguishing data
types. | [
"Creates",
"the",
"name",
"inside",
"an",
"enumeration",
"for",
"distinguishing",
"data",
"types",
"."
] | def EntryTagName(self, entry):
"""Creates the name inside an enumeration for distinguishing data
types."""
name = "%s_%s" % (self._name, entry.Name())
return name.upper() | [
"def",
"EntryTagName",
"(",
"self",
",",
"entry",
")",
":",
"name",
"=",
"\"%s_%s\"",
"%",
"(",
"self",
".",
"_name",
",",
"entry",
".",
"Name",
"(",
")",
")",
"return",
"name",
".",
"upper",
"(",
")"
] | https://github.com/fluffos/fluffos/blob/bf54d5d4acef4de49dbed7d184849a7b7b354156/src/thirdparty/libevent/event_rpcgen.py#L86-L90 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/control_flow_state.py | python | _GradLoopState.grad_index | (self) | return self._grad_index | The loop index of backprop loop. | The loop index of backprop loop. | [
"The",
"loop",
"index",
"of",
"backprop",
"loop",
"."
] | def grad_index(self):
"""The loop index of backprop loop."""
return self._grad_index | [
"def",
"grad_index",
"(",
"self",
")",
":",
"return",
"self",
".",
"_grad_index"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/control_flow_state.py#L241-L243 | |
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/showbase/RandomNumGen.py | python | RandomNumGen.randint | (self, a, b) | return a+r | returns integer in [a, b] | returns integer in [a, b] | [
"returns",
"integer",
"in",
"[",
"a",
"b",
"]"
] | def randint(self, a, b):
"""returns integer in [a, b]"""
assert a <= b
range = b-a+1
r = self.__rand(range)
return a+r | [
"def",
"randint",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"assert",
"a",
"<=",
"b",
"range",
"=",
"b",
"-",
"a",
"+",
"1",
"r",
"=",
"self",
".",
"__rand",
"(",
"range",
")",
"return",
"a",
"+",
"r"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/showbase/RandomNumGen.py#L120-L125 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/io/matlab/miobase.py | python | arr_dtype_number | (arr, num) | return np.dtype(arr.dtype.str[:2] + str(num)) | Return dtype for given number of items per element | Return dtype for given number of items per element | [
"Return",
"dtype",
"for",
"given",
"number",
"of",
"items",
"per",
"element"
] | def arr_dtype_number(arr, num):
''' Return dtype for given number of items per element'''
return np.dtype(arr.dtype.str[:2] + str(num)) | [
"def",
"arr_dtype_number",
"(",
"arr",
",",
"num",
")",
":",
"return",
"np",
".",
"dtype",
"(",
"arr",
".",
"dtype",
".",
"str",
"[",
":",
"2",
"]",
"+",
"str",
"(",
"num",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/io/matlab/miobase.py#L396-L398 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/message.py | python | Message.get_content_disposition | (self) | return c_d | Return the message's content-disposition if it exists, or None.
The return values can be either 'inline', 'attachment' or None
according to the rfc2183. | Return the message's content-disposition if it exists, or None. | [
"Return",
"the",
"message",
"s",
"content",
"-",
"disposition",
"if",
"it",
"exists",
"or",
"None",
"."
] | def get_content_disposition(self):
"""Return the message's content-disposition if it exists, or None.
The return values can be either 'inline', 'attachment' or None
according to the rfc2183.
"""
value = self.get('content-disposition')
if value is None:
return None
c_d = _splitparam(value)[0].lower()
return c_d | [
"def",
"get_content_disposition",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"get",
"(",
"'content-disposition'",
")",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"c_d",
"=",
"_splitparam",
"(",
"value",
")",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"return",
"c_d"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/message.py#L929-L939 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/client/timeline.py | python | _TensorTracker.__init__ | (self, name, object_id, timestamp, pid, allocator, num_bytes) | Creates an object to track tensor references.
This class is not thread safe and is intended only for internal use by
the 'Timeline' class in this file.
Args:
name: The name of the Tensor as a string.
object_id: Chrome Trace object identifier assigned for this Tensor.
timestamp: The creation timestamp of this event as a long integer.
pid: Process identifier of the assicaiated device, as an integer.
allocator: Name of the allocator used to create the Tensor.
num_bytes: Number of bytes allocated (long integer).
Returns:
A 'TensorTracker' object. | Creates an object to track tensor references. | [
"Creates",
"an",
"object",
"to",
"track",
"tensor",
"references",
"."
] | def __init__(self, name, object_id, timestamp, pid, allocator, num_bytes):
"""Creates an object to track tensor references.
This class is not thread safe and is intended only for internal use by
the 'Timeline' class in this file.
Args:
name: The name of the Tensor as a string.
object_id: Chrome Trace object identifier assigned for this Tensor.
timestamp: The creation timestamp of this event as a long integer.
pid: Process identifier of the assicaiated device, as an integer.
allocator: Name of the allocator used to create the Tensor.
num_bytes: Number of bytes allocated (long integer).
Returns:
A 'TensorTracker' object.
"""
self._name = name
self._pid = pid
self._object_id = object_id
self._create_time = timestamp
self._allocator = allocator
self._num_bytes = num_bytes
self._ref_times = []
self._unref_times = [] | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"object_id",
",",
"timestamp",
",",
"pid",
",",
"allocator",
",",
"num_bytes",
")",
":",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_pid",
"=",
"pid",
"self",
".",
"_object_id",
"=",
"object_id",
"self",
".",
"_create_time",
"=",
"timestamp",
"self",
".",
"_allocator",
"=",
"allocator",
"self",
".",
"_num_bytes",
"=",
"num_bytes",
"self",
".",
"_ref_times",
"=",
"[",
"]",
"self",
".",
"_unref_times",
"=",
"[",
"]"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/client/timeline.py#L267-L291 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/__init__.py | python | Process.name | (self) | return name | The process name. The return value is cached after first call. | The process name. The return value is cached after first call. | [
"The",
"process",
"name",
".",
"The",
"return",
"value",
"is",
"cached",
"after",
"first",
"call",
"."
] | def name(self):
"""The process name. The return value is cached after first call."""
# Process name is only cached on Windows as on POSIX it may
# change, see:
# https://github.com/giampaolo/psutil/issues/692
if WINDOWS and self._name is not None:
return self._name
name = self._proc.name()
if POSIX and len(name) >= 15:
# On UNIX the name gets truncated to the first 15 characters.
# If it matches the first part of the cmdline we return that
# one instead because it's usually more explicative.
# Examples are "gnome-keyring-d" vs. "gnome-keyring-daemon".
try:
cmdline = self.cmdline()
except AccessDenied:
pass
else:
if cmdline:
extended_name = os.path.basename(cmdline[0])
if extended_name.startswith(name):
name = extended_name
self._name = name
self._proc._name = name
return name | [
"def",
"name",
"(",
"self",
")",
":",
"# Process name is only cached on Windows as on POSIX it may",
"# change, see:",
"# https://github.com/giampaolo/psutil/issues/692",
"if",
"WINDOWS",
"and",
"self",
".",
"_name",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_name",
"name",
"=",
"self",
".",
"_proc",
".",
"name",
"(",
")",
"if",
"POSIX",
"and",
"len",
"(",
"name",
")",
">=",
"15",
":",
"# On UNIX the name gets truncated to the first 15 characters.",
"# If it matches the first part of the cmdline we return that",
"# one instead because it's usually more explicative.",
"# Examples are \"gnome-keyring-d\" vs. \"gnome-keyring-daemon\".",
"try",
":",
"cmdline",
"=",
"self",
".",
"cmdline",
"(",
")",
"except",
"AccessDenied",
":",
"pass",
"else",
":",
"if",
"cmdline",
":",
"extended_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"cmdline",
"[",
"0",
"]",
")",
"if",
"extended_name",
".",
"startswith",
"(",
"name",
")",
":",
"name",
"=",
"extended_name",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_proc",
".",
"_name",
"=",
"name",
"return",
"name"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/__init__.py#L623-L647 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | Region.XorRect | (*args, **kwargs) | return _gdi_.Region_XorRect(*args, **kwargs) | XorRect(self, Rect rect) -> bool | XorRect(self, Rect rect) -> bool | [
"XorRect",
"(",
"self",
"Rect",
"rect",
")",
"-",
">",
"bool"
] | def XorRect(*args, **kwargs):
"""XorRect(self, Rect rect) -> bool"""
return _gdi_.Region_XorRect(*args, **kwargs) | [
"def",
"XorRect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Region_XorRect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L1623-L1625 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/polynomial/legendre.py | python | legder | (cs, m=1, scl=1) | Differentiate a Legendre series.
Returns the series `cs` differentiated `m` times. At each iteration the
result is multiplied by `scl` (the scaling factor is for use in a linear
change of variable). The argument `cs` is the sequence of coefficients
from lowest order "term" to highest, e.g., [1,2,3] represents the series
``P_0 + 2*P_1 + 3*P_2``.
Parameters
----------
cs : array_like
1-D array of Legendre series coefficients ordered from low to high.
m : int, optional
Number of derivatives taken, must be non-negative. (Default: 1)
scl : scalar, optional
Each differentiation is multiplied by `scl`. The end result is
multiplication by ``scl**m``. This is for use in a linear change of
variable. (Default: 1)
Returns
-------
der : ndarray
Legendre series of the derivative.
See Also
--------
legint
Notes
-----
In general, the result of differentiating a Legendre series does not
resemble the same operation on a power series. Thus the result of this
function may be "un-intuitive," albeit correct; see Examples section
below.
Examples
--------
>>> from numpy.polynomial import legendre as L
>>> cs = (1,2,3,4)
>>> L.legder(cs)
array([ 6., 9., 20.])
>>> L.legder(cs,3)
array([ 60.])
>>> L.legder(cs,scl=-1)
array([ -6., -9., -20.])
>>> L.legder(cs,2,-1)
array([ 9., 60.]) | Differentiate a Legendre series. | [
"Differentiate",
"a",
"Legendre",
"series",
"."
] | def legder(cs, m=1, scl=1) :
"""
Differentiate a Legendre series.
Returns the series `cs` differentiated `m` times. At each iteration the
result is multiplied by `scl` (the scaling factor is for use in a linear
change of variable). The argument `cs` is the sequence of coefficients
from lowest order "term" to highest, e.g., [1,2,3] represents the series
``P_0 + 2*P_1 + 3*P_2``.
Parameters
----------
cs : array_like
1-D array of Legendre series coefficients ordered from low to high.
m : int, optional
Number of derivatives taken, must be non-negative. (Default: 1)
scl : scalar, optional
Each differentiation is multiplied by `scl`. The end result is
multiplication by ``scl**m``. This is for use in a linear change of
variable. (Default: 1)
Returns
-------
der : ndarray
Legendre series of the derivative.
See Also
--------
legint
Notes
-----
In general, the result of differentiating a Legendre series does not
resemble the same operation on a power series. Thus the result of this
function may be "un-intuitive," albeit correct; see Examples section
below.
Examples
--------
>>> from numpy.polynomial import legendre as L
>>> cs = (1,2,3,4)
>>> L.legder(cs)
array([ 6., 9., 20.])
>>> L.legder(cs,3)
array([ 60.])
>>> L.legder(cs,scl=-1)
array([ -6., -9., -20.])
>>> L.legder(cs,2,-1)
array([ 9., 60.])
"""
cnt = int(m)
if cnt != m:
raise ValueError, "The order of derivation must be integer"
if cnt < 0 :
raise ValueError, "The order of derivation must be non-negative"
# cs is a trimmed copy
[cs] = pu.as_series([cs])
if cnt == 0:
return cs
elif cnt >= len(cs):
return cs[:1]*0
else :
for i in range(cnt):
n = len(cs) - 1
cs *= scl
der = np.empty(n, dtype=cs.dtype)
for j in range(n, 0, -1):
der[j - 1] = (2*j - 1)*cs[j]
cs[j - 2] += cs[j]
cs = der
return cs | [
"def",
"legder",
"(",
"cs",
",",
"m",
"=",
"1",
",",
"scl",
"=",
"1",
")",
":",
"cnt",
"=",
"int",
"(",
"m",
")",
"if",
"cnt",
"!=",
"m",
":",
"raise",
"ValueError",
",",
"\"The order of derivation must be integer\"",
"if",
"cnt",
"<",
"0",
":",
"raise",
"ValueError",
",",
"\"The order of derivation must be non-negative\"",
"# cs is a trimmed copy",
"[",
"cs",
"]",
"=",
"pu",
".",
"as_series",
"(",
"[",
"cs",
"]",
")",
"if",
"cnt",
"==",
"0",
":",
"return",
"cs",
"elif",
"cnt",
">=",
"len",
"(",
"cs",
")",
":",
"return",
"cs",
"[",
":",
"1",
"]",
"*",
"0",
"else",
":",
"for",
"i",
"in",
"range",
"(",
"cnt",
")",
":",
"n",
"=",
"len",
"(",
"cs",
")",
"-",
"1",
"cs",
"*=",
"scl",
"der",
"=",
"np",
".",
"empty",
"(",
"n",
",",
"dtype",
"=",
"cs",
".",
"dtype",
")",
"for",
"j",
"in",
"range",
"(",
"n",
",",
"0",
",",
"-",
"1",
")",
":",
"der",
"[",
"j",
"-",
"1",
"]",
"=",
"(",
"2",
"*",
"j",
"-",
"1",
")",
"*",
"cs",
"[",
"j",
"]",
"cs",
"[",
"j",
"-",
"2",
"]",
"+=",
"cs",
"[",
"j",
"]",
"cs",
"=",
"der",
"return",
"cs"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/polynomial/legendre.py#L628-L701 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/turtle.py | python | _turtle_docrevise | (docstr) | return newdocstr | To reduce docstrings from RawTurtle class for functions | To reduce docstrings from RawTurtle class for functions | [
"To",
"reduce",
"docstrings",
"from",
"RawTurtle",
"class",
"for",
"functions"
] | def _turtle_docrevise(docstr):
"""To reduce docstrings from RawTurtle class for functions
"""
import re
if docstr is None:
return None
turtlename = _CFG["exampleturtle"]
newdocstr = docstr.replace("%s." % turtlename,"")
parexp = re.compile(r' \(.+ %s\):' % turtlename)
newdocstr = parexp.sub(":", newdocstr)
return newdocstr | [
"def",
"_turtle_docrevise",
"(",
"docstr",
")",
":",
"import",
"re",
"if",
"docstr",
"is",
"None",
":",
"return",
"None",
"turtlename",
"=",
"_CFG",
"[",
"\"exampleturtle\"",
"]",
"newdocstr",
"=",
"docstr",
".",
"replace",
"(",
"\"%s.\"",
"%",
"turtlename",
",",
"\"\"",
")",
"parexp",
"=",
"re",
".",
"compile",
"(",
"r' \\(.+ %s\\):'",
"%",
"turtlename",
")",
"newdocstr",
"=",
"parexp",
".",
"sub",
"(",
"\":\"",
",",
"newdocstr",
")",
"return",
"newdocstr"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/turtle.py#L3916-L3926 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/collective_ops.py | python | broadcast_recv_v2 | (shape,
dtype,
group_size,
group_key,
instance_key,
communication_hint='auto',
timeout=0) | return gen_collective_ops.collective_bcast_recv_v2(
T=dtype,
group_size=group_size,
group_key=group_key,
instance_key=instance_key,
shape=shape,
communication_hint=communication_hint.lower(),
timeout_seconds=timeout) | Receives a broadcasts tensor, across devices.
Args:
shape: an int tensor. Shape of the tensor to be received.
dtype: Type of the tensor to be received.
group_size: an int32 tensor. One plus the number of receiving tensors, i.e.
the total number of devices participating. Each tensor must reside on a
different device.
group_key: an int32 tensor identifying the group of devices.
instance_key: an int32 tensor identifying the participating group of Ops.
communication_hint: preferred collective communication. The implementation
may fall back to another mechanism. Options include `auto`, `ring`, and
`nccl`.
timeout: If set to a non zero, set a completion timeout to detect staleness.
If the timer goes off, a DeadlineExceededError is raised.
The timeout value in seconds. This feature is experimental.
Returns:
An Op implementing the broadcast receive. | Receives a broadcasts tensor, across devices. | [
"Receives",
"a",
"broadcasts",
"tensor",
"across",
"devices",
"."
] | def broadcast_recv_v2(shape,
dtype,
group_size,
group_key,
instance_key,
communication_hint='auto',
timeout=0):
"""Receives a broadcasts tensor, across devices.
Args:
shape: an int tensor. Shape of the tensor to be received.
dtype: Type of the tensor to be received.
group_size: an int32 tensor. One plus the number of receiving tensors, i.e.
the total number of devices participating. Each tensor must reside on a
different device.
group_key: an int32 tensor identifying the group of devices.
instance_key: an int32 tensor identifying the participating group of Ops.
communication_hint: preferred collective communication. The implementation
may fall back to another mechanism. Options include `auto`, `ring`, and
`nccl`.
timeout: If set to a non zero, set a completion timeout to detect staleness.
If the timer goes off, a DeadlineExceededError is raised.
The timeout value in seconds. This feature is experimental.
Returns:
An Op implementing the broadcast receive.
"""
return gen_collective_ops.collective_bcast_recv_v2(
T=dtype,
group_size=group_size,
group_key=group_key,
instance_key=instance_key,
shape=shape,
communication_hint=communication_hint.lower(),
timeout_seconds=timeout) | [
"def",
"broadcast_recv_v2",
"(",
"shape",
",",
"dtype",
",",
"group_size",
",",
"group_key",
",",
"instance_key",
",",
"communication_hint",
"=",
"'auto'",
",",
"timeout",
"=",
"0",
")",
":",
"return",
"gen_collective_ops",
".",
"collective_bcast_recv_v2",
"(",
"T",
"=",
"dtype",
",",
"group_size",
"=",
"group_size",
",",
"group_key",
"=",
"group_key",
",",
"instance_key",
"=",
"instance_key",
",",
"shape",
"=",
"shape",
",",
"communication_hint",
"=",
"communication_hint",
".",
"lower",
"(",
")",
",",
"timeout_seconds",
"=",
"timeout",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/collective_ops.py#L366-L400 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/config.py | python | ConfigHandler._parse_file | (cls, value) | return '\n'.join(
cls._read_file(path)
for path in filepaths
if (cls._assert_local(path) or True)
and os.path.isfile(path)
) | Represents value as a string, allowing including text
from nearest files using `file:` directive.
Directive is sandboxed and won't reach anything outside
directory with setup.py.
Examples:
file: LICENSE
file: README.rst, CHANGELOG.md, src/file.txt
:param str value:
:rtype: str | Represents value as a string, allowing including text
from nearest files using `file:` directive. | [
"Represents",
"value",
"as",
"a",
"string",
"allowing",
"including",
"text",
"from",
"nearest",
"files",
"using",
"file",
":",
"directive",
"."
] | def _parse_file(cls, value):
"""Represents value as a string, allowing including text
from nearest files using `file:` directive.
Directive is sandboxed and won't reach anything outside
directory with setup.py.
Examples:
file: LICENSE
file: README.rst, CHANGELOG.md, src/file.txt
:param str value:
:rtype: str
"""
include_directive = 'file:'
if not isinstance(value, string_types):
return value
if not value.startswith(include_directive):
return value
spec = value[len(include_directive):]
filepaths = (os.path.abspath(path.strip()) for path in spec.split(','))
return '\n'.join(
cls._read_file(path)
for path in filepaths
if (cls._assert_local(path) or True)
and os.path.isfile(path)
) | [
"def",
"_parse_file",
"(",
"cls",
",",
"value",
")",
":",
"include_directive",
"=",
"'file:'",
"if",
"not",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"return",
"value",
"if",
"not",
"value",
".",
"startswith",
"(",
"include_directive",
")",
":",
"return",
"value",
"spec",
"=",
"value",
"[",
"len",
"(",
"include_directive",
")",
":",
"]",
"filepaths",
"=",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
".",
"strip",
"(",
")",
")",
"for",
"path",
"in",
"spec",
".",
"split",
"(",
"','",
")",
")",
"return",
"'\\n'",
".",
"join",
"(",
"cls",
".",
"_read_file",
"(",
"path",
")",
"for",
"path",
"in",
"filepaths",
"if",
"(",
"cls",
".",
"_assert_local",
"(",
"path",
")",
"or",
"True",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/config.py#L240-L269 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | chrome/tools/webforms_aggregator.py | python | Retriever.Run | (self) | return False | Called only once for the initial url when we do not have more urls.
Downloads the originally-specified site url, parses it and gets the links.
Returns:
True, if a registration page is found, and False otherwise. | Called only once for the initial url when we do not have more urls. | [
"Called",
"only",
"once",
"for",
"the",
"initial",
"url",
"when",
"we",
"do",
"not",
"have",
"more",
"urls",
"."
] | def Run(self):
"""Called only once for the initial url when we do not have more urls.
Downloads the originally-specified site url, parses it and gets the links.
Returns:
True, if a registration page is found, and False otherwise.
"""
if self.Download():
if not self._domain:
url_parsed = urlparse.urlparse(self._url)
self._domain = url_parsed[1]
if self._domain.startswith('www'):
self._domain = '.'.join(self._domain.split('.')[1:])
if self.ParseAndGetLinks():
return True
return False | [
"def",
"Run",
"(",
"self",
")",
":",
"if",
"self",
".",
"Download",
"(",
")",
":",
"if",
"not",
"self",
".",
"_domain",
":",
"url_parsed",
"=",
"urlparse",
".",
"urlparse",
"(",
"self",
".",
"_url",
")",
"self",
".",
"_domain",
"=",
"url_parsed",
"[",
"1",
"]",
"if",
"self",
".",
"_domain",
".",
"startswith",
"(",
"'www'",
")",
":",
"self",
".",
"_domain",
"=",
"'.'",
".",
"join",
"(",
"self",
".",
"_domain",
".",
"split",
"(",
"'.'",
")",
"[",
"1",
":",
"]",
")",
"if",
"self",
".",
"ParseAndGetLinks",
"(",
")",
":",
"return",
"True",
"return",
"False"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/chrome/tools/webforms_aggregator.py#L294-L310 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/utils/validation.py | python | check_symmetric | (array, tol=1E-10, raise_warning=True,
raise_exception=False) | return array | Make sure that array is 2D, square and symmetric.
If the array is not symmetric, then a symmetrized version is returned.
Optionally, a warning or exception is raised if the matrix is not
symmetric.
Parameters
----------
array : nd-array or sparse matrix
Input object to check / convert. Must be two-dimensional and square,
otherwise a ValueError will be raised.
tol : float
Absolute tolerance for equivalence of arrays. Default = 1E-10.
raise_warning : boolean (default=True)
If True then raise a warning if conversion is required.
raise_exception : boolean (default=False)
If True then raise an exception if array is not symmetric.
Returns
-------
array_sym : ndarray or sparse matrix
Symmetrized version of the input array, i.e. the average of array
and array.transpose(). If sparse, then duplicate entries are first
summed and zeros are eliminated. | Make sure that array is 2D, square and symmetric. | [
"Make",
"sure",
"that",
"array",
"is",
"2D",
"square",
"and",
"symmetric",
"."
] | def check_symmetric(array, tol=1E-10, raise_warning=True,
raise_exception=False):
"""Make sure that array is 2D, square and symmetric.
If the array is not symmetric, then a symmetrized version is returned.
Optionally, a warning or exception is raised if the matrix is not
symmetric.
Parameters
----------
array : nd-array or sparse matrix
Input object to check / convert. Must be two-dimensional and square,
otherwise a ValueError will be raised.
tol : float
Absolute tolerance for equivalence of arrays. Default = 1E-10.
raise_warning : boolean (default=True)
If True then raise a warning if conversion is required.
raise_exception : boolean (default=False)
If True then raise an exception if array is not symmetric.
Returns
-------
array_sym : ndarray or sparse matrix
Symmetrized version of the input array, i.e. the average of array
and array.transpose(). If sparse, then duplicate entries are first
summed and zeros are eliminated.
"""
if (array.ndim != 2) or (array.shape[0] != array.shape[1]):
raise ValueError("array must be 2-dimensional and square. "
"shape = {0}".format(array.shape))
if sp.issparse(array):
diff = array - array.T
# only csr, csc, and coo have `data` attribute
if diff.format not in ['csr', 'csc', 'coo']:
diff = diff.tocsr()
symmetric = np.all(abs(diff.data) < tol)
else:
symmetric = np.allclose(array, array.T, atol=tol)
if not symmetric:
if raise_exception:
raise ValueError("Array must be symmetric")
if raise_warning:
warnings.warn("Array is not symmetric, and will be converted "
"to symmetric by average with its transpose.")
if sp.issparse(array):
conversion = 'to' + array.format
array = getattr(0.5 * (array + array.T), conversion)()
else:
array = 0.5 * (array + array.T)
return array | [
"def",
"check_symmetric",
"(",
"array",
",",
"tol",
"=",
"1E-10",
",",
"raise_warning",
"=",
"True",
",",
"raise_exception",
"=",
"False",
")",
":",
"if",
"(",
"array",
".",
"ndim",
"!=",
"2",
")",
"or",
"(",
"array",
".",
"shape",
"[",
"0",
"]",
"!=",
"array",
".",
"shape",
"[",
"1",
"]",
")",
":",
"raise",
"ValueError",
"(",
"\"array must be 2-dimensional and square. \"",
"\"shape = {0}\"",
".",
"format",
"(",
"array",
".",
"shape",
")",
")",
"if",
"sp",
".",
"issparse",
"(",
"array",
")",
":",
"diff",
"=",
"array",
"-",
"array",
".",
"T",
"# only csr, csc, and coo have `data` attribute",
"if",
"diff",
".",
"format",
"not",
"in",
"[",
"'csr'",
",",
"'csc'",
",",
"'coo'",
"]",
":",
"diff",
"=",
"diff",
".",
"tocsr",
"(",
")",
"symmetric",
"=",
"np",
".",
"all",
"(",
"abs",
"(",
"diff",
".",
"data",
")",
"<",
"tol",
")",
"else",
":",
"symmetric",
"=",
"np",
".",
"allclose",
"(",
"array",
",",
"array",
".",
"T",
",",
"atol",
"=",
"tol",
")",
"if",
"not",
"symmetric",
":",
"if",
"raise_exception",
":",
"raise",
"ValueError",
"(",
"\"Array must be symmetric\"",
")",
"if",
"raise_warning",
":",
"warnings",
".",
"warn",
"(",
"\"Array is not symmetric, and will be converted \"",
"\"to symmetric by average with its transpose.\"",
")",
"if",
"sp",
".",
"issparse",
"(",
"array",
")",
":",
"conversion",
"=",
"'to'",
"+",
"array",
".",
"format",
"array",
"=",
"getattr",
"(",
"0.5",
"*",
"(",
"array",
"+",
"array",
".",
"T",
")",
",",
"conversion",
")",
"(",
")",
"else",
":",
"array",
"=",
"0.5",
"*",
"(",
"array",
"+",
"array",
".",
"T",
")",
"return",
"array"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/utils/validation.py#L596-L648 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/io/pytables.py | python | WORMTable.write | (self, **kwargs) | write in a format that we can search later on (but cannot append
to): write out the indices and the values using _write_array
(e.g. a CArray) create an indexing table so that we can search | write in a format that we can search later on (but cannot append
to): write out the indices and the values using _write_array
(e.g. a CArray) create an indexing table so that we can search | [
"write",
"in",
"a",
"format",
"that",
"we",
"can",
"search",
"later",
"on",
"(",
"but",
"cannot",
"append",
"to",
")",
":",
"write",
"out",
"the",
"indices",
"and",
"the",
"values",
"using",
"_write_array",
"(",
"e",
".",
"g",
".",
"a",
"CArray",
")",
"create",
"an",
"indexing",
"table",
"so",
"that",
"we",
"can",
"search"
] | def write(self, **kwargs):
"""
write in a format that we can search later on (but cannot append
to): write out the indices and the values using _write_array
(e.g. a CArray) create an indexing table so that we can search
"""
raise NotImplementedError("WORMTable needs to implement write") | [
"def",
"write",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"WORMTable needs to implement write\"",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/pytables.py#L4259-L4265 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/richtext.py | python | RichTextBuffer.SaveFile | (*args, **kwargs) | return _richtext.RichTextBuffer_SaveFile(*args, **kwargs) | SaveFile(self, String filename, int type=RICHTEXT_TYPE_ANY) -> bool | SaveFile(self, String filename, int type=RICHTEXT_TYPE_ANY) -> bool | [
"SaveFile",
"(",
"self",
"String",
"filename",
"int",
"type",
"=",
"RICHTEXT_TYPE_ANY",
")",
"-",
">",
"bool"
] | def SaveFile(*args, **kwargs):
"""SaveFile(self, String filename, int type=RICHTEXT_TYPE_ANY) -> bool"""
return _richtext.RichTextBuffer_SaveFile(*args, **kwargs) | [
"def",
"SaveFile",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextBuffer_SaveFile",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L2249-L2251 | |
netease-youdao/hex | d7b8773dae8dde63f3807cef1d48c017077db727 | tools/file_util.py | python | copy_files | (src_glob, dst_folder, quiet = True) | Copy multiple files. | Copy multiple files. | [
"Copy",
"multiple",
"files",
"."
] | def copy_files(src_glob, dst_folder, quiet = True):
""" Copy multiple files. """
for fname in iglob(src_glob):
dst = os.path.join(dst_folder, os.path.basename(fname))
if os.path.isdir(fname):
copy_dir(fname, dst, quiet)
else:
copy_file(fname, dst, quiet) | [
"def",
"copy_files",
"(",
"src_glob",
",",
"dst_folder",
",",
"quiet",
"=",
"True",
")",
":",
"for",
"fname",
"in",
"iglob",
"(",
"src_glob",
")",
":",
"dst",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dst_folder",
",",
"os",
".",
"path",
".",
"basename",
"(",
"fname",
")",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"fname",
")",
":",
"copy_dir",
"(",
"fname",
",",
"dst",
",",
"quiet",
")",
"else",
":",
"copy_file",
"(",
"fname",
",",
"dst",
",",
"quiet",
")"
] | https://github.com/netease-youdao/hex/blob/d7b8773dae8dde63f3807cef1d48c017077db727/tools/file_util.py#L77-L84 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/feature_extraction/_hash.py | python | _iteritems | (d) | return d.iteritems() if hasattr(d, "iteritems") else d.items() | Like d.iteritems, but accepts any collections.Mapping. | Like d.iteritems, but accepts any collections.Mapping. | [
"Like",
"d",
".",
"iteritems",
"but",
"accepts",
"any",
"collections",
".",
"Mapping",
"."
] | def _iteritems(d):
"""Like d.iteritems, but accepts any collections.Mapping."""
return d.iteritems() if hasattr(d, "iteritems") else d.items() | [
"def",
"_iteritems",
"(",
"d",
")",
":",
"return",
"d",
".",
"iteritems",
"(",
")",
"if",
"hasattr",
"(",
"d",
",",
"\"iteritems\"",
")",
"else",
"d",
".",
"items",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/feature_extraction/_hash.py#L22-L24 | |
0vercl0k/blazefox | 0ffeddfc1de3acb2254c505388e4cf9ab9d1f0a7 | src/js/builtin/intl/make_intl_data.py | python | readICUTimeZonesFromTimezoneTypes | (icuTzDir) | return (zones, links) | Read the ICU time zone information from `icuTzDir`/timezoneTypes.txt
and returns the tuple (zones, links). | Read the ICU time zone information from `icuTzDir`/timezoneTypes.txt
and returns the tuple (zones, links). | [
"Read",
"the",
"ICU",
"time",
"zone",
"information",
"from",
"icuTzDir",
"/",
"timezoneTypes",
".",
"txt",
"and",
"returns",
"the",
"tuple",
"(",
"zones",
"links",
")",
"."
] | def readICUTimeZonesFromTimezoneTypes(icuTzDir):
""" Read the ICU time zone information from `icuTzDir`/timezoneTypes.txt
and returns the tuple (zones, links).
"""
typeMapTimeZoneKey = "timezoneTypes:table(nofallback)|typeMap|timezone|"
typeAliasTimeZoneKey = "timezoneTypes:table(nofallback)|typeAlias|timezone|"
def toTimeZone(name): return Zone(name.replace(":", "/"))
zones = set()
links = dict()
for name, value in readICUResourceFile(os.path.join(icuTzDir, "timezoneTypes.txt")):
if name.startswith(typeMapTimeZoneKey):
zones.add(toTimeZone(name[len(typeMapTimeZoneKey):]))
if name.startswith(typeAliasTimeZoneKey):
links[toTimeZone(name[len(typeAliasTimeZoneKey):])] = value
# Remove the ICU placeholder time zone "Etc/Unknown".
zones.remove(Zone("Etc/Unknown"))
# tzdata2017c removed the link Canada/East-Saskatchewan -> America/Regina,
# but it is still present in ICU sources. Manually remove it to keep our
# tables consistent with IANA.
del links[Zone("Canada/East-Saskatchewan")]
validateTimeZones(zones, links)
return (zones, links) | [
"def",
"readICUTimeZonesFromTimezoneTypes",
"(",
"icuTzDir",
")",
":",
"typeMapTimeZoneKey",
"=",
"\"timezoneTypes:table(nofallback)|typeMap|timezone|\"",
"typeAliasTimeZoneKey",
"=",
"\"timezoneTypes:table(nofallback)|typeAlias|timezone|\"",
"def",
"toTimeZone",
"(",
"name",
")",
":",
"return",
"Zone",
"(",
"name",
".",
"replace",
"(",
"\":\"",
",",
"\"/\"",
")",
")",
"zones",
"=",
"set",
"(",
")",
"links",
"=",
"dict",
"(",
")",
"for",
"name",
",",
"value",
"in",
"readICUResourceFile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"icuTzDir",
",",
"\"timezoneTypes.txt\"",
")",
")",
":",
"if",
"name",
".",
"startswith",
"(",
"typeMapTimeZoneKey",
")",
":",
"zones",
".",
"add",
"(",
"toTimeZone",
"(",
"name",
"[",
"len",
"(",
"typeMapTimeZoneKey",
")",
":",
"]",
")",
")",
"if",
"name",
".",
"startswith",
"(",
"typeAliasTimeZoneKey",
")",
":",
"links",
"[",
"toTimeZone",
"(",
"name",
"[",
"len",
"(",
"typeAliasTimeZoneKey",
")",
":",
"]",
")",
"]",
"=",
"value",
"# Remove the ICU placeholder time zone \"Etc/Unknown\".",
"zones",
".",
"remove",
"(",
"Zone",
"(",
"\"Etc/Unknown\"",
")",
")",
"# tzdata2017c removed the link Canada/East-Saskatchewan -> America/Regina,",
"# but it is still present in ICU sources. Manually remove it to keep our",
"# tables consistent with IANA.",
"del",
"links",
"[",
"Zone",
"(",
"\"Canada/East-Saskatchewan\"",
")",
"]",
"validateTimeZones",
"(",
"zones",
",",
"links",
")",
"return",
"(",
"zones",
",",
"links",
")"
] | https://github.com/0vercl0k/blazefox/blob/0ffeddfc1de3acb2254c505388e4cf9ab9d1f0a7/src/js/builtin/intl/make_intl_data.py#L821-L849 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.