nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/Tkinter.py | python | Canvas.create_rectangle | (self, *args, **kw) | return self._create('rectangle', args, kw) | Create rectangle with coordinates x1,y1,x2,y2. | Create rectangle with coordinates x1,y1,x2,y2. | [
"Create",
"rectangle",
"with",
"coordinates",
"x1",
"y1",
"x2",
"y2",
"."
] | def create_rectangle(self, *args, **kw):
"""Create rectangle with coordinates x1,y1,x2,y2."""
return self._create('rectangle', args, kw) | [
"def",
"create_rectangle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"_create",
"(",
"'rectangle'",
",",
"args",
",",
"kw",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L2335-L2337 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | src/bindings/python/src/openvino/runtime/opset8/ops.py | python | gather | (
data: NodeInput,
indices: NodeInput,
axis: NodeInput,
batch_dims: Optional[int] = 0,
) | return _get_node_factory_opset8().create("Gather", inputs, attributes) | Return a node which performs Gather with support of negative indices.
@param data: N-D tensor with data for gathering
@param indices: N-D tensor with indices by which data is gathered. Negative indices
indicate reverse indexing from the end
@param axis: axis along which elements are gathered
@param batch_dims: number of batch dimensions
@return: The new node which performs Gather | Return a node which performs Gather with support of negative indices. | [
"Return",
"a",
"node",
"which",
"performs",
"Gather",
"with",
"support",
"of",
"negative",
"indices",
"."
] | def gather(
data: NodeInput,
indices: NodeInput,
axis: NodeInput,
batch_dims: Optional[int] = 0,
) -> Node:
"""Return a node which performs Gather with support of negative indices.
@param data: N-D tensor with data for gathering
@param indices: N-D tensor with indices by which data is gathered. Negative indices
indicate reverse indexing from the end
@param axis: axis along which elements are gathered
@param batch_dims: number of batch dimensions
@return: The new node which performs Gather
"""
inputs = as_nodes(data, indices, axis)
attributes = {
"batch_dims": batch_dims
}
return _get_node_factory_opset8().create("Gather", inputs, attributes) | [
"def",
"gather",
"(",
"data",
":",
"NodeInput",
",",
"indices",
":",
"NodeInput",
",",
"axis",
":",
"NodeInput",
",",
"batch_dims",
":",
"Optional",
"[",
"int",
"]",
"=",
"0",
",",
")",
"->",
"Node",
":",
"inputs",
"=",
"as_nodes",
"(",
"data",
",",
"indices",
",",
"axis",
")",
"attributes",
"=",
"{",
"\"batch_dims\"",
":",
"batch_dims",
"}",
"return",
"_get_node_factory_opset8",
"(",
")",
".",
"create",
"(",
"\"Gather\"",
",",
"inputs",
",",
"attributes",
")"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/openvino/runtime/opset8/ops.py#L243-L262 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | python/mozbuild/mozpack/mozjar.py | python | JarFileReader.seek | (self, pos, whence=os.SEEK_SET) | return self.uncompressed_data.seek(pos, whence) | Change the current position in the uncompressed data. Subsequent reads
will start from there. | Change the current position in the uncompressed data. Subsequent reads
will start from there. | [
"Change",
"the",
"current",
"position",
"in",
"the",
"uncompressed",
"data",
".",
"Subsequent",
"reads",
"will",
"start",
"from",
"there",
"."
] | def seek(self, pos, whence=os.SEEK_SET):
'''
Change the current position in the uncompressed data. Subsequent reads
will start from there.
'''
return self.uncompressed_data.seek(pos, whence) | [
"def",
"seek",
"(",
"self",
",",
"pos",
",",
"whence",
"=",
"os",
".",
"SEEK_SET",
")",
":",
"return",
"self",
".",
"uncompressed_data",
".",
"seek",
"(",
"pos",
",",
"whence",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/mozbuild/mozpack/mozjar.py#L290-L295 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/cmd.py | python | Command.ensure_string_list | (self, option) | r"""Ensure that 'option' is a list of strings. If 'option' is
currently a string, we split it either on /,\s*/ or /\s+/, so
"foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
["foo", "bar", "baz"]. | r"""Ensure that 'option' is a list of strings. If 'option' is
currently a string, we split it either on /,\s*/ or /\s+/, so
"foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
["foo", "bar", "baz"]. | [
"r",
"Ensure",
"that",
"option",
"is",
"a",
"list",
"of",
"strings",
".",
"If",
"option",
"is",
"currently",
"a",
"string",
"we",
"split",
"it",
"either",
"on",
"/",
"\\",
"s",
"*",
"/",
"or",
"/",
"\\",
"s",
"+",
"/",
"so",
"foo",
"bar",
"baz",
"foo",
"bar",
"baz",
"and",
"foo",
"bar",
"baz",
"all",
"become",
"[",
"foo",
"bar",
"baz",
"]",
"."
] | def ensure_string_list(self, option):
r"""Ensure that 'option' is a list of strings. If 'option' is
currently a string, we split it either on /,\s*/ or /\s+/, so
"foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
["foo", "bar", "baz"].
"""
val = getattr(self, option)
if val is None:
return
elif isinstance(val, str):
setattr(self, option, re.split(r',\s*|\s+', val))
else:
if isinstance(val, list):
ok = all(isinstance(v, str) for v in val)
else:
ok = False
if not ok:
raise DistutilsOptionError(
"'%s' must be a list of strings (got %r)"
% (option, val)) | [
"def",
"ensure_string_list",
"(",
"self",
",",
"option",
")",
":",
"val",
"=",
"getattr",
"(",
"self",
",",
"option",
")",
"if",
"val",
"is",
"None",
":",
"return",
"elif",
"isinstance",
"(",
"val",
",",
"str",
")",
":",
"setattr",
"(",
"self",
",",
"option",
",",
"re",
".",
"split",
"(",
"r',\\s*|\\s+'",
",",
"val",
")",
")",
"else",
":",
"if",
"isinstance",
"(",
"val",
",",
"list",
")",
":",
"ok",
"=",
"all",
"(",
"isinstance",
"(",
"v",
",",
"str",
")",
"for",
"v",
"in",
"val",
")",
"else",
":",
"ok",
"=",
"False",
"if",
"not",
"ok",
":",
"raise",
"DistutilsOptionError",
"(",
"\"'%s' must be a list of strings (got %r)\"",
"%",
"(",
"option",
",",
"val",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/cmd.py#L223-L242 | ||
tiny-dnn/tiny-dnn | c0f576f5cb7b35893f62127cb7aec18f77a3bcc5 | third_party/gemmlowp/meta/generators/zip_Nx8_neon.py | python | GenerateZipLanes | (emitter, registers, zip_lanes, input_address, stride) | return lanes | Prepares read lanes for the zip operation.
Args:
emitter: ARM/NEON emitter.
registers: ARM/NEON registers state.
zip_lanes: number of lanes to prepare.
input_address: register that contains the input address for the first lane.
stride: memory stride for lane inputs.
Returns:
Array of ZipLane objects. | Prepares read lanes for the zip operation. | [
"Prepares",
"read",
"lanes",
"for",
"the",
"zip",
"operation",
"."
] | def GenerateZipLanes(emitter, registers, zip_lanes, input_address, stride):
"""Prepares read lanes for the zip operation.
Args:
emitter: ARM/NEON emitter.
registers: ARM/NEON registers state.
zip_lanes: number of lanes to prepare.
input_address: register that contains the input address for the first lane.
stride: memory stride for lane inputs.
Returns:
Array of ZipLane objects.
"""
lanes = []
last_address_register = input_address
for i in range(zip_lanes):
if not i:
lanes.append(ZipLane(input_address, registers.DoubleRegister(),
registers.QuadRegister(4)))
else:
address_register = registers.GeneralRegister()
lanes.append(ZipLane(address_register, registers.DoubleRegister(),
registers.QuadRegister(4)))
emitter.EmitAdd(address_register, last_address_register, stride)
last_address_register = address_register
return lanes | [
"def",
"GenerateZipLanes",
"(",
"emitter",
",",
"registers",
",",
"zip_lanes",
",",
"input_address",
",",
"stride",
")",
":",
"lanes",
"=",
"[",
"]",
"last_address_register",
"=",
"input_address",
"for",
"i",
"in",
"range",
"(",
"zip_lanes",
")",
":",
"if",
"not",
"i",
":",
"lanes",
".",
"append",
"(",
"ZipLane",
"(",
"input_address",
",",
"registers",
".",
"DoubleRegister",
"(",
")",
",",
"registers",
".",
"QuadRegister",
"(",
"4",
")",
")",
")",
"else",
":",
"address_register",
"=",
"registers",
".",
"GeneralRegister",
"(",
")",
"lanes",
".",
"append",
"(",
"ZipLane",
"(",
"address_register",
",",
"registers",
".",
"DoubleRegister",
"(",
")",
",",
"registers",
".",
"QuadRegister",
"(",
"4",
")",
")",
")",
"emitter",
".",
"EmitAdd",
"(",
"address_register",
",",
"last_address_register",
",",
"stride",
")",
"last_address_register",
"=",
"address_register",
"return",
"lanes"
] | https://github.com/tiny-dnn/tiny-dnn/blob/c0f576f5cb7b35893f62127cb7aec18f77a3bcc5/third_party/gemmlowp/meta/generators/zip_Nx8_neon.py#L25-L50 | |
choasup/caffe-yolo9000 | e8a476c4c23d756632f7a26c681a96e3ab672544 | scripts/cpp_lint.py | python | _SetFilters | (filters) | Sets the module's error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "whitespace/indent").
Each filter should start with + or -; else we die. | Sets the module's error-message filters. | [
"Sets",
"the",
"module",
"s",
"error",
"-",
"message",
"filters",
"."
] | def _SetFilters(filters):
"""Sets the module's error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "whitespace/indent").
Each filter should start with + or -; else we die.
"""
_cpplint_state.SetFilters(filters) | [
"def",
"_SetFilters",
"(",
"filters",
")",
":",
"_cpplint_state",
".",
"SetFilters",
"(",
"filters",
")"
] | https://github.com/choasup/caffe-yolo9000/blob/e8a476c4c23d756632f7a26c681a96e3ab672544/scripts/cpp_lint.py#L797-L807 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/cognito/sync/layer1.py | python | CognitoSyncConnection.register_device | (self, identity_pool_id, identity_id, platform, token) | return self.make_request('POST', uri, expected_status=200,
data=json.dumps(params), headers=headers,
params=query_params) | Registers a device to receive push sync notifications.
:type identity_pool_id: string
:param identity_pool_id: A name-spaced GUID (for example, us-
east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon
Cognito. Here, the ID of the pool that the identity belongs to.
:type identity_id: string
:param identity_id: The unique ID for this identity.
:type platform: string
:param platform: The SNS platform type (e.g. GCM, SDM, APNS,
APNS_SANDBOX).
:type token: string
:param token: The push token. | Registers a device to receive push sync notifications. | [
"Registers",
"a",
"device",
"to",
"receive",
"push",
"sync",
"notifications",
"."
] | def register_device(self, identity_pool_id, identity_id, platform, token):
"""
Registers a device to receive push sync notifications.
:type identity_pool_id: string
:param identity_pool_id: A name-spaced GUID (for example, us-
east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon
Cognito. Here, the ID of the pool that the identity belongs to.
:type identity_id: string
:param identity_id: The unique ID for this identity.
:type platform: string
:param platform: The SNS platform type (e.g. GCM, SDM, APNS,
APNS_SANDBOX).
:type token: string
:param token: The push token.
"""
uri = '/identitypools/{0}/identity/{1}/device'.format(
identity_pool_id, identity_id)
params = {'Platform': platform, 'Token': token, }
headers = {}
query_params = {}
return self.make_request('POST', uri, expected_status=200,
data=json.dumps(params), headers=headers,
params=query_params) | [
"def",
"register_device",
"(",
"self",
",",
"identity_pool_id",
",",
"identity_id",
",",
"platform",
",",
"token",
")",
":",
"uri",
"=",
"'/identitypools/{0}/identity/{1}/device'",
".",
"format",
"(",
"identity_pool_id",
",",
"identity_id",
")",
"params",
"=",
"{",
"'Platform'",
":",
"platform",
",",
"'Token'",
":",
"token",
",",
"}",
"headers",
"=",
"{",
"}",
"query_params",
"=",
"{",
"}",
"return",
"self",
".",
"make_request",
"(",
"'POST'",
",",
"uri",
",",
"expected_status",
"=",
"200",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"params",
")",
",",
"headers",
"=",
"headers",
",",
"params",
"=",
"query_params",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/cognito/sync/layer1.py#L314-L342 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/linalg_ops.py | python | _SelfAdjointEigV2ShapeHelper | (op, input_shape) | Shape inference helper for {Batch}SelfAdjointEigV2. | Shape inference helper for {Batch}SelfAdjointEigV2. | [
"Shape",
"inference",
"helper",
"for",
"{",
"Batch",
"}",
"SelfAdjointEigV2",
"."
] | def _SelfAdjointEigV2ShapeHelper(op, input_shape):
"""Shape inference helper for {Batch}SelfAdjointEigV2."""
batch_shape = input_shape[:-2]
n = input_shape[-1].merge_with(input_shape[-2])
compute_v = op.get_attr("compute_v")
if compute_v:
return [batch_shape.concatenate([n]), batch_shape.concatenate([n, n])]
else:
return [batch_shape.concatenate([n]), [0]] | [
"def",
"_SelfAdjointEigV2ShapeHelper",
"(",
"op",
",",
"input_shape",
")",
":",
"batch_shape",
"=",
"input_shape",
"[",
":",
"-",
"2",
"]",
"n",
"=",
"input_shape",
"[",
"-",
"1",
"]",
".",
"merge_with",
"(",
"input_shape",
"[",
"-",
"2",
"]",
")",
"compute_v",
"=",
"op",
".",
"get_attr",
"(",
"\"compute_v\"",
")",
"if",
"compute_v",
":",
"return",
"[",
"batch_shape",
".",
"concatenate",
"(",
"[",
"n",
"]",
")",
",",
"batch_shape",
".",
"concatenate",
"(",
"[",
"n",
",",
"n",
"]",
")",
"]",
"else",
":",
"return",
"[",
"batch_shape",
".",
"concatenate",
"(",
"[",
"n",
"]",
")",
",",
"[",
"0",
"]",
"]"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/linalg_ops.py#L100-L108 | ||
ApolloAuto/apollo | 463fb82f9e979d02dcb25044e60931293ab2dba0 | scripts/record_message.py | python | ArgManager.__init__ | (self) | Init. | Init. | [
"Init",
"."
] | def __init__(self):
"""Init."""
self.parser = argparse.ArgumentParser(
description="Manage apollo data recording.")
self.parser.add_argument('--start', default=False, action="store_true",
help='Start recorder. It is the default '
'action if no other actions are triggered. In '
'that case, the False value is ignored.')
self.parser.add_argument('--stop', default=False, action="store_true",
help='Stop recorder.')
self._args = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Manage apollo data recording.\"",
")",
"self",
".",
"parser",
".",
"add_argument",
"(",
"'--start'",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"'Start recorder. It is the default '",
"'action if no other actions are triggered. In '",
"'that case, the False value is ignored.'",
")",
"self",
".",
"parser",
".",
"add_argument",
"(",
"'--stop'",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"'Stop recorder.'",
")",
"self",
".",
"_args",
"=",
"None"
] | https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/scripts/record_message.py#L57-L67 | ||
yrnkrn/zapcc | c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50 | tools/clang/bindings/python/clang/cindex.py | python | Cursor.raw_comment | (self) | return conf.lib.clang_Cursor_getRawCommentText(self) | Returns the raw comment text associated with that Cursor | Returns the raw comment text associated with that Cursor | [
"Returns",
"the",
"raw",
"comment",
"text",
"associated",
"with",
"that",
"Cursor"
] | def raw_comment(self):
"""Returns the raw comment text associated with that Cursor"""
return conf.lib.clang_Cursor_getRawCommentText(self) | [
"def",
"raw_comment",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_Cursor_getRawCommentText",
"(",
"self",
")"
] | https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/tools/clang/bindings/python/clang/cindex.py#L1772-L1774 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/glcanvas.py | python | GLContext.SetCurrent | (*args, **kwargs) | return _glcanvas.GLContext_SetCurrent(*args, **kwargs) | SetCurrent(self, GLCanvas win) -> bool | SetCurrent(self, GLCanvas win) -> bool | [
"SetCurrent",
"(",
"self",
"GLCanvas",
"win",
")",
"-",
">",
"bool"
] | def SetCurrent(*args, **kwargs):
"""SetCurrent(self, GLCanvas win) -> bool"""
return _glcanvas.GLContext_SetCurrent(*args, **kwargs) | [
"def",
"SetCurrent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_glcanvas",
".",
"GLContext_SetCurrent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/glcanvas.py#L70-L72 | |
zerollzeng/tiny-tensorrt | e7bdb8f82934342a0f22ce68dfefdb8e15eb72b2 | third_party/pybind11/tools/clang/cindex.py | python | CompilationDatabase.fromDirectory | (buildDir) | return cdb | Builds a CompilationDatabase from the database found in buildDir | Builds a CompilationDatabase from the database found in buildDir | [
"Builds",
"a",
"CompilationDatabase",
"from",
"the",
"database",
"found",
"in",
"buildDir"
] | def fromDirectory(buildDir):
"""Builds a CompilationDatabase from the database found in buildDir"""
errorCode = c_uint()
try:
cdb = conf.lib.clang_CompilationDatabase_fromDirectory(buildDir,
byref(errorCode))
except CompilationDatabaseError as e:
raise CompilationDatabaseError(int(errorCode.value),
"CompilationDatabase loading failed")
return cdb | [
"def",
"fromDirectory",
"(",
"buildDir",
")",
":",
"errorCode",
"=",
"c_uint",
"(",
")",
"try",
":",
"cdb",
"=",
"conf",
".",
"lib",
".",
"clang_CompilationDatabase_fromDirectory",
"(",
"buildDir",
",",
"byref",
"(",
"errorCode",
")",
")",
"except",
"CompilationDatabaseError",
"as",
"e",
":",
"raise",
"CompilationDatabaseError",
"(",
"int",
"(",
"errorCode",
".",
"value",
")",
",",
"\"CompilationDatabase loading failed\"",
")",
"return",
"cdb"
] | https://github.com/zerollzeng/tiny-tensorrt/blob/e7bdb8f82934342a0f22ce68dfefdb8e15eb72b2/third_party/pybind11/tools/clang/cindex.py#L2950-L2959 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/model/calibrate.py | python | RobotExtrinsicCalibration.updateRobotSensors | (self) | Uses the current camera transforms to update the robot model's
sensors. | Uses the current camera transforms to update the robot model's
sensors. | [
"Uses",
"the",
"current",
"camera",
"transforms",
"to",
"update",
"the",
"robot",
"model",
"s",
"sensors",
"."
] | def updateRobotSensors(self) -> None:
"""Uses the current camera transforms to update the robot model's
sensors.
"""
for i,c in self.cameras.items():
try:
s = self.robot.sensor(i)
if s.name()=='':
raise ValueError()
except Exception:
#create a new camera on the robot
s = self.robot.addSensor(str(i),'CameraSensor')
sensing.intrinsics_to_camera(c.intrinsics,s,'json')
s.setSetting('zmin','0.1')
s.setSetting('zmax','10')
s.setSetting('link',str(_linkIndex(c.link,self.robot)))
sensing.set_sensor_xform(s,c.local_coordinates) | [
"def",
"updateRobotSensors",
"(",
"self",
")",
"->",
"None",
":",
"for",
"i",
",",
"c",
"in",
"self",
".",
"cameras",
".",
"items",
"(",
")",
":",
"try",
":",
"s",
"=",
"self",
".",
"robot",
".",
"sensor",
"(",
"i",
")",
"if",
"s",
".",
"name",
"(",
")",
"==",
"''",
":",
"raise",
"ValueError",
"(",
")",
"except",
"Exception",
":",
"#create a new camera on the robot",
"s",
"=",
"self",
".",
"robot",
".",
"addSensor",
"(",
"str",
"(",
"i",
")",
",",
"'CameraSensor'",
")",
"sensing",
".",
"intrinsics_to_camera",
"(",
"c",
".",
"intrinsics",
",",
"s",
",",
"'json'",
")",
"s",
".",
"setSetting",
"(",
"'zmin'",
",",
"'0.1'",
")",
"s",
".",
"setSetting",
"(",
"'zmax'",
",",
"'10'",
")",
"s",
".",
"setSetting",
"(",
"'link'",
",",
"str",
"(",
"_linkIndex",
"(",
"c",
".",
"link",
",",
"self",
".",
"robot",
")",
")",
")",
"sensing",
".",
"set_sensor_xform",
"(",
"s",
",",
"c",
".",
"local_coordinates",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/model/calibrate.py#L916-L932 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/writers/s5_html/__init__.py | python | S5HTMLTranslator.copy_file | (self, name, source_dir, dest_dir) | Copy file `name` from `source_dir` to `dest_dir`.
Return 1 if the file exists in either `source_dir` or `dest_dir`. | Copy file `name` from `source_dir` to `dest_dir`.
Return 1 if the file exists in either `source_dir` or `dest_dir`. | [
"Copy",
"file",
"name",
"from",
"source_dir",
"to",
"dest_dir",
".",
"Return",
"1",
"if",
"the",
"file",
"exists",
"in",
"either",
"source_dir",
"or",
"dest_dir",
"."
] | def copy_file(self, name, source_dir, dest_dir):
"""
Copy file `name` from `source_dir` to `dest_dir`.
Return 1 if the file exists in either `source_dir` or `dest_dir`.
"""
source = os.path.join(source_dir, name)
dest = os.path.join(dest_dir, name)
if dest in self.theme_files_copied:
return 1
else:
self.theme_files_copied[dest] = 1
if os.path.isfile(source):
if self.files_to_skip_pattern.search(source):
return None
settings = self.document.settings
if os.path.exists(dest) and not settings.overwrite_theme_files:
settings.record_dependencies.add(dest)
else:
src_file = open(source, 'rb')
src_data = src_file.read()
src_file.close()
dest_file = open(dest, 'wb')
dest_dir = dest_dir.replace(os.sep, '/')
dest_file.write(src_data.replace(
b('ui/default'),
dest_dir[dest_dir.rfind('ui/'):].encode(
sys.getfilesystemencoding())))
dest_file.close()
settings.record_dependencies.add(source)
return 1
if os.path.isfile(dest):
return 1 | [
"def",
"copy_file",
"(",
"self",
",",
"name",
",",
"source_dir",
",",
"dest_dir",
")",
":",
"source",
"=",
"os",
".",
"path",
".",
"join",
"(",
"source_dir",
",",
"name",
")",
"dest",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dest_dir",
",",
"name",
")",
"if",
"dest",
"in",
"self",
".",
"theme_files_copied",
":",
"return",
"1",
"else",
":",
"self",
".",
"theme_files_copied",
"[",
"dest",
"]",
"=",
"1",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"source",
")",
":",
"if",
"self",
".",
"files_to_skip_pattern",
".",
"search",
"(",
"source",
")",
":",
"return",
"None",
"settings",
"=",
"self",
".",
"document",
".",
"settings",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dest",
")",
"and",
"not",
"settings",
".",
"overwrite_theme_files",
":",
"settings",
".",
"record_dependencies",
".",
"add",
"(",
"dest",
")",
"else",
":",
"src_file",
"=",
"open",
"(",
"source",
",",
"'rb'",
")",
"src_data",
"=",
"src_file",
".",
"read",
"(",
")",
"src_file",
".",
"close",
"(",
")",
"dest_file",
"=",
"open",
"(",
"dest",
",",
"'wb'",
")",
"dest_dir",
"=",
"dest_dir",
".",
"replace",
"(",
"os",
".",
"sep",
",",
"'/'",
")",
"dest_file",
".",
"write",
"(",
"src_data",
".",
"replace",
"(",
"b",
"(",
"'ui/default'",
")",
",",
"dest_dir",
"[",
"dest_dir",
".",
"rfind",
"(",
"'ui/'",
")",
":",
"]",
".",
"encode",
"(",
"sys",
".",
"getfilesystemencoding",
"(",
")",
")",
")",
")",
"dest_file",
".",
"close",
"(",
")",
"settings",
".",
"record_dependencies",
".",
"add",
"(",
"source",
")",
"return",
"1",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"dest",
")",
":",
"return",
"1"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/writers/s5_html/__init__.py#L248-L279 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | third_party/Python/module/pexpect-4.6/pexpect/popen_spawn.py | python | PopenSpawn._read_incoming | (self) | Run in a thread to move output from a pipe to a queue. | Run in a thread to move output from a pipe to a queue. | [
"Run",
"in",
"a",
"thread",
"to",
"move",
"output",
"from",
"a",
"pipe",
"to",
"a",
"queue",
"."
] | def _read_incoming(self):
"""Run in a thread to move output from a pipe to a queue."""
fileno = self.proc.stdout.fileno()
while 1:
buf = b''
try:
buf = os.read(fileno, 1024)
except OSError as e:
self._log(e, 'read')
if not buf:
# This indicates we have reached EOF
self._read_queue.put(None)
return
self._read_queue.put(buf) | [
"def",
"_read_incoming",
"(",
"self",
")",
":",
"fileno",
"=",
"self",
".",
"proc",
".",
"stdout",
".",
"fileno",
"(",
")",
"while",
"1",
":",
"buf",
"=",
"b''",
"try",
":",
"buf",
"=",
"os",
".",
"read",
"(",
"fileno",
",",
"1024",
")",
"except",
"OSError",
"as",
"e",
":",
"self",
".",
"_log",
"(",
"e",
",",
"'read'",
")",
"if",
"not",
"buf",
":",
"# This indicates we have reached EOF",
"self",
".",
"_read_queue",
".",
"put",
"(",
"None",
")",
"return",
"self",
".",
"_read_queue",
".",
"put",
"(",
"buf",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/third_party/Python/module/pexpect-4.6/pexpect/popen_spawn.py#L100-L115 | ||
papyrussolution/OpenPapyrus | bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91 | Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/well_known_types.py | python | Timestamp.FromJsonString | (self, value) | Parse a RFC 3339 date string format to Timestamp.
Args:
value: A date string. Any fractional digits (or none) and any offset are
accepted as long as they fit into nano-seconds precision.
Example of accepted format: '1972-01-01T10:00:20.021-05:00'
Raises:
ValueError: On parsing problems. | Parse a RFC 3339 date string format to Timestamp. | [
"Parse",
"a",
"RFC",
"3339",
"date",
"string",
"format",
"to",
"Timestamp",
"."
] | def FromJsonString(self, value):
"""Parse a RFC 3339 date string format to Timestamp.
Args:
value: A date string. Any fractional digits (or none) and any offset are
accepted as long as they fit into nano-seconds precision.
Example of accepted format: '1972-01-01T10:00:20.021-05:00'
Raises:
ValueError: On parsing problems.
"""
if not isinstance(value, str):
raise ValueError('Timestamp JSON value not a string: {!r}'.format(value))
timezone_offset = value.find('Z')
if timezone_offset == -1:
timezone_offset = value.find('+')
if timezone_offset == -1:
timezone_offset = value.rfind('-')
if timezone_offset == -1:
raise ValueError(
'Failed to parse timestamp: missing valid timezone offset.')
time_value = value[0:timezone_offset]
# Parse datetime and nanos.
point_position = time_value.find('.')
if point_position == -1:
second_value = time_value
nano_value = ''
else:
second_value = time_value[:point_position]
nano_value = time_value[point_position + 1:]
if 't' in second_value:
raise ValueError(
'time data \'{0}\' does not match format \'%Y-%m-%dT%H:%M:%S\', '
'lowercase \'t\' is not accepted'.format(second_value))
date_object = datetime.strptime(second_value, _TIMESTAMPFOMAT)
td = date_object - datetime(1970, 1, 1)
seconds = td.seconds + td.days * _SECONDS_PER_DAY
if len(nano_value) > 9:
raise ValueError(
'Failed to parse Timestamp: nanos {0} more than '
'9 fractional digits.'.format(nano_value))
if nano_value:
nanos = round(float('0.' + nano_value) * 1e9)
else:
nanos = 0
# Parse timezone offsets.
if value[timezone_offset] == 'Z':
if len(value) != timezone_offset + 1:
raise ValueError('Failed to parse timestamp: invalid trailing'
' data {0}.'.format(value))
else:
timezone = value[timezone_offset:]
pos = timezone.find(':')
if pos == -1:
raise ValueError(
'Invalid timezone offset value: {0}.'.format(timezone))
if timezone[0] == '+':
seconds -= (int(timezone[1:pos])*60+int(timezone[pos+1:]))*60
else:
seconds += (int(timezone[1:pos])*60+int(timezone[pos+1:]))*60
# Set seconds and nanos
self.seconds = int(seconds)
self.nanos = int(nanos) | [
"def",
"FromJsonString",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"raise",
"ValueError",
"(",
"'Timestamp JSON value not a string: {!r}'",
".",
"format",
"(",
"value",
")",
")",
"timezone_offset",
"=",
"value",
".",
"find",
"(",
"'Z'",
")",
"if",
"timezone_offset",
"==",
"-",
"1",
":",
"timezone_offset",
"=",
"value",
".",
"find",
"(",
"'+'",
")",
"if",
"timezone_offset",
"==",
"-",
"1",
":",
"timezone_offset",
"=",
"value",
".",
"rfind",
"(",
"'-'",
")",
"if",
"timezone_offset",
"==",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"'Failed to parse timestamp: missing valid timezone offset.'",
")",
"time_value",
"=",
"value",
"[",
"0",
":",
"timezone_offset",
"]",
"# Parse datetime and nanos.",
"point_position",
"=",
"time_value",
".",
"find",
"(",
"'.'",
")",
"if",
"point_position",
"==",
"-",
"1",
":",
"second_value",
"=",
"time_value",
"nano_value",
"=",
"''",
"else",
":",
"second_value",
"=",
"time_value",
"[",
":",
"point_position",
"]",
"nano_value",
"=",
"time_value",
"[",
"point_position",
"+",
"1",
":",
"]",
"if",
"'t'",
"in",
"second_value",
":",
"raise",
"ValueError",
"(",
"'time data \\'{0}\\' does not match format \\'%Y-%m-%dT%H:%M:%S\\', '",
"'lowercase \\'t\\' is not accepted'",
".",
"format",
"(",
"second_value",
")",
")",
"date_object",
"=",
"datetime",
".",
"strptime",
"(",
"second_value",
",",
"_TIMESTAMPFOMAT",
")",
"td",
"=",
"date_object",
"-",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
")",
"seconds",
"=",
"td",
".",
"seconds",
"+",
"td",
".",
"days",
"*",
"_SECONDS_PER_DAY",
"if",
"len",
"(",
"nano_value",
")",
">",
"9",
":",
"raise",
"ValueError",
"(",
"'Failed to parse Timestamp: nanos {0} more than '",
"'9 fractional digits.'",
".",
"format",
"(",
"nano_value",
")",
")",
"if",
"nano_value",
":",
"nanos",
"=",
"round",
"(",
"float",
"(",
"'0.'",
"+",
"nano_value",
")",
"*",
"1e9",
")",
"else",
":",
"nanos",
"=",
"0",
"# Parse timezone offsets.",
"if",
"value",
"[",
"timezone_offset",
"]",
"==",
"'Z'",
":",
"if",
"len",
"(",
"value",
")",
"!=",
"timezone_offset",
"+",
"1",
":",
"raise",
"ValueError",
"(",
"'Failed to parse timestamp: invalid trailing'",
"' data {0}.'",
".",
"format",
"(",
"value",
")",
")",
"else",
":",
"timezone",
"=",
"value",
"[",
"timezone_offset",
":",
"]",
"pos",
"=",
"timezone",
".",
"find",
"(",
"':'",
")",
"if",
"pos",
"==",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"'Invalid timezone offset value: {0}.'",
".",
"format",
"(",
"timezone",
")",
")",
"if",
"timezone",
"[",
"0",
"]",
"==",
"'+'",
":",
"seconds",
"-=",
"(",
"int",
"(",
"timezone",
"[",
"1",
":",
"pos",
"]",
")",
"*",
"60",
"+",
"int",
"(",
"timezone",
"[",
"pos",
"+",
"1",
":",
"]",
")",
")",
"*",
"60",
"else",
":",
"seconds",
"+=",
"(",
"int",
"(",
"timezone",
"[",
"1",
":",
"pos",
"]",
")",
"*",
"60",
"+",
"int",
"(",
"timezone",
"[",
"pos",
"+",
"1",
":",
"]",
")",
")",
"*",
"60",
"# Set seconds and nanos",
"self",
".",
"seconds",
"=",
"int",
"(",
"seconds",
")",
"self",
".",
"nanos",
"=",
"int",
"(",
"nanos",
")"
] | https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/well_known_types.py#L128-L190 | ||
Slicer/SlicerGitSVNArchive | 65e92bb16c2b32ea47a1a66bee71f238891ee1ca | Modules/Scripted/EditorLib/EditUtil.py | python | EditUtil.getSliceWidget | (layoutName='Red') | return sliceWidget | use the Red slice widget as the default | use the Red slice widget as the default | [
"use",
"the",
"Red",
"slice",
"widget",
"as",
"the",
"default"
] | def getSliceWidget(layoutName='Red'):
""" use the Red slice widget as the default"""
layoutManager = slicer.app.layoutManager()
sliceWidget = layoutManager.sliceWidget(layoutName)
return sliceWidget | [
"def",
"getSliceWidget",
"(",
"layoutName",
"=",
"'Red'",
")",
":",
"layoutManager",
"=",
"slicer",
".",
"app",
".",
"layoutManager",
"(",
")",
"sliceWidget",
"=",
"layoutManager",
".",
"sliceWidget",
"(",
"layoutName",
")",
"return",
"sliceWidget"
] | https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Modules/Scripted/EditorLib/EditUtil.py#L87-L91 | |
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythplugins/mythgame/mythgame/scripts/giantbomb/giantbomb_api.py | python | gamedbQueries.htmlToString | (self, context, html) | return self.massageText(html).strip().replace(u'\n', u' ').replace(u'', u"'").replace(u'', u"'") | Remove HTML tags and LFs from a string
return the string without HTML tags or LFs | Remove HTML tags and LFs from a string
return the string without HTML tags or LFs | [
"Remove",
"HTML",
"tags",
"and",
"LFs",
"from",
"a",
"string",
"return",
"the",
"string",
"without",
"HTML",
"tags",
"or",
"LFs"
] | def htmlToString(self, context, html):
''' Remove HTML tags and LFs from a string
return the string without HTML tags or LFs
'''
if not len(html):
return u""
return self.massageText(html).strip().replace(u'\n', u' ').replace(u'', u"'").replace(u'', u"'") | [
"def",
"htmlToString",
"(",
"self",
",",
"context",
",",
"html",
")",
":",
"if",
"not",
"len",
"(",
"html",
")",
":",
"return",
"u\"\"",
"return",
"self",
".",
"massageText",
"(",
"html",
")",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"u'\\n'",
",",
"u' '",
")",
".",
"replace",
"(",
"u'',",
" ",
"\"'\")",
".",
"r",
"eplace(",
"u",
"'', ",
"u",
"'\")",
""
] | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythplugins/mythgame/mythgame/scripts/giantbomb/giantbomb_api.py#L202-L208 | |
google/tink | 59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14 | python/tink/core/_tink_error.py | python | use_tink_errors | (func) | return wrapper | Transforms StatusNotOk errors into TinkErrors. | Transforms StatusNotOk errors into TinkErrors. | [
"Transforms",
"StatusNotOk",
"errors",
"into",
"TinkErrors",
"."
] | def use_tink_errors(func):
"""Transforms StatusNotOk errors into TinkErrors."""
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except KNOWN_STATUS_NOT_OK_TYPES as e:
raise TinkError(e)
return wrapper | [
"def",
"use_tink_errors",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"KNOWN_STATUS_NOT_OK_TYPES",
"as",
"e",
":",
"raise",
"TinkError",
"(",
"e",
")",
"return",
"wrapper"
] | https://github.com/google/tink/blob/59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14/python/tink/core/_tink_error.py#L29-L37 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Fem/feminout/importFenicsMesh.py | python | export | (objectslist, fileString, group_values_dict_nogui=None) | Called when freecad exports a file.
group_dict_no_gui: dictionary with group_numbers as keys and tuples
of (marked_value (default=1), default_value (default=0)) | Called when freecad exports a file.
group_dict_no_gui: dictionary with group_numbers as keys and tuples
of (marked_value (default=1), default_value (default=0)) | [
"Called",
"when",
"freecad",
"exports",
"a",
"file",
".",
"group_dict_no_gui",
":",
"dictionary",
"with",
"group_numbers",
"as",
"keys",
"and",
"tuples",
"of",
"(",
"marked_value",
"(",
"default",
"=",
"1",
")",
"default_value",
"(",
"default",
"=",
"0",
"))"
] | def export(objectslist, fileString, group_values_dict_nogui=None):
"""
Called when freecad exports a file.
group_dict_no_gui: dictionary with group_numbers as keys and tuples
of (marked_value (default=1), default_value (default=0))
"""
if len(objectslist) != 1:
Console.PrintError(
"This exporter can only export one object.\n")
return
obj = objectslist[0]
if not obj.isDerivedFrom("Fem::FemMeshObject"):
Console.PrintError("No FEM mesh object selected.\n")
return
if fileString != "":
fileName, fileExtension = os.path.splitext(fileString)
if fileExtension.lower() == ".xml":
Console.PrintWarning(
"XML is not designed to save higher order elements.\n")
Console.PrintWarning(
"Reducing order for second order mesh.\n")
Console.PrintWarning("Tri6 -> Tri3, Tet10 -> Tet4, etc.\n")
writeFenicsXML.write_fenics_mesh_xml(obj, fileString)
elif fileExtension.lower() == ".xdmf":
mesh_groups = importToolsFem.get_FemMeshObjectMeshGroups(obj)
if mesh_groups != ():
# if there are groups found, make task panel available if GuiUp
if FreeCAD.GuiUp == 1:
panel = WriteXDMFTaskPanel(obj, fileString)
FreeCADGui.Control.showDialog(panel)
else:
# create default dict if groupdict_nogui is not None
if group_values_dict_nogui is None:
group_values_dict_nogui = dict([(g, (1, 0))
for g in mesh_groups])
writeFenicsXDMF.write_fenics_mesh_xdmf(
obj, fileString,
group_values_dict=group_values_dict_nogui)
else:
writeFenicsXDMF.write_fenics_mesh_xdmf(obj, fileString) | [
"def",
"export",
"(",
"objectslist",
",",
"fileString",
",",
"group_values_dict_nogui",
"=",
"None",
")",
":",
"if",
"len",
"(",
"objectslist",
")",
"!=",
"1",
":",
"Console",
".",
"PrintError",
"(",
"\"This exporter can only export one object.\\n\"",
")",
"return",
"obj",
"=",
"objectslist",
"[",
"0",
"]",
"if",
"not",
"obj",
".",
"isDerivedFrom",
"(",
"\"Fem::FemMeshObject\"",
")",
":",
"Console",
".",
"PrintError",
"(",
"\"No FEM mesh object selected.\\n\"",
")",
"return",
"if",
"fileString",
"!=",
"\"\"",
":",
"fileName",
",",
"fileExtension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"fileString",
")",
"if",
"fileExtension",
".",
"lower",
"(",
")",
"==",
"\".xml\"",
":",
"Console",
".",
"PrintWarning",
"(",
"\"XML is not designed to save higher order elements.\\n\"",
")",
"Console",
".",
"PrintWarning",
"(",
"\"Reducing order for second order mesh.\\n\"",
")",
"Console",
".",
"PrintWarning",
"(",
"\"Tri6 -> Tri3, Tet10 -> Tet4, etc.\\n\"",
")",
"writeFenicsXML",
".",
"write_fenics_mesh_xml",
"(",
"obj",
",",
"fileString",
")",
"elif",
"fileExtension",
".",
"lower",
"(",
")",
"==",
"\".xdmf\"",
":",
"mesh_groups",
"=",
"importToolsFem",
".",
"get_FemMeshObjectMeshGroups",
"(",
"obj",
")",
"if",
"mesh_groups",
"!=",
"(",
")",
":",
"# if there are groups found, make task panel available if GuiUp",
"if",
"FreeCAD",
".",
"GuiUp",
"==",
"1",
":",
"panel",
"=",
"WriteXDMFTaskPanel",
"(",
"obj",
",",
"fileString",
")",
"FreeCADGui",
".",
"Control",
".",
"showDialog",
"(",
"panel",
")",
"else",
":",
"# create default dict if groupdict_nogui is not None",
"if",
"group_values_dict_nogui",
"is",
"None",
":",
"group_values_dict_nogui",
"=",
"dict",
"(",
"[",
"(",
"g",
",",
"(",
"1",
",",
"0",
")",
")",
"for",
"g",
"in",
"mesh_groups",
"]",
")",
"writeFenicsXDMF",
".",
"write_fenics_mesh_xdmf",
"(",
"obj",
",",
"fileString",
",",
"group_values_dict",
"=",
"group_values_dict_nogui",
")",
"else",
":",
"writeFenicsXDMF",
".",
"write_fenics_mesh_xdmf",
"(",
"obj",
",",
"fileString",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Fem/feminout/importFenicsMesh.py#L164-L204 | ||
intel/llvm | e6d0547e9d99b5a56430c4749f6c7e328bf221ab | mlir/python/mlir/dialects/_std_ops_ext.py | python | CallOp.__init__ | (self,
calleeOrResults: Union[FuncOp, List[Type]],
argumentsOrCallee: Union[List, FlatSymbolRefAttr, str],
arguments: Optional[List] = None,
*,
loc=None,
ip=None) | Creates an call operation.
The constructor accepts three different forms:
1. A function op to be called followed by a list of arguments.
2. A list of result types, followed by the name of the function to be
called as string, following by a list of arguments.
3. A list of result types, followed by the name of the function to be
called as symbol reference attribute, followed by a list of arguments.
For example
f = builtin.FuncOp("foo", ...)
std.CallOp(f, [args])
std.CallOp([result_types], "foo", [args])
In all cases, the location and insertion point may be specified as keyword
arguments if not provided by the surrounding context managers. | Creates an call operation. | [
"Creates",
"an",
"call",
"operation",
"."
] | def __init__(self,
calleeOrResults: Union[FuncOp, List[Type]],
argumentsOrCallee: Union[List, FlatSymbolRefAttr, str],
arguments: Optional[List] = None,
*,
loc=None,
ip=None):
"""Creates an call operation.
The constructor accepts three different forms:
1. A function op to be called followed by a list of arguments.
2. A list of result types, followed by the name of the function to be
called as string, following by a list of arguments.
3. A list of result types, followed by the name of the function to be
called as symbol reference attribute, followed by a list of arguments.
For example
f = builtin.FuncOp("foo", ...)
std.CallOp(f, [args])
std.CallOp([result_types], "foo", [args])
In all cases, the location and insertion point may be specified as keyword
arguments if not provided by the surrounding context managers.
"""
# TODO: consider supporting constructor "overloads", e.g., through a custom
# or pybind-provided metaclass.
if isinstance(calleeOrResults, FuncOp):
if not isinstance(argumentsOrCallee, list):
raise ValueError(
"when constructing a call to a function, expected " +
"the second argument to be a list of call arguments, " +
f"got {type(argumentsOrCallee)}")
if arguments is not None:
raise ValueError("unexpected third argument when constructing a call" +
"to a function")
super().__init__(
calleeOrResults.type.results,
FlatSymbolRefAttr.get(
calleeOrResults.name.value,
context=_get_default_loc_context(loc)),
argumentsOrCallee,
loc=loc,
ip=ip)
return
if isinstance(argumentsOrCallee, list):
raise ValueError("when constructing a call to a function by name, " +
"expected the second argument to be a string or a " +
f"FlatSymbolRefAttr, got {type(argumentsOrCallee)}")
if isinstance(argumentsOrCallee, FlatSymbolRefAttr):
super().__init__(
calleeOrResults, argumentsOrCallee, arguments, loc=loc, ip=ip)
elif isinstance(argumentsOrCallee, str):
super().__init__(
calleeOrResults,
FlatSymbolRefAttr.get(
argumentsOrCallee, context=_get_default_loc_context(loc)),
arguments,
loc=loc,
ip=ip) | [
"def",
"__init__",
"(",
"self",
",",
"calleeOrResults",
":",
"Union",
"[",
"FuncOp",
",",
"List",
"[",
"Type",
"]",
"]",
",",
"argumentsOrCallee",
":",
"Union",
"[",
"List",
",",
"FlatSymbolRefAttr",
",",
"str",
"]",
",",
"arguments",
":",
"Optional",
"[",
"List",
"]",
"=",
"None",
",",
"*",
",",
"loc",
"=",
"None",
",",
"ip",
"=",
"None",
")",
":",
"# TODO: consider supporting constructor \"overloads\", e.g., through a custom",
"# or pybind-provided metaclass.",
"if",
"isinstance",
"(",
"calleeOrResults",
",",
"FuncOp",
")",
":",
"if",
"not",
"isinstance",
"(",
"argumentsOrCallee",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"\"when constructing a call to a function, expected \"",
"+",
"\"the second argument to be a list of call arguments, \"",
"+",
"f\"got {type(argumentsOrCallee)}\"",
")",
"if",
"arguments",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"unexpected third argument when constructing a call\"",
"+",
"\"to a function\"",
")",
"super",
"(",
")",
".",
"__init__",
"(",
"calleeOrResults",
".",
"type",
".",
"results",
",",
"FlatSymbolRefAttr",
".",
"get",
"(",
"calleeOrResults",
".",
"name",
".",
"value",
",",
"context",
"=",
"_get_default_loc_context",
"(",
"loc",
")",
")",
",",
"argumentsOrCallee",
",",
"loc",
"=",
"loc",
",",
"ip",
"=",
"ip",
")",
"return",
"if",
"isinstance",
"(",
"argumentsOrCallee",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"\"when constructing a call to a function by name, \"",
"+",
"\"expected the second argument to be a string or a \"",
"+",
"f\"FlatSymbolRefAttr, got {type(argumentsOrCallee)}\"",
")",
"if",
"isinstance",
"(",
"argumentsOrCallee",
",",
"FlatSymbolRefAttr",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"calleeOrResults",
",",
"argumentsOrCallee",
",",
"arguments",
",",
"loc",
"=",
"loc",
",",
"ip",
"=",
"ip",
")",
"elif",
"isinstance",
"(",
"argumentsOrCallee",
",",
"str",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"calleeOrResults",
",",
"FlatSymbolRefAttr",
".",
"get",
"(",
"argumentsOrCallee",
",",
"context",
"=",
"_get_default_loc_context",
"(",
"loc",
")",
")",
",",
"arguments",
",",
"loc",
"=",
"loc",
",",
"ip",
"=",
"ip",
")"
] | https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/mlir/python/mlir/dialects/_std_ops_ext.py#L29-L93 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/string.py | python | lower | (s) | return s.lower() | lower(s) -> string
Return a copy of the string s converted to lowercase. | lower(s) -> string | [
"lower",
"(",
"s",
")",
"-",
">",
"string"
] | def lower(s):
"""lower(s) -> string
Return a copy of the string s converted to lowercase.
"""
return s.lower() | [
"def",
"lower",
"(",
"s",
")",
":",
"return",
"s",
".",
"lower",
"(",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/string.py#L220-L226 | |
kushview/Element | 1cc16380caa2ab79461246ba758b9de1f46db2a5 | waflib/Options.py | python | OptionsContext.execute | (self) | See :py:func:`waflib.Context.Context.execute` | See :py:func:`waflib.Context.Context.execute` | [
"See",
":",
"py",
":",
"func",
":",
"waflib",
".",
"Context",
".",
"Context",
".",
"execute"
] | def execute(self):
"""
See :py:func:`waflib.Context.Context.execute`
"""
super(OptionsContext, self).execute()
self.parse_args()
Utils.alloc_process_pool(options.jobs) | [
"def",
"execute",
"(",
"self",
")",
":",
"super",
"(",
"OptionsContext",
",",
"self",
")",
".",
"execute",
"(",
")",
"self",
".",
"parse_args",
"(",
")",
"Utils",
".",
"alloc_process_pool",
"(",
"options",
".",
"jobs",
")"
] | https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Options.py#L352-L358 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/urllib3/connection.py | python | HTTPConnection.request_chunked | (self, method, url, body=None, headers=None) | Alternative to the common request method, which sends the
body with chunked encoding and not as one block | Alternative to the common request method, which sends the
body with chunked encoding and not as one block | [
"Alternative",
"to",
"the",
"common",
"request",
"method",
"which",
"sends",
"the",
"body",
"with",
"chunked",
"encoding",
"and",
"not",
"as",
"one",
"block"
] | def request_chunked(self, method, url, body=None, headers=None):
"""
Alternative to the common request method, which sends the
body with chunked encoding and not as one block
"""
headers = HTTPHeaderDict(headers if headers is not None else {})
skip_accept_encoding = "accept-encoding" in headers
skip_host = "host" in headers
self.putrequest(
method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host
)
for header, value in headers.items():
self.putheader(header, value)
if "transfer-encoding" not in headers:
self.putheader("Transfer-Encoding", "chunked")
self.endheaders()
if body is not None:
stringish_types = six.string_types + (bytes,)
if isinstance(body, stringish_types):
body = (body,)
for chunk in body:
if not chunk:
continue
if not isinstance(chunk, bytes):
chunk = chunk.encode("utf8")
len_str = hex(len(chunk))[2:]
self.send(len_str.encode("utf-8"))
self.send(b"\r\n")
self.send(chunk)
self.send(b"\r\n")
# After the if clause, to always have a closed body
self.send(b"0\r\n\r\n") | [
"def",
"request_chunked",
"(",
"self",
",",
"method",
",",
"url",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"headers",
"=",
"HTTPHeaderDict",
"(",
"headers",
"if",
"headers",
"is",
"not",
"None",
"else",
"{",
"}",
")",
"skip_accept_encoding",
"=",
"\"accept-encoding\"",
"in",
"headers",
"skip_host",
"=",
"\"host\"",
"in",
"headers",
"self",
".",
"putrequest",
"(",
"method",
",",
"url",
",",
"skip_accept_encoding",
"=",
"skip_accept_encoding",
",",
"skip_host",
"=",
"skip_host",
")",
"for",
"header",
",",
"value",
"in",
"headers",
".",
"items",
"(",
")",
":",
"self",
".",
"putheader",
"(",
"header",
",",
"value",
")",
"if",
"\"transfer-encoding\"",
"not",
"in",
"headers",
":",
"self",
".",
"putheader",
"(",
"\"Transfer-Encoding\"",
",",
"\"chunked\"",
")",
"self",
".",
"endheaders",
"(",
")",
"if",
"body",
"is",
"not",
"None",
":",
"stringish_types",
"=",
"six",
".",
"string_types",
"+",
"(",
"bytes",
",",
")",
"if",
"isinstance",
"(",
"body",
",",
"stringish_types",
")",
":",
"body",
"=",
"(",
"body",
",",
")",
"for",
"chunk",
"in",
"body",
":",
"if",
"not",
"chunk",
":",
"continue",
"if",
"not",
"isinstance",
"(",
"chunk",
",",
"bytes",
")",
":",
"chunk",
"=",
"chunk",
".",
"encode",
"(",
"\"utf8\"",
")",
"len_str",
"=",
"hex",
"(",
"len",
"(",
"chunk",
")",
")",
"[",
"2",
":",
"]",
"self",
".",
"send",
"(",
"len_str",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"self",
".",
"send",
"(",
"b\"\\r\\n\"",
")",
"self",
".",
"send",
"(",
"chunk",
")",
"self",
".",
"send",
"(",
"b\"\\r\\n\"",
")",
"# After the if clause, to always have a closed body",
"self",
".",
"send",
"(",
"b\"0\\r\\n\\r\\n\"",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/urllib3/connection.py#L187-L220 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/botocore/configloader.py | python | load_config | (config_filename) | return build_profile_map(parsed) | Parse a INI config with profiles.
This will parse an INI config file and map top level profiles
into a top level "profile" key.
If you want to parse an INI file and map all section names to
top level keys, use ``raw_config_parse`` instead. | Parse a INI config with profiles. | [
"Parse",
"a",
"INI",
"config",
"with",
"profiles",
"."
] | def load_config(config_filename):
"""Parse a INI config with profiles.
This will parse an INI config file and map top level profiles
into a top level "profile" key.
If you want to parse an INI file and map all section names to
top level keys, use ``raw_config_parse`` instead.
"""
parsed = raw_config_parse(config_filename)
return build_profile_map(parsed) | [
"def",
"load_config",
"(",
"config_filename",
")",
":",
"parsed",
"=",
"raw_config_parse",
"(",
"config_filename",
")",
"return",
"build_profile_map",
"(",
"parsed",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/configloader.py#L96-L107 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.SetMultipleSelection | (*args, **kwargs) | return _stc.StyledTextCtrl_SetMultipleSelection(*args, **kwargs) | SetMultipleSelection(self, bool multipleSelection)
Set whether multiple selections can be made | SetMultipleSelection(self, bool multipleSelection) | [
"SetMultipleSelection",
"(",
"self",
"bool",
"multipleSelection",
")"
] | def SetMultipleSelection(*args, **kwargs):
"""
SetMultipleSelection(self, bool multipleSelection)
Set whether multiple selections can be made
"""
return _stc.StyledTextCtrl_SetMultipleSelection(*args, **kwargs) | [
"def",
"SetMultipleSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_SetMultipleSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L6040-L6046 | |
rsummers11/CADLab | 976ed959a0b5208bb4173127a7ef732ac73a9b6f | lesion_detector_3DCE/rcnn/processing/bbox_transform.py | python | iou_transform | (ex_rois, gt_rois) | return gt_rois | return bbox targets, IoU loss uses gt_rois as gt | return bbox targets, IoU loss uses gt_rois as gt | [
"return",
"bbox",
"targets",
"IoU",
"loss",
"uses",
"gt_rois",
"as",
"gt"
] | def iou_transform(ex_rois, gt_rois):
""" return bbox targets, IoU loss uses gt_rois as gt """
assert ex_rois.shape[0] == gt_rois.shape[0], 'inconsistent rois number'
return gt_rois | [
"def",
"iou_transform",
"(",
"ex_rois",
",",
"gt_rois",
")",
":",
"assert",
"ex_rois",
".",
"shape",
"[",
"0",
"]",
"==",
"gt_rois",
".",
"shape",
"[",
"0",
"]",
",",
"'inconsistent rois number'",
"return",
"gt_rois"
] | https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/lesion_detector_3DCE/rcnn/processing/bbox_transform.py#L119-L122 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing.py | python | dictOf | ( key, value ) | return Dict( ZeroOrMore( Group ( key + value ) ) ) | Helper to easily and clearly define a dictionary by specifying the respective patterns
for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens
in the proper order. The key pattern can include delimiting markers or punctuation,
as long as they are suppressed, thereby leaving the significant key text. The value
pattern can include named results, so that the C{Dict} results can include named token
fields.
Example::
text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
print(OneOrMore(attr_expr).parseString(text).dump())
attr_label = label
attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)
# similar to Dict, but simpler call format
result = dictOf(attr_label, attr_value).parseString(text)
print(result.dump())
print(result['shape'])
print(result.shape) # object attribute access works too
print(result.asDict())
prints::
[['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
- color: light blue
- posn: upper left
- shape: SQUARE
- texture: burlap
SQUARE
SQUARE
{'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'} | [] | def dictOf( key, value ):
"""
Helper to easily and clearly define a dictionary by specifying the respective patterns
for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens
in the proper order. The key pattern can include delimiting markers or punctuation,
as long as they are suppressed, thereby leaving the significant key text. The value
pattern can include named results, so that the C{Dict} results can include named token
fields.
Example::
text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
print(OneOrMore(attr_expr).parseString(text).dump())
attr_label = label
attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)
# similar to Dict, but simpler call format
result = dictOf(attr_label, attr_value).parseString(text)
print(result.dump())
print(result['shape'])
print(result.shape) # object attribute access works too
print(result.asDict())
prints::
[['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
- color: light blue
- posn: upper left
- shape: SQUARE
- texture: burlap
SQUARE
SQUARE
{'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'}
"""
return Dict( ZeroOrMore( Group ( key + value ) ) ) | [
"def",
"dictOf",
"(",
"key",
",",
"value",
")",
":",
"return",
"Dict",
"(",
"ZeroOrMore",
"(",
"Group",
"(",
"key",
"+",
"value",
")",
")",
")"
] | 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#L9291-L9357 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/model/multipath.py | python | MultiPath.deaggregateHolds | (self) | De-aggregates holds from the global holdSet variable into the sections' holds. | De-aggregates holds from the global holdSet variable into the sections' holds. | [
"De",
"-",
"aggregates",
"holds",
"from",
"the",
"global",
"holdSet",
"variable",
"into",
"the",
"sections",
"holds",
"."
] | def deaggregateHolds(self):
"""De-aggregates holds from the global holdSet variable into the sections' holds."""
for s in self.sections:
for h in s.holdIndices:
s.holds.append(self.holdSet[h])
s.holdIndices = []
self.holdSet = dict() | [
"def",
"deaggregateHolds",
"(",
"self",
")",
":",
"for",
"s",
"in",
"self",
".",
"sections",
":",
"for",
"h",
"in",
"s",
".",
"holdIndices",
":",
"s",
".",
"holds",
".",
"append",
"(",
"self",
".",
"holdSet",
"[",
"h",
"]",
")",
"s",
".",
"holdIndices",
"=",
"[",
"]",
"self",
".",
"holdSet",
"=",
"dict",
"(",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/model/multipath.py#L197-L203 | ||
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | src/bindings/python/src/compatibility/ngraph/utils/node_factory.py | python | NodeFactory._set_node_attr_value | (node: Node, attr_name: str, value: Any) | Set the node attribute value.
@param node: The node we change attribute value for.
@param attr_name: The attribute name.
@param value: The new attribute value. | Set the node attribute value. | [
"Set",
"the",
"node",
"attribute",
"value",
"."
] | def _set_node_attr_value(node: Node, attr_name: str, value: Any) -> None:
"""Set the node attribute value.
@param node: The node we change attribute value for.
@param attr_name: The attribute name.
@param value: The new attribute value.
"""
node.set_attribute(attr_name, value)
node._attr_cache[attr_name] = value | [
"def",
"_set_node_attr_value",
"(",
"node",
":",
"Node",
",",
"attr_name",
":",
"str",
",",
"value",
":",
"Any",
")",
"->",
"None",
":",
"node",
".",
"set_attribute",
"(",
"attr_name",
",",
"value",
")",
"node",
".",
"_attr_cache",
"[",
"attr_name",
"]",
"=",
"value"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/compatibility/ngraph/utils/node_factory.py#L159-L167 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/swf/layer2.py | python | WorkflowExecution.history | (self, **kwargs) | return self._swf.get_workflow_execution_history(self.domain, self.runId,
self.workflowId, **kwargs)['events'] | GetWorkflowExecutionHistory. | GetWorkflowExecutionHistory. | [
"GetWorkflowExecutionHistory",
"."
] | def history(self, **kwargs):
"""GetWorkflowExecutionHistory."""
return self._swf.get_workflow_execution_history(self.domain, self.runId,
self.workflowId, **kwargs)['events'] | [
"def",
"history",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_swf",
".",
"get_workflow_execution_history",
"(",
"self",
".",
"domain",
",",
"self",
".",
"runId",
",",
"self",
".",
"workflowId",
",",
"*",
"*",
"kwargs",
")",
"[",
"'events'",
"]"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/swf/layer2.py#L300-L303 | |
cztomczak/cefpython | 5679f28cec18a57a56e298da2927aac8d8f83ad6 | examples/pysdl2.py | python | RenderHandler.OnPaint | (self, element_type, paint_buffer, **_) | Using the pixel data from CEF's offscreen rendering
the data is converted by PIL into a SDL2 surface
which can then be rendered as a SDL2 texture. | Using the pixel data from CEF's offscreen rendering
the data is converted by PIL into a SDL2 surface
which can then be rendered as a SDL2 texture. | [
"Using",
"the",
"pixel",
"data",
"from",
"CEF",
"s",
"offscreen",
"rendering",
"the",
"data",
"is",
"converted",
"by",
"PIL",
"into",
"a",
"SDL2",
"surface",
"which",
"can",
"then",
"be",
"rendered",
"as",
"a",
"SDL2",
"texture",
"."
] | def OnPaint(self, element_type, paint_buffer, **_):
"""
Using the pixel data from CEF's offscreen rendering
the data is converted by PIL into a SDL2 surface
which can then be rendered as a SDL2 texture.
"""
if element_type == cef.PET_VIEW:
image = Image.frombuffer(
'RGBA',
(self.__width, self.__height),
paint_buffer.GetString(mode="rgba", origin="top-left"),
'raw',
'BGRA'
)
# Following PIL to SDL2 surface code from pysdl2 source.
mode = image.mode
rmask = gmask = bmask = amask = 0
depth = None
pitch = None
if mode == "RGB":
# 3x8-bit, 24bpp
if sdl2.endian.SDL_BYTEORDER == sdl2.endian.SDL_LIL_ENDIAN:
rmask = 0x0000FF
gmask = 0x00FF00
bmask = 0xFF0000
else:
rmask = 0xFF0000
gmask = 0x00FF00
bmask = 0x0000FF
depth = 24
pitch = self.__width * 3
elif mode in ("RGBA", "RGBX"):
# RGBX: 4x8-bit, no alpha
# RGBA: 4x8-bit, alpha
if sdl2.endian.SDL_BYTEORDER == sdl2.endian.SDL_LIL_ENDIAN:
rmask = 0x00000000
gmask = 0x0000FF00
bmask = 0x00FF0000
if mode == "RGBA":
amask = 0xFF000000
else:
rmask = 0xFF000000
gmask = 0x00FF0000
bmask = 0x0000FF00
if mode == "RGBA":
amask = 0x000000FF
depth = 32
pitch = self.__width * 4
else:
logging.error("ERROR: Unsupported mode: %s" % mode)
exit_app()
pxbuf = image.tobytes()
# Create surface
surface = sdl2.SDL_CreateRGBSurfaceFrom(
pxbuf,
self.__width,
self.__height,
depth,
pitch,
rmask,
gmask,
bmask,
amask
)
if self.texture:
# free memory used by previous texture
sdl2.SDL_DestroyTexture(self.texture)
# Create texture
self.texture = sdl2.SDL_CreateTextureFromSurface(self.__renderer,
surface)
# Free the surface
sdl2.SDL_FreeSurface(surface)
else:
logging.warning("Unsupport element_type in OnPaint") | [
"def",
"OnPaint",
"(",
"self",
",",
"element_type",
",",
"paint_buffer",
",",
"*",
"*",
"_",
")",
":",
"if",
"element_type",
"==",
"cef",
".",
"PET_VIEW",
":",
"image",
"=",
"Image",
".",
"frombuffer",
"(",
"'RGBA'",
",",
"(",
"self",
".",
"__width",
",",
"self",
".",
"__height",
")",
",",
"paint_buffer",
".",
"GetString",
"(",
"mode",
"=",
"\"rgba\"",
",",
"origin",
"=",
"\"top-left\"",
")",
",",
"'raw'",
",",
"'BGRA'",
")",
"# Following PIL to SDL2 surface code from pysdl2 source.",
"mode",
"=",
"image",
".",
"mode",
"rmask",
"=",
"gmask",
"=",
"bmask",
"=",
"amask",
"=",
"0",
"depth",
"=",
"None",
"pitch",
"=",
"None",
"if",
"mode",
"==",
"\"RGB\"",
":",
"# 3x8-bit, 24bpp",
"if",
"sdl2",
".",
"endian",
".",
"SDL_BYTEORDER",
"==",
"sdl2",
".",
"endian",
".",
"SDL_LIL_ENDIAN",
":",
"rmask",
"=",
"0x0000FF",
"gmask",
"=",
"0x00FF00",
"bmask",
"=",
"0xFF0000",
"else",
":",
"rmask",
"=",
"0xFF0000",
"gmask",
"=",
"0x00FF00",
"bmask",
"=",
"0x0000FF",
"depth",
"=",
"24",
"pitch",
"=",
"self",
".",
"__width",
"*",
"3",
"elif",
"mode",
"in",
"(",
"\"RGBA\"",
",",
"\"RGBX\"",
")",
":",
"# RGBX: 4x8-bit, no alpha",
"# RGBA: 4x8-bit, alpha",
"if",
"sdl2",
".",
"endian",
".",
"SDL_BYTEORDER",
"==",
"sdl2",
".",
"endian",
".",
"SDL_LIL_ENDIAN",
":",
"rmask",
"=",
"0x00000000",
"gmask",
"=",
"0x0000FF00",
"bmask",
"=",
"0x00FF0000",
"if",
"mode",
"==",
"\"RGBA\"",
":",
"amask",
"=",
"0xFF000000",
"else",
":",
"rmask",
"=",
"0xFF000000",
"gmask",
"=",
"0x00FF0000",
"bmask",
"=",
"0x0000FF00",
"if",
"mode",
"==",
"\"RGBA\"",
":",
"amask",
"=",
"0x000000FF",
"depth",
"=",
"32",
"pitch",
"=",
"self",
".",
"__width",
"*",
"4",
"else",
":",
"logging",
".",
"error",
"(",
"\"ERROR: Unsupported mode: %s\"",
"%",
"mode",
")",
"exit_app",
"(",
")",
"pxbuf",
"=",
"image",
".",
"tobytes",
"(",
")",
"# Create surface",
"surface",
"=",
"sdl2",
".",
"SDL_CreateRGBSurfaceFrom",
"(",
"pxbuf",
",",
"self",
".",
"__width",
",",
"self",
".",
"__height",
",",
"depth",
",",
"pitch",
",",
"rmask",
",",
"gmask",
",",
"bmask",
",",
"amask",
")",
"if",
"self",
".",
"texture",
":",
"# free memory used by previous texture",
"sdl2",
".",
"SDL_DestroyTexture",
"(",
"self",
".",
"texture",
")",
"# Create texture",
"self",
".",
"texture",
"=",
"sdl2",
".",
"SDL_CreateTextureFromSurface",
"(",
"self",
".",
"__renderer",
",",
"surface",
")",
"# Free the surface",
"sdl2",
".",
"SDL_FreeSurface",
"(",
"surface",
")",
"else",
":",
"logging",
".",
"warning",
"(",
"\"Unsupport element_type in OnPaint\"",
")"
] | https://github.com/cztomczak/cefpython/blob/5679f28cec18a57a56e298da2927aac8d8f83ad6/examples/pysdl2.py#L505-L579 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pyparsing.py | python | removeQuotes | (s, l, t) | return t[0][1:-1] | Helper parse action for removing quotation marks from parsed
quoted strings.
Example::
# by default, quotation marks are included in parsed results
quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"]
# use removeQuotes to strip quotation marks from parsed results
quotedString.setParseAction(removeQuotes)
quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"] | Helper parse action for removing quotation marks from parsed
quoted strings. | [
"Helper",
"parse",
"action",
"for",
"removing",
"quotation",
"marks",
"from",
"parsed",
"quoted",
"strings",
"."
] | def removeQuotes(s, l, t):
"""Helper parse action for removing quotation marks from parsed
quoted strings.
Example::
# by default, quotation marks are included in parsed results
quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"]
# use removeQuotes to strip quotation marks from parsed results
quotedString.setParseAction(removeQuotes)
quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"]
"""
return t[0][1:-1] | [
"def",
"removeQuotes",
"(",
"s",
",",
"l",
",",
"t",
")",
":",
"return",
"t",
"[",
"0",
"]",
"[",
"1",
":",
"-",
"1",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pyparsing.py#L5735-L5748 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/suncxx.py | python | generate | (env) | Add Builders and construction variables for SunPRO C++. | Add Builders and construction variables for SunPRO C++. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"SunPRO",
"C",
"++",
"."
] | def generate(env):
"""Add Builders and construction variables for SunPRO C++."""
path, cxx, shcxx, version = get_cppc(env)
if path:
cxx = os.path.join(path, cxx)
shcxx = os.path.join(path, shcxx)
cplusplus.generate(env)
env['CXX'] = cxx
env['SHCXX'] = shcxx
env['CXXVERSION'] = version
env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS -KPIC')
env['SHOBJPREFIX'] = 'so_'
env['SHOBJSUFFIX'] = '.o' | [
"def",
"generate",
"(",
"env",
")",
":",
"path",
",",
"cxx",
",",
"shcxx",
",",
"version",
"=",
"get_cppc",
"(",
"env",
")",
"if",
"path",
":",
"cxx",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"cxx",
")",
"shcxx",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"shcxx",
")",
"cplusplus",
".",
"generate",
"(",
"env",
")",
"env",
"[",
"'CXX'",
"]",
"=",
"cxx",
"env",
"[",
"'SHCXX'",
"]",
"=",
"shcxx",
"env",
"[",
"'CXXVERSION'",
"]",
"=",
"version",
"env",
"[",
"'SHCXXFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"'$CXXFLAGS -KPIC'",
")",
"env",
"[",
"'SHOBJPREFIX'",
"]",
"=",
"'so_'",
"env",
"[",
"'SHOBJSUFFIX'",
"]",
"=",
"'.o'"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/suncxx.py#L136-L150 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/packages/urllib3/fields.py | python | guess_content_type | (filename, default='application/octet-stream') | return default | Guess the "Content-Type" of a file.
:param filename:
The filename to guess the "Content-Type" of using :mod:`mimetypes`.
:param default:
If no "Content-Type" can be guessed, default to `default`. | Guess the "Content-Type" of a file. | [
"Guess",
"the",
"Content",
"-",
"Type",
"of",
"a",
"file",
"."
] | def guess_content_type(filename, default='application/octet-stream'):
"""
Guess the "Content-Type" of a file.
:param filename:
The filename to guess the "Content-Type" of using :mod:`mimetypes`.
:param default:
If no "Content-Type" can be guessed, default to `default`.
"""
if filename:
return mimetypes.guess_type(filename)[0] or default
return default | [
"def",
"guess_content_type",
"(",
"filename",
",",
"default",
"=",
"'application/octet-stream'",
")",
":",
"if",
"filename",
":",
"return",
"mimetypes",
".",
"guess_type",
"(",
"filename",
")",
"[",
"0",
"]",
"or",
"default",
"return",
"default"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/packages/urllib3/fields.py#L7-L18 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/gyp/pylib/gyp/__init__.py | python | RegenerateAppendFlag | (flag, values, predicate, env_name, options) | return flags | Regenerate a list of command line flags, for an option of action='append'.
The |env_name|, if given, is checked in the environment and used to generate
an initial list of options, then the options that were specified on the
command line (given in |values|) are appended. This matches the handling of
environment variables and command line flags where command line flags override
the environment, while not requiring the environment to be set when the flags
are used again. | Regenerate a list of command line flags, for an option of action='append'. | [
"Regenerate",
"a",
"list",
"of",
"command",
"line",
"flags",
"for",
"an",
"option",
"of",
"action",
"=",
"append",
"."
] | def RegenerateAppendFlag(flag, values, predicate, env_name, options):
"""Regenerate a list of command line flags, for an option of action='append'.
The |env_name|, if given, is checked in the environment and used to generate
an initial list of options, then the options that were specified on the
command line (given in |values|) are appended. This matches the handling of
environment variables and command line flags where command line flags override
the environment, while not requiring the environment to be set when the flags
are used again.
"""
flags = []
if options.use_environment and env_name:
for flag_value in ShlexEnv(env_name):
value = FormatOpt(flag, predicate(flag_value))
if value in flags:
flags.remove(value)
flags.append(value)
if values:
for flag_value in values:
flags.append(FormatOpt(flag, predicate(flag_value)))
return flags | [
"def",
"RegenerateAppendFlag",
"(",
"flag",
",",
"values",
",",
"predicate",
",",
"env_name",
",",
"options",
")",
":",
"flags",
"=",
"[",
"]",
"if",
"options",
".",
"use_environment",
"and",
"env_name",
":",
"for",
"flag_value",
"in",
"ShlexEnv",
"(",
"env_name",
")",
":",
"value",
"=",
"FormatOpt",
"(",
"flag",
",",
"predicate",
"(",
"flag_value",
")",
")",
"if",
"value",
"in",
"flags",
":",
"flags",
".",
"remove",
"(",
"value",
")",
"flags",
".",
"append",
"(",
"value",
")",
"if",
"values",
":",
"for",
"flag_value",
"in",
"values",
":",
"flags",
".",
"append",
"(",
"FormatOpt",
"(",
"flag",
",",
"predicate",
"(",
"flag_value",
")",
")",
")",
"return",
"flags"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/__init__.py#L192-L212 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/ir/builder.py | python | IRBuilder.fcmp_unordered | (self, cmpop, lhs, rhs, name='', flags=[]) | return instr | Floating-point unordered comparison:
name = lhs <cmpop> rhs
where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno' | Floating-point unordered comparison:
name = lhs <cmpop> rhs | [
"Floating",
"-",
"point",
"unordered",
"comparison",
":",
"name",
"=",
"lhs",
"<cmpop",
">",
"rhs"
] | def fcmp_unordered(self, cmpop, lhs, rhs, name='', flags=[]):
"""
Floating-point unordered comparison:
name = lhs <cmpop> rhs
where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno'
"""
if cmpop in _CMP_MAP:
op = 'u' + _CMP_MAP[cmpop]
else:
op = cmpop
instr = instructions.FCMPInstr(self.block, op, lhs, rhs, name=name, flags=flags)
self._insert(instr)
return instr | [
"def",
"fcmp_unordered",
"(",
"self",
",",
"cmpop",
",",
"lhs",
",",
"rhs",
",",
"name",
"=",
"''",
",",
"flags",
"=",
"[",
"]",
")",
":",
"if",
"cmpop",
"in",
"_CMP_MAP",
":",
"op",
"=",
"'u'",
"+",
"_CMP_MAP",
"[",
"cmpop",
"]",
"else",
":",
"op",
"=",
"cmpop",
"instr",
"=",
"instructions",
".",
"FCMPInstr",
"(",
"self",
".",
"block",
",",
"op",
",",
"lhs",
",",
"rhs",
",",
"name",
"=",
"name",
",",
"flags",
"=",
"flags",
")",
"self",
".",
"_insert",
"(",
"instr",
")",
"return",
"instr"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/ir/builder.py#L576-L589 | |
line/stellite | 5bd1c1f5f0cdc22a65319068f4f8b2ca7769bfa1 | tools/build.py | python | BuildObject.fetch_node | (self) | fetch nodejs | fetch nodejs | [
"fetch",
"nodejs"
] | def fetch_node(self):
"""fetch nodejs"""
for tag, version in NODE_VERSIONS.iteritems():
node_path = os.path.join(self.node_root_path, str(tag))
if os.path.exists(node_path):
continue
os.makedirs(node_path)
try:
temp_dir = tempfile.mkdtemp(dir=self.root_path)
self.install_node(temp_dir, tag, version)
finally:
shutil.rmtree(temp_dir) | [
"def",
"fetch_node",
"(",
"self",
")",
":",
"for",
"tag",
",",
"version",
"in",
"NODE_VERSIONS",
".",
"iteritems",
"(",
")",
":",
"node_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"node_root_path",
",",
"str",
"(",
"tag",
")",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"node_path",
")",
":",
"continue",
"os",
".",
"makedirs",
"(",
"node_path",
")",
"try",
":",
"temp_dir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"dir",
"=",
"self",
".",
"root_path",
")",
"self",
".",
"install_node",
"(",
"temp_dir",
",",
"tag",
",",
"version",
")",
"finally",
":",
"shutil",
".",
"rmtree",
"(",
"temp_dir",
")"
] | https://github.com/line/stellite/blob/5bd1c1f5f0cdc22a65319068f4f8b2ca7769bfa1/tools/build.py#L748-L760 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Path/PathScripts/PathAreaOp.py | python | ObjectOp.initOperation | (self, obj) | initOperation(obj) ... sets up standard Path.Area properties and calls initAreaOp().
Do not overwrite, overwrite initAreaOp(obj) instead. | initOperation(obj) ... sets up standard Path.Area properties and calls initAreaOp().
Do not overwrite, overwrite initAreaOp(obj) instead. | [
"initOperation",
"(",
"obj",
")",
"...",
"sets",
"up",
"standard",
"Path",
".",
"Area",
"properties",
"and",
"calls",
"initAreaOp",
"()",
".",
"Do",
"not",
"overwrite",
"overwrite",
"initAreaOp",
"(",
"obj",
")",
"instead",
"."
] | def initOperation(self, obj):
"""initOperation(obj) ... sets up standard Path.Area properties and calls initAreaOp().
Do not overwrite, overwrite initAreaOp(obj) instead."""
PathLog.track()
# Debugging
obj.addProperty("App::PropertyString", "AreaParams", "Path")
obj.setEditorMode("AreaParams", 2) # hide
obj.addProperty("App::PropertyString", "PathParams", "Path")
obj.setEditorMode("PathParams", 2) # hide
obj.addProperty("Part::PropertyPartShape", "removalshape", "Path")
obj.setEditorMode("removalshape", 2) # hide
obj.addProperty(
"App::PropertyBool",
"SplitArcs",
"Path",
QT_TRANSLATE_NOOP("App::Property", "Split Arcs into discrete segments"),
)
# obj.Proxy = self
self.initAreaOp(obj) | [
"def",
"initOperation",
"(",
"self",
",",
"obj",
")",
":",
"PathLog",
".",
"track",
"(",
")",
"# Debugging",
"obj",
".",
"addProperty",
"(",
"\"App::PropertyString\"",
",",
"\"AreaParams\"",
",",
"\"Path\"",
")",
"obj",
".",
"setEditorMode",
"(",
"\"AreaParams\"",
",",
"2",
")",
"# hide",
"obj",
".",
"addProperty",
"(",
"\"App::PropertyString\"",
",",
"\"PathParams\"",
",",
"\"Path\"",
")",
"obj",
".",
"setEditorMode",
"(",
"\"PathParams\"",
",",
"2",
")",
"# hide",
"obj",
".",
"addProperty",
"(",
"\"Part::PropertyPartShape\"",
",",
"\"removalshape\"",
",",
"\"Path\"",
")",
"obj",
".",
"setEditorMode",
"(",
"\"removalshape\"",
",",
"2",
")",
"# hide",
"obj",
".",
"addProperty",
"(",
"\"App::PropertyBool\"",
",",
"\"SplitArcs\"",
",",
"\"Path\"",
",",
"QT_TRANSLATE_NOOP",
"(",
"\"App::Property\"",
",",
"\"Split Arcs into discrete segments\"",
")",
",",
")",
"# obj.Proxy = self",
"self",
".",
"initAreaOp",
"(",
"obj",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathAreaOp.py#L82-L104 | ||
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/dask_cudf/versioneer.py | python | git_get_keywords | (versionfile_abs) | return keywords | Extract version information from the given file. | Extract version information from the given file. | [
"Extract",
"version",
"information",
"from",
"the",
"given",
"file",
"."
] | def git_get_keywords(versionfile_abs):
"""Extract version information from the given file."""
# the code embedded in _version.py can just fetch the value of these
# keywords. When used from setup.py, we don't want to import _version.py,
# so we do it with a regexp instead. This function is not used from
# _version.py.
keywords = {}
try:
f = open(versionfile_abs, "r")
for line in f.readlines():
if line.strip().startswith("git_refnames ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["refnames"] = mo.group(1)
if line.strip().startswith("git_full ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["full"] = mo.group(1)
if line.strip().startswith("git_date ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["date"] = mo.group(1)
f.close()
except EnvironmentError:
pass
return keywords | [
"def",
"git_get_keywords",
"(",
"versionfile_abs",
")",
":",
"# the code embedded in _version.py can just fetch the value of these",
"# keywords. When used from setup.py, we don't want to import _version.py,",
"# so we do it with a regexp instead. This function is not used from",
"# _version.py.",
"keywords",
"=",
"{",
"}",
"try",
":",
"f",
"=",
"open",
"(",
"versionfile_abs",
",",
"\"r\"",
")",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
":",
"if",
"line",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"\"git_refnames =\"",
")",
":",
"mo",
"=",
"re",
".",
"search",
"(",
"r'=\\s*\"(.*)\"'",
",",
"line",
")",
"if",
"mo",
":",
"keywords",
"[",
"\"refnames\"",
"]",
"=",
"mo",
".",
"group",
"(",
"1",
")",
"if",
"line",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"\"git_full =\"",
")",
":",
"mo",
"=",
"re",
".",
"search",
"(",
"r'=\\s*\"(.*)\"'",
",",
"line",
")",
"if",
"mo",
":",
"keywords",
"[",
"\"full\"",
"]",
"=",
"mo",
".",
"group",
"(",
"1",
")",
"if",
"line",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"\"git_date =\"",
")",
":",
"mo",
"=",
"re",
".",
"search",
"(",
"r'=\\s*\"(.*)\"'",
",",
"line",
")",
"if",
"mo",
":",
"keywords",
"[",
"\"date\"",
"]",
"=",
"mo",
".",
"group",
"(",
"1",
")",
"f",
".",
"close",
"(",
")",
"except",
"EnvironmentError",
":",
"pass",
"return",
"keywords"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/dask_cudf/versioneer.py#L959-L984 | |
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | lldb/third_party/Python/module/pexpect-2.4/pexpect.py | python | spawn.__iter__ | (self) | return self | This is to support iterators over a file-like object. | This is to support iterators over a file-like object. | [
"This",
"is",
"to",
"support",
"iterators",
"over",
"a",
"file",
"-",
"like",
"object",
"."
] | def __iter__(self): # File-like object.
"""This is to support iterators over a file-like object.
"""
return self | [
"def",
"__iter__",
"(",
"self",
")",
":",
"# File-like object.",
"return",
"self"
] | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/third_party/Python/module/pexpect-2.4/pexpect.py#L943-L947 | |
ducha-aiki/LSUVinit | a42ecdc0d44c217a29b65e98748d80b90d5c6279 | scripts/cpp_lint.py | python | _NestingState.SeenOpenBrace | (self) | return (not self.stack) or self.stack[-1].seen_open_brace | Check if we have seen the opening brace for the innermost block.
Returns:
True if we have seen the opening brace, False if the innermost
block is still expecting an opening brace. | Check if we have seen the opening brace for the innermost block. | [
"Check",
"if",
"we",
"have",
"seen",
"the",
"opening",
"brace",
"for",
"the",
"innermost",
"block",
"."
] | def SeenOpenBrace(self):
"""Check if we have seen the opening brace for the innermost block.
Returns:
True if we have seen the opening brace, False if the innermost
block is still expecting an opening brace.
"""
return (not self.stack) or self.stack[-1].seen_open_brace | [
"def",
"SeenOpenBrace",
"(",
"self",
")",
":",
"return",
"(",
"not",
"self",
".",
"stack",
")",
"or",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"seen_open_brace"
] | https://github.com/ducha-aiki/LSUVinit/blob/a42ecdc0d44c217a29b65e98748d80b90d5c6279/scripts/cpp_lint.py#L1931-L1938 | |
ArduPilot/ardupilot | 6e684b3496122b8158ac412b609d00004b7ac306 | Tools/scripts/tempcal_IMU.py | python | Coefficients.correction_gyro | (self, imu, temperature) | return Vector3(self.correction(self.gcoef[imu], imu, temperature, 'X', cal_temp),
self.correction(self.gcoef[imu], imu, temperature, 'Y', cal_temp),
self.correction(self.gcoef[imu], imu, temperature, 'Z', cal_temp)) | calculate gyro correction from temperature calibration from
log data using parameters | calculate gyro correction from temperature calibration from
log data using parameters | [
"calculate",
"gyro",
"correction",
"from",
"temperature",
"calibration",
"from",
"log",
"data",
"using",
"parameters"
] | def correction_gyro(self, imu, temperature):
'''calculate gyro correction from temperature calibration from
log data using parameters'''
cal_temp = self.gtcal.get(imu, TEMP_REF)
return Vector3(self.correction(self.gcoef[imu], imu, temperature, 'X', cal_temp),
self.correction(self.gcoef[imu], imu, temperature, 'Y', cal_temp),
self.correction(self.gcoef[imu], imu, temperature, 'Z', cal_temp)) | [
"def",
"correction_gyro",
"(",
"self",
",",
"imu",
",",
"temperature",
")",
":",
"cal_temp",
"=",
"self",
".",
"gtcal",
".",
"get",
"(",
"imu",
",",
"TEMP_REF",
")",
"return",
"Vector3",
"(",
"self",
".",
"correction",
"(",
"self",
".",
"gcoef",
"[",
"imu",
"]",
",",
"imu",
",",
"temperature",
",",
"'X'",
",",
"cal_temp",
")",
",",
"self",
".",
"correction",
"(",
"self",
".",
"gcoef",
"[",
"imu",
"]",
",",
"imu",
",",
"temperature",
",",
"'Y'",
",",
"cal_temp",
")",
",",
"self",
".",
"correction",
"(",
"self",
".",
"gcoef",
"[",
"imu",
"]",
",",
"imu",
",",
"temperature",
",",
"'Z'",
",",
"cal_temp",
")",
")"
] | https://github.com/ArduPilot/ardupilot/blob/6e684b3496122b8158ac412b609d00004b7ac306/Tools/scripts/tempcal_IMU.py#L126-L132 | |
ApolloAuto/apollo | 463fb82f9e979d02dcb25044e60931293ab2dba0 | modules/tools/sensor_calibration/extract_data.py | python | Extractor.get_substring | (str, prefix, suffix) | return str[str_p:end_p] | return substring, eclusive prefix or suffix | return substring, eclusive prefix or suffix | [
"return",
"substring",
"eclusive",
"prefix",
"or",
"suffix"
] | def get_substring(str, prefix, suffix):
"""return substring, eclusive prefix or suffix"""
str_p = str.rfind(prefix) + len(prefix)
end_p = str.rfind(suffix)
return str[str_p:end_p] | [
"def",
"get_substring",
"(",
"str",
",",
"prefix",
",",
"suffix",
")",
":",
"str_p",
"=",
"str",
".",
"rfind",
"(",
"prefix",
")",
"+",
"len",
"(",
"prefix",
")",
"end_p",
"=",
"str",
".",
"rfind",
"(",
"suffix",
")",
"return",
"str",
"[",
"str_p",
":",
"end_p",
"]"
] | https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/modules/tools/sensor_calibration/extract_data.py#L467-L471 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/antithesis_suite.py | python | generate_all | () | Generate all suites. | Generate all suites. | [
"Generate",
"all",
"suites",
"."
] | def generate_all():
"""Generate all suites."""
for path in os.listdir(_SUITES_PATH):
if os.path.isfile(os.path.join(_SUITES_PATH, path)):
suite = path.split(".")[0]
_generate(suite) | [
"def",
"generate_all",
"(",
")",
":",
"for",
"path",
"in",
"os",
".",
"listdir",
"(",
"_SUITES_PATH",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"_SUITES_PATH",
",",
"path",
")",
")",
":",
"suite",
"=",
"path",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
"_generate",
"(",
"suite",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/antithesis_suite.py#L116-L121 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/SANS/sans/algorithm_detail/calibration.py | python | get_missing_parameters | (calibration_workspace, workspace) | return missing_parameter_names | Get a list of missing parameter names which are on the data workspace but not on the calibration workspace.
:param calibration_workspace: the calibration workspace
:param workspace: the data workspace (which is to be calibrated later on).
:return: a list of parameters which exist on the data workspace but not on the calibration workspace. | Get a list of missing parameter names which are on the data workspace but not on the calibration workspace. | [
"Get",
"a",
"list",
"of",
"missing",
"parameter",
"names",
"which",
"are",
"on",
"the",
"data",
"workspace",
"but",
"not",
"on",
"the",
"calibration",
"workspace",
"."
] | def get_missing_parameters(calibration_workspace, workspace):
"""
Get a list of missing parameter names which are on the data workspace but not on the calibration workspace.
:param calibration_workspace: the calibration workspace
:param workspace: the data workspace (which is to be calibrated later on).
:return: a list of parameters which exist on the data workspace but not on the calibration workspace.
"""
original_parameter_names = workspace.getInstrument().getParameterNames()
calibration_workspace_instrument = calibration_workspace.getInstrument()
missing_parameter_names = []
for parameter in original_parameter_names:
if not calibration_workspace_instrument.hasParameter(parameter):
missing_parameter_names.append(parameter)
return missing_parameter_names | [
"def",
"get_missing_parameters",
"(",
"calibration_workspace",
",",
"workspace",
")",
":",
"original_parameter_names",
"=",
"workspace",
".",
"getInstrument",
"(",
")",
".",
"getParameterNames",
"(",
")",
"calibration_workspace_instrument",
"=",
"calibration_workspace",
".",
"getInstrument",
"(",
")",
"missing_parameter_names",
"=",
"[",
"]",
"for",
"parameter",
"in",
"original_parameter_names",
":",
"if",
"not",
"calibration_workspace_instrument",
".",
"hasParameter",
"(",
"parameter",
")",
":",
"missing_parameter_names",
".",
"append",
"(",
"parameter",
")",
"return",
"missing_parameter_names"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/sans/algorithm_detail/calibration.py#L205-L219 | |
fatih/subvim | 241b6d170597857105da219c9b7d36059e9f11fb | vim/base/YouCompleteMe/third_party/jedi/jedi/parser/__init__.py | python | Parser._parse_dot_name | (self, pre_used_token=None) | return n, token_type, tok | The dot name parser parses a name, variable or function and returns
their names.
:return: Tuple of Name, token_type, nexttoken.
:rtype: tuple(Name, int, str) | The dot name parser parses a name, variable or function and returns
their names. | [
"The",
"dot",
"name",
"parser",
"parses",
"a",
"name",
"variable",
"or",
"function",
"and",
"returns",
"their",
"names",
"."
] | def _parse_dot_name(self, pre_used_token=None):
"""
The dot name parser parses a name, variable or function and returns
their names.
:return: Tuple of Name, token_type, nexttoken.
:rtype: tuple(Name, int, str)
"""
def append(el):
names.append(el)
self.module.temp_used_names.append(el[0])
names = []
if pre_used_token is None:
token_type, tok = self.next()
if token_type != tokenize.NAME and tok != '*':
return [], token_type, tok
else:
token_type, tok = pre_used_token
if token_type != tokenize.NAME and tok != '*':
# token maybe a name or star
return None, token_type, tok
append((tok, self.start_pos))
first_pos = self.start_pos
while True:
end_pos = self.end_pos
token_type, tok = self.next()
if tok != '.':
break
token_type, tok = self.next()
if token_type != tokenize.NAME:
break
append((tok, self.start_pos))
n = pr.Name(self.module, names, first_pos, end_pos) if names else None
return n, token_type, tok | [
"def",
"_parse_dot_name",
"(",
"self",
",",
"pre_used_token",
"=",
"None",
")",
":",
"def",
"append",
"(",
"el",
")",
":",
"names",
".",
"append",
"(",
"el",
")",
"self",
".",
"module",
".",
"temp_used_names",
".",
"append",
"(",
"el",
"[",
"0",
"]",
")",
"names",
"=",
"[",
"]",
"if",
"pre_used_token",
"is",
"None",
":",
"token_type",
",",
"tok",
"=",
"self",
".",
"next",
"(",
")",
"if",
"token_type",
"!=",
"tokenize",
".",
"NAME",
"and",
"tok",
"!=",
"'*'",
":",
"return",
"[",
"]",
",",
"token_type",
",",
"tok",
"else",
":",
"token_type",
",",
"tok",
"=",
"pre_used_token",
"if",
"token_type",
"!=",
"tokenize",
".",
"NAME",
"and",
"tok",
"!=",
"'*'",
":",
"# token maybe a name or star",
"return",
"None",
",",
"token_type",
",",
"tok",
"append",
"(",
"(",
"tok",
",",
"self",
".",
"start_pos",
")",
")",
"first_pos",
"=",
"self",
".",
"start_pos",
"while",
"True",
":",
"end_pos",
"=",
"self",
".",
"end_pos",
"token_type",
",",
"tok",
"=",
"self",
".",
"next",
"(",
")",
"if",
"tok",
"!=",
"'.'",
":",
"break",
"token_type",
",",
"tok",
"=",
"self",
".",
"next",
"(",
")",
"if",
"token_type",
"!=",
"tokenize",
".",
"NAME",
":",
"break",
"append",
"(",
"(",
"tok",
",",
"self",
".",
"start_pos",
")",
")",
"n",
"=",
"pr",
".",
"Name",
"(",
"self",
".",
"module",
",",
"names",
",",
"first_pos",
",",
"end_pos",
")",
"if",
"names",
"else",
"None",
"return",
"n",
",",
"token_type",
",",
"tok"
] | https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/third_party/jedi/jedi/parser/__init__.py#L113-L150 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/posixpath.py | python | normpath | (path) | return path or dot | Normalize path, eliminating double slashes, etc. | Normalize path, eliminating double slashes, etc. | [
"Normalize",
"path",
"eliminating",
"double",
"slashes",
"etc",
"."
] | def normpath(path):
"""Normalize path, eliminating double slashes, etc."""
# Preserve unicode (if path is unicode)
slash, dot = (u'/', u'.') if isinstance(path, _unicode) else ('/', '.')
if path == '':
return dot
initial_slashes = path.startswith('/')
# POSIX allows one or two initial slashes, but treats three or more
# as single slash.
if (initial_slashes and
path.startswith('//') and not path.startswith('///')):
initial_slashes = 2
comps = path.split('/')
new_comps = []
for comp in comps:
if comp in ('', '.'):
continue
if (comp != '..' or (not initial_slashes and not new_comps) or
(new_comps and new_comps[-1] == '..')):
new_comps.append(comp)
elif new_comps:
new_comps.pop()
comps = new_comps
path = slash.join(comps)
if initial_slashes:
path = slash*initial_slashes + path
return path or dot | [
"def",
"normpath",
"(",
"path",
")",
":",
"# Preserve unicode (if path is unicode)",
"slash",
",",
"dot",
"=",
"(",
"u'/'",
",",
"u'.'",
")",
"if",
"isinstance",
"(",
"path",
",",
"_unicode",
")",
"else",
"(",
"'/'",
",",
"'.'",
")",
"if",
"path",
"==",
"''",
":",
"return",
"dot",
"initial_slashes",
"=",
"path",
".",
"startswith",
"(",
"'/'",
")",
"# POSIX allows one or two initial slashes, but treats three or more",
"# as single slash.",
"if",
"(",
"initial_slashes",
"and",
"path",
".",
"startswith",
"(",
"'//'",
")",
"and",
"not",
"path",
".",
"startswith",
"(",
"'///'",
")",
")",
":",
"initial_slashes",
"=",
"2",
"comps",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
"new_comps",
"=",
"[",
"]",
"for",
"comp",
"in",
"comps",
":",
"if",
"comp",
"in",
"(",
"''",
",",
"'.'",
")",
":",
"continue",
"if",
"(",
"comp",
"!=",
"'..'",
"or",
"(",
"not",
"initial_slashes",
"and",
"not",
"new_comps",
")",
"or",
"(",
"new_comps",
"and",
"new_comps",
"[",
"-",
"1",
"]",
"==",
"'..'",
")",
")",
":",
"new_comps",
".",
"append",
"(",
"comp",
")",
"elif",
"new_comps",
":",
"new_comps",
".",
"pop",
"(",
")",
"comps",
"=",
"new_comps",
"path",
"=",
"slash",
".",
"join",
"(",
"comps",
")",
"if",
"initial_slashes",
":",
"path",
"=",
"slash",
"*",
"initial_slashes",
"+",
"path",
"return",
"path",
"or",
"dot"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/posixpath.py#L321-L347 | |
raspberrypi/tools | 13474ee775d0c5ec8a7da4fb0a9fa84187abfc87 | arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/share/gdb/python/gdb/command/type_printers.py | python | InfoTypePrinter.invoke | (self, arg, from_tty) | GDB calls this to perform the command. | GDB calls this to perform the command. | [
"GDB",
"calls",
"this",
"to",
"perform",
"the",
"command",
"."
] | def invoke(self, arg, from_tty):
"""GDB calls this to perform the command."""
sep = ''
for objfile in gdb.objfiles():
if objfile.type_printers:
print ("%sType printers for %s:" % (sep, objfile.name))
self.list_type_printers(objfile.type_printers)
sep = '\n'
if gdb.current_progspace().type_printers:
print ("%sType printers for program space:" % sep)
self.list_type_printers(gdb.current_progspace().type_printers)
sep = '\n'
if gdb.type_printers:
print ("%sGlobal type printers:" % sep)
self.list_type_printers(gdb.type_printers) | [
"def",
"invoke",
"(",
"self",
",",
"arg",
",",
"from_tty",
")",
":",
"sep",
"=",
"''",
"for",
"objfile",
"in",
"gdb",
".",
"objfiles",
"(",
")",
":",
"if",
"objfile",
".",
"type_printers",
":",
"print",
"(",
"\"%sType printers for %s:\"",
"%",
"(",
"sep",
",",
"objfile",
".",
"name",
")",
")",
"self",
".",
"list_type_printers",
"(",
"objfile",
".",
"type_printers",
")",
"sep",
"=",
"'\\n'",
"if",
"gdb",
".",
"current_progspace",
"(",
")",
".",
"type_printers",
":",
"print",
"(",
"\"%sType printers for program space:\"",
"%",
"sep",
")",
"self",
".",
"list_type_printers",
"(",
"gdb",
".",
"current_progspace",
"(",
")",
".",
"type_printers",
")",
"sep",
"=",
"'\\n'",
"if",
"gdb",
".",
"type_printers",
":",
"print",
"(",
"\"%sGlobal type printers:\"",
"%",
"sep",
")",
"self",
".",
"list_type_printers",
"(",
"gdb",
".",
"type_printers",
")"
] | https://github.com/raspberrypi/tools/blob/13474ee775d0c5ec8a7da4fb0a9fa84187abfc87/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/share/gdb/python/gdb/command/type_printers.py#L45-L59 | ||
stellar-deprecated/stellard | 67eabb2217bdfa9a6ea317f62338fb6bca458c90 | src/protobuf/python/google/protobuf/text_format.py | python | _Tokenizer.NextToken | (self) | Reads the next meaningful token. | Reads the next meaningful token. | [
"Reads",
"the",
"next",
"meaningful",
"token",
"."
] | def NextToken(self):
"""Reads the next meaningful token."""
self._previous_line = self._line
self._previous_column = self._column
self._column += len(self.token)
self._SkipWhitespace()
if not self._lines and len(self._current_line) <= self._column:
self.token = ''
return
match = self._TOKEN.match(self._current_line, self._column)
if match:
token = match.group(0)
self.token = token
else:
self.token = self._current_line[self._column] | [
"def",
"NextToken",
"(",
"self",
")",
":",
"self",
".",
"_previous_line",
"=",
"self",
".",
"_line",
"self",
".",
"_previous_column",
"=",
"self",
".",
"_column",
"self",
".",
"_column",
"+=",
"len",
"(",
"self",
".",
"token",
")",
"self",
".",
"_SkipWhitespace",
"(",
")",
"if",
"not",
"self",
".",
"_lines",
"and",
"len",
"(",
"self",
".",
"_current_line",
")",
"<=",
"self",
".",
"_column",
":",
"self",
".",
"token",
"=",
"''",
"return",
"match",
"=",
"self",
".",
"_TOKEN",
".",
"match",
"(",
"self",
".",
"_current_line",
",",
"self",
".",
"_column",
")",
"if",
"match",
":",
"token",
"=",
"match",
".",
"group",
"(",
"0",
")",
"self",
".",
"token",
"=",
"token",
"else",
":",
"self",
".",
"token",
"=",
"self",
".",
"_current_line",
"[",
"self",
".",
"_column",
"]"
] | https://github.com/stellar-deprecated/stellard/blob/67eabb2217bdfa9a6ea317f62338fb6bca458c90/src/protobuf/python/google/protobuf/text_format.py#L569-L586 | ||
neoml-lib/neoml | a0d370fba05269a1b2258cef126f77bbd2054a3e | NeoML/Python/neoml/Dnn/Transformer.py | python | TransformerEncoder.head_count | (self) | return self._internal.get_head_count() | Gets the head count of the attention. | Gets the head count of the attention. | [
"Gets",
"the",
"head",
"count",
"of",
"the",
"attention",
"."
] | def head_count(self):
"""Gets the head count of the attention.
"""
return self._internal.get_head_count() | [
"def",
"head_count",
"(",
"self",
")",
":",
"return",
"self",
".",
"_internal",
".",
"get_head_count",
"(",
")"
] | https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/Transformer.py#L101-L104 | |
neoml-lib/neoml | a0d370fba05269a1b2258cef126f77bbd2054a3e | NeoML/Python/neoml/Dnn/Loss.py | python | Loss.max_gradient | (self, max_value) | Sets the upper limit for the absolute value of the function gradient. | Sets the upper limit for the absolute value of the function gradient. | [
"Sets",
"the",
"upper",
"limit",
"for",
"the",
"absolute",
"value",
"of",
"the",
"function",
"gradient",
"."
] | def max_gradient(self, max_value):
"""Sets the upper limit for the absolute value of the function gradient.
"""
if max_value <= 0 :
raise ValueError('The `max_value` must be > 0.')
self._internal.set_max_gradient(max_value) | [
"def",
"max_gradient",
"(",
"self",
",",
"max_value",
")",
":",
"if",
"max_value",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"'The `max_value` must be > 0.'",
")",
"self",
".",
"_internal",
".",
"set_max_gradient",
"(",
"max_value",
")"
] | https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/Loss.py#L72-L78 | ||
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/ML/Data/DataUtils.py | python | TakeEnsemble | (vect, ensembleIds, isDataVect=False) | return vect | >>> v = [10,20,30,40,50]
>>> TakeEnsemble(v,(1,2,3))
[20, 30, 40]
>>> v = ['foo',10,20,30,40,50,1]
>>> TakeEnsemble(v,(1,2,3),isDataVect=True)
['foo', 20, 30, 40, 1] | [] | def TakeEnsemble(vect, ensembleIds, isDataVect=False):
"""
>>> v = [10,20,30,40,50]
>>> TakeEnsemble(v,(1,2,3))
[20, 30, 40]
>>> v = ['foo',10,20,30,40,50,1]
>>> TakeEnsemble(v,(1,2,3),isDataVect=True)
['foo', 20, 30, 40, 1]
"""
if isDataVect:
ensembleIds = [x + 1 for x in ensembleIds]
vect = [vect[0]] + [vect[x] for x in ensembleIds] + [vect[-1]]
else:
vect = [vect[x] for x in ensembleIds]
return vect | [
"def",
"TakeEnsemble",
"(",
"vect",
",",
"ensembleIds",
",",
"isDataVect",
"=",
"False",
")",
":",
"if",
"isDataVect",
":",
"ensembleIds",
"=",
"[",
"x",
"+",
"1",
"for",
"x",
"in",
"ensembleIds",
"]",
"vect",
"=",
"[",
"vect",
"[",
"0",
"]",
"]",
"+",
"[",
"vect",
"[",
"x",
"]",
"for",
"x",
"in",
"ensembleIds",
"]",
"+",
"[",
"vect",
"[",
"-",
"1",
"]",
"]",
"else",
":",
"vect",
"=",
"[",
"vect",
"[",
"x",
"]",
"for",
"x",
"in",
"ensembleIds",
"]",
"return",
"vect"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/ML/Data/DataUtils.py#L334-L350 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/distributed/optim/zero_redundancy_optimizer.py | python | _get_global_rank | (group: Any, rank: int) | return (rank if group is dist.group.WORLD
else dist.distributed_c10d._get_global_rank(group, rank)) | r"""
Returns the global rank for the given group and rank. | r"""
Returns the global rank for the given group and rank. | [
"r",
"Returns",
"the",
"global",
"rank",
"for",
"the",
"given",
"group",
"and",
"rank",
"."
] | def _get_global_rank(group: Any, rank: int) -> int:
r"""
Returns the global rank for the given group and rank.
"""
return (rank if group is dist.group.WORLD
else dist.distributed_c10d._get_global_rank(group, rank)) | [
"def",
"_get_global_rank",
"(",
"group",
":",
"Any",
",",
"rank",
":",
"int",
")",
"->",
"int",
":",
"return",
"(",
"rank",
"if",
"group",
"is",
"dist",
".",
"group",
".",
"WORLD",
"else",
"dist",
".",
"distributed_c10d",
".",
"_get_global_rank",
"(",
"group",
",",
"rank",
")",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/optim/zero_redundancy_optimizer.py#L101-L106 | |
ValveSoftware/source-sdk-2013 | 0d8dceea4310fde5706b3ce1c70609d72a38efdf | sp/src/thirdparty/protobuf-2.3.0/python/mox.py | python | MultipleTimesGroup.IsSatisfied | (self) | return False | Return True if all methods in this group are called at least once. | Return True if all methods in this group are called at least once. | [
"Return",
"True",
"if",
"all",
"methods",
"in",
"this",
"group",
"are",
"called",
"at",
"least",
"once",
"."
] | def IsSatisfied(self):
"""Return True if all methods in this group are called at least once."""
# NOTE(psycho): We can't use the simple set difference here because we want
# to match different parameters which are considered the same e.g. IsA(str)
# and some string. This solution is O(n^2) but n should be small.
tmp = self._methods.copy()
for called in self._methods_called:
for expected in tmp:
if called == expected:
tmp.remove(expected)
if not tmp:
return True
break
return False | [
"def",
"IsSatisfied",
"(",
"self",
")",
":",
"# NOTE(psycho): We can't use the simple set difference here because we want",
"# to match different parameters which are considered the same e.g. IsA(str)",
"# and some string. This solution is O(n^2) but n should be small.",
"tmp",
"=",
"self",
".",
"_methods",
".",
"copy",
"(",
")",
"for",
"called",
"in",
"self",
".",
"_methods_called",
":",
"for",
"expected",
"in",
"tmp",
":",
"if",
"called",
"==",
"expected",
":",
"tmp",
".",
"remove",
"(",
"expected",
")",
"if",
"not",
"tmp",
":",
"return",
"True",
"break",
"return",
"False"
] | https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/sp/src/thirdparty/protobuf-2.3.0/python/mox.py#L1318-L1331 | |
apple/foundationdb | f7118ad406f44ab7a33970fc8370647ed0085e18 | contrib/transaction_profiling_analyzer/transaction_profiling_analyzer.py | python | TransactionInfoLoader.__init__ | (self, db, full_output=True, type_filter=None, min_timestamp=None, max_timestamp=None) | Keys look like this
FF - 2 bytes \xff\x02
SSSSSSSSSS - 10 bytes Version Stamp
RRRRRRRRRRRRRRRR - 16 bytes Transaction id
NNNN - 4 Bytes Chunk number
TTTT - 4 Bytes Total number of chunks | Keys look like this
FF - 2 bytes \xff\x02
SSSSSSSSSS - 10 bytes Version Stamp
RRRRRRRRRRRRRRRR - 16 bytes Transaction id
NNNN - 4 Bytes Chunk number
TTTT - 4 Bytes Total number of chunks | [
"Keys",
"look",
"like",
"this",
"FF",
"-",
"2",
"bytes",
"\\",
"xff",
"\\",
"x02",
"SSSSSSSSSS",
"-",
"10",
"bytes",
"Version",
"Stamp",
"RRRRRRRRRRRRRRRR",
"-",
"16",
"bytes",
"Transaction",
"id",
"NNNN",
"-",
"4",
"Bytes",
"Chunk",
"number",
"TTTT",
"-",
"4",
"Bytes",
"Total",
"number",
"of",
"chunks"
] | def __init__(self, db, full_output=True, type_filter=None, min_timestamp=None, max_timestamp=None):
self.db = db
self.full_output = full_output
self.type_filter = type_filter
self.min_timestamp = min_timestamp
self.max_timestamp = max_timestamp
'''
Keys look like this
FF - 2 bytes \xff\x02
SSSSSSSSSS - 10 bytes Version Stamp
RRRRRRRRRRRRRRRR - 16 bytes Transaction id
NNNN - 4 Bytes Chunk number
TTTT - 4 Bytes Total number of chunks
'''
sample_key = "FF/fdbClientInfo/client_latency/SSSSSSSSSS/RRRRRRRRRRRRRRRR/NNNNTTTT/"
self.client_latency_start = b'\xff\x02/fdbClientInfo/client_latency/'
self.client_latency_start_key_selector = fdb.KeySelector.first_greater_than(self.client_latency_start)
self.client_latency_end_key_selector = fdb.KeySelector.first_greater_or_equal(strinc(self.client_latency_start))
self.version_stamp_start_idx = sample_key.index('S')
self.version_stamp_end_idx = sample_key.rindex('S')
self.tr_id_start_idx = sample_key.index('R')
self.tr_id_end_idx = sample_key.rindex('R')
self.chunk_num_start_idx = sample_key.index('N')
self.num_chunks_start_idx = sample_key.index('T')
self.tr_info_map = {}
self.num_chunks_stored = 0
self.num_transactions_discarded = 0 | [
"def",
"__init__",
"(",
"self",
",",
"db",
",",
"full_output",
"=",
"True",
",",
"type_filter",
"=",
"None",
",",
"min_timestamp",
"=",
"None",
",",
"max_timestamp",
"=",
"None",
")",
":",
"self",
".",
"db",
"=",
"db",
"self",
".",
"full_output",
"=",
"full_output",
"self",
".",
"type_filter",
"=",
"type_filter",
"self",
".",
"min_timestamp",
"=",
"min_timestamp",
"self",
".",
"max_timestamp",
"=",
"max_timestamp",
"sample_key",
"=",
"\"FF/fdbClientInfo/client_latency/SSSSSSSSSS/RRRRRRRRRRRRRRRR/NNNNTTTT/\"",
"self",
".",
"client_latency_start",
"=",
"b'\\xff\\x02/fdbClientInfo/client_latency/'",
"self",
".",
"client_latency_start_key_selector",
"=",
"fdb",
".",
"KeySelector",
".",
"first_greater_than",
"(",
"self",
".",
"client_latency_start",
")",
"self",
".",
"client_latency_end_key_selector",
"=",
"fdb",
".",
"KeySelector",
".",
"first_greater_or_equal",
"(",
"strinc",
"(",
"self",
".",
"client_latency_start",
")",
")",
"self",
".",
"version_stamp_start_idx",
"=",
"sample_key",
".",
"index",
"(",
"'S'",
")",
"self",
".",
"version_stamp_end_idx",
"=",
"sample_key",
".",
"rindex",
"(",
"'S'",
")",
"self",
".",
"tr_id_start_idx",
"=",
"sample_key",
".",
"index",
"(",
"'R'",
")",
"self",
".",
"tr_id_end_idx",
"=",
"sample_key",
".",
"rindex",
"(",
"'R'",
")",
"self",
".",
"chunk_num_start_idx",
"=",
"sample_key",
".",
"index",
"(",
"'N'",
")",
"self",
".",
"num_chunks_start_idx",
"=",
"sample_key",
".",
"index",
"(",
"'T'",
")",
"self",
".",
"tr_info_map",
"=",
"{",
"}",
"self",
".",
"num_chunks_stored",
"=",
"0",
"self",
".",
"num_transactions_discarded",
"=",
"0"
] | https://github.com/apple/foundationdb/blob/f7118ad406f44ab7a33970fc8370647ed0085e18/contrib/transaction_profiling_analyzer/transaction_profiling_analyzer.py#L349-L377 | ||
nodejs/nan | 8db8c8f544f2b6ce1b0859ef6ecdd0a3873a9e62 | cpplint.py | python | ProcessGlobalSuppresions | (lines) | Updates the list of global error suppressions.
Parses any lint directives in the file that have global effect.
Args:
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline. | Updates the list of global error suppressions. | [
"Updates",
"the",
"list",
"of",
"global",
"error",
"suppressions",
"."
] | def ProcessGlobalSuppresions(lines):
"""Updates the list of global error suppressions.
Parses any lint directives in the file that have global effect.
Args:
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
"""
for line in lines:
if _SEARCH_C_FILE.search(line):
for category in _DEFAULT_C_SUPPRESSED_CATEGORIES:
_global_error_suppressions[category] = True
if _SEARCH_KERNEL_FILE.search(line):
for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES:
_global_error_suppressions[category] = True | [
"def",
"ProcessGlobalSuppresions",
"(",
"lines",
")",
":",
"for",
"line",
"in",
"lines",
":",
"if",
"_SEARCH_C_FILE",
".",
"search",
"(",
"line",
")",
":",
"for",
"category",
"in",
"_DEFAULT_C_SUPPRESSED_CATEGORIES",
":",
"_global_error_suppressions",
"[",
"category",
"]",
"=",
"True",
"if",
"_SEARCH_KERNEL_FILE",
".",
"search",
"(",
"line",
")",
":",
"for",
"category",
"in",
"_DEFAULT_KERNEL_SUPPRESSED_CATEGORIES",
":",
"_global_error_suppressions",
"[",
"category",
"]",
"=",
"True"
] | https://github.com/nodejs/nan/blob/8db8c8f544f2b6ce1b0859ef6ecdd0a3873a9e62/cpplint.py#L755-L770 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | Window.Center | (*args, **kwargs) | return _core_.Window_Center(*args, **kwargs) | Center(self, int direction=BOTH)
Centers the window. The parameter specifies the direction for
centering, and may be wx.HORIZONTAL, wx.VERTICAL or wx.BOTH. It may
also include wx.CENTER_ON_SCREEN flag if you want to center the window
on the entire screen and not on its parent window. If it is a
top-level window and has no parent then it will always be centered
relative to the screen. | Center(self, int direction=BOTH) | [
"Center",
"(",
"self",
"int",
"direction",
"=",
"BOTH",
")"
] | def Center(*args, **kwargs):
"""
Center(self, int direction=BOTH)
Centers the window. The parameter specifies the direction for
centering, and may be wx.HORIZONTAL, wx.VERTICAL or wx.BOTH. It may
also include wx.CENTER_ON_SCREEN flag if you want to center the window
on the entire screen and not on its parent window. If it is a
top-level window and has no parent then it will always be centered
relative to the screen.
"""
return _core_.Window_Center(*args, **kwargs) | [
"def",
"Center",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_Center",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L9655-L9666 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/keras/python/keras/backend.py | python | cast_to_floatx | (x) | return np.asarray(x, dtype=_FLOATX) | Cast a Numpy array to the default Keras float type.
Arguments:
x: Numpy array.
Returns:
The same Numpy array, cast to its new type.
Example:
```python
>>> from keras import backend as K
>>> K.floatx()
'float32'
>>> arr = numpy.array([1.0, 2.0], dtype='float64')
>>> arr.dtype
dtype('float64')
>>> new_arr = K.cast_to_floatx(arr)
>>> new_arr
array([ 1., 2.], dtype=float32)
>>> new_arr.dtype
dtype('float32')
``` | Cast a Numpy array to the default Keras float type. | [
"Cast",
"a",
"Numpy",
"array",
"to",
"the",
"default",
"Keras",
"float",
"type",
"."
] | def cast_to_floatx(x):
"""Cast a Numpy array to the default Keras float type.
Arguments:
x: Numpy array.
Returns:
The same Numpy array, cast to its new type.
Example:
```python
>>> from keras import backend as K
>>> K.floatx()
'float32'
>>> arr = numpy.array([1.0, 2.0], dtype='float64')
>>> arr.dtype
dtype('float64')
>>> new_arr = K.cast_to_floatx(arr)
>>> new_arr
array([ 1., 2.], dtype=float32)
>>> new_arr.dtype
dtype('float32')
```
"""
return np.asarray(x, dtype=_FLOATX) | [
"def",
"cast_to_floatx",
"(",
"x",
")",
":",
"return",
"np",
".",
"asarray",
"(",
"x",
",",
"dtype",
"=",
"_FLOATX",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/backend.py#L181-L205 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/roslaunch/src/roslaunch/nodeprocess.py | python | LocalProcess.stop | (self, errors=None) | Stop the process. Record any significant error messages in the errors parameter
@param errors: error messages. stop() will record messages into this list.
@type errors: [str] | Stop the process. Record any significant error messages in the errors parameter | [
"Stop",
"the",
"process",
".",
"Record",
"any",
"significant",
"error",
"messages",
"in",
"the",
"errors",
"parameter"
] | def stop(self, errors=None):
"""
Stop the process. Record any significant error messages in the errors parameter
@param errors: error messages. stop() will record messages into this list.
@type errors: [str]
"""
if errors is None:
errors = []
super(LocalProcess, self).stop(errors)
self.lock.acquire()
try:
try:
_logger.debug("process[%s].stop() starting", self.name)
if self.popen is None:
_logger.debug("process[%s].stop(): popen is None, nothing to kill")
return
if sys.platform in ['win32']: # cygwin seems to be ok
self._stop_win32(errors)
else:
self._stop_unix(errors)
except:
#traceback.print_exc()
_logger.error("[%s] EXCEPTION %s", self.name, traceback.format_exc())
finally:
self.stopped = True
self.lock.release() | [
"def",
"stop",
"(",
"self",
",",
"errors",
"=",
"None",
")",
":",
"if",
"errors",
"is",
"None",
":",
"errors",
"=",
"[",
"]",
"super",
"(",
"LocalProcess",
",",
"self",
")",
".",
"stop",
"(",
"errors",
")",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"try",
":",
"_logger",
".",
"debug",
"(",
"\"process[%s].stop() starting\"",
",",
"self",
".",
"name",
")",
"if",
"self",
".",
"popen",
"is",
"None",
":",
"_logger",
".",
"debug",
"(",
"\"process[%s].stop(): popen is None, nothing to kill\"",
")",
"return",
"if",
"sys",
".",
"platform",
"in",
"[",
"'win32'",
"]",
":",
"# cygwin seems to be ok",
"self",
".",
"_stop_win32",
"(",
"errors",
")",
"else",
":",
"self",
".",
"_stop_unix",
"(",
"errors",
")",
"except",
":",
"#traceback.print_exc() ",
"_logger",
".",
"error",
"(",
"\"[%s] EXCEPTION %s\"",
",",
"self",
".",
"name",
",",
"traceback",
".",
"format_exc",
"(",
")",
")",
"finally",
":",
"self",
".",
"stopped",
"=",
"True",
"self",
".",
"lock",
".",
"release",
"(",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/roslaunch/src/roslaunch/nodeprocess.py#L498-L524 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/logging/__init__.py | python | LoggerAdapter.isEnabledFor | (self, level) | return self.logger.isEnabledFor(level) | See if the underlying logger is enabled for the specified level. | See if the underlying logger is enabled for the specified level. | [
"See",
"if",
"the",
"underlying",
"logger",
"is",
"enabled",
"for",
"the",
"specified",
"level",
"."
] | def isEnabledFor(self, level):
"""
See if the underlying logger is enabled for the specified level.
"""
return self.logger.isEnabledFor(level) | [
"def",
"isEnabledFor",
"(",
"self",
",",
"level",
")",
":",
"return",
"self",
".",
"logger",
".",
"isEnabledFor",
"(",
"level",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/logging/__init__.py#L1473-L1477 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/grit/grit/format/data_pack.py | python | ReadDataPack | (input_file) | return DataPackContents(resources, encoding) | Reads a data pack file and returns a dictionary. | Reads a data pack file and returns a dictionary. | [
"Reads",
"a",
"data",
"pack",
"file",
"and",
"returns",
"a",
"dictionary",
"."
] | def ReadDataPack(input_file):
"""Reads a data pack file and returns a dictionary."""
data = util.ReadFile(input_file, util.BINARY)
original_data = data
# Read the header.
version, num_entries, encoding = struct.unpack('<IIB', data[:HEADER_LENGTH])
if version != PACK_FILE_VERSION:
print 'Wrong file version in ', input_file
raise WrongFileVersion
resources = {}
if num_entries == 0:
return DataPackContents(resources, encoding)
# Read the index and data.
data = data[HEADER_LENGTH:]
kIndexEntrySize = 2 + 4 # Each entry is a uint16 and a uint32.
for _ in range(num_entries):
id, offset = struct.unpack('<HI', data[:kIndexEntrySize])
data = data[kIndexEntrySize:]
next_id, next_offset = struct.unpack('<HI', data[:kIndexEntrySize])
resources[id] = original_data[offset:next_offset]
return DataPackContents(resources, encoding) | [
"def",
"ReadDataPack",
"(",
"input_file",
")",
":",
"data",
"=",
"util",
".",
"ReadFile",
"(",
"input_file",
",",
"util",
".",
"BINARY",
")",
"original_data",
"=",
"data",
"# Read the header.",
"version",
",",
"num_entries",
",",
"encoding",
"=",
"struct",
".",
"unpack",
"(",
"'<IIB'",
",",
"data",
"[",
":",
"HEADER_LENGTH",
"]",
")",
"if",
"version",
"!=",
"PACK_FILE_VERSION",
":",
"print",
"'Wrong file version in '",
",",
"input_file",
"raise",
"WrongFileVersion",
"resources",
"=",
"{",
"}",
"if",
"num_entries",
"==",
"0",
":",
"return",
"DataPackContents",
"(",
"resources",
",",
"encoding",
")",
"# Read the index and data.",
"data",
"=",
"data",
"[",
"HEADER_LENGTH",
":",
"]",
"kIndexEntrySize",
"=",
"2",
"+",
"4",
"# Each entry is a uint16 and a uint32.",
"for",
"_",
"in",
"range",
"(",
"num_entries",
")",
":",
"id",
",",
"offset",
"=",
"struct",
".",
"unpack",
"(",
"'<HI'",
",",
"data",
"[",
":",
"kIndexEntrySize",
"]",
")",
"data",
"=",
"data",
"[",
"kIndexEntrySize",
":",
"]",
"next_id",
",",
"next_offset",
"=",
"struct",
".",
"unpack",
"(",
"'<HI'",
",",
"data",
"[",
":",
"kIndexEntrySize",
"]",
")",
"resources",
"[",
"id",
"]",
"=",
"original_data",
"[",
"offset",
":",
"next_offset",
"]",
"return",
"DataPackContents",
"(",
"resources",
",",
"encoding",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/format/data_pack.py#L51-L75 | |
msftguy/ssh-rd | a5f3a79daeac5844edebf01916c9613563f1c390 | _3rd/boost_1_48_0/tools/build/v2/build/project.py | python | ProjectRegistry.add_rule | (self, name, callable) | Makes rule 'name' available to all subsequently loaded Jamfiles.
Calling that rule wil relay to 'callable'. | Makes rule 'name' available to all subsequently loaded Jamfiles. | [
"Makes",
"rule",
"name",
"available",
"to",
"all",
"subsequently",
"loaded",
"Jamfiles",
"."
] | def add_rule(self, name, callable):
"""Makes rule 'name' available to all subsequently loaded Jamfiles.
Calling that rule wil relay to 'callable'."""
self.project_rules_.add_rule(name, callable) | [
"def",
"add_rule",
"(",
"self",
",",
"name",
",",
"callable",
")",
":",
"self",
".",
"project_rules_",
".",
"add_rule",
"(",
"name",
",",
"callable",
")"
] | https://github.com/msftguy/ssh-rd/blob/a5f3a79daeac5844edebf01916c9613563f1c390/_3rd/boost_1_48_0/tools/build/v2/build/project.py#L583-L587 | ||
nasa/trick | 7b85aa66329d62fe8816462627c09a353aac8299 | share/trick/trickops/TrickWorkflow.py | python | TrickWorkflow.__init__ | (self, project_top_level, log_dir, trick_dir, config_file, cpus=3, quiet=False) | Initialize this instance.
>>> tw = TrickWorkflow(project_top_level=this_trick, log_dir='/tmp/', trick_dir=this_trick, config_file=os.path.join(this_trick,"share/trick/trickops/tests/trick_sims.yml"))
Parameters
----------
project_top_level : str
Path to the top level of this project a.k.a root directory
log_dir : str
Path to directory where all test log output will be written
trick_dir : str
Path to root trick directory for this project
config_file : str
Path to YAML file describing this Trick Workflow
cpus : int
Maximum number of CPUs to use when running parallel jobs
quiet : bool
Flag for keeping verbose output to a minimum. Suppresses all progress bars
when true which is useful for running in a CI system where stdin isn't
available | Initialize this instance. | [
"Initialize",
"this",
"instance",
"."
] | def __init__(self, project_top_level, log_dir, trick_dir, config_file, cpus=3, quiet=False):
"""
Initialize this instance.
>>> tw = TrickWorkflow(project_top_level=this_trick, log_dir='/tmp/', trick_dir=this_trick, config_file=os.path.join(this_trick,"share/trick/trickops/tests/trick_sims.yml"))
Parameters
----------
project_top_level : str
Path to the top level of this project a.k.a root directory
log_dir : str
Path to directory where all test log output will be written
trick_dir : str
Path to root trick directory for this project
config_file : str
Path to YAML file describing this Trick Workflow
cpus : int
Maximum number of CPUs to use when running parallel jobs
quiet : bool
Flag for keeping verbose output to a minimum. Suppresses all progress bars
when true which is useful for running in a CI system where stdin isn't
available
"""
super().__init__(project_top_level=project_top_level, log_dir=log_dir, quiet=quiet)
# If not found in the config file, these defaults are used
self.defaults = {'cpus': 3, 'name': None, 'description': None,
'build_command': 'trick-CP', 'size': 2200000, 'env': None}
self.config_errors = False
self.compare_errors = False # True if comparison errors were found
self.sims = [] # list of Sim() instances, filled out from config file
self.config_file = config_file # path to yml config
self.cpus = cpus # Number of CPUs this workflow should use when running
# 'loose' or 'strict' controls if multiple input files per RUN dir are allowed in YAML config file
self.parallel_safety = 'loose'
self.config = self._read_config(self.config_file) # Contains resulting Dict parsed by yaml.load
self.trick_dir = trick_dir
self.trick_host_cpu = self.get_trick_host_cpu()
self._validate_config() | [
"def",
"__init__",
"(",
"self",
",",
"project_top_level",
",",
"log_dir",
",",
"trick_dir",
",",
"config_file",
",",
"cpus",
"=",
"3",
",",
"quiet",
"=",
"False",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"project_top_level",
"=",
"project_top_level",
",",
"log_dir",
"=",
"log_dir",
",",
"quiet",
"=",
"quiet",
")",
"# If not found in the config file, these defaults are used",
"self",
".",
"defaults",
"=",
"{",
"'cpus'",
":",
"3",
",",
"'name'",
":",
"None",
",",
"'description'",
":",
"None",
",",
"'build_command'",
":",
"'trick-CP'",
",",
"'size'",
":",
"2200000",
",",
"'env'",
":",
"None",
"}",
"self",
".",
"config_errors",
"=",
"False",
"self",
".",
"compare_errors",
"=",
"False",
"# True if comparison errors were found",
"self",
".",
"sims",
"=",
"[",
"]",
"# list of Sim() instances, filled out from config file",
"self",
".",
"config_file",
"=",
"config_file",
"# path to yml config",
"self",
".",
"cpus",
"=",
"cpus",
"# Number of CPUs this workflow should use when running",
"# 'loose' or 'strict' controls if multiple input files per RUN dir are allowed in YAML config file",
"self",
".",
"parallel_safety",
"=",
"'loose'",
"self",
".",
"config",
"=",
"self",
".",
"_read_config",
"(",
"self",
".",
"config_file",
")",
"# Contains resulting Dict parsed by yaml.load",
"self",
".",
"trick_dir",
"=",
"trick_dir",
"self",
".",
"trick_host_cpu",
"=",
"self",
".",
"get_trick_host_cpu",
"(",
")",
"self",
".",
"_validate_config",
"(",
")"
] | https://github.com/nasa/trick/blob/7b85aa66329d62fe8816462627c09a353aac8299/share/trick/trickops/TrickWorkflow.py#L79-L116 | ||
fengbingchun/NN_Test | d6305825d5273e4569ccd1eda9ffa2a9c72e18d2 | src/tiny-dnn/third_party/cpplint.py | python | CheckForMultilineCommentsAndStrings | (filename, clean_lines, linenum, error) | Logs an error if we see /* ... */ or "..." that extend past one line.
/* ... */ comments are legit inside macros, for one line.
Otherwise, we prefer // comments, so it's ok to warn about the
other. Likewise, it's ok for strings to extend across multiple
lines, as long as a line continuation character (backslash)
terminates each line. Although not currently prohibited by the C++
style guide, it's ugly and unnecessary. We don't do well with either
in this lint program, so we warn about both.
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. | Logs an error if we see /* ... */ or "..." that extend past one line. | [
"Logs",
"an",
"error",
"if",
"we",
"see",
"/",
"*",
"...",
"*",
"/",
"or",
"...",
"that",
"extend",
"past",
"one",
"line",
"."
] | def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
"""Logs an error if we see /* ... */ or "..." that extend past one line.
/* ... */ comments are legit inside macros, for one line.
Otherwise, we prefer // comments, so it's ok to warn about the
other. Likewise, it's ok for strings to extend across multiple
lines, as long as a line continuation character (backslash)
terminates each line. Although not currently prohibited by the C++
style guide, it's ugly and unnecessary. We don't do well with either
in this lint program, so we warn about both.
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]
# Remove all \\ (escaped backslashes) from the line. They are OK, and the
# second (escaped) slash may trigger later \" detection erroneously.
line = line.replace('\\\\', '')
if line.count('/*') > line.count('*/'):
error(filename, linenum, 'readability/multiline_comment', 5,
'Complex multi-line /*...*/-style comment found. '
'Lint may give bogus warnings. '
'Consider replacing these with //-style comments, '
'with #if 0...#endif, '
'or with more clearly structured multi-line comments.')
if (line.count('"') - line.count('\\"')) % 2:
error(filename, linenum, 'readability/multiline_string', 5,
'Multi-line string ("...") found. This lint script doesn\'t '
'do well with such strings, and may give bogus warnings. '
'Use C++11 raw strings or concatenation instead.') | [
"def",
"CheckForMultilineCommentsAndStrings",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# Remove all \\\\ (escaped backslashes) from the line. They are OK, and the",
"# second (escaped) slash may trigger later \\\" detection erroneously.",
"line",
"=",
"line",
".",
"replace",
"(",
"'\\\\\\\\'",
",",
"''",
")",
"if",
"line",
".",
"count",
"(",
"'/*'",
")",
">",
"line",
".",
"count",
"(",
"'*/'",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/multiline_comment'",
",",
"5",
",",
"'Complex multi-line /*...*/-style comment found. '",
"'Lint may give bogus warnings. '",
"'Consider replacing these with //-style comments, '",
"'with #if 0...#endif, '",
"'or with more clearly structured multi-line comments.'",
")",
"if",
"(",
"line",
".",
"count",
"(",
"'\"'",
")",
"-",
"line",
".",
"count",
"(",
"'\\\\\"'",
")",
")",
"%",
"2",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/multiline_string'",
",",
"5",
",",
"'Multi-line string (\"...\") found. This lint script doesn\\'t '",
"'do well with such strings, and may give bogus warnings. '",
"'Use C++11 raw strings or concatenation instead.'",
")"
] | https://github.com/fengbingchun/NN_Test/blob/d6305825d5273e4569ccd1eda9ffa2a9c72e18d2/src/tiny-dnn/third_party/cpplint.py#L2159-L2194 | ||
apache/incubator-weex | 5c25f0b59f7ac90703c363e7261f60bd06356dbe | weex_core/tools/cpplint.py | python | _IncludeState.IsInAlphabeticalOrder | (self, clean_lines, linenum, header_path) | return True | Check if a header is in alphabetical order with the previous header.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
header_path: Canonicalized header to be checked.
Returns:
Returns true if the header is in alphabetical order. | Check if a header is in alphabetical order with the previous header. | [
"Check",
"if",
"a",
"header",
"is",
"in",
"alphabetical",
"order",
"with",
"the",
"previous",
"header",
"."
] | def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):
"""Check if a header is in alphabetical order with the previous header.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
header_path: Canonicalized header to be checked.
Returns:
Returns true if the header is in alphabetical order.
"""
# If previous section is different from current section, _last_header will
# be reset to empty string, so it's always less than current header.
#
# If previous line was a blank line, assume that the headers are
# intentionally sorted the way they are.
if (self._last_header > header_path and
Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])):
return False
return True | [
"def",
"IsInAlphabeticalOrder",
"(",
"self",
",",
"clean_lines",
",",
"linenum",
",",
"header_path",
")",
":",
"# If previous section is different from current section, _last_header will",
"# be reset to empty string, so it's always less than current header.",
"#",
"# If previous line was a blank line, assume that the headers are",
"# intentionally sorted the way they are.",
"if",
"(",
"self",
".",
"_last_header",
">",
"header_path",
"and",
"Match",
"(",
"r'^\\s*#\\s*include\\b'",
",",
"clean_lines",
".",
"elided",
"[",
"linenum",
"-",
"1",
"]",
")",
")",
":",
"return",
"False",
"return",
"True"
] | https://github.com/apache/incubator-weex/blob/5c25f0b59f7ac90703c363e7261f60bd06356dbe/weex_core/tools/cpplint.py#L787-L806 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/signal/bsplines.py | python | cspline1d_eval | (cj, newx, dx=1.0, x0=0) | return res | Evaluate a spline at the new set of points.
`dx` is the old sample-spacing while `x0` was the old origin. In
other-words the old-sample points (knot-points) for which the `cj`
represent spline coefficients were at equally-spaced points of:
oldx = x0 + j*dx j=0...N-1, with N=len(cj)
Edges are handled using mirror-symmetric boundary conditions. | Evaluate a spline at the new set of points. | [
"Evaluate",
"a",
"spline",
"at",
"the",
"new",
"set",
"of",
"points",
"."
] | def cspline1d_eval(cj, newx, dx=1.0, x0=0):
"""Evaluate a spline at the new set of points.
`dx` is the old sample-spacing while `x0` was the old origin. In
other-words the old-sample points (knot-points) for which the `cj`
represent spline coefficients were at equally-spaced points of:
oldx = x0 + j*dx j=0...N-1, with N=len(cj)
Edges are handled using mirror-symmetric boundary conditions.
"""
newx = (asarray(newx) - x0) / float(dx)
res = zeros_like(newx)
if res.size == 0:
return res
N = len(cj)
cond1 = newx < 0
cond2 = newx > (N - 1)
cond3 = ~(cond1 | cond2)
# handle general mirror-symmetry
res[cond1] = cspline1d_eval(cj, -newx[cond1])
res[cond2] = cspline1d_eval(cj, 2 * (N - 1) - newx[cond2])
newx = newx[cond3]
if newx.size == 0:
return res
result = zeros_like(newx)
jlower = floor(newx - 2).astype(int) + 1
for i in range(4):
thisj = jlower + i
indj = thisj.clip(0, N - 1) # handle edge cases
result += cj[indj] * cubic(newx - thisj)
res[cond3] = result
return res | [
"def",
"cspline1d_eval",
"(",
"cj",
",",
"newx",
",",
"dx",
"=",
"1.0",
",",
"x0",
"=",
"0",
")",
":",
"newx",
"=",
"(",
"asarray",
"(",
"newx",
")",
"-",
"x0",
")",
"/",
"float",
"(",
"dx",
")",
"res",
"=",
"zeros_like",
"(",
"newx",
")",
"if",
"res",
".",
"size",
"==",
"0",
":",
"return",
"res",
"N",
"=",
"len",
"(",
"cj",
")",
"cond1",
"=",
"newx",
"<",
"0",
"cond2",
"=",
"newx",
">",
"(",
"N",
"-",
"1",
")",
"cond3",
"=",
"~",
"(",
"cond1",
"|",
"cond2",
")",
"# handle general mirror-symmetry",
"res",
"[",
"cond1",
"]",
"=",
"cspline1d_eval",
"(",
"cj",
",",
"-",
"newx",
"[",
"cond1",
"]",
")",
"res",
"[",
"cond2",
"]",
"=",
"cspline1d_eval",
"(",
"cj",
",",
"2",
"*",
"(",
"N",
"-",
"1",
")",
"-",
"newx",
"[",
"cond2",
"]",
")",
"newx",
"=",
"newx",
"[",
"cond3",
"]",
"if",
"newx",
".",
"size",
"==",
"0",
":",
"return",
"res",
"result",
"=",
"zeros_like",
"(",
"newx",
")",
"jlower",
"=",
"floor",
"(",
"newx",
"-",
"2",
")",
".",
"astype",
"(",
"int",
")",
"+",
"1",
"for",
"i",
"in",
"range",
"(",
"4",
")",
":",
"thisj",
"=",
"jlower",
"+",
"i",
"indj",
"=",
"thisj",
".",
"clip",
"(",
"0",
",",
"N",
"-",
"1",
")",
"# handle edge cases",
"result",
"+=",
"cj",
"[",
"indj",
"]",
"*",
"cubic",
"(",
"newx",
"-",
"thisj",
")",
"res",
"[",
"cond3",
"]",
"=",
"result",
"return",
"res"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/signal/bsplines.py#L312-L345 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/image_ops.py | python | _ImageEncodeShape | (op) | return [tensor_shape.scalar()] | Shape function for image encoding ops. | Shape function for image encoding ops. | [
"Shape",
"function",
"for",
"image",
"encoding",
"ops",
"."
] | def _ImageEncodeShape(op):
"""Shape function for image encoding ops."""
unused_input_shape = op.inputs[0].get_shape().with_rank(3)
return [tensor_shape.scalar()] | [
"def",
"_ImageEncodeShape",
"(",
"op",
")",
":",
"unused_input_shape",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
".",
"with_rank",
"(",
"3",
")",
"return",
"[",
"tensor_shape",
".",
"scalar",
"(",
")",
"]"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/image_ops.py#L1042-L1045 | |
scp-fs2open/fs2open.github.com | b6474f795cfd9f5024f180a26771b056c404ac3d | ci/linux/clang-tidy-diff.py | python | merge_replacement_files | (tmpdir, mergefile) | Merge all replacement files in a directory into a single file | Merge all replacement files in a directory into a single file | [
"Merge",
"all",
"replacement",
"files",
"in",
"a",
"directory",
"into",
"a",
"single",
"file"
] | def merge_replacement_files(tmpdir, mergefile):
"""Merge all replacement files in a directory into a single file"""
# The fixes suggested by clang-tidy >= 4.0.0 are given under
# the top level key 'Diagnostics' in the output yaml files
mergekey = "Diagnostics"
merged = []
for replacefile in glob.iglob(os.path.join(tmpdir, '*.yaml')):
content = yaml.safe_load(open(replacefile, 'r'))
if not content:
continue # Skip empty files.
merged.extend(content.get(mergekey, []))
if merged:
# MainSourceFile: The key is required by the definition inside
# include/clang/Tooling/ReplacementsYaml.h, but the value
# is actually never used inside clang-apply-replacements,
# so we set it to '' here.
output = { 'MainSourceFile': '', mergekey: merged }
with open(mergefile, 'w') as out:
yaml.safe_dump(output, out)
else:
# Empty the file:
open(mergefile, 'w').close() | [
"def",
"merge_replacement_files",
"(",
"tmpdir",
",",
"mergefile",
")",
":",
"# The fixes suggested by clang-tidy >= 4.0.0 are given under",
"# the top level key 'Diagnostics' in the output yaml files",
"mergekey",
"=",
"\"Diagnostics\"",
"merged",
"=",
"[",
"]",
"for",
"replacefile",
"in",
"glob",
".",
"iglob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"tmpdir",
",",
"'*.yaml'",
")",
")",
":",
"content",
"=",
"yaml",
".",
"safe_load",
"(",
"open",
"(",
"replacefile",
",",
"'r'",
")",
")",
"if",
"not",
"content",
":",
"continue",
"# Skip empty files.",
"merged",
".",
"extend",
"(",
"content",
".",
"get",
"(",
"mergekey",
",",
"[",
"]",
")",
")",
"if",
"merged",
":",
"# MainSourceFile: The key is required by the definition inside",
"# include/clang/Tooling/ReplacementsYaml.h, but the value",
"# is actually never used inside clang-apply-replacements,",
"# so we set it to '' here.",
"output",
"=",
"{",
"'MainSourceFile'",
":",
"''",
",",
"mergekey",
":",
"merged",
"}",
"with",
"open",
"(",
"mergefile",
",",
"'w'",
")",
"as",
"out",
":",
"yaml",
".",
"safe_dump",
"(",
"output",
",",
"out",
")",
"else",
":",
"# Empty the file:",
"open",
"(",
"mergefile",
",",
"'w'",
")",
".",
"close",
"(",
")"
] | https://github.com/scp-fs2open/fs2open.github.com/blob/b6474f795cfd9f5024f180a26771b056c404ac3d/ci/linux/clang-tidy-diff.py#L92-L114 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib2to3/refactor.py | python | RefactoringTool.refactor_tree | (self, tree, name) | return tree.was_changed | Refactors a parse tree (modifying the tree in place).
For compatible patterns the bottom matcher module is
used. Otherwise the tree is traversed node-to-node for
matches.
Args:
tree: a pytree.Node instance representing the root of the tree
to be refactored.
name: a human-readable name for this tree.
Returns:
True if the tree was modified, False otherwise. | Refactors a parse tree (modifying the tree in place). | [
"Refactors",
"a",
"parse",
"tree",
"(",
"modifying",
"the",
"tree",
"in",
"place",
")",
"."
] | def refactor_tree(self, tree, name):
"""Refactors a parse tree (modifying the tree in place).
For compatible patterns the bottom matcher module is
used. Otherwise the tree is traversed node-to-node for
matches.
Args:
tree: a pytree.Node instance representing the root of the tree
to be refactored.
name: a human-readable name for this tree.
Returns:
True if the tree was modified, False otherwise.
"""
for fixer in chain(self.pre_order, self.post_order):
fixer.start_tree(tree, name)
#use traditional matching for the incompatible fixers
self.traverse_by(self.bmi_pre_order_heads, tree.pre_order())
self.traverse_by(self.bmi_post_order_heads, tree.post_order())
# obtain a set of candidate nodes
match_set = self.BM.run(tree.leaves())
while any(match_set.values()):
for fixer in self.BM.fixers:
if fixer in match_set and match_set[fixer]:
#sort by depth; apply fixers from bottom(of the AST) to top
match_set[fixer].sort(key=pytree.Base.depth, reverse=True)
if fixer.keep_line_order:
#some fixers(eg fix_imports) must be applied
#with the original file's line order
match_set[fixer].sort(key=pytree.Base.get_lineno)
for node in list(match_set[fixer]):
if node in match_set[fixer]:
match_set[fixer].remove(node)
try:
find_root(node)
except ValueError:
# this node has been cut off from a
# previous transformation ; skip
continue
if node.fixers_applied and fixer in node.fixers_applied:
# do not apply the same fixer again
continue
results = fixer.match(node)
if results:
new = fixer.transform(node, results)
if new is not None:
node.replace(new)
#new.fixers_applied.append(fixer)
for node in new.post_order():
# do not apply the fixer again to
# this or any subnode
if not node.fixers_applied:
node.fixers_applied = []
node.fixers_applied.append(fixer)
# update the original match set for
# the added code
new_matches = self.BM.run(new.leaves())
for fxr in new_matches:
if not fxr in match_set:
match_set[fxr]=[]
match_set[fxr].extend(new_matches[fxr])
for fixer in chain(self.pre_order, self.post_order):
fixer.finish_tree(tree, name)
return tree.was_changed | [
"def",
"refactor_tree",
"(",
"self",
",",
"tree",
",",
"name",
")",
":",
"for",
"fixer",
"in",
"chain",
"(",
"self",
".",
"pre_order",
",",
"self",
".",
"post_order",
")",
":",
"fixer",
".",
"start_tree",
"(",
"tree",
",",
"name",
")",
"#use traditional matching for the incompatible fixers",
"self",
".",
"traverse_by",
"(",
"self",
".",
"bmi_pre_order_heads",
",",
"tree",
".",
"pre_order",
"(",
")",
")",
"self",
".",
"traverse_by",
"(",
"self",
".",
"bmi_post_order_heads",
",",
"tree",
".",
"post_order",
"(",
")",
")",
"# obtain a set of candidate nodes",
"match_set",
"=",
"self",
".",
"BM",
".",
"run",
"(",
"tree",
".",
"leaves",
"(",
")",
")",
"while",
"any",
"(",
"match_set",
".",
"values",
"(",
")",
")",
":",
"for",
"fixer",
"in",
"self",
".",
"BM",
".",
"fixers",
":",
"if",
"fixer",
"in",
"match_set",
"and",
"match_set",
"[",
"fixer",
"]",
":",
"#sort by depth; apply fixers from bottom(of the AST) to top",
"match_set",
"[",
"fixer",
"]",
".",
"sort",
"(",
"key",
"=",
"pytree",
".",
"Base",
".",
"depth",
",",
"reverse",
"=",
"True",
")",
"if",
"fixer",
".",
"keep_line_order",
":",
"#some fixers(eg fix_imports) must be applied",
"#with the original file's line order",
"match_set",
"[",
"fixer",
"]",
".",
"sort",
"(",
"key",
"=",
"pytree",
".",
"Base",
".",
"get_lineno",
")",
"for",
"node",
"in",
"list",
"(",
"match_set",
"[",
"fixer",
"]",
")",
":",
"if",
"node",
"in",
"match_set",
"[",
"fixer",
"]",
":",
"match_set",
"[",
"fixer",
"]",
".",
"remove",
"(",
"node",
")",
"try",
":",
"find_root",
"(",
"node",
")",
"except",
"ValueError",
":",
"# this node has been cut off from a",
"# previous transformation ; skip",
"continue",
"if",
"node",
".",
"fixers_applied",
"and",
"fixer",
"in",
"node",
".",
"fixers_applied",
":",
"# do not apply the same fixer again",
"continue",
"results",
"=",
"fixer",
".",
"match",
"(",
"node",
")",
"if",
"results",
":",
"new",
"=",
"fixer",
".",
"transform",
"(",
"node",
",",
"results",
")",
"if",
"new",
"is",
"not",
"None",
":",
"node",
".",
"replace",
"(",
"new",
")",
"#new.fixers_applied.append(fixer)",
"for",
"node",
"in",
"new",
".",
"post_order",
"(",
")",
":",
"# do not apply the fixer again to",
"# this or any subnode",
"if",
"not",
"node",
".",
"fixers_applied",
":",
"node",
".",
"fixers_applied",
"=",
"[",
"]",
"node",
".",
"fixers_applied",
".",
"append",
"(",
"fixer",
")",
"# update the original match set for",
"# the added code",
"new_matches",
"=",
"self",
".",
"BM",
".",
"run",
"(",
"new",
".",
"leaves",
"(",
")",
")",
"for",
"fxr",
"in",
"new_matches",
":",
"if",
"not",
"fxr",
"in",
"match_set",
":",
"match_set",
"[",
"fxr",
"]",
"=",
"[",
"]",
"match_set",
"[",
"fxr",
"]",
".",
"extend",
"(",
"new_matches",
"[",
"fxr",
"]",
")",
"for",
"fixer",
"in",
"chain",
"(",
"self",
".",
"pre_order",
",",
"self",
".",
"post_order",
")",
":",
"fixer",
".",
"finish_tree",
"(",
"tree",
",",
"name",
")",
"return",
"tree",
".",
"was_changed"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib2to3/refactor.py#L405-L482 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/numpy/random.py | python | logistic | (loc=0.0, scale=1.0, size=None, device=None, out=None) | return _mx_nd_np.random.logistic(loc, scale, size, device, out) | r"""Draw samples from a logistic distribution.
Samples are drawn from a logistic distribution with specified
parameters, loc (location or mean, also median), and scale (>0).
Parameters
----------
loc : float or array_like of floats, optional
Parameter of the distribution. Default is 0.
scale : float or array_like of floats, optional
Parameter of the distribution. Must be non-negative.
Default is 1.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``loc`` and ``scale`` are both scalars.
Otherwise, ``np.broadcast(loc, scale).size`` samples are drawn.
device : Device, optional
Device context of output, default is current device.
out : ``ndarray``, optional
Store output to an existing ``ndarray``.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized logistic distribution.
Examples
--------
Draw samples from the distribution:
>>> loc, scale = 10, 1
>>> s = np.random.logistic(loc, scale, 10000)
>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, bins=50)
# plot against distribution
>>> def logist(x, loc, scale):
... return np.exp((loc-x)/scale)/(scale*(1+np.exp((loc-x)/scale))**2)
>>> lgst_val = logist(bins, loc, scale)
>>> plt.plot(bins, lgst_val * count.max() / lgst_val.max())
>>> plt.show() | r"""Draw samples from a logistic distribution. | [
"r",
"Draw",
"samples",
"from",
"a",
"logistic",
"distribution",
"."
] | def logistic(loc=0.0, scale=1.0, size=None, device=None, out=None):
r"""Draw samples from a logistic distribution.
Samples are drawn from a logistic distribution with specified
parameters, loc (location or mean, also median), and scale (>0).
Parameters
----------
loc : float or array_like of floats, optional
Parameter of the distribution. Default is 0.
scale : float or array_like of floats, optional
Parameter of the distribution. Must be non-negative.
Default is 1.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``loc`` and ``scale`` are both scalars.
Otherwise, ``np.broadcast(loc, scale).size`` samples are drawn.
device : Device, optional
Device context of output, default is current device.
out : ``ndarray``, optional
Store output to an existing ``ndarray``.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized logistic distribution.
Examples
--------
Draw samples from the distribution:
>>> loc, scale = 10, 1
>>> s = np.random.logistic(loc, scale, 10000)
>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, bins=50)
# plot against distribution
>>> def logist(x, loc, scale):
... return np.exp((loc-x)/scale)/(scale*(1+np.exp((loc-x)/scale))**2)
>>> lgst_val = logist(bins, loc, scale)
>>> plt.plot(bins, lgst_val * count.max() / lgst_val.max())
>>> plt.show()
"""
return _mx_nd_np.random.logistic(loc, scale, size, device, out) | [
"def",
"logistic",
"(",
"loc",
"=",
"0.0",
",",
"scale",
"=",
"1.0",
",",
"size",
"=",
"None",
",",
"device",
"=",
"None",
",",
"out",
"=",
"None",
")",
":",
"return",
"_mx_nd_np",
".",
"random",
".",
"logistic",
"(",
"loc",
",",
"scale",
",",
"size",
",",
"device",
",",
"out",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/random.py#L284-L326 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/rosdep2/lookup.py | python | RosdepLookup.get_rosdep_view_for_resource | (self, resource_name, verbose=False) | return self.get_rosdep_view(view_key, verbose=verbose) | Get a :class:`RosdepView` for a specific ROS resource *resource_name*.
Views can be queries to resolve rosdep keys to
definitions.
:param resource_name: Name of ROS resource (e.g. stack,
package) to create view for, ``str``.
:returns: :class:`RosdepView` for specific ROS resource
*resource_name*, or ``None`` if no view is associated with this resource.
:raises: :exc:`RosdepConflict` if view cannot be created due
to conflict rosdep definitions.
:raises: :exc:`rospkg.ResourceNotFound` if *view_key* cannot be located
:raises: :exc:`RosdepInternalError` | Get a :class:`RosdepView` for a specific ROS resource *resource_name*.
Views can be queries to resolve rosdep keys to
definitions. | [
"Get",
"a",
":",
"class",
":",
"RosdepView",
"for",
"a",
"specific",
"ROS",
"resource",
"*",
"resource_name",
"*",
".",
"Views",
"can",
"be",
"queries",
"to",
"resolve",
"rosdep",
"keys",
"to",
"definitions",
"."
] | def get_rosdep_view_for_resource(self, resource_name, verbose=False):
"""
Get a :class:`RosdepView` for a specific ROS resource *resource_name*.
Views can be queries to resolve rosdep keys to
definitions.
:param resource_name: Name of ROS resource (e.g. stack,
package) to create view for, ``str``.
:returns: :class:`RosdepView` for specific ROS resource
*resource_name*, or ``None`` if no view is associated with this resource.
:raises: :exc:`RosdepConflict` if view cannot be created due
to conflict rosdep definitions.
:raises: :exc:`rospkg.ResourceNotFound` if *view_key* cannot be located
:raises: :exc:`RosdepInternalError`
"""
view_key = self.loader.get_view_key(resource_name)
if not view_key:
#NOTE: this may not be the right behavior and this happens
#for packages that are not in a stack.
return None
return self.get_rosdep_view(view_key, verbose=verbose) | [
"def",
"get_rosdep_view_for_resource",
"(",
"self",
",",
"resource_name",
",",
"verbose",
"=",
"False",
")",
":",
"view_key",
"=",
"self",
".",
"loader",
".",
"get_view_key",
"(",
"resource_name",
")",
"if",
"not",
"view_key",
":",
"#NOTE: this may not be the right behavior and this happens",
"#for packages that are not in a stack.",
"return",
"None",
"return",
"self",
".",
"get_rosdep_view",
"(",
"view_key",
",",
"verbose",
"=",
"verbose",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/rosdep2/lookup.py#L555-L577 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/lite/python/lite.py | python | TFLiteConverterBase._optimize_tflite_model | (self, model, quant_mode, quant_io=True) | return model | Apply optimizations on a TFLite model. | Apply optimizations on a TFLite model. | [
"Apply",
"optimizations",
"on",
"a",
"TFLite",
"model",
"."
] | def _optimize_tflite_model(self, model, quant_mode, quant_io=True):
"""Apply optimizations on a TFLite model."""
if quant_mode.is_integer_quantization():
in_type, out_type = self.inference_input_type, self.inference_output_type
if quant_mode.is_post_training_integer_quantization():
q_in_type = in_type if in_type and quant_io else _dtypes.float32
q_out_type = out_type if out_type and quant_io else _dtypes.float32
q_activations_type = quant_mode.activations_type()
q_bias_type = quant_mode.bias_type()
q_allow_float = quant_mode.is_allow_float()
model = self._quantize(model, q_in_type, q_out_type, q_activations_type,
q_bias_type, q_allow_float)
m_in_type = in_type if in_type else _dtypes.float32
m_out_type = out_type if out_type else _dtypes.float32
# Skip updating model io types if MLIR quantizer already takes care of it
if not (quant_mode.is_post_training_integer_quantization() and
self.experimental_new_quantizer and quant_io and
(m_in_type in [_dtypes.int8, _dtypes.uint8, _dtypes.float32]) and
(m_out_type in [_dtypes.int8, _dtypes.uint8, _dtypes.float32])):
model = _modify_model_io_type(model, m_in_type, m_out_type)
if self._sparsify_model():
model = _mlir_sparsify(model)
try:
model = _deduplicate_readonly_buffers(model)
except Exception: # pylint: disable=broad-except
# Skip buffer deduplication when flatbuffer library is not ready to be
# utilized.
logging.warning(
"Buffer deduplication procedure will be skipped when flatbuffer "
"library is not properly loaded")
return model | [
"def",
"_optimize_tflite_model",
"(",
"self",
",",
"model",
",",
"quant_mode",
",",
"quant_io",
"=",
"True",
")",
":",
"if",
"quant_mode",
".",
"is_integer_quantization",
"(",
")",
":",
"in_type",
",",
"out_type",
"=",
"self",
".",
"inference_input_type",
",",
"self",
".",
"inference_output_type",
"if",
"quant_mode",
".",
"is_post_training_integer_quantization",
"(",
")",
":",
"q_in_type",
"=",
"in_type",
"if",
"in_type",
"and",
"quant_io",
"else",
"_dtypes",
".",
"float32",
"q_out_type",
"=",
"out_type",
"if",
"out_type",
"and",
"quant_io",
"else",
"_dtypes",
".",
"float32",
"q_activations_type",
"=",
"quant_mode",
".",
"activations_type",
"(",
")",
"q_bias_type",
"=",
"quant_mode",
".",
"bias_type",
"(",
")",
"q_allow_float",
"=",
"quant_mode",
".",
"is_allow_float",
"(",
")",
"model",
"=",
"self",
".",
"_quantize",
"(",
"model",
",",
"q_in_type",
",",
"q_out_type",
",",
"q_activations_type",
",",
"q_bias_type",
",",
"q_allow_float",
")",
"m_in_type",
"=",
"in_type",
"if",
"in_type",
"else",
"_dtypes",
".",
"float32",
"m_out_type",
"=",
"out_type",
"if",
"out_type",
"else",
"_dtypes",
".",
"float32",
"# Skip updating model io types if MLIR quantizer already takes care of it",
"if",
"not",
"(",
"quant_mode",
".",
"is_post_training_integer_quantization",
"(",
")",
"and",
"self",
".",
"experimental_new_quantizer",
"and",
"quant_io",
"and",
"(",
"m_in_type",
"in",
"[",
"_dtypes",
".",
"int8",
",",
"_dtypes",
".",
"uint8",
",",
"_dtypes",
".",
"float32",
"]",
")",
"and",
"(",
"m_out_type",
"in",
"[",
"_dtypes",
".",
"int8",
",",
"_dtypes",
".",
"uint8",
",",
"_dtypes",
".",
"float32",
"]",
")",
")",
":",
"model",
"=",
"_modify_model_io_type",
"(",
"model",
",",
"m_in_type",
",",
"m_out_type",
")",
"if",
"self",
".",
"_sparsify_model",
"(",
")",
":",
"model",
"=",
"_mlir_sparsify",
"(",
"model",
")",
"try",
":",
"model",
"=",
"_deduplicate_readonly_buffers",
"(",
"model",
")",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"# Skip buffer deduplication when flatbuffer library is not ready to be",
"# utilized.",
"logging",
".",
"warning",
"(",
"\"Buffer deduplication procedure will be skipped when flatbuffer \"",
"\"library is not properly loaded\"",
")",
"return",
"model"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/lite/python/lite.py#L847-L883 | |
AojunZhou/Incremental-Network-Quantization | c7f6a609d5817d8424ce224209cf4c50f1e4de50 | python/caffe/detector.py | python | Detector.crop | (self, im, window) | return crop | Crop a window from the image for detection. Include surrounding context
according to the `context_pad` configuration.
Parameters
----------
im: H x W x K image ndarray to crop.
window: bounding box coordinates as ymin, xmin, ymax, xmax.
Returns
-------
crop: cropped window. | Crop a window from the image for detection. Include surrounding context
according to the `context_pad` configuration. | [
"Crop",
"a",
"window",
"from",
"the",
"image",
"for",
"detection",
".",
"Include",
"surrounding",
"context",
"according",
"to",
"the",
"context_pad",
"configuration",
"."
] | def crop(self, im, window):
"""
Crop a window from the image for detection. Include surrounding context
according to the `context_pad` configuration.
Parameters
----------
im: H x W x K image ndarray to crop.
window: bounding box coordinates as ymin, xmin, ymax, xmax.
Returns
-------
crop: cropped window.
"""
# Crop window from the image.
crop = im[window[0]:window[2], window[1]:window[3]]
if self.context_pad:
box = window.copy()
crop_size = self.blobs[self.inputs[0]].width # assumes square
scale = crop_size / (1. * crop_size - self.context_pad * 2)
# Crop a box + surrounding context.
half_h = (box[2] - box[0] + 1) / 2.
half_w = (box[3] - box[1] + 1) / 2.
center = (box[0] + half_h, box[1] + half_w)
scaled_dims = scale * np.array((-half_h, -half_w, half_h, half_w))
box = np.round(np.tile(center, 2) + scaled_dims)
full_h = box[2] - box[0] + 1
full_w = box[3] - box[1] + 1
scale_h = crop_size / full_h
scale_w = crop_size / full_w
pad_y = round(max(0, -box[0]) * scale_h) # amount out-of-bounds
pad_x = round(max(0, -box[1]) * scale_w)
# Clip box to image dimensions.
im_h, im_w = im.shape[:2]
box = np.clip(box, 0., [im_h, im_w, im_h, im_w])
clip_h = box[2] - box[0] + 1
clip_w = box[3] - box[1] + 1
assert(clip_h > 0 and clip_w > 0)
crop_h = round(clip_h * scale_h)
crop_w = round(clip_w * scale_w)
if pad_y + crop_h > crop_size:
crop_h = crop_size - pad_y
if pad_x + crop_w > crop_size:
crop_w = crop_size - pad_x
# collect with context padding and place in input
# with mean padding
context_crop = im[box[0]:box[2], box[1]:box[3]]
context_crop = caffe.io.resize_image(context_crop, (crop_h, crop_w))
crop = np.ones(self.crop_dims, dtype=np.float32) * self.crop_mean
crop[pad_y:(pad_y + crop_h), pad_x:(pad_x + crop_w)] = context_crop
return crop | [
"def",
"crop",
"(",
"self",
",",
"im",
",",
"window",
")",
":",
"# Crop window from the image.",
"crop",
"=",
"im",
"[",
"window",
"[",
"0",
"]",
":",
"window",
"[",
"2",
"]",
",",
"window",
"[",
"1",
"]",
":",
"window",
"[",
"3",
"]",
"]",
"if",
"self",
".",
"context_pad",
":",
"box",
"=",
"window",
".",
"copy",
"(",
")",
"crop_size",
"=",
"self",
".",
"blobs",
"[",
"self",
".",
"inputs",
"[",
"0",
"]",
"]",
".",
"width",
"# assumes square",
"scale",
"=",
"crop_size",
"/",
"(",
"1.",
"*",
"crop_size",
"-",
"self",
".",
"context_pad",
"*",
"2",
")",
"# Crop a box + surrounding context.",
"half_h",
"=",
"(",
"box",
"[",
"2",
"]",
"-",
"box",
"[",
"0",
"]",
"+",
"1",
")",
"/",
"2.",
"half_w",
"=",
"(",
"box",
"[",
"3",
"]",
"-",
"box",
"[",
"1",
"]",
"+",
"1",
")",
"/",
"2.",
"center",
"=",
"(",
"box",
"[",
"0",
"]",
"+",
"half_h",
",",
"box",
"[",
"1",
"]",
"+",
"half_w",
")",
"scaled_dims",
"=",
"scale",
"*",
"np",
".",
"array",
"(",
"(",
"-",
"half_h",
",",
"-",
"half_w",
",",
"half_h",
",",
"half_w",
")",
")",
"box",
"=",
"np",
".",
"round",
"(",
"np",
".",
"tile",
"(",
"center",
",",
"2",
")",
"+",
"scaled_dims",
")",
"full_h",
"=",
"box",
"[",
"2",
"]",
"-",
"box",
"[",
"0",
"]",
"+",
"1",
"full_w",
"=",
"box",
"[",
"3",
"]",
"-",
"box",
"[",
"1",
"]",
"+",
"1",
"scale_h",
"=",
"crop_size",
"/",
"full_h",
"scale_w",
"=",
"crop_size",
"/",
"full_w",
"pad_y",
"=",
"round",
"(",
"max",
"(",
"0",
",",
"-",
"box",
"[",
"0",
"]",
")",
"*",
"scale_h",
")",
"# amount out-of-bounds",
"pad_x",
"=",
"round",
"(",
"max",
"(",
"0",
",",
"-",
"box",
"[",
"1",
"]",
")",
"*",
"scale_w",
")",
"# Clip box to image dimensions.",
"im_h",
",",
"im_w",
"=",
"im",
".",
"shape",
"[",
":",
"2",
"]",
"box",
"=",
"np",
".",
"clip",
"(",
"box",
",",
"0.",
",",
"[",
"im_h",
",",
"im_w",
",",
"im_h",
",",
"im_w",
"]",
")",
"clip_h",
"=",
"box",
"[",
"2",
"]",
"-",
"box",
"[",
"0",
"]",
"+",
"1",
"clip_w",
"=",
"box",
"[",
"3",
"]",
"-",
"box",
"[",
"1",
"]",
"+",
"1",
"assert",
"(",
"clip_h",
">",
"0",
"and",
"clip_w",
">",
"0",
")",
"crop_h",
"=",
"round",
"(",
"clip_h",
"*",
"scale_h",
")",
"crop_w",
"=",
"round",
"(",
"clip_w",
"*",
"scale_w",
")",
"if",
"pad_y",
"+",
"crop_h",
">",
"crop_size",
":",
"crop_h",
"=",
"crop_size",
"-",
"pad_y",
"if",
"pad_x",
"+",
"crop_w",
">",
"crop_size",
":",
"crop_w",
"=",
"crop_size",
"-",
"pad_x",
"# collect with context padding and place in input",
"# with mean padding",
"context_crop",
"=",
"im",
"[",
"box",
"[",
"0",
"]",
":",
"box",
"[",
"2",
"]",
",",
"box",
"[",
"1",
"]",
":",
"box",
"[",
"3",
"]",
"]",
"context_crop",
"=",
"caffe",
".",
"io",
".",
"resize_image",
"(",
"context_crop",
",",
"(",
"crop_h",
",",
"crop_w",
")",
")",
"crop",
"=",
"np",
".",
"ones",
"(",
"self",
".",
"crop_dims",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"*",
"self",
".",
"crop_mean",
"crop",
"[",
"pad_y",
":",
"(",
"pad_y",
"+",
"crop_h",
")",
",",
"pad_x",
":",
"(",
"pad_x",
"+",
"crop_w",
")",
"]",
"=",
"context_crop",
"return",
"crop"
] | https://github.com/AojunZhou/Incremental-Network-Quantization/blob/c7f6a609d5817d8424ce224209cf4c50f1e4de50/python/caffe/detector.py#L125-L179 | |
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | gr-filter/python/filter/file_taps_loader.py | python | file_taps_loader.get_taps | (self) | return self.taps | Return taps | Return taps | [
"Return",
"taps"
] | def get_taps(self):
" Return taps "
return self.taps | [
"def",
"get_taps",
"(",
"self",
")",
":",
"return",
"self",
".",
"taps"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-filter/python/filter/file_taps_loader.py#L86-L88 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/urllib3/filepost.py | python | encode_multipart_formdata | (fields, boundary=None) | return body.getvalue(), content_type | Encode a dictionary of ``fields`` using the multipart/form-data MIME format.
:param fields:
Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`).
:param boundary:
If not specified, then a random boundary will be generated using
:func:`urllib3.filepost.choose_boundary`. | Encode a dictionary of ``fields`` using the multipart/form-data MIME format. | [
"Encode",
"a",
"dictionary",
"of",
"fields",
"using",
"the",
"multipart",
"/",
"form",
"-",
"data",
"MIME",
"format",
"."
] | def encode_multipart_formdata(fields, boundary=None):
"""
Encode a dictionary of ``fields`` using the multipart/form-data MIME format.
:param fields:
Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`).
:param boundary:
If not specified, then a random boundary will be generated using
:func:`urllib3.filepost.choose_boundary`.
"""
body = BytesIO()
if boundary is None:
boundary = choose_boundary()
for field in iter_field_objects(fields):
body.write(b("--%s\r\n" % (boundary)))
writer(body).write(field.render_headers())
data = field.data
if isinstance(data, int):
data = str(data) # Backwards compatibility
if isinstance(data, six.text_type):
writer(body).write(data)
else:
body.write(data)
body.write(b"\r\n")
body.write(b("--%s--\r\n" % (boundary)))
content_type = str("multipart/form-data; boundary=%s" % boundary)
return body.getvalue(), content_type | [
"def",
"encode_multipart_formdata",
"(",
"fields",
",",
"boundary",
"=",
"None",
")",
":",
"body",
"=",
"BytesIO",
"(",
")",
"if",
"boundary",
"is",
"None",
":",
"boundary",
"=",
"choose_boundary",
"(",
")",
"for",
"field",
"in",
"iter_field_objects",
"(",
"fields",
")",
":",
"body",
".",
"write",
"(",
"b",
"(",
"\"--%s\\r\\n\"",
"%",
"(",
"boundary",
")",
")",
")",
"writer",
"(",
"body",
")",
".",
"write",
"(",
"field",
".",
"render_headers",
"(",
")",
")",
"data",
"=",
"field",
".",
"data",
"if",
"isinstance",
"(",
"data",
",",
"int",
")",
":",
"data",
"=",
"str",
"(",
"data",
")",
"# Backwards compatibility",
"if",
"isinstance",
"(",
"data",
",",
"six",
".",
"text_type",
")",
":",
"writer",
"(",
"body",
")",
".",
"write",
"(",
"data",
")",
"else",
":",
"body",
".",
"write",
"(",
"data",
")",
"body",
".",
"write",
"(",
"b\"\\r\\n\"",
")",
"body",
".",
"write",
"(",
"b",
"(",
"\"--%s--\\r\\n\"",
"%",
"(",
"boundary",
")",
")",
")",
"content_type",
"=",
"str",
"(",
"\"multipart/form-data; boundary=%s\"",
"%",
"boundary",
")",
"return",
"body",
".",
"getvalue",
"(",
")",
",",
"content_type"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/urllib3/filepost.py#L63-L98 | |
qt/qtbase | 81b9ee66b8e40ed145185fe46b7c91929688cafd | util/locale_database/cldr.py | python | CldrAccess.locale | (self, name) | return LocaleScanner(name, self.__localeRoots(name), self.__rootLocale) | Loads all data for a locale as a LocaleScanner object.
The name should be a locale name; adding suffix '.xml' to it
should usually yield a file in common/main/. The returned
LocaleScanner object packages this file along with all those
from which it inherits; its methods know how to handle that
inheritance, where relevant. | Loads all data for a locale as a LocaleScanner object. | [
"Loads",
"all",
"data",
"for",
"a",
"locale",
"as",
"a",
"LocaleScanner",
"object",
"."
] | def locale(self, name):
"""Loads all data for a locale as a LocaleScanner object.
The name should be a locale name; adding suffix '.xml' to it
should usually yield a file in common/main/. The returned
LocaleScanner object packages this file along with all those
from which it inherits; its methods know how to handle that
inheritance, where relevant."""
return LocaleScanner(name, self.__localeRoots(name), self.__rootLocale) | [
"def",
"locale",
"(",
"self",
",",
"name",
")",
":",
"return",
"LocaleScanner",
"(",
"name",
",",
"self",
".",
"__localeRoots",
"(",
"name",
")",
",",
"self",
".",
"__rootLocale",
")"
] | https://github.com/qt/qtbase/blob/81b9ee66b8e40ed145185fe46b7c91929688cafd/util/locale_database/cldr.py#L272-L280 | |
hakuna-m/wubiuefi | caec1af0a09c78fd5a345180ada1fe45e0c63493 | src/wubi/backends/common/distro.py | python | Distro.parse_isoinfo | (self, info) | return name, version, subversion, arch | Parses the file within the ISO
that contains metadata on the iso
e.g. .disk/info in Ubuntu
Ubuntu 9.04 "Jaunty Jackalope" - Alpha i386 (20090106)
Ubuntu 9.04 "Jaunty Jackalope" - Alpha i386 (20090106.1)
Ubuntu Split Name 9.04.1 "Jaunty Jackalope" - Final Release i386 (20090106.2)
Ubuntu-Studio 12.10 "Quantal Quetzal" - Release amd64 (20121017.1) | Parses the file within the ISO
that contains metadata on the iso
e.g. .disk/info in Ubuntu
Ubuntu 9.04 "Jaunty Jackalope" - Alpha i386 (20090106)
Ubuntu 9.04 "Jaunty Jackalope" - Alpha i386 (20090106.1)
Ubuntu Split Name 9.04.1 "Jaunty Jackalope" - Final Release i386 (20090106.2)
Ubuntu-Studio 12.10 "Quantal Quetzal" - Release amd64 (20121017.1) | [
"Parses",
"the",
"file",
"within",
"the",
"ISO",
"that",
"contains",
"metadata",
"on",
"the",
"iso",
"e",
".",
"g",
".",
".",
"disk",
"/",
"info",
"in",
"Ubuntu",
"Ubuntu",
"9",
".",
"04",
"Jaunty",
"Jackalope",
"-",
"Alpha",
"i386",
"(",
"20090106",
")",
"Ubuntu",
"9",
".",
"04",
"Jaunty",
"Jackalope",
"-",
"Alpha",
"i386",
"(",
"20090106",
".",
"1",
")",
"Ubuntu",
"Split",
"Name",
"9",
".",
"04",
".",
"1",
"Jaunty",
"Jackalope",
"-",
"Final",
"Release",
"i386",
"(",
"20090106",
".",
"2",
")",
"Ubuntu",
"-",
"Studio",
"12",
".",
"10",
"Quantal",
"Quetzal",
"-",
"Release",
"amd64",
"(",
"20121017",
".",
"1",
")"
] | def parse_isoinfo(self, info):
'''
Parses the file within the ISO
that contains metadata on the iso
e.g. .disk/info in Ubuntu
Ubuntu 9.04 "Jaunty Jackalope" - Alpha i386 (20090106)
Ubuntu 9.04 "Jaunty Jackalope" - Alpha i386 (20090106.1)
Ubuntu Split Name 9.04.1 "Jaunty Jackalope" - Final Release i386 (20090106.2)
Ubuntu-Studio 12.10 "Quantal Quetzal" - Release amd64 (20121017.1)
'''
log.debug(" parsing info from str=%s" % info)
if not info:
return
info = disk_info_re.match(info)
if info is None:
name = ""
version = ""
subversion = ""
arch = self.arch
log.debug(" parsed info=None")
else:
name = info.group('name').replace('-', ' ')
version = info.group('version')
subversion = info.group('subversion')
arch = info.group('arch')
log.debug(" parsed info=%s" % info.groupdict())
return name, version, subversion, arch | [
"def",
"parse_isoinfo",
"(",
"self",
",",
"info",
")",
":",
"log",
".",
"debug",
"(",
"\" parsing info from str=%s\"",
"%",
"info",
")",
"if",
"not",
"info",
":",
"return",
"info",
"=",
"disk_info_re",
".",
"match",
"(",
"info",
")",
"if",
"info",
"is",
"None",
":",
"name",
"=",
"\"\"",
"version",
"=",
"\"\"",
"subversion",
"=",
"\"\"",
"arch",
"=",
"self",
".",
"arch",
"log",
".",
"debug",
"(",
"\" parsed info=None\"",
")",
"else",
":",
"name",
"=",
"info",
".",
"group",
"(",
"'name'",
")",
".",
"replace",
"(",
"'-'",
",",
"' '",
")",
"version",
"=",
"info",
".",
"group",
"(",
"'version'",
")",
"subversion",
"=",
"info",
".",
"group",
"(",
"'subversion'",
")",
"arch",
"=",
"info",
".",
"group",
"(",
"'arch'",
")",
"log",
".",
"debug",
"(",
"\" parsed info=%s\"",
"%",
"info",
".",
"groupdict",
"(",
")",
")",
"return",
"name",
",",
"version",
",",
"subversion",
",",
"arch"
] | https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/wubi/backends/common/distro.py#L180-L206 | |
seqan/seqan | f5f658343c366c9c3d44ba358ffc9317e78a09ed | util/py_lib/seqan/dox/sig_parser.py | python | SigEntry.toString | (self) | Convert the SigEntry object back into a string. | Convert the SigEntry object back into a string. | [
"Convert",
"the",
"SigEntry",
"object",
"back",
"into",
"a",
"string",
"."
] | def toString(self):
"""Convert the SigEntry object back into a string."""
types = ['concept', 'class', 'struct', 'enum']
if not self.is_tpl and self.kind in types:
return '%s %s;' % (self.kind, self.name)
elif not self.is_tpl and self.kind == 'function':
params = ', '.join(['%s %s' % (p.type, p.name) for p in self.params])
if self.return_type:
return '%s %s(%s);' % (self.return_type, self.name, params)
else:
return '%s(%s);' % (self.name, params)
elif self.is_tpl and self.kind == 'function':
tparams = ', '.join(['%s %s' % (p.type, p.name) for p in self.tparams])
params = ', '.join(['%s %s' % (p.type, p.name) for p in self.params])
return 'template <%s>\n%s %s(%s);' % (tparams, self.return_type, self.name, params)
elif self.is_tpl and self.kind in ['struct', 'class']:
tparams = ', '.join(['%s %s' % (p.type, p.name) for p in self.tparams])
params = ', '.join(['%s %s' % (p.type, p.name) for p in self.params])
return 'template <%s>\n%s %s;' % (tparams, self.kind, self.name)
elif self.kind == 'metafunction':
tparams = ', '.join([p.name for p in self.tparams])
if self.return_type:
return '%s %s<%s>::%s;' % (self.return_type, self.name, tparams,
self.return_name)
else:
return '%s<%s>::%s;' % (self.name, tparams, self.return_name)
elif self.kind == 'variable':
return '%s %s;' % (self.var_type, self.name) | [
"def",
"toString",
"(",
"self",
")",
":",
"types",
"=",
"[",
"'concept'",
",",
"'class'",
",",
"'struct'",
",",
"'enum'",
"]",
"if",
"not",
"self",
".",
"is_tpl",
"and",
"self",
".",
"kind",
"in",
"types",
":",
"return",
"'%s %s;'",
"%",
"(",
"self",
".",
"kind",
",",
"self",
".",
"name",
")",
"elif",
"not",
"self",
".",
"is_tpl",
"and",
"self",
".",
"kind",
"==",
"'function'",
":",
"params",
"=",
"', '",
".",
"join",
"(",
"[",
"'%s %s'",
"%",
"(",
"p",
".",
"type",
",",
"p",
".",
"name",
")",
"for",
"p",
"in",
"self",
".",
"params",
"]",
")",
"if",
"self",
".",
"return_type",
":",
"return",
"'%s %s(%s);'",
"%",
"(",
"self",
".",
"return_type",
",",
"self",
".",
"name",
",",
"params",
")",
"else",
":",
"return",
"'%s(%s);'",
"%",
"(",
"self",
".",
"name",
",",
"params",
")",
"elif",
"self",
".",
"is_tpl",
"and",
"self",
".",
"kind",
"==",
"'function'",
":",
"tparams",
"=",
"', '",
".",
"join",
"(",
"[",
"'%s %s'",
"%",
"(",
"p",
".",
"type",
",",
"p",
".",
"name",
")",
"for",
"p",
"in",
"self",
".",
"tparams",
"]",
")",
"params",
"=",
"', '",
".",
"join",
"(",
"[",
"'%s %s'",
"%",
"(",
"p",
".",
"type",
",",
"p",
".",
"name",
")",
"for",
"p",
"in",
"self",
".",
"params",
"]",
")",
"return",
"'template <%s>\\n%s %s(%s);'",
"%",
"(",
"tparams",
",",
"self",
".",
"return_type",
",",
"self",
".",
"name",
",",
"params",
")",
"elif",
"self",
".",
"is_tpl",
"and",
"self",
".",
"kind",
"in",
"[",
"'struct'",
",",
"'class'",
"]",
":",
"tparams",
"=",
"', '",
".",
"join",
"(",
"[",
"'%s %s'",
"%",
"(",
"p",
".",
"type",
",",
"p",
".",
"name",
")",
"for",
"p",
"in",
"self",
".",
"tparams",
"]",
")",
"params",
"=",
"', '",
".",
"join",
"(",
"[",
"'%s %s'",
"%",
"(",
"p",
".",
"type",
",",
"p",
".",
"name",
")",
"for",
"p",
"in",
"self",
".",
"params",
"]",
")",
"return",
"'template <%s>\\n%s %s;'",
"%",
"(",
"tparams",
",",
"self",
".",
"kind",
",",
"self",
".",
"name",
")",
"elif",
"self",
".",
"kind",
"==",
"'metafunction'",
":",
"tparams",
"=",
"', '",
".",
"join",
"(",
"[",
"p",
".",
"name",
"for",
"p",
"in",
"self",
".",
"tparams",
"]",
")",
"if",
"self",
".",
"return_type",
":",
"return",
"'%s %s<%s>::%s;'",
"%",
"(",
"self",
".",
"return_type",
",",
"self",
".",
"name",
",",
"tparams",
",",
"self",
".",
"return_name",
")",
"else",
":",
"return",
"'%s<%s>::%s;'",
"%",
"(",
"self",
".",
"name",
",",
"tparams",
",",
"self",
".",
"return_name",
")",
"elif",
"self",
".",
"kind",
"==",
"'variable'",
":",
"return",
"'%s %s;'",
"%",
"(",
"self",
".",
"var_type",
",",
"self",
".",
"name",
")"
] | https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/util/py_lib/seqan/dox/sig_parser.py#L84-L111 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/logging/__init__.py | python | Formatter.usesTime | (self) | return self._style.usesTime() | Check if the format uses the creation time of the record. | Check if the format uses the creation time of the record. | [
"Check",
"if",
"the",
"format",
"uses",
"the",
"creation",
"time",
"of",
"the",
"record",
"."
] | def usesTime(self):
"""
Check if the format uses the creation time of the record.
"""
return self._style.usesTime() | [
"def",
"usesTime",
"(",
"self",
")",
":",
"return",
"self",
".",
"_style",
".",
"usesTime",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/logging/__init__.py#L573-L577 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/coremltools_wrap/coremltools/coremltools/models/tree_ensemble.py | python | TreeEnsembleBase.set_default_prediction_value | (self, values) | Set the default prediction value(s).
The values given here form the base prediction value that the values
at activated leaves are added to. If values is a scalar, then
the output of the tree must also be 1 dimensional; otherwise, values
must be a list with length matching the dimension of values in the tree.
Parameters
----------
values: [int | double | list[double]]
Default values for predictions. | Set the default prediction value(s). | [
"Set",
"the",
"default",
"prediction",
"value",
"(",
"s",
")",
"."
] | def set_default_prediction_value(self, values):
"""
Set the default prediction value(s).
The values given here form the base prediction value that the values
at activated leaves are added to. If values is a scalar, then
the output of the tree must also be 1 dimensional; otherwise, values
must be a list with length matching the dimension of values in the tree.
Parameters
----------
values: [int | double | list[double]]
Default values for predictions.
"""
if type(values) is not list:
values = [float(values)]
self.tree_parameters.numPredictionDimensions = len(values)
for value in values:
self.tree_parameters.basePredictionValue.append(value) | [
"def",
"set_default_prediction_value",
"(",
"self",
",",
"values",
")",
":",
"if",
"type",
"(",
"values",
")",
"is",
"not",
"list",
":",
"values",
"=",
"[",
"float",
"(",
"values",
")",
"]",
"self",
".",
"tree_parameters",
".",
"numPredictionDimensions",
"=",
"len",
"(",
"values",
")",
"for",
"value",
"in",
"values",
":",
"self",
".",
"tree_parameters",
".",
"basePredictionValue",
".",
"append",
"(",
"value",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/models/tree_ensemble.py#L37-L56 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/TreeWidget.py | python | TreeItem._GetSubList | (self) | return sublist | Do not override! Called by TreeNode. | Do not override! Called by TreeNode. | [
"Do",
"not",
"override!",
"Called",
"by",
"TreeNode",
"."
] | def _GetSubList(self):
"""Do not override! Called by TreeNode."""
if not self.IsExpandable():
return []
sublist = self.GetSubList()
if not sublist:
self.expandable = 0
return sublist | [
"def",
"_GetSubList",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"IsExpandable",
"(",
")",
":",
"return",
"[",
"]",
"sublist",
"=",
"self",
".",
"GetSubList",
"(",
")",
"if",
"not",
"sublist",
":",
"self",
".",
"expandable",
"=",
"0",
"return",
"sublist"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/TreeWidget.py#L334-L341 | |
psi4/psi4 | be533f7f426b6ccc263904e55122899b16663395 | psi4/driver/procrouting/response/scf_response.py | python | _solve_loop | (wfn,
ptype,
solve_function,
states_per_irrep: List[int],
maxiter: int,
restricted: bool = True,
spin_mult: str = "singlet") | return results | References
----------
For the expression of the transition moments in length and velocity gauges:
- T. B. Pedersen, A. E. Hansen, "Ab Initio Calculation and Display of the
Rotary Strength Tensor in the Random Phase Approximation. Method and Model
Studies." Chem. Phys. Lett., 246, 1 (1995)
- P. J. Lestrange, F. Egidi, X. Li, "The Consequences of Improperly
Describing Oscillator Strengths beyond the Electric Dipole Approximation."
J. Chem. Phys., 143, 234103 (2015) | [] | def _solve_loop(wfn,
ptype,
solve_function,
states_per_irrep: List[int],
maxiter: int,
restricted: bool = True,
spin_mult: str = "singlet") -> List[_TDSCFResults]:
"""
References
----------
For the expression of the transition moments in length and velocity gauges:
- T. B. Pedersen, A. E. Hansen, "Ab Initio Calculation and Display of the
Rotary Strength Tensor in the Random Phase Approximation. Method and Model
Studies." Chem. Phys. Lett., 246, 1 (1995)
- P. J. Lestrange, F. Egidi, X. Li, "The Consequences of Improperly
Describing Oscillator Strengths beyond the Electric Dipole Approximation."
J. Chem. Phys., 143, 234103 (2015)
"""
core.print_out("\n ==> Requested Excitations <==\n\n")
for nstate, state_sym in zip(states_per_irrep, wfn.molecule().irrep_labels()):
core.print_out(f" {nstate} {spin_mult} states with {state_sym} symmetry\n")
# construct the engine
if restricted:
if spin_mult == "triplet":
engine = TDRSCFEngine(wfn, ptype=ptype.lower(), triplet=True)
else:
engine = TDRSCFEngine(wfn, ptype=ptype.lower(), triplet=False)
else:
engine = TDUSCFEngine(wfn, ptype=ptype.lower())
# collect results and compute some spectroscopic observables
mints = core.MintsHelper(wfn.basisset())
results = []
irrep_GS = wfn.molecule().irrep_labels()[engine.G_gs]
for state_sym, nstates in enumerate(states_per_irrep):
if nstates == 0:
continue
irrep_ES = wfn.molecule().irrep_labels()[state_sym]
core.print_out(f"\n\n ==> Seeking the lowest {nstates} {spin_mult} states with {irrep_ES} symmetry")
engine.reset_for_state_symm(state_sym)
guess_ = engine.generate_guess(nstates * 4)
# ret = {"eigvals": ee, "eigvecs": (rvecs, rvecs), "stats": stats} (TDA)
# ret = {"eigvals": ee, "eigvecs": (rvecs, lvecs), "stats": stats} (RPA)
ret = solve_function(engine, nstates, guess_, maxiter)
# check whether all roots converged
if not ret["stats"][-1]["done"]:
# raise error
raise TDSCFConvergenceError(maxiter, wfn, f"singlet excitations in irrep {irrep_ES}", ret["stats"][-1])
# flatten dictionary: helps with sorting by energy
# also append state symmetry to return value
for e, (R, L) in zip(ret["eigvals"], ret["eigvecs"]):
irrep_trans = wfn.molecule().irrep_labels()[engine.G_gs ^ state_sym]
# length-gauge electric dipole transition moment
edtm_length = engine.residue(R, mints.so_dipole())
# length-gauge oscillator strength
f_length = ((2 * e) / 3) * np.sum(edtm_length**2)
# velocity-gauge electric dipole transition moment
edtm_velocity = engine.residue(L, mints.so_nabla())
## velocity-gauge oscillator strength
f_velocity = (2 / (3 * e)) * np.sum(edtm_velocity**2)
# length gauge magnetic dipole transition moment
# 1/2 is the Bohr magneton in atomic units
mdtm = 0.5 * engine.residue(L, mints.so_angular_momentum())
# NOTE The signs for rotatory strengths are opposite WRT the cited paper.
# This is becasue Psi4 defines length-gauge dipole integral to include the electron charge (-1.0)
# length gauge rotatory strength
R_length = np.einsum("i,i", edtm_length, mdtm)
# velocity gauge rotatory strength
R_velocity = -np.einsum("i,i", edtm_velocity, mdtm) / e
results.append(
_TDSCFResults(e, irrep_GS, irrep_ES, irrep_trans, edtm_length, f_length, edtm_velocity, f_velocity,
mdtm, R_length, R_velocity, spin_mult, R, L))
return results | [
"def",
"_solve_loop",
"(",
"wfn",
",",
"ptype",
",",
"solve_function",
",",
"states_per_irrep",
":",
"List",
"[",
"int",
"]",
",",
"maxiter",
":",
"int",
",",
"restricted",
":",
"bool",
"=",
"True",
",",
"spin_mult",
":",
"str",
"=",
"\"singlet\"",
")",
"->",
"List",
"[",
"_TDSCFResults",
"]",
":",
"core",
".",
"print_out",
"(",
"\"\\n ==> Requested Excitations <==\\n\\n\"",
")",
"for",
"nstate",
",",
"state_sym",
"in",
"zip",
"(",
"states_per_irrep",
",",
"wfn",
".",
"molecule",
"(",
")",
".",
"irrep_labels",
"(",
")",
")",
":",
"core",
".",
"print_out",
"(",
"f\" {nstate} {spin_mult} states with {state_sym} symmetry\\n\"",
")",
"# construct the engine",
"if",
"restricted",
":",
"if",
"spin_mult",
"==",
"\"triplet\"",
":",
"engine",
"=",
"TDRSCFEngine",
"(",
"wfn",
",",
"ptype",
"=",
"ptype",
".",
"lower",
"(",
")",
",",
"triplet",
"=",
"True",
")",
"else",
":",
"engine",
"=",
"TDRSCFEngine",
"(",
"wfn",
",",
"ptype",
"=",
"ptype",
".",
"lower",
"(",
")",
",",
"triplet",
"=",
"False",
")",
"else",
":",
"engine",
"=",
"TDUSCFEngine",
"(",
"wfn",
",",
"ptype",
"=",
"ptype",
".",
"lower",
"(",
")",
")",
"# collect results and compute some spectroscopic observables",
"mints",
"=",
"core",
".",
"MintsHelper",
"(",
"wfn",
".",
"basisset",
"(",
")",
")",
"results",
"=",
"[",
"]",
"irrep_GS",
"=",
"wfn",
".",
"molecule",
"(",
")",
".",
"irrep_labels",
"(",
")",
"[",
"engine",
".",
"G_gs",
"]",
"for",
"state_sym",
",",
"nstates",
"in",
"enumerate",
"(",
"states_per_irrep",
")",
":",
"if",
"nstates",
"==",
"0",
":",
"continue",
"irrep_ES",
"=",
"wfn",
".",
"molecule",
"(",
")",
".",
"irrep_labels",
"(",
")",
"[",
"state_sym",
"]",
"core",
".",
"print_out",
"(",
"f\"\\n\\n ==> Seeking the lowest {nstates} {spin_mult} states with {irrep_ES} symmetry\"",
")",
"engine",
".",
"reset_for_state_symm",
"(",
"state_sym",
")",
"guess_",
"=",
"engine",
".",
"generate_guess",
"(",
"nstates",
"*",
"4",
")",
"# ret = {\"eigvals\": ee, \"eigvecs\": (rvecs, rvecs), \"stats\": stats} (TDA)",
"# ret = {\"eigvals\": ee, \"eigvecs\": (rvecs, lvecs), \"stats\": stats} (RPA)",
"ret",
"=",
"solve_function",
"(",
"engine",
",",
"nstates",
",",
"guess_",
",",
"maxiter",
")",
"# check whether all roots converged",
"if",
"not",
"ret",
"[",
"\"stats\"",
"]",
"[",
"-",
"1",
"]",
"[",
"\"done\"",
"]",
":",
"# raise error",
"raise",
"TDSCFConvergenceError",
"(",
"maxiter",
",",
"wfn",
",",
"f\"singlet excitations in irrep {irrep_ES}\"",
",",
"ret",
"[",
"\"stats\"",
"]",
"[",
"-",
"1",
"]",
")",
"# flatten dictionary: helps with sorting by energy",
"# also append state symmetry to return value",
"for",
"e",
",",
"(",
"R",
",",
"L",
")",
"in",
"zip",
"(",
"ret",
"[",
"\"eigvals\"",
"]",
",",
"ret",
"[",
"\"eigvecs\"",
"]",
")",
":",
"irrep_trans",
"=",
"wfn",
".",
"molecule",
"(",
")",
".",
"irrep_labels",
"(",
")",
"[",
"engine",
".",
"G_gs",
"^",
"state_sym",
"]",
"# length-gauge electric dipole transition moment",
"edtm_length",
"=",
"engine",
".",
"residue",
"(",
"R",
",",
"mints",
".",
"so_dipole",
"(",
")",
")",
"# length-gauge oscillator strength",
"f_length",
"=",
"(",
"(",
"2",
"*",
"e",
")",
"/",
"3",
")",
"*",
"np",
".",
"sum",
"(",
"edtm_length",
"**",
"2",
")",
"# velocity-gauge electric dipole transition moment",
"edtm_velocity",
"=",
"engine",
".",
"residue",
"(",
"L",
",",
"mints",
".",
"so_nabla",
"(",
")",
")",
"## velocity-gauge oscillator strength",
"f_velocity",
"=",
"(",
"2",
"/",
"(",
"3",
"*",
"e",
")",
")",
"*",
"np",
".",
"sum",
"(",
"edtm_velocity",
"**",
"2",
")",
"# length gauge magnetic dipole transition moment",
"# 1/2 is the Bohr magneton in atomic units",
"mdtm",
"=",
"0.5",
"*",
"engine",
".",
"residue",
"(",
"L",
",",
"mints",
".",
"so_angular_momentum",
"(",
")",
")",
"# NOTE The signs for rotatory strengths are opposite WRT the cited paper.",
"# This is becasue Psi4 defines length-gauge dipole integral to include the electron charge (-1.0)",
"# length gauge rotatory strength",
"R_length",
"=",
"np",
".",
"einsum",
"(",
"\"i,i\"",
",",
"edtm_length",
",",
"mdtm",
")",
"# velocity gauge rotatory strength",
"R_velocity",
"=",
"-",
"np",
".",
"einsum",
"(",
"\"i,i\"",
",",
"edtm_velocity",
",",
"mdtm",
")",
"/",
"e",
"results",
".",
"append",
"(",
"_TDSCFResults",
"(",
"e",
",",
"irrep_GS",
",",
"irrep_ES",
",",
"irrep_trans",
",",
"edtm_length",
",",
"f_length",
",",
"edtm_velocity",
",",
"f_velocity",
",",
"mdtm",
",",
"R_length",
",",
"R_velocity",
",",
"spin_mult",
",",
"R",
",",
"L",
")",
")",
"return",
"results"
] | https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/procrouting/response/scf_response.py#L257-L339 | ||
Slicer/Slicer | ba9fadf332cb0303515b68d8d06a344c82e3e3e5 | Base/Python/slicer/util.py | python | launchConsoleProcess | (args, useStartupEnvironment=True, updateEnvironment=None, cwd=None) | return proc | Launch a process. Hiding the console and captures the process output.
The console window is hidden when running on Windows.
:param args: executable name, followed by command-line arguments
:param useStartupEnvironment: launch the process in the original environment as the original Slicer process
:param updateEnvironment: map containing optional additional environment variables (existing variables are overwritten)
:param cwd: current working directory
:return: process object. | Launch a process. Hiding the console and captures the process output. | [
"Launch",
"a",
"process",
".",
"Hiding",
"the",
"console",
"and",
"captures",
"the",
"process",
"output",
"."
] | def launchConsoleProcess(args, useStartupEnvironment=True, updateEnvironment=None, cwd=None):
"""Launch a process. Hiding the console and captures the process output.
The console window is hidden when running on Windows.
:param args: executable name, followed by command-line arguments
:param useStartupEnvironment: launch the process in the original environment as the original Slicer process
:param updateEnvironment: map containing optional additional environment variables (existing variables are overwritten)
:param cwd: current working directory
:return: process object.
"""
import subprocess
import os
if useStartupEnvironment:
startupEnv = startupEnvironment()
if updateEnvironment:
startupEnv.update(updateEnvironment)
else:
if updateEnvironment:
startupEnv = os.environ.copy()
startupEnv.update(updateEnvironment)
else:
startupEnv = None
if os.name == 'nt':
# Hide console window (only needed on Windows)
info = subprocess.STARTUPINFO()
info.dwFlags = 1
info.wShowWindow = 0
proc = subprocess.Popen(args, env=startupEnv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, startupinfo=info, cwd=cwd)
else:
proc = subprocess.Popen(args, env=startupEnv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, cwd=cwd)
return proc | [
"def",
"launchConsoleProcess",
"(",
"args",
",",
"useStartupEnvironment",
"=",
"True",
",",
"updateEnvironment",
"=",
"None",
",",
"cwd",
"=",
"None",
")",
":",
"import",
"subprocess",
"import",
"os",
"if",
"useStartupEnvironment",
":",
"startupEnv",
"=",
"startupEnvironment",
"(",
")",
"if",
"updateEnvironment",
":",
"startupEnv",
".",
"update",
"(",
"updateEnvironment",
")",
"else",
":",
"if",
"updateEnvironment",
":",
"startupEnv",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"startupEnv",
".",
"update",
"(",
"updateEnvironment",
")",
"else",
":",
"startupEnv",
"=",
"None",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"# Hide console window (only needed on Windows)",
"info",
"=",
"subprocess",
".",
"STARTUPINFO",
"(",
")",
"info",
".",
"dwFlags",
"=",
"1",
"info",
".",
"wShowWindow",
"=",
"0",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"env",
"=",
"startupEnv",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
",",
"universal_newlines",
"=",
"True",
",",
"startupinfo",
"=",
"info",
",",
"cwd",
"=",
"cwd",
")",
"else",
":",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"env",
"=",
"startupEnv",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
",",
"universal_newlines",
"=",
"True",
",",
"cwd",
"=",
"cwd",
")",
"return",
"proc"
] | https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Base/Python/slicer/util.py#L3044-L3075 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/math/symbolic.py | python | Context.bind | (self,vars,values) | Assigns multiple variables to values | Assigns multiple variables to values | [
"Assigns",
"multiple",
"variables",
"to",
"values"
] | def bind(self,vars,values):
"""Assigns multiple variables to values"""
for v,val in zip(vars,values):
if isinstance(v,str):
self.variableDict[v].value = val
else:
assert isinstance(v,Variable)
v.value = val | [
"def",
"bind",
"(",
"self",
",",
"vars",
",",
"values",
")",
":",
"for",
"v",
",",
"val",
"in",
"zip",
"(",
"vars",
",",
"values",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"str",
")",
":",
"self",
".",
"variableDict",
"[",
"v",
"]",
".",
"value",
"=",
"val",
"else",
":",
"assert",
"isinstance",
"(",
"v",
",",
"Variable",
")",
"v",
".",
"value",
"=",
"val"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/math/symbolic.py#L1371-L1378 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | JoystickEvent.SetZPosition | (*args, **kwargs) | return _misc_.JoystickEvent_SetZPosition(*args, **kwargs) | SetZPosition(self, int zPos) | SetZPosition(self, int zPos) | [
"SetZPosition",
"(",
"self",
"int",
"zPos",
")"
] | def SetZPosition(*args, **kwargs):
"""SetZPosition(self, int zPos)"""
return _misc_.JoystickEvent_SetZPosition(*args, **kwargs) | [
"def",
"SetZPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"JoystickEvent_SetZPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L2378-L2380 | |
citizenfx/fivem | 88276d40cc7baf8285d02754cc5ae42ec7a8563f | code/tools/idl/xpidl/xpidl.py | python | IDLParser.p_productions_interface | (self, p) | productions : interface productions
| typedef productions
| native productions | productions : interface productions
| typedef productions
| native productions | [
"productions",
":",
"interface",
"productions",
"|",
"typedef",
"productions",
"|",
"native",
"productions"
] | def p_productions_interface(self, p):
"""productions : interface productions
| typedef productions
| native productions"""
p[0] = list(p[2])
p[0].insert(0, p[1]) | [
"def",
"p_productions_interface",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"list",
"(",
"p",
"[",
"2",
"]",
")",
"p",
"[",
"0",
"]",
".",
"insert",
"(",
"0",
",",
"p",
"[",
"1",
"]",
")"
] | https://github.com/citizenfx/fivem/blob/88276d40cc7baf8285d02754cc5ae42ec7a8563f/code/tools/idl/xpidl/xpidl.py#L1155-L1160 | ||
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/fsm/StateData.py | python | StateData.getDoneStatus | (self) | return self.doneStatus | The done status of a state data may be anything. It is common
practice to return a Python dictionary or a string; the default
value is None. | The done status of a state data may be anything. It is common
practice to return a Python dictionary or a string; the default
value is None. | [
"The",
"done",
"status",
"of",
"a",
"state",
"data",
"may",
"be",
"anything",
".",
"It",
"is",
"common",
"practice",
"to",
"return",
"a",
"Python",
"dictionary",
"or",
"a",
"string",
";",
"the",
"default",
"value",
"is",
"None",
"."
] | def getDoneStatus(self):
"""
The done status of a state data may be anything. It is common
practice to return a Python dictionary or a string; the default
value is None.
"""
return self.doneStatus | [
"def",
"getDoneStatus",
"(",
"self",
")",
":",
"return",
"self",
".",
"doneStatus"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/fsm/StateData.py#L82-L88 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/combo.py | python | ComboPopup.Create | (*args, **kwargs) | return _combo.ComboPopup_Create(*args, **kwargs) | Create(self, Window parent) -> bool
The derived class must implement this method to create the popup
control. It should be a child of the ``parent`` passed in, but other
than that there is much flexibility in what the widget can be, its
style, etc. Return ``True`` for success, ``False`` otherwise. (NOTE:
this return value is not currently checked...) | Create(self, Window parent) -> bool | [
"Create",
"(",
"self",
"Window",
"parent",
")",
"-",
">",
"bool"
] | def Create(*args, **kwargs):
"""
Create(self, Window parent) -> bool
The derived class must implement this method to create the popup
control. It should be a child of the ``parent`` passed in, but other
than that there is much flexibility in what the widget can be, its
style, etc. Return ``True`` for success, ``False`` otherwise. (NOTE:
this return value is not currently checked...)
"""
return _combo.ComboPopup_Create(*args, **kwargs) | [
"def",
"Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_combo",
".",
"ComboPopup_Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/combo.py#L621-L631 | |
papyrussolution/OpenPapyrus | bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91 | Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/encoder.py | python | MessageSetItemSizer | (field_number) | return FieldSize | Returns a sizer for extensions of MessageSet.
The message set message looks like this:
message MessageSet {
repeated group Item = 1 {
required int32 type_id = 2;
required string message = 3;
}
} | Returns a sizer for extensions of MessageSet. | [
"Returns",
"a",
"sizer",
"for",
"extensions",
"of",
"MessageSet",
"."
] | def MessageSetItemSizer(field_number):
"""Returns a sizer for extensions of MessageSet.
The message set message looks like this:
message MessageSet {
repeated group Item = 1 {
required int32 type_id = 2;
required string message = 3;
}
}
"""
static_size = (_TagSize(1) * 2 + _TagSize(2) + _VarintSize(field_number) +
_TagSize(3))
local_VarintSize = _VarintSize
def FieldSize(value):
l = value.ByteSize()
return static_size + local_VarintSize(l) + l
return FieldSize | [
"def",
"MessageSetItemSizer",
"(",
"field_number",
")",
":",
"static_size",
"=",
"(",
"_TagSize",
"(",
"1",
")",
"*",
"2",
"+",
"_TagSize",
"(",
"2",
")",
"+",
"_VarintSize",
"(",
"field_number",
")",
"+",
"_TagSize",
"(",
"3",
")",
")",
"local_VarintSize",
"=",
"_VarintSize",
"def",
"FieldSize",
"(",
"value",
")",
":",
"l",
"=",
"value",
".",
"ByteSize",
"(",
")",
"return",
"static_size",
"+",
"local_VarintSize",
"(",
"l",
")",
"+",
"l",
"return",
"FieldSize"
] | https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/encoder.py#L315-L334 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/external/bazel_tools/tools/android/merge_manifests.py | python | MergeManifests._RemoveIntentFilters | (self, node) | Remove intent-filter in activity element.
So there are no duplicate apps.
Args:
node: Node for which to remove intent filters. | Remove intent-filter in activity element. | [
"Remove",
"intent",
"-",
"filter",
"in",
"activity",
"element",
"."
] | def _RemoveIntentFilters(self, node):
"""Remove intent-filter in activity element.
So there are no duplicate apps.
Args:
node: Node for which to remove intent filters.
"""
intent_filters = node.getElementsByTagName(self._INTENT_FILTER)
if intent_filters.length > 0:
for sub_node in intent_filters:
node.removeChild(sub_node) | [
"def",
"_RemoveIntentFilters",
"(",
"self",
",",
"node",
")",
":",
"intent_filters",
"=",
"node",
".",
"getElementsByTagName",
"(",
"self",
".",
"_INTENT_FILTER",
")",
"if",
"intent_filters",
".",
"length",
">",
"0",
":",
"for",
"sub_node",
"in",
"intent_filters",
":",
"node",
".",
"removeChild",
"(",
"sub_node",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/external/bazel_tools/tools/android/merge_manifests.py#L220-L231 | ||
perilouswithadollarsign/cstrike15_src | f82112a2388b841d72cb62ca48ab1846dfcc11c8 | thirdparty/protobuf-2.5.0/python/google/protobuf/internal/containers.py | python | BaseContainer.__getitem__ | (self, key) | return self._values[key] | Retrieves item by the specified key. | Retrieves item by the specified key. | [
"Retrieves",
"item",
"by",
"the",
"specified",
"key",
"."
] | def __getitem__(self, key):
"""Retrieves item by the specified key."""
return self._values[key] | [
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"return",
"self",
".",
"_values",
"[",
"key",
"]"
] | https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/google/protobuf/internal/containers.py#L62-L64 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | CondCore/Utilities/python/CondDBFW/uploads.py | python | uploader.upload | (self) | Calls methods that send HTTP requests to the upload server. | Calls methods that send HTTP requests to the upload server. | [
"Calls",
"methods",
"that",
"send",
"HTTP",
"requests",
"to",
"the",
"upload",
"server",
"."
] | def upload(self):
"""
Calls methods that send HTTP requests to the upload server.
"""
"""
Open an upload session on the server - this also gives us a tag lock on the tag being uploaded, if it is available.
"""
try:
# get upload session, check response for error key
upload_session_data = self.get_upload_session_id()
no_error = self.check_response_for_error_key(upload_session_data)
# if there was an error and we're testing, return False for the testing module
if not(no_error) and self._testing:
return False
self.upload_session_id = upload_session_data["id"]
self._outputter.write("Upload session obtained with token '%s'." % self.upload_session_id)
self.server_side_log_file = upload_session_data["log_file"]
except errors.NoMoreRetriesException as no_more_retries:
return self.exit_upload("Ran out of retries opening an upload session, where the limit was 3.")
except Exception as e:
# something went wrong that we have no specific exception for, so just exit and output the traceback if --debug is set.
self._outputter.write(traceback.format_exc(), ignore_verbose=True)
if not(self._verbose):
self._outputter.write("Something went wrong that isn't handled by code - to get the traceback, run again with --verbose.")
else:
self._outputter.write("Something went wrong that isn't handled by code - the traceback is above.")
return self.exit_upload()
"""
Only if a value is given for --fcsr-filter, run FCSR filtering on the IOVs locally.
"""
if self.data_to_send["fcsr_filter"] != None:
"""
FCSR Filtering:
Filtering the IOVs before we send them by getting the First Conditions Safe Run
from the server based on the target synchronization type.
"""
if self.data_to_send["inputTagData"]["time_type"] != "Time":
# if we have a time-based tag, we can't do FCSR validation - this is also the case on the server side
try:
self.filter_iovs_by_fcsr(self.upload_session_id)
# this function does not return a value, since it just operates on data - so no point checking for an error key
# the error key check is done inside the function on the response from the server
except errors.NoMoreRetriesException as no_more_retries:
return self.exit_upload("Ran out of retries trying to filter IOVs by FCSR from server, where the limit was 3.")
except Exception as e:
# something went wrong that we have no specific exception for, so just exit and output the traceback if --debug is set.
self._outputter.write(traceback.format_exc(), ignore_verbose=True)
if not(self._verbose):
self._outputter.write("Something went wrong that isn't handled by code - to get the traceback, run again with --verbose.")
else:
self._outputter.write("Something went wrong that isn't handled by code - the traceback is above.")
return self.exit_upload()
else:
self._outputter.write("The Tag you're uploading is time-based, so we can't do any FCSR-based validation. FCSR filtering is being skipped.")
"""
Check for the hashes that the server doesn't have - only send these (but in the next step).
"""
try:
check_hashes_response = self.get_hashes_to_send(self.upload_session_id)
# check for an error key in the response
no_error = self.check_response_for_error_key(check_hashes_response)
# if there was an error and we're testing, return False for the testing module
if not(no_error) and self._testing:
return False
# finally, check hashes_not_found with hashes not found locally - if there is an intersection, we stop the upload
# because if a hash is not found and is not on the server, there is no data to upload
all_hashes = [iov["payload_hash"] for iov in self.data_to_send["iovs"]]
hashes_not_found = check_hashes_response["hashes_not_found"]
hashes_found = list(set(all_hashes) - set(hashes_not_found))
self._outputter.write("Checking for IOVs that have no Payload locally or on the server.")
# check if any hashes not found on the server is used in the local SQLite database
for hash_not_found in hashes_not_found:
if hash_not_found in self.hashes_with_no_local_payload:
return self.exit_upload("IOV with hash '%s' does not have a Payload locally or on the server. Cannot continue." % hash_not_found)
for hash_found in hashes_found:
if hash_found in self.hashes_with_no_local_payload:
self._outputter.write("Payload with hash %s on server, so can upload IOV." % hash_found)
self._outputter.write("All IOVs either come with Payloads or point to a Payload already on the server.")
except errors.NoMoreRetriesException as no_more_retries:
# for now, just write the log if we get a NoMoreRetriesException
return self.exit_upload("Ran out of retries trying to check hashes of payloads to send, where the limit was 3.")
except Exception as e:
# something went wrong that we have no specific exception for, so just exit and output the traceback if --debug is set.
self._outputter.write(traceback.format_exc(), ignore_verbose=True)
if not(self._verbose):
self._outputter.write("Something went wrong that isn't handled by code - to get the traceback, run again with --verbose.")
else:
self._outputter.write("Something went wrong that isn't handled by code - the traceback is above.")
return self.exit_upload()
"""
Send the payloads the server told us about in the previous step (returned from get_hashes_to_send)
exception handling is done inside this method, since it calls a method itself for each payload.
"""
send_payloads_response = self.send_payloads(check_hashes_response["hashes_not_found"], self.upload_session_id)
if self._testing and not(send_payloads_response):
return False
"""
Final stage - send metadata to server (since the payloads are there now)
if this is successful, once it finished the upload session is closed on the server and the tag lock is released.
"""
try:
# note that the response (in send_metadata_response) is already decoded from base64 by the response check decorator
send_metadata_response = self.send_metadata(self.upload_session_id)
no_error = self.check_response_for_error_key(send_metadata_response)
if not(no_error) and self._testing:
return False
# we have to call this explicitly here since check_response_for_error_key only writes the log file
# if an error has occurred, whereas it should always be written here
self.write_server_side_log(self._log_data)
except errors.NoMoreRetriesException as no_more_retries:
return self.exit_upload("Ran out of retries trying to send metadata, where the limit was 3.")
except Exception as e:
# something went wrong that we have no specific exception for, so just exit and output the traceback if --debug is set.
self._outputter.write(traceback.format_exc(), ignore_verbose=True)
if not(self._verbose):
self._outputter.write("Something went wrong that isn't handled by code - to get the traceback, run again with --verbose.")
else:
self._outputter.write("Something went wrong that isn't handled by code - the traceback is above.")
return self.exit_upload()
# close client side log handle
self._handle.close()
# if we're running the testing script, return True to say the upload has worked
if self._testing:
return True | [
"def",
"upload",
"(",
"self",
")",
":",
"\"\"\"\n\t\tOpen an upload session on the server - this also gives us a tag lock on the tag being uploaded, if it is available.\n\t\t\"\"\"",
"try",
":",
"# get upload session, check response for error key",
"upload_session_data",
"=",
"self",
".",
"get_upload_session_id",
"(",
")",
"no_error",
"=",
"self",
".",
"check_response_for_error_key",
"(",
"upload_session_data",
")",
"# if there was an error and we're testing, return False for the testing module",
"if",
"not",
"(",
"no_error",
")",
"and",
"self",
".",
"_testing",
":",
"return",
"False",
"self",
".",
"upload_session_id",
"=",
"upload_session_data",
"[",
"\"id\"",
"]",
"self",
".",
"_outputter",
".",
"write",
"(",
"\"Upload session obtained with token '%s'.\"",
"%",
"self",
".",
"upload_session_id",
")",
"self",
".",
"server_side_log_file",
"=",
"upload_session_data",
"[",
"\"log_file\"",
"]",
"except",
"errors",
".",
"NoMoreRetriesException",
"as",
"no_more_retries",
":",
"return",
"self",
".",
"exit_upload",
"(",
"\"Ran out of retries opening an upload session, where the limit was 3.\"",
")",
"except",
"Exception",
"as",
"e",
":",
"# something went wrong that we have no specific exception for, so just exit and output the traceback if --debug is set.",
"self",
".",
"_outputter",
".",
"write",
"(",
"traceback",
".",
"format_exc",
"(",
")",
",",
"ignore_verbose",
"=",
"True",
")",
"if",
"not",
"(",
"self",
".",
"_verbose",
")",
":",
"self",
".",
"_outputter",
".",
"write",
"(",
"\"Something went wrong that isn't handled by code - to get the traceback, run again with --verbose.\"",
")",
"else",
":",
"self",
".",
"_outputter",
".",
"write",
"(",
"\"Something went wrong that isn't handled by code - the traceback is above.\"",
")",
"return",
"self",
".",
"exit_upload",
"(",
")",
"\"\"\"\n\t\tOnly if a value is given for --fcsr-filter, run FCSR filtering on the IOVs locally.\n\t\t\"\"\"",
"if",
"self",
".",
"data_to_send",
"[",
"\"fcsr_filter\"",
"]",
"!=",
"None",
":",
"\"\"\"\n\t\t\tFCSR Filtering:\n\t\t\tFiltering the IOVs before we send them by getting the First Conditions Safe Run\n\t\t\tfrom the server based on the target synchronization type.\n\t\t\t\"\"\"",
"if",
"self",
".",
"data_to_send",
"[",
"\"inputTagData\"",
"]",
"[",
"\"time_type\"",
"]",
"!=",
"\"Time\"",
":",
"# if we have a time-based tag, we can't do FCSR validation - this is also the case on the server side",
"try",
":",
"self",
".",
"filter_iovs_by_fcsr",
"(",
"self",
".",
"upload_session_id",
")",
"# this function does not return a value, since it just operates on data - so no point checking for an error key",
"# the error key check is done inside the function on the response from the server",
"except",
"errors",
".",
"NoMoreRetriesException",
"as",
"no_more_retries",
":",
"return",
"self",
".",
"exit_upload",
"(",
"\"Ran out of retries trying to filter IOVs by FCSR from server, where the limit was 3.\"",
")",
"except",
"Exception",
"as",
"e",
":",
"# something went wrong that we have no specific exception for, so just exit and output the traceback if --debug is set.",
"self",
".",
"_outputter",
".",
"write",
"(",
"traceback",
".",
"format_exc",
"(",
")",
",",
"ignore_verbose",
"=",
"True",
")",
"if",
"not",
"(",
"self",
".",
"_verbose",
")",
":",
"self",
".",
"_outputter",
".",
"write",
"(",
"\"Something went wrong that isn't handled by code - to get the traceback, run again with --verbose.\"",
")",
"else",
":",
"self",
".",
"_outputter",
".",
"write",
"(",
"\"Something went wrong that isn't handled by code - the traceback is above.\"",
")",
"return",
"self",
".",
"exit_upload",
"(",
")",
"else",
":",
"self",
".",
"_outputter",
".",
"write",
"(",
"\"The Tag you're uploading is time-based, so we can't do any FCSR-based validation. FCSR filtering is being skipped.\"",
")",
"\"\"\"\n\t\tCheck for the hashes that the server doesn't have - only send these (but in the next step).\n\t\t\"\"\"",
"try",
":",
"check_hashes_response",
"=",
"self",
".",
"get_hashes_to_send",
"(",
"self",
".",
"upload_session_id",
")",
"# check for an error key in the response",
"no_error",
"=",
"self",
".",
"check_response_for_error_key",
"(",
"check_hashes_response",
")",
"# if there was an error and we're testing, return False for the testing module",
"if",
"not",
"(",
"no_error",
")",
"and",
"self",
".",
"_testing",
":",
"return",
"False",
"# finally, check hashes_not_found with hashes not found locally - if there is an intersection, we stop the upload",
"# because if a hash is not found and is not on the server, there is no data to upload",
"all_hashes",
"=",
"[",
"iov",
"[",
"\"payload_hash\"",
"]",
"for",
"iov",
"in",
"self",
".",
"data_to_send",
"[",
"\"iovs\"",
"]",
"]",
"hashes_not_found",
"=",
"check_hashes_response",
"[",
"\"hashes_not_found\"",
"]",
"hashes_found",
"=",
"list",
"(",
"set",
"(",
"all_hashes",
")",
"-",
"set",
"(",
"hashes_not_found",
")",
")",
"self",
".",
"_outputter",
".",
"write",
"(",
"\"Checking for IOVs that have no Payload locally or on the server.\"",
")",
"# check if any hashes not found on the server is used in the local SQLite database",
"for",
"hash_not_found",
"in",
"hashes_not_found",
":",
"if",
"hash_not_found",
"in",
"self",
".",
"hashes_with_no_local_payload",
":",
"return",
"self",
".",
"exit_upload",
"(",
"\"IOV with hash '%s' does not have a Payload locally or on the server. Cannot continue.\"",
"%",
"hash_not_found",
")",
"for",
"hash_found",
"in",
"hashes_found",
":",
"if",
"hash_found",
"in",
"self",
".",
"hashes_with_no_local_payload",
":",
"self",
".",
"_outputter",
".",
"write",
"(",
"\"Payload with hash %s on server, so can upload IOV.\"",
"%",
"hash_found",
")",
"self",
".",
"_outputter",
".",
"write",
"(",
"\"All IOVs either come with Payloads or point to a Payload already on the server.\"",
")",
"except",
"errors",
".",
"NoMoreRetriesException",
"as",
"no_more_retries",
":",
"# for now, just write the log if we get a NoMoreRetriesException",
"return",
"self",
".",
"exit_upload",
"(",
"\"Ran out of retries trying to check hashes of payloads to send, where the limit was 3.\"",
")",
"except",
"Exception",
"as",
"e",
":",
"# something went wrong that we have no specific exception for, so just exit and output the traceback if --debug is set.",
"self",
".",
"_outputter",
".",
"write",
"(",
"traceback",
".",
"format_exc",
"(",
")",
",",
"ignore_verbose",
"=",
"True",
")",
"if",
"not",
"(",
"self",
".",
"_verbose",
")",
":",
"self",
".",
"_outputter",
".",
"write",
"(",
"\"Something went wrong that isn't handled by code - to get the traceback, run again with --verbose.\"",
")",
"else",
":",
"self",
".",
"_outputter",
".",
"write",
"(",
"\"Something went wrong that isn't handled by code - the traceback is above.\"",
")",
"return",
"self",
".",
"exit_upload",
"(",
")",
"\"\"\"\n\t\tSend the payloads the server told us about in the previous step (returned from get_hashes_to_send)\n\t\texception handling is done inside this method, since it calls a method itself for each payload.\n\t\t\"\"\"",
"send_payloads_response",
"=",
"self",
".",
"send_payloads",
"(",
"check_hashes_response",
"[",
"\"hashes_not_found\"",
"]",
",",
"self",
".",
"upload_session_id",
")",
"if",
"self",
".",
"_testing",
"and",
"not",
"(",
"send_payloads_response",
")",
":",
"return",
"False",
"\"\"\"\n\t\tFinal stage - send metadata to server (since the payloads are there now)\n\t\tif this is successful, once it finished the upload session is closed on the server and the tag lock is released.\n\t\t\"\"\"",
"try",
":",
"# note that the response (in send_metadata_response) is already decoded from base64 by the response check decorator",
"send_metadata_response",
"=",
"self",
".",
"send_metadata",
"(",
"self",
".",
"upload_session_id",
")",
"no_error",
"=",
"self",
".",
"check_response_for_error_key",
"(",
"send_metadata_response",
")",
"if",
"not",
"(",
"no_error",
")",
"and",
"self",
".",
"_testing",
":",
"return",
"False",
"# we have to call this explicitly here since check_response_for_error_key only writes the log file",
"# if an error has occurred, whereas it should always be written here",
"self",
".",
"write_server_side_log",
"(",
"self",
".",
"_log_data",
")",
"except",
"errors",
".",
"NoMoreRetriesException",
"as",
"no_more_retries",
":",
"return",
"self",
".",
"exit_upload",
"(",
"\"Ran out of retries trying to send metadata, where the limit was 3.\"",
")",
"except",
"Exception",
"as",
"e",
":",
"# something went wrong that we have no specific exception for, so just exit and output the traceback if --debug is set.",
"self",
".",
"_outputter",
".",
"write",
"(",
"traceback",
".",
"format_exc",
"(",
")",
",",
"ignore_verbose",
"=",
"True",
")",
"if",
"not",
"(",
"self",
".",
"_verbose",
")",
":",
"self",
".",
"_outputter",
".",
"write",
"(",
"\"Something went wrong that isn't handled by code - to get the traceback, run again with --verbose.\"",
")",
"else",
":",
"self",
".",
"_outputter",
".",
"write",
"(",
"\"Something went wrong that isn't handled by code - the traceback is above.\"",
")",
"return",
"self",
".",
"exit_upload",
"(",
")",
"# close client side log handle",
"self",
".",
"_handle",
".",
"close",
"(",
")",
"# if we're running the testing script, return True to say the upload has worked",
"if",
"self",
".",
"_testing",
":",
"return",
"True"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/CondCore/Utilities/python/CondDBFW/uploads.py#L340-L491 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/io/arff/arffread.py | python | maxnomlen | (atrv) | return max(len(i) for i in nomtp) | Given a string containing a nominal type definition, returns the
string len of the biggest component.
A nominal type is defined as seomthing framed between brace ({}).
Parameters
----------
atrv : str
Nominal type definition
Returns
-------
slen : int
length of longest component
Examples
--------
maxnomlen("{floup, bouga, fl, ratata}") returns 6 (the size of
ratata, the longest nominal value).
>>> maxnomlen("{floup, bouga, fl, ratata}")
6 | Given a string containing a nominal type definition, returns the
string len of the biggest component. | [
"Given",
"a",
"string",
"containing",
"a",
"nominal",
"type",
"definition",
"returns",
"the",
"string",
"len",
"of",
"the",
"biggest",
"component",
"."
] | def maxnomlen(atrv):
"""Given a string containing a nominal type definition, returns the
string len of the biggest component.
A nominal type is defined as seomthing framed between brace ({}).
Parameters
----------
atrv : str
Nominal type definition
Returns
-------
slen : int
length of longest component
Examples
--------
maxnomlen("{floup, bouga, fl, ratata}") returns 6 (the size of
ratata, the longest nominal value).
>>> maxnomlen("{floup, bouga, fl, ratata}")
6
"""
nomtp = get_nom_val(atrv)
return max(len(i) for i in nomtp) | [
"def",
"maxnomlen",
"(",
"atrv",
")",
":",
"nomtp",
"=",
"get_nom_val",
"(",
"atrv",
")",
"return",
"max",
"(",
"len",
"(",
"i",
")",
"for",
"i",
"in",
"nomtp",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/io/arff/arffread.py#L116-L141 | |
sigmaai/self-driving-golf-cart | 8d891600af3d851add27a10ae45cf3c2108bb87c | ros/src/ros_carla_bridge/carla_ros_bridge/src/carla_ros_bridge/collision_sensor.py | python | CollisionSensor.sensor_data_updated | (self, collision_event) | Function to wrap the collision event into a ros messsage
:param collision_event: carla collision event object
:type collision_event: carla.CollisionEvent | Function to wrap the collision event into a ros messsage | [
"Function",
"to",
"wrap",
"the",
"collision",
"event",
"into",
"a",
"ros",
"messsage"
] | def sensor_data_updated(self, collision_event):
"""
Function to wrap the collision event into a ros messsage
:param collision_event: carla collision event object
:type collision_event: carla.CollisionEvent
"""
collision_msg = CarlaCollisionEvent()
collision_msg.header = self.get_msg_header()
collision_msg.other_actor_id = collision_event.other_actor.id
collision_msg.normal_impulse.x = collision_event.normal_impulse.x
collision_msg.normal_impulse.y = collision_event.normal_impulse.y
collision_msg.normal_impulse.z = collision_event.normal_impulse.z
self.publish_message(
self.get_topic_prefix(), collision_msg) | [
"def",
"sensor_data_updated",
"(",
"self",
",",
"collision_event",
")",
":",
"collision_msg",
"=",
"CarlaCollisionEvent",
"(",
")",
"collision_msg",
".",
"header",
"=",
"self",
".",
"get_msg_header",
"(",
")",
"collision_msg",
".",
"other_actor_id",
"=",
"collision_event",
".",
"other_actor",
".",
"id",
"collision_msg",
".",
"normal_impulse",
".",
"x",
"=",
"collision_event",
".",
"normal_impulse",
".",
"x",
"collision_msg",
".",
"normal_impulse",
".",
"y",
"=",
"collision_event",
".",
"normal_impulse",
".",
"y",
"collision_msg",
".",
"normal_impulse",
".",
"z",
"=",
"collision_event",
".",
"normal_impulse",
".",
"z",
"self",
".",
"publish_message",
"(",
"self",
".",
"get_topic_prefix",
"(",
")",
",",
"collision_msg",
")"
] | https://github.com/sigmaai/self-driving-golf-cart/blob/8d891600af3d851add27a10ae45cf3c2108bb87c/ros/src/ros_carla_bridge/carla_ros_bridge/src/carla_ros_bridge/collision_sensor.py#L44-L59 | ||
kismetwireless/kismet | a7c0dc270c960fb1f58bd9cec4601c201885fd4e | capture_sdr_rtladsb/KismetCaptureRtladsb/__init__.py | python | KismetRtladsb.adsb_msg_get_ac13_altitude | (self, data) | return 0 | Extract 13 bit altitude (in feet) from 0, 4, 16, 20 | Extract 13 bit altitude (in feet) from 0, 4, 16, 20 | [
"Extract",
"13",
"bit",
"altitude",
"(",
"in",
"feet",
")",
"from",
"0",
"4",
"16",
"20"
] | def adsb_msg_get_ac13_altitude(self, data):
"""
Extract 13 bit altitude (in feet) from 0, 4, 16, 20
"""
m_bit = data[3] & (1 << 6)
q_bit = data[3] & (1 << 4)
if not m_bit:
if q_bit:
# N is the 11 bit integer resulting in the removal of bit q and m
n = (data[2] & 31) << 6
n |= (data[3] & 0x80) >> 2
n |= (data[3] & 0x20) >> 1
n |= (data[3] & 0x15)
return n * 25 - 1000
return 0 | [
"def",
"adsb_msg_get_ac13_altitude",
"(",
"self",
",",
"data",
")",
":",
"m_bit",
"=",
"data",
"[",
"3",
"]",
"&",
"(",
"1",
"<<",
"6",
")",
"q_bit",
"=",
"data",
"[",
"3",
"]",
"&",
"(",
"1",
"<<",
"4",
")",
"if",
"not",
"m_bit",
":",
"if",
"q_bit",
":",
"# N is the 11 bit integer resulting in the removal of bit q and m",
"n",
"=",
"(",
"data",
"[",
"2",
"]",
"&",
"31",
")",
"<<",
"6",
"n",
"|=",
"(",
"data",
"[",
"3",
"]",
"&",
"0x80",
")",
">>",
"2",
"n",
"|=",
"(",
"data",
"[",
"3",
"]",
"&",
"0x20",
")",
">>",
"1",
"n",
"|=",
"(",
"data",
"[",
"3",
"]",
"&",
"0x15",
")",
"return",
"n",
"*",
"25",
"-",
"1000",
"return",
"0"
] | https://github.com/kismetwireless/kismet/blob/a7c0dc270c960fb1f58bd9cec4601c201885fd4e/capture_sdr_rtladsb/KismetCaptureRtladsb/__init__.py#L801-L819 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/signal/filter_design.py | python | _validate_sos | (sos) | return sos, n_sections | Helper to validate a SOS input | Helper to validate a SOS input | [
"Helper",
"to",
"validate",
"a",
"SOS",
"input"
] | def _validate_sos(sos):
"""Helper to validate a SOS input"""
sos = np.atleast_2d(sos)
if sos.ndim != 2:
raise ValueError('sos array must be 2D')
n_sections, m = sos.shape
if m != 6:
raise ValueError('sos array must be shape (n_sections, 6)')
if not (sos[:, 3] == 1).all():
raise ValueError('sos[:, 3] should be all ones')
return sos, n_sections | [
"def",
"_validate_sos",
"(",
"sos",
")",
":",
"sos",
"=",
"np",
".",
"atleast_2d",
"(",
"sos",
")",
"if",
"sos",
".",
"ndim",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"'sos array must be 2D'",
")",
"n_sections",
",",
"m",
"=",
"sos",
".",
"shape",
"if",
"m",
"!=",
"6",
":",
"raise",
"ValueError",
"(",
"'sos array must be shape (n_sections, 6)'",
")",
"if",
"not",
"(",
"sos",
"[",
":",
",",
"3",
"]",
"==",
"1",
")",
".",
"all",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'sos[:, 3] should be all ones'",
")",
"return",
"sos",
",",
"n_sections"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/signal/filter_design.py#L696-L706 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/client/timeline.py | python | Timeline._alloc_pid | (self) | return pid | Allocate a process Id. | Allocate a process Id. | [
"Allocate",
"a",
"process",
"Id",
"."
] | def _alloc_pid(self):
"""Allocate a process Id."""
pid = self._next_pid
self._next_pid += 1
return pid | [
"def",
"_alloc_pid",
"(",
"self",
")",
":",
"pid",
"=",
"self",
".",
"_next_pid",
"self",
".",
"_next_pid",
"+=",
"1",
"return",
"pid"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/client/timeline.py#L375-L379 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/_pydecimal.py | python | Decimal.max | (self, other, context=None) | return ans._fix(context) | Returns the larger value.
Like max(self, other) except if one is not a number, returns
NaN (and signals if one is sNaN). Also rounds. | Returns the larger value. | [
"Returns",
"the",
"larger",
"value",
"."
] | def max(self, other, context=None):
"""Returns the larger value.
Like max(self, other) except if one is not a number, returns
NaN (and signals if one is sNaN). Also rounds.
"""
other = _convert_other(other, raiseit=True)
if context is None:
context = getcontext()
if self._is_special or other._is_special:
# If one operand is a quiet NaN and the other is number, then the
# number is always returned
sn = self._isnan()
on = other._isnan()
if sn or on:
if on == 1 and sn == 0:
return self._fix(context)
if sn == 1 and on == 0:
return other._fix(context)
return self._check_nans(other, context)
c = self._cmp(other)
if c == 0:
# If both operands are finite and equal in numerical value
# then an ordering is applied:
#
# If the signs differ then max returns the operand with the
# positive sign and min returns the operand with the negative sign
#
# If the signs are the same then the exponent is used to select
# the result. This is exactly the ordering used in compare_total.
c = self.compare_total(other)
if c == -1:
ans = other
else:
ans = self
return ans._fix(context) | [
"def",
"max",
"(",
"self",
",",
"other",
",",
"context",
"=",
"None",
")",
":",
"other",
"=",
"_convert_other",
"(",
"other",
",",
"raiseit",
"=",
"True",
")",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"getcontext",
"(",
")",
"if",
"self",
".",
"_is_special",
"or",
"other",
".",
"_is_special",
":",
"# If one operand is a quiet NaN and the other is number, then the",
"# number is always returned",
"sn",
"=",
"self",
".",
"_isnan",
"(",
")",
"on",
"=",
"other",
".",
"_isnan",
"(",
")",
"if",
"sn",
"or",
"on",
":",
"if",
"on",
"==",
"1",
"and",
"sn",
"==",
"0",
":",
"return",
"self",
".",
"_fix",
"(",
"context",
")",
"if",
"sn",
"==",
"1",
"and",
"on",
"==",
"0",
":",
"return",
"other",
".",
"_fix",
"(",
"context",
")",
"return",
"self",
".",
"_check_nans",
"(",
"other",
",",
"context",
")",
"c",
"=",
"self",
".",
"_cmp",
"(",
"other",
")",
"if",
"c",
"==",
"0",
":",
"# If both operands are finite and equal in numerical value",
"# then an ordering is applied:",
"#",
"# If the signs differ then max returns the operand with the",
"# positive sign and min returns the operand with the negative sign",
"#",
"# If the signs are the same then the exponent is used to select",
"# the result. This is exactly the ordering used in compare_total.",
"c",
"=",
"self",
".",
"compare_total",
"(",
"other",
")",
"if",
"c",
"==",
"-",
"1",
":",
"ans",
"=",
"other",
"else",
":",
"ans",
"=",
"self",
"return",
"ans",
".",
"_fix",
"(",
"context",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/_pydecimal.py#L2816-L2856 | |
wyrover/book-code | 7f4883d9030d553bc6bcfa3da685e34789839900 | apibook/07_Performance/redundant_includes/generate_includes.py | python | generate_makefile | (dir, max) | Create the Makefile to compile the set of all generated files | Create the Makefile to compile the set of all generated files | [
"Create",
"the",
"Makefile",
"to",
"compile",
"the",
"set",
"of",
"all",
"generated",
"files"
] | def generate_makefile(dir, max):
'''
Create the Makefile to compile the set of all generated files
'''
fp = open_output_file(os.path.join(dir, "Makefile"))
fp.write("default:\n")
for i in range(0, max):
name = "inc%d" % i
fp.write("\t%s -c %s.cpp -o %s.o\n" % (COMPILER, name, name))
fp.close() | [
"def",
"generate_makefile",
"(",
"dir",
",",
"max",
")",
":",
"fp",
"=",
"open_output_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"\"Makefile\"",
")",
")",
"fp",
".",
"write",
"(",
"\"default:\\n\"",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"max",
")",
":",
"name",
"=",
"\"inc%d\"",
"%",
"i",
"fp",
".",
"write",
"(",
"\"\\t%s -c %s.cpp -o %s.o\\n\"",
"%",
"(",
"COMPILER",
",",
"name",
",",
"name",
")",
")",
"fp",
".",
"close",
"(",
")"
] | https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/apibook/07_Performance/redundant_includes/generate_includes.py#L91-L102 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.