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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/grid.py | python | Grid.DisableDragColSize | (*args, **kwargs) | return _grid.Grid_DisableDragColSize(*args, **kwargs) | DisableDragColSize(self) | DisableDragColSize(self) | [
"DisableDragColSize",
"(",
"self",
")"
] | def DisableDragColSize(*args, **kwargs):
"""DisableDragColSize(self)"""
return _grid.Grid_DisableDragColSize(*args, **kwargs) | [
"def",
"DisableDragColSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_DisableDragColSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L1610-L1612 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/s3transfer/bandwidth.py | python | TimeUtils.time | (self) | return time.time() | Get the current time back
:rtype: float
:returns: The current time in seconds | Get the current time back | [
"Get",
"the",
"current",
"time",
"back"
] | def time(self):
"""Get the current time back
:rtype: float
:returns: The current time in seconds
"""
return time.time() | [
"def",
"time",
"(",
"self",
")",
":",
"return",
"time",
".",
"time",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/s3transfer/bandwidth.py#L46-L52 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py | python | TNavigator.towards | (self, x, y=None) | return (self._angleOffset + self._angleOrient*result) % self._fullcircle | Return the angle of the line from the turtle's position to (x, y).
Arguments:
x -- a number or a pair/vector of numbers or a turtle instance
y -- a number None None
call: distance(x, y) # two coordinates
--or: distance((x, y)) # a pair (tuple) of coordinates
--or: distance(vec) # e.g. as returned by pos()
--or: distance(mypen) # where mypen is another turtle
Return the angle, between the line from turtle-position to position
specified by x, y and the turtle's start orientation. (Depends on
modes - "standard" or "logo")
Example (for a Turtle instance named turtle):
>>> turtle.pos()
(10.00, 10.00)
>>> turtle.towards(0,0)
225.0 | Return the angle of the line from the turtle's position to (x, y). | [
"Return",
"the",
"angle",
"of",
"the",
"line",
"from",
"the",
"turtle",
"s",
"position",
"to",
"(",
"x",
"y",
")",
"."
] | def towards(self, x, y=None):
"""Return the angle of the line from the turtle's position to (x, y).
Arguments:
x -- a number or a pair/vector of numbers or a turtle instance
y -- a number None None
call: distance(x, y) # two coordinates
--or: distance((x, y)) # a pair (tuple) of coordinates
--or: distance(vec) # e.g. as returned by pos()
--or: distance(mypen) # where mypen is another turtle
Return the angle, between the line from turtle-position to position
specified by x, y and the turtle's start orientation. (Depends on
modes - "standard" or "logo")
Example (for a Turtle instance named turtle):
>>> turtle.pos()
(10.00, 10.00)
>>> turtle.towards(0,0)
225.0
"""
if y is not None:
pos = Vec2D(x, y)
if isinstance(x, Vec2D):
pos = x
elif isinstance(x, tuple):
pos = Vec2D(*x)
elif isinstance(x, TNavigator):
pos = x._position
x, y = pos - self._position
result = round(math.atan2(y, x)*180.0/math.pi, 10) % 360.0
result /= self._degreesPerAU
return (self._angleOffset + self._angleOrient*result) % self._fullcircle | [
"def",
"towards",
"(",
"self",
",",
"x",
",",
"y",
"=",
"None",
")",
":",
"if",
"y",
"is",
"not",
"None",
":",
"pos",
"=",
"Vec2D",
"(",
"x",
",",
"y",
")",
"if",
"isinstance",
"(",
"x",
",",
"Vec2D",
")",
":",
"pos",
"=",
"x",
"elif",
"isi... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py#L1775-L1808 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/distributed/elastic/rendezvous/etcd_store.py | python | EtcdStore.add | (self, key, num: int) | Atomically increment a value by an integer amount. The integer is
represented as a string using base 10. If key is not present,
a default value of ``0`` will be assumed.
Returns:
the new (incremented) value | Atomically increment a value by an integer amount. The integer is
represented as a string using base 10. If key is not present,
a default value of ``0`` will be assumed. | [
"Atomically",
"increment",
"a",
"value",
"by",
"an",
"integer",
"amount",
".",
"The",
"integer",
"is",
"represented",
"as",
"a",
"string",
"using",
"base",
"10",
".",
"If",
"key",
"is",
"not",
"present",
"a",
"default",
"value",
"of",
"0",
"will",
"be",
... | def add(self, key, num: int) -> int:
"""
Atomically increment a value by an integer amount. The integer is
represented as a string using base 10. If key is not present,
a default value of ``0`` will be assumed.
Returns:
the new (incremented) value
"""
b64_key = self._encode(key)
# c10d Store assumes value is an integer represented as a decimal string
try:
# Assume default value "0", if this key didn't yet:
node = self.client.write(
key=self.prefix + b64_key,
value=self._encode(str(num)), # i.e. 0 + num
prevExist=False,
)
return int(self._decode(node.value))
except etcd.EtcdAlreadyExist:
pass
while True:
# Note: c10d Store does not have a method to delete keys, so we
# can be sure it's still there.
node = self.client.get(key=self.prefix + b64_key)
new_value = self._encode(str(int(self._decode(node.value)) + num))
try:
node = self.client.test_and_set(
key=node.key, value=new_value, prev_value=node.value
)
return int(self._decode(node.value))
except etcd.EtcdCompareFailed:
cas_delay() | [
"def",
"add",
"(",
"self",
",",
"key",
",",
"num",
":",
"int",
")",
"->",
"int",
":",
"b64_key",
"=",
"self",
".",
"_encode",
"(",
"key",
")",
"# c10d Store assumes value is an integer represented as a decimal string",
"try",
":",
"# Assume default value \"0\", if t... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/elastic/rendezvous/etcd_store.py#L79-L114 | ||
traveller59/spconv | 647927ce6b64dc51fbec4eb50c7194f8ca5007e5 | spconv/pytorch/hash.py | python | HashTable.insert_exist_keys | (self, keys: torch.Tensor, values: torch.Tensor) | return is_success | insert kv that k exists in table. return a uint8 tensor that
whether insert success. | insert kv that k exists in table. return a uint8 tensor that
whether insert success. | [
"insert",
"kv",
"that",
"k",
"exists",
"in",
"table",
".",
"return",
"a",
"uint8",
"tensor",
"that",
"whether",
"insert",
"success",
"."
] | def insert_exist_keys(self, keys: torch.Tensor, values: torch.Tensor):
"""insert kv that k exists in table. return a uint8 tensor that
whether insert success.
"""
keys_tv = torch_tensor_to_tv(keys)
values_tv = torch_tensor_to_tv(values)
stream = 0
if not self.is_cpu:
stream = get_current_stream()
is_success = torch.empty([keys.shape[0]], dtype=torch.uint8, device=keys.device)
is_success_tv = torch_tensor_to_tv(is_success)
self._table.insert_exist_keys(keys_tv, values_tv, is_success_tv, stream)
return is_success | [
"def",
"insert_exist_keys",
"(",
"self",
",",
"keys",
":",
"torch",
".",
"Tensor",
",",
"values",
":",
"torch",
".",
"Tensor",
")",
":",
"keys_tv",
"=",
"torch_tensor_to_tv",
"(",
"keys",
")",
"values_tv",
"=",
"torch_tensor_to_tv",
"(",
"values",
")",
"st... | https://github.com/traveller59/spconv/blob/647927ce6b64dc51fbec4eb50c7194f8ca5007e5/spconv/pytorch/hash.py#L96-L108 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/base.py | python | ancestors | (path) | Emit the parent directories of a path. | Emit the parent directories of a path. | [
"Emit",
"the",
"parent",
"directories",
"of",
"a",
"path",
"."
] | def ancestors(path):
"""Emit the parent directories of a path."""
while path:
yield path
newpath = os.path.dirname(path)
if newpath == path:
break
path = newpath | [
"def",
"ancestors",
"(",
"path",
")",
":",
"while",
"path",
":",
"yield",
"path",
"newpath",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"if",
"newpath",
"==",
"path",
":",
"break",
"path",
"=",
"newpath"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/base.py#L31-L38 | ||
yuxng/PoseCNN | 9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04 | lib/datasets/shapenet_scene.py | python | shapenet_scene.depth_path_at | (self, i) | return self.depth_path_from_index(self.image_index[i]) | Return the absolute path to depth i in the image sequence. | Return the absolute path to depth i in the image sequence. | [
"Return",
"the",
"absolute",
"path",
"to",
"depth",
"i",
"in",
"the",
"image",
"sequence",
"."
] | def depth_path_at(self, i):
"""
Return the absolute path to depth i in the image sequence.
"""
return self.depth_path_from_index(self.image_index[i]) | [
"def",
"depth_path_at",
"(",
"self",
",",
"i",
")",
":",
"return",
"self",
".",
"depth_path_from_index",
"(",
"self",
".",
"image_index",
"[",
"i",
"]",
")"
] | https://github.com/yuxng/PoseCNN/blob/9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04/lib/datasets/shapenet_scene.py#L49-L53 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPMT_SYM_DEF.fromBytes | (buffer) | return TpmBuffer(buffer).createObj(TPMT_SYM_DEF) | Returns new TPMT_SYM_DEF object constructed from its marshaled
representation in the given byte buffer | Returns new TPMT_SYM_DEF object constructed from its marshaled
representation in the given byte buffer | [
"Returns",
"new",
"TPMT_SYM_DEF",
"object",
"constructed",
"from",
"its",
"marshaled",
"representation",
"in",
"the",
"given",
"byte",
"buffer"
] | def fromBytes(buffer):
""" Returns new TPMT_SYM_DEF object constructed from its marshaled
representation in the given byte buffer
"""
return TpmBuffer(buffer).createObj(TPMT_SYM_DEF) | [
"def",
"fromBytes",
"(",
"buffer",
")",
":",
"return",
"TpmBuffer",
"(",
"buffer",
")",
".",
"createObj",
"(",
"TPMT_SYM_DEF",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L5832-L5836 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextEvent.SetWParam | (*args, **kwargs) | return _stc.StyledTextEvent_SetWParam(*args, **kwargs) | SetWParam(self, int val) | SetWParam(self, int val) | [
"SetWParam",
"(",
"self",
"int",
"val",
")"
] | def SetWParam(*args, **kwargs):
"""SetWParam(self, int val)"""
return _stc.StyledTextEvent_SetWParam(*args, **kwargs) | [
"def",
"SetWParam",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextEvent_SetWParam",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L7074-L7076 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/richtext.py | python | RichTextBuffer.InitStandardHandlers | (*args, **kwargs) | return _richtext.RichTextBuffer_InitStandardHandlers(*args, **kwargs) | InitStandardHandlers() | InitStandardHandlers() | [
"InitStandardHandlers",
"()"
] | def InitStandardHandlers(*args, **kwargs):
"""InitStandardHandlers()"""
return _richtext.RichTextBuffer_InitStandardHandlers(*args, **kwargs) | [
"def",
"InitStandardHandlers",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextBuffer_InitStandardHandlers",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L2600-L2602 | |
nvdla/sw | 79538ba1b52b040a4a4645f630e457fa01839e90 | umd/external/protobuf-2.6/python/mox.py | python | MockMethod.InAnyOrder | (self, group_name="default") | return self._CheckAndCreateNewGroup(group_name, UnorderedGroup) | Move this method into a group of unordered calls.
A group of unordered calls must be defined together, and must be executed
in full before the next expected method can be called. There can be
multiple groups that are expected serially, if they are given
different group names. The same group name can be reused if there is a
standard method call, or a group with a different name, spliced between
usages.
Args:
group_name: the name of the unordered group.
Returns:
self | Move this method into a group of unordered calls. | [
"Move",
"this",
"method",
"into",
"a",
"group",
"of",
"unordered",
"calls",
"."
] | def InAnyOrder(self, group_name="default"):
"""Move this method into a group of unordered calls.
A group of unordered calls must be defined together, and must be executed
in full before the next expected method can be called. There can be
multiple groups that are expected serially, if they are given
different group names. The same group name can be reused if there is a
standard method call, or a group with a different name, spliced between
usages.
Args:
group_name: the name of the unordered group.
Returns:
self
"""
return self._CheckAndCreateNewGroup(group_name, UnorderedGroup) | [
"def",
"InAnyOrder",
"(",
"self",
",",
"group_name",
"=",
"\"default\"",
")",
":",
"return",
"self",
".",
"_CheckAndCreateNewGroup",
"(",
"group_name",
",",
"UnorderedGroup",
")"
] | https://github.com/nvdla/sw/blob/79538ba1b52b040a4a4645f630e457fa01839e90/umd/external/protobuf-2.6/python/mox.py#L686-L702 | |
apple/swift-clang | d7403439fc6641751840b723e7165fb02f52db95 | bindings/python/clang/cindex.py | python | Cursor.is_move_constructor | (self) | return conf.lib.clang_CXXConstructor_isMoveConstructor(self) | Returns True if the cursor refers to a C++ move constructor. | Returns True if the cursor refers to a C++ move constructor. | [
"Returns",
"True",
"if",
"the",
"cursor",
"refers",
"to",
"a",
"C",
"++",
"move",
"constructor",
"."
] | def is_move_constructor(self):
"""Returns True if the cursor refers to a C++ move constructor.
"""
return conf.lib.clang_CXXConstructor_isMoveConstructor(self) | [
"def",
"is_move_constructor",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_CXXConstructor_isMoveConstructor",
"(",
"self",
")"
] | https://github.com/apple/swift-clang/blob/d7403439fc6641751840b723e7165fb02f52db95/bindings/python/clang/cindex.py#L1465-L1468 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/notebook/callback.py | python | PandasLogger.eval_cb | (self, param) | Callback function for evaluation | Callback function for evaluation | [
"Callback",
"function",
"for",
"evaluation"
] | def eval_cb(self, param):
"""Callback function for evaluation
"""
self._process_batch(param, 'eval') | [
"def",
"eval_cb",
"(",
"self",
",",
"param",
")",
":",
"self",
".",
"_process_batch",
"(",
"param",
",",
"'eval'",
")"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/notebook/callback.py#L150-L153 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | KeyboardState.GetModifiers | (*args, **kwargs) | return _core_.KeyboardState_GetModifiers(*args, **kwargs) | GetModifiers(self) -> int
Returns a bitmask of the current modifier settings. Can be used to
check if the key event has exactly the given modifiers without having
to explicitly check that the other modifiers are not down. For
example::
if event.GetModifers() == wx.MOD_CONTROL:
DoSomething() | GetModifiers(self) -> int | [
"GetModifiers",
"(",
"self",
")",
"-",
">",
"int"
] | def GetModifiers(*args, **kwargs):
"""
GetModifiers(self) -> int
Returns a bitmask of the current modifier settings. Can be used to
check if the key event has exactly the given modifiers without having
to explicitly check that the other modifiers are not down. For
example::
if event.GetModifers() == wx.MOD_CONTROL:
DoSomething()
"""
return _core_.KeyboardState_GetModifiers(*args, **kwargs) | [
"def",
"GetModifiers",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"KeyboardState_GetModifiers",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L4297-L4310 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/src/robotsim.py | python | RobotModelDriver.getType | (self) | return _robotsim.RobotModelDriver_getType(self) | r"""
getType(RobotModelDriver self) -> char const *
Gets the type of the driver.
Returns:
One of "normal", "affine", "rotation", "translation", or "custom" | r"""
getType(RobotModelDriver self) -> char const * | [
"r",
"getType",
"(",
"RobotModelDriver",
"self",
")",
"-",
">",
"char",
"const",
"*"
] | def getType(self) -> "char const *":
r"""
getType(RobotModelDriver self) -> char const *
Gets the type of the driver.
Returns:
One of "normal", "affine", "rotation", "translation", or "custom"
"""
return _robotsim.RobotModelDriver_getType(self) | [
"def",
"getType",
"(",
"self",
")",
"->",
"\"char const *\"",
":",
"return",
"_robotsim",
".",
"RobotModelDriver_getType",
"(",
"self",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L4615-L4627 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/training/device_setter.py | python | _ReplicaDeviceChooser.device_function | (self, op) | return spec.to_string() | Chose a device for `op`.
Args:
op: an `Operation`.
Returns:
The device to use for the `Operation`. | Chose a device for `op`. | [
"Chose",
"a",
"device",
"for",
"op",
"."
] | def device_function(self, op):
"""Chose a device for `op`.
Args:
op: an `Operation`.
Returns:
The device to use for the `Operation`.
"""
if not self._merge_devices and op.device:
return op.device
current_device = pydev.DeviceSpec.from_string(op.device or "")
spec = pydev.DeviceSpec()
if self._ps_tasks and self._ps_device:
node_def = op if isinstance(op, graph_pb2.NodeDef) else op.node_def
if node_def.op in self._ps_ops:
device_string = "%s/task:%d" % (self._ps_device, self._next_task())
if self._merge_devices:
spec = pydev.DeviceSpec.from_string(device_string)
spec.merge_from(current_device)
return spec.to_string()
else:
return device_string
if self._worker_device:
if not self._merge_devices:
return self._worker_device
spec = pydev.DeviceSpec.from_string(self._worker_device)
if not self._merge_devices:
return ""
spec.merge_from(current_device)
return spec.to_string() | [
"def",
"device_function",
"(",
"self",
",",
"op",
")",
":",
"if",
"not",
"self",
".",
"_merge_devices",
"and",
"op",
".",
"device",
":",
"return",
"op",
".",
"device",
"current_device",
"=",
"pydev",
".",
"DeviceSpec",
".",
"from_string",
"(",
"op",
".",... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/training/device_setter.py#L65-L97 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pbr/core.py | python | pbr | (dist, attr, value) | Implements the actual pbr setup() keyword.
When used, this should be the only keyword in your setup() aside from
`setup_requires`.
If given as a string, the value of pbr is assumed to be the relative path
to the setup.cfg file to use. Otherwise, if it evaluates to true, it
simply assumes that pbr should be used, and the default 'setup.cfg' is
used.
This works by reading the setup.cfg file, parsing out the supported
metadata and command options, and using them to rebuild the
`DistributionMetadata` object and set the newly added command options.
The reason for doing things this way is that a custom `Distribution` class
will not play nicely with setup_requires; however, this implementation may
not work well with distributions that do use a `Distribution` subclass. | Implements the actual pbr setup() keyword. | [
"Implements",
"the",
"actual",
"pbr",
"setup",
"()",
"keyword",
"."
] | def pbr(dist, attr, value):
"""Implements the actual pbr setup() keyword.
When used, this should be the only keyword in your setup() aside from
`setup_requires`.
If given as a string, the value of pbr is assumed to be the relative path
to the setup.cfg file to use. Otherwise, if it evaluates to true, it
simply assumes that pbr should be used, and the default 'setup.cfg' is
used.
This works by reading the setup.cfg file, parsing out the supported
metadata and command options, and using them to rebuild the
`DistributionMetadata` object and set the newly added command options.
The reason for doing things this way is that a custom `Distribution` class
will not play nicely with setup_requires; however, this implementation may
not work well with distributions that do use a `Distribution` subclass.
"""
if not value:
return
if isinstance(value, string_type):
path = os.path.abspath(value)
else:
path = os.path.abspath('setup.cfg')
if not os.path.exists(path):
raise errors.DistutilsFileError(
'The setup.cfg file %s does not exist.' % path)
# Converts the setup.cfg file to setup() arguments
try:
attrs = util.cfg_to_args(path, dist.script_args)
except Exception:
e = sys.exc_info()[1]
# NB: This will output to the console if no explicit logging has
# been setup - but thats fine, this is a fatal distutils error, so
# being pretty isn't the #1 goal.. being diagnosable is.
logging.exception('Error parsing')
raise errors.DistutilsSetupError(
'Error parsing %s: %s: %s' % (path, e.__class__.__name__, e))
# Repeat some of the Distribution initialization code with the newly
# provided attrs
if attrs:
# Skips 'options' and 'licence' support which are rarely used; may
# add back in later if demanded
for key, val in attrs.items():
if hasattr(dist.metadata, 'set_' + key):
getattr(dist.metadata, 'set_' + key)(val)
elif hasattr(dist.metadata, key):
setattr(dist.metadata, key, val)
elif hasattr(dist, key):
setattr(dist, key, val)
else:
msg = 'Unknown distribution option: %s' % repr(key)
warnings.warn(msg)
# Re-finalize the underlying Distribution
try:
super(dist.__class__, dist).finalize_options()
except TypeError:
# If dist is not declared as a new-style class (with object as
# a subclass) then super() will not work on it. This is the case
# for Python 2. In that case, fall back to doing this the ugly way
dist.__class__.__bases__[-1].finalize_options(dist)
# This bit comes out of distribute/setuptools
if isinstance(dist.metadata.version, integer_types + (float,)):
# Some people apparently take "version number" too literally :)
dist.metadata.version = str(dist.metadata.version) | [
"def",
"pbr",
"(",
"dist",
",",
"attr",
",",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"if",
"isinstance",
"(",
"value",
",",
"string_type",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"value",
")",
"else",
":",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pbr/core.py#L64-L134 | ||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/insufficient-nodes-in-root-to-leaf-paths.py | python | Solution.sufficientSubset | (self, root, limit) | return root | :type root: TreeNode
:type limit: int
:rtype: TreeNode | :type root: TreeNode
:type limit: int
:rtype: TreeNode | [
":",
"type",
"root",
":",
"TreeNode",
":",
"type",
"limit",
":",
"int",
":",
"rtype",
":",
"TreeNode"
] | def sufficientSubset(self, root, limit):
"""
:type root: TreeNode
:type limit: int
:rtype: TreeNode
"""
if not root:
return None
if not root.left and not root.right:
return None if root.val < limit else root
root.left = self.sufficientSubset(root.left, limit-root.val)
root.right = self.sufficientSubset(root.right, limit-root.val)
if not root.left and not root.right:
return None
return root | [
"def",
"sufficientSubset",
"(",
"self",
",",
"root",
",",
"limit",
")",
":",
"if",
"not",
"root",
":",
"return",
"None",
"if",
"not",
"root",
".",
"left",
"and",
"not",
"root",
".",
"right",
":",
"return",
"None",
"if",
"root",
".",
"val",
"<",
"li... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/insufficient-nodes-in-root-to-leaf-paths.py#L13-L27 | |
KhronosGroup/Vulkan-Samples | 11a0eeffa223e3c049780fd783900da0bfe50431 | .github/docker/scripts/clang_format.py | python | print_diff | (old_tree, new_tree) | Print the diff between the two trees to stdout. | Print the diff between the two trees to stdout. | [
"Print",
"the",
"diff",
"between",
"the",
"two",
"trees",
"to",
"stdout",
"."
] | def print_diff(old_tree, new_tree):
"""Print the diff between the two trees to stdout."""
# We use the porcelain 'diff' and not plumbing 'diff-tree' because the output
# is expected to be viewed by the user, and only the former does nice things
# like color and pagination.
#
# We also only print modified files since `new_tree` only contains the files
# that were modified, so unmodified files would show as deleted without the
# filter.
subprocess.check_call(['git', 'diff', '--diff-filter=M', old_tree, new_tree,
'--']) | [
"def",
"print_diff",
"(",
"old_tree",
",",
"new_tree",
")",
":",
"# We use the porcelain 'diff' and not plumbing 'diff-tree' because the output",
"# is expected to be viewed by the user, and only the former does nice things",
"# like color and pagination.",
"#",
"# We also only print modifie... | https://github.com/KhronosGroup/Vulkan-Samples/blob/11a0eeffa223e3c049780fd783900da0bfe50431/.github/docker/scripts/clang_format.py#L470-L480 | ||
psnonis/FinBERT | c0c555d833a14e2316a3701e59c0b5156f804b4e | bert/run_squad.py | python | read_squad_examples | (input_file, is_training) | return examples | Read a SQuAD json file into a list of SquadExample. | Read a SQuAD json file into a list of SquadExample. | [
"Read",
"a",
"SQuAD",
"json",
"file",
"into",
"a",
"list",
"of",
"SquadExample",
"."
] | def read_squad_examples(input_file, is_training):
"""Read a SQuAD json file into a list of SquadExample."""
with tf.gfile.Open(input_file, "r") as reader:
input_data = json.load(reader)["data"]
def is_whitespace(c):
if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
return True
return False
examples = []
for entry in input_data:
for paragraph in entry["paragraphs"]:
paragraph_text = paragraph["context"]
doc_tokens = []
char_to_word_offset = []
prev_is_whitespace = True
for c in paragraph_text:
if is_whitespace(c):
prev_is_whitespace = True
else:
if prev_is_whitespace:
doc_tokens.append(c)
else:
doc_tokens[-1] += c
prev_is_whitespace = False
char_to_word_offset.append(len(doc_tokens) - 1)
for qa in paragraph["qas"]:
qas_id = qa["id"]
question_text = qa["question"]
start_position = None
end_position = None
orig_answer_text = None
is_impossible = False
if is_training:
if FLAGS.version_2_with_negative:
is_impossible = qa["is_impossible"]
if (len(qa["answers"]) != 1) and (not is_impossible):
raise ValueError(
"For training, each question should have exactly 1 answer.")
if not is_impossible:
answer = qa["answers"][0]
orig_answer_text = answer["text"]
answer_offset = answer["answer_start"]
answer_length = len(orig_answer_text)
start_position = char_to_word_offset[answer_offset]
end_position = char_to_word_offset[answer_offset + answer_length -
1]
# Only add answers where the text can be exactly recovered from the
# document. If this CAN'T happen it's likely due to weird Unicode
# stuff so we will just skip the example.
#
# Note that this means for training mode, every example is NOT
# guaranteed to be preserved.
actual_text = " ".join(
doc_tokens[start_position:(end_position + 1)])
cleaned_answer_text = " ".join(
tokenization.whitespace_tokenize(orig_answer_text))
if actual_text.find(cleaned_answer_text) == -1:
tf.logging.warning("Could not find answer: '%s' vs. '%s'",
actual_text, cleaned_answer_text)
continue
else:
start_position = -1
end_position = -1
orig_answer_text = ""
example = SquadExample(
qas_id=qas_id,
question_text=question_text,
doc_tokens=doc_tokens,
orig_answer_text=orig_answer_text,
start_position=start_position,
end_position=end_position,
is_impossible=is_impossible)
examples.append(example)
return examples | [
"def",
"read_squad_examples",
"(",
"input_file",
",",
"is_training",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"input_file",
",",
"\"r\"",
")",
"as",
"reader",
":",
"input_data",
"=",
"json",
".",
"load",
"(",
"reader",
")",
"[",
"\"data\""... | https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/bert/run_squad.py#L227-L306 | |
TGAC/KAT | e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216 | deps/boost/tools/build/src/build/feature.py | python | expand | (properties) | return expand_composites (expanded) | Given a property set which may consist of composite and implicit
properties and combined subfeature values, returns an expanded,
normalized property set with all implicit features expressed
explicitly, all subfeature values individually expressed, and all
components of composite properties expanded. Non-free features
directly expressed in the input properties cause any values of
those features due to composite feature expansion to be dropped. If
two values of a given non-free feature are directly expressed in the
input, an error is issued. | Given a property set which may consist of composite and implicit
properties and combined subfeature values, returns an expanded,
normalized property set with all implicit features expressed
explicitly, all subfeature values individually expressed, and all
components of composite properties expanded. Non-free features
directly expressed in the input properties cause any values of
those features due to composite feature expansion to be dropped. If
two values of a given non-free feature are directly expressed in the
input, an error is issued. | [
"Given",
"a",
"property",
"set",
"which",
"may",
"consist",
"of",
"composite",
"and",
"implicit",
"properties",
"and",
"combined",
"subfeature",
"values",
"returns",
"an",
"expanded",
"normalized",
"property",
"set",
"with",
"all",
"implicit",
"features",
"express... | def expand (properties):
""" Given a property set which may consist of composite and implicit
properties and combined subfeature values, returns an expanded,
normalized property set with all implicit features expressed
explicitly, all subfeature values individually expressed, and all
components of composite properties expanded. Non-free features
directly expressed in the input properties cause any values of
those features due to composite feature expansion to be dropped. If
two values of a given non-free feature are directly expressed in the
input, an error is issued.
"""
if __debug__:
from .property import Property
assert is_iterable_typed(properties, Property)
expanded = expand_subfeatures(properties)
return expand_composites (expanded) | [
"def",
"expand",
"(",
"properties",
")",
":",
"if",
"__debug__",
":",
"from",
".",
"property",
"import",
"Property",
"assert",
"is_iterable_typed",
"(",
"properties",
",",
"Property",
")",
"expanded",
"=",
"expand_subfeatures",
"(",
"properties",
")",
"return",
... | https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/deps/boost/tools/build/src/build/feature.py#L664-L679 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py | python | TarFile.next | (self) | return tarinfo | Return the next member of the archive as a TarInfo object, when
TarFile is opened for reading. Return None if there is no more
available. | Return the next member of the archive as a TarInfo object, when | [
"Return",
"the",
"next",
"member",
"of",
"the",
"archive",
"as",
"a",
"TarInfo",
"object",
"when"
] | def next(self):
"""Return the next member of the archive as a TarInfo object, when
TarFile is opened for reading. Return None if there is no more
available.
"""
self._check("ra")
if self.firstmember is not None:
m = self.firstmember
self.firstmember = None
return m
# Read the next block.
self.fileobj.seek(self.offset)
tarinfo = None
while True:
try:
tarinfo = self.tarinfo.fromtarfile(self)
except EOFHeaderError as e:
if self.ignore_zeros:
self._dbg(2, "0x%X: %s" % (self.offset, e))
self.offset += BLOCKSIZE
continue
except InvalidHeaderError as e:
if self.ignore_zeros:
self._dbg(2, "0x%X: %s" % (self.offset, e))
self.offset += BLOCKSIZE
continue
elif self.offset == 0:
raise ReadError(str(e))
except EmptyHeaderError:
if self.offset == 0:
raise ReadError("empty file")
except TruncatedHeaderError as e:
if self.offset == 0:
raise ReadError(str(e))
except SubsequentHeaderError as e:
raise ReadError(str(e))
break
if tarinfo is not None:
self.members.append(tarinfo)
else:
self._loaded = True
return tarinfo | [
"def",
"next",
"(",
"self",
")",
":",
"self",
".",
"_check",
"(",
"\"ra\"",
")",
"if",
"self",
".",
"firstmember",
"is",
"not",
"None",
":",
"m",
"=",
"self",
".",
"firstmember",
"self",
".",
"firstmember",
"=",
"None",
"return",
"m",
"# Read the next ... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L4827-L4915 | |
kushview/Element | 1cc16380caa2ab79461246ba758b9de1f46db2a5 | waflib/Tools/fc_config.py | python | check_fortran_dummy_main | (self, *k, **kw) | Determines if a main function is needed by compiling a code snippet with
the C compiler and linking it with the Fortran compiler (useful on unix-like systems) | Determines if a main function is needed by compiling a code snippet with
the C compiler and linking it with the Fortran compiler (useful on unix-like systems) | [
"Determines",
"if",
"a",
"main",
"function",
"is",
"needed",
"by",
"compiling",
"a",
"code",
"snippet",
"with",
"the",
"C",
"compiler",
"and",
"linking",
"it",
"with",
"the",
"Fortran",
"compiler",
"(",
"useful",
"on",
"unix",
"-",
"like",
"systems",
")"
] | def check_fortran_dummy_main(self, *k, **kw):
"""
Determines if a main function is needed by compiling a code snippet with
the C compiler and linking it with the Fortran compiler (useful on unix-like systems)
"""
if not self.env.CC:
self.fatal('A c compiler is required for check_fortran_dummy_main')
lst = ['MAIN__', '__MAIN', '_MAIN', 'MAIN_', 'MAIN']
lst.extend([m.lower() for m in lst])
lst.append('')
self.start_msg('Detecting whether we need a dummy main')
for main in lst:
kw['fortran_main'] = main
try:
self.check_cc(
fragment = 'int %s() { return 0; }\n' % (main or 'test'),
features = 'c fcprogram',
mandatory = True
)
if not main:
self.env.FC_MAIN = -1
self.end_msg('no')
else:
self.env.FC_MAIN = main
self.end_msg('yes %s' % main)
break
except self.errors.ConfigurationError:
pass
else:
self.end_msg('not found')
self.fatal('could not detect whether fortran requires a dummy main, see the config.log') | [
"def",
"check_fortran_dummy_main",
"(",
"self",
",",
"*",
"k",
",",
"*",
"*",
"kw",
")",
":",
"if",
"not",
"self",
".",
"env",
".",
"CC",
":",
"self",
".",
"fatal",
"(",
"'A c compiler is required for check_fortran_dummy_main'",
")",
"lst",
"=",
"[",
"'MAI... | https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Tools/fc_config.py#L144-L176 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/io/formats/info.py | python | DataFrameTableBuilder.ids | (self) | return self.info.ids | Dataframe columns. | Dataframe columns. | [
"Dataframe",
"columns",
"."
] | def ids(self) -> Index:
"""Dataframe columns."""
return self.info.ids | [
"def",
"ids",
"(",
"self",
")",
"->",
"Index",
":",
"return",
"self",
".",
"info",
".",
"ids"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/formats/info.py#L496-L498 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py2/IPython/lib/pretty.py | python | RepresentationPrinter._in_deferred_types | (self, cls) | return printer | Check if the given class is specified in the deferred type registry.
Returns the printer from the registry if it exists, and None if the
class is not in the registry. Successful matches will be moved to the
regular type registry for future use. | Check if the given class is specified in the deferred type registry. | [
"Check",
"if",
"the",
"given",
"class",
"is",
"specified",
"in",
"the",
"deferred",
"type",
"registry",
"."
] | def _in_deferred_types(self, cls):
"""
Check if the given class is specified in the deferred type registry.
Returns the printer from the registry if it exists, and None if the
class is not in the registry. Successful matches will be moved to the
regular type registry for future use.
"""
mod = _safe_getattr(cls, '__module__', None)
name = _safe_getattr(cls, '__name__', None)
key = (mod, name)
printer = None
if key in self.deferred_pprinters:
# Move the printer over to the regular registry.
printer = self.deferred_pprinters.pop(key)
self.type_pprinters[cls] = printer
return printer | [
"def",
"_in_deferred_types",
"(",
"self",
",",
"cls",
")",
":",
"mod",
"=",
"_safe_getattr",
"(",
"cls",
",",
"'__module__'",
",",
"None",
")",
"name",
"=",
"_safe_getattr",
"(",
"cls",
",",
"'__name__'",
",",
"None",
")",
"key",
"=",
"(",
"mod",
",",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/lib/pretty.py#L410-L426 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/auibook.py | python | TabNavigatorWindow.__init__ | (self, parent, props) | Default class constructor. Used internally.
:param `parent`: the :class:`TabNavigatorWindow` parent;
:param `props`: the :class:`TabNavigatorProps` object. | Default class constructor. Used internally. | [
"Default",
"class",
"constructor",
".",
"Used",
"internally",
"."
] | def __init__(self, parent, props):
"""
Default class constructor. Used internally.
:param `parent`: the :class:`TabNavigatorWindow` parent;
:param `props`: the :class:`TabNavigatorProps` object.
"""
wx.Dialog.__init__(self, parent, wx.ID_ANY, "", size=props.MinSize, style=0)
self._selectedItem = -1
self._indexMap = []
self._props = props
if not self._props.Icon.IsOk():
self._props.Icon = Mondrian.GetBitmap()
if props.Icon.GetSize() != (16, 16):
img = self._props.Icon.ConvertToImage()
img.Rescale(16, 16, wx.IMAGE_QUALITY_HIGH)
self._props.Icon = wx.BitmapFromImage(img)
if self._props.Font.IsOk():
self.Font = self._props.Font
sz = wx.BoxSizer(wx.VERTICAL)
self._listBox = wx.ListBox(self, wx.ID_ANY,
wx.DefaultPosition,
wx.Size(200, 150), [],
wx.LB_SINGLE | wx.NO_BORDER)
mem_dc = wx.MemoryDC()
mem_dc.SelectObject(wx.EmptyBitmap(1,1))
font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
font.SetWeight(wx.BOLD)
mem_dc.SetFont(font)
panelHeight = mem_dc.GetCharHeight()
panelHeight += 4 # Place a spacer of 2 pixels
# Out signpost bitmap is 24 pixels
if panelHeight < 24:
panelHeight = 24
self._panel = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition,
wx.Size(-1, panelHeight))
sz.Add(self._panel, 0, wx.EXPAND)
sz.Add(self._listBox, 1, wx.EXPAND)
self.SetSizer(sz)
# Connect events to the list box
self._listBox.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
self._listBox.Bind(wx.EVT_NAVIGATION_KEY, self.OnNavigationKey)
self._listBox.Bind(wx.EVT_LISTBOX_DCLICK, self.OnItemSelected)
# Connect paint event to the panel
self._panel.Bind(wx.EVT_PAINT, self.OnPanelPaint)
self._panel.Bind(wx.EVT_ERASE_BACKGROUND, self.OnPanelEraseBg)
self.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE))
self._listBox.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE))
self.PopulateListControl(parent)
self.SetInitialSize(props.MinSize)
self.Centre()
# Set focus on the list box to avoid having to click on it to change
# the tab selection under GTK.
self._listBox.SetFocus() | [
"def",
"__init__",
"(",
"self",
",",
"parent",
",",
"props",
")",
":",
"wx",
".",
"Dialog",
".",
"__init__",
"(",
"self",
",",
"parent",
",",
"wx",
".",
"ID_ANY",
",",
"\"\"",
",",
"size",
"=",
"props",
".",
"MinSize",
",",
"style",
"=",
"0",
")"... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibook.py#L588-L659 | ||
metashell/metashell | f4177e4854ea00c8dbc722cadab26ef413d798ea | 3rd/templight/clang/bindings/python/clang/cindex.py | python | Diagnostic.disable_option | (self) | return _CXString.from_result(disable) | The command-line option that disables this diagnostic. | The command-line option that disables this diagnostic. | [
"The",
"command",
"-",
"line",
"option",
"that",
"disables",
"this",
"diagnostic",
"."
] | def disable_option(self):
"""The command-line option that disables this diagnostic."""
disable = _CXString()
conf.lib.clang_getDiagnosticOption(self, byref(disable))
return _CXString.from_result(disable) | [
"def",
"disable_option",
"(",
"self",
")",
":",
"disable",
"=",
"_CXString",
"(",
")",
"conf",
".",
"lib",
".",
"clang_getDiagnosticOption",
"(",
"self",
",",
"byref",
"(",
"disable",
")",
")",
"return",
"_CXString",
".",
"from_result",
"(",
"disable",
")"... | https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/clang/bindings/python/clang/cindex.py#L475-L479 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/optimize/_linprog.py | python | linprog_terse_callback | (res) | A sample callback function demonstrating the linprog callback interface.
This callback produces brief output to sys.stdout before each iteration
and after the final iteration of the simplex algorithm.
Parameters
----------
res : A `scipy.optimize.OptimizeResult` consisting of the following fields:
x : 1D array
The independent variable vector which optimizes the linear
programming problem.
fun : float
Value of the objective function.
success : bool
True if the algorithm succeeded in finding an optimal solution.
slack : 1D array
The values of the slack variables. Each slack variable corresponds
to an inequality constraint. If the slack is zero, then the
corresponding constraint is active.
con : 1D array
The (nominally zero) residuals of the equality constraints, that is,
``b - A_eq @ x``
phase : int
The phase of the optimization being executed. In phase 1 a basic
feasible solution is sought and the T has an additional row
representing an alternate objective function.
status : int
An integer representing the exit status of the optimization::
0 : Optimization terminated successfully
1 : Iteration limit reached
2 : Problem appears to be infeasible
3 : Problem appears to be unbounded
4 : Serious numerical difficulties encountered
nit : int
The number of iterations performed.
message : str
A string descriptor of the exit status of the optimization. | A sample callback function demonstrating the linprog callback interface.
This callback produces brief output to sys.stdout before each iteration
and after the final iteration of the simplex algorithm. | [
"A",
"sample",
"callback",
"function",
"demonstrating",
"the",
"linprog",
"callback",
"interface",
".",
"This",
"callback",
"produces",
"brief",
"output",
"to",
"sys",
".",
"stdout",
"before",
"each",
"iteration",
"and",
"after",
"the",
"final",
"iteration",
"of... | def linprog_terse_callback(res):
"""
A sample callback function demonstrating the linprog callback interface.
This callback produces brief output to sys.stdout before each iteration
and after the final iteration of the simplex algorithm.
Parameters
----------
res : A `scipy.optimize.OptimizeResult` consisting of the following fields:
x : 1D array
The independent variable vector which optimizes the linear
programming problem.
fun : float
Value of the objective function.
success : bool
True if the algorithm succeeded in finding an optimal solution.
slack : 1D array
The values of the slack variables. Each slack variable corresponds
to an inequality constraint. If the slack is zero, then the
corresponding constraint is active.
con : 1D array
The (nominally zero) residuals of the equality constraints, that is,
``b - A_eq @ x``
phase : int
The phase of the optimization being executed. In phase 1 a basic
feasible solution is sought and the T has an additional row
representing an alternate objective function.
status : int
An integer representing the exit status of the optimization::
0 : Optimization terminated successfully
1 : Iteration limit reached
2 : Problem appears to be infeasible
3 : Problem appears to be unbounded
4 : Serious numerical difficulties encountered
nit : int
The number of iterations performed.
message : str
A string descriptor of the exit status of the optimization.
"""
nit = res['nit']
x = res['x']
if nit == 0:
print("Iter: X:")
print("{0: <5d} ".format(nit), end="")
print(x) | [
"def",
"linprog_terse_callback",
"(",
"res",
")",
":",
"nit",
"=",
"res",
"[",
"'nit'",
"]",
"x",
"=",
"res",
"[",
"'x'",
"]",
"if",
"nit",
"==",
"0",
":",
"print",
"(",
"\"Iter: X:\"",
")",
"print",
"(",
"\"{0: <5d} \"",
".",
"format",
"(",
"nit... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/_linprog.py#L112-L160 | ||
RamadhanAmizudin/malware | 2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1 | GMBot/gmbot/apps/smsg_r/smsapp/command_queue.py | python | get_next_command | (uniq_id) | return vv if vv is None else vv.decode('UTF-8') | Return next command for the phone ID
@param uniq_id: ID of the phone to check
@type uniq_id: str
@return: A command to process client-side
@rtype: str or None | Return next command for the phone ID | [
"Return",
"next",
"command",
"for",
"the",
"phone",
"ID"
] | def get_next_command(uniq_id):
"""
Return next command for the phone ID
@param uniq_id: ID of the phone to check
@type uniq_id: str
@return: A command to process client-side
@rtype: str or None
"""
vv = settings.REDIS.lpop(FMT_QUEUE_NAME.format(uniq_id))
return vv if vv is None else vv.decode('UTF-8') | [
"def",
"get_next_command",
"(",
"uniq_id",
")",
":",
"vv",
"=",
"settings",
".",
"REDIS",
".",
"lpop",
"(",
"FMT_QUEUE_NAME",
".",
"format",
"(",
"uniq_id",
")",
")",
"return",
"vv",
"if",
"vv",
"is",
"None",
"else",
"vv",
".",
"decode",
"(",
"'UTF-8'"... | https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/GMBot/gmbot/apps/smsg_r/smsapp/command_queue.py#L31-L40 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/utils/misc.py | python | dist_location | (dist) | return dist.location | Get the site-packages location of this distribution. Generally
this is dist.location, except in the case of develop-installed
packages, where dist.location is the source code location, and we
want to know where the egg-link file is. | Get the site-packages location of this distribution. Generally
this is dist.location, except in the case of develop-installed
packages, where dist.location is the source code location, and we
want to know where the egg-link file is. | [
"Get",
"the",
"site",
"-",
"packages",
"location",
"of",
"this",
"distribution",
".",
"Generally",
"this",
"is",
"dist",
".",
"location",
"except",
"in",
"the",
"case",
"of",
"develop",
"-",
"installed",
"packages",
"where",
"dist",
".",
"location",
"is",
... | def dist_location(dist):
# type: (Distribution) -> str
"""
Get the site-packages location of this distribution. Generally
this is dist.location, except in the case of develop-installed
packages, where dist.location is the source code location, and we
want to know where the egg-link file is.
"""
egg_link = egg_link_path(dist)
if egg_link:
return egg_link
return dist.location | [
"def",
"dist_location",
"(",
"dist",
")",
":",
"# type: (Distribution) -> str",
"egg_link",
"=",
"egg_link_path",
"(",
"dist",
")",
"if",
"egg_link",
":",
"return",
"egg_link",
"return",
"dist",
".",
"location"
] | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/utils/misc.py#L468-L480 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rosmaster/src/rosmaster/master_api.py | python | ROSMasterHandler.getPid | (self, caller_id) | return 1, "", os.getpid() | Get the PID of this server
@param caller_id: ROS caller id
@type caller_id: str
@return: [1, "", serverProcessPID]
@rtype: [int, str, int] | Get the PID of this server | [
"Get",
"the",
"PID",
"of",
"this",
"server"
] | def getPid(self, caller_id):
"""
Get the PID of this server
@param caller_id: ROS caller id
@type caller_id: str
@return: [1, "", serverProcessPID]
@rtype: [int, str, int]
"""
return 1, "", os.getpid() | [
"def",
"getPid",
"(",
"self",
",",
"caller_id",
")",
":",
"return",
"1",
",",
"\"\"",
",",
"os",
".",
"getpid",
"(",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rosmaster/src/rosmaster/master_api.py#L312-L320 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/cef_parser.py | python | obj_class.get_analysis | (self, value, named = True) | return obj_analysis([self, self.parent], value, named) | Return an analysis of the value based on the class definition
context. | Return an analysis of the value based on the class definition
context. | [
"Return",
"an",
"analysis",
"of",
"the",
"value",
"based",
"on",
"the",
"class",
"definition",
"context",
"."
] | def get_analysis(self, value, named = True):
""" Return an analysis of the value based on the class definition
context.
"""
return obj_analysis([self, self.parent], value, named) | [
"def",
"get_analysis",
"(",
"self",
",",
"value",
",",
"named",
"=",
"True",
")",
":",
"return",
"obj_analysis",
"(",
"[",
"self",
",",
"self",
".",
"parent",
"]",
",",
"value",
",",
"named",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/pristine/cef_source/tools/cef_parser.py#L977-L981 | |
Komnomnomnom/swigibpy | cfd307fdbfaffabc69a2dc037538d7e34a8b8daf | swigibpy.py | python | EClient.reqGlobalCancel | (self) | return _swigibpy.EClient_reqGlobalCancel(self) | reqGlobalCancel(EClient self) | reqGlobalCancel(EClient self) | [
"reqGlobalCancel",
"(",
"EClient",
"self",
")"
] | def reqGlobalCancel(self):
"""reqGlobalCancel(EClient self)"""
return _swigibpy.EClient_reqGlobalCancel(self) | [
"def",
"reqGlobalCancel",
"(",
"self",
")",
":",
"return",
"_swigibpy",
".",
"EClient_reqGlobalCancel",
"(",
"self",
")"
] | https://github.com/Komnomnomnom/swigibpy/blob/cfd307fdbfaffabc69a2dc037538d7e34a8b8daf/swigibpy.py#L1290-L1292 | |
wenwei202/caffe | f54a74abaf6951d8485cbdcfa1d74a4c37839466 | python/caffe/io.py | python | array_to_datum | (arr, label=None) | return datum | Converts a 3-dimensional array to datum. If the array has dtype uint8,
the output data will be encoded as a string. Otherwise, the output data
will be stored in float format. | Converts a 3-dimensional array to datum. If the array has dtype uint8,
the output data will be encoded as a string. Otherwise, the output data
will be stored in float format. | [
"Converts",
"a",
"3",
"-",
"dimensional",
"array",
"to",
"datum",
".",
"If",
"the",
"array",
"has",
"dtype",
"uint8",
"the",
"output",
"data",
"will",
"be",
"encoded",
"as",
"a",
"string",
".",
"Otherwise",
"the",
"output",
"data",
"will",
"be",
"stored"... | def array_to_datum(arr, label=None):
"""Converts a 3-dimensional array to datum. If the array has dtype uint8,
the output data will be encoded as a string. Otherwise, the output data
will be stored in float format.
"""
if arr.ndim != 3:
raise ValueError('Incorrect array shape.')
datum = caffe_pb2.Datum()
datum.channels, datum.height, datum.width = arr.shape
if arr.dtype == np.uint8:
datum.data = arr.tostring()
else:
datum.float_data.extend(arr.flat)
if label is not None:
datum.label = label
return datum | [
"def",
"array_to_datum",
"(",
"arr",
",",
"label",
"=",
"None",
")",
":",
"if",
"arr",
".",
"ndim",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"'Incorrect array shape.'",
")",
"datum",
"=",
"caffe_pb2",
".",
"Datum",
"(",
")",
"datum",
".",
"channels",
... | https://github.com/wenwei202/caffe/blob/f54a74abaf6951d8485cbdcfa1d74a4c37839466/python/caffe/io.py#L66-L81 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/crywaflib/cryengine_modules.py | python | SetupRunTimeLibraries | (ctx, kw, overwrite_settings = None) | Util-function to set the correct flags and defines for the runtime CRT (and to keep non windows defines in sync with windows defines)
By default CryEngine uses the "Multithreaded, dynamic link" variant (/MD) | Util-function to set the correct flags and defines for the runtime CRT (and to keep non windows defines in sync with windows defines)
By default CryEngine uses the "Multithreaded, dynamic link" variant (/MD) | [
"Util",
"-",
"function",
"to",
"set",
"the",
"correct",
"flags",
"and",
"defines",
"for",
"the",
"runtime",
"CRT",
"(",
"and",
"to",
"keep",
"non",
"windows",
"defines",
"in",
"sync",
"with",
"windows",
"defines",
")",
"By",
"default",
"CryEngine",
"uses",... | def SetupRunTimeLibraries(ctx, kw, overwrite_settings = None):
"""
Util-function to set the correct flags and defines for the runtime CRT (and to keep non windows defines in sync with windows defines)
By default CryEngine uses the "Multithreaded, dynamic link" variant (/MD)
"""
runtime_crt = 'dynamic' # Global Setting
if overwrite_settings: # Setting per Task Generator Type
runtime_crt = overwrite_settings
if kw.get('force_static_crt', False): # Setting per Task Generator
runtime_crt = 'static'
if kw.get('force_dynamic_crt', False): # Setting per Task Generator
runtime_crt = 'dynamic'
if runtime_crt != 'static' and runtime_crt != 'dynamic':
ctx.fatal('Invalid Settings: "%s" for runtime_crt' % runtime_crt )
crt_flag = []
config = ctx.GetConfiguration(kw['target'])
if runtime_crt == 'static':
kw['defines'] += [ '_MT' ]
if ctx.env['CC_NAME'] == 'msvc':
if config == 'debug':
crt_flag = [ '/MTd' ]
else:
crt_flag = [ '/MT' ]
else: # runtime_crt == 'dynamic':
kw['defines'] += [ '_MT', '_DLL' ]
if ctx.env['CC_NAME'] == 'msvc':
if config == 'debug':
crt_flag = [ '/MDd' ]
else:
crt_flag = [ '/MD' ]
kw['cflags'] += crt_flag
kw['cxxflags'] += crt_flag | [
"def",
"SetupRunTimeLibraries",
"(",
"ctx",
",",
"kw",
",",
"overwrite_settings",
"=",
"None",
")",
":",
"runtime_crt",
"=",
"'dynamic'",
"# Global Setting",
"if",
"overwrite_settings",
":",
"# Setting per Task Generator Type",
"runtime_crt",
"=",
"overwrite_settings",
... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/crywaflib/cryengine_modules.py#L224-L259 | ||
facebookarchive/LogDevice | ce7726050edc49a1e15d9160e81c890736b779e2 | logdevice/ops/ldops/admin_api.py | python | update_nodes | (
client: AdminAPI, req: UpdateNodesRequest
) | return await client.updateNodes(req) | Wrapper for updateNodes() Thrift method | Wrapper for updateNodes() Thrift method | [
"Wrapper",
"for",
"updateNodes",
"()",
"Thrift",
"method"
] | async def update_nodes(
client: AdminAPI, req: UpdateNodesRequest
) -> UpdateNodesResponse:
"""
Wrapper for updateNodes() Thrift method
"""
return await client.updateNodes(req) | [
"async",
"def",
"update_nodes",
"(",
"client",
":",
"AdminAPI",
",",
"req",
":",
"UpdateNodesRequest",
")",
"->",
"UpdateNodesResponse",
":",
"return",
"await",
"client",
".",
"updateNodes",
"(",
"req",
")"
] | https://github.com/facebookarchive/LogDevice/blob/ce7726050edc49a1e15d9160e81c890736b779e2/logdevice/ops/ldops/admin_api.py#L115-L121 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py | python | Distribution.insert_on | (self, path, loc=None, replace=False) | return | Ensure self.location is on path
If replace=False (default):
- If location is already in path anywhere, do nothing.
- Else:
- If it's an egg and its parent directory is on path,
insert just ahead of the parent.
- Else: add to the end of path.
If replace=True:
- If location is already on path anywhere (not eggs)
or higher priority than its parent (eggs)
do nothing.
- Else:
- If it's an egg and its parent directory is on path,
insert just ahead of the parent,
removing any lower-priority entries.
- Else: add it to the front of path. | Ensure self.location is on path | [
"Ensure",
"self",
".",
"location",
"is",
"on",
"path"
] | def insert_on(self, path, loc=None, replace=False):
"""Ensure self.location is on path
If replace=False (default):
- If location is already in path anywhere, do nothing.
- Else:
- If it's an egg and its parent directory is on path,
insert just ahead of the parent.
- Else: add to the end of path.
If replace=True:
- If location is already on path anywhere (not eggs)
or higher priority than its parent (eggs)
do nothing.
- Else:
- If it's an egg and its parent directory is on path,
insert just ahead of the parent,
removing any lower-priority entries.
- Else: add it to the front of path.
"""
loc = loc or self.location
if not loc:
return
nloc = _normalize_cached(loc)
bdir = os.path.dirname(nloc)
npath = [(p and _normalize_cached(p) or p) for p in path]
for p, item in enumerate(npath):
if item == nloc:
if replace:
break
else:
# don't modify path (even removing duplicates) if
# found and not replace
return
elif item == bdir and self.precedence == EGG_DIST:
# if it's an .egg, give it precedence over its directory
# UNLESS it's already been added to sys.path and replace=False
if (not replace) and nloc in npath[p:]:
return
if path is sys.path:
self.check_version_conflict()
path.insert(p, loc)
npath.insert(p, nloc)
break
else:
if path is sys.path:
self.check_version_conflict()
if replace:
path.insert(0, loc)
else:
path.append(loc)
return
# p is the spot where we found or inserted loc; now remove duplicates
while True:
try:
np = npath.index(nloc, p + 1)
except ValueError:
break
else:
del npath[np], path[np]
# ha!
p = np
return | [
"def",
"insert_on",
"(",
"self",
",",
"path",
",",
"loc",
"=",
"None",
",",
"replace",
"=",
"False",
")",
":",
"loc",
"=",
"loc",
"or",
"self",
".",
"location",
"if",
"not",
"loc",
":",
"return",
"nloc",
"=",
"_normalize_cached",
"(",
"loc",
")",
"... | 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/pkg_resources/__init__.py#L2870-L2936 | |
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | ThirdParty/cinema/paraview/tpl/cinema_python/database/vti_store.py | python | VTIFileStore.load | (self) | loads an existing filestore | loads an existing filestore | [
"loads",
"an",
"existing",
"filestore"
] | def load(self):
"""loads an existing filestore"""
super(VTIFileStore, self).load()
with open(self.__dbfilename, mode="rb") as file:
info_json = json.load(file)
self._set_parameter_list(info_json['arguments'])
self.metadata = info_json['metadata'] | [
"def",
"load",
"(",
"self",
")",
":",
"super",
"(",
"VTIFileStore",
",",
"self",
")",
".",
"load",
"(",
")",
"with",
"open",
"(",
"self",
".",
"__dbfilename",
",",
"mode",
"=",
"\"rb\"",
")",
"as",
"file",
":",
"info_json",
"=",
"json",
".",
"load"... | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/ThirdParty/cinema/paraview/tpl/cinema_python/database/vti_store.py#L45-L51 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/dataset.py | python | InMemoryDataset.set_fleet_send_sleep_seconds | (self, fleet_send_sleep_seconds=0) | Set fleet send sleep time, default is 0
Args:
fleet_send_sleep_seconds(int): fleet send sleep time
Examples:
.. code-block:: python
import paddle.fluid as fluid
dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset")
dataset.set_fleet_send_sleep_seconds(2) | Set fleet send sleep time, default is 0 | [
"Set",
"fleet",
"send",
"sleep",
"time",
"default",
"is",
"0"
] | def set_fleet_send_sleep_seconds(self, fleet_send_sleep_seconds=0):
"""
Set fleet send sleep time, default is 0
Args:
fleet_send_sleep_seconds(int): fleet send sleep time
Examples:
.. code-block:: python
import paddle.fluid as fluid
dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset")
dataset.set_fleet_send_sleep_seconds(2)
"""
self.fleet_send_sleep_seconds = fleet_send_sleep_seconds | [
"def",
"set_fleet_send_sleep_seconds",
"(",
"self",
",",
"fleet_send_sleep_seconds",
"=",
"0",
")",
":",
"self",
".",
"fleet_send_sleep_seconds",
"=",
"fleet_send_sleep_seconds"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/dataset.py#L661-L676 | ||
giuspen/cherrytree | 84712f206478fcf9acf30174009ad28c648c6344 | pygtk2/modules/findreplace.py | python | FindReplace.find_in_all_nodes | (self, father_tree_iter) | Search for a pattern in all the Tree Nodes | Search for a pattern in all the Tree Nodes | [
"Search",
"for",
"a",
"pattern",
"in",
"all",
"the",
"Tree",
"Nodes"
] | def find_in_all_nodes(self, father_tree_iter):
"""Search for a pattern in all the Tree Nodes"""
if not self.from_find_iterated:
self.latest_node_offset = {}
iter_insert = self.dad.curr_buffer.get_iter_at_mark(self.dad.curr_buffer.get_insert())
iter_bound = self.dad.curr_buffer.get_iter_at_mark(self.dad.curr_buffer.get_selection_bound())
entry_predefined_text = self.dad.curr_buffer.get_text(iter_insert, iter_bound)
if entry_predefined_text:
self.search_replace_dict['find'] = entry_predefined_text
if self.replace_active:
if father_tree_iter: title = _("Replace in Selected Node and Subnodes")
else: title = _("Replace in All Nodes")
else:
if father_tree_iter: title = _("Search in Selected Node and Subnodes")
else: title = _("Search in All Nodes")
pattern = self.dialog_search(title, self.replace_active, True, True)
if entry_predefined_text != "":
self.dad.curr_buffer.move_mark(self.dad.curr_buffer.get_insert(), iter_insert)
self.dad.curr_buffer.move_mark(self.dad.curr_buffer.get_selection_bound(), iter_bound)
if pattern:
if not father_tree_iter: self.curr_find = ["in_all_nodes", pattern]
else: self.curr_find = ["in_sel_nod_n_sub", pattern]
else: return
else: pattern = self.curr_find[1]
starting_tree_iter = self.dad.curr_tree_iter.copy()
current_cursor_pos = self.dad.curr_buffer.get_property(cons.STR_CURSOR_POSITION)
forward = self.search_replace_dict['fw']
if self.from_find_back:
forward = not forward
self.from_find_back = False
first_fromsel = self.search_replace_dict['a_ff_fa'] == 1
all_matches = self.search_replace_dict['a_ff_fa'] == 0
if first_fromsel or father_tree_iter:
self.first_useful_node = False # no one node content was parsed yet
node_iter = self.dad.curr_tree_iter.copy()
else:
self.first_useful_node = True # all range will be parsed so no matter
if forward: node_iter = self.dad.treestore.get_iter_first()
else: node_iter = self.dad.get_tree_iter_last_sibling(None)
self.matches_num = 0
if all_matches: self.allmatches_liststore.clear()
config.get_tree_expanded_collapsed_string(self.dad)
# searching start
if self.dad.user_active:
self.dad.user_active = False
user_active_restore = True
else: user_active_restore = False
self.processed_nodes = 0
self.latest_matches = 0
self.dad.update_num_nodes(father_tree_iter)
if all_matches:
self.dad.progressbar.set_text("0")
self.dad.progresstop.show()
self.dad.progressbar.show()
while gtk.events_pending(): gtk.main_iteration()
search_start_time = time.time()
while node_iter:
self.all_matches_first_in_node = True
while self.parse_given_node_content(node_iter, pattern, forward, first_fromsel, all_matches):
self.matches_num += 1
if not all_matches or self.dad.progress_stop: break
self.processed_nodes += 1
if self.matches_num == 1 and not all_matches: break
if father_tree_iter and not self.from_find_iterated: break
last_top_node_iter = node_iter.copy() # we need this if we start from a node that is not in top level
if forward: node_iter = self.dad.treestore.iter_next(node_iter)
else: node_iter = self.dad.get_tree_iter_prev_sibling(self.dad.treestore, node_iter)
if not node_iter and father_tree_iter: break
# code that, in case we start from a node that is not top level, climbs towards the top
while not node_iter:
node_iter = self.dad.treestore.iter_parent(last_top_node_iter)
if node_iter:
last_top_node_iter = node_iter.copy()
# we do not check the parent on purpose, only the uncles in the proper direction
if forward: node_iter = self.dad.treestore.iter_next(node_iter)
else: node_iter = self.dad.get_tree_iter_prev_sibling(self.dad.treestore, node_iter)
else: break
if self.dad.progress_stop: break
if all_matches:
self.update_all_matches_progress()
search_end_time = time.time()
print search_end_time - search_start_time, "sec"
if user_active_restore: self.dad.user_active = True
config.set_tree_expanded_collapsed_string(self.dad)
if not self.matches_num or all_matches:
self.dad.treeview_safe_set_cursor(starting_tree_iter)
self.dad.objects_buffer_refresh()
self.dad.sourceview.grab_focus()
self.dad.curr_buffer.place_cursor(self.dad.curr_buffer.get_iter_at_offset(current_cursor_pos))
self.dad.sourceview.scroll_to_mark(self.dad.curr_buffer.get_insert(), cons.SCROLL_MARGIN)
if not self.matches_num:
support.dialog_info(_("The pattern '%s' was not found") % pattern, self.dad.window)
else:
if all_matches:
self.allmatches_title = str(self.matches_num) + cons.CHAR_SPACE + _("Matches")
self.allmatchesdialog_show()
else:
self.dad.treeview_safe_set_cursor(self.dad.curr_tree_iter)
if self.search_replace_dict['idialog']:
self.iterated_find_dialog()
if all_matches:
assert self.processed_nodes == self.dad.num_nodes or self.dad.progress_stop, "%s != %s" % (self.processed_nodes, self.dad.num_nodes)
self.dad.progresstop.hide()
self.dad.progressbar.hide()
self.dad.progress_stop = False | [
"def",
"find_in_all_nodes",
"(",
"self",
",",
"father_tree_iter",
")",
":",
"if",
"not",
"self",
".",
"from_find_iterated",
":",
"self",
".",
"latest_node_offset",
"=",
"{",
"}",
"iter_insert",
"=",
"self",
".",
"dad",
".",
"curr_buffer",
".",
"get_iter_at_mar... | https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/findreplace.py#L417-L521 | ||
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | clang/tools/scan-build-py/libscanbuild/analyze.py | python | arch_check | (opts, continuation=language_check) | Do run analyzer through one of the given architectures. | Do run analyzer through one of the given architectures. | [
"Do",
"run",
"analyzer",
"through",
"one",
"of",
"the",
"given",
"architectures",
"."
] | def arch_check(opts, continuation=language_check):
""" Do run analyzer through one of the given architectures. """
disabled = frozenset({'ppc', 'ppc64'})
received_list = opts.pop('arch_list')
if received_list:
# filter out disabled architectures and -arch switches
filtered_list = [a for a in received_list if a not in disabled]
if filtered_list:
# There should be only one arch given (or the same multiple
# times). If there are multiple arch are given and are not
# the same, those should not change the pre-processing step.
# But that's the only pass we have before run the analyzer.
current = filtered_list.pop()
logging.debug('analysis, on arch: %s', current)
opts.update({'flags': ['-arch', current] + opts['flags']})
return continuation(opts)
else:
logging.debug('skip analysis, found not supported arch')
return None
else:
logging.debug('analysis, on default arch')
return continuation(opts) | [
"def",
"arch_check",
"(",
"opts",
",",
"continuation",
"=",
"language_check",
")",
":",
"disabled",
"=",
"frozenset",
"(",
"{",
"'ppc'",
",",
"'ppc64'",
"}",
")",
"received_list",
"=",
"opts",
".",
"pop",
"(",
"'arch_list'",
")",
"if",
"received_list",
":"... | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/clang/tools/scan-build-py/libscanbuild/analyze.py#L708-L732 | ||
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/extensions_native/NodePath_extensions.py | python | iPosHpr | (self, other = None) | Deprecated. Set node path's pos and hpr to 0, 0, 0 | Deprecated. Set node path's pos and hpr to 0, 0, 0 | [
"Deprecated",
".",
"Set",
"node",
"path",
"s",
"pos",
"and",
"hpr",
"to",
"0",
"0",
"0"
] | def iPosHpr(self, other = None):
""" Deprecated. Set node path's pos and hpr to 0, 0, 0 """
if __debug__:
warnings.warn("NodePath.iPosHpr() is deprecated.", DeprecationWarning, stacklevel=2)
if other:
self.setPosHpr(other, 0, 0, 0, 0, 0, 0)
else:
self.setPosHpr(0, 0, 0, 0, 0, 0) | [
"def",
"iPosHpr",
"(",
"self",
",",
"other",
"=",
"None",
")",
":",
"if",
"__debug__",
":",
"warnings",
".",
"warn",
"(",
"\"NodePath.iPosHpr() is deprecated.\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"if",
"other",
":",
"self",
".",
... | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/extensions_native/NodePath_extensions.py#L411-L418 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/protobuf/python/google/protobuf/internal/well_known_types.py | python | Any.Unpack | (self, msg) | return True | Unpacks the current Any message into specified message. | Unpacks the current Any message into specified message. | [
"Unpacks",
"the",
"current",
"Any",
"message",
"into",
"specified",
"message",
"."
] | def Unpack(self, msg):
"""Unpacks the current Any message into specified message."""
descriptor = msg.DESCRIPTOR
if not self.Is(descriptor):
return False
msg.ParseFromString(self.value)
return True | [
"def",
"Unpack",
"(",
"self",
",",
"msg",
")",
":",
"descriptor",
"=",
"msg",
".",
"DESCRIPTOR",
"if",
"not",
"self",
".",
"Is",
"(",
"descriptor",
")",
":",
"return",
"False",
"msg",
".",
"ParseFromString",
"(",
"self",
".",
"value",
")",
"return",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/protobuf/python/google/protobuf/internal/well_known_types.py#L77-L83 | |
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exomerge3.py | python | ExodusModel._delete_nodes | (self, node_list) | Delete the given nodes.
This will also delete all references to those nodes in node sets. If a
node is still being used by an element, it cannot be deleted.
Example:
>>> model.delete_nodes([0, 1, 2, 3]) | Delete the given nodes. | [
"Delete",
"the",
"given",
"nodes",
"."
] | def _delete_nodes(self, node_list):
"""
Delete the given nodes.
This will also delete all references to those nodes in node sets. If a
node is still being used by an element, it cannot be deleted.
Example:
>>> model.delete_nodes([0, 1, 2, 3])
"""
node_list = self._remove_duplicates(node_list, preserve_order=False)
# find node mapping
# old node i refers to new node node_map[i]
keep_node = [True] * len(self.nodes)
for node_index in node_list:
keep_node[node_index] = False
node_map = [None] * len(self.nodes)
reverse_node_map = []
next_index = 0
for index, keep in enumerate(keep_node):
if keep:
reverse_node_map.append(index)
node_map[index] = next_index
next_index += 1
# delete nodes
new_nodes = [self.nodes[x] for x in reverse_node_map]
self.nodes = new_nodes
# update connectivity in each element block
for element_block_id in self.get_element_block_ids():
connectivity = self.get_connectivity(element_block_id)
new_connectivity = [node_map[x] for x in connectivity]
if None in new_connectivity:
self._error(
'Node still used.',
'A node in the list of nodes to delete is still '
'used by elements in element block %d and cannot '
'be deleted.' % element_block_id)
connectivity[:] = new_connectivity
# update node fields
for field in list(self.node_fields.values()):
for timestep_index in range(len(self.timesteps)):
new_values = [
field[timestep_index][x] for x in reverse_node_map
]
field[timestep_index] = new_values
# delete nodes from node sets and fields
for node_set_id in self.get_node_set_ids():
members = self.get_node_set_members(node_set_id)
fields = self._get_node_set_fields(node_set_id)
# find new mapping
value_map = []
new_members = []
for index, member in enumerate(members):
if node_map[member] is not None:
value_map.append(index)
new_members.append(node_map[member])
# update member list
members[:] = new_members
# delete these nodes from the field
for field in list(fields.values()):
for timestep_index in range(len(self.timesteps)):
new_values = [field[timestep_index][x] for x in value_map]
field[timestep_index] = new_values | [
"def",
"_delete_nodes",
"(",
"self",
",",
"node_list",
")",
":",
"node_list",
"=",
"self",
".",
"_remove_duplicates",
"(",
"node_list",
",",
"preserve_order",
"=",
"False",
")",
"# find node mapping",
"# old node i refers to new node node_map[i]",
"keep_node",
"=",
"[... | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge3.py#L5470-L5533 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/apitools/samples/storage_sample/storage/storage_v1.py | python | BucketAccessControlsInsert.RunWithArgs | (self, bucket) | Creates a new ACL entry on the specified bucket.
Args:
bucket: The name of the bucket.
Flags:
domain: The domain associated with the entity, if any.
email: The email address associated with the entity, if any.
entity: The entity holding the permission, in one of the following
forms: - user-userId - user-email - group-groupId - group-email -
domain-domain - project-team-projectId - allUsers -
allAuthenticatedUsers Examples: - The user liz@example.com would be
user-liz@example.com. - The group example@googlegroups.com would be
group-example@googlegroups.com. - To refer to all members of the
Google Apps for Business domain example.com, the entity would be
domain-example.com.
entityId: The ID for the entity, if any.
etag: HTTP 1.1 Entity tag for the access-control entry.
id: The ID of the access-control entry.
kind: The kind of item this is. For bucket access control entries, this
is always storage#bucketAccessControl.
projectTeam: The project team associated with the entity, if any.
role: The access permission for the entity. Can be READER, WRITER, or
OWNER.
selfLink: The link to this access-control entry. | Creates a new ACL entry on the specified bucket. | [
"Creates",
"a",
"new",
"ACL",
"entry",
"on",
"the",
"specified",
"bucket",
"."
] | def RunWithArgs(self, bucket):
"""Creates a new ACL entry on the specified bucket.
Args:
bucket: The name of the bucket.
Flags:
domain: The domain associated with the entity, if any.
email: The email address associated with the entity, if any.
entity: The entity holding the permission, in one of the following
forms: - user-userId - user-email - group-groupId - group-email -
domain-domain - project-team-projectId - allUsers -
allAuthenticatedUsers Examples: - The user liz@example.com would be
user-liz@example.com. - The group example@googlegroups.com would be
group-example@googlegroups.com. - To refer to all members of the
Google Apps for Business domain example.com, the entity would be
domain-example.com.
entityId: The ID for the entity, if any.
etag: HTTP 1.1 Entity tag for the access-control entry.
id: The ID of the access-control entry.
kind: The kind of item this is. For bucket access control entries, this
is always storage#bucketAccessControl.
projectTeam: The project team associated with the entity, if any.
role: The access permission for the entity. Can be READER, WRITER, or
OWNER.
selfLink: The link to this access-control entry.
"""
client = GetClientFromFlags()
global_params = GetGlobalParamsFromFlags()
request = messages.BucketAccessControl(
bucket=bucket.decode('utf8'),
)
if FLAGS['domain'].present:
request.domain = FLAGS.domain.decode('utf8')
if FLAGS['email'].present:
request.email = FLAGS.email.decode('utf8')
if FLAGS['entity'].present:
request.entity = FLAGS.entity.decode('utf8')
if FLAGS['entityId'].present:
request.entityId = FLAGS.entityId.decode('utf8')
if FLAGS['etag'].present:
request.etag = FLAGS.etag.decode('utf8')
if FLAGS['id'].present:
request.id = FLAGS.id.decode('utf8')
if FLAGS['kind'].present:
request.kind = FLAGS.kind.decode('utf8')
if FLAGS['projectTeam'].present:
request.projectTeam = apitools_base.JsonToMessage(messages.BucketAccessControl.ProjectTeamValue, FLAGS.projectTeam)
if FLAGS['role'].present:
request.role = FLAGS.role.decode('utf8')
if FLAGS['selfLink'].present:
request.selfLink = FLAGS.selfLink.decode('utf8')
result = client.bucketAccessControls.Insert(
request, global_params=global_params)
print apitools_base_cli.FormatOutput(result) | [
"def",
"RunWithArgs",
"(",
"self",
",",
"bucket",
")",
":",
"client",
"=",
"GetClientFromFlags",
"(",
")",
"global_params",
"=",
"GetGlobalParamsFromFlags",
"(",
")",
"request",
"=",
"messages",
".",
"BucketAccessControl",
"(",
"bucket",
"=",
"bucket",
".",
"d... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/apitools/samples/storage_sample/storage/storage_v1.py#L290-L344 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/utils/_pprint.py | python | _EstimatorPrettyPrinter._pprint_key_val_tuple | (self, object, stream, indent, allowance, context,
level) | Pretty printing for key-value tuples from dict or parameters. | Pretty printing for key-value tuples from dict or parameters. | [
"Pretty",
"printing",
"for",
"key",
"-",
"value",
"tuples",
"from",
"dict",
"or",
"parameters",
"."
] | def _pprint_key_val_tuple(self, object, stream, indent, allowance, context,
level):
"""Pretty printing for key-value tuples from dict or parameters."""
k, v = object
rep = self._repr(k, context, level)
if isinstance(object, KeyValTupleParam):
rep = rep.strip("'")
middle = '='
else:
middle = ': '
stream.write(rep)
stream.write(middle)
self._format(v, stream, indent + len(rep) + len(middle), allowance,
context, level) | [
"def",
"_pprint_key_val_tuple",
"(",
"self",
",",
"object",
",",
"stream",
",",
"indent",
",",
"allowance",
",",
"context",
",",
"level",
")",
":",
"k",
",",
"v",
"=",
"object",
"rep",
"=",
"self",
".",
"_repr",
"(",
"k",
",",
"context",
",",
"level"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/utils/_pprint.py#L309-L322 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/cpplint.py | python | CheckPosixThreading | (filename, clean_lines, linenum, error) | Checks for calls to thread-unsafe functions.
Much code has been originally written without consideration of
multi-threading. Also, engineers are relying on their old experience;
they have learned posix before threading extensions were added. These
tests guide the engineers to use thread-safe functions (when using
posix directly).
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks for calls to thread-unsafe functions. | [
"Checks",
"for",
"calls",
"to",
"thread",
"-",
"unsafe",
"functions",
"."
] | def CheckPosixThreading(filename, clean_lines, linenum, error):
"""Checks for calls to thread-unsafe functions.
Much code has been originally written without consideration of
multi-threading. Also, engineers are relying on their old experience;
they have learned posix before threading extensions were added. These
tests guide the engineers to use thread-safe functions (when using
posix directly).
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]
for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST:
# Additional pattern matching check to confirm that this is the
# function we are looking for
if Search(pattern, line):
error(filename, linenum, 'runtime/threadsafe_fn', 2,
'Consider using ' + multithread_safe_func +
'...) instead of ' + single_thread_func +
'...) for improved thread safety.') | [
"def",
"CheckPosixThreading",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"for",
"single_thread_func",
",",
"multithread_safe_func",
",",
"pattern",
"in",
"_THREADIN... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/cpplint.py#L2221-L2244 | ||
blackberry/Boost | fc90c3fde129c62565c023f091eddc4a7ed9902b | tools/build/v2/build/virtual_target.py | python | NotFileTarget.path | (self) | return None | Returns nothing, to indicate that target path is not known. | Returns nothing, to indicate that target path is not known. | [
"Returns",
"nothing",
"to",
"indicate",
"that",
"target",
"path",
"is",
"not",
"known",
"."
] | def path(self):
"""Returns nothing, to indicate that target path is not known."""
return None | [
"def",
"path",
"(",
"self",
")",
":",
"return",
"None"
] | https://github.com/blackberry/Boost/blob/fc90c3fde129c62565c023f091eddc4a7ed9902b/tools/build/v2/build/virtual_target.py#L719-L721 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/utils/temp_dir.py | python | TempDirectoryTypeRegistry.set_delete | (self, kind, value) | Indicate whether a TempDirectory of the given kind should be
auto-deleted. | Indicate whether a TempDirectory of the given kind should be
auto-deleted. | [
"Indicate",
"whether",
"a",
"TempDirectory",
"of",
"the",
"given",
"kind",
"should",
"be",
"auto",
"-",
"deleted",
"."
] | def set_delete(self, kind, value):
# type: (str, bool) -> None
"""Indicate whether a TempDirectory of the given kind should be
auto-deleted.
"""
self._should_delete[kind] = value | [
"def",
"set_delete",
"(",
"self",
",",
"kind",
",",
"value",
")",
":",
"# type: (str, bool) -> None",
"self",
".",
"_should_delete",
"[",
"kind",
"]",
"=",
"value"
] | 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/_internal/utils/temp_dir.py#L56-L61 | ||
KratosMultiphysics/Kratos | 0000833054ed0503424eb28205d6508d9ca6cbbc | applications/PfemFluidDynamicsApplication/python_scripts/pfem_fluid_dynamics_analysis.py | python | PfemFluidDynamicsAnalysis._CreateSolver | (self) | return solver_wrapper.CreateSolverByParameters(self.model, self.project_parameters["solver_settings"],self.project_parameters["problem_data"]["parallel_type"].GetString()) | Create the solver | Create the solver | [
"Create",
"the",
"solver"
] | def _CreateSolver(self):
"""Create the solver
"""
return solver_wrapper.CreateSolverByParameters(self.model, self.project_parameters["solver_settings"],self.project_parameters["problem_data"]["parallel_type"].GetString()) | [
"def",
"_CreateSolver",
"(",
"self",
")",
":",
"return",
"solver_wrapper",
".",
"CreateSolverByParameters",
"(",
"self",
".",
"model",
",",
"self",
".",
"project_parameters",
"[",
"\"solver_settings\"",
"]",
",",
"self",
".",
"project_parameters",
"[",
"\"problem_... | https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/PfemFluidDynamicsApplication/python_scripts/pfem_fluid_dynamics_analysis.py#L86-L89 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Source/ThirdParty/CEF3/cef_source/tools/gn_args.py | python | ValidateArgs | (args) | Validate GN arg combinations that we know about. Also provide suggestions
where appropriate. | Validate GN arg combinations that we know about. Also provide suggestions
where appropriate. | [
"Validate",
"GN",
"arg",
"combinations",
"that",
"we",
"know",
"about",
".",
"Also",
"provide",
"suggestions",
"where",
"appropriate",
"."
] | def ValidateArgs(args):
"""
Validate GN arg combinations that we know about. Also provide suggestions
where appropriate.
"""
dcheck_always_on = GetArgValue(args, 'dcheck_always_on')
is_asan = GetArgValue(args, 'is_asan')
is_debug = GetArgValue(args, 'is_debug')
is_official_build = GetArgValue(args, 'is_official_build')
target_cpu = GetArgValue(args, 'target_cpu')
if platform == 'linux':
use_sysroot = GetArgValue(args, 'use_sysroot')
if platform == 'windows':
is_win_fastlink = GetArgValue(args, 'is_win_fastlink')
visual_studio_path = GetArgValue(args, 'visual_studio_path')
visual_studio_version = GetArgValue(args, 'visual_studio_version')
visual_studio_runtime_dirs = GetArgValue(args, 'visual_studio_runtime_dirs')
windows_sdk_path = GetArgValue(args, 'windows_sdk_path')
# Target CPU architecture.
# - Windows supports "x86" and "x64".
# - Mac supports only "x64".
# - Linux supports only "x64" unless using a sysroot environment.
if platform == 'macosx':
assert target_cpu == 'x64', 'target_cpu must be "x64"'
elif platform == 'windows':
assert target_cpu in ('x86', 'x64'), 'target_cpu must be "x86" or "x64"'
elif platform == 'linux':
assert target_cpu in ('x86', 'x64', 'arm'), 'target_cpu must be "x86", "x64" or "arm"'
if platform == 'linux':
if target_cpu == 'x86':
assert use_sysroot, 'target_cpu="x86" requires use_sysroot=true'
elif target_cpu == 'arm':
assert use_sysroot, 'target_cpu="arm" requires use_sysroot=true'
# ASAN requires Release builds.
if is_asan:
assert not is_debug, "is_asan=true requires is_debug=false"
if not dcheck_always_on:
msg('is_asan=true recommends dcheck_always_on=true')
# Official build requires Release builds.
if is_official_build:
assert not is_debug, "is_official_build=true requires is_debug=false"
if platform == 'windows':
# Official builds should not use /DEBUG:FASTLINK.
if is_official_build:
assert not is_win_fastlink, "is_official_build=true precludes is_win_fastlink=true"
# Non-official debug builds should use /DEBUG:FASTLINK.
if not is_official_build and is_debug and not is_win_fastlink:
msg('is_official_build=false + is_debug=true recommends is_win_fastlink=true')
# Windows custom toolchain requirements.
#
# Required GN arguments:
# visual_studio_path="<path to VS root>"
# The directory that contains Visual Studio. For example, a subset of
# "C:\Program Files (x86)\Microsoft Visual Studio 14.0".
# visual_studio_version="<VS version>"
# The VS version. For example, "2015".
# visual_studio_runtime_dirs="<path to VS CRT>"
# The directory that contains the VS CRT. For example, the contents of
# "C:\Program Files (x86)\Windows Kits\10\Redist\ucrt\DLLs\x64" plus
# "C:\Windows\System32\ucrtbased.dll"
# windows_sdk_path="<path to WinSDK>"
# The directory that contains the Win SDK. For example, a subset of
# "C:\Program Files (x86)\Windows Kits\10".
#
# Required environment variables:
# DEPOT_TOOLS_WIN_TOOLCHAIN=0
# GYP_MSVS_OVERRIDE_PATH=<path to VS root, must match visual_studio_path>
# GYP_MSVS_VERSION=<VS version, must match visual_studio_version>
# CEF_VCVARS=none
# INCLUDE=<VS include paths>
# LIB=<VS library paths>
# PATH=<VS executable paths>
#
# See comments in gclient_hook.py for environment variable usage.
#
if visual_studio_path != '':
assert visual_studio_version != '', 'visual_studio_path requires visual_studio_version'
assert visual_studio_runtime_dirs != '', 'visual_studio_path requires visual_studio_runtime_dirs'
assert windows_sdk_path != '', 'visual_studio_path requires windows_sdk_path'
assert os.environ.get('DEPOT_TOOLS_WIN_TOOLCHAIN', '') == '0', \
"visual_studio_path requires DEPOT_TOOLS_WIN_TOOLCHAIN=0 env variable"
msvs_path = os.environ.get('GYP_MSVS_OVERRIDE_PATH', '')
assert msvs_path == visual_studio_path and os.path.exists(msvs_path), \
"visual_studio_path requires matching GYP_MSVS_OVERRIDE_PATH env variable"
msvs_version = os.environ.get('GYP_MSVS_VERSION', '')
assert msvs_version == visual_studio_version, \
"visual_studio_version requires matching GYP_MSVS_VERSION env variable"
assert os.environ.get('CEF_VCVARS', '') == 'none', \
"visual_studio_path requires CEF_VCVARS=none env variable"
assert 'INCLUDE' in os.environ \
and 'LIB' in os.environ \
and 'PATH' in os.environ, \
"visual_studio_path requires INCLUDE, LIB and PATH env variables"
# If "%GYP_MSVS_OVERRIDE_PATH%\VC\vcvarsall.bat" exists then environment
# variables will be derived from there and the specified INCLUDE/LIB/PATH
# values will be ignored by Chromium. If this file does not exist then the
# INCLUDE/LIB/PATH values are also required by Chromium.
vcvars_path = os.path.join(msvs_path, 'VC', 'vcvarsall.bat')
if (os.path.exists(vcvars_path)):
msg('INCLUDE/LIB/PATH values will be derived from %s' % vcvars_path) | [
"def",
"ValidateArgs",
"(",
"args",
")",
":",
"dcheck_always_on",
"=",
"GetArgValue",
"(",
"args",
",",
"'dcheck_always_on'",
")",
"is_asan",
"=",
"GetArgValue",
"(",
"args",
",",
"'is_asan'",
")",
"is_debug",
"=",
"GetArgValue",
"(",
"args",
",",
"'is_debug'"... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/cef_source/tools/gn_args.py#L261-L375 | ||
InsightSoftwareConsortium/ITK | 87acfce9a93d928311c38bc371b666b515b9f19d | Modules/ThirdParty/pygccxml/src/pygccxml/declarations/type_traits.py | python | remove_elaborated | (type_) | return type_ | removes type-declaration class-binder :class:`elaborated_t` from
the `type_`
If `type_` is not :class:`elaborated_t`, it will be returned as is | removes type-declaration class-binder :class:`elaborated_t` from
the `type_` | [
"removes",
"type",
"-",
"declaration",
"class",
"-",
"binder",
":",
"class",
":",
"elaborated_t",
"from",
"the",
"type_"
] | def remove_elaborated(type_):
"""removes type-declaration class-binder :class:`elaborated_t` from
the `type_`
If `type_` is not :class:`elaborated_t`, it will be returned as is
"""
nake_type = remove_alias(type_)
if not is_elaborated(nake_type):
return type_
else:
if isinstance(type_, cpptypes.elaborated_t):
type_ = type_.base
return type_ | [
"def",
"remove_elaborated",
"(",
"type_",
")",
":",
"nake_type",
"=",
"remove_alias",
"(",
"type_",
")",
"if",
"not",
"is_elaborated",
"(",
"nake_type",
")",
":",
"return",
"type_",
"else",
":",
"if",
"isinstance",
"(",
"type_",
",",
"cpptypes",
".",
"elab... | https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/type_traits.py#L406-L418 | |
microsoft/onnxruntime | f92e47e95b13a240e37caf7b36577983544f98fc | tools/python/FindOptimizerOpsetVersionUpdatesRequired.py | python | get_call_args_from_file | (filename, function_or_declaration) | return results | Search a file for all function calls or declarations that match the provided name.
Currently requires both the opening '(' and closing ')' to be on the same line. | Search a file for all function calls or declarations that match the provided name.
Currently requires both the opening '(' and closing ')' to be on the same line. | [
"Search",
"a",
"file",
"for",
"all",
"function",
"calls",
"or",
"declarations",
"that",
"match",
"the",
"provided",
"name",
".",
"Currently",
"requires",
"both",
"the",
"opening",
"(",
"and",
"closing",
")",
"to",
"be",
"on",
"the",
"same",
"line",
"."
] | def get_call_args_from_file(filename, function_or_declaration):
"""Search a file for all function calls or declarations that match the provided name.
Currently requires both the opening '(' and closing ')' to be on the same line."""
results = []
with open(filename) as f:
line_num = 0
for line in f.readlines():
for match in re.finditer(function_or_declaration, line):
# check we have both the opening and closing brackets for the function call/declaration.
# if we do we have all the arguments
start = line.find('(', match.end())
end = line.find(')', match.end())
have_all_args = start != -1 and end != -1
if have_all_args:
results.append(line[start + 1: end])
else:
# TODO: handle automatically by merging lines
log.error("Call/Declaration is split over multiple lines. Please check manually."
"File:{} Line:{}".format(filename, line_num))
continue
line_num += 1
return results | [
"def",
"get_call_args_from_file",
"(",
"filename",
",",
"function_or_declaration",
")",
":",
"results",
"=",
"[",
"]",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"line_num",
"=",
"0",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
":",
... | https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/tools/python/FindOptimizerOpsetVersionUpdatesRequired.py#L30-L55 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/binomial.py | python | Binomial.batch_shape | (self, name="batch_shape") | return array_ops.shape(self._mean) | Batch dimensions of this instance as a 1-D int32 `Tensor`.
The product of the dimensions of the `batch_shape` is the number of
independent distributions of this kind the instance represents.
Args:
name: name to give to the op
Returns:
`Tensor` `batch_shape` | Batch dimensions of this instance as a 1-D int32 `Tensor`. | [
"Batch",
"dimensions",
"of",
"this",
"instance",
"as",
"a",
"1",
"-",
"D",
"int32",
"Tensor",
"."
] | def batch_shape(self, name="batch_shape"):
"""Batch dimensions of this instance as a 1-D int32 `Tensor`.
The product of the dimensions of the `batch_shape` is the number of
independent distributions of this kind the instance represents.
Args:
name: name to give to the op
Returns:
`Tensor` `batch_shape`
"""
return array_ops.shape(self._mean) | [
"def",
"batch_shape",
"(",
"self",
",",
"name",
"=",
"\"batch_shape\"",
")",
":",
"return",
"array_ops",
".",
"shape",
"(",
"self",
".",
"_mean",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/binomial.py#L172-L184 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/turtle.py | python | ScrolledCanvas.onResize | (self, event) | self-explanatory | self-explanatory | [
"self",
"-",
"explanatory"
] | def onResize(self, event):
"""self-explanatory"""
self.adjustScrolls() | [
"def",
"onResize",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"adjustScrolls",
"(",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/turtle.py#L418-L420 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/parenmatch.py | python | ParenMatch.paren_closed_event | (self, event) | return | Handle user input of closer. | Handle user input of closer. | [
"Handle",
"user",
"input",
"of",
"closer",
"."
] | def paren_closed_event(self, event):
"Handle user input of closer."
# If user bound non-closer to <<paren-closed>>, quit.
closer = self.text.get("insert-1c")
if closer not in _openers:
return
hp = HyperParser(self.editwin, "insert-1c")
if not hp.is_in_code():
return
indices = hp.get_surrounding_brackets(_openers[closer], True)
self.finish_paren_event(indices)
return | [
"def",
"paren_closed_event",
"(",
"self",
",",
"event",
")",
":",
"# If user bound non-closer to <<paren-closed>>, quit.",
"closer",
"=",
"self",
".",
"text",
".",
"get",
"(",
"\"insert-1c\"",
")",
"if",
"closer",
"not",
"in",
"_openers",
":",
"return",
"hp",
"=... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/parenmatch.py#L83-L94 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/logging/handlers.py | python | SysLogHandler.__init__ | (self, address=('localhost', SYSLOG_UDP_PORT),
facility=LOG_USER, socktype=None) | Initialize a handler.
If address is specified as a string, a UNIX socket is used. To log to a
local syslogd, "SysLogHandler(address="/dev/log")" can be used.
If facility is not specified, LOG_USER is used. If socktype is
specified as socket.SOCK_DGRAM or socket.SOCK_STREAM, that specific
socket type will be used. For Unix sockets, you can also specify a
socktype of None, in which case socket.SOCK_DGRAM will be used, falling
back to socket.SOCK_STREAM. | Initialize a handler. | [
"Initialize",
"a",
"handler",
"."
] | def __init__(self, address=('localhost', SYSLOG_UDP_PORT),
facility=LOG_USER, socktype=None):
"""
Initialize a handler.
If address is specified as a string, a UNIX socket is used. To log to a
local syslogd, "SysLogHandler(address="/dev/log")" can be used.
If facility is not specified, LOG_USER is used. If socktype is
specified as socket.SOCK_DGRAM or socket.SOCK_STREAM, that specific
socket type will be used. For Unix sockets, you can also specify a
socktype of None, in which case socket.SOCK_DGRAM will be used, falling
back to socket.SOCK_STREAM.
"""
logging.Handler.__init__(self)
self.address = address
self.facility = facility
self.socktype = socktype
if isinstance(address, str):
self.unixsocket = True
# Syslog server may be unavailable during handler initialisation.
# C's openlog() function also ignores connection errors.
# Moreover, we ignore these errors while logging, so it not worse
# to ignore it also here.
try:
self._connect_unixsocket(address)
except OSError:
pass
else:
self.unixsocket = False
if socktype is None:
socktype = socket.SOCK_DGRAM
host, port = address
ress = socket.getaddrinfo(host, port, 0, socktype)
if not ress:
raise OSError("getaddrinfo returns an empty list")
for res in ress:
af, socktype, proto, _, sa = res
err = sock = None
try:
sock = socket.socket(af, socktype, proto)
if socktype == socket.SOCK_STREAM:
sock.connect(sa)
break
except OSError as exc:
err = exc
if sock is not None:
sock.close()
if err is not None:
raise err
self.socket = sock
self.socktype = socktype | [
"def",
"__init__",
"(",
"self",
",",
"address",
"=",
"(",
"'localhost'",
",",
"SYSLOG_UDP_PORT",
")",
",",
"facility",
"=",
"LOG_USER",
",",
"socktype",
"=",
"None",
")",
":",
"logging",
".",
"Handler",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/logging/handlers.py#L839-L891 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/probability/bijector/bijector.py | python | Bijector._add_parameter | (self, value, name) | return value_t | Cast `value` to a tensor and add it to `self.default_parameters`.
Add `name` into and `self.parameter_names`. | Cast `value` to a tensor and add it to `self.default_parameters`.
Add `name` into and `self.parameter_names`. | [
"Cast",
"value",
"to",
"a",
"tensor",
"and",
"add",
"it",
"to",
"self",
".",
"default_parameters",
".",
"Add",
"name",
"into",
"and",
"self",
".",
"parameter_names",
"."
] | def _add_parameter(self, value, name):
"""
Cast `value` to a tensor and add it to `self.default_parameters`.
Add `name` into and `self.parameter_names`.
"""
# initialize the attributes if they do not exist yet
if not hasattr(self, 'default_parameters'):
self.default_parameters = []
self.parameter_names = []
self.common_dtype = None
# cast value to a tensor if it is not None
if isinstance(value, bool) or value is None:
raise TypeError("{} cannot be type {}".format(name, type(value)))
value_t = Tensor(value)
# if the bijector's dtype is not specified
if self.dtype is None:
if self.common_dtype is None:
self.common_dtype = value_t.dtype
elif value_t.dtype != self.common_dtype:
raise TypeError(
f"{name} should have the same dtype as other arguments.")
# check if the parameters are casted into float-type tensors
validator.check_type_name(
f"dtype of {name}", value_t.dtype, mstype.float_type, type(self).__name__)
# check if the dtype of the input_parameter agrees with the bijector's dtype
elif value_t.dtype != self.dtype:
raise TypeError(
f"{name} should have the same dtype as the bijector's dtype.")
self.default_parameters += [value,]
self.parameter_names += [name,]
return value_t | [
"def",
"_add_parameter",
"(",
"self",
",",
"value",
",",
"name",
")",
":",
"# initialize the attributes if they do not exist yet",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'default_parameters'",
")",
":",
"self",
".",
"default_parameters",
"=",
"[",
"]",
"self",... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/bijector/bijector.py#L155-L185 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | examples/benchmark.py | python | benchmark_ungraph | (Graph) | return results | Perform benchmark tests for Undirected Graphs | Perform benchmark tests for Undirected Graphs | [
"Perform",
"benchmark",
"tests",
"for",
"Undirected",
"Graphs"
] | def benchmark_ungraph(Graph):
'''
Perform benchmark tests for Undirected Graphs
'''
results = {}
results['num_nodes'] = Graph.GetNodes()
results['num_edges'] = Graph.GetEdges()
for degree in range(0,11):
num = snap.NodesGTEDegree_PUNGraph(Graph, degree)
percent_deg = float(num) / results['num_nodes']
results['deg_gte_%d' % degree] = num
results['deg_gte_%d_percent' % degree] = percent_deg
# Check for over-weighted nodes
results['max_degree'] = snap.MxDegree_PUNGraph(Graph)
num = snap.NodesGTEDegree_PUNGraph(Graph, results['max_degree'])
results['max_degree_num'] = num
results['max_wcc_percent'] = snap.MxWccSz_PUNGraph(Graph) \
/ results['num_nodes']
results['max_scc_percent'] = snap.MxSccSz_PUNGraph(Graph).GetNodes() \
/ results['num_nodes']
# TODO: Calculate graph skew
return results | [
"def",
"benchmark_ungraph",
"(",
"Graph",
")",
":",
"results",
"=",
"{",
"}",
"results",
"[",
"'num_nodes'",
"]",
"=",
"Graph",
".",
"GetNodes",
"(",
")",
"results",
"[",
"'num_edges'",
"]",
"=",
"Graph",
".",
"GetEdges",
"(",
")",
"for",
"degree",
"in... | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/examples/benchmark.py#L109-L135 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/caching.py | python | Cache.load_overload | (self, sig, target_context) | Load and recreate the cached object for the given signature,
using the *target_context*. | Load and recreate the cached object for the given signature,
using the *target_context*. | [
"Load",
"and",
"recreate",
"the",
"cached",
"object",
"for",
"the",
"given",
"signature",
"using",
"the",
"*",
"target_context",
"*",
"."
] | def load_overload(self, sig, target_context):
"""
Load and recreate the cached object for the given signature,
using the *target_context*.
"""
# Refresh the context to ensure it is initialized
target_context.refresh()
with self._guard_against_spurious_io_errors():
return self._load_overload(sig, target_context) | [
"def",
"load_overload",
"(",
"self",
",",
"sig",
",",
"target_context",
")",
":",
"# Refresh the context to ensure it is initialized",
"target_context",
".",
"refresh",
"(",
")",
"with",
"self",
".",
"_guard_against_spurious_io_errors",
"(",
")",
":",
"return",
"self"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/caching.py#L640-L648 | ||
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | grc/gui/BlockTreeWindow.py | python | BlockTreeWindow.update_docs | (self) | Update the documentation column of every block | Update the documentation column of every block | [
"Update",
"the",
"documentation",
"column",
"of",
"every",
"block"
] | def update_docs(self):
"""Update the documentation column of every block"""
def update_doc(model, _, iter_):
key = model.get_value(iter_, KEY_INDEX)
if not key:
return # category node, no doc string
block = self.platform.blocks[key]
model.set_value(iter_, DOC_INDEX, _format_doc(block.documentation))
self.treestore.foreach(update_doc)
self.treestore_search.foreach(update_doc) | [
"def",
"update_docs",
"(",
"self",
")",
":",
"def",
"update_doc",
"(",
"model",
",",
"_",
",",
"iter_",
")",
":",
"key",
"=",
"model",
".",
"get_value",
"(",
"iter_",
",",
"KEY_INDEX",
")",
"if",
"not",
"key",
":",
"return",
"# category node, no doc stri... | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/gui/BlockTreeWindow.py#L179-L190 | ||
taichi-dev/taichi | 973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6 | python/taichi/lang/ops.py | python | floordiv | (a, b) | return _binary_operation(_ti_core.expr_floordiv, _bt_ops_mod.floordiv, a,
b) | The floor division function.
Args:
a (Union[:class:`~taichi.lang.expr.Expr`, :class:`~taichi.lang.matrix.Matrix`]): A number or a matrix.
b (Union[:class:`~taichi.lang.expr.Expr`, :class:`~taichi.lang.matrix.Matrix`]): A number or a matrix with elements not equal to zero.
Returns:
The floor function of `a` divided by `b`. | The floor division function. | [
"The",
"floor",
"division",
"function",
"."
] | def floordiv(a, b):
"""The floor division function.
Args:
a (Union[:class:`~taichi.lang.expr.Expr`, :class:`~taichi.lang.matrix.Matrix`]): A number or a matrix.
b (Union[:class:`~taichi.lang.expr.Expr`, :class:`~taichi.lang.matrix.Matrix`]): A number or a matrix with elements not equal to zero.
Returns:
The floor function of `a` divided by `b`.
"""
return _binary_operation(_ti_core.expr_floordiv, _bt_ops_mod.floordiv, a,
b) | [
"def",
"floordiv",
"(",
"a",
",",
"b",
")",
":",
"return",
"_binary_operation",
"(",
"_ti_core",
".",
"expr_floordiv",
",",
"_bt_ops_mod",
".",
"floordiv",
",",
"a",
",",
"b",
")"
] | https://github.com/taichi-dev/taichi/blob/973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6/python/taichi/lang/ops.py#L478-L489 | |
KhronosGroup/Vulkan-Headers | b32da5329b50e3cb96229aaecba9ded032fe29cc | registry/generator.py | python | OutputGenerator.genEnum | (self, enuminfo, typeName, alias) | Generate interface for an enum (constant).
- enuminfo - EnumInfo for an enum
- name - enum name
Extend to generate as desired in your derived class. | Generate interface for an enum (constant). | [
"Generate",
"interface",
"for",
"an",
"enum",
"(",
"constant",
")",
"."
] | def genEnum(self, enuminfo, typeName, alias):
"""Generate interface for an enum (constant).
- enuminfo - EnumInfo for an enum
- name - enum name
Extend to generate as desired in your derived class."""
self.validateFeature('enum', typeName) | [
"def",
"genEnum",
"(",
"self",
",",
"enuminfo",
",",
"typeName",
",",
"alias",
")",
":",
"self",
".",
"validateFeature",
"(",
"'enum'",
",",
"typeName",
")"
] | https://github.com/KhronosGroup/Vulkan-Headers/blob/b32da5329b50e3cb96229aaecba9ded032fe29cc/registry/generator.py#L897-L904 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | SpinCtrl.GetClassDefaultAttributes | (*args, **kwargs) | return _controls_.SpinCtrl_GetClassDefaultAttributes(*args, **kwargs) | GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this. | GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes | [
"GetClassDefaultAttributes",
"(",
"int",
"variant",
"=",
"WINDOW_VARIANT_NORMAL",
")",
"-",
">",
"VisualAttributes"
] | def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.SpinCtrl_GetClassDefaultAttributes(*args, **kwargs) | [
"def",
"GetClassDefaultAttributes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"SpinCtrl_GetClassDefaultAttributes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L2392-L2407 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/propgrid.py | python | PropertyGridInterface.Collapse | (*args, **kwargs) | return _propgrid.PropertyGridInterface_Collapse(*args, **kwargs) | Collapse(self, PGPropArg id) -> bool | Collapse(self, PGPropArg id) -> bool | [
"Collapse",
"(",
"self",
"PGPropArg",
"id",
")",
"-",
">",
"bool"
] | def Collapse(*args, **kwargs):
"""Collapse(self, PGPropArg id) -> bool"""
return _propgrid.PropertyGridInterface_Collapse(*args, **kwargs) | [
"def",
"Collapse",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGridInterface_Collapse",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L1119-L1121 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pep517/wrappers.py | python | Pep517HookCaller.build_wheel | (
self, wheel_directory, config_settings=None,
metadata_directory=None) | return self._call_hook('build_wheel', {
'wheel_directory': abspath(wheel_directory),
'config_settings': config_settings,
'metadata_directory': metadata_directory,
}) | Build a wheel from this project.
Returns the name of the newly created file.
In general, this will call the 'build_wheel' hook in the backend.
However, if that was previously called by
'prepare_metadata_for_build_wheel', and the same metadata_directory is
used, the previously built wheel will be copied to wheel_directory. | Build a wheel from this project. | [
"Build",
"a",
"wheel",
"from",
"this",
"project",
"."
] | def build_wheel(
self, wheel_directory, config_settings=None,
metadata_directory=None):
"""Build a wheel from this project.
Returns the name of the newly created file.
In general, this will call the 'build_wheel' hook in the backend.
However, if that was previously called by
'prepare_metadata_for_build_wheel', and the same metadata_directory is
used, the previously built wheel will be copied to wheel_directory.
"""
if metadata_directory is not None:
metadata_directory = abspath(metadata_directory)
return self._call_hook('build_wheel', {
'wheel_directory': abspath(wheel_directory),
'config_settings': config_settings,
'metadata_directory': metadata_directory,
}) | [
"def",
"build_wheel",
"(",
"self",
",",
"wheel_directory",
",",
"config_settings",
"=",
"None",
",",
"metadata_directory",
"=",
"None",
")",
":",
"if",
"metadata_directory",
"is",
"not",
"None",
":",
"metadata_directory",
"=",
"abspath",
"(",
"metadata_directory",... | 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/pep517/wrappers.py#L199-L217 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/aui/auibar.py | python | AuiToolBar.OnLeaveWindow | (self, event) | Handles the ``wx.EVT_LEAVE_WINDOW`` event for :class:`AuiToolBar`.
:param `event`: a :class:`MouseEvent` event to be processed. | Handles the ``wx.EVT_LEAVE_WINDOW`` event for :class:`AuiToolBar`. | [
"Handles",
"the",
"wx",
".",
"EVT_LEAVE_WINDOW",
"event",
"for",
":",
"class",
":",
"AuiToolBar",
"."
] | def OnLeaveWindow(self, event):
"""
Handles the ``wx.EVT_LEAVE_WINDOW`` event for :class:`AuiToolBar`.
:param `event`: a :class:`MouseEvent` event to be processed.
"""
self.RefreshOverflowState()
self.SetHoverItem(None)
self.SetPressedItem(None)
self._tip_item = None
self.StopPreviewTimer() | [
"def",
"OnLeaveWindow",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"RefreshOverflowState",
"(",
")",
"self",
".",
"SetHoverItem",
"(",
"None",
")",
"self",
".",
"SetPressedItem",
"(",
"None",
")",
"self",
".",
"_tip_item",
"=",
"None",
"self",
"."... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/auibar.py#L3902-L3914 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/resmokelib/utils/history.py | python | _get_location | () | return "".join(traceback.format_stack(limit=STACK_LIMIT + 2)[:-2]) | Return the location as a string, accounting for this function and the parent in the stack. | Return the location as a string, accounting for this function and the parent in the stack. | [
"Return",
"the",
"location",
"as",
"a",
"string",
"accounting",
"for",
"this",
"function",
"and",
"the",
"parent",
"in",
"the",
"stack",
"."
] | def _get_location():
"""Return the location as a string, accounting for this function and the parent in the stack."""
return "".join(traceback.format_stack(limit=STACK_LIMIT + 2)[:-2]) | [
"def",
"_get_location",
"(",
")",
":",
"return",
"\"\"",
".",
"join",
"(",
"traceback",
".",
"format_stack",
"(",
"limit",
"=",
"STACK_LIMIT",
"+",
"2",
")",
"[",
":",
"-",
"2",
"]",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/utils/history.py#L384-L386 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/distutils/misc_util.py | python | generate_config_py | (target) | return target | Generate config.py file containing system_info information
used during building the package.
Usage:
config['py_modules'].append((packagename, '__config__',generate_config_py)) | Generate config.py file containing system_info information
used during building the package. | [
"Generate",
"config",
".",
"py",
"file",
"containing",
"system_info",
"information",
"used",
"during",
"building",
"the",
"package",
"."
] | def generate_config_py(target):
"""Generate config.py file containing system_info information
used during building the package.
Usage:
config['py_modules'].append((packagename, '__config__',generate_config_py))
"""
from numpy.distutils.system_info import system_info
from distutils.dir_util import mkpath
mkpath(os.path.dirname(target))
with open(target, 'w') as f:
f.write('# This file is generated by numpy\'s %s\n' % (os.path.basename(sys.argv[0])))
f.write('# It contains system_info results at the time of building this package.\n')
f.write('__all__ = ["get_info","show"]\n\n')
# For gfortran+msvc combination, extra shared libraries may exist
f.write(textwrap.dedent("""
import os
import sys
extra_dll_dir = os.path.join(os.path.dirname(__file__), '.libs')
if sys.platform == 'win32' and os.path.isdir(extra_dll_dir):
if sys.version_info >= (3, 8):
os.add_dll_directory(extra_dll_dir)
else:
os.environ.setdefault('PATH', '')
os.environ['PATH'] += os.pathsep + extra_dll_dir
"""))
for k, i in system_info.saved_results.items():
f.write('%s=%r\n' % (k, i))
f.write(textwrap.dedent(r'''
def get_info(name):
g = globals()
return g.get(name, g.get(name + "_info", {}))
def show():
"""
Show libraries in the system on which NumPy was built.
Print information about various resources (libraries, library
directories, include directories, etc.) in the system on which
NumPy was built.
See Also
--------
get_include : Returns the directory containing NumPy C
header files.
Notes
-----
Classes specifying the information to be printed are defined
in the `numpy.distutils.system_info` module.
Information may include:
* ``language``: language used to write the libraries (mostly
C or f77)
* ``libraries``: names of libraries found in the system
* ``library_dirs``: directories containing the libraries
* ``include_dirs``: directories containing library header files
* ``src_dirs``: directories containing library source files
* ``define_macros``: preprocessor macros used by
``distutils.setup``
* ``baseline``: minimum CPU features required
* ``found``: dispatched features supported in the system
* ``not found``: dispatched features that are not supported
in the system
Examples
--------
>>> import numpy as np
>>> np.show_config()
blas_opt_info:
language = c
define_macros = [('HAVE_CBLAS', None)]
libraries = ['openblas', 'openblas']
library_dirs = ['/usr/local/lib']
"""
from numpy.core._multiarray_umath import (
__cpu_features__, __cpu_baseline__, __cpu_dispatch__
)
for name,info_dict in globals().items():
if name[0] == "_" or type(info_dict) is not type({}): continue
print(name + ":")
if not info_dict:
print(" NOT AVAILABLE")
for k,v in info_dict.items():
v = str(v)
if k == "sources" and len(v) > 200:
v = v[:60] + " ...\n... " + v[-60:]
print(" %s = %s" % (k,v))
features_found, features_not_found = [], []
for feature in __cpu_dispatch__:
if __cpu_features__[feature]:
features_found.append(feature)
else:
features_not_found.append(feature)
print("Supported SIMD extensions in this NumPy install:")
print(" baseline = %s" % (','.join(__cpu_baseline__)))
print(" found = %s" % (','.join(features_found)))
print(" not found = %s" % (','.join(features_not_found)))
'''))
return target | [
"def",
"generate_config_py",
"(",
"target",
")",
":",
"from",
"numpy",
".",
"distutils",
".",
"system_info",
"import",
"system_info",
"from",
"distutils",
".",
"dir_util",
"import",
"mkpath",
"mkpath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"target",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/distutils/misc_util.py#L2292-L2401 | |
yrnkrn/zapcc | c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50 | tools/clang/bindings/python/clang/cindex.py | python | File.name | (self) | return conf.lib.clang_getFileName(self) | Return the complete file and path name of the file. | Return the complete file and path name of the file. | [
"Return",
"the",
"complete",
"file",
"and",
"path",
"name",
"of",
"the",
"file",
"."
] | def name(self):
"""Return the complete file and path name of the file."""
return conf.lib.clang_getFileName(self) | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getFileName",
"(",
"self",
")"
] | https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/tools/clang/bindings/python/clang/cindex.py#L3072-L3074 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/gyp/pylib/gyp/MSVSToolFile.py | python | Writer.AddCustomBuildRule | (
self, name, cmd, description, additional_dependencies, outputs, extensions
) | Adds a rule to the tool file.
Args:
name: Name of the rule.
description: Description of the rule.
cmd: Command line of the rule.
additional_dependencies: other files which may trigger the rule.
outputs: outputs of the rule.
extensions: extensions handled by the rule. | Adds a rule to the tool file. | [
"Adds",
"a",
"rule",
"to",
"the",
"tool",
"file",
"."
] | def AddCustomBuildRule(
self, name, cmd, description, additional_dependencies, outputs, extensions
):
"""Adds a rule to the tool file.
Args:
name: Name of the rule.
description: Description of the rule.
cmd: Command line of the rule.
additional_dependencies: other files which may trigger the rule.
outputs: outputs of the rule.
extensions: extensions handled by the rule.
"""
rule = [
"CustomBuildRule",
{
"Name": name,
"ExecutionDescription": description,
"CommandLine": cmd,
"Outputs": ";".join(outputs),
"FileExtensions": ";".join(extensions),
"AdditionalDependencies": ";".join(additional_dependencies),
},
]
self.rules_section.append(rule) | [
"def",
"AddCustomBuildRule",
"(",
"self",
",",
"name",
",",
"cmd",
",",
"description",
",",
"additional_dependencies",
",",
"outputs",
",",
"extensions",
")",
":",
"rule",
"=",
"[",
"\"CustomBuildRule\"",
",",
"{",
"\"Name\"",
":",
"name",
",",
"\"ExecutionDes... | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/MSVSToolFile.py#L24-L48 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/debug/cli/debugger_cli_common.py | python | TabCompletionRegistry._common_prefix | (self, m) | return s1 | Given a list of str, returns the longest common prefix.
Args:
m: (list of str) A list of strings.
Returns:
(str) The longest common prefix. | Given a list of str, returns the longest common prefix. | [
"Given",
"a",
"list",
"of",
"str",
"returns",
"the",
"longest",
"common",
"prefix",
"."
] | def _common_prefix(self, m):
"""Given a list of str, returns the longest common prefix.
Args:
m: (list of str) A list of strings.
Returns:
(str) The longest common prefix.
"""
if not m:
return ""
s1 = min(m)
s2 = max(m)
for i, c in enumerate(s1):
if c != s2[i]:
return s1[:i]
return s1 | [
"def",
"_common_prefix",
"(",
"self",
",",
"m",
")",
":",
"if",
"not",
"m",
":",
"return",
"\"\"",
"s1",
"=",
"min",
"(",
"m",
")",
"s2",
"=",
"max",
"(",
"m",
")",
"for",
"i",
",",
"c",
"in",
"enumerate",
"(",
"s1",
")",
":",
"if",
"c",
"!... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/debug/cli/debugger_cli_common.py#L670-L688 | |
NVIDIA-Merlin/HugeCTR | b596bcc44e14bb0c62c4f7e9c0b55301d94f2154 | sparse_operation_kit/sparse_operation_kit/saver/Saver.py | python | Saver.load_embedding_values | (self, embedding_variable, tensors) | This function is used to assign embedding_variable's value with tf.Tensors.
When multiple CPU processes is used, this function must be called
within each CPU processes.
Parameters
----------
embedding_variable: sok.EmbeddingVariable, tf.DistributedVariable
Which embedding_variable's value will be assigned.
tensors: tf.Tensor, list of tf.Tensor, tuple of tf.Tensor
Each tf.Tensor must be 2-rank and the shape must be `[None, embedding_vec_size]`,
where the `embedding_vec_size` must be equal to that of embedding_variable's.
All tf.Tensors make up to a big tensor, which just like they are stacked. For example:
`[tf.Tensor(shape=(bs_0, embedding_vec_size)), tf.Tensor(shape=(bs_1, embedding_vec_size)),\
tf.Tensor(shape=(bs_2, embedding_vec_size))]` will be treated as
`tf.Tensor(shape=(bs_0 + bs_1 + bs_2, embedding_vec_size))`.
Returns
-------
status: tf.Tensor
If this op executed successfully, then 'OK' will be returned. | This function is used to assign embedding_variable's value with tf.Tensors. | [
"This",
"function",
"is",
"used",
"to",
"assign",
"embedding_variable",
"s",
"value",
"with",
"tf",
".",
"Tensors",
"."
] | def load_embedding_values(self, embedding_variable, tensors):
"""
This function is used to assign embedding_variable's value with tf.Tensors.
When multiple CPU processes is used, this function must be called
within each CPU processes.
Parameters
----------
embedding_variable: sok.EmbeddingVariable, tf.DistributedVariable
Which embedding_variable's value will be assigned.
tensors: tf.Tensor, list of tf.Tensor, tuple of tf.Tensor
Each tf.Tensor must be 2-rank and the shape must be `[None, embedding_vec_size]`,
where the `embedding_vec_size` must be equal to that of embedding_variable's.
All tf.Tensors make up to a big tensor, which just like they are stacked. For example:
`[tf.Tensor(shape=(bs_0, embedding_vec_size)), tf.Tensor(shape=(bs_1, embedding_vec_size)),\
tf.Tensor(shape=(bs_2, embedding_vec_size))]` will be treated as
`tf.Tensor(shape=(bs_0 + bs_1 + bs_2, embedding_vec_size))`.
Returns
-------
status: tf.Tensor
If this op executed successfully, then 'OK' will be returned.
"""
if kit_lib.in_tensorflow2():
context = ops.NullContextmanager
initializers = None
else:
context = ops.control_dependencies
# in case the embedding layer has not been created
collections = ops.get_collection(GraphKeys.SparseOperationKitEmbeddingLayers)
initializers = [collect.initializer for collect in collections]
if isinstance(tensors, list) or isinstance(tensors, tuple):
# stack those tensors along dim-0
tensors = array_ops.concat(tensors, axis=0)
with context(initializers):
if hasattr(embedding_variable, "emb_handle"):
# horovod branch
return kit_lib.load_embedding_values(embedding_variable.emb_handle, tensors)
else:
# strategy branch
return kit_lib.load_embedding_values(embedding_variable.values[0].emb_handle, tensors) | [
"def",
"load_embedding_values",
"(",
"self",
",",
"embedding_variable",
",",
"tensors",
")",
":",
"if",
"kit_lib",
".",
"in_tensorflow2",
"(",
")",
":",
"context",
"=",
"ops",
".",
"NullContextmanager",
"initializers",
"=",
"None",
"else",
":",
"context",
"=",... | https://github.com/NVIDIA-Merlin/HugeCTR/blob/b596bcc44e14bb0c62c4f7e9c0b55301d94f2154/sparse_operation_kit/sparse_operation_kit/saver/Saver.py#L98-L141 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/roc/api.py | python | finegrain_array | (shape, dtype=np.float, strides=None, order='C') | return _host_array(finegrain=False, shape=shape, dtype=dtype,
strides=strides, order=order) | finegrain_array(shape, dtype=np.float, strides=None, order='C')
Similar to np.empty(). | finegrain_array(shape, dtype=np.float, strides=None, order='C') | [
"finegrain_array",
"(",
"shape",
"dtype",
"=",
"np",
".",
"float",
"strides",
"=",
"None",
"order",
"=",
"C",
")"
] | def finegrain_array(shape, dtype=np.float, strides=None, order='C'):
"""finegrain_array(shape, dtype=np.float, strides=None, order='C')
Similar to np.empty().
"""
return _host_array(finegrain=False, shape=shape, dtype=dtype,
strides=strides, order=order) | [
"def",
"finegrain_array",
"(",
"shape",
",",
"dtype",
"=",
"np",
".",
"float",
",",
"strides",
"=",
"None",
",",
"order",
"=",
"'C'",
")",
":",
"return",
"_host_array",
"(",
"finegrain",
"=",
"False",
",",
"shape",
"=",
"shape",
",",
"dtype",
"=",
"d... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/roc/api.py#L190-L196 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/ndarray/numpy/_op.py | python | column_stack | (tup) | return _api_internal.column_stack(*tup) | Stack 1-D arrays as columns into a 2-D array.
Take a sequence of 1-D arrays and stack them as columns
to make a single 2-D array. 2-D arrays are stacked as-is,
just like with `hstack`. 1-D arrays are turned into 2-D columns
first.
Returns
--------
stacked : 2-D array
The array formed by stacking the given arrays.
See Also
--------
stack, hstack, vstack, concatenate
Examples
--------
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.column_stack((a,b))
array([[1., 2.],
[2., 3.],
[3., 4.]]) | Stack 1-D arrays as columns into a 2-D array.
Take a sequence of 1-D arrays and stack them as columns
to make a single 2-D array. 2-D arrays are stacked as-is,
just like with `hstack`. 1-D arrays are turned into 2-D columns
first. | [
"Stack",
"1",
"-",
"D",
"arrays",
"as",
"columns",
"into",
"a",
"2",
"-",
"D",
"array",
".",
"Take",
"a",
"sequence",
"of",
"1",
"-",
"D",
"arrays",
"and",
"stack",
"them",
"as",
"columns",
"to",
"make",
"a",
"single",
"2",
"-",
"D",
"array",
"."... | def column_stack(tup):
"""
Stack 1-D arrays as columns into a 2-D array.
Take a sequence of 1-D arrays and stack them as columns
to make a single 2-D array. 2-D arrays are stacked as-is,
just like with `hstack`. 1-D arrays are turned into 2-D columns
first.
Returns
--------
stacked : 2-D array
The array formed by stacking the given arrays.
See Also
--------
stack, hstack, vstack, concatenate
Examples
--------
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.column_stack((a,b))
array([[1., 2.],
[2., 3.],
[3., 4.]])
"""
return _api_internal.column_stack(*tup) | [
"def",
"column_stack",
"(",
"tup",
")",
":",
"return",
"_api_internal",
".",
"column_stack",
"(",
"*",
"tup",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/numpy/_op.py#L4842-L4868 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/psutil/_pswindows.py | python | swap_memory | () | return _common.sswap(total, used, free, percent, 0, 0) | Swap system memory as a (total, used, free, sin, sout) tuple. | Swap system memory as a (total, used, free, sin, sout) tuple. | [
"Swap",
"system",
"memory",
"as",
"a",
"(",
"total",
"used",
"free",
"sin",
"sout",
")",
"tuple",
"."
] | def swap_memory():
"""Swap system memory as a (total, used, free, sin, sout) tuple."""
mem = cext.virtual_mem()
total = mem[2]
free = mem[3]
used = total - free
percent = usage_percent(used, total, round_=1)
return _common.sswap(total, used, free, percent, 0, 0) | [
"def",
"swap_memory",
"(",
")",
":",
"mem",
"=",
"cext",
".",
"virtual_mem",
"(",
")",
"total",
"=",
"mem",
"[",
"2",
"]",
"free",
"=",
"mem",
"[",
"3",
"]",
"used",
"=",
"total",
"-",
"free",
"percent",
"=",
"usage_percent",
"(",
"used",
",",
"t... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/psutil/_pswindows.py#L241-L248 | |
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/tools/gyp/pylib/gyp/generator/msvs.py | python | _GetMSBuildPropertyGroup | (spec, label, properties) | return [group] | Returns a PropertyGroup definition for the specified properties.
Arguments:
spec: The target project dict.
label: An optional label for the PropertyGroup.
properties: The dictionary to be converted. The key is the name of the
property. The value is itself a dictionary; its key is the value and
the value a list of condition for which this value is true. | Returns a PropertyGroup definition for the specified properties. | [
"Returns",
"a",
"PropertyGroup",
"definition",
"for",
"the",
"specified",
"properties",
"."
] | def _GetMSBuildPropertyGroup(spec, label, properties):
"""Returns a PropertyGroup definition for the specified properties.
Arguments:
spec: The target project dict.
label: An optional label for the PropertyGroup.
properties: The dictionary to be converted. The key is the name of the
property. The value is itself a dictionary; its key is the value and
the value a list of condition for which this value is true.
"""
group = ['PropertyGroup']
if label:
group.append({'Label': label})
num_configurations = len(spec['configurations'])
def GetEdges(node):
# Use a definition of edges such that user_of_variable -> used_varible.
# This happens to be easier in this case, since a variable's
# definition contains all variables it references in a single string.
edges = set()
for value in sorted(properties[node].keys()):
# Add to edges all $(...) references to variables.
#
# Variable references that refer to names not in properties are excluded
# These can exist for instance to refer built in definitions like
# $(SolutionDir).
#
# Self references are ignored. Self reference is used in a few places to
# append to the default value. I.e. PATH=$(PATH);other_path
edges.update(set([v for v in MSVS_VARIABLE_REFERENCE.findall(value)
if v in properties and v != node]))
return edges
properties_ordered = gyp.common.TopologicallySorted(
properties.keys(), GetEdges)
# Walk properties in the reverse of a topological sort on
# user_of_variable -> used_variable as this ensures variables are
# defined before they are used.
# NOTE: reverse(topsort(DAG)) = topsort(reverse_edges(DAG))
for name in reversed(properties_ordered):
values = properties[name]
for value, conditions in sorted(values.iteritems()):
if len(conditions) == num_configurations:
# If the value is the same all configurations,
# just add one unconditional entry.
group.append([name, value])
else:
for condition in conditions:
group.append([name, {'Condition': condition}, value])
return [group] | [
"def",
"_GetMSBuildPropertyGroup",
"(",
"spec",
",",
"label",
",",
"properties",
")",
":",
"group",
"=",
"[",
"'PropertyGroup'",
"]",
"if",
"label",
":",
"group",
".",
"append",
"(",
"{",
"'Label'",
":",
"label",
"}",
")",
"num_configurations",
"=",
"len",... | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/generator/msvs.py#L2985-L3032 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/spatial/kdtree.py | python | KDTree.query_ball_tree | (self, other, r, p=2., eps=0) | return results | Find all pairs of points whose distance is at most r
Parameters
----------
other : KDTree instance
The tree containing points to search against.
r : float
The maximum distance, has to be positive.
p : float, optional
Which Minkowski norm to use. `p` has to meet the condition
``1 <= p <= infinity``.
eps : float, optional
Approximate search. Branches of the tree are not explored
if their nearest points are further than ``r/(1+eps)``, and
branches are added in bulk if their furthest points are nearer
than ``r * (1+eps)``. `eps` has to be non-negative.
Returns
-------
results : list of lists
For each element ``self.data[i]`` of this tree, ``results[i]`` is a
list of the indices of its neighbors in ``other.data``. | Find all pairs of points whose distance is at most r | [
"Find",
"all",
"pairs",
"of",
"points",
"whose",
"distance",
"is",
"at",
"most",
"r"
] | def query_ball_tree(self, other, r, p=2., eps=0):
"""Find all pairs of points whose distance is at most r
Parameters
----------
other : KDTree instance
The tree containing points to search against.
r : float
The maximum distance, has to be positive.
p : float, optional
Which Minkowski norm to use. `p` has to meet the condition
``1 <= p <= infinity``.
eps : float, optional
Approximate search. Branches of the tree are not explored
if their nearest points are further than ``r/(1+eps)``, and
branches are added in bulk if their furthest points are nearer
than ``r * (1+eps)``. `eps` has to be non-negative.
Returns
-------
results : list of lists
For each element ``self.data[i]`` of this tree, ``results[i]`` is a
list of the indices of its neighbors in ``other.data``.
"""
results = [[] for i in range(self.n)]
def traverse_checking(node1, rect1, node2, rect2):
if rect1.min_distance_rectangle(rect2, p) > r/(1.+eps):
return
elif rect1.max_distance_rectangle(rect2, p) < r*(1.+eps):
traverse_no_checking(node1, node2)
elif isinstance(node1, KDTree.leafnode):
if isinstance(node2, KDTree.leafnode):
d = other.data[node2.idx]
for i in node1.idx:
results[i] += node2.idx[minkowski_distance(d,self.data[i],p) <= r].tolist()
else:
less, greater = rect2.split(node2.split_dim, node2.split)
traverse_checking(node1,rect1,node2.less,less)
traverse_checking(node1,rect1,node2.greater,greater)
elif isinstance(node2, KDTree.leafnode):
less, greater = rect1.split(node1.split_dim, node1.split)
traverse_checking(node1.less,less,node2,rect2)
traverse_checking(node1.greater,greater,node2,rect2)
else:
less1, greater1 = rect1.split(node1.split_dim, node1.split)
less2, greater2 = rect2.split(node2.split_dim, node2.split)
traverse_checking(node1.less,less1,node2.less,less2)
traverse_checking(node1.less,less1,node2.greater,greater2)
traverse_checking(node1.greater,greater1,node2.less,less2)
traverse_checking(node1.greater,greater1,node2.greater,greater2)
def traverse_no_checking(node1, node2):
if isinstance(node1, KDTree.leafnode):
if isinstance(node2, KDTree.leafnode):
for i in node1.idx:
results[i] += node2.idx.tolist()
else:
traverse_no_checking(node1, node2.less)
traverse_no_checking(node1, node2.greater)
else:
traverse_no_checking(node1.less, node2)
traverse_no_checking(node1.greater, node2)
traverse_checking(self.tree, Rectangle(self.maxes, self.mins),
other.tree, Rectangle(other.maxes, other.mins))
return results | [
"def",
"query_ball_tree",
"(",
"self",
",",
"other",
",",
"r",
",",
"p",
"=",
"2.",
",",
"eps",
"=",
"0",
")",
":",
"results",
"=",
"[",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"n",
")",
"]",
"def",
"traverse_checking",
"(",
"nod... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/spatial/kdtree.py#L629-L696 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_windows.py | python | ColourData.__init__ | (self, *args, **kwargs) | __init__(self) -> ColourData
Constructor, sets default values. | __init__(self) -> ColourData | [
"__init__",
"(",
"self",
")",
"-",
">",
"ColourData"
] | def __init__(self, *args, **kwargs):
"""
__init__(self) -> ColourData
Constructor, sets default values.
"""
_windows_.ColourData_swiginit(self,_windows_.new_ColourData(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_windows_",
".",
"ColourData_swiginit",
"(",
"self",
",",
"_windows_",
".",
"new_ColourData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L2922-L2928 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/stats/mstats_basic.py | python | kendalltau | (x, y, use_ties=True, use_missing=False, method='auto') | return KendalltauResult(tau, prob) | Computes Kendall's rank correlation tau on two variables *x* and *y*.
Parameters
----------
x : sequence
First data list (for example, time).
y : sequence
Second data list.
use_ties : {True, False}, optional
Whether ties correction should be performed.
use_missing : {False, True}, optional
Whether missing data should be allocated a rank of 0 (False) or the
average rank (True)
method: {'auto', 'asymptotic', 'exact'}, optional
Defines which method is used to calculate the p-value [1]_.
'asymptotic' uses a normal approximation valid for large samples.
'exact' computes the exact p-value, but can only be used if no ties
are present. 'auto' is the default and selects the appropriate
method based on a trade-off between speed and accuracy.
Returns
-------
correlation : float
Kendall tau
pvalue : float
Approximate 2-side p-value.
References
----------
.. [1] Maurice G. Kendall, "Rank Correlation Methods" (4th Edition),
Charles Griffin & Co., 1970. | Computes Kendall's rank correlation tau on two variables *x* and *y*. | [
"Computes",
"Kendall",
"s",
"rank",
"correlation",
"tau",
"on",
"two",
"variables",
"*",
"x",
"*",
"and",
"*",
"y",
"*",
"."
] | def kendalltau(x, y, use_ties=True, use_missing=False, method='auto'):
"""
Computes Kendall's rank correlation tau on two variables *x* and *y*.
Parameters
----------
x : sequence
First data list (for example, time).
y : sequence
Second data list.
use_ties : {True, False}, optional
Whether ties correction should be performed.
use_missing : {False, True}, optional
Whether missing data should be allocated a rank of 0 (False) or the
average rank (True)
method: {'auto', 'asymptotic', 'exact'}, optional
Defines which method is used to calculate the p-value [1]_.
'asymptotic' uses a normal approximation valid for large samples.
'exact' computes the exact p-value, but can only be used if no ties
are present. 'auto' is the default and selects the appropriate
method based on a trade-off between speed and accuracy.
Returns
-------
correlation : float
Kendall tau
pvalue : float
Approximate 2-side p-value.
References
----------
.. [1] Maurice G. Kendall, "Rank Correlation Methods" (4th Edition),
Charles Griffin & Co., 1970.
"""
(x, y, n) = _chk_size(x, y)
(x, y) = (x.flatten(), y.flatten())
m = ma.mask_or(ma.getmask(x), ma.getmask(y))
if m is not nomask:
x = ma.array(x, mask=m, copy=True)
y = ma.array(y, mask=m, copy=True)
# need int() here, otherwise numpy defaults to 32 bit
# integer on all Windows architectures, causing overflow.
# int() will keep it infinite precision.
n -= int(m.sum())
if n < 2:
return KendalltauResult(np.nan, np.nan)
rx = ma.masked_equal(rankdata(x, use_missing=use_missing), 0)
ry = ma.masked_equal(rankdata(y, use_missing=use_missing), 0)
idx = rx.argsort()
(rx, ry) = (rx[idx], ry[idx])
C = np.sum([((ry[i+1:] > ry[i]) * (rx[i+1:] > rx[i])).filled(0).sum()
for i in range(len(ry)-1)], dtype=float)
D = np.sum([((ry[i+1:] < ry[i])*(rx[i+1:] > rx[i])).filled(0).sum()
for i in range(len(ry)-1)], dtype=float)
xties = count_tied_groups(x)
yties = count_tied_groups(y)
if use_ties:
corr_x = np.sum([v*k*(k-1) for (k,v) in iteritems(xties)], dtype=float)
corr_y = np.sum([v*k*(k-1) for (k,v) in iteritems(yties)], dtype=float)
denom = ma.sqrt((n*(n-1)-corr_x)/2. * (n*(n-1)-corr_y)/2.)
else:
denom = n*(n-1)/2.
tau = (C-D) / denom
if method == 'exact' and (xties or yties):
raise ValueError("Ties found, exact method cannot be used.")
if method == 'auto':
if (not xties and not yties) and (n <= 33 or min(C, n*(n-1)/2.0-C) <= 1):
method = 'exact'
else:
method = 'asymptotic'
if not xties and not yties and method == 'exact':
# Exact p-value, see Maurice G. Kendall, "Rank Correlation Methods" (4th Edition), Charles Griffin & Co., 1970.
c = int(min(C, (n*(n-1))/2-C))
if n <= 0:
raise ValueError
elif c < 0 or 2*c > n*(n-1):
raise ValueError
elif n == 1:
prob = 1.0
elif n == 2:
prob = 1.0
elif c == 0:
prob = 2.0/np.math.factorial(n)
elif c == 1:
prob = 2.0/np.math.factorial(n-1)
else:
old = [0.0]*(c+1)
new = [0.0]*(c+1)
new[0] = 1.0
new[1] = 1.0
for j in range(3,n+1):
old = new[:]
for k in range(1,min(j,c+1)):
new[k] += new[k-1]
for k in range(j,c+1):
new[k] += new[k-1] - old[k-j]
prob = 2.0*sum(new)/np.math.factorial(n)
elif method == 'asymptotic':
var_s = n*(n-1)*(2*n+5)
if use_ties:
var_s -= np.sum([v*k*(k-1)*(2*k+5)*1. for (k,v) in iteritems(xties)])
var_s -= np.sum([v*k*(k-1)*(2*k+5)*1. for (k,v) in iteritems(yties)])
v1 = np.sum([v*k*(k-1) for (k, v) in iteritems(xties)], dtype=float) *\
np.sum([v*k*(k-1) for (k, v) in iteritems(yties)], dtype=float)
v1 /= 2.*n*(n-1)
if n > 2:
v2 = np.sum([v*k*(k-1)*(k-2) for (k,v) in iteritems(xties)],
dtype=float) * \
np.sum([v*k*(k-1)*(k-2) for (k,v) in iteritems(yties)],
dtype=float)
v2 /= 9.*n*(n-1)*(n-2)
else:
v2 = 0
else:
v1 = v2 = 0
var_s /= 18.
var_s += (v1 + v2)
z = (C-D)/np.sqrt(var_s)
prob = special.erfc(abs(z)/np.sqrt(2))
else:
raise ValueError("Unknown method "+str(method)+" specified, please use auto, exact or asymptotic.")
return KendalltauResult(tau, prob) | [
"def",
"kendalltau",
"(",
"x",
",",
"y",
",",
"use_ties",
"=",
"True",
",",
"use_missing",
"=",
"False",
",",
"method",
"=",
"'auto'",
")",
":",
"(",
"x",
",",
"y",
",",
"n",
")",
"=",
"_chk_size",
"(",
"x",
",",
"y",
")",
"(",
"x",
",",
"y",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/stats/mstats_basic.py#L543-L672 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/learn/python/learn/estimators/head.py | python | _LossOnlyHead.create_model_fn_ops | (self,
features,
mode,
labels=None,
train_op_fn=None,
logits=None,
logits_input=None,
scope=None) | return model_fn.ModelFnOps(
mode=mode,
loss=loss,
train_op=train_op,
predictions={},
eval_metric_ops={}) | See `_Head.create_model_fn_ops`.
Args:
features: Not been used.
mode: Estimator's `ModeKeys`.
labels: Labels `Tensor`, or `dict` of same.
train_op_fn: Function that takes a scalar loss and returns an op to
optimize with the loss.
logits: Not been used.
logits_input: Not been used.
scope: Optional scope for variable_scope. If provided, will be passed to
all heads. Most users will want to set this to `None`, so each head
constructs a separate variable_scope according to its `head_name`.
Returns:
A `ModelFnOps` object.
Raises:
ValueError: if `mode` is not recognition. | See `_Head.create_model_fn_ops`. | [
"See",
"_Head",
".",
"create_model_fn_ops",
"."
] | def create_model_fn_ops(self,
features,
mode,
labels=None,
train_op_fn=None,
logits=None,
logits_input=None,
scope=None):
"""See `_Head.create_model_fn_ops`.
Args:
features: Not been used.
mode: Estimator's `ModeKeys`.
labels: Labels `Tensor`, or `dict` of same.
train_op_fn: Function that takes a scalar loss and returns an op to
optimize with the loss.
logits: Not been used.
logits_input: Not been used.
scope: Optional scope for variable_scope. If provided, will be passed to
all heads. Most users will want to set this to `None`, so each head
constructs a separate variable_scope according to its `head_name`.
Returns:
A `ModelFnOps` object.
Raises:
ValueError: if `mode` is not recognition.
"""
_check_mode_valid(mode)
loss = None
train_op = None
if mode != model_fn.ModeKeys.INFER:
with variable_scope.variable_scope(scope, default_name=self.head_name):
loss = self._loss_fn()
if isinstance(loss, list):
loss = math_ops.add_n(loss)
logging_ops.scalar_summary(
_summary_key(self.head_name, mkey.LOSS), loss)
if mode == model_fn.ModeKeys.TRAIN:
if train_op_fn is None:
raise ValueError("train_op_fn can not be None in TRAIN mode")
with ops.name_scope(None, "train_op", (loss,)):
train_op = train_op_fn(loss)
return model_fn.ModelFnOps(
mode=mode,
loss=loss,
train_op=train_op,
predictions={},
eval_metric_ops={}) | [
"def",
"create_model_fn_ops",
"(",
"self",
",",
"features",
",",
"mode",
",",
"labels",
"=",
"None",
",",
"train_op_fn",
"=",
"None",
",",
"logits",
"=",
"None",
",",
"logits_input",
"=",
"None",
",",
"scope",
"=",
"None",
")",
":",
"_check_mode_valid",
... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/estimators/head.py#L1448-L1497 | |
xiaohaoChen/rrc_detection | 4f2b110cd122da7f55e8533275a9b4809a88785a | scripts/cpp_lint.py | python | _CppLintState.PrintErrorCounts | (self) | Print a summary of errors by category, and the total. | Print a summary of errors by category, and the total. | [
"Print",
"a",
"summary",
"of",
"errors",
"by",
"category",
"and",
"the",
"total",
"."
] | def PrintErrorCounts(self):
"""Print a summary of errors by category, and the total."""
for category, count in self.errors_by_category.iteritems():
sys.stderr.write('Category \'%s\' errors found: %d\n' %
(category, count))
sys.stderr.write('Total errors found: %d\n' % self.error_count) | [
"def",
"PrintErrorCounts",
"(",
"self",
")",
":",
"for",
"category",
",",
"count",
"in",
"self",
".",
"errors_by_category",
".",
"iteritems",
"(",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Category \\'%s\\' errors found: %d\\n'",
"%",
"(",
"category... | https://github.com/xiaohaoChen/rrc_detection/blob/4f2b110cd122da7f55e8533275a9b4809a88785a/scripts/cpp_lint.py#L757-L762 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/math/symbolic.py | python | Context.renameUserData | (self,itemname,newname) | Renames a userData | Renames a userData | [
"Renames",
"a",
"userData"
] | def renameUserData(self,itemname,newname):
"""Renames a userData"""
assert itemname in self.userData,"Userdata "+itemname+" does not exist"
if itemname == newname: return
assert newname not in self.userData,"Renamed userdata name "+newname+" already exists"
self.userData[newname] = self.userData[itemname]
del self.userData[itemname] | [
"def",
"renameUserData",
"(",
"self",
",",
"itemname",
",",
"newname",
")",
":",
"assert",
"itemname",
"in",
"self",
".",
"userData",
",",
"\"Userdata \"",
"+",
"itemname",
"+",
"\" does not exist\"",
"if",
"itemname",
"==",
"newname",
":",
"return",
"assert",... | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/math/symbolic.py#L1491-L1497 | ||
Slicer/SlicerGitSVNArchive | 65e92bb16c2b32ea47a1a66bee71f238891ee1ca | Utilities/Scripts/SlicerWizard/GithubHelper.py | python | getPullRequest | (upstream, ref, user=None, fork=None, target=None) | return None | Get pull request for the specified user's fork and ref.
:param upstream:
Upstream (target) repository of the requested pull request.
:type upstream:
:class:`github:github.Repository.Repository`
:param user:
Github user or organization which owns the requested pull request.
:type user:
:class:`github:github.NamedUser.NamedUser`,
:class:`github:github.AuthenticatedUser.AuthenticatedUser`,
:class:`github:github.Organization.Organization` or ``None``
:param ref:
Branch name or git ref of the requested pull request.
:type ref:
:class:`str`
:param fork:
Downstream (fork) repository of the requested pull request.
:type fork:
:class:`github:github.Repository.Repository` or ``None``
:param target:
Branch name or git ref of the requested pull request target.
:type target:
:class:`str` or ``None``
:return:
The specified pull request, or ``None`` if no such pull request exists.
:rtype:
:class:`github:github.PullRequest.PullRequest` or ``None``.
This function attempts to look up the pull request made by ``user`` for
``upstream`` to integrate the user's ``ref`` into upstream's ``target``:
.. code-block:: python
# Create session
session = GithubHelper.logIn()
# Get user and upstream repository
user = session.get_user("jdoe")
repo = GithubHelper.getRepo(session, 'octocat/Hello-World')
# Look up request to merge 'my-branch' of any fork into 'master'
pr = GithubHelper.getPullRequest(upstream=repo, user=user,
ref='my-branch', target='master')
If any of ``user``, ``fork`` or ``target`` are ``None``, those criteria are
not considered when searching for a matching pull request. If multiple
matching requests exist, the first matching request is returned. | Get pull request for the specified user's fork and ref. | [
"Get",
"pull",
"request",
"for",
"the",
"specified",
"user",
"s",
"fork",
"and",
"ref",
"."
] | def getPullRequest(upstream, ref, user=None, fork=None, target=None):
"""Get pull request for the specified user's fork and ref.
:param upstream:
Upstream (target) repository of the requested pull request.
:type upstream:
:class:`github:github.Repository.Repository`
:param user:
Github user or organization which owns the requested pull request.
:type user:
:class:`github:github.NamedUser.NamedUser`,
:class:`github:github.AuthenticatedUser.AuthenticatedUser`,
:class:`github:github.Organization.Organization` or ``None``
:param ref:
Branch name or git ref of the requested pull request.
:type ref:
:class:`str`
:param fork:
Downstream (fork) repository of the requested pull request.
:type fork:
:class:`github:github.Repository.Repository` or ``None``
:param target:
Branch name or git ref of the requested pull request target.
:type target:
:class:`str` or ``None``
:return:
The specified pull request, or ``None`` if no such pull request exists.
:rtype:
:class:`github:github.PullRequest.PullRequest` or ``None``.
This function attempts to look up the pull request made by ``user`` for
``upstream`` to integrate the user's ``ref`` into upstream's ``target``:
.. code-block:: python
# Create session
session = GithubHelper.logIn()
# Get user and upstream repository
user = session.get_user("jdoe")
repo = GithubHelper.getRepo(session, 'octocat/Hello-World')
# Look up request to merge 'my-branch' of any fork into 'master'
pr = GithubHelper.getPullRequest(upstream=repo, user=user,
ref='my-branch', target='master')
If any of ``user``, ``fork`` or ``target`` are ``None``, those criteria are
not considered when searching for a matching pull request. If multiple
matching requests exist, the first matching request is returned.
"""
if user is not None:
user = user.login
for p in upstream.get_pulls():
# Check candidate request against specified criteria
if p.head.ref != ref:
continue
if user is not None and p.head.user.login != user:
continue
if fork is not None and p.head.repo.url != fork.url:
continue
if target is not None and p.base.ref != target:
continue
# If we get here, we found a match
return p
# No match
return None | [
"def",
"getPullRequest",
"(",
"upstream",
",",
"ref",
",",
"user",
"=",
"None",
",",
"fork",
"=",
"None",
",",
"target",
"=",
"None",
")",
":",
"if",
"user",
"is",
"not",
"None",
":",
"user",
"=",
"user",
".",
"login",
"for",
"p",
"in",
"upstream",... | https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Utilities/Scripts/SlicerWizard/GithubHelper.py#L235-L308 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/distributions/util.py | python | embed_check_nonnegative_integer_form | (
x, name="embed_check_nonnegative_integer_form") | Assert x is a non-negative tensor, and optionally of integers. | Assert x is a non-negative tensor, and optionally of integers. | [
"Assert",
"x",
"is",
"a",
"non",
"-",
"negative",
"tensor",
"and",
"optionally",
"of",
"integers",
"."
] | def embed_check_nonnegative_integer_form(
x, name="embed_check_nonnegative_integer_form"):
"""Assert x is a non-negative tensor, and optionally of integers."""
with ops.name_scope(name, values=[x]):
x = ops.convert_to_tensor(x, name="x")
assertions = [
check_ops.assert_non_negative(
x, message="'{}' must be non-negative.".format(x)),
]
if not x.dtype.is_integer:
assertions += [
assert_integer_form(
x,
message="'{}' cannot contain fractional components.".format(x)),
]
return control_flow_ops.with_dependencies(assertions, x) | [
"def",
"embed_check_nonnegative_integer_form",
"(",
"x",
",",
"name",
"=",
"\"embed_check_nonnegative_integer_form\"",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"values",
"=",
"[",
"x",
"]",
")",
":",
"x",
"=",
"ops",
".",
"convert_to_tenso... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/distributions/util.py#L86-L101 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/control/robotinterfaceutils.py | python | RobotInterfaceCompleter.softStop | (self) | Requires reset | Requires reset | [
"Requires",
"reset"
] | def softStop(self):
"""Requires reset"""
self._base.softStop()
self._emulator.softStop(self._indices) | [
"def",
"softStop",
"(",
"self",
")",
":",
"self",
".",
"_base",
".",
"softStop",
"(",
")",
"self",
".",
"_emulator",
".",
"softStop",
"(",
"self",
".",
"_indices",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/control/robotinterfaceutils.py#L2658-L2661 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/ExodusViewer/plugins/MeshPlugin.py | python | MeshPlugin._callbackViewMeshToggle | (self) | Callback for ViewMeshToggle widget. (protected) | Callback for ViewMeshToggle widget. (protected) | [
"Callback",
"for",
"ViewMeshToggle",
"widget",
".",
"(",
"protected",
")"
] | def _callbackViewMeshToggle(self):
"""
Callback for ViewMeshToggle widget. (protected)
"""
self.store(self.ViewMeshToggle)
self.updateOptions()
self.windowRequiresUpdate.emit() | [
"def",
"_callbackViewMeshToggle",
"(",
"self",
")",
":",
"self",
".",
"store",
"(",
"self",
".",
"ViewMeshToggle",
")",
"self",
".",
"updateOptions",
"(",
")",
"self",
".",
"windowRequiresUpdate",
".",
"emit",
"(",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/ExodusViewer/plugins/MeshPlugin.py#L262-L268 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/ensemble/_gb_losses.py | python | LossFunction.__call__ | (self, y, raw_predictions, sample_weight=None) | Compute the loss.
Parameters
----------
y : 1d array, shape (n_samples,)
True labels.
raw_predictions : 2d array, shape (n_samples, K)
The raw predictions (i.e. values from the tree leaves).
sample_weight : 1d array, shape (n_samples,), optional
Sample weights. | Compute the loss. | [
"Compute",
"the",
"loss",
"."
] | def __call__(self, y, raw_predictions, sample_weight=None):
"""Compute the loss.
Parameters
----------
y : 1d array, shape (n_samples,)
True labels.
raw_predictions : 2d array, shape (n_samples, K)
The raw predictions (i.e. values from the tree leaves).
sample_weight : 1d array, shape (n_samples,), optional
Sample weights.
""" | [
"def",
"__call__",
"(",
"self",
",",
"y",
",",
"raw_predictions",
",",
"sample_weight",
"=",
"None",
")",
":"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/ensemble/_gb_losses.py#L44-L57 | ||
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | buildsystem/codecompliance/authors.py | python | find_issues | () | compares the output of git shortlog -sne to the authors table in copying.md
prints all discrepancies, and returns False if one is detected. | compares the output of git shortlog -sne to the authors table in copying.md | [
"compares",
"the",
"output",
"of",
"git",
"shortlog",
"-",
"sne",
"to",
"the",
"authors",
"table",
"in",
"copying",
".",
"md"
] | def find_issues():
"""
compares the output of git shortlog -sne to the authors table in copying.md
prints all discrepancies, and returns False if one is detected.
"""
relevant_exts = ('.cpp', '.h', '.py', '.pyi', '.pyx', '.cmake',
'.qml')
copying_md_emails = set(get_author_emails_copying_md())
git_shortlog_emails = set(get_author_emails_git_shortlog(relevant_exts))
# look for git emails that are unlisted in copying.md
for email in git_shortlog_emails - copying_md_emails:
if email in {'coop@sft.mx', '?'}:
continue
yield (
"author inconsistency",
f"{email}\n\temail appears in git log, but not in copying.md or .mailmap",
None
) | [
"def",
"find_issues",
"(",
")",
":",
"relevant_exts",
"=",
"(",
"'.cpp'",
",",
"'.h'",
",",
"'.py'",
",",
"'.pyi'",
",",
"'.pyx'",
",",
"'.cmake'",
",",
"'.qml'",
")",
"copying_md_emails",
"=",
"set",
"(",
"get_author_emails_copying_md",
"(",
")",
")",
"gi... | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/buildsystem/codecompliance/authors.py#L76-L97 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/quantization/tools/quantize_graph.py | python | GraphRewriter.add_output_graph_node | (self, output_node) | Inserts one node into the new graph. | Inserts one node into the new graph. | [
"Inserts",
"one",
"node",
"into",
"the",
"new",
"graph",
"."
] | def add_output_graph_node(self, output_node):
"""Inserts one node into the new graph."""
self.output_graph.node.extend([output_node]) | [
"def",
"add_output_graph_node",
"(",
"self",
",",
"output_node",
")",
":",
"self",
".",
"output_graph",
".",
"node",
".",
"extend",
"(",
"[",
"output_node",
"]",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/quantization/tools/quantize_graph.py#L800-L802 | ||
intel/caffe | 3f494b442ee3f9d17a07b09ecbd5fa2bbda00836 | python/caffe/pycaffe.py | python | _Net_backward | (self, diffs=None, start=None, end=None, **kwargs) | return {out: self.blobs[out].diff for out in outputs} | Backward pass: prepare diffs and run the net backward.
Parameters
----------
diffs : list of diffs to return in addition to bottom diffs.
kwargs : Keys are output blob names and values are diff ndarrays.
If None, top diffs are taken from forward loss.
start : optional name of layer at which to begin the backward pass
end : optional name of layer at which to finish the backward pass
(inclusive)
Returns
-------
outs: {blob name: diff ndarray} dict. | Backward pass: prepare diffs and run the net backward. | [
"Backward",
"pass",
":",
"prepare",
"diffs",
"and",
"run",
"the",
"net",
"backward",
"."
] | def _Net_backward(self, diffs=None, start=None, end=None, **kwargs):
"""
Backward pass: prepare diffs and run the net backward.
Parameters
----------
diffs : list of diffs to return in addition to bottom diffs.
kwargs : Keys are output blob names and values are diff ndarrays.
If None, top diffs are taken from forward loss.
start : optional name of layer at which to begin the backward pass
end : optional name of layer at which to finish the backward pass
(inclusive)
Returns
-------
outs: {blob name: diff ndarray} dict.
"""
if diffs is None:
diffs = []
if start is not None:
start_ind = list(self._layer_names).index(start)
else:
start_ind = len(self.layers) - 1
if end is not None:
end_ind = list(self._layer_names).index(end)
outputs = set(self.bottom_names[end] + diffs)
else:
end_ind = 0
outputs = set(self.inputs + diffs)
if kwargs:
if set(kwargs.keys()) != set(self.outputs):
raise Exception('Top diff arguments do not match net outputs.')
# Set top diffs according to defined shapes and make arrays single and
# C-contiguous as Caffe expects.
for top, diff in six.iteritems(kwargs):
if diff.shape[0] != self.blobs[top].shape[0]:
raise Exception('Diff is not batch sized')
self.blobs[top].diff[...] = diff
self._backward(start_ind, end_ind)
# Unpack diffs to extract
return {out: self.blobs[out].diff for out in outputs} | [
"def",
"_Net_backward",
"(",
"self",
",",
"diffs",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"diffs",
"is",
"None",
":",
"diffs",
"=",
"[",
"]",
"if",
"start",
"is",
"not",
"None",
... | https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/python/caffe/pycaffe.py#L172-L217 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/linear_model/logistic.py | python | _multinomial_loss | (w, X, Y, alpha, sample_weight) | return loss, p, w | Computes multinomial loss and class probabilities.
Parameters
----------
w : ndarray, shape (n_classes * n_features,) or
(n_classes * (n_features + 1),)
Coefficient vector.
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data.
Y : ndarray, shape (n_samples, n_classes)
Transformed labels according to the output of LabelBinarizer.
alpha : float
Regularization parameter. alpha is equal to 1 / C.
sample_weight : array-like, shape (n_samples,) optional
Array of weights that are assigned to individual samples.
If not provided, then each sample is given unit weight.
Returns
-------
loss : float
Multinomial loss.
p : ndarray, shape (n_samples, n_classes)
Estimated class probabilities.
w : ndarray, shape (n_classes, n_features)
Reshaped param vector excluding intercept terms.
Reference
---------
Bishop, C. M. (2006). Pattern recognition and machine learning.
Springer. (Chapter 4.3.4) | Computes multinomial loss and class probabilities. | [
"Computes",
"multinomial",
"loss",
"and",
"class",
"probabilities",
"."
] | def _multinomial_loss(w, X, Y, alpha, sample_weight):
"""Computes multinomial loss and class probabilities.
Parameters
----------
w : ndarray, shape (n_classes * n_features,) or
(n_classes * (n_features + 1),)
Coefficient vector.
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data.
Y : ndarray, shape (n_samples, n_classes)
Transformed labels according to the output of LabelBinarizer.
alpha : float
Regularization parameter. alpha is equal to 1 / C.
sample_weight : array-like, shape (n_samples,) optional
Array of weights that are assigned to individual samples.
If not provided, then each sample is given unit weight.
Returns
-------
loss : float
Multinomial loss.
p : ndarray, shape (n_samples, n_classes)
Estimated class probabilities.
w : ndarray, shape (n_classes, n_features)
Reshaped param vector excluding intercept terms.
Reference
---------
Bishop, C. M. (2006). Pattern recognition and machine learning.
Springer. (Chapter 4.3.4)
"""
n_classes = Y.shape[1]
n_features = X.shape[1]
fit_intercept = w.size == (n_classes * (n_features + 1))
w = w.reshape(n_classes, -1)
sample_weight = sample_weight[:, np.newaxis]
if fit_intercept:
intercept = w[:, -1]
w = w[:, :-1]
else:
intercept = 0
p = safe_sparse_dot(X, w.T)
p += intercept
p -= logsumexp(p, axis=1)[:, np.newaxis]
loss = -(sample_weight * Y * p).sum()
loss += 0.5 * alpha * squared_norm(w)
p = np.exp(p, p)
return loss, p, w | [
"def",
"_multinomial_loss",
"(",
"w",
",",
"X",
",",
"Y",
",",
"alpha",
",",
"sample_weight",
")",
":",
"n_classes",
"=",
"Y",
".",
"shape",
"[",
"1",
"]",
"n_features",
"=",
"X",
".",
"shape",
"[",
"1",
"]",
"fit_intercept",
"=",
"w",
".",
"size",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/linear_model/logistic.py#L242-L296 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | PyApp.IsMainLoopRunning | (*args, **kwargs) | return _core_.PyApp_IsMainLoopRunning(*args, **kwargs) | IsMainLoopRunning() -> bool
Returns True if we're running the main loop, i.e. if the events can
currently be dispatched. | IsMainLoopRunning() -> bool | [
"IsMainLoopRunning",
"()",
"-",
">",
"bool"
] | def IsMainLoopRunning(*args, **kwargs):
"""
IsMainLoopRunning() -> bool
Returns True if we're running the main loop, i.e. if the events can
currently be dispatched.
"""
return _core_.PyApp_IsMainLoopRunning(*args, **kwargs) | [
"def",
"IsMainLoopRunning",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"PyApp_IsMainLoopRunning",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L7935-L7942 | |
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/bindings/python/ttvdbv4/myth4ttvdbv4.py | python | Myth4TTVDBv4.buildCollection | (self, other_inetref=None, xml_output=True) | return ser_x | Creates a single extendedSeriesRecord matching the 'inetref' provided by the
command line.
If xml_output requested, update the common xml data, otherwise return this record.
The 'other_inetref' option overrides the default 'inetref' from the command line. | Creates a single extendedSeriesRecord matching the 'inetref' provided by the
command line.
If xml_output requested, update the common xml data, otherwise return this record.
The 'other_inetref' option overrides the default 'inetref' from the command line. | [
"Creates",
"a",
"single",
"extendedSeriesRecord",
"matching",
"the",
"inetref",
"provided",
"by",
"the",
"command",
"line",
".",
"If",
"xml_output",
"requested",
"update",
"the",
"common",
"xml",
"data",
"otherwise",
"return",
"this",
"record",
".",
"The",
"othe... | def buildCollection(self, other_inetref=None, xml_output=True):
"""
Creates a single extendedSeriesRecord matching the 'inetref' provided by the
command line.
If xml_output requested, update the common xml data, otherwise return this record.
The 'other_inetref' option overrides the default 'inetref' from the command line.
"""
# option -C inetref
# $ ttvdb4.py -l en -C 360893 --debug
# $ ttvdb4.py -l de -C 360893 --debug
# $ ttvdb4.py -l ja -C 360893 --debug (missing Japanese overview)
# $ ttvdb4.py -l fr -C 76568 --debug
if other_inetref:
tvinetref = other_inetref
else:
tvinetref = self.collectionref[0]
if self.debug:
print("\n%04d: buildCollection: Query 'buildCollection' called with "
"'%s', xml_output = %s"
% (self._get_ellapsed_time(), tvinetref, xml_output))
# get data for passed inetref and preferred translations
ser_x = ttvdb.getSeriesExtended(tvinetref)
ser_x.fetched_translations = []
for lang in self._select_preferred_langs(ser_x.nameTranslations):
translation = ttvdb.getSeriesTranslation(tvinetref, lang)
ser_x.fetched_translations.append(translation)
# define exact name found:
ser_x.name_similarity = 1.0
if self.debug:
print("%04d: buildCollection: Series information for %s:"
% (self._get_ellapsed_time(), tvinetref))
_print_class_content(ser_x)
if xml_output:
self._format_xml(ser_x)
return ser_x | [
"def",
"buildCollection",
"(",
"self",
",",
"other_inetref",
"=",
"None",
",",
"xml_output",
"=",
"True",
")",
":",
"# option -C inetref",
"# $ ttvdb4.py -l en -C 360893 --debug",
"# $ ttvdb4.py -l de -C 360893 --debug",
"# $ ttvdb4.py -l ja -C 360893 --debug (missing Japanese ove... | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/bindings/python/ttvdbv4/myth4ttvdbv4.py#L579-L621 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/botocore/errorfactory.py | python | BaseClientExceptions.from_code | (self, error_code) | return self._code_to_exception.get(error_code, self.ClientError) | Retrieves the error class based on the error code
This is helpful for identifying the exception class needing to be
caught based on the ClientError.parsed_reponse['Error']['Code'] value
:type error_code: string
:param error_code: The error code associated to a ClientError exception
:rtype: ClientError or a subclass of ClientError
:returns: The appropriate modeled exception class for that error
code. If the error code does not match any of the known
modeled exceptions then return a generic ClientError. | Retrieves the error class based on the error code | [
"Retrieves",
"the",
"error",
"class",
"based",
"on",
"the",
"error",
"code"
] | def from_code(self, error_code):
"""Retrieves the error class based on the error code
This is helpful for identifying the exception class needing to be
caught based on the ClientError.parsed_reponse['Error']['Code'] value
:type error_code: string
:param error_code: The error code associated to a ClientError exception
:rtype: ClientError or a subclass of ClientError
:returns: The appropriate modeled exception class for that error
code. If the error code does not match any of the known
modeled exceptions then return a generic ClientError.
"""
return self._code_to_exception.get(error_code, self.ClientError) | [
"def",
"from_code",
"(",
"self",
",",
"error_code",
")",
":",
"return",
"self",
".",
"_code_to_exception",
".",
"get",
"(",
"error_code",
",",
"self",
".",
"ClientError",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/botocore/errorfactory.py#L30-L44 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py | python | ResourceManager.resource_string | (self, package_or_requirement, resource_name) | return get_provider(package_or_requirement).get_resource_string(
self, resource_name
) | Return specified resource as a string | Return specified resource as a string | [
"Return",
"specified",
"resource",
"as",
"a",
"string"
] | def resource_string(self, package_or_requirement, resource_name):
"""Return specified resource as a string"""
return get_provider(package_or_requirement).get_resource_string(
self, resource_name
) | [
"def",
"resource_string",
"(",
"self",
",",
"package_or_requirement",
",",
"resource_name",
")",
":",
"return",
"get_provider",
"(",
"package_or_requirement",
")",
".",
"get_resource_string",
"(",
"self",
",",
"resource_name",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py#L1154-L1158 | |
HKUST-Aerial-Robotics/Fast-Planner | 2ddd7793eecd573dbb5b47e2c985aa06606df3cf | uav_simulator/Utils/multi_map_server/src/multi_map_server/msg/_MultiSparseMap3D.py | python | MultiSparseMap3D._get_types | (self) | return self._slot_types | internal API method | internal API method | [
"internal",
"API",
"method"
] | def _get_types(self):
"""
internal API method
"""
return self._slot_types | [
"def",
"_get_types",
"(",
"self",
")",
":",
"return",
"self",
".",
"_slot_types"
] | https://github.com/HKUST-Aerial-Robotics/Fast-Planner/blob/2ddd7793eecd573dbb5b47e2c985aa06606df3cf/uav_simulator/Utils/multi_map_server/src/multi_map_server/msg/_MultiSparseMap3D.py#L120-L124 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/utils/download.py | python | _decompress | (fname) | return uncompressed_path | Decompress for zip and tar file | Decompress for zip and tar file | [
"Decompress",
"for",
"zip",
"and",
"tar",
"file"
] | def _decompress(fname):
"""
Decompress for zip and tar file
"""
logger.info("Decompressing {}...".format(fname))
# For protecting decompressing interupted,
# decompress to fpath_tmp directory firstly, if decompress
# successed, move decompress files to fpath and delete
# fpath_tmp and remove download compress file.
if tarfile.is_tarfile(fname):
uncompressed_path = _uncompress_file_tar(fname)
elif zipfile.is_zipfile(fname):
uncompressed_path = _uncompress_file_zip(fname)
else:
raise TypeError("Unsupport compress file type {}".format(fname))
return uncompressed_path | [
"def",
"_decompress",
"(",
"fname",
")",
":",
"logger",
".",
"info",
"(",
"\"Decompressing {}...\"",
".",
"format",
"(",
"fname",
")",
")",
"# For protecting decompressing interupted,",
"# decompress to fpath_tmp directory firstly, if decompress",
"# successed, move decompress ... | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/utils/download.py#L283-L301 | |
turesnake/tprPix | 6b5471a072a1a8b423834ab04ff03e64df215d5e | deps/fmt-6.1.2/support/docopt.py | python | parse_atom | (tokens, options) | atom ::= '(' expr ')' | '[' expr ']' | 'options'
| long | shorts | argument | command ; | atom ::= '(' expr ')' | '[' expr ']' | 'options'
| long | shorts | argument | command ; | [
"atom",
"::",
"=",
"(",
"expr",
")",
"|",
"[",
"expr",
"]",
"|",
"options",
"|",
"long",
"|",
"shorts",
"|",
"argument",
"|",
"command",
";"
] | def parse_atom(tokens, options):
"""atom ::= '(' expr ')' | '[' expr ']' | 'options'
| long | shorts | argument | command ;
"""
token = tokens.current()
result = []
if token in '([':
tokens.move()
matching, pattern = {'(': [')', Required], '[': [']', Optional]}[token]
result = pattern(*parse_expr(tokens, options))
if tokens.move() != matching:
raise tokens.error("unmatched '%s'" % token)
return [result]
elif token == 'options':
tokens.move()
return [OptionsShortcut()]
elif token.startswith('--') and token != '--':
return parse_long(tokens, options)
elif token.startswith('-') and token not in ('-', '--'):
return parse_shorts(tokens, options)
elif token.startswith('<') and token.endswith('>') or token.isupper():
return [Argument(tokens.move())]
else:
return [Command(tokens.move())] | [
"def",
"parse_atom",
"(",
"tokens",
",",
"options",
")",
":",
"token",
"=",
"tokens",
".",
"current",
"(",
")",
"result",
"=",
"[",
"]",
"if",
"token",
"in",
"'(['",
":",
"tokens",
".",
"move",
"(",
")",
"matching",
",",
"pattern",
"=",
"{",
"'('",... | https://github.com/turesnake/tprPix/blob/6b5471a072a1a8b423834ab04ff03e64df215d5e/deps/fmt-6.1.2/support/docopt.py#L402-L425 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/control-examples/klampt_catkin/src/klampt/scripts/rosbaxtercontroller.py | python | RosBaxterController.setPositionCommand | (self,inputs,res,index,value) | Given a return dictionary res for the output() function, sets a joint command for a single
link, qdes[index]=value. If a velocity command is already given, this will figure out how to
go there. Index can also be a joint name. | Given a return dictionary res for the output() function, sets a joint command for a single
link, qdes[index]=value. If a velocity command is already given, this will figure out how to
go there. Index can also be a joint name. | [
"Given",
"a",
"return",
"dictionary",
"res",
"for",
"the",
"output",
"()",
"function",
"sets",
"a",
"joint",
"command",
"for",
"a",
"single",
"link",
"qdes",
"[",
"index",
"]",
"=",
"value",
".",
"If",
"a",
"velocity",
"command",
"is",
"already",
"given"... | def setPositionCommand(self,inputs,res,index,value):
"""Given a return dictionary res for the output() function, sets a joint command for a single
link, qdes[index]=value. If a velocity command is already given, this will figure out how to
go there. Index can also be a joint name."""
if isinstance(index,str):
#perform the mapping automatically
index = self.nameToLinkIndex[index]
#klampt can only do uniform position, velocity, or torque commands
if 'qcmd' in res:
res['qcmd'][index] = value
elif 'dqcmd' in res:
res['dqcmd'][index] = (value - inputs['qcmd'][index]) / inputs['dt']
res['tcmd']=inputs['dt']
elif 'torquecmd' in res:
print "Cannot combine joint position commands with joint torque commands"
else:
#no joint commands set yet, set a position command
res['qcmd'] = inputs['qcmd']
res['qcmd'][index] = value | [
"def",
"setPositionCommand",
"(",
"self",
",",
"inputs",
",",
"res",
",",
"index",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"str",
")",
":",
"#perform the mapping automatically",
"index",
"=",
"self",
".",
"nameToLinkIndex",
"[",
"index... | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/control-examples/klampt_catkin/src/klampt/scripts/rosbaxtercontroller.py#L215-L233 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.