nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | buildconfig/cmakelists_utils.py | python | add_to_cmake | (subproject, classname, args, subfolder) | Add the class to the cmake list of the given class
Parameters:
subproject : API, Kernel
classname : name of the class
args : argparse args
subfolder : subfolder under inc and src | Add the class to the cmake list of the given class
Parameters:
subproject : API, Kernel
classname : name of the class
args : argparse args
subfolder : subfolder under inc and src | [
"Add",
"the",
"class",
"to",
"the",
"cmake",
"list",
"of",
"the",
"given",
"class",
"Parameters",
":",
"subproject",
":",
"API",
"Kernel",
"classname",
":",
"name",
"of",
"the",
"class",
"args",
":",
"argparse",
"args",
"subfolder",
":",
"subfolder",
"unde... | def add_to_cmake(subproject, classname, args, subfolder):
""" Add the class to the cmake list of the given class
Parameters:
subproject : API, Kernel
classname : name of the class
args : argparse args
subfolder : subfolder under inc and src
"""
basedir, header_folder = find_basedir(args.project, subproject)
cmake_path = os.path.join(basedir, "CMakeLists.txt")
source = open(cmake_path).read()
lines = source.split("\n")
if args.header:
lines = redo_cmake_section(lines, "INC_FILES", "inc/" + header_folder + "/" + subfolder + classname + ".h")
if args.cpp:
lines = redo_cmake_section(lines, "SRC_FILES", "src/" + subfolder + classname + ".cpp")
if args.test:
lines = redo_cmake_section(lines, "TEST_FILES", classname + "Test.h")
f = open(cmake_path, 'w')
text = "\n".join(lines)
f.write(text)
f.close() | [
"def",
"add_to_cmake",
"(",
"subproject",
",",
"classname",
",",
"args",
",",
"subfolder",
")",
":",
"basedir",
",",
"header_folder",
"=",
"find_basedir",
"(",
"args",
".",
"project",
",",
"subproject",
")",
"cmake_path",
"=",
"os",
".",
"path",
".",
"join... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/buildconfig/cmakelists_utils.py#L130-L153 | ||
cornell-zhang/heterocl | 6d9e4b4acc2ee2707b2d25b27298c0335bccedfd | python/heterocl/tvm/build_module.py | python | DumpIR.exit | (self) | recover outermost nest | recover outermost nest | [
"recover",
"outermost",
"nest"
] | def exit(self):
"""recover outermost nest"""
if DumpIR.scope_level > 1:
return
# recover decorated functions
for f in self._recover_list:
f()
schedule.ScheduleOps = self._old_sgpass
BuildConfig.current.add_lower_pass = self._old_custom_pass
DumpIR.scope_level -= 1 | [
"def",
"exit",
"(",
"self",
")",
":",
"if",
"DumpIR",
".",
"scope_level",
">",
"1",
":",
"return",
"# recover decorated functions",
"for",
"f",
"in",
"self",
".",
"_recover_list",
":",
"f",
"(",
")",
"schedule",
".",
"ScheduleOps",
"=",
"self",
".",
"_ol... | https://github.com/cornell-zhang/heterocl/blob/6d9e4b4acc2ee2707b2d25b27298c0335bccedfd/python/heterocl/tvm/build_module.py#L94-L103 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/distutils/misc_util.py | python | allpath | (name) | return os.path.join(*splitted) | Convert a /-separated pathname to one using the OS's path separator. | Convert a /-separated pathname to one using the OS's path separator. | [
"Convert",
"a",
"/",
"-",
"separated",
"pathname",
"to",
"one",
"using",
"the",
"OS",
"s",
"path",
"separator",
"."
] | def allpath(name):
"Convert a /-separated pathname to one using the OS's path separator."
splitted = name.split('/')
return os.path.join(*splitted) | [
"def",
"allpath",
"(",
"name",
")",
":",
"splitted",
"=",
"name",
".",
"split",
"(",
"'/'",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"*",
"splitted",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/distutils/misc_util.py#L127-L130 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/graph_editor/transform.py | python | copy | (sgv, dst_graph=None, dst_scope="", src_scope="",
reuse_dst_scope=False) | return copier(
sgv, dst_graph, dst_scope, src_scope, reuse_dst_scope=reuse_dst_scope) | Copy a subgraph.
Args:
sgv: the source subgraph-view. This argument is converted to a subgraph
using the same rules than the function subgraph.make_view.
dst_graph: the destination graph.
dst_scope: the destination scope.
src_scope: the source scope.
reuse_dst_scope: if True the dst_scope is re-used if it already exists.
Otherwise, the scope is given a unique name based on the one given
by appending an underscore followed by a digit (default).
Returns:
A tuple `(sgv, info)` where:
`sgv` is the transformed subgraph view;
`info` is an instance of TransformerInfo containing
information about the transform, including mapping between
original and transformed tensors and operations.
Raises:
TypeError: if `dst_graph` is not a `tf.Graph`.
StandardError: if sgv cannot be converted to a SubGraphView using
the same rules than the function subgraph.make_view. | Copy a subgraph. | [
"Copy",
"a",
"subgraph",
"."
] | def copy(sgv, dst_graph=None, dst_scope="", src_scope="",
reuse_dst_scope=False):
"""Copy a subgraph.
Args:
sgv: the source subgraph-view. This argument is converted to a subgraph
using the same rules than the function subgraph.make_view.
dst_graph: the destination graph.
dst_scope: the destination scope.
src_scope: the source scope.
reuse_dst_scope: if True the dst_scope is re-used if it already exists.
Otherwise, the scope is given a unique name based on the one given
by appending an underscore followed by a digit (default).
Returns:
A tuple `(sgv, info)` where:
`sgv` is the transformed subgraph view;
`info` is an instance of TransformerInfo containing
information about the transform, including mapping between
original and transformed tensors and operations.
Raises:
TypeError: if `dst_graph` is not a `tf.Graph`.
StandardError: if sgv cannot be converted to a SubGraphView using
the same rules than the function subgraph.make_view.
"""
sgv = subgraph.make_view(sgv)
if dst_graph is None:
dst_graph = sgv.graph
if not isinstance(dst_graph, tf_ops.Graph):
raise TypeError("Expected a tf.Graph, got: {}".format(type(dst_graph)))
copier = Transformer()
return copier(
sgv, dst_graph, dst_scope, src_scope, reuse_dst_scope=reuse_dst_scope) | [
"def",
"copy",
"(",
"sgv",
",",
"dst_graph",
"=",
"None",
",",
"dst_scope",
"=",
"\"\"",
",",
"src_scope",
"=",
"\"\"",
",",
"reuse_dst_scope",
"=",
"False",
")",
":",
"sgv",
"=",
"subgraph",
".",
"make_view",
"(",
"sgv",
")",
"if",
"dst_graph",
"is",
... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/graph_editor/transform.py#L543-L575 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tempfile.py | python | mktemp | (suffix="", prefix=template, dir=None) | User-callable function to return a unique temporary file name. The
file is not created.
Arguments are similar to mkstemp, except that the 'text' argument is
not accepted, and suffix=None, prefix=None and bytes file names are not
supported.
THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may
refer to a file that did not exist at some point, but by the time
you get around to creating it, someone else may have beaten you to
the punch. | User-callable function to return a unique temporary file name. The
file is not created. | [
"User",
"-",
"callable",
"function",
"to",
"return",
"a",
"unique",
"temporary",
"file",
"name",
".",
"The",
"file",
"is",
"not",
"created",
"."
] | def mktemp(suffix="", prefix=template, dir=None):
"""User-callable function to return a unique temporary file name. The
file is not created.
Arguments are similar to mkstemp, except that the 'text' argument is
not accepted, and suffix=None, prefix=None and bytes file names are not
supported.
THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may
refer to a file that did not exist at some point, but by the time
you get around to creating it, someone else may have beaten you to
the punch.
"""
## from warnings import warn as _warn
## _warn("mktemp is a potential security risk to your program",
## RuntimeWarning, stacklevel=2)
if dir is None:
dir = gettempdir()
names = _get_candidate_names()
for seq in range(TMP_MAX):
name = next(names)
file = _os.path.join(dir, prefix + name + suffix)
if not _exists(file):
return file
raise FileExistsError(_errno.EEXIST,
"No usable temporary filename found") | [
"def",
"mktemp",
"(",
"suffix",
"=",
"\"\"",
",",
"prefix",
"=",
"template",
",",
"dir",
"=",
"None",
")",
":",
"## from warnings import warn as _warn",
"## _warn(\"mktemp is a potential security risk to your program\",",
"## RuntimeWarning, stacklevel=2)",
"if",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tempfile.py#L382-L411 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/py/editor.py | python | directory | (parent=None, message='Choose a directory', path='', style=0,
pos=wx.DefaultPosition, size=wx.DefaultSize) | return result | Dir dialog wrapper function. | Dir dialog wrapper function. | [
"Dir",
"dialog",
"wrapper",
"function",
"."
] | def directory(parent=None, message='Choose a directory', path='', style=0,
pos=wx.DefaultPosition, size=wx.DefaultSize):
"""Dir dialog wrapper function."""
dialog = wx.DirDialog(parent, message, path, style, pos, size)
result = DialogResults(dialog.ShowModal())
if result.positive:
result.path = dialog.GetPath()
else:
result.path = None
dialog.Destroy()
return result | [
"def",
"directory",
"(",
"parent",
"=",
"None",
",",
"message",
"=",
"'Choose a directory'",
",",
"path",
"=",
"''",
",",
"style",
"=",
"0",
",",
"pos",
"=",
"wx",
".",
"DefaultPosition",
",",
"size",
"=",
"wx",
".",
"DefaultSize",
")",
":",
"dialog",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/py/editor.py#L818-L828 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/lib/grpc_debug_server.py | python | EventListenerBaseServicer._process_encoded_graph_def_in_chunks | (self,
event,
graph_def_chunks) | Process an Event proto containing a chunk of encoded GraphDef.
Args:
event: the Event proto containing the chunk of encoded GraphDef.
graph_def_chunks: A dict mapping keys for GraphDefs (i.e.,
"<graph_def_hash>,<device_name>,<wall_time>") to a list of chunks of
encoded GraphDefs.
Returns:
If all chunks of the GraphDef have arrived,
return decoded GraphDef proto, device name, wall_time.
Otherwise,
return None, None, None. | Process an Event proto containing a chunk of encoded GraphDef. | [
"Process",
"an",
"Event",
"proto",
"containing",
"a",
"chunk",
"of",
"encoded",
"GraphDef",
"."
] | def _process_encoded_graph_def_in_chunks(self,
event,
graph_def_chunks):
"""Process an Event proto containing a chunk of encoded GraphDef.
Args:
event: the Event proto containing the chunk of encoded GraphDef.
graph_def_chunks: A dict mapping keys for GraphDefs (i.e.,
"<graph_def_hash>,<device_name>,<wall_time>") to a list of chunks of
encoded GraphDefs.
Returns:
If all chunks of the GraphDef have arrived,
return decoded GraphDef proto, device name, wall_time.
Otherwise,
return None, None, None.
"""
graph_def = graph_pb2.GraphDef()
index_bar_0 = event.graph_def.find(b"|")
index_bar_1 = event.graph_def.find(b"|", index_bar_0 + 1)
index_bar_2 = event.graph_def.find(b"|", index_bar_1 + 1)
graph_def_hash_device_timestamp = event.graph_def[:index_bar_0]
chunk_index = int(event.graph_def[index_bar_0 + 1 : index_bar_1])
num_chunks = int(event.graph_def[index_bar_1 + 1 : index_bar_2])
if graph_def_hash_device_timestamp not in graph_def_chunks:
graph_def_chunks[graph_def_hash_device_timestamp] = [None] * num_chunks
graph_def_chunks[graph_def_hash_device_timestamp][
chunk_index] = event.graph_def[index_bar_2 + 1:]
if all(graph_def_chunks[graph_def_hash_device_timestamp]):
device_name = graph_def_hash_device_timestamp.split(b",")[1]
wall_time = int(graph_def_hash_device_timestamp.split(b",")[2])
graph_def.ParseFromString(
b"".join(graph_def_chunks[graph_def_hash_device_timestamp]))
del graph_def_chunks[graph_def_hash_device_timestamp]
self._process_graph_def(graph_def)
return graph_def, device_name, wall_time
else:
return None, None, None | [
"def",
"_process_encoded_graph_def_in_chunks",
"(",
"self",
",",
"event",
",",
"graph_def_chunks",
")",
":",
"graph_def",
"=",
"graph_pb2",
".",
"GraphDef",
"(",
")",
"index_bar_0",
"=",
"event",
".",
"graph_def",
".",
"find",
"(",
"b\"|\"",
")",
"index_bar_1",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/lib/grpc_debug_server.py#L284-L321 | ||
freeorion/freeorion | c266a40eccd3a99a17de8fe57c36ef6ba3771665 | default/python/universe_generation/monsters.py | python | StarlaneAlteringMonsters.place | (self, system, plan) | Create map altering monster fleet ''plan'' at ''system''. | Create map altering monster fleet ''plan'' at ''system''. | [
"Create",
"map",
"altering",
"monster",
"fleet",
"plan",
"at",
"system",
"."
] | def place(self, system, plan):
"""
Create map altering monster fleet ''plan'' at ''system''.
"""
local_lanes = {(min(system, s), max(system, s)) for s in fo.sys_get_starlanes(system)}
populate_monster_fleet(plan, system)
if system not in self.placed:
self.placed.add(system)
self.removed_lanes |= local_lanes | [
"def",
"place",
"(",
"self",
",",
"system",
",",
"plan",
")",
":",
"local_lanes",
"=",
"{",
"(",
"min",
"(",
"system",
",",
"s",
")",
",",
"max",
"(",
"system",
",",
"s",
")",
")",
"for",
"s",
"in",
"fo",
".",
"sys_get_starlanes",
"(",
"system",
... | https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/universe_generation/monsters.py#L55-L64 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/propgrid.py | python | PGProperty.SetValueInEvent | (*args, **kwargs) | return _propgrid.PGProperty_SetValueInEvent(*args, **kwargs) | SetValueInEvent(self, wxVariant value) | SetValueInEvent(self, wxVariant value) | [
"SetValueInEvent",
"(",
"self",
"wxVariant",
"value",
")"
] | def SetValueInEvent(*args, **kwargs):
"""SetValueInEvent(self, wxVariant value)"""
return _propgrid.PGProperty_SetValueInEvent(*args, **kwargs) | [
"def",
"SetValueInEvent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PGProperty_SetValueInEvent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L718-L720 | |
chatopera/clause | dee31153d5ffdef33deedb6bff03e7806c296968 | var/assets/clients/gen-py/clause/Serving.py | python | Client.myDicts | (self, request) | return self.recv_myDicts() | Parameters:
- request | Parameters:
- request | [
"Parameters",
":",
"-",
"request"
] | def myDicts(self, request):
"""
Parameters:
- request
"""
self.send_myDicts(request)
return self.recv_myDicts() | [
"def",
"myDicts",
"(",
"self",
",",
"request",
")",
":",
"self",
".",
"send_myDicts",
"(",
"request",
")",
"return",
"self",
".",
"recv_myDicts",
"(",
")"
] | https://github.com/chatopera/clause/blob/dee31153d5ffdef33deedb6bff03e7806c296968/var/assets/clients/gen-py/clause/Serving.py#L734-L741 | |
genn-team/genn | 75e1eb218cafa228bf36ae4613d1ce26e877b12c | pygenn/genn_model.py | python | GeNNModel.push_state_to_device | (self, pop_name) | Push state to the device for a given population | Push state to the device for a given population | [
"Push",
"state",
"to",
"the",
"device",
"for",
"a",
"given",
"population"
] | def push_state_to_device(self, pop_name):
"""Push state to the device for a given population"""
if not self._loaded:
raise Exception("GeNN model has to be loaded before pushing")
self._slm.push_state_to_device(pop_name) | [
"def",
"push_state_to_device",
"(",
"self",
",",
"pop_name",
")",
":",
"if",
"not",
"self",
".",
"_loaded",
":",
"raise",
"Exception",
"(",
"\"GeNN model has to be loaded before pushing\"",
")",
"self",
".",
"_slm",
".",
"push_state_to_device",
"(",
"pop_name",
")... | https://github.com/genn-team/genn/blob/75e1eb218cafa228bf36ae4613d1ce26e877b12c/pygenn/genn_model.py#L767-L772 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/framework/tensor_shape.py | python | Dimension.__sub__ | (self, other) | Returns the subtraction of `other` from `self`.
Dimensions are subtracted as follows:
Dimension(m) - Dimension(n) == Dimension(m - n)
Dimension(m) - Dimension(None) == Dimension(None)
Dimension(None) - Dimension(n) == Dimension(None)
Dimension(None) - Dimension(None) == Dimension(None)
Args:
other: Another Dimension.
Returns:
A Dimension whose value is the subtraction of sum of `other` from `self`. | Returns the subtraction of `other` from `self`. | [
"Returns",
"the",
"subtraction",
"of",
"other",
"from",
"self",
"."
] | def __sub__(self, other):
"""Returns the subtraction of `other` from `self`.
Dimensions are subtracted as follows:
Dimension(m) - Dimension(n) == Dimension(m - n)
Dimension(m) - Dimension(None) == Dimension(None)
Dimension(None) - Dimension(n) == Dimension(None)
Dimension(None) - Dimension(None) == Dimension(None)
Args:
other: Another Dimension.
Returns:
A Dimension whose value is the subtraction of sum of `other` from `self`.
"""
other = as_dimension(other)
if self._value is None or other.value is None:
return Dimension(None)
else:
return Dimension(self._value - other.value) | [
"def",
"__sub__",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"as_dimension",
"(",
"other",
")",
"if",
"self",
".",
"_value",
"is",
"None",
"or",
"other",
".",
"value",
"is",
"None",
":",
"return",
"Dimension",
"(",
"None",
")",
"else",
":",
... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/framework/tensor_shape.py#L161-L181 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | FileConfig_GetLocalFileName | (*args, **kwargs) | return _misc_.FileConfig_GetLocalFileName(*args, **kwargs) | FileConfig_GetLocalFileName(String szFile, int style=0) -> String | FileConfig_GetLocalFileName(String szFile, int style=0) -> String | [
"FileConfig_GetLocalFileName",
"(",
"String",
"szFile",
"int",
"style",
"=",
"0",
")",
"-",
">",
"String"
] | def FileConfig_GetLocalFileName(*args, **kwargs):
"""FileConfig_GetLocalFileName(String szFile, int style=0) -> String"""
return _misc_.FileConfig_GetLocalFileName(*args, **kwargs) | [
"def",
"FileConfig_GetLocalFileName",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"FileConfig_GetLocalFileName",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L3533-L3535 | |
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | pygimli/physics/SIP/models.py | python | modelColeColeRhoDouble | (f, rho, m1, t1, c1, m2, t2, c2, a=1) | return rho * (Z1 + Z2) | Frequency-domain Double Cole-Cole impedance model
Frequency-domain Double Cole-Cole impedance model returns the sum of
two Cole-Cole Models with a common amplitude.
Z = rho * (Z1(Cole-Cole) + Z2(Cole-Cole)) | Frequency-domain Double Cole-Cole impedance model | [
"Frequency",
"-",
"domain",
"Double",
"Cole",
"-",
"Cole",
"impedance",
"model"
] | def modelColeColeRhoDouble(f, rho, m1, t1, c1, m2, t2, c2, a=1):
"""Frequency-domain Double Cole-Cole impedance model
Frequency-domain Double Cole-Cole impedance model returns the sum of
two Cole-Cole Models with a common amplitude.
Z = rho * (Z1(Cole-Cole) + Z2(Cole-Cole))
"""
Z1 = modelColeColeRho(f, rho=1, m=m1, tau=t1, c=c1, a=a)
Z2 = modelColeColeRho(f, rho=1, m=m2, tau=t2, c=c2, a=a)
return rho * (Z1 + Z2) | [
"def",
"modelColeColeRhoDouble",
"(",
"f",
",",
"rho",
",",
"m1",
",",
"t1",
",",
"c1",
",",
"m2",
",",
"t2",
",",
"c2",
",",
"a",
"=",
"1",
")",
":",
"Z1",
"=",
"modelColeColeRho",
"(",
"f",
",",
"rho",
"=",
"1",
",",
"m",
"=",
"m1",
",",
... | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/SIP/models.py#L88-L97 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | MenuItem_GetLabelText | (*args, **kwargs) | return _core_.MenuItem_GetLabelText(*args, **kwargs) | MenuItem_GetLabelText(String label) -> String | MenuItem_GetLabelText(String label) -> String | [
"MenuItem_GetLabelText",
"(",
"String",
"label",
")",
"-",
">",
"String"
] | def MenuItem_GetLabelText(*args, **kwargs):
"""MenuItem_GetLabelText(String label) -> String"""
return _core_.MenuItem_GetLabelText(*args, **kwargs) | [
"def",
"MenuItem_GetLabelText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"MenuItem_GetLabelText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L12628-L12630 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLEnergyTransfer.py | python | IndirectILLEnergyTransfer._get_single_detectors_number | (ws) | return mtd[ws].getNumberHistograms() - N_TUBES * N_PIXELS_PER_TUBE - monitor_count | Get the total number of single detectors in the workspace.
@param ws :: the workspace name, a string
@return the total number of single detectors | Get the total number of single detectors in the workspace. | [
"Get",
"the",
"total",
"number",
"of",
"single",
"detectors",
"in",
"the",
"workspace",
"."
] | def _get_single_detectors_number(ws):
"""
Get the total number of single detectors in the workspace.
@param ws :: the workspace name, a string
@return the total number of single detectors
"""
monitor_count = N_MONITOR if mtd[ws].getDetector(0).isMonitor() else 0
return mtd[ws].getNumberHistograms() - N_TUBES * N_PIXELS_PER_TUBE - monitor_count | [
"def",
"_get_single_detectors_number",
"(",
"ws",
")",
":",
"monitor_count",
"=",
"N_MONITOR",
"if",
"mtd",
"[",
"ws",
"]",
".",
"getDetector",
"(",
"0",
")",
".",
"isMonitor",
"(",
")",
"else",
"0",
"return",
"mtd",
"[",
"ws",
"]",
".",
"getNumberHistog... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLEnergyTransfer.py#L797-L804 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ultimatelistctrl.py | python | UltimateListLineData.InitItems | (self, num) | Initializes the list of items.
:param `num`: the initial number of items to store. | Initializes the list of items. | [
"Initializes",
"the",
"list",
"of",
"items",
"."
] | def InitItems(self, num):
"""
Initializes the list of items.
:param `num`: the initial number of items to store.
"""
for i in xrange(num):
self._items.append(UltimateListItemData(self._owner)) | [
"def",
"InitItems",
"(",
"self",
",",
"num",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"num",
")",
":",
"self",
".",
"_items",
".",
"append",
"(",
"UltimateListItemData",
"(",
"self",
".",
"_owner",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L4076-L4084 | ||
glotzerlab/hoomd-blue | f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a | hoomd/data/parameterdicts.py | python | ParameterDict.__len__ | (self) | return len(self._dict) | int: The number of keys. | int: The number of keys. | [
"int",
":",
"The",
"number",
"of",
"keys",
"."
] | def __len__(self):
"""int: The number of keys."""
return len(self._dict) | [
"def",
"__len__",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"_dict",
")"
] | https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/data/parameterdicts.py#L687-L689 | |
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | clang/tools/scan-build-py/lib/libscanbuild/report.py | python | encode_value | (container, key, encode) | Run 'encode' on 'container[key]' value and update it. | Run 'encode' on 'container[key]' value and update it. | [
"Run",
"encode",
"on",
"container",
"[",
"key",
"]",
"value",
"and",
"update",
"it",
"."
] | def encode_value(container, key, encode):
""" Run 'encode' on 'container[key]' value and update it. """
if key in container:
value = encode(container[key])
container.update({key: value}) | [
"def",
"encode_value",
"(",
"container",
",",
"key",
",",
"encode",
")",
":",
"if",
"key",
"in",
"container",
":",
"value",
"=",
"encode",
"(",
"container",
"[",
"key",
"]",
")",
"container",
".",
"update",
"(",
"{",
"key",
":",
"value",
"}",
")"
] | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/clang/tools/scan-build-py/lib/libscanbuild/report.py#L533-L538 | ||
hakuna-m/wubiuefi | caec1af0a09c78fd5a345180ada1fe45e0c63493 | src/pypack/altgraph/Graph.py | python | Graph.restore_all_nodes | (self) | Restores all hidden nodes. | Restores all hidden nodes. | [
"Restores",
"all",
"hidden",
"nodes",
"."
] | def restore_all_nodes(self):
"""
Restores all hidden nodes.
"""
for node in self.hidden_nodes.keys():
self.restore_node(node) | [
"def",
"restore_all_nodes",
"(",
"self",
")",
":",
"for",
"node",
"in",
"self",
".",
"hidden_nodes",
".",
"keys",
"(",
")",
":",
"self",
".",
"restore_node",
"(",
"node",
")"
] | https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/pypack/altgraph/Graph.py#L169-L174 | ||
rodeofx/OpenWalter | 6116fbe3f04f1146c854afbfbdbe944feaee647e | walter/common/walterWidgets/walterBaseTreeView.py | python | BaseModel.columnCount | (self, parent=None) | return 1 | Return the number of columns for the children of the given parent. | Return the number of columns for the children of the given parent. | [
"Return",
"the",
"number",
"of",
"columns",
"for",
"the",
"children",
"of",
"the",
"given",
"parent",
"."
] | def columnCount(self, parent=None):
"""Return the number of columns for the children of the given parent."""
return 1 | [
"def",
"columnCount",
"(",
"self",
",",
"parent",
"=",
"None",
")",
":",
"return",
"1"
] | https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/common/walterWidgets/walterBaseTreeView.py#L148-L150 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/packages/urllib3/__init__.py | python | disable_warnings | (category=exceptions.HTTPWarning) | Helper for quickly disabling all urllib3 warnings. | Helper for quickly disabling all urllib3 warnings. | [
"Helper",
"for",
"quickly",
"disabling",
"all",
"urllib3",
"warnings",
"."
] | def disable_warnings(category=exceptions.HTTPWarning):
"""
Helper for quickly disabling all urllib3 warnings.
"""
warnings.simplefilter('ignore', category) | [
"def",
"disable_warnings",
"(",
"category",
"=",
"exceptions",
".",
"HTTPWarning",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"'ignore'",
",",
"category",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/packages/urllib3/__init__.py#L65-L69 | ||
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/oldnumeric/ma.py | python | MaskedArray.raw_mask | (self) | return self._mask | Obsolete; use mask property instead.
May be noncontiguous. Expert use only. | Obsolete; use mask property instead.
May be noncontiguous. Expert use only. | [
"Obsolete",
";",
"use",
"mask",
"property",
"instead",
".",
"May",
"be",
"noncontiguous",
".",
"Expert",
"use",
"only",
"."
] | def raw_mask (self):
""" Obsolete; use mask property instead.
May be noncontiguous. Expert use only.
"""
return self._mask | [
"def",
"raw_mask",
"(",
"self",
")",
":",
"return",
"self",
".",
"_mask"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/oldnumeric/ma.py#L1300-L1304 | |
lawy623/SVS | b7c7ae367c82a4797ff4a896a2ff304f02e7f724 | caffe/python/caffe/draw.py | python | get_pooling_types_dict | () | return d | Get dictionary mapping pooling type number to type name | Get dictionary mapping pooling type number to type name | [
"Get",
"dictionary",
"mapping",
"pooling",
"type",
"number",
"to",
"type",
"name"
] | def get_pooling_types_dict():
"""Get dictionary mapping pooling type number to type name
"""
desc = caffe_pb2.PoolingParameter.PoolMethod.DESCRIPTOR
d = {}
for k, v in desc.values_by_name.items():
d[v.number] = k
return d | [
"def",
"get_pooling_types_dict",
"(",
")",
":",
"desc",
"=",
"caffe_pb2",
".",
"PoolingParameter",
".",
"PoolMethod",
".",
"DESCRIPTOR",
"d",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"desc",
".",
"values_by_name",
".",
"items",
"(",
")",
":",
"d",
"[... | https://github.com/lawy623/SVS/blob/b7c7ae367c82a4797ff4a896a2ff304f02e7f724/caffe/python/caffe/draw.py#L36-L43 | |
InsightSoftwareConsortium/ITK | 87acfce9a93d928311c38bc371b666b515b9f19d | Modules/ThirdParty/pygccxml/src/pygccxml/declarations/class_declaration.py | python | class_t.private_members | (self) | return self._private_members | list of all private :class:`members <declarationt_>` | list of all private :class:`members <declarationt_>` | [
"list",
"of",
"all",
"private",
":",
"class",
":",
"members",
"<declarationt_",
">"
] | def private_members(self):
"""list of all private :class:`members <declarationt_>`"""
return self._private_members | [
"def",
"private_members",
"(",
"self",
")",
":",
"return",
"self",
".",
"_private_members"
] | https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/class_declaration.py#L334-L336 | |
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/dot_layout.py | python | dot_layout | (cy_elements,edge_labels=False,subgraph_boxes=False,node_gt=None) | return cy_elements | Get a CyElements object and augment it (in-place) with positions,
widths, heights, and spline data from a dot based layout.
edge_labels is true if labels should appear on edges
subgraph_boxes is true if boxes should be drawn around subgraphs
Returns the object. | Get a CyElements object and augment it (in-place) with positions,
widths, heights, and spline data from a dot based layout. | [
"Get",
"a",
"CyElements",
"object",
"and",
"augment",
"it",
"(",
"in",
"-",
"place",
")",
"with",
"positions",
"widths",
"heights",
"and",
"spline",
"data",
"from",
"a",
"dot",
"based",
"layout",
"."
] | def dot_layout(cy_elements,edge_labels=False,subgraph_boxes=False,node_gt=None):
"""
Get a CyElements object and augment it (in-place) with positions,
widths, heights, and spline data from a dot based layout.
edge_labels is true if labels should appear on edges
subgraph_boxes is true if boxes should be drawn around subgraphs
Returns the object.
"""
elements = cy_elements.elements
# g = AGraph(directed=True, strict=False)
g = AGraph(directed=True, strict=False, forcelabels=True)
# make transitive relations appear top to bottom
elements = list(elements)
nodes_by_id = dict(
(e["data"]["id"], e)
for e in elements if e["group"] == "nodes"
)
order = [
(nodes_by_id[e["data"]["source"]], nodes_by_id[e["data"]["target"]])
for e in elements if
e["group"] == "edges" and
"transitive" in e["data"] and
e["data"]["transitive"]
]
elements = topological_sort(elements, order, lambda e: e["data"]["id"])
# get the node id's and stable sort them by cluster
# the idea here is to convert the graph into a dag by sorting
# the nodes, then reversing the back edges. In particular, we try to make
# all the edges between two clusters go in the same direction so clustering
# doesn't result in horizontal edges, which dot renders badly.
sorted_nodes = [e["data"]["id"] for e in elements if e["group"] == "nodes"]
sorted_nodes = sorted(enumerate(sorted_nodes),key = lambda x: (nodes_by_id[x[1]]["data"]["cluster"],x[0]))
sorted_nodes = [y for idx,y in sorted_nodes]
node_key = dict((id,idx) for idx,id in enumerate(sorted_nodes))
if node_gt is None:
node_gt = lambda X,y:False
else:
node_gt = lambda x,y: node_key[x] > node_key[y]
# add nodes to the graph
for e in elements:
if e["group"] == "nodes" and e["classes"] != 'non_existing':
g.add_node(e["data"]["id"], label=e["data"]["label"].replace('\n', '\\n'))
# TODO: remove this, it's specific to leader_demo
weight = {
'reach': 10,
'le': 10,
'id': 1,
}
constraint = {
'pending': False,
}
# add edges to the graph
for e in elements:
if e["group"] == "edges":
# kwargs = {'weight': weight.get(e["data"]["obj"], 0)},
kwargs = {'label':e["data"]["label"]} if edge_labels else {}
if node_gt(e["data"]["source"],e["data"]["target"]):
g.add_edge(
e["data"]["target"],
e["data"]["source"],
e["data"]["id"],
dir = 'back',
**kwargs
#constraint=constraint.get(e["data"]["obj"], True),
)
else:
g.add_edge(
e["data"]["source"],
e["data"]["target"],
e["data"]["id"],
**kwargs
#constraint=constraint.get(e["data"]["obj"], True),
)
# add clusters
clusters = defaultdict(list)
for e in elements:
if e["group"] == "nodes" and e["data"]["cluster"] is not None and e["classes"] != 'non_existing':
clusters[e["data"]["cluster"]].append(e["data"]["id"])
for i, k in enumerate(sorted(clusters.keys())):
g.add_subgraph(
name='cluster_{}'.format(i),
nbunch=clusters[k],
rank='min',
)
# now get positions, heights, widths, and bsplines
g.layout(prog='dot')
# get the y origin. we want the top left of the graph to be a
# fixed coordinate (hopefully (0,0)) so the graph doesn't jump when
# its height changes. Unfortunately, pygraphviz has a bug a gives
# the wrong bbox, so we compute the max y coord.
# bbox = pygraphviz.graphviz.agget(g.handle,'bb')
global y_origin
y_origin = 0.0
for n in g.nodes():
top = float(n.attr['pos'].split(',')[1]) + float(n.attr['height'])/2
if top > y_origin:
y_origin = top
if subgraph_boxes:
for sg in g.subgraphs():
top = float(sg.graph_attr['bb'].split(',')[3])
if top > y_origin:
y_origin = top
for e in elements:
if e["group"] == "nodes" and e["classes"] != 'non_existing':
attr = g.get_node(e["data"]["id"]).attr
e["position"] = _to_position(attr['pos'])
e["data"]["width"] = 72 * float(attr['width'])
e["data"]["height"] = 72 * float(attr['height'])
elif e["group"] == "edges":
if node_gt(e["data"]["source"],e["data"]["target"]):
attr = g.get_edge(e["data"]["target"], e["data"]["source"], e["data"]["id"]).attr
pos = attr['pos']
pe = pos.split()
ppe = pe[1:]
ppe.reverse()
pos = ' '.join([pe[0].replace('s','e')] + ppe)
else:
attr = g.get_edge(e["data"]["source"], e["data"]["target"], e["data"]["id"]).attr
pos = attr['pos']
e["data"].update(_to_edge_position(pos))
if edge_labels and e["data"]["label"] != '':
e["data"]["lp"] = _to_position(attr['lp'])
# g.draw('g.png')
if subgraph_boxes:
for sg in g.subgraphs():
box = cy_elements.add_shape(sg.name,classes='subgraphs')
coords = _to_coord_list(sg.graph_attr['bb'])
box["data"]["coords"] = coords
return cy_elements | [
"def",
"dot_layout",
"(",
"cy_elements",
",",
"edge_labels",
"=",
"False",
",",
"subgraph_boxes",
"=",
"False",
",",
"node_gt",
"=",
"None",
")",
":",
"elements",
"=",
"cy_elements",
".",
"elements",
"# g = AGraph(directed=True, strict=False)",
"g",
"=",
"AGrap... | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/dot_layout.py#L136-L284 | |
trailofbits/llvm-sanitizer-tutorial | d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99 | llvm/utils/lit/lit/run.py | python | abort_now | () | Abort the current process without doing any exception teardown | Abort the current process without doing any exception teardown | [
"Abort",
"the",
"current",
"process",
"without",
"doing",
"any",
"exception",
"teardown"
] | def abort_now():
"""Abort the current process without doing any exception teardown"""
sys.stdout.flush()
if win32api:
win32api.TerminateProcess(win32api.GetCurrentProcess(), 3)
else:
os.kill(0, 9) | [
"def",
"abort_now",
"(",
")",
":",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"if",
"win32api",
":",
"win32api",
".",
"TerminateProcess",
"(",
"win32api",
".",
"GetCurrentProcess",
"(",
")",
",",
"3",
")",
"else",
":",
"os",
".",
"kill",
"(",
"0",... | https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/utils/lit/lit/run.py#L19-L25 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_gdi.py | python | NativeEncodingInfo.ToString | (*args, **kwargs) | return _gdi_.NativeEncodingInfo_ToString(*args, **kwargs) | ToString(self) -> String | ToString(self) -> String | [
"ToString",
"(",
"self",
")",
"-",
">",
"String"
] | def ToString(*args, **kwargs):
"""ToString(self) -> String"""
return _gdi_.NativeEncodingInfo_ToString(*args, **kwargs) | [
"def",
"ToString",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"NativeEncodingInfo_ToString",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L2082-L2084 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/formats/style.py | python | Styler._background_gradient | (
s,
cmap="PuBu",
low=0,
high=0,
text_color_threshold=0.408,
vmin: Optional[float] = None,
vmax: Optional[float] = None,
) | Color background in a range according to the data. | Color background in a range according to the data. | [
"Color",
"background",
"in",
"a",
"range",
"according",
"to",
"the",
"data",
"."
] | def _background_gradient(
s,
cmap="PuBu",
low=0,
high=0,
text_color_threshold=0.408,
vmin: Optional[float] = None,
vmax: Optional[float] = None,
):
"""
Color background in a range according to the data.
"""
if (
not isinstance(text_color_threshold, (float, int))
or not 0 <= text_color_threshold <= 1
):
msg = "`text_color_threshold` must be a value from 0 to 1."
raise ValueError(msg)
with _mpl(Styler.background_gradient) as (plt, colors):
smin = np.nanmin(s.to_numpy()) if vmin is None else vmin
smax = np.nanmax(s.to_numpy()) if vmax is None else vmax
rng = smax - smin
# extend lower / upper bounds, compresses color range
norm = colors.Normalize(smin - (rng * low), smax + (rng * high))
# matplotlib colors.Normalize modifies inplace?
# https://github.com/matplotlib/matplotlib/issues/5427
rgbas = plt.cm.get_cmap(cmap)(norm(s.to_numpy(dtype=float)))
def relative_luminance(rgba):
"""
Calculate relative luminance of a color.
The calculation adheres to the W3C standards
(https://www.w3.org/WAI/GL/wiki/Relative_luminance)
Parameters
----------
color : rgb or rgba tuple
Returns
-------
float
The relative luminance as a value from 0 to 1
"""
r, g, b = (
x / 12.92 if x <= 0.03928 else ((x + 0.055) / 1.055 ** 2.4)
for x in rgba[:3]
)
return 0.2126 * r + 0.7152 * g + 0.0722 * b
def css(rgba):
dark = relative_luminance(rgba) < text_color_threshold
text_color = "#f1f1f1" if dark else "#000000"
return f"background-color: {colors.rgb2hex(rgba)};color: {text_color};"
if s.ndim == 1:
return [css(rgba) for rgba in rgbas]
else:
return pd.DataFrame(
[[css(rgba) for rgba in row] for row in rgbas],
index=s.index,
columns=s.columns,
) | [
"def",
"_background_gradient",
"(",
"s",
",",
"cmap",
"=",
"\"PuBu\"",
",",
"low",
"=",
"0",
",",
"high",
"=",
"0",
",",
"text_color_threshold",
"=",
"0.408",
",",
"vmin",
":",
"Optional",
"[",
"float",
"]",
"=",
"None",
",",
"vmax",
":",
"Optional",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/formats/style.py#L1069-L1132 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/aui.py | python | AuiMDIChildFrame.IsMaximized | (*args, **kwargs) | return _aui.AuiMDIChildFrame_IsMaximized(*args, **kwargs) | IsMaximized(self) -> bool | IsMaximized(self) -> bool | [
"IsMaximized",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsMaximized(*args, **kwargs):
"""IsMaximized(self) -> bool"""
return _aui.AuiMDIChildFrame_IsMaximized(*args, **kwargs) | [
"def",
"IsMaximized",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiMDIChildFrame_IsMaximized",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/aui.py#L1574-L1576 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | ColourPickerCtrl.SetColour | (self, col) | Returns the currently selected colour. | Returns the currently selected colour. | [
"Returns",
"the",
"currently",
"selected",
"colour",
"."
] | def SetColour(self, col):
"""Returns the currently selected colour."""
self.GetPickerCtrl().SetColour(col)
self.UpdateTextCtrlFromPicker() | [
"def",
"SetColour",
"(",
"self",
",",
"col",
")",
":",
"self",
".",
"GetPickerCtrl",
"(",
")",
".",
"SetColour",
"(",
"col",
")",
"self",
".",
"UpdateTextCtrlFromPicker",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L7027-L7030 | ||
bareos/bareos | 56a10bb368b0a81e977bb51304033fe49d59efb0 | contrib/dir-plugins/graphite/BareosDirPluginGraphiteSender.py | python | BareosDirPluginGraphiteSender.transmitResult | (self, context) | Here we send the result to the Icinga / Nagios server using NSCA
Overload this method if you want ot submit your changes on a different way | Here we send the result to the Icinga / Nagios server using NSCA
Overload this method if you want ot submit your changes on a different way | [
"Here",
"we",
"send",
"the",
"result",
"to",
"the",
"Icinga",
"/",
"Nagios",
"server",
"using",
"NSCA",
"Overload",
"this",
"method",
"if",
"you",
"want",
"ot",
"submit",
"your",
"changes",
"on",
"a",
"different",
"way"
] | def transmitResult(self, context):
'''
Here we send the result to the Icinga / Nagios server using NSCA
Overload this method if you want ot submit your changes on a different way
'''
DebugMessage(context, 100, "Submitting metrics to {}:{}".format(self.collectorHost,
self.collectorPort))
try:
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((self.collectorHost, self.collectorPort))
for key, value in self.metrics.items():
sock.send('{prefix}.{key} {value} {time}\n'.format(prefix=self.metricPrefix,
key=key,
value=value,
time=int(time.time())))
sock.close()
except Exception as e:
JobMessage(context, bJobMessageType['M_WARNING'],
"Plugin {} could not transmit check result to {}:{}: {}\n".format(self.__class__,
self.collectorHost,
self.collectorPort,
e.message)) | [
"def",
"transmitResult",
"(",
"self",
",",
"context",
")",
":",
"DebugMessage",
"(",
"context",
",",
"100",
",",
"\"Submitting metrics to {}:{}\"",
".",
"format",
"(",
"self",
".",
"collectorHost",
",",
"self",
".",
"collectorPort",
")",
")",
"try",
":",
"so... | https://github.com/bareos/bareos/blob/56a10bb368b0a81e977bb51304033fe49d59efb0/contrib/dir-plugins/graphite/BareosDirPluginGraphiteSender.py#L97-L118 | ||
google/angle | d5df233189cad620b8e0de653fe5e6cb778e209d | third_party/logdog/logdog/stream.py | python | StreamClient.text | (self, name, **kwargs) | Context manager to create, use, and teardown a TEXT stream.
This context manager creates a new butler TEXT stream with the specified
parameters, yields it, and closes it on teardown.
Args:
name (str): the LogDog name of the stream.
kwargs (dict): Log stream parameters. These may be any keyword arguments
accepted by `open_text`.
Returns (file): A file-like object to a Butler UTF-8 text stream supporting
`write`. | Context manager to create, use, and teardown a TEXT stream. | [
"Context",
"manager",
"to",
"create",
"use",
"and",
"teardown",
"a",
"TEXT",
"stream",
"."
] | def text(self, name, **kwargs):
"""Context manager to create, use, and teardown a TEXT stream.
This context manager creates a new butler TEXT stream with the specified
parameters, yields it, and closes it on teardown.
Args:
name (str): the LogDog name of the stream.
kwargs (dict): Log stream parameters. These may be any keyword arguments
accepted by `open_text`.
Returns (file): A file-like object to a Butler UTF-8 text stream supporting
`write`.
"""
fobj = None
try:
fobj = self.open_text(name, **kwargs)
yield fobj
finally:
if fobj is not None:
fobj.close() | [
"def",
"text",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"fobj",
"=",
"None",
"try",
":",
"fobj",
"=",
"self",
".",
"open_text",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
"yield",
"fobj",
"finally",
":",
"if",
"fobj",
"is",
... | https://github.com/google/angle/blob/d5df233189cad620b8e0de653fe5e6cb778e209d/third_party/logdog/logdog/stream.py#L380-L400 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py | python | _Log10Memoize.getdigits | (self, p) | return int(self.digits[:p+1]) | Given an integer p >= 0, return floor(10**p)*log(10).
For example, self.getdigits(3) returns 2302. | Given an integer p >= 0, return floor(10**p)*log(10). | [
"Given",
"an",
"integer",
"p",
">",
"=",
"0",
"return",
"floor",
"(",
"10",
"**",
"p",
")",
"*",
"log",
"(",
"10",
")",
"."
] | def getdigits(self, p):
"""Given an integer p >= 0, return floor(10**p)*log(10).
For example, self.getdigits(3) returns 2302.
"""
# digits are stored as a string, for quick conversion to
# integer in the case that we've already computed enough
# digits; the stored digits should always be correct
# (truncated, not rounded to nearest).
if p < 0:
raise ValueError("p should be nonnegative")
if p >= len(self.digits):
# compute p+3, p+6, p+9, ... digits; continue until at
# least one of the extra digits is nonzero
extra = 3
while True:
# compute p+extra digits, correct to within 1ulp
M = 10**(p+extra+2)
digits = str(_div_nearest(_ilog(10*M, M), 100))
if digits[-extra:] != '0'*extra:
break
extra += 3
# keep all reliable digits so far; remove trailing zeros
# and next nonzero digit
self.digits = digits.rstrip('0')[:-1]
return int(self.digits[:p+1]) | [
"def",
"getdigits",
"(",
"self",
",",
"p",
")",
":",
"# digits are stored as a string, for quick conversion to",
"# integer in the case that we've already computed enough",
"# digits; the stored digits should always be correct",
"# (truncated, not rounded to nearest).",
"if",
"p",
"<",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py#L5679-L5705 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/richtext.py | python | RichTextPrinting.GetRichTextBufferPreview | (*args, **kwargs) | return _richtext.RichTextPrinting_GetRichTextBufferPreview(*args, **kwargs) | GetRichTextBufferPreview(self) -> RichTextBuffer | GetRichTextBufferPreview(self) -> RichTextBuffer | [
"GetRichTextBufferPreview",
"(",
"self",
")",
"-",
">",
"RichTextBuffer"
] | def GetRichTextBufferPreview(*args, **kwargs):
"""GetRichTextBufferPreview(self) -> RichTextBuffer"""
return _richtext.RichTextPrinting_GetRichTextBufferPreview(*args, **kwargs) | [
"def",
"GetRichTextBufferPreview",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextPrinting_GetRichTextBufferPreview",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L4568-L4570 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/ndimage/measurements.py | python | _stats | (input, labels=None, index=None, centered=False) | Count, sum, and optionally compute (sum - centre)^2 of input by label
Parameters
----------
input : array_like, n-dimensional
The input data to be analyzed.
labels : array_like (n-dimensional), optional
The labels of the data in `input`. This array must be broadcast
compatible with `input`; typically it is the same shape as `input`.
If `labels` is None, all nonzero values in `input` are treated as
the single labeled group.
index : label or sequence of labels, optional
These are the labels of the groups for which the stats are computed.
If `index` is None, the stats are computed for the single group where
`labels` is greater than 0.
centered : bool, optional
If True, the centered sum of squares for each labeled group is
also returned. Default is False.
Returns
-------
counts : int or ndarray of ints
The number of elements in each labeled group.
sums : scalar or ndarray of scalars
The sums of the values in each labeled group.
sums_c : scalar or ndarray of scalars, optional
The sums of mean-centered squares of the values in each labeled group.
This is only returned if `centered` is True. | Count, sum, and optionally compute (sum - centre)^2 of input by label | [
"Count",
"sum",
"and",
"optionally",
"compute",
"(",
"sum",
"-",
"centre",
")",
"^2",
"of",
"input",
"by",
"label"
] | def _stats(input, labels=None, index=None, centered=False):
"""Count, sum, and optionally compute (sum - centre)^2 of input by label
Parameters
----------
input : array_like, n-dimensional
The input data to be analyzed.
labels : array_like (n-dimensional), optional
The labels of the data in `input`. This array must be broadcast
compatible with `input`; typically it is the same shape as `input`.
If `labels` is None, all nonzero values in `input` are treated as
the single labeled group.
index : label or sequence of labels, optional
These are the labels of the groups for which the stats are computed.
If `index` is None, the stats are computed for the single group where
`labels` is greater than 0.
centered : bool, optional
If True, the centered sum of squares for each labeled group is
also returned. Default is False.
Returns
-------
counts : int or ndarray of ints
The number of elements in each labeled group.
sums : scalar or ndarray of scalars
The sums of the values in each labeled group.
sums_c : scalar or ndarray of scalars, optional
The sums of mean-centered squares of the values in each labeled group.
This is only returned if `centered` is True.
"""
def single_group(vals):
if centered:
vals_c = vals - vals.mean()
return vals.size, vals.sum(), (vals_c * vals_c.conjugate()).sum()
else:
return vals.size, vals.sum()
if labels is None:
return single_group(input)
# ensure input and labels match sizes
input, labels = numpy.broadcast_arrays(input, labels)
if index is None:
return single_group(input[labels > 0])
if numpy.isscalar(index):
return single_group(input[labels == index])
def _sum_centered(labels):
# `labels` is expected to be an ndarray with the same shape as `input`.
# It must contain the label indices (which are not necessarily the labels
# themselves).
means = sums / counts
centered_input = input - means[labels]
# bincount expects 1d inputs, so we ravel the arguments.
bc = numpy.bincount(labels.ravel(),
weights=(centered_input *
centered_input.conjugate()).ravel())
return bc
# Remap labels to unique integers if necessary, or if the largest
# label is larger than the number of values.
if (not _safely_castable_to_int(labels.dtype) or
labels.min() < 0 or labels.max() > labels.size):
# Use numpy.unique to generate the label indices. `new_labels` will
# be 1-d, but it should be interpreted as the flattened n-d array of
# label indices.
unique_labels, new_labels = numpy.unique(labels, return_inverse=True)
counts = numpy.bincount(new_labels)
sums = numpy.bincount(new_labels, weights=input.ravel())
if centered:
# Compute the sum of the mean-centered squares.
# We must reshape new_labels to the n-d shape of `input` before
# passing it _sum_centered.
sums_c = _sum_centered(new_labels.reshape(labels.shape))
idxs = numpy.searchsorted(unique_labels, index)
# make all of idxs valid
idxs[idxs >= unique_labels.size] = 0
found = (unique_labels[idxs] == index)
else:
# labels are an integer type allowed by bincount, and there aren't too
# many, so call bincount directly.
counts = numpy.bincount(labels.ravel())
sums = numpy.bincount(labels.ravel(), weights=input.ravel())
if centered:
sums_c = _sum_centered(labels)
# make sure all index values are valid
idxs = numpy.asanyarray(index, numpy.int).copy()
found = (idxs >= 0) & (idxs < counts.size)
idxs[~found] = 0
counts = counts[idxs]
counts[~found] = 0
sums = sums[idxs]
sums[~found] = 0
if not centered:
return (counts, sums)
else:
sums_c = sums_c[idxs]
sums_c[~found] = 0
return (counts, sums, sums_c) | [
"def",
"_stats",
"(",
"input",
",",
"labels",
"=",
"None",
",",
"index",
"=",
"None",
",",
"centered",
"=",
"False",
")",
":",
"def",
"single_group",
"(",
"vals",
")",
":",
"if",
"centered",
":",
"vals_c",
"=",
"vals",
"-",
"vals",
".",
"mean",
"("... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/ndimage/measurements.py#L436-L540 | ||
seqan/seqan | f5f658343c366c9c3d44ba358ffc9317e78a09ed | util/py_lib/seqan/fixgcov/app.py | python | AstTraverser._recurse | (self, node) | return True | Recursion helper. | Recursion helper. | [
"Recursion",
"helper",
"."
] | def _recurse(self, node):
"""Recursion helper."""
if not self.visit_allowed_rule.visitAllowed(node):
return False # We did not visit this node.
self.node_visitor.enterNode(node)
for c in node.get_children():
self._recurse(c)
self.node_visitor.exitNode(node)
return True | [
"def",
"_recurse",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"self",
".",
"visit_allowed_rule",
".",
"visitAllowed",
"(",
"node",
")",
":",
"return",
"False",
"# We did not visit this node.",
"self",
".",
"node_visitor",
".",
"enterNode",
"(",
"node",
... | https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/util/py_lib/seqan/fixgcov/app.py#L123-L131 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py | python | _GenerateProject | (project, options, version, generator_flags, spec) | Generates a vcproj file.
Arguments:
project: the MSVSProject object.
options: global generator options.
version: the MSVSVersion object.
generator_flags: dict of generator-specific flags.
Returns:
A list of source files that cannot be found on disk. | Generates a vcproj file. | [
"Generates",
"a",
"vcproj",
"file",
"."
] | def _GenerateProject(project, options, version, generator_flags, spec):
"""Generates a vcproj file.
Arguments:
project: the MSVSProject object.
options: global generator options.
version: the MSVSVersion object.
generator_flags: dict of generator-specific flags.
Returns:
A list of source files that cannot be found on disk.
"""
default_config = _GetDefaultConfiguration(project.spec)
# Skip emitting anything if told to with msvs_existing_vcproj option.
if default_config.get("msvs_existing_vcproj"):
return []
if version.UsesVcxproj():
return _GenerateMSBuildProject(project, options, version, generator_flags, spec)
else:
return _GenerateMSVSProject(project, options, version, generator_flags) | [
"def",
"_GenerateProject",
"(",
"project",
",",
"options",
",",
"version",
",",
"generator_flags",
",",
"spec",
")",
":",
"default_config",
"=",
"_GetDefaultConfiguration",
"(",
"project",
".",
"spec",
")",
"# Skip emitting anything if told to with msvs_existing_vcproj op... | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L1009-L1029 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftobjects/fillet.py | python | Fillet.execute | (self, obj) | Run when the object is created or recomputed. | Run when the object is created or recomputed. | [
"Run",
"when",
"the",
"object",
"is",
"created",
"or",
"recomputed",
"."
] | def execute(self, obj):
"""Run when the object is created or recomputed."""
if hasattr(obj, "Length"):
obj.Length = obj.Shape.Length
if hasattr(obj, "Start"):
obj.Start = obj.Shape.Vertexes[0].Point
if hasattr(obj, "End"):
obj.End = obj.Shape.Vertexes[-1].Point | [
"def",
"execute",
"(",
"self",
",",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"\"Length\"",
")",
":",
"obj",
".",
"Length",
"=",
"obj",
".",
"Shape",
".",
"Length",
"if",
"hasattr",
"(",
"obj",
",",
"\"Start\"",
")",
":",
"obj",
".",
"St... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftobjects/fillet.py#L103-L110 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | Sizer.InformFirstDirection | (*args, **kwargs) | return _core_.Sizer_InformFirstDirection(*args, **kwargs) | InformFirstDirection(self, int direction, int size, int availableOtherDir) -> bool
Inform sizer about the first direction that has been decided (by
parent item). Returns true if it made use of the informtion (and
recalculated min size). | InformFirstDirection(self, int direction, int size, int availableOtherDir) -> bool | [
"InformFirstDirection",
"(",
"self",
"int",
"direction",
"int",
"size",
"int",
"availableOtherDir",
")",
"-",
">",
"bool"
] | def InformFirstDirection(*args, **kwargs):
"""
InformFirstDirection(self, int direction, int size, int availableOtherDir) -> bool
Inform sizer about the first direction that has been decided (by
parent item). Returns true if it made use of the informtion (and
recalculated min size).
"""
return _core_.Sizer_InformFirstDirection(*args, **kwargs) | [
"def",
"InformFirstDirection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Sizer_InformFirstDirection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L14947-L14955 | |
dimkanovikov/KITScenarist | cc42e727ace13d3af8c4f5a7b86fdc0fed2584ee | src/libs/qBreakpad/third_party/breakpad/src/tools/python/filter_syms.py | python | SymbolFileParser._ParseLineRecord | (self, line_record) | return ' '.join(line_info) | Parses and corrects a Line record. | Parses and corrects a Line record. | [
"Parses",
"and",
"corrects",
"a",
"Line",
"record",
"."
] | def _ParseLineRecord(self, line_record):
"""Parses and corrects a Line record."""
line_info = line_record.split(' ', 5)
if len(line_info) > 4:
raise BreakpadParseError('Unsupported Line record: ' + line_record)
file_index = int(line_info[3])
line_info[3] = str(self.duplicate_files.get(file_index, file_index))
return ' '.join(line_info) | [
"def",
"_ParseLineRecord",
"(",
"self",
",",
"line_record",
")",
":",
"line_info",
"=",
"line_record",
".",
"split",
"(",
"' '",
",",
"5",
")",
"if",
"len",
"(",
"line_info",
")",
">",
"4",
":",
"raise",
"BreakpadParseError",
"(",
"'Unsupported Line record: ... | https://github.com/dimkanovikov/KITScenarist/blob/cc42e727ace13d3af8c4f5a7b86fdc0fed2584ee/src/libs/qBreakpad/third_party/breakpad/src/tools/python/filter_syms.py#L163-L170 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/vis/glprogram.py | python | GLViewport.setCurrentGL | (self) | Sets up the view in the current OpenGL context | Sets up the view in the current OpenGL context | [
"Sets",
"up",
"the",
"view",
"in",
"the",
"current",
"OpenGL",
"context"
] | def setCurrentGL(self):
"""Sets up the view in the current OpenGL context"""
# Projection
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
aspect = float(self.w)/float(self.h)
n,f = self.clippingplanes
if self.camera.dist*1.05 > f:
#allow super zoomed-out views to work without adjusting far plane
f = self.camera.dist*1.05
gluPerspective (self.fov/aspect,aspect,n,f)
# Initialize ModelView matrix
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
# View transformation
mat = se3.homogeneous(se3.inv(self.camera.matrix()))
cols = zip(*mat)
pack = sum((list(c) for c in cols),[])
glMultMatrixf(pack) | [
"def",
"setCurrentGL",
"(",
"self",
")",
":",
"# Projection",
"glMatrixMode",
"(",
"GL_PROJECTION",
")",
"glLoadIdentity",
"(",
")",
"aspect",
"=",
"float",
"(",
"self",
".",
"w",
")",
"/",
"float",
"(",
"self",
".",
"h",
")",
"n",
",",
"f",
"=",
"se... | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/vis/glprogram.py#L144-L164 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/distutils/ccompiler.py | python | CCompiler_cxx_compiler | (self) | return cxx | Return the C++ compiler.
Parameters
----------
None
Returns
-------
cxx : class instance
The C++ compiler, as a `CCompiler` instance. | Return the C++ compiler. | [
"Return",
"the",
"C",
"++",
"compiler",
"."
] | def CCompiler_cxx_compiler(self):
"""
Return the C++ compiler.
Parameters
----------
None
Returns
-------
cxx : class instance
The C++ compiler, as a `CCompiler` instance.
"""
if self.compiler_type in ('msvc', 'intelw', 'intelemw'):
return self
cxx = copy(self)
cxx.compiler_so = [cxx.compiler_cxx[0]] + cxx.compiler_so[1:]
if sys.platform.startswith('aix') and 'ld_so_aix' in cxx.linker_so[0]:
# AIX needs the ld_so_aix script included with Python
cxx.linker_so = [cxx.linker_so[0], cxx.compiler_cxx[0]] \
+ cxx.linker_so[2:]
else:
cxx.linker_so = [cxx.compiler_cxx[0]] + cxx.linker_so[1:]
return cxx | [
"def",
"CCompiler_cxx_compiler",
"(",
"self",
")",
":",
"if",
"self",
".",
"compiler_type",
"in",
"(",
"'msvc'",
",",
"'intelw'",
",",
"'intelemw'",
")",
":",
"return",
"self",
"cxx",
"=",
"copy",
"(",
"self",
")",
"cxx",
".",
"compiler_so",
"=",
"[",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/distutils/ccompiler.py#L667-L692 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/hypertreelist.py | python | TreeListColumnInfo.__init__ | (self, input="", width=_DEFAULT_COL_WIDTH, flag=wx.ALIGN_LEFT,
image=-1, shown=True, colour=None, edit=False) | Default class constructor.
:param `input`: can be a string (representing the column header text) or
another instance of :class:`TreeListColumnInfo`. In the latter case, all the
other input parameters are not used;
:param `width`: the column width in pixels;
:param `flag`: the column alignment flag, one of ``wx.ALIGN_LEFT``,
``wx.ALIGN_RIGHT``, ``wx.ALIGN_CENTER``;
:param `image`: an index within the normal image list assigned to
:class:`HyperTreeList` specifying the image to use for the column;
:param `shown`: ``True`` to show the column, ``False`` to hide it;
:param `colour`: a valid :class:`Colour`, representing the text foreground colour
for the column;
:param `edit`: ``True`` to set the column as editable, ``False`` otherwise. | Default class constructor. | [
"Default",
"class",
"constructor",
"."
] | def __init__(self, input="", width=_DEFAULT_COL_WIDTH, flag=wx.ALIGN_LEFT,
image=-1, shown=True, colour=None, edit=False):
"""
Default class constructor.
:param `input`: can be a string (representing the column header text) or
another instance of :class:`TreeListColumnInfo`. In the latter case, all the
other input parameters are not used;
:param `width`: the column width in pixels;
:param `flag`: the column alignment flag, one of ``wx.ALIGN_LEFT``,
``wx.ALIGN_RIGHT``, ``wx.ALIGN_CENTER``;
:param `image`: an index within the normal image list assigned to
:class:`HyperTreeList` specifying the image to use for the column;
:param `shown`: ``True`` to show the column, ``False`` to hide it;
:param `colour`: a valid :class:`Colour`, representing the text foreground colour
for the column;
:param `edit`: ``True`` to set the column as editable, ``False`` otherwise.
"""
if isinstance(input, basestring):
self._text = input
self._width = width
self._flag = flag
self._image = image
self._selected_image = -1
self._shown = shown
self._edit = edit
self._font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
if colour is None:
self._colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT)
else:
self._colour = colour
else:
self._text = input._text
self._width = input._width
self._flag = input._flag
self._image = input._image
self._selected_image = input._selected_image
self._shown = input._shown
self._edit = input._edit
self._colour = input._colour
self._font = input._font | [
"def",
"__init__",
"(",
"self",
",",
"input",
"=",
"\"\"",
",",
"width",
"=",
"_DEFAULT_COL_WIDTH",
",",
"flag",
"=",
"wx",
".",
"ALIGN_LEFT",
",",
"image",
"=",
"-",
"1",
",",
"shown",
"=",
"True",
",",
"colour",
"=",
"None",
",",
"edit",
"=",
"Fa... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/hypertreelist.py#L397-L440 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/aui/framemanager.py | python | AuiPaneInfo.IsFloatable | (self) | return self.HasFlag(self.optionFloatable) | Returns ``True`` if the pane can be undocked and displayed as a
floating window. | Returns ``True`` if the pane can be undocked and displayed as a
floating window. | [
"Returns",
"True",
"if",
"the",
"pane",
"can",
"be",
"undocked",
"and",
"displayed",
"as",
"a",
"floating",
"window",
"."
] | def IsFloatable(self):
"""
Returns ``True`` if the pane can be undocked and displayed as a
floating window.
"""
return self.HasFlag(self.optionFloatable) | [
"def",
"IsFloatable",
"(",
"self",
")",
":",
"return",
"self",
".",
"HasFlag",
"(",
"self",
".",
"optionFloatable",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/framemanager.py#L696-L702 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/cloudsearch2/layer1.py | python | CloudSearchConnection.delete_analysis_scheme | (self, domain_name, analysis_scheme_name) | return self._make_request(
action='DeleteAnalysisScheme',
verb='POST',
path='/', params=params) | Deletes an analysis scheme. For more information, see
`Configuring Analysis Schemes`_ in the Amazon CloudSearch
Developer Guide .
:type domain_name: string
:param domain_name: A string that represents the name of a domain.
Domain names are unique across the domains owned by an account
within an AWS region. Domain names start with a letter or number
and can contain the following characters: a-z (lowercase), 0-9, and
- (hyphen).
:type analysis_scheme_name: string
:param analysis_scheme_name: The name of the analysis scheme you want
to delete. | Deletes an analysis scheme. For more information, see
`Configuring Analysis Schemes`_ in the Amazon CloudSearch
Developer Guide . | [
"Deletes",
"an",
"analysis",
"scheme",
".",
"For",
"more",
"information",
"see",
"Configuring",
"Analysis",
"Schemes",
"_",
"in",
"the",
"Amazon",
"CloudSearch",
"Developer",
"Guide",
"."
] | def delete_analysis_scheme(self, domain_name, analysis_scheme_name):
"""
Deletes an analysis scheme. For more information, see
`Configuring Analysis Schemes`_ in the Amazon CloudSearch
Developer Guide .
:type domain_name: string
:param domain_name: A string that represents the name of a domain.
Domain names are unique across the domains owned by an account
within an AWS region. Domain names start with a letter or number
and can contain the following characters: a-z (lowercase), 0-9, and
- (hyphen).
:type analysis_scheme_name: string
:param analysis_scheme_name: The name of the analysis scheme you want
to delete.
"""
params = {
'DomainName': domain_name,
'AnalysisSchemeName': analysis_scheme_name,
}
return self._make_request(
action='DeleteAnalysisScheme',
verb='POST',
path='/', params=params) | [
"def",
"delete_analysis_scheme",
"(",
"self",
",",
"domain_name",
",",
"analysis_scheme_name",
")",
":",
"params",
"=",
"{",
"'DomainName'",
":",
"domain_name",
",",
"'AnalysisSchemeName'",
":",
"analysis_scheme_name",
",",
"}",
"return",
"self",
".",
"_make_request... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/cloudsearch2/layer1.py#L238-L263 | |
cinder/Cinder | e83f5bb9c01a63eec20168d02953a0879e5100f7 | docs/generateDocs.py | python | render_template | (path, content) | return bs4 | Generates a BeautifulSoup instance from the template and injects content
:param path:
:param content:
:return: | Generates a BeautifulSoup instance from the template and injects content
:param path:
:param content:
:return: | [
"Generates",
"a",
"BeautifulSoup",
"instance",
"from",
"the",
"template",
"and",
"injects",
"content",
":",
"param",
"path",
":",
":",
"param",
"content",
":",
":",
"return",
":"
] | def render_template(path, content):
"""
Generates a BeautifulSoup instance from the template and injects content
:param path:
:param content:
:return:
"""
# try:
# renderer = Renderer(file_encoding="utf-8", string_encoding="utf-8", decode_errors="xmlcharrefreplace")
# renderer.search_dirs.append(TEMPLATE_PATH)
# output = renderer.render_path(path, content)
# print content
# print path
# step 1: render content in template
content_renderer = Renderer(file_encoding="utf-8", string_encoding="utf-8", decode_errors="xmlcharrefreplace")
content_renderer.search_dirs.append(TEMPLATE_PATH)
output = content_renderer.render_path(path, content)
# step 2: place rendered content into main template
# - should have the following custom partials:
# - page title (define in object for page templates)
# - page content (rendered page content)
# - any other common partials that may lie outside the basic content area
# loader = Loader()
# template = loader.read("title")
# title_partial = loader.load_name(os.path.join(CLASS_TEMPLATE_DIR, "title"))
# except Exception as exc:
# print "\t**--------------------------------"
# print "\t** Warning: cannot render template"
# print "\t**--------------------------------"
# print exc
# print exc.message
# print(traceback.format_exc())
# exc_type, exc_obj, exc_tb = sys.exc_info()
# fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
# print(exc_type, fname, exc_tb.tb_lineno)
#
# if config.BREAK_ON_STOP_ERRORS:
# quit()
# else:
# return
bs4 = generate_bs4_from_string(output)
return bs4 | [
"def",
"render_template",
"(",
"path",
",",
"content",
")",
":",
"# try:",
"# renderer = Renderer(file_encoding=\"utf-8\", string_encoding=\"utf-8\", decode_errors=\"xmlcharrefreplace\")",
"# renderer.search_dirs.append(TEMPLATE_PATH)",
"# output = renderer.render_path(path, content)",
"# pr... | https://github.com/cinder/Cinder/blob/e83f5bb9c01a63eec20168d02953a0879e5100f7/docs/generateDocs.py#L3445-L3492 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/dateutil/tz/_common.py | python | _validate_fromutc_inputs | (f) | return fromutc | The CPython version of ``fromutc`` checks that the input is a ``datetime``
object and that ``self`` is attached as its ``tzinfo``. | The CPython version of ``fromutc`` checks that the input is a ``datetime``
object and that ``self`` is attached as its ``tzinfo``. | [
"The",
"CPython",
"version",
"of",
"fromutc",
"checks",
"that",
"the",
"input",
"is",
"a",
"datetime",
"object",
"and",
"that",
"self",
"is",
"attached",
"as",
"its",
"tzinfo",
"."
] | def _validate_fromutc_inputs(f):
"""
The CPython version of ``fromutc`` checks that the input is a ``datetime``
object and that ``self`` is attached as its ``tzinfo``.
"""
@wraps(f)
def fromutc(self, dt):
if not isinstance(dt, datetime):
raise TypeError("fromutc() requires a datetime argument")
if dt.tzinfo is not self:
raise ValueError("dt.tzinfo is not self")
return f(self, dt)
return fromutc | [
"def",
"_validate_fromutc_inputs",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"fromutc",
"(",
"self",
",",
"dt",
")",
":",
"if",
"not",
"isinstance",
"(",
"dt",
",",
"datetime",
")",
":",
"raise",
"TypeError",
"(",
"\"fromutc() requires a da... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/dateutil/tz/_common.py#L132-L146 | |
Cantera/cantera | 0119484b261967ccb55a0066c020599cacc312e4 | interfaces/cython/cantera/ctml_writer.py | python | XMLnode.value | (self) | return self._value | A string containing the element value. | A string containing the element value. | [
"A",
"string",
"containing",
"the",
"element",
"value",
"."
] | def value(self):
"""A string containing the element value."""
return self._value | [
"def",
"value",
"(",
"self",
")",
":",
"return",
"self",
".",
"_value"
] | https://github.com/Cantera/cantera/blob/0119484b261967ccb55a0066c020599cacc312e4/interfaces/cython/cantera/ctml_writer.py#L126-L128 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_gdi.py | python | MemoryDC.__init__ | (self, *args, **kwargs) | __init__(self, Bitmap bitmap=NullBitmap) -> MemoryDC
Constructs a new memory device context.
Use the Ok member to test whether the constructor was successful in
creating a usable device context. If a bitmap is not given to this
constructor then don't forget to select a bitmap into the DC before
drawing on it. | __init__(self, Bitmap bitmap=NullBitmap) -> MemoryDC | [
"__init__",
"(",
"self",
"Bitmap",
"bitmap",
"=",
"NullBitmap",
")",
"-",
">",
"MemoryDC"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, Bitmap bitmap=NullBitmap) -> MemoryDC
Constructs a new memory device context.
Use the Ok member to test whether the constructor was successful in
creating a usable device context. If a bitmap is not given to this
constructor then don't forget to select a bitmap into the DC before
drawing on it.
"""
_gdi_.MemoryDC_swiginit(self,_gdi_.new_MemoryDC(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_gdi_",
".",
"MemoryDC_swiginit",
"(",
"self",
",",
"_gdi_",
".",
"new_MemoryDC",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L5145-L5156 | ||
nasa/meshNetwork | ff4bd66e0ca6bd424fd8897a97252bb3925d8b3c | python/mesh/generic/li1Radio.py | python | Li1Radio.parseCommand | (self, serBytes) | return len(serBytes), None | Search raw received bytes for commands. | Search raw received bytes for commands. | [
"Search",
"raw",
"received",
"bytes",
"for",
"commands",
"."
] | def parseCommand(self, serBytes):
"""Search raw received bytes for commands."""
cmd = {'header': None, 'payload': None}
for i in range(len(serBytes) - (lenSyncBytes-1)):
# Search serial bytes for sync characters
if (serBytes[i:i+lenSyncBytes] == Li1SyncBytes): # sync bytes found
#print("Message Found")
msgStart = i
if (len(serBytes[msgStart:]) >= Li1HeaderLength): # entire header received
# Parse command header
headerFound = self.parseCmdHeader(cmd, serBytes[msgStart:])
else: # incomplete command
return len(serBytes), None
# Update buffer position
msgEnd = msgStart + Li1HeaderLength
if headerFound:
# Check if payload present
if cmd['cmdType'] in Li1RadioPayloadCmds.values():
payloadSize = unpack('>H', cmd['header'][2:])[0]
if payloadSize == 0: # No payload
return msgEnd, cmd # header only command
elif payloadSize == 65535: # receive error
return msgEnd, cmd
else: # payload present
if len(serBytes) >= (Li1HeaderLength + payloadSize + checksumLen): # entire message received
payloadEnd, cmd['payload'] = self.parseCmdPayload(payloadSize, serBytes[msgStart+Li1HeaderLength:], cmd['rawHeader'])
msgEnd += payloadEnd # update buffer position
if cmd['payload']:
return msgEnd, cmd
else:
return msgEnd, None # invalid payload
else: # incomplete command
return len(serBytes), None
else: # no payload
return msgEnd, cmd # header only command
else: # invalid header
return msgEnd, None
return len(serBytes), None | [
"def",
"parseCommand",
"(",
"self",
",",
"serBytes",
")",
":",
"cmd",
"=",
"{",
"'header'",
":",
"None",
",",
"'payload'",
":",
"None",
"}",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"serBytes",
")",
"-",
"(",
"lenSyncBytes",
"-",
"1",
")",
")",
... | https://github.com/nasa/meshNetwork/blob/ff4bd66e0ca6bd424fd8897a97252bb3925d8b3c/python/mesh/generic/li1Radio.py#L141-L186 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/action/webidl.py | python | main | (argv) | Perform WebIDL code generation required by the build system. | Perform WebIDL code generation required by the build system. | [
"Perform",
"WebIDL",
"code",
"generation",
"required",
"by",
"the",
"build",
"system",
"."
] | def main(argv):
"""Perform WebIDL code generation required by the build system."""
manager = BuildSystemWebIDL.from_environment().manager
manager.generate_build_files() | [
"def",
"main",
"(",
"argv",
")",
":",
"manager",
"=",
"BuildSystemWebIDL",
".",
"from_environment",
"(",
")",
".",
"manager",
"manager",
".",
"generate_build_files",
"(",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/action/webidl.py#L10-L13 | ||
lzhang10/maxent | 3560c94b737d4272ed86de529e50d823200e6d8e | example/postagger/context.py | python | get_context12 | (words, pos, i, rare_word) | return context | get tag context for words[i] | get tag context for words[i] | [
"get",
"tag",
"context",
"for",
"words",
"[",
"i",
"]"
] | def get_context12(words, pos, i, rare_word):
'get tag context for words[i]'
context = []
w = words[i]
n = len(words)
if rare_word:
prefix, suffix = get_prefix_suffix2(w, 2)
for p in prefix:
context.append('prefix=' + p)
for s in suffix:
context.append('suffix=' + s)
else:
context.append('curword=' + w)
if i > 0:
context.append('word-1=' + words[i - 1])
else:
context.append('word-1=BOUNDARY')
if i + 1 < n:
context.append('word+1=' + words[i + 1])
else:
context.append('word+1=BOUNDARY')
return context | [
"def",
"get_context12",
"(",
"words",
",",
"pos",
",",
"i",
",",
"rare_word",
")",
":",
"context",
"=",
"[",
"]",
"w",
"=",
"words",
"[",
"i",
"]",
"n",
"=",
"len",
"(",
"words",
")",
"if",
"rare_word",
":",
"prefix",
",",
"suffix",
"=",
"get_pre... | https://github.com/lzhang10/maxent/blob/3560c94b737d4272ed86de529e50d823200e6d8e/example/postagger/context.py#L275-L299 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/configHandler.py | python | IdleConf.GetExtensions | (self, active_only=True, editor_only=False, shell_only=False) | Gets a list of all idle extensions declared in the config files.
active_only - boolean, if true only return active (enabled) extensions | Gets a list of all idle extensions declared in the config files.
active_only - boolean, if true only return active (enabled) extensions | [
"Gets",
"a",
"list",
"of",
"all",
"idle",
"extensions",
"declared",
"in",
"the",
"config",
"files",
".",
"active_only",
"-",
"boolean",
"if",
"true",
"only",
"return",
"active",
"(",
"enabled",
")",
"extensions"
] | def GetExtensions(self, active_only=True, editor_only=False, shell_only=False):
"""
Gets a list of all idle extensions declared in the config files.
active_only - boolean, if true only return active (enabled) extensions
"""
extns=self.RemoveKeyBindNames(
self.GetSectionList('default','extensions'))
userExtns=self.RemoveKeyBindNames(
self.GetSectionList('user','extensions'))
for extn in userExtns:
if extn not in extns: #user has added own extension
extns.append(extn)
if active_only:
activeExtns=[]
for extn in extns:
if self.GetOption('extensions', extn, 'enable', default=True,
type='bool'):
#the extension is enabled
if editor_only or shell_only:
if editor_only:
option = "enable_editor"
else:
option = "enable_shell"
if self.GetOption('extensions', extn,option,
default=True, type='bool',
warn_on_default=False):
activeExtns.append(extn)
else:
activeExtns.append(extn)
return activeExtns
else:
return extns | [
"def",
"GetExtensions",
"(",
"self",
",",
"active_only",
"=",
"True",
",",
"editor_only",
"=",
"False",
",",
"shell_only",
"=",
"False",
")",
":",
"extns",
"=",
"self",
".",
"RemoveKeyBindNames",
"(",
"self",
".",
"GetSectionList",
"(",
"'default'",
",",
"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/configHandler.py#L400-L431 | ||
wyrover/book-code | 7f4883d9030d553bc6bcfa3da685e34789839900 | 3rdparty/protobuf/python/mox.py | python | IsAlmost.__init__ | (self, float_value, places=7) | Initialize IsAlmost.
Args:
float_value: The value for making the comparison.
places: The number of decimal places to round to. | Initialize IsAlmost. | [
"Initialize",
"IsAlmost",
"."
] | def __init__(self, float_value, places=7):
"""Initialize IsAlmost.
Args:
float_value: The value for making the comparison.
places: The number of decimal places to round to.
"""
self._float_value = float_value
self._places = places | [
"def",
"__init__",
"(",
"self",
",",
"float_value",
",",
"places",
"=",
"7",
")",
":",
"self",
".",
"_float_value",
"=",
"float_value",
"self",
".",
"_places",
"=",
"places"
] | https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/mox.py#L835-L844 | ||
ptrkrysik/gr-gsm | 2de47e28ce1fb9a518337bfc0add36c8e3cff5eb | docs/doxygen/swig_doc.py | python | make_func_entry | (func, name=None, description=None, params=None) | return make_entry(func, name=name, description=description, params=params) | Create a function docstring entry for a swig interface file.
func - a doxyxml object from which documentation will be extracted.
name - the name of the C object (defaults to func.name())
description - if this optional variable is set then it's value is
used as the description instead of extracting it from func.
params - a parameter list that overrides using func.params. | Create a function docstring entry for a swig interface file. | [
"Create",
"a",
"function",
"docstring",
"entry",
"for",
"a",
"swig",
"interface",
"file",
"."
] | def make_func_entry(func, name=None, description=None, params=None):
"""
Create a function docstring entry for a swig interface file.
func - a doxyxml object from which documentation will be extracted.
name - the name of the C object (defaults to func.name())
description - if this optional variable is set then it's value is
used as the description instead of extracting it from func.
params - a parameter list that overrides using func.params.
"""
#if params is None:
# params = func.params
#params = [prm.declname for prm in params]
#if params:
# sig = "Params: (%s)" % ", ".join(params)
#else:
# sig = "Params: (NONE)"
#templ = "{description}\n\n" + sig
#return make_entry(func, name=name, templ=utoascii(templ),
# description=description)
return make_entry(func, name=name, description=description, params=params) | [
"def",
"make_func_entry",
"(",
"func",
",",
"name",
"=",
"None",
",",
"description",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"#if params is None:",
"# params = func.params",
"#params = [prm.declname for prm in params]",
"#if params:",
"# sig = \"Params: (... | https://github.com/ptrkrysik/gr-gsm/blob/2de47e28ce1fb9a518337bfc0add36c8e3cff5eb/docs/doxygen/swig_doc.py#L145-L165 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/_extends/parse/standard_method.py | python | reshape | (x, *shape) | return F.reshape(x, new_shape) | Give a new shape to a tensor without changing its data.
Args:
shape(Union[int, tuple(int), list(int)]): The new shape should be compatible
with the original shape. If an integer, then the result will be a 1-D
array of that length. One shape dimension can be -1. In this case, the
value is inferred from the length of the array and remaining dimensions.
Returns:
Tensor, with new specified shape.
Raises:
TypeError: If new_shape is not integer, list or tuple, or `x` is not tensor.
ValueError: If new_shape is not compatible with the original shape.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> from mindspore import Tensor
>>> from mindspore import dtype as mstype
>>> x = Tensor([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]], dtype=mstype.float32)
>>> output = x.reshape((3, 2))
>>> print(output)
[[-0.1 0.3]
[ 3.6 0.4]
[ 0.5 -3.2]] | Give a new shape to a tensor without changing its data. | [
"Give",
"a",
"new",
"shape",
"to",
"a",
"tensor",
"without",
"changing",
"its",
"data",
"."
] | def reshape(x, *shape):
"""
Give a new shape to a tensor without changing its data.
Args:
shape(Union[int, tuple(int), list(int)]): The new shape should be compatible
with the original shape. If an integer, then the result will be a 1-D
array of that length. One shape dimension can be -1. In this case, the
value is inferred from the length of the array and remaining dimensions.
Returns:
Tensor, with new specified shape.
Raises:
TypeError: If new_shape is not integer, list or tuple, or `x` is not tensor.
ValueError: If new_shape is not compatible with the original shape.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> from mindspore import Tensor
>>> from mindspore import dtype as mstype
>>> x = Tensor([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]], dtype=mstype.float32)
>>> output = x.reshape((3, 2))
>>> print(output)
[[-0.1 0.3]
[ 3.6 0.4]
[ 0.5 -3.2]]
"""
new_shape = check_reshape_shp_const(shape)
return F.reshape(x, new_shape) | [
"def",
"reshape",
"(",
"x",
",",
"*",
"shape",
")",
":",
"new_shape",
"=",
"check_reshape_shp_const",
"(",
"shape",
")",
"return",
"F",
".",
"reshape",
"(",
"x",
",",
"new_shape",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/parse/standard_method.py#L265-L296 | |
kushview/Element | 1cc16380caa2ab79461246ba758b9de1f46db2a5 | waflib/Task.py | python | compile_fun_noshell | (line) | return (funex(fun), dvars) | Creates a compiled function to execute a process without a sub-shell | Creates a compiled function to execute a process without a sub-shell | [
"Creates",
"a",
"compiled",
"function",
"to",
"execute",
"a",
"process",
"without",
"a",
"sub",
"-",
"shell"
] | def compile_fun_noshell(line):
"""
Creates a compiled function to execute a process without a sub-shell
"""
buf = []
dvars = []
merge = False
app = buf.append
def add_dvar(x):
if x not in dvars:
dvars.append(x)
def replc(m):
# performs substitutions and populates dvars
if m.group('and'):
return ' and '
elif m.group('or'):
return ' or '
else:
x = m.group('var')
add_dvar(x)
return 'env[%r]' % x
for m in reg_act_noshell.finditer(line):
if m.group('space'):
merge = False
continue
elif m.group('text'):
app('[%r]' % m.group('text').replace('$$', '$'))
elif m.group('subst'):
var = m.group('var')
code = m.group('code')
if var == 'SRC':
if code:
app('[tsk.inputs%s]' % code)
else:
app('[a.path_from(cwdx) for a in tsk.inputs]')
elif var == 'TGT':
if code:
app('[tsk.outputs%s]' % code)
else:
app('[a.path_from(cwdx) for a in tsk.outputs]')
elif code:
if code.startswith(':'):
# a composed variable ${FOO:OUT}
add_dvar(var)
m = code[1:]
if m == 'SRC':
m = '[a.path_from(cwdx) for a in tsk.inputs]'
elif m == 'TGT':
m = '[a.path_from(cwdx) for a in tsk.outputs]'
elif re_novar.match(m):
m = '[tsk.inputs%s]' % m[3:]
elif re_novar.match(m):
m = '[tsk.outputs%s]' % m[3:]
else:
add_dvar(m)
if m[:3] not in ('tsk', 'gen', 'bld'):
m = '%r' % m
app('tsk.colon(%r, %s)' % (var, m))
elif code.startswith('?'):
# In A?B|C output env.A if one of env.B or env.C is non-empty
expr = re_cond.sub(replc, code[1:])
app('to_list(env[%r] if (%s) else [])' % (var, expr))
else:
# plain code such as ${tsk.inputs[0].abspath()}
call = '%s%s' % (var, code)
add_dvar(call)
app('to_list(%s)' % call)
else:
# a plain variable such as # a plain variable like ${AR}
app('to_list(env[%r])' % var)
add_dvar(var)
if merge:
tmp = 'merge(%s, %s)' % (buf[-2], buf[-1])
del buf[-1]
buf[-1] = tmp
merge = True # next turn
buf = ['lst.extend(%s)' % x for x in buf]
fun = COMPILE_TEMPLATE_NOSHELL % "\n\t".join(buf)
Logs.debug('action: %s', fun.strip().splitlines())
return (funex(fun), dvars) | [
"def",
"compile_fun_noshell",
"(",
"line",
")",
":",
"buf",
"=",
"[",
"]",
"dvars",
"=",
"[",
"]",
"merge",
"=",
"False",
"app",
"=",
"buf",
".",
"append",
"def",
"add_dvar",
"(",
"x",
")",
":",
"if",
"x",
"not",
"in",
"dvars",
":",
"dvars",
".",... | https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Task.py#L1139-L1222 | |
microsoft/ELL | a1d6bacc37a14879cc025d9be2ba40b1a0632315 | tools/utilities/pythonlibs/audio/view_audio.py | python | AudioDemo.load_settings | (self) | load the previously saved settings from disk, if any | load the previously saved settings from disk, if any | [
"load",
"the",
"previously",
"saved",
"settings",
"from",
"disk",
"if",
"any"
] | def load_settings(self):
""" load the previously saved settings from disk, if any """
self.settings = {}
print("loading settings from: {}".format(self.settings_file_name))
if os.path.isfile(self.settings_file_name):
with open(self.settings_file_name, "r") as f:
self.settings = json.load(f) | [
"def",
"load_settings",
"(",
"self",
")",
":",
"self",
".",
"settings",
"=",
"{",
"}",
"print",
"(",
"\"loading settings from: {}\"",
".",
"format",
"(",
"self",
".",
"settings_file_name",
")",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".... | https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/utilities/pythonlibs/audio/view_audio.py#L228-L234 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/command/easy_install.py | python | extract_wininst_cfg | (dist_filename) | Extract configuration data from a bdist_wininst .exe
Returns a configparser.RawConfigParser, or None | Extract configuration data from a bdist_wininst .exe | [
"Extract",
"configuration",
"data",
"from",
"a",
"bdist_wininst",
".",
"exe"
] | def extract_wininst_cfg(dist_filename):
"""Extract configuration data from a bdist_wininst .exe
Returns a configparser.RawConfigParser, or None
"""
f = open(dist_filename, 'rb')
try:
endrec = zipfile._EndRecData(f)
if endrec is None:
return None
prepended = (endrec[9] - endrec[5]) - endrec[6]
if prepended < 12: # no wininst data here
return None
f.seek(prepended - 12)
tag, cfglen, bmlen = struct.unpack("<iii", f.read(12))
if tag not in (0x1234567A, 0x1234567B):
return None # not a valid tag
f.seek(prepended - (12 + cfglen))
init = {'version': '', 'target_version': ''}
cfg = configparser.RawConfigParser(init)
try:
part = f.read(cfglen)
# Read up to the first null byte.
config = part.split(b'\0', 1)[0]
# Now the config is in bytes, but for RawConfigParser, it should
# be text, so decode it.
config = config.decode(sys.getfilesystemencoding())
cfg.readfp(six.StringIO(config))
except configparser.Error:
return None
if not cfg.has_section('metadata') or not cfg.has_section('Setup'):
return None
return cfg
finally:
f.close() | [
"def",
"extract_wininst_cfg",
"(",
"dist_filename",
")",
":",
"f",
"=",
"open",
"(",
"dist_filename",
",",
"'rb'",
")",
"try",
":",
"endrec",
"=",
"zipfile",
".",
"_EndRecData",
"(",
"f",
")",
"if",
"endrec",
"is",
"None",
":",
"return",
"None",
"prepend... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/command/easy_install.py#L1493-L1531 | ||
rsummers11/CADLab | 976ed959a0b5208bb4173127a7ef732ac73a9b6f | LymphNodeRFCNNPipeline/pyconvnet/ordereddict.py | python | OrderedDict.iteritems | (self) | od.iteritems -> an iterator over the (key, value) items in od | od.iteritems -> an iterator over the (key, value) items in od | [
"od",
".",
"iteritems",
"-",
">",
"an",
"iterator",
"over",
"the",
"(",
"key",
"value",
")",
"items",
"in",
"od"
] | def iteritems(self):
'od.iteritems -> an iterator over the (key, value) items in od'
for k in self:
yield (k, self[k]) | [
"def",
"iteritems",
"(",
"self",
")",
":",
"for",
"k",
"in",
"self",
":",
"yield",
"(",
"k",
",",
"self",
"[",
"k",
"]",
")"
] | https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/LymphNodeRFCNNPipeline/pyconvnet/ordereddict.py#L136-L139 | ||
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | sdhash-ui/cherrypy/wsgiserver/wsgiserver2.py | python | WSGIGateway.respond | (self) | Process the current request. | Process the current request. | [
"Process",
"the",
"current",
"request",
"."
] | def respond(self):
"""Process the current request."""
response = self.req.server.wsgi_app(self.env, self.start_response)
try:
for chunk in response:
# "The start_response callable must not actually transmit
# the response headers. Instead, it must store them for the
# server or gateway to transmit only after the first
# iteration of the application return value that yields
# a NON-EMPTY string, or upon the application's first
# invocation of the write() callable." (PEP 333)
if chunk:
if isinstance(chunk, unicodestr):
chunk = chunk.encode('ISO-8859-1')
self.write(chunk)
finally:
if hasattr(response, "close"):
response.close() | [
"def",
"respond",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"req",
".",
"server",
".",
"wsgi_app",
"(",
"self",
".",
"env",
",",
"self",
".",
"start_response",
")",
"try",
":",
"for",
"chunk",
"in",
"response",
":",
"# \"The start_response cal... | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/wsgiserver/wsgiserver2.py#L2113-L2130 | ||
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/intelhex/__init__.py | python | IntelHex.tofile | (self, fobj, format, byte_count=16) | Write data to hex or bin file. Preferred method over tobin or tohex.
@param fobj file name or file-like object
@param format file format ("hex" or "bin")
@param byte_count bytes per line | Write data to hex or bin file. Preferred method over tobin or tohex. | [
"Write",
"data",
"to",
"hex",
"or",
"bin",
"file",
".",
"Preferred",
"method",
"over",
"tobin",
"or",
"tohex",
"."
] | def tofile(self, fobj, format, byte_count=16):
"""Write data to hex or bin file. Preferred method over tobin or tohex.
@param fobj file name or file-like object
@param format file format ("hex" or "bin")
@param byte_count bytes per line
"""
if format == 'hex':
self.write_hex_file(fobj, byte_count=byte_count)
elif format == 'bin':
self.tobinfile(fobj)
else:
raise ValueError('format should be either "hex" or "bin";'
' got %r instead' % format) | [
"def",
"tofile",
"(",
"self",
",",
"fobj",
",",
"format",
",",
"byte_count",
"=",
"16",
")",
":",
"if",
"format",
"==",
"'hex'",
":",
"self",
".",
"write_hex_file",
"(",
"fobj",
",",
"byte_count",
"=",
"byte_count",
")",
"elif",
"format",
"==",
"'bin'"... | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/intelhex/__init__.py#L712-L725 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/io/povray.py | python | mark_transient | (properties,object,transient=False) | If you know object will not change over time, use this function to tell
povray. This saves computation. | If you know object will not change over time, use this function to tell
povray. This saves computation. | [
"If",
"you",
"know",
"object",
"will",
"not",
"change",
"over",
"time",
"use",
"this",
"function",
"to",
"tell",
"povray",
".",
"This",
"saves",
"computation",
"."
] | def mark_transient(properties,object,transient=False):
"""If you know object will not change over time, use this function to tell
povray. This saves computation."""
if object not in properties:
properties[object.getName()]={}
properties[object.getName()]["transient"]=transient | [
"def",
"mark_transient",
"(",
"properties",
",",
"object",
",",
"transient",
"=",
"False",
")",
":",
"if",
"object",
"not",
"in",
"properties",
":",
"properties",
"[",
"object",
".",
"getName",
"(",
")",
"]",
"=",
"{",
"}",
"properties",
"[",
"object",
... | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/io/povray.py#L474-L479 | ||
tuttleofx/TuttleOFX | 36fc4cae15092a84ea8c29b9c6658c7cabfadb6e | applications/sam/sam_mv.py | python | Sam_mv._processSequence | (self, inputItem, outputSequence, outputSequencePath, moveManipulators, dryRun) | Apply operation to the sequence contained in inputItem (used by sam-mv and sam-cp).
Depending on args, update the frame ranges of the output sequence.
Return if the operation was a success or not.
:param inputItem: the item which contains the input sequence to process (move, copy...)
:param outputSequence: the output sequence to write (destination of move, copy...)
:param outputSequence: the path of the outputSequence.
:param moveManipulators: dict which contains
{
first time of the inputSequence,
last time of the inputSequence,
offset used to retime the output sequence,
list of holes to remove in the output sequence
}
:param dryRun: only print what it will do. | Apply operation to the sequence contained in inputItem (used by sam-mv and sam-cp).
Depending on args, update the frame ranges of the output sequence.
Return if the operation was a success or not. | [
"Apply",
"operation",
"to",
"the",
"sequence",
"contained",
"in",
"inputItem",
"(",
"used",
"by",
"sam",
"-",
"mv",
"and",
"sam",
"-",
"cp",
")",
".",
"Depending",
"on",
"args",
"update",
"the",
"frame",
"ranges",
"of",
"the",
"output",
"sequence",
".",
... | def _processSequence(self, inputItem, outputSequence, outputSequencePath, moveManipulators, dryRun):
"""
Apply operation to the sequence contained in inputItem (used by sam-mv and sam-cp).
Depending on args, update the frame ranges of the output sequence.
Return if the operation was a success or not.
:param inputItem: the item which contains the input sequence to process (move, copy...)
:param outputSequence: the output sequence to write (destination of move, copy...)
:param outputSequence: the path of the outputSequence.
:param moveManipulators: dict which contains
{
first time of the inputSequence,
last time of the inputSequence,
offset used to retime the output sequence,
list of holes to remove in the output sequence
}
:param dryRun: only print what it will do.
"""
# create output directory if not exists
try:
if not os.path.exists(outputSequencePath):
# sam-rm --dry-run
if not dryRun:
os.makedirs(outputSequencePath)
except Exception as e:
self.logger.error('Cannot create directory tree for "' + outputSequencePath + '": ' + str(e))
return 1
# log brief of the operation
self.logger.info(os.path.join(self.command + ' ' + inputItem.getFolder(), str(inputItem.getSequence())) + ' to ' + os.path.join(outputSequencePath, str(outputSequence)))
# get frame ranges
inputFrameList = list(inputItem.getSequence().getFramesIterable(moveManipulators['first'], moveManipulators['last']))
outputFrameList = sorted(inputFrameList + moveManipulators['holes'])
if moveManipulators['offset'] > 0:
inputFrameList = reversed(inputFrameList)
outputFrameList = reversed(outputFrameList)
# for each time of sequence
for inputTime, outputTime in zip(inputFrameList, outputFrameList):
inputPath = os.path.join(inputItem.getFolder(), inputItem.getSequence().getFilenameAt(inputTime))
outputPath = os.path.join(outputSequencePath, outputSequence.getFilenameAt(outputTime + moveManipulators['offset']))
# security: check if file already exist
if os.path.exists(outputPath):
self.logger.error('The output path "' + outputPath + '" already exist!')
return 1
# process the image at time
self.logger.info(inputPath + ' -> ' + outputPath)
# sam-rm --dry-run
if not dryRun:
self._operation(inputPath, outputPath) | [
"def",
"_processSequence",
"(",
"self",
",",
"inputItem",
",",
"outputSequence",
",",
"outputSequencePath",
",",
"moveManipulators",
",",
"dryRun",
")",
":",
"# create output directory if not exists",
"try",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",... | https://github.com/tuttleofx/TuttleOFX/blob/36fc4cae15092a84ea8c29b9c6658c7cabfadb6e/applications/sam/sam_mv.py#L90-L142 | ||
NervanaSystems/ngraph | f677a119765ca30636cf407009dabd118664951f | python/src/ngraph/ops.py | python | unsqueeze | (data: NodeInput, axes: NodeInput, name: Optional[str] = None) | return _get_node_factory().create("Unsqueeze", as_nodes(data, axes)) | Perform unsqueeze operation on input tensor.
Insert single-dimensional entries to the shape of a tensor. Takes one required argument axes,
a list of dimensions that will be inserted.
Dimension indices in axes are as seen in the output tensor.
For example: Inputs: tensor with shape [3, 4, 5], axes=[0, 4]
Result: tensor with shape [1, 3, 4, 5, 1]
:param data: The node with data tensor.
:param axes: List of non-negative integers, indicate the dimensions to be inserted.
One of: input node or array.
:return: The new node performing an unsqueeze operation on input tensor. | Perform unsqueeze operation on input tensor. | [
"Perform",
"unsqueeze",
"operation",
"on",
"input",
"tensor",
"."
] | def unsqueeze(data: NodeInput, axes: NodeInput, name: Optional[str] = None) -> Node:
"""Perform unsqueeze operation on input tensor.
Insert single-dimensional entries to the shape of a tensor. Takes one required argument axes,
a list of dimensions that will be inserted.
Dimension indices in axes are as seen in the output tensor.
For example: Inputs: tensor with shape [3, 4, 5], axes=[0, 4]
Result: tensor with shape [1, 3, 4, 5, 1]
:param data: The node with data tensor.
:param axes: List of non-negative integers, indicate the dimensions to be inserted.
One of: input node or array.
:return: The new node performing an unsqueeze operation on input tensor.
"""
return _get_node_factory().create("Unsqueeze", as_nodes(data, axes)) | [
"def",
"unsqueeze",
"(",
"data",
":",
"NodeInput",
",",
"axes",
":",
"NodeInput",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Node",
":",
"return",
"_get_node_factory",
"(",
")",
".",
"create",
"(",
"\"Unsqueeze\"",
",",
"as... | https://github.com/NervanaSystems/ngraph/blob/f677a119765ca30636cf407009dabd118664951f/python/src/ngraph/ops.py#L194-L209 | |
kevinlin311tw/Caffe-DeepBinaryCode | 9eaa7662be47d49f475ecbeea2bd51be105270d2 | scripts/cpp_lint.py | python | IsErrorSuppressedByNolint | (category, linenum) | return (linenum in _error_suppressions.get(category, set()) or
linenum in _error_suppressions.get(None, set())) | Returns true if the specified error category is suppressed on this line.
Consults the global error_suppressions map populated by
ParseNolintSuppressions/ResetNolintSuppressions.
Args:
category: str, the category of the error.
linenum: int, the current line number.
Returns:
bool, True iff the error should be suppressed due to a NOLINT comment. | Returns true if the specified error category is suppressed on this line. | [
"Returns",
"true",
"if",
"the",
"specified",
"error",
"category",
"is",
"suppressed",
"on",
"this",
"line",
"."
] | def IsErrorSuppressedByNolint(category, linenum):
"""Returns true if the specified error category is suppressed on this line.
Consults the global error_suppressions map populated by
ParseNolintSuppressions/ResetNolintSuppressions.
Args:
category: str, the category of the error.
linenum: int, the current line number.
Returns:
bool, True iff the error should be suppressed due to a NOLINT comment.
"""
return (linenum in _error_suppressions.get(category, set()) or
linenum in _error_suppressions.get(None, set())) | [
"def",
"IsErrorSuppressedByNolint",
"(",
"category",
",",
"linenum",
")",
":",
"return",
"(",
"linenum",
"in",
"_error_suppressions",
".",
"get",
"(",
"category",
",",
"set",
"(",
")",
")",
"or",
"linenum",
"in",
"_error_suppressions",
".",
"get",
"(",
"None... | https://github.com/kevinlin311tw/Caffe-DeepBinaryCode/blob/9eaa7662be47d49f475ecbeea2bd51be105270d2/scripts/cpp_lint.py#L500-L513 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/framework/docs.py | python | Library.write_other_members | (self, f, catch_all=False) | Writes the leftover members to `f`.
Args:
f: File to write to.
catch_all: If true, document all missing symbols from any module.
Otherwise, document missing symbols from just this module. | Writes the leftover members to `f`. | [
"Writes",
"the",
"leftover",
"members",
"to",
"f",
"."
] | def write_other_members(self, f, catch_all=False):
"""Writes the leftover members to `f`.
Args:
f: File to write to.
catch_all: If true, document all missing symbols from any module.
Otherwise, document missing symbols from just this module.
"""
if catch_all:
names = self._members.items()
else:
names = inspect.getmembers(self._module)
all_names = getattr(self._module, "__all__", None)
if all_names is not None:
names = [(n, m) for n, m in names if n in all_names]
leftovers = []
for name, _ in names:
if name in self._members and name not in self._documented:
leftovers.append(name)
if leftovers:
print("%s: undocumented members: %d" % (self._title, len(leftovers)))
print("\n## Other Functions and Classes", file=f)
for name in sorted(leftovers):
print(" %s" % name)
self._documented.add(name)
self._mentioned.add(name)
self._write_member_markdown_to_file(f, "###", *self._members[name]) | [
"def",
"write_other_members",
"(",
"self",
",",
"f",
",",
"catch_all",
"=",
"False",
")",
":",
"if",
"catch_all",
":",
"names",
"=",
"self",
".",
"_members",
".",
"items",
"(",
")",
"else",
":",
"names",
"=",
"inspect",
".",
"getmembers",
"(",
"self",
... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/framework/docs.py#L529-L555 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/deps/v8/third_party/jinja2/utils.py | python | evalcontextfunction | (f) | return f | This decorator can be used to mark a function or method as an eval
context callable. This is similar to the :func:`contextfunction`
but instead of passing the context, an evaluation context object is
passed. For more information about the eval context, see
:ref:`eval-context`.
.. versionadded:: 2.4 | This decorator can be used to mark a function or method as an eval
context callable. This is similar to the :func:`contextfunction`
but instead of passing the context, an evaluation context object is
passed. For more information about the eval context, see
:ref:`eval-context`. | [
"This",
"decorator",
"can",
"be",
"used",
"to",
"mark",
"a",
"function",
"or",
"method",
"as",
"an",
"eval",
"context",
"callable",
".",
"This",
"is",
"similar",
"to",
"the",
":",
"func",
":",
"contextfunction",
"but",
"instead",
"of",
"passing",
"the",
... | def evalcontextfunction(f):
"""This decorator can be used to mark a function or method as an eval
context callable. This is similar to the :func:`contextfunction`
but instead of passing the context, an evaluation context object is
passed. For more information about the eval context, see
:ref:`eval-context`.
.. versionadded:: 2.4
"""
f.evalcontextfunction = True
return f | [
"def",
"evalcontextfunction",
"(",
"f",
")",
":",
"f",
".",
"evalcontextfunction",
"=",
"True",
"return",
"f"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/third_party/jinja2/utils.py#L60-L70 | |
raymondlu/super-animation-samples | 04234269112ff0dc32447f27a761dbbb00b8ba17 | samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py | python | Config.set_compatibility_check | (check_status) | Perform compatibility check when loading libclang
The python bindings are only tested and evaluated with the version of
libclang they are provided with. To ensure correct behavior a (limited)
compatibility check is performed when loading the bindings. This check
will throw an exception, as soon as it fails.
In case these bindings are used with an older version of libclang, parts
that have been stable between releases may still work. Users of the
python bindings can disable the compatibility check. This will cause
the python bindings to load, even though they are written for a newer
version of libclang. Failures now arise if unsupported or incompatible
features are accessed. The user is required to test himself if the
features he is using are available and compatible between different
libclang versions. | Perform compatibility check when loading libclang | [
"Perform",
"compatibility",
"check",
"when",
"loading",
"libclang"
] | def set_compatibility_check(check_status):
""" Perform compatibility check when loading libclang
The python bindings are only tested and evaluated with the version of
libclang they are provided with. To ensure correct behavior a (limited)
compatibility check is performed when loading the bindings. This check
will throw an exception, as soon as it fails.
In case these bindings are used with an older version of libclang, parts
that have been stable between releases may still work. Users of the
python bindings can disable the compatibility check. This will cause
the python bindings to load, even though they are written for a newer
version of libclang. Failures now arise if unsupported or incompatible
features are accessed. The user is required to test himself if the
features he is using are available and compatible between different
libclang versions.
"""
if Config.loaded:
raise Exception("compatibility_check must be set before before " \
"using any other functionalities in libclang.")
Config.compatibility_check = check_status | [
"def",
"set_compatibility_check",
"(",
"check_status",
")",
":",
"if",
"Config",
".",
"loaded",
":",
"raise",
"Exception",
"(",
"\"compatibility_check must be set before before \"",
"\"using any other functionalities in libclang.\"",
")",
"Config",
".",
"compatibility_check",
... | https://github.com/raymondlu/super-animation-samples/blob/04234269112ff0dc32447f27a761dbbb00b8ba17/samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L3158-L3179 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/toolkits/_private_utils.py | python | _summarize_accessible_fields | (
field_descriptions, width=40, section_title="Accessible fields"
) | return "\n".join(items) | Create a summary string for the accessible fields in a model. Unlike
`_toolkit_repr_print`, this function does not look up the values of the
fields, it just formats the names and descriptions.
Parameters
----------
field_descriptions : dict{str: str}
Name of each field and its description, in a dictionary. Keys and
values should be strings.
width : int, optional
Width of the names. This is usually determined and passed by the
calling `__repr__` method.
section_title : str, optional
Name of the accessible fields section in the summary string.
Returns
-------
out : str | Create a summary string for the accessible fields in a model. Unlike
`_toolkit_repr_print`, this function does not look up the values of the
fields, it just formats the names and descriptions. | [
"Create",
"a",
"summary",
"string",
"for",
"the",
"accessible",
"fields",
"in",
"a",
"model",
".",
"Unlike",
"_toolkit_repr_print",
"this",
"function",
"does",
"not",
"look",
"up",
"the",
"values",
"of",
"the",
"fields",
"it",
"just",
"formats",
"the",
"name... | def _summarize_accessible_fields(
field_descriptions, width=40, section_title="Accessible fields"
):
"""
Create a summary string for the accessible fields in a model. Unlike
`_toolkit_repr_print`, this function does not look up the values of the
fields, it just formats the names and descriptions.
Parameters
----------
field_descriptions : dict{str: str}
Name of each field and its description, in a dictionary. Keys and
values should be strings.
width : int, optional
Width of the names. This is usually determined and passed by the
calling `__repr__` method.
section_title : str, optional
Name of the accessible fields section in the summary string.
Returns
-------
out : str
"""
key_str = "{:<{}}: {}"
items = []
items.append(section_title)
items.append("-" * len(section_title))
for field_name, field_desc in field_descriptions.items():
items.append(key_str.format(field_name, width, field_desc))
return "\n".join(items) | [
"def",
"_summarize_accessible_fields",
"(",
"field_descriptions",
",",
"width",
"=",
"40",
",",
"section_title",
"=",
"\"Accessible fields\"",
")",
":",
"key_str",
"=",
"\"{:<{}}: {}\"",
"items",
"=",
"[",
"]",
"items",
".",
"append",
"(",
"section_title",
")",
... | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/_private_utils.py#L238-L272 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/sparse/dok.py | python | isspmatrix_dok | (x) | return isinstance(x, dok_matrix) | Is x of dok_matrix type?
Parameters
----------
x
object to check for being a dok matrix
Returns
-------
bool
True if x is a dok matrix, False otherwise
Examples
--------
>>> from scipy.sparse import dok_matrix, isspmatrix_dok
>>> isspmatrix_dok(dok_matrix([[5]]))
True
>>> from scipy.sparse import dok_matrix, csr_matrix, isspmatrix_dok
>>> isspmatrix_dok(csr_matrix([[5]]))
False | Is x of dok_matrix type? | [
"Is",
"x",
"of",
"dok_matrix",
"type?"
] | def isspmatrix_dok(x):
"""Is x of dok_matrix type?
Parameters
----------
x
object to check for being a dok matrix
Returns
-------
bool
True if x is a dok matrix, False otherwise
Examples
--------
>>> from scipy.sparse import dok_matrix, isspmatrix_dok
>>> isspmatrix_dok(dok_matrix([[5]]))
True
>>> from scipy.sparse import dok_matrix, csr_matrix, isspmatrix_dok
>>> isspmatrix_dok(csr_matrix([[5]]))
False
"""
return isinstance(x, dok_matrix) | [
"def",
"isspmatrix_dok",
"(",
"x",
")",
":",
"return",
"isinstance",
"(",
"x",
",",
"dok_matrix",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/sparse/dok.py#L508-L531 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/defchararray.py | python | greater_equal | (x1, x2) | return compare_chararrays(x1, x2, '>=', True) | Return (x1 >= x2) element-wise.
Unlike `numpy.greater_equal`, this comparison is performed by
first stripping whitespace characters from the end of the string.
This behavior is provided for backward-compatibility with
numarray.
Parameters
----------
x1, x2 : array_like of str or unicode
Input arrays of the same shape.
Returns
-------
out : {ndarray, bool}
Output array of bools, or a single bool if x1 and x2 are scalars.
See Also
--------
equal, not_equal, less_equal, greater, less | Return (x1 >= x2) element-wise. | [
"Return",
"(",
"x1",
">",
"=",
"x2",
")",
"element",
"-",
"wise",
"."
] | def greater_equal(x1, x2):
"""
Return (x1 >= x2) element-wise.
Unlike `numpy.greater_equal`, this comparison is performed by
first stripping whitespace characters from the end of the string.
This behavior is provided for backward-compatibility with
numarray.
Parameters
----------
x1, x2 : array_like of str or unicode
Input arrays of the same shape.
Returns
-------
out : {ndarray, bool}
Output array of bools, or a single bool if x1 and x2 are scalars.
See Also
--------
equal, not_equal, less_equal, greater, less
"""
return compare_chararrays(x1, x2, '>=', True) | [
"def",
"greater_equal",
"(",
"x1",
",",
"x2",
")",
":",
"return",
"compare_chararrays",
"(",
"x1",
",",
"x2",
",",
"'>='",
",",
"True",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/defchararray.py#L145-L168 | |
microsoft/onnxruntime | f92e47e95b13a240e37caf7b36577983544f98fc | orttraining/orttraining/python/training/orttrainer.py | python | ORTTrainer.eval_step | (self, *args, **kwargs) | return results[0] if len (results) == 1 else results | r"""Evaluation step method
Args:
*args: Arbitrary arguments that are used as model input (data only)
**kwargs: Arbitrary keyword arguments that are used as model input (data only)
Returns:
ordered :py:obj:`list` with model outputs as described by :py:attr:`.ORTTrainer.model_desc` | r"""Evaluation step method | [
"r",
"Evaluation",
"step",
"method"
] | def eval_step(self, *args, **kwargs):
r"""Evaluation step method
Args:
*args: Arbitrary arguments that are used as model input (data only)
**kwargs: Arbitrary keyword arguments that are used as model input (data only)
Returns:
ordered :py:obj:`list` with model outputs as described by :py:attr:`.ORTTrainer.model_desc`
"""
# Get data. CombineTorchModelLossFn takes label as last input and outputs loss first
sample_input = self._prepare_model_input(self.model_desc.inputs,
None, None, *args, **kwargs)
# Export model to ONNX
if self._onnx_model is None:
if self._torch_model is not None:
self._init_onnx_model(sample_input)
else:
raise RuntimeError("Model is uninitialized. Only ONNX and PyTorch models are supported")
# Prepare input/output description
inputs_desc = self.model_desc.inputs
outputs_desc = self.model_desc.outputs
if self._train_step_info.fetches:
outputs_desc = [o_desc for o_desc in outputs_desc if o_desc.name in self._train_step_info.fetches]
if len(outputs_desc) != len(self._train_step_info.fetches):
raise RuntimeError("The specified fetches list contains invalid output names")
# Normalize input
if not isinstance(sample_input, (list, tuple)):
sample_input = (sample_input,)
# RunOptions
run_options = ort.RunOptions()
run_options.only_execute_path_to_fetches = True
run_options.training_mode = False
# Run a eval step and return
session_run_results = self._training_session_run_helper(False,
sample_input,
inputs_desc,
outputs_desc,
run_options)
# Output must be returned in the same order as defined in the model description
results = [session_run_results[o_desc.name] for o_desc in outputs_desc]
return results[0] if len (results) == 1 else results | [
"def",
"eval_step",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get data. CombineTorchModelLossFn takes label as last input and outputs loss first",
"sample_input",
"=",
"self",
".",
"_prepare_model_input",
"(",
"self",
".",
"model_desc",
".",
... | https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/orttraining/orttraining/python/training/orttrainer.py#L212-L259 | |
msitt/blpapi-python | bebcf43668c9e5f5467b1f685f9baebbfc45bc87 | src/blpapi/chandle.py | python | CHandle.__init__ | (self, handle, dtor) | Set the handle and the dtor | Set the handle and the dtor | [
"Set",
"the",
"handle",
"and",
"the",
"dtor"
] | def __init__(self, handle, dtor):
""" Set the handle and the dtor """
self.__handle = handle
self._dtor = dtor | [
"def",
"__init__",
"(",
"self",
",",
"handle",
",",
"dtor",
")",
":",
"self",
".",
"__handle",
"=",
"handle",
"self",
".",
"_dtor",
"=",
"dtor"
] | https://github.com/msitt/blpapi-python/blob/bebcf43668c9e5f5467b1f685f9baebbfc45bc87/src/blpapi/chandle.py#L14-L17 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/layer/pooling.py | python | AvgPool2d.__init__ | (self,
kernel_size=1,
stride=1,
pad_mode="valid",
data_format="NCHW") | Initialize AvgPool2d. | Initialize AvgPool2d. | [
"Initialize",
"AvgPool2d",
"."
] | def __init__(self,
kernel_size=1,
stride=1,
pad_mode="valid",
data_format="NCHW"):
"""Initialize AvgPool2d."""
super(AvgPool2d, self).__init__(kernel_size, stride, pad_mode, data_format)
self.avg_pool = P.AvgPool(kernel_size=self.kernel_size,
strides=self.stride,
pad_mode=self.pad_mode,
data_format=self.format) | [
"def",
"__init__",
"(",
"self",
",",
"kernel_size",
"=",
"1",
",",
"stride",
"=",
"1",
",",
"pad_mode",
"=",
"\"valid\"",
",",
"data_format",
"=",
"\"NCHW\"",
")",
":",
"super",
"(",
"AvgPool2d",
",",
"self",
")",
".",
"__init__",
"(",
"kernel_size",
"... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/layer/pooling.py#L291-L301 | ||
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exomerge2.py | python | ExodusModel._delete_side_set_members | (self, side_set_id, side_set_members) | Delete the specified members from the given node set.
Node set fields are updates.
Members are given as (node_index). | Delete the specified members from the given node set. | [
"Delete",
"the",
"specified",
"members",
"from",
"the",
"given",
"node",
"set",
"."
] | def _delete_side_set_members(self, side_set_id, side_set_members):
"""
Delete the specified members from the given node set.
Node set fields are updates.
Members are given as (node_index).
"""
# validate input
[side_set_id] = self._format_side_set_id_list(
[side_set_id],
single=True)
members = self.get_side_set_members(side_set_id)
fields = self._get_side_set_fields(side_set_id)
# find members to keep
indices_to_keep = self._find_member_indices_to_keep(members,
side_set_members)
# delete members from node set fields
for all_values in fields.values():
all_values[:] = [[values[x] for x in indices_to_keep]
for values in all_values]
# delete members
members[:] = [members[x] for x in indices_to_keep] | [
"def",
"_delete_side_set_members",
"(",
"self",
",",
"side_set_id",
",",
"side_set_members",
")",
":",
"# validate input",
"[",
"side_set_id",
"]",
"=",
"self",
".",
"_format_side_set_id_list",
"(",
"[",
"side_set_id",
"]",
",",
"single",
"=",
"True",
")",
"memb... | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge2.py#L5578-L5601 | ||
Manu343726/siplasplas | 9fae7559f87087cf8ef34f04bd1e774b84b2ea9c | reference/cindex.py | python | Index.create | (excludeDecls=False) | return Index(conf.lib.clang_createIndex(excludeDecls, 0)) | Create a new Index.
Parameters:
excludeDecls -- Exclude local declarations from translation units. | Create a new Index.
Parameters:
excludeDecls -- Exclude local declarations from translation units. | [
"Create",
"a",
"new",
"Index",
".",
"Parameters",
":",
"excludeDecls",
"--",
"Exclude",
"local",
"declarations",
"from",
"translation",
"units",
"."
] | def create(excludeDecls=False):
"""
Create a new Index.
Parameters:
excludeDecls -- Exclude local declarations from translation units.
"""
return Index(conf.lib.clang_createIndex(excludeDecls, 0)) | [
"def",
"create",
"(",
"excludeDecls",
"=",
"False",
")",
":",
"return",
"Index",
"(",
"conf",
".",
"lib",
".",
"clang_createIndex",
"(",
"excludeDecls",
",",
"0",
")",
")"
] | https://github.com/Manu343726/siplasplas/blob/9fae7559f87087cf8ef34f04bd1e774b84b2ea9c/reference/cindex.py#L2238-L2244 | |
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/tools/gyp/pylib/gyp/xcodeproj_file.py | python | PBXGroup.AddOrGetVariantGroupByNameAndPath | (self, name, path) | return variant_group_ref | Returns an existing or new PBXVariantGroup for name and path.
If a PBXVariantGroup identified by the name and path arguments is already
present as a child of this object, it is returned. Otherwise, a new
PBXVariantGroup with the correct properties is created, added as a child,
and returned.
This method will generally be called by AddOrGetFileByPath, which knows
when to create a variant group based on the structure of the pathnames
passed to it. | Returns an existing or new PBXVariantGroup for name and path. | [
"Returns",
"an",
"existing",
"or",
"new",
"PBXVariantGroup",
"for",
"name",
"and",
"path",
"."
] | def AddOrGetVariantGroupByNameAndPath(self, name, path):
"""Returns an existing or new PBXVariantGroup for name and path.
If a PBXVariantGroup identified by the name and path arguments is already
present as a child of this object, it is returned. Otherwise, a new
PBXVariantGroup with the correct properties is created, added as a child,
and returned.
This method will generally be called by AddOrGetFileByPath, which knows
when to create a variant group based on the structure of the pathnames
passed to it.
"""
key = (name, path)
if key in self._variant_children_by_name_and_path:
variant_group_ref = self._variant_children_by_name_and_path[key]
assert variant_group_ref.__class__ == PBXVariantGroup
return variant_group_ref
variant_group_properties = {'name': name}
if path != None:
variant_group_properties['path'] = path
variant_group_ref = PBXVariantGroup(variant_group_properties)
self.AppendChild(variant_group_ref)
return variant_group_ref | [
"def",
"AddOrGetVariantGroupByNameAndPath",
"(",
"self",
",",
"name",
",",
"path",
")",
":",
"key",
"=",
"(",
"name",
",",
"path",
")",
"if",
"key",
"in",
"self",
".",
"_variant_children_by_name_and_path",
":",
"variant_group_ref",
"=",
"self",
".",
"_variant_... | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/xcodeproj_file.py#L1306-L1331 | |
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/gyp/generator/eclipse.py | python | GetAllIncludeDirectories | (target_list, target_dicts,
shared_intermediate_dirs, config_name, params,
compiler_path) | return all_includes_list | Calculate the set of include directories to be used.
Returns:
A list including all the include_dir's specified for every target followed
by any include directories that were added as cflag compiler options. | Calculate the set of include directories to be used. | [
"Calculate",
"the",
"set",
"of",
"include",
"directories",
"to",
"be",
"used",
"."
] | def GetAllIncludeDirectories(target_list, target_dicts,
shared_intermediate_dirs, config_name, params,
compiler_path):
"""Calculate the set of include directories to be used.
Returns:
A list including all the include_dir's specified for every target followed
by any include directories that were added as cflag compiler options.
"""
gyp_includes_set = set()
compiler_includes_list = []
# Find compiler's default include dirs.
if compiler_path:
command = shlex.split(compiler_path)
command.extend(['-E', '-xc++', '-v', '-'])
proc = subprocess.Popen(args=command, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = proc.communicate()[1]
# Extract the list of include dirs from the output, which has this format:
# ...
# #include "..." search starts here:
# #include <...> search starts here:
# /usr/include/c++/4.6
# /usr/local/include
# End of search list.
# ...
in_include_list = False
for line in output.splitlines():
if line.startswith('#include'):
in_include_list = True
continue
if line.startswith('End of search list.'):
break
if in_include_list:
include_dir = line.strip()
if include_dir not in compiler_includes_list:
compiler_includes_list.append(include_dir)
flavor = gyp.common.GetFlavor(params)
for target_name in target_list:
target = target_dicts[target_name]
if config_name in target['configurations']:
config = target['configurations'][config_name]
# Look for any include dirs that were explicitly added via cflags. This
# may be done in gyp files to force certain includes to come at the end.
# TODO(jgreenwald): Change the gyp files to not abuse cflags for this, and
# remove this.
if flavor == 'win':
generator_flags = params.get('generator_flags', {})
msvs_settings = gyp.msvs_emulation.MsvsSettings(target, generator_flags)
cflags = msvs_settings.GetCflags(config_name)
else:
cflags = config['cflags']
for cflag in cflags:
if cflag.startswith('-I'):
include_dir = cflag[2:]
if include_dir not in compiler_includes_list:
compiler_includes_list.append(include_dir)
# Find standard gyp include dirs.
if 'include_dirs' in config:
include_dirs = config['include_dirs']
for shared_intermediate_dir in shared_intermediate_dirs:
for include_dir in include_dirs:
include_dir = include_dir.replace('$SHARED_INTERMEDIATE_DIR',
shared_intermediate_dir)
if not os.path.isabs(include_dir):
base_dir = os.path.dirname(target_name)
include_dir = base_dir + '/' + include_dir
include_dir = os.path.abspath(include_dir)
gyp_includes_set.add(include_dir)
# Generate a list that has all the include dirs.
all_includes_list = list(gyp_includes_set)
all_includes_list.sort()
for compiler_include in compiler_includes_list:
if not compiler_include in gyp_includes_set:
all_includes_list.append(compiler_include)
# All done.
return all_includes_list | [
"def",
"GetAllIncludeDirectories",
"(",
"target_list",
",",
"target_dicts",
",",
"shared_intermediate_dirs",
",",
"config_name",
",",
"params",
",",
"compiler_path",
")",
":",
"gyp_includes_set",
"=",
"set",
"(",
")",
"compiler_includes_list",
"=",
"[",
"]",
"# Find... | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/generator/eclipse.py#L76-L161 | |
microsoft/onnxruntime | f92e47e95b13a240e37caf7b36577983544f98fc | orttraining/orttraining/python/training/model_desc_validation.py | python | _model_desc_inputs_validation | (field, value, error) | r'''Cerberus custom check method for 'model_desc.inputs'
'model_desc.inputs' is a list of tuples.
The list has variable length, but each tuple has size 2
The first element of the tuple is a string which represents the input name
The second element is a list of shapes. Each shape must be either an int or string.
Empty list represents a scalar output
Validation is done within each tuple to enforce the schema described above.
Example:
.. code-block:: python
model_desc['inputs'] = [('input1', ['batch', 1024]),
('input2', [])
('input3', [512])] | r'''Cerberus custom check method for 'model_desc.inputs' | [
"r",
"Cerberus",
"custom",
"check",
"method",
"for",
"model_desc",
".",
"inputs"
] | def _model_desc_inputs_validation(field, value, error):
r'''Cerberus custom check method for 'model_desc.inputs'
'model_desc.inputs' is a list of tuples.
The list has variable length, but each tuple has size 2
The first element of the tuple is a string which represents the input name
The second element is a list of shapes. Each shape must be either an int or string.
Empty list represents a scalar output
Validation is done within each tuple to enforce the schema described above.
Example:
.. code-block:: python
model_desc['inputs'] = [('input1', ['batch', 1024]),
('input2', [])
('input3', [512])]
'''
if not isinstance(value, tuple) or len(value) != 2:
error(field, "must be a tuple with size 2")
if not isinstance(value[0], str):
error(field, "the first element of the tuple (aka name) must be a string")
if not isinstance(value[1], list):
error(field, "the second element of the tuple (aka shape) must be a list")
else:
for shape in value[1]:
if not isinstance(shape, str) and not isinstance(shape, int) or isinstance(shape, bool):
error(field, "each shape must be either a string or integer") | [
"def",
"_model_desc_inputs_validation",
"(",
"field",
",",
"value",
",",
"error",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"tuple",
")",
"or",
"len",
"(",
"value",
")",
"!=",
"2",
":",
"error",
"(",
"field",
",",
"\"must be a tuple with size... | https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/orttraining/orttraining/python/training/model_desc_validation.py#L294-L324 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/reduction/instruments/example/example_reducer.py | python | ExampleReducer.set_normalizer | (self, normalize_algorithm) | This is an example of a plug-and-play algorithm to be
used as part of a reduction step | This is an example of a plug-and-play algorithm to be
used as part of a reduction step | [
"This",
"is",
"an",
"example",
"of",
"a",
"plug",
"-",
"and",
"-",
"play",
"algorithm",
"to",
"be",
"used",
"as",
"part",
"of",
"a",
"reduction",
"step"
] | def set_normalizer(self, normalize_algorithm):
"""
This is an example of a plug-and-play algorithm to be
used as part of a reduction step
"""
self._normalizer = normalize_algorithm | [
"def",
"set_normalizer",
"(",
"self",
",",
"normalize_algorithm",
")",
":",
"self",
".",
"_normalizer",
"=",
"normalize_algorithm"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/reduction/instruments/example/example_reducer.py#L66-L71 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/http/cookiejar.py | python | CookiePolicy.domain_return_ok | (self, domain, request) | return True | Return false if cookies should not be returned, given cookie domain. | Return false if cookies should not be returned, given cookie domain. | [
"Return",
"false",
"if",
"cookies",
"should",
"not",
"be",
"returned",
"given",
"cookie",
"domain",
"."
] | def domain_return_ok(self, domain, request):
"""Return false if cookies should not be returned, given cookie domain.
"""
return True | [
"def",
"domain_return_ok",
"(",
"self",
",",
"domain",
",",
"request",
")",
":",
"return",
"True"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/http/cookiejar.py#L855-L858 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/summary/writer/event_file_writer.py | python | EventFileWriter.reopen | (self) | Reopens the EventFileWriter.
Can be called after `close()` to add more events in the same directory.
The events will go into a new events file.
Does nothing if the EventFileWriter was not closed. | Reopens the EventFileWriter. | [
"Reopens",
"the",
"EventFileWriter",
"."
] | def reopen(self):
"""Reopens the EventFileWriter.
Can be called after `close()` to add more events in the same directory.
The events will go into a new events file.
Does nothing if the EventFileWriter was not closed.
"""
if self._closed:
self._worker = _EventLoggerThread(self._event_queue, self._ev_writer,
self._flush_secs, self._sentinel_event)
self._worker.start()
self._closed = False | [
"def",
"reopen",
"(",
"self",
")",
":",
"if",
"self",
".",
"_closed",
":",
"self",
".",
"_worker",
"=",
"_EventLoggerThread",
"(",
"self",
".",
"_event_queue",
",",
"self",
".",
"_ev_writer",
",",
"self",
".",
"_flush_secs",
",",
"self",
".",
"_sentinel_... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/summary/writer/event_file_writer.py#L89-L101 | ||
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/traci/_simulation.py | python | SimulationDomain.getEndTime | (self) | return self._getUniversal(tc.VAR_END) | getEndTime() -> double
Returns the configured end time of the simulation in s or -1 | getEndTime() -> double | [
"getEndTime",
"()",
"-",
">",
"double"
] | def getEndTime(self):
"""getEndTime() -> double
Returns the configured end time of the simulation in s or -1
"""
return self._getUniversal(tc.VAR_END) | [
"def",
"getEndTime",
"(",
"self",
")",
":",
"return",
"self",
".",
"_getUniversal",
"(",
"tc",
".",
"VAR_END",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_simulation.py#L259-L264 | |
kevinlin311tw/caffe-cvprw15 | 45c2a1bf0368569c54e0be4edf8d34285cf79e70 | scripts/cpp_lint.py | python | ProcessFileData | (filename, file_extension, lines, error,
extra_check_functions=[]) | Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error | Performs lint checks and reports any errors to the given error function. | [
"Performs",
"lint",
"checks",
"and",
"reports",
"any",
"errors",
"to",
"the",
"given",
"error",
"function",
"."
] | def ProcessFileData(filename, file_extension, lines, error,
extra_check_functions=[]):
"""Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
lines = (['// marker so line numbers and indices both start at 1'] + lines +
['// marker so line numbers end in a known way'])
include_state = _IncludeState()
function_state = _FunctionState()
nesting_state = _NestingState()
ResetNolintSuppressions()
CheckForCopyright(filename, lines, error)
if file_extension == 'h':
CheckForHeaderGuard(filename, lines, error)
RemoveMultiLineComments(filename, lines, error)
clean_lines = CleansedLines(lines)
for line in xrange(clean_lines.NumLines()):
ProcessLine(filename, file_extension, clean_lines, line,
include_state, function_state, nesting_state, error,
extra_check_functions)
nesting_state.CheckCompletedBlocks(filename, error)
CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
# We check here rather than inside ProcessLine so that we see raw
# lines rather than "cleaned" lines.
CheckForBadCharacters(filename, lines, error)
CheckForNewlineAtEOF(filename, lines, error) | [
"def",
"ProcessFileData",
"(",
"filename",
",",
"file_extension",
",",
"lines",
",",
"error",
",",
"extra_check_functions",
"=",
"[",
"]",
")",
":",
"lines",
"=",
"(",
"[",
"'// marker so line numbers and indices both start at 1'",
"]",
"+",
"lines",
"+",
"[",
"... | https://github.com/kevinlin311tw/caffe-cvprw15/blob/45c2a1bf0368569c54e0be4edf8d34285cf79e70/scripts/cpp_lint.py#L4644-L4687 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/propgrid.py | python | PropertyGrid.EditorsValueWasNotModified | (*args, **kwargs) | return _propgrid.PropertyGrid_EditorsValueWasNotModified(*args, **kwargs) | EditorsValueWasNotModified(self) | EditorsValueWasNotModified(self) | [
"EditorsValueWasNotModified",
"(",
"self",
")"
] | def EditorsValueWasNotModified(*args, **kwargs):
"""EditorsValueWasNotModified(self)"""
return _propgrid.PropertyGrid_EditorsValueWasNotModified(*args, **kwargs) | [
"def",
"EditorsValueWasNotModified",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGrid_EditorsValueWasNotModified",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L2024-L2026 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/formats/printing.py | python | _justify | (
head: List[Sequence[str]], tail: List[Sequence[str]]
) | return head, tail | Justify items in head and tail, so they are right-aligned when stacked.
Parameters
----------
head : list-like of list-likes of strings
tail : list-like of list-likes of strings
Returns
-------
tuple of list of tuples of strings
Same as head and tail, but items are right aligned when stacked
vertically.
Examples
--------
>>> _justify([['a', 'b']], [['abc', 'abcd']])
([(' a', ' b')], [('abc', 'abcd')]) | Justify items in head and tail, so they are right-aligned when stacked. | [
"Justify",
"items",
"in",
"head",
"and",
"tail",
"so",
"they",
"are",
"right",
"-",
"aligned",
"when",
"stacked",
"."
] | def _justify(
head: List[Sequence[str]], tail: List[Sequence[str]]
) -> Tuple[List[Tuple[str, ...]], List[Tuple[str, ...]]]:
"""
Justify items in head and tail, so they are right-aligned when stacked.
Parameters
----------
head : list-like of list-likes of strings
tail : list-like of list-likes of strings
Returns
-------
tuple of list of tuples of strings
Same as head and tail, but items are right aligned when stacked
vertically.
Examples
--------
>>> _justify([['a', 'b']], [['abc', 'abcd']])
([(' a', ' b')], [('abc', 'abcd')])
"""
combined = head + tail
# For each position for the sequences in ``combined``,
# find the length of the largest string.
max_length = [0] * len(combined[0])
for inner_seq in combined:
length = [len(item) for item in inner_seq]
max_length = [max(x, y) for x, y in zip(max_length, length)]
# justify each item in each list-like in head and tail using max_length
head = [
tuple(x.rjust(max_len) for x, max_len in zip(seq, max_length)) for seq in head
]
tail = [
tuple(x.rjust(max_len) for x, max_len in zip(seq, max_length)) for seq in tail
]
# https://github.com/python/mypy/issues/4975
# error: Incompatible return value type (got "Tuple[List[Sequence[str]],
# List[Sequence[str]]]", expected "Tuple[List[Tuple[str, ...]],
# List[Tuple[str, ...]]]")
return head, tail | [
"def",
"_justify",
"(",
"head",
":",
"List",
"[",
"Sequence",
"[",
"str",
"]",
"]",
",",
"tail",
":",
"List",
"[",
"Sequence",
"[",
"str",
"]",
"]",
")",
"->",
"Tuple",
"[",
"List",
"[",
"Tuple",
"[",
"str",
",",
"...",
"]",
"]",
",",
"List",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/formats/printing.py#L452-L494 | |
bareos/bareos | 56a10bb368b0a81e977bb51304033fe49d59efb0 | core/src/plugins/filed/python/postgres/BareosFdPluginPostgres.py | python | BareosFdPluginPostgres.start_backup_job | (self) | return bareosfd.bRC_OK | Make filelist in super class and tell Postgres
that we start a backup now | Make filelist in super class and tell Postgres
that we start a backup now | [
"Make",
"filelist",
"in",
"super",
"class",
"and",
"tell",
"Postgres",
"that",
"we",
"start",
"a",
"backup",
"now"
] | def start_backup_job(self):
"""
Make filelist in super class and tell Postgres
that we start a backup now
"""
bareosfd.DebugMessage(100, "start_backup_job in PostgresPlugin called")
try:
if self.options["dbHost"].startswith("/"):
self.dbCon = pg8000.Connection(
self.dbuser, database=self.dbname, unix_sock=self.dbHost
)
else:
self.dbCon = pg8000.Connection(
self.dbuser, database=self.dbname, host=self.dbHost
)
result = self.dbCon.run("SELECT current_setting('server_version_num')")
self.pgVersion = int(result[0][0])
# WARNING: JobMessages cause fatal errors at this stage
bareosfd.JobMessage(
bareosfd.M_INFO,
"Connected to Postgres version %d\n" % self.pgVersion,
)
except Exception as e:
bareosfd.JobMessage(
bareosfd.M_FATAL,
"Could not connect to database %s, user %s, host: %s: %s\n"
% (self.dbname, self.dbuser, self.dbHost, e),
)
return bareosfd.bRC_Error
if chr(self.level) == "F":
# For Full we backup the Postgres data directory
# Restore object ROP comes later, after file backup
# is done.
startDir = self.options["postgresDataDir"]
self.files_to_backup.append(startDir)
bareosfd.DebugMessage(
100, "dataDir: %s\n" % self.options["postgresDataDir"]
)
bareosfd.JobMessage(
bareosfd.M_INFO, "dataDir: %s\n" % self.options["postgresDataDir"]
)
else:
# If level is not Full, we only backup WAL files
# and create a restore object ROP with timestamp information.
startDir = self.options["walArchive"]
self.files_to_backup.append("ROP")
# get current Log Sequence Number (LSN)
# PG8: not supported
# PG9: pg_get_current_xlog_location
# PG10: pg_current_wal_lsn
pgMajorVersion = self.pgVersion // 10000
if pgMajorVersion >= 10:
getLsnStmt = "SELECT pg_current_wal_lsn()"
switchLsnStmt = "SELECT pg_switch_wal()"
elif pgMajorVersion >= 9:
getLsnStmt = "SELECT pg_current_xlog_location()"
switchLsnStmt = "SELECT pg_switch_xlog()"
if pgMajorVersion < 9:
bareosfd.JobMessage(
bareosfd.M_INFO,
"WAL switching not supported on Postgres Version < 9\n",
)
else:
try:
currentLSN = self.formatLSN(self.dbCon.run(getLsnStmt)[0][0])
bareosfd.JobMessage(
bareosfd.M_INFO,
"Current LSN %s, last LSN: %s\n" % (currentLSN, self.lastLSN),
)
except Exception as e:
currentLSN = 0
bareosfd.JobMessage(
bareosfd.M_WARNING,
"Could not get current LSN, last LSN was: %s : %s \n"
% (self.lastLSN, e),
)
if currentLSN > self.lastLSN and self.switchWal:
# Let Postgres write latest transaction into a new WAL file now
try:
result = self.dbCon.run(switchLsnStmt)
except Exception as e:
bareosfd.JobMessage(
bareosfd.M_WARNING,
"Could not switch to next WAL segment: %s\n" % e,
)
try:
result = self.dbCon.run(getLsnStmt)
currentLSNraw = result[0][0]
currentLSN = self.formatLSN(currentLSNraw)
bareosfd.DebugMessage(
150,
"after pg_switch_wal(): currentLSN: %s lastLSN: %s\n"
% (currentLSN, self.lastLSN),
)
self.lastLSN = currentLSN
except Exception as e:
bareosfd.JobMessage(
bareosfd.M_WARNING,
"Could not read LSN after switching to new WAL segment: %s\n"
% e,
)
if not self.wait_for_wal_archiving(currentLSNraw):
return bareosfd.bRC_Error
else:
# Nothing has changed since last backup - only send ROP this time
bareosfd.JobMessage(
bareosfd.M_INFO,
"Same LSN %s as last time - nothing to do\n" % currentLSN,
)
return bareosfd.bRC_OK
# Gather files from startDir (Postgres data dir or walArchive for incr/diff jobs)
for fileName in os.listdir(startDir):
fullName = os.path.join(startDir, fileName)
# We need a trailing '/' for directories
if os.path.isdir(fullName) and not fullName.endswith("/"):
fullName += "/"
bareosfd.DebugMessage(100, "fullName: %s\n" % fullName)
# Usually Bareos takes care about timestamps when doing incremental backups
# but here we have to compare against last BackupPostgres timestamp
try:
mTime = os.stat(fullName).st_mtime
except Exception as e:
bareosfd.JobMessage(
bareosfd.M_ERROR,
"Could net get stat-info for file %s: %s\n" % (fullName, e),
)
continue
bareosfd.DebugMessage(
150,
"%s fullTime: %d mtime: %d\n"
% (fullName, self.lastBackupStopTime, mTime),
)
if mTime > self.lastBackupStopTime + 1:
bareosfd.DebugMessage(
150,
"file: %s, fullTime: %d mtime: %d\n"
% (fullName, self.lastBackupStopTime, mTime),
)
self.files_to_backup.append(fullName)
if os.path.isdir(fullName) and fileName not in self.ignoreSubdirs:
for topdir, dirNames, fileNames in os.walk(fullName):
for fileName in fileNames:
self.files_to_backup.append(os.path.join(topdir, fileName))
for dirName in dirNames:
fullDirName = os.path.join(topdir, dirName) + "/"
self.files_to_backup.append(fullDirName)
# If level is not Full, we are done here and set the new
# lastBackupStopTime as reference for future jobs
# Will be written into the Restore Object
if not chr(self.level) == "F":
self.lastBackupStopTime = int(time.time())
return bareosfd.bRC_OK
# For Full we check for a running job and tell Postgres that
# we want to backup the DB files now.
if os.path.exists(self.labelFileName):
self.parseBackupLabelFile()
bareosfd.JobMessage(
bareosfd.M_FATAL,
'Another Postgres Backup Operation is in progress ("{}" file exists). You may stop it using SELECT pg_stop_backup()\n'.format(
self.labelFileName
),
)
return bareosfd.bRC_Error
bareosfd.DebugMessage(100, "Send 'SELECT pg_start_backup' to Postgres\n")
# We tell Postgres that we want to start to backup file now
self.backupStartTime = datetime.datetime.now(
tz=dateutil.tz.tzoffset(None, self.tzOffset)
)
try:
result = self.dbCon.run(
"SELECT pg_start_backup('%s');" % self.backupLabelString
)
except Exception as e:
bareosfd.JobMessage(
bareosfd.M_FATAL, "pg_start_backup statement failed: %s" % (e)
)
return bareosfd.bRC_Error
bareosfd.DebugMessage(150, "Start response: %s\n" % str(result))
bareosfd.DebugMessage(
150, "Adding label file %s to fileset\n" % self.labelFileName
)
self.files_to_backup.append(self.labelFileName)
bareosfd.DebugMessage(150, "Filelist: %s\n" % (self.files_to_backup))
self.PostgressFullBackupRunning = True
return bareosfd.bRC_OK | [
"def",
"start_backup_job",
"(",
"self",
")",
":",
"bareosfd",
".",
"DebugMessage",
"(",
"100",
",",
"\"start_backup_job in PostgresPlugin called\"",
")",
"try",
":",
"if",
"self",
".",
"options",
"[",
"\"dbHost\"",
"]",
".",
"startswith",
"(",
"\"/\"",
")",
":... | https://github.com/bareos/bareos/blob/56a10bb368b0a81e977bb51304033fe49d59efb0/core/src/plugins/filed/python/postgres/BareosFdPluginPostgres.py#L170-L365 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py | python | Decimal._round_up | (self, prec) | return -self._round_down(prec) | Rounds away from 0. | Rounds away from 0. | [
"Rounds",
"away",
"from",
"0",
"."
] | def _round_up(self, prec):
"""Rounds away from 0."""
return -self._round_down(prec) | [
"def",
"_round_up",
"(",
"self",
",",
"prec",
")",
":",
"return",
"-",
"self",
".",
"_round_down",
"(",
"prec",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py#L1749-L1751 | |
muccc/gr-iridium | d0e7efcb6ee55a35042acd267d65af90847e5475 | docs/doxygen/update_pydoc.py | python | combine_descriptions | (obj) | return utoascii('\n\n'.join(description)).strip() | Combines the brief and detailed descriptions of an object together. | Combines the brief and detailed descriptions of an object together. | [
"Combines",
"the",
"brief",
"and",
"detailed",
"descriptions",
"of",
"an",
"object",
"together",
"."
] | def combine_descriptions(obj):
"""
Combines the brief and detailed descriptions of an object together.
"""
description = []
bd = obj.brief_description.strip()
dd = obj.detailed_description.strip()
if bd:
description.append(bd)
if dd:
description.append(dd)
return utoascii('\n\n'.join(description)).strip() | [
"def",
"combine_descriptions",
"(",
"obj",
")",
":",
"description",
"=",
"[",
"]",
"bd",
"=",
"obj",
".",
"brief_description",
".",
"strip",
"(",
")",
"dd",
"=",
"obj",
".",
"detailed_description",
".",
"strip",
"(",
")",
"if",
"bd",
":",
"description",
... | https://github.com/muccc/gr-iridium/blob/d0e7efcb6ee55a35042acd267d65af90847e5475/docs/doxygen/update_pydoc.py#L84-L95 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/type_check.py | python | isrealobj | (x) | return not iscomplexobj(x) | Return True if x is a not complex type or an array of complex numbers.
The type of the input is checked, not the value. So even if the input
has an imaginary part equal to zero, `isrealobj` evaluates to False
if the data type is complex.
Parameters
----------
x : any
The input can be of any type and shape.
Returns
-------
y : bool
The return value, False if `x` is of a complex type.
See Also
--------
iscomplexobj, isreal
Examples
--------
>>> np.isrealobj(1)
True
>>> np.isrealobj(1+0j)
False
>>> np.isrealobj([3, 1+0j, True])
False | Return True if x is a not complex type or an array of complex numbers. | [
"Return",
"True",
"if",
"x",
"is",
"a",
"not",
"complex",
"type",
"or",
"an",
"array",
"of",
"complex",
"numbers",
"."
] | def isrealobj(x):
"""
Return True if x is a not complex type or an array of complex numbers.
The type of the input is checked, not the value. So even if the input
has an imaginary part equal to zero, `isrealobj` evaluates to False
if the data type is complex.
Parameters
----------
x : any
The input can be of any type and shape.
Returns
-------
y : bool
The return value, False if `x` is of a complex type.
See Also
--------
iscomplexobj, isreal
Examples
--------
>>> np.isrealobj(1)
True
>>> np.isrealobj(1+0j)
False
>>> np.isrealobj([3, 1+0j, True])
False
"""
return not iscomplexobj(x) | [
"def",
"isrealobj",
"(",
"x",
")",
":",
"return",
"not",
"iscomplexobj",
"(",
"x",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/type_check.py#L322-L354 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | ListCtrl.Select | (self, idx, on=1) | [de]select an item | [de]select an item | [
"[",
"de",
"]",
"select",
"an",
"item"
] | def Select(self, idx, on=1):
'''[de]select an item'''
if on: state = wx.LIST_STATE_SELECTED
else: state = 0
self.SetItemState(idx, state, wx.LIST_STATE_SELECTED) | [
"def",
"Select",
"(",
"self",
",",
"idx",
",",
"on",
"=",
"1",
")",
":",
"if",
"on",
":",
"state",
"=",
"wx",
".",
"LIST_STATE_SELECTED",
"else",
":",
"state",
"=",
"0",
"self",
".",
"SetItemState",
"(",
"idx",
",",
"state",
",",
"wx",
".",
"LIST... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L4762-L4766 | ||
twtygqyy/caffe-augmentation | c76600d247e5132fa5bd89d87bb5df458341fa84 | tools/extra/parse_log.py | python | parse_log | (path_to_log) | return train_dict_list, test_dict_list | Parse log file
Returns (train_dict_list, test_dict_list)
train_dict_list and test_dict_list are lists of dicts that define the table
rows | Parse log file
Returns (train_dict_list, test_dict_list) | [
"Parse",
"log",
"file",
"Returns",
"(",
"train_dict_list",
"test_dict_list",
")"
] | def parse_log(path_to_log):
"""Parse log file
Returns (train_dict_list, test_dict_list)
train_dict_list and test_dict_list are lists of dicts that define the table
rows
"""
regex_iteration = re.compile('Iteration (\d+)')
regex_train_output = re.compile('Train net output #(\d+): (\S+) = ([\.\deE+-]+)')
regex_test_output = re.compile('Test net output #(\d+): (\S+) = ([\.\deE+-]+)')
regex_learning_rate = re.compile('lr = ([-+]?[0-9]*\.?[0-9]+([eE]?[-+]?[0-9]+)?)')
# Pick out lines of interest
iteration = -1
learning_rate = float('NaN')
train_dict_list = []
test_dict_list = []
train_row = None
test_row = None
logfile_year = extract_seconds.get_log_created_year(path_to_log)
with open(path_to_log) as f:
start_time = extract_seconds.get_start_time(f, logfile_year)
last_time = start_time
for line in f:
iteration_match = regex_iteration.search(line)
if iteration_match:
iteration = float(iteration_match.group(1))
if iteration == -1:
# Only start parsing for other stuff if we've found the first
# iteration
continue
try:
time = extract_seconds.extract_datetime_from_line(line,
logfile_year)
except ValueError:
# Skip lines with bad formatting, for example when resuming solver
continue
# if it's another year
if time.month < last_time.month:
logfile_year += 1
time = extract_seconds.extract_datetime_from_line(line, logfile_year)
last_time = time
seconds = (time - start_time).total_seconds()
learning_rate_match = regex_learning_rate.search(line)
if learning_rate_match:
learning_rate = float(learning_rate_match.group(1))
train_dict_list, train_row = parse_line_for_net_output(
regex_train_output, train_row, train_dict_list,
line, iteration, seconds, learning_rate
)
test_dict_list, test_row = parse_line_for_net_output(
regex_test_output, test_row, test_dict_list,
line, iteration, seconds, learning_rate
)
fix_initial_nan_learning_rate(train_dict_list)
fix_initial_nan_learning_rate(test_dict_list)
return train_dict_list, test_dict_list | [
"def",
"parse_log",
"(",
"path_to_log",
")",
":",
"regex_iteration",
"=",
"re",
".",
"compile",
"(",
"'Iteration (\\d+)'",
")",
"regex_train_output",
"=",
"re",
".",
"compile",
"(",
"'Train net output #(\\d+): (\\S+) = ([\\.\\deE+-]+)'",
")",
"regex_test_output",
"=",
... | https://github.com/twtygqyy/caffe-augmentation/blob/c76600d247e5132fa5bd89d87bb5df458341fa84/tools/extra/parse_log.py#L17-L83 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/pyfakefs/pyfakefs/fake_filesystem.py | python | FakeOsModule._fdopen_ver2 | (self, file_des, mode='r', bufsize=None) | Returns an open file object connected to the file descriptor file_des.
Args:
file_des: An integer file descriptor for the file object requested.
mode: additional file flags. Currently checks to see if the mode matches
the mode of the requested file object.
bufsize: ignored. (Used for signature compliance with __builtin__.fdopen)
Returns:
File object corresponding to file_des.
Raises:
OSError: if bad file descriptor or incompatible mode is given.
TypeError: if file descriptor is not an integer. | Returns an open file object connected to the file descriptor file_des. | [
"Returns",
"an",
"open",
"file",
"object",
"connected",
"to",
"the",
"file",
"descriptor",
"file_des",
"."
] | def _fdopen_ver2(self, file_des, mode='r', bufsize=None):
"""Returns an open file object connected to the file descriptor file_des.
Args:
file_des: An integer file descriptor for the file object requested.
mode: additional file flags. Currently checks to see if the mode matches
the mode of the requested file object.
bufsize: ignored. (Used for signature compliance with __builtin__.fdopen)
Returns:
File object corresponding to file_des.
Raises:
OSError: if bad file descriptor or incompatible mode is given.
TypeError: if file descriptor is not an integer.
"""
if not isinstance(file_des, int):
raise TypeError('an integer is required')
try:
return FakeFileOpen(self.filesystem).Call(file_des, mode=mode)
except IOError as e:
raise OSError(e) | [
"def",
"_fdopen_ver2",
"(",
"self",
",",
"file_des",
",",
"mode",
"=",
"'r'",
",",
"bufsize",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"file_des",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"'an integer is required'",
")",
"try",
":",... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/pyfakefs/pyfakefs/fake_filesystem.py#L1208-L1230 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/dispatcher.py | python | _DispatcherBase._search_new_conversions | (self, *args, **kws) | return found | Callback for the C _Dispatcher object.
Search for approximately matching signatures for the given arguments,
and ensure the corresponding conversions are registered in the C++
type manager. | Callback for the C _Dispatcher object.
Search for approximately matching signatures for the given arguments,
and ensure the corresponding conversions are registered in the C++
type manager. | [
"Callback",
"for",
"the",
"C",
"_Dispatcher",
"object",
".",
"Search",
"for",
"approximately",
"matching",
"signatures",
"for",
"the",
"given",
"arguments",
"and",
"ensure",
"the",
"corresponding",
"conversions",
"are",
"registered",
"in",
"the",
"C",
"++",
"typ... | def _search_new_conversions(self, *args, **kws):
"""
Callback for the C _Dispatcher object.
Search for approximately matching signatures for the given arguments,
and ensure the corresponding conversions are registered in the C++
type manager.
"""
assert not kws, "kwargs not handled"
args = [self.typeof_pyval(a) for a in args]
found = False
for sig in self.nopython_signatures:
conv = self.typingctx.install_possible_conversions(args, sig.args)
if conv:
found = True
return found | [
"def",
"_search_new_conversions",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kws",
")",
":",
"assert",
"not",
"kws",
",",
"\"kwargs not handled\"",
"args",
"=",
"[",
"self",
".",
"typeof_pyval",
"(",
"a",
")",
"for",
"a",
"in",
"args",
"]",
"found"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/dispatcher.py#L576-L590 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/telnetlib.py | python | Telnet.read_very_eager | (self) | return self.read_very_lazy() | Read everything that's possible without blocking in I/O (eager).
Raise EOFError if connection closed and no cooked data
available. Return '' if no cooked data available otherwise.
Don't block unless in the midst of an IAC sequence. | Read everything that's possible without blocking in I/O (eager). | [
"Read",
"everything",
"that",
"s",
"possible",
"without",
"blocking",
"in",
"I",
"/",
"O",
"(",
"eager",
")",
"."
] | def read_very_eager(self):
"""Read everything that's possible without blocking in I/O (eager).
Raise EOFError if connection closed and no cooked data
available. Return '' if no cooked data available otherwise.
Don't block unless in the midst of an IAC sequence.
"""
self.process_rawq()
while not self.eof and self.sock_avail():
self.fill_rawq()
self.process_rawq()
return self.read_very_lazy() | [
"def",
"read_very_eager",
"(",
"self",
")",
":",
"self",
".",
"process_rawq",
"(",
")",
"while",
"not",
"self",
".",
"eof",
"and",
"self",
".",
"sock_avail",
"(",
")",
":",
"self",
".",
"fill_rawq",
"(",
")",
"self",
".",
"process_rawq",
"(",
")",
"r... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/telnetlib.py#L403-L415 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/distutils/misc_util.py | python | get_path_from_frame | (frame, parent_path=None) | return d or '.' | Return path of the module given a frame object from the call stack.
Returned path is relative to parent_path when given,
otherwise it is absolute path. | Return path of the module given a frame object from the call stack. | [
"Return",
"path",
"of",
"the",
"module",
"given",
"a",
"frame",
"object",
"from",
"the",
"call",
"stack",
"."
] | def get_path_from_frame(frame, parent_path=None):
"""Return path of the module given a frame object from the call stack.
Returned path is relative to parent_path when given,
otherwise it is absolute path.
"""
# First, try to find if the file name is in the frame.
try:
caller_file = eval('__file__', frame.f_globals, frame.f_locals)
d = os.path.dirname(os.path.abspath(caller_file))
except NameError:
# __file__ is not defined, so let's try __name__. We try this second
# because setuptools spoofs __name__ to be '__main__' even though
# sys.modules['__main__'] might be something else, like easy_install(1).
caller_name = eval('__name__', frame.f_globals, frame.f_locals)
__import__(caller_name)
mod = sys.modules[caller_name]
if hasattr(mod, '__file__'):
d = os.path.dirname(os.path.abspath(mod.__file__))
else:
# we're probably running setup.py as execfile("setup.py")
# (likely we're building an egg)
d = os.path.abspath('.')
# hmm, should we use sys.argv[0] like in __builtin__ case?
if parent_path is not None:
d = rel_path(d, parent_path)
return d or '.' | [
"def",
"get_path_from_frame",
"(",
"frame",
",",
"parent_path",
"=",
"None",
")",
":",
"# First, try to find if the file name is in the frame.",
"try",
":",
"caller_file",
"=",
"eval",
"(",
"'__file__'",
",",
"frame",
".",
"f_globals",
",",
"frame",
".",
"f_locals",... | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/distutils/misc_util.py#L89-L118 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/mplgraphicsview.py | python | MplGraphicsView.addImage | (self, imagefilename) | return | Add an image by file | Add an image by file | [
"Add",
"an",
"image",
"by",
"file"
] | def addImage(self, imagefilename):
""" Add an image by file
"""
# check
if os.path.exists(imagefilename) is False:
raise NotImplementedError("Image file %s does not exist." % (imagefilename))
self._myCanvas.addImage(imagefilename)
return | [
"def",
"addImage",
"(",
"self",
",",
"imagefilename",
")",
":",
"# check",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"imagefilename",
")",
"is",
"False",
":",
"raise",
"NotImplementedError",
"(",
"\"Image file %s does not exist.\"",
"%",
"(",
"imagefilename",... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/mplgraphicsview.py#L609-L618 | |
seqan/seqan | f5f658343c366c9c3d44ba358ffc9317e78a09ed | util/py_lib/seqan/dox/proc_doc.py | python | RawTextToTextNodeConverter.handleTag | (self, token) | Handle a HTML tag.
The HTML tag is translated into a TextNode and appended to self.current.
Note that this is meant for parsing one tag only. | Handle a HTML tag. | [
"Handle",
"a",
"HTML",
"tag",
"."
] | def handleTag(self, token):
"""Handle a HTML tag.
The HTML tag is translated into a TextNode and appended to self.current.
Note that this is meant for parsing one tag only.
"""
self.html_parser.parse(token.val)
tag_name = self.html_parser.tag
if tag_name not in self.expected_tags:
msg = 'Unknown tag "%s". Expected one of %s.' % (tag_name, self.expected_tags)
self.doc_proc.msg_printer.printTokenError(token, msg, 'warning')
if self.html_parser.is_open: # Opening tag.
self.tag_stack.append(self.html_parser.tag)
self.node_stack.append(self.current)
tag = TextNode(type=self.html_parser.tag, raw_html=True)
for key, value in self.html_parser.attrs.items():
tag.setAttr(key, value)
self.current = self.current.addChild(tag)
if self.html_parser.is_close: # No else, also handle standalone tags.
if self.tag_stack and self.tag_stack[-1] == tag_name:
self.tag_stack.pop() # correct closing tag
elif self.tag_stack and self.tag_stack[-1] != tag_name:
# incorrect closing, pop and return
args = (tag_name, self.tag_stack[-1])
self.doc_proc.msg_printer.printTokenError(token, 'Closing wrong tag %s instead of %s' % args, 'warning')
self.tag_stack.pop()
return
else: # not self.tag_stack
self.doc_proc.msg_printer.printTokenError(token, 'Closing tag without opening %s!' % tag_name, 'warning')
# Pop from node stack.
if self.node_stack:
self.current = self.node_stack[-1]
self.node_stack.pop()
else:
self.doc_proc.msg_printer.printTokenError(token, 'Having closed too many tags!', 'warning') | [
"def",
"handleTag",
"(",
"self",
",",
"token",
")",
":",
"self",
".",
"html_parser",
".",
"parse",
"(",
"token",
".",
"val",
")",
"tag_name",
"=",
"self",
".",
"html_parser",
".",
"tag",
"if",
"tag_name",
"not",
"in",
"self",
".",
"expected_tags",
":",... | https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/util/py_lib/seqan/dox/proc_doc.py#L967-L1003 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.