nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/telnetlib.py | python | Telnet.process_rawq | (self) | Transfer from raw queue to cooked queue.
Set self.eof when connection is closed. Don't block unless in
the midst of an IAC sequence. | Transfer from raw queue to cooked queue. | [
"Transfer",
"from",
"raw",
"queue",
"to",
"cooked",
"queue",
"."
] | def process_rawq(self):
"""Transfer from raw queue to cooked queue.
Set self.eof when connection is closed. Don't block unless in
the midst of an IAC sequence.
"""
buf = [b'', b'']
try:
while self.rawq:
c = self.rawq_getchar()
if not self.iacseq:
if c == theNULL:
continue
if c == b"\021":
continue
if c != IAC:
buf[self.sb] = buf[self.sb] + c
continue
else:
self.iacseq += c
elif len(self.iacseq) == 1:
# 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'
if c in (DO, DONT, WILL, WONT):
self.iacseq += c
continue
self.iacseq = b''
if c == IAC:
buf[self.sb] = buf[self.sb] + c
else:
if c == SB: # SB ... SE start.
self.sb = 1
self.sbdataq = b''
elif c == SE:
self.sb = 0
self.sbdataq = self.sbdataq + buf[1]
buf[1] = b''
if self.option_callback:
# Callback is supposed to look into
# the sbdataq
self.option_callback(self.sock, c, NOOPT)
else:
# We can't offer automatic processing of
# suboptions. Alas, we should not get any
# unless we did a WILL/DO before.
self.msg('IAC %d not recognized' % ord(c))
elif len(self.iacseq) == 2:
cmd = self.iacseq[1:2]
self.iacseq = b''
opt = c
if cmd in (DO, DONT):
self.msg('IAC %s %d',
cmd == DO and 'DO' or 'DONT', ord(opt))
if self.option_callback:
self.option_callback(self.sock, cmd, opt)
else:
self.sock.sendall(IAC + WONT + opt)
elif cmd in (WILL, WONT):
self.msg('IAC %s %d',
cmd == WILL and 'WILL' or 'WONT', ord(opt))
if self.option_callback:
self.option_callback(self.sock, cmd, opt)
else:
self.sock.sendall(IAC + DONT + opt)
except EOFError: # raised by self.rawq_getchar()
self.iacseq = b'' # Reset on EOF
self.sb = 0
pass
self.cookedq = self.cookedq + buf[0]
self.sbdataq = self.sbdataq + buf[1] | [
"def",
"process_rawq",
"(",
"self",
")",
":",
"buf",
"=",
"[",
"b''",
",",
"b''",
"]",
"try",
":",
"while",
"self",
".",
"rawq",
":",
"c",
"=",
"self",
".",
"rawq_getchar",
"(",
")",
"if",
"not",
"self",
".",
"iacseq",
":",
"if",
"c",
"==",
"theNULL",
":",
"continue",
"if",
"c",
"==",
"b\"\\021\"",
":",
"continue",
"if",
"c",
"!=",
"IAC",
":",
"buf",
"[",
"self",
".",
"sb",
"]",
"=",
"buf",
"[",
"self",
".",
"sb",
"]",
"+",
"c",
"continue",
"else",
":",
"self",
".",
"iacseq",
"+=",
"c",
"elif",
"len",
"(",
"self",
".",
"iacseq",
")",
"==",
"1",
":",
"# 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'",
"if",
"c",
"in",
"(",
"DO",
",",
"DONT",
",",
"WILL",
",",
"WONT",
")",
":",
"self",
".",
"iacseq",
"+=",
"c",
"continue",
"self",
".",
"iacseq",
"=",
"b''",
"if",
"c",
"==",
"IAC",
":",
"buf",
"[",
"self",
".",
"sb",
"]",
"=",
"buf",
"[",
"self",
".",
"sb",
"]",
"+",
"c",
"else",
":",
"if",
"c",
"==",
"SB",
":",
"# SB ... SE start.",
"self",
".",
"sb",
"=",
"1",
"self",
".",
"sbdataq",
"=",
"b''",
"elif",
"c",
"==",
"SE",
":",
"self",
".",
"sb",
"=",
"0",
"self",
".",
"sbdataq",
"=",
"self",
".",
"sbdataq",
"+",
"buf",
"[",
"1",
"]",
"buf",
"[",
"1",
"]",
"=",
"b''",
"if",
"self",
".",
"option_callback",
":",
"# Callback is supposed to look into",
"# the sbdataq",
"self",
".",
"option_callback",
"(",
"self",
".",
"sock",
",",
"c",
",",
"NOOPT",
")",
"else",
":",
"# We can't offer automatic processing of",
"# suboptions. Alas, we should not get any",
"# unless we did a WILL/DO before.",
"self",
".",
"msg",
"(",
"'IAC %d not recognized'",
"%",
"ord",
"(",
"c",
")",
")",
"elif",
"len",
"(",
"self",
".",
"iacseq",
")",
"==",
"2",
":",
"cmd",
"=",
"self",
".",
"iacseq",
"[",
"1",
":",
"2",
"]",
"self",
".",
"iacseq",
"=",
"b''",
"opt",
"=",
"c",
"if",
"cmd",
"in",
"(",
"DO",
",",
"DONT",
")",
":",
"self",
".",
"msg",
"(",
"'IAC %s %d'",
",",
"cmd",
"==",
"DO",
"and",
"'DO'",
"or",
"'DONT'",
",",
"ord",
"(",
"opt",
")",
")",
"if",
"self",
".",
"option_callback",
":",
"self",
".",
"option_callback",
"(",
"self",
".",
"sock",
",",
"cmd",
",",
"opt",
")",
"else",
":",
"self",
".",
"sock",
".",
"sendall",
"(",
"IAC",
"+",
"WONT",
"+",
"opt",
")",
"elif",
"cmd",
"in",
"(",
"WILL",
",",
"WONT",
")",
":",
"self",
".",
"msg",
"(",
"'IAC %s %d'",
",",
"cmd",
"==",
"WILL",
"and",
"'WILL'",
"or",
"'WONT'",
",",
"ord",
"(",
"opt",
")",
")",
"if",
"self",
".",
"option_callback",
":",
"self",
".",
"option_callback",
"(",
"self",
".",
"sock",
",",
"cmd",
",",
"opt",
")",
"else",
":",
"self",
".",
"sock",
".",
"sendall",
"(",
"IAC",
"+",
"DONT",
"+",
"opt",
")",
"except",
"EOFError",
":",
"# raised by self.rawq_getchar()",
"self",
".",
"iacseq",
"=",
"b''",
"# Reset on EOF",
"self",
".",
"sb",
"=",
"0",
"pass",
"self",
".",
"cookedq",
"=",
"self",
".",
"cookedq",
"+",
"buf",
"[",
"0",
"]",
"self",
".",
"sbdataq",
"=",
"self",
".",
"sbdataq",
"+",
"buf",
"[",
"1",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/telnetlib.py#L424-L494 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/summary/impl/gcs.py | python | ListDirectory | (directory) | return subprocess.check_output(command).splitlines() | Lists all files in the given directory. | Lists all files in the given directory. | [
"Lists",
"all",
"files",
"in",
"the",
"given",
"directory",
"."
] | def ListDirectory(directory):
"""Lists all files in the given directory."""
command = ['gsutil', 'ls', directory]
return subprocess.check_output(command).splitlines() | [
"def",
"ListDirectory",
"(",
"directory",
")",
":",
"command",
"=",
"[",
"'gsutil'",
",",
"'ls'",
",",
"directory",
"]",
"return",
"subprocess",
".",
"check_output",
"(",
"command",
")",
".",
"splitlines",
"(",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/summary/impl/gcs.py#L50-L53 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/SANS/sans/algorithm_detail/CreateSANSAdjustmentWorkspaces.py | python | CreateSANSAdjustmentWorkspaces.create_sans_adjustment_workspaces | (self, transmission_ws, direct_ws, monitor_ws,
sample_data, wav_range: WavRange) | return to_return | Creates the adjustment workspace
:param transmission_ws: The transmission workspace.
:param direct_ws: The direct workspace.
:param monitor_ws: The scatter monitor workspace. This workspace only contains monitors.
:param sample_data: A workspace cropped to the detector to be reduced (the SAME as the input to Q1D).
This used to verify the solid angle. The workspace is not modified, just inspected.
:return: A dict containing the following:
wavelength_adj : The workspace for wavelength-based adjustments.
pixel_adj : The workspace for wavelength-based adjustments.
wavelength_pixel_adj : The workspace for, both, wavelength- and pixel-based adjustments.
calculated_trans_ws : The calculated transmission workspace
unfitted_trans_ws : The unfitted transmission workspace | Creates the adjustment workspace
:param transmission_ws: The transmission workspace.
:param direct_ws: The direct workspace.
:param monitor_ws: The scatter monitor workspace. This workspace only contains monitors.
:param sample_data: A workspace cropped to the detector to be reduced (the SAME as the input to Q1D).
This used to verify the solid angle. The workspace is not modified, just inspected.
:return: A dict containing the following:
wavelength_adj : The workspace for wavelength-based adjustments.
pixel_adj : The workspace for wavelength-based adjustments.
wavelength_pixel_adj : The workspace for, both, wavelength- and pixel-based adjustments.
calculated_trans_ws : The calculated transmission workspace
unfitted_trans_ws : The unfitted transmission workspace | [
"Creates",
"the",
"adjustment",
"workspace",
":",
"param",
"transmission_ws",
":",
"The",
"transmission",
"workspace",
".",
":",
"param",
"direct_ws",
":",
"The",
"direct",
"workspace",
".",
":",
"param",
"monitor_ws",
":",
"The",
"scatter",
"monitor",
"workspace",
".",
"This",
"workspace",
"only",
"contains",
"monitors",
".",
":",
"param",
"sample_data",
":",
"A",
"workspace",
"cropped",
"to",
"the",
"detector",
"to",
"be",
"reduced",
"(",
"the",
"SAME",
"as",
"the",
"input",
"to",
"Q1D",
")",
".",
"This",
"used",
"to",
"verify",
"the",
"solid",
"angle",
".",
"The",
"workspace",
"is",
"not",
"modified",
"just",
"inspected",
".",
":",
"return",
":",
"A",
"dict",
"containing",
"the",
"following",
":",
"wavelength_adj",
":",
"The",
"workspace",
"for",
"wavelength",
"-",
"based",
"adjustments",
".",
"pixel_adj",
":",
"The",
"workspace",
"for",
"wavelength",
"-",
"based",
"adjustments",
".",
"wavelength_pixel_adj",
":",
"The",
"workspace",
"for",
"both",
"wavelength",
"-",
"and",
"pixel",
"-",
"based",
"adjustments",
".",
"calculated_trans_ws",
":",
"The",
"calculated",
"transmission",
"workspace",
"unfitted_trans_ws",
":",
"The",
"unfitted",
"transmission",
"workspace"
] | def create_sans_adjustment_workspaces(self, transmission_ws, direct_ws, monitor_ws,
sample_data, wav_range: WavRange):
"""
Creates the adjustment workspace
:param transmission_ws: The transmission workspace.
:param direct_ws: The direct workspace.
:param monitor_ws: The scatter monitor workspace. This workspace only contains monitors.
:param sample_data: A workspace cropped to the detector to be reduced (the SAME as the input to Q1D).
This used to verify the solid angle. The workspace is not modified, just inspected.
:return: A dict containing the following:
wavelength_adj : The workspace for wavelength-based adjustments.
pixel_adj : The workspace for wavelength-based adjustments.
wavelength_pixel_adj : The workspace for, both, wavelength- and pixel-based adjustments.
calculated_trans_ws : The calculated transmission workspace
unfitted_trans_ws : The unfitted transmission workspace
"""
# --------------------------------------
# Get the monitor normalization workspace
# --------------------------------------
monitor_normalization_workspace = self._get_monitor_normalization_workspace(monitor_ws=monitor_ws,
wav_range=wav_range)
# --------------------------------------
# Get the calculated transmission
# --------------------------------------
calculated_trans_ws, unfitted_transmission_workspace = \
self._get_calculated_transmission_workspace(direct_ws=direct_ws, transmission_ws=transmission_ws,
wav_range=wav_range)
# --------------------------------------
# Get the wide angle correction workspace
# --------------------------------------
wavelength_and_pixel_adj_workspace = \
self._get_wide_angle_correction_workspace(sample_data=sample_data,
calculated_transmission_workspace=calculated_trans_ws)
# --------------------------------------------
# Get the full wavelength and pixel adjustment
# --------------------------------------------
wavelength_adjustment_workspace, pixel_length_adjustment_workspace = \
self._get_wavelength_and_pixel_adjustment_workspaces(
calculated_transmission_workspace=calculated_trans_ws, wav_range=wav_range,
monitor_normalization_workspace=monitor_normalization_workspace)
to_return = {"wavelength_adj": wavelength_adjustment_workspace,
"pixel_adj": pixel_length_adjustment_workspace,
"wavelength_pixel_adj": wavelength_and_pixel_adj_workspace,
"calculated_trans_ws": calculated_trans_ws,
"unfitted_trans_ws": unfitted_transmission_workspace}
return to_return | [
"def",
"create_sans_adjustment_workspaces",
"(",
"self",
",",
"transmission_ws",
",",
"direct_ws",
",",
"monitor_ws",
",",
"sample_data",
",",
"wav_range",
":",
"WavRange",
")",
":",
"# --------------------------------------",
"# Get the monitor normalization workspace",
"# --------------------------------------",
"monitor_normalization_workspace",
"=",
"self",
".",
"_get_monitor_normalization_workspace",
"(",
"monitor_ws",
"=",
"monitor_ws",
",",
"wav_range",
"=",
"wav_range",
")",
"# --------------------------------------",
"# Get the calculated transmission",
"# --------------------------------------",
"calculated_trans_ws",
",",
"unfitted_transmission_workspace",
"=",
"self",
".",
"_get_calculated_transmission_workspace",
"(",
"direct_ws",
"=",
"direct_ws",
",",
"transmission_ws",
"=",
"transmission_ws",
",",
"wav_range",
"=",
"wav_range",
")",
"# --------------------------------------",
"# Get the wide angle correction workspace",
"# --------------------------------------",
"wavelength_and_pixel_adj_workspace",
"=",
"self",
".",
"_get_wide_angle_correction_workspace",
"(",
"sample_data",
"=",
"sample_data",
",",
"calculated_transmission_workspace",
"=",
"calculated_trans_ws",
")",
"# --------------------------------------------",
"# Get the full wavelength and pixel adjustment",
"# --------------------------------------------",
"wavelength_adjustment_workspace",
",",
"pixel_length_adjustment_workspace",
"=",
"self",
".",
"_get_wavelength_and_pixel_adjustment_workspaces",
"(",
"calculated_transmission_workspace",
"=",
"calculated_trans_ws",
",",
"wav_range",
"=",
"wav_range",
",",
"monitor_normalization_workspace",
"=",
"monitor_normalization_workspace",
")",
"to_return",
"=",
"{",
"\"wavelength_adj\"",
":",
"wavelength_adjustment_workspace",
",",
"\"pixel_adj\"",
":",
"pixel_length_adjustment_workspace",
",",
"\"wavelength_pixel_adj\"",
":",
"wavelength_and_pixel_adj_workspace",
",",
"\"calculated_trans_ws\"",
":",
"calculated_trans_ws",
",",
"\"unfitted_trans_ws\"",
":",
"unfitted_transmission_workspace",
"}",
"return",
"to_return"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/sans/algorithm_detail/CreateSANSAdjustmentWorkspaces.py#L38-L88 | |
sigmaai/self-driving-golf-cart | 8d891600af3d851add27a10ae45cf3c2108bb87c | ros/src/autopilot/scripts/pilot.py | python | Pilot.__init__ | (self, weight_path, model_type, input_length, img_height, img_width) | Constructor for SteeringPredictor class
:param weight_path:
:param model_type: | Constructor for SteeringPredictor class
:param weight_path:
:param model_type: | [
"Constructor",
"for",
"SteeringPredictor",
"class",
":",
"param",
"weight_path",
":",
":",
"param",
"model_type",
":"
] | def __init__(self, weight_path, model_type, input_length, img_height, img_width):
"""
Constructor for SteeringPredictor class
:param weight_path:
:param model_type:
"""
self.img_height = img_height
self.img_width = img_width
self.length = input_length
self.model = Inception3D(input_shape=(input_length, self.img_height, self.img_width, 3), weights_path=weight_path)
self.inputs = []
self.model_type = model_type | [
"def",
"__init__",
"(",
"self",
",",
"weight_path",
",",
"model_type",
",",
"input_length",
",",
"img_height",
",",
"img_width",
")",
":",
"self",
".",
"img_height",
"=",
"img_height",
"self",
".",
"img_width",
"=",
"img_width",
"self",
".",
"length",
"=",
"input_length",
"self",
".",
"model",
"=",
"Inception3D",
"(",
"input_shape",
"=",
"(",
"input_length",
",",
"self",
".",
"img_height",
",",
"self",
".",
"img_width",
",",
"3",
")",
",",
"weights_path",
"=",
"weight_path",
")",
"self",
".",
"inputs",
"=",
"[",
"]",
"self",
".",
"model_type",
"=",
"model_type"
] | https://github.com/sigmaai/self-driving-golf-cart/blob/8d891600af3d851add27a10ae45cf3c2108bb87c/ros/src/autopilot/scripts/pilot.py#L18-L31 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/warnings.py | python | filterwarnings | (action, message="", category=Warning, module="", lineno=0,
append=False) | Insert an entry into the list of warnings filters (at the front).
'action' -- one of "error", "ignore", "always", "default", "module",
or "once"
'message' -- a regex that the warning message must match
'category' -- a class that the warning must be a subclass of
'module' -- a regex that the module name must match
'lineno' -- an integer line number, 0 matches all warnings
'append' -- if true, append to the list of filters | Insert an entry into the list of warnings filters (at the front). | [
"Insert",
"an",
"entry",
"into",
"the",
"list",
"of",
"warnings",
"filters",
"(",
"at",
"the",
"front",
")",
"."
] | def filterwarnings(action, message="", category=Warning, module="", lineno=0,
append=False):
"""Insert an entry into the list of warnings filters (at the front).
'action' -- one of "error", "ignore", "always", "default", "module",
or "once"
'message' -- a regex that the warning message must match
'category' -- a class that the warning must be a subclass of
'module' -- a regex that the module name must match
'lineno' -- an integer line number, 0 matches all warnings
'append' -- if true, append to the list of filters
"""
assert action in ("error", "ignore", "always", "default", "module",
"once"), "invalid action: %r" % (action,)
assert isinstance(message, str), "message must be a string"
assert isinstance(category, type), "category must be a class"
assert issubclass(category, Warning), "category must be a Warning subclass"
assert isinstance(module, str), "module must be a string"
assert isinstance(lineno, int) and lineno >= 0, \
"lineno must be an int >= 0"
if message or module:
import re
if message:
message = re.compile(message, re.I)
else:
message = None
if module:
module = re.compile(module)
else:
module = None
_add_filter(action, message, category, module, lineno, append=append) | [
"def",
"filterwarnings",
"(",
"action",
",",
"message",
"=",
"\"\"",
",",
"category",
"=",
"Warning",
",",
"module",
"=",
"\"\"",
",",
"lineno",
"=",
"0",
",",
"append",
"=",
"False",
")",
":",
"assert",
"action",
"in",
"(",
"\"error\"",
",",
"\"ignore\"",
",",
"\"always\"",
",",
"\"default\"",
",",
"\"module\"",
",",
"\"once\"",
")",
",",
"\"invalid action: %r\"",
"%",
"(",
"action",
",",
")",
"assert",
"isinstance",
"(",
"message",
",",
"str",
")",
",",
"\"message must be a string\"",
"assert",
"isinstance",
"(",
"category",
",",
"type",
")",
",",
"\"category must be a class\"",
"assert",
"issubclass",
"(",
"category",
",",
"Warning",
")",
",",
"\"category must be a Warning subclass\"",
"assert",
"isinstance",
"(",
"module",
",",
"str",
")",
",",
"\"module must be a string\"",
"assert",
"isinstance",
"(",
"lineno",
",",
"int",
")",
"and",
"lineno",
">=",
"0",
",",
"\"lineno must be an int >= 0\"",
"if",
"message",
"or",
"module",
":",
"import",
"re",
"if",
"message",
":",
"message",
"=",
"re",
".",
"compile",
"(",
"message",
",",
"re",
".",
"I",
")",
"else",
":",
"message",
"=",
"None",
"if",
"module",
":",
"module",
"=",
"re",
".",
"compile",
"(",
"module",
")",
"else",
":",
"module",
"=",
"None",
"_add_filter",
"(",
"action",
",",
"message",
",",
"category",
",",
"module",
",",
"lineno",
",",
"append",
"=",
"append",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/warnings.py#L130-L163 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/metrics/pairwise.py | python | check_paired_arrays | (X, Y) | return X, Y | Set X and Y appropriately and checks inputs for paired distances
All paired distance metrics should use this function first to assert that
the given parameters are correct and safe to use.
Specifically, this function first ensures that both X and Y are arrays,
then checks that they are at least two dimensional while ensuring that
their elements are floats. Finally, the function checks that the size
of the dimensions of the two arrays are equal.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples_a, n_features)
Y : {array-like, sparse matrix}, shape (n_samples_b, n_features)
Returns
-------
safe_X : {array-like, sparse matrix}, shape (n_samples_a, n_features)
An array equal to X, guaranteed to be a numpy array.
safe_Y : {array-like, sparse matrix}, shape (n_samples_b, n_features)
An array equal to Y if Y was not None, guaranteed to be a numpy array.
If Y was None, safe_Y will be a pointer to X. | Set X and Y appropriately and checks inputs for paired distances | [
"Set",
"X",
"and",
"Y",
"appropriately",
"and",
"checks",
"inputs",
"for",
"paired",
"distances"
] | def check_paired_arrays(X, Y):
""" Set X and Y appropriately and checks inputs for paired distances
All paired distance metrics should use this function first to assert that
the given parameters are correct and safe to use.
Specifically, this function first ensures that both X and Y are arrays,
then checks that they are at least two dimensional while ensuring that
their elements are floats. Finally, the function checks that the size
of the dimensions of the two arrays are equal.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples_a, n_features)
Y : {array-like, sparse matrix}, shape (n_samples_b, n_features)
Returns
-------
safe_X : {array-like, sparse matrix}, shape (n_samples_a, n_features)
An array equal to X, guaranteed to be a numpy array.
safe_Y : {array-like, sparse matrix}, shape (n_samples_b, n_features)
An array equal to Y if Y was not None, guaranteed to be a numpy array.
If Y was None, safe_Y will be a pointer to X.
"""
X, Y = check_pairwise_arrays(X, Y)
if X.shape != Y.shape:
raise ValueError("X and Y should be of same shape. They were "
"respectively %r and %r long." % (X.shape, Y.shape))
return X, Y | [
"def",
"check_paired_arrays",
"(",
"X",
",",
"Y",
")",
":",
"X",
",",
"Y",
"=",
"check_pairwise_arrays",
"(",
"X",
",",
"Y",
")",
"if",
"X",
".",
"shape",
"!=",
"Y",
".",
"shape",
":",
"raise",
"ValueError",
"(",
"\"X and Y should be of same shape. They were \"",
"\"respectively %r and %r long.\"",
"%",
"(",
"X",
".",
"shape",
",",
"Y",
".",
"shape",
")",
")",
"return",
"X",
",",
"Y"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/metrics/pairwise.py#L160-L191 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/symtable.py | python | Symbol.get_namespace | (self) | return self.__namespaces[0] | Returns the single namespace bound to this name.
Raises ValueError if the name is bound to multiple namespaces. | Returns the single namespace bound to this name. | [
"Returns",
"the",
"single",
"namespace",
"bound",
"to",
"this",
"name",
"."
] | def get_namespace(self):
"""Returns the single namespace bound to this name.
Raises ValueError if the name is bound to multiple namespaces.
"""
if len(self.__namespaces) != 1:
raise ValueError, "name is bound to multiple namespaces"
return self.__namespaces[0] | [
"def",
"get_namespace",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"__namespaces",
")",
"!=",
"1",
":",
"raise",
"ValueError",
",",
"\"name is bound to multiple namespaces\"",
"return",
"self",
".",
"__namespaces",
"[",
"0",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/symtable.py#L227-L234 | |
baldurk/renderdoc | ec5c14dee844b18dc545b52c4bd705ae20cba5d7 | docs/pycharm_helpers/plugins/python-ce/helpers/generator3/module_redeclarator.py | python | ModuleRedeclarator.parse_func_doc | (self, func_doc, func_id, func_name, class_name, deco=None, sip_generated=False) | @param func_doc: __doc__ of the function.
@param func_id: name to look for as identifier of the function in docstring
@param func_name: name of the function.
@param class_name: name of the containing class, or None
@param deco: decorator to use
@return (reconstructed_spec, return_literal, note) or (None, _, _) if failed. | [] | def parse_func_doc(self, func_doc, func_id, func_name, class_name, deco=None, sip_generated=False):
"""
@param func_doc: __doc__ of the function.
@param func_id: name to look for as identifier of the function in docstring
@param func_name: name of the function.
@param class_name: name of the containing class, or None
@param deco: decorator to use
@return (reconstructed_spec, return_literal, note) or (None, _, _) if failed.
"""
if sip_generated:
overloads = []
for part in func_doc.split('\n'):
signature = func_id + '('
i = part.find(signature)
if i >= 0:
overloads.append(part[i + len(signature):])
if len(overloads) > 1:
docstring_results = [self.restore_by_docstring(overload, class_name, deco) for overload in overloads]
import_types = []
ret_types = []
for result in docstring_results:
rt = result[1]
if rt and rt not in ret_types:
ret_types.append(rt)
imps = result[3]
for imp in imps:
if imp and imp not in import_types:
import_types.append(imp)
if ret_types:
ret_literal = " or ".join(ret_types)
else:
ret_literal = None
param_lists = [result[0] for result in docstring_results]
spec = build_signature(func_name, restore_parameters_for_overloads(param_lists))
return (spec, ret_literal, "restored from __doc__ with multiple overloads", import_types)
# find the first thing to look like a definition
prefix_re = re.compile(r"\s*(?:(\w+)[ \t]+)?" + func_id + r"\s*\(") # "foo(..." or "int foo(..."
match = prefix_re.search(func_doc) # Note: this and previous line may consume up to 35% of time
# parse the part that looks right
if match:
ret_hint = match.group(1)
params, ret, doc_note, import_types, ret_hint = self.restore_by_docstring(func_doc[match.end():], class_name, deco, ret_hint)
spec = func_name + flatten(params)
# if we got a type hint, put it on the function declaration
if ret_hint:
spec = spec + ' -> ' + ret_hint
return (spec, ret, doc_note, import_types)
else:
return (None, None, None, []) | [
"def",
"parse_func_doc",
"(",
"self",
",",
"func_doc",
",",
"func_id",
",",
"func_name",
",",
"class_name",
",",
"deco",
"=",
"None",
",",
"sip_generated",
"=",
"False",
")",
":",
"if",
"sip_generated",
":",
"overloads",
"=",
"[",
"]",
"for",
"part",
"in",
"func_doc",
".",
"split",
"(",
"'\\n'",
")",
":",
"signature",
"=",
"func_id",
"+",
"'('",
"i",
"=",
"part",
".",
"find",
"(",
"signature",
")",
"if",
"i",
">=",
"0",
":",
"overloads",
".",
"append",
"(",
"part",
"[",
"i",
"+",
"len",
"(",
"signature",
")",
":",
"]",
")",
"if",
"len",
"(",
"overloads",
")",
">",
"1",
":",
"docstring_results",
"=",
"[",
"self",
".",
"restore_by_docstring",
"(",
"overload",
",",
"class_name",
",",
"deco",
")",
"for",
"overload",
"in",
"overloads",
"]",
"import_types",
"=",
"[",
"]",
"ret_types",
"=",
"[",
"]",
"for",
"result",
"in",
"docstring_results",
":",
"rt",
"=",
"result",
"[",
"1",
"]",
"if",
"rt",
"and",
"rt",
"not",
"in",
"ret_types",
":",
"ret_types",
".",
"append",
"(",
"rt",
")",
"imps",
"=",
"result",
"[",
"3",
"]",
"for",
"imp",
"in",
"imps",
":",
"if",
"imp",
"and",
"imp",
"not",
"in",
"import_types",
":",
"import_types",
".",
"append",
"(",
"imp",
")",
"if",
"ret_types",
":",
"ret_literal",
"=",
"\" or \"",
".",
"join",
"(",
"ret_types",
")",
"else",
":",
"ret_literal",
"=",
"None",
"param_lists",
"=",
"[",
"result",
"[",
"0",
"]",
"for",
"result",
"in",
"docstring_results",
"]",
"spec",
"=",
"build_signature",
"(",
"func_name",
",",
"restore_parameters_for_overloads",
"(",
"param_lists",
")",
")",
"return",
"(",
"spec",
",",
"ret_literal",
",",
"\"restored from __doc__ with multiple overloads\"",
",",
"import_types",
")",
"# find the first thing to look like a definition",
"prefix_re",
"=",
"re",
".",
"compile",
"(",
"r\"\\s*(?:(\\w+)[ \\t]+)?\"",
"+",
"func_id",
"+",
"r\"\\s*\\(\"",
")",
"# \"foo(...\" or \"int foo(...\"",
"match",
"=",
"prefix_re",
".",
"search",
"(",
"func_doc",
")",
"# Note: this and previous line may consume up to 35% of time",
"# parse the part that looks right",
"if",
"match",
":",
"ret_hint",
"=",
"match",
".",
"group",
"(",
"1",
")",
"params",
",",
"ret",
",",
"doc_note",
",",
"import_types",
",",
"ret_hint",
"=",
"self",
".",
"restore_by_docstring",
"(",
"func_doc",
"[",
"match",
".",
"end",
"(",
")",
":",
"]",
",",
"class_name",
",",
"deco",
",",
"ret_hint",
")",
"spec",
"=",
"func_name",
"+",
"flatten",
"(",
"params",
")",
"# if we got a type hint, put it on the function declaration",
"if",
"ret_hint",
":",
"spec",
"=",
"spec",
"+",
"' -> '",
"+",
"ret_hint",
"return",
"(",
"spec",
",",
"ret",
",",
"doc_note",
",",
"import_types",
")",
"else",
":",
"return",
"(",
"None",
",",
"None",
",",
"None",
",",
"[",
"]",
")"
] | https://github.com/baldurk/renderdoc/blob/ec5c14dee844b18dc545b52c4bd705ae20cba5d7/docs/pycharm_helpers/plugins/python-ce/helpers/generator3/module_redeclarator.py#L538-L587 | |||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/wizard.py | python | PyWizardPage.DoGetBestSize | (*args, **kwargs) | return _wizard.PyWizardPage_DoGetBestSize(*args, **kwargs) | DoGetBestSize(self) -> Size | DoGetBestSize(self) -> Size | [
"DoGetBestSize",
"(",
"self",
")",
"-",
">",
"Size"
] | def DoGetBestSize(*args, **kwargs):
"""DoGetBestSize(self) -> Size"""
return _wizard.PyWizardPage_DoGetBestSize(*args, **kwargs) | [
"def",
"DoGetBestSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_wizard",
".",
"PyWizardPage_DoGetBestSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/wizard.py#L183-L185 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/propgrid.py | python | PropertyGridInterface.SetPropertyReadOnly | (*args, **kwargs) | return _propgrid.PropertyGridInterface_SetPropertyReadOnly(*args, **kwargs) | SetPropertyReadOnly(self, PGPropArg id, bool set=True, int flags=PG_RECURSE) | SetPropertyReadOnly(self, PGPropArg id, bool set=True, int flags=PG_RECURSE) | [
"SetPropertyReadOnly",
"(",
"self",
"PGPropArg",
"id",
"bool",
"set",
"=",
"True",
"int",
"flags",
"=",
"PG_RECURSE",
")"
] | def SetPropertyReadOnly(*args, **kwargs):
"""SetPropertyReadOnly(self, PGPropArg id, bool set=True, int flags=PG_RECURSE)"""
return _propgrid.PropertyGridInterface_SetPropertyReadOnly(*args, **kwargs) | [
"def",
"SetPropertyReadOnly",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGridInterface_SetPropertyReadOnly",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L1426-L1428 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | TaskBarIcon.IsOk | (*args, **kwargs) | return _windows_.TaskBarIcon_IsOk(*args, **kwargs) | IsOk(self) -> bool | IsOk(self) -> bool | [
"IsOk",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsOk(*args, **kwargs):
"""IsOk(self) -> bool"""
return _windows_.TaskBarIcon_IsOk(*args, **kwargs) | [
"def",
"IsOk",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"TaskBarIcon_IsOk",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L2830-L2832 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/nntplib.py | python | _parse_datetime | (date_str, time_str=None) | return datetime.datetime(year, month, day, hours, minutes, seconds) | Parse a pair of (date, time) strings, and return a datetime object.
If only the date is given, it is assumed to be date and time
concatenated together (e.g. response to the DATE command). | Parse a pair of (date, time) strings, and return a datetime object.
If only the date is given, it is assumed to be date and time
concatenated together (e.g. response to the DATE command). | [
"Parse",
"a",
"pair",
"of",
"(",
"date",
"time",
")",
"strings",
"and",
"return",
"a",
"datetime",
"object",
".",
"If",
"only",
"the",
"date",
"is",
"given",
"it",
"is",
"assumed",
"to",
"be",
"date",
"and",
"time",
"concatenated",
"together",
"(",
"e",
".",
"g",
".",
"response",
"to",
"the",
"DATE",
"command",
")",
"."
] | def _parse_datetime(date_str, time_str=None):
"""Parse a pair of (date, time) strings, and return a datetime object.
If only the date is given, it is assumed to be date and time
concatenated together (e.g. response to the DATE command).
"""
if time_str is None:
time_str = date_str[-6:]
date_str = date_str[:-6]
hours = int(time_str[:2])
minutes = int(time_str[2:4])
seconds = int(time_str[4:])
year = int(date_str[:-4])
month = int(date_str[-4:-2])
day = int(date_str[-2:])
# RFC 3977 doesn't say how to interpret 2-char years. Assume that
# there are no dates before 1970 on Usenet.
if year < 70:
year += 2000
elif year < 100:
year += 1900
return datetime.datetime(year, month, day, hours, minutes, seconds) | [
"def",
"_parse_datetime",
"(",
"date_str",
",",
"time_str",
"=",
"None",
")",
":",
"if",
"time_str",
"is",
"None",
":",
"time_str",
"=",
"date_str",
"[",
"-",
"6",
":",
"]",
"date_str",
"=",
"date_str",
"[",
":",
"-",
"6",
"]",
"hours",
"=",
"int",
"(",
"time_str",
"[",
":",
"2",
"]",
")",
"minutes",
"=",
"int",
"(",
"time_str",
"[",
"2",
":",
"4",
"]",
")",
"seconds",
"=",
"int",
"(",
"time_str",
"[",
"4",
":",
"]",
")",
"year",
"=",
"int",
"(",
"date_str",
"[",
":",
"-",
"4",
"]",
")",
"month",
"=",
"int",
"(",
"date_str",
"[",
"-",
"4",
":",
"-",
"2",
"]",
")",
"day",
"=",
"int",
"(",
"date_str",
"[",
"-",
"2",
":",
"]",
")",
"# RFC 3977 doesn't say how to interpret 2-char years. Assume that",
"# there are no dates before 1970 on Usenet.",
"if",
"year",
"<",
"70",
":",
"year",
"+=",
"2000",
"elif",
"year",
"<",
"100",
":",
"year",
"+=",
"1900",
"return",
"datetime",
".",
"datetime",
"(",
"year",
",",
"month",
",",
"day",
",",
"hours",
",",
"minutes",
",",
"seconds",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/nntplib.py#L232-L252 | |
logcabin/logcabin | ee6c55ae9744b82b451becd9707d26c7c1b6bbfb | scripts/cpplint.py | python | FileInfo.Extension | (self) | return self.Split()[2] | File extension - text following the final period. | File extension - text following the final period. | [
"File",
"extension",
"-",
"text",
"following",
"the",
"final",
"period",
"."
] | def Extension(self):
"""File extension - text following the final period."""
return self.Split()[2] | [
"def",
"Extension",
"(",
"self",
")",
":",
"return",
"self",
".",
"Split",
"(",
")",
"[",
"2",
"]"
] | https://github.com/logcabin/logcabin/blob/ee6c55ae9744b82b451becd9707d26c7c1b6bbfb/scripts/cpplint.py#L706-L708 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/backend.py | python | random_binomial | (shape, p=0.0, dtype=None, seed=None) | return random_bernoulli(shape, p, dtype, seed) | Returns a tensor with random binomial distribution of values.
DEPRECATED, use `tf.keras.backend.random_bernoulli` instead.
The binomial distribution with parameters `n` and `p` is the probability
distribution of the number of successful Bernoulli process. Only supports
`n` = 1 for now.
Args:
shape: A tuple of integers, the shape of tensor to create.
p: A float, `0. <= p <= 1`, probability of binomial distribution.
dtype: String, dtype of returned tensor.
seed: Integer, random seed.
Returns:
A tensor.
Example:
>>> random_binomial_tensor = tf.keras.backend.random_binomial(shape=(2,3),
... p=0.5)
>>> random_binomial_tensor
<tf.Tensor: shape=(2, 3), dtype=float32, numpy=...,
dtype=float32)> | Returns a tensor with random binomial distribution of values. | [
"Returns",
"a",
"tensor",
"with",
"random",
"binomial",
"distribution",
"of",
"values",
"."
] | def random_binomial(shape, p=0.0, dtype=None, seed=None):
"""Returns a tensor with random binomial distribution of values.
DEPRECATED, use `tf.keras.backend.random_bernoulli` instead.
The binomial distribution with parameters `n` and `p` is the probability
distribution of the number of successful Bernoulli process. Only supports
`n` = 1 for now.
Args:
shape: A tuple of integers, the shape of tensor to create.
p: A float, `0. <= p <= 1`, probability of binomial distribution.
dtype: String, dtype of returned tensor.
seed: Integer, random seed.
Returns:
A tensor.
Example:
>>> random_binomial_tensor = tf.keras.backend.random_binomial(shape=(2,3),
... p=0.5)
>>> random_binomial_tensor
<tf.Tensor: shape=(2, 3), dtype=float32, numpy=...,
dtype=float32)>
"""
warnings.warn('`tf.keras.backend.random_binomial` is deprecated, '
'and will be removed in a future version.'
'Please use `tf.keras.backend.random_bernoulli` instead.')
return random_bernoulli(shape, p, dtype, seed) | [
"def",
"random_binomial",
"(",
"shape",
",",
"p",
"=",
"0.0",
",",
"dtype",
"=",
"None",
",",
"seed",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"'`tf.keras.backend.random_binomial` is deprecated, '",
"'and will be removed in a future version.'",
"'Please use `tf.keras.backend.random_bernoulli` instead.'",
")",
"return",
"random_bernoulli",
"(",
"shape",
",",
"p",
",",
"dtype",
",",
"seed",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/backend.py#L6098-L6127 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/typing.py | python | _check_generic | (cls, parameters) | Check correct count for parameters of a generic cls (internal helper).
This gives a nice error message in case of count mismatch. | Check correct count for parameters of a generic cls (internal helper).
This gives a nice error message in case of count mismatch. | [
"Check",
"correct",
"count",
"for",
"parameters",
"of",
"a",
"generic",
"cls",
"(",
"internal",
"helper",
")",
".",
"This",
"gives",
"a",
"nice",
"error",
"message",
"in",
"case",
"of",
"count",
"mismatch",
"."
] | def _check_generic(cls, parameters):
"""Check correct count for parameters of a generic cls (internal helper).
This gives a nice error message in case of count mismatch.
"""
if not cls.__parameters__:
raise TypeError(f"{cls} is not a generic class")
alen = len(parameters)
elen = len(cls.__parameters__)
if alen != elen:
raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
f" actual {alen}, expected {elen}") | [
"def",
"_check_generic",
"(",
"cls",
",",
"parameters",
")",
":",
"if",
"not",
"cls",
".",
"__parameters__",
":",
"raise",
"TypeError",
"(",
"f\"{cls} is not a generic class\"",
")",
"alen",
"=",
"len",
"(",
"parameters",
")",
"elen",
"=",
"len",
"(",
"cls",
".",
"__parameters__",
")",
"if",
"alen",
"!=",
"elen",
":",
"raise",
"TypeError",
"(",
"f\"Too {'many' if alen > elen else 'few'} parameters for {cls};\"",
"f\" actual {alen}, expected {elen}\"",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/typing.py#L199-L209 | ||
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TIntV.IsIn | (self, *args) | return _snap.TIntV_IsIn(self, *args) | IsIn(TIntV self, TInt Val) -> bool
Parameters:
Val: TInt const &
IsIn(TIntV self, TInt Val, int & ValN) -> bool
Parameters:
Val: TInt const &
ValN: int & | IsIn(TIntV self, TInt Val) -> bool | [
"IsIn",
"(",
"TIntV",
"self",
"TInt",
"Val",
")",
"-",
">",
"bool"
] | def IsIn(self, *args):
"""
IsIn(TIntV self, TInt Val) -> bool
Parameters:
Val: TInt const &
IsIn(TIntV self, TInt Val, int & ValN) -> bool
Parameters:
Val: TInt const &
ValN: int &
"""
return _snap.TIntV_IsIn(self, *args) | [
"def",
"IsIn",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TIntV_IsIn",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L16146-L16160 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/closure_compiler/processor.py | python | Processor.get_file_from_line | (self, line_number) | return LineNumber(self._lines[line_number][0], self._lines[line_number][1]) | Get the original file and line number for an expanded file's line number.
Args:
line_number: A processed file's line number (as an integer or string). | Get the original file and line number for an expanded file's line number. | [
"Get",
"the",
"original",
"file",
"and",
"line",
"number",
"for",
"an",
"expanded",
"file",
"s",
"line",
"number",
"."
] | def get_file_from_line(self, line_number):
"""Get the original file and line number for an expanded file's line number.
Args:
line_number: A processed file's line number (as an integer or string).
"""
line_number = int(line_number) - 1
return LineNumber(self._lines[line_number][0], self._lines[line_number][1]) | [
"def",
"get_file_from_line",
"(",
"self",
",",
"line_number",
")",
":",
"line_number",
"=",
"int",
"(",
"line_number",
")",
"-",
"1",
"return",
"LineNumber",
"(",
"self",
".",
"_lines",
"[",
"line_number",
"]",
"[",
"0",
"]",
",",
"self",
".",
"_lines",
"[",
"line_number",
"]",
"[",
"1",
"]",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/closure_compiler/processor.py#L111-L118 | |
Smorodov/Multitarget-tracker | bee300e8bfd660c86cbeb6892c65a5b7195c9381 | thirdparty/pybind11/tools/clang/cindex.py | python | Cursor.semantic_parent | (self) | return self._semantic_parent | Return the semantic parent for this cursor. | Return the semantic parent for this cursor. | [
"Return",
"the",
"semantic",
"parent",
"for",
"this",
"cursor",
"."
] | def semantic_parent(self):
"""Return the semantic parent for this cursor."""
if not hasattr(self, '_semantic_parent'):
self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self)
return self._semantic_parent | [
"def",
"semantic_parent",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_semantic_parent'",
")",
":",
"self",
".",
"_semantic_parent",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorSemanticParent",
"(",
"self",
")",
"return",
"self",
".",
"_semantic_parent"
] | https://github.com/Smorodov/Multitarget-tracker/blob/bee300e8bfd660c86cbeb6892c65a5b7195c9381/thirdparty/pybind11/tools/clang/cindex.py#L1573-L1578 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/extras.py | python | compress_nd | (x, axis=None) | return data | Suppress slices from multiple dimensions which contain masked values.
Parameters
----------
x : array_like, MaskedArray
The array to operate on. If not a MaskedArray instance (or if no array
elements are masked, `x` is interpreted as a MaskedArray with `mask`
set to `nomask`.
axis : tuple of ints or int, optional
Which dimensions to suppress slices from can be configured with this
parameter.
- If axis is a tuple of ints, those are the axes to suppress slices from.
- If axis is an int, then that is the only axis to suppress slices from.
- If axis is None, all axis are selected.
Returns
-------
compress_array : ndarray
The compressed array. | Suppress slices from multiple dimensions which contain masked values. | [
"Suppress",
"slices",
"from",
"multiple",
"dimensions",
"which",
"contain",
"masked",
"values",
"."
] | def compress_nd(x, axis=None):
"""Suppress slices from multiple dimensions which contain masked values.
Parameters
----------
x : array_like, MaskedArray
The array to operate on. If not a MaskedArray instance (or if no array
elements are masked, `x` is interpreted as a MaskedArray with `mask`
set to `nomask`.
axis : tuple of ints or int, optional
Which dimensions to suppress slices from can be configured with this
parameter.
- If axis is a tuple of ints, those are the axes to suppress slices from.
- If axis is an int, then that is the only axis to suppress slices from.
- If axis is None, all axis are selected.
Returns
-------
compress_array : ndarray
The compressed array.
"""
x = asarray(x)
m = getmask(x)
# Set axis to tuple of ints
if axis is None:
axis = tuple(range(x.ndim))
else:
axis = normalize_axis_tuple(axis, x.ndim)
# Nothing is masked: return x
if m is nomask or not m.any():
return x._data
# All is masked: return empty
if m.all():
return nxarray([])
# Filter elements through boolean indexing
data = x._data
for ax in axis:
axes = tuple(list(range(ax)) + list(range(ax + 1, x.ndim)))
data = data[(slice(None),)*ax + (~m.any(axis=axes),)]
return data | [
"def",
"compress_nd",
"(",
"x",
",",
"axis",
"=",
"None",
")",
":",
"x",
"=",
"asarray",
"(",
"x",
")",
"m",
"=",
"getmask",
"(",
"x",
")",
"# Set axis to tuple of ints",
"if",
"axis",
"is",
"None",
":",
"axis",
"=",
"tuple",
"(",
"range",
"(",
"x",
".",
"ndim",
")",
")",
"else",
":",
"axis",
"=",
"normalize_axis_tuple",
"(",
"axis",
",",
"x",
".",
"ndim",
")",
"# Nothing is masked: return x",
"if",
"m",
"is",
"nomask",
"or",
"not",
"m",
".",
"any",
"(",
")",
":",
"return",
"x",
".",
"_data",
"# All is masked: return empty",
"if",
"m",
".",
"all",
"(",
")",
":",
"return",
"nxarray",
"(",
"[",
"]",
")",
"# Filter elements through boolean indexing",
"data",
"=",
"x",
".",
"_data",
"for",
"ax",
"in",
"axis",
":",
"axes",
"=",
"tuple",
"(",
"list",
"(",
"range",
"(",
"ax",
")",
")",
"+",
"list",
"(",
"range",
"(",
"ax",
"+",
"1",
",",
"x",
".",
"ndim",
")",
")",
")",
"data",
"=",
"data",
"[",
"(",
"slice",
"(",
"None",
")",
",",
")",
"*",
"ax",
"+",
"(",
"~",
"m",
".",
"any",
"(",
"axis",
"=",
"axes",
")",
",",
")",
"]",
"return",
"data"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/extras.py#L809-L849 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | Rect.GetY | (*args, **kwargs) | return _core_.Rect_GetY(*args, **kwargs) | GetY(self) -> int | GetY(self) -> int | [
"GetY",
"(",
"self",
")",
"-",
">",
"int"
] | def GetY(*args, **kwargs):
"""GetY(self) -> int"""
return _core_.Rect_GetY(*args, **kwargs) | [
"def",
"GetY",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Rect_GetY",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L1277-L1279 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/io.py | python | IOBase.writable | (self) | return False | Return whether object was opened for writing.
If False, write() and truncate() will raise IOError. | Return whether object was opened for writing. | [
"Return",
"whether",
"object",
"was",
"opened",
"for",
"writing",
"."
] | def writable(self):
"""Return whether object was opened for writing.
If False, write() and truncate() will raise IOError.
"""
return False | [
"def",
"writable",
"(",
"self",
")",
":",
"return",
"False"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/io.py#L431-L436 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/data_flow_ops.py | python | _LookupTableExportShape | (op) | return [keys_shape, values_shape] | Shape function for data_flow_ops._lookup_table_export_values. | Shape function for data_flow_ops._lookup_table_export_values. | [
"Shape",
"function",
"for",
"data_flow_ops",
".",
"_lookup_table_export_values",
"."
] | def _LookupTableExportShape(op):
"""Shape function for data_flow_ops._lookup_table_export_values."""
op.inputs[0].get_shape().merge_with(tensor_shape.scalar())
keys_shape = tensor_shape.vector(None)
values_shape = tensor_shape.unknown_shape()
return [keys_shape, values_shape] | [
"def",
"_LookupTableExportShape",
"(",
"op",
")",
":",
"op",
".",
"inputs",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
".",
"merge_with",
"(",
"tensor_shape",
".",
"scalar",
"(",
")",
")",
"keys_shape",
"=",
"tensor_shape",
".",
"vector",
"(",
"None",
")",
"values_shape",
"=",
"tensor_shape",
".",
"unknown_shape",
"(",
")",
"return",
"[",
"keys_shape",
",",
"values_shape",
"]"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/data_flow_ops.py#L1147-L1152 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/telemetry/third_party/png/png.py | python | check_palette | (palette) | return p | Check a palette argument (to the :class:`Writer` class) for validity.
Returns the palette as a list if okay; raises an exception otherwise. | Check a palette argument (to the :class:`Writer` class) for validity.
Returns the palette as a list if okay; raises an exception otherwise. | [
"Check",
"a",
"palette",
"argument",
"(",
"to",
"the",
":",
"class",
":",
"Writer",
"class",
")",
"for",
"validity",
".",
"Returns",
"the",
"palette",
"as",
"a",
"list",
"if",
"okay",
";",
"raises",
"an",
"exception",
"otherwise",
"."
] | def check_palette(palette):
"""Check a palette argument (to the :class:`Writer` class) for validity.
Returns the palette as a list if okay; raises an exception otherwise.
"""
# None is the default and is allowed.
if palette is None:
return None
p = list(palette)
if not (0 < len(p) <= 256):
raise ValueError("a palette must have between 1 and 256 entries")
seen_triple = False
for i,t in enumerate(p):
if len(t) not in (3,4):
raise ValueError(
"palette entry %d: entries must be 3- or 4-tuples." % i)
if len(t) == 3:
seen_triple = True
if seen_triple and len(t) == 4:
raise ValueError(
"palette entry %d: all 4-tuples must precede all 3-tuples" % i)
for x in t:
if int(x) != x or not(0 <= x <= 255):
raise ValueError(
"palette entry %d: values must be integer: 0 <= x <= 255" % i)
return p | [
"def",
"check_palette",
"(",
"palette",
")",
":",
"# None is the default and is allowed.",
"if",
"palette",
"is",
"None",
":",
"return",
"None",
"p",
"=",
"list",
"(",
"palette",
")",
"if",
"not",
"(",
"0",
"<",
"len",
"(",
"p",
")",
"<=",
"256",
")",
":",
"raise",
"ValueError",
"(",
"\"a palette must have between 1 and 256 entries\"",
")",
"seen_triple",
"=",
"False",
"for",
"i",
",",
"t",
"in",
"enumerate",
"(",
"p",
")",
":",
"if",
"len",
"(",
"t",
")",
"not",
"in",
"(",
"3",
",",
"4",
")",
":",
"raise",
"ValueError",
"(",
"\"palette entry %d: entries must be 3- or 4-tuples.\"",
"%",
"i",
")",
"if",
"len",
"(",
"t",
")",
"==",
"3",
":",
"seen_triple",
"=",
"True",
"if",
"seen_triple",
"and",
"len",
"(",
"t",
")",
"==",
"4",
":",
"raise",
"ValueError",
"(",
"\"palette entry %d: all 4-tuples must precede all 3-tuples\"",
"%",
"i",
")",
"for",
"x",
"in",
"t",
":",
"if",
"int",
"(",
"x",
")",
"!=",
"x",
"or",
"not",
"(",
"0",
"<=",
"x",
"<=",
"255",
")",
":",
"raise",
"ValueError",
"(",
"\"palette entry %d: values must be integer: 0 <= x <= 255\"",
"%",
"i",
")",
"return",
"p"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/png/png.py#L272-L298 | |
GoSSIP-SJTU/TripleDoggy | 03648d6b19c812504b14e8b98c8c7b3f443f4e54 | tools/clang/tools/scan-build-py/libscanbuild/intercept.py | python | capture | (args) | The entry point of build command interception. | The entry point of build command interception. | [
"The",
"entry",
"point",
"of",
"build",
"command",
"interception",
"."
] | def capture(args):
""" The entry point of build command interception. """
def post_processing(commands):
""" To make a compilation database, it needs to filter out commands
which are not compiler calls. Needs to find the source file name
from the arguments. And do shell escaping on the command.
To support incremental builds, it is desired to read elements from
an existing compilation database from a previous run. These elements
shall be merged with the new elements. """
# create entries from the current run
current = itertools.chain.from_iterable(
# creates a sequence of entry generators from an exec,
format_entry(command) for command in commands)
# read entries from previous run
if 'append' in args and args.append and os.path.isfile(args.cdb):
with open(args.cdb) as handle:
previous = iter(json.load(handle))
else:
previous = iter([])
# filter out duplicate entries from both
duplicate = duplicate_check(entry_hash)
return (entry
for entry in itertools.chain(previous, current)
if os.path.exists(entry['file']) and not duplicate(entry))
with TemporaryDirectory(prefix='intercept-') as tmp_dir:
# run the build command
environment = setup_environment(args, tmp_dir)
exit_code = run_build(args.build, env=environment)
# read the intercepted exec calls
exec_traces = itertools.chain.from_iterable(
parse_exec_trace(os.path.join(tmp_dir, filename))
for filename in sorted(glob.iglob(os.path.join(tmp_dir, '*.cmd'))))
# do post processing
entries = post_processing(exec_traces)
# dump the compilation database
with open(args.cdb, 'w+') as handle:
json.dump(list(entries), handle, sort_keys=True, indent=4)
return exit_code | [
"def",
"capture",
"(",
"args",
")",
":",
"def",
"post_processing",
"(",
"commands",
")",
":",
"\"\"\" To make a compilation database, it needs to filter out commands\n which are not compiler calls. Needs to find the source file name\n from the arguments. And do shell escaping on the command.\n\n To support incremental builds, it is desired to read elements from\n an existing compilation database from a previous run. These elements\n shall be merged with the new elements. \"\"\"",
"# create entries from the current run",
"current",
"=",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"# creates a sequence of entry generators from an exec,",
"format_entry",
"(",
"command",
")",
"for",
"command",
"in",
"commands",
")",
"# read entries from previous run",
"if",
"'append'",
"in",
"args",
"and",
"args",
".",
"append",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"args",
".",
"cdb",
")",
":",
"with",
"open",
"(",
"args",
".",
"cdb",
")",
"as",
"handle",
":",
"previous",
"=",
"iter",
"(",
"json",
".",
"load",
"(",
"handle",
")",
")",
"else",
":",
"previous",
"=",
"iter",
"(",
"[",
"]",
")",
"# filter out duplicate entries from both",
"duplicate",
"=",
"duplicate_check",
"(",
"entry_hash",
")",
"return",
"(",
"entry",
"for",
"entry",
"in",
"itertools",
".",
"chain",
"(",
"previous",
",",
"current",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"entry",
"[",
"'file'",
"]",
")",
"and",
"not",
"duplicate",
"(",
"entry",
")",
")",
"with",
"TemporaryDirectory",
"(",
"prefix",
"=",
"'intercept-'",
")",
"as",
"tmp_dir",
":",
"# run the build command",
"environment",
"=",
"setup_environment",
"(",
"args",
",",
"tmp_dir",
")",
"exit_code",
"=",
"run_build",
"(",
"args",
".",
"build",
",",
"env",
"=",
"environment",
")",
"# read the intercepted exec calls",
"exec_traces",
"=",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"parse_exec_trace",
"(",
"os",
".",
"path",
".",
"join",
"(",
"tmp_dir",
",",
"filename",
")",
")",
"for",
"filename",
"in",
"sorted",
"(",
"glob",
".",
"iglob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"tmp_dir",
",",
"'*.cmd'",
")",
")",
")",
")",
"# do post processing",
"entries",
"=",
"post_processing",
"(",
"exec_traces",
")",
"# dump the compilation database",
"with",
"open",
"(",
"args",
".",
"cdb",
",",
"'w+'",
")",
"as",
"handle",
":",
"json",
".",
"dump",
"(",
"list",
"(",
"entries",
")",
",",
"handle",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"4",
")",
"return",
"exit_code"
] | https://github.com/GoSSIP-SJTU/TripleDoggy/blob/03648d6b19c812504b14e8b98c8c7b3f443f4e54/tools/clang/tools/scan-build-py/libscanbuild/intercept.py#L59-L100 | ||
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Util.py | python | RenameFunction | (function, name) | return FunctionType(function.func_code,
function.func_globals,
name,
function.func_defaults) | Returns a function identical to the specified function, but with
the specified name. | Returns a function identical to the specified function, but with
the specified name. | [
"Returns",
"a",
"function",
"identical",
"to",
"the",
"specified",
"function",
"but",
"with",
"the",
"specified",
"name",
"."
] | def RenameFunction(function, name):
"""
Returns a function identical to the specified function, but with
the specified name.
"""
return FunctionType(function.func_code,
function.func_globals,
name,
function.func_defaults) | [
"def",
"RenameFunction",
"(",
"function",
",",
"name",
")",
":",
"return",
"FunctionType",
"(",
"function",
".",
"func_code",
",",
"function",
".",
"func_globals",
",",
"name",
",",
"function",
".",
"func_defaults",
")"
] | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Util.py#L1405-L1413 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/stone-game-iv.py | python | Solution.winnerSquareGame | (self, n) | return dp[-1] | :type n: int
:rtype: bool | :type n: int
:rtype: bool | [
":",
"type",
"n",
":",
"int",
":",
"rtype",
":",
"bool"
] | def winnerSquareGame(self, n):
"""
:type n: int
:rtype: bool
"""
dp = [False]*(n+1)
for i in xrange(1, n+1):
j = 1
while j*j <= i:
if not dp[i-j*j]:
dp[i] = True
break
j += 1
return dp[-1] | [
"def",
"winnerSquareGame",
"(",
"self",
",",
"n",
")",
":",
"dp",
"=",
"[",
"False",
"]",
"*",
"(",
"n",
"+",
"1",
")",
"for",
"i",
"in",
"xrange",
"(",
"1",
",",
"n",
"+",
"1",
")",
":",
"j",
"=",
"1",
"while",
"j",
"*",
"j",
"<=",
"i",
":",
"if",
"not",
"dp",
"[",
"i",
"-",
"j",
"*",
"j",
"]",
":",
"dp",
"[",
"i",
"]",
"=",
"True",
"break",
"j",
"+=",
"1",
"return",
"dp",
"[",
"-",
"1",
"]"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/stone-game-iv.py#L5-L18 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/reduction_workflow/reducer.py | python | Reducer.append_data_file | (self, data_file, workspace=None) | Append a file to be processed.
@param data_file: name of the file to be processed
@param workspace: optional name of the workspace for this data,
default will be the name of the file
TODO: this needs to be an ordered list | Append a file to be processed. | [
"Append",
"a",
"file",
"to",
"be",
"processed",
"."
] | def append_data_file(self, data_file, workspace=None):
"""
Append a file to be processed.
@param data_file: name of the file to be processed
@param workspace: optional name of the workspace for this data,
default will be the name of the file
TODO: this needs to be an ordered list
"""
if data_file is None:
if AnalysisDataService.doesExist(workspace):
self._data_files[workspace] = None
return
else:
raise RuntimeError("Trying to append a data set without a file name or an existing workspace.")
if isinstance(data_file, list):
if workspace is None:
# Use the first file to determine the workspace name
workspace = extract_workspace_name(data_file[0])
else:
if workspace is None:
workspace = extract_workspace_name(data_file)
self._data_files[workspace] = data_file | [
"def",
"append_data_file",
"(",
"self",
",",
"data_file",
",",
"workspace",
"=",
"None",
")",
":",
"if",
"data_file",
"is",
"None",
":",
"if",
"AnalysisDataService",
".",
"doesExist",
"(",
"workspace",
")",
":",
"self",
".",
"_data_files",
"[",
"workspace",
"]",
"=",
"None",
"return",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Trying to append a data set without a file name or an existing workspace.\"",
")",
"if",
"isinstance",
"(",
"data_file",
",",
"list",
")",
":",
"if",
"workspace",
"is",
"None",
":",
"# Use the first file to determine the workspace name",
"workspace",
"=",
"extract_workspace_name",
"(",
"data_file",
"[",
"0",
"]",
")",
"else",
":",
"if",
"workspace",
"is",
"None",
":",
"workspace",
"=",
"extract_workspace_name",
"(",
"data_file",
")",
"self",
".",
"_data_files",
"[",
"workspace",
"]",
"=",
"data_file"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/reduction_workflow/reducer.py#L94-L116 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_op_impl/tbe/mul_no_nan.py | python | _mul_no_nan_tbe | () | return | MulNoNan TBE register | MulNoNan TBE register | [
"MulNoNan",
"TBE",
"register"
] | def _mul_no_nan_tbe():
"""MulNoNan TBE register"""
return | [
"def",
"_mul_no_nan_tbe",
"(",
")",
":",
"return"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/mul_no_nan.py#L37-L39 | |
i42output/neoGFX | 529857e006466271f9775e1a77882c3919e1c3e1 | 3rdparty/harfbuzz/harfbuzz-3.2.0/src/gen-tag-table.py | python | LanguageTag.get_group | (self) | return ('und'
if (self.language == 'und'
or self.variant in bcp_47.prefixes and len (bcp_47.prefixes[self.variant]) == 1)
else self.language[0]) | Return the group into which this tag should be categorized in
``hb_ot_tags_from_complex_language``.
The group is the first letter of the tag, or ``'und'`` if this tag
should not be matched in a ``switch`` statement in the generated
code.
Returns:
This tag's group. | Return the group into which this tag should be categorized in
``hb_ot_tags_from_complex_language``. | [
"Return",
"the",
"group",
"into",
"which",
"this",
"tag",
"should",
"be",
"categorized",
"in",
"hb_ot_tags_from_complex_language",
"."
] | def get_group (self):
"""Return the group into which this tag should be categorized in
``hb_ot_tags_from_complex_language``.
The group is the first letter of the tag, or ``'und'`` if this tag
should not be matched in a ``switch`` statement in the generated
code.
Returns:
This tag's group.
"""
return ('und'
if (self.language == 'und'
or self.variant in bcp_47.prefixes and len (bcp_47.prefixes[self.variant]) == 1)
else self.language[0]) | [
"def",
"get_group",
"(",
"self",
")",
":",
"return",
"(",
"'und'",
"if",
"(",
"self",
".",
"language",
"==",
"'und'",
"or",
"self",
".",
"variant",
"in",
"bcp_47",
".",
"prefixes",
"and",
"len",
"(",
"bcp_47",
".",
"prefixes",
"[",
"self",
".",
"variant",
"]",
")",
"==",
"1",
")",
"else",
"self",
".",
"language",
"[",
"0",
"]",
")"
] | https://github.com/i42output/neoGFX/blob/529857e006466271f9775e1a77882c3919e1c3e1/3rdparty/harfbuzz/harfbuzz-3.2.0/src/gen-tag-table.py#L299-L313 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | caffe2/python/binarysize.py | python | PrintTrie | (trie, prefix, max_depth, min_size, color) | Prints the symbol trie in a readable manner. | Prints the symbol trie in a readable manner. | [
"Prints",
"the",
"symbol",
"trie",
"in",
"a",
"readable",
"manner",
"."
] | def PrintTrie(trie, prefix, max_depth, min_size, color):
"""Prints the symbol trie in a readable manner.
"""
if len(trie.name) == max_depth or not trie.dictionary.keys():
# If we are reaching a leaf node or the maximum depth, we will print the
# result.
if trie.size > min_size:
print('{0}{1} {2}'.format(
prefix,
MaybeAddColor(trie.name, color),
ReadableSize(trie.size)))
elif len(trie.dictionary.keys()) == 1:
# There is only one child in this dictionary, so we will just delegate
# to the downstream trie to print stuff.
PrintTrie(
trie.dictionary.values()[0], prefix, max_depth, min_size, color)
elif trie.size > min_size:
print('{0}{1} {2}'.format(
prefix,
MaybeAddColor(trie.name, color),
ReadableSize(trie.size)))
keys_with_sizes = [
(k, trie.dictionary[k].size) for k in trie.dictionary.keys()]
keys_with_sizes.sort(key=lambda x: x[1])
for k, _ in keys_with_sizes[::-1]:
PrintTrie(
trie.dictionary[k], prefix + ' |', max_depth, min_size, color) | [
"def",
"PrintTrie",
"(",
"trie",
",",
"prefix",
",",
"max_depth",
",",
"min_size",
",",
"color",
")",
":",
"if",
"len",
"(",
"trie",
".",
"name",
")",
"==",
"max_depth",
"or",
"not",
"trie",
".",
"dictionary",
".",
"keys",
"(",
")",
":",
"# If we are reaching a leaf node or the maximum depth, we will print the",
"# result.",
"if",
"trie",
".",
"size",
">",
"min_size",
":",
"print",
"(",
"'{0}{1} {2}'",
".",
"format",
"(",
"prefix",
",",
"MaybeAddColor",
"(",
"trie",
".",
"name",
",",
"color",
")",
",",
"ReadableSize",
"(",
"trie",
".",
"size",
")",
")",
")",
"elif",
"len",
"(",
"trie",
".",
"dictionary",
".",
"keys",
"(",
")",
")",
"==",
"1",
":",
"# There is only one child in this dictionary, so we will just delegate",
"# to the downstream trie to print stuff.",
"PrintTrie",
"(",
"trie",
".",
"dictionary",
".",
"values",
"(",
")",
"[",
"0",
"]",
",",
"prefix",
",",
"max_depth",
",",
"min_size",
",",
"color",
")",
"elif",
"trie",
".",
"size",
">",
"min_size",
":",
"print",
"(",
"'{0}{1} {2}'",
".",
"format",
"(",
"prefix",
",",
"MaybeAddColor",
"(",
"trie",
".",
"name",
",",
"color",
")",
",",
"ReadableSize",
"(",
"trie",
".",
"size",
")",
")",
")",
"keys_with_sizes",
"=",
"[",
"(",
"k",
",",
"trie",
".",
"dictionary",
"[",
"k",
"]",
".",
"size",
")",
"for",
"k",
"in",
"trie",
".",
"dictionary",
".",
"keys",
"(",
")",
"]",
"keys_with_sizes",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
")",
"for",
"k",
",",
"_",
"in",
"keys_with_sizes",
"[",
":",
":",
"-",
"1",
"]",
":",
"PrintTrie",
"(",
"trie",
".",
"dictionary",
"[",
"k",
"]",
",",
"prefix",
"+",
"' |'",
",",
"max_depth",
",",
"min_size",
",",
"color",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/binarysize.py#L106-L132 | ||
tkn-tub/ns3-gym | 19bfe0a583e641142609939a090a09dfc63a095f | utils/grid.py | python | Colors.lookup | (self, name) | return self.__colors.get(name) | ! Lookup name
@param self this object
@param name name
@return named color | ! Lookup name | [
"!",
"Lookup",
"name"
] | def lookup(self, name):
"""! Lookup name
@param self this object
@param name name
@return named color
"""
if not self.__colors.has_key(name):
self.add(name, self.default_colors.pop())
return self.__colors.get(name) | [
"def",
"lookup",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"self",
".",
"__colors",
".",
"has_key",
"(",
"name",
")",
":",
"self",
".",
"add",
"(",
"name",
",",
"self",
".",
"default_colors",
".",
"pop",
"(",
")",
")",
"return",
"self",
".",
"__colors",
".",
"get",
"(",
"name",
")"
] | https://github.com/tkn-tub/ns3-gym/blob/19bfe0a583e641142609939a090a09dfc63a095f/utils/grid.py#L489-L497 | |
stack-of-tasks/pinocchio | 593d4d43fded997bb9aa2421f4e55294dbd233c4 | bindings/python/pinocchio/visualize/meshcat_visualizer.py | python | MeshcatVisualizer.display | (self, q = None) | Display the robot at configuration q in the viewer by placing all the bodies. | Display the robot at configuration q in the viewer by placing all the bodies. | [
"Display",
"the",
"robot",
"at",
"configuration",
"q",
"in",
"the",
"viewer",
"by",
"placing",
"all",
"the",
"bodies",
"."
] | def display(self, q = None):
"""Display the robot at configuration q in the viewer by placing all the bodies."""
if q is not None:
pin.forwardKinematics(self.model,self.data,q)
if self.display_collisions:
self.updatePlacements(pin.GeometryType.COLLISION)
if self.display_visuals:
self.updatePlacements(pin.GeometryType.VISUAL) | [
"def",
"display",
"(",
"self",
",",
"q",
"=",
"None",
")",
":",
"if",
"q",
"is",
"not",
"None",
":",
"pin",
".",
"forwardKinematics",
"(",
"self",
".",
"model",
",",
"self",
".",
"data",
",",
"q",
")",
"if",
"self",
".",
"display_collisions",
":",
"self",
".",
"updatePlacements",
"(",
"pin",
".",
"GeometryType",
".",
"COLLISION",
")",
"if",
"self",
".",
"display_visuals",
":",
"self",
".",
"updatePlacements",
"(",
"pin",
".",
"GeometryType",
".",
"VISUAL",
")"
] | https://github.com/stack-of-tasks/pinocchio/blob/593d4d43fded997bb9aa2421f4e55294dbd233c4/bindings/python/pinocchio/visualize/meshcat_visualizer.py#L280-L289 | ||
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/jax/nfsp.py | python | NFSP.step | (self, time_step, is_evaluation=False) | return agent_output | Returns the action to be taken and updates the Q-networks if needed.
Args:
time_step: an instance of rl_environment.TimeStep.
is_evaluation: bool, whether this is a training or evaluation call.
Returns:
A `rl_agent.StepOutput` containing the action probs and chosen action. | Returns the action to be taken and updates the Q-networks if needed. | [
"Returns",
"the",
"action",
"to",
"be",
"taken",
"and",
"updates",
"the",
"Q",
"-",
"networks",
"if",
"needed",
"."
] | def step(self, time_step, is_evaluation=False):
"""Returns the action to be taken and updates the Q-networks if needed.
Args:
time_step: an instance of rl_environment.TimeStep.
is_evaluation: bool, whether this is a training or evaluation call.
Returns:
A `rl_agent.StepOutput` containing the action probs and chosen action.
"""
if self._mode == MODE.best_response:
agent_output = self._rl_agent.step(time_step, is_evaluation)
if not is_evaluation and not time_step.last():
self._add_transition(time_step, agent_output)
elif self._mode == MODE.average_policy:
# Act step: don't act at terminal info states.
if not time_step.last():
info_state = time_step.observations["info_state"][self.player_id]
legal_actions = time_step.observations["legal_actions"][self.player_id]
action, probs = self._act(info_state, legal_actions)
agent_output = rl_agent.StepOutput(action=action, probs=probs)
if self._prev_timestep and not is_evaluation:
self._rl_agent.add_transition(self._prev_timestep, self._prev_action,
time_step)
else:
raise ValueError("Invalid mode ({})".format(self._mode))
if not is_evaluation:
self._step_counter += 1
if self._step_counter % self._learn_every == 0:
self._last_sl_loss_value = self._learn()
# If learn step not triggered by rl policy, learn.
if self._mode == MODE.average_policy:
self._rl_agent.learn()
# Prepare for the next episode.
if time_step.last():
self._sample_episode_policy()
self._prev_timestep = None
self._prev_action = None
return
else:
self._prev_timestep = time_step
self._prev_action = agent_output.action
return agent_output | [
"def",
"step",
"(",
"self",
",",
"time_step",
",",
"is_evaluation",
"=",
"False",
")",
":",
"if",
"self",
".",
"_mode",
"==",
"MODE",
".",
"best_response",
":",
"agent_output",
"=",
"self",
".",
"_rl_agent",
".",
"step",
"(",
"time_step",
",",
"is_evaluation",
")",
"if",
"not",
"is_evaluation",
"and",
"not",
"time_step",
".",
"last",
"(",
")",
":",
"self",
".",
"_add_transition",
"(",
"time_step",
",",
"agent_output",
")",
"elif",
"self",
".",
"_mode",
"==",
"MODE",
".",
"average_policy",
":",
"# Act step: don't act at terminal info states.",
"if",
"not",
"time_step",
".",
"last",
"(",
")",
":",
"info_state",
"=",
"time_step",
".",
"observations",
"[",
"\"info_state\"",
"]",
"[",
"self",
".",
"player_id",
"]",
"legal_actions",
"=",
"time_step",
".",
"observations",
"[",
"\"legal_actions\"",
"]",
"[",
"self",
".",
"player_id",
"]",
"action",
",",
"probs",
"=",
"self",
".",
"_act",
"(",
"info_state",
",",
"legal_actions",
")",
"agent_output",
"=",
"rl_agent",
".",
"StepOutput",
"(",
"action",
"=",
"action",
",",
"probs",
"=",
"probs",
")",
"if",
"self",
".",
"_prev_timestep",
"and",
"not",
"is_evaluation",
":",
"self",
".",
"_rl_agent",
".",
"add_transition",
"(",
"self",
".",
"_prev_timestep",
",",
"self",
".",
"_prev_action",
",",
"time_step",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid mode ({})\"",
".",
"format",
"(",
"self",
".",
"_mode",
")",
")",
"if",
"not",
"is_evaluation",
":",
"self",
".",
"_step_counter",
"+=",
"1",
"if",
"self",
".",
"_step_counter",
"%",
"self",
".",
"_learn_every",
"==",
"0",
":",
"self",
".",
"_last_sl_loss_value",
"=",
"self",
".",
"_learn",
"(",
")",
"# If learn step not triggered by rl policy, learn.",
"if",
"self",
".",
"_mode",
"==",
"MODE",
".",
"average_policy",
":",
"self",
".",
"_rl_agent",
".",
"learn",
"(",
")",
"# Prepare for the next episode.",
"if",
"time_step",
".",
"last",
"(",
")",
":",
"self",
".",
"_sample_episode_policy",
"(",
")",
"self",
".",
"_prev_timestep",
"=",
"None",
"self",
".",
"_prev_action",
"=",
"None",
"return",
"else",
":",
"self",
".",
"_prev_timestep",
"=",
"time_step",
"self",
".",
"_prev_action",
"=",
"agent_output",
".",
"action",
"return",
"agent_output"
] | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/jax/nfsp.py#L191-L238 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_windows.py | python | Dialog.IsModal | (*args, **kwargs) | return _windows_.Dialog_IsModal(*args, **kwargs) | IsModal(self) -> bool | IsModal(self) -> bool | [
"IsModal",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsModal(*args, **kwargs):
"""IsModal(self) -> bool"""
return _windows_.Dialog_IsModal(*args, **kwargs) | [
"def",
"IsModal",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"Dialog_IsModal",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L799-L801 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | Window.GetChildren | (*args, **kwargs) | return _core_.Window_GetChildren(*args, **kwargs) | GetChildren(self) -> WindowList
Returns an object containing a list of the window's children. The
object provides a Python sequence-like interface over the internal
list maintained by the window.. | GetChildren(self) -> WindowList | [
"GetChildren",
"(",
"self",
")",
"-",
">",
"WindowList"
] | def GetChildren(*args, **kwargs):
"""
GetChildren(self) -> WindowList
Returns an object containing a list of the window's children. The
object provides a Python sequence-like interface over the internal
list maintained by the window..
"""
return _core_.Window_GetChildren(*args, **kwargs) | [
"def",
"GetChildren",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_GetChildren",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L10247-L10255 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/android/list_java_targets.py | python | _TargetEntry.proguard_enabled | (self) | return self.build_config()['deps_info'].get('proguard_enabled', False) | Returns whether proguard runs for this target. | Returns whether proguard runs for this target. | [
"Returns",
"whether",
"proguard",
"runs",
"for",
"this",
"target",
"."
] | def proguard_enabled(self):
"""Returns whether proguard runs for this target."""
# Modules set proguard_enabled, but the proguarding happens only once at the
# bundle level.
if self.get_type() == 'android_app_bundle_module':
return False
return self.build_config()['deps_info'].get('proguard_enabled', False) | [
"def",
"proguard_enabled",
"(",
"self",
")",
":",
"# Modules set proguard_enabled, but the proguarding happens only once at the",
"# bundle level.",
"if",
"self",
".",
"get_type",
"(",
")",
"==",
"'android_app_bundle_module'",
":",
"return",
"False",
"return",
"self",
".",
"build_config",
"(",
")",
"[",
"'deps_info'",
"]",
".",
"get",
"(",
"'proguard_enabled'",
",",
"False",
")"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/list_java_targets.py#L126-L132 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/util/compat.py | python | as_bytes | (bytes_or_text) | Converts either bytes or unicode to `bytes`, using utf-8 encoding for text.
Args:
bytes_or_text: A `bytes`, `str`, or `unicode` object.
Returns:
A `bytes` object.
Raises:
TypeError: If `bytes_or_text` is not a binary or unicode string. | Converts either bytes or unicode to `bytes`, using utf-8 encoding for text. | [
"Converts",
"either",
"bytes",
"or",
"unicode",
"to",
"bytes",
"using",
"utf",
"-",
"8",
"encoding",
"for",
"text",
"."
] | def as_bytes(bytes_or_text):
"""Converts either bytes or unicode to `bytes`, using utf-8 encoding for text.
Args:
bytes_or_text: A `bytes`, `str`, or `unicode` object.
Returns:
A `bytes` object.
Raises:
TypeError: If `bytes_or_text` is not a binary or unicode string.
"""
if isinstance(bytes_or_text, six.text_type):
return bytes_or_text.encode('utf-8')
elif isinstance(bytes_or_text, bytes):
return bytes_or_text
else:
raise TypeError('Expected binary or unicode string, got %r' %
(bytes_or_text,)) | [
"def",
"as_bytes",
"(",
"bytes_or_text",
")",
":",
"if",
"isinstance",
"(",
"bytes_or_text",
",",
"six",
".",
"text_type",
")",
":",
"return",
"bytes_or_text",
".",
"encode",
"(",
"'utf-8'",
")",
"elif",
"isinstance",
"(",
"bytes_or_text",
",",
"bytes",
")",
":",
"return",
"bytes_or_text",
"else",
":",
"raise",
"TypeError",
"(",
"'Expected binary or unicode string, got %r'",
"%",
"(",
"bytes_or_text",
",",
")",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/util/compat.py#L27-L45 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/rnn.py | python | TensorFlowRNNRegressor.__init__ | (self,
rnn_size,
cell_type='gru',
num_layers=1,
input_op_fn=null_input_op_fn,
initial_state=None,
bidirectional=False,
sequence_length=None,
attn_length=None,
attn_size=None,
attn_vec_size=None,
n_classes=0,
batch_size=32,
steps=50,
optimizer='Adagrad',
learning_rate=0.1,
clip_gradients=5.0,
continue_training=False,
config=None,
verbose=1) | Initializes a TensorFlowRNNRegressor instance.
Args:
rnn_size: The size for rnn cell, e.g. size of your word embeddings.
cell_type: The type of rnn cell, including rnn, gru, and lstm.
num_layers: The number of layers of the rnn model.
input_op_fn: Function that will transform the input tensor, such as
creating word embeddings, byte list, etc. This takes
an argument x for input and returns transformed x.
bidirectional: boolean, Whether this is a bidirectional rnn.
sequence_length: If sequence_length is provided, dynamic calculation
is performed. This saves computational time when unrolling past max
sequence length.
attn_length: integer, the size of attention vector attached to rnn cells.
attn_size: integer, the size of an attention window attached to rnn cells.
attn_vec_size: integer, the number of convolutional features calculated on
attention state and the size of the hidden layer built from base cell state.
initial_state: An initial state for the RNN. This must be a tensor of
appropriate type and shape [batch_size x cell.state_size].
batch_size: Mini batch size.
steps: Number of steps to run over data.
optimizer: Optimizer name (or class), for example "SGD", "Adam",
"Adagrad".
learning_rate: If this is constant float value, no decay function is
used. Instead, a customized decay function can be passed that accepts
global_step as parameter and returns a Tensor.
e.g. exponential decay function:
````python
def exp_decay(global_step):
return tf.train.exponential_decay(
learning_rate=0.1, global_step,
decay_steps=2, decay_rate=0.001)
````
continue_training: when continue_training is True, once initialized
model will be continuely trained on every call of fit.
config: RunConfig object that controls the configurations of the
session, e.g. num_cores, gpu_memory_fraction, etc.
verbose: Controls the verbosity, possible values:
* 0: the algorithm and debug information is muted.
* 1: trainer prints the progress.
* 2: log device placement is printed. | Initializes a TensorFlowRNNRegressor instance. | [
"Initializes",
"a",
"TensorFlowRNNRegressor",
"instance",
"."
] | def __init__(self,
rnn_size,
cell_type='gru',
num_layers=1,
input_op_fn=null_input_op_fn,
initial_state=None,
bidirectional=False,
sequence_length=None,
attn_length=None,
attn_size=None,
attn_vec_size=None,
n_classes=0,
batch_size=32,
steps=50,
optimizer='Adagrad',
learning_rate=0.1,
clip_gradients=5.0,
continue_training=False,
config=None,
verbose=1):
"""Initializes a TensorFlowRNNRegressor instance.
Args:
rnn_size: The size for rnn cell, e.g. size of your word embeddings.
cell_type: The type of rnn cell, including rnn, gru, and lstm.
num_layers: The number of layers of the rnn model.
input_op_fn: Function that will transform the input tensor, such as
creating word embeddings, byte list, etc. This takes
an argument x for input and returns transformed x.
bidirectional: boolean, Whether this is a bidirectional rnn.
sequence_length: If sequence_length is provided, dynamic calculation
is performed. This saves computational time when unrolling past max
sequence length.
attn_length: integer, the size of attention vector attached to rnn cells.
attn_size: integer, the size of an attention window attached to rnn cells.
attn_vec_size: integer, the number of convolutional features calculated on
attention state and the size of the hidden layer built from base cell state.
initial_state: An initial state for the RNN. This must be a tensor of
appropriate type and shape [batch_size x cell.state_size].
batch_size: Mini batch size.
steps: Number of steps to run over data.
optimizer: Optimizer name (or class), for example "SGD", "Adam",
"Adagrad".
learning_rate: If this is constant float value, no decay function is
used. Instead, a customized decay function can be passed that accepts
global_step as parameter and returns a Tensor.
e.g. exponential decay function:
````python
def exp_decay(global_step):
return tf.train.exponential_decay(
learning_rate=0.1, global_step,
decay_steps=2, decay_rate=0.001)
````
continue_training: when continue_training is True, once initialized
model will be continuely trained on every call of fit.
config: RunConfig object that controls the configurations of the
session, e.g. num_cores, gpu_memory_fraction, etc.
verbose: Controls the verbosity, possible values:
* 0: the algorithm and debug information is muted.
* 1: trainer prints the progress.
* 2: log device placement is printed.
"""
self.rnn_size = rnn_size
self.cell_type = cell_type
self.input_op_fn = input_op_fn
self.bidirectional = bidirectional
self.num_layers = num_layers
self.sequence_length = sequence_length
self.initial_state = initial_state
self.attn_length = attn_length
self.attn_size = attn_size
self.attn_vec_size = attn_vec_size
super(TensorFlowRNNRegressor, self).__init__(
model_fn=self._model_fn,
n_classes=n_classes,
batch_size=batch_size,
steps=steps,
optimizer=optimizer,
learning_rate=learning_rate,
clip_gradients=clip_gradients,
continue_training=continue_training,
config=config,
verbose=verbose) | [
"def",
"__init__",
"(",
"self",
",",
"rnn_size",
",",
"cell_type",
"=",
"'gru'",
",",
"num_layers",
"=",
"1",
",",
"input_op_fn",
"=",
"null_input_op_fn",
",",
"initial_state",
"=",
"None",
",",
"bidirectional",
"=",
"False",
",",
"sequence_length",
"=",
"None",
",",
"attn_length",
"=",
"None",
",",
"attn_size",
"=",
"None",
",",
"attn_vec_size",
"=",
"None",
",",
"n_classes",
"=",
"0",
",",
"batch_size",
"=",
"32",
",",
"steps",
"=",
"50",
",",
"optimizer",
"=",
"'Adagrad'",
",",
"learning_rate",
"=",
"0.1",
",",
"clip_gradients",
"=",
"5.0",
",",
"continue_training",
"=",
"False",
",",
"config",
"=",
"None",
",",
"verbose",
"=",
"1",
")",
":",
"self",
".",
"rnn_size",
"=",
"rnn_size",
"self",
".",
"cell_type",
"=",
"cell_type",
"self",
".",
"input_op_fn",
"=",
"input_op_fn",
"self",
".",
"bidirectional",
"=",
"bidirectional",
"self",
".",
"num_layers",
"=",
"num_layers",
"self",
".",
"sequence_length",
"=",
"sequence_length",
"self",
".",
"initial_state",
"=",
"initial_state",
"self",
".",
"attn_length",
"=",
"attn_length",
"self",
".",
"attn_size",
"=",
"attn_size",
"self",
".",
"attn_vec_size",
"=",
"attn_vec_size",
"super",
"(",
"TensorFlowRNNRegressor",
",",
"self",
")",
".",
"__init__",
"(",
"model_fn",
"=",
"self",
".",
"_model_fn",
",",
"n_classes",
"=",
"n_classes",
",",
"batch_size",
"=",
"batch_size",
",",
"steps",
"=",
"steps",
",",
"optimizer",
"=",
"optimizer",
",",
"learning_rate",
"=",
"learning_rate",
",",
"clip_gradients",
"=",
"clip_gradients",
",",
"continue_training",
"=",
"continue_training",
",",
"config",
"=",
"config",
",",
"verbose",
"=",
"verbose",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/rnn.py#L146-L231 | ||
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/traci/_multientryexit.py | python | MultiEntryExitDomain.getLastIntervalMeanTimeLoss | (self, detID) | return self._getUniversal(tc.VAR_TIMELOSS, detID) | getLastIntervalMeanTimeLoss(string) -> double
Returns the average time loss of vehicles that passed the detector in
the previous measurement interval | getLastIntervalMeanTimeLoss(string) -> double | [
"getLastIntervalMeanTimeLoss",
"(",
"string",
")",
"-",
">",
"double"
] | def getLastIntervalMeanTimeLoss(self, detID):
"""getLastIntervalMeanTimeLoss(string) -> double
Returns the average time loss of vehicles that passed the detector in
the previous measurement interval
"""
return self._getUniversal(tc.VAR_TIMELOSS, detID) | [
"def",
"getLastIntervalMeanTimeLoss",
"(",
"self",
",",
"detID",
")",
":",
"return",
"self",
".",
"_getUniversal",
"(",
"tc",
".",
"VAR_TIMELOSS",
",",
"detID",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_multientryexit.py#L79-L85 | |
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exodus3.in.py | python | exodus.get_times | (self) | return self.times | get the time values
>>> time_vals = exo.get_times()
Returns
-------
if array_type == 'ctype' :
<list<ctypes.c_double>> time_vals
if array_type == 'numpy' :
<np_array<double>> time_vals | get the time values | [
"get",
"the",
"time",
"values"
] | def get_times(self):
"""
get the time values
>>> time_vals = exo.get_times()
Returns
-------
if array_type == 'ctype' :
<list<ctypes.c_double>> time_vals
if array_type == 'numpy' :
<np_array<double>> time_vals
"""
if self.numTimes.value == 0:
self.times = []
else:
self.__ex_get_all_times()
if self.use_numpy:
self.times = ctype_to_numpy(self, self.times)
return self.times | [
"def",
"get_times",
"(",
"self",
")",
":",
"if",
"self",
".",
"numTimes",
".",
"value",
"==",
"0",
":",
"self",
".",
"times",
"=",
"[",
"]",
"else",
":",
"self",
".",
"__ex_get_all_times",
"(",
")",
"if",
"self",
".",
"use_numpy",
":",
"self",
".",
"times",
"=",
"ctype_to_numpy",
"(",
"self",
",",
"self",
".",
"times",
")",
"return",
"self",
".",
"times"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exodus3.in.py#L1113-L1133 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/more-itertools/py3/more_itertools/more.py | python | collapse | (iterable, base_type=None, levels=None) | Flatten an iterable with multiple levels of nesting (e.g., a list of
lists of tuples) into non-iterable types.
>>> iterable = [(1, 2), ([3, 4], [[5], [6]])]
>>> list(collapse(iterable))
[1, 2, 3, 4, 5, 6]
Binary and text strings are not considered iterable and
will not be collapsed.
To avoid collapsing other types, specify *base_type*:
>>> iterable = ['ab', ('cd', 'ef'), ['gh', 'ij']]
>>> list(collapse(iterable, base_type=tuple))
['ab', ('cd', 'ef'), 'gh', 'ij']
Specify *levels* to stop flattening after a certain level:
>>> iterable = [('a', ['b']), ('c', ['d'])]
>>> list(collapse(iterable)) # Fully flattened
['a', 'b', 'c', 'd']
>>> list(collapse(iterable, levels=1)) # Only one level flattened
['a', ['b'], 'c', ['d']] | Flatten an iterable with multiple levels of nesting (e.g., a list of
lists of tuples) into non-iterable types. | [
"Flatten",
"an",
"iterable",
"with",
"multiple",
"levels",
"of",
"nesting",
"(",
"e",
".",
"g",
".",
"a",
"list",
"of",
"lists",
"of",
"tuples",
")",
"into",
"non",
"-",
"iterable",
"types",
"."
] | def collapse(iterable, base_type=None, levels=None):
"""Flatten an iterable with multiple levels of nesting (e.g., a list of
lists of tuples) into non-iterable types.
>>> iterable = [(1, 2), ([3, 4], [[5], [6]])]
>>> list(collapse(iterable))
[1, 2, 3, 4, 5, 6]
Binary and text strings are not considered iterable and
will not be collapsed.
To avoid collapsing other types, specify *base_type*:
>>> iterable = ['ab', ('cd', 'ef'), ['gh', 'ij']]
>>> list(collapse(iterable, base_type=tuple))
['ab', ('cd', 'ef'), 'gh', 'ij']
Specify *levels* to stop flattening after a certain level:
>>> iterable = [('a', ['b']), ('c', ['d'])]
>>> list(collapse(iterable)) # Fully flattened
['a', 'b', 'c', 'd']
>>> list(collapse(iterable, levels=1)) # Only one level flattened
['a', ['b'], 'c', ['d']]
"""
def walk(node, level):
if (
((levels is not None) and (level > levels))
or isinstance(node, (str, bytes))
or ((base_type is not None) and isinstance(node, base_type))
):
yield node
return
try:
tree = iter(node)
except TypeError:
yield node
return
else:
for child in tree:
yield from walk(child, level + 1)
yield from walk(iterable, 0) | [
"def",
"collapse",
"(",
"iterable",
",",
"base_type",
"=",
"None",
",",
"levels",
"=",
"None",
")",
":",
"def",
"walk",
"(",
"node",
",",
"level",
")",
":",
"if",
"(",
"(",
"(",
"levels",
"is",
"not",
"None",
")",
"and",
"(",
"level",
">",
"levels",
")",
")",
"or",
"isinstance",
"(",
"node",
",",
"(",
"str",
",",
"bytes",
")",
")",
"or",
"(",
"(",
"base_type",
"is",
"not",
"None",
")",
"and",
"isinstance",
"(",
"node",
",",
"base_type",
")",
")",
")",
":",
"yield",
"node",
"return",
"try",
":",
"tree",
"=",
"iter",
"(",
"node",
")",
"except",
"TypeError",
":",
"yield",
"node",
"return",
"else",
":",
"for",
"child",
"in",
"tree",
":",
"yield",
"from",
"walk",
"(",
"child",
",",
"level",
"+",
"1",
")",
"yield",
"from",
"walk",
"(",
"iterable",
",",
"0",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/more-itertools/py3/more_itertools/more.py#L1178-L1223 | ||
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/ext.py | python | InternationalizationExtension.parse | (self, parser) | Parse a translatable tag. | Parse a translatable tag. | [
"Parse",
"a",
"translatable",
"tag",
"."
] | def parse(self, parser):
"""Parse a translatable tag."""
lineno = next(parser.stream).lineno
num_called_num = False
# find all the variables referenced. Additionally a variable can be
# defined in the body of the trans block too, but this is checked at
# a later state.
plural_expr = None
plural_expr_assignment = None
variables = {}
while parser.stream.current.type != 'block_end':
if variables:
parser.stream.expect('comma')
# skip colon for python compatibility
if parser.stream.skip_if('colon'):
break
name = parser.stream.expect('name')
if name.value in variables:
parser.fail('translatable variable %r defined twice.' %
name.value, name.lineno,
exc=TemplateAssertionError)
# expressions
if parser.stream.current.type == 'assign':
next(parser.stream)
variables[name.value] = var = parser.parse_expression()
else:
variables[name.value] = var = nodes.Name(name.value, 'load')
if plural_expr is None:
if isinstance(var, nodes.Call):
plural_expr = nodes.Name('_trans', 'load')
variables[name.value] = plural_expr
plural_expr_assignment = nodes.Assign(
nodes.Name('_trans', 'store'), var)
else:
plural_expr = var
num_called_num = name.value == 'num'
parser.stream.expect('block_end')
plural = plural_names = None
have_plural = False
referenced = set()
# now parse until endtrans or pluralize
singular_names, singular = self._parse_block(parser, True)
if singular_names:
referenced.update(singular_names)
if plural_expr is None:
plural_expr = nodes.Name(singular_names[0], 'load')
num_called_num = singular_names[0] == 'num'
# if we have a pluralize block, we parse that too
if parser.stream.current.test('name:pluralize'):
have_plural = True
next(parser.stream)
if parser.stream.current.type != 'block_end':
name = parser.stream.expect('name')
if name.value not in variables:
parser.fail('unknown variable %r for pluralization' %
name.value, name.lineno,
exc=TemplateAssertionError)
plural_expr = variables[name.value]
num_called_num = name.value == 'num'
parser.stream.expect('block_end')
plural_names, plural = self._parse_block(parser, False)
next(parser.stream)
referenced.update(plural_names)
else:
next(parser.stream)
# register free names as simple name expressions
for var in referenced:
if var not in variables:
variables[var] = nodes.Name(var, 'load')
if not have_plural:
plural_expr = None
elif plural_expr is None:
parser.fail('pluralize without variables', lineno)
node = self._make_node(singular, plural, variables, plural_expr,
bool(referenced),
num_called_num and have_plural)
node.set_lineno(lineno)
if plural_expr_assignment is not None:
return [plural_expr_assignment, node]
else:
return node | [
"def",
"parse",
"(",
"self",
",",
"parser",
")",
":",
"lineno",
"=",
"next",
"(",
"parser",
".",
"stream",
")",
".",
"lineno",
"num_called_num",
"=",
"False",
"# find all the variables referenced. Additionally a variable can be",
"# defined in the body of the trans block too, but this is checked at",
"# a later state.",
"plural_expr",
"=",
"None",
"plural_expr_assignment",
"=",
"None",
"variables",
"=",
"{",
"}",
"while",
"parser",
".",
"stream",
".",
"current",
".",
"type",
"!=",
"'block_end'",
":",
"if",
"variables",
":",
"parser",
".",
"stream",
".",
"expect",
"(",
"'comma'",
")",
"# skip colon for python compatibility",
"if",
"parser",
".",
"stream",
".",
"skip_if",
"(",
"'colon'",
")",
":",
"break",
"name",
"=",
"parser",
".",
"stream",
".",
"expect",
"(",
"'name'",
")",
"if",
"name",
".",
"value",
"in",
"variables",
":",
"parser",
".",
"fail",
"(",
"'translatable variable %r defined twice.'",
"%",
"name",
".",
"value",
",",
"name",
".",
"lineno",
",",
"exc",
"=",
"TemplateAssertionError",
")",
"# expressions",
"if",
"parser",
".",
"stream",
".",
"current",
".",
"type",
"==",
"'assign'",
":",
"next",
"(",
"parser",
".",
"stream",
")",
"variables",
"[",
"name",
".",
"value",
"]",
"=",
"var",
"=",
"parser",
".",
"parse_expression",
"(",
")",
"else",
":",
"variables",
"[",
"name",
".",
"value",
"]",
"=",
"var",
"=",
"nodes",
".",
"Name",
"(",
"name",
".",
"value",
",",
"'load'",
")",
"if",
"plural_expr",
"is",
"None",
":",
"if",
"isinstance",
"(",
"var",
",",
"nodes",
".",
"Call",
")",
":",
"plural_expr",
"=",
"nodes",
".",
"Name",
"(",
"'_trans'",
",",
"'load'",
")",
"variables",
"[",
"name",
".",
"value",
"]",
"=",
"plural_expr",
"plural_expr_assignment",
"=",
"nodes",
".",
"Assign",
"(",
"nodes",
".",
"Name",
"(",
"'_trans'",
",",
"'store'",
")",
",",
"var",
")",
"else",
":",
"plural_expr",
"=",
"var",
"num_called_num",
"=",
"name",
".",
"value",
"==",
"'num'",
"parser",
".",
"stream",
".",
"expect",
"(",
"'block_end'",
")",
"plural",
"=",
"plural_names",
"=",
"None",
"have_plural",
"=",
"False",
"referenced",
"=",
"set",
"(",
")",
"# now parse until endtrans or pluralize",
"singular_names",
",",
"singular",
"=",
"self",
".",
"_parse_block",
"(",
"parser",
",",
"True",
")",
"if",
"singular_names",
":",
"referenced",
".",
"update",
"(",
"singular_names",
")",
"if",
"plural_expr",
"is",
"None",
":",
"plural_expr",
"=",
"nodes",
".",
"Name",
"(",
"singular_names",
"[",
"0",
"]",
",",
"'load'",
")",
"num_called_num",
"=",
"singular_names",
"[",
"0",
"]",
"==",
"'num'",
"# if we have a pluralize block, we parse that too",
"if",
"parser",
".",
"stream",
".",
"current",
".",
"test",
"(",
"'name:pluralize'",
")",
":",
"have_plural",
"=",
"True",
"next",
"(",
"parser",
".",
"stream",
")",
"if",
"parser",
".",
"stream",
".",
"current",
".",
"type",
"!=",
"'block_end'",
":",
"name",
"=",
"parser",
".",
"stream",
".",
"expect",
"(",
"'name'",
")",
"if",
"name",
".",
"value",
"not",
"in",
"variables",
":",
"parser",
".",
"fail",
"(",
"'unknown variable %r for pluralization'",
"%",
"name",
".",
"value",
",",
"name",
".",
"lineno",
",",
"exc",
"=",
"TemplateAssertionError",
")",
"plural_expr",
"=",
"variables",
"[",
"name",
".",
"value",
"]",
"num_called_num",
"=",
"name",
".",
"value",
"==",
"'num'",
"parser",
".",
"stream",
".",
"expect",
"(",
"'block_end'",
")",
"plural_names",
",",
"plural",
"=",
"self",
".",
"_parse_block",
"(",
"parser",
",",
"False",
")",
"next",
"(",
"parser",
".",
"stream",
")",
"referenced",
".",
"update",
"(",
"plural_names",
")",
"else",
":",
"next",
"(",
"parser",
".",
"stream",
")",
"# register free names as simple name expressions",
"for",
"var",
"in",
"referenced",
":",
"if",
"var",
"not",
"in",
"variables",
":",
"variables",
"[",
"var",
"]",
"=",
"nodes",
".",
"Name",
"(",
"var",
",",
"'load'",
")",
"if",
"not",
"have_plural",
":",
"plural_expr",
"=",
"None",
"elif",
"plural_expr",
"is",
"None",
":",
"parser",
".",
"fail",
"(",
"'pluralize without variables'",
",",
"lineno",
")",
"node",
"=",
"self",
".",
"_make_node",
"(",
"singular",
",",
"plural",
",",
"variables",
",",
"plural_expr",
",",
"bool",
"(",
"referenced",
")",
",",
"num_called_num",
"and",
"have_plural",
")",
"node",
".",
"set_lineno",
"(",
"lineno",
")",
"if",
"plural_expr_assignment",
"is",
"not",
"None",
":",
"return",
"[",
"plural_expr_assignment",
",",
"node",
"]",
"else",
":",
"return",
"node"
] | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/ext.py#L215-L307 | ||
potassco/clingo | e0c91d8f95cc28de1c480a871f9c97c30de83d40 | libpyclingo/clingo/control.py | python | Control.backend | (self) | return Backend(_c_call('clingo_backend_t*', _lib.clingo_control_backend, self._rep), self._error) | Returns a `Backend` object providing a low level interface to extend a
logic program.
See Also
--------
clingo.backend | Returns a `Backend` object providing a low level interface to extend a
logic program. | [
"Returns",
"a",
"Backend",
"object",
"providing",
"a",
"low",
"level",
"interface",
"to",
"extend",
"a",
"logic",
"program",
"."
] | def backend(self) -> Backend:
'''
Returns a `Backend` object providing a low level interface to extend a
logic program.
See Also
--------
clingo.backend
'''
return Backend(_c_call('clingo_backend_t*', _lib.clingo_control_backend, self._rep), self._error) | [
"def",
"backend",
"(",
"self",
")",
"->",
"Backend",
":",
"return",
"Backend",
"(",
"_c_call",
"(",
"'clingo_backend_t*'",
",",
"_lib",
".",
"clingo_control_backend",
",",
"self",
".",
"_rep",
")",
",",
"self",
".",
"_error",
")"
] | https://github.com/potassco/clingo/blob/e0c91d8f95cc28de1c480a871f9c97c30de83d40/libpyclingo/clingo/control.py#L242-L251 | |
choasup/caffe-yolo9000 | e8a476c4c23d756632f7a26c681a96e3ab672544 | scripts/cpp_lint.py | python | _BlockInfo.CheckBegin | (self, filename, clean_lines, linenum, error) | Run checks that applies to text up to the opening brace.
This is mostly for checking the text after the class identifier
and the "{", usually where the base class is specified. For other
blocks, there isn't much to check, so we always pass.
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. | Run checks that applies to text up to the opening brace. | [
"Run",
"checks",
"that",
"applies",
"to",
"text",
"up",
"to",
"the",
"opening",
"brace",
"."
] | def CheckBegin(self, filename, clean_lines, linenum, error):
"""Run checks that applies to text up to the opening brace.
This is mostly for checking the text after the class identifier
and the "{", usually where the base class is specified. For other
blocks, there isn't much to check, so we always pass.
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.
"""
pass | [
"def",
"CheckBegin",
"(",
"self",
",",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"pass"
] | https://github.com/choasup/caffe-yolo9000/blob/e8a476c4c23d756632f7a26c681a96e3ab672544/scripts/cpp_lint.py#L1767-L1780 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/shape_base.py | python | vstack | (tup) | return _nx.concatenate(arrs, 0) | Stack arrays in sequence vertically (row wise).
This is equivalent to concatenation along the first axis after 1-D arrays
of shape `(N,)` have been reshaped to `(1,N)`. Rebuilds arrays divided by
`vsplit`.
This function makes most sense for arrays with up to 3 dimensions. For
instance, for pixel-data with a height (first axis), width (second axis),
and r/g/b channels (third axis). The functions `concatenate`, `stack` and
`block` provide more general stacking and concatenation operations.
Parameters
----------
tup : sequence of ndarrays
The arrays must have the same shape along all but the first axis.
1-D arrays must have the same length.
Returns
-------
stacked : ndarray
The array formed by stacking the given arrays, will be at least 2-D.
See Also
--------
stack : Join a sequence of arrays along a new axis.
hstack : Stack arrays in sequence horizontally (column wise).
dstack : Stack arrays in sequence depth wise (along third dimension).
concatenate : Join a sequence of arrays along an existing axis.
vsplit : Split array into a list of multiple sub-arrays vertically.
block : Assemble arrays from blocks.
Examples
--------
>>> a = np.array([1, 2, 3])
>>> b = np.array([2, 3, 4])
>>> np.vstack((a,b))
array([[1, 2, 3],
[2, 3, 4]])
>>> a = np.array([[1], [2], [3]])
>>> b = np.array([[2], [3], [4]])
>>> np.vstack((a,b))
array([[1],
[2],
[3],
[2],
[3],
[4]]) | Stack arrays in sequence vertically (row wise). | [
"Stack",
"arrays",
"in",
"sequence",
"vertically",
"(",
"row",
"wise",
")",
"."
] | def vstack(tup):
"""
Stack arrays in sequence vertically (row wise).
This is equivalent to concatenation along the first axis after 1-D arrays
of shape `(N,)` have been reshaped to `(1,N)`. Rebuilds arrays divided by
`vsplit`.
This function makes most sense for arrays with up to 3 dimensions. For
instance, for pixel-data with a height (first axis), width (second axis),
and r/g/b channels (third axis). The functions `concatenate`, `stack` and
`block` provide more general stacking and concatenation operations.
Parameters
----------
tup : sequence of ndarrays
The arrays must have the same shape along all but the first axis.
1-D arrays must have the same length.
Returns
-------
stacked : ndarray
The array formed by stacking the given arrays, will be at least 2-D.
See Also
--------
stack : Join a sequence of arrays along a new axis.
hstack : Stack arrays in sequence horizontally (column wise).
dstack : Stack arrays in sequence depth wise (along third dimension).
concatenate : Join a sequence of arrays along an existing axis.
vsplit : Split array into a list of multiple sub-arrays vertically.
block : Assemble arrays from blocks.
Examples
--------
>>> a = np.array([1, 2, 3])
>>> b = np.array([2, 3, 4])
>>> np.vstack((a,b))
array([[1, 2, 3],
[2, 3, 4]])
>>> a = np.array([[1], [2], [3]])
>>> b = np.array([[2], [3], [4]])
>>> np.vstack((a,b))
array([[1],
[2],
[3],
[2],
[3],
[4]])
"""
if not overrides.ARRAY_FUNCTION_ENABLED:
# raise warning if necessary
_arrays_for_stack_dispatcher(tup, stacklevel=2)
arrs = atleast_2d(*tup)
if not isinstance(arrs, list):
arrs = [arrs]
return _nx.concatenate(arrs, 0) | [
"def",
"vstack",
"(",
"tup",
")",
":",
"if",
"not",
"overrides",
".",
"ARRAY_FUNCTION_ENABLED",
":",
"# raise warning if necessary",
"_arrays_for_stack_dispatcher",
"(",
"tup",
",",
"stacklevel",
"=",
"2",
")",
"arrs",
"=",
"atleast_2d",
"(",
"*",
"tup",
")",
"if",
"not",
"isinstance",
"(",
"arrs",
",",
"list",
")",
":",
"arrs",
"=",
"[",
"arrs",
"]",
"return",
"_nx",
".",
"concatenate",
"(",
"arrs",
",",
"0",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/shape_base.py#L225-L283 | |
tangzhenyu/Scene-Text-Understanding | 0f7ffc7aea5971a50cdc03d33d0a41075285948b | SynthText_Chinese/text_utils.py | python | FontState.sample | (self) | return {
'font': self.fonts[int(np.random.randint(0, len(self.fonts)))],
'size': self.size[1]*np.random.randn() + self.size[0],
'underline': np.random.rand() < self.underline,
'underline_adjustment': max(2.0, min(-2.0, self.underline_adjustment[1]*np.random.randn() + self.underline_adjustment[0])),
'strong': np.random.rand() < self.strong,
'oblique': np.random.rand() < self.oblique,
'strength': (self.strength[1] - self.strength[0])*np.random.rand() + self.strength[0],
'char_spacing': int(self.kerning[3]*(np.random.beta(self.kerning[0], self.kerning[1])) + self.kerning[2]),
'border': np.random.rand() < self.border,
'random_caps': np.random.rand() < self.random_caps,
'capsmode': random.choice(self.capsmode),
'curved': np.random.rand() < self.curved,
'random_kerning': np.random.rand() < self.random_kerning,
'random_kerning_amount': self.random_kerning_amount,
} | Samples from the font state distribution | Samples from the font state distribution | [
"Samples",
"from",
"the",
"font",
"state",
"distribution"
] | def sample(self):
"""
Samples from the font state distribution
"""
return {
'font': self.fonts[int(np.random.randint(0, len(self.fonts)))],
'size': self.size[1]*np.random.randn() + self.size[0],
'underline': np.random.rand() < self.underline,
'underline_adjustment': max(2.0, min(-2.0, self.underline_adjustment[1]*np.random.randn() + self.underline_adjustment[0])),
'strong': np.random.rand() < self.strong,
'oblique': np.random.rand() < self.oblique,
'strength': (self.strength[1] - self.strength[0])*np.random.rand() + self.strength[0],
'char_spacing': int(self.kerning[3]*(np.random.beta(self.kerning[0], self.kerning[1])) + self.kerning[2]),
'border': np.random.rand() < self.border,
'random_caps': np.random.rand() < self.random_caps,
'capsmode': random.choice(self.capsmode),
'curved': np.random.rand() < self.curved,
'random_kerning': np.random.rand() < self.random_kerning,
'random_kerning_amount': self.random_kerning_amount,
} | [
"def",
"sample",
"(",
"self",
")",
":",
"return",
"{",
"'font'",
":",
"self",
".",
"fonts",
"[",
"int",
"(",
"np",
".",
"random",
".",
"randint",
"(",
"0",
",",
"len",
"(",
"self",
".",
"fonts",
")",
")",
")",
"]",
",",
"'size'",
":",
"self",
".",
"size",
"[",
"1",
"]",
"*",
"np",
".",
"random",
".",
"randn",
"(",
")",
"+",
"self",
".",
"size",
"[",
"0",
"]",
",",
"'underline'",
":",
"np",
".",
"random",
".",
"rand",
"(",
")",
"<",
"self",
".",
"underline",
",",
"'underline_adjustment'",
":",
"max",
"(",
"2.0",
",",
"min",
"(",
"-",
"2.0",
",",
"self",
".",
"underline_adjustment",
"[",
"1",
"]",
"*",
"np",
".",
"random",
".",
"randn",
"(",
")",
"+",
"self",
".",
"underline_adjustment",
"[",
"0",
"]",
")",
")",
",",
"'strong'",
":",
"np",
".",
"random",
".",
"rand",
"(",
")",
"<",
"self",
".",
"strong",
",",
"'oblique'",
":",
"np",
".",
"random",
".",
"rand",
"(",
")",
"<",
"self",
".",
"oblique",
",",
"'strength'",
":",
"(",
"self",
".",
"strength",
"[",
"1",
"]",
"-",
"self",
".",
"strength",
"[",
"0",
"]",
")",
"*",
"np",
".",
"random",
".",
"rand",
"(",
")",
"+",
"self",
".",
"strength",
"[",
"0",
"]",
",",
"'char_spacing'",
":",
"int",
"(",
"self",
".",
"kerning",
"[",
"3",
"]",
"*",
"(",
"np",
".",
"random",
".",
"beta",
"(",
"self",
".",
"kerning",
"[",
"0",
"]",
",",
"self",
".",
"kerning",
"[",
"1",
"]",
")",
")",
"+",
"self",
".",
"kerning",
"[",
"2",
"]",
")",
",",
"'border'",
":",
"np",
".",
"random",
".",
"rand",
"(",
")",
"<",
"self",
".",
"border",
",",
"'random_caps'",
":",
"np",
".",
"random",
".",
"rand",
"(",
")",
"<",
"self",
".",
"random_caps",
",",
"'capsmode'",
":",
"random",
".",
"choice",
"(",
"self",
".",
"capsmode",
")",
",",
"'curved'",
":",
"np",
".",
"random",
".",
"rand",
"(",
")",
"<",
"self",
".",
"curved",
",",
"'random_kerning'",
":",
"np",
".",
"random",
".",
"rand",
"(",
")",
"<",
"self",
".",
"random_kerning",
",",
"'random_kerning_amount'",
":",
"self",
".",
"random_kerning_amount",
",",
"}"
] | https://github.com/tangzhenyu/Scene-Text-Understanding/blob/0f7ffc7aea5971a50cdc03d33d0a41075285948b/SynthText_Chinese/text_utils.py#L480-L499 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | DateSpan_Months | (*args, **kwargs) | return _misc_.DateSpan_Months(*args, **kwargs) | DateSpan_Months(int mon) -> DateSpan | DateSpan_Months(int mon) -> DateSpan | [
"DateSpan_Months",
"(",
"int",
"mon",
")",
"-",
">",
"DateSpan"
] | def DateSpan_Months(*args, **kwargs):
"""DateSpan_Months(int mon) -> DateSpan"""
return _misc_.DateSpan_Months(*args, **kwargs) | [
"def",
"DateSpan_Months",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateSpan_Months",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L4768-L4770 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/apitools/apitools/base/py/transfer.py | python | Upload.StreamMedia | (self, callback=None, finish_callback=None,
additional_headers=None) | return self.__StreamMedia(
callback=callback, finish_callback=finish_callback,
additional_headers=additional_headers, use_chunks=False) | Send this resumable upload in a single request.
Args:
callback: Progress callback function with inputs
(http_wrapper.Response, transfer.Upload)
finish_callback: Final callback function with inputs
(http_wrapper.Response, transfer.Upload)
additional_headers: Dict of headers to include with the upload
http_wrapper.Request.
Returns:
http_wrapper.Response of final response. | Send this resumable upload in a single request. | [
"Send",
"this",
"resumable",
"upload",
"in",
"a",
"single",
"request",
"."
] | def StreamMedia(self, callback=None, finish_callback=None,
additional_headers=None):
"""Send this resumable upload in a single request.
Args:
callback: Progress callback function with inputs
(http_wrapper.Response, transfer.Upload)
finish_callback: Final callback function with inputs
(http_wrapper.Response, transfer.Upload)
additional_headers: Dict of headers to include with the upload
http_wrapper.Request.
Returns:
http_wrapper.Response of final response.
"""
return self.__StreamMedia(
callback=callback, finish_callback=finish_callback,
additional_headers=additional_headers, use_chunks=False) | [
"def",
"StreamMedia",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"finish_callback",
"=",
"None",
",",
"additional_headers",
"=",
"None",
")",
":",
"return",
"self",
".",
"__StreamMedia",
"(",
"callback",
"=",
"callback",
",",
"finish_callback",
"=",
"finish_callback",
",",
"additional_headers",
"=",
"additional_headers",
",",
"use_chunks",
"=",
"False",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/apitools/apitools/base/py/transfer.py#L888-L905 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/pep8.py | python | comparison_type | (logical_line) | r"""Object type comparisons should always use isinstance().
Do not compare types directly.
Okay: if isinstance(obj, int):
E721: if type(obj) is type(1):
When checking if an object is a string, keep in mind that it might be a
unicode string too! In Python 2.3, str and unicode have a common base
class, basestring, so you can do:
Okay: if isinstance(obj, basestring):
Okay: if type(a1) is type(b1): | r"""Object type comparisons should always use isinstance(). | [
"r",
"Object",
"type",
"comparisons",
"should",
"always",
"use",
"isinstance",
"()",
"."
] | def comparison_type(logical_line):
r"""Object type comparisons should always use isinstance().
Do not compare types directly.
Okay: if isinstance(obj, int):
E721: if type(obj) is type(1):
When checking if an object is a string, keep in mind that it might be a
unicode string too! In Python 2.3, str and unicode have a common base
class, basestring, so you can do:
Okay: if isinstance(obj, basestring):
Okay: if type(a1) is type(b1):
"""
match = COMPARE_TYPE_REGEX.search(logical_line)
if match:
inst = match.group(1)
if inst and isidentifier(inst) and inst not in SINGLETONS:
return # Allow comparison for types which are not obvious
yield match.start(), "E721 do not compare types, use 'isinstance()'" | [
"def",
"comparison_type",
"(",
"logical_line",
")",
":",
"match",
"=",
"COMPARE_TYPE_REGEX",
".",
"search",
"(",
"logical_line",
")",
"if",
"match",
":",
"inst",
"=",
"match",
".",
"group",
"(",
"1",
")",
"if",
"inst",
"and",
"isidentifier",
"(",
"inst",
")",
"and",
"inst",
"not",
"in",
"SINGLETONS",
":",
"return",
"# Allow comparison for types which are not obvious",
"yield",
"match",
".",
"start",
"(",
")",
",",
"\"E721 do not compare types, use 'isinstance()'\""
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/pep8.py#L960-L980 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/calltip_w.py | python | CalltipWindow.position_window | (self) | Reposition the window if needed. | Reposition the window if needed. | [
"Reposition",
"the",
"window",
"if",
"needed",
"."
] | def position_window(self):
"Reposition the window if needed."
curline = int(self.anchor_widget.index("insert").split('.')[0])
if curline == self.lastline:
return
self.lastline = curline
self.anchor_widget.see("insert")
super(CalltipWindow, self).position_window() | [
"def",
"position_window",
"(",
"self",
")",
":",
"curline",
"=",
"int",
"(",
"self",
".",
"anchor_widget",
".",
"index",
"(",
"\"insert\"",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
"if",
"curline",
"==",
"self",
".",
"lastline",
":",
"return",
"self",
".",
"lastline",
"=",
"curline",
"self",
".",
"anchor_widget",
".",
"see",
"(",
"\"insert\"",
")",
"super",
"(",
"CalltipWindow",
",",
"self",
")",
".",
"position_window",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/calltip_w.py#L50-L57 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | Window.LineDown | (*args, **kwargs) | return _core_.Window_LineDown(*args, **kwargs) | LineDown(self) -> bool
This is just a wrapper for ScrollLines(1). | LineDown(self) -> bool | [
"LineDown",
"(",
"self",
")",
"-",
">",
"bool"
] | def LineDown(*args, **kwargs):
"""
LineDown(self) -> bool
This is just a wrapper for ScrollLines(1).
"""
return _core_.Window_LineDown(*args, **kwargs) | [
"def",
"LineDown",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_LineDown",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L11301-L11307 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/layers/utils.py | python | conv_input_length | (output_length, filter_size, padding, stride) | return (output_length - 1) * stride - 2 * pad + filter_size | Determines input length of a convolution given output length.
Args:
output_length: integer.
filter_size: integer.
padding: one of "same", "valid", "full".
stride: integer.
Returns:
The input length (integer). | Determines input length of a convolution given output length. | [
"Determines",
"input",
"length",
"of",
"a",
"convolution",
"given",
"output",
"length",
"."
] | def conv_input_length(output_length, filter_size, padding, stride):
"""Determines input length of a convolution given output length.
Args:
output_length: integer.
filter_size: integer.
padding: one of "same", "valid", "full".
stride: integer.
Returns:
The input length (integer).
"""
if output_length is None:
return None
assert padding in {'same', 'valid', 'full'}
if padding == 'same':
pad = filter_size // 2
elif padding == 'valid':
pad = 0
elif padding == 'full':
pad = filter_size - 1
return (output_length - 1) * stride - 2 * pad + filter_size | [
"def",
"conv_input_length",
"(",
"output_length",
",",
"filter_size",
",",
"padding",
",",
"stride",
")",
":",
"if",
"output_length",
"is",
"None",
":",
"return",
"None",
"assert",
"padding",
"in",
"{",
"'same'",
",",
"'valid'",
",",
"'full'",
"}",
"if",
"padding",
"==",
"'same'",
":",
"pad",
"=",
"filter_size",
"//",
"2",
"elif",
"padding",
"==",
"'valid'",
":",
"pad",
"=",
"0",
"elif",
"padding",
"==",
"'full'",
":",
"pad",
"=",
"filter_size",
"-",
"1",
"return",
"(",
"output_length",
"-",
"1",
")",
"*",
"stride",
"-",
"2",
"*",
"pad",
"+",
"filter_size"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/layers/utils.py#L130-L151 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/keras/_impl/keras/backend.py | python | softplus | (x) | return nn.softplus(x) | Softplus of a tensor.
Arguments:
x: A tensor or variable.
Returns:
A tensor. | Softplus of a tensor. | [
"Softplus",
"of",
"a",
"tensor",
"."
] | def softplus(x):
"""Softplus of a tensor.
Arguments:
x: A tensor or variable.
Returns:
A tensor.
"""
return nn.softplus(x) | [
"def",
"softplus",
"(",
"x",
")",
":",
"return",
"nn",
".",
"softplus",
"(",
"x",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/backend.py#L2922-L2931 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/events.py | python | AbstractEventLoop.sendfile | (self, transport, file, offset=0, count=None,
*, fallback=True) | Send a file through a transport.
Return an amount of sent bytes. | Send a file through a transport. | [
"Send",
"a",
"file",
"through",
"a",
"transport",
"."
] | async def sendfile(self, transport, file, offset=0, count=None,
*, fallback=True):
"""Send a file through a transport.
Return an amount of sent bytes.
"""
raise NotImplementedError | [
"async",
"def",
"sendfile",
"(",
"self",
",",
"transport",
",",
"file",
",",
"offset",
"=",
"0",
",",
"count",
"=",
"None",
",",
"*",
",",
"fallback",
"=",
"True",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/events.py#L364-L370 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/elasticache/layer1.py | python | ElastiCacheConnection.create_replication_group | (self, replication_group_id,
primary_cluster_id,
replication_group_description) | return self._make_request(
action='CreateReplicationGroup',
verb='POST',
path='/', params=params) | The CreateReplicationGroup operation creates a replication
group. A replication group is a collection of cache clusters,
where one of the clusters is a read/write primary and the
other clusters are read-only replicas. Writes to the primary
are automatically propagated to the replicas.
When you create a replication group, you must specify an
existing cache cluster that is in the primary role. When the
replication group has been successfully created, you can add
one or more read replica replicas to it, up to a total of five
read replicas.
:type replication_group_id: string
:param replication_group_id:
The replication group identifier. This parameter is stored as a
lowercase string.
Constraints:
+ Must contain from 1 to 20 alphanumeric characters or hyphens.
+ First character must be a letter.
+ Cannot end with a hyphen or contain two consecutive hyphens.
:type primary_cluster_id: string
:param primary_cluster_id: The identifier of the cache cluster that
will serve as the primary for this replication group. This cache
cluster must already exist and have a status of available .
:type replication_group_description: string
:param replication_group_description: A user-specified description for
the replication group. | The CreateReplicationGroup operation creates a replication
group. A replication group is a collection of cache clusters,
where one of the clusters is a read/write primary and the
other clusters are read-only replicas. Writes to the primary
are automatically propagated to the replicas. | [
"The",
"CreateReplicationGroup",
"operation",
"creates",
"a",
"replication",
"group",
".",
"A",
"replication",
"group",
"is",
"a",
"collection",
"of",
"cache",
"clusters",
"where",
"one",
"of",
"the",
"clusters",
"is",
"a",
"read",
"/",
"write",
"primary",
"and",
"the",
"other",
"clusters",
"are",
"read",
"-",
"only",
"replicas",
".",
"Writes",
"to",
"the",
"primary",
"are",
"automatically",
"propagated",
"to",
"the",
"replicas",
"."
] | def create_replication_group(self, replication_group_id,
primary_cluster_id,
replication_group_description):
"""
The CreateReplicationGroup operation creates a replication
group. A replication group is a collection of cache clusters,
where one of the clusters is a read/write primary and the
other clusters are read-only replicas. Writes to the primary
are automatically propagated to the replicas.
When you create a replication group, you must specify an
existing cache cluster that is in the primary role. When the
replication group has been successfully created, you can add
one or more read replica replicas to it, up to a total of five
read replicas.
:type replication_group_id: string
:param replication_group_id:
The replication group identifier. This parameter is stored as a
lowercase string.
Constraints:
+ Must contain from 1 to 20 alphanumeric characters or hyphens.
+ First character must be a letter.
+ Cannot end with a hyphen or contain two consecutive hyphens.
:type primary_cluster_id: string
:param primary_cluster_id: The identifier of the cache cluster that
will serve as the primary for this replication group. This cache
cluster must already exist and have a status of available .
:type replication_group_description: string
:param replication_group_description: A user-specified description for
the replication group.
"""
params = {
'ReplicationGroupId': replication_group_id,
'PrimaryClusterId': primary_cluster_id,
'ReplicationGroupDescription': replication_group_description,
}
return self._make_request(
action='CreateReplicationGroup',
verb='POST',
path='/', params=params) | [
"def",
"create_replication_group",
"(",
"self",
",",
"replication_group_id",
",",
"primary_cluster_id",
",",
"replication_group_description",
")",
":",
"params",
"=",
"{",
"'ReplicationGroupId'",
":",
"replication_group_id",
",",
"'PrimaryClusterId'",
":",
"primary_cluster_id",
",",
"'ReplicationGroupDescription'",
":",
"replication_group_description",
",",
"}",
"return",
"self",
".",
"_make_request",
"(",
"action",
"=",
"'CreateReplicationGroup'",
",",
"verb",
"=",
"'POST'",
",",
"path",
"=",
"'/'",
",",
"params",
"=",
"params",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/elasticache/layer1.py#L393-L439 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/reduction_gui/widgets/data_table_view.py | python | DataTableModel._ensureHasRows | (self, numRows) | ensure the table has numRows
:param numRows: number of rows that should exist | ensure the table has numRows
:param numRows: number of rows that should exist | [
"ensure",
"the",
"table",
"has",
"numRows",
":",
"param",
"numRows",
":",
"number",
"of",
"rows",
"that",
"should",
"exist"
] | def _ensureHasRows(self, numRows):
"""
ensure the table has numRows
:param numRows: number of rows that should exist
"""
while self._numRows() < numRows:
self.tableData.append(self._createEmptyRow()) | [
"def",
"_ensureHasRows",
"(",
"self",
",",
"numRows",
")",
":",
"while",
"self",
".",
"_numRows",
"(",
")",
"<",
"numRows",
":",
"self",
".",
"tableData",
".",
"append",
"(",
"self",
".",
"_createEmptyRow",
"(",
")",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/reduction_gui/widgets/data_table_view.py#L76-L82 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pep517/wrappers.py | python | default_subprocess_runner | (cmd, cwd=None, extra_environ=None) | The default method of calling the wrapper subprocess. | The default method of calling the wrapper subprocess. | [
"The",
"default",
"method",
"of",
"calling",
"the",
"wrapper",
"subprocess",
"."
] | def default_subprocess_runner(cmd, cwd=None, extra_environ=None):
"""The default method of calling the wrapper subprocess."""
env = os.environ.copy()
if extra_environ:
env.update(extra_environ)
check_call(cmd, cwd=cwd, env=env) | [
"def",
"default_subprocess_runner",
"(",
"cmd",
",",
"cwd",
"=",
"None",
",",
"extra_environ",
"=",
"None",
")",
":",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"if",
"extra_environ",
":",
"env",
".",
"update",
"(",
"extra_environ",
")",
"check_call",
"(",
"cmd",
",",
"cwd",
"=",
"cwd",
",",
"env",
"=",
"env",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pep517/wrappers.py#L137-L149 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/numbers.py | python | Complex.__add__ | (self, other) | self + other | self + other | [
"self",
"+",
"other"
] | def __add__(self, other):
"""self + other"""
raise NotImplementedError | [
"def",
"__add__",
"(",
"self",
",",
"other",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/numbers.py#L72-L74 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rospy/src/rospy/topics.py | python | _PublisherImpl.enable_latch | (self) | Enable publish() latch. The latch contains the last published
message and is sent to any new subscribers. | Enable publish() latch. The latch contains the last published
message and is sent to any new subscribers. | [
"Enable",
"publish",
"()",
"latch",
".",
"The",
"latch",
"contains",
"the",
"last",
"published",
"message",
"and",
"is",
"sent",
"to",
"any",
"new",
"subscribers",
"."
] | def enable_latch(self):
"""
Enable publish() latch. The latch contains the last published
message and is sent to any new subscribers.
"""
self.is_latch = True | [
"def",
"enable_latch",
"(",
"self",
")",
":",
"self",
".",
"is_latch",
"=",
"True"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/topics.py#L942-L947 | ||
pgRouting/osm2pgrouting | 8491929fc4037d308f271e84d59bb96da3c28aa2 | tools/cpplint.py | python | CleansedLines._CollapseStrings | (elided) | return collapsed | Collapses strings and chars on a line to simple "" or '' blocks.
We nix strings first so we're not fooled by text like '"http://"'
Args:
elided: The line being processed.
Returns:
The line with collapsed strings. | Collapses strings and chars on a line to simple "" or '' blocks. | [
"Collapses",
"strings",
"and",
"chars",
"on",
"a",
"line",
"to",
"simple",
"or",
"blocks",
"."
] | def _CollapseStrings(elided):
"""Collapses strings and chars on a line to simple "" or '' blocks.
We nix strings first so we're not fooled by text like '"http://"'
Args:
elided: The line being processed.
Returns:
The line with collapsed strings.
"""
if _RE_PATTERN_INCLUDE.match(elided):
return elided
# Remove escaped characters first to make quote/single quote collapsing
# basic. Things that look like escaped characters shouldn't occur
# outside of strings and chars.
elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
# Replace quoted strings and digit separators. Both single quotes
# and double quotes are processed in the same loop, otherwise
# nested quotes wouldn't work.
collapsed = ''
while True:
# Find the first quote character
match = Match(r'^([^\'"]*)([\'"])(.*)$', elided)
if not match:
collapsed += elided
break
head, quote, tail = match.groups()
if quote == '"':
# Collapse double quoted strings
second_quote = tail.find('"')
if second_quote >= 0:
collapsed += head + '""'
elided = tail[second_quote + 1:]
else:
# Unmatched double quote, don't bother processing the rest
# of the line since this is probably a multiline string.
collapsed += elided
break
else:
# Found single quote, check nearby text to eliminate digit separators.
#
# There is no special handling for floating point here, because
# the integer/fractional/exponent parts would all be parsed
# correctly as long as there are digits on both sides of the
# separator. So we are fine as long as we don't see something
# like "0.'3" (gcc 4.9.0 will not allow this literal).
if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):
match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail)
collapsed += head + match_literal.group(1).replace("'", '')
elided = match_literal.group(2)
else:
second_quote = tail.find('\'')
if second_quote >= 0:
collapsed += head + "''"
elided = tail[second_quote + 1:]
else:
# Unmatched single quote
collapsed += elided
break
return collapsed | [
"def",
"_CollapseStrings",
"(",
"elided",
")",
":",
"if",
"_RE_PATTERN_INCLUDE",
".",
"match",
"(",
"elided",
")",
":",
"return",
"elided",
"# Remove escaped characters first to make quote/single quote collapsing",
"# basic. Things that look like escaped characters shouldn't occur",
"# outside of strings and chars.",
"elided",
"=",
"_RE_PATTERN_CLEANSE_LINE_ESCAPES",
".",
"sub",
"(",
"''",
",",
"elided",
")",
"# Replace quoted strings and digit separators. Both single quotes",
"# and double quotes are processed in the same loop, otherwise",
"# nested quotes wouldn't work.",
"collapsed",
"=",
"''",
"while",
"True",
":",
"# Find the first quote character",
"match",
"=",
"Match",
"(",
"r'^([^\\'\"]*)([\\'\"])(.*)$'",
",",
"elided",
")",
"if",
"not",
"match",
":",
"collapsed",
"+=",
"elided",
"break",
"head",
",",
"quote",
",",
"tail",
"=",
"match",
".",
"groups",
"(",
")",
"if",
"quote",
"==",
"'\"'",
":",
"# Collapse double quoted strings",
"second_quote",
"=",
"tail",
".",
"find",
"(",
"'\"'",
")",
"if",
"second_quote",
">=",
"0",
":",
"collapsed",
"+=",
"head",
"+",
"'\"\"'",
"elided",
"=",
"tail",
"[",
"second_quote",
"+",
"1",
":",
"]",
"else",
":",
"# Unmatched double quote, don't bother processing the rest",
"# of the line since this is probably a multiline string.",
"collapsed",
"+=",
"elided",
"break",
"else",
":",
"# Found single quote, check nearby text to eliminate digit separators.",
"#",
"# There is no special handling for floating point here, because",
"# the integer/fractional/exponent parts would all be parsed",
"# correctly as long as there are digits on both sides of the",
"# separator. So we are fine as long as we don't see something",
"# like \"0.'3\" (gcc 4.9.0 will not allow this literal).",
"if",
"Search",
"(",
"r'\\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$'",
",",
"head",
")",
":",
"match_literal",
"=",
"Match",
"(",
"r'^((?:\\'?[0-9a-zA-Z_])*)(.*)$'",
",",
"\"'\"",
"+",
"tail",
")",
"collapsed",
"+=",
"head",
"+",
"match_literal",
".",
"group",
"(",
"1",
")",
".",
"replace",
"(",
"\"'\"",
",",
"''",
")",
"elided",
"=",
"match_literal",
".",
"group",
"(",
"2",
")",
"else",
":",
"second_quote",
"=",
"tail",
".",
"find",
"(",
"'\\''",
")",
"if",
"second_quote",
">=",
"0",
":",
"collapsed",
"+=",
"head",
"+",
"\"''\"",
"elided",
"=",
"tail",
"[",
"second_quote",
"+",
"1",
":",
"]",
"else",
":",
"# Unmatched single quote",
"collapsed",
"+=",
"elided",
"break",
"return",
"collapsed"
] | https://github.com/pgRouting/osm2pgrouting/blob/8491929fc4037d308f271e84d59bb96da3c28aa2/tools/cpplint.py#L1316-L1380 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/reduction_gui/reduction/inelastic/dgs_sample_data_setup_script.py | python | SampleSetupScript.from_xml | (self, xml_str) | Read in data from XML
@param xml_str: text to read the data from | Read in data from XML | [
"Read",
"in",
"data",
"from",
"XML"
] | def from_xml(self, xml_str):
"""
Read in data from XML
@param xml_str: text to read the data from
"""
dom = xml.dom.minidom.parseString(xml_str)
element_list = dom.getElementsByTagName("SampleSetup")
if len(element_list) > 0:
instrument_dom = element_list[0]
self.sample_file = BaseScriptElement.getStringElement(instrument_dom,
"sample_input_file",
default=SampleSetupScript.sample_file)
self.live_button = BaseScriptElement.getBoolElement(instrument_dom,
"live_button",
default=SampleSetupScript.live_button)
self.output_wsname = BaseScriptElement.getStringElement(instrument_dom,
"output_wsname",
default=SampleSetupScript.output_wsname)
self.detcal_file = BaseScriptElement.getStringElement(instrument_dom,
"detcal_file",
default=SampleSetupScript.detcal_file)
self.relocate_dets = BaseScriptElement.getBoolElement(instrument_dom,
"relocate_dets",
default=SampleSetupScript.relocate_dets)
self.incident_energy_guess = BaseScriptElement.getStringElement(instrument_dom,
"incident_energy_guess",
default=SampleSetupScript.incident_energy_guess)
self.use_ei_guess = BaseScriptElement.getBoolElement(instrument_dom,
"use_ei_guess",
default=SampleSetupScript.use_ei_guess)
self.tzero_guess = BaseScriptElement.getFloatElement(instrument_dom,
"tzero_guess",
default=SampleSetupScript.tzero_guess)
self.monitor1_specid = BaseScriptElement.getStringElement(instrument_dom,
"monitor1_specid",
default=SampleSetupScript.monitor1_specid)
self.monitor2_specid = BaseScriptElement.getStringElement(instrument_dom,
"monitor2_specid",
default=SampleSetupScript.monitor2_specid)
self.et_range_low = BaseScriptElement.getStringElement(instrument_dom,
"et_range/low",
default=SampleSetupScript.et_range_low)
self.et_range_width = BaseScriptElement.getStringElement(instrument_dom,
"et_range/width",
default=SampleSetupScript.et_range_width)
self.et_range_high = BaseScriptElement.getStringElement(instrument_dom,
"et_range/high",
default=SampleSetupScript.et_range_high)
self.et_is_distribution = BaseScriptElement.getBoolElement(instrument_dom,
"sofphie_is_distribution",
default=SampleSetupScript.et_is_distribution)
self.hardmask_file = BaseScriptElement.getStringElement(instrument_dom,
"hardmask_file",
default=SampleSetupScript.hardmask_file)
self.grouping_file = BaseScriptElement.getStringElement(instrument_dom,
"grouping_file",
default=SampleSetupScript.grouping_file)
self.show_workspaces = BaseScriptElement.getBoolElement(instrument_dom,
"show_workspaces",
default=SampleSetupScript.show_workspaces)
self.savedir = BaseScriptElement.getStringElement(instrument_dom,
"savedir",
default=SampleSetupScript.savedir) | [
"def",
"from_xml",
"(",
"self",
",",
"xml_str",
")",
":",
"dom",
"=",
"xml",
".",
"dom",
".",
"minidom",
".",
"parseString",
"(",
"xml_str",
")",
"element_list",
"=",
"dom",
".",
"getElementsByTagName",
"(",
"\"SampleSetup\"",
")",
"if",
"len",
"(",
"element_list",
")",
">",
"0",
":",
"instrument_dom",
"=",
"element_list",
"[",
"0",
"]",
"self",
".",
"sample_file",
"=",
"BaseScriptElement",
".",
"getStringElement",
"(",
"instrument_dom",
",",
"\"sample_input_file\"",
",",
"default",
"=",
"SampleSetupScript",
".",
"sample_file",
")",
"self",
".",
"live_button",
"=",
"BaseScriptElement",
".",
"getBoolElement",
"(",
"instrument_dom",
",",
"\"live_button\"",
",",
"default",
"=",
"SampleSetupScript",
".",
"live_button",
")",
"self",
".",
"output_wsname",
"=",
"BaseScriptElement",
".",
"getStringElement",
"(",
"instrument_dom",
",",
"\"output_wsname\"",
",",
"default",
"=",
"SampleSetupScript",
".",
"output_wsname",
")",
"self",
".",
"detcal_file",
"=",
"BaseScriptElement",
".",
"getStringElement",
"(",
"instrument_dom",
",",
"\"detcal_file\"",
",",
"default",
"=",
"SampleSetupScript",
".",
"detcal_file",
")",
"self",
".",
"relocate_dets",
"=",
"BaseScriptElement",
".",
"getBoolElement",
"(",
"instrument_dom",
",",
"\"relocate_dets\"",
",",
"default",
"=",
"SampleSetupScript",
".",
"relocate_dets",
")",
"self",
".",
"incident_energy_guess",
"=",
"BaseScriptElement",
".",
"getStringElement",
"(",
"instrument_dom",
",",
"\"incident_energy_guess\"",
",",
"default",
"=",
"SampleSetupScript",
".",
"incident_energy_guess",
")",
"self",
".",
"use_ei_guess",
"=",
"BaseScriptElement",
".",
"getBoolElement",
"(",
"instrument_dom",
",",
"\"use_ei_guess\"",
",",
"default",
"=",
"SampleSetupScript",
".",
"use_ei_guess",
")",
"self",
".",
"tzero_guess",
"=",
"BaseScriptElement",
".",
"getFloatElement",
"(",
"instrument_dom",
",",
"\"tzero_guess\"",
",",
"default",
"=",
"SampleSetupScript",
".",
"tzero_guess",
")",
"self",
".",
"monitor1_specid",
"=",
"BaseScriptElement",
".",
"getStringElement",
"(",
"instrument_dom",
",",
"\"monitor1_specid\"",
",",
"default",
"=",
"SampleSetupScript",
".",
"monitor1_specid",
")",
"self",
".",
"monitor2_specid",
"=",
"BaseScriptElement",
".",
"getStringElement",
"(",
"instrument_dom",
",",
"\"monitor2_specid\"",
",",
"default",
"=",
"SampleSetupScript",
".",
"monitor2_specid",
")",
"self",
".",
"et_range_low",
"=",
"BaseScriptElement",
".",
"getStringElement",
"(",
"instrument_dom",
",",
"\"et_range/low\"",
",",
"default",
"=",
"SampleSetupScript",
".",
"et_range_low",
")",
"self",
".",
"et_range_width",
"=",
"BaseScriptElement",
".",
"getStringElement",
"(",
"instrument_dom",
",",
"\"et_range/width\"",
",",
"default",
"=",
"SampleSetupScript",
".",
"et_range_width",
")",
"self",
".",
"et_range_high",
"=",
"BaseScriptElement",
".",
"getStringElement",
"(",
"instrument_dom",
",",
"\"et_range/high\"",
",",
"default",
"=",
"SampleSetupScript",
".",
"et_range_high",
")",
"self",
".",
"et_is_distribution",
"=",
"BaseScriptElement",
".",
"getBoolElement",
"(",
"instrument_dom",
",",
"\"sofphie_is_distribution\"",
",",
"default",
"=",
"SampleSetupScript",
".",
"et_is_distribution",
")",
"self",
".",
"hardmask_file",
"=",
"BaseScriptElement",
".",
"getStringElement",
"(",
"instrument_dom",
",",
"\"hardmask_file\"",
",",
"default",
"=",
"SampleSetupScript",
".",
"hardmask_file",
")",
"self",
".",
"grouping_file",
"=",
"BaseScriptElement",
".",
"getStringElement",
"(",
"instrument_dom",
",",
"\"grouping_file\"",
",",
"default",
"=",
"SampleSetupScript",
".",
"grouping_file",
")",
"self",
".",
"show_workspaces",
"=",
"BaseScriptElement",
".",
"getBoolElement",
"(",
"instrument_dom",
",",
"\"show_workspaces\"",
",",
"default",
"=",
"SampleSetupScript",
".",
"show_workspaces",
")",
"self",
".",
"savedir",
"=",
"BaseScriptElement",
".",
"getStringElement",
"(",
"instrument_dom",
",",
"\"savedir\"",
",",
"default",
"=",
"SampleSetupScript",
".",
"savedir",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/reduction_gui/reduction/inelastic/dgs_sample_data_setup_script.py#L134-L196 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/tracking/data_structures.py | python | TrackableDataStructure._layers | (self) | return collected | All Layers and Layer containers, including empty containers. | All Layers and Layer containers, including empty containers. | [
"All",
"Layers",
"and",
"Layer",
"containers",
"including",
"empty",
"containers",
"."
] | def _layers(self):
"""All Layers and Layer containers, including empty containers."""
# Filter objects on demand so that wrapper objects use values from the thing
# they're wrapping if out of sync.
collected = []
for obj in self._values:
if (isinstance(obj, TrackableDataStructure)
or layer_utils.is_layer(obj)
or layer_utils.has_weights(obj)):
collected.append(obj)
return collected | [
"def",
"_layers",
"(",
"self",
")",
":",
"# Filter objects on demand so that wrapper objects use values from the thing",
"# they're wrapping if out of sync.",
"collected",
"=",
"[",
"]",
"for",
"obj",
"in",
"self",
".",
"_values",
":",
"if",
"(",
"isinstance",
"(",
"obj",
",",
"TrackableDataStructure",
")",
"or",
"layer_utils",
".",
"is_layer",
"(",
"obj",
")",
"or",
"layer_utils",
".",
"has_weights",
"(",
"obj",
")",
")",
":",
"collected",
".",
"append",
"(",
"obj",
")",
"return",
"collected"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/tracking/data_structures.py#L175-L185 | |
stellar-deprecated/stellard | 67eabb2217bdfa9a6ea317f62338fb6bca458c90 | src/protobuf/python/google/protobuf/internal/cpp_message.py | python | CompositeProperty | (cdescriptor, message_type) | return property(Getter) | Returns a Python property the given composite field. | Returns a Python property the given composite field. | [
"Returns",
"a",
"Python",
"property",
"the",
"given",
"composite",
"field",
"."
] | def CompositeProperty(cdescriptor, message_type):
"""Returns a Python property the given composite field."""
def Getter(self):
sub_message = self._composite_fields.get(cdescriptor.name, None)
if sub_message is None:
cmessage = self._cmsg.NewSubMessage(cdescriptor)
sub_message = message_type._concrete_class(__cmessage=cmessage)
self._composite_fields[cdescriptor.name] = sub_message
return sub_message
return property(Getter) | [
"def",
"CompositeProperty",
"(",
"cdescriptor",
",",
"message_type",
")",
":",
"def",
"Getter",
"(",
"self",
")",
":",
"sub_message",
"=",
"self",
".",
"_composite_fields",
".",
"get",
"(",
"cdescriptor",
".",
"name",
",",
"None",
")",
"if",
"sub_message",
"is",
"None",
":",
"cmessage",
"=",
"self",
".",
"_cmsg",
".",
"NewSubMessage",
"(",
"cdescriptor",
")",
"sub_message",
"=",
"message_type",
".",
"_concrete_class",
"(",
"__cmessage",
"=",
"cmessage",
")",
"self",
".",
"_composite_fields",
"[",
"cdescriptor",
".",
"name",
"]",
"=",
"sub_message",
"return",
"sub_message",
"return",
"property",
"(",
"Getter",
")"
] | https://github.com/stellar-deprecated/stellard/blob/67eabb2217bdfa9a6ea317f62338fb6bca458c90/src/protobuf/python/google/protobuf/internal/cpp_message.py#L90-L101 | |
rootm0s/Protectors | 5b3f4d11687a5955caf9c3af30666c4bfc2c19ab | OWASP-ZSC/module/readline_windows/pyreadline/modes/emacs.py | python | EmacsMode.dump_macros | (self, e) | Print all of the Readline key sequences bound to macros and the
strings they output. If a numeric argument is supplied, the output
is formatted in such a way that it can be made part of an inputrc
file. This command is unbound by default. | Print all of the Readline key sequences bound to macros and the
strings they output. If a numeric argument is supplied, the output
is formatted in such a way that it can be made part of an inputrc
file. This command is unbound by default. | [
"Print",
"all",
"of",
"the",
"Readline",
"key",
"sequences",
"bound",
"to",
"macros",
"and",
"the",
"strings",
"they",
"output",
".",
"If",
"a",
"numeric",
"argument",
"is",
"supplied",
"the",
"output",
"is",
"formatted",
"in",
"such",
"a",
"way",
"that",
"it",
"can",
"be",
"made",
"part",
"of",
"an",
"inputrc",
"file",
".",
"This",
"command",
"is",
"unbound",
"by",
"default",
"."
] | def dump_macros(self, e): # ()
'''Print all of the Readline key sequences bound to macros and the
strings they output. If a numeric argument is supplied, the output
is formatted in such a way that it can be made part of an inputrc
file. This command is unbound by default.'''
self.finalize() | [
"def",
"dump_macros",
"(",
"self",
",",
"e",
")",
":",
"# ()",
"self",
".",
"finalize",
"(",
")"
] | https://github.com/rootm0s/Protectors/blob/5b3f4d11687a5955caf9c3af30666c4bfc2c19ab/OWASP-ZSC/module/readline_windows/pyreadline/modes/emacs.py#L601-L606 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/variable_scope.py | python | _get_unique_variable_scope | (prefix) | return prefix + ("_%d" % idx) | Get a name with the given prefix unique in the current variable scope. | Get a name with the given prefix unique in the current variable scope. | [
"Get",
"a",
"name",
"with",
"the",
"given",
"prefix",
"unique",
"in",
"the",
"current",
"variable",
"scope",
"."
] | def _get_unique_variable_scope(prefix):
"""Get a name with the given prefix unique in the current variable scope."""
var_scope_store = get_variable_scope_store()
current_scope = get_variable_scope()
name = current_scope.name + "/" + prefix if current_scope.name else prefix
if var_scope_store.variable_scope_count(name) == 0:
return prefix
idx = 1
while var_scope_store.variable_scope_count(name + ("_%d" % idx)) > 0:
idx += 1
return prefix + ("_%d" % idx) | [
"def",
"_get_unique_variable_scope",
"(",
"prefix",
")",
":",
"var_scope_store",
"=",
"get_variable_scope_store",
"(",
")",
"current_scope",
"=",
"get_variable_scope",
"(",
")",
"name",
"=",
"current_scope",
".",
"name",
"+",
"\"/\"",
"+",
"prefix",
"if",
"current_scope",
".",
"name",
"else",
"prefix",
"if",
"var_scope_store",
".",
"variable_scope_count",
"(",
"name",
")",
"==",
"0",
":",
"return",
"prefix",
"idx",
"=",
"1",
"while",
"var_scope_store",
".",
"variable_scope_count",
"(",
"name",
"+",
"(",
"\"_%d\"",
"%",
"idx",
")",
")",
">",
"0",
":",
"idx",
"+=",
"1",
"return",
"prefix",
"+",
"(",
"\"_%d\"",
"%",
"idx",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/variable_scope.py#L1961-L1971 | |
chromiumembedded/cef | 80caf947f3fe2210e5344713c5281d8af9bdc295 | tools/yapf/yapf/yapflib/verifier.py | python | _NormalizeCode | (code) | return code + '\n' | Make sure that the code snippet is compilable. | Make sure that the code snippet is compilable. | [
"Make",
"sure",
"that",
"the",
"code",
"snippet",
"is",
"compilable",
"."
] | def _NormalizeCode(code):
"""Make sure that the code snippet is compilable."""
code = textwrap.dedent(code.lstrip('\n')).lstrip()
# Split the code to lines and get rid of all leading full-comment lines as
# they can mess up the normalization attempt.
lines = code.split('\n')
i = 0
for i, line in enumerate(lines):
line = line.strip()
if line and not line.startswith('#'):
break
code = '\n'.join(lines[i:]) + '\n'
if re.match(r'(if|while|for|with|def|class|async|await)\b', code):
code += '\n pass'
elif re.match(r'(elif|else)\b', code):
try:
try_code = 'if True:\n pass\n' + code + '\n pass'
ast.parse(
textwrap.dedent(try_code.lstrip('\n')).lstrip(), '<string>', 'exec')
code = try_code
except SyntaxError:
# The assumption here is that the code is on a single line.
code = 'if True: pass\n' + code
elif code.startswith('@'):
code += '\ndef _():\n pass'
elif re.match(r'try\b', code):
code += '\n pass\nexcept:\n pass'
elif re.match(r'(except|finally)\b', code):
code = 'try:\n pass\n' + code + '\n pass'
elif re.match(r'(return|yield)\b', code):
code = 'def _():\n ' + code
elif re.match(r'(continue|break)\b', code):
code = 'while True:\n ' + code
elif re.match(r'print\b', code):
code = 'from __future__ import print_function\n' + code
return code + '\n' | [
"def",
"_NormalizeCode",
"(",
"code",
")",
":",
"code",
"=",
"textwrap",
".",
"dedent",
"(",
"code",
".",
"lstrip",
"(",
"'\\n'",
")",
")",
".",
"lstrip",
"(",
")",
"# Split the code to lines and get rid of all leading full-comment lines as",
"# they can mess up the normalization attempt.",
"lines",
"=",
"code",
".",
"split",
"(",
"'\\n'",
")",
"i",
"=",
"0",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
"and",
"not",
"line",
".",
"startswith",
"(",
"'#'",
")",
":",
"break",
"code",
"=",
"'\\n'",
".",
"join",
"(",
"lines",
"[",
"i",
":",
"]",
")",
"+",
"'\\n'",
"if",
"re",
".",
"match",
"(",
"r'(if|while|for|with|def|class|async|await)\\b'",
",",
"code",
")",
":",
"code",
"+=",
"'\\n pass'",
"elif",
"re",
".",
"match",
"(",
"r'(elif|else)\\b'",
",",
"code",
")",
":",
"try",
":",
"try_code",
"=",
"'if True:\\n pass\\n'",
"+",
"code",
"+",
"'\\n pass'",
"ast",
".",
"parse",
"(",
"textwrap",
".",
"dedent",
"(",
"try_code",
".",
"lstrip",
"(",
"'\\n'",
")",
")",
".",
"lstrip",
"(",
")",
",",
"'<string>'",
",",
"'exec'",
")",
"code",
"=",
"try_code",
"except",
"SyntaxError",
":",
"# The assumption here is that the code is on a single line.",
"code",
"=",
"'if True: pass\\n'",
"+",
"code",
"elif",
"code",
".",
"startswith",
"(",
"'@'",
")",
":",
"code",
"+=",
"'\\ndef _():\\n pass'",
"elif",
"re",
".",
"match",
"(",
"r'try\\b'",
",",
"code",
")",
":",
"code",
"+=",
"'\\n pass\\nexcept:\\n pass'",
"elif",
"re",
".",
"match",
"(",
"r'(except|finally)\\b'",
",",
"code",
")",
":",
"code",
"=",
"'try:\\n pass\\n'",
"+",
"code",
"+",
"'\\n pass'",
"elif",
"re",
".",
"match",
"(",
"r'(return|yield)\\b'",
",",
"code",
")",
":",
"code",
"=",
"'def _():\\n '",
"+",
"code",
"elif",
"re",
".",
"match",
"(",
"r'(continue|break)\\b'",
",",
"code",
")",
":",
"code",
"=",
"'while True:\\n '",
"+",
"code",
"elif",
"re",
".",
"match",
"(",
"r'print\\b'",
",",
"code",
")",
":",
"code",
"=",
"'from __future__ import print_function\\n'",
"+",
"code",
"return",
"code",
"+",
"'\\n'"
] | https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/yapf/yapf/yapflib/verifier.py#L55-L93 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_windows.py | python | TopLevelWindow.SetIcon | (*args, **kwargs) | return _windows_.TopLevelWindow_SetIcon(*args, **kwargs) | SetIcon(self, Icon icon) | SetIcon(self, Icon icon) | [
"SetIcon",
"(",
"self",
"Icon",
"icon",
")"
] | def SetIcon(*args, **kwargs):
"""SetIcon(self, Icon icon)"""
return _windows_.TopLevelWindow_SetIcon(*args, **kwargs) | [
"def",
"SetIcon",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"TopLevelWindow_SetIcon",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L433-L435 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/mailbox.py | python | MH.remove_folder | (self, folder) | Delete the named folder, which must be empty. | Delete the named folder, which must be empty. | [
"Delete",
"the",
"named",
"folder",
"which",
"must",
"be",
"empty",
"."
] | def remove_folder(self, folder):
"""Delete the named folder, which must be empty."""
path = os.path.join(self._path, folder)
entries = os.listdir(path)
if entries == ['.mh_sequences']:
os.remove(os.path.join(path, '.mh_sequences'))
elif entries == []:
pass
else:
raise NotEmptyError('Folder not empty: %s' % self._path)
os.rmdir(path) | [
"def",
"remove_folder",
"(",
"self",
",",
"folder",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"folder",
")",
"entries",
"=",
"os",
".",
"listdir",
"(",
"path",
")",
"if",
"entries",
"==",
"[",
"'.mh_sequences'",
"]",
":",
"os",
".",
"remove",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'.mh_sequences'",
")",
")",
"elif",
"entries",
"==",
"[",
"]",
":",
"pass",
"else",
":",
"raise",
"NotEmptyError",
"(",
"'Folder not empty: %s'",
"%",
"self",
".",
"_path",
")",
"os",
".",
"rmdir",
"(",
"path",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/mailbox.py#L1120-L1130 | ||
hakuna-m/wubiuefi | caec1af0a09c78fd5a345180ada1fe45e0c63493 | src/openpgp/sap/util/ordict.py | python | ordict.__init__ | (self) | Initialize keylist. | Initialize keylist. | [
"Initialize",
"keylist",
"."
] | def __init__(self):
"Initialize keylist."
self.keylist = [] | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"keylist",
"=",
"[",
"]"
] | https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/openpgp/sap/util/ordict.py#L40-L42 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/WebOb/webob/request.py | python | BaseRequest.POST | (self) | return vars | Return a MultiDict containing all the variables from a form
request. Returns an empty dict-like object for non-form requests.
Form requests are typically POST requests, however PUT & PATCH requests
with an appropriate Content-Type are also supported. | Return a MultiDict containing all the variables from a form
request. Returns an empty dict-like object for non-form requests. | [
"Return",
"a",
"MultiDict",
"containing",
"all",
"the",
"variables",
"from",
"a",
"form",
"request",
".",
"Returns",
"an",
"empty",
"dict",
"-",
"like",
"object",
"for",
"non",
"-",
"form",
"requests",
"."
] | def POST(self):
"""
Return a MultiDict containing all the variables from a form
request. Returns an empty dict-like object for non-form requests.
Form requests are typically POST requests, however PUT & PATCH requests
with an appropriate Content-Type are also supported.
"""
env = self.environ
if self.method not in ('POST', 'PUT', 'PATCH'):
return NoVars('Not a form request')
if 'webob._parsed_post_vars' in env:
vars, body_file = env['webob._parsed_post_vars']
if body_file is self.body_file_raw:
return vars
content_type = self.content_type
if ((self.method == 'PUT' and not content_type)
or content_type not in
('',
'application/x-www-form-urlencoded',
'multipart/form-data')
):
# Not an HTML form submission
return NoVars('Not an HTML form submission (Content-Type: %s)'
% content_type)
self._check_charset()
self.make_body_seekable()
self.body_file_raw.seek(0)
fs_environ = env.copy()
# FieldStorage assumes a missing CONTENT_LENGTH, but a
# default of 0 is better:
fs_environ.setdefault('CONTENT_LENGTH', '0')
fs_environ['QUERY_STRING'] = ''
if PY3: # pragma: no cover
fs = cgi_FieldStorage(
fp=self.body_file,
environ=fs_environ,
keep_blank_values=True,
encoding='utf8')
vars = MultiDict.from_fieldstorage(fs)
else:
fs = cgi_FieldStorage(
fp=self.body_file,
environ=fs_environ,
keep_blank_values=True)
vars = MultiDict.from_fieldstorage(fs)
env['webob._parsed_post_vars'] = (vars, self.body_file_raw)
return vars | [
"def",
"POST",
"(",
"self",
")",
":",
"env",
"=",
"self",
".",
"environ",
"if",
"self",
".",
"method",
"not",
"in",
"(",
"'POST'",
",",
"'PUT'",
",",
"'PATCH'",
")",
":",
"return",
"NoVars",
"(",
"'Not a form request'",
")",
"if",
"'webob._parsed_post_vars'",
"in",
"env",
":",
"vars",
",",
"body_file",
"=",
"env",
"[",
"'webob._parsed_post_vars'",
"]",
"if",
"body_file",
"is",
"self",
".",
"body_file_raw",
":",
"return",
"vars",
"content_type",
"=",
"self",
".",
"content_type",
"if",
"(",
"(",
"self",
".",
"method",
"==",
"'PUT'",
"and",
"not",
"content_type",
")",
"or",
"content_type",
"not",
"in",
"(",
"''",
",",
"'application/x-www-form-urlencoded'",
",",
"'multipart/form-data'",
")",
")",
":",
"# Not an HTML form submission",
"return",
"NoVars",
"(",
"'Not an HTML form submission (Content-Type: %s)'",
"%",
"content_type",
")",
"self",
".",
"_check_charset",
"(",
")",
"self",
".",
"make_body_seekable",
"(",
")",
"self",
".",
"body_file_raw",
".",
"seek",
"(",
"0",
")",
"fs_environ",
"=",
"env",
".",
"copy",
"(",
")",
"# FieldStorage assumes a missing CONTENT_LENGTH, but a",
"# default of 0 is better:",
"fs_environ",
".",
"setdefault",
"(",
"'CONTENT_LENGTH'",
",",
"'0'",
")",
"fs_environ",
"[",
"'QUERY_STRING'",
"]",
"=",
"''",
"if",
"PY3",
":",
"# pragma: no cover",
"fs",
"=",
"cgi_FieldStorage",
"(",
"fp",
"=",
"self",
".",
"body_file",
",",
"environ",
"=",
"fs_environ",
",",
"keep_blank_values",
"=",
"True",
",",
"encoding",
"=",
"'utf8'",
")",
"vars",
"=",
"MultiDict",
".",
"from_fieldstorage",
"(",
"fs",
")",
"else",
":",
"fs",
"=",
"cgi_FieldStorage",
"(",
"fp",
"=",
"self",
".",
"body_file",
",",
"environ",
"=",
"fs_environ",
",",
"keep_blank_values",
"=",
"True",
")",
"vars",
"=",
"MultiDict",
".",
"from_fieldstorage",
"(",
"fs",
")",
"env",
"[",
"'webob._parsed_post_vars'",
"]",
"=",
"(",
"vars",
",",
"self",
".",
"body_file_raw",
")",
"return",
"vars"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/WebOb/webob/request.py#L762-L812 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Inelastic/CrystalField/function.py | python | PeaksFunction.attr | (self) | return self._attrib | Get or set the function attributes.
Returns a FunctionAttributes object that accesses the peaks' attributes. | Get or set the function attributes.
Returns a FunctionAttributes object that accesses the peaks' attributes. | [
"Get",
"or",
"set",
"the",
"function",
"attributes",
".",
"Returns",
"a",
"FunctionAttributes",
"object",
"that",
"accesses",
"the",
"peaks",
"attributes",
"."
] | def attr(self):
"""Get or set the function attributes.
Returns a FunctionAttributes object that accesses the peaks' attributes.
"""
return self._attrib | [
"def",
"attr",
"(",
"self",
")",
":",
"return",
"self",
".",
"_attrib"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/CrystalField/function.py#L244-L248 | |
emscripten-core/emscripten | 0d413d3c5af8b28349682496edc14656f5700c2f | third_party/ply/example/BASIC/basparse.py | python | p_expr_unary | (p) | expr : MINUS expr %prec UMINUS | expr : MINUS expr %prec UMINUS | [
"expr",
":",
"MINUS",
"expr",
"%prec",
"UMINUS"
] | def p_expr_unary(p):
'''expr : MINUS expr %prec UMINUS'''
p[0] = ('UNARY','-',p[2]) | [
"def",
"p_expr_unary",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"(",
"'UNARY'",
",",
"'-'",
",",
"p",
"[",
"2",
"]",
")"
] | https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/BASIC/basparse.py#L304-L306 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/imaplib.py | python | IMAP4.getquota | (self, root) | return self._untagged_response(typ, dat, 'QUOTA') | Get the quota root's resource usage and limits.
Part of the IMAP4 QUOTA extension defined in rfc2087.
(typ, [data]) = <instance>.getquota(root) | Get the quota root's resource usage and limits. | [
"Get",
"the",
"quota",
"root",
"s",
"resource",
"usage",
"and",
"limits",
"."
] | def getquota(self, root):
"""Get the quota root's resource usage and limits.
Part of the IMAP4 QUOTA extension defined in rfc2087.
(typ, [data]) = <instance>.getquota(root)
"""
typ, dat = self._simple_command('GETQUOTA', root)
return self._untagged_response(typ, dat, 'QUOTA') | [
"def",
"getquota",
"(",
"self",
",",
"root",
")",
":",
"typ",
",",
"dat",
"=",
"self",
".",
"_simple_command",
"(",
"'GETQUOTA'",
",",
"root",
")",
"return",
"self",
".",
"_untagged_response",
"(",
"typ",
",",
"dat",
",",
"'QUOTA'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/imaplib.py#L555-L563 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/turtle.py | python | TNavigator.speed | (self, s=0) | dummy method - to be overwritten by child class | dummy method - to be overwritten by child class | [
"dummy",
"method",
"-",
"to",
"be",
"overwritten",
"by",
"child",
"class"
] | def speed(self, s=0):
"""dummy method - to be overwritten by child class""" | [
"def",
"speed",
"(",
"self",
",",
"s",
"=",
"0",
")",
":"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/turtle.py#L2004-L2005 | ||
microsoft/ELL | a1d6bacc37a14879cc025d9be2ba40b1a0632315 | tools/importers/common/converters.py | python | ConvertBinaryOperation.convert_node | (self, conversion_parameters: typing.Mapping[str, typing.Any]) | Derived classes override to convert the importer node to appropriate ELL node(s)
and insert into the model | Derived classes override to convert the importer node to appropriate ELL node(s)
and insert into the model | [
"Derived",
"classes",
"override",
"to",
"convert",
"the",
"importer",
"node",
"to",
"appropriate",
"ELL",
"node",
"(",
"s",
")",
"and",
"insert",
"into",
"the",
"model"
] | def convert_node(self, conversion_parameters: typing.Mapping[str, typing.Any]):
"""
Derived classes override to convert the importer node to appropriate ELL node(s)
and insert into the model
"""
model = conversion_parameters["model"]
builder = conversion_parameters["builder"]
lookup_table = conversion_parameters["lookup_table"]
# Get the port elements and memory layout from the two inputs.
# Since the 2 inputs and output could have different padding,
# we need both the port elements and the memory layouts for each.
input1_port_elements, input1_port_memory_layout = lookup_table.get_port_elements_and_memory_layout_for_input(
self.importer_node, 0)
input2_port_elements, input2_port_memory_layout = lookup_table.get_port_elements_and_memory_layout_for_input(
self.importer_node, 1)
output_shape_tuple = self.importer_node.output_shapes[0]
output_port_memory_layout = memory_shapes.get_ell_port_memory_layout(
output_shape_tuple[0],
output_shape_tuple[1],
self.importer_node.output_padding["size"])
# see if the shapes match
input1_port_elements, _ = self.reinterpret_input(builder, model, input1_port_elements,
input1_port_memory_layout)
input2_port_elements, _ = self.reinterpret_input(builder, model, input2_port_elements,
input2_port_memory_layout)
# Add the BinaryOperationNode to the model.
ell_node = builder.AddBinaryOperationNode(
model,
input1_port_elements,
input2_port_elements,
self.operator)
output_elements = ell.nodes.PortElements(ell_node.GetOutputPort("output"))
output_port_elements, new_output_node = self.reinterpret_input(builder, model, output_elements,
output_port_memory_layout)
if new_output_node is not None:
ell_node = new_output_node
# Register the mapping
lookup_table.add_imported_ell_node(self.importer_node, ell_node) | [
"def",
"convert_node",
"(",
"self",
",",
"conversion_parameters",
":",
"typing",
".",
"Mapping",
"[",
"str",
",",
"typing",
".",
"Any",
"]",
")",
":",
"model",
"=",
"conversion_parameters",
"[",
"\"model\"",
"]",
"builder",
"=",
"conversion_parameters",
"[",
"\"builder\"",
"]",
"lookup_table",
"=",
"conversion_parameters",
"[",
"\"lookup_table\"",
"]",
"# Get the port elements and memory layout from the two inputs.",
"# Since the 2 inputs and output could have different padding,",
"# we need both the port elements and the memory layouts for each.",
"input1_port_elements",
",",
"input1_port_memory_layout",
"=",
"lookup_table",
".",
"get_port_elements_and_memory_layout_for_input",
"(",
"self",
".",
"importer_node",
",",
"0",
")",
"input2_port_elements",
",",
"input2_port_memory_layout",
"=",
"lookup_table",
".",
"get_port_elements_and_memory_layout_for_input",
"(",
"self",
".",
"importer_node",
",",
"1",
")",
"output_shape_tuple",
"=",
"self",
".",
"importer_node",
".",
"output_shapes",
"[",
"0",
"]",
"output_port_memory_layout",
"=",
"memory_shapes",
".",
"get_ell_port_memory_layout",
"(",
"output_shape_tuple",
"[",
"0",
"]",
",",
"output_shape_tuple",
"[",
"1",
"]",
",",
"self",
".",
"importer_node",
".",
"output_padding",
"[",
"\"size\"",
"]",
")",
"# see if the shapes match",
"input1_port_elements",
",",
"_",
"=",
"self",
".",
"reinterpret_input",
"(",
"builder",
",",
"model",
",",
"input1_port_elements",
",",
"input1_port_memory_layout",
")",
"input2_port_elements",
",",
"_",
"=",
"self",
".",
"reinterpret_input",
"(",
"builder",
",",
"model",
",",
"input2_port_elements",
",",
"input2_port_memory_layout",
")",
"# Add the BinaryOperationNode to the model.",
"ell_node",
"=",
"builder",
".",
"AddBinaryOperationNode",
"(",
"model",
",",
"input1_port_elements",
",",
"input2_port_elements",
",",
"self",
".",
"operator",
")",
"output_elements",
"=",
"ell",
".",
"nodes",
".",
"PortElements",
"(",
"ell_node",
".",
"GetOutputPort",
"(",
"\"output\"",
")",
")",
"output_port_elements",
",",
"new_output_node",
"=",
"self",
".",
"reinterpret_input",
"(",
"builder",
",",
"model",
",",
"output_elements",
",",
"output_port_memory_layout",
")",
"if",
"new_output_node",
"is",
"not",
"None",
":",
"ell_node",
"=",
"new_output_node",
"# Register the mapping",
"lookup_table",
".",
"add_imported_ell_node",
"(",
"self",
".",
"importer_node",
",",
"ell_node",
")"
] | https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/importers/common/converters.py#L1326-L1367 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/plan/motionplanning.py | python | CSpaceInterface.interpolate | (self, a, b, u) | return _motionplanning.CSpaceInterface_interpolate(self, a, b, u) | Interpolates between two configurations.
Args:
a (:obj:`object`)
b (:obj:`object`)
u (float)
Returns:
(:obj:`object`): | Interpolates between two configurations. | [
"Interpolates",
"between",
"two",
"configurations",
"."
] | def interpolate(self, a, b, u):
"""
Interpolates between two configurations.
Args:
a (:obj:`object`)
b (:obj:`object`)
u (float)
Returns:
(:obj:`object`):
"""
return _motionplanning.CSpaceInterface_interpolate(self, a, b, u) | [
"def",
"interpolate",
"(",
"self",
",",
"a",
",",
"b",
",",
"u",
")",
":",
"return",
"_motionplanning",
".",
"CSpaceInterface_interpolate",
"(",
"self",
",",
"a",
",",
"b",
",",
"u",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/plan/motionplanning.py#L520-L531 | |
0ad/0ad | f58db82e0e925016d83f4e3fa7ca599e3866e2af | source/tools/i18n/i18n_helper/globber.py | python | getCatalogs | (inputFilePath, filters : List[str] = None) | return existingTranslationCatalogs | Returns a list of "real" catalogs (.po) in the given folder. | Returns a list of "real" catalogs (.po) in the given folder. | [
"Returns",
"a",
"list",
"of",
"real",
"catalogs",
"(",
".",
"po",
")",
"in",
"the",
"given",
"folder",
"."
] | def getCatalogs(inputFilePath, filters : List[str] = None) -> List[Catalog]:
"""Returns a list of "real" catalogs (.po) in the given folder."""
existingTranslationCatalogs = []
l10nFolderPath = os.path.dirname(inputFilePath)
inputFileName = os.path.basename(inputFilePath)
for filename in os.listdir(str(l10nFolderPath)):
if filename.startswith("long") or not filename.endswith(".po"):
continue
if filename.split(".")[1] != inputFileName.split(".")[0]:
continue
if not filters or filename.split(".")[0] in filters:
existingTranslationCatalogs.append(
Catalog.readFrom(os.path.join(l10nFolderPath, filename), locale=filename.split('.')[0]))
return existingTranslationCatalogs | [
"def",
"getCatalogs",
"(",
"inputFilePath",
",",
"filters",
":",
"List",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"Catalog",
"]",
":",
"existingTranslationCatalogs",
"=",
"[",
"]",
"l10nFolderPath",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"inputFilePath",
")",
"inputFileName",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"inputFilePath",
")",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"str",
"(",
"l10nFolderPath",
")",
")",
":",
"if",
"filename",
".",
"startswith",
"(",
"\"long\"",
")",
"or",
"not",
"filename",
".",
"endswith",
"(",
"\".po\"",
")",
":",
"continue",
"if",
"filename",
".",
"split",
"(",
"\".\"",
")",
"[",
"1",
"]",
"!=",
"inputFileName",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
":",
"continue",
"if",
"not",
"filters",
"or",
"filename",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
"in",
"filters",
":",
"existingTranslationCatalogs",
".",
"append",
"(",
"Catalog",
".",
"readFrom",
"(",
"os",
".",
"path",
".",
"join",
"(",
"l10nFolderPath",
",",
"filename",
")",
",",
"locale",
"=",
"filename",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
")",
"return",
"existingTranslationCatalogs"
] | https://github.com/0ad/0ad/blob/f58db82e0e925016d83f4e3fa7ca599e3866e2af/source/tools/i18n/i18n_helper/globber.py#L7-L22 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | chrome/tools/extract_actions.py | python | AddComputedActions | (actions) | Add computed actions to the actions list.
Arguments:
actions: set of actions to add to. | Add computed actions to the actions list. | [
"Add",
"computed",
"actions",
"to",
"the",
"actions",
"list",
"."
] | def AddComputedActions(actions):
"""Add computed actions to the actions list.
Arguments:
actions: set of actions to add to.
"""
# Actions for back_forward_menu_model.cc.
for dir in ('BackMenu_', 'ForwardMenu_'):
actions.add(dir + 'ShowFullHistory')
actions.add(dir + 'Popup')
for i in range(1, 20):
actions.add(dir + 'HistoryClick' + str(i))
actions.add(dir + 'ChapterClick' + str(i))
# Actions for new_tab_ui.cc.
for i in range(1, 10):
actions.add('MostVisited%d' % i)
# Actions for safe_browsing_blocking_page.cc.
for interstitial in ('Phishing', 'Malware', 'Multiple'):
for action in ('Show', 'Proceed', 'DontProceed'):
actions.add('SBInterstitial%s%s' % (interstitial, action))
# Actions for language_options_handler.cc (Chrome OS specific).
for input_method_id in INPUT_METHOD_IDS:
actions.add('LanguageOptions_DisableInputMethod_%s' % input_method_id)
actions.add('LanguageOptions_EnableInputMethod_%s' % input_method_id)
actions.add('InputMethodOptions_Open_%s' % input_method_id)
for language_code in LANGUAGE_CODES:
actions.add('LanguageOptions_UiLanguageChange_%s' % language_code)
actions.add('LanguageOptions_SpellCheckLanguageChange_%s' % language_code) | [
"def",
"AddComputedActions",
"(",
"actions",
")",
":",
"# Actions for back_forward_menu_model.cc.",
"for",
"dir",
"in",
"(",
"'BackMenu_'",
",",
"'ForwardMenu_'",
")",
":",
"actions",
".",
"add",
"(",
"dir",
"+",
"'ShowFullHistory'",
")",
"actions",
".",
"add",
"(",
"dir",
"+",
"'Popup'",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"20",
")",
":",
"actions",
".",
"add",
"(",
"dir",
"+",
"'HistoryClick'",
"+",
"str",
"(",
"i",
")",
")",
"actions",
".",
"add",
"(",
"dir",
"+",
"'ChapterClick'",
"+",
"str",
"(",
"i",
")",
")",
"# Actions for new_tab_ui.cc.",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"10",
")",
":",
"actions",
".",
"add",
"(",
"'MostVisited%d'",
"%",
"i",
")",
"# Actions for safe_browsing_blocking_page.cc.",
"for",
"interstitial",
"in",
"(",
"'Phishing'",
",",
"'Malware'",
",",
"'Multiple'",
")",
":",
"for",
"action",
"in",
"(",
"'Show'",
",",
"'Proceed'",
",",
"'DontProceed'",
")",
":",
"actions",
".",
"add",
"(",
"'SBInterstitial%s%s'",
"%",
"(",
"interstitial",
",",
"action",
")",
")",
"# Actions for language_options_handler.cc (Chrome OS specific).",
"for",
"input_method_id",
"in",
"INPUT_METHOD_IDS",
":",
"actions",
".",
"add",
"(",
"'LanguageOptions_DisableInputMethod_%s'",
"%",
"input_method_id",
")",
"actions",
".",
"add",
"(",
"'LanguageOptions_EnableInputMethod_%s'",
"%",
"input_method_id",
")",
"actions",
".",
"add",
"(",
"'InputMethodOptions_Open_%s'",
"%",
"input_method_id",
")",
"for",
"language_code",
"in",
"LANGUAGE_CODES",
":",
"actions",
".",
"add",
"(",
"'LanguageOptions_UiLanguageChange_%s'",
"%",
"language_code",
")",
"actions",
".",
"add",
"(",
"'LanguageOptions_SpellCheckLanguageChange_%s'",
"%",
"language_code",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/chrome/tools/extract_actions.py#L108-L139 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib2to3/pytree.py | python | Base.prev_sibling | (self) | The node immediately preceding the invocant in their parent's children
list. If the invocant does not have a previous sibling, it is None. | The node immediately preceding the invocant in their parent's children
list. If the invocant does not have a previous sibling, it is None. | [
"The",
"node",
"immediately",
"preceding",
"the",
"invocant",
"in",
"their",
"parent",
"s",
"children",
"list",
".",
"If",
"the",
"invocant",
"does",
"not",
"have",
"a",
"previous",
"sibling",
"it",
"is",
"None",
"."
] | def prev_sibling(self):
"""
The node immediately preceding the invocant in their parent's children
list. If the invocant does not have a previous sibling, it is None.
"""
if self.parent is None:
return None
# Can't use index(); we need to test by identity
for i, child in enumerate(self.parent.children):
if child is self:
if i == 0:
return None
return self.parent.children[i-1] | [
"def",
"prev_sibling",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
"is",
"None",
":",
"return",
"None",
"# Can't use index(); we need to test by identity",
"for",
"i",
",",
"child",
"in",
"enumerate",
"(",
"self",
".",
"parent",
".",
"children",
")",
":",
"if",
"child",
"is",
"self",
":",
"if",
"i",
"==",
"0",
":",
"return",
"None",
"return",
"self",
".",
"parent",
".",
"children",
"[",
"i",
"-",
"1",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib2to3/pytree.py#L200-L213 | ||
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/column_accessor.py | python | ColumnAccessor.insert | (
self, name: Any, value: Any, loc: int = -1, validate: bool = True
) | Insert column into the ColumnAccessor at the specified location.
Parameters
----------
name : Name corresponding to the new column
value : column-like
loc : int, optional
The location to insert the new value at.
Must be (0 <= loc <= ncols). By default, the column is added
to the end.
Returns
-------
None, this function operates in-place. | Insert column into the ColumnAccessor at the specified location. | [
"Insert",
"column",
"into",
"the",
"ColumnAccessor",
"at",
"the",
"specified",
"location",
"."
] | def insert(
self, name: Any, value: Any, loc: int = -1, validate: bool = True
):
"""
Insert column into the ColumnAccessor at the specified location.
Parameters
----------
name : Name corresponding to the new column
value : column-like
loc : int, optional
The location to insert the new value at.
Must be (0 <= loc <= ncols). By default, the column is added
to the end.
Returns
-------
None, this function operates in-place.
"""
name = self._pad_key(name)
ncols = len(self._data)
if loc == -1:
loc = ncols
if not (0 <= loc <= ncols):
raise ValueError(
"insert: loc out of bounds: must be 0 <= loc <= ncols"
)
# TODO: we should move all insert logic here
if name in self._data:
raise ValueError(f"Cannot insert '{name}', already exists")
if loc == len(self._data):
if validate:
value = column.as_column(value)
if len(self._data) > 0:
if len(value) != self._column_length:
raise ValueError("All columns must be of equal length")
else:
self._column_length = len(value)
self._data[name] = value
else:
new_keys = self.names[:loc] + (name,) + self.names[loc:]
new_values = self.columns[:loc] + (value,) + self.columns[loc:]
self._data = self._data.__class__(zip(new_keys, new_values))
self._clear_cache() | [
"def",
"insert",
"(",
"self",
",",
"name",
":",
"Any",
",",
"value",
":",
"Any",
",",
"loc",
":",
"int",
"=",
"-",
"1",
",",
"validate",
":",
"bool",
"=",
"True",
")",
":",
"name",
"=",
"self",
".",
"_pad_key",
"(",
"name",
")",
"ncols",
"=",
"len",
"(",
"self",
".",
"_data",
")",
"if",
"loc",
"==",
"-",
"1",
":",
"loc",
"=",
"ncols",
"if",
"not",
"(",
"0",
"<=",
"loc",
"<=",
"ncols",
")",
":",
"raise",
"ValueError",
"(",
"\"insert: loc out of bounds: must be 0 <= loc <= ncols\"",
")",
"# TODO: we should move all insert logic here",
"if",
"name",
"in",
"self",
".",
"_data",
":",
"raise",
"ValueError",
"(",
"f\"Cannot insert '{name}', already exists\"",
")",
"if",
"loc",
"==",
"len",
"(",
"self",
".",
"_data",
")",
":",
"if",
"validate",
":",
"value",
"=",
"column",
".",
"as_column",
"(",
"value",
")",
"if",
"len",
"(",
"self",
".",
"_data",
")",
">",
"0",
":",
"if",
"len",
"(",
"value",
")",
"!=",
"self",
".",
"_column_length",
":",
"raise",
"ValueError",
"(",
"\"All columns must be of equal length\"",
")",
"else",
":",
"self",
".",
"_column_length",
"=",
"len",
"(",
"value",
")",
"self",
".",
"_data",
"[",
"name",
"]",
"=",
"value",
"else",
":",
"new_keys",
"=",
"self",
".",
"names",
"[",
":",
"loc",
"]",
"+",
"(",
"name",
",",
")",
"+",
"self",
".",
"names",
"[",
"loc",
":",
"]",
"new_values",
"=",
"self",
".",
"columns",
"[",
":",
"loc",
"]",
"+",
"(",
"value",
",",
")",
"+",
"self",
".",
"columns",
"[",
"loc",
":",
"]",
"self",
".",
"_data",
"=",
"self",
".",
"_data",
".",
"__class__",
"(",
"zip",
"(",
"new_keys",
",",
"new_values",
")",
")",
"self",
".",
"_clear_cache",
"(",
")"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/column_accessor.py#L261-L305 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/boost/boost_1_68_0/tools/build/src/build/project.py | python | ProjectAttributes.dump | (self) | Prints the project attributes. | Prints the project attributes. | [
"Prints",
"the",
"project",
"attributes",
"."
] | def dump(self):
"""Prints the project attributes."""
id = self.get("id")
if not id:
id = "(none)"
else:
id = id[0]
parent = self.get("parent")
if not parent:
parent = "(none)"
else:
parent = parent[0]
print "'%s'" % id
print "Parent project:%s", parent
print "Requirements:%s", self.get("requirements")
print "Default build:%s", string.join(self.get("debuild-build"))
print "Source location:%s", string.join(self.get("source-location"))
print "Projects to build:%s", string.join(self.get("projects-to-build").sort()); | [
"def",
"dump",
"(",
"self",
")",
":",
"id",
"=",
"self",
".",
"get",
"(",
"\"id\"",
")",
"if",
"not",
"id",
":",
"id",
"=",
"\"(none)\"",
"else",
":",
"id",
"=",
"id",
"[",
"0",
"]",
"parent",
"=",
"self",
".",
"get",
"(",
"\"parent\"",
")",
"if",
"not",
"parent",
":",
"parent",
"=",
"\"(none)\"",
"else",
":",
"parent",
"=",
"parent",
"[",
"0",
"]",
"print",
"\"'%s'\"",
"%",
"id",
"print",
"\"Parent project:%s\"",
",",
"parent",
"print",
"\"Requirements:%s\"",
",",
"self",
".",
"get",
"(",
"\"requirements\"",
")",
"print",
"\"Default build:%s\"",
",",
"string",
".",
"join",
"(",
"self",
".",
"get",
"(",
"\"debuild-build\"",
")",
")",
"print",
"\"Source location:%s\"",
",",
"string",
".",
"join",
"(",
"self",
".",
"get",
"(",
"\"source-location\"",
")",
")",
"print",
"\"Projects to build:%s\"",
",",
"string",
".",
"join",
"(",
"self",
".",
"get",
"(",
"\"projects-to-build\"",
")",
".",
"sort",
"(",
")",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/boost/boost_1_68_0/tools/build/src/build/project.py#L954-L973 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_controls.py | python | HelpEvent.SetPosition | (*args, **kwargs) | return _controls_.HelpEvent_SetPosition(*args, **kwargs) | SetPosition(self, Point pos)
Sets the left-click position of the mouse, in screen coordinates. | SetPosition(self, Point pos) | [
"SetPosition",
"(",
"self",
"Point",
"pos",
")"
] | def SetPosition(*args, **kwargs):
"""
SetPosition(self, Point pos)
Sets the left-click position of the mouse, in screen coordinates.
"""
return _controls_.HelpEvent_SetPosition(*args, **kwargs) | [
"def",
"SetPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"HelpEvent_SetPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L6051-L6057 | |
Tokutek/mongo | 0653eabe2c5b9d12b4814617cb7fb2d799937a0f | buildscripts/moduleconfig.py | python | discover_modules | (module_root) | return found_modules | Scans module_root for subdirectories that look like MongoDB modules.
Returns a list of imported build.py module objects. | Scans module_root for subdirectories that look like MongoDB modules. | [
"Scans",
"module_root",
"for",
"subdirectories",
"that",
"look",
"like",
"MongoDB",
"modules",
"."
] | def discover_modules(module_root):
"""Scans module_root for subdirectories that look like MongoDB modules.
Returns a list of imported build.py module objects.
"""
found_modules = []
if not os.path.isdir(module_root):
return found_modules
for name in os.listdir(module_root):
root = os.path.join(module_root, name)
if name.startswith('.') or not os.path.isdir(root):
continue
build_py = os.path.join(root, 'build.py')
module = None
if os.path.isfile(build_py):
print "adding module: %s" % name
fp = open(build_py, "r")
try:
module = imp.load_module("module_" + name, fp, build_py,
(".py", "r", imp.PY_SOURCE))
if getattr(module, "name", None) is None:
module.name = name
found_modules.append(module)
finally:
fp.close()
return found_modules | [
"def",
"discover_modules",
"(",
"module_root",
")",
":",
"found_modules",
"=",
"[",
"]",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"module_root",
")",
":",
"return",
"found_modules",
"for",
"name",
"in",
"os",
".",
"listdir",
"(",
"module_root",
")",
":",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"module_root",
",",
"name",
")",
"if",
"name",
".",
"startswith",
"(",
"'.'",
")",
"or",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"root",
")",
":",
"continue",
"build_py",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"'build.py'",
")",
"module",
"=",
"None",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"build_py",
")",
":",
"print",
"\"adding module: %s\"",
"%",
"name",
"fp",
"=",
"open",
"(",
"build_py",
",",
"\"r\"",
")",
"try",
":",
"module",
"=",
"imp",
".",
"load_module",
"(",
"\"module_\"",
"+",
"name",
",",
"fp",
",",
"build_py",
",",
"(",
"\".py\"",
",",
"\"r\"",
",",
"imp",
".",
"PY_SOURCE",
")",
")",
"if",
"getattr",
"(",
"module",
",",
"\"name\"",
",",
"None",
")",
"is",
"None",
":",
"module",
".",
"name",
"=",
"name",
"found_modules",
".",
"append",
"(",
"module",
")",
"finally",
":",
"fp",
".",
"close",
"(",
")",
"return",
"found_modules"
] | https://github.com/Tokutek/mongo/blob/0653eabe2c5b9d12b4814617cb7fb2d799937a0f/buildscripts/moduleconfig.py#L33-L63 | |
apiaryio/drafter | 4634ebd07f6c6f257cc656598ccd535492fdfb55 | tools/gyp/buildbot/buildbot_run.py | python | PrepareCmake | () | Build CMake 2.8.8 since the version in Precise is 2.8.7. | Build CMake 2.8.8 since the version in Precise is 2.8.7. | [
"Build",
"CMake",
"2",
".",
"8",
".",
"8",
"since",
"the",
"version",
"in",
"Precise",
"is",
"2",
".",
"8",
".",
"7",
"."
] | def PrepareCmake():
"""Build CMake 2.8.8 since the version in Precise is 2.8.7."""
if os.environ['BUILDBOT_CLOBBER'] == '1':
print '@@@BUILD_STEP Clobber CMake checkout@@@'
shutil.rmtree(CMAKE_DIR)
# We always build CMake 2.8.8, so no need to do anything
# if the directory already exists.
if os.path.isdir(CMAKE_DIR):
return
print '@@@BUILD_STEP Initialize CMake checkout@@@'
os.mkdir(CMAKE_DIR)
print '@@@BUILD_STEP Sync CMake@@@'
CallSubProcess(
['git', 'clone',
'--depth', '1',
'--single-branch',
'--branch', 'v2.8.8',
'--',
'git://cmake.org/cmake.git',
CMAKE_DIR],
cwd=CMAKE_DIR)
print '@@@BUILD_STEP Build CMake@@@'
CallSubProcess(
['/bin/bash', 'bootstrap', '--prefix=%s' % CMAKE_DIR],
cwd=CMAKE_DIR)
CallSubProcess( ['make', 'cmake'], cwd=CMAKE_DIR) | [
"def",
"PrepareCmake",
"(",
")",
":",
"if",
"os",
".",
"environ",
"[",
"'BUILDBOT_CLOBBER'",
"]",
"==",
"'1'",
":",
"print",
"'@@@BUILD_STEP Clobber CMake checkout@@@'",
"shutil",
".",
"rmtree",
"(",
"CMAKE_DIR",
")",
"# We always build CMake 2.8.8, so no need to do anything",
"# if the directory already exists.",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"CMAKE_DIR",
")",
":",
"return",
"print",
"'@@@BUILD_STEP Initialize CMake checkout@@@'",
"os",
".",
"mkdir",
"(",
"CMAKE_DIR",
")",
"print",
"'@@@BUILD_STEP Sync CMake@@@'",
"CallSubProcess",
"(",
"[",
"'git'",
",",
"'clone'",
",",
"'--depth'",
",",
"'1'",
",",
"'--single-branch'",
",",
"'--branch'",
",",
"'v2.8.8'",
",",
"'--'",
",",
"'git://cmake.org/cmake.git'",
",",
"CMAKE_DIR",
"]",
",",
"cwd",
"=",
"CMAKE_DIR",
")",
"print",
"'@@@BUILD_STEP Build CMake@@@'",
"CallSubProcess",
"(",
"[",
"'/bin/bash'",
",",
"'bootstrap'",
",",
"'--prefix=%s'",
"%",
"CMAKE_DIR",
"]",
",",
"cwd",
"=",
"CMAKE_DIR",
")",
"CallSubProcess",
"(",
"[",
"'make'",
",",
"'cmake'",
"]",
",",
"cwd",
"=",
"CMAKE_DIR",
")"
] | https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/buildbot/buildbot_run.py#L31-L61 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/closure_linter/closure_linter/requireprovidesorter.py | python | RequireProvideSorter.CheckProvides | (self, token) | return None | Checks alphabetization of goog.provide statements.
Iterates over tokens in given token stream, identifies goog.provide tokens,
and checks that they occur in alphabetical order by the object being
provided.
Args:
token: A token in the token stream before any goog.provide tokens.
Returns:
The first provide token in the token stream.
None is returned if all goog.provide statements are already sorted. | Checks alphabetization of goog.provide statements. | [
"Checks",
"alphabetization",
"of",
"goog",
".",
"provide",
"statements",
"."
] | def CheckProvides(self, token):
"""Checks alphabetization of goog.provide statements.
Iterates over tokens in given token stream, identifies goog.provide tokens,
and checks that they occur in alphabetical order by the object being
provided.
Args:
token: A token in the token stream before any goog.provide tokens.
Returns:
The first provide token in the token stream.
None is returned if all goog.provide statements are already sorted.
"""
provide_tokens = self._GetRequireOrProvideTokens(token, 'goog.provide')
provide_strings = self._GetRequireOrProvideTokenStrings(provide_tokens)
sorted_provide_strings = sorted(provide_strings)
if provide_strings != sorted_provide_strings:
return provide_tokens[0]
return None | [
"def",
"CheckProvides",
"(",
"self",
",",
"token",
")",
":",
"provide_tokens",
"=",
"self",
".",
"_GetRequireOrProvideTokens",
"(",
"token",
",",
"'goog.provide'",
")",
"provide_strings",
"=",
"self",
".",
"_GetRequireOrProvideTokenStrings",
"(",
"provide_tokens",
")",
"sorted_provide_strings",
"=",
"sorted",
"(",
"provide_strings",
")",
"if",
"provide_strings",
"!=",
"sorted_provide_strings",
":",
"return",
"provide_tokens",
"[",
"0",
"]",
"return",
"None"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/closure_linter/closure_linter/requireprovidesorter.py#L46-L66 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/indexes/base.py | python | Index._get_grouper_for_level | (self, mapper, level=None) | return grouper, None, None | Get index grouper corresponding to an index level
Parameters
----------
mapper: Group mapping function or None
Function mapping index values to groups
level : int or None
Index level
Returns
-------
grouper : Index
Index of values to group on.
labels : ndarray of int or None
Array of locations in level_index.
uniques : Index or None
Index of unique values for level. | Get index grouper corresponding to an index level | [
"Get",
"index",
"grouper",
"corresponding",
"to",
"an",
"index",
"level"
] | def _get_grouper_for_level(self, mapper, level=None):
"""
Get index grouper corresponding to an index level
Parameters
----------
mapper: Group mapping function or None
Function mapping index values to groups
level : int or None
Index level
Returns
-------
grouper : Index
Index of values to group on.
labels : ndarray of int or None
Array of locations in level_index.
uniques : Index or None
Index of unique values for level.
"""
assert level is None or level == 0
if mapper is None:
grouper = self
else:
grouper = self.map(mapper)
return grouper, None, None | [
"def",
"_get_grouper_for_level",
"(",
"self",
",",
"mapper",
",",
"level",
"=",
"None",
")",
":",
"assert",
"level",
"is",
"None",
"or",
"level",
"==",
"0",
"if",
"mapper",
"is",
"None",
":",
"grouper",
"=",
"self",
"else",
":",
"grouper",
"=",
"self",
".",
"map",
"(",
"mapper",
")",
"return",
"grouper",
",",
"None",
",",
"None"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/indexes/base.py#L1909-L1935 | |
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/boost_1.75.0/tools/build/src/build/virtual_target.py | python | VirtualTargetRegistry.add_suffix | (self, specified_name, file_type, prop_set) | Appends the suffix appropriate to 'type/property_set' combination
to the specified name and returns the result. | Appends the suffix appropriate to 'type/property_set' combination
to the specified name and returns the result. | [
"Appends",
"the",
"suffix",
"appropriate",
"to",
"type",
"/",
"property_set",
"combination",
"to",
"the",
"specified",
"name",
"and",
"returns",
"the",
"result",
"."
] | def add_suffix (self, specified_name, file_type, prop_set):
""" Appends the suffix appropriate to 'type/property_set' combination
to the specified name and returns the result.
"""
assert isinstance(specified_name, basestring)
assert isinstance(file_type, basestring)
assert isinstance(prop_set, property_set.PropertySet)
suffix = b2.build.type.generated_target_suffix (file_type, prop_set)
if suffix:
return specified_name + '.' + suffix
else:
return specified_name | [
"def",
"add_suffix",
"(",
"self",
",",
"specified_name",
",",
"file_type",
",",
"prop_set",
")",
":",
"assert",
"isinstance",
"(",
"specified_name",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"file_type",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"prop_set",
",",
"property_set",
".",
"PropertySet",
")",
"suffix",
"=",
"b2",
".",
"build",
".",
"type",
".",
"generated_target_suffix",
"(",
"file_type",
",",
"prop_set",
")",
"if",
"suffix",
":",
"return",
"specified_name",
"+",
"'.'",
"+",
"suffix",
"else",
":",
"return",
"specified_name"
] | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/boost_1.75.0/tools/build/src/build/virtual_target.py#L248-L261 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/sched.py | python | scheduler.queue | (self) | return map(heapq.heappop, [events]*len(events)) | An ordered list of upcoming events.
Events are named tuples with fields for:
time, priority, action, arguments | An ordered list of upcoming events. | [
"An",
"ordered",
"list",
"of",
"upcoming",
"events",
"."
] | def queue(self):
"""An ordered list of upcoming events.
Events are named tuples with fields for:
time, priority, action, arguments
"""
# Use heapq to sort the queue rather than using 'sorted(self._queue)'.
# With heapq, two events scheduled at the same time will show in
# the actual order they would be retrieved.
events = self._queue[:]
return map(heapq.heappop, [events]*len(events)) | [
"def",
"queue",
"(",
"self",
")",
":",
"# Use heapq to sort the queue rather than using 'sorted(self._queue)'.",
"# With heapq, two events scheduled at the same time will show in",
"# the actual order they would be retrieved.",
"events",
"=",
"self",
".",
"_queue",
"[",
":",
"]",
"return",
"map",
"(",
"heapq",
".",
"heappop",
",",
"[",
"events",
"]",
"*",
"len",
"(",
"events",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/sched.py#L123-L134 | |
bareos/bareos | 56a10bb368b0a81e977bb51304033fe49d59efb0 | restapi/bareos_restapi/__init__.py | python | post_pool | (
*,
poolDef: poolResource = Body(..., title="pool resource"),
response: Response,
current_user: User = Depends(get_current_user),
) | return configure_add_standard_component(
componentDef=poolDef,
response=response,
current_user=current_user,
componentType="pool",
) | Create a new pool resource.
Console command used: _configure add pool_ | Create a new pool resource.
Console command used: _configure add pool_ | [
"Create",
"a",
"new",
"pool",
"resource",
".",
"Console",
"command",
"used",
":",
"_configure",
"add",
"pool_"
] | def post_pool(
*,
poolDef: poolResource = Body(..., title="pool resource"),
response: Response,
current_user: User = Depends(get_current_user),
):
"""
Create a new pool resource.
Console command used: _configure add pool_
"""
return configure_add_standard_component(
componentDef=poolDef,
response=response,
current_user=current_user,
componentType="pool",
) | [
"def",
"post_pool",
"(",
"*",
",",
"poolDef",
":",
"poolResource",
"=",
"Body",
"(",
"...",
",",
"title",
"=",
"\"pool resource\"",
")",
",",
"response",
":",
"Response",
",",
"current_user",
":",
"User",
"=",
"Depends",
"(",
"get_current_user",
")",
",",
")",
":",
"return",
"configure_add_standard_component",
"(",
"componentDef",
"=",
"poolDef",
",",
"response",
"=",
"response",
",",
"current_user",
"=",
"current_user",
",",
"componentType",
"=",
"\"pool\"",
",",
")"
] | https://github.com/bareos/bareos/blob/56a10bb368b0a81e977bb51304033fe49d59efb0/restapi/bareos_restapi/__init__.py#L1503-L1518 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBProcess.GetNumRestartedReasonsFromEvent | (event) | return _lldb.SBProcess_GetNumRestartedReasonsFromEvent(event) | GetNumRestartedReasonsFromEvent(SBEvent event) -> size_t | GetNumRestartedReasonsFromEvent(SBEvent event) -> size_t | [
"GetNumRestartedReasonsFromEvent",
"(",
"SBEvent",
"event",
")",
"-",
">",
"size_t"
] | def GetNumRestartedReasonsFromEvent(event):
"""GetNumRestartedReasonsFromEvent(SBEvent event) -> size_t"""
return _lldb.SBProcess_GetNumRestartedReasonsFromEvent(event) | [
"def",
"GetNumRestartedReasonsFromEvent",
"(",
"event",
")",
":",
"return",
"_lldb",
".",
"SBProcess_GetNumRestartedReasonsFromEvent",
"(",
"event",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L8659-L8661 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/xml/sax/handler.py | python | ContentHandler.skippedEntity | (self, name) | Receive notification of a skipped entity.
The Parser will invoke this method once for each entity
skipped. Non-validating processors may skip entities if they
have not seen the declarations (because, for example, the
entity was declared in an external DTD subset). All processors
may skip external entities, depending on the values of the
http://xml.org/sax/features/external-general-entities and the
http://xml.org/sax/features/external-parameter-entities
properties. | Receive notification of a skipped entity. | [
"Receive",
"notification",
"of",
"a",
"skipped",
"entity",
"."
] | def skippedEntity(self, name):
"""Receive notification of a skipped entity.
The Parser will invoke this method once for each entity
skipped. Non-validating processors may skip entities if they
have not seen the declarations (because, for example, the
entity was declared in an external DTD subset). All processors
may skip external entities, depending on the values of the
http://xml.org/sax/features/external-general-entities and the
http://xml.org/sax/features/external-parameter-entities
properties.""" | [
"def",
"skippedEntity",
"(",
"self",
",",
"name",
")",
":"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/xml/sax/handler.py#L193-L203 | ||
vnpy/vnpy | f50f2535ed39dd33272e0985ed40c7078e4c19f6 | vnpy/trader/ui/mainwindow.py | python | MainWindow.restore_window_setting | (self) | Restore window to default setting. | Restore window to default setting. | [
"Restore",
"window",
"to",
"default",
"setting",
"."
] | def restore_window_setting(self) -> None:
"""
Restore window to default setting.
"""
self.load_window_setting("default")
self.showMaximized() | [
"def",
"restore_window_setting",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"load_window_setting",
"(",
"\"default\"",
")",
"self",
".",
"showMaximized",
"(",
")"
] | https://github.com/vnpy/vnpy/blob/f50f2535ed39dd33272e0985ed40c7078e4c19f6/vnpy/trader/ui/mainwindow.py#L310-L315 | ||
glotzerlab/hoomd-blue | f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a | hoomd/md/pair/pair.py | python | Pair.nlist | (self) | return self._nlist | Neighbor list used to compute the pair potential. | Neighbor list used to compute the pair potential. | [
"Neighbor",
"list",
"used",
"to",
"compute",
"the",
"pair",
"potential",
"."
] | def nlist(self):
"""Neighbor list used to compute the pair potential."""
return self._nlist | [
"def",
"nlist",
"(",
"self",
")",
":",
"return",
"self",
".",
"_nlist"
] | https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/md/pair/pair.py#L275-L277 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_gdi.py | python | FontEnumerator.EnumerateFacenames | (*args, **kwargs) | return _gdi_.FontEnumerator_EnumerateFacenames(*args, **kwargs) | EnumerateFacenames(self, int encoding=FONTENCODING_SYSTEM, bool fixedWidthOnly=False) -> bool | EnumerateFacenames(self, int encoding=FONTENCODING_SYSTEM, bool fixedWidthOnly=False) -> bool | [
"EnumerateFacenames",
"(",
"self",
"int",
"encoding",
"=",
"FONTENCODING_SYSTEM",
"bool",
"fixedWidthOnly",
"=",
"False",
")",
"-",
">",
"bool"
] | def EnumerateFacenames(*args, **kwargs):
"""EnumerateFacenames(self, int encoding=FONTENCODING_SYSTEM, bool fixedWidthOnly=False) -> bool"""
return _gdi_.FontEnumerator_EnumerateFacenames(*args, **kwargs) | [
"def",
"EnumerateFacenames",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"FontEnumerator_EnumerateFacenames",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L2661-L2663 | |
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/gdal.py | python | Group.CreateAttribute | (self, *args) | return _gdal.Group_CreateAttribute(self, *args) | r"""CreateAttribute(Group self, char const * name, int nDimensions, ExtendedDataType data_type, char ** options=None) -> Attribute | r"""CreateAttribute(Group self, char const * name, int nDimensions, ExtendedDataType data_type, char ** options=None) -> Attribute | [
"r",
"CreateAttribute",
"(",
"Group",
"self",
"char",
"const",
"*",
"name",
"int",
"nDimensions",
"ExtendedDataType",
"data_type",
"char",
"**",
"options",
"=",
"None",
")",
"-",
">",
"Attribute"
] | def CreateAttribute(self, *args):
r"""CreateAttribute(Group self, char const * name, int nDimensions, ExtendedDataType data_type, char ** options=None) -> Attribute"""
return _gdal.Group_CreateAttribute(self, *args) | [
"def",
"CreateAttribute",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_gdal",
".",
"Group_CreateAttribute",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L2655-L2657 | |
p4lang/PI | 38d87e81253feff9fff0660d662c885be78fb719 | tools/cpplint.py | python | _CppLintState.PrintErrorCounts | (self) | Print a summary of errors by category, and the total. | Print a summary of errors by category, and the total. | [
"Print",
"a",
"summary",
"of",
"errors",
"by",
"category",
"and",
"the",
"total",
"."
] | def PrintErrorCounts(self):
"""Print a summary of errors by category, and the total."""
for category, count in sorted(iteritems(self.errors_by_category)):
self.PrintInfo('Category \'%s\' errors found: %d\n' %
(category, count))
if self.error_count > 0:
self.PrintInfo('Total errors found: %d\n' % self.error_count) | [
"def",
"PrintErrorCounts",
"(",
"self",
")",
":",
"for",
"category",
",",
"count",
"in",
"sorted",
"(",
"iteritems",
"(",
"self",
".",
"errors_by_category",
")",
")",
":",
"self",
".",
"PrintInfo",
"(",
"'Category \\'%s\\' errors found: %d\\n'",
"%",
"(",
"category",
",",
"count",
")",
")",
"if",
"self",
".",
"error_count",
">",
"0",
":",
"self",
".",
"PrintInfo",
"(",
"'Total errors found: %d\\n'",
"%",
"self",
".",
"error_count",
")"
] | https://github.com/p4lang/PI/blob/38d87e81253feff9fff0660d662c885be78fb719/tools/cpplint.py#L1345-L1351 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | AnyButton.GetBitmapHover | (*args, **kwargs) | return _controls_.AnyButton_GetBitmapHover(*args, **kwargs) | GetBitmapHover(self) -> Bitmap | GetBitmapHover(self) -> Bitmap | [
"GetBitmapHover",
"(",
"self",
")",
"-",
">",
"Bitmap"
] | def GetBitmapHover(*args, **kwargs):
"""GetBitmapHover(self) -> Bitmap"""
return _controls_.AnyButton_GetBitmapHover(*args, **kwargs) | [
"def",
"GetBitmapHover",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"AnyButton_GetBitmapHover",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L129-L131 | |
hunterlew/mstar_deeplearning_project | 3761624dcbd7d44af257200542d13d1444dc634a | classification/caffe/build/Release/pycaffe/caffe/io.py | python | Transformer.set_raw_scale | (self, in_, scale) | Set the scale of raw features s.t. the input blob = input * scale.
While Python represents images in [0, 1], certain Caffe models
like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale
of these models must be 255.
Parameters
----------
in_ : which input to assign this scale factor
scale : scale coefficient | Set the scale of raw features s.t. the input blob = input * scale.
While Python represents images in [0, 1], certain Caffe models
like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale
of these models must be 255. | [
"Set",
"the",
"scale",
"of",
"raw",
"features",
"s",
".",
"t",
".",
"the",
"input",
"blob",
"=",
"input",
"*",
"scale",
".",
"While",
"Python",
"represents",
"images",
"in",
"[",
"0",
"1",
"]",
"certain",
"Caffe",
"models",
"like",
"CaffeNet",
"and",
"AlexNet",
"represent",
"images",
"in",
"[",
"0",
"255",
"]",
"so",
"the",
"raw_scale",
"of",
"these",
"models",
"must",
"be",
"255",
"."
] | def set_raw_scale(self, in_, scale):
"""
Set the scale of raw features s.t. the input blob = input * scale.
While Python represents images in [0, 1], certain Caffe models
like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale
of these models must be 255.
Parameters
----------
in_ : which input to assign this scale factor
scale : scale coefficient
"""
self.__check_input(in_)
self.raw_scale[in_] = scale | [
"def",
"set_raw_scale",
"(",
"self",
",",
"in_",
",",
"scale",
")",
":",
"self",
".",
"__check_input",
"(",
"in_",
")",
"self",
".",
"raw_scale",
"[",
"in_",
"]",
"=",
"scale"
] | https://github.com/hunterlew/mstar_deeplearning_project/blob/3761624dcbd7d44af257200542d13d1444dc634a/classification/caffe/build/Release/pycaffe/caffe/io.py#L221-L234 | ||
rrwick/Unicycler | 96ffea71e3a78d63ade19d6124946773e65cf129 | unicycler/alignment.py | python | Alignment.setup_using_sam | (self, sam_line, read_dict, reference_dict) | This function sets up the Alignment using a SAM line. | This function sets up the Alignment using a SAM line. | [
"This",
"function",
"sets",
"up",
"the",
"Alignment",
"using",
"a",
"SAM",
"line",
"."
] | def setup_using_sam(self, sam_line, read_dict, reference_dict):
"""
This function sets up the Alignment using a SAM line.
"""
sam_parts = sam_line.split('\t', 6)
self.rev_comp = bool(int(sam_parts[1]) & 0x10)
self.cigar_parts = re.findall(r'\d+\w', sam_parts[5])
self.read = read_dict[sam_parts[0]]
self.read_start_pos = self.get_start_soft_clips()
self.read_end_pos = self.read.get_length() - self.get_end_soft_clips()
self.read_end_gap = self.get_end_soft_clips()
self.ref = reference_dict[get_nice_header(sam_parts[2])]
self.ref_start_pos = int(sam_parts[3]) - 1
self.ref_end_pos = self.ref_start_pos
for cigar_part in self.cigar_parts:
self.ref_end_pos += get_ref_shift_from_cigar_part(cigar_part)
# If all is good with the CIGAR, then we should never end up with a ref_end_pos out of the
# reference range. But we check just to be safe.
if self.ref_end_pos > len(self.ref.sequence):
self.ref_end_pos = len(self.ref.sequence) | [
"def",
"setup_using_sam",
"(",
"self",
",",
"sam_line",
",",
"read_dict",
",",
"reference_dict",
")",
":",
"sam_parts",
"=",
"sam_line",
".",
"split",
"(",
"'\\t'",
",",
"6",
")",
"self",
".",
"rev_comp",
"=",
"bool",
"(",
"int",
"(",
"sam_parts",
"[",
"1",
"]",
")",
"&",
"0x10",
")",
"self",
".",
"cigar_parts",
"=",
"re",
".",
"findall",
"(",
"r'\\d+\\w'",
",",
"sam_parts",
"[",
"5",
"]",
")",
"self",
".",
"read",
"=",
"read_dict",
"[",
"sam_parts",
"[",
"0",
"]",
"]",
"self",
".",
"read_start_pos",
"=",
"self",
".",
"get_start_soft_clips",
"(",
")",
"self",
".",
"read_end_pos",
"=",
"self",
".",
"read",
".",
"get_length",
"(",
")",
"-",
"self",
".",
"get_end_soft_clips",
"(",
")",
"self",
".",
"read_end_gap",
"=",
"self",
".",
"get_end_soft_clips",
"(",
")",
"self",
".",
"ref",
"=",
"reference_dict",
"[",
"get_nice_header",
"(",
"sam_parts",
"[",
"2",
"]",
")",
"]",
"self",
".",
"ref_start_pos",
"=",
"int",
"(",
"sam_parts",
"[",
"3",
"]",
")",
"-",
"1",
"self",
".",
"ref_end_pos",
"=",
"self",
".",
"ref_start_pos",
"for",
"cigar_part",
"in",
"self",
".",
"cigar_parts",
":",
"self",
".",
"ref_end_pos",
"+=",
"get_ref_shift_from_cigar_part",
"(",
"cigar_part",
")",
"# If all is good with the CIGAR, then we should never end up with a ref_end_pos out of the",
"# reference range. But we check just to be safe.",
"if",
"self",
".",
"ref_end_pos",
">",
"len",
"(",
"self",
".",
"ref",
".",
"sequence",
")",
":",
"self",
".",
"ref_end_pos",
"=",
"len",
"(",
"self",
".",
"ref",
".",
"sequence",
")"
] | https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/unicycler/alignment.py#L118-L140 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/normal.py | python | Normal.batch_shape | (self, name="batch_shape") | Batch dimensions of this instance as a 1-D int32 `Tensor`.
The product of the dimensions of the `batch_shape` is the number of
independent distributions of this kind the instance represents.
Args:
name: name to give to the op.
Returns:
`Tensor` `batch_shape` | Batch dimensions of this instance as a 1-D int32 `Tensor`. | [
"Batch",
"dimensions",
"of",
"this",
"instance",
"as",
"a",
"1",
"-",
"D",
"int32",
"Tensor",
"."
] | def batch_shape(self, name="batch_shape"):
"""Batch dimensions of this instance as a 1-D int32 `Tensor`.
The product of the dimensions of the `batch_shape` is the number of
independent distributions of this kind the instance represents.
Args:
name: name to give to the op.
Returns:
`Tensor` `batch_shape`
"""
with ops.name_scope(self.name):
with ops.op_scope([], name):
return array_ops.shape(self._ones()) | [
"def",
"batch_shape",
"(",
"self",
",",
"name",
"=",
"\"batch_shape\"",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"self",
".",
"name",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"]",
",",
"name",
")",
":",
"return",
"array_ops",
".",
"shape",
"(",
"self",
".",
"_ones",
"(",
")",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/normal.py#L142-L156 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.