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
sequence | function
stringlengths 34
151k
| function_tokens
sequence | url
stringlengths 90
278
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/ir.py | python | FunctionIR.derive | (self, blocks, arg_count=None, arg_names=None,
force_non_generator=False) | return new_ir | Derive a new function IR from this one, using the given blocks,
and possibly modifying the argument count and generator flag.
Post-processing will have to be run again on the new IR. | Derive a new function IR from this one, using the given blocks,
and possibly modifying the argument count and generator flag. | [
"Derive",
"a",
"new",
"function",
"IR",
"from",
"this",
"one",
"using",
"the",
"given",
"blocks",
"and",
"possibly",
"modifying",
"the",
"argument",
"count",
"and",
"generator",
"flag",
"."
] | def derive(self, blocks, arg_count=None, arg_names=None,
force_non_generator=False):
"""
Derive a new function IR from this one, using the given blocks,
and possibly modifying the argument count and generator flag.
Post-processing will have to be run again on the new IR.
"""
firstblock = blocks[min(blocks)]
new_ir = copy.copy(self)
new_ir.blocks = blocks
new_ir.loc = firstblock.loc
if force_non_generator:
new_ir.is_generator = False
if arg_count is not None:
new_ir.arg_count = arg_count
if arg_names is not None:
new_ir.arg_names = arg_names
new_ir._reset_analysis_variables()
# Make fresh func_id
new_ir.func_id = new_ir.func_id.derive()
return new_ir | [
"def",
"derive",
"(",
"self",
",",
"blocks",
",",
"arg_count",
"=",
"None",
",",
"arg_names",
"=",
"None",
",",
"force_non_generator",
"=",
"False",
")",
":",
"firstblock",
"=",
"blocks",
"[",
"min",
"(",
"blocks",
")",
"]",
"new_ir",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"new_ir",
".",
"blocks",
"=",
"blocks",
"new_ir",
".",
"loc",
"=",
"firstblock",
".",
"loc",
"if",
"force_non_generator",
":",
"new_ir",
".",
"is_generator",
"=",
"False",
"if",
"arg_count",
"is",
"not",
"None",
":",
"new_ir",
".",
"arg_count",
"=",
"arg_count",
"if",
"arg_names",
"is",
"not",
"None",
":",
"new_ir",
".",
"arg_names",
"=",
"arg_names",
"new_ir",
".",
"_reset_analysis_variables",
"(",
")",
"# Make fresh func_id",
"new_ir",
".",
"func_id",
"=",
"new_ir",
".",
"func_id",
".",
"derive",
"(",
")",
"return",
"new_ir"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/ir.py#L1350-L1372 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/datamodel/models.py | python | DataModel.traverse_models | (self) | return [self._dmm[t] for t in self.traverse_types()] | Recursively list all models involved in this model. | Recursively list all models involved in this model. | [
"Recursively",
"list",
"all",
"models",
"involved",
"in",
"this",
"model",
"."
] | def traverse_models(self):
"""
Recursively list all models involved in this model.
"""
return [self._dmm[t] for t in self.traverse_types()] | [
"def",
"traverse_models",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"_dmm",
"[",
"t",
"]",
"for",
"t",
"in",
"self",
".",
"traverse_types",
"(",
")",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/datamodel/models.py#L97-L101 |
|
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/distribute/distribute_coordinator_context.py | python | get_current_worker_context | () | Returns the current task context. | Returns the current task context. | [
"Returns",
"the",
"current",
"task",
"context",
"."
] | def get_current_worker_context():
"""Returns the current task context."""
try:
return _worker_context.current
except AttributeError:
return None | [
"def",
"get_current_worker_context",
"(",
")",
":",
"try",
":",
"return",
"_worker_context",
".",
"current",
"except",
"AttributeError",
":",
"return",
"None"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/distribute_coordinator_context.py#L22-L27 |
||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/rdatatype.py | python | to_text | (value) | return text | Convert a DNS rdata type to text.
@param value: the rdata type value
@type value: int
@raises ValueError: the rdata type value is not >= 0 and <= 65535
@rtype: string | Convert a DNS rdata type to text. | [
"Convert",
"a",
"DNS",
"rdata",
"type",
"to",
"text",
"."
] | def to_text(value):
"""Convert a DNS rdata type to text.
@param value: the rdata type value
@type value: int
@raises ValueError: the rdata type value is not >= 0 and <= 65535
@rtype: string"""
if value < 0 or value > 65535:
raise ValueError("type must be between >= 0 and <= 65535")
text = _by_value.get(value)
if text is None:
text = 'TYPE' + `value`
return text | [
"def",
"to_text",
"(",
"value",
")",
":",
"if",
"value",
"<",
"0",
"or",
"value",
">",
"65535",
":",
"raise",
"ValueError",
"(",
"\"type must be between >= 0 and <= 65535\"",
")",
"text",
"=",
"_by_value",
".",
"get",
"(",
"value",
")",
"if",
"text",
"is",
"None",
":",
"text",
"=",
"'TYPE'",
"+",
"`value`",
"return",
"text"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/rdatatype.py#L200-L212 |
|
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | python/mxnet/ndarray/ndarray.py | python | NDArray.argmax_channel | (self, *args, **kwargs) | return op.argmax_channel(self, *args, **kwargs) | Convenience fluent method for :py:func:`argmax_channel`.
The arguments are the same as for :py:func:`argmax_channel`, with
this array as data. | Convenience fluent method for :py:func:`argmax_channel`. | [
"Convenience",
"fluent",
"method",
"for",
":",
"py",
":",
"func",
":",
"argmax_channel",
"."
] | def argmax_channel(self, *args, **kwargs):
"""Convenience fluent method for :py:func:`argmax_channel`.
The arguments are the same as for :py:func:`argmax_channel`, with
this array as data.
"""
return op.argmax_channel(self, *args, **kwargs) | [
"def",
"argmax_channel",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"op",
".",
"argmax_channel",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/ndarray/ndarray.py#L1116-L1122 |
|
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/PyShell.py | python | extended_linecache_checkcache | (filename=None,
orig_checkcache=linecache.checkcache) | Extend linecache.checkcache to preserve the <pyshell#...> entries
Rather than repeating the linecache code, patch it to save the
<pyshell#...> entries, call the original linecache.checkcache()
(skipping them), and then restore the saved entries.
orig_checkcache is bound at definition time to the original
method, allowing it to be patched. | Extend linecache.checkcache to preserve the <pyshell#...> entries | [
"Extend",
"linecache",
".",
"checkcache",
"to",
"preserve",
"the",
"<pyshell#",
"...",
">",
"entries"
] | def extended_linecache_checkcache(filename=None,
orig_checkcache=linecache.checkcache):
"""Extend linecache.checkcache to preserve the <pyshell#...> entries
Rather than repeating the linecache code, patch it to save the
<pyshell#...> entries, call the original linecache.checkcache()
(skipping them), and then restore the saved entries.
orig_checkcache is bound at definition time to the original
method, allowing it to be patched.
"""
cache = linecache.cache
save = {}
for key in list(cache):
if key[:1] + key[-1:] == '<>':
save[key] = cache.pop(key)
orig_checkcache(filename)
cache.update(save) | [
"def",
"extended_linecache_checkcache",
"(",
"filename",
"=",
"None",
",",
"orig_checkcache",
"=",
"linecache",
".",
"checkcache",
")",
":",
"cache",
"=",
"linecache",
".",
"cache",
"save",
"=",
"{",
"}",
"for",
"key",
"in",
"list",
"(",
"cache",
")",
":",
"if",
"key",
"[",
":",
"1",
"]",
"+",
"key",
"[",
"-",
"1",
":",
"]",
"==",
"'<>'",
":",
"save",
"[",
"key",
"]",
"=",
"cache",
".",
"pop",
"(",
"key",
")",
"orig_checkcache",
"(",
"filename",
")",
"cache",
".",
"update",
"(",
"save",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/PyShell.py#L83-L100 |
||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/calendar.py | python | TextCalendar.formatweek | (self, theweek, width) | return ' '.join(self.formatday(d, wd, width) for (d, wd) in theweek) | Returns a single week in a string (no newline). | Returns a single week in a string (no newline). | [
"Returns",
"a",
"single",
"week",
"in",
"a",
"string",
"(",
"no",
"newline",
")",
"."
] | def formatweek(self, theweek, width):
"""
Returns a single week in a string (no newline).
"""
return ' '.join(self.formatday(d, wd, width) for (d, wd) in theweek) | [
"def",
"formatweek",
"(",
"self",
",",
"theweek",
",",
"width",
")",
":",
"return",
"' '",
".",
"join",
"(",
"self",
".",
"formatday",
"(",
"d",
",",
"wd",
",",
"width",
")",
"for",
"(",
"d",
",",
"wd",
")",
"in",
"theweek",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/calendar.py#L277-L281 |
|
carla-simulator/carla | 8854804f4d7748e14d937ec763a2912823a7e5f5 | Co-Simulation/Sumo/sumo_integration/bridge_helper.py | python | BridgeHelper.get_carla_lights_state | (current_carla_lights, sumo_lights) | return current_lights | Returns carla vehicle light state based on sumo signals. | Returns carla vehicle light state based on sumo signals. | [
"Returns",
"carla",
"vehicle",
"light",
"state",
"based",
"on",
"sumo",
"signals",
"."
] | def get_carla_lights_state(current_carla_lights, sumo_lights):
"""
Returns carla vehicle light state based on sumo signals.
"""
current_lights = current_carla_lights
# Blinker right / emergency.
if (any([
bool(sumo_lights & SumoVehSignal.BLINKER_RIGHT),
bool(sumo_lights & SumoVehSignal.BLINKER_EMERGENCY)
]) != bool(current_lights & carla.VehicleLightState.RightBlinker)):
current_lights ^= carla.VehicleLightState.RightBlinker
# Blinker left / emergency.
if (any([
bool(sumo_lights & SumoVehSignal.BLINKER_LEFT),
bool(sumo_lights & SumoVehSignal.BLINKER_EMERGENCY)
]) != bool(current_lights & carla.VehicleLightState.LeftBlinker)):
current_lights ^= carla.VehicleLightState.LeftBlinker
# Break.
if (bool(sumo_lights & SumoVehSignal.BRAKELIGHT) !=
bool(current_lights & carla.VehicleLightState.Brake)):
current_lights ^= carla.VehicleLightState.Brake
# Front (low beam).
if (bool(sumo_lights & SumoVehSignal.FRONTLIGHT) !=
bool(current_lights & carla.VehicleLightState.LowBeam)):
current_lights ^= carla.VehicleLightState.LowBeam
# Fog.
if (bool(sumo_lights & SumoVehSignal.FOGLIGHT) !=
bool(current_lights & carla.VehicleLightState.Fog)):
current_lights ^= carla.VehicleLightState.Fog
# High beam.
if (bool(sumo_lights & SumoVehSignal.HIGHBEAM) !=
bool(current_lights & carla.VehicleLightState.HighBeam)):
current_lights ^= carla.VehicleLightState.HighBeam
# Backdrive (reverse).
if (bool(sumo_lights & SumoVehSignal.BACKDRIVE) !=
bool(current_lights & carla.VehicleLightState.Reverse)):
current_lights ^= carla.VehicleLightState.Reverse
# Door open left/right.
if (any([
bool(sumo_lights & SumoVehSignal.DOOR_OPEN_LEFT),
bool(sumo_lights & SumoVehSignal.DOOR_OPEN_RIGHT)
]) != bool(current_lights & carla.VehicleLightState.Position)):
current_lights ^= carla.VehicleLightState.Position
return current_lights | [
"def",
"get_carla_lights_state",
"(",
"current_carla_lights",
",",
"sumo_lights",
")",
":",
"current_lights",
"=",
"current_carla_lights",
"# Blinker right / emergency.",
"if",
"(",
"any",
"(",
"[",
"bool",
"(",
"sumo_lights",
"&",
"SumoVehSignal",
".",
"BLINKER_RIGHT",
")",
",",
"bool",
"(",
"sumo_lights",
"&",
"SumoVehSignal",
".",
"BLINKER_EMERGENCY",
")",
"]",
")",
"!=",
"bool",
"(",
"current_lights",
"&",
"carla",
".",
"VehicleLightState",
".",
"RightBlinker",
")",
")",
":",
"current_lights",
"^=",
"carla",
".",
"VehicleLightState",
".",
"RightBlinker",
"# Blinker left / emergency.",
"if",
"(",
"any",
"(",
"[",
"bool",
"(",
"sumo_lights",
"&",
"SumoVehSignal",
".",
"BLINKER_LEFT",
")",
",",
"bool",
"(",
"sumo_lights",
"&",
"SumoVehSignal",
".",
"BLINKER_EMERGENCY",
")",
"]",
")",
"!=",
"bool",
"(",
"current_lights",
"&",
"carla",
".",
"VehicleLightState",
".",
"LeftBlinker",
")",
")",
":",
"current_lights",
"^=",
"carla",
".",
"VehicleLightState",
".",
"LeftBlinker",
"# Break.",
"if",
"(",
"bool",
"(",
"sumo_lights",
"&",
"SumoVehSignal",
".",
"BRAKELIGHT",
")",
"!=",
"bool",
"(",
"current_lights",
"&",
"carla",
".",
"VehicleLightState",
".",
"Brake",
")",
")",
":",
"current_lights",
"^=",
"carla",
".",
"VehicleLightState",
".",
"Brake",
"# Front (low beam).",
"if",
"(",
"bool",
"(",
"sumo_lights",
"&",
"SumoVehSignal",
".",
"FRONTLIGHT",
")",
"!=",
"bool",
"(",
"current_lights",
"&",
"carla",
".",
"VehicleLightState",
".",
"LowBeam",
")",
")",
":",
"current_lights",
"^=",
"carla",
".",
"VehicleLightState",
".",
"LowBeam",
"# Fog.",
"if",
"(",
"bool",
"(",
"sumo_lights",
"&",
"SumoVehSignal",
".",
"FOGLIGHT",
")",
"!=",
"bool",
"(",
"current_lights",
"&",
"carla",
".",
"VehicleLightState",
".",
"Fog",
")",
")",
":",
"current_lights",
"^=",
"carla",
".",
"VehicleLightState",
".",
"Fog",
"# High beam.",
"if",
"(",
"bool",
"(",
"sumo_lights",
"&",
"SumoVehSignal",
".",
"HIGHBEAM",
")",
"!=",
"bool",
"(",
"current_lights",
"&",
"carla",
".",
"VehicleLightState",
".",
"HighBeam",
")",
")",
":",
"current_lights",
"^=",
"carla",
".",
"VehicleLightState",
".",
"HighBeam",
"# Backdrive (reverse).",
"if",
"(",
"bool",
"(",
"sumo_lights",
"&",
"SumoVehSignal",
".",
"BACKDRIVE",
")",
"!=",
"bool",
"(",
"current_lights",
"&",
"carla",
".",
"VehicleLightState",
".",
"Reverse",
")",
")",
":",
"current_lights",
"^=",
"carla",
".",
"VehicleLightState",
".",
"Reverse",
"# Door open left/right.",
"if",
"(",
"any",
"(",
"[",
"bool",
"(",
"sumo_lights",
"&",
"SumoVehSignal",
".",
"DOOR_OPEN_LEFT",
")",
",",
"bool",
"(",
"sumo_lights",
"&",
"SumoVehSignal",
".",
"DOOR_OPEN_RIGHT",
")",
"]",
")",
"!=",
"bool",
"(",
"current_lights",
"&",
"carla",
".",
"VehicleLightState",
".",
"Position",
")",
")",
":",
"current_lights",
"^=",
"carla",
".",
"VehicleLightState",
".",
"Position",
"return",
"current_lights"
] | https://github.com/carla-simulator/carla/blob/8854804f4d7748e14d937ec763a2912823a7e5f5/Co-Simulation/Sumo/sumo_integration/bridge_helper.py#L228-L280 |
|
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/timeseries/python/timeseries/state_space_models/state_space_model.py | python | StateSpaceModel.get_prior_covariance | (self) | Constructs a variable prior covariance with data-based initialization.
Models should wrap any variables defined here in the model's variable scope.
Returns:
A two-dimensional [state dimension, state dimension] floating point Tensor
with a (positive definite) prior state covariance matrix. | Constructs a variable prior covariance with data-based initialization. | [
"Constructs",
"a",
"variable",
"prior",
"covariance",
"with",
"data",
"-",
"based",
"initialization",
"."
] | def get_prior_covariance(self):
"""Constructs a variable prior covariance with data-based initialization.
Models should wrap any variables defined here in the model's variable scope.
Returns:
A two-dimensional [state dimension, state dimension] floating point Tensor
with a (positive definite) prior state covariance matrix.
"""
with variable_scope.variable_scope(self._variable_scope):
state_dimension = ops.convert_to_tensor(
self.get_state_transition()).get_shape()[0].value
if self._configuration.trainable_start_state:
base_covariance = math_utils.variable_covariance_matrix(
state_dimension, "prior_state_var",
dtype=self.dtype)
else:
return linalg_ops.eye(state_dimension, dtype=self.dtype)
if self._input_statistics is not None:
# Make sure initial latent value uncertainty is at least on the same
# scale as noise in the data.
covariance_multiplier = math_ops.reduce_max(
self._input_statistics.series_start_moments.variance)
return base_covariance * gen_math_ops.maximum(
covariance_multiplier, 1.0)
else:
return base_covariance | [
"def",
"get_prior_covariance",
"(",
"self",
")",
":",
"with",
"variable_scope",
".",
"variable_scope",
"(",
"self",
".",
"_variable_scope",
")",
":",
"state_dimension",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"self",
".",
"get_state_transition",
"(",
")",
")",
".",
"get_shape",
"(",
")",
"[",
"0",
"]",
".",
"value",
"if",
"self",
".",
"_configuration",
".",
"trainable_start_state",
":",
"base_covariance",
"=",
"math_utils",
".",
"variable_covariance_matrix",
"(",
"state_dimension",
",",
"\"prior_state_var\"",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
"else",
":",
"return",
"linalg_ops",
".",
"eye",
"(",
"state_dimension",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
"if",
"self",
".",
"_input_statistics",
"is",
"not",
"None",
":",
"# Make sure initial latent value uncertainty is at least on the same",
"# scale as noise in the data.",
"covariance_multiplier",
"=",
"math_ops",
".",
"reduce_max",
"(",
"self",
".",
"_input_statistics",
".",
"series_start_moments",
".",
"variance",
")",
"return",
"base_covariance",
"*",
"gen_math_ops",
".",
"maximum",
"(",
"covariance_multiplier",
",",
"1.0",
")",
"else",
":",
"return",
"base_covariance"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/timeseries/python/timeseries/state_space_models/state_space_model.py#L703-L729 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_gdi.py | python | _wxPyInitTheBrushList | (*args) | return _gdi_._wxPyInitTheBrushList(*args) | _wxPyInitTheBrushList() -> BrushList | _wxPyInitTheBrushList() -> BrushList | [
"_wxPyInitTheBrushList",
"()",
"-",
">",
"BrushList"
] | def _wxPyInitTheBrushList(*args):
"""_wxPyInitTheBrushList() -> BrushList"""
return _gdi_._wxPyInitTheBrushList(*args) | [
"def",
"_wxPyInitTheBrushList",
"(",
"*",
"args",
")",
":",
"return",
"_gdi_",
".",
"_wxPyInitTheBrushList",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L7089-L7091 |
|
generalized-intelligence/GAAS | 29ab17d3e8a4ba18edef3a57c36d8db6329fac73 | algorithms/src/SystemManagement/json_request_response_lib/src/third_party/nlohmann_json/third_party/cpplint/cpplint.py | python | CheckSpacing | (filename, clean_lines, linenum, nesting_state, error) | Checks for the correctness of various spacing issues in the code.
Things we check for: spaces around operators, spaces after
if/for/while/switch, no spaces around parens in function calls, two
spaces between code and comment, don't start a block with a blank
line, don't end a function with a blank line, don't add a blank line
after public/protected/private, don't have too many blank lines in a row.
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: The function to call with any errors found. | Checks for the correctness of various spacing issues in the code. | [
"Checks",
"for",
"the",
"correctness",
"of",
"various",
"spacing",
"issues",
"in",
"the",
"code",
"."
] | def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
"""Checks for the correctness of various spacing issues in the code.
Things we check for: spaces around operators, spaces after
if/for/while/switch, no spaces around parens in function calls, two
spaces between code and comment, don't start a block with a blank
line, don't end a function with a blank line, don't add a blank line
after public/protected/private, don't have too many blank lines in a row.
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: The function to call with any errors found.
"""
# Don't use "elided" lines here, otherwise we can't check commented lines.
# Don't want to use "raw" either, because we don't want to check inside C++11
# raw strings,
raw = clean_lines.lines_without_raw_strings
line = raw[linenum]
# Before nixing comments, check if the line is blank for no good
# reason. This includes the first line after a block is opened, and
# blank lines at the end of a function (ie, right before a line like '}'
#
# Skip all the blank line checks if we are immediately inside a
# namespace body. In other words, don't issue blank line warnings
# for this block:
# namespace {
#
# }
#
# A warning about missing end of namespace comments will be issued instead.
#
# Also skip blank line checks for 'extern "C"' blocks, which are formatted
# like namespaces.
if (IsBlankLine(line) and
not nesting_state.InNamespaceBody() and
not nesting_state.InExternC()):
elided = clean_lines.elided
prev_line = elided[linenum - 1]
prevbrace = prev_line.rfind('{')
# TODO(unknown): Don't complain if line before blank line, and line after,
# both start with alnums and are indented the same amount.
# This ignores whitespace at the start of a namespace block
# because those are not usually indented.
if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
# OK, we have a blank line at the start of a code block. Before we
# complain, we check if it is an exception to the rule: The previous
# non-empty line has the parameters of a function header that are indented
# 4 spaces (because they did not fit in a 80 column line when placed on
# the same line as the function name). We also check for the case where
# the previous line is indented 6 spaces, which may happen when the
# initializers of a constructor do not fit into a 80 column line.
exception = False
if Match(r' {6}\w', prev_line): # Initializer list?
# We are looking for the opening column of initializer list, which
# should be indented 4 spaces to cause 6 space indentation afterwards.
search_position = linenum-2
while (search_position >= 0
and Match(r' {6}\w', elided[search_position])):
search_position -= 1
exception = (search_position >= 0
and elided[search_position][:5] == ' :')
else:
# Search for the function arguments or an initializer list. We use a
# simple heuristic here: If the line is indented 4 spaces; and we have a
# closing paren, without the opening paren, followed by an opening brace
# or colon (for initializer lists) we assume that it is the last line of
# a function header. If we have a colon indented 4 spaces, it is an
# initializer list.
exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
prev_line)
or Match(r' {4}:', prev_line))
if not exception:
error(filename, linenum, 'whitespace/blank_line', 2,
'Redundant blank line at the start of a code block '
'should be deleted.')
# Ignore blank lines at the end of a block in a long if-else
# chain, like this:
# if (condition1) {
# // Something followed by a blank line
#
# } else if (condition2) {
# // Something else
# }
if linenum + 1 < clean_lines.NumLines():
next_line = raw[linenum + 1]
if (next_line
and Match(r'\s*}', next_line)
and next_line.find('} else ') == -1):
error(filename, linenum, 'whitespace/blank_line', 3,
'Redundant blank line at the end of a code block '
'should be deleted.')
matched = Match(r'\s*(public|protected|private):', prev_line)
if matched:
error(filename, linenum, 'whitespace/blank_line', 3,
'Do not leave a blank line after "%s:"' % matched.group(1))
# Next, check comments
next_line_start = 0
if linenum + 1 < clean_lines.NumLines():
next_line = raw[linenum + 1]
next_line_start = len(next_line) - len(next_line.lstrip())
CheckComment(line, filename, linenum, next_line_start, error)
# get rid of comments and strings
line = clean_lines.elided[linenum]
# You shouldn't have spaces before your brackets, except maybe after
# 'delete []' or 'return []() {};'
if Search(r'\w\s+\[', line) and not Search(r'(?:delete|return)\s+\[', line):
error(filename, linenum, 'whitespace/braces', 5,
'Extra space before [')
# In range-based for, we wanted spaces before and after the colon, but
# not around "::" tokens that might appear.
if (Search(r'for *\(.*[^:]:[^: ]', line) or
Search(r'for *\(.*[^: ]:[^:]', line)):
error(filename, linenum, 'whitespace/forcolon', 2,
'Missing space around colon in range-based for loop') | [
"def",
"CheckSpacing",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"# Don't use \"elided\" lines here, otherwise we can't check commented lines.",
"# Don't want to use \"raw\" either, because we don't want to check inside C++11",
"# raw strings,",
"raw",
"=",
"clean_lines",
".",
"lines_without_raw_strings",
"line",
"=",
"raw",
"[",
"linenum",
"]",
"# Before nixing comments, check if the line is blank for no good",
"# reason. This includes the first line after a block is opened, and",
"# blank lines at the end of a function (ie, right before a line like '}'",
"#",
"# Skip all the blank line checks if we are immediately inside a",
"# namespace body. In other words, don't issue blank line warnings",
"# for this block:",
"# namespace {",
"#",
"# }",
"#",
"# A warning about missing end of namespace comments will be issued instead.",
"#",
"# Also skip blank line checks for 'extern \"C\"' blocks, which are formatted",
"# like namespaces.",
"if",
"(",
"IsBlankLine",
"(",
"line",
")",
"and",
"not",
"nesting_state",
".",
"InNamespaceBody",
"(",
")",
"and",
"not",
"nesting_state",
".",
"InExternC",
"(",
")",
")",
":",
"elided",
"=",
"clean_lines",
".",
"elided",
"prev_line",
"=",
"elided",
"[",
"linenum",
"-",
"1",
"]",
"prevbrace",
"=",
"prev_line",
".",
"rfind",
"(",
"'{'",
")",
"# TODO(unknown): Don't complain if line before blank line, and line after,",
"# both start with alnums and are indented the same amount.",
"# This ignores whitespace at the start of a namespace block",
"# because those are not usually indented.",
"if",
"prevbrace",
"!=",
"-",
"1",
"and",
"prev_line",
"[",
"prevbrace",
":",
"]",
".",
"find",
"(",
"'}'",
")",
"==",
"-",
"1",
":",
"# OK, we have a blank line at the start of a code block. Before we",
"# complain, we check if it is an exception to the rule: The previous",
"# non-empty line has the parameters of a function header that are indented",
"# 4 spaces (because they did not fit in a 80 column line when placed on",
"# the same line as the function name). We also check for the case where",
"# the previous line is indented 6 spaces, which may happen when the",
"# initializers of a constructor do not fit into a 80 column line.",
"exception",
"=",
"False",
"if",
"Match",
"(",
"r' {6}\\w'",
",",
"prev_line",
")",
":",
"# Initializer list?",
"# We are looking for the opening column of initializer list, which",
"# should be indented 4 spaces to cause 6 space indentation afterwards.",
"search_position",
"=",
"linenum",
"-",
"2",
"while",
"(",
"search_position",
">=",
"0",
"and",
"Match",
"(",
"r' {6}\\w'",
",",
"elided",
"[",
"search_position",
"]",
")",
")",
":",
"search_position",
"-=",
"1",
"exception",
"=",
"(",
"search_position",
">=",
"0",
"and",
"elided",
"[",
"search_position",
"]",
"[",
":",
"5",
"]",
"==",
"' :'",
")",
"else",
":",
"# Search for the function arguments or an initializer list. We use a",
"# simple heuristic here: If the line is indented 4 spaces; and we have a",
"# closing paren, without the opening paren, followed by an opening brace",
"# or colon (for initializer lists) we assume that it is the last line of",
"# a function header. If we have a colon indented 4 spaces, it is an",
"# initializer list.",
"exception",
"=",
"(",
"Match",
"(",
"r' {4}\\w[^\\(]*\\)\\s*(const\\s*)?(\\{\\s*$|:)'",
",",
"prev_line",
")",
"or",
"Match",
"(",
"r' {4}:'",
",",
"prev_line",
")",
")",
"if",
"not",
"exception",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/blank_line'",
",",
"2",
",",
"'Redundant blank line at the start of a code block '",
"'should be deleted.'",
")",
"# Ignore blank lines at the end of a block in a long if-else",
"# chain, like this:",
"# if (condition1) {",
"# // Something followed by a blank line",
"#",
"# } else if (condition2) {",
"# // Something else",
"# }",
"if",
"linenum",
"+",
"1",
"<",
"clean_lines",
".",
"NumLines",
"(",
")",
":",
"next_line",
"=",
"raw",
"[",
"linenum",
"+",
"1",
"]",
"if",
"(",
"next_line",
"and",
"Match",
"(",
"r'\\s*}'",
",",
"next_line",
")",
"and",
"next_line",
".",
"find",
"(",
"'} else '",
")",
"==",
"-",
"1",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/blank_line'",
",",
"3",
",",
"'Redundant blank line at the end of a code block '",
"'should be deleted.'",
")",
"matched",
"=",
"Match",
"(",
"r'\\s*(public|protected|private):'",
",",
"prev_line",
")",
"if",
"matched",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/blank_line'",
",",
"3",
",",
"'Do not leave a blank line after \"%s:\"'",
"%",
"matched",
".",
"group",
"(",
"1",
")",
")",
"# Next, check comments",
"next_line_start",
"=",
"0",
"if",
"linenum",
"+",
"1",
"<",
"clean_lines",
".",
"NumLines",
"(",
")",
":",
"next_line",
"=",
"raw",
"[",
"linenum",
"+",
"1",
"]",
"next_line_start",
"=",
"len",
"(",
"next_line",
")",
"-",
"len",
"(",
"next_line",
".",
"lstrip",
"(",
")",
")",
"CheckComment",
"(",
"line",
",",
"filename",
",",
"linenum",
",",
"next_line_start",
",",
"error",
")",
"# get rid of comments and strings",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# You shouldn't have spaces before your brackets, except maybe after",
"# 'delete []' or 'return []() {};'",
"if",
"Search",
"(",
"r'\\w\\s+\\['",
",",
"line",
")",
"and",
"not",
"Search",
"(",
"r'(?:delete|return)\\s+\\['",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/braces'",
",",
"5",
",",
"'Extra space before ['",
")",
"# In range-based for, we wanted spaces before and after the colon, but",
"# not around \"::\" tokens that might appear.",
"if",
"(",
"Search",
"(",
"r'for *\\(.*[^:]:[^: ]'",
",",
"line",
")",
"or",
"Search",
"(",
"r'for *\\(.*[^: ]:[^:]'",
",",
"line",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/forcolon'",
",",
"2",
",",
"'Missing space around colon in range-based for loop'",
")"
] | https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/algorithms/src/SystemManagement/json_request_response_lib/src/third_party/nlohmann_json/third_party/cpplint/cpplint.py#L3398-L3523 |
||
turi-code/SFrame | 796b9bdfb2fa1b881d82080754643c7e68629cd2 | oss_src/unity/python/sframe/data_structures/sframe.py | python | SFrame.add_columns | (self, data, namelist=None) | return self | Adds multiple columns to this SFrame. The number of elements in all
columns must match the length of every other column of the SFrame. This
operation modifies the current SFrame in place and returns self.
Parameters
----------
data : list[SArray] or SFrame
The columns to add.
namelist : list of string, optional
A list of column names. All names must be specified. ``namelist`` is
ignored if data is an SFrame.
Returns
-------
out : SFrame
The current SFrame.
See Also
--------
add_column
Examples
--------
>>> sf = graphlab.SFrame({'id': [1, 2, 3], 'val': ['A', 'B', 'C']})
>>> sf2 = graphlab.SFrame({'species': ['cat', 'dog', 'fossa'],
... 'age': [3, 5, 9]})
>>> sf.add_columns(sf2)
>>> sf
+----+-----+-----+---------+
| id | val | age | species |
+----+-----+-----+---------+
| 1 | A | 3 | cat |
| 2 | B | 5 | dog |
| 3 | C | 9 | fossa |
+----+-----+-----+---------+
[3 rows x 4 columns] | Adds multiple columns to this SFrame. The number of elements in all
columns must match the length of every other column of the SFrame. This
operation modifies the current SFrame in place and returns self. | [
"Adds",
"multiple",
"columns",
"to",
"this",
"SFrame",
".",
"The",
"number",
"of",
"elements",
"in",
"all",
"columns",
"must",
"match",
"the",
"length",
"of",
"every",
"other",
"column",
"of",
"the",
"SFrame",
".",
"This",
"operation",
"modifies",
"the",
"current",
"SFrame",
"in",
"place",
"and",
"returns",
"self",
"."
] | def add_columns(self, data, namelist=None):
"""
Adds multiple columns to this SFrame. The number of elements in all
columns must match the length of every other column of the SFrame. This
operation modifies the current SFrame in place and returns self.
Parameters
----------
data : list[SArray] or SFrame
The columns to add.
namelist : list of string, optional
A list of column names. All names must be specified. ``namelist`` is
ignored if data is an SFrame.
Returns
-------
out : SFrame
The current SFrame.
See Also
--------
add_column
Examples
--------
>>> sf = graphlab.SFrame({'id': [1, 2, 3], 'val': ['A', 'B', 'C']})
>>> sf2 = graphlab.SFrame({'species': ['cat', 'dog', 'fossa'],
... 'age': [3, 5, 9]})
>>> sf.add_columns(sf2)
>>> sf
+----+-----+-----+---------+
| id | val | age | species |
+----+-----+-----+---------+
| 1 | A | 3 | cat |
| 2 | B | 5 | dog |
| 3 | C | 9 | fossa |
+----+-----+-----+---------+
[3 rows x 4 columns]
"""
datalist = data
if isinstance(data, SFrame):
other = data
datalist = [other.select_column(name) for name in other.column_names()]
namelist = other.column_names()
my_columns = set(self.column_names())
for name in namelist:
if name in my_columns:
raise ValueError("Column '" + name + "' already exists in current SFrame")
else:
if not _is_non_string_iterable(datalist):
raise TypeError("datalist must be an iterable")
if not _is_non_string_iterable(namelist):
raise TypeError("namelist must be an iterable")
if not all([isinstance(x, SArray) for x in datalist]):
raise TypeError("Must give column as SArray")
if not all([isinstance(x, str) for x in namelist]):
raise TypeError("Invalid column name in list : must all be str")
with cython_context():
self.__proxy__.add_columns([x.__proxy__ for x in datalist], namelist)
self._cache = None
return self | [
"def",
"add_columns",
"(",
"self",
",",
"data",
",",
"namelist",
"=",
"None",
")",
":",
"datalist",
"=",
"data",
"if",
"isinstance",
"(",
"data",
",",
"SFrame",
")",
":",
"other",
"=",
"data",
"datalist",
"=",
"[",
"other",
".",
"select_column",
"(",
"name",
")",
"for",
"name",
"in",
"other",
".",
"column_names",
"(",
")",
"]",
"namelist",
"=",
"other",
".",
"column_names",
"(",
")",
"my_columns",
"=",
"set",
"(",
"self",
".",
"column_names",
"(",
")",
")",
"for",
"name",
"in",
"namelist",
":",
"if",
"name",
"in",
"my_columns",
":",
"raise",
"ValueError",
"(",
"\"Column '\"",
"+",
"name",
"+",
"\"' already exists in current SFrame\"",
")",
"else",
":",
"if",
"not",
"_is_non_string_iterable",
"(",
"datalist",
")",
":",
"raise",
"TypeError",
"(",
"\"datalist must be an iterable\"",
")",
"if",
"not",
"_is_non_string_iterable",
"(",
"namelist",
")",
":",
"raise",
"TypeError",
"(",
"\"namelist must be an iterable\"",
")",
"if",
"not",
"all",
"(",
"[",
"isinstance",
"(",
"x",
",",
"SArray",
")",
"for",
"x",
"in",
"datalist",
"]",
")",
":",
"raise",
"TypeError",
"(",
"\"Must give column as SArray\"",
")",
"if",
"not",
"all",
"(",
"[",
"isinstance",
"(",
"x",
",",
"str",
")",
"for",
"x",
"in",
"namelist",
"]",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid column name in list : must all be str\"",
")",
"with",
"cython_context",
"(",
")",
":",
"self",
".",
"__proxy__",
".",
"add_columns",
"(",
"[",
"x",
".",
"__proxy__",
"for",
"x",
"in",
"datalist",
"]",
",",
"namelist",
")",
"self",
".",
"_cache",
"=",
"None",
"return",
"self"
] | https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/sframe.py#L3736-L3800 |
|
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | gr-utils/modtool/cli/add.py | python | cli | (**kwargs) | Adds a block to the out-of-tree module. | Adds a block to the out-of-tree module. | [
"Adds",
"a",
"block",
"to",
"the",
"out",
"-",
"of",
"-",
"tree",
"module",
"."
] | def cli(**kwargs):
"""Adds a block to the out-of-tree module."""
kwargs['cli'] = True
self = ModToolAdd(**kwargs)
click.secho("GNU Radio module name identified: " +
self.info['modname'], fg='green')
get_blockname(self)
get_blocktype(self)
get_lang(self)
info_lang = {'cpp': 'C++', 'python': 'Python'}[self.info['lang']]
click.secho(f"Language: {info_lang}", fg='green')
if ((self.skip_subdirs['lib'] and self.info['lang'] == 'cpp') or
(self.skip_subdirs['python'] and self.info['lang'] == 'python')):
raise ModToolException('Missing or skipping relevant subdir.')
click.secho("Block/code identifier: " + self.info['blockname'], fg='green')
if not self.license_file:
get_copyrightholder(self)
self.info['license'] = self.setup_choose_license()
get_arglist(self)
get_py_qa(self)
get_cpp_qa(self)
if self.info['version'] == 'autofoo' and not self.skip_cmakefiles:
click.secho("Warning: Autotools modules are not supported. " +
"Files will be created, but Makefiles will not be edited.",
fg='yellow')
self.skip_cmakefiles = True
run(self) | [
"def",
"cli",
"(",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'cli'",
"]",
"=",
"True",
"self",
"=",
"ModToolAdd",
"(",
"*",
"*",
"kwargs",
")",
"click",
".",
"secho",
"(",
"\"GNU Radio module name identified: \"",
"+",
"self",
".",
"info",
"[",
"'modname'",
"]",
",",
"fg",
"=",
"'green'",
")",
"get_blockname",
"(",
"self",
")",
"get_blocktype",
"(",
"self",
")",
"get_lang",
"(",
"self",
")",
"info_lang",
"=",
"{",
"'cpp'",
":",
"'C++'",
",",
"'python'",
":",
"'Python'",
"}",
"[",
"self",
".",
"info",
"[",
"'lang'",
"]",
"]",
"click",
".",
"secho",
"(",
"f\"Language: {info_lang}\"",
",",
"fg",
"=",
"'green'",
")",
"if",
"(",
"(",
"self",
".",
"skip_subdirs",
"[",
"'lib'",
"]",
"and",
"self",
".",
"info",
"[",
"'lang'",
"]",
"==",
"'cpp'",
")",
"or",
"(",
"self",
".",
"skip_subdirs",
"[",
"'python'",
"]",
"and",
"self",
".",
"info",
"[",
"'lang'",
"]",
"==",
"'python'",
")",
")",
":",
"raise",
"ModToolException",
"(",
"'Missing or skipping relevant subdir.'",
")",
"click",
".",
"secho",
"(",
"\"Block/code identifier: \"",
"+",
"self",
".",
"info",
"[",
"'blockname'",
"]",
",",
"fg",
"=",
"'green'",
")",
"if",
"not",
"self",
".",
"license_file",
":",
"get_copyrightholder",
"(",
"self",
")",
"self",
".",
"info",
"[",
"'license'",
"]",
"=",
"self",
".",
"setup_choose_license",
"(",
")",
"get_arglist",
"(",
"self",
")",
"get_py_qa",
"(",
"self",
")",
"get_cpp_qa",
"(",
"self",
")",
"if",
"self",
".",
"info",
"[",
"'version'",
"]",
"==",
"'autofoo'",
"and",
"not",
"self",
".",
"skip_cmakefiles",
":",
"click",
".",
"secho",
"(",
"\"Warning: Autotools modules are not supported. \"",
"+",
"\"Files will be created, but Makefiles will not be edited.\"",
",",
"fg",
"=",
"'yellow'",
")",
"self",
".",
"skip_cmakefiles",
"=",
"True",
"run",
"(",
"self",
")"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-utils/modtool/cli/add.py#L42-L68 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/syntax/syntax.py | python | SyntaxMgr.GetLangId | (self, ext) | return synglob.LANG_MAP[ftype][LANG_ID] | Gets the language Id that is associated with the file
extension.
@param ext: extension to get lang id for | Gets the language Id that is associated with the file
extension.
@param ext: extension to get lang id for | [
"Gets",
"the",
"language",
"Id",
"that",
"is",
"associated",
"with",
"the",
"file",
"extension",
".",
"@param",
"ext",
":",
"extension",
"to",
"get",
"lang",
"id",
"for"
] | def GetLangId(self, ext):
"""Gets the language Id that is associated with the file
extension.
@param ext: extension to get lang id for
"""
ftype = self._extreg.FileTypeFromExt(ext)
return synglob.LANG_MAP[ftype][LANG_ID] | [
"def",
"GetLangId",
"(",
"self",
",",
"ext",
")",
":",
"ftype",
"=",
"self",
".",
"_extreg",
".",
"FileTypeFromExt",
"(",
"ext",
")",
"return",
"synglob",
".",
"LANG_MAP",
"[",
"ftype",
"]",
"[",
"LANG_ID",
"]"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/syntax.py#L115-L122 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.StyleSetWeight | (*args, **kwargs) | return _stc.StyledTextCtrl_StyleSetWeight(*args, **kwargs) | StyleSetWeight(self, int style, int weight) | StyleSetWeight(self, int style, int weight) | [
"StyleSetWeight",
"(",
"self",
"int",
"style",
"int",
"weight",
")"
] | def StyleSetWeight(*args, **kwargs):
"""StyleSetWeight(self, int style, int weight)"""
return _stc.StyledTextCtrl_StyleSetWeight(*args, **kwargs) | [
"def",
"StyleSetWeight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_StyleSetWeight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L2707-L2709 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/aui.py | python | AuiPaneInfo.HasGripperTop | (*args, **kwargs) | return _aui.AuiPaneInfo_HasGripperTop(*args, **kwargs) | HasGripperTop(self) -> bool | HasGripperTop(self) -> bool | [
"HasGripperTop",
"(",
"self",
")",
"-",
">",
"bool"
] | def HasGripperTop(*args, **kwargs):
"""HasGripperTop(self) -> bool"""
return _aui.AuiPaneInfo_HasGripperTop(*args, **kwargs) | [
"def",
"HasGripperTop",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiPaneInfo_HasGripperTop",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L329-L331 |
|
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/boost_1.75.0/tools/build/src/build/generators.py | python | Generator.determine_output_name | (self, sources) | return self.determine_target_name(sources[0].name()) | Determine the name of the produced target from the
names of the sources. | Determine the name of the produced target from the
names of the sources. | [
"Determine",
"the",
"name",
"of",
"the",
"produced",
"target",
"from",
"the",
"names",
"of",
"the",
"sources",
"."
] | def determine_output_name(self, sources):
"""Determine the name of the produced target from the
names of the sources."""
assert is_iterable_typed(sources, virtual_target.VirtualTarget)
# The simple case if when a name
# of source has single dot. Then, we take the part before
# dot. Several dots can be caused by:
# - Using source file like a.host.cpp
# - A type which suffix has a dot. Say, we can
# type 'host_cpp' with extension 'host.cpp'.
# In the first case, we want to take the part till the last
# dot. In the second case -- no sure, but for now take
# the part till the last dot too.
name = os.path.splitext(sources[0].name())[0]
for s in sources[1:]:
n2 = os.path.splitext(s.name())
if n2 != name:
get_manager().errors()(
"%s: source targets have different names: cannot determine target name"
% (self.id_))
# Names of sources might include directory. We should strip it.
return self.determine_target_name(sources[0].name()) | [
"def",
"determine_output_name",
"(",
"self",
",",
"sources",
")",
":",
"assert",
"is_iterable_typed",
"(",
"sources",
",",
"virtual_target",
".",
"VirtualTarget",
")",
"# The simple case if when a name",
"# of source has single dot. Then, we take the part before",
"# dot. Several dots can be caused by:",
"# - Using source file like a.host.cpp",
"# - A type which suffix has a dot. Say, we can",
"# type 'host_cpp' with extension 'host.cpp'.",
"# In the first case, we want to take the part till the last",
"# dot. In the second case -- no sure, but for now take",
"# the part till the last dot too.",
"name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"sources",
"[",
"0",
"]",
".",
"name",
"(",
")",
")",
"[",
"0",
"]",
"for",
"s",
"in",
"sources",
"[",
"1",
":",
"]",
":",
"n2",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"s",
".",
"name",
"(",
")",
")",
"if",
"n2",
"!=",
"name",
":",
"get_manager",
"(",
")",
".",
"errors",
"(",
")",
"(",
"\"%s: source targets have different names: cannot determine target name\"",
"%",
"(",
"self",
".",
"id_",
")",
")",
"# Names of sources might include directory. We should strip it.",
"return",
"self",
".",
"determine_target_name",
"(",
"sources",
"[",
"0",
"]",
".",
"name",
"(",
")",
")"
] | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/boost_1.75.0/tools/build/src/build/generators.py#L451-L475 |
|
apache/arrow | af33dd1157eb8d7d9bfac25ebf61445b793b7943 | cpp/build-support/cpplint.py | python | CheckEmptyBlockBody | (filename, clean_lines, linenum, error) | Look for empty loop/conditional body with only a single semicolon.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Look for empty loop/conditional body with only a single semicolon. | [
"Look",
"for",
"empty",
"loop",
"/",
"conditional",
"body",
"with",
"only",
"a",
"single",
"semicolon",
"."
] | def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
"""Look for empty loop/conditional body with only a single semicolon.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Search for loop keywords at the beginning of the line. Because only
# whitespaces are allowed before the keywords, this will also ignore most
# do-while-loops, since those lines should start with closing brace.
#
# We also check "if" blocks here, since an empty conditional block
# is likely an error.
line = clean_lines.elided[linenum]
matched = Match(r'\s*(for|while|if)\s*\(', line)
if matched:
# Find the end of the conditional expression.
(end_line, end_linenum, end_pos) = CloseExpression(
clean_lines, linenum, line.find('('))
# Output warning if what follows the condition expression is a semicolon.
# No warning for all other cases, including whitespace or newline, since we
# have a separate check for semicolons preceded by whitespace.
if end_pos >= 0 and Match(r';', end_line[end_pos:]):
if matched.group(1) == 'if':
error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
'Empty conditional bodies should use {}')
else:
error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
'Empty loop bodies should use {} or continue')
# Check for if statements that have completely empty bodies (no comments)
# and no else clauses.
if end_pos >= 0 and matched.group(1) == 'if':
# Find the position of the opening { for the if statement.
# Return without logging an error if it has no brackets.
opening_linenum = end_linenum
opening_line_fragment = end_line[end_pos:]
# Loop until EOF or find anything that's not whitespace or opening {.
while not Search(r'^\s*\{', opening_line_fragment):
if Search(r'^(?!\s*$)', opening_line_fragment):
# Conditional has no brackets.
return
opening_linenum += 1
if opening_linenum == len(clean_lines.elided):
# Couldn't find conditional's opening { or any code before EOF.
return
opening_line_fragment = clean_lines.elided[opening_linenum]
# Set opening_line (opening_line_fragment may not be entire opening line).
opening_line = clean_lines.elided[opening_linenum]
# Find the position of the closing }.
opening_pos = opening_line_fragment.find('{')
if opening_linenum == end_linenum:
# We need to make opening_pos relative to the start of the entire line.
opening_pos += end_pos
(closing_line, closing_linenum, closing_pos) = CloseExpression(
clean_lines, opening_linenum, opening_pos)
if closing_pos < 0:
return
# Now construct the body of the conditional. This consists of the portion
# of the opening line after the {, all lines until the closing line,
# and the portion of the closing line before the }.
if (clean_lines.raw_lines[opening_linenum] !=
CleanseComments(clean_lines.raw_lines[opening_linenum])):
# Opening line ends with a comment, so conditional isn't empty.
return
if closing_linenum > opening_linenum:
# Opening line after the {. Ignore comments here since we checked above.
bodylist = list(opening_line[opening_pos+1:])
# All lines until closing line, excluding closing line, with comments.
bodylist.extend(clean_lines.raw_lines[opening_linenum+1:closing_linenum])
# Closing line before the }. Won't (and can't) have comments.
bodylist.append(clean_lines.elided[closing_linenum][:closing_pos-1])
body = '\n'.join(bodylist)
else:
# If statement has brackets and fits on a single line.
body = opening_line[opening_pos+1:closing_pos-1]
# Check if the body is empty
if not _EMPTY_CONDITIONAL_BODY_PATTERN.search(body):
return
# The body is empty. Now make sure there's not an else clause.
current_linenum = closing_linenum
current_line_fragment = closing_line[closing_pos:]
# Loop until EOF or find anything that's not whitespace or else clause.
while Search(r'^\s*$|^(?=\s*else)', current_line_fragment):
if Search(r'^(?=\s*else)', current_line_fragment):
# Found an else clause, so don't log an error.
return
current_linenum += 1
if current_linenum == len(clean_lines.elided):
break
current_line_fragment = clean_lines.elided[current_linenum]
# The body is empty and there's no else clause until EOF or other code.
error(filename, end_linenum, 'whitespace/empty_if_body', 4,
('If statement had no body and no else clause')) | [
"def",
"CheckEmptyBlockBody",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"# Search for loop keywords at the beginning of the line. Because only",
"# whitespaces are allowed before the keywords, this will also ignore most",
"# do-while-loops, since those lines should start with closing brace.",
"#",
"# We also check \"if\" blocks here, since an empty conditional block",
"# is likely an error.",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"matched",
"=",
"Match",
"(",
"r'\\s*(for|while|if)\\s*\\('",
",",
"line",
")",
"if",
"matched",
":",
"# Find the end of the conditional expression.",
"(",
"end_line",
",",
"end_linenum",
",",
"end_pos",
")",
"=",
"CloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"line",
".",
"find",
"(",
"'('",
")",
")",
"# Output warning if what follows the condition expression is a semicolon.",
"# No warning for all other cases, including whitespace or newline, since we",
"# have a separate check for semicolons preceded by whitespace.",
"if",
"end_pos",
">=",
"0",
"and",
"Match",
"(",
"r';'",
",",
"end_line",
"[",
"end_pos",
":",
"]",
")",
":",
"if",
"matched",
".",
"group",
"(",
"1",
")",
"==",
"'if'",
":",
"error",
"(",
"filename",
",",
"end_linenum",
",",
"'whitespace/empty_conditional_body'",
",",
"5",
",",
"'Empty conditional bodies should use {}'",
")",
"else",
":",
"error",
"(",
"filename",
",",
"end_linenum",
",",
"'whitespace/empty_loop_body'",
",",
"5",
",",
"'Empty loop bodies should use {} or continue'",
")",
"# Check for if statements that have completely empty bodies (no comments)",
"# and no else clauses.",
"if",
"end_pos",
">=",
"0",
"and",
"matched",
".",
"group",
"(",
"1",
")",
"==",
"'if'",
":",
"# Find the position of the opening { for the if statement.",
"# Return without logging an error if it has no brackets.",
"opening_linenum",
"=",
"end_linenum",
"opening_line_fragment",
"=",
"end_line",
"[",
"end_pos",
":",
"]",
"# Loop until EOF or find anything that's not whitespace or opening {.",
"while",
"not",
"Search",
"(",
"r'^\\s*\\{'",
",",
"opening_line_fragment",
")",
":",
"if",
"Search",
"(",
"r'^(?!\\s*$)'",
",",
"opening_line_fragment",
")",
":",
"# Conditional has no brackets.",
"return",
"opening_linenum",
"+=",
"1",
"if",
"opening_linenum",
"==",
"len",
"(",
"clean_lines",
".",
"elided",
")",
":",
"# Couldn't find conditional's opening { or any code before EOF.",
"return",
"opening_line_fragment",
"=",
"clean_lines",
".",
"elided",
"[",
"opening_linenum",
"]",
"# Set opening_line (opening_line_fragment may not be entire opening line).",
"opening_line",
"=",
"clean_lines",
".",
"elided",
"[",
"opening_linenum",
"]",
"# Find the position of the closing }.",
"opening_pos",
"=",
"opening_line_fragment",
".",
"find",
"(",
"'{'",
")",
"if",
"opening_linenum",
"==",
"end_linenum",
":",
"# We need to make opening_pos relative to the start of the entire line.",
"opening_pos",
"+=",
"end_pos",
"(",
"closing_line",
",",
"closing_linenum",
",",
"closing_pos",
")",
"=",
"CloseExpression",
"(",
"clean_lines",
",",
"opening_linenum",
",",
"opening_pos",
")",
"if",
"closing_pos",
"<",
"0",
":",
"return",
"# Now construct the body of the conditional. This consists of the portion",
"# of the opening line after the {, all lines until the closing line,",
"# and the portion of the closing line before the }.",
"if",
"(",
"clean_lines",
".",
"raw_lines",
"[",
"opening_linenum",
"]",
"!=",
"CleanseComments",
"(",
"clean_lines",
".",
"raw_lines",
"[",
"opening_linenum",
"]",
")",
")",
":",
"# Opening line ends with a comment, so conditional isn't empty.",
"return",
"if",
"closing_linenum",
">",
"opening_linenum",
":",
"# Opening line after the {. Ignore comments here since we checked above.",
"bodylist",
"=",
"list",
"(",
"opening_line",
"[",
"opening_pos",
"+",
"1",
":",
"]",
")",
"# All lines until closing line, excluding closing line, with comments.",
"bodylist",
".",
"extend",
"(",
"clean_lines",
".",
"raw_lines",
"[",
"opening_linenum",
"+",
"1",
":",
"closing_linenum",
"]",
")",
"# Closing line before the }. Won't (and can't) have comments.",
"bodylist",
".",
"append",
"(",
"clean_lines",
".",
"elided",
"[",
"closing_linenum",
"]",
"[",
":",
"closing_pos",
"-",
"1",
"]",
")",
"body",
"=",
"'\\n'",
".",
"join",
"(",
"bodylist",
")",
"else",
":",
"# If statement has brackets and fits on a single line.",
"body",
"=",
"opening_line",
"[",
"opening_pos",
"+",
"1",
":",
"closing_pos",
"-",
"1",
"]",
"# Check if the body is empty",
"if",
"not",
"_EMPTY_CONDITIONAL_BODY_PATTERN",
".",
"search",
"(",
"body",
")",
":",
"return",
"# The body is empty. Now make sure there's not an else clause.",
"current_linenum",
"=",
"closing_linenum",
"current_line_fragment",
"=",
"closing_line",
"[",
"closing_pos",
":",
"]",
"# Loop until EOF or find anything that's not whitespace or else clause.",
"while",
"Search",
"(",
"r'^\\s*$|^(?=\\s*else)'",
",",
"current_line_fragment",
")",
":",
"if",
"Search",
"(",
"r'^(?=\\s*else)'",
",",
"current_line_fragment",
")",
":",
"# Found an else clause, so don't log an error.",
"return",
"current_linenum",
"+=",
"1",
"if",
"current_linenum",
"==",
"len",
"(",
"clean_lines",
".",
"elided",
")",
":",
"break",
"current_line_fragment",
"=",
"clean_lines",
".",
"elided",
"[",
"current_linenum",
"]",
"# The body is empty and there's no else clause until EOF or other code.",
"error",
"(",
"filename",
",",
"end_linenum",
",",
"'whitespace/empty_if_body'",
",",
"4",
",",
"(",
"'If statement had no body and no else clause'",
")",
")"
] | https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/cpp/build-support/cpplint.py#L4144-L4245 |
||
linyouhappy/kongkongxiyou | 7a69b2913eb29f4be77f9a62fb90cdd72c4160f1 | cocosjs/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py | python | Cursor.get_usr | (self) | return conf.lib.clang_getCursorUSR(self) | Return the Unified Symbol Resultion (USR) for the entity referenced
by the given cursor (or None).
A Unified Symbol Resolution (USR) is a string that identifies a
particular entity (function, class, variable, etc.) within a
program. USRs can be compared across translation units to determine,
e.g., when references in one translation refer to an entity defined in
another translation unit. | Return the Unified Symbol Resultion (USR) for the entity referenced
by the given cursor (or None). | [
"Return",
"the",
"Unified",
"Symbol",
"Resultion",
"(",
"USR",
")",
"for",
"the",
"entity",
"referenced",
"by",
"the",
"given",
"cursor",
"(",
"or",
"None",
")",
"."
] | def get_usr(self):
"""Return the Unified Symbol Resultion (USR) for the entity referenced
by the given cursor (or None).
A Unified Symbol Resolution (USR) is a string that identifies a
particular entity (function, class, variable, etc.) within a
program. USRs can be compared across translation units to determine,
e.g., when references in one translation refer to an entity defined in
another translation unit."""
return conf.lib.clang_getCursorUSR(self) | [
"def",
"get_usr",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getCursorUSR",
"(",
"self",
")"
] | https://github.com/linyouhappy/kongkongxiyou/blob/7a69b2913eb29f4be77f9a62fb90cdd72c4160f1/cocosjs/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L1235-L1244 |
|
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | tools/site_compare/command_line.py | python | Command.GetArgument | (self, name) | return self.arg_dict[name.lower()] | Return an argument from a name. | Return an argument from a name. | [
"Return",
"an",
"argument",
"from",
"a",
"name",
"."
] | def GetArgument(self, name):
"""Return an argument from a name."""
return self.arg_dict[name.lower()] | [
"def",
"GetArgument",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"arg_dict",
"[",
"name",
".",
"lower",
"(",
")",
"]"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/site_compare/command_line.py#L223-L225 |
|
clementine-player/Clementine | 111379dfd027802b59125829fcf87e3e1d0ad73b | dist/cpplint.py | python | IsRValueType | (clean_lines, nesting_state, linenum, column) | return False | Check if the token ending on (linenum, column) is a type.
Assumes that text to the right of the column is "&&" or a function
name.
Args:
clean_lines: A CleansedLines instance containing the file.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
linenum: the number of the line to check.
column: end column of the token to check.
Returns:
True if this token is a type, False if we are not sure. | Check if the token ending on (linenum, column) is a type. | [
"Check",
"if",
"the",
"token",
"ending",
"on",
"(",
"linenum",
"column",
")",
"is",
"a",
"type",
"."
] | def IsRValueType(clean_lines, nesting_state, linenum, column):
"""Check if the token ending on (linenum, column) is a type.
Assumes that text to the right of the column is "&&" or a function
name.
Args:
clean_lines: A CleansedLines instance containing the file.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
linenum: the number of the line to check.
column: end column of the token to check.
Returns:
True if this token is a type, False if we are not sure.
"""
prefix = clean_lines.elided[linenum][0:column]
# Get one word to the left. If we failed to do so, this is most
# likely not a type, since it's unlikely that the type name and "&&"
# would be split across multiple lines.
match = Match(r'^(.*)(\b\w+|[>*)&])\s*$', prefix)
if not match:
return False
# Check text following the token. If it's "&&>" or "&&," or "&&...", it's
# most likely a rvalue reference used inside a template.
suffix = clean_lines.elided[linenum][column:]
if Match(r'&&\s*(?:[>,]|\.\.\.)', suffix):
return True
# Check for simple type and end of templates:
# int&& variable
# vector<int>&& variable
#
# Because this function is called recursively, we also need to
# recognize pointer and reference types:
# int* Function()
# int& Function()
if match.group(2) in ['char', 'char16_t', 'char32_t', 'wchar_t', 'bool',
'short', 'int', 'long', 'signed', 'unsigned',
'float', 'double', 'void', 'auto', '>', '*', '&']:
return True
# If we see a close parenthesis, look for decltype on the other side.
# decltype would unambiguously identify a type, anything else is
# probably a parenthesized expression and not a type.
if match.group(2) == ')':
return IsDecltype(
clean_lines, linenum, len(match.group(1)) + len(match.group(2)) - 1)
# Check for casts and cv-qualifiers.
# match.group(1) remainder
# -------------- ---------
# const_cast< type&&
# const type&&
# type const&&
if Search(r'\b(?:const_cast\s*<|static_cast\s*<|dynamic_cast\s*<|'
r'reinterpret_cast\s*<|\w+\s)\s*$',
match.group(1)):
return True
# Look for a preceding symbol that might help differentiate the context.
# These are the cases that would be ambiguous:
# match.group(1) remainder
# -------------- ---------
# Call ( expression &&
# Declaration ( type&&
# sizeof ( type&&
# if ( expression &&
# while ( expression &&
# for ( type&&
# for( ; expression &&
# statement ; type&&
# block { type&&
# constructor { expression &&
start = linenum
line = match.group(1)
match_symbol = None
while start >= 0:
# We want to skip over identifiers and commas to get to a symbol.
# Commas are skipped so that we can find the opening parenthesis
# for function parameter lists.
match_symbol = Match(r'^(.*)([^\w\s,])[\w\s,]*$', line)
if match_symbol:
break
start -= 1
line = clean_lines.elided[start]
if not match_symbol:
# Probably the first statement in the file is an rvalue reference
return True
if match_symbol.group(2) == '}':
# Found closing brace, probably an indicate of this:
# block{} type&&
return True
if match_symbol.group(2) == ';':
# Found semicolon, probably one of these:
# for(; expression &&
# statement; type&&
# Look for the previous 'for(' in the previous lines.
before_text = match_symbol.group(1)
for i in xrange(start - 1, max(start - 6, 0), -1):
before_text = clean_lines.elided[i] + before_text
if Search(r'for\s*\([^{};]*$', before_text):
# This is the condition inside a for-loop
return False
# Did not find a for-init-statement before this semicolon, so this
# is probably a new statement and not a condition.
return True
if match_symbol.group(2) == '{':
# Found opening brace, probably one of these:
# block{ type&& = ... ; }
# constructor{ expression && expression }
# Look for a closing brace or a semicolon. If we see a semicolon
# first, this is probably a rvalue reference.
line = clean_lines.elided[start][0:len(match_symbol.group(1)) + 1]
end = start
depth = 1
while True:
for ch in line:
if ch == ';':
return True
elif ch == '{':
depth += 1
elif ch == '}':
depth -= 1
if depth == 0:
return False
end += 1
if end >= clean_lines.NumLines():
break
line = clean_lines.elided[end]
# Incomplete program?
return False
if match_symbol.group(2) == '(':
# Opening parenthesis. Need to check what's to the left of the
# parenthesis. Look back one extra line for additional context.
before_text = match_symbol.group(1)
if linenum > 1:
before_text = clean_lines.elided[linenum - 1] + before_text
before_text = match_symbol.group(1)
# Patterns that are likely to be types:
# [](type&&
# for (type&&
# sizeof(type&&
# operator=(type&&
#
if Search(r'(?:\]|\bfor|\bsizeof|\boperator\s*\S+\s*)\s*$', before_text):
return True
# Patterns that are likely to be expressions:
# if (expression &&
# while (expression &&
# : initializer(expression &&
# , initializer(expression &&
# ( FunctionCall(expression &&
# + FunctionCall(expression &&
# + (expression &&
#
# The last '+' represents operators such as '+' and '-'.
if Search(r'(?:\bif|\bwhile|[-+=%^(<!?:,&*]\s*)$', before_text):
return False
# Something else. Check that tokens to the left look like
# return_type function_name
match_func = Match(r'^(.*)\s+\w(?:\w|::)*(?:<[^<>]*>)?\s*$',
match_symbol.group(1))
if match_func:
# Check for constructors, which don't have return types.
if Search(r'\b(?:explicit|inline)$', match_func.group(1)):
return True
implicit_constructor = Match(r'\s*(\w+)\((?:const\s+)?(\w+)', prefix)
if (implicit_constructor and
implicit_constructor.group(1) == implicit_constructor.group(2)):
return True
return IsRValueType(clean_lines, nesting_state, linenum,
len(match_func.group(1)))
# Nothing before the function name. If this is inside a block scope,
# this is probably a function call.
return not (nesting_state.previous_stack_top and
nesting_state.previous_stack_top.IsBlockInfo())
if match_symbol.group(2) == '>':
# Possibly a closing bracket, check that what's on the other side
# looks like the start of a template.
return IsTemplateParameterList(
clean_lines, start, len(match_symbol.group(1)))
# Some other symbol, usually something like "a=b&&c". This is most
# likely not a type.
return False | [
"def",
"IsRValueType",
"(",
"clean_lines",
",",
"nesting_state",
",",
"linenum",
",",
"column",
")",
":",
"prefix",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"[",
"0",
":",
"column",
"]",
"# Get one word to the left. If we failed to do so, this is most",
"# likely not a type, since it's unlikely that the type name and \"&&\"",
"# would be split across multiple lines.",
"match",
"=",
"Match",
"(",
"r'^(.*)(\\b\\w+|[>*)&])\\s*$'",
",",
"prefix",
")",
"if",
"not",
"match",
":",
"return",
"False",
"# Check text following the token. If it's \"&&>\" or \"&&,\" or \"&&...\", it's",
"# most likely a rvalue reference used inside a template.",
"suffix",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"[",
"column",
":",
"]",
"if",
"Match",
"(",
"r'&&\\s*(?:[>,]|\\.\\.\\.)'",
",",
"suffix",
")",
":",
"return",
"True",
"# Check for simple type and end of templates:",
"# int&& variable",
"# vector<int>&& variable",
"#",
"# Because this function is called recursively, we also need to",
"# recognize pointer and reference types:",
"# int* Function()",
"# int& Function()",
"if",
"match",
".",
"group",
"(",
"2",
")",
"in",
"[",
"'char'",
",",
"'char16_t'",
",",
"'char32_t'",
",",
"'wchar_t'",
",",
"'bool'",
",",
"'short'",
",",
"'int'",
",",
"'long'",
",",
"'signed'",
",",
"'unsigned'",
",",
"'float'",
",",
"'double'",
",",
"'void'",
",",
"'auto'",
",",
"'>'",
",",
"'*'",
",",
"'&'",
"]",
":",
"return",
"True",
"# If we see a close parenthesis, look for decltype on the other side.",
"# decltype would unambiguously identify a type, anything else is",
"# probably a parenthesized expression and not a type.",
"if",
"match",
".",
"group",
"(",
"2",
")",
"==",
"')'",
":",
"return",
"IsDecltype",
"(",
"clean_lines",
",",
"linenum",
",",
"len",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
"+",
"len",
"(",
"match",
".",
"group",
"(",
"2",
")",
")",
"-",
"1",
")",
"# Check for casts and cv-qualifiers.",
"# match.group(1) remainder",
"# -------------- ---------",
"# const_cast< type&&",
"# const type&&",
"# type const&&",
"if",
"Search",
"(",
"r'\\b(?:const_cast\\s*<|static_cast\\s*<|dynamic_cast\\s*<|'",
"r'reinterpret_cast\\s*<|\\w+\\s)\\s*$'",
",",
"match",
".",
"group",
"(",
"1",
")",
")",
":",
"return",
"True",
"# Look for a preceding symbol that might help differentiate the context.",
"# These are the cases that would be ambiguous:",
"# match.group(1) remainder",
"# -------------- ---------",
"# Call ( expression &&",
"# Declaration ( type&&",
"# sizeof ( type&&",
"# if ( expression &&",
"# while ( expression &&",
"# for ( type&&",
"# for( ; expression &&",
"# statement ; type&&",
"# block { type&&",
"# constructor { expression &&",
"start",
"=",
"linenum",
"line",
"=",
"match",
".",
"group",
"(",
"1",
")",
"match_symbol",
"=",
"None",
"while",
"start",
">=",
"0",
":",
"# We want to skip over identifiers and commas to get to a symbol.",
"# Commas are skipped so that we can find the opening parenthesis",
"# for function parameter lists.",
"match_symbol",
"=",
"Match",
"(",
"r'^(.*)([^\\w\\s,])[\\w\\s,]*$'",
",",
"line",
")",
"if",
"match_symbol",
":",
"break",
"start",
"-=",
"1",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"start",
"]",
"if",
"not",
"match_symbol",
":",
"# Probably the first statement in the file is an rvalue reference",
"return",
"True",
"if",
"match_symbol",
".",
"group",
"(",
"2",
")",
"==",
"'}'",
":",
"# Found closing brace, probably an indicate of this:",
"# block{} type&&",
"return",
"True",
"if",
"match_symbol",
".",
"group",
"(",
"2",
")",
"==",
"';'",
":",
"# Found semicolon, probably one of these:",
"# for(; expression &&",
"# statement; type&&",
"# Look for the previous 'for(' in the previous lines.",
"before_text",
"=",
"match_symbol",
".",
"group",
"(",
"1",
")",
"for",
"i",
"in",
"xrange",
"(",
"start",
"-",
"1",
",",
"max",
"(",
"start",
"-",
"6",
",",
"0",
")",
",",
"-",
"1",
")",
":",
"before_text",
"=",
"clean_lines",
".",
"elided",
"[",
"i",
"]",
"+",
"before_text",
"if",
"Search",
"(",
"r'for\\s*\\([^{};]*$'",
",",
"before_text",
")",
":",
"# This is the condition inside a for-loop",
"return",
"False",
"# Did not find a for-init-statement before this semicolon, so this",
"# is probably a new statement and not a condition.",
"return",
"True",
"if",
"match_symbol",
".",
"group",
"(",
"2",
")",
"==",
"'{'",
":",
"# Found opening brace, probably one of these:",
"# block{ type&& = ... ; }",
"# constructor{ expression && expression }",
"# Look for a closing brace or a semicolon. If we see a semicolon",
"# first, this is probably a rvalue reference.",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"start",
"]",
"[",
"0",
":",
"len",
"(",
"match_symbol",
".",
"group",
"(",
"1",
")",
")",
"+",
"1",
"]",
"end",
"=",
"start",
"depth",
"=",
"1",
"while",
"True",
":",
"for",
"ch",
"in",
"line",
":",
"if",
"ch",
"==",
"';'",
":",
"return",
"True",
"elif",
"ch",
"==",
"'{'",
":",
"depth",
"+=",
"1",
"elif",
"ch",
"==",
"'}'",
":",
"depth",
"-=",
"1",
"if",
"depth",
"==",
"0",
":",
"return",
"False",
"end",
"+=",
"1",
"if",
"end",
">=",
"clean_lines",
".",
"NumLines",
"(",
")",
":",
"break",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"end",
"]",
"# Incomplete program?",
"return",
"False",
"if",
"match_symbol",
".",
"group",
"(",
"2",
")",
"==",
"'('",
":",
"# Opening parenthesis. Need to check what's to the left of the",
"# parenthesis. Look back one extra line for additional context.",
"before_text",
"=",
"match_symbol",
".",
"group",
"(",
"1",
")",
"if",
"linenum",
">",
"1",
":",
"before_text",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"-",
"1",
"]",
"+",
"before_text",
"before_text",
"=",
"match_symbol",
".",
"group",
"(",
"1",
")",
"# Patterns that are likely to be types:",
"# [](type&&",
"# for (type&&",
"# sizeof(type&&",
"# operator=(type&&",
"#",
"if",
"Search",
"(",
"r'(?:\\]|\\bfor|\\bsizeof|\\boperator\\s*\\S+\\s*)\\s*$'",
",",
"before_text",
")",
":",
"return",
"True",
"# Patterns that are likely to be expressions:",
"# if (expression &&",
"# while (expression &&",
"# : initializer(expression &&",
"# , initializer(expression &&",
"# ( FunctionCall(expression &&",
"# + FunctionCall(expression &&",
"# + (expression &&",
"#",
"# The last '+' represents operators such as '+' and '-'.",
"if",
"Search",
"(",
"r'(?:\\bif|\\bwhile|[-+=%^(<!?:,&*]\\s*)$'",
",",
"before_text",
")",
":",
"return",
"False",
"# Something else. Check that tokens to the left look like",
"# return_type function_name",
"match_func",
"=",
"Match",
"(",
"r'^(.*)\\s+\\w(?:\\w|::)*(?:<[^<>]*>)?\\s*$'",
",",
"match_symbol",
".",
"group",
"(",
"1",
")",
")",
"if",
"match_func",
":",
"# Check for constructors, which don't have return types.",
"if",
"Search",
"(",
"r'\\b(?:explicit|inline)$'",
",",
"match_func",
".",
"group",
"(",
"1",
")",
")",
":",
"return",
"True",
"implicit_constructor",
"=",
"Match",
"(",
"r'\\s*(\\w+)\\((?:const\\s+)?(\\w+)'",
",",
"prefix",
")",
"if",
"(",
"implicit_constructor",
"and",
"implicit_constructor",
".",
"group",
"(",
"1",
")",
"==",
"implicit_constructor",
".",
"group",
"(",
"2",
")",
")",
":",
"return",
"True",
"return",
"IsRValueType",
"(",
"clean_lines",
",",
"nesting_state",
",",
"linenum",
",",
"len",
"(",
"match_func",
".",
"group",
"(",
"1",
")",
")",
")",
"# Nothing before the function name. If this is inside a block scope,",
"# this is probably a function call.",
"return",
"not",
"(",
"nesting_state",
".",
"previous_stack_top",
"and",
"nesting_state",
".",
"previous_stack_top",
".",
"IsBlockInfo",
"(",
")",
")",
"if",
"match_symbol",
".",
"group",
"(",
"2",
")",
"==",
"'>'",
":",
"# Possibly a closing bracket, check that what's on the other side",
"# looks like the start of a template.",
"return",
"IsTemplateParameterList",
"(",
"clean_lines",
",",
"start",
",",
"len",
"(",
"match_symbol",
".",
"group",
"(",
"1",
")",
")",
")",
"# Some other symbol, usually something like \"a=b&&c\". This is most",
"# likely not a type.",
"return",
"False"
] | https://github.com/clementine-player/Clementine/blob/111379dfd027802b59125829fcf87e3e1d0ad73b/dist/cpplint.py#L3358-L3557 |
|
stereolabs/zed-examples | ed3f068301fbdf3898f7c42de864dc578467e061 | body tracking/python/cv_viewer/tracking_viewer.py | python | cvt | (pt, scale) | return out | Function that scales point coordinates | Function that scales point coordinates | [
"Function",
"that",
"scales",
"point",
"coordinates"
] | def cvt(pt, scale):
'''
Function that scales point coordinates
'''
out = [pt[0]*scale[0], pt[1]*scale[1]]
return out | [
"def",
"cvt",
"(",
"pt",
",",
"scale",
")",
":",
"out",
"=",
"[",
"pt",
"[",
"0",
"]",
"*",
"scale",
"[",
"0",
"]",
",",
"pt",
"[",
"1",
"]",
"*",
"scale",
"[",
"1",
"]",
"]",
"return",
"out"
] | https://github.com/stereolabs/zed-examples/blob/ed3f068301fbdf3898f7c42de864dc578467e061/body tracking/python/cv_viewer/tracking_viewer.py#L10-L15 |
|
apache/kudu | 90895ce76590f10730ad7aac3613b69d89ff5422 | build-support/check_compatibility.py | python | clean_scratch_dir | (scratch_dir) | Clean up and re-create the scratch directory. | Clean up and re-create the scratch directory. | [
"Clean",
"up",
"and",
"re",
"-",
"create",
"the",
"scratch",
"directory",
"."
] | def clean_scratch_dir(scratch_dir):
""" Clean up and re-create the scratch directory. """
if os.path.exists(scratch_dir):
logging.info("Removing scratch dir %s...", scratch_dir)
shutil.rmtree(scratch_dir)
logging.info("Creating empty scratch dir %s...", scratch_dir)
os.makedirs(scratch_dir) | [
"def",
"clean_scratch_dir",
"(",
"scratch_dir",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"scratch_dir",
")",
":",
"logging",
".",
"info",
"(",
"\"Removing scratch dir %s...\"",
",",
"scratch_dir",
")",
"shutil",
".",
"rmtree",
"(",
"scratch_dir",
")",
"logging",
".",
"info",
"(",
"\"Creating empty scratch dir %s...\"",
",",
"scratch_dir",
")",
"os",
".",
"makedirs",
"(",
"scratch_dir",
")"
] | https://github.com/apache/kudu/blob/90895ce76590f10730ad7aac3613b69d89ff5422/build-support/check_compatibility.py#L72-L78 |
||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBThread.SetSelectedFrame | (self, frame_idx) | return _lldb.SBThread_SetSelectedFrame(self, frame_idx) | SetSelectedFrame(SBThread self, uint32_t frame_idx) -> SBFrame | SetSelectedFrame(SBThread self, uint32_t frame_idx) -> SBFrame | [
"SetSelectedFrame",
"(",
"SBThread",
"self",
"uint32_t",
"frame_idx",
")",
"-",
">",
"SBFrame"
] | def SetSelectedFrame(self, frame_idx):
"""SetSelectedFrame(SBThread self, uint32_t frame_idx) -> SBFrame"""
return _lldb.SBThread_SetSelectedFrame(self, frame_idx) | [
"def",
"SetSelectedFrame",
"(",
"self",
",",
"frame_idx",
")",
":",
"return",
"_lldb",
".",
"SBThread_SetSelectedFrame",
"(",
"self",
",",
"frame_idx",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L11845-L11847 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/tornado/tornado-6/tornado/util.py | python | GzipDecompressor.flush | (self) | return self.decompressobj.flush() | Return any remaining buffered data not yet returned by decompress.
Also checks for errors such as truncated input.
No other methods may be called on this object after `flush`. | Return any remaining buffered data not yet returned by decompress. | [
"Return",
"any",
"remaining",
"buffered",
"data",
"not",
"yet",
"returned",
"by",
"decompress",
"."
] | def flush(self) -> bytes:
"""Return any remaining buffered data not yet returned by decompress.
Also checks for errors such as truncated input.
No other methods may be called on this object after `flush`.
"""
return self.decompressobj.flush() | [
"def",
"flush",
"(",
"self",
")",
"->",
"bytes",
":",
"return",
"self",
".",
"decompressobj",
".",
"flush",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/util.py#L122-L128 |
|
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/virtualenv/files/virtualenv.py | python | Logger._stdout_level | (self) | return self.FATAL | Returns the level that stdout runs at | Returns the level that stdout runs at | [
"Returns",
"the",
"level",
"that",
"stdout",
"runs",
"at"
] | def _stdout_level(self):
"""Returns the level that stdout runs at"""
for level, consumer in self.consumers:
if consumer is sys.stdout:
return level
return self.FATAL | [
"def",
"_stdout_level",
"(",
"self",
")",
":",
"for",
"level",
",",
"consumer",
"in",
"self",
".",
"consumers",
":",
"if",
"consumer",
"is",
"sys",
".",
"stdout",
":",
"return",
"level",
"return",
"self",
".",
"FATAL"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/virtualenv/files/virtualenv.py#L332-L337 |
|
bryanyzhu/Hidden-Two-Stream | f7f684adbdacb6df6b1cf196c3a476cd23484a0f | scripts/cpp_lint.py | python | CheckAccess | (filename, clean_lines, linenum, nesting_state, error) | Checks for improper use of DISALLOW* macros.
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: The function to call with any errors found. | Checks for improper use of DISALLOW* macros. | [
"Checks",
"for",
"improper",
"use",
"of",
"DISALLOW",
"*",
"macros",
"."
] | def CheckAccess(filename, clean_lines, linenum, nesting_state, error):
"""Checks for improper use of DISALLOW* macros.
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: The function to call with any errors found.
"""
line = clean_lines.elided[linenum] # get rid of comments and strings
matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|'
r'DISALLOW_EVIL_CONSTRUCTORS|'
r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line)
if not matched:
return
if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo):
if nesting_state.stack[-1].access != 'private':
error(filename, linenum, 'readability/constructors', 3,
'%s must be in the private: section' % matched.group(1))
else:
# Found DISALLOW* macro outside a class declaration, or perhaps it
# was used inside a function when it should have been part of the
# class declaration. We could issue a warning here, but it
# probably resulted in a compiler error already.
pass | [
"def",
"CheckAccess",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# get rid of comments and strings",
"matched",
"=",
"Match",
"(",
"(",
"r'\\s*(DISALLOW_COPY_AND_ASSIGN|'",
"r'DISALLOW_EVIL_CONSTRUCTORS|'",
"r'DISALLOW_IMPLICIT_CONSTRUCTORS)'",
")",
",",
"line",
")",
"if",
"not",
"matched",
":",
"return",
"if",
"nesting_state",
".",
"stack",
"and",
"isinstance",
"(",
"nesting_state",
".",
"stack",
"[",
"-",
"1",
"]",
",",
"_ClassInfo",
")",
":",
"if",
"nesting_state",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"access",
"!=",
"'private'",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/constructors'",
",",
"3",
",",
"'%s must be in the private: section'",
"%",
"matched",
".",
"group",
"(",
"1",
")",
")",
"else",
":",
"# Found DISALLOW* macro outside a class declaration, or perhaps it",
"# was used inside a function when it should have been part of the",
"# class declaration. We could issue a warning here, but it",
"# probably resulted in a compiler error already.",
"pass"
] | https://github.com/bryanyzhu/Hidden-Two-Stream/blob/f7f684adbdacb6df6b1cf196c3a476cd23484a0f/scripts/cpp_lint.py#L2486-L2514 |
||
alibaba/MNN | c4d9566171d589c3ded23aa18ffb197016995a12 | pymnn/pip_package/MNN/expr/__init__.py | python | atan | (x) | return _F.atan(x) | atan(x)
Return the arctan(x), element-wise.
alias name: `arctan`.
Parameters
----------
x : var_like, input value.
Returns
-------
y : Var. The arctan of `x`.
Example:
-------
>>> expr.atan([9., 0.5])
var([1.4601392, 0.4636476]) | atan(x)
Return the arctan(x), element-wise.
alias name: `arctan`. | [
"atan",
"(",
"x",
")",
"Return",
"the",
"arctan",
"(",
"x",
")",
"element",
"-",
"wise",
".",
"alias",
"name",
":",
"arctan",
"."
] | def atan(x):
'''
atan(x)
Return the arctan(x), element-wise.
alias name: `arctan`.
Parameters
----------
x : var_like, input value.
Returns
-------
y : Var. The arctan of `x`.
Example:
-------
>>> expr.atan([9., 0.5])
var([1.4601392, 0.4636476])
'''
x = _to_var(x)
return _F.atan(x) | [
"def",
"atan",
"(",
"x",
")",
":",
"x",
"=",
"_to_var",
"(",
"x",
")",
"return",
"_F",
".",
"atan",
"(",
"x",
")"
] | https://github.com/alibaba/MNN/blob/c4d9566171d589c3ded23aa18ffb197016995a12/pymnn/pip_package/MNN/expr/__init__.py#L555-L575 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/containers.py | python | Window._get_margin_width | (self, margin: Margin) | return self._margin_width_cache.get(key, get_width) | Return the width for this margin.
(Calculate only once per render time.) | Return the width for this margin.
(Calculate only once per render time.) | [
"Return",
"the",
"width",
"for",
"this",
"margin",
".",
"(",
"Calculate",
"only",
"once",
"per",
"render",
"time",
".",
")"
] | def _get_margin_width(self, margin: Margin) -> int:
"""
Return the width for this margin.
(Calculate only once per render time.)
"""
# Margin.get_width, needs to have a UIContent instance.
def get_ui_content() -> UIContent:
return self._get_ui_content(width=0, height=0)
def get_width() -> int:
return margin.get_width(get_ui_content)
key = (margin, get_app().render_counter)
return self._margin_width_cache.get(key, get_width) | [
"def",
"_get_margin_width",
"(",
"self",
",",
"margin",
":",
"Margin",
")",
"->",
"int",
":",
"# Margin.get_width, needs to have a UIContent instance.",
"def",
"get_ui_content",
"(",
")",
"->",
"UIContent",
":",
"return",
"self",
".",
"_get_ui_content",
"(",
"width",
"=",
"0",
",",
"height",
"=",
"0",
")",
"def",
"get_width",
"(",
")",
"->",
"int",
":",
"return",
"margin",
".",
"get_width",
"(",
"get_ui_content",
")",
"key",
"=",
"(",
"margin",
",",
"get_app",
"(",
")",
".",
"render_counter",
")",
"return",
"self",
".",
"_margin_width_cache",
".",
"get",
"(",
"key",
",",
"get_width",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/containers.py#L1549-L1562 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextCtrl.SetUseAntiAliasing | (*args, **kwargs) | return _stc.StyledTextCtrl_SetUseAntiAliasing(*args, **kwargs) | SetUseAntiAliasing(self, bool useAA)
Specify whether anti-aliased fonts should be used. Will have no
effect on some platforms, but on some (wxMac for example) can greatly
improve performance. | SetUseAntiAliasing(self, bool useAA) | [
"SetUseAntiAliasing",
"(",
"self",
"bool",
"useAA",
")"
] | def SetUseAntiAliasing(*args, **kwargs):
"""
SetUseAntiAliasing(self, bool useAA)
Specify whether anti-aliased fonts should be used. Will have no
effect on some platforms, but on some (wxMac for example) can greatly
improve performance.
"""
return _stc.StyledTextCtrl_SetUseAntiAliasing(*args, **kwargs) | [
"def",
"SetUseAntiAliasing",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_SetUseAntiAliasing",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L6669-L6677 |
|
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/integrate/python/ops/odes.py | python | _ta_append | (tensor_array, value) | return tensor_array.write(tensor_array.size(), value) | Append a value to the end of a tf.TensorArray. | Append a value to the end of a tf.TensorArray. | [
"Append",
"a",
"value",
"to",
"the",
"end",
"of",
"a",
"tf",
".",
"TensorArray",
"."
] | def _ta_append(tensor_array, value):
"""Append a value to the end of a tf.TensorArray."""
return tensor_array.write(tensor_array.size(), value) | [
"def",
"_ta_append",
"(",
"tensor_array",
",",
"value",
")",
":",
"return",
"tensor_array",
".",
"write",
"(",
"tensor_array",
".",
"size",
"(",
")",
",",
"value",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/integrate/python/ops/odes.py#L244-L246 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/imaplib.py | python | IMAP4_stream.send | (self, data) | Send data to remote. | Send data to remote. | [
"Send",
"data",
"to",
"remote",
"."
] | def send(self, data):
"""Send data to remote."""
self.writefile.write(data)
self.writefile.flush() | [
"def",
"send",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"writefile",
".",
"write",
"(",
"data",
")",
"self",
".",
"writefile",
".",
"flush",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/imaplib.py#L1263-L1266 |
||
sofa-framework/sofa | 70628e35a44fcc258cf8250109b5e4eba8c5abe9 | applications/plugins/PSL/python/pslparserxml.py | python | toAst | (xmlnode) | return [(xmlnode.tag, childList)] | Takes an XMLNode and convert it into the AST structured used by PSL Engine. | Takes an XMLNode and convert it into the AST structured used by PSL Engine. | [
"Takes",
"an",
"XMLNode",
"and",
"convert",
"it",
"into",
"the",
"AST",
"structured",
"used",
"by",
"PSL",
"Engine",
"."
] | def toAst(xmlnode):
'''Takes an XMLNode and convert it into the AST structured used by PSL Engine.'''
childList = []
for k in xmlnode.attrib:
v = xmlnode.attrib[k]
if len(v) > 2 and v[0] == "p" and v[1] == "'" and v[-1] == "'":
childList.append( (k, ('p', v[2:-1] ) ) )
else:
childList.append( (k, ('s', v ) ) )
childList.reverse()
for child in xmlnode:
for j in toAst(child):
childList.append( j )
if len(childList) == 0:
if xmlnode.text == None:
return [(xmlnode.tag, [])]
else:
return [(xmlnode.tag, xmlnode.text)]
return [(xmlnode.tag, childList)] | [
"def",
"toAst",
"(",
"xmlnode",
")",
":",
"childList",
"=",
"[",
"]",
"for",
"k",
"in",
"xmlnode",
".",
"attrib",
":",
"v",
"=",
"xmlnode",
".",
"attrib",
"[",
"k",
"]",
"if",
"len",
"(",
"v",
")",
">",
"2",
"and",
"v",
"[",
"0",
"]",
"==",
"\"p\"",
"and",
"v",
"[",
"1",
"]",
"==",
"\"'\"",
"and",
"v",
"[",
"-",
"1",
"]",
"==",
"\"'\"",
":",
"childList",
".",
"append",
"(",
"(",
"k",
",",
"(",
"'p'",
",",
"v",
"[",
"2",
":",
"-",
"1",
"]",
")",
")",
")",
"else",
":",
"childList",
".",
"append",
"(",
"(",
"k",
",",
"(",
"'s'",
",",
"v",
")",
")",
")",
"childList",
".",
"reverse",
"(",
")",
"for",
"child",
"in",
"xmlnode",
":",
"for",
"j",
"in",
"toAst",
"(",
"child",
")",
":",
"childList",
".",
"append",
"(",
"j",
")",
"if",
"len",
"(",
"childList",
")",
"==",
"0",
":",
"if",
"xmlnode",
".",
"text",
"==",
"None",
":",
"return",
"[",
"(",
"xmlnode",
".",
"tag",
",",
"[",
"]",
")",
"]",
"else",
":",
"return",
"[",
"(",
"xmlnode",
".",
"tag",
",",
"xmlnode",
".",
"text",
")",
"]",
"return",
"[",
"(",
"xmlnode",
".",
"tag",
",",
"childList",
")",
"]"
] | https://github.com/sofa-framework/sofa/blob/70628e35a44fcc258cf8250109b5e4eba8c5abe9/applications/plugins/PSL/python/pslparserxml.py#L49-L70 |
|
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/make.py | python | MakefileWriter.WriteSubMake | (self, output_filename, makefile_path, targets, build_dir) | Write a "sub-project" Makefile.
This is a small, wrapper Makefile that calls the top-level Makefile to build
the targets from a single gyp file (i.e. a sub-project).
Arguments:
output_filename: sub-project Makefile name to write
makefile_path: path to the top-level Makefile
targets: list of "all" targets for this sub-project
build_dir: build output directory, relative to the sub-project | Write a "sub-project" Makefile. | [
"Write",
"a",
"sub",
"-",
"project",
"Makefile",
"."
] | def WriteSubMake(self, output_filename, makefile_path, targets, build_dir):
"""Write a "sub-project" Makefile.
This is a small, wrapper Makefile that calls the top-level Makefile to build
the targets from a single gyp file (i.e. a sub-project).
Arguments:
output_filename: sub-project Makefile name to write
makefile_path: path to the top-level Makefile
targets: list of "all" targets for this sub-project
build_dir: build output directory, relative to the sub-project
"""
ensure_directory_exists(output_filename)
self.fp = open(output_filename, 'w')
self.fp.write(header)
# For consistency with other builders, put sub-project build output in the
# sub-project dir (see test/subdirectory/gyptest-subdir-all.py).
self.WriteLn('export builddir_name ?= %s' %
os.path.join(os.path.dirname(output_filename), build_dir))
self.WriteLn('.PHONY: all')
self.WriteLn('all:')
if makefile_path:
makefile_path = ' -C ' + makefile_path
self.WriteLn('\t$(MAKE)%s %s' % (makefile_path, ' '.join(targets)))
self.fp.close() | [
"def",
"WriteSubMake",
"(",
"self",
",",
"output_filename",
",",
"makefile_path",
",",
"targets",
",",
"build_dir",
")",
":",
"ensure_directory_exists",
"(",
"output_filename",
")",
"self",
".",
"fp",
"=",
"open",
"(",
"output_filename",
",",
"'w'",
")",
"self",
".",
"fp",
".",
"write",
"(",
"header",
")",
"# For consistency with other builders, put sub-project build output in the",
"# sub-project dir (see test/subdirectory/gyptest-subdir-all.py).",
"self",
".",
"WriteLn",
"(",
"'export builddir_name ?= %s'",
"%",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"output_filename",
")",
",",
"build_dir",
")",
")",
"self",
".",
"WriteLn",
"(",
"'.PHONY: all'",
")",
"self",
".",
"WriteLn",
"(",
"'all:'",
")",
"if",
"makefile_path",
":",
"makefile_path",
"=",
"' -C '",
"+",
"makefile_path",
"self",
".",
"WriteLn",
"(",
"'\\t$(MAKE)%s %s'",
"%",
"(",
"makefile_path",
",",
"' '",
".",
"join",
"(",
"targets",
")",
")",
")",
"self",
".",
"fp",
".",
"close",
"(",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/make.py#L808-L832 |
||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/learn/python/learn/trainable.py | python | Trainable.fit | (self, x=None, y=None, input_fn=None, steps=None, batch_size=None,
monitors=None, max_steps=None) | Trains a model given training data `x` predictions and `y` labels.
Args:
x: Matrix of shape [n_samples, n_features...] or the dictionary of Matrices.
Can be iterator that returns arrays of features or dictionary of arrays of features.
The training input samples for fitting the model. If set, `input_fn` must be `None`.
y: Vector or matrix [n_samples] or [n_samples, n_outputs] or the dictionary of same.
Can be iterator that returns array of labels or dictionary of array of labels.
The training label values (class labels in classification, real numbers in regression).
If set, `input_fn` must be `None`. Note: For classification, label values must
be integers representing the class index (i.e. values from 0 to
n_classes-1).
input_fn: Input function returning a tuple of:
features - `Tensor` or dictionary of string feature name to `Tensor`.
labels - `Tensor` or dictionary of `Tensor` with labels.
If input_fn is set, `x`, `y`, and `batch_size` must be `None`.
steps: Number of steps for which to train model. If `None`, train forever.
'steps' works incrementally. If you call two times fit(steps=10) then
training occurs in total 20 steps. If you don't want to have incremental
behavior please set `max_steps` instead. If set, `max_steps` must be
`None`.
batch_size: minibatch size to use on the input, defaults to first
dimension of `x`. Must be `None` if `input_fn` is provided.
monitors: List of `BaseMonitor` subclass instances. Used for callbacks
inside the training loop.
max_steps: Number of total steps for which to train model. If `None`,
train forever. If set, `steps` must be `None`.
Two calls to `fit(steps=100)` means 200 training
iterations. On the other hand, two calls to `fit(max_steps=100)` means
that the second call will not do any iteration since first call did
all 100 steps.
Returns:
`self`, for chaining. | Trains a model given training data `x` predictions and `y` labels. | [
"Trains",
"a",
"model",
"given",
"training",
"data",
"x",
"predictions",
"and",
"y",
"labels",
"."
] | def fit(self, x=None, y=None, input_fn=None, steps=None, batch_size=None,
monitors=None, max_steps=None):
"""Trains a model given training data `x` predictions and `y` labels.
Args:
x: Matrix of shape [n_samples, n_features...] or the dictionary of Matrices.
Can be iterator that returns arrays of features or dictionary of arrays of features.
The training input samples for fitting the model. If set, `input_fn` must be `None`.
y: Vector or matrix [n_samples] or [n_samples, n_outputs] or the dictionary of same.
Can be iterator that returns array of labels or dictionary of array of labels.
The training label values (class labels in classification, real numbers in regression).
If set, `input_fn` must be `None`. Note: For classification, label values must
be integers representing the class index (i.e. values from 0 to
n_classes-1).
input_fn: Input function returning a tuple of:
features - `Tensor` or dictionary of string feature name to `Tensor`.
labels - `Tensor` or dictionary of `Tensor` with labels.
If input_fn is set, `x`, `y`, and `batch_size` must be `None`.
steps: Number of steps for which to train model. If `None`, train forever.
'steps' works incrementally. If you call two times fit(steps=10) then
training occurs in total 20 steps. If you don't want to have incremental
behavior please set `max_steps` instead. If set, `max_steps` must be
`None`.
batch_size: minibatch size to use on the input, defaults to first
dimension of `x`. Must be `None` if `input_fn` is provided.
monitors: List of `BaseMonitor` subclass instances. Used for callbacks
inside the training loop.
max_steps: Number of total steps for which to train model. If `None`,
train forever. If set, `steps` must be `None`.
Two calls to `fit(steps=100)` means 200 training
iterations. On the other hand, two calls to `fit(max_steps=100)` means
that the second call will not do any iteration since first call did
all 100 steps.
Returns:
`self`, for chaining.
"""
raise NotImplementedError | [
"def",
"fit",
"(",
"self",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"input_fn",
"=",
"None",
",",
"steps",
"=",
"None",
",",
"batch_size",
"=",
"None",
",",
"monitors",
"=",
"None",
",",
"max_steps",
"=",
"None",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/trainable.py#L31-L69 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/_psaix.py | python | swap_memory | () | return _common.sswap(total, used, free, percent, sin, sout) | Swap system memory as a (total, used, free, sin, sout) tuple. | Swap system memory as a (total, used, free, sin, sout) tuple. | [
"Swap",
"system",
"memory",
"as",
"a",
"(",
"total",
"used",
"free",
"sin",
"sout",
")",
"tuple",
"."
] | def swap_memory():
"""Swap system memory as a (total, used, free, sin, sout) tuple."""
total, free, sin, sout = cext.swap_mem()
used = total - free
percent = usage_percent(used, total, round_=1)
return _common.sswap(total, used, free, percent, sin, sout) | [
"def",
"swap_memory",
"(",
")",
":",
"total",
",",
"free",
",",
"sin",
",",
"sout",
"=",
"cext",
".",
"swap_mem",
"(",
")",
"used",
"=",
"total",
"-",
"free",
"percent",
"=",
"usage_percent",
"(",
"used",
",",
"total",
",",
"round_",
"=",
"1",
")",
"return",
"_common",
".",
"sswap",
"(",
"total",
",",
"used",
",",
"free",
",",
"percent",
",",
"sin",
",",
"sout",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/_psaix.py#L112-L117 |
|
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/probability/distribution/uniform.py | python | Uniform._entropy | (self, low=None, high=None) | return self.log(high - low) | r"""
.. math::
H(U) = \log(high - low). | r"""
.. math::
H(U) = \log(high - low). | [
"r",
"..",
"math",
"::",
"H",
"(",
"U",
")",
"=",
"\\",
"log",
"(",
"high",
"-",
"low",
")",
"."
] | def _entropy(self, low=None, high=None):
r"""
.. math::
H(U) = \log(high - low).
"""
low, high = self._check_param_type(low, high)
return self.log(high - low) | [
"def",
"_entropy",
"(",
"self",
",",
"low",
"=",
"None",
",",
"high",
"=",
"None",
")",
":",
"low",
",",
"high",
"=",
"self",
".",
"_check_param_type",
"(",
"low",
",",
"high",
")",
"return",
"self",
".",
"log",
"(",
"high",
"-",
"low",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/distribution/uniform.py#L264-L270 |
|
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/python-gflags/gflags.py | python | BooleanParser.Convert | (self, argument) | Converts the argument to a boolean; raise ValueError on errors. | Converts the argument to a boolean; raise ValueError on errors. | [
"Converts",
"the",
"argument",
"to",
"a",
"boolean",
";",
"raise",
"ValueError",
"on",
"errors",
"."
] | def Convert(self, argument):
"""Converts the argument to a boolean; raise ValueError on errors."""
if type(argument) == str:
if argument.lower() in ['true', 't', '1']:
return True
elif argument.lower() in ['false', 'f', '0']:
return False
bool_argument = bool(argument)
if argument == bool_argument:
# The argument is a valid boolean (True, False, 0, or 1), and not just
# something that always converts to bool (list, string, int, etc.).
return bool_argument
raise ValueError('Non-boolean argument to boolean flag', argument) | [
"def",
"Convert",
"(",
"self",
",",
"argument",
")",
":",
"if",
"type",
"(",
"argument",
")",
"==",
"str",
":",
"if",
"argument",
".",
"lower",
"(",
")",
"in",
"[",
"'true'",
",",
"'t'",
",",
"'1'",
"]",
":",
"return",
"True",
"elif",
"argument",
".",
"lower",
"(",
")",
"in",
"[",
"'false'",
",",
"'f'",
",",
"'0'",
"]",
":",
"return",
"False",
"bool_argument",
"=",
"bool",
"(",
"argument",
")",
"if",
"argument",
"==",
"bool_argument",
":",
"# The argument is a valid boolean (True, False, 0, or 1), and not just",
"# something that always converts to bool (list, string, int, etc.).",
"return",
"bool_argument",
"raise",
"ValueError",
"(",
"'Non-boolean argument to boolean flag'",
",",
"argument",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/python-gflags/gflags.py#L2324-L2338 |
||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py | python | uCSIsTaiXuanJingSymbols | (code) | return ret | Check whether the character is part of TaiXuanJingSymbols
UCS Block | Check whether the character is part of TaiXuanJingSymbols
UCS Block | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"TaiXuanJingSymbols",
"UCS",
"Block"
] | def uCSIsTaiXuanJingSymbols(code):
"""Check whether the character is part of TaiXuanJingSymbols
UCS Block """
ret = libxml2mod.xmlUCSIsTaiXuanJingSymbols(code)
return ret | [
"def",
"uCSIsTaiXuanJingSymbols",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsTaiXuanJingSymbols",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L2927-L2931 |
|
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | chrome/common/extensions/docs/examples/apps/hello-python/httplib2/__init__.py | python | Authentication.response | (self, response, content) | return False | Gives us a chance to update with new nonces
or such returned from the last authorized response.
Over-rise this in sub-classes if necessary.
Return TRUE is the request is to be retried, for
example Digest may return stale=true. | Gives us a chance to update with new nonces
or such returned from the last authorized response.
Over-rise this in sub-classes if necessary. | [
"Gives",
"us",
"a",
"chance",
"to",
"update",
"with",
"new",
"nonces",
"or",
"such",
"returned",
"from",
"the",
"last",
"authorized",
"response",
".",
"Over",
"-",
"rise",
"this",
"in",
"sub",
"-",
"classes",
"if",
"necessary",
"."
] | def response(self, response, content):
"""Gives us a chance to update with new nonces
or such returned from the last authorized response.
Over-rise this in sub-classes if necessary.
Return TRUE is the request is to be retried, for
example Digest may return stale=true.
"""
return False | [
"def",
"response",
"(",
"self",
",",
"response",
",",
"content",
")",
":",
"return",
"False"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/chrome/common/extensions/docs/examples/apps/hello-python/httplib2/__init__.py#L436-L444 |
|
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/io_ops.py | python | _ReadFileShape | (op) | return [op.inputs[0].get_shape().merge_with(tensor_shape.scalar())] | Shape function for the ReadFile op. | Shape function for the ReadFile op. | [
"Shape",
"function",
"for",
"the",
"ReadFile",
"op",
"."
] | def _ReadFileShape(op):
"""Shape function for the ReadFile op."""
return [op.inputs[0].get_shape().merge_with(tensor_shape.scalar())] | [
"def",
"_ReadFileShape",
"(",
"op",
")",
":",
"return",
"[",
"op",
".",
"inputs",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
".",
"merge_with",
"(",
"tensor_shape",
".",
"scalar",
"(",
")",
")",
"]"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/io_ops.py#L622-L624 |
|
CalcProgrammer1/OpenRGB | 8156b0167a7590dd8ba561dfde524bfcacf46b5e | dependencies/mbedtls-2.24.0/scripts/assemble_changelog.py | python | main | () | Command line entry point. | Command line entry point. | [
"Command",
"line",
"entry",
"point",
"."
] | def main():
"""Command line entry point."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--dir', '-d', metavar='DIR',
default='ChangeLog.d',
help='Directory to read entries from'
' (default: ChangeLog.d)')
parser.add_argument('--input', '-i', metavar='FILE',
default='ChangeLog',
help='Existing changelog file to read from and augment'
' (default: ChangeLog)')
parser.add_argument('--keep-entries',
action='store_true', dest='keep_entries', default=None,
help='Keep the files containing entries'
' (default: remove them if --output/-o is not specified)')
parser.add_argument('--no-keep-entries',
action='store_false', dest='keep_entries',
help='Remove the files containing entries after they are merged'
' (default: remove them if --output/-o is not specified)')
parser.add_argument('--output', '-o', metavar='FILE',
help='Output changelog file'
' (default: overwrite the input)')
parser.add_argument('--list-files-only',
action='store_true',
help=('Only list the files that would be processed '
'(with some debugging information)'))
options = parser.parse_args()
set_defaults(options)
if options.list_files_only:
show_file_timestamps(options)
return
merge_entries(options) | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"'--dir'",
",",
"'-d'",
",",
"metavar",
"=",
"'DIR'",
",",
"default",
"=",
"'ChangeLog.d'",
",",
"help",
"=",
"'Directory to read entries from'",
"' (default: ChangeLog.d)'",
")",
"parser",
".",
"add_argument",
"(",
"'--input'",
",",
"'-i'",
",",
"metavar",
"=",
"'FILE'",
",",
"default",
"=",
"'ChangeLog'",
",",
"help",
"=",
"'Existing changelog file to read from and augment'",
"' (default: ChangeLog)'",
")",
"parser",
".",
"add_argument",
"(",
"'--keep-entries'",
",",
"action",
"=",
"'store_true'",
",",
"dest",
"=",
"'keep_entries'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"'Keep the files containing entries'",
"' (default: remove them if --output/-o is not specified)'",
")",
"parser",
".",
"add_argument",
"(",
"'--no-keep-entries'",
",",
"action",
"=",
"'store_false'",
",",
"dest",
"=",
"'keep_entries'",
",",
"help",
"=",
"'Remove the files containing entries after they are merged'",
"' (default: remove them if --output/-o is not specified)'",
")",
"parser",
".",
"add_argument",
"(",
"'--output'",
",",
"'-o'",
",",
"metavar",
"=",
"'FILE'",
",",
"help",
"=",
"'Output changelog file'",
"' (default: overwrite the input)'",
")",
"parser",
".",
"add_argument",
"(",
"'--list-files-only'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"(",
"'Only list the files that would be processed '",
"'(with some debugging information)'",
")",
")",
"options",
"=",
"parser",
".",
"parse_args",
"(",
")",
"set_defaults",
"(",
"options",
")",
"if",
"options",
".",
"list_files_only",
":",
"show_file_timestamps",
"(",
"options",
")",
"return",
"merge_entries",
"(",
"options",
")"
] | https://github.com/CalcProgrammer1/OpenRGB/blob/8156b0167a7590dd8ba561dfde524bfcacf46b5e/dependencies/mbedtls-2.24.0/scripts/assemble_changelog.py#L469-L500 |
||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/_pyio.py | python | BufferedIOBase.write | (self, b) | Write the given buffer to the IO stream.
Return the number of bytes written, which is never less than
len(b).
Raises BlockingIOError if the buffer is full and the
underlying raw stream cannot accept more data at the moment. | Write the given buffer to the IO stream. | [
"Write",
"the",
"given",
"buffer",
"to",
"the",
"IO",
"stream",
"."
] | def write(self, b):
"""Write the given buffer to the IO stream.
Return the number of bytes written, which is never less than
len(b).
Raises BlockingIOError if the buffer is full and the
underlying raw stream cannot accept more data at the moment.
"""
self._unsupported("write") | [
"def",
"write",
"(",
"self",
",",
"b",
")",
":",
"self",
".",
"_unsupported",
"(",
"\"write\"",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/_pyio.py#L656-L665 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/graphics.py | python | GraphicsPath.AddCurveToPoint | (self, cx1, cy1, cx2, cy2, x, y) | return self | Adds a cubic Bezier curve from the current point, using two
control points and an end point. | Adds a cubic Bezier curve from the current point, using two
control points and an end point. | [
"Adds",
"a",
"cubic",
"Bezier",
"curve",
"from",
"the",
"current",
"point",
"using",
"two",
"control",
"points",
"and",
"an",
"end",
"point",
"."
] | def AddCurveToPoint(self, cx1, cy1, cx2, cy2, x, y):
"""
Adds a cubic Bezier curve from the current point, using two
control points and an end point.
"""
self._pathContext.curve_to(cx1, cy1, cx2, cy2, x, y)
return self | [
"def",
"AddCurveToPoint",
"(",
"self",
",",
"cx1",
",",
"cy1",
",",
"cx2",
",",
"cy2",
",",
"x",
",",
"y",
")",
":",
"self",
".",
"_pathContext",
".",
"curve_to",
"(",
"cx1",
",",
"cy1",
",",
"cx2",
",",
"cy2",
",",
"x",
",",
"y",
")",
"return",
"self"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/graphics.py#L723-L729 |
|
deepmind/reverb | ef3c8f0be1b720a741d2dee335e15e44668c291a | reverb/trajectory_writer.py | python | _ColumnHistory.__init__ | (self,
path: Tuple[Union[str, int], ...],
buffer_size: int,
history_padding: int = 0) | Constructor for _ColumnHistory.
Args:
path: A Tuple of strings and ints that represents which leaf-node this
column represents in TrajectoryWriter._structure.
buffer_size: The maximum number of values to keep in the buffer.
history_padding: The number of Nones used to forward-pad the column's
history. | Constructor for _ColumnHistory. | [
"Constructor",
"for",
"_ColumnHistory",
"."
] | def __init__(self,
path: Tuple[Union[str, int], ...],
buffer_size: int,
history_padding: int = 0):
"""Constructor for _ColumnHistory.
Args:
path: A Tuple of strings and ints that represents which leaf-node this
column represents in TrajectoryWriter._structure.
buffer_size: The maximum number of values to keep in the buffer.
history_padding: The number of Nones used to forward-pad the column's
history.
"""
self._path = path
self._buffer_size = buffer_size
self._data_references: List[Optional[pybind.WeakCellRef]] = (
[None] * min(buffer_size, history_padding))
self._offset = history_padding - len(self._data_references) | [
"def",
"__init__",
"(",
"self",
",",
"path",
":",
"Tuple",
"[",
"Union",
"[",
"str",
",",
"int",
"]",
",",
"...",
"]",
",",
"buffer_size",
":",
"int",
",",
"history_padding",
":",
"int",
"=",
"0",
")",
":",
"self",
".",
"_path",
"=",
"path",
"self",
".",
"_buffer_size",
"=",
"buffer_size",
"self",
".",
"_data_references",
":",
"List",
"[",
"Optional",
"[",
"pybind",
".",
"WeakCellRef",
"]",
"]",
"=",
"(",
"[",
"None",
"]",
"*",
"min",
"(",
"buffer_size",
",",
"history_padding",
")",
")",
"self",
".",
"_offset",
"=",
"history_padding",
"-",
"len",
"(",
"self",
".",
"_data_references",
")"
] | https://github.com/deepmind/reverb/blob/ef3c8f0be1b720a741d2dee335e15e44668c291a/reverb/trajectory_writer.py#L504-L521 |
||
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/resmokelib/logging/loggers.py | python | FixtureNodeLogger.__init__ | (self, fixture_class, job_num, node_name, fixture_logger) | Initialize a FixtureNodeLogger.
:param fixture_class: the name of the fixture implementation class.
:param job_num: the number of the job the fixture is running on.
:param node_name: the node display name.
:param fixture_logger: the parent fixture logger. | Initialize a FixtureNodeLogger. | [
"Initialize",
"a",
"FixtureNodeLogger",
"."
] | def __init__(self, fixture_class, job_num, node_name, fixture_logger):
"""Initialize a FixtureNodeLogger.
:param fixture_class: the name of the fixture implementation class.
:param job_num: the number of the job the fixture is running on.
:param node_name: the node display name.
:param fixture_logger: the parent fixture logger.
"""
BaseLogger.__init__(self, "%s:job%d:%s" % (fixture_class, job_num, node_name),
parent=fixture_logger)
self.fixture_class = fixture_class
self.job_num = job_num
self.node_name = node_name | [
"def",
"__init__",
"(",
"self",
",",
"fixture_class",
",",
"job_num",
",",
"node_name",
",",
"fixture_logger",
")",
":",
"BaseLogger",
".",
"__init__",
"(",
"self",
",",
"\"%s:job%d:%s\"",
"%",
"(",
"fixture_class",
",",
"job_num",
",",
"node_name",
")",
",",
"parent",
"=",
"fixture_logger",
")",
"self",
".",
"fixture_class",
"=",
"fixture_class",
"self",
".",
"job_num",
"=",
"job_num",
"self",
".",
"node_name",
"=",
"node_name"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/resmokelib/logging/loggers.py#L276-L288 |
||
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/boost_1.75.0/tools/build/src/util/regex.py | python | replace_list | (items, match, replacement) | return [replace(item, match, replacement) for item in items] | Replaces occurrences of a match string in a given list of strings and returns
a list of new strings. The match string can be a regex expression.
Args:
items (list): the list of strings to modify.
match (str): the search expression.
replacement (str): the string to replace with. | Replaces occurrences of a match string in a given list of strings and returns
a list of new strings. The match string can be a regex expression. | [
"Replaces",
"occurrences",
"of",
"a",
"match",
"string",
"in",
"a",
"given",
"list",
"of",
"strings",
"and",
"returns",
"a",
"list",
"of",
"new",
"strings",
".",
"The",
"match",
"string",
"can",
"be",
"a",
"regex",
"expression",
"."
] | def replace_list(items, match, replacement):
"""Replaces occurrences of a match string in a given list of strings and returns
a list of new strings. The match string can be a regex expression.
Args:
items (list): the list of strings to modify.
match (str): the search expression.
replacement (str): the string to replace with.
"""
return [replace(item, match, replacement) for item in items] | [
"def",
"replace_list",
"(",
"items",
",",
"match",
",",
"replacement",
")",
":",
"return",
"[",
"replace",
"(",
"item",
",",
"match",
",",
"replacement",
")",
"for",
"item",
"in",
"items",
"]"
] | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/boost_1.75.0/tools/build/src/util/regex.py#L54-L63 |
|
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/nn/functional.py | python | glu | (input: Tensor, dim: int = -1) | return torch._C._nn.glu(input, dim) | r"""
glu(input, dim=-1) -> Tensor
The gated linear unit. Computes:
.. math ::
\text{GLU}(a, b) = a \otimes \sigma(b)
where `input` is split in half along `dim` to form `a` and `b`, :math:`\sigma`
is the sigmoid function and :math:`\otimes` is the element-wise product between matrices.
See `Language Modeling with Gated Convolutional Networks <https://arxiv.org/abs/1612.08083>`_.
Args:
input (Tensor): input tensor
dim (int): dimension on which to split the input. Default: -1 | r"""
glu(input, dim=-1) -> Tensor | [
"r",
"glu",
"(",
"input",
"dim",
"=",
"-",
"1",
")",
"-",
">",
"Tensor"
] | def glu(input: Tensor, dim: int = -1) -> Tensor:
r"""
glu(input, dim=-1) -> Tensor
The gated linear unit. Computes:
.. math ::
\text{GLU}(a, b) = a \otimes \sigma(b)
where `input` is split in half along `dim` to form `a` and `b`, :math:`\sigma`
is the sigmoid function and :math:`\otimes` is the element-wise product between matrices.
See `Language Modeling with Gated Convolutional Networks <https://arxiv.org/abs/1612.08083>`_.
Args:
input (Tensor): input tensor
dim (int): dimension on which to split the input. Default: -1
"""
if has_torch_function_unary(input):
return handle_torch_function(glu, (input,), input, dim=dim)
if input.dim() == 0:
raise RuntimeError("glu does not support scalars because halving size must be even")
return torch._C._nn.glu(input, dim) | [
"def",
"glu",
"(",
"input",
":",
"Tensor",
",",
"dim",
":",
"int",
"=",
"-",
"1",
")",
"->",
"Tensor",
":",
"if",
"has_torch_function_unary",
"(",
"input",
")",
":",
"return",
"handle_torch_function",
"(",
"glu",
",",
"(",
"input",
",",
")",
",",
"input",
",",
"dim",
"=",
"dim",
")",
"if",
"input",
".",
"dim",
"(",
")",
"==",
"0",
":",
"raise",
"RuntimeError",
"(",
"\"glu does not support scalars because halving size must be even\"",
")",
"return",
"torch",
".",
"_C",
".",
"_nn",
".",
"glu",
"(",
"input",
",",
"dim",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/nn/functional.py#L1456-L1478 |
|
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/incubate/fleet/utils/fleet_util.py | python | FleetUtil.save_cache_model | (self, output_path, day, pass_id, mode=1, **kwargs) | return key_num | save cache model
Args:
output_path(str): output path
day(str|int): training day
pass_id(str|int): training pass id
mode(str|int): save mode
kwargs(dict): user defined properties
table_id(int): table id to save cache
Returns:
key_num(int): cache key num
Examples:
.. code-block:: python
from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
fleet_util = FleetUtil()
fleet_util.save_cache_model("hdfs:/my/path", 20190722, 88) | save cache model | [
"save",
"cache",
"model"
] | def save_cache_model(self, output_path, day, pass_id, mode=1, **kwargs):
"""
save cache model
Args:
output_path(str): output path
day(str|int): training day
pass_id(str|int): training pass id
mode(str|int): save mode
kwargs(dict): user defined properties
table_id(int): table id to save cache
Returns:
key_num(int): cache key num
Examples:
.. code-block:: python
from paddle.fluid.incubate.fleet.utils.fleet_util import FleetUtil
fleet_util = FleetUtil()
fleet_util.save_cache_model("hdfs:/my/path", 20190722, 88)
"""
day = str(day)
pass_id = str(pass_id)
mode = int(mode)
table_id = kwargs.get("table_id", 0)
suffix_name = "/%s/delta-%s" % (day, pass_id)
model_path = output_path.rstrip("/") + suffix_name
self.rank0_print("going to save_cache_model %s" % model_path)
key_num = fleet.save_cache_model(
None, model_path, mode=mode, table_id=table_id)
self.rank0_print("save_cache_model done")
return key_num | [
"def",
"save_cache_model",
"(",
"self",
",",
"output_path",
",",
"day",
",",
"pass_id",
",",
"mode",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"day",
"=",
"str",
"(",
"day",
")",
"pass_id",
"=",
"str",
"(",
"pass_id",
")",
"mode",
"=",
"int",
"(",
"mode",
")",
"table_id",
"=",
"kwargs",
".",
"get",
"(",
"\"table_id\"",
",",
"0",
")",
"suffix_name",
"=",
"\"/%s/delta-%s\"",
"%",
"(",
"day",
",",
"pass_id",
")",
"model_path",
"=",
"output_path",
".",
"rstrip",
"(",
"\"/\"",
")",
"+",
"suffix_name",
"self",
".",
"rank0_print",
"(",
"\"going to save_cache_model %s\"",
"%",
"model_path",
")",
"key_num",
"=",
"fleet",
".",
"save_cache_model",
"(",
"None",
",",
"model_path",
",",
"mode",
"=",
"mode",
",",
"table_id",
"=",
"table_id",
")",
"self",
".",
"rank0_print",
"(",
"\"save_cache_model done\"",
")",
"return",
"key_num"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/incubate/fleet/utils/fleet_util.py#L750-L783 |
|
AojunZhou/Incremental-Network-Quantization | c7f6a609d5817d8424ce224209cf4c50f1e4de50 | scripts/cpp_lint.py | python | CheckComment | (comment, filename, linenum, error) | Checks for common mistakes in TODO comments.
Args:
comment: The text of the comment from the line in question.
filename: The name of the current file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks for common mistakes in TODO comments. | [
"Checks",
"for",
"common",
"mistakes",
"in",
"TODO",
"comments",
"."
] | def CheckComment(comment, filename, linenum, error):
"""Checks for common mistakes in TODO comments.
Args:
comment: The text of the comment from the line in question.
filename: The name of the current file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
match = _RE_PATTERN_TODO.match(comment)
if match:
# One whitespace is correct; zero whitespace is handled elsewhere.
leading_whitespace = match.group(1)
if len(leading_whitespace) > 1:
error(filename, linenum, 'whitespace/todo', 2,
'Too many spaces before TODO')
username = match.group(2)
if not username:
error(filename, linenum, 'readability/todo', 2,
'Missing username in TODO; it should look like '
'"// TODO(my_username): Stuff."')
middle_whitespace = match.group(3)
# Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
if middle_whitespace != ' ' and middle_whitespace != '':
error(filename, linenum, 'whitespace/todo', 2,
'TODO(my_username) should be followed by a space') | [
"def",
"CheckComment",
"(",
"comment",
",",
"filename",
",",
"linenum",
",",
"error",
")",
":",
"match",
"=",
"_RE_PATTERN_TODO",
".",
"match",
"(",
"comment",
")",
"if",
"match",
":",
"# One whitespace is correct; zero whitespace is handled elsewhere.",
"leading_whitespace",
"=",
"match",
".",
"group",
"(",
"1",
")",
"if",
"len",
"(",
"leading_whitespace",
")",
">",
"1",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/todo'",
",",
"2",
",",
"'Too many spaces before TODO'",
")",
"username",
"=",
"match",
".",
"group",
"(",
"2",
")",
"if",
"not",
"username",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/todo'",
",",
"2",
",",
"'Missing username in TODO; it should look like '",
"'\"// TODO(my_username): Stuff.\"'",
")",
"middle_whitespace",
"=",
"match",
".",
"group",
"(",
"3",
")",
"# Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison",
"if",
"middle_whitespace",
"!=",
"' '",
"and",
"middle_whitespace",
"!=",
"''",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/todo'",
",",
"2",
",",
"'TODO(my_username) should be followed by a space'",
")"
] | https://github.com/AojunZhou/Incremental-Network-Quantization/blob/c7f6a609d5817d8424ce224209cf4c50f1e4de50/scripts/cpp_lint.py#L2457-L2484 |
||
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | bindings/python/cntk/contrib/crosstalkcaffe/adapter/bvlccaffe/caffeadapter.py | python | SetupCaffeParameters.default | (caffe_parameters, inputs_info, cntk_layer_def, tensor_check=True) | The default Caffe to CNTK uniform model setup
Args:
caffe_parameters (:class:`caffe.Parameters`): the parameters of Caffe
inputs_info ('class':`cntk.contrib.crosstalkcaffe.unimodel.cntkmodel.CntkTensorDefinition`):
The input information of current layer
cntk_layer_def ('class':`cntk.contrib.crosstalkcaffe.unimodel.cntkmodel.CntkLayersDefinition`):
The converted definition of CNTK layers
tensor_check (bool, default=True): Whether to check the tensor shape
Return:
None | The default Caffe to CNTK uniform model setup | [
"The",
"default",
"Caffe",
"to",
"CNTK",
"uniform",
"model",
"setup"
] | def default(caffe_parameters, inputs_info, cntk_layer_def, tensor_check=True):
'''
The default Caffe to CNTK uniform model setup
Args:
caffe_parameters (:class:`caffe.Parameters`): the parameters of Caffe
inputs_info ('class':`cntk.contrib.crosstalkcaffe.unimodel.cntkmodel.CntkTensorDefinition`):
The input information of current layer
cntk_layer_def ('class':`cntk.contrib.crosstalkcaffe.unimodel.cntkmodel.CntkLayersDefinition`):
The converted definition of CNTK layers
tensor_check (bool, default=True): Whether to check the tensor shape
Return:
None
'''
if caffe_parameters:
pass
# tensor align check
if not tensor_check:
cntk_layer_def.parameters = cntkmodel.CntkParameters()
return
try:
identity_check = inputs_info[0].tensor[:]
for input_info in inputs_info:
if not input_info.tensor == identity_check:
raise AttributeError('Non-align input tensor %s', cntk_layer_def.op_name)
except OverflowError:
raise AttributeError('Non-align input tensor %s', cntk_layer_def.op_name)
cntk_layer_def.tensor = identity_check
if not cntk_layer_def.parameters:
cntk_layer_def.parameters = cntkmodel.CntkParameters() | [
"def",
"default",
"(",
"caffe_parameters",
",",
"inputs_info",
",",
"cntk_layer_def",
",",
"tensor_check",
"=",
"True",
")",
":",
"if",
"caffe_parameters",
":",
"pass",
"# tensor align check",
"if",
"not",
"tensor_check",
":",
"cntk_layer_def",
".",
"parameters",
"=",
"cntkmodel",
".",
"CntkParameters",
"(",
")",
"return",
"try",
":",
"identity_check",
"=",
"inputs_info",
"[",
"0",
"]",
".",
"tensor",
"[",
":",
"]",
"for",
"input_info",
"in",
"inputs_info",
":",
"if",
"not",
"input_info",
".",
"tensor",
"==",
"identity_check",
":",
"raise",
"AttributeError",
"(",
"'Non-align input tensor %s'",
",",
"cntk_layer_def",
".",
"op_name",
")",
"except",
"OverflowError",
":",
"raise",
"AttributeError",
"(",
"'Non-align input tensor %s'",
",",
"cntk_layer_def",
".",
"op_name",
")",
"cntk_layer_def",
".",
"tensor",
"=",
"identity_check",
"if",
"not",
"cntk_layer_def",
".",
"parameters",
":",
"cntk_layer_def",
".",
"parameters",
"=",
"cntkmodel",
".",
"CntkParameters",
"(",
")"
] | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/contrib/crosstalkcaffe/adapter/bvlccaffe/caffeadapter.py#L61-L92 |
||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/gyp/pylib/gyp/generator/msvs.py | python | _AddConditionalProperty | (properties, condition, name, value) | Adds a property / conditional value pair to a dictionary.
Arguments:
properties: The dictionary to be modified. The key is the name of the
property. The value is itself a dictionary; its key is the value and
the value a list of condition for which this value is true.
condition: The condition under which the named property has the value.
name: The name of the property.
value: The value of the property. | Adds a property / conditional value pair to a dictionary. | [
"Adds",
"a",
"property",
"/",
"conditional",
"value",
"pair",
"to",
"a",
"dictionary",
"."
] | def _AddConditionalProperty(properties, condition, name, value):
"""Adds a property / conditional value pair to a dictionary.
Arguments:
properties: The dictionary to be modified. The key is the name of the
property. The value is itself a dictionary; its key is the value and
the value a list of condition for which this value is true.
condition: The condition under which the named property has the value.
name: The name of the property.
value: The value of the property.
"""
if name not in properties:
properties[name] = {}
values = properties[name]
if value not in values:
values[value] = []
conditions = values[value]
conditions.append(condition) | [
"def",
"_AddConditionalProperty",
"(",
"properties",
",",
"condition",
",",
"name",
",",
"value",
")",
":",
"if",
"name",
"not",
"in",
"properties",
":",
"properties",
"[",
"name",
"]",
"=",
"{",
"}",
"values",
"=",
"properties",
"[",
"name",
"]",
"if",
"value",
"not",
"in",
"values",
":",
"values",
"[",
"value",
"]",
"=",
"[",
"]",
"conditions",
"=",
"values",
"[",
"value",
"]",
"conditions",
".",
"append",
"(",
"condition",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/generator/msvs.py#L2979-L2996 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/package_index.py | python | find_external_links | (url, page) | Find rel="homepage" and rel="download" links in `page`, yielding URLs | Find rel="homepage" and rel="download" links in `page`, yielding URLs | [
"Find",
"rel",
"=",
"homepage",
"and",
"rel",
"=",
"download",
"links",
"in",
"page",
"yielding",
"URLs"
] | def find_external_links(url, page):
"""Find rel="homepage" and rel="download" links in `page`, yielding URLs"""
for match in REL.finditer(page):
tag, rel = match.groups()
rels = set(map(str.strip, rel.lower().split(',')))
if 'homepage' in rels or 'download' in rels:
for match in HREF.finditer(tag):
yield urllib.parse.urljoin(url, htmldecode(match.group(1)))
for tag in ("<th>Home Page", "<th>Download URL"):
pos = page.find(tag)
if pos != -1:
match = HREF.search(page, pos)
if match:
yield urllib.parse.urljoin(url, htmldecode(match.group(1))) | [
"def",
"find_external_links",
"(",
"url",
",",
"page",
")",
":",
"for",
"match",
"in",
"REL",
".",
"finditer",
"(",
"page",
")",
":",
"tag",
",",
"rel",
"=",
"match",
".",
"groups",
"(",
")",
"rels",
"=",
"set",
"(",
"map",
"(",
"str",
".",
"strip",
",",
"rel",
".",
"lower",
"(",
")",
".",
"split",
"(",
"','",
")",
")",
")",
"if",
"'homepage'",
"in",
"rels",
"or",
"'download'",
"in",
"rels",
":",
"for",
"match",
"in",
"HREF",
".",
"finditer",
"(",
"tag",
")",
":",
"yield",
"urllib",
".",
"parse",
".",
"urljoin",
"(",
"url",
",",
"htmldecode",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
")",
"for",
"tag",
"in",
"(",
"\"<th>Home Page\"",
",",
"\"<th>Download URL\"",
")",
":",
"pos",
"=",
"page",
".",
"find",
"(",
"tag",
")",
"if",
"pos",
"!=",
"-",
"1",
":",
"match",
"=",
"HREF",
".",
"search",
"(",
"page",
",",
"pos",
")",
"if",
"match",
":",
"yield",
"urllib",
".",
"parse",
".",
"urljoin",
"(",
"url",
",",
"htmldecode",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/package_index.py#L223-L238 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/locators.py | python | DependencyFinder.remove_distribution | (self, dist) | Remove a distribution from the finder. This will update internal
information about who provides what.
:param dist: The distribution to remove. | Remove a distribution from the finder. This will update internal
information about who provides what.
:param dist: The distribution to remove. | [
"Remove",
"a",
"distribution",
"from",
"the",
"finder",
".",
"This",
"will",
"update",
"internal",
"information",
"about",
"who",
"provides",
"what",
".",
":",
"param",
"dist",
":",
"The",
"distribution",
"to",
"remove",
"."
] | def remove_distribution(self, dist):
"""
Remove a distribution from the finder. This will update internal
information about who provides what.
:param dist: The distribution to remove.
"""
logger.debug('removing distribution %s', dist)
name = dist.key
del self.dists_by_name[name]
del self.dists[(name, dist.version)]
for p in dist.provides:
name, version = parse_name_and_version(p)
logger.debug('Remove from provided: %s, %s, %s', name, version, dist)
s = self.provided[name]
s.remove((version, dist))
if not s:
del self.provided[name] | [
"def",
"remove_distribution",
"(",
"self",
",",
"dist",
")",
":",
"logger",
".",
"debug",
"(",
"'removing distribution %s'",
",",
"dist",
")",
"name",
"=",
"dist",
".",
"key",
"del",
"self",
".",
"dists_by_name",
"[",
"name",
"]",
"del",
"self",
".",
"dists",
"[",
"(",
"name",
",",
"dist",
".",
"version",
")",
"]",
"for",
"p",
"in",
"dist",
".",
"provides",
":",
"name",
",",
"version",
"=",
"parse_name_and_version",
"(",
"p",
")",
"logger",
".",
"debug",
"(",
"'Remove from provided: %s, %s, %s'",
",",
"name",
",",
"version",
",",
"dist",
")",
"s",
"=",
"self",
".",
"provided",
"[",
"name",
"]",
"s",
".",
"remove",
"(",
"(",
"version",
",",
"dist",
")",
")",
"if",
"not",
"s",
":",
"del",
"self",
".",
"provided",
"[",
"name",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/locators.py#L1096-L1112 |
||
baidu/unit-uskit | ee283f3be42a1dadaef80751d4ed4358ee83c2e8 | conf/us/demo/conf_generator.py | python | generate_redis_backend_conf | (fout) | Generate redis backend | Generate redis backend | [
"Generate",
"redis",
"backend"
] | def generate_redis_backend_conf(fout):
"""
Generate redis backend
"""
with open('./conf_templates/redis_backend.template') as fin:
template = ConfTemplate(fin.read())
print(template.substitute(options), file=fout) | [
"def",
"generate_redis_backend_conf",
"(",
"fout",
")",
":",
"with",
"open",
"(",
"'./conf_templates/redis_backend.template'",
")",
"as",
"fin",
":",
"template",
"=",
"ConfTemplate",
"(",
"fin",
".",
"read",
"(",
")",
")",
"print",
"(",
"template",
".",
"substitute",
"(",
"options",
")",
",",
"file",
"=",
"fout",
")"
] | https://github.com/baidu/unit-uskit/blob/ee283f3be42a1dadaef80751d4ed4358ee83c2e8/conf/us/demo/conf_generator.py#L40-L46 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/_config/config.py | python | _is_deprecated | (key) | return key in _deprecated_options | Returns True if the given option has been deprecated | Returns True if the given option has been deprecated | [
"Returns",
"True",
"if",
"the",
"given",
"option",
"has",
"been",
"deprecated"
] | def _is_deprecated(key):
""" Returns True if the given option has been deprecated """
key = key.lower()
return key in _deprecated_options | [
"def",
"_is_deprecated",
"(",
"key",
")",
":",
"key",
"=",
"key",
".",
"lower",
"(",
")",
"return",
"key",
"in",
"_deprecated_options"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/_config/config.py#L559-L563 |
|
protocolbuffers/protobuf | b5ab0b7a18b7336c60130f4ddb2d97c51792f896 | python/google/protobuf/text_format.py | python | Tokenizer.ConsumeString | (self) | Consumes a string value.
Returns:
The string parsed.
Raises:
ParseError: If a string value couldn't be consumed. | Consumes a string value. | [
"Consumes",
"a",
"string",
"value",
"."
] | def ConsumeString(self):
"""Consumes a string value.
Returns:
The string parsed.
Raises:
ParseError: If a string value couldn't be consumed.
"""
the_bytes = self.ConsumeByteString()
try:
return str(the_bytes, 'utf-8')
except UnicodeDecodeError as e:
raise self._StringParseError(e) | [
"def",
"ConsumeString",
"(",
"self",
")",
":",
"the_bytes",
"=",
"self",
".",
"ConsumeByteString",
"(",
")",
"try",
":",
"return",
"str",
"(",
"the_bytes",
",",
"'utf-8'",
")",
"except",
"UnicodeDecodeError",
"as",
"e",
":",
"raise",
"self",
".",
"_StringParseError",
"(",
"e",
")"
] | https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/google/protobuf/text_format.py#L1452-L1465 |
||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/image_ops_impl.py | python | stateless_random_jpeg_quality | (image,
min_jpeg_quality,
max_jpeg_quality,
seed) | return adjust_jpeg_quality(image, jpeg_quality) | Deterministically radomize jpeg encoding quality for inducing jpeg noise.
Guarantees the same results given the same `seed` independent of how many
times the function is called, and independent of global seed settings (e.g.
`tf.random.set_seed`).
`min_jpeg_quality` must be in the interval `[0, 100]` and less than
`max_jpeg_quality`.
`max_jpeg_quality` must be in the interval `[0, 100]`.
Usage Example:
>>> x = [[[1, 2, 3],
... [4, 5, 6]],
... [[7, 8, 9],
... [10, 11, 12]]]
>>> x_uint8 = tf.cast(x, tf.uint8)
>>> seed = (1, 2)
>>> tf.image.stateless_random_jpeg_quality(x_uint8, 75, 95, seed)
<tf.Tensor: shape=(2, 2, 3), dtype=uint8, numpy=
array([[[ 0, 4, 5],
[ 1, 5, 6]],
[[ 5, 9, 10],
[ 5, 9, 10]]], dtype=uint8)>
Args:
image: 3D image. Size of the last dimension must be 1 or 3.
min_jpeg_quality: Minimum jpeg encoding quality to use.
max_jpeg_quality: Maximum jpeg encoding quality to use.
seed: A shape [2] Tensor, the seed to the random number generator. Must have
dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.)
Returns:
Adjusted image(s), same shape and DType as `image`.
Raises:
ValueError: if `min_jpeg_quality` or `max_jpeg_quality` is invalid. | Deterministically radomize jpeg encoding quality for inducing jpeg noise. | [
"Deterministically",
"radomize",
"jpeg",
"encoding",
"quality",
"for",
"inducing",
"jpeg",
"noise",
"."
] | def stateless_random_jpeg_quality(image,
min_jpeg_quality,
max_jpeg_quality,
seed):
"""Deterministically radomize jpeg encoding quality for inducing jpeg noise.
Guarantees the same results given the same `seed` independent of how many
times the function is called, and independent of global seed settings (e.g.
`tf.random.set_seed`).
`min_jpeg_quality` must be in the interval `[0, 100]` and less than
`max_jpeg_quality`.
`max_jpeg_quality` must be in the interval `[0, 100]`.
Usage Example:
>>> x = [[[1, 2, 3],
... [4, 5, 6]],
... [[7, 8, 9],
... [10, 11, 12]]]
>>> x_uint8 = tf.cast(x, tf.uint8)
>>> seed = (1, 2)
>>> tf.image.stateless_random_jpeg_quality(x_uint8, 75, 95, seed)
<tf.Tensor: shape=(2, 2, 3), dtype=uint8, numpy=
array([[[ 0, 4, 5],
[ 1, 5, 6]],
[[ 5, 9, 10],
[ 5, 9, 10]]], dtype=uint8)>
Args:
image: 3D image. Size of the last dimension must be 1 or 3.
min_jpeg_quality: Minimum jpeg encoding quality to use.
max_jpeg_quality: Maximum jpeg encoding quality to use.
seed: A shape [2] Tensor, the seed to the random number generator. Must have
dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.)
Returns:
Adjusted image(s), same shape and DType as `image`.
Raises:
ValueError: if `min_jpeg_quality` or `max_jpeg_quality` is invalid.
"""
if (min_jpeg_quality < 0 or max_jpeg_quality < 0 or min_jpeg_quality > 100 or
max_jpeg_quality > 100):
raise ValueError('jpeg encoding range must be between 0 and 100.')
if min_jpeg_quality >= max_jpeg_quality:
raise ValueError('`min_jpeg_quality` must be less than `max_jpeg_quality`.')
jpeg_quality = stateless_random_ops.stateless_random_uniform(
shape=[], minval=min_jpeg_quality, maxval=max_jpeg_quality, seed=seed,
dtype=dtypes.int32)
return adjust_jpeg_quality(image, jpeg_quality) | [
"def",
"stateless_random_jpeg_quality",
"(",
"image",
",",
"min_jpeg_quality",
",",
"max_jpeg_quality",
",",
"seed",
")",
":",
"if",
"(",
"min_jpeg_quality",
"<",
"0",
"or",
"max_jpeg_quality",
"<",
"0",
"or",
"min_jpeg_quality",
">",
"100",
"or",
"max_jpeg_quality",
">",
"100",
")",
":",
"raise",
"ValueError",
"(",
"'jpeg encoding range must be between 0 and 100.'",
")",
"if",
"min_jpeg_quality",
">=",
"max_jpeg_quality",
":",
"raise",
"ValueError",
"(",
"'`min_jpeg_quality` must be less than `max_jpeg_quality`.'",
")",
"jpeg_quality",
"=",
"stateless_random_ops",
".",
"stateless_random_uniform",
"(",
"shape",
"=",
"[",
"]",
",",
"minval",
"=",
"min_jpeg_quality",
",",
"maxval",
"=",
"max_jpeg_quality",
",",
"seed",
"=",
"seed",
",",
"dtype",
"=",
"dtypes",
".",
"int32",
")",
"return",
"adjust_jpeg_quality",
"(",
"image",
",",
"jpeg_quality",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/image_ops_impl.py#L2785-L2837 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/message.py | python | Message.get_payload | (self, i=None, decode=False) | return payload | Return a reference to the payload.
The payload will either be a list object or a string. If you mutate
the list object, you modify the message's payload in place. Optional
i returns that index into the payload.
Optional decode is a flag indicating whether the payload should be
decoded or not, according to the Content-Transfer-Encoding header
(default is False).
When True and the message is not a multipart, the payload will be
decoded if this header's value is `quoted-printable' or `base64'. If
some other encoding is used, or the header is missing, or if the
payload has bogus data (i.e. bogus base64 or uuencoded data), the
payload is returned as-is.
If the message is a multipart and the decode flag is True, then None
is returned. | Return a reference to the payload. | [
"Return",
"a",
"reference",
"to",
"the",
"payload",
"."
] | def get_payload(self, i=None, decode=False):
"""Return a reference to the payload.
The payload will either be a list object or a string. If you mutate
the list object, you modify the message's payload in place. Optional
i returns that index into the payload.
Optional decode is a flag indicating whether the payload should be
decoded or not, according to the Content-Transfer-Encoding header
(default is False).
When True and the message is not a multipart, the payload will be
decoded if this header's value is `quoted-printable' or `base64'. If
some other encoding is used, or the header is missing, or if the
payload has bogus data (i.e. bogus base64 or uuencoded data), the
payload is returned as-is.
If the message is a multipart and the decode flag is True, then None
is returned.
"""
# Here is the logic table for this code, based on the email5.0.0 code:
# i decode is_multipart result
# ------ ------ ------------ ------------------------------
# None True True None
# i True True None
# None False True _payload (a list)
# i False True _payload element i (a Message)
# i False False error (not a list)
# i True False error (not a list)
# None False False _payload
# None True False _payload decoded (bytes)
# Note that Barry planned to factor out the 'decode' case, but that
# isn't so easy now that we handle the 8 bit data, which needs to be
# converted in both the decode and non-decode path.
if self.is_multipart():
if decode:
return None
if i is None:
return self._payload
else:
return self._payload[i]
# For backward compatibility, Use isinstance and this error message
# instead of the more logical is_multipart test.
if i is not None and not isinstance(self._payload, list):
raise TypeError('Expected list, got %s' % type(self._payload))
payload = self._payload
# cte might be a Header, so for now stringify it.
cte = str(self.get('content-transfer-encoding', '')).lower()
# payload may be bytes here.
if isinstance(payload, str):
if utils._has_surrogates(payload):
bpayload = payload.encode('ascii', 'surrogateescape')
if not decode:
try:
payload = bpayload.decode(self.get_param('charset', 'ascii'), 'replace')
except LookupError:
payload = bpayload.decode('ascii', 'replace')
elif decode:
try:
bpayload = payload.encode('ascii')
except UnicodeError:
# This won't happen for RFC compliant messages (messages
# containing only ASCII code points in the unicode input).
# If it does happen, turn the string into bytes in a way
# guaranteed not to fail.
bpayload = payload.encode('raw-unicode-escape')
if not decode:
return payload
if cte == 'quoted-printable':
return quopri.decodestring(bpayload)
elif cte == 'base64':
# XXX: this is a bit of a hack; decode_b should probably be factored
# out somewhere, but I haven't figured out where yet.
value, defects = decode_b(b''.join(bpayload.splitlines()))
for defect in defects:
self.policy.handle_defect(self, defect)
return value
elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
in_file = BytesIO(bpayload)
out_file = BytesIO()
try:
uu.decode(in_file, out_file, quiet=True)
return out_file.getvalue()
except uu.Error:
# Some decoding problem
return bpayload
if isinstance(payload, str):
return bpayload
return payload | [
"def",
"get_payload",
"(",
"self",
",",
"i",
"=",
"None",
",",
"decode",
"=",
"False",
")",
":",
"# Here is the logic table for this code, based on the email5.0.0 code:",
"# i decode is_multipart result",
"# ------ ------ ------------ ------------------------------",
"# None True True None",
"# i True True None",
"# None False True _payload (a list)",
"# i False True _payload element i (a Message)",
"# i False False error (not a list)",
"# i True False error (not a list)",
"# None False False _payload",
"# None True False _payload decoded (bytes)",
"# Note that Barry planned to factor out the 'decode' case, but that",
"# isn't so easy now that we handle the 8 bit data, which needs to be",
"# converted in both the decode and non-decode path.",
"if",
"self",
".",
"is_multipart",
"(",
")",
":",
"if",
"decode",
":",
"return",
"None",
"if",
"i",
"is",
"None",
":",
"return",
"self",
".",
"_payload",
"else",
":",
"return",
"self",
".",
"_payload",
"[",
"i",
"]",
"# For backward compatibility, Use isinstance and this error message",
"# instead of the more logical is_multipart test.",
"if",
"i",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"self",
".",
"_payload",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"'Expected list, got %s'",
"%",
"type",
"(",
"self",
".",
"_payload",
")",
")",
"payload",
"=",
"self",
".",
"_payload",
"# cte might be a Header, so for now stringify it.",
"cte",
"=",
"str",
"(",
"self",
".",
"get",
"(",
"'content-transfer-encoding'",
",",
"''",
")",
")",
".",
"lower",
"(",
")",
"# payload may be bytes here.",
"if",
"isinstance",
"(",
"payload",
",",
"str",
")",
":",
"if",
"utils",
".",
"_has_surrogates",
"(",
"payload",
")",
":",
"bpayload",
"=",
"payload",
".",
"encode",
"(",
"'ascii'",
",",
"'surrogateescape'",
")",
"if",
"not",
"decode",
":",
"try",
":",
"payload",
"=",
"bpayload",
".",
"decode",
"(",
"self",
".",
"get_param",
"(",
"'charset'",
",",
"'ascii'",
")",
",",
"'replace'",
")",
"except",
"LookupError",
":",
"payload",
"=",
"bpayload",
".",
"decode",
"(",
"'ascii'",
",",
"'replace'",
")",
"elif",
"decode",
":",
"try",
":",
"bpayload",
"=",
"payload",
".",
"encode",
"(",
"'ascii'",
")",
"except",
"UnicodeError",
":",
"# This won't happen for RFC compliant messages (messages",
"# containing only ASCII code points in the unicode input).",
"# If it does happen, turn the string into bytes in a way",
"# guaranteed not to fail.",
"bpayload",
"=",
"payload",
".",
"encode",
"(",
"'raw-unicode-escape'",
")",
"if",
"not",
"decode",
":",
"return",
"payload",
"if",
"cte",
"==",
"'quoted-printable'",
":",
"return",
"quopri",
".",
"decodestring",
"(",
"bpayload",
")",
"elif",
"cte",
"==",
"'base64'",
":",
"# XXX: this is a bit of a hack; decode_b should probably be factored",
"# out somewhere, but I haven't figured out where yet.",
"value",
",",
"defects",
"=",
"decode_b",
"(",
"b''",
".",
"join",
"(",
"bpayload",
".",
"splitlines",
"(",
")",
")",
")",
"for",
"defect",
"in",
"defects",
":",
"self",
".",
"policy",
".",
"handle_defect",
"(",
"self",
",",
"defect",
")",
"return",
"value",
"elif",
"cte",
"in",
"(",
"'x-uuencode'",
",",
"'uuencode'",
",",
"'uue'",
",",
"'x-uue'",
")",
":",
"in_file",
"=",
"BytesIO",
"(",
"bpayload",
")",
"out_file",
"=",
"BytesIO",
"(",
")",
"try",
":",
"uu",
".",
"decode",
"(",
"in_file",
",",
"out_file",
",",
"quiet",
"=",
"True",
")",
"return",
"out_file",
".",
"getvalue",
"(",
")",
"except",
"uu",
".",
"Error",
":",
"# Some decoding problem",
"return",
"bpayload",
"if",
"isinstance",
"(",
"payload",
",",
"str",
")",
":",
"return",
"bpayload",
"return",
"payload"
] | 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#L213-L301 |
|
vgough/encfs | c444f9b9176beea1ad41a7b2e29ca26e709b57f7 | vendor/github.com/muflihun/easyloggingpp/tools/cpplint.py | python | CheckVlogArguments | (filename, clean_lines, linenum, error) | Checks that VLOG() is only used for defining a logging level.
For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
VLOG(FATAL) are not.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks that VLOG() is only used for defining a logging level. | [
"Checks",
"that",
"VLOG",
"()",
"is",
"only",
"used",
"for",
"defining",
"a",
"logging",
"level",
"."
] | def CheckVlogArguments(filename, clean_lines, linenum, error):
"""Checks that VLOG() is only used for defining a logging level.
For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
VLOG(FATAL) are not.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line):
error(filename, linenum, 'runtime/vlog', 5,
'VLOG() should be used with numeric verbosity level. '
'Use LOG() if you want symbolic severity levels.') | [
"def",
"CheckVlogArguments",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"Search",
"(",
"r'\\bVLOG\\((INFO|ERROR|WARNING|DFATAL|FATAL)\\)'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/vlog'",
",",
"5",
",",
"'VLOG() should be used with numeric verbosity level. '",
"'Use LOG() if you want symbolic severity levels.'",
")"
] | https://github.com/vgough/encfs/blob/c444f9b9176beea1ad41a7b2e29ca26e709b57f7/vendor/github.com/muflihun/easyloggingpp/tools/cpplint.py#L1585-L1601 |
||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/requests/requests/adapters.py | python | HTTPAdapter.proxy_manager_for | (self, proxy, **proxy_kwargs) | return self.proxy_manager[proxy] | Return urllib3 ProxyManager for the given proxy.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param proxy: The proxy to return a urllib3 ProxyManager for.
:param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.
:returns: ProxyManager | Return urllib3 ProxyManager for the given proxy. | [
"Return",
"urllib3",
"ProxyManager",
"for",
"the",
"given",
"proxy",
"."
] | def proxy_manager_for(self, proxy, **proxy_kwargs):
"""Return urllib3 ProxyManager for the given proxy.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param proxy: The proxy to return a urllib3 ProxyManager for.
:param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.
:returns: ProxyManager
"""
if not proxy in self.proxy_manager:
proxy_headers = self.proxy_headers(proxy)
self.proxy_manager[proxy] = proxy_from_url(
proxy,
proxy_headers=proxy_headers,
num_pools=self._pool_connections,
maxsize=self._pool_maxsize,
block=self._pool_block,
**proxy_kwargs)
return self.proxy_manager[proxy] | [
"def",
"proxy_manager_for",
"(",
"self",
",",
"proxy",
",",
"*",
"*",
"proxy_kwargs",
")",
":",
"if",
"not",
"proxy",
"in",
"self",
".",
"proxy_manager",
":",
"proxy_headers",
"=",
"self",
".",
"proxy_headers",
"(",
"proxy",
")",
"self",
".",
"proxy_manager",
"[",
"proxy",
"]",
"=",
"proxy_from_url",
"(",
"proxy",
",",
"proxy_headers",
"=",
"proxy_headers",
",",
"num_pools",
"=",
"self",
".",
"_pool_connections",
",",
"maxsize",
"=",
"self",
".",
"_pool_maxsize",
",",
"block",
"=",
"self",
".",
"_pool_block",
",",
"*",
"*",
"proxy_kwargs",
")",
"return",
"self",
".",
"proxy_manager",
"[",
"proxy",
"]"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/requests/requests/adapters.py#L136-L157 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/xrc.py | python | XmlDocument.IsOk | (*args, **kwargs) | return _xrc.XmlDocument_IsOk(*args, **kwargs) | IsOk(self) -> bool | IsOk(self) -> bool | [
"IsOk",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsOk(*args, **kwargs):
"""IsOk(self) -> bool"""
return _xrc.XmlDocument_IsOk(*args, **kwargs) | [
"def",
"IsOk",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_xrc",
".",
"XmlDocument_IsOk",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/xrc.py#L531-L533 |
|
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/log/__init__.py | python | info | (msg, *args, **kwargs) | info message | info message | [
"info",
"message"
] | def info(msg, *args, **kwargs):
""" info message """
logging.info(msg, *args, **kwargs) | [
"def",
"info",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"logging",
".",
"info",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/log/__init__.py#L109-L111 |
||
PixarAnimationStudios/USD | faed18ce62c8736b02413635b584a2f637156bad | pxr/usdImaging/usdviewq/plugin.py | python | PluginMenu.findOrCreateSubmenu | (self, menuName) | Get a PluginMenu object for the submenu with the given name. If no
submenu with the given name exists, it is created. | Get a PluginMenu object for the submenu with the given name. If no
submenu with the given name exists, it is created. | [
"Get",
"a",
"PluginMenu",
"object",
"for",
"the",
"submenu",
"with",
"the",
"given",
"name",
".",
"If",
"no",
"submenu",
"with",
"the",
"given",
"name",
"exists",
"it",
"is",
"created",
"."
] | def findOrCreateSubmenu(self, menuName):
"""Get a PluginMenu object for the submenu with the given name. If no
submenu with the given name exists, it is created.
"""
if menuName in self._submenus:
return self._submenus[menuName]
else:
subQMenu = self._qMenu.addMenu(menuName)
subQMenu.setToolTipsVisible(True)
submenu = PluginMenu(subQMenu)
self._submenus[menuName] = submenu
return submenu | [
"def",
"findOrCreateSubmenu",
"(",
"self",
",",
"menuName",
")",
":",
"if",
"menuName",
"in",
"self",
".",
"_submenus",
":",
"return",
"self",
".",
"_submenus",
"[",
"menuName",
"]",
"else",
":",
"subQMenu",
"=",
"self",
".",
"_qMenu",
".",
"addMenu",
"(",
"menuName",
")",
"subQMenu",
".",
"setToolTipsVisible",
"(",
"True",
")",
"submenu",
"=",
"PluginMenu",
"(",
"subQMenu",
")",
"self",
".",
"_submenus",
"[",
"menuName",
"]",
"=",
"submenu",
"return",
"submenu"
] | https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/plugin.py#L207-L219 |
||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBModuleSpecList.__str__ | (self) | return _lldb.SBModuleSpecList___str__(self) | __str__(self) -> PyObject | __str__(self) -> PyObject | [
"__str__",
"(",
"self",
")",
"-",
">",
"PyObject"
] | def __str__(self):
"""__str__(self) -> PyObject"""
return _lldb.SBModuleSpecList___str__(self) | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBModuleSpecList___str__",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L6637-L6639 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/waflib/extras/run_r_script.py | python | apply_run_r_script | (tg) | Task generator customising the options etc. to call R in batch
mode for running a R script. | Task generator customising the options etc. to call R in batch
mode for running a R script. | [
"Task",
"generator",
"customising",
"the",
"options",
"etc",
".",
"to",
"call",
"R",
"in",
"batch",
"mode",
"for",
"running",
"a",
"R",
"script",
"."
] | def apply_run_r_script(tg):
"""Task generator customising the options etc. to call R in batch
mode for running a R script.
"""
# Convert sources and targets to nodes
src_node = tg.path.find_resource(tg.source)
tgt_nodes = [tg.path.find_or_declare(t) for t in tg.to_list(tg.target)]
tsk = tg.create_task('run_r_script', src=src_node, tgt=tgt_nodes)
tsk.env.LOGFILEPATH = os.path.join(tg.bld.bldnode.abspath(), '%s_%d.log' % (os.path.splitext(src_node.name)[0], tg.idx))
# dependencies (if the attribute 'deps' changes, trigger a recompilation)
for x in tg.to_list(getattr(tg, 'deps', [])):
node = tg.path.find_resource(x)
if not node:
tg.bld.fatal('Could not find dependency %r for running %r' % (x, src_node.nice_path()))
tsk.dep_nodes.append(node)
Logs.debug('deps: found dependencies %r for running %r' % (tsk.dep_nodes, src_node.nice_path()))
# Bypass the execution of process_source by setting the source to an empty list
tg.source = [] | [
"def",
"apply_run_r_script",
"(",
"tg",
")",
":",
"# Convert sources and targets to nodes",
"src_node",
"=",
"tg",
".",
"path",
".",
"find_resource",
"(",
"tg",
".",
"source",
")",
"tgt_nodes",
"=",
"[",
"tg",
".",
"path",
".",
"find_or_declare",
"(",
"t",
")",
"for",
"t",
"in",
"tg",
".",
"to_list",
"(",
"tg",
".",
"target",
")",
"]",
"tsk",
"=",
"tg",
".",
"create_task",
"(",
"'run_r_script'",
",",
"src",
"=",
"src_node",
",",
"tgt",
"=",
"tgt_nodes",
")",
"tsk",
".",
"env",
".",
"LOGFILEPATH",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tg",
".",
"bld",
".",
"bldnode",
".",
"abspath",
"(",
")",
",",
"'%s_%d.log'",
"%",
"(",
"os",
".",
"path",
".",
"splitext",
"(",
"src_node",
".",
"name",
")",
"[",
"0",
"]",
",",
"tg",
".",
"idx",
")",
")",
"# dependencies (if the attribute 'deps' changes, trigger a recompilation)",
"for",
"x",
"in",
"tg",
".",
"to_list",
"(",
"getattr",
"(",
"tg",
",",
"'deps'",
",",
"[",
"]",
")",
")",
":",
"node",
"=",
"tg",
".",
"path",
".",
"find_resource",
"(",
"x",
")",
"if",
"not",
"node",
":",
"tg",
".",
"bld",
".",
"fatal",
"(",
"'Could not find dependency %r for running %r'",
"%",
"(",
"x",
",",
"src_node",
".",
"nice_path",
"(",
")",
")",
")",
"tsk",
".",
"dep_nodes",
".",
"append",
"(",
"node",
")",
"Logs",
".",
"debug",
"(",
"'deps: found dependencies %r for running %r'",
"%",
"(",
"tsk",
".",
"dep_nodes",
",",
"src_node",
".",
"nice_path",
"(",
")",
")",
")",
"# Bypass the execution of process_source by setting the source to an empty list",
"tg",
".",
"source",
"=",
"[",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/extras/run_r_script.py#L65-L86 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/urllib/request.py | python | HTTPPasswordMgr.is_suburi | (self, base, test) | return False | Check if test is below base in a URI tree
Both args must be URIs in reduced form. | Check if test is below base in a URI tree | [
"Check",
"if",
"test",
"is",
"below",
"base",
"in",
"a",
"URI",
"tree"
] | def is_suburi(self, base, test):
"""Check if test is below base in a URI tree
Both args must be URIs in reduced form.
"""
if base == test:
return True
if base[0] != test[0]:
return False
common = posixpath.commonprefix((base[1], test[1]))
if len(common) == len(base[1]):
return True
return False | [
"def",
"is_suburi",
"(",
"self",
",",
"base",
",",
"test",
")",
":",
"if",
"base",
"==",
"test",
":",
"return",
"True",
"if",
"base",
"[",
"0",
"]",
"!=",
"test",
"[",
"0",
"]",
":",
"return",
"False",
"common",
"=",
"posixpath",
".",
"commonprefix",
"(",
"(",
"base",
"[",
"1",
"]",
",",
"test",
"[",
"1",
"]",
")",
")",
"if",
"len",
"(",
"common",
")",
"==",
"len",
"(",
"base",
"[",
"1",
"]",
")",
":",
"return",
"True",
"return",
"False"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/urllib/request.py#L884-L896 |
|
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/ntpath.py | python | basename | (p) | return split(p)[1] | Returns the final component of a pathname | Returns the final component of a pathname | [
"Returns",
"the",
"final",
"component",
"of",
"a",
"pathname"
] | def basename(p):
"""Returns the final component of a pathname"""
return split(p)[1] | [
"def",
"basename",
"(",
"p",
")",
":",
"return",
"split",
"(",
"p",
")",
"[",
"1",
"]"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/ntpath.py#L196-L198 |
|
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/training/training_ops.py | python | _SparseApplyProximalAdagradShape | (op) | return [accum_shape] | Shape function for the SparseApplyProximalAdagrad op. | Shape function for the SparseApplyProximalAdagrad op. | [
"Shape",
"function",
"for",
"the",
"SparseApplyProximalAdagrad",
"op",
"."
] | def _SparseApplyProximalAdagradShape(op):
"""Shape function for the SparseApplyProximalAdagrad op."""
var_shape = op.inputs[0].get_shape()
accum_shape = op.inputs[1].get_shape().merge_with(var_shape)
_AssertInputIsScalar(op, 2) # lr
_AssertInputIsScalar(op, 3) # l1
_AssertInputIsScalar(op, 4) # l2
grad_shape = op.inputs[5].get_shape().merge_with(
tensor_shape.TensorShape([None]).concatenate(accum_shape[1:]))
unused_indices_shape = op.inputs[6].get_shape().merge_with(
tensor_shape.vector(grad_shape[0]))
return [accum_shape] | [
"def",
"_SparseApplyProximalAdagradShape",
"(",
"op",
")",
":",
"var_shape",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
"accum_shape",
"=",
"op",
".",
"inputs",
"[",
"1",
"]",
".",
"get_shape",
"(",
")",
".",
"merge_with",
"(",
"var_shape",
")",
"_AssertInputIsScalar",
"(",
"op",
",",
"2",
")",
"# lr",
"_AssertInputIsScalar",
"(",
"op",
",",
"3",
")",
"# l1",
"_AssertInputIsScalar",
"(",
"op",
",",
"4",
")",
"# l2",
"grad_shape",
"=",
"op",
".",
"inputs",
"[",
"5",
"]",
".",
"get_shape",
"(",
")",
".",
"merge_with",
"(",
"tensor_shape",
".",
"TensorShape",
"(",
"[",
"None",
"]",
")",
".",
"concatenate",
"(",
"accum_shape",
"[",
"1",
":",
"]",
")",
")",
"unused_indices_shape",
"=",
"op",
".",
"inputs",
"[",
"6",
"]",
".",
"get_shape",
"(",
")",
".",
"merge_with",
"(",
"tensor_shape",
".",
"vector",
"(",
"grad_shape",
"[",
"0",
"]",
")",
")",
"return",
"[",
"accum_shape",
"]"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/training/training_ops.py#L220-L231 |
|
ucb-bar/esp-llvm | 8aec2ae754fd66d4e73b9b777a9f20c4583a0f03 | bindings/python/llvm/object.py | python | Section.__init__ | (self, ptr) | Construct a new section instance.
Section instances can currently only be created from an ObjectFile
instance. Therefore, this constructor should not be used outside of
this module. | Construct a new section instance. | [
"Construct",
"a",
"new",
"section",
"instance",
"."
] | def __init__(self, ptr):
"""Construct a new section instance.
Section instances can currently only be created from an ObjectFile
instance. Therefore, this constructor should not be used outside of
this module.
"""
LLVMObject.__init__(self, ptr)
self.expired = False | [
"def",
"__init__",
"(",
"self",
",",
"ptr",
")",
":",
"LLVMObject",
".",
"__init__",
"(",
"self",
",",
"ptr",
")",
"self",
".",
"expired",
"=",
"False"
] | https://github.com/ucb-bar/esp-llvm/blob/8aec2ae754fd66d4e73b9b777a9f20c4583a0f03/bindings/python/llvm/object.py#L182-L191 |
||
btgraham/SparseConvNet | 89818ebd2a508bb05e552168c83d6b60add8a051 | sparseconvnet/inputBatch.py | python | InputBatch.precompute_metadata | (self, size) | Optional.
Allows precomputation of 'rulebooks' in data loading threads.
Use size == 2 if downsizing with size-2 stride-2 operations
Use size == 3 if downsizing with size-3 stride-2 operations | Optional.
Allows precomputation of 'rulebooks' in data loading threads.
Use size == 2 if downsizing with size-2 stride-2 operations
Use size == 3 if downsizing with size-3 stride-2 operations | [
"Optional",
".",
"Allows",
"precomputation",
"of",
"rulebooks",
"in",
"data",
"loading",
"threads",
".",
"Use",
"size",
"==",
"2",
"if",
"downsizing",
"with",
"size",
"-",
"2",
"stride",
"-",
"2",
"operations",
"Use",
"size",
"==",
"3",
"if",
"downsizing",
"with",
"size",
"-",
"3",
"stride",
"-",
"2",
"operations"
] | def precompute_metadata(self, size):
"""
Optional.
Allows precomputation of 'rulebooks' in data loading threads.
Use size == 2 if downsizing with size-2 stride-2 operations
Use size == 3 if downsizing with size-3 stride-2 operations
"""
if size == 2:
self.metadata.generateRuleBooks2s2()
if size == 3 :
self.metadata.generateRuleBooks3s2() | [
"def",
"precompute_metadata",
"(",
"self",
",",
"size",
")",
":",
"if",
"size",
"==",
"2",
":",
"self",
".",
"metadata",
".",
"generateRuleBooks2s2",
"(",
")",
"if",
"size",
"==",
"3",
":",
"self",
".",
"metadata",
".",
"generateRuleBooks3s2",
"(",
")"
] | https://github.com/btgraham/SparseConvNet/blob/89818ebd2a508bb05e552168c83d6b60add8a051/sparseconvnet/inputBatch.py#L70-L80 |
||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/html5lib/treebuilders/_base.py | python | TreeBuilder.getTableMisnestedNodePosition | (self) | return fosterParent, insertBefore | Get the foster parent element, and sibling to insert before
(or None) when inserting a misnested table node | Get the foster parent element, and sibling to insert before
(or None) when inserting a misnested table node | [
"Get",
"the",
"foster",
"parent",
"element",
"and",
"sibling",
"to",
"insert",
"before",
"(",
"or",
"None",
")",
"when",
"inserting",
"a",
"misnested",
"table",
"node"
] | def getTableMisnestedNodePosition(self):
"""Get the foster parent element, and sibling to insert before
(or None) when inserting a misnested table node"""
# The foster parent element is the one which comes before the most
# recently opened table element
# XXX - this is really inelegant
lastTable = None
fosterParent = None
insertBefore = None
for elm in self.openElements[::-1]:
if elm.name == "table":
lastTable = elm
break
if lastTable:
# XXX - we should really check that this parent is actually a
# node here
if lastTable.parent:
fosterParent = lastTable.parent
insertBefore = lastTable
else:
fosterParent = self.openElements[
self.openElements.index(lastTable) - 1]
else:
fosterParent = self.openElements[0]
return fosterParent, insertBefore | [
"def",
"getTableMisnestedNodePosition",
"(",
"self",
")",
":",
"# The foster parent element is the one which comes before the most",
"# recently opened table element",
"# XXX - this is really inelegant",
"lastTable",
"=",
"None",
"fosterParent",
"=",
"None",
"insertBefore",
"=",
"None",
"for",
"elm",
"in",
"self",
".",
"openElements",
"[",
":",
":",
"-",
"1",
"]",
":",
"if",
"elm",
".",
"name",
"==",
"\"table\"",
":",
"lastTable",
"=",
"elm",
"break",
"if",
"lastTable",
":",
"# XXX - we should really check that this parent is actually a",
"# node here",
"if",
"lastTable",
".",
"parent",
":",
"fosterParent",
"=",
"lastTable",
".",
"parent",
"insertBefore",
"=",
"lastTable",
"else",
":",
"fosterParent",
"=",
"self",
".",
"openElements",
"[",
"self",
".",
"openElements",
".",
"index",
"(",
"lastTable",
")",
"-",
"1",
"]",
"else",
":",
"fosterParent",
"=",
"self",
".",
"openElements",
"[",
"0",
"]",
"return",
"fosterParent",
",",
"insertBefore"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/html5lib/treebuilders/_base.py#L327-L351 |
|
ros-controls/ros_control | 53c2487d1b56a40f1d00b06c49512aa7fd2bf465 | rqt_controller_manager/src/rqt_controller_manager/controller_manager.py | python | _append_ns | (in_ns, suffix) | return ns | Append a sub-namespace (suffix) to the input namespace
@param in_ns Input namespace
@type in_ns str
@return Suffix namespace
@rtype str | Append a sub-namespace (suffix) to the input namespace | [
"Append",
"a",
"sub",
"-",
"namespace",
"(",
"suffix",
")",
"to",
"the",
"input",
"namespace"
] | def _append_ns(in_ns, suffix):
"""
Append a sub-namespace (suffix) to the input namespace
@param in_ns Input namespace
@type in_ns str
@return Suffix namespace
@rtype str
"""
ns = in_ns
if ns[-1] != '/':
ns += '/'
ns += suffix
return ns | [
"def",
"_append_ns",
"(",
"in_ns",
",",
"suffix",
")",
":",
"ns",
"=",
"in_ns",
"if",
"ns",
"[",
"-",
"1",
"]",
"!=",
"'/'",
":",
"ns",
"+=",
"'/'",
"ns",
"+=",
"suffix",
"return",
"ns"
] | https://github.com/ros-controls/ros_control/blob/53c2487d1b56a40f1d00b06c49512aa7fd2bf465/rqt_controller_manager/src/rqt_controller_manager/controller_manager.py#L449-L461 |
|
mhammond/pywin32 | 44afd86ba8485194df93234639243252deeb40d5 | com/win32comext/authorization/demos/EditServiceSecurity.py | python | ServiceSecurity.EditSecurity | (self, owner_hwnd=0) | Creates an ACL editor dialog based on parameters returned by interface methods | Creates an ACL editor dialog based on parameters returned by interface methods | [
"Creates",
"an",
"ACL",
"editor",
"dialog",
"based",
"on",
"parameters",
"returned",
"by",
"interface",
"methods"
] | def EditSecurity(self, owner_hwnd=0):
"""Creates an ACL editor dialog based on parameters returned by interface methods"""
isi = pythoncom.WrapObject(
self, authorization.IID_ISecurityInformation, pythoncom.IID_IUnknown
)
authorization.EditSecurity(owner_hwnd, isi) | [
"def",
"EditSecurity",
"(",
"self",
",",
"owner_hwnd",
"=",
"0",
")",
":",
"isi",
"=",
"pythoncom",
".",
"WrapObject",
"(",
"self",
",",
"authorization",
".",
"IID_ISecurityInformation",
",",
"pythoncom",
".",
"IID_IUnknown",
")",
"authorization",
".",
"EditSecurity",
"(",
"owner_hwnd",
",",
"isi",
")"
] | https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/com/win32comext/authorization/demos/EditServiceSecurity.py#L221-L226 |
||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/pydoc.py | python | HTMLDoc.namelink | (self, name, *dicts) | return name | Make a link for an identifier, given name-to-URL mappings. | Make a link for an identifier, given name-to-URL mappings. | [
"Make",
"a",
"link",
"for",
"an",
"identifier",
"given",
"name",
"-",
"to",
"-",
"URL",
"mappings",
"."
] | def namelink(self, name, *dicts):
"""Make a link for an identifier, given name-to-URL mappings."""
for dict in dicts:
if name in dict:
return '<a href="%s">%s</a>' % (dict[name], name)
return name | [
"def",
"namelink",
"(",
"self",
",",
"name",
",",
"*",
"dicts",
")",
":",
"for",
"dict",
"in",
"dicts",
":",
"if",
"name",
"in",
"dict",
":",
"return",
"'<a href=\"%s\">%s</a>'",
"%",
"(",
"dict",
"[",
"name",
"]",
",",
"name",
")",
"return",
"name"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/pydoc.py#L492-L497 |
|
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/meta_graph.py | python | add_collection_def | (meta_graph_def, key, graph=None,
export_scope=None, exclude_nodes=None,
override_contents=None) | Adds a collection to MetaGraphDef protocol buffer.
Args:
meta_graph_def: MetaGraphDef protocol buffer.
key: One of the GraphKeys or user-defined string.
graph: The `Graph` from which to get collections.
export_scope: Optional `string`. Name scope to remove.
exclude_nodes: An iterable of nodes or `string` node names to omit from the
collection, or None.
override_contents: An iterable of values to place in the collection,
ignoring the current values (if set). | Adds a collection to MetaGraphDef protocol buffer. | [
"Adds",
"a",
"collection",
"to",
"MetaGraphDef",
"protocol",
"buffer",
"."
] | def add_collection_def(meta_graph_def, key, graph=None,
export_scope=None, exclude_nodes=None,
override_contents=None):
"""Adds a collection to MetaGraphDef protocol buffer.
Args:
meta_graph_def: MetaGraphDef protocol buffer.
key: One of the GraphKeys or user-defined string.
graph: The `Graph` from which to get collections.
export_scope: Optional `string`. Name scope to remove.
exclude_nodes: An iterable of nodes or `string` node names to omit from the
collection, or None.
override_contents: An iterable of values to place in the collection,
ignoring the current values (if set).
"""
if graph and not isinstance(graph, ops.Graph):
raise TypeError("graph must be of type Graph, not %s", type(graph))
if not isinstance(key, six.string_types) and not isinstance(key, bytes):
logging.warning("Only collections with string type keys will be "
"serialized. This key has %s", type(key))
return
# Sets graph to default graph if it's not passed in.
graph = graph or ops.get_default_graph()
if override_contents:
collection_list = override_contents
else:
collection_list = graph.get_collection(key)
# Remove nodes that should not be exported from the collection list.
collection_list = [x for x in collection_list if
_should_include_node(x, export_scope, exclude_nodes)]
if not collection_list:
return
try:
col_def = meta_graph_def.collection_def[key]
to_proto = ops.get_to_proto_function(key)
proto_type = ops.get_collection_proto_type(key)
if to_proto:
kind = "bytes_list"
for x in collection_list:
# Additional type check to make sure the returned proto is indeed
# what we expect.
proto = to_proto(x, export_scope=export_scope)
if proto:
assert isinstance(proto, proto_type)
getattr(col_def, kind).value.append(proto.SerializeToString())
else:
kind = _get_kind_name(collection_list[0])
if kind == "node_list":
for x in collection_list:
if not export_scope or x.name.startswith(export_scope):
getattr(col_def, kind).value.append(
ops.strip_name_scope(x.name, export_scope))
elif kind == "bytes_list":
# NOTE(opensource): This force conversion is to work around the fact
# that Python3 distinguishes between bytes and strings.
getattr(col_def, kind).value.extend(
[compat.as_bytes(x) for x in collection_list])
else:
getattr(col_def, kind).value.extend([x for x in collection_list])
except Exception as e: # pylint: disable=broad-except
logging.warning("Issue encountered when serializing %s.\n"
"Type is unsupported, or the types of the items don't "
"match field type in CollectionDef. Note this is a warning "
"and probably safe to ignore.\n%s", key, str(e))
if key in meta_graph_def.collection_def:
del meta_graph_def.collection_def[key]
return | [
"def",
"add_collection_def",
"(",
"meta_graph_def",
",",
"key",
",",
"graph",
"=",
"None",
",",
"export_scope",
"=",
"None",
",",
"exclude_nodes",
"=",
"None",
",",
"override_contents",
"=",
"None",
")",
":",
"if",
"graph",
"and",
"not",
"isinstance",
"(",
"graph",
",",
"ops",
".",
"Graph",
")",
":",
"raise",
"TypeError",
"(",
"\"graph must be of type Graph, not %s\"",
",",
"type",
"(",
"graph",
")",
")",
"if",
"not",
"isinstance",
"(",
"key",
",",
"six",
".",
"string_types",
")",
"and",
"not",
"isinstance",
"(",
"key",
",",
"bytes",
")",
":",
"logging",
".",
"warning",
"(",
"\"Only collections with string type keys will be \"",
"\"serialized. This key has %s\"",
",",
"type",
"(",
"key",
")",
")",
"return",
"# Sets graph to default graph if it's not passed in.",
"graph",
"=",
"graph",
"or",
"ops",
".",
"get_default_graph",
"(",
")",
"if",
"override_contents",
":",
"collection_list",
"=",
"override_contents",
"else",
":",
"collection_list",
"=",
"graph",
".",
"get_collection",
"(",
"key",
")",
"# Remove nodes that should not be exported from the collection list.",
"collection_list",
"=",
"[",
"x",
"for",
"x",
"in",
"collection_list",
"if",
"_should_include_node",
"(",
"x",
",",
"export_scope",
",",
"exclude_nodes",
")",
"]",
"if",
"not",
"collection_list",
":",
"return",
"try",
":",
"col_def",
"=",
"meta_graph_def",
".",
"collection_def",
"[",
"key",
"]",
"to_proto",
"=",
"ops",
".",
"get_to_proto_function",
"(",
"key",
")",
"proto_type",
"=",
"ops",
".",
"get_collection_proto_type",
"(",
"key",
")",
"if",
"to_proto",
":",
"kind",
"=",
"\"bytes_list\"",
"for",
"x",
"in",
"collection_list",
":",
"# Additional type check to make sure the returned proto is indeed",
"# what we expect.",
"proto",
"=",
"to_proto",
"(",
"x",
",",
"export_scope",
"=",
"export_scope",
")",
"if",
"proto",
":",
"assert",
"isinstance",
"(",
"proto",
",",
"proto_type",
")",
"getattr",
"(",
"col_def",
",",
"kind",
")",
".",
"value",
".",
"append",
"(",
"proto",
".",
"SerializeToString",
"(",
")",
")",
"else",
":",
"kind",
"=",
"_get_kind_name",
"(",
"collection_list",
"[",
"0",
"]",
")",
"if",
"kind",
"==",
"\"node_list\"",
":",
"for",
"x",
"in",
"collection_list",
":",
"if",
"not",
"export_scope",
"or",
"x",
".",
"name",
".",
"startswith",
"(",
"export_scope",
")",
":",
"getattr",
"(",
"col_def",
",",
"kind",
")",
".",
"value",
".",
"append",
"(",
"ops",
".",
"strip_name_scope",
"(",
"x",
".",
"name",
",",
"export_scope",
")",
")",
"elif",
"kind",
"==",
"\"bytes_list\"",
":",
"# NOTE(opensource): This force conversion is to work around the fact",
"# that Python3 distinguishes between bytes and strings.",
"getattr",
"(",
"col_def",
",",
"kind",
")",
".",
"value",
".",
"extend",
"(",
"[",
"compat",
".",
"as_bytes",
"(",
"x",
")",
"for",
"x",
"in",
"collection_list",
"]",
")",
"else",
":",
"getattr",
"(",
"col_def",
",",
"kind",
")",
".",
"value",
".",
"extend",
"(",
"[",
"x",
"for",
"x",
"in",
"collection_list",
"]",
")",
"except",
"Exception",
"as",
"e",
":",
"# pylint: disable=broad-except",
"logging",
".",
"warning",
"(",
"\"Issue encountered when serializing %s.\\n\"",
"\"Type is unsupported, or the types of the items don't \"",
"\"match field type in CollectionDef. Note this is a warning \"",
"\"and probably safe to ignore.\\n%s\"",
",",
"key",
",",
"str",
"(",
"e",
")",
")",
"if",
"key",
"in",
"meta_graph_def",
".",
"collection_def",
":",
"del",
"meta_graph_def",
".",
"collection_def",
"[",
"key",
"]",
"return"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/meta_graph.py#L380-L451 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | MouseEvent.LeftDown | (*args, **kwargs) | return _core_.MouseEvent_LeftDown(*args, **kwargs) | LeftDown(self) -> bool
Returns true if the left mouse button state changed to down. | LeftDown(self) -> bool | [
"LeftDown",
"(",
"self",
")",
"-",
">",
"bool"
] | def LeftDown(*args, **kwargs):
"""
LeftDown(self) -> bool
Returns true if the left mouse button state changed to down.
"""
return _core_.MouseEvent_LeftDown(*args, **kwargs) | [
"def",
"LeftDown",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"MouseEvent_LeftDown",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L5625-L5631 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/boto3/dynamodb/conditions.py | python | ConditionExpressionBuilder.reset | (self) | Resets the placeholder name and values | Resets the placeholder name and values | [
"Resets",
"the",
"placeholder",
"name",
"and",
"values"
] | def reset(self):
"""Resets the placeholder name and values"""
self._name_count = 0
self._value_count = 0 | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"_name_count",
"=",
"0",
"self",
".",
"_value_count",
"=",
"0"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/boto3/dynamodb/conditions.py#L310-L313 |
||
v8/v8 | fee3bf095260bf657a3eea4d3d41f90c42c6c857 | tools/grokdump.py | python | InspectionShell.do_lm | (self, arg) | return self.do_list_modules(arg) | see list_modules | see list_modules | [
"see",
"list_modules"
] | def do_lm(self, arg):
""" see list_modules """
return self.do_list_modules(arg) | [
"def",
"do_lm",
"(",
"self",
",",
"arg",
")",
":",
"return",
"self",
".",
"do_list_modules",
"(",
"arg",
")"
] | https://github.com/v8/v8/blob/fee3bf095260bf657a3eea4d3d41f90c42c6c857/tools/grokdump.py#L3758-L3760 |
|
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/saved_model/loader_impl.py | python | contains_saved_model | (export_dir) | return maybe_saved_model_directory(export_dir) | Checks whether the provided export directory could contain a SavedModel.
Note that the method does not load any data by itself. If the method returns
`false`, the export directory definitely does not contain a SavedModel. If the
method returns `true`, the export directory may contain a SavedModel but
provides no guarantee that it can be loaded.
Args:
export_dir: Absolute string path to possible export location. For example,
'/my/foo/model'.
Returns:
True if the export directory contains SavedModel files, False otherwise. | Checks whether the provided export directory could contain a SavedModel. | [
"Checks",
"whether",
"the",
"provided",
"export",
"directory",
"could",
"contain",
"a",
"SavedModel",
"."
] | def contains_saved_model(export_dir):
"""Checks whether the provided export directory could contain a SavedModel.
Note that the method does not load any data by itself. If the method returns
`false`, the export directory definitely does not contain a SavedModel. If the
method returns `true`, the export directory may contain a SavedModel but
provides no guarantee that it can be loaded.
Args:
export_dir: Absolute string path to possible export location. For example,
'/my/foo/model'.
Returns:
True if the export directory contains SavedModel files, False otherwise.
"""
return maybe_saved_model_directory(export_dir) | [
"def",
"contains_saved_model",
"(",
"export_dir",
")",
":",
"return",
"maybe_saved_model_directory",
"(",
"export_dir",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/saved_model/loader_impl.py#L220-L235 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/boto3/resources/model.py | python | ResourceModel.subresources | (self) | return self._get_related_resources(True) | Get a list of sub-resources.
:type: list(:py:class:`ResponseResource`) | Get a list of sub-resources. | [
"Get",
"a",
"list",
"of",
"sub",
"-",
"resources",
"."
] | def subresources(self):
"""
Get a list of sub-resources.
:type: list(:py:class:`ResponseResource`)
"""
return self._get_related_resources(True) | [
"def",
"subresources",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_related_resources",
"(",
"True",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/boto3/resources/model.py#L577-L583 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/lib/npyio.py | python | recfromcsv | (fname, **kwargs) | return output | Load ASCII data stored in a comma-separated file.
The returned array is a record array (if ``usemask=False``, see
`recarray`) or a masked record array (if ``usemask=True``,
see `ma.mrecords.MaskedRecords`).
Parameters
----------
fname, kwargs : For a description of input parameters, see `genfromtxt`.
See Also
--------
numpy.genfromtxt : generic function to load ASCII data.
Notes
-----
By default, `dtype` is None, which means that the data-type of the output
array will be determined from the data. | Load ASCII data stored in a comma-separated file. | [
"Load",
"ASCII",
"data",
"stored",
"in",
"a",
"comma",
"-",
"separated",
"file",
"."
] | def recfromcsv(fname, **kwargs):
"""
Load ASCII data stored in a comma-separated file.
The returned array is a record array (if ``usemask=False``, see
`recarray`) or a masked record array (if ``usemask=True``,
see `ma.mrecords.MaskedRecords`).
Parameters
----------
fname, kwargs : For a description of input parameters, see `genfromtxt`.
See Also
--------
numpy.genfromtxt : generic function to load ASCII data.
Notes
-----
By default, `dtype` is None, which means that the data-type of the output
array will be determined from the data.
"""
# Set default kwargs for genfromtxt as relevant to csv import.
kwargs.setdefault("case_sensitive", "lower")
kwargs.setdefault("names", True)
kwargs.setdefault("delimiter", ",")
kwargs.setdefault("dtype", None)
output = genfromtxt(fname, **kwargs)
usemask = kwargs.get("usemask", False)
if usemask:
from numpy.ma.mrecords import MaskedRecords
output = output.view(MaskedRecords)
else:
output = output.view(np.recarray)
return output | [
"def",
"recfromcsv",
"(",
"fname",
",",
"*",
"*",
"kwargs",
")",
":",
"# Set default kwargs for genfromtxt as relevant to csv import.",
"kwargs",
".",
"setdefault",
"(",
"\"case_sensitive\"",
",",
"\"lower\"",
")",
"kwargs",
".",
"setdefault",
"(",
"\"names\"",
",",
"True",
")",
"kwargs",
".",
"setdefault",
"(",
"\"delimiter\"",
",",
"\",\"",
")",
"kwargs",
".",
"setdefault",
"(",
"\"dtype\"",
",",
"None",
")",
"output",
"=",
"genfromtxt",
"(",
"fname",
",",
"*",
"*",
"kwargs",
")",
"usemask",
"=",
"kwargs",
".",
"get",
"(",
"\"usemask\"",
",",
"False",
")",
"if",
"usemask",
":",
"from",
"numpy",
".",
"ma",
".",
"mrecords",
"import",
"MaskedRecords",
"output",
"=",
"output",
".",
"view",
"(",
"MaskedRecords",
")",
"else",
":",
"output",
"=",
"output",
".",
"view",
"(",
"np",
".",
"recarray",
")",
"return",
"output"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/lib/npyio.py#L2380-L2415 |
|
ideawu/ssdb-rocks | a3cbb322cafb2f493252829c608e2239df98c9ac | deps/cpy/antlr3/streams.py | python | TokenStream.LT | (self, k) | Get Token at current input pointer + i ahead where i=1 is next Token.
i<0 indicates tokens in the past. So -1 is previous token and -2 is
two tokens ago. LT(0) is undefined. For i>=n, return Token.EOFToken.
Return null for LT(0) and any index that results in an absolute address
that is negative. | Get Token at current input pointer + i ahead where i=1 is next Token.
i<0 indicates tokens in the past. So -1 is previous token and -2 is
two tokens ago. LT(0) is undefined. For i>=n, return Token.EOFToken.
Return null for LT(0) and any index that results in an absolute address
that is negative. | [
"Get",
"Token",
"at",
"current",
"input",
"pointer",
"+",
"i",
"ahead",
"where",
"i",
"=",
"1",
"is",
"next",
"Token",
".",
"i<0",
"indicates",
"tokens",
"in",
"the",
"past",
".",
"So",
"-",
"1",
"is",
"previous",
"token",
"and",
"-",
"2",
"is",
"two",
"tokens",
"ago",
".",
"LT",
"(",
"0",
")",
"is",
"undefined",
".",
"For",
"i",
">",
"=",
"n",
"return",
"Token",
".",
"EOFToken",
".",
"Return",
"null",
"for",
"LT",
"(",
"0",
")",
"and",
"any",
"index",
"that",
"results",
"in",
"an",
"absolute",
"address",
"that",
"is",
"negative",
"."
] | def LT(self, k):
"""
Get Token at current input pointer + i ahead where i=1 is next Token.
i<0 indicates tokens in the past. So -1 is previous token and -2 is
two tokens ago. LT(0) is undefined. For i>=n, return Token.EOFToken.
Return null for LT(0) and any index that results in an absolute address
that is negative.
"""
raise NotImplementedError | [
"def",
"LT",
"(",
"self",
",",
"k",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/ideawu/ssdb-rocks/blob/a3cbb322cafb2f493252829c608e2239df98c9ac/deps/cpy/antlr3/streams.py#L255-L264 |
||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/third_party/Python/module/pexpect-2.4/examples/rippy.py | python | calculate_revised_bitrate | (
video_bitrate,
video_target_size,
video_actual_size) | return int(math.floor(video_bitrate * \
(float(video_target_size) / float(video_actual_size)))) | This calculates a revised video bitrate given the video_bitrate used,
the actual size that resulted, and the video_target_size.
This can be used if you want to compress the video all over again in an
attempt to get closer to the video_target_size. | This calculates a revised video bitrate given the video_bitrate used,
the actual size that resulted, and the video_target_size.
This can be used if you want to compress the video all over again in an
attempt to get closer to the video_target_size. | [
"This",
"calculates",
"a",
"revised",
"video",
"bitrate",
"given",
"the",
"video_bitrate",
"used",
"the",
"actual",
"size",
"that",
"resulted",
"and",
"the",
"video_target_size",
".",
"This",
"can",
"be",
"used",
"if",
"you",
"want",
"to",
"compress",
"the",
"video",
"all",
"over",
"again",
"in",
"an",
"attempt",
"to",
"get",
"closer",
"to",
"the",
"video_target_size",
"."
] | def calculate_revised_bitrate(
video_bitrate,
video_target_size,
video_actual_size):
"""This calculates a revised video bitrate given the video_bitrate used,
the actual size that resulted, and the video_target_size.
This can be used if you want to compress the video all over again in an
attempt to get closer to the video_target_size.
"""
return int(math.floor(video_bitrate * \
(float(video_target_size) / float(video_actual_size)))) | [
"def",
"calculate_revised_bitrate",
"(",
"video_bitrate",
",",
"video_target_size",
",",
"video_actual_size",
")",
":",
"return",
"int",
"(",
"math",
".",
"floor",
"(",
"video_bitrate",
"*",
"(",
"float",
"(",
"video_target_size",
")",
"/",
"float",
"(",
"video_actual_size",
")",
")",
")",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/third_party/Python/module/pexpect-2.4/examples/rippy.py#L432-L442 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cgutils.py | python | pointer_add | (builder, ptr, offset, return_type=None) | return builder.inttoptr(intptr, return_type or ptr.type) | Add an integral *offset* to pointer *ptr*, and return a pointer
of *return_type* (or, if omitted, the same type as *ptr*).
Note the computation is done in bytes, and ignores the width of
the pointed item type. | Add an integral *offset* to pointer *ptr*, and return a pointer
of *return_type* (or, if omitted, the same type as *ptr*). | [
"Add",
"an",
"integral",
"*",
"offset",
"*",
"to",
"pointer",
"*",
"ptr",
"*",
"and",
"return",
"a",
"pointer",
"of",
"*",
"return_type",
"*",
"(",
"or",
"if",
"omitted",
"the",
"same",
"type",
"as",
"*",
"ptr",
"*",
")",
"."
] | def pointer_add(builder, ptr, offset, return_type=None):
"""
Add an integral *offset* to pointer *ptr*, and return a pointer
of *return_type* (or, if omitted, the same type as *ptr*).
Note the computation is done in bytes, and ignores the width of
the pointed item type.
"""
intptr = builder.ptrtoint(ptr, intp_t)
if isinstance(offset, utils.INT_TYPES):
offset = intp_t(offset)
intptr = builder.add(intptr, offset)
return builder.inttoptr(intptr, return_type or ptr.type) | [
"def",
"pointer_add",
"(",
"builder",
",",
"ptr",
",",
"offset",
",",
"return_type",
"=",
"None",
")",
":",
"intptr",
"=",
"builder",
".",
"ptrtoint",
"(",
"ptr",
",",
"intp_t",
")",
"if",
"isinstance",
"(",
"offset",
",",
"utils",
".",
"INT_TYPES",
")",
":",
"offset",
"=",
"intp_t",
"(",
"offset",
")",
"intptr",
"=",
"builder",
".",
"add",
"(",
"intptr",
",",
"offset",
")",
"return",
"builder",
".",
"inttoptr",
"(",
"intptr",
",",
"return_type",
"or",
"ptr",
".",
"type",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cgutils.py#L885-L897 |
|
plumonito/dtslam | 5994bb9cf7a11981b830370db206bceb654c085d | 3rdparty/opencv-git/platforms/ios/build_framework.py | python | build_opencv | (srcroot, buildroot, target, arch) | builds OpenCV for device or simulator | builds OpenCV for device or simulator | [
"builds",
"OpenCV",
"for",
"device",
"or",
"simulator"
] | def build_opencv(srcroot, buildroot, target, arch):
"builds OpenCV for device or simulator"
builddir = os.path.join(buildroot, target + '-' + arch)
if not os.path.isdir(builddir):
os.makedirs(builddir)
currdir = os.getcwd()
os.chdir(builddir)
# for some reason, if you do not specify CMAKE_BUILD_TYPE, it puts libs to "RELEASE" rather than "Release"
cmakeargs = ("-GXcode " +
"-DCMAKE_BUILD_TYPE=Release " +
"-DCMAKE_TOOLCHAIN_FILE=%s/platforms/ios/cmake/Toolchains/Toolchain-%s_Xcode.cmake " +
"-DBUILD_opencv_world=ON " +
"-DCMAKE_C_FLAGS=\"-Wno-implicit-function-declaration\" " +
"-DCMAKE_INSTALL_PREFIX=install") % (srcroot, target)
# if cmake cache exists, just rerun cmake to update OpenCV.xproj if necessary
if os.path.isfile(os.path.join(builddir, "CMakeCache.txt")):
os.system("cmake %s ." % (cmakeargs,))
else:
os.system("cmake %s %s" % (cmakeargs, srcroot))
for wlib in [builddir + "/modules/world/UninstalledProducts/libopencv_world.a",
builddir + "/lib/Release/libopencv_world.a"]:
if os.path.isfile(wlib):
os.remove(wlib)
os.system("xcodebuild IPHONEOS_DEPLOYMENT_TARGET=6.0 -parallelizeTargets ARCHS=%s -jobs 8 -sdk %s -configuration Release -target ALL_BUILD" % (arch, target.lower()))
os.system("xcodebuild IPHONEOS_DEPLOYMENT_TARGET=6.0 ARCHS=%s -sdk %s -configuration Release -target install install" % (arch, target.lower()))
os.chdir(currdir) | [
"def",
"build_opencv",
"(",
"srcroot",
",",
"buildroot",
",",
"target",
",",
"arch",
")",
":",
"builddir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"buildroot",
",",
"target",
"+",
"'-'",
"+",
"arch",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"builddir",
")",
":",
"os",
".",
"makedirs",
"(",
"builddir",
")",
"currdir",
"=",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"builddir",
")",
"# for some reason, if you do not specify CMAKE_BUILD_TYPE, it puts libs to \"RELEASE\" rather than \"Release\"",
"cmakeargs",
"=",
"(",
"\"-GXcode \"",
"+",
"\"-DCMAKE_BUILD_TYPE=Release \"",
"+",
"\"-DCMAKE_TOOLCHAIN_FILE=%s/platforms/ios/cmake/Toolchains/Toolchain-%s_Xcode.cmake \"",
"+",
"\"-DBUILD_opencv_world=ON \"",
"+",
"\"-DCMAKE_C_FLAGS=\\\"-Wno-implicit-function-declaration\\\" \"",
"+",
"\"-DCMAKE_INSTALL_PREFIX=install\"",
")",
"%",
"(",
"srcroot",
",",
"target",
")",
"# if cmake cache exists, just rerun cmake to update OpenCV.xproj if necessary",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"builddir",
",",
"\"CMakeCache.txt\"",
")",
")",
":",
"os",
".",
"system",
"(",
"\"cmake %s .\"",
"%",
"(",
"cmakeargs",
",",
")",
")",
"else",
":",
"os",
".",
"system",
"(",
"\"cmake %s %s\"",
"%",
"(",
"cmakeargs",
",",
"srcroot",
")",
")",
"for",
"wlib",
"in",
"[",
"builddir",
"+",
"\"/modules/world/UninstalledProducts/libopencv_world.a\"",
",",
"builddir",
"+",
"\"/lib/Release/libopencv_world.a\"",
"]",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"wlib",
")",
":",
"os",
".",
"remove",
"(",
"wlib",
")",
"os",
".",
"system",
"(",
"\"xcodebuild IPHONEOS_DEPLOYMENT_TARGET=6.0 -parallelizeTargets ARCHS=%s -jobs 8 -sdk %s -configuration Release -target ALL_BUILD\"",
"%",
"(",
"arch",
",",
"target",
".",
"lower",
"(",
")",
")",
")",
"os",
".",
"system",
"(",
"\"xcodebuild IPHONEOS_DEPLOYMENT_TARGET=6.0 ARCHS=%s -sdk %s -configuration Release -target install install\"",
"%",
"(",
"arch",
",",
"target",
".",
"lower",
"(",
")",
")",
")",
"os",
".",
"chdir",
"(",
"currdir",
")"
] | https://github.com/plumonito/dtslam/blob/5994bb9cf7a11981b830370db206bceb654c085d/3rdparty/opencv-git/platforms/ios/build_framework.py#L30-L58 |
||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Spreadsheet/App/Spreadsheet_legacy.py | python | SpreadsheetView.update | (self) | updates the cells with the contents of the spreadsheet | updates the cells with the contents of the spreadsheet | [
"updates",
"the",
"cells",
"with",
"the",
"contents",
"of",
"the",
"spreadsheet"
] | def update(self):
"updates the cells with the contents of the spreadsheet"
if self.spreadsheet:
controlled = self.spreadsheet.Proxy.getControlledCells(self.spreadsheet)
controlling = self.spreadsheet.Proxy.getControllingCells(self.spreadsheet)
for cell in self.spreadsheet.Proxy._cells.keys():
if not cell in ["Type","Object"]:
c,r = self.spreadsheet.Proxy.splitKey(cell)
c = "abcdefghijklmnopqrstuvwxyz".index(c)
r = int(str(r))-1
content = getattr(self.spreadsheet.Proxy,cell)
if self.spreadsheet.Proxy.isFunction(cell):
self.doNotChange = True
if content is None:
content = ""
if DEBUG: print("Updating ",cell," to ",content)
if self.table.item(r,c):
self.table.item(r,c).setText(str(content))
else:
self.table.setItem(r,c,QtGui.QTableWidgetItem(str(content)))
if cell in controlled:
brush = QtGui.QBrush(QtGui.QColor(255, 0, 0))
brush.setStyle(QtCore.Qt.Dense6Pattern)
if self.table.item(r,c):
self.table.item(r,c).setBackground(brush)
elif cell in controlling:
brush = QtGui.QBrush(QtGui.QColor(0, 0, 255))
brush.setStyle(QtCore.Qt.Dense6Pattern)
if self.table.item(r,c):
self.table.item(r,c).setBackground(brush)
else:
brush = QtGui.QBrush()
if self.table.item(r,c):
self.table.item(r,c).setBackground(brush) | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"self",
".",
"spreadsheet",
":",
"controlled",
"=",
"self",
".",
"spreadsheet",
".",
"Proxy",
".",
"getControlledCells",
"(",
"self",
".",
"spreadsheet",
")",
"controlling",
"=",
"self",
".",
"spreadsheet",
".",
"Proxy",
".",
"getControllingCells",
"(",
"self",
".",
"spreadsheet",
")",
"for",
"cell",
"in",
"self",
".",
"spreadsheet",
".",
"Proxy",
".",
"_cells",
".",
"keys",
"(",
")",
":",
"if",
"not",
"cell",
"in",
"[",
"\"Type\"",
",",
"\"Object\"",
"]",
":",
"c",
",",
"r",
"=",
"self",
".",
"spreadsheet",
".",
"Proxy",
".",
"splitKey",
"(",
"cell",
")",
"c",
"=",
"\"abcdefghijklmnopqrstuvwxyz\"",
".",
"index",
"(",
"c",
")",
"r",
"=",
"int",
"(",
"str",
"(",
"r",
")",
")",
"-",
"1",
"content",
"=",
"getattr",
"(",
"self",
".",
"spreadsheet",
".",
"Proxy",
",",
"cell",
")",
"if",
"self",
".",
"spreadsheet",
".",
"Proxy",
".",
"isFunction",
"(",
"cell",
")",
":",
"self",
".",
"doNotChange",
"=",
"True",
"if",
"content",
"is",
"None",
":",
"content",
"=",
"\"\"",
"if",
"DEBUG",
":",
"print",
"(",
"\"Updating \"",
",",
"cell",
",",
"\" to \"",
",",
"content",
")",
"if",
"self",
".",
"table",
".",
"item",
"(",
"r",
",",
"c",
")",
":",
"self",
".",
"table",
".",
"item",
"(",
"r",
",",
"c",
")",
".",
"setText",
"(",
"str",
"(",
"content",
")",
")",
"else",
":",
"self",
".",
"table",
".",
"setItem",
"(",
"r",
",",
"c",
",",
"QtGui",
".",
"QTableWidgetItem",
"(",
"str",
"(",
"content",
")",
")",
")",
"if",
"cell",
"in",
"controlled",
":",
"brush",
"=",
"QtGui",
".",
"QBrush",
"(",
"QtGui",
".",
"QColor",
"(",
"255",
",",
"0",
",",
"0",
")",
")",
"brush",
".",
"setStyle",
"(",
"QtCore",
".",
"Qt",
".",
"Dense6Pattern",
")",
"if",
"self",
".",
"table",
".",
"item",
"(",
"r",
",",
"c",
")",
":",
"self",
".",
"table",
".",
"item",
"(",
"r",
",",
"c",
")",
".",
"setBackground",
"(",
"brush",
")",
"elif",
"cell",
"in",
"controlling",
":",
"brush",
"=",
"QtGui",
".",
"QBrush",
"(",
"QtGui",
".",
"QColor",
"(",
"0",
",",
"0",
",",
"255",
")",
")",
"brush",
".",
"setStyle",
"(",
"QtCore",
".",
"Qt",
".",
"Dense6Pattern",
")",
"if",
"self",
".",
"table",
".",
"item",
"(",
"r",
",",
"c",
")",
":",
"self",
".",
"table",
".",
"item",
"(",
"r",
",",
"c",
")",
".",
"setBackground",
"(",
"brush",
")",
"else",
":",
"brush",
"=",
"QtGui",
".",
"QBrush",
"(",
")",
"if",
"self",
".",
"table",
".",
"item",
"(",
"r",
",",
"c",
")",
":",
"self",
".",
"table",
".",
"item",
"(",
"r",
",",
"c",
")",
".",
"setBackground",
"(",
"brush",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Spreadsheet/App/Spreadsheet_legacy.py#L798-L831 |
||
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/boost_1.75.0/tools/build/src/build/targets.py | python | ProjectTarget.create_main_target | (self, name) | return self.main_targets_.get (name, None) | Returns a 'MainTarget' class instance corresponding to the 'name'. | Returns a 'MainTarget' class instance corresponding to the 'name'. | [
"Returns",
"a",
"MainTarget",
"class",
"instance",
"corresponding",
"to",
"the",
"name",
"."
] | def create_main_target (self, name):
""" Returns a 'MainTarget' class instance corresponding to the 'name'.
"""
assert isinstance(name, basestring)
if not self.built_main_targets_:
self.build_main_targets ()
return self.main_targets_.get (name, None) | [
"def",
"create_main_target",
"(",
"self",
",",
"name",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"basestring",
")",
"if",
"not",
"self",
".",
"built_main_targets_",
":",
"self",
".",
"build_main_targets",
"(",
")",
"return",
"self",
".",
"main_targets_",
".",
"get",
"(",
"name",
",",
"None",
")"
] | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/boost_1.75.0/tools/build/src/build/targets.py#L508-L515 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_basestc.py | python | EditraBaseStc.GetCompleter | (self) | return self._code['compsvc'] | Get this buffers completer object
@return: Completer | Get this buffers completer object
@return: Completer | [
"Get",
"this",
"buffers",
"completer",
"object",
"@return",
":",
"Completer"
] | def GetCompleter(self):
"""Get this buffers completer object
@return: Completer
"""
return self._code['compsvc'] | [
"def",
"GetCompleter",
"(",
"self",
")",
":",
"return",
"self",
".",
"_code",
"[",
"'compsvc'",
"]"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_basestc.py#L651-L656 |
|
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/debug/lib/debug_gradients.py | python | _identify_gradient_grad | (op, dy) | return dy | Gradient function for the DebugIdentity op. | Gradient function for the DebugIdentity op. | [
"Gradient",
"function",
"for",
"the",
"DebugIdentity",
"op",
"."
] | def _identify_gradient_grad(op, dy):
"""Gradient function for the DebugIdentity op."""
# TODO(cais): Allow overriding gradient.
grad_debugger_uuid, orig_tensor_name = _parse_grad_debug_op_name(op.name)
grad_debugger = _gradient_debuggers[grad_debugger_uuid]
grad_debugger.register_gradient_tensor(orig_tensor_name, dy)
return dy | [
"def",
"_identify_gradient_grad",
"(",
"op",
",",
"dy",
")",
":",
"# TODO(cais): Allow overriding gradient.",
"grad_debugger_uuid",
",",
"orig_tensor_name",
"=",
"_parse_grad_debug_op_name",
"(",
"op",
".",
"name",
")",
"grad_debugger",
"=",
"_gradient_debuggers",
"[",
"grad_debugger_uuid",
"]",
"grad_debugger",
".",
"register_gradient_tensor",
"(",
"orig_tensor_name",
",",
"dy",
")",
"return",
"dy"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/debug/lib/debug_gradients.py#L362-L368 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ebmlib/_dirmon.py | python | WatcherThread.SetFrequency | (self, milli) | Set the update frequency
@param milli: int (milliseconds) | Set the update frequency
@param milli: int (milliseconds) | [
"Set",
"the",
"update",
"frequency",
"@param",
"milli",
":",
"int",
"(",
"milliseconds",
")"
] | def SetFrequency(self, milli):
"""Set the update frequency
@param milli: int (milliseconds)
"""
self._freq = float(milli) | [
"def",
"SetFrequency",
"(",
"self",
",",
"milli",
")",
":",
"self",
".",
"_freq",
"=",
"float",
"(",
"milli",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ebmlib/_dirmon.py#L299-L304 |
||
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | Examples/ReinforcementLearning/DeepQNeuralNetwork.py | python | ReplayMemory.minibatch | (self, size) | return pre_states, actions, post_states, rewards, dones | Generate a minibatch with the number of samples specified by the size parameter.
Attributes:
size (int): Minibatch size
Returns:
tuple: Tensor[minibatch_size, input_shape...], [int], [float], [bool] | Generate a minibatch with the number of samples specified by the size parameter. | [
"Generate",
"a",
"minibatch",
"with",
"the",
"number",
"of",
"samples",
"specified",
"by",
"the",
"size",
"parameter",
"."
] | def minibatch(self, size):
""" Generate a minibatch with the number of samples specified by the size parameter.
Attributes:
size (int): Minibatch size
Returns:
tuple: Tensor[minibatch_size, input_shape...], [int], [float], [bool]
"""
indexes = self.sample(size)
pre_states = np.array([self.get_state(index) for index in indexes], dtype=np.float32)
post_states = np.array([self.get_state(index + 1) for index in indexes], dtype=np.float32)
actions = self._actions[indexes]
rewards = self._rewards[indexes]
dones = self._terminals[indexes]
return pre_states, actions, post_states, rewards, dones | [
"def",
"minibatch",
"(",
"self",
",",
"size",
")",
":",
"indexes",
"=",
"self",
".",
"sample",
"(",
"size",
")",
"pre_states",
"=",
"np",
".",
"array",
"(",
"[",
"self",
".",
"get_state",
"(",
"index",
")",
"for",
"index",
"in",
"indexes",
"]",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"post_states",
"=",
"np",
".",
"array",
"(",
"[",
"self",
".",
"get_state",
"(",
"index",
"+",
"1",
")",
"for",
"index",
"in",
"indexes",
"]",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"actions",
"=",
"self",
".",
"_actions",
"[",
"indexes",
"]",
"rewards",
"=",
"self",
".",
"_rewards",
"[",
"indexes",
"]",
"dones",
"=",
"self",
".",
"_terminals",
"[",
"indexes",
"]",
"return",
"pre_states",
",",
"actions",
",",
"post_states",
",",
"rewards",
",",
"dones"
] | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/Examples/ReinforcementLearning/DeepQNeuralNetwork.py#L96-L113 |
|
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/normal.py | python | Normal.mean | (self, name="mean") | Mean of this distribution. | Mean of this distribution. | [
"Mean",
"of",
"this",
"distribution",
"."
] | def mean(self, name="mean"):
"""Mean of this distribution."""
with ops.name_scope(self.name):
with ops.op_scope([self._sigma, self._mu], name):
return self._mu * array_ops.ones_like(self._sigma) | [
"def",
"mean",
"(",
"self",
",",
"name",
"=",
"\"mean\"",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"self",
".",
"name",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"self",
".",
"_sigma",
",",
"self",
".",
"_mu",
"]",
",",
"name",
")",
":",
"return",
"self",
".",
"_mu",
"*",
"array_ops",
".",
"ones_like",
"(",
"self",
".",
"_sigma",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/normal.py#L201-L205 |
||
ZintrulCre/LeetCode_Archiver | de23e16ead29336b5ee7aa1898a392a5d6463d27 | LeetCode/python/283.py | python | Solution.moveZeroes | (self, nums) | :type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead. | :type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead. | [
":",
"type",
"nums",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"void",
"Do",
"not",
"return",
"anything",
"modify",
"nums",
"in",
"-",
"place",
"instead",
"."
] | def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
nonZero = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[nonZero] = nums[i]
nonZero += 1
for i in range(nonZero,len(nums)):
nums[i] = 0 | [
"def",
"moveZeroes",
"(",
"self",
",",
"nums",
")",
":",
"nonZero",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"nums",
")",
")",
":",
"if",
"nums",
"[",
"i",
"]",
"!=",
"0",
":",
"nums",
"[",
"nonZero",
"]",
"=",
"nums",
"[",
"i",
"]",
"nonZero",
"+=",
"1",
"for",
"i",
"in",
"range",
"(",
"nonZero",
",",
"len",
"(",
"nums",
")",
")",
":",
"nums",
"[",
"i",
"]",
"=",
"0"
] | https://github.com/ZintrulCre/LeetCode_Archiver/blob/de23e16ead29336b5ee7aa1898a392a5d6463d27/LeetCode/python/283.py#L2-L13 |
||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/training/saver.py | python | Saver.set_last_checkpoints_with_time | (self, last_checkpoints_with_time) | Sets the list of old checkpoint filenames and timestamps.
Args:
last_checkpoints_with_time: A list of tuples of checkpoint filenames and
timestamps.
Raises:
AssertionError: If last_checkpoints_with_time is not a list. | Sets the list of old checkpoint filenames and timestamps. | [
"Sets",
"the",
"list",
"of",
"old",
"checkpoint",
"filenames",
"and",
"timestamps",
"."
] | def set_last_checkpoints_with_time(self, last_checkpoints_with_time):
"""Sets the list of old checkpoint filenames and timestamps.
Args:
last_checkpoints_with_time: A list of tuples of checkpoint filenames and
timestamps.
Raises:
AssertionError: If last_checkpoints_with_time is not a list.
"""
assert isinstance(last_checkpoints_with_time, list)
self._last_checkpoints = last_checkpoints_with_time | [
"def",
"set_last_checkpoints_with_time",
"(",
"self",
",",
"last_checkpoints_with_time",
")",
":",
"assert",
"isinstance",
"(",
"last_checkpoints_with_time",
",",
"list",
")",
"self",
".",
"_last_checkpoints",
"=",
"last_checkpoints_with_time"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/training/saver.py#L1000-L1011 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/_vendor/pyparsing.py | python | indentedBlock | (blockStatementExpr, indentStack, indent=True) | return smExpr.setName('indented block') | Helper method for defining space-delimited indentation blocks, such as
those used to define block statements in Python source code.
Parameters:
- blockStatementExpr - expression defining syntax of statement that
is repeated within the indented block
- indentStack - list created by caller to manage indentation stack
(multiple statementWithIndentedBlock expressions within a single grammar
should share a common indentStack)
- indent - boolean indicating whether block must be indented beyond the
the current level; set to False for block of left-most statements
(default=C{True})
A valid block must contain at least one C{blockStatement}.
Example::
data = '''
def A(z):
A1
B = 100
G = A2
A2
A3
B
def BB(a,b,c):
BB1
def BBA():
bba1
bba2
bba3
C
D
def spam(x,y):
def eggs(z):
pass
'''
indentStack = [1]
stmt = Forward()
identifier = Word(alphas, alphanums)
funcDecl = ("def" + identifier + Group( "(" + Optional( delimitedList(identifier) ) + ")" ) + ":")
func_body = indentedBlock(stmt, indentStack)
funcDef = Group( funcDecl + func_body )
rvalue = Forward()
funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")")
rvalue << (funcCall | identifier | Word(nums))
assignment = Group(identifier + "=" + rvalue)
stmt << ( funcDef | assignment | identifier )
module_body = OneOrMore(stmt)
parseTree = module_body.parseString(data)
parseTree.pprint()
prints::
[['def',
'A',
['(', 'z', ')'],
':',
[['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]],
'B',
['def',
'BB',
['(', 'a', 'b', 'c', ')'],
':',
[['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]],
'C',
'D',
['def',
'spam',
['(', 'x', 'y', ')'],
':',
[[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]] | Helper method for defining space-delimited indentation blocks, such as
those used to define block statements in Python source code. | [
"Helper",
"method",
"for",
"defining",
"space",
"-",
"delimited",
"indentation",
"blocks",
"such",
"as",
"those",
"used",
"to",
"define",
"block",
"statements",
"in",
"Python",
"source",
"code",
"."
] | def indentedBlock(blockStatementExpr, indentStack, indent=True):
"""
Helper method for defining space-delimited indentation blocks, such as
those used to define block statements in Python source code.
Parameters:
- blockStatementExpr - expression defining syntax of statement that
is repeated within the indented block
- indentStack - list created by caller to manage indentation stack
(multiple statementWithIndentedBlock expressions within a single grammar
should share a common indentStack)
- indent - boolean indicating whether block must be indented beyond the
the current level; set to False for block of left-most statements
(default=C{True})
A valid block must contain at least one C{blockStatement}.
Example::
data = '''
def A(z):
A1
B = 100
G = A2
A2
A3
B
def BB(a,b,c):
BB1
def BBA():
bba1
bba2
bba3
C
D
def spam(x,y):
def eggs(z):
pass
'''
indentStack = [1]
stmt = Forward()
identifier = Word(alphas, alphanums)
funcDecl = ("def" + identifier + Group( "(" + Optional( delimitedList(identifier) ) + ")" ) + ":")
func_body = indentedBlock(stmt, indentStack)
funcDef = Group( funcDecl + func_body )
rvalue = Forward()
funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")")
rvalue << (funcCall | identifier | Word(nums))
assignment = Group(identifier + "=" + rvalue)
stmt << ( funcDef | assignment | identifier )
module_body = OneOrMore(stmt)
parseTree = module_body.parseString(data)
parseTree.pprint()
prints::
[['def',
'A',
['(', 'z', ')'],
':',
[['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]],
'B',
['def',
'BB',
['(', 'a', 'b', 'c', ')'],
':',
[['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]],
'C',
'D',
['def',
'spam',
['(', 'x', 'y', ')'],
':',
[[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]]
"""
def checkPeerIndent(s,l,t):
if l >= len(s): return
curCol = col(l,s)
if curCol != indentStack[-1]:
if curCol > indentStack[-1]:
raise ParseFatalException(s,l,"illegal nesting")
raise ParseException(s,l,"not a peer entry")
def checkSubIndent(s,l,t):
curCol = col(l,s)
if curCol > indentStack[-1]:
indentStack.append( curCol )
else:
raise ParseException(s,l,"not a subentry")
def checkUnindent(s,l,t):
if l >= len(s): return
curCol = col(l,s)
if not(indentStack and curCol < indentStack[-1] and curCol <= indentStack[-2]):
raise ParseException(s,l,"not an unindent")
indentStack.pop()
NL = OneOrMore(LineEnd().setWhitespaceChars("\t ").suppress())
INDENT = (Empty() + Empty().setParseAction(checkSubIndent)).setName('INDENT')
PEER = Empty().setParseAction(checkPeerIndent).setName('')
UNDENT = Empty().setParseAction(checkUnindent).setName('UNINDENT')
if indent:
smExpr = Group( Optional(NL) +
#~ FollowedBy(blockStatementExpr) +
INDENT + (OneOrMore( PEER + Group(blockStatementExpr) + Optional(NL) )) + UNDENT)
else:
smExpr = Group( Optional(NL) +
(OneOrMore( PEER + Group(blockStatementExpr) + Optional(NL) )) )
blockStatementExpr.ignore(_bslash + LineEnd())
return smExpr.setName('indented block') | [
"def",
"indentedBlock",
"(",
"blockStatementExpr",
",",
"indentStack",
",",
"indent",
"=",
"True",
")",
":",
"def",
"checkPeerIndent",
"(",
"s",
",",
"l",
",",
"t",
")",
":",
"if",
"l",
">=",
"len",
"(",
"s",
")",
":",
"return",
"curCol",
"=",
"col",
"(",
"l",
",",
"s",
")",
"if",
"curCol",
"!=",
"indentStack",
"[",
"-",
"1",
"]",
":",
"if",
"curCol",
">",
"indentStack",
"[",
"-",
"1",
"]",
":",
"raise",
"ParseFatalException",
"(",
"s",
",",
"l",
",",
"\"illegal nesting\"",
")",
"raise",
"ParseException",
"(",
"s",
",",
"l",
",",
"\"not a peer entry\"",
")",
"def",
"checkSubIndent",
"(",
"s",
",",
"l",
",",
"t",
")",
":",
"curCol",
"=",
"col",
"(",
"l",
",",
"s",
")",
"if",
"curCol",
">",
"indentStack",
"[",
"-",
"1",
"]",
":",
"indentStack",
".",
"append",
"(",
"curCol",
")",
"else",
":",
"raise",
"ParseException",
"(",
"s",
",",
"l",
",",
"\"not a subentry\"",
")",
"def",
"checkUnindent",
"(",
"s",
",",
"l",
",",
"t",
")",
":",
"if",
"l",
">=",
"len",
"(",
"s",
")",
":",
"return",
"curCol",
"=",
"col",
"(",
"l",
",",
"s",
")",
"if",
"not",
"(",
"indentStack",
"and",
"curCol",
"<",
"indentStack",
"[",
"-",
"1",
"]",
"and",
"curCol",
"<=",
"indentStack",
"[",
"-",
"2",
"]",
")",
":",
"raise",
"ParseException",
"(",
"s",
",",
"l",
",",
"\"not an unindent\"",
")",
"indentStack",
".",
"pop",
"(",
")",
"NL",
"=",
"OneOrMore",
"(",
"LineEnd",
"(",
")",
".",
"setWhitespaceChars",
"(",
"\"\\t \"",
")",
".",
"suppress",
"(",
")",
")",
"INDENT",
"=",
"(",
"Empty",
"(",
")",
"+",
"Empty",
"(",
")",
".",
"setParseAction",
"(",
"checkSubIndent",
")",
")",
".",
"setName",
"(",
"'INDENT'",
")",
"PEER",
"=",
"Empty",
"(",
")",
".",
"setParseAction",
"(",
"checkPeerIndent",
")",
".",
"setName",
"(",
"''",
")",
"UNDENT",
"=",
"Empty",
"(",
")",
".",
"setParseAction",
"(",
"checkUnindent",
")",
".",
"setName",
"(",
"'UNINDENT'",
")",
"if",
"indent",
":",
"smExpr",
"=",
"Group",
"(",
"Optional",
"(",
"NL",
")",
"+",
"#~ FollowedBy(blockStatementExpr) +",
"INDENT",
"+",
"(",
"OneOrMore",
"(",
"PEER",
"+",
"Group",
"(",
"blockStatementExpr",
")",
"+",
"Optional",
"(",
"NL",
")",
")",
")",
"+",
"UNDENT",
")",
"else",
":",
"smExpr",
"=",
"Group",
"(",
"Optional",
"(",
"NL",
")",
"+",
"(",
"OneOrMore",
"(",
"PEER",
"+",
"Group",
"(",
"blockStatementExpr",
")",
"+",
"Optional",
"(",
"NL",
")",
")",
")",
")",
"blockStatementExpr",
".",
"ignore",
"(",
"_bslash",
"+",
"LineEnd",
"(",
")",
")",
"return",
"smExpr",
".",
"setName",
"(",
"'indented block'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/_vendor/pyparsing.py#L5248-L5360 |
|
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/rfc822.py | python | Message.getdate_tz | (self, name) | return parsedate_tz(data) | Retrieve a date field from a header as a 10-tuple.
The first 9 elements make up a tuple compatible with time.mktime(),
and the 10th is the offset of the poster's time zone from GMT/UTC. | Retrieve a date field from a header as a 10-tuple. | [
"Retrieve",
"a",
"date",
"field",
"from",
"a",
"header",
"as",
"a",
"10",
"-",
"tuple",
"."
] | def getdate_tz(self, name):
"""Retrieve a date field from a header as a 10-tuple.
The first 9 elements make up a tuple compatible with time.mktime(),
and the 10th is the offset of the poster's time zone from GMT/UTC.
"""
try:
data = self[name]
except KeyError:
return None
return parsedate_tz(data) | [
"def",
"getdate_tz",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"data",
"=",
"self",
"[",
"name",
"]",
"except",
"KeyError",
":",
"return",
"None",
"return",
"parsedate_tz",
"(",
"data",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/rfc822.py#L367-L377 |
|
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/traci/_vehicle.py | python | VehicleDomain.getTypeID | (self, vehID) | return self._getUniversal(tc.VAR_TYPE, vehID) | getTypeID(string) -> string
Returns the id of the type of the named vehicle. | getTypeID(string) -> string | [
"getTypeID",
"(",
"string",
")",
"-",
">",
"string"
] | def getTypeID(self, vehID):
"""getTypeID(string) -> string
Returns the id of the type of the named vehicle.
"""
return self._getUniversal(tc.VAR_TYPE, vehID) | [
"def",
"getTypeID",
"(",
"self",
",",
"vehID",
")",
":",
"return",
"self",
".",
"_getUniversal",
"(",
"tc",
".",
"VAR_TYPE",
",",
"vehID",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_vehicle.py#L315-L320 |
|
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TIntHI.GetKey | (self) | return _snap.TIntHI_GetKey(self) | GetKey(TIntHI self) -> TInt
Parameters:
self: THashKeyDatI< TInt,TInt > const * | GetKey(TIntHI self) -> TInt | [
"GetKey",
"(",
"TIntHI",
"self",
")",
"-",
">",
"TInt"
] | def GetKey(self):
"""
GetKey(TIntHI self) -> TInt
Parameters:
self: THashKeyDatI< TInt,TInt > const *
"""
return _snap.TIntHI_GetKey(self) | [
"def",
"GetKey",
"(",
"self",
")",
":",
"return",
"_snap",
".",
"TIntHI_GetKey",
"(",
"self",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L19057-L19065 |
|
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Fem/femtools/tokrules.py | python | p_expression_group | (p) | expression : LPAREN expression RPAREN | expression : LPAREN expression RPAREN | [
"expression",
":",
"LPAREN",
"expression",
"RPAREN"
] | def p_expression_group(p):
'expression : LPAREN expression RPAREN'
p[0] = p[2] | [
"def",
"p_expression_group",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"2",
"]"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Fem/femtools/tokrules.py#L127-L129 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.