nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/MRInspectData.py | python | fit_2d_peak | (workspace) | return [x_min, x_max], [y_min, y_max] | Fit a 2D Gaussian peak
:param workspace: workspace to work with | Fit a 2D Gaussian peak
:param workspace: workspace to work with | [
"Fit",
"a",
"2D",
"Gaussian",
"peak",
":",
"param",
"workspace",
":",
"workspace",
"to",
"work",
"with"
] | def fit_2d_peak(workspace):
"""
Fit a 2D Gaussian peak
:param workspace: workspace to work with
"""
n_x = int(workspace.getInstrument().getNumberParameter("number-of-x-pixels")[0])
n_y = int(workspace.getInstrument().getNumberParameter("number-of-y-pixels")[0])
# Prepare data to fit
_integrated = mantid.simpleapi.Integration(InputWorkspace=workspace)
signal = _integrated.extractY()
z=np.reshape(signal, (n_x, n_y))
x = np.arange(0, n_x)
y = np.arange(0, n_y)
_x, _y = np.meshgrid(x, y)
_x = _x.T
_y = _y.T
code = coord_to_code(_x, _y).ravel()
data_to_fit = z.ravel()
err_y = np.sqrt(np.fabs(data_to_fit))
err_y[err_y<1] = 1
# Use the highest data point as a starting point for a simple Gaussian fit
x_dist = np.sum(z, 1)
y_dist = np.sum(z, 0)
center_x = np.argmax(x_dist)
center_y = np.argmax(y_dist)
# Gaussian fit
p0 = [np.max(z), center_x, 5, center_y, 50, 0]
try:
gauss_coef, _ = opt.curve_fit(gauss_simple, code, data_to_fit, p0=p0, sigma=err_y)
except:
logger.notice("Could not fit simple Gaussian")
gauss_coef = p0
# Keep track of the result
th = gauss_simple(code, *gauss_coef)
th = np.reshape(th, (n_x, n_y))
_chi2 = chi2(th, z)
guess_x = gauss_coef[1]
guess_wx = 2.0 * gauss_coef[2]
guess_y = gauss_coef[3]
guess_wy = 2.0 * gauss_coef[4]
guess_chi2 = _chi2
# Fit a polynomial background, as a starting point to fitting signal + background
try:
step_coef, _ = opt.curve_fit(poly_bck, code, data_to_fit, p0=[0, 0, 0, center_x, 0], sigma=err_y)
except:
logger.notice("Could not fit polynomial background")
step_coef = [0, 0, 0, center_x, 0]
th = poly_bck(code, *step_coef)
th = np.reshape(th, (n_x, n_y))
# Now fit a Gaussian + background
# A, mu_x, sigma_x, mu_y, sigma_y, poly_a, poly_b, poly_c, center, background
coef = [np.max(z), center_x, 5, center_y, 50,
step_coef[0], step_coef[1], step_coef[2], step_coef[3], step_coef[4]]
try:
coef, _ = opt.curve_fit(poly_bck_signal, code, data_to_fit, p0=coef, sigma=err_y)
except:
logger.notice("Could not fit Gaussian + polynomial")
th = poly_bck_signal(code, *coef)
th = np.reshape(th, (n_x, n_y))
_chi2 = chi2(th, z)
if _chi2 < guess_chi2:
guess_x = coef[1]
guess_wx = 2.0 * coef[2]
guess_y = coef[3]
guess_wy = 2.0 * coef[4]
guess_chi2 = _chi2
# Package the best results
x_min = max(0, int(guess_x-np.fabs(guess_wx)))
x_max = min(n_x-1, int(guess_x+np.fabs(guess_wx)))
y_min = max(0, int(guess_y-np.fabs(guess_wy)))
y_max = min(n_y-1, int(guess_y+np.fabs(guess_wy)))
return [x_min, x_max], [y_min, y_max] | [
"def",
"fit_2d_peak",
"(",
"workspace",
")",
":",
"n_x",
"=",
"int",
"(",
"workspace",
".",
"getInstrument",
"(",
")",
".",
"getNumberParameter",
"(",
"\"number-of-x-pixels\"",
")",
"[",
"0",
"]",
")",
"n_y",
"=",
"int",
"(",
"workspace",
".",
"getInstrume... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/MRInspectData.py#L437-L517 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/urllib3/util/request.py | python | set_file_position | (body, pos) | return pos | If a position is provided, move file to that point.
Otherwise, we'll attempt to record a position for future use. | If a position is provided, move file to that point.
Otherwise, we'll attempt to record a position for future use. | [
"If",
"a",
"position",
"is",
"provided",
"move",
"file",
"to",
"that",
"point",
".",
"Otherwise",
"we",
"ll",
"attempt",
"to",
"record",
"a",
"position",
"for",
"future",
"use",
"."
] | def set_file_position(body, pos):
"""
If a position is provided, move file to that point.
Otherwise, we'll attempt to record a position for future use.
"""
if pos is not None:
rewind_body(body, pos)
elif getattr(body, "tell", None) is not None:
try:
pos = body.tell()
except (IOError, OSError):
# This differentiates from None, allowing us to catch
# a failed `tell()` later when trying to rewind the body.
pos = _FAILEDTELL
return pos | [
"def",
"set_file_position",
"(",
"body",
",",
"pos",
")",
":",
"if",
"pos",
"is",
"not",
"None",
":",
"rewind_body",
"(",
"body",
",",
"pos",
")",
"elif",
"getattr",
"(",
"body",
",",
"\"tell\"",
",",
"None",
")",
"is",
"not",
"None",
":",
"try",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/urllib3/util/request.py#L90-L105 | |
sailing-pmls/bosen | 06cb58902d011fbea5f9428f10ce30e621492204 | style_script/cpplint.py | python | CheckRedundantOverrideOrFinal | (filename, clean_lines, linenum, error) | Check if line contains a redundant "override" or "final" virt-specifier.
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. | Check if line contains a redundant "override" or "final" virt-specifier. | [
"Check",
"if",
"line",
"contains",
"a",
"redundant",
"override",
"or",
"final",
"virt",
"-",
"specifier",
"."
] | def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):
"""Check if line contains a redundant "override" or "final" virt-specifier.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Look for closing parenthesis nearby. We need one to confirm where
# the declarator ends and where the virt-specifier starts to avoid
# false positives.
line = clean_lines.elided[linenum]
declarator_end = line.rfind(')')
if declarator_end >= 0:
fragment = line[declarator_end:]
else:
if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:
fragment = line
else:
return
# Check that at most one of "override" or "final" is present, not both
if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment):
error(filename, linenum, 'readability/inheritance', 4,
('"override" is redundant since function is '
'already declared as "final"')) | [
"def",
"CheckRedundantOverrideOrFinal",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"# Look for closing parenthesis nearby. We need one to confirm where",
"# the declarator ends and where the virt-specifier starts to avoid",
"# false positives.",
"line... | https://github.com/sailing-pmls/bosen/blob/06cb58902d011fbea5f9428f10ce30e621492204/style_script/cpplint.py#L5811-L5837 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/chigger/base/ColorMap.py | python | ColorMap.__default | (self) | return lut | Build Peacock style colormap. | Build Peacock style colormap. | [
"Build",
"Peacock",
"style",
"colormap",
"."
] | def __default(self):
"""
Build Peacock style colormap.
"""
n = self.getOption('cmap_num_colors')
lut = vtk.vtkLookupTable()
if self.getOption('cmap_reverse'):
lut.SetHueRange(0.0, 0.667)
else:
lut.SetHueRange(0.667, 0.0)
lut.SetNumberOfColors(n)
return lut | [
"def",
"__default",
"(",
"self",
")",
":",
"n",
"=",
"self",
".",
"getOption",
"(",
"'cmap_num_colors'",
")",
"lut",
"=",
"vtk",
".",
"vtkLookupTable",
"(",
")",
"if",
"self",
".",
"getOption",
"(",
"'cmap_reverse'",
")",
":",
"lut",
".",
"SetHueRange",
... | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/chigger/base/ColorMap.py#L109-L120 | |
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_envs/minitaur/envs/motor.py | python | MotorModel.convert_to_torque | (self,
motor_commands,
motor_angle,
motor_velocity,
true_motor_velocity,
kp=None,
kd=None) | return self._convert_to_torque_from_pwm(pwm, true_motor_velocity) | Convert the commands (position control or torque control) to torque.
Args:
motor_commands: The desired motor angle if the motor is in position
control mode. The pwm signal if the motor is in torque control mode.
motor_angle: The motor angle observed at the current time step. It is
actually the true motor angle observed a few milliseconds ago (pd
latency).
motor_velocity: The motor velocity observed at the current time step, it
is actually the true motor velocity a few milliseconds ago (pd latency).
true_motor_velocity: The true motor velocity. The true velocity is used
to compute back EMF voltage and viscous damping.
kp: Proportional gains for the motors' PD controllers. If not provided, it
uses the default kp of the minitaur for all the motors.
kd: Derivative gains for the motors' PD controllers. If not provided, it
uses the default kp of the minitaur for all the motors.
Returns:
actual_torque: The torque that needs to be applied to the motor.
observed_torque: The torque observed by the sensor. | Convert the commands (position control or torque control) to torque. | [
"Convert",
"the",
"commands",
"(",
"position",
"control",
"or",
"torque",
"control",
")",
"to",
"torque",
"."
] | def convert_to_torque(self,
motor_commands,
motor_angle,
motor_velocity,
true_motor_velocity,
kp=None,
kd=None):
"""Convert the commands (position control or torque control) to torque.
Args:
motor_commands: The desired motor angle if the motor is in position
control mode. The pwm signal if the motor is in torque control mode.
motor_angle: The motor angle observed at the current time step. It is
actually the true motor angle observed a few milliseconds ago (pd
latency).
motor_velocity: The motor velocity observed at the current time step, it
is actually the true motor velocity a few milliseconds ago (pd latency).
true_motor_velocity: The true motor velocity. The true velocity is used
to compute back EMF voltage and viscous damping.
kp: Proportional gains for the motors' PD controllers. If not provided, it
uses the default kp of the minitaur for all the motors.
kd: Derivative gains for the motors' PD controllers. If not provided, it
uses the default kp of the minitaur for all the motors.
Returns:
actual_torque: The torque that needs to be applied to the motor.
observed_torque: The torque observed by the sensor.
"""
if self._torque_control_enabled:
pwm = motor_commands
else:
if kp is None:
kp = np.full(NUM_MOTORS, self._kp)
if kd is None:
kd = np.full(NUM_MOTORS, self._kd)
pwm = -1 * kp * (motor_angle - motor_commands) - kd * motor_velocity
pwm = np.clip(pwm, -1.0, 1.0)
return self._convert_to_torque_from_pwm(pwm, true_motor_velocity) | [
"def",
"convert_to_torque",
"(",
"self",
",",
"motor_commands",
",",
"motor_angle",
",",
"motor_velocity",
",",
"true_motor_velocity",
",",
"kp",
"=",
"None",
",",
"kd",
"=",
"None",
")",
":",
"if",
"self",
".",
"_torque_control_enabled",
":",
"pwm",
"=",
"m... | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/envs/motor.py#L74-L112 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/__init__.py | python | connect_logs | (aws_access_key_id=None,
aws_secret_access_key=None,
**kwargs) | return CloudWatchLogsConnection(
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key,
**kwargs
) | Connect to Amazon CloudWatch Logs
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
rtype: :class:`boto.kinesis.layer1.CloudWatchLogsConnection`
:return: A connection to the Amazon CloudWatch Logs service | Connect to Amazon CloudWatch Logs | [
"Connect",
"to",
"Amazon",
"CloudWatch",
"Logs"
] | def connect_logs(aws_access_key_id=None,
aws_secret_access_key=None,
**kwargs):
"""
Connect to Amazon CloudWatch Logs
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
rtype: :class:`boto.kinesis.layer1.CloudWatchLogsConnection`
:return: A connection to the Amazon CloudWatch Logs service
"""
from boto.logs.layer1 import CloudWatchLogsConnection
return CloudWatchLogsConnection(
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key,
**kwargs
) | [
"def",
"connect_logs",
"(",
"aws_access_key_id",
"=",
"None",
",",
"aws_secret_access_key",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"boto",
".",
"logs",
".",
"layer1",
"import",
"CloudWatchLogsConnection",
"return",
"CloudWatchLogsConnection",
"(",... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/__init__.py#L863-L883 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/_vendor/ordered_set.py | python | OrderedSet.difference | (self, *sets) | return cls(items) | Returns all elements that are in this set but not the others.
Example:
>>> OrderedSet([1, 2, 3]).difference(OrderedSet([2]))
OrderedSet([1, 3])
>>> OrderedSet([1, 2, 3]).difference(OrderedSet([2]), OrderedSet([3]))
OrderedSet([1])
>>> OrderedSet([1, 2, 3]) - OrderedSet([2])
OrderedSet([1, 3])
>>> OrderedSet([1, 2, 3]).difference()
OrderedSet([1, 2, 3]) | Returns all elements that are in this set but not the others. | [
"Returns",
"all",
"elements",
"that",
"are",
"in",
"this",
"set",
"but",
"not",
"the",
"others",
"."
] | def difference(self, *sets):
"""
Returns all elements that are in this set but not the others.
Example:
>>> OrderedSet([1, 2, 3]).difference(OrderedSet([2]))
OrderedSet([1, 3])
>>> OrderedSet([1, 2, 3]).difference(OrderedSet([2]), OrderedSet([3]))
OrderedSet([1])
>>> OrderedSet([1, 2, 3]) - OrderedSet([2])
OrderedSet([1, 3])
>>> OrderedSet([1, 2, 3]).difference()
OrderedSet([1, 2, 3])
"""
cls = self.__class__
if sets:
other = set.union(*map(set, sets))
items = (item for item in self if item not in other)
else:
items = self
return cls(items) | [
"def",
"difference",
"(",
"self",
",",
"*",
"sets",
")",
":",
"cls",
"=",
"self",
".",
"__class__",
"if",
"sets",
":",
"other",
"=",
"set",
".",
"union",
"(",
"*",
"map",
"(",
"set",
",",
"sets",
")",
")",
"items",
"=",
"(",
"item",
"for",
"ite... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/_vendor/ordered_set.py#L355-L375 | |
grpc/grpc-web | ce7d734e8a1a7d1f09fd6bdb23299f3ef7447887 | packages/grpc-web/scripts/common.py | python | get_files_with_suffix | (root_dir: str, suffix: str) | Yields file names under a directory with a given suffix. | Yields file names under a directory with a given suffix. | [
"Yields",
"file",
"names",
"under",
"a",
"directory",
"with",
"a",
"given",
"suffix",
"."
] | def get_files_with_suffix(root_dir: str, suffix: str) -> Iterator[str]:
"""Yields file names under a directory with a given suffix."""
for dir_path, _, file_names in os.walk(root_dir):
for file_name in file_names:
if file_name.endswith(suffix):
yield os.path.join(dir_path, file_name) | [
"def",
"get_files_with_suffix",
"(",
"root_dir",
":",
"str",
",",
"suffix",
":",
"str",
")",
"->",
"Iterator",
"[",
"str",
"]",
":",
"for",
"dir_path",
",",
"_",
",",
"file_names",
"in",
"os",
".",
"walk",
"(",
"root_dir",
")",
":",
"for",
"file_name",... | https://github.com/grpc/grpc-web/blob/ce7d734e8a1a7d1f09fd6bdb23299f3ef7447887/packages/grpc-web/scripts/common.py#L40-L45 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/python_gflags/gflags.py | python | RegisterValidator | (flag_name,
checker,
message='Flag validation failed',
flag_values=FLAGS) | Adds a constraint, which will be enforced during program execution.
The constraint is validated when flags are initially parsed, and after each
change of the corresponding flag's value.
Args:
flag_name: string, name of the flag to be checked.
checker: method to validate the flag.
input - value of the corresponding flag (string, boolean, etc.
This value will be passed to checker by the library). See file's
docstring for examples.
output - Boolean.
Must return True if validator constraint is satisfied.
If constraint is not satisfied, it should either return False or
raise gflags_validators.Error(desired_error_message).
message: error text to be shown to the user if checker returns False.
If checker raises gflags_validators.Error, message from the raised
Error will be shown.
flag_values: FlagValues
Raises:
AttributeError: if flag_name is not registered as a valid flag name. | Adds a constraint, which will be enforced during program execution. | [
"Adds",
"a",
"constraint",
"which",
"will",
"be",
"enforced",
"during",
"program",
"execution",
"."
] | def RegisterValidator(flag_name,
checker,
message='Flag validation failed',
flag_values=FLAGS):
"""Adds a constraint, which will be enforced during program execution.
The constraint is validated when flags are initially parsed, and after each
change of the corresponding flag's value.
Args:
flag_name: string, name of the flag to be checked.
checker: method to validate the flag.
input - value of the corresponding flag (string, boolean, etc.
This value will be passed to checker by the library). See file's
docstring for examples.
output - Boolean.
Must return True if validator constraint is satisfied.
If constraint is not satisfied, it should either return False or
raise gflags_validators.Error(desired_error_message).
message: error text to be shown to the user if checker returns False.
If checker raises gflags_validators.Error, message from the raised
Error will be shown.
flag_values: FlagValues
Raises:
AttributeError: if flag_name is not registered as a valid flag name.
"""
flag_values.AddValidator(gflags_validators.SimpleValidator(flag_name,
checker,
message)) | [
"def",
"RegisterValidator",
"(",
"flag_name",
",",
"checker",
",",
"message",
"=",
"'Flag validation failed'",
",",
"flag_values",
"=",
"FLAGS",
")",
":",
"flag_values",
".",
"AddValidator",
"(",
"gflags_validators",
".",
"SimpleValidator",
"(",
"flag_name",
",",
... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/python_gflags/gflags.py#L2082-L2109 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/robotsim.py | python | PointCloud.addProperty | (self, *args) | return _robotsim.PointCloud_addProperty(self, *args) | r"""
Adds a new property with name pname, and sets values for this property to the
given length-n array.
addProperty (pname)
addProperty (pname,np_array)
Args:
pname (str):
np_array (:obj:`1D Numpy array of floats`, optional): | r"""
Adds a new property with name pname, and sets values for this property to the
given length-n array. | [
"r",
"Adds",
"a",
"new",
"property",
"with",
"name",
"pname",
"and",
"sets",
"values",
"for",
"this",
"property",
"to",
"the",
"given",
"length",
"-",
"n",
"array",
"."
] | def addProperty(self, *args) ->None:
r"""
Adds a new property with name pname, and sets values for this property to the
given length-n array.
addProperty (pname)
addProperty (pname,np_array)
Args:
pname (str):
np_array (:obj:`1D Numpy array of floats`, optional):
"""
return _robotsim.PointCloud_addProperty(self, *args) | [
"def",
"addProperty",
"(",
"self",
",",
"*",
"args",
")",
"->",
"None",
":",
"return",
"_robotsim",
".",
"PointCloud_addProperty",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L1226-L1240 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | NotificationMessage.SetTitle | (*args, **kwargs) | return _misc_.NotificationMessage_SetTitle(*args, **kwargs) | SetTitle(self, String title) | SetTitle(self, String title) | [
"SetTitle",
"(",
"self",
"String",
"title",
")"
] | def SetTitle(*args, **kwargs):
"""SetTitle(self, String title)"""
return _misc_.NotificationMessage_SetTitle(*args, **kwargs) | [
"def",
"SetTitle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"NotificationMessage_SetTitle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L1218-L1220 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/beanstalk/layer1.py | python | Layer1.describe_application_versions | (self, application_name=None,
version_labels=None) | return self._get_response('DescribeApplicationVersions', params) | Returns descriptions for existing application versions.
:type application_name: string
:param application_name: If specified, AWS Elastic Beanstalk restricts
the returned descriptions to only include ones that are associated
with the specified application.
:type version_labels: list
:param version_labels: If specified, restricts the returned
descriptions to only include ones that have the specified version
labels. | Returns descriptions for existing application versions. | [
"Returns",
"descriptions",
"for",
"existing",
"application",
"versions",
"."
] | def describe_application_versions(self, application_name=None,
version_labels=None):
"""Returns descriptions for existing application versions.
:type application_name: string
:param application_name: If specified, AWS Elastic Beanstalk restricts
the returned descriptions to only include ones that are associated
with the specified application.
:type version_labels: list
:param version_labels: If specified, restricts the returned
descriptions to only include ones that have the specified version
labels.
"""
params = {}
if application_name:
params['ApplicationName'] = application_name
if version_labels:
self.build_list_params(params, version_labels,
'VersionLabels.member')
return self._get_response('DescribeApplicationVersions', params) | [
"def",
"describe_application_versions",
"(",
"self",
",",
"application_name",
"=",
"None",
",",
"version_labels",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"application_name",
":",
"params",
"[",
"'ApplicationName'",
"]",
"=",
"application_name",
"if... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/beanstalk/layer1.py#L466-L487 | |
yujinrobot/kobuki | 23748ed3dfb082831ca8eaaef1a0b08588dbcb65 | kobuki_auto_docking/scripts/DockDriveControl.py | python | Controller.__init__ | (self) | # initial values
external_power = DigitalOutput()
external_power.values = [ True, True, True, True ]
external_power.mask = [ True, True, True, True ]
digital_output = DigitalOutput()
digital_output.values = [ True, True, True, True ]
digital_output.mask = [ True, True, True, True ]
leds = []
leds.append(Led())
leds.append(Led())
leds[0].value = Led.GREEN
leds[1].value = Led.GREEN
# initialize outputs
while not pub_ext_pwr.get_num_connections():
rate.sleep()
pub_ext_pwr.publish(external_power)
while not pub_dgt_out.get_num_connections():
rate.sleep()
pub_dgt_out.publish(digital_output)
while not pub[0].get_num_connections():
rate.sleep()
pub[0].publish(leds[0])
while not pub[1].get_num_connections():
rate.sleep()
pub[1].publish(leds[1]) | # initial values
external_power = DigitalOutput()
external_power.values = [ True, True, True, True ]
external_power.mask = [ True, True, True, True ]
digital_output = DigitalOutput()
digital_output.values = [ True, True, True, True ]
digital_output.mask = [ True, True, True, True ]
leds = []
leds.append(Led())
leds.append(Led())
leds[0].value = Led.GREEN
leds[1].value = Led.GREEN
# initialize outputs
while not pub_ext_pwr.get_num_connections():
rate.sleep()
pub_ext_pwr.publish(external_power)
while not pub_dgt_out.get_num_connections():
rate.sleep()
pub_dgt_out.publish(digital_output)
while not pub[0].get_num_connections():
rate.sleep()
pub[0].publish(leds[0])
while not pub[1].get_num_connections():
rate.sleep()
pub[1].publish(leds[1]) | [
"#",
"initial",
"values",
"external_power",
"=",
"DigitalOutput",
"()",
"external_power",
".",
"values",
"=",
"[",
"True",
"True",
"True",
"True",
"]",
"external_power",
".",
"mask",
"=",
"[",
"True",
"True",
"True",
"True",
"]",
"digital_output",
"=",
"Digi... | def __init__(self):
#rospy initial setup
rospy.init_node("dock_drive_control")
rospy.on_shutdown(self.clearing)
rate = rospy.Rate(10)
self.message = "Idle"
self.publish_cmd_vel=False
self.cmd_vel=Twist()
self.sensors = SensorState()
self.dock_ir = DockInfraRed()
self.bat_name = self.getBatteryName()
self.state = "N/A"
self.percentage = 0.0
self.pub = {
# 'enable':rospy.Publisher('/enable', String),
# 'disable':rospy.Publisher('/disable', String),
'motor_power':rospy.Publisher('/mobile_base/commands/motor_power',MotorPower),
# 'do_dock':rospy.Publisher('/dock_drive/commands/do_dock', Empty),
# 'cancel_dock':rospy.Publisher('/dock_drive/commands/cancel_dock', Empty),
'debug':rospy.Publisher('/dock_drive/debug/mode_shift', String),
'external_power':rospy.Publisher('/mobile_base/commands/external_power',ExternalPower),
'digital_output':rospy.Publisher('/mobile_base/commands/digital_output',DigitalOutput),
'led1':rospy.Publisher('/mobile_base/commands/led1',Led),
'led2':rospy.Publisher('/mobile_base/commands/led2',Led),
'sound':rospy.Publisher('/mobile_base/commands/sound',Sound),
'cmd_vel':rospy.Publisher('/mobile_base/commands/velocity',Twist),
}
self.sub = {
'core':rospy.Subscriber('/mobile_base/sensors/core', SensorState, self.sensorsCallback),
'dock_ir':rospy.Subscriber('/mobile_base/sensors/dock_ir', DockInfraRed, self.dockIRCallback),
}
self.keyBindings = {
'1':(self.pub['debug'].publish, String('enable') ,'enable'),
'2':(self.pub['debug'].publish, String('run') ,'run'),
'3':(self.pub['debug'].publish, String('stop') ,'stop'),
'4':(self.pub['debug'].publish, String('disable'),'disable'),
'5':5,
'6':6,
'7':7,
'8':'eight',
'9':'nine',
'0':'null',
# 'e':(self.pub['motor_power'].publish,MotorPower(MotorPower.ON),'enabled'),
# 'r':(self.pub['motor_power'].publish,MotorPower(MotorPower.OFF),'disabled'),
'e':(self.toggleMotor,True,'enabled'),
'r':(self.toggleMotor,False,'disabled'),
' ':(self.resetVel,'','resetted'),
'a':(self.pub['sound'].publish,Sound(Sound.ON),'sound.on'),
's':(self.pub['sound'].publish,Sound(Sound.OFF),'sound.off'),
'd':(self.pub['sound'].publish,Sound(Sound.RECHARGE),'sound.recharge'),
'f':(self.pub['sound'].publish,Sound(Sound.BUTTON),'sound.button'),
'z':(self.pub['sound'].publish,Sound(Sound.ERROR),'sound.error'),
'x':(self.pub['sound'].publish,Sound(Sound.CLEANINGSTART),'sound.cleaningstart'),
'c':(self.pub['sound'].publish,Sound(Sound.CLEANINGEND),'sound.cleaningend'),
'q':(rospy.signal_shutdown,'user reuest','quit'),
'Q':(rospy.signal_shutdown,'user reuest','quit'),
}
rospy.Timer(rospy.Duration(0.1), self.keyopCallback)
if len(self.bat_name) > 0:
rospy.Timer(rospy.Duration(1.0), self.batteryCallback)
rospy.Timer(rospy.Duration(1.0), self.stateCallback) # to check status of rostopics
self.printFront()
'''
# initial values
external_power = DigitalOutput()
external_power.values = [ True, True, True, True ]
external_power.mask = [ True, True, True, True ]
digital_output = DigitalOutput()
digital_output.values = [ True, True, True, True ]
digital_output.mask = [ True, True, True, True ]
leds = []
leds.append(Led())
leds.append(Led())
leds[0].value = Led.GREEN
leds[1].value = Led.GREEN
# initialize outputs
while not pub_ext_pwr.get_num_connections():
rate.sleep()
pub_ext_pwr.publish(external_power)
while not pub_dgt_out.get_num_connections():
rate.sleep()
pub_dgt_out.publish(digital_output)
while not pub[0].get_num_connections():
rate.sleep()
pub[0].publish(leds[0])
while not pub[1].get_num_connections():
rate.sleep()
pub[1].publish(leds[1])
''' | [
"def",
"__init__",
"(",
"self",
")",
":",
"#rospy initial setup",
"rospy",
".",
"init_node",
"(",
"\"dock_drive_control\"",
")",
"rospy",
".",
"on_shutdown",
"(",
"self",
".",
"clearing",
")",
"rate",
"=",
"rospy",
".",
"Rate",
"(",
"10",
")",
"self",
".",... | https://github.com/yujinrobot/kobuki/blob/23748ed3dfb082831ca8eaaef1a0b08588dbcb65/kobuki_auto_docking/scripts/DockDriveControl.py#L70-L166 | ||
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | bindings/python/cntk/ops/__init__.py | python | cosh | (x, name='') | return cosh(x, name) | Computes the element-wise cosh of ``x``:
The output tensor has the same shape as ``x``.
Example:
>>> np.round(C.cosh([[1,0.5],[-0.25,-0.75]]).eval(),5)
array([[ 1.54308, 1.12763],
[ 1.03141, 1.29468]], dtype=float32)
Args:
x: numpy array or any :class:`~cntk.ops.functions.Function` that outputs a tensor
name (str, optional): the name of the Function instance in the network
Returns:
:class:`~cntk.ops.functions.Function` | Computes the element-wise cosh of ``x``: | [
"Computes",
"the",
"element",
"-",
"wise",
"cosh",
"of",
"x",
":"
] | def cosh(x, name=''):
'''
Computes the element-wise cosh of ``x``:
The output tensor has the same shape as ``x``.
Example:
>>> np.round(C.cosh([[1,0.5],[-0.25,-0.75]]).eval(),5)
array([[ 1.54308, 1.12763],
[ 1.03141, 1.29468]], dtype=float32)
Args:
x: numpy array or any :class:`~cntk.ops.functions.Function` that outputs a tensor
name (str, optional): the name of the Function instance in the network
Returns:
:class:`~cntk.ops.functions.Function`
'''
from cntk.cntk_py import cosh
x = sanitize_input(x)
return cosh(x, name) | [
"def",
"cosh",
"(",
"x",
",",
"name",
"=",
"''",
")",
":",
"from",
"cntk",
".",
"cntk_py",
"import",
"cosh",
"x",
"=",
"sanitize_input",
"(",
"x",
")",
"return",
"cosh",
"(",
"x",
",",
"name",
")"
] | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/ops/__init__.py#L1835-L1854 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/httplib2/python2/httplib2/socks.py | python | socksocket.__negotiatehttp | (self, destaddr, destport) | __negotiatehttp(self,destaddr,destport)
Negotiates a connection through an HTTP server. | __negotiatehttp(self,destaddr,destport)
Negotiates a connection through an HTTP server. | [
"__negotiatehttp",
"(",
"self",
"destaddr",
"destport",
")",
"Negotiates",
"a",
"connection",
"through",
"an",
"HTTP",
"server",
"."
] | def __negotiatehttp(self, destaddr, destport):
"""__negotiatehttp(self,destaddr,destport)
Negotiates a connection through an HTTP server.
"""
# If we need to resolve locally, we do this now
if not self.__proxy[3]:
addr = socket.gethostbyname(destaddr)
else:
addr = destaddr
headers = ["CONNECT ", addr, ":", str(destport), " HTTP/1.1\r\n"]
headers += ["Host: ", destaddr, "\r\n"]
if (self.__proxy[4] != None and self.__proxy[5] != None):
headers += [self.__getauthheader(), "\r\n"]
headers.append("\r\n")
self.sendall("".join(headers).encode())
# We read the response until we get the string "\r\n\r\n"
resp = self.recv(1)
while resp.find("\r\n\r\n".encode()) == -1:
resp = resp + self.recv(1)
# We just need the first line to check if the connection
# was successful
statusline = resp.splitlines()[0].split(" ".encode(), 2)
if statusline[0] not in ("HTTP/1.0".encode(), "HTTP/1.1".encode()):
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
try:
statuscode = int(statusline[1])
except ValueError:
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
if statuscode != 200:
self.close()
raise HTTPError((statuscode, statusline[2]))
self.__proxysockname = ("0.0.0.0", 0)
self.__proxypeername = (addr, destport) | [
"def",
"__negotiatehttp",
"(",
"self",
",",
"destaddr",
",",
"destport",
")",
":",
"# If we need to resolve locally, we do this now",
"if",
"not",
"self",
".",
"__proxy",
"[",
"3",
"]",
":",
"addr",
"=",
"socket",
".",
"gethostbyname",
"(",
"destaddr",
")",
"e... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/httplib2/python2/httplib2/socks.py#L358-L392 | ||
ArduPilot/ardupilot | 6e684b3496122b8158ac412b609d00004b7ac306 | libraries/SITL/examples/JSON/pybullet/robot.py | python | quaternion_from_AP | (q) | return [q.q[1], -q.q[2], -q.q[3], q.q[0]] | convert ArduPilot quaternion to pybullet quaternion | convert ArduPilot quaternion to pybullet quaternion | [
"convert",
"ArduPilot",
"quaternion",
"to",
"pybullet",
"quaternion"
] | def quaternion_from_AP(q):
'''convert ArduPilot quaternion to pybullet quaternion'''
return [q.q[1], -q.q[2], -q.q[3], q.q[0]] | [
"def",
"quaternion_from_AP",
"(",
"q",
")",
":",
"return",
"[",
"q",
".",
"q",
"[",
"1",
"]",
",",
"-",
"q",
".",
"q",
"[",
"2",
"]",
",",
"-",
"q",
".",
"q",
"[",
"3",
"]",
",",
"q",
".",
"q",
"[",
"0",
"]",
"]"
] | https://github.com/ArduPilot/ardupilot/blob/6e684b3496122b8158ac412b609d00004b7ac306/libraries/SITL/examples/JSON/pybullet/robot.py#L129-L131 | |
apache/mesos | 97d9a4063332aae3825d78de71611657e05cf5e2 | support/cpplint.py | python | _FunctionState.End | (self) | Stop analyzing function body. | Stop analyzing function body. | [
"Stop",
"analyzing",
"function",
"body",
"."
] | def End(self):
"""Stop analyzing function body."""
self.in_a_function = False | [
"def",
"End",
"(",
"self",
")",
":",
"self",
".",
"in_a_function",
"=",
"False"
] | https://github.com/apache/mesos/blob/97d9a4063332aae3825d78de71611657e05cf5e2/support/cpplint.py#L1092-L1094 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/turtle.py | python | TPen.pensize | (self, width=None) | Set or return the line thickness.
Aliases: pensize | width
Argument:
width -- positive number
Set the line thickness to width or return it. If resizemode is set
to "auto" and turtleshape is a polygon, that polygon is drawn with
the same line thickness. If no argument is given, current pensize
is returned.
Example (for a Turtle instance named turtle):
>>> turtle.pensize()
1
>>> turtle.pensize(10) # from here on lines of width 10 are drawn | Set or return the line thickness. | [
"Set",
"or",
"return",
"the",
"line",
"thickness",
"."
] | def pensize(self, width=None):
"""Set or return the line thickness.
Aliases: pensize | width
Argument:
width -- positive number
Set the line thickness to width or return it. If resizemode is set
to "auto" and turtleshape is a polygon, that polygon is drawn with
the same line thickness. If no argument is given, current pensize
is returned.
Example (for a Turtle instance named turtle):
>>> turtle.pensize()
1
>>> turtle.pensize(10) # from here on lines of width 10 are drawn
"""
if width is None:
return self._pensize
self.pen(pensize=width) | [
"def",
"pensize",
"(",
"self",
",",
"width",
"=",
"None",
")",
":",
"if",
"width",
"is",
"None",
":",
"return",
"self",
".",
"_pensize",
"self",
".",
"pen",
"(",
"pensize",
"=",
"width",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/turtle.py#L2072-L2092 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/SimpleHTTPServer.py | python | SimpleHTTPRequestHandler.guess_type | (self, path) | Guess the type of a file.
Argument is a PATH (a filename).
Return value is a string of the form type/subtype,
usable for a MIME Content-type header.
The default implementation looks the file's extension
up in the table self.extensions_map, using application/octet-stream
as a default; however it would be permissible (if
slow) to look inside the data to make a better guess. | Guess the type of a file. | [
"Guess",
"the",
"type",
"of",
"a",
"file",
"."
] | def guess_type(self, path):
"""Guess the type of a file.
Argument is a PATH (a filename).
Return value is a string of the form type/subtype,
usable for a MIME Content-type header.
The default implementation looks the file's extension
up in the table self.extensions_map, using application/octet-stream
as a default; however it would be permissible (if
slow) to look inside the data to make a better guess.
"""
base, ext = posixpath.splitext(path)
if ext in self.extensions_map:
return self.extensions_map[ext]
ext = ext.lower()
if ext in self.extensions_map:
return self.extensions_map[ext]
else:
return self.extensions_map[''] | [
"def",
"guess_type",
"(",
"self",
",",
"path",
")",
":",
"base",
",",
"ext",
"=",
"posixpath",
".",
"splitext",
"(",
"path",
")",
"if",
"ext",
"in",
"self",
".",
"extensions_map",
":",
"return",
"self",
".",
"extensions_map",
"[",
"ext",
"]",
"ext",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/SimpleHTTPServer.py#L179-L201 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBTypeFilter.IsEqualTo | (self, *args) | return _lldb.SBTypeFilter_IsEqualTo(self, *args) | IsEqualTo(self, SBTypeFilter rhs) -> bool | IsEqualTo(self, SBTypeFilter rhs) -> bool | [
"IsEqualTo",
"(",
"self",
"SBTypeFilter",
"rhs",
")",
"-",
">",
"bool"
] | def IsEqualTo(self, *args):
"""IsEqualTo(self, SBTypeFilter rhs) -> bool"""
return _lldb.SBTypeFilter_IsEqualTo(self, *args) | [
"def",
"IsEqualTo",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_lldb",
".",
"SBTypeFilter_IsEqualTo",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L11107-L11109 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/training/adadelta.py | python | AdadeltaOptimizer.__init__ | (self, learning_rate=0.001, rho=0.95, epsilon=1e-8,
use_locking=False, name="Adadelta") | Construct a new Adadelta optimizer.
Args:
learning_rate: A `Tensor` or a floating point value. The learning rate.
rho: A `Tensor` or a floating point value. The decay rate.
epsilon: A `Tensor` or a floating point value. A constant epsilon used
to better conditioning the grad update.
use_locking: If `True` use locks for update operations.
name: Optional name prefix for the operations created when applying
gradients. Defaults to "Adadelta". | Construct a new Adadelta optimizer. | [
"Construct",
"a",
"new",
"Adadelta",
"optimizer",
"."
] | def __init__(self, learning_rate=0.001, rho=0.95, epsilon=1e-8,
use_locking=False, name="Adadelta"):
"""Construct a new Adadelta optimizer.
Args:
learning_rate: A `Tensor` or a floating point value. The learning rate.
rho: A `Tensor` or a floating point value. The decay rate.
epsilon: A `Tensor` or a floating point value. A constant epsilon used
to better conditioning the grad update.
use_locking: If `True` use locks for update operations.
name: Optional name prefix for the operations created when applying
gradients. Defaults to "Adadelta".
"""
super(AdadeltaOptimizer, self).__init__(use_locking, name)
self._lr = learning_rate
self._rho = rho
self._epsilon = epsilon
# Tensor versions of the constructor arguments, created in _prepare().
self._lr_t = None
self._rho_t = None
self._epsilon_t = None | [
"def",
"__init__",
"(",
"self",
",",
"learning_rate",
"=",
"0.001",
",",
"rho",
"=",
"0.95",
",",
"epsilon",
"=",
"1e-8",
",",
"use_locking",
"=",
"False",
",",
"name",
"=",
"\"Adadelta\"",
")",
":",
"super",
"(",
"AdadeltaOptimizer",
",",
"self",
")",
... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/training/adadelta.py#L36-L57 | ||
kismetwireless/kismet | a7c0dc270c960fb1f58bd9cec4601c201885fd4e | capture_sdr_rtladsb/KismetCaptureRtladsb/__init__.py | python | KismetRtladsb.adsb_msg_get_airborne_velocity | (self, data) | return velocity | Airborne velocity from message 17, synthesized from EW/NS velocities | Airborne velocity from message 17, synthesized from EW/NS velocities | [
"Airborne",
"velocity",
"from",
"message",
"17",
"synthesized",
"from",
"EW",
"/",
"NS",
"velocities"
] | def adsb_msg_get_airborne_velocity(self, data):
"""
Airborne velocity from message 17, synthesized from EW/NS velocities
"""
ew_dir = (data[5] & 4) >> 2
ew_velocity = ((data[5] & 3) << 8) | data[6]
ns_dir = (data[7] & 0x80) >> 7
ns_velocity = ((data[7] & 0x7f) << 3) | ((data[8] & 0xe0) >> 5)
# Compute velocity from two speed components
velocity = math.sqrt(ns_velocity * ns_velocity + ew_velocity * ew_velocity)
return velocity | [
"def",
"adsb_msg_get_airborne_velocity",
"(",
"self",
",",
"data",
")",
":",
"ew_dir",
"=",
"(",
"data",
"[",
"5",
"]",
"&",
"4",
")",
">>",
"2",
"ew_velocity",
"=",
"(",
"(",
"data",
"[",
"5",
"]",
"&",
"3",
")",
"<<",
"8",
")",
"|",
"data",
"... | https://github.com/kismetwireless/kismet/blob/a7c0dc270c960fb1f58bd9cec4601c201885fd4e/capture_sdr_rtladsb/KismetCaptureRtladsb/__init__.py#L878-L891 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing.py | python | ParseResults.getName | (self) | r"""
Returns the results name for this token expression. Useful when several
different expressions might match at a particular location.
Example::
integer = Word(nums)
ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d")
house_number_expr = Suppress('#') + Word(nums, alphanums)
user_data = (Group(house_number_expr)("house_number")
| Group(ssn_expr)("ssn")
| Group(integer)("age"))
user_info = OneOrMore(user_data)
result = user_info.parseString("22 111-22-3333 #221B")
for item in result:
print(item.getName(), ':', item[0])
prints::
age : 22
ssn : 111-22-3333
house_number : 221B | r""" | [
"r"
] | def getName(self):
r"""
Returns the results name for this token expression. Useful when several
different expressions might match at a particular location.
Example::
integer = Word(nums)
ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d")
house_number_expr = Suppress('#') + Word(nums, alphanums)
user_data = (Group(house_number_expr)("house_number")
| Group(ssn_expr)("ssn")
| Group(integer)("age"))
user_info = OneOrMore(user_data)
result = user_info.parseString("22 111-22-3333 #221B")
for item in result:
print(item.getName(), ':', item[0])
prints::
age : 22
ssn : 111-22-3333
house_number : 221B
"""
if self.__name:
return self.__name
elif self.__parent:
par = self.__parent()
if par:
return par.__lookup(self)
else:
return None
elif (len(self) == 1 and
len(self.__tokdict) == 1 and
next(iter(self.__tokdict.values()))[0][1] in (0,-1)):
return next(iter(self.__tokdict.keys()))
else:
return None | [
"def",
"getName",
"(",
"self",
")",
":",
"if",
"self",
".",
"__name",
":",
"return",
"self",
".",
"__name",
"elif",
"self",
".",
"__parent",
":",
"par",
"=",
"self",
".",
"__parent",
"(",
")",
"if",
"par",
":",
"return",
"par",
".",
"__lookup",
"("... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing.py#L1667-L1737 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/ops/rnn_cell.py | python | BasicRNNCell.__call__ | (self, inputs, state, scope=None) | return output, output | Most basic RNN: output = new_state = activation(W * input + U * state + B). | Most basic RNN: output = new_state = activation(W * input + U * state + B). | [
"Most",
"basic",
"RNN",
":",
"output",
"=",
"new_state",
"=",
"activation",
"(",
"W",
"*",
"input",
"+",
"U",
"*",
"state",
"+",
"B",
")",
"."
] | def __call__(self, inputs, state, scope=None):
"""Most basic RNN: output = new_state = activation(W * input + U * state + B)."""
with vs.variable_scope(scope or type(self).__name__): # "BasicRNNCell"
output = self._activation(_linear([inputs, state], self._num_units, True))
return output, output | [
"def",
"__call__",
"(",
"self",
",",
"inputs",
",",
"state",
",",
"scope",
"=",
"None",
")",
":",
"with",
"vs",
".",
"variable_scope",
"(",
"scope",
"or",
"type",
"(",
"self",
")",
".",
"__name__",
")",
":",
"# \"BasicRNNCell\"",
"output",
"=",
"self",... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/rnn_cell.py#L197-L201 | |
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/osr.py | python | SpatialReference.SetGeogCS | (self, *args) | return _osr.SpatialReference_SetGeogCS(self, *args) | r"""SetGeogCS(SpatialReference self, char const * pszGeogName, char const * pszDatumName, char const * pszEllipsoidName, double dfSemiMajor, double dfInvFlattening, char const * pszPMName="Greenwich", double dfPMOffset=0.0, char const * pszUnits="degree", double dfConvertToRadians=0.0174532925199433) -> OGRErr | r"""SetGeogCS(SpatialReference self, char const * pszGeogName, char const * pszDatumName, char const * pszEllipsoidName, double dfSemiMajor, double dfInvFlattening, char const * pszPMName="Greenwich", double dfPMOffset=0.0, char const * pszUnits="degree", double dfConvertToRadians=0.0174532925199433) -> OGRErr | [
"r",
"SetGeogCS",
"(",
"SpatialReference",
"self",
"char",
"const",
"*",
"pszGeogName",
"char",
"const",
"*",
"pszDatumName",
"char",
"const",
"*",
"pszEllipsoidName",
"double",
"dfSemiMajor",
"double",
"dfInvFlattening",
"char",
"const",
"*",
"pszPMName",
"=",
"G... | def SetGeogCS(self, *args):
r"""SetGeogCS(SpatialReference self, char const * pszGeogName, char const * pszDatumName, char const * pszEllipsoidName, double dfSemiMajor, double dfInvFlattening, char const * pszPMName="Greenwich", double dfPMOffset=0.0, char const * pszUnits="degree", double dfConvertToRadians=0.0174532925199433) -> OGRErr"""
return _osr.SpatialReference_SetGeogCS(self, *args) | [
"def",
"SetGeogCS",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_osr",
".",
"SpatialReference_SetGeogCS",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/osr.py#L734-L736 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/deps/v8/tools/sanitizers/sancov_merger.py | python | generate_inputs | (keep, coverage_dir, file_map, cpus) | return inputs | Generate inputs for multiprocessed merging.
Splits the sancov files into several buckets, so that each bucket can be
merged in a separate process. We have only few executables in total with
mostly lots of associated files. In the general case, with many executables
we might need to avoid splitting buckets of executables with few files.
Returns: List of args as expected by merge above. | Generate inputs for multiprocessed merging. | [
"Generate",
"inputs",
"for",
"multiprocessed",
"merging",
"."
] | def generate_inputs(keep, coverage_dir, file_map, cpus):
"""Generate inputs for multiprocessed merging.
Splits the sancov files into several buckets, so that each bucket can be
merged in a separate process. We have only few executables in total with
mostly lots of associated files. In the general case, with many executables
we might need to avoid splitting buckets of executables with few files.
Returns: List of args as expected by merge above.
"""
inputs = []
for executable, files in file_map.iteritems():
# What's the bucket size for distributing files for merging? E.g. with
# 2 cpus and 9 files we want bucket size 5.
n = max(2, int(math.ceil(len(files) / float(cpus))))
# Chop files into buckets.
buckets = [files[i:i+n] for i in range(0, len(files), n)]
# Inputs for multiprocessing. List of tuples containing:
# Keep-files option, base path, executable name, index of bucket,
# list of files.
inputs.extend([(keep, coverage_dir, executable, i, b)
for i, b in enumerate(buckets)])
return inputs | [
"def",
"generate_inputs",
"(",
"keep",
",",
"coverage_dir",
",",
"file_map",
",",
"cpus",
")",
":",
"inputs",
"=",
"[",
"]",
"for",
"executable",
",",
"files",
"in",
"file_map",
".",
"iteritems",
"(",
")",
":",
"# What's the bucket size for distributing files fo... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/tools/sanitizers/sancov_merger.py#L92-L116 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | Validation/RecoTau/python/RecoTauValidation_cfi.py | python | SetYmodulesToLog | (matchingNames = []) | return yLogger | set all modules whose name contains one of the matching names to log y scale | set all modules whose name contains one of the matching names to log y scale | [
"set",
"all",
"modules",
"whose",
"name",
"contains",
"one",
"of",
"the",
"matching",
"names",
"to",
"log",
"y",
"scale"
] | def SetYmodulesToLog(matchingNames = []):
''' set all modules whose name contains one of the matching names to log y scale'''
def yLogger(module):
''' set a module to use log scaling in the yAxis'''
if hasattr(module, 'drawJobs'):
print("EK DEBUG")
drawJobParamGetter = lambda subName : getattr(module.drawJobs, subName)
#for subModule in [getattr(module.drawJobs, subModuleName) for subModuleName in dir(module.drawJobs)]:
attrNames = dir(module.drawJobs)
for subModuleName, subModule in zip(attrNames, map(drawJobParamGetter, attrNames)):
matchedNames = [name for name in matchingNames if subModuleName.find( name) > -1] # matching sub strings
if len(matchingNames) == 0:
matchedNames = ['take','everything','and','dont','bother']
if hasattr(subModule, "yAxis") and len(matchedNames):
print("Setting drawJob: ", subModuleName, " to log scale.")
subModule.yAxis = cms.string('fakeRate') #'fakeRate' configuration specifies the log scaling
if len(matchingNames) == 0:
module.yAxes.efficiency.maxY_log = 40
module.yAxes.fakeRate.maxY_log = 40
return yLogger | [
"def",
"SetYmodulesToLog",
"(",
"matchingNames",
"=",
"[",
"]",
")",
":",
"def",
"yLogger",
"(",
"module",
")",
":",
"''' set a module to use log scaling in the yAxis'''",
"if",
"hasattr",
"(",
"module",
",",
"'drawJobs'",
")",
":",
"print",
"(",
"\"EK DEBUG\"",
... | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Validation/RecoTau/python/RecoTauValidation_cfi.py#L505-L524 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/npyimpl.py | python | _prepare_argument | (ctxt, bld, inp, tyinp, where='input operand') | returns an instance of the appropriate Helper (either
_ScalarHelper or _ArrayHelper) class to handle the argument.
using the polymorphic interface of the Helper classes, scalar
and array cases can be handled with the same code | returns an instance of the appropriate Helper (either
_ScalarHelper or _ArrayHelper) class to handle the argument.
using the polymorphic interface of the Helper classes, scalar
and array cases can be handled with the same code | [
"returns",
"an",
"instance",
"of",
"the",
"appropriate",
"Helper",
"(",
"either",
"_ScalarHelper",
"or",
"_ArrayHelper",
")",
"class",
"to",
"handle",
"the",
"argument",
".",
"using",
"the",
"polymorphic",
"interface",
"of",
"the",
"Helper",
"classes",
"scalar",... | def _prepare_argument(ctxt, bld, inp, tyinp, where='input operand'):
"""returns an instance of the appropriate Helper (either
_ScalarHelper or _ArrayHelper) class to handle the argument.
using the polymorphic interface of the Helper classes, scalar
and array cases can be handled with the same code"""
# first un-Optional Optionals
if isinstance(tyinp, types.Optional):
oty = tyinp
tyinp = tyinp.type
inp = ctxt.cast(bld, inp, oty, tyinp)
# then prepare the arg for a concrete instance
if isinstance(tyinp, types.ArrayCompatible):
ary = ctxt.make_array(tyinp)(ctxt, bld, inp)
shape = cgutils.unpack_tuple(bld, ary.shape, tyinp.ndim)
strides = cgutils.unpack_tuple(bld, ary.strides, tyinp.ndim)
return _ArrayHelper(ctxt, bld, shape, strides, ary.data,
tyinp.layout, tyinp.dtype, tyinp.ndim, inp)
elif types.unliteral(tyinp) in types.number_domain | set([types.boolean]):
return _ScalarHelper(ctxt, bld, inp, tyinp)
else:
raise NotImplementedError('unsupported type for {0}: {1}'.format(where, str(tyinp))) | [
"def",
"_prepare_argument",
"(",
"ctxt",
",",
"bld",
",",
"inp",
",",
"tyinp",
",",
"where",
"=",
"'input operand'",
")",
":",
"# first un-Optional Optionals",
"if",
"isinstance",
"(",
"tyinp",
",",
"types",
".",
"Optional",
")",
":",
"oty",
"=",
"tyinp",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/npyimpl.py#L160-L182 | ||
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/parser.py | python | Parser.parse_for | (self) | return nodes.For(target, iter, body, else_, test,
recursive, lineno=lineno) | Parse a for loop. | Parse a for loop. | [
"Parse",
"a",
"for",
"loop",
"."
] | def parse_for(self):
"""Parse a for loop."""
lineno = self.stream.expect('name:for').lineno
target = self.parse_assign_target(extra_end_rules=('name:in',))
self.stream.expect('name:in')
iter = self.parse_tuple(with_condexpr=False,
extra_end_rules=('name:recursive',))
test = None
if self.stream.skip_if('name:if'):
test = self.parse_expression()
recursive = self.stream.skip_if('name:recursive')
body = self.parse_statements(('name:endfor', 'name:else'))
if next(self.stream).value == 'endfor':
else_ = []
else:
else_ = self.parse_statements(('name:endfor',), drop_needle=True)
return nodes.For(target, iter, body, else_, test,
recursive, lineno=lineno) | [
"def",
"parse_for",
"(",
"self",
")",
":",
"lineno",
"=",
"self",
".",
"stream",
".",
"expect",
"(",
"'name:for'",
")",
".",
"lineno",
"target",
"=",
"self",
".",
"parse_assign_target",
"(",
"extra_end_rules",
"=",
"(",
"'name:in'",
",",
")",
")",
"self"... | 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/parser.py#L178-L195 | |
LisaAnne/lisa-caffe-public | 49b8643ddef23a4f6120017968de30c45e693f59 | tools/extra/resize_and_crop_images.py | python | OpenCVResizeCrop.resize_and_crop_image | (self, input_file, output_file, output_side_length = 256) | Takes an image name, resize it and crop the center square | Takes an image name, resize it and crop the center square | [
"Takes",
"an",
"image",
"name",
"resize",
"it",
"and",
"crop",
"the",
"center",
"square"
] | def resize_and_crop_image(self, input_file, output_file, output_side_length = 256):
'''Takes an image name, resize it and crop the center square
'''
img = cv2.imread(input_file)
height, width, depth = img.shape
new_height = output_side_length
new_width = output_side_length
if height > width:
new_height = output_side_length * height / width
else:
new_width = output_side_length * width / height
resized_img = cv2.resize(img, (new_width, new_height))
height_offset = (new_height - output_side_length) / 2
width_offset = (new_width - output_side_length) / 2
cropped_img = resized_img[height_offset:height_offset + output_side_length,
width_offset:width_offset + output_side_length]
cv2.imwrite(output_file, cropped_img) | [
"def",
"resize_and_crop_image",
"(",
"self",
",",
"input_file",
",",
"output_file",
",",
"output_side_length",
"=",
"256",
")",
":",
"img",
"=",
"cv2",
".",
"imread",
"(",
"input_file",
")",
"height",
",",
"width",
",",
"depth",
"=",
"img",
".",
"shape",
... | https://github.com/LisaAnne/lisa-caffe-public/blob/49b8643ddef23a4f6120017968de30c45e693f59/tools/extra/resize_and_crop_images.py#L20-L36 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/aquabutton.py | python | AquaButtonEvent.SetButtonObj | (self, btn) | Sets the event object for the event.
:param `btn`: the button object, an instance of :class:`AquaButton`. | Sets the event object for the event. | [
"Sets",
"the",
"event",
"object",
"for",
"the",
"event",
"."
] | def SetButtonObj(self, btn):
"""
Sets the event object for the event.
:param `btn`: the button object, an instance of :class:`AquaButton`.
"""
self.theButton = btn | [
"def",
"SetButtonObj",
"(",
"self",
",",
"btn",
")",
":",
"self",
".",
"theButton",
"=",
"btn"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aquabutton.py#L134-L141 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/protobuf/python/mox.py | python | Or.equals | (self, rhs) | return False | Checks whether any Comparator is equal to rhs.
Args:
# rhs: can be anything
Returns:
bool | Checks whether any Comparator is equal to rhs. | [
"Checks",
"whether",
"any",
"Comparator",
"is",
"equal",
"to",
"rhs",
"."
] | def equals(self, rhs):
"""Checks whether any Comparator is equal to rhs.
Args:
# rhs: can be anything
Returns:
bool
"""
for comparator in self._comparators:
if comparator.equals(rhs):
return True
return False | [
"def",
"equals",
"(",
"self",
",",
"rhs",
")",
":",
"for",
"comparator",
"in",
"self",
".",
"_comparators",
":",
"if",
"comparator",
".",
"equals",
"(",
"rhs",
")",
":",
"return",
"True",
"return",
"False"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/protobuf/python/mox.py#L1092-L1106 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/script_ops.py | python | FuncRegistry.size | (self) | return len(self._funcs) | Returns how many functions are currently registered. | Returns how many functions are currently registered. | [
"Returns",
"how",
"many",
"functions",
"are",
"currently",
"registered",
"."
] | def size(self):
"""Returns how many functions are currently registered."""
return len(self._funcs) | [
"def",
"size",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"_funcs",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/script_ops.py#L89-L91 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/util/_cloudpickle/_cloudpickle_fast.py | python | _file_reduce | (obj) | return _file_reconstructor, (retval,) | Save a file | Save a file | [
"Save",
"a",
"file"
] | def _file_reduce(obj):
"""Save a file"""
import io
if not hasattr(obj, "name") or not hasattr(obj, "mode"):
raise pickle.PicklingError(
"Cannot pickle files that do not map to an actual file"
)
if obj is sys.stdout:
return getattr, (sys, "stdout")
if obj is sys.stderr:
return getattr, (sys, "stderr")
if obj is sys.stdin:
raise pickle.PicklingError("Cannot pickle standard input")
if obj.closed:
raise pickle.PicklingError("Cannot pickle closed files")
if hasattr(obj, "isatty") and obj.isatty():
raise pickle.PicklingError(
"Cannot pickle files that map to tty objects"
)
if "r" not in obj.mode and "+" not in obj.mode:
raise pickle.PicklingError(
"Cannot pickle files that are not opened for reading: %s"
% obj.mode
)
name = obj.name
retval = io.StringIO()
try:
# Read the whole file
curloc = obj.tell()
obj.seek(0)
contents = obj.read()
obj.seek(curloc)
except IOError as e:
raise pickle.PicklingError(
"Cannot pickle file %s as it cannot be read" % name
) from e
retval.write(contents)
retval.seek(curloc)
retval.name = name
return _file_reconstructor, (retval,) | [
"def",
"_file_reduce",
"(",
"obj",
")",
":",
"import",
"io",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"\"name\"",
")",
"or",
"not",
"hasattr",
"(",
"obj",
",",
"\"mode\"",
")",
":",
"raise",
"pickle",
".",
"PicklingError",
"(",
"\"Cannot pickle files that ... | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/util/_cloudpickle/_cloudpickle_fast.py#L319-L363 | |
swift/swift | 12d031cf8177fdec0137f9aa7e2912fa23c4416b | 3rdParty/SCons/scons-3.0.1/engine/SCons/Script/SConsOptions.py | python | SConsOptionGroup.format_help | (self, formatter) | return result | Format an option group's help text, outdenting the title so it's
flush with the "SCons Options" title we print at the top. | Format an option group's help text, outdenting the title so it's
flush with the "SCons Options" title we print at the top. | [
"Format",
"an",
"option",
"group",
"s",
"help",
"text",
"outdenting",
"the",
"title",
"so",
"it",
"s",
"flush",
"with",
"the",
"SCons",
"Options",
"title",
"we",
"print",
"at",
"the",
"top",
"."
] | def format_help(self, formatter):
"""
Format an option group's help text, outdenting the title so it's
flush with the "SCons Options" title we print at the top.
"""
formatter.dedent()
result = formatter.format_heading(self.title)
formatter.indent()
result = result + optparse.OptionContainer.format_help(self, formatter)
return result | [
"def",
"format_help",
"(",
"self",
",",
"formatter",
")",
":",
"formatter",
".",
"dedent",
"(",
")",
"result",
"=",
"formatter",
".",
"format_heading",
"(",
"self",
".",
"title",
")",
"formatter",
".",
"indent",
"(",
")",
"result",
"=",
"result",
"+",
... | https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Script/SConsOptions.py#L270-L279 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/saved_model/function_serialization.py | python | _serialize_function_spec | (function_spec) | return proto | Serialize a FunctionSpec object into its proto representation. | Serialize a FunctionSpec object into its proto representation. | [
"Serialize",
"a",
"FunctionSpec",
"object",
"into",
"its",
"proto",
"representation",
"."
] | def _serialize_function_spec(function_spec):
"""Serialize a FunctionSpec object into its proto representation."""
if function_spec.is_method and not function_spec.fullargspec.args:
raise NotImplementedError(
"Cannot serialize a method function without a named "
"'self' argument.")
proto = saved_object_graph_pb2.FunctionSpec()
# Intentionally skip encoding annotations of a function because function
# annotations are mainly for optional type checking during development
# and does not affect runtime behavior.
# https://www.python.org/dev/peps/pep-3107/
# https://docs.python.org/3/library/inspect.html#inspect.getfullargspec
proto.fullargspec.CopyFrom(
nested_structure_coder.encode_structure(
function_spec.fullargspec._replace(annotations={})))
proto.is_method = function_spec.is_method
proto.input_signature.CopyFrom(
nested_structure_coder.encode_structure(function_spec.input_signature))
# See `tf.function` and the JitCompile proto for details.
proto.jit_compile = {
None: saved_object_graph_pb2.FunctionSpec.JitCompile.DEFAULT,
True: saved_object_graph_pb2.FunctionSpec.JitCompile.ON,
False: saved_object_graph_pb2.FunctionSpec.JitCompile.OFF,
}.get(function_spec.jit_compile)
return proto | [
"def",
"_serialize_function_spec",
"(",
"function_spec",
")",
":",
"if",
"function_spec",
".",
"is_method",
"and",
"not",
"function_spec",
".",
"fullargspec",
".",
"args",
":",
"raise",
"NotImplementedError",
"(",
"\"Cannot serialize a method function without a named \"",
... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/saved_model/function_serialization.py#L25-L53 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/telnetlib.py | python | Telnet.read_some | (self) | return buf | Read at least one byte of cooked data unless EOF is hit.
Return b'' if EOF is hit. Block if no data is immediately
available. | Read at least one byte of cooked data unless EOF is hit. | [
"Read",
"at",
"least",
"one",
"byte",
"of",
"cooked",
"data",
"unless",
"EOF",
"is",
"hit",
"."
] | def read_some(self):
"""Read at least one byte of cooked data unless EOF is hit.
Return b'' if EOF is hit. Block if no data is immediately
available.
"""
self.process_rawq()
while not self.cookedq and not self.eof:
self.fill_rawq()
self.process_rawq()
buf = self.cookedq
self.cookedq = b''
return buf | [
"def",
"read_some",
"(",
"self",
")",
":",
"self",
".",
"process_rawq",
"(",
")",
"while",
"not",
"self",
".",
"cookedq",
"and",
"not",
"self",
".",
"eof",
":",
"self",
".",
"fill_rawq",
"(",
")",
"self",
".",
"process_rawq",
"(",
")",
"buf",
"=",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/telnetlib.py#L341-L354 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rospy/src/rospy/impl/tcpros_base.py | python | TCPROSTransport.send_message | (self, msg, seq) | Convenience routine for services to send a message across a
particular connection. NOTE: write_data is much more efficient
if same message is being sent to multiple connections. Not
threadsafe.
@param msg: message to send
@type msg: Msg
@param seq: sequence number for message
@type seq: int
@raise TransportException: if error occurred sending message | Convenience routine for services to send a message across a
particular connection. NOTE: write_data is much more efficient
if same message is being sent to multiple connections. Not
threadsafe. | [
"Convenience",
"routine",
"for",
"services",
"to",
"send",
"a",
"message",
"across",
"a",
"particular",
"connection",
".",
"NOTE",
":",
"write_data",
"is",
"much",
"more",
"efficient",
"if",
"same",
"message",
"is",
"being",
"sent",
"to",
"multiple",
"connecti... | def send_message(self, msg, seq):
"""
Convenience routine for services to send a message across a
particular connection. NOTE: write_data is much more efficient
if same message is being sent to multiple connections. Not
threadsafe.
@param msg: message to send
@type msg: Msg
@param seq: sequence number for message
@type seq: int
@raise TransportException: if error occurred sending message
"""
# this will call write_data(), so no need to keep track of stats
serialize_message(self.write_buff, seq, msg)
self.write_data(self.write_buff.getvalue())
self.write_buff.truncate(0) | [
"def",
"send_message",
"(",
"self",
",",
"msg",
",",
"seq",
")",
":",
"# this will call write_data(), so no need to keep track of stats",
"serialize_message",
"(",
"self",
".",
"write_buff",
",",
"seq",
",",
"msg",
")",
"self",
".",
"write_data",
"(",
"self",
".",... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/impl/tcpros_base.py#L626-L641 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/resmokelib/utils/jscomment.py | python | _strip_jscomments | (string) | return "\n".join(yaml_lines) | Strip JS comments from a 'string'.
Given a string 'string' that represents the contents after the "@tags:"
annotation in the JS file, this function returns a string that can
be converted to YAML.
e.g.
[ "tag1", # double quoted
* 'tag2' # single quoted
* # line with only a comment
* , tag3 # no quotes
* tag4, # trailing comma
* ]
If the //-style JS comments were used, then the example remains the,
same except with the '*' character is replaced by '//'. | Strip JS comments from a 'string'. | [
"Strip",
"JS",
"comments",
"from",
"a",
"string",
"."
] | def _strip_jscomments(string):
"""Strip JS comments from a 'string'.
Given a string 'string' that represents the contents after the "@tags:"
annotation in the JS file, this function returns a string that can
be converted to YAML.
e.g.
[ "tag1", # double quoted
* 'tag2' # single quoted
* # line with only a comment
* , tag3 # no quotes
* tag4, # trailing comma
* ]
If the //-style JS comments were used, then the example remains the,
same except with the '*' character is replaced by '//'.
"""
yaml_lines = []
if isinstance(string, bytes):
string = string.decode("utf-8")
for line in string.splitlines():
# Remove leading whitespace and symbols that commonly appear in JS comments.
line = line.lstrip("\t ").lstrip("*/")
yaml_lines.append(line)
return "\n".join(yaml_lines) | [
"def",
"_strip_jscomments",
"(",
"string",
")",
":",
"yaml_lines",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"string",
",",
"bytes",
")",
":",
"string",
"=",
"string",
".",
"decode",
"(",
"\"utf-8\"",
")",
"for",
"line",
"in",
"string",
".",
"splitlines",
... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/utils/jscomment.py#L47-L77 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TIntH.IsAutoSize | (self) | return _snap.TIntH_IsAutoSize(self) | IsAutoSize(TIntH self) -> bool
Parameters:
self: THash< TInt,TInt > const * | IsAutoSize(TIntH self) -> bool | [
"IsAutoSize",
"(",
"TIntH",
"self",
")",
"-",
">",
"bool"
] | def IsAutoSize(self):
"""
IsAutoSize(TIntH self) -> bool
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_IsAutoSize(self) | [
"def",
"IsAutoSize",
"(",
"self",
")",
":",
"return",
"_snap",
".",
"TIntH_IsAutoSize",
"(",
"self",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L18494-L18502 | |
hwwang55/DKN | 90a188021a82ddaadffc44f6d87e1e72b1c3db9a | data/news/news_preprocess.py | python | construct_word2id_and_entity2id | () | Allocate each valid word and entity a unique index (start from 1)
:return: None | Allocate each valid word and entity a unique index (start from 1)
:return: None | [
"Allocate",
"each",
"valid",
"word",
"and",
"entity",
"a",
"unique",
"index",
"(",
"start",
"from",
"1",
")",
":",
"return",
":",
"None"
] | def construct_word2id_and_entity2id():
"""
Allocate each valid word and entity a unique index (start from 1)
:return: None
"""
cnt = 1 # 0 is for dummy word
for w, freq in word2freq.items():
if freq >= WORD_FREQ_THRESHOLD:
word2index[w] = cnt
cnt += 1
print('- word size: %d' % len(word2index))
writer = open('../kg/entity2index.txt', 'w', encoding='utf-8')
cnt = 1
for entity, freq in entity2freq.items():
if freq >= ENTITY_FREQ_THRESHOLD:
entity2index[entity] = cnt
writer.write('%s\t%d\n' % (entity, cnt)) # for later use
cnt += 1
writer.close()
print('- entity size: %d' % len(entity2index)) | [
"def",
"construct_word2id_and_entity2id",
"(",
")",
":",
"cnt",
"=",
"1",
"# 0 is for dummy word",
"for",
"w",
",",
"freq",
"in",
"word2freq",
".",
"items",
"(",
")",
":",
"if",
"freq",
">=",
"WORD_FREQ_THRESHOLD",
":",
"word2index",
"[",
"w",
"]",
"=",
"c... | https://github.com/hwwang55/DKN/blob/90a188021a82ddaadffc44f6d87e1e72b1c3db9a/data/news/news_preprocess.py#L52-L72 | ||
vnpy/vnpy | f50f2535ed39dd33272e0985ed40c7078e4c19f6 | vnpy/trader/ui/widget.py | python | BaseCell.set_content | (self, content: Any, data: Any) | Set text content. | Set text content. | [
"Set",
"text",
"content",
"."
] | def set_content(self, content: Any, data: Any) -> None:
"""
Set text content.
"""
self.setText(str(content))
self._data = data | [
"def",
"set_content",
"(",
"self",
",",
"content",
":",
"Any",
",",
"data",
":",
"Any",
")",
"->",
"None",
":",
"self",
".",
"setText",
"(",
"str",
"(",
"content",
")",
")",
"self",
".",
"_data",
"=",
"data"
] | https://github.com/vnpy/vnpy/blob/f50f2535ed39dd33272e0985ed40c7078e4c19f6/vnpy/trader/ui/widget.py#L51-L56 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/control_flow_ops.py | python | ControlFlowContext._RemoveExternalControlEdges | (self, op) | return internal_control_inputs | Remove any external control dependency on this op. | Remove any external control dependency on this op. | [
"Remove",
"any",
"external",
"control",
"dependency",
"on",
"this",
"op",
"."
] | def _RemoveExternalControlEdges(self, op):
"""Remove any external control dependency on this op."""
while_ctxt = self.GetWhileContext()
# A control input of `op` is internal if it is in the same while
# loop context as the enclosing while loop context of self.
if while_ctxt is None:
internal_control_inputs = op.control_inputs
else:
internal_control_inputs = []
for x in op.control_inputs:
ctxt = _GetOutputContext(x)
if ctxt is not None and ctxt.GetWhileContext() == while_ctxt:
internal_control_inputs.append(x)
if len(internal_control_inputs) != len(op.control_inputs):
del op.control_inputs[:]
op._add_control_inputs(internal_control_inputs)
return internal_control_inputs | [
"def",
"_RemoveExternalControlEdges",
"(",
"self",
",",
"op",
")",
":",
"while_ctxt",
"=",
"self",
".",
"GetWhileContext",
"(",
")",
"# A control input of `op` is internal if it is in the same while",
"# loop context as the enclosing while loop context of self.",
"if",
"while_ctx... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/control_flow_ops.py#L1456-L1472 | |
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/concept_interactive_session.py | python | ConceptInteractiveSession.get_projections | (self, node) | return result | Return a list of (name, binary_concept) with all possible
projections at node | Return a list of (name, binary_concept) with all possible
projections at node | [
"Return",
"a",
"list",
"of",
"(",
"name",
"binary_concept",
")",
"with",
"all",
"possible",
"projections",
"at",
"node"
] | def get_projections(self, node):
"""
Return a list of (name, binary_concept) with all possible
projections at node
"""
witnesses = self._get_witnesses(node)
if len(witnesses) == 0:
return []
w = witnesses[0]
result = []
n_concept = self.domain.concepts[node]
for t_name in self.domain.concepts_by_arity(3):
t_concept = self.domain.concepts[t_name]
for v in t_concept.variables:
if v.sort == w.sort:
variables = [x for x in t_concept.variables if x is not v]
formula = substitute(t_concept.formula, {v: w})
name = str(formula)
concept = Concept(name,variables, formula)
result.append((name, concept))
return result | [
"def",
"get_projections",
"(",
"self",
",",
"node",
")",
":",
"witnesses",
"=",
"self",
".",
"_get_witnesses",
"(",
"node",
")",
"if",
"len",
"(",
"witnesses",
")",
"==",
"0",
":",
"return",
"[",
"]",
"w",
"=",
"witnesses",
"[",
"0",
"]",
"result",
... | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/concept_interactive_session.py#L299-L320 | |
google/tink | 59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14 | python/tink/streaming_aead/_streaming_aead_wrapper.py | python | _DecryptingStreamWrapper.readinto | (self, b: bytearray) | return n | Read bytes into a pre-allocated bytes-like object b. | Read bytes into a pre-allocated bytes-like object b. | [
"Read",
"bytes",
"into",
"a",
"pre",
"-",
"allocated",
"bytes",
"-",
"like",
"object",
"b",
"."
] | def readinto(self, b: bytearray) -> Optional[int]:
"""Read bytes into a pre-allocated bytes-like object b."""
data = self.read(len(b))
if data is None:
return None
n = len(data)
b[:n] = data
return n | [
"def",
"readinto",
"(",
"self",
",",
"b",
":",
"bytearray",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"data",
"=",
"self",
".",
"read",
"(",
"len",
"(",
"b",
")",
")",
"if",
"data",
"is",
"None",
":",
"return",
"None",
"n",
"=",
"len",
"(",
... | https://github.com/google/tink/blob/59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14/python/tink/streaming_aead/_streaming_aead_wrapper.py#L111-L118 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/arrays/_mixins.py | python | NDArrayBackedExtensionArray._box_func | (self, x) | return x | Wrap numpy type in our dtype.type if necessary. | Wrap numpy type in our dtype.type if necessary. | [
"Wrap",
"numpy",
"type",
"in",
"our",
"dtype",
".",
"type",
"if",
"necessary",
"."
] | def _box_func(self, x):
"""
Wrap numpy type in our dtype.type if necessary.
"""
return x | [
"def",
"_box_func",
"(",
"self",
",",
"x",
")",
":",
"return",
"x"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/arrays/_mixins.py#L76-L80 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py | python | NavigableString.__getattr__ | (self, attr) | text.string gives you text. This is for backwards
compatibility for Navigable*String, but for CData* it lets you
get the string without the CData wrapper. | text.string gives you text. This is for backwards
compatibility for Navigable*String, but for CData* it lets you
get the string without the CData wrapper. | [
"text",
".",
"string",
"gives",
"you",
"text",
".",
"This",
"is",
"for",
"backwards",
"compatibility",
"for",
"Navigable",
"*",
"String",
"but",
"for",
"CData",
"*",
"it",
"lets",
"you",
"get",
"the",
"string",
"without",
"the",
"CData",
"wrapper",
"."
] | def __getattr__(self, attr):
"""text.string gives you text. This is for backwards
compatibility for Navigable*String, but for CData* it lets you
get the string without the CData wrapper."""
if attr == 'string':
return self
else:
raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__.__name__, attr) | [
"def",
"__getattr__",
"(",
"self",
",",
"attr",
")",
":",
"if",
"attr",
"==",
"'string'",
":",
"return",
"self",
"else",
":",
"raise",
"AttributeError",
",",
"\"'%s' object has no attribute '%s'\"",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"... | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py#L441-L448 | ||
vnpy/vnpy | f50f2535ed39dd33272e0985ed40c7078e4c19f6 | vnpy/trader/engine.py | python | LogEngine.process_log_event | (self, event: Event) | Process log event. | Process log event. | [
"Process",
"log",
"event",
"."
] | def process_log_event(self, event: Event) -> None:
"""
Process log event.
"""
log = event.data
self.logger.log(log.level, log.msg) | [
"def",
"process_log_event",
"(",
"self",
",",
"event",
":",
"Event",
")",
"->",
"None",
":",
"log",
"=",
"event",
".",
"data",
"self",
".",
"logger",
".",
"log",
"(",
"log",
".",
"level",
",",
"log",
".",
"msg",
")"
] | https://github.com/vnpy/vnpy/blob/f50f2535ed39dd33272e0985ed40c7078e4c19f6/vnpy/trader/engine.py#L328-L333 | ||
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/gyp/pylib/gyp/xcode_emulation.py | python | XcodeSettings.GetWrapperExtension | (self) | Returns the bundle extension (.app, .framework, .plugin, etc). Only
valid for bundles. | Returns the bundle extension (.app, .framework, .plugin, etc). Only
valid for bundles. | [
"Returns",
"the",
"bundle",
"extension",
"(",
".",
"app",
".",
"framework",
".",
"plugin",
"etc",
")",
".",
"Only",
"valid",
"for",
"bundles",
"."
] | def GetWrapperExtension(self):
"""Returns the bundle extension (.app, .framework, .plugin, etc). Only
valid for bundles."""
assert self._IsBundle()
if self.spec["type"] in ("loadable_module", "shared_library"):
default_wrapper_extension = {
"loadable_module": "bundle",
"shared_library": "framework",
}[self.spec["type"]]
wrapper_extension = self.GetPerTargetSetting(
"WRAPPER_EXTENSION", default=default_wrapper_extension
)
return "." + self.spec.get("product_extension", wrapper_extension)
elif self.spec["type"] == "executable":
if self._IsIosAppExtension() or self._IsIosWatchKitExtension():
return "." + self.spec.get("product_extension", "appex")
else:
return "." + self.spec.get("product_extension", "app")
else:
assert False, "Don't know extension for '{}', target '{}'".format(
self.spec["type"],
self.spec["target_name"],
) | [
"def",
"GetWrapperExtension",
"(",
"self",
")",
":",
"assert",
"self",
".",
"_IsBundle",
"(",
")",
"if",
"self",
".",
"spec",
"[",
"\"type\"",
"]",
"in",
"(",
"\"loadable_module\"",
",",
"\"shared_library\"",
")",
":",
"default_wrapper_extension",
"=",
"{",
... | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/xcode_emulation.py#L262-L284 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/signal/filter_design.py | python | lp2hp | (b, a, wo=1.0) | return normalize(outb, outa) | Transform a lowpass filter prototype to a highpass filter.
Return an analog high-pass filter with cutoff frequency `wo`
from an analog low-pass filter prototype with unity cutoff frequency, in
transfer function ('ba') representation.
See Also
--------
lp2lp, lp2bp, lp2bs, bilinear
lp2hp_zpk | Transform a lowpass filter prototype to a highpass filter. | [
"Transform",
"a",
"lowpass",
"filter",
"prototype",
"to",
"a",
"highpass",
"filter",
"."
] | def lp2hp(b, a, wo=1.0):
"""
Transform a lowpass filter prototype to a highpass filter.
Return an analog high-pass filter with cutoff frequency `wo`
from an analog low-pass filter prototype with unity cutoff frequency, in
transfer function ('ba') representation.
See Also
--------
lp2lp, lp2bp, lp2bs, bilinear
lp2hp_zpk
"""
a, b = map(atleast_1d, (a, b))
try:
wo = float(wo)
except TypeError:
wo = float(wo[0])
d = len(a)
n = len(b)
if wo != 1:
pwo = pow(wo, numpy.arange(max((d, n))))
else:
pwo = numpy.ones(max((d, n)), b.dtype.char)
if d >= n:
outa = a[::-1] * pwo
outb = resize(b, (d,))
outb[n:] = 0.0
outb[:n] = b[::-1] * pwo[:n]
else:
outb = b[::-1] * pwo
outa = resize(a, (n,))
outa[d:] = 0.0
outa[:d] = a[::-1] * pwo[:d]
return normalize(outb, outa) | [
"def",
"lp2hp",
"(",
"b",
",",
"a",
",",
"wo",
"=",
"1.0",
")",
":",
"a",
",",
"b",
"=",
"map",
"(",
"atleast_1d",
",",
"(",
"a",
",",
"b",
")",
")",
"try",
":",
"wo",
"=",
"float",
"(",
"wo",
")",
"except",
"TypeError",
":",
"wo",
"=",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/signal/filter_design.py#L1662-L1698 | |
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | pygimli/frameworks/inversion.py | python | Inversion.dataVals | (self, d) | Set mandatory data values.
Values == 0.0. Will be set to Tolerance | Set mandatory data values. | [
"Set",
"mandatory",
"data",
"values",
"."
] | def dataVals(self, d):
"""Set mandatory data values.
Values == 0.0. Will be set to Tolerance
"""
self._dataVals = d
if self._dataVals is None:
pg._y(d)
pg.critical("Inversion framework needs data values to run") | [
"def",
"dataVals",
"(",
"self",
",",
"d",
")",
":",
"self",
".",
"_dataVals",
"=",
"d",
"if",
"self",
".",
"_dataVals",
"is",
"None",
":",
"pg",
".",
"_y",
"(",
"d",
")",
"pg",
".",
"critical",
"(",
"\"Inversion framework needs data values to run\"",
")"... | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/frameworks/inversion.py#L213-L222 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/metrics_impl.py | python | mean_iou | (labels,
predictions,
num_classes,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None) | Calculate per-step mean Intersection-Over-Union (mIOU).
Mean Intersection-Over-Union is a common evaluation metric for
semantic image segmentation, which first computes the IOU for each
semantic class and then computes the average over classes.
IOU is defined as follows:
IOU = true_positive / (true_positive + false_positive + false_negative).
The predictions are accumulated in a confusion matrix, weighted by `weights`,
and mIOU is then calculated from it.
For estimation of the metric over a stream of data, the function creates an
`update_op` operation that updates these variables and returns the `mean_iou`.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
Args:
labels: A `Tensor` of ground truth labels with shape [batch size] and of
type `int32` or `int64`. The tensor will be flattened if its rank > 1.
predictions: A `Tensor` of prediction results for semantic labels, whose
shape is [batch size] and type `int32` or `int64`. The tensor will be
flattened if its rank > 1.
num_classes: The possible number of labels the prediction task can
have. This value must be provided, since a confusion matrix of
dimension = [num_classes, num_classes] will be allocated.
weights: Optional `Tensor` whose rank is either 0, or the same rank as
`labels`, and must be broadcastable to `labels` (i.e., all dimensions must
be either `1`, or the same as the corresponding `labels` dimension).
metrics_collections: An optional list of collections that `mean_iou`
should be added to.
updates_collections: An optional list of collections `update_op` should be
added to.
name: An optional variable_scope name.
Returns:
mean_iou: A `Tensor` representing the mean intersection-over-union.
update_op: An operation that increments the confusion matrix.
Raises:
ValueError: If `predictions` and `labels` have mismatched shapes, or if
`weights` is not `None` and its shape doesn't match `predictions`, or if
either `metrics_collections` or `updates_collections` are not a list or
tuple. | Calculate per-step mean Intersection-Over-Union (mIOU). | [
"Calculate",
"per",
"-",
"step",
"mean",
"Intersection",
"-",
"Over",
"-",
"Union",
"(",
"mIOU",
")",
"."
] | def mean_iou(labels,
predictions,
num_classes,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None):
"""Calculate per-step mean Intersection-Over-Union (mIOU).
Mean Intersection-Over-Union is a common evaluation metric for
semantic image segmentation, which first computes the IOU for each
semantic class and then computes the average over classes.
IOU is defined as follows:
IOU = true_positive / (true_positive + false_positive + false_negative).
The predictions are accumulated in a confusion matrix, weighted by `weights`,
and mIOU is then calculated from it.
For estimation of the metric over a stream of data, the function creates an
`update_op` operation that updates these variables and returns the `mean_iou`.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
Args:
labels: A `Tensor` of ground truth labels with shape [batch size] and of
type `int32` or `int64`. The tensor will be flattened if its rank > 1.
predictions: A `Tensor` of prediction results for semantic labels, whose
shape is [batch size] and type `int32` or `int64`. The tensor will be
flattened if its rank > 1.
num_classes: The possible number of labels the prediction task can
have. This value must be provided, since a confusion matrix of
dimension = [num_classes, num_classes] will be allocated.
weights: Optional `Tensor` whose rank is either 0, or the same rank as
`labels`, and must be broadcastable to `labels` (i.e., all dimensions must
be either `1`, or the same as the corresponding `labels` dimension).
metrics_collections: An optional list of collections that `mean_iou`
should be added to.
updates_collections: An optional list of collections `update_op` should be
added to.
name: An optional variable_scope name.
Returns:
mean_iou: A `Tensor` representing the mean intersection-over-union.
update_op: An operation that increments the confusion matrix.
Raises:
ValueError: If `predictions` and `labels` have mismatched shapes, or if
`weights` is not `None` and its shape doesn't match `predictions`, or if
either `metrics_collections` or `updates_collections` are not a list or
tuple.
"""
with variable_scope.variable_scope(
name, 'mean_iou', (predictions, labels, weights)):
# Check if shape is compatible.
predictions.get_shape().assert_is_compatible_with(labels.get_shape())
total_cm, update_op = _streaming_confusion_matrix(labels, predictions,
num_classes, weights)
def compute_mean_iou(name):
"""Compute the mean intersection-over-union via the confusion matrix."""
sum_over_row = math_ops.to_float(math_ops.reduce_sum(total_cm, 0))
sum_over_col = math_ops.to_float(math_ops.reduce_sum(total_cm, 1))
cm_diag = math_ops.to_float(array_ops.diag_part(total_cm))
denominator = sum_over_row + sum_over_col - cm_diag
# The mean is only computed over classes that appear in the
# label or prediction tensor. If the denominator is 0, we need to
# ignore the class.
num_valid_entries = math_ops.reduce_sum(math_ops.cast(
math_ops.not_equal(denominator, 0), dtype=dtypes.float32))
# If the value of the denominator is 0, set it to 1 to avoid
# zero division.
denominator = array_ops.where(
math_ops.greater(denominator, 0),
denominator,
array_ops.ones_like(denominator))
iou = math_ops.div(cm_diag, denominator)
# If the number of valid entries is 0 (no classes) we return 0.
result = array_ops.where(
math_ops.greater(num_valid_entries, 0),
math_ops.reduce_sum(iou, name=name) / num_valid_entries,
0)
return result
mean_iou_v = compute_mean_iou('mean_iou')
if metrics_collections:
ops.add_to_collections(metrics_collections, mean_iou_v)
if updates_collections:
ops.add_to_collections(updates_collections, update_op)
return mean_iou_v, update_op | [
"def",
"mean_iou",
"(",
"labels",
",",
"predictions",
",",
"num_classes",
",",
"weights",
"=",
"None",
",",
"metrics_collections",
"=",
"None",
",",
"updates_collections",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"with",
"variable_scope",
".",
"varia... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/metrics_impl.py#L888-L981 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/syntax/synxml.py | python | EditraXml.SetIndentation | (self, indent) | Set the indentation level
@param indent: int | Set the indentation level
@param indent: int | [
"Set",
"the",
"indentation",
"level",
"@param",
"indent",
":",
"int"
] | def SetIndentation(self, indent):
"""Set the indentation level
@param indent: int
"""
self.indent = indent | [
"def",
"SetIndentation",
"(",
"self",
",",
"indent",
")",
":",
"self",
".",
"indent",
"=",
"indent"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/synxml.py#L302-L307 | ||
jsupancic/deep_hand_pose | 22cbeae1a8410ff5d37c060c7315719d0a5d608f | scripts/cpp_lint.py | python | CheckVlogArguments | (filename, clean_lines, linenum, error) | Checks that VLOG() is only used for defining a logging level.
For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
VLOG(FATAL) are not.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks that VLOG() is only used for defining a logging level. | [
"Checks",
"that",
"VLOG",
"()",
"is",
"only",
"used",
"for",
"defining",
"a",
"logging",
"level",
"."
] | def CheckVlogArguments(filename, clean_lines, linenum, error):
"""Checks that VLOG() is only used for defining a logging level.
For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
VLOG(FATAL) are not.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line):
error(filename, linenum, 'runtime/vlog', 5,
'VLOG() should be used with numeric verbosity level. '
'Use LOG() if you want symbolic severity levels.') | [
"def",
"CheckVlogArguments",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"Search",
"(",
"r'\\bVLOG\\((INFO|ERROR|WARNING|DFATAL|FATAL)\\)'",
",",
"line",
")",
... | https://github.com/jsupancic/deep_hand_pose/blob/22cbeae1a8410ff5d37c060c7315719d0a5d608f/scripts/cpp_lint.py#L1708-L1724 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/pdfviewer/viewer.py | python | pdfPrintout.PrintDirect | (self, page) | Provide the data for page by rendering the drawing commands
to the printer DC using dcGraphicsContext | Provide the data for page by rendering the drawing commands
to the printer DC using dcGraphicsContext | [
"Provide",
"the",
"data",
"for",
"page",
"by",
"rendering",
"the",
"drawing",
"commands",
"to",
"the",
"printer",
"DC",
"using",
"dcGraphicsContext"
] | def PrintDirect(self, page):
""" Provide the data for page by rendering the drawing commands
to the printer DC using dcGraphicsContext
"""
pageno = page - 1 # zero based
width = self.view.pagewidth
height = self.view.pageheight
self.FitThisSizeToPage(wx.Size(width, height))
dc = self.GetDC()
gc = dcGraphicsContext.Create(dc, height, have_cairo)
self.view.pdfdoc.RenderPage(gc, pageno) | [
"def",
"PrintDirect",
"(",
"self",
",",
"page",
")",
":",
"pageno",
"=",
"page",
"-",
"1",
"# zero based",
"width",
"=",
"self",
".",
"view",
".",
"pagewidth",
"height",
"=",
"self",
".",
"view",
".",
"pageheight",
"self",
".",
"FitThisSizeToPage",
"(",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/pdfviewer/viewer.py#L996-L1006 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/cross_validation.py | python | _score | (estimator, X_test, y_test, scorer) | return score | Compute the score of an estimator on a given test set. | Compute the score of an estimator on a given test set. | [
"Compute",
"the",
"score",
"of",
"an",
"estimator",
"on",
"a",
"given",
"test",
"set",
"."
] | def _score(estimator, X_test, y_test, scorer):
"""Compute the score of an estimator on a given test set."""
if y_test is None:
score = scorer(estimator, X_test)
else:
score = scorer(estimator, X_test, y_test)
if hasattr(score, 'item'):
try:
# e.g. unwrap memmapped scalars
score = score.item()
except ValueError:
# non-scalar?
pass
if not isinstance(score, numbers.Number):
raise ValueError("scoring must return a number, got %s (%s) instead."
% (str(score), type(score)))
return score | [
"def",
"_score",
"(",
"estimator",
",",
"X_test",
",",
"y_test",
",",
"scorer",
")",
":",
"if",
"y_test",
"is",
"None",
":",
"score",
"=",
"scorer",
"(",
"estimator",
",",
"X_test",
")",
"else",
":",
"score",
"=",
"scorer",
"(",
"estimator",
",",
"X_... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/cross_validation.py#L1736-L1752 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | build/android/pylib/forwarder.py | python | Forwarder._KillHostLocked | (self) | Kills the forwarder process running on the host.
Note that the global lock must be acquired before calling this method. | Kills the forwarder process running on the host. | [
"Kills",
"the",
"forwarder",
"process",
"running",
"on",
"the",
"host",
"."
] | def _KillHostLocked(self):
"""Kills the forwarder process running on the host.
Note that the global lock must be acquired before calling this method.
"""
logging.info('Killing host_forwarder.')
(exit_code, output) = cmd_helper.GetCmdStatusAndOutput(
[self._host_forwarder_path, '--kill-server'])
if exit_code != 0:
(exit_code, output) = cmd_helper.GetCmdStatusAndOutput(
['pkill', '-9', 'host_forwarder'])
if exit_code != 0:
raise Exception('%s exited with %d:\n%s' % (
self._host_forwarder_path, exit_code, '\n'.join(output))) | [
"def",
"_KillHostLocked",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"'Killing host_forwarder.'",
")",
"(",
"exit_code",
",",
"output",
")",
"=",
"cmd_helper",
".",
"GetCmdStatusAndOutput",
"(",
"[",
"self",
".",
"_host_forwarder_path",
",",
"'--kill-se... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/android/pylib/forwarder.py#L293-L306 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/receptive_field/python/util/receptive_field.py | python | _get_effective_stride_node_input | (stride, effective_stride_output) | return stride * effective_stride_output | Computes effective stride at the input of a given layer.
Args:
stride: Stride of given layer (integer).
effective_stride_output: Effective stride at output of given layer
(integer).
Returns:
effective_stride_input: Effective stride at input of given layer
(integer). | Computes effective stride at the input of a given layer. | [
"Computes",
"effective",
"stride",
"at",
"the",
"input",
"of",
"a",
"given",
"layer",
"."
] | def _get_effective_stride_node_input(stride, effective_stride_output):
"""Computes effective stride at the input of a given layer.
Args:
stride: Stride of given layer (integer).
effective_stride_output: Effective stride at output of given layer
(integer).
Returns:
effective_stride_input: Effective stride at input of given layer
(integer).
"""
return stride * effective_stride_output | [
"def",
"_get_effective_stride_node_input",
"(",
"stride",
",",
"effective_stride_output",
")",
":",
"return",
"stride",
"*",
"effective_stride_output"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/receptive_field/python/util/receptive_field.py#L278-L290 | |
giuspen/cherrytree | 84712f206478fcf9acf30174009ad28c648c6344 | pygtk2/modules/core.py | python | CherryTree.export_print_page_setup | (self, action) | Print Page Setup Operations | Print Page Setup Operations | [
"Print",
"Page",
"Setup",
"Operations"
] | def export_print_page_setup(self, action):
"""Print Page Setup Operations"""
if self.print_handler.settings is None:
self.print_handler.settings = gtk.PrintSettings()
self.print_handler.page_setup = gtk.print_run_page_setup_dialog(self.window,
self.print_handler.page_setup,
self.print_handler.settings) | [
"def",
"export_print_page_setup",
"(",
"self",
",",
"action",
")",
":",
"if",
"self",
".",
"print_handler",
".",
"settings",
"is",
"None",
":",
"self",
".",
"print_handler",
".",
"settings",
"=",
"gtk",
".",
"PrintSettings",
"(",
")",
"self",
".",
"print_h... | https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/core.py#L2257-L2263 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/stcspellcheck.py | python | STCSpellCheck.getSuggestions | (self, word) | return [] | Get suggestion for the correct spelling of a word.
@param word: word to check
@return: list of suggestions, or an empty list if any of the following
are true: there are no suggestions, the word is shorter than the
minimum length, or the dictionary can't be found. | Get suggestion for the correct spelling of a word. | [
"Get",
"suggestion",
"for",
"the",
"correct",
"spelling",
"of",
"a",
"word",
"."
] | def getSuggestions(self, word):
"""Get suggestion for the correct spelling of a word.
@param word: word to check
@return: list of suggestions, or an empty list if any of the following
are true: there are no suggestions, the word is shorter than the
minimum length, or the dictionary can't be found.
"""
spell = self._spelling_dict
if spell and len(word) >= self._spelling_word_size:
words = spell.suggest(word)
if self._spelling_debug:
print("suggestions for %s: %s" % (word, words))
return words
return [] | [
"def",
"getSuggestions",
"(",
"self",
",",
"word",
")",
":",
"spell",
"=",
"self",
".",
"_spelling_dict",
"if",
"spell",
"and",
"len",
"(",
"word",
")",
">=",
"self",
".",
"_spelling_word_size",
":",
"words",
"=",
"spell",
".",
"suggest",
"(",
"word",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/stcspellcheck.py#L480-L495 | |
htcondor/htcondor | 4829724575176d1d6c936e4693dfd78a728569b0 | bindings/python/htcondor/htchirp/htchirp.py | python | HTChirp.whoami | (self) | return result | Get the user's current identity with respect to this server.
:returns: The user's identity | Get the user's current identity with respect to this server. | [
"Get",
"the",
"user",
"s",
"current",
"identity",
"with",
"respect",
"to",
"this",
"server",
"."
] | def whoami(self):
"""Get the user's current identity with respect to this server.
:returns: The user's identity
"""
length = int(
self._simple_command("whoami {0}\n".format(self.__class__.CHIRP_LINE_MAX))
)
result = self._get_fixed_data(length).decode()
return result | [
"def",
"whoami",
"(",
"self",
")",
":",
"length",
"=",
"int",
"(",
"self",
".",
"_simple_command",
"(",
"\"whoami {0}\\n\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"CHIRP_LINE_MAX",
")",
")",
")",
"result",
"=",
"self",
".",
"_get_fixed_data",
... | https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/bindings/python/htcondor/htchirp/htchirp.py#L1002-L1014 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py2/IPython/utils/path.py | python | get_py_filename | (name, force_win32=None) | Return a valid python filename in the current directory.
If the given name is not a file, it adds '.py' and searches again.
Raises IOError with an informative message if the file isn't found. | Return a valid python filename in the current directory. | [
"Return",
"a",
"valid",
"python",
"filename",
"in",
"the",
"current",
"directory",
"."
] | def get_py_filename(name, force_win32=None):
"""Return a valid python filename in the current directory.
If the given name is not a file, it adds '.py' and searches again.
Raises IOError with an informative message if the file isn't found.
"""
name = os.path.expanduser(name)
if force_win32 is not None:
warn("The 'force_win32' argument to 'get_py_filename' is deprecated "
"since IPython 5.0 and should not be used anymore",
DeprecationWarning, stacklevel=2)
if not os.path.isfile(name) and not name.endswith('.py'):
name += '.py'
if os.path.isfile(name):
return name
else:
raise IOError('File `%r` not found.' % name) | [
"def",
"get_py_filename",
"(",
"name",
",",
"force_win32",
"=",
"None",
")",
":",
"name",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"name",
")",
"if",
"force_win32",
"is",
"not",
"None",
":",
"warn",
"(",
"\"The 'force_win32' argument to 'get_py_filename... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/utils/path.py#L96-L113 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/propgrid.py | python | PGArrayEditorDialog.EnableCustomNewAction | (*args, **kwargs) | return _propgrid.PGArrayEditorDialog_EnableCustomNewAction(*args, **kwargs) | EnableCustomNewAction(self) | EnableCustomNewAction(self) | [
"EnableCustomNewAction",
"(",
"self",
")"
] | def EnableCustomNewAction(*args, **kwargs):
"""EnableCustomNewAction(self)"""
return _propgrid.PGArrayEditorDialog_EnableCustomNewAction(*args, **kwargs) | [
"def",
"EnableCustomNewAction",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PGArrayEditorDialog_EnableCustomNewAction",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L3186-L3188 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/protobuf/py3/google/protobuf/internal/encoder.py | python | _SignedVarintSize | (value) | return 10 | Compute the size of a signed varint value. | Compute the size of a signed varint value. | [
"Compute",
"the",
"size",
"of",
"a",
"signed",
"varint",
"value",
"."
] | def _SignedVarintSize(value):
"""Compute the size of a signed varint value."""
if value < 0: return 10
if value <= 0x7f: return 1
if value <= 0x3fff: return 2
if value <= 0x1fffff: return 3
if value <= 0xfffffff: return 4
if value <= 0x7ffffffff: return 5
if value <= 0x3ffffffffff: return 6
if value <= 0x1ffffffffffff: return 7
if value <= 0xffffffffffffff: return 8
if value <= 0x7fffffffffffffff: return 9
return 10 | [
"def",
"_SignedVarintSize",
"(",
"value",
")",
":",
"if",
"value",
"<",
"0",
":",
"return",
"10",
"if",
"value",
"<=",
"0x7f",
":",
"return",
"1",
"if",
"value",
"<=",
"0x3fff",
":",
"return",
"2",
"if",
"value",
"<=",
"0x1fffff",
":",
"return",
"3",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/internal/encoder.py#L96-L108 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib2to3/pytree.py | python | Node.__unicode__ | (self) | return u"".join(map(unicode, self.children)) | Return a pretty string representation.
This reproduces the input source exactly. | Return a pretty string representation. | [
"Return",
"a",
"pretty",
"string",
"representation",
"."
] | def __unicode__(self):
"""
Return a pretty string representation.
This reproduces the input source exactly.
"""
return u"".join(map(unicode, self.children)) | [
"def",
"__unicode__",
"(",
"self",
")",
":",
"return",
"u\"\"",
".",
"join",
"(",
"map",
"(",
"unicode",
",",
"self",
".",
"children",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib2to3/pytree.py#L274-L280 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/probability/distribution/gumbel.py | python | Gumbel.loc | (self) | return self._loc | Return the location of the distribution after casting to dtype.
Output:
Tensor, the loc parameter of the distribution. | Return the location of the distribution after casting to dtype. | [
"Return",
"the",
"location",
"of",
"the",
"distribution",
"after",
"casting",
"to",
"dtype",
"."
] | def loc(self):
"""
Return the location of the distribution after casting to dtype.
Output:
Tensor, the loc parameter of the distribution.
"""
return self._loc | [
"def",
"loc",
"(",
"self",
")",
":",
"return",
"self",
".",
"_loc"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/distribution/gumbel.py#L121-L128 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/training/training_ops.py | python | _SparseApplyRMSPropShape | (op) | return [mom_shape] | Shape function for the SparseApplyRMSProp op. | Shape function for the SparseApplyRMSProp op. | [
"Shape",
"function",
"for",
"the",
"SparseApplyRMSProp",
"op",
"."
] | def _SparseApplyRMSPropShape(op):
"""Shape function for the SparseApplyRMSProp op."""
var_shape = op.inputs[0].get_shape()
ms_shape = op.inputs[1].get_shape().merge_with(var_shape)
mom_shape = op.inputs[2].get_shape().merge_with(ms_shape)
_AssertInputIsScalar(op, 3) # lr
_AssertInputIsScalar(op, 4) # rho
_AssertInputIsScalar(op, 5) # momentum
_AssertInputIsScalar(op, 6) # epsilon
grad_shape = op.inputs[7].get_shape().merge_with(
tensor_shape.TensorShape([None]).concatenate(mom_shape[1:]))
unused_indices_shape = op.inputs[8].get_shape().merge_with(
tensor_shape.vector(grad_shape[0]))
return [mom_shape] | [
"def",
"_SparseApplyRMSPropShape",
"(",
"op",
")",
":",
"var_shape",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
"ms_shape",
"=",
"op",
".",
"inputs",
"[",
"1",
"]",
".",
"get_shape",
"(",
")",
".",
"merge_with",
"(",
"var_sh... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/training/training_ops.py#L174-L187 | |
neoml-lib/neoml | a0d370fba05269a1b2258cef126f77bbd2054a3e | NeoML/Python/neoml/Dnn/Transform.py | python | Transform.transforms | (self) | return result | Gets the array of transformations. | Gets the array of transformations. | [
"Gets",
"the",
"array",
"of",
"transformations",
"."
] | def transforms(self):
"""Gets the array of transformations.
"""
operations = self._internal.get_operations()
parameters = self._internal.get_parameters()
result = []
for i in range(operations.size):
result.append((self.rules[operations[i]], parameters[i]))
return result | [
"def",
"transforms",
"(",
"self",
")",
":",
"operations",
"=",
"self",
".",
"_internal",
".",
"get_operations",
"(",
")",
"parameters",
"=",
"self",
".",
"_internal",
".",
"get_parameters",
"(",
")",
"result",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
... | https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/Transform.py#L87-L96 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Path/PathScripts/PathDrilling.py | python | ObjectDrilling.initCircularHoleOperation | (self, obj) | initCircularHoleOperation(obj) ... add drilling specific properties to obj. | initCircularHoleOperation(obj) ... add drilling specific properties to obj. | [
"initCircularHoleOperation",
"(",
"obj",
")",
"...",
"add",
"drilling",
"specific",
"properties",
"to",
"obj",
"."
] | def initCircularHoleOperation(self, obj):
"""initCircularHoleOperation(obj) ... add drilling specific properties to obj."""
obj.addProperty(
"App::PropertyLength",
"PeckDepth",
"Drill",
QT_TRANSLATE_NOOP(
"App::Property",
"Incremental Drill depth before retracting to clear chips",
),
)
obj.addProperty(
"App::PropertyBool",
"PeckEnabled",
"Drill",
QT_TRANSLATE_NOOP("App::Property", "Enable pecking"),
)
obj.addProperty(
"App::PropertyFloat",
"DwellTime",
"Drill",
QT_TRANSLATE_NOOP("App::Property", "The time to dwell between peck cycles"),
)
obj.addProperty(
"App::PropertyBool",
"DwellEnabled",
"Drill",
QT_TRANSLATE_NOOP("App::Property", "Enable dwell"),
)
obj.addProperty(
"App::PropertyBool",
"AddTipLength",
"Drill",
QT_TRANSLATE_NOOP(
"App::Property",
"Calculate the tip length and subtract from final depth",
),
)
obj.addProperty(
"App::PropertyEnumeration",
"ReturnLevel",
"Drill",
QT_TRANSLATE_NOOP(
"App::Property", "Controls how tool retracts Default=G99"
),
)
obj.addProperty(
"App::PropertyDistance",
"RetractHeight",
"Drill",
QT_TRANSLATE_NOOP(
"App::Property",
"The height where feed starts and height during retract tool when path is finished while in a peck operation",
),
)
obj.addProperty(
"App::PropertyEnumeration",
"ExtraOffset",
"Drill",
QT_TRANSLATE_NOOP("App::Property", "How far the drill depth is extended"),
)
for n in self.propertyEnumerations():
setattr(obj, n[0], n[1]) | [
"def",
"initCircularHoleOperation",
"(",
"self",
",",
"obj",
")",
":",
"obj",
".",
"addProperty",
"(",
"\"App::PropertyLength\"",
",",
"\"PeckDepth\"",
",",
"\"Drill\"",
",",
"QT_TRANSLATE_NOOP",
"(",
"\"App::Property\"",
",",
"\"Incremental Drill depth before retracting ... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathDrilling.py#L101-L164 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/covariance/_elliptic_envelope.py | python | EllipticEnvelope.fit | (self, X, y=None) | return self | Fit the EllipticEnvelope model.
Parameters
----------
X : numpy array or sparse matrix, shape (n_samples, n_features).
Training data
y : Ignored
not used, present for API consistency by convention. | Fit the EllipticEnvelope model. | [
"Fit",
"the",
"EllipticEnvelope",
"model",
"."
] | def fit(self, X, y=None):
"""Fit the EllipticEnvelope model.
Parameters
----------
X : numpy array or sparse matrix, shape (n_samples, n_features).
Training data
y : Ignored
not used, present for API consistency by convention.
"""
super().fit(X)
self.offset_ = np.percentile(-self.dist_, 100. * self.contamination)
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"super",
"(",
")",
".",
"fit",
"(",
"X",
")",
"self",
".",
"offset_",
"=",
"np",
".",
"percentile",
"(",
"-",
"self",
".",
"dist_",
",",
"100.",
"*",
"self",
".",
"contamin... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/covariance/_elliptic_envelope.py#L117-L131 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/web-page-replay/customhandlers.py | python | SimpleResponse | (status) | return httparchive.create_response(status) | Return a ArchivedHttpResponse with |status| code and a simple text body. | Return a ArchivedHttpResponse with |status| code and a simple text body. | [
"Return",
"a",
"ArchivedHttpResponse",
"with",
"|status|",
"code",
"and",
"a",
"simple",
"text",
"body",
"."
] | def SimpleResponse(status):
"""Return a ArchivedHttpResponse with |status| code and a simple text body."""
return httparchive.create_response(status) | [
"def",
"SimpleResponse",
"(",
"status",
")",
":",
"return",
"httparchive",
".",
"create_response",
"(",
"status",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/customhandlers.py#L42-L44 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/linalg/_solvers.py | python | _solve_discrete_lyapunov_bilinear | (a, q) | return solve_lyapunov(b.conj().transpose(), -c) | Solves the discrete Lyapunov equation using a bilinear transformation.
This function is called by the `solve_discrete_lyapunov` function with
`method=bilinear`. It is not supposed to be called directly. | Solves the discrete Lyapunov equation using a bilinear transformation. | [
"Solves",
"the",
"discrete",
"Lyapunov",
"equation",
"using",
"a",
"bilinear",
"transformation",
"."
] | def _solve_discrete_lyapunov_bilinear(a, q):
"""
Solves the discrete Lyapunov equation using a bilinear transformation.
This function is called by the `solve_discrete_lyapunov` function with
`method=bilinear`. It is not supposed to be called directly.
"""
eye = np.eye(a.shape[0])
aH = a.conj().transpose()
aHI_inv = inv(aH + eye)
b = np.dot(aH - eye, aHI_inv)
c = 2*np.dot(np.dot(inv(a + eye), q), aHI_inv)
return solve_lyapunov(b.conj().transpose(), -c) | [
"def",
"_solve_discrete_lyapunov_bilinear",
"(",
"a",
",",
"q",
")",
":",
"eye",
"=",
"np",
".",
"eye",
"(",
"a",
".",
"shape",
"[",
"0",
"]",
")",
"aH",
"=",
"a",
".",
"conj",
"(",
")",
".",
"transpose",
"(",
")",
"aHI_inv",
"=",
"inv",
"(",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/linalg/_solvers.py#L142-L154 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/crywaflib/msvs.py | python | vsnode_target.GetPlatformSettings | (self, target_platform, target_configuration, entry, settings) | return result | Util function to apply flags based on current platform | Util function to apply flags based on current platform | [
"Util",
"function",
"to",
"apply",
"flags",
"based",
"on",
"current",
"platform"
] | def GetPlatformSettings(self, target_platform, target_configuration, entry, settings):
"""
Util function to apply flags based on current platform
"""
result = []
platforms = [target_platform]
# Append common win platform for windows hosts
if target_platform == 'win_x86' or target_platform == 'win_x64':
platforms.append('win')
if target_platform == 'linux_x86_gcc' or target_platform == 'linux_x64_gcc' or target_platform == 'linux_x86_clang' or target_platform == 'linux_x64_clang':
platforms.append('linux')
if target_platform == 'linux_x86_gcc' or target_platform == 'linux_x86_clang':
platforms.append('linux_x86')
if target_platform == 'linux_x64_gcc' or target_platform == 'linux_x64_clang':
platforms.append('linux_x64')
if target_platform == 'darwin_x86' or target_platform == 'darwin_x64':
platforms.append('darwin')
settings_dict = self.ConvertToDict(settings)
if not settings_dict:
Logs.error("[ERROR]: Unsupported type '%s' for 'settings' variable encountered." % type(settings))
return
# add non platform specific settings
try:
if isinstance(settings_dict[entry],list):
result += settings_dict[entry]
else:
result += [settings_dict[entry]]
except:
pass
# add per configuration flags
configuration_specific_name = ( target_configuration + '_' + entry )
try:
if isinstance(settings_dict[configuration_specific_name],list):
result += settings_dict[configuration_specific_name]
else:
result += [settings_dict[configuration_specific_name]]
except:
pass
# add per platform flags
for platform in platforms:
platform_specific_name = (platform + '_' + entry)
try:
if isinstance(settings_dict[platform_specific_name],list):
result += settings_dict[platform_specific_name]
else:
result += [settings_dict[platform_specific_name]]
except:
pass
# add per platform_configuration flags
for platform in platforms:
platform_configuration_specific_name = (platform + '_' + target_configuration + '_' + entry)
try:
if isinstance(settings_dict[platform_configuration_specific_name],list):
result += settings_dict[platform_configuration_specific_name]
else:
result += [settings_dict[platform_configuration_specific_name]]
except:
pass
return result | [
"def",
"GetPlatformSettings",
"(",
"self",
",",
"target_platform",
",",
"target_configuration",
",",
"entry",
",",
"settings",
")",
":",
"result",
"=",
"[",
"]",
"platforms",
"=",
"[",
"target_platform",
"]",
"# Append common win platform for windows hosts",
"if",
"... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/crywaflib/msvs.py#L1392-L1458 | |
papyrussolution/OpenPapyrus | bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91 | Src/OSF/protobuf-3.19.1/python/google/protobuf/descriptor.py | python | _ParseOptions | (message, string) | return message | Parses serialized options.
This helper function is used to parse serialized options in generated
proto2 files. It must not be used outside proto2. | Parses serialized options. | [
"Parses",
"serialized",
"options",
"."
] | def _ParseOptions(message, string):
"""Parses serialized options.
This helper function is used to parse serialized options in generated
proto2 files. It must not be used outside proto2.
"""
message.ParseFromString(string)
return message | [
"def",
"_ParseOptions",
"(",
"message",
",",
"string",
")",
":",
"message",
".",
"ParseFromString",
"(",
"string",
")",
"return",
"message"
] | https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/protobuf-3.19.1/python/google/protobuf/descriptor.py#L1022-L1029 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/ogl/_diagram.py | python | Diagram.InsertShape | (self, object) | Insert a shape at the front of the shape list. | Insert a shape at the front of the shape list. | [
"Insert",
"a",
"shape",
"at",
"the",
"front",
"of",
"the",
"shape",
"list",
"."
] | def InsertShape(self, object):
"""Insert a shape at the front of the shape list."""
self._shapeList.insert(0, object) | [
"def",
"InsertShape",
"(",
"self",
",",
"object",
")",
":",
"self",
".",
"_shapeList",
".",
"insert",
"(",
"0",
",",
"object",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/ogl/_diagram.py#L61-L63 | ||
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/boost_1.75.0/libs/metaparse/tools/benchmark/generate.py | python | Template._get_line | (self, regex) | return self._match(regex).group(1) | Get a line based on a regex | Get a line based on a regex | [
"Get",
"a",
"line",
"based",
"on",
"a",
"regex"
] | def _get_line(self, regex):
"""Get a line based on a regex"""
return self._match(regex).group(1) | [
"def",
"_get_line",
"(",
"self",
",",
"regex",
")",
":",
"return",
"self",
".",
"_match",
"(",
"regex",
")",
".",
"group",
"(",
"1",
")"
] | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/boost_1.75.0/libs/metaparse/tools/benchmark/generate.py#L175-L177 | |
chromiumembedded/cef | 80caf947f3fe2210e5344713c5281d8af9bdc295 | tools/crash_server.py | python | CrashHTTPRequestHandler.do_POST | (self) | Handle a multi-part POST request submitted by Breakpad/Crashpad. | Handle a multi-part POST request submitted by Breakpad/Crashpad. | [
"Handle",
"a",
"multi",
"-",
"part",
"POST",
"request",
"submitted",
"by",
"Breakpad",
"/",
"Crashpad",
"."
] | def do_POST(self):
""" Handle a multi-part POST request submitted by Breakpad/Crashpad. """
self._send_default_response_headers()
# Create a unique ID for the dump.
dump_id = self._create_new_dump_id()
# Return the unique ID to the caller.
self.wfile.write(dump_id.encode('utf-8'))
dmp_stream = None
metadata = {}
# Request body may be chunked and/or gzip compressed. For example:
#
# 3029 branch on Windows:
# User-Agent: Crashpad/0.8.0
# Host: localhost:8080
# Connection: Keep-Alive
# Transfer-Encoding: chunked
# Content-Type: multipart/form-data; boundary=---MultipartBoundary-vp5j9HdSRYK8DvX2DhtpqEbMNjSN1wnL---
# Content-Encoding: gzip
#
# 2987 branch on Windows:
# User-Agent: Crashpad/0.8.0
# Host: localhost:8080
# Connection: Keep-Alive
# Content-Type: multipart/form-data; boundary=---MultipartBoundary-qFhorGA40vDJ1fgmc2mjorL0fRfKOqup---
# Content-Length: 609894
#
# 2883 branch on Linux:
# User-Agent: Wget/1.15 (linux-gnu)
# Host: localhost:8080
# Accept: */*
# Connection: Keep-Alive
# Content-Type: multipart/form-data; boundary=--------------------------83572861f14cc736
# Content-Length: 32237
# Content-Encoding: gzip
print(self.headers)
chunked = 'Transfer-Encoding' in self.headers and self.headers['Transfer-Encoding'].lower(
) == 'chunked'
compressed = 'Content-Encoding' in self.headers and self.headers['Content-Encoding'].lower(
) == 'gzip'
if chunked:
request_body = self._unchunk_request(compressed)
else:
content_length = int(self.headers[
'Content-Length']) if 'Content-Length' in self.headers else 0
if content_length > 0:
request_body = self.rfile.read(content_length)
else:
request_body = self.rfile.read()
if compressed:
request_body = zlib.decompress(request_body, 16 + zlib.MAX_WBITS)
# Parse the multi-part request.
form_data = self._parse_post_data(request_body)
for key in form_data.keys():
if key == minidump_key and form_data[minidump_key].file:
dmp_stream = form_data[minidump_key].file
else:
metadata[key] = form_data[key].value
if dmp_stream is None:
# Exit early if the request is invalid.
print_msg('Invalid dump %s' % dump_id)
return
print_msg('Dump %s' % dump_id)
# Write the minidump to file.
dump_file = os.path.join(self._dump_directory, dump_id + '.dmp')
with open(dump_file, 'wb') as fp:
shutil.copyfileobj(dmp_stream, fp)
# Write the metadata to file.
meta_file = os.path.join(self._dump_directory, dump_id + '.json')
if is_python2:
with open(meta_file, 'w') as fp:
json.dump(
metadata,
fp,
ensure_ascii=False,
encoding='utf-8',
indent=2,
sort_keys=True)
else:
with open(meta_file, 'w', encoding='utf-8') as fp:
json.dump(metadata, fp, indent=2, sort_keys=True) | [
"def",
"do_POST",
"(",
"self",
")",
":",
"self",
".",
"_send_default_response_headers",
"(",
")",
"# Create a unique ID for the dump.",
"dump_id",
"=",
"self",
".",
"_create_new_dump_id",
"(",
")",
"# Return the unique ID to the caller.",
"self",
".",
"wfile",
".",
"w... | https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/crash_server.py#L224-L313 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/learn/python/learn/ops/seq2seq_ops.py | python | seq2seq_inputs | (x, y, input_length, output_length, sentinel=None, name=None) | Processes inputs for Sequence to Sequence models.
Args:
x: Input Tensor [batch_size, input_length, embed_dim].
y: Output Tensor [batch_size, output_length, embed_dim].
input_length: length of input x.
output_length: length of output y.
sentinel: optional first input to decoder and final output expected.
If sentinel is not provided, zeros are used. Due to fact that y is not
available in sampling time, shape of sentinel will be inferred from x.
name: Operation name.
Returns:
Encoder input from x, and decoder inputs and outputs from y. | Processes inputs for Sequence to Sequence models. | [
"Processes",
"inputs",
"for",
"Sequence",
"to",
"Sequence",
"models",
"."
] | def seq2seq_inputs(x, y, input_length, output_length, sentinel=None, name=None):
"""Processes inputs for Sequence to Sequence models.
Args:
x: Input Tensor [batch_size, input_length, embed_dim].
y: Output Tensor [batch_size, output_length, embed_dim].
input_length: length of input x.
output_length: length of output y.
sentinel: optional first input to decoder and final output expected.
If sentinel is not provided, zeros are used. Due to fact that y is not
available in sampling time, shape of sentinel will be inferred from x.
name: Operation name.
Returns:
Encoder input from x, and decoder inputs and outputs from y.
"""
with ops.op_scope([x, y], name, "seq2seq_inputs"):
in_x = array_ops_.unpack(x, axis=1)
y = array_ops_.unpack(y, axis=1)
if not sentinel:
# Set to zeros of shape of y[0], using x for batch size.
sentinel_shape = array_ops_.pack(
[array_ops_.shape(x)[0], y[0].get_shape()[1]])
sentinel = array_ops_.zeros(sentinel_shape)
sentinel.set_shape(y[0].get_shape())
in_y = [sentinel] + y
out_y = y + [sentinel]
return in_x, in_y, out_y | [
"def",
"seq2seq_inputs",
"(",
"x",
",",
"y",
",",
"input_length",
",",
"output_length",
",",
"sentinel",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"x",
",",
"y",
"]",
",",
"name",
",",
"\"seq2seq_input... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/learn/python/learn/ops/seq2seq_ops.py#L60-L87 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/pkg_resources/__init__.py | python | invalid_marker | (text) | return False | Validate text as a PEP 508 environment marker; return an exception
if invalid or False otherwise. | Validate text as a PEP 508 environment marker; return an exception
if invalid or False otherwise. | [
"Validate",
"text",
"as",
"a",
"PEP",
"508",
"environment",
"marker",
";",
"return",
"an",
"exception",
"if",
"invalid",
"or",
"False",
"otherwise",
"."
] | def invalid_marker(text):
"""
Validate text as a PEP 508 environment marker; return an exception
if invalid or False otherwise.
"""
try:
evaluate_marker(text)
except SyntaxError as e:
e.filename = None
e.lineno = None
return e
return False | [
"def",
"invalid_marker",
"(",
"text",
")",
":",
"try",
":",
"evaluate_marker",
"(",
"text",
")",
"except",
"SyntaxError",
"as",
"e",
":",
"e",
".",
"filename",
"=",
"None",
"e",
".",
"lineno",
"=",
"None",
"return",
"e",
"return",
"False"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/pkg_resources/__init__.py#L1346-L1357 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | tools/mo/openvino/tools/mo/back/SpecialNodesFinalization.py | python | CreateConstNodesReplacement._check_that_node_from_body | (node) | return np.any(internal_port_in_out_ports) and n_ports | Check that all output edges from node have 'internal_port_id'
(that shows that this node is from TI body) | Check that all output edges from node have 'internal_port_id'
(that shows that this node is from TI body) | [
"Check",
"that",
"all",
"output",
"edges",
"from",
"node",
"have",
"internal_port_id",
"(",
"that",
"shows",
"that",
"this",
"node",
"is",
"from",
"TI",
"body",
")"
] | def _check_that_node_from_body(node):
"""Check that all output edges from node have 'internal_port_id'
(that shows that this node is from TI body)"""
n_ports = len(node.out_edges())
internal_port_in_out_ports = ['internal_port_id' in edge for edge in node.out_edges()]
return np.any(internal_port_in_out_ports) and n_ports | [
"def",
"_check_that_node_from_body",
"(",
"node",
")",
":",
"n_ports",
"=",
"len",
"(",
"node",
".",
"out_edges",
"(",
")",
")",
"internal_port_in_out_ports",
"=",
"[",
"'internal_port_id'",
"in",
"edge",
"for",
"edge",
"in",
"node",
".",
"out_edges",
"(",
"... | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/back/SpecialNodesFinalization.py#L62-L67 | |
LLNL/lbann | 26083e6c86050302ce33148aea70f62e61cacb92 | applications/graph/GNN/NNConvModel.py | python | graph_data_splitter | (_input,
NUM_NODES,
NUM_EDGES,
NUM_NODE_FEATURES,
NUM_EDGE_FEATURES,
EMBEDDING_DIM,
EDGE_EMBEDDING_DIM) | return \
embedded_node_features, neighbor_feature_mat, embedded_edge_features, source_nodes, label | Helper function to split the input data into
Args:
NUM_NODES (int): The number of nodes in the largest graph in the dataset (51 for LSC-PPQM4M)
NUM_EDGES (int): The number of edges in the largest graph in the dataset (118 for LSC-PPQM4M)
NUM_NODE_FEATURES (int): The dimensionality of the input node features vector (9 for LSC-PPQM4M)
NUM_EDGE_FEATURES (int): The dimensionality of the input edge feature vectors (3 for LSC-PPQM4M)
EMBEDDING_DIM (int): The embedding dimensionality of the node feature vector
EDGE_EMBEDDING_DIM (int): The embedding dimensionality of the edge feature vector
Returns:
(Layer, Layer, Layer, Layer, Layer): Returns 5 Layers. The embedded node feature matrix, the
neighbord nodes feature tensor, the embedded edge feature matrix,
the source node index vector, and the label | Helper function to split the input data into | [
"Helper",
"function",
"to",
"split",
"the",
"input",
"data",
"into"
] | def graph_data_splitter(_input,
NUM_NODES,
NUM_EDGES,
NUM_NODE_FEATURES,
NUM_EDGE_FEATURES,
EMBEDDING_DIM,
EDGE_EMBEDDING_DIM):
"""Helper function to split the input data into
Args:
NUM_NODES (int): The number of nodes in the largest graph in the dataset (51 for LSC-PPQM4M)
NUM_EDGES (int): The number of edges in the largest graph in the dataset (118 for LSC-PPQM4M)
NUM_NODE_FEATURES (int): The dimensionality of the input node features vector (9 for LSC-PPQM4M)
NUM_EDGE_FEATURES (int): The dimensionality of the input edge feature vectors (3 for LSC-PPQM4M)
EMBEDDING_DIM (int): The embedding dimensionality of the node feature vector
EDGE_EMBEDDING_DIM (int): The embedding dimensionality of the edge feature vector
Returns:
(Layer, Layer, Layer, Layer, Layer): Returns 5 Layers. The embedded node feature matrix, the
neighbord nodes feature tensor, the embedded edge feature matrix,
the source node index vector, and the label
"""
split_indices = []
start_index = 0
split_indices.append(start_index)
node_feature = [NUM_NODES for i in range(1, NUM_NODE_FEATURES + 1)]
split_indices.extend(node_feature)
edge_features = [NUM_EDGES for i in range(1, NUM_EDGE_FEATURES + 1)]
split_indices.extend(edge_features)
edge_indices_sources = NUM_EDGES
split_indices.append(edge_indices_sources)
edge_indices_targets = NUM_EDGES
split_indices.append(edge_indices_targets)
target = 1
split_indices.append(target)
for i in range(1, len(split_indices)):
split_indices[i] = split_indices[i] + split_indices[i - 1]
graph_input = lbann.Slice(_input, axis=0,
slice_points=str_list(split_indices))
neighbor_feature_dims = str_list([NUM_EDGES, 1, EMBEDDING_DIM])
node_feature_columns = [lbann.Reshape(lbann.Identity(graph_input),
dims=str_list([NUM_NODES]),
name="node_ft_{}_col".format(x)) for x in range(NUM_NODE_FEATURES)]
edge_feature_columns = [lbann.Reshape(lbann.Identity(graph_input),
dims=str_list([NUM_EDGES]),
name="edge_ft_{}_col".format(x)) for x in range(NUM_EDGE_FEATURES)]
source_nodes = lbann.Reshape(lbann.Identity(graph_input),
dims=str_list([NUM_EDGES]),
name="source_nodes")
target_nodes = lbann.Reshape(lbann.Identity(graph_input),
dims=str_list([NUM_EDGES]),
name="target_nodes")
label = lbann.Reshape(lbann.Identity(graph_input),
dims=str_list([1]),
name="Graph_Label")
embedded_node_features = AtomEncoder(node_feature_columns, EMBEDDING_DIM)
embedded_edge_features = BondEncoder(edge_feature_columns, EDGE_EMBEDDING_DIM)
neighbor_features = lbann.Gather(embedded_node_features,
target_nodes,
axis=0)
neighbor_feature_mat = lbann.Reshape(neighbor_features,
dims=neighbor_feature_dims)
return \
embedded_node_features, neighbor_feature_mat, embedded_edge_features, source_nodes, label | [
"def",
"graph_data_splitter",
"(",
"_input",
",",
"NUM_NODES",
",",
"NUM_EDGES",
",",
"NUM_NODE_FEATURES",
",",
"NUM_EDGE_FEATURES",
",",
"EMBEDDING_DIM",
",",
"EDGE_EMBEDDING_DIM",
")",
":",
"split_indices",
"=",
"[",
"]",
"start_index",
"=",
"0",
"split_indices",
... | https://github.com/LLNL/lbann/blob/26083e6c86050302ce33148aea70f62e61cacb92/applications/graph/GNN/NNConvModel.py#L94-L174 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/dateutil/rrule.py | python | rrule.__str__ | (self) | return '\n'.join(output) | Output a string that would generate this RRULE if passed to rrulestr.
This is mostly compatible with RFC5545, except for the
dateutil-specific extension BYEASTER. | Output a string that would generate this RRULE if passed to rrulestr.
This is mostly compatible with RFC5545, except for the
dateutil-specific extension BYEASTER. | [
"Output",
"a",
"string",
"that",
"would",
"generate",
"this",
"RRULE",
"if",
"passed",
"to",
"rrulestr",
".",
"This",
"is",
"mostly",
"compatible",
"with",
"RFC5545",
"except",
"for",
"the",
"dateutil",
"-",
"specific",
"extension",
"BYEASTER",
"."
] | def __str__(self):
"""
Output a string that would generate this RRULE if passed to rrulestr.
This is mostly compatible with RFC5545, except for the
dateutil-specific extension BYEASTER.
"""
output = []
h, m, s = [None] * 3
if self._dtstart:
output.append(self._dtstart.strftime('DTSTART:%Y%m%dT%H%M%S'))
h, m, s = self._dtstart.timetuple()[3:6]
parts = ['FREQ=' + FREQNAMES[self._freq]]
if self._interval != 1:
parts.append('INTERVAL=' + str(self._interval))
if self._wkst:
parts.append('WKST=' + repr(weekday(self._wkst))[0:2])
if self._count is not None:
parts.append('COUNT=' + str(self._count))
if self._until:
parts.append(self._until.strftime('UNTIL=%Y%m%dT%H%M%S'))
if self._original_rule.get('byweekday') is not None:
# The str() method on weekday objects doesn't generate
# RFC5545-compliant strings, so we should modify that.
original_rule = dict(self._original_rule)
wday_strings = []
for wday in original_rule['byweekday']:
if wday.n:
wday_strings.append('{n:+d}{wday}'.format(
n=wday.n,
wday=repr(wday)[0:2]))
else:
wday_strings.append(repr(wday))
original_rule['byweekday'] = wday_strings
else:
original_rule = self._original_rule
partfmt = '{name}={vals}'
for name, key in [('BYSETPOS', 'bysetpos'),
('BYMONTH', 'bymonth'),
('BYMONTHDAY', 'bymonthday'),
('BYYEARDAY', 'byyearday'),
('BYWEEKNO', 'byweekno'),
('BYDAY', 'byweekday'),
('BYHOUR', 'byhour'),
('BYMINUTE', 'byminute'),
('BYSECOND', 'bysecond'),
('BYEASTER', 'byeaster')]:
value = original_rule.get(key)
if value:
parts.append(partfmt.format(name=name, vals=(','.join(str(v)
for v in value))))
output.append('RRULE:' + ';'.join(parts))
return '\n'.join(output) | [
"def",
"__str__",
"(",
"self",
")",
":",
"output",
"=",
"[",
"]",
"h",
",",
"m",
",",
"s",
"=",
"[",
"None",
"]",
"*",
"3",
"if",
"self",
".",
"_dtstart",
":",
"output",
".",
"append",
"(",
"self",
".",
"_dtstart",
".",
"strftime",
"(",
"'DTSTA... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/dateutil/rrule.py#L698-L758 | |
turi-code/SFrame | 796b9bdfb2fa1b881d82080754643c7e68629cd2 | oss_src/unity/python/sframe/data_structures/sarray.py | python | SArray.__init__ | (self, data=[], dtype=None, ignore_cast_failure=False, _proxy=None) | __init__(data=list(), dtype=None, ignore_cast_failure=False)
Construct a new SArray. The source of data includes: list,
numpy.ndarray, pandas.Series, and urls. | __init__(data=list(), dtype=None, ignore_cast_failure=False) | [
"__init__",
"(",
"data",
"=",
"list",
"()",
"dtype",
"=",
"None",
"ignore_cast_failure",
"=",
"False",
")"
] | def __init__(self, data=[], dtype=None, ignore_cast_failure=False, _proxy=None):
"""
__init__(data=list(), dtype=None, ignore_cast_failure=False)
Construct a new SArray. The source of data includes: list,
numpy.ndarray, pandas.Series, and urls.
"""
SArray.__construct_ctr += 1
if SArray.__construct_ctr % 1000 == 0:
_mt._get_metric_tracker().track('sarray.init1000')
if dtype is not None and type(dtype) != type:
raise TypeError('dtype must be a type, e.g. use int rather than \'int\'')
if (_proxy):
self.__proxy__ = _proxy
elif type(data) == SArray:
self.__proxy__ = data.__proxy__
else:
self.__proxy__ = UnitySArrayProxy(glconnect.get_client())
# we need to perform type inference
if dtype is None:
if HAS_PANDAS and isinstance(data, pandas.Series):
# if it is a pandas series get the dtype of the series
dtype = pytype_from_dtype(data.dtype)
if dtype == object:
# we need to get a bit more fine grained than that
dtype = infer_type_of_sequence(data.values)
elif HAS_NUMPY and isinstance(data, numpy.ndarray):
# first try the fast inproc method
try:
from .. import numpy_loader
if numpy_loader.numpy_activation_successful():
from ..numpy import _fast_numpy_to_sarray
ret = _fast_numpy_to_sarray(data)
# conversion is good!
# swap the proxy.
self.__proxy__, ret.__proxy__ = ret.__proxy__, self.__proxy__
return
else:
dtype = infer_type_of_sequence(data)
except:
pass
# if it is a numpy array, get the dtype of the array
dtype = pytype_from_dtype(data.dtype)
if dtype == object:
# we need to get a bit more fine grained than that
dtype = infer_type_of_sequence(data)
if len(data.shape) == 2:
# we need to make it an array or a list
if dtype == float or dtype == int:
dtype = array.array
else:
dtype = list
elif len(data.shape) > 2:
raise TypeError("Cannot convert Numpy arrays of greater than 2 dimensions")
elif (isinstance(data, str) or
(sys.version_info.major < 3 and isinstance(data, unicode))):
# if it is a file, we default to string
dtype = str
elif isinstance(data, array.array):
dtype = pytype_from_array_typecode(data.typecode)
elif isinstance(data, collections.Sequence):
# Covers any ordered python container and arrays.
# Convert it to a list first.
dtype = infer_type_of_sequence(data)
else:
dtype = None
if HAS_PANDAS and isinstance(data, pandas.Series):
with cython_context():
self.__proxy__.load_from_iterable(data.values, dtype, ignore_cast_failure)
elif (isinstance(data, str) or (sys.version_info.major <= 2 and isinstance(data, unicode))):
internal_url = _make_internal_url(data)
with cython_context():
self.__proxy__.load_autodetect(internal_url, dtype)
elif ((HAS_NUMPY and isinstance(data, numpy.ndarray))
or isinstance(data, array.array)
or isinstance(data, collections.Sequence)):
with cython_context():
self.__proxy__.load_from_iterable(data, dtype, ignore_cast_failure)
else:
raise TypeError("Unexpected data source. " \
"Possible data source types are: list, " \
"numpy.ndarray, pandas.Series, and string(url)") | [
"def",
"__init__",
"(",
"self",
",",
"data",
"=",
"[",
"]",
",",
"dtype",
"=",
"None",
",",
"ignore_cast_failure",
"=",
"False",
",",
"_proxy",
"=",
"None",
")",
":",
"SArray",
".",
"__construct_ctr",
"+=",
"1",
"if",
"SArray",
".",
"__construct_ctr",
... | https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/sarray.py#L308-L396 | ||
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2_ReadClock_REQUEST.fromTpm | (buf) | return buf.createObj(TPM2_ReadClock_REQUEST) | Returns new TPM2_ReadClock_REQUEST object constructed from its
marshaled representation in the given TpmBuffer buffer | Returns new TPM2_ReadClock_REQUEST object constructed from its
marshaled representation in the given TpmBuffer buffer | [
"Returns",
"new",
"TPM2_ReadClock_REQUEST",
"object",
"constructed",
"from",
"its",
"marshaled",
"representation",
"in",
"the",
"given",
"TpmBuffer",
"buffer"
] | def fromTpm(buf):
""" Returns new TPM2_ReadClock_REQUEST object constructed from its
marshaled representation in the given TpmBuffer buffer
"""
return buf.createObj(TPM2_ReadClock_REQUEST) | [
"def",
"fromTpm",
"(",
"buf",
")",
":",
"return",
"buf",
".",
"createObj",
"(",
"TPM2_ReadClock_REQUEST",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L16289-L16293 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/multi.py | python | MultiIndex._is_memory_usage_qualified | (self) | return any(f(l) for l in self._inferred_type_levels) | return a boolean if we need a qualified .info display | return a boolean if we need a qualified .info display | [
"return",
"a",
"boolean",
"if",
"we",
"need",
"a",
"qualified",
".",
"info",
"display"
] | def _is_memory_usage_qualified(self) -> bool:
""" return a boolean if we need a qualified .info display """
def f(l):
return "mixed" in l or "string" in l or "unicode" in l
return any(f(l) for l in self._inferred_type_levels) | [
"def",
"_is_memory_usage_qualified",
"(",
"self",
")",
"->",
"bool",
":",
"def",
"f",
"(",
"l",
")",
":",
"return",
"\"mixed\"",
"in",
"l",
"or",
"\"string\"",
"in",
"l",
"or",
"\"unicode\"",
"in",
"l",
"return",
"any",
"(",
"f",
"(",
"l",
")",
"for"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/multi.py#L1003-L1009 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | ConfigBase.Flush | (*args, **kwargs) | return _misc_.ConfigBase_Flush(*args, **kwargs) | Flush(self, bool currentOnly=False) -> bool
permanently writes all changes | Flush(self, bool currentOnly=False) -> bool | [
"Flush",
"(",
"self",
"bool",
"currentOnly",
"=",
"False",
")",
"-",
">",
"bool"
] | def Flush(*args, **kwargs):
"""
Flush(self, bool currentOnly=False) -> bool
permanently writes all changes
"""
return _misc_.ConfigBase_Flush(*args, **kwargs) | [
"def",
"Flush",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"ConfigBase_Flush",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L3319-L3325 | |
facebook/ThreatExchange | 31914a51820c73c8a0daffe62ccca29a6e3d359e | python-threatexchange/threatexchange/threat_updates.py | python | ThreatUpdateSerialization.load | (cls, state_dir: pathlib.Path) | Load this serialization from the state directory | Load this serialization from the state directory | [
"Load",
"this",
"serialization",
"from",
"the",
"state",
"directory"
] | def load(cls, state_dir: pathlib.Path) -> t.Iterable["ThreatUpdateSerialization"]:
"""Load this serialization from the state directory"""
raise NotImplementedError | [
"def",
"load",
"(",
"cls",
",",
"state_dir",
":",
"pathlib",
".",
"Path",
")",
"->",
"t",
".",
"Iterable",
"[",
"\"ThreatUpdateSerialization\"",
"]",
":",
"raise",
"NotImplementedError"
] | https://github.com/facebook/ThreatExchange/blob/31914a51820c73c8a0daffe62ccca29a6e3d359e/python-threatexchange/threatexchange/threat_updates.py#L52-L54 | ||
ArduPilot/ardupilot | 6e684b3496122b8158ac412b609d00004b7ac306 | libraries/SITL/examples/JSON/pybullet/robot.py | python | control_racecar | (pwm) | control racecar | control racecar | [
"control",
"racecar"
] | def control_racecar(pwm):
'''control racecar'''
steer_max = 45.0
throttle_max = 200.0
steering = constrain((pwm[0] - 1500.0)/500.0, -1, 1) * math.radians(steer_max) * -1
throttle = constrain((pwm[2] - 1500.0)/500.0, -1, 1) * throttle_max
robot.steer(steering)
robot.drive(throttle) | [
"def",
"control_racecar",
"(",
"pwm",
")",
":",
"steer_max",
"=",
"45.0",
"throttle_max",
"=",
"200.0",
"steering",
"=",
"constrain",
"(",
"(",
"pwm",
"[",
"0",
"]",
"-",
"1500.0",
")",
"/",
"500.0",
",",
"-",
"1",
",",
"1",
")",
"*",
"math",
".",
... | https://github.com/ArduPilot/ardupilot/blob/6e684b3496122b8158ac412b609d00004b7ac306/libraries/SITL/examples/JSON/pybullet/robot.py#L65-L73 | ||
clementine-player/Clementine | 111379dfd027802b59125829fcf87e3e1d0ad73b | dist/cpplint.py | python | CheckLanguage | (filename, clean_lines, linenum, file_extension,
include_state, nesting_state, error) | Checks rules from the 'C++ language rules' section of cppguide.html.
Some of these rules are hard to test (function overloading, using
uint32 inappropriately), but we do the best we can.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
file_extension: The extension (without the dot) of the filename.
include_state: An _IncludeState instance in which the headers are inserted.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found. | Checks rules from the 'C++ language rules' section of cppguide.html. | [
"Checks",
"rules",
"from",
"the",
"C",
"++",
"language",
"rules",
"section",
"of",
"cppguide",
".",
"html",
"."
] | def CheckLanguage(filename, clean_lines, linenum, file_extension,
include_state, nesting_state, error):
"""Checks rules from the 'C++ language rules' section of cppguide.html.
Some of these rules are hard to test (function overloading, using
uint32 inappropriately), but we do the best we can.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
file_extension: The extension (without the dot) of the filename.
include_state: An _IncludeState instance in which the headers are inserted.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# If the line is empty or consists of entirely a comment, no need to
# check it.
line = clean_lines.elided[linenum]
if not line:
return
match = _RE_PATTERN_INCLUDE.search(line)
if match:
CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
return
# Reset include state across preprocessor directives. This is meant
# to silence warnings for conditional includes.
match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line)
if match:
include_state.ResetSection(match.group(1))
# Make Windows paths like Unix.
fullname = os.path.abspath(filename).replace('\\', '/')
# Perform other checks now that we are sure that this is not an include line
CheckCasts(filename, clean_lines, linenum, error)
CheckGlobalStatic(filename, clean_lines, linenum, error)
CheckPrintf(filename, clean_lines, linenum, error)
if file_extension == 'h':
# TODO(unknown): check that 1-arg constructors are explicit.
# How to tell it's a constructor?
# (handled in CheckForNonStandardConstructs for now)
# TODO(unknown): check that classes declare or disable copy/assign
# (level 1 error)
pass
# Check if people are using the verboten C basic types. The only exception
# we regularly allow is "unsigned short port" for port.
if Search(r'\bshort port\b', line):
if not Search(r'\bunsigned short port\b', line):
error(filename, linenum, 'runtime/int', 4,
'Use "unsigned short" for ports, not "short"')
else:
match = Search(r'\b(short|long(?! +double)|long long)\b', line)
if match:
error(filename, linenum, 'runtime/int', 4,
'Use int16/int64/etc, rather than the C type %s' % match.group(1))
# Check if some verboten operator overloading is going on
# TODO(unknown): catch out-of-line unary operator&:
# class X {};
# int operator&(const X& x) { return 42; } // unary operator&
# The trick is it's hard to tell apart from binary operator&:
# class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
if Search(r'\boperator\s*&\s*\(\s*\)', line):
error(filename, linenum, 'runtime/operator', 4,
'Unary operator& is dangerous. Do not use it.')
# Check for suspicious usage of "if" like
# } if (a == b) {
if Search(r'\}\s*if\s*\(', line):
error(filename, linenum, 'readability/braces', 4,
'Did you mean "else if"? If not, start a new line for "if".')
# Check for potential format string bugs like printf(foo).
# We constrain the pattern not to pick things like DocidForPrintf(foo).
# Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
# TODO(unknown): Catch the following case. Need to change the calling
# convention of the whole function to process multiple line to handle it.
# printf(
# boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
if printf_args:
match = Match(r'([\w.\->()]+)$', printf_args)
if match and match.group(1) != '__VA_ARGS__':
function_name = re.search(r'\b((?:string)?printf)\s*\(',
line, re.I).group(1)
error(filename, linenum, 'runtime/printf', 4,
'Potential format string bug. Do %s("%%s", %s) instead.'
% (function_name, match.group(1)))
# Check for potential memset bugs like memset(buf, sizeof(buf), 0).
match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
error(filename, linenum, 'runtime/memset', 4,
'Did you mean "memset(%s, 0, %s)"?'
% (match.group(1), match.group(2)))
if Search(r'\busing namespace\b', line):
error(filename, linenum, 'build/namespaces', 5,
'Do not use namespace using-directives. '
'Use using-declarations instead.')
# Detect variable-length arrays.
match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
match.group(3).find(']') == -1):
# Split the size using space and arithmetic operators as delimiters.
# If any of the resulting tokens are not compile time constants then
# report the error.
tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
is_const = True
skip_next = False
for tok in tokens:
if skip_next:
skip_next = False
continue
if Search(r'sizeof\(.+\)', tok): continue
if Search(r'arraysize\(\w+\)', tok): continue
tok = tok.lstrip('(')
tok = tok.rstrip(')')
if not tok: continue
if Match(r'\d+', tok): continue
if Match(r'0[xX][0-9a-fA-F]+', tok): continue
if Match(r'k[A-Z0-9]\w*', tok): continue
if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
# A catch all for tricky sizeof cases, including 'sizeof expression',
# 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
# requires skipping the next token because we split on ' ' and '*'.
if tok.startswith('sizeof'):
skip_next = True
continue
is_const = False
break
if not is_const:
error(filename, linenum, 'runtime/arrays', 1,
'Do not use variable-length arrays. Use an appropriately named '
"('k' followed by CamelCase) compile-time constant for the size.")
# If DISALLOW_COPY_AND_ASSIGN DISALLOW_IMPLICIT_CONSTRUCTORS is present,
# then it should be the last thing in the class declaration.
match = Match(
(r'\s*'
r'(DISALLOW_(COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))'
r'\(.*\);$'),
line)
if match and linenum + 1 < clean_lines.NumLines():
next_line = clean_lines.elided[linenum + 1]
# We allow some, but not all, declarations of variables to be present
# in the statement that defines the class. The [\w\*,\s]* fragment of
# the regular expression below allows users to declare instances of
# the class or pointers to instances, but not less common types such
# as function pointers or arrays. It's a tradeoff between allowing
# reasonable code and avoiding trying to parse more C++ using regexps.
if not Search(r'^\s*}[\w\*,\s]*;', next_line):
error(filename, linenum, 'readability/constructors', 3,
match.group(1) + ' should be the last thing in the class')
# Check for use of unnamed namespaces in header files. Registration
# macros are typically OK, so we allow use of "namespace {" on lines
# that end with backslashes.
if (file_extension == 'h'
and Search(r'\bnamespace\s*{', line)
and line[-1] != '\\'):
error(filename, linenum, 'build/namespaces', 4,
'Do not use unnamed namespaces in header files. See '
'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
' for more information.') | [
"def",
"CheckLanguage",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"file_extension",
",",
"include_state",
",",
"nesting_state",
",",
"error",
")",
":",
"# If the line is empty or consists of entirely a comment, no need to",
"# check it.",
"line",
"=",
"cle... | https://github.com/clementine-player/Clementine/blob/111379dfd027802b59125829fcf87e3e1d0ad73b/dist/cpplint.py#L4613-L4787 | ||
Caffe-MPI/Caffe-MPI.github.io | df5992af571a2a19981b69635115c393f18d1c76 | python/draw_net.py | python | parse_args | () | return args | Parse input arguments | Parse input arguments | [
"Parse",
"input",
"arguments"
] | def parse_args():
"""Parse input arguments
"""
parser = ArgumentParser(description=__doc__,
formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument('input_net_proto_file',
help='Input network prototxt file')
parser.add_argument('output_image_file',
help='Output image file')
parser.add_argument('--rankdir',
help=('One of TB (top-bottom, i.e., vertical), '
'RL (right-left, i.e., horizontal), or another '
'valid dot option; see '
'http://www.graphviz.org/doc/info/'
'attrs.html#k:rankdir'),
default='LR')
args = parser.parse_args()
return args | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
",",
"formatter_class",
"=",
"ArgumentDefaultsHelpFormatter",
")",
"parser",
".",
"add_argument",
"(",
"'input_net_proto_file'",
",",
"help",
"=",
"'Input networ... | https://github.com/Caffe-MPI/Caffe-MPI.github.io/blob/df5992af571a2a19981b69635115c393f18d1c76/python/draw_net.py#L13-L33 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/gyp/pylib/gyp/common.py | python | WriteOnDiff | (filename) | return Writer() | Write to a file only if the new contents differ.
Arguments:
filename: name of the file to potentially write to.
Returns:
A file like object which will write to temporary file and only overwrite
the target if it differs (on close). | Write to a file only if the new contents differ. | [
"Write",
"to",
"a",
"file",
"only",
"if",
"the",
"new",
"contents",
"differ",
"."
] | def WriteOnDiff(filename):
"""Write to a file only if the new contents differ.
Arguments:
filename: name of the file to potentially write to.
Returns:
A file like object which will write to temporary file and only overwrite
the target if it differs (on close).
"""
class Writer(object):
"""Wrapper around file which only covers the target if it differs."""
def __init__(self):
# On Cygwin remove the "dir" argument because `C:` prefixed paths are treated as relative,
# consequently ending up with current dir "/cygdrive/c/..." being prefixed to those, which was
# obviously a non-existent path, for example: "/cygdrive/c/<some folder>/C:\<my win style abs path>".
# See https://docs.python.org/2/library/tempfile.html#tempfile.mkstemp for more details
base_temp_dir = "" if IsCygwin() else os.path.dirname(filename)
# Pick temporary file.
tmp_fd, self.tmp_path = tempfile.mkstemp(
suffix='.tmp',
prefix=os.path.split(filename)[1] + '.gyp.',
dir=base_temp_dir)
try:
self.tmp_file = os.fdopen(tmp_fd, 'wb')
except Exception:
# Don't leave turds behind.
os.unlink(self.tmp_path)
raise
def __getattr__(self, attrname):
# Delegate everything else to self.tmp_file
return getattr(self.tmp_file, attrname)
def close(self):
try:
# Close tmp file.
self.tmp_file.close()
# Determine if different.
same = False
try:
same = filecmp.cmp(self.tmp_path, filename, False)
except OSError as e:
if e.errno != errno.ENOENT:
raise
if same:
# The new file is identical to the old one, just get rid of the new
# one.
os.unlink(self.tmp_path)
else:
# The new file is different from the old one, or there is no old one.
# Rename the new file to the permanent name.
#
# tempfile.mkstemp uses an overly restrictive mode, resulting in a
# file that can only be read by the owner, regardless of the umask.
# There's no reason to not respect the umask here, which means that
# an extra hoop is required to fetch it and reset the new file's mode.
#
# No way to get the umask without setting a new one? Set a safe one
# and then set it back to the old value.
umask = os.umask(0o77)
os.umask(umask)
os.chmod(self.tmp_path, 0o666 & ~umask)
if sys.platform == 'win32' and os.path.exists(filename):
# NOTE: on windows (but not cygwin) rename will not replace an
# existing file, so it must be preceded with a remove. Sadly there
# is no way to make the switch atomic.
os.remove(filename)
os.rename(self.tmp_path, filename)
except Exception:
# Don't leave turds behind.
os.unlink(self.tmp_path)
raise
def write(self, s):
self.tmp_file.write(s.encode('utf-8'))
return Writer() | [
"def",
"WriteOnDiff",
"(",
"filename",
")",
":",
"class",
"Writer",
"(",
"object",
")",
":",
"\"\"\"Wrapper around file which only covers the target if it differs.\"\"\"",
"def",
"__init__",
"(",
"self",
")",
":",
"# On Cygwin remove the \"dir\" argument because `C:` prefixed p... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/common.py#L334-L412 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Inelastic/Direct/ReductionWrapper.py | python | ReductionWrapper._check_progress_log_run_completed | (self,run_number_requested) | return(run_written >= run_number_requested,run_written,'') | Method to verify experiment progress log file and check if the file to reduce
has been written.
Input:
run_number_requested -- the number expected to be in logged in the log file
Output:
returns: (True,run_number_written,'') if the run_number stored in the log is
higher then the run number requested
(False,run_number_written,'') if the stored number is lower then the requested
If progress log is nod defined or not available, the method returns True, last known run number
and additional text information indicating the reason for failure
so further checks are necessary to verify if actual file is indeed available | Method to verify experiment progress log file and check if the file to reduce
has been written.
Input:
run_number_requested -- the number expected to be in logged in the log file | [
"Method",
"to",
"verify",
"experiment",
"progress",
"log",
"file",
"and",
"check",
"if",
"the",
"file",
"to",
"reduce",
"has",
"been",
"written",
".",
"Input",
":",
"run_number_requested",
"--",
"the",
"number",
"expected",
"to",
"be",
"in",
"logged",
"in",
... | def _check_progress_log_run_completed(self,run_number_requested):
""" Method to verify experiment progress log file and check if the file to reduce
has been written.
Input:
run_number_requested -- the number expected to be in logged in the log file
Output:
returns: (True,run_number_written,'') if the run_number stored in the log is
higher then the run number requested
(False,run_number_written,'') if the stored number is lower then the requested
If progress log is nod defined or not available, the method returns True, last known run number
and additional text information indicating the reason for failure
so further checks are necessary to verify if actual file is indeed available
"""
propman = self.reducer.prop_man
if len(propman.archive_upload_log_file)==0 :
return (True,0,'log test disabled as no log file available')
mod_time = os.path.getmtime(propman.archive_upload_log_file)
if self._last_commit_log_modification_time == mod_time: # Still old data in archive
run_num = self._last_runnum_added_to_archive
return (run_num >= run_number_requested,run_num,'no new data have been added to archive')
self._last_commit_log_modification_time = mod_time
# Here the file may be modified during the access. Let's try to catch
# any errors, which may occur due to this modification
try:
with open(propman.archive_upload_log_file) as fh:
contents = fh.read()
except:
return(False,self._last_runnum_added_to_archive,
'Error accessing log file {0}'.format(propman.archive_upload_log_file))
# If the file is modified during the read operation, the read can return anything
# Let's be on a safe side and guard the contents parsing too.
try:
contents = contents.split()
run_written = int(contents[1])
except:
return(False,self._last_runnum_added_to_archive,
'Error processing the contents of the log file {0}'.format(propman.archive_upload_log_file))
self._last_runnum_added_to_archive = run_written
return(run_written >= run_number_requested,run_written,'') | [
"def",
"_check_progress_log_run_completed",
"(",
"self",
",",
"run_number_requested",
")",
":",
"propman",
"=",
"self",
".",
"reducer",
".",
"prop_man",
"if",
"len",
"(",
"propman",
".",
"archive_upload_log_file",
")",
"==",
"0",
":",
"return",
"(",
"True",
",... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/Direct/ReductionWrapper.py#L450-L492 | |
PixarAnimationStudios/USD | faed18ce62c8736b02413635b584a2f637156bad | pxr/usdImaging/usdviewq/appController.py | python | AppController._updateOnFrameChange | (self) | Called when the frame changes, updates the renderer and such | Called when the frame changes, updates the renderer and such | [
"Called",
"when",
"the",
"frame",
"changes",
"updates",
"the",
"renderer",
"and",
"such"
] | def _updateOnFrameChange(self):
"""Called when the frame changes, updates the renderer and such"""
# do not update HUD/BBOX if scrubbing or playing
if not (self._dataModel.playing or self._ui.frameSlider.isSliderDown()):
self._updateGUIForFrameChange()
if self._stageView:
# this is the part that renders
if self._dataModel.playing:
highlightMode = self._dataModel.viewSettings.selHighlightMode
if highlightMode == SelectionHighlightModes.ALWAYS:
# We don't want to resend the selection to the renderer
# every frame during playback unless we are actually going
# to see the selection (which is only when highlight mode is
# ALWAYS).
self._stageView.updateSelection()
self._stageView.updateForPlayback()
else:
self._stageView.updateSelection()
self._stageView.updateView() | [
"def",
"_updateOnFrameChange",
"(",
"self",
")",
":",
"# do not update HUD/BBOX if scrubbing or playing",
"if",
"not",
"(",
"self",
".",
"_dataModel",
".",
"playing",
"or",
"self",
".",
"_ui",
".",
"frameSlider",
".",
"isSliderDown",
"(",
")",
")",
":",
"self",
... | https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/appController.py#L3490-L3508 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/variables.py | python | Variable._TensorConversionFunction | (v, dtype=None, name=None, as_ref=False) | Utility function for converting a Variable to a Tensor. | Utility function for converting a Variable to a Tensor. | [
"Utility",
"function",
"for",
"converting",
"a",
"Variable",
"to",
"a",
"Tensor",
"."
] | def _TensorConversionFunction(v, dtype=None, name=None, as_ref=False): # pylint: disable=invalid-name
"""Utility function for converting a Variable to a Tensor."""
_ = name
if dtype and not dtype.is_compatible_with(v.dtype):
raise ValueError(
"Incompatible type conversion requested to type '%s' for variable "
"of type '%s'" % (dtype.name, v.dtype.name))
if as_ref:
return v._ref() # pylint: disable=protected-access
else:
return v.value() | [
"def",
"_TensorConversionFunction",
"(",
"v",
",",
"dtype",
"=",
"None",
",",
"name",
"=",
"None",
",",
"as_ref",
"=",
"False",
")",
":",
"# pylint: disable=invalid-name",
"_",
"=",
"name",
"if",
"dtype",
"and",
"not",
"dtype",
".",
"is_compatible_with",
"("... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/variables.py#L671-L681 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/aui/framemanager.py | python | AuiManager.DetachPane | (self, window) | return False | Tells the :class:`AuiManager` to stop managing the pane specified
by `window`. The window, if in a floated frame, is reparented to the frame
managed by :class:`AuiManager`.
:param Window `window`: the window to be un-managed. | Tells the :class:`AuiManager` to stop managing the pane specified
by `window`. The window, if in a floated frame, is reparented to the frame
managed by :class:`AuiManager`. | [
"Tells",
"the",
":",
"class",
":",
"AuiManager",
"to",
"stop",
"managing",
"the",
"pane",
"specified",
"by",
"window",
".",
"The",
"window",
"if",
"in",
"a",
"floated",
"frame",
"is",
"reparented",
"to",
"the",
"frame",
"managed",
"by",
":",
"class",
":"... | def DetachPane(self, window):
"""
Tells the :class:`AuiManager` to stop managing the pane specified
by `window`. The window, if in a floated frame, is reparented to the frame
managed by :class:`AuiManager`.
:param Window `window`: the window to be un-managed.
"""
for p in self._panes:
if p.window == window:
if p.frame:
# we have a floating frame which is being detached. We need to
# reparent it to self._frame and destroy the floating frame
# reduce flicker
p.window.SetSize((1, 1))
if p.frame.IsShown():
p.frame.Show(False)
if self._action_window == p.frame:
self._action_window = None
# reparent to self._frame and destroy the pane
p.window.Reparent(self._frame)
p.frame.SetSizer(None)
p.frame.Destroy()
p.frame = None
elif p.IsNotebookPage():
notebook = self._notebooks[p.notebook_id]
id = notebook.GetPageIndex(p.window)
notebook.RemovePage(id)
p.window.Reparent(self._frame)
# make sure there are no references to this pane in our uiparts,
# just in case the caller doesn't call Update() immediately after
# the DetachPane() call. This prevets obscure crashes which would
# happen at window repaint if the caller forgets to call Update()
counter = 0
for pi in xrange(len(self._uiparts)):
part = self._uiparts[counter]
if part.pane == p:
self._uiparts.pop(counter)
counter -= 1
counter += 1
self._panes.remove(p)
return True
return False | [
"def",
"DetachPane",
"(",
"self",
",",
"window",
")",
":",
"for",
"p",
"in",
"self",
".",
"_panes",
":",
"if",
"p",
".",
"window",
"==",
"window",
":",
"if",
"p",
".",
"frame",
":",
"# we have a floating frame which is being detached. We need to",
"# reparent ... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/framemanager.py#L4941-L4992 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/distributions/continuous_bernoulli.py | python | ContinuousBernoulli._cont_bern_log_norm | (self) | return torch.where(self._outside_unstable_region(), log_norm, taylor) | computes the log normalizing constant as a function of the 'probs' parameter | computes the log normalizing constant as a function of the 'probs' parameter | [
"computes",
"the",
"log",
"normalizing",
"constant",
"as",
"a",
"function",
"of",
"the",
"probs",
"parameter"
] | def _cont_bern_log_norm(self):
'''computes the log normalizing constant as a function of the 'probs' parameter'''
cut_probs = self._cut_probs()
cut_probs_below_half = torch.where(torch.le(cut_probs, 0.5),
cut_probs,
torch.zeros_like(cut_probs))
cut_probs_above_half = torch.where(torch.ge(cut_probs, 0.5),
cut_probs,
torch.ones_like(cut_probs))
log_norm = torch.log(torch.abs(torch.log1p(-cut_probs) - torch.log(cut_probs))) - torch.where(
torch.le(cut_probs, 0.5),
torch.log1p(-2.0 * cut_probs_below_half),
torch.log(2.0 * cut_probs_above_half - 1.0))
x = torch.pow(self.probs - 0.5, 2)
taylor = math.log(2.0) + (4.0 / 3.0 + 104.0 / 45.0 * x) * x
return torch.where(self._outside_unstable_region(), log_norm, taylor) | [
"def",
"_cont_bern_log_norm",
"(",
"self",
")",
":",
"cut_probs",
"=",
"self",
".",
"_cut_probs",
"(",
")",
"cut_probs_below_half",
"=",
"torch",
".",
"where",
"(",
"torch",
".",
"le",
"(",
"cut_probs",
",",
"0.5",
")",
",",
"cut_probs",
",",
"torch",
".... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributions/continuous_bernoulli.py#L91-L106 | |
ApolloAuto/apollo | 463fb82f9e979d02dcb25044e60931293ab2dba0 | modules/tools/navigator/dbmap/libs/point.py | python | PointUtils.latlon2latlondict | (lat, lon) | return {'lat': lat, 'lng': lon} | latlon to latlon dictionary | latlon to latlon dictionary | [
"latlon",
"to",
"latlon",
"dictionary"
] | def latlon2latlondict(lat, lon):
"""latlon to latlon dictionary"""
return {'lat': lat, 'lng': lon} | [
"def",
"latlon2latlondict",
"(",
"lat",
",",
"lon",
")",
":",
"return",
"{",
"'lat'",
":",
"lat",
",",
"'lng'",
":",
"lon",
"}"
] | https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/modules/tools/navigator/dbmap/libs/point.py#L59-L61 | |
rsummers11/CADLab | 976ed959a0b5208bb4173127a7ef732ac73a9b6f | lesion_detector_3DCE/rcnn/symbol/symbol_vgg.py | python | get_vgg | (is_train, num_classes=config.NUM_CLASSES, num_anchors=config.NUM_ANCHORS) | return group | end-to-end train with VGG 16 conv layers with RPN
:param num_classes: used to determine output size
:param num_anchors: used to determine output size
:return: Symbol | end-to-end train with VGG 16 conv layers with RPN
:param num_classes: used to determine output size
:param num_anchors: used to determine output size
:return: Symbol | [
"end",
"-",
"to",
"-",
"end",
"train",
"with",
"VGG",
"16",
"conv",
"layers",
"with",
"RPN",
":",
"param",
"num_classes",
":",
"used",
"to",
"determine",
"output",
"size",
":",
"param",
"num_anchors",
":",
"used",
"to",
"determine",
"output",
"size",
":"... | def get_vgg(is_train, num_classes=config.NUM_CLASSES, num_anchors=config.NUM_ANCHORS):
"""
end-to-end train with VGG 16 conv layers with RPN
:param num_classes: used to determine output size
:param num_anchors: used to determine output size
:return: Symbol
"""
# data
data = mx.symbol.Variable(name="data")
im_info = mx.symbol.Variable(name="im_info")
if is_train:
gt_boxes = mx.symbol.Variable(name="gt_boxes")
rpn_label = mx.symbol.Variable(name='label')
rpn_bbox_target = mx.symbol.Variable(name='bbox_target')
rpn_bbox_weight = mx.symbol.Variable(name='bbox_weight')
# shared convolutional layers
relu5_3 = get_vgg_conv(data)
# RPN
if is_train:
rois, rpn_cls_prob, rpn_bbox_loss = _get_rpn(
is_train, relu5_3, im_info, num_anchors, rpn_label, rpn_bbox_target, rpn_bbox_weight)
# ROI proposal target
group = mx.symbol.Custom(rois=rois, gt_boxes=gt_boxes, op_type='proposal_target',
num_classes=num_classes, batch_images=config.TRAIN.SAMPLES_PER_BATCH,
batch_rois=config.TRAIN.BATCH_ROIS, fg_fraction=config.TRAIN.FG_FRACTION)
rois, label, bbox_target, bbox_weight = group
else:
rois = _get_rpn(is_train, relu5_3, im_info, num_anchors)
# RCNN head
cls_score, bbox_pred = eval('_get_'+config.FRAMEWORK+'_head')(is_train, relu5_3, rois, num_classes)
# loss and output
if is_train:
cls_prob = mx.symbol.SoftmaxOutput(name='cls_prob', data=cls_score, label=label, normalization='batch')
bbox_loss_ = bbox_weight * mx.symbol.smooth_l1(name='bbox_loss_', scalar=1.0, data=(bbox_pred - bbox_target))
bbox_loss_norm = bbox_loss_ / config.TRAIN.BATCH_ROIS / config.TRAIN.SAMPLES_PER_BATCH
bbox_loss = mx.sym.MakeLoss(name='bbox_loss', data=bbox_loss_norm, grad_scale=config.TRAIN.RCNN_REG_LOSS_WEIGHT)
# reshape output
label = mx.symbol.Reshape(data=label, shape=(config.TRAIN.SAMPLES_PER_BATCH, -1), name='label_reshape')
cls_prob = mx.symbol.Reshape(data=cls_prob, shape=(config.TRAIN.SAMPLES_PER_BATCH, -1, num_classes), name='cls_prob_reshape')
bbox_loss = mx.symbol.Reshape(data=bbox_loss, shape=(config.TRAIN.SAMPLES_PER_BATCH, -1, 4 * num_classes), name='bbox_loss_reshape')
group = mx.symbol.Group([rpn_cls_prob, rpn_bbox_loss, cls_prob, bbox_loss, mx.symbol.BlockGrad(label)])
else:
cls_prob = mx.symbol.softmax(name='cls_prob', data=cls_score)
# reshape output
batchsize = config.TEST.SAMPLES_PER_BATCH
cls_prob = mx.symbol.Reshape(data=cls_prob, shape=(batchsize, -1, num_classes), name='cls_prob_reshape')
bbox_pred = mx.symbol.Reshape(data=bbox_pred, shape=(batchsize, -1, 4 * num_classes), name='bbox_pred_reshape')
group = mx.symbol.Group([rois, cls_prob, bbox_pred])
return group | [
"def",
"get_vgg",
"(",
"is_train",
",",
"num_classes",
"=",
"config",
".",
"NUM_CLASSES",
",",
"num_anchors",
"=",
"config",
".",
"NUM_ANCHORS",
")",
":",
"# data",
"data",
"=",
"mx",
".",
"symbol",
".",
"Variable",
"(",
"name",
"=",
"\"data\"",
")",
"im... | https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/lesion_detector_3DCE/rcnn/symbol/symbol_vgg.py#L186-L241 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/examples/speech_commands/models.py | python | create_low_latency_svdf_model | (fingerprint_input, model_settings,
is_training, runtime_settings) | Builds an SVDF model with low compute requirements.
This is based in the topology presented in the 'Compressing Deep Neural
Networks using a Rank-Constrained Topology' paper:
https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/43813.pdf
Here's the layout of the graph:
(fingerprint_input)
v
[SVDF]<-(weights)
v
[BiasAdd]<-(bias)
v
[Relu]
v
[MatMul]<-(weights)
v
[BiasAdd]<-(bias)
v
[MatMul]<-(weights)
v
[BiasAdd]<-(bias)
v
[MatMul]<-(weights)
v
[BiasAdd]<-(bias)
v
This model produces lower recognition accuracy than the 'conv' model above,
but requires fewer weight parameters and, significantly fewer computations.
During training, dropout nodes are introduced after the relu, controlled by a
placeholder.
Args:
fingerprint_input: TensorFlow node that will output audio feature vectors.
The node is expected to produce a 2D Tensor of shape:
[batch, model_settings['dct_coefficient_count'] *
model_settings['spectrogram_length']]
with the features corresponding to the same time slot arranged contiguously,
and the oldest slot at index [:, 0], and newest at [:, -1].
model_settings: Dictionary of information about the model.
is_training: Whether the model is going to be used for training.
runtime_settings: Dictionary of information about the runtime.
Returns:
TensorFlow node outputting logits results, and optionally a dropout
placeholder.
Raises:
ValueError: If the inputs tensor is incorrectly shaped. | Builds an SVDF model with low compute requirements. | [
"Builds",
"an",
"SVDF",
"model",
"with",
"low",
"compute",
"requirements",
"."
] | def create_low_latency_svdf_model(fingerprint_input, model_settings,
is_training, runtime_settings):
"""Builds an SVDF model with low compute requirements.
This is based in the topology presented in the 'Compressing Deep Neural
Networks using a Rank-Constrained Topology' paper:
https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/43813.pdf
Here's the layout of the graph:
(fingerprint_input)
v
[SVDF]<-(weights)
v
[BiasAdd]<-(bias)
v
[Relu]
v
[MatMul]<-(weights)
v
[BiasAdd]<-(bias)
v
[MatMul]<-(weights)
v
[BiasAdd]<-(bias)
v
[MatMul]<-(weights)
v
[BiasAdd]<-(bias)
v
This model produces lower recognition accuracy than the 'conv' model above,
but requires fewer weight parameters and, significantly fewer computations.
During training, dropout nodes are introduced after the relu, controlled by a
placeholder.
Args:
fingerprint_input: TensorFlow node that will output audio feature vectors.
The node is expected to produce a 2D Tensor of shape:
[batch, model_settings['dct_coefficient_count'] *
model_settings['spectrogram_length']]
with the features corresponding to the same time slot arranged contiguously,
and the oldest slot at index [:, 0], and newest at [:, -1].
model_settings: Dictionary of information about the model.
is_training: Whether the model is going to be used for training.
runtime_settings: Dictionary of information about the runtime.
Returns:
TensorFlow node outputting logits results, and optionally a dropout
placeholder.
Raises:
ValueError: If the inputs tensor is incorrectly shaped.
"""
if is_training:
dropout_prob = tf.placeholder(tf.float32, name='dropout_prob')
input_frequency_size = model_settings['dct_coefficient_count']
input_time_size = model_settings['spectrogram_length']
# Validation.
input_shape = fingerprint_input.get_shape()
if len(input_shape) != 2:
raise ValueError('Inputs to `SVDF` should have rank == 2.')
if input_shape[-1].value is None:
raise ValueError('The last dimension of the inputs to `SVDF` '
'should be defined. Found `None`.')
if input_shape[-1].value % input_frequency_size != 0:
raise ValueError('Inputs feature dimension %d must be a multiple of '
'frame size %d', fingerprint_input.shape[-1].value,
input_frequency_size)
# Set number of units (i.e. nodes) and rank.
rank = 2
num_units = 1280
# Number of filters: pairs of feature and time filters.
num_filters = rank * num_units
# Create the runtime memory: [num_filters, batch, input_time_size]
batch = 1
memory = tf.Variable(tf.zeros([num_filters, batch, input_time_size]),
trainable=False, name='runtime-memory')
# Determine the number of new frames in the input, such that we only operate
# on those. For training we do not use the memory, and thus use all frames
# provided in the input.
# new_fingerprint_input: [batch, num_new_frames*input_frequency_size]
if is_training:
num_new_frames = input_time_size
else:
window_stride_ms = int(model_settings['window_stride_samples'] * 1000 /
model_settings['sample_rate'])
num_new_frames = tf.cond(
tf.equal(tf.count_nonzero(memory), 0),
lambda: input_time_size,
lambda: int(runtime_settings['clip_stride_ms'] / window_stride_ms))
new_fingerprint_input = fingerprint_input[
:, -num_new_frames*input_frequency_size:]
# Expand to add input channels dimension.
new_fingerprint_input = tf.expand_dims(new_fingerprint_input, 2)
# Create the frequency filters.
weights_frequency = tf.Variable(
tf.truncated_normal([input_frequency_size, num_filters], stddev=0.01))
# Expand to add input channels dimensions.
# weights_frequency: [input_frequency_size, 1, num_filters]
weights_frequency = tf.expand_dims(weights_frequency, 1)
# Convolve the 1D feature filters sliding over the time dimension.
# activations_time: [batch, num_new_frames, num_filters]
activations_time = tf.nn.conv1d(
new_fingerprint_input, weights_frequency, input_frequency_size, 'VALID')
# Rearrange such that we can perform the batched matmul.
# activations_time: [num_filters, batch, num_new_frames]
activations_time = tf.transpose(activations_time, perm=[2, 0, 1])
# Runtime memory optimization.
if not is_training:
# We need to drop the activations corresponding to the oldest frames, and
# then add those corresponding to the new frames.
new_memory = memory[:, :, num_new_frames:]
new_memory = tf.concat([new_memory, activations_time], 2)
tf.assign(memory, new_memory)
activations_time = new_memory
# Create the time filters.
weights_time = tf.Variable(
tf.truncated_normal([num_filters, input_time_size], stddev=0.01))
# Apply the time filter on the outputs of the feature filters.
# weights_time: [num_filters, input_time_size, 1]
# outputs: [num_filters, batch, 1]
weights_time = tf.expand_dims(weights_time, 2)
outputs = tf.matmul(activations_time, weights_time)
# Split num_units and rank into separate dimensions (the remaining
# dimension is the input_shape[0] -i.e. batch size). This also squeezes
# the last dimension, since it's not used.
# [num_filters, batch, 1] => [num_units, rank, batch]
outputs = tf.reshape(outputs, [num_units, rank, -1])
# Sum the rank outputs per unit => [num_units, batch].
units_output = tf.reduce_sum(outputs, axis=1)
# Transpose to shape [batch, num_units]
units_output = tf.transpose(units_output)
# Appy bias.
bias = tf.Variable(tf.zeros([num_units]))
first_bias = tf.nn.bias_add(units_output, bias)
# Relu.
first_relu = tf.nn.relu(first_bias)
if is_training:
first_dropout = tf.nn.dropout(first_relu, dropout_prob)
else:
first_dropout = first_relu
first_fc_output_channels = 256
first_fc_weights = tf.Variable(
tf.truncated_normal([num_units, first_fc_output_channels], stddev=0.01))
first_fc_bias = tf.Variable(tf.zeros([first_fc_output_channels]))
first_fc = tf.matmul(first_dropout, first_fc_weights) + first_fc_bias
if is_training:
second_fc_input = tf.nn.dropout(first_fc, dropout_prob)
else:
second_fc_input = first_fc
second_fc_output_channels = 256
second_fc_weights = tf.Variable(
tf.truncated_normal(
[first_fc_output_channels, second_fc_output_channels], stddev=0.01))
second_fc_bias = tf.Variable(tf.zeros([second_fc_output_channels]))
second_fc = tf.matmul(second_fc_input, second_fc_weights) + second_fc_bias
if is_training:
final_fc_input = tf.nn.dropout(second_fc, dropout_prob)
else:
final_fc_input = second_fc
label_count = model_settings['label_count']
final_fc_weights = tf.Variable(
tf.truncated_normal(
[second_fc_output_channels, label_count], stddev=0.01))
final_fc_bias = tf.Variable(tf.zeros([label_count]))
final_fc = tf.matmul(final_fc_input, final_fc_weights) + final_fc_bias
if is_training:
return final_fc, dropout_prob
else:
return final_fc | [
"def",
"create_low_latency_svdf_model",
"(",
"fingerprint_input",
",",
"model_settings",
",",
"is_training",
",",
"runtime_settings",
")",
":",
"if",
"is_training",
":",
"dropout_prob",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"float32",
",",
"name",
"=",
... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/examples/speech_commands/models.py#L385-L566 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/coverage/coverage/control.py | python | Coverage.analysis | (self, morf) | return f, s, m, mf | Like `analysis2` but doesn't return excluded line numbers. | Like `analysis2` but doesn't return excluded line numbers. | [
"Like",
"analysis2",
"but",
"doesn",
"t",
"return",
"excluded",
"line",
"numbers",
"."
] | def analysis(self, morf):
"""Like `analysis2` but doesn't return excluded line numbers."""
f, s, _, m, mf = self.analysis2(morf)
return f, s, m, mf | [
"def",
"analysis",
"(",
"self",
",",
"morf",
")",
":",
"f",
",",
"s",
",",
"_",
",",
"m",
",",
"mf",
"=",
"self",
".",
"analysis2",
"(",
"morf",
")",
"return",
"f",
",",
"s",
",",
"m",
",",
"mf"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/coverage/coverage/control.py#L849-L852 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.