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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
priyankchheda/algorithms | c361aa9071573fa9966d5b02d05e524815abcf2b | queue/library/queue.py | python | Queue.is_empty | (self) | return self.items == [] | Returns a boolean value expressing whether or not the list
representing the Queue is empty.
Runs in constant time, because it's only checking for equality.
:return: returns true if stack is empty, else false | Returns a boolean value expressing whether or not the list
representing the Queue is empty. | [
"Returns",
"a",
"boolean",
"value",
"expressing",
"whether",
"or",
"not",
"the",
"list",
"representing",
"the",
"Queue",
"is",
"empty",
"."
] | def is_empty(self):
""" Returns a boolean value expressing whether or not the list
representing the Queue is empty.
Runs in constant time, because it's only checking for equality.
:return: returns true if stack is empty, else false
"""
return self.items == [] | [
"def",
"is_empty",
"(",
"self",
")",
":",
"return",
"self",
".",
"items",
"==",
"[",
"]"
] | https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/queue/library/queue.py#L66-L74 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/command/easy_install.py | python | easy_install.select_scheme | (self, name) | Sets the install directories by applying the install schemes. | Sets the install directories by applying the install schemes. | [
"Sets",
"the",
"install",
"directories",
"by",
"applying",
"the",
"install",
"schemes",
"."
] | def select_scheme(self, name):
"""Sets the install directories by applying the install schemes."""
# it's the caller's problem if they supply a bad name!
scheme = INSTALL_SCHEMES[name]
for key in SCHEME_KEYS:
attrname = 'install_' + key
if getattr(self, attrname) is None:
setattr(self, attrname, scheme[key]) | [
"def",
"select_scheme",
"(",
"self",
",",
"name",
")",
":",
"# it's the caller's problem if they supply a bad name!",
"scheme",
"=",
"INSTALL_SCHEMES",
"[",
"name",
"]",
"for",
"key",
"in",
"SCHEME_KEYS",
":",
"attrname",
"=",
"'install_'",
"+",
"key",
"if",
"geta... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/command/easy_install.py#L731-L738 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/__init__.py | python | _find_all_simple | (path) | return filter(os.path.isfile, results) | Find all files under 'path' | Find all files under 'path' | [
"Find",
"all",
"files",
"under",
"path"
] | def _find_all_simple(path):
"""
Find all files under 'path'
"""
results = (
os.path.join(base, file)
for base, dirs, files in os.walk(path, followlinks=True)
for file in files
)
return filter(os.path.isfile, results) | [
"def",
"_find_all_simple",
"(",
"path",
")",
":",
"results",
"=",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"file",
")",
"for",
"base",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
",",
"followlinks",
"=",
"True",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/__init__.py#L203-L212 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/docview.py | python | Document.SetDocumentName | (self, name) | Sets he document type name given to the wxDocTemplate constructor,
copied to this document when the document is created. If several
document templates are created that use the same document type, this
variable is used in wxDocManager::CreateView to collate a list of
alternative view types that can be used on this kind of document. Do
not change the value of this variable. | Sets he document type name given to the wxDocTemplate constructor,
copied to this document when the document is created. If several
document templates are created that use the same document type, this
variable is used in wxDocManager::CreateView to collate a list of
alternative view types that can be used on this kind of document. Do
not change the value of this variable. | [
"Sets",
"he",
"document",
"type",
"name",
"given",
"to",
"the",
"wxDocTemplate",
"constructor",
"copied",
"to",
"this",
"document",
"when",
"the",
"document",
"is",
"created",
".",
"If",
"several",
"document",
"templates",
"are",
"created",
"that",
"use",
"the... | def SetDocumentName(self, name):
"""
Sets he document type name given to the wxDocTemplate constructor,
copied to this document when the document is created. If several
document templates are created that use the same document type, this
variable is used in wxDocManager::CreateView to collate a list of
alternative view types that can be used on this kind of document. Do
not change the value of this variable.
"""
self._documentTypeName = name | [
"def",
"SetDocumentName",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"_documentTypeName",
"=",
"name"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/docview.py#L157-L166 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/computation/pytables.py | python | BinOp.kind | (self) | return getattr(self.queryables.get(self.lhs), 'kind', None) | the kind of my field | the kind of my field | [
"the",
"kind",
"of",
"my",
"field"
] | def kind(self):
""" the kind of my field """
return getattr(self.queryables.get(self.lhs), 'kind', None) | [
"def",
"kind",
"(",
"self",
")",
":",
"return",
"getattr",
"(",
"self",
".",
"queryables",
".",
"get",
"(",
"self",
".",
"lhs",
")",
",",
"'kind'",
",",
"None",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/computation/pytables.py#L151-L153 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/resources/find_unused_resources.py | python | GetBaseResourceId | (resource_id) | return resource_id | Removes common suffixes from a resource ID.
Removes suffixies that may be added by macros like IMAGE_GRID or IMAGE_BORDER.
For example, converts IDR_FOO_LEFT and IDR_FOO_RIGHT to just IDR_FOO.
Args:
resource_id: String resource ID.
Returns:
A string with the base part of the resource ID. | Removes common suffixes from a resource ID. | [
"Removes",
"common",
"suffixes",
"from",
"a",
"resource",
"ID",
"."
] | def GetBaseResourceId(resource_id):
"""Removes common suffixes from a resource ID.
Removes suffixies that may be added by macros like IMAGE_GRID or IMAGE_BORDER.
For example, converts IDR_FOO_LEFT and IDR_FOO_RIGHT to just IDR_FOO.
Args:
resource_id: String resource ID.
Returns:
A string with the base part of the resource ID.
"""
suffixes = [
'_TOP_LEFT', '_TOP', '_TOP_RIGHT',
'_LEFT', '_CENTER', '_RIGHT',
'_BOTTOM_LEFT', '_BOTTOM', '_BOTTOM_RIGHT',
'_TL', '_T', '_TR',
'_L', '_M', '_R',
'_BL', '_B', '_BR']
# Note: This does not check _HOVER, _PRESSED, _HOT, etc. as those are never
# used in macros.
for suffix in suffixes:
if resource_id.endswith(suffix):
resource_id = resource_id[:-len(suffix)]
return resource_id | [
"def",
"GetBaseResourceId",
"(",
"resource_id",
")",
":",
"suffixes",
"=",
"[",
"'_TOP_LEFT'",
",",
"'_TOP'",
",",
"'_TOP_RIGHT'",
",",
"'_LEFT'",
",",
"'_CENTER'",
",",
"'_RIGHT'",
",",
"'_BOTTOM_LEFT'",
",",
"'_BOTTOM'",
",",
"'_BOTTOM_RIGHT'",
",",
"'_TL'",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/resources/find_unused_resources.py#L27-L51 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/training/saver.py | python | BaseSaverBuilder._AddSaveOps | (self, filename_tensor, vars_to_save) | return control_flow_ops.with_dependencies([save], filename_tensor) | Add ops to save variables that are on the same shard.
Args:
filename_tensor: String Tensor.
vars_to_save: A list of _VarToSave objects.
Returns:
A tensor with the filename used to save. | Add ops to save variables that are on the same shard. | [
"Add",
"ops",
"to",
"save",
"variables",
"that",
"are",
"on",
"the",
"same",
"shard",
"."
] | def _AddSaveOps(self, filename_tensor, vars_to_save):
"""Add ops to save variables that are on the same shard.
Args:
filename_tensor: String Tensor.
vars_to_save: A list of _VarToSave objects.
Returns:
A tensor with the filename used to save.
"""
save = self.save_op(filename_tensor, vars_to_save)
return control_flow_ops.with_dependencies([save], filename_tensor) | [
"def",
"_AddSaveOps",
"(",
"self",
",",
"filename_tensor",
",",
"vars_to_save",
")",
":",
"save",
"=",
"self",
".",
"save_op",
"(",
"filename_tensor",
",",
"vars_to_save",
")",
"return",
"control_flow_ops",
".",
"with_dependencies",
"(",
"[",
"save",
"]",
",",... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/training/saver.py#L203-L214 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | tools/heapcheck/suppressions.py | python | Suppression.Match | (self, report) | Returns bool indicating whether the suppression matches the given report.
Args:
report: list of strings (function names).
Returns:
True if the suppression is not empty and matches the report. | Returns bool indicating whether the suppression matches the given report. | [
"Returns",
"bool",
"indicating",
"whether",
"the",
"suppression",
"matches",
"the",
"given",
"report",
"."
] | def Match(self, report):
"""Returns bool indicating whether the suppression matches the given report.
Args:
report: list of strings (function names).
Returns:
True if the suppression is not empty and matches the report.
"""
if not self._stack:
return False
if self._re.match('\n'.join(report) + '\n'):
return True
else:
return False | [
"def",
"Match",
"(",
"self",
",",
"report",
")",
":",
"if",
"not",
"self",
".",
"_stack",
":",
"return",
"False",
"if",
"self",
".",
"_re",
".",
"match",
"(",
"'\\n'",
".",
"join",
"(",
"report",
")",
"+",
"'\\n'",
")",
":",
"return",
"True",
"el... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/heapcheck/suppressions.py#L74-L87 | ||
freeorion/freeorion | c266a40eccd3a99a17de8fe57c36ef6ba3771665 | default/python/universe_generation/galaxy.py | python | DisjointSets._has_root | (self, pos) | return [root.pos] | Check if pos is the root of a cluster otherwise shorten
the tree while tranversing it and return the root | Check if pos is the root of a cluster otherwise shorten
the tree while tranversing it and return the root | [
"Check",
"if",
"pos",
"is",
"the",
"root",
"of",
"a",
"cluster",
"otherwise",
"shorten",
"the",
"tree",
"while",
"tranversing",
"it",
"and",
"return",
"the",
"root"
] | def _has_root(self, pos):
"""
Check if pos is the root of a cluster otherwise shorten
the tree while tranversing it and return the root
"""
# traverse tree and fetch parents for compression
def parents(p1, children):
# print "pp p1 ", p1.pos, " children a ", children
if p1.parent:
# print "pp deeper ", p1.pos, " chlidren b ", children
children.append(p1)
return parents(p1.parent, children)
else:
# print "pp done p1 ", p1.pos, " children c ", children
return (p1, children)
if pos not in self.dsets:
return []
(root, children) = parents(self.dsets[pos], [])
# squash the chain of children
for child in children:
child.bind_parent(root)
return [root.pos] | [
"def",
"_has_root",
"(",
"self",
",",
"pos",
")",
":",
"# traverse tree and fetch parents for compression",
"def",
"parents",
"(",
"p1",
",",
"children",
")",
":",
"# print \"pp p1 \", p1.pos, \" children a \", children",
"if",
"p1",
".",
"parent",
":",
"# print \"pp de... | https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/universe_generation/galaxy.py#L184-L207 | |
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/showbase/EventManager.py | python | EventManager.parseEventParameter | (self, eventParameter) | Extract the actual data from the eventParameter | Extract the actual data from the eventParameter | [
"Extract",
"the",
"actual",
"data",
"from",
"the",
"eventParameter"
] | def parseEventParameter(self, eventParameter):
"""
Extract the actual data from the eventParameter
"""
if eventParameter.isInt():
return eventParameter.getIntValue()
elif eventParameter.isDouble():
return eventParameter.getDoubleValue()
elif eventParameter.isString():
return eventParameter.getStringValue()
elif eventParameter.isWstring():
return eventParameter.getWstringValue()
elif eventParameter.isTypedRefCount():
return eventParameter.getTypedRefCountValue()
elif eventParameter.isEmpty():
return None
else:
# Must be some user defined type, return the ptr
# which will be downcast to that type.
return eventParameter.getPtr() | [
"def",
"parseEventParameter",
"(",
"self",
",",
"eventParameter",
")",
":",
"if",
"eventParameter",
".",
"isInt",
"(",
")",
":",
"return",
"eventParameter",
".",
"getIntValue",
"(",
")",
"elif",
"eventParameter",
".",
"isDouble",
"(",
")",
":",
"return",
"ev... | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/showbase/EventManager.py#L54-L73 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/linalg/linear_operator_low_rank_update.py | python | LinearOperatorLowRankUpdate.base_operator | (self) | return self._base_operator | If this operator is `A = L + U D V^H`, this is the `L`. | If this operator is `A = L + U D V^H`, this is the `L`. | [
"If",
"this",
"operator",
"is",
"A",
"=",
"L",
"+",
"U",
"D",
"V^H",
"this",
"is",
"the",
"L",
"."
] | def base_operator(self):
"""If this operator is `A = L + U D V^H`, this is the `L`."""
return self._base_operator | [
"def",
"base_operator",
"(",
"self",
")",
":",
"return",
"self",
".",
"_base_operator"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/linalg/linear_operator_low_rank_update.py#L336-L338 | |
tfwu/FaceDetection-ConvNet-3D | f9251c48eb40c5aec8fba7455115c355466555be | dmlc-core/scripts/lint.py | python | LintHelper.print_summary | (self, strm) | return nerr | Print summary of lint. | Print summary of lint. | [
"Print",
"summary",
"of",
"lint",
"."
] | def print_summary(self, strm):
"""Print summary of lint."""
nerr = 0
nerr += LintHelper._print_summary_map(strm, self.cpp_header_map, 'cpp-header')
nerr += LintHelper._print_summary_map(strm, self.cpp_src_map, 'cpp-soruce')
nerr += LintHelper._print_summary_map(strm, self.python_map, 'python')
if nerr == 0:
strm.write('All passed!\n')
else:
strm.write('%d files failed lint\n' % nerr)
return nerr | [
"def",
"print_summary",
"(",
"self",
",",
"strm",
")",
":",
"nerr",
"=",
"0",
"nerr",
"+=",
"LintHelper",
".",
"_print_summary_map",
"(",
"strm",
",",
"self",
".",
"cpp_header_map",
",",
"'cpp-header'",
")",
"nerr",
"+=",
"LintHelper",
".",
"_print_summary_m... | https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/dmlc-core/scripts/lint.py#L89-L99 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/categorical.py | python | Categorical.dropna | (self) | return result | Return the Categorical without null values.
Missing values (-1 in .codes) are detected.
Returns
-------
valid : Categorical | Return the Categorical without null values. | [
"Return",
"the",
"Categorical",
"without",
"null",
"values",
"."
] | def dropna(self):
"""
Return the Categorical without null values.
Missing values (-1 in .codes) are detected.
Returns
-------
valid : Categorical
"""
result = self[self.notna()]
return result | [
"def",
"dropna",
"(",
"self",
")",
":",
"result",
"=",
"self",
"[",
"self",
".",
"notna",
"(",
")",
"]",
"return",
"result"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/categorical.py#L1421-L1433 | |
funnyzhou/Adaptive_Feeding | 9c78182331d8c0ea28de47226e805776c638d46f | tools/compress_net.py | python | compress_weights | (W, l) | return Ul, L | Compress the weight matrix W of an inner product (fully connected) layer
using truncated SVD.
Parameters:
W: N x M weights matrix
l: number of singular values to retain
Returns:
Ul, L: matrices such that W \approx Ul*L | Compress the weight matrix W of an inner product (fully connected) layer
using truncated SVD. | [
"Compress",
"the",
"weight",
"matrix",
"W",
"of",
"an",
"inner",
"product",
"(",
"fully",
"connected",
")",
"layer",
"using",
"truncated",
"SVD",
"."
] | def compress_weights(W, l):
"""Compress the weight matrix W of an inner product (fully connected) layer
using truncated SVD.
Parameters:
W: N x M weights matrix
l: number of singular values to retain
Returns:
Ul, L: matrices such that W \approx Ul*L
"""
# numpy doesn't seem to have a fast truncated SVD algorithm...
# this could be faster
U, s, V = np.linalg.svd(W, full_matrices=False)
Ul = U[:, :l]
sl = s[:l]
Vl = V[:l, :]
L = np.dot(np.diag(sl), Vl)
return Ul, L | [
"def",
"compress_weights",
"(",
"W",
",",
"l",
")",
":",
"# numpy doesn't seem to have a fast truncated SVD algorithm...",
"# this could be faster",
"U",
",",
"s",
",",
"V",
"=",
"np",
".",
"linalg",
".",
"svd",
"(",
"W",
",",
"full_matrices",
"=",
"False",
")",... | https://github.com/funnyzhou/Adaptive_Feeding/blob/9c78182331d8c0ea28de47226e805776c638d46f/tools/compress_net.py#L38-L59 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/_binary.py | python | i32le | (c, o=0) | return unpack_from("<I", c, o)[0] | Converts a 4-bytes (32 bits) string to an unsigned integer.
:param c: string containing bytes to convert
:param o: offset of bytes to convert in string | Converts a 4-bytes (32 bits) string to an unsigned integer. | [
"Converts",
"a",
"4",
"-",
"bytes",
"(",
"32",
"bits",
")",
"string",
"to",
"an",
"unsigned",
"integer",
"."
] | def i32le(c, o=0):
"""
Converts a 4-bytes (32 bits) string to an unsigned integer.
:param c: string containing bytes to convert
:param o: offset of bytes to convert in string
"""
return unpack_from("<I", c, o)[0] | [
"def",
"i32le",
"(",
"c",
",",
"o",
"=",
"0",
")",
":",
"return",
"unpack_from",
"(",
"\"<I\"",
",",
"c",
",",
"o",
")",
"[",
"0",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/_binary.py#L46-L53 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/share/gdb/python/gdb/FrameIterator.py | python | FrameIterator.__init__ | (self, frame_obj) | Initialize a FrameIterator.
Arguments:
frame_obj the starting frame. | Initialize a FrameIterator. | [
"Initialize",
"a",
"FrameIterator",
"."
] | def __init__(self, frame_obj):
"""Initialize a FrameIterator.
Arguments:
frame_obj the starting frame."""
super(FrameIterator, self).__init__()
self.frame = frame_obj | [
"def",
"__init__",
"(",
"self",
",",
"frame_obj",
")",
":",
"super",
"(",
"FrameIterator",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"frame",
"=",
"frame_obj"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/share/gdb/python/gdb/FrameIterator.py#L23-L30 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | ListCtrl.GetItemSpacing | (*args, **kwargs) | return _controls_.ListCtrl_GetItemSpacing(*args, **kwargs) | GetItemSpacing(self) -> Size | GetItemSpacing(self) -> Size | [
"GetItemSpacing",
"(",
"self",
")",
"-",
">",
"Size"
] | def GetItemSpacing(*args, **kwargs):
"""GetItemSpacing(self) -> Size"""
return _controls_.ListCtrl_GetItemSpacing(*args, **kwargs) | [
"def",
"GetItemSpacing",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ListCtrl_GetItemSpacing",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L4583-L4585 | |
cztomczak/cefpython | 5679f28cec18a57a56e298da2927aac8d8f83ad6 | examples/pyinstaller/hook-cefpython3.py | python | get_cefpython_modules | () | return modules | Get all cefpython Cython modules in the cefpython3 package.
It returns a list of names without file extension. Eg.
'cefpython_py27'. | Get all cefpython Cython modules in the cefpython3 package.
It returns a list of names without file extension. Eg.
'cefpython_py27'. | [
"Get",
"all",
"cefpython",
"Cython",
"modules",
"in",
"the",
"cefpython3",
"package",
".",
"It",
"returns",
"a",
"list",
"of",
"names",
"without",
"file",
"extension",
".",
"Eg",
".",
"cefpython_py27",
"."
] | def get_cefpython_modules():
"""Get all cefpython Cython modules in the cefpython3 package.
It returns a list of names without file extension. Eg.
'cefpython_py27'. """
pyds = glob.glob(os.path.join(CEFPYTHON3_DIR,
"cefpython_py*" + CYTHON_MODULE_EXT))
assert len(pyds) > 1, "Missing cefpython3 Cython modules"
modules = []
for path in pyds:
filename = os.path.basename(path)
mod = filename.replace(CYTHON_MODULE_EXT, "")
modules.append(mod)
return modules | [
"def",
"get_cefpython_modules",
"(",
")",
":",
"pyds",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"CEFPYTHON3_DIR",
",",
"\"cefpython_py*\"",
"+",
"CYTHON_MODULE_EXT",
")",
")",
"assert",
"len",
"(",
"pyds",
")",
">",
"1",
",",
... | https://github.com/cztomczak/cefpython/blob/5679f28cec18a57a56e298da2927aac8d8f83ad6/examples/pyinstaller/hook-cefpython3.py#L68-L80 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | PhysicsTools/HeppyCore/python/utils/edmIntegrityCheck.py | python | PublishToFileSystem.get | (self, dir) | return self.read(files[-1][1]) | Finds the lastest file and reads it | Finds the lastest file and reads it | [
"Finds",
"the",
"lastest",
"file",
"and",
"reads",
"it"
] | def get(self, dir):
"""Finds the lastest file and reads it"""
reg = '^%s_.*\.txt$' % self.parent
files = castortools.matchingFiles(dir, reg)
files = sorted([ (os.path.basename(f), f) for f in files])
if not files:
return None
return self.read(files[-1][1]) | [
"def",
"get",
"(",
"self",
",",
"dir",
")",
":",
"reg",
"=",
"'^%s_.*\\.txt$'",
"%",
"self",
".",
"parent",
"files",
"=",
"castortools",
".",
"matchingFiles",
"(",
"dir",
",",
"reg",
")",
"files",
"=",
"sorted",
"(",
"[",
"(",
"os",
".",
"path",
".... | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/PhysicsTools/HeppyCore/python/utils/edmIntegrityCheck.py#L64-L71 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/saved_model/load.py | python | Loader._recreate_user_object | (self, proto) | return looked_up | Instantiates a SavedUserObject. | Instantiates a SavedUserObject. | [
"Instantiates",
"a",
"SavedUserObject",
"."
] | def _recreate_user_object(self, proto):
"""Instantiates a SavedUserObject."""
looked_up = revived_types.deserialize(proto)
if looked_up is None:
return self._recreate_base_user_object(proto)
return looked_up | [
"def",
"_recreate_user_object",
"(",
"self",
",",
"proto",
")",
":",
"looked_up",
"=",
"revived_types",
".",
"deserialize",
"(",
"proto",
")",
"if",
"looked_up",
"is",
"None",
":",
"return",
"self",
".",
"_recreate_base_user_object",
"(",
"proto",
")",
"return... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/saved_model/load.py#L324-L329 | |
svn2github/webrtc | 0e4615a75ed555ec866cd5543bfea586f3385ceb | tools/network_emulator/config.py | python | ConnectionConfig.__str__ | (self) | return '%2s %24s %5s kbps %5s kbps %4s %5s ms %3s %%' % (
self.num, left_aligned_name, self.receive_bw_kbps, self.send_bw_kbps,
self.queue_slots, self.delay_ms, self.packet_loss_percent) | String representing the configuration.
Returns:
A string formatted and padded like this example:
12 Name 375 kbps 375 kbps 10 145 ms 0.1 % | String representing the configuration. | [
"String",
"representing",
"the",
"configuration",
"."
] | def __str__(self):
"""String representing the configuration.
Returns:
A string formatted and padded like this example:
12 Name 375 kbps 375 kbps 10 145 ms 0.1 %
"""
left_aligned_name = self.name.ljust(24, ' ')
return '%2s %24s %5s kbps %5s kbps %4s %5s ms %3s %%' % (
self.num, left_aligned_name, self.receive_bw_kbps, self.send_bw_kbps,
self.queue_slots, self.delay_ms, self.packet_loss_percent) | [
"def",
"__str__",
"(",
"self",
")",
":",
"left_aligned_name",
"=",
"self",
".",
"name",
".",
"ljust",
"(",
"24",
",",
"' '",
")",
"return",
"'%2s %24s %5s kbps %5s kbps %4s %5s ms %3s %%'",
"%",
"(",
"self",
".",
"num",
",",
"left_aligned_name",
",",
"self",
... | https://github.com/svn2github/webrtc/blob/0e4615a75ed555ec866cd5543bfea586f3385ceb/tools/network_emulator/config.py#L26-L36 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/eclib/platebtn.py | python | PlateButton.OnErase | (self, evt) | Trap the erase event to keep the background transparent
on windows.
@param evt: wx.EVT_ERASE_BACKGROUND | Trap the erase event to keep the background transparent
on windows.
@param evt: wx.EVT_ERASE_BACKGROUND | [
"Trap",
"the",
"erase",
"event",
"to",
"keep",
"the",
"background",
"transparent",
"on",
"windows",
".",
"@param",
"evt",
":",
"wx",
".",
"EVT_ERASE_BACKGROUND"
] | def OnErase(self, evt):
"""Trap the erase event to keep the background transparent
on windows.
@param evt: wx.EVT_ERASE_BACKGROUND
"""
if not (PB_STYLE_NOBG & self._style):
evt.Skip() | [
"def",
"OnErase",
"(",
"self",
",",
"evt",
")",
":",
"if",
"not",
"(",
"PB_STYLE_NOBG",
"&",
"self",
".",
"_style",
")",
":",
"evt",
".",
"Skip",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/platebtn.py#L498-L505 | ||
chuckcho/video-caffe | fc232b3e3a90ea22dd041b9fc5c542f170581f20 | python/caffe/net_spec.py | python | Top.to_proto | (self) | return to_proto(self) | Generate a NetParameter that contains all layers needed to compute
this top. | Generate a NetParameter that contains all layers needed to compute
this top. | [
"Generate",
"a",
"NetParameter",
"that",
"contains",
"all",
"layers",
"needed",
"to",
"compute",
"this",
"top",
"."
] | def to_proto(self):
"""Generate a NetParameter that contains all layers needed to compute
this top."""
return to_proto(self) | [
"def",
"to_proto",
"(",
"self",
")",
":",
"return",
"to_proto",
"(",
"self",
")"
] | https://github.com/chuckcho/video-caffe/blob/fc232b3e3a90ea22dd041b9fc5c542f170581f20/python/caffe/net_spec.py#L90-L94 | |
Bareflank/hypervisor | 10af879f58a0b1d9ace17b84cd9b1e41a1cc67d0 | utils/iwyu_tool.py | python | _bootstrap | (sys_argv) | return main(args.dbpath, args.source, args.verbose,
FORMATTERS[args.output_format], args.jobs, extra_args) | Parse arguments and dispatch to main(). | Parse arguments and dispatch to main(). | [
"Parse",
"arguments",
"and",
"dispatch",
"to",
"main",
"()",
"."
] | def _bootstrap(sys_argv):
""" Parse arguments and dispatch to main(). """
# This hackery is necessary to add the forwarded IWYU args to the
# usage and help strings.
def customize_usage(parser):
""" Rewrite the parser's format_usage. """
original_format_usage = parser.format_usage
parser.format_usage = lambda: original_format_usage().rstrip() + \
' -- [<IWYU args>]' + os.linesep
def customize_help(parser):
""" Rewrite the parser's format_help. """
original_format_help = parser.format_help
def custom_help():
""" Customized help string, calls the adjusted format_usage. """
helpmsg = original_format_help()
helplines = helpmsg.splitlines()
helplines[0] = parser.format_usage().rstrip()
return os.linesep.join(helplines) + os.linesep
parser.format_help = custom_help
# Parse arguments.
parser = argparse.ArgumentParser(
description='Include-what-you-use compilation database driver.',
epilog='Assumes include-what-you-use is available on the PATH.')
customize_usage(parser)
customize_help(parser)
parser.add_argument('-v', '--verbose', action='store_true',
help='Print IWYU commands')
parser.add_argument('-o', '--output-format', type=str,
choices=FORMATTERS.keys(), default=DEFAULT_FORMAT,
help='Output format (default: %s)' % DEFAULT_FORMAT)
parser.add_argument('-j', '--jobs', type=int, default=1,
help='Number of concurrent subprocesses')
parser.add_argument('-p', metavar='<build-path>', required=True,
help='Compilation database path', dest='dbpath')
parser.add_argument('source', nargs='*',
help=('Zero or more source files (or directories) to '
'run IWYU on. Defaults to all in compilation '
'database.'))
def partition_args(argv):
""" Split around '--' into driver args and IWYU args. """
try:
double_dash = argv.index('--')
return argv[:double_dash], argv[double_dash+1:]
except ValueError:
return argv, []
argv, extra_args = partition_args(sys_argv[1:])
args = parser.parse_args(argv)
return main(args.dbpath, args.source, args.verbose,
FORMATTERS[args.output_format], args.jobs, extra_args) | [
"def",
"_bootstrap",
"(",
"sys_argv",
")",
":",
"# This hackery is necessary to add the forwarded IWYU args to the",
"# usage and help strings.",
"def",
"customize_usage",
"(",
"parser",
")",
":",
"\"\"\" Rewrite the parser's format_usage. \"\"\"",
"original_format_usage",
"=",
"pa... | https://github.com/Bareflank/hypervisor/blob/10af879f58a0b1d9ace17b84cd9b1e41a1cc67d0/utils/iwyu_tool.py#L425-L481 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_txt.py | python | CheckBom | (line) | return has_bom | Try to look for a bom byte at the beginning of the given line
@param line: line (first line) of a file
@return: encoding or None | Try to look for a bom byte at the beginning of the given line
@param line: line (first line) of a file
@return: encoding or None | [
"Try",
"to",
"look",
"for",
"a",
"bom",
"byte",
"at",
"the",
"beginning",
"of",
"the",
"given",
"line",
"@param",
"line",
":",
"line",
"(",
"first",
"line",
")",
"of",
"a",
"file",
"@return",
":",
"encoding",
"or",
"None"
] | def CheckBom(line):
"""Try to look for a bom byte at the beginning of the given line
@param line: line (first line) of a file
@return: encoding or None
"""
Log("[ed_txt][info] CheckBom called")
has_bom = None
# NOTE: MUST check UTF-32 BEFORE utf-16
for enc in ('utf-8', 'utf-32', 'utf-16'):
bom = BOM[enc]
if line.startswith(bom):
has_bom = enc
break
return has_bom | [
"def",
"CheckBom",
"(",
"line",
")",
":",
"Log",
"(",
"\"[ed_txt][info] CheckBom called\"",
")",
"has_bom",
"=",
"None",
"# NOTE: MUST check UTF-32 BEFORE utf-16",
"for",
"enc",
"in",
"(",
"'utf-8'",
",",
"'utf-32'",
",",
"'utf-16'",
")",
":",
"bom",
"=",
"BOM",... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_txt.py#L661-L675 | |
apiaryio/snowcrash | b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3 | tools/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.IsLinkIncremental | (self, config) | return link_inc != '1' | Returns whether the target should be linked incrementally. | Returns whether the target should be linked incrementally. | [
"Returns",
"whether",
"the",
"target",
"should",
"be",
"linked",
"incrementally",
"."
] | def IsLinkIncremental(self, config):
"""Returns whether the target should be linked incrementally."""
config = self._TargetConfig(config)
link_inc = self._Setting(('VCLinkerTool', 'LinkIncremental'), config)
return link_inc != '1' | [
"def",
"IsLinkIncremental",
"(",
"self",
",",
"config",
")",
":",
"config",
"=",
"self",
".",
"_TargetConfig",
"(",
"config",
")",
"link_inc",
"=",
"self",
".",
"_Setting",
"(",
"(",
"'VCLinkerTool'",
",",
"'LinkIncremental'",
")",
",",
"config",
")",
"ret... | https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/msvs_emulation.py#L771-L775 | |
dscharrer/innoextract | 5519d364cc8898f906f6285d81a87ab8c5469cde | cmake/cpplint.py | python | FileInfo.NoExtension | (self) | return '/'.join(self.Split()[0:2]) | File has no source file extension. | File has no source file extension. | [
"File",
"has",
"no",
"source",
"file",
"extension",
"."
] | def NoExtension(self):
"""File has no source file extension."""
return '/'.join(self.Split()[0:2]) | [
"def",
"NoExtension",
"(",
"self",
")",
":",
"return",
"'/'",
".",
"join",
"(",
"self",
".",
"Split",
"(",
")",
"[",
"0",
":",
"2",
"]",
")"
] | https://github.com/dscharrer/innoextract/blob/5519d364cc8898f906f6285d81a87ab8c5469cde/cmake/cpplint.py#L819-L821 | |
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | mlir/python/mlir/dialects/linalg/opdsl/lang/comprehension.py | python | TensorExpression.collect_indices | (self, indices: Set["index"]) | Collects all index accesses reachable through this expression. | Collects all index accesses reachable through this expression. | [
"Collects",
"all",
"index",
"accesses",
"reachable",
"through",
"this",
"expression",
"."
] | def collect_indices(self, indices: Set["index"]):
"""Collects all index accesses reachable through this expression."""
def visit_index(expr):
if isinstance(expr, index):
indices.add(expr)
self.visit_tensor_exprs(visit_index) | [
"def",
"collect_indices",
"(",
"self",
",",
"indices",
":",
"Set",
"[",
"\"index\"",
"]",
")",
":",
"def",
"visit_index",
"(",
"expr",
")",
":",
"if",
"isinstance",
"(",
"expr",
",",
"index",
")",
":",
"indices",
".",
"add",
"(",
"expr",
")",
"self",... | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/mlir/python/mlir/dialects/linalg/opdsl/lang/comprehension.py#L61-L68 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/cluster/_mean_shift.py | python | mean_shift | (X, bandwidth=None, seeds=None, bin_seeding=False,
min_bin_freq=1, cluster_all=True, max_iter=300,
n_jobs=None) | return model.cluster_centers_, model.labels_ | Perform mean shift clustering of data using a flat kernel.
Read more in the :ref:`User Guide <mean_shift>`.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Input data.
bandwidth : float, optional
Kernel bandwidth.
If bandwidth is not given, it is determined using a heuristic based on
the median of all pairwise distances. This will take quadratic time in
the number of samples. The sklearn.cluster.estimate_bandwidth function
can be used to do this more efficiently.
seeds : array-like of shape (n_seeds, n_features) or None
Point used as initial kernel locations. If None and bin_seeding=False,
each data point is used as a seed. If None and bin_seeding=True,
see bin_seeding.
bin_seeding : boolean, default=False
If true, initial kernel locations are not locations of all
points, but rather the location of the discretized version of
points, where points are binned onto a grid whose coarseness
corresponds to the bandwidth. Setting this option to True will speed
up the algorithm because fewer seeds will be initialized.
Ignored if seeds argument is not None.
min_bin_freq : int, default=1
To speed up the algorithm, accept only those bins with at least
min_bin_freq points as seeds.
cluster_all : boolean, default True
If true, then all points are clustered, even those orphans that are
not within any kernel. Orphans are assigned to the nearest kernel.
If false, then orphans are given cluster label -1.
max_iter : int, default 300
Maximum number of iterations, per seed point before the clustering
operation terminates (for that seed point), if has not converged yet.
n_jobs : int or None, optional (default=None)
The number of jobs to use for the computation. This works by computing
each of the n_init runs in parallel.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.
.. versionadded:: 0.17
Parallel Execution using *n_jobs*.
Returns
-------
cluster_centers : array, shape=[n_clusters, n_features]
Coordinates of cluster centers.
labels : array, shape=[n_samples]
Cluster labels for each point.
Notes
-----
For an example, see :ref:`examples/cluster/plot_mean_shift.py
<sphx_glr_auto_examples_cluster_plot_mean_shift.py>`. | Perform mean shift clustering of data using a flat kernel. | [
"Perform",
"mean",
"shift",
"clustering",
"of",
"data",
"using",
"a",
"flat",
"kernel",
"."
] | def mean_shift(X, bandwidth=None, seeds=None, bin_seeding=False,
min_bin_freq=1, cluster_all=True, max_iter=300,
n_jobs=None):
"""Perform mean shift clustering of data using a flat kernel.
Read more in the :ref:`User Guide <mean_shift>`.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Input data.
bandwidth : float, optional
Kernel bandwidth.
If bandwidth is not given, it is determined using a heuristic based on
the median of all pairwise distances. This will take quadratic time in
the number of samples. The sklearn.cluster.estimate_bandwidth function
can be used to do this more efficiently.
seeds : array-like of shape (n_seeds, n_features) or None
Point used as initial kernel locations. If None and bin_seeding=False,
each data point is used as a seed. If None and bin_seeding=True,
see bin_seeding.
bin_seeding : boolean, default=False
If true, initial kernel locations are not locations of all
points, but rather the location of the discretized version of
points, where points are binned onto a grid whose coarseness
corresponds to the bandwidth. Setting this option to True will speed
up the algorithm because fewer seeds will be initialized.
Ignored if seeds argument is not None.
min_bin_freq : int, default=1
To speed up the algorithm, accept only those bins with at least
min_bin_freq points as seeds.
cluster_all : boolean, default True
If true, then all points are clustered, even those orphans that are
not within any kernel. Orphans are assigned to the nearest kernel.
If false, then orphans are given cluster label -1.
max_iter : int, default 300
Maximum number of iterations, per seed point before the clustering
operation terminates (for that seed point), if has not converged yet.
n_jobs : int or None, optional (default=None)
The number of jobs to use for the computation. This works by computing
each of the n_init runs in parallel.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.
.. versionadded:: 0.17
Parallel Execution using *n_jobs*.
Returns
-------
cluster_centers : array, shape=[n_clusters, n_features]
Coordinates of cluster centers.
labels : array, shape=[n_samples]
Cluster labels for each point.
Notes
-----
For an example, see :ref:`examples/cluster/plot_mean_shift.py
<sphx_glr_auto_examples_cluster_plot_mean_shift.py>`.
"""
model = MeanShift(bandwidth=bandwidth, seeds=seeds,
min_bin_freq=min_bin_freq,
bin_seeding=bin_seeding,
cluster_all=cluster_all, n_jobs=n_jobs,
max_iter=max_iter).fit(X)
return model.cluster_centers_, model.labels_ | [
"def",
"mean_shift",
"(",
"X",
",",
"bandwidth",
"=",
"None",
",",
"seeds",
"=",
"None",
",",
"bin_seeding",
"=",
"False",
",",
"min_bin_freq",
"=",
"1",
",",
"cluster_all",
"=",
"True",
",",
"max_iter",
"=",
"300",
",",
"n_jobs",
"=",
"None",
")",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/cluster/_mean_shift.py#L109-L187 | |
philogb/v8-gl | 157c113914659b8d0cecc92b9cbc0703f15f35ec | glesbindings/glesbind.py | python | generate_call | (obj) | generates the native function call syntax | generates the native function call syntax | [
"generates",
"the",
"native",
"function",
"call",
"syntax"
] | def generate_call(obj):
"""generates the native function call syntax"""
acc = get_accessor(obj['return_type'])
function_call = obj['name'] + "(" + ", ".join(['(' + param + ') ' + "arg" + str(i) \
for i, param in enumerate(obj['parameters'])]) + ")"
#dot-this-dot-that feature
if acc is None:
return function_call + ';\n Handle<Object> res(GlesFactory::self_);\n return res;'
else:
return 'return ' + acc + '::New(' + function_call + ');' | [
"def",
"generate_call",
"(",
"obj",
")",
":",
"acc",
"=",
"get_accessor",
"(",
"obj",
"[",
"'return_type'",
"]",
")",
"function_call",
"=",
"obj",
"[",
"'name'",
"]",
"+",
"\"(\"",
"+",
"\", \"",
".",
"join",
"(",
"[",
"'('",
"+",
"param",
"+",
"') '... | https://github.com/philogb/v8-gl/blob/157c113914659b8d0cecc92b9cbc0703f15f35ec/glesbindings/glesbind.py#L282-L293 | ||
openthread/openthread | 9fcdbed9c526c70f1556d1ed84099c1535c7cd32 | tools/harness-sniffer/OT_Sniffer.py | python | OT_Sniffer.isSnifferCapturing | (self) | return self.is_active | method that will return true when sniffer device is capturing
@return : bool | method that will return true when sniffer device is capturing | [
"method",
"that",
"will",
"return",
"true",
"when",
"sniffer",
"device",
"is",
"capturing"
] | def isSnifferCapturing(self):
"""
method that will return true when sniffer device is capturing
@return : bool
"""
return self.is_active | [
"def",
"isSnifferCapturing",
"(",
"self",
")",
":",
"return",
"self",
".",
"is_active"
] | https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/harness-sniffer/OT_Sniffer.py#L142-L147 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/protobuf/py3/google/protobuf/message.py | python | Message.ByteSize | (self) | Returns the serialized size of this message.
Recursively calls ByteSize() on all contained messages.
Returns:
int: The number of bytes required to serialize this message. | Returns the serialized size of this message. | [
"Returns",
"the",
"serialized",
"size",
"of",
"this",
"message",
"."
] | def ByteSize(self):
"""Returns the serialized size of this message.
Recursively calls ByteSize() on all contained messages.
Returns:
int: The number of bytes required to serialize this message.
"""
raise NotImplementedError | [
"def",
"ByteSize",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/message.py#L352-L360 | ||
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | python/mxnet/gluon/loss.py | python | _reshape_like | (F, x, y) | return x.reshape(y.shape) if F is ndarray else F.reshape_like(x, y) | Reshapes x to the same shape as y. | Reshapes x to the same shape as y. | [
"Reshapes",
"x",
"to",
"the",
"same",
"shape",
"as",
"y",
"."
] | def _reshape_like(F, x, y):
"""Reshapes x to the same shape as y."""
return x.reshape(y.shape) if F is ndarray else F.reshape_like(x, y) | [
"def",
"_reshape_like",
"(",
"F",
",",
"x",
",",
"y",
")",
":",
"return",
"x",
".",
"reshape",
"(",
"y",
".",
"shape",
")",
"if",
"F",
"is",
"ndarray",
"else",
"F",
".",
"reshape_like",
"(",
"x",
",",
"y",
")"
] | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/gluon/loss.py#L62-L64 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/ogl/_basic.py | python | Shape.AttachmentIsValid | (self, attachment) | return False | TRUE if attachment is a valid attachment point. | TRUE if attachment is a valid attachment point. | [
"TRUE",
"if",
"attachment",
"is",
"a",
"valid",
"attachment",
"point",
"."
] | def AttachmentIsValid(self, attachment):
"""TRUE if attachment is a valid attachment point."""
if len(self._attachmentPoints) == 0:
return attachment in range(4)
for point in self._attachmentPoints:
if point._id == attachment:
return True
return False | [
"def",
"AttachmentIsValid",
"(",
"self",
",",
"attachment",
")",
":",
"if",
"len",
"(",
"self",
".",
"_attachmentPoints",
")",
"==",
"0",
":",
"return",
"attachment",
"in",
"range",
"(",
"4",
")",
"for",
"point",
"in",
"self",
".",
"_attachmentPoints",
"... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/ogl/_basic.py#L1478-L1486 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/stats/_distn_infrastructure.py | python | rv_discrete.expect | (self, func=None, args=(), loc=0, lb=None, ub=None,
conditional=False, maxcount=1000, tolerance=1e-10, chunksize=32) | return res / invfac | Calculate expected value of a function with respect to the distribution
for discrete distribution by numerical summation.
Parameters
----------
func : callable, optional
Function for which the expectation value is calculated.
Takes only one argument.
The default is the identity mapping f(k) = k.
args : tuple, optional
Shape parameters of the distribution.
loc : float, optional
Location parameter.
Default is 0.
lb, ub : int, optional
Lower and upper bound for the summation, default is set to the
support of the distribution, inclusive (``ul <= k <= ub``).
conditional : bool, optional
If true then the expectation is corrected by the conditional
probability of the summation interval. The return value is the
expectation of the function, `func`, conditional on being in
the given interval (k such that ``ul <= k <= ub``).
Default is False.
maxcount : int, optional
Maximal number of terms to evaluate (to avoid an endless loop for
an infinite sum). Default is 1000.
tolerance : float, optional
Absolute tolerance for the summation. Default is 1e-10.
chunksize : int, optional
Iterate over the support of a distributions in chunks of this size.
Default is 32.
Returns
-------
expect : float
Expected value.
Notes
-----
For heavy-tailed distributions, the expected value may or may not exist,
depending on the function, `func`. If it does exist, but the sum converges
slowly, the accuracy of the result may be rather low. For instance, for
``zipf(4)``, accuracy for mean, variance in example is only 1e-5.
increasing `maxcount` and/or `chunksize` may improve the result, but may
also make zipf very slow.
The function is not vectorized. | Calculate expected value of a function with respect to the distribution
for discrete distribution by numerical summation. | [
"Calculate",
"expected",
"value",
"of",
"a",
"function",
"with",
"respect",
"to",
"the",
"distribution",
"for",
"discrete",
"distribution",
"by",
"numerical",
"summation",
"."
] | def expect(self, func=None, args=(), loc=0, lb=None, ub=None,
conditional=False, maxcount=1000, tolerance=1e-10, chunksize=32):
"""
Calculate expected value of a function with respect to the distribution
for discrete distribution by numerical summation.
Parameters
----------
func : callable, optional
Function for which the expectation value is calculated.
Takes only one argument.
The default is the identity mapping f(k) = k.
args : tuple, optional
Shape parameters of the distribution.
loc : float, optional
Location parameter.
Default is 0.
lb, ub : int, optional
Lower and upper bound for the summation, default is set to the
support of the distribution, inclusive (``ul <= k <= ub``).
conditional : bool, optional
If true then the expectation is corrected by the conditional
probability of the summation interval. The return value is the
expectation of the function, `func`, conditional on being in
the given interval (k such that ``ul <= k <= ub``).
Default is False.
maxcount : int, optional
Maximal number of terms to evaluate (to avoid an endless loop for
an infinite sum). Default is 1000.
tolerance : float, optional
Absolute tolerance for the summation. Default is 1e-10.
chunksize : int, optional
Iterate over the support of a distributions in chunks of this size.
Default is 32.
Returns
-------
expect : float
Expected value.
Notes
-----
For heavy-tailed distributions, the expected value may or may not exist,
depending on the function, `func`. If it does exist, but the sum converges
slowly, the accuracy of the result may be rather low. For instance, for
``zipf(4)``, accuracy for mean, variance in example is only 1e-5.
increasing `maxcount` and/or `chunksize` may improve the result, but may
also make zipf very slow.
The function is not vectorized.
"""
if func is None:
def fun(x):
# loc and args from outer scope
return (x+loc)*self._pmf(x, *args)
else:
def fun(x):
# loc and args from outer scope
return func(x+loc)*self._pmf(x, *args)
# used pmf because _pmf does not check support in randint and there
# might be problems(?) with correct self.a, self.b at this stage maybe
# not anymore, seems to work now with _pmf
self._argcheck(*args) # (re)generate scalar self.a and self.b
if lb is None:
lb = self.a
else:
lb = lb - loc # convert bound for standardized distribution
if ub is None:
ub = self.b
else:
ub = ub - loc # convert bound for standardized distribution
if conditional:
invfac = self.sf(lb-1, *args) - self.sf(ub, *args)
else:
invfac = 1.0
# iterate over the support, starting from the median
x0 = self.ppf(0.5, *args)
res = _expect(fun, lb, ub, x0, self.inc, maxcount, tolerance, chunksize)
return res / invfac | [
"def",
"expect",
"(",
"self",
",",
"func",
"=",
"None",
",",
"args",
"=",
"(",
")",
",",
"loc",
"=",
"0",
",",
"lb",
"=",
"None",
",",
"ub",
"=",
"None",
",",
"conditional",
"=",
"False",
",",
"maxcount",
"=",
"1000",
",",
"tolerance",
"=",
"1e... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/stats/_distn_infrastructure.py#L3172-L3253 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | CommandEvent.GetExtraLong | (*args, **kwargs) | return _core_.CommandEvent_GetExtraLong(*args, **kwargs) | GetExtraLong(self) -> long
Returns extra information dependant on the event objects type. If the
event comes from a listbox selection, it is a boolean determining
whether the event was a selection (true) or a deselection (false). A
listbox deselection only occurs for multiple-selection boxes, and in
this case the index and string values are indeterminate and the
listbox must be examined by the application. | GetExtraLong(self) -> long | [
"GetExtraLong",
"(",
"self",
")",
"-",
">",
"long"
] | def GetExtraLong(*args, **kwargs):
"""
GetExtraLong(self) -> long
Returns extra information dependant on the event objects type. If the
event comes from a listbox selection, it is a boolean determining
whether the event was a selection (true) or a deselection (false). A
listbox deselection only occurs for multiple-selection boxes, and in
this case the index and string values are indeterminate and the
listbox must be examined by the application.
"""
return _core_.CommandEvent_GetExtraLong(*args, **kwargs) | [
"def",
"GetExtraLong",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"CommandEvent_GetExtraLong",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L5260-L5271 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/arrays/period.py | python | validate_dtype_freq | (dtype, freq) | return freq | If both a dtype and a freq are available, ensure they match. If only
dtype is available, extract the implied freq.
Parameters
----------
dtype : dtype
freq : DateOffset or None
Returns
-------
freq : DateOffset
Raises
------
ValueError : non-period dtype
IncompatibleFrequency : mismatch between dtype and freq | If both a dtype and a freq are available, ensure they match. If only
dtype is available, extract the implied freq. | [
"If",
"both",
"a",
"dtype",
"and",
"a",
"freq",
"are",
"available",
"ensure",
"they",
"match",
".",
"If",
"only",
"dtype",
"is",
"available",
"extract",
"the",
"implied",
"freq",
"."
] | def validate_dtype_freq(dtype, freq):
"""
If both a dtype and a freq are available, ensure they match. If only
dtype is available, extract the implied freq.
Parameters
----------
dtype : dtype
freq : DateOffset or None
Returns
-------
freq : DateOffset
Raises
------
ValueError : non-period dtype
IncompatibleFrequency : mismatch between dtype and freq
"""
if freq is not None:
freq = to_offset(freq)
if dtype is not None:
dtype = pandas_dtype(dtype)
if not is_period_dtype(dtype):
raise ValueError("dtype must be PeriodDtype")
if freq is None:
freq = dtype.freq
elif freq != dtype.freq:
raise IncompatibleFrequency("specified freq and dtype are different")
return freq | [
"def",
"validate_dtype_freq",
"(",
"dtype",
",",
"freq",
")",
":",
"if",
"freq",
"is",
"not",
"None",
":",
"freq",
"=",
"to_offset",
"(",
"freq",
")",
"if",
"dtype",
"is",
"not",
"None",
":",
"dtype",
"=",
"pandas_dtype",
"(",
"dtype",
")",
"if",
"no... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/arrays/period.py#L1015-L1045 | |
wy1iu/LargeMargin_Softmax_Loss | c3e9f20e4f16e2b4daf7d358a614366b9b39a6ec | scripts/cpp_lint.py | python | CheckSectionSpacing | (filename, clean_lines, class_info, linenum, error) | Checks for additional blank line issues related to sections.
Currently the only thing checked here is blank line before protected/private.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
class_info: A _ClassInfo objects.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks for additional blank line issues related to sections. | [
"Checks",
"for",
"additional",
"blank",
"line",
"issues",
"related",
"to",
"sections",
"."
] | def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
"""Checks for additional blank line issues related to sections.
Currently the only thing checked here is blank line before protected/private.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
class_info: A _ClassInfo objects.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Skip checks if the class is small, where small means 25 lines or less.
# 25 lines seems like a good cutoff since that's the usual height of
# terminals, and any class that can't fit in one screen can't really
# be considered "small".
#
# Also skip checks if we are on the first line. This accounts for
# classes that look like
# class Foo { public: ... };
#
# If we didn't find the end of the class, last_line would be zero,
# and the check will be skipped by the first condition.
if (class_info.last_line - class_info.starting_linenum <= 24 or
linenum <= class_info.starting_linenum):
return
matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
if matched:
# Issue warning if the line before public/protected/private was
# not a blank line, but don't do this if the previous line contains
# "class" or "struct". This can happen two ways:
# - We are at the beginning of the class.
# - We are forward-declaring an inner class that is semantically
# private, but needed to be public for implementation reasons.
# Also ignores cases where the previous line ends with a backslash as can be
# common when defining classes in C macros.
prev_line = clean_lines.lines[linenum - 1]
if (not IsBlankLine(prev_line) and
not Search(r'\b(class|struct)\b', prev_line) and
not Search(r'\\$', prev_line)):
# Try a bit harder to find the beginning of the class. This is to
# account for multi-line base-specifier lists, e.g.:
# class Derived
# : public Base {
end_class_head = class_info.starting_linenum
for i in range(class_info.starting_linenum, linenum):
if Search(r'\{\s*$', clean_lines.lines[i]):
end_class_head = i
break
if end_class_head < linenum - 1:
error(filename, linenum, 'whitespace/blank_line', 3,
'"%s:" should be preceded by a blank line' % matched.group(1)) | [
"def",
"CheckSectionSpacing",
"(",
"filename",
",",
"clean_lines",
",",
"class_info",
",",
"linenum",
",",
"error",
")",
":",
"# Skip checks if the class is small, where small means 25 lines or less.",
"# 25 lines seems like a good cutoff since that's the usual height of",
"# termina... | https://github.com/wy1iu/LargeMargin_Softmax_Loss/blob/c3e9f20e4f16e2b4daf7d358a614366b9b39a6ec/scripts/cpp_lint.py#L2991-L3043 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/probability/distribution/gumbel.py | python | Gumbel._mean | (self) | return self.loc + self.scale * np.euler_gamma | r"""
The mean of the distribution.
.. math::
MEAN(X) = loc + scale * Euler-Mascheroni_constant | r"""
The mean of the distribution. | [
"r",
"The",
"mean",
"of",
"the",
"distribution",
"."
] | def _mean(self):
r"""
The mean of the distribution.
.. math::
MEAN(X) = loc + scale * Euler-Mascheroni_constant
"""
return self.loc + self.scale * np.euler_gamma | [
"def",
"_mean",
"(",
"self",
")",
":",
"return",
"self",
".",
"loc",
"+",
"self",
".",
"scale",
"*",
"np",
".",
"euler_gamma"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/distribution/gumbel.py#L162-L169 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pyio.py | python | BytesIO.getbuffer | (self) | return memoryview(self._buffer) | Return a readable and writable view of the buffer. | Return a readable and writable view of the buffer. | [
"Return",
"a",
"readable",
"and",
"writable",
"view",
"of",
"the",
"buffer",
"."
] | def getbuffer(self):
"""Return a readable and writable view of the buffer.
"""
if self.closed:
raise ValueError("getbuffer on closed file")
return memoryview(self._buffer) | [
"def",
"getbuffer",
"(",
"self",
")",
":",
"if",
"self",
".",
"closed",
":",
"raise",
"ValueError",
"(",
"\"getbuffer on closed file\"",
")",
"return",
"memoryview",
"(",
"self",
".",
"_buffer",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pyio.py#L865-L870 | |
mhammond/pywin32 | 44afd86ba8485194df93234639243252deeb40d5 | Pythonwin/pywin/framework/app.py | python | CheckCreateDefaultGUI | () | return rc | Checks and creates if necessary a default GUI environment. | Checks and creates if necessary a default GUI environment. | [
"Checks",
"and",
"creates",
"if",
"necessary",
"a",
"default",
"GUI",
"environment",
"."
] | def CheckCreateDefaultGUI():
"""Checks and creates if necessary a default GUI environment."""
rc = HaveGoodGUI()
if not rc:
CreateDefaultGUI()
return rc | [
"def",
"CheckCreateDefaultGUI",
"(",
")",
":",
"rc",
"=",
"HaveGoodGUI",
"(",
")",
"if",
"not",
"rc",
":",
"CreateDefaultGUI",
"(",
")",
"return",
"rc"
] | https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/Pythonwin/pywin/framework/app.py#L449-L454 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/aui.py | python | AuiPaneInfo.Dockable | (*args, **kwargs) | return _aui.AuiPaneInfo_Dockable(*args, **kwargs) | Dockable(self, bool b=True) -> AuiPaneInfo | Dockable(self, bool b=True) -> AuiPaneInfo | [
"Dockable",
"(",
"self",
"bool",
"b",
"=",
"True",
")",
"-",
">",
"AuiPaneInfo"
] | def Dockable(*args, **kwargs):
"""Dockable(self, bool b=True) -> AuiPaneInfo"""
return _aui.AuiPaneInfo_Dockable(*args, **kwargs) | [
"def",
"Dockable",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiPaneInfo_Dockable",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L505-L507 | |
envoyproxy/envoy | 65541accdafe255e72310b4298d646e091da2d80 | restarter/hot-restarter.py | python | shutdown | () | Attempt to gracefully shutdown all child Envoy processes and then exit.
See term_all_children() for further discussion. | Attempt to gracefully shutdown all child Envoy processes and then exit.
See term_all_children() for further discussion. | [
"Attempt",
"to",
"gracefully",
"shutdown",
"all",
"child",
"Envoy",
"processes",
"and",
"then",
"exit",
".",
"See",
"term_all_children",
"()",
"for",
"further",
"discussion",
"."
] | def shutdown():
""" Attempt to gracefully shutdown all child Envoy processes and then exit.
See term_all_children() for further discussion. """
term_all_children()
sys.exit(0) | [
"def",
"shutdown",
"(",
")",
":",
"term_all_children",
"(",
")",
"sys",
".",
"exit",
"(",
"0",
")"
] | https://github.com/envoyproxy/envoy/blob/65541accdafe255e72310b4298d646e091da2d80/restarter/hot-restarter.py#L81-L85 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tpu/tpu.py | python | rewrite | (computation,
inputs=None,
infeed_queue=None,
device_assignment=None,
name=None) | return replicate(
computation,
None if inputs is None else [inputs],
infeed_queue=infeed_queue,
device_assignment=device_assignment,
name=name)[0] | Rewrites `computation` for execution on a TPU system.
Args:
computation: A Python function that builds a computation to apply to the
input. If the function takes n inputs, 'inputs' should be a list of n
tensors.
`computation` may return a list of operations and tensors. Tensors must
come before operations in the returned list. The return value of
`rewrite` is a list of tensors corresponding to the tensors from the
output of `computation`.
All `Operation`s constructed during `computation` will be executed when
evaluating any of the returned output tensors, not just the ones returned.
inputs: A list of input tensors or `None` (equivalent to an empty list).
Each input can be a nested structure containing values that are
convertible to tensors. Note that passing an N-dimension list of
compatible values will result in a N-dimention list of scalar tensors
rather than a single Rank-N tensors. If you need different behavior,
convert part of inputs to tensors with `tf.convert_to_tensor`.
infeed_queue: If not `None`, the `InfeedQueue` from which to append a tuple
of arguments as inputs to `computation`.
device_assignment: if not `None`, a `DeviceAssignment` describing the
mapping between logical cores in the computation with physical cores in
the TPU topology. May be omitted for a single-core computation, in which
case the core attached to task 0, TPU device 0 is used.
name: (Deprecated) Does nothing.
Returns:
Same data structure as if computation(*inputs) is called directly with some
exceptions for correctness. Exceptions include:
1) None output: a NoOp would be returned which control-depends on
computation.
2) Single value output: A tuple containing the value would be returned.
3) Operation-only outputs: a NoOp would be returned which
control-depends on computation.
TODO(b/121383831): Investigate into removing these special cases. | Rewrites `computation` for execution on a TPU system. | [
"Rewrites",
"computation",
"for",
"execution",
"on",
"a",
"TPU",
"system",
"."
] | def rewrite(computation,
inputs=None,
infeed_queue=None,
device_assignment=None,
name=None):
"""Rewrites `computation` for execution on a TPU system.
Args:
computation: A Python function that builds a computation to apply to the
input. If the function takes n inputs, 'inputs' should be a list of n
tensors.
`computation` may return a list of operations and tensors. Tensors must
come before operations in the returned list. The return value of
`rewrite` is a list of tensors corresponding to the tensors from the
output of `computation`.
All `Operation`s constructed during `computation` will be executed when
evaluating any of the returned output tensors, not just the ones returned.
inputs: A list of input tensors or `None` (equivalent to an empty list).
Each input can be a nested structure containing values that are
convertible to tensors. Note that passing an N-dimension list of
compatible values will result in a N-dimention list of scalar tensors
rather than a single Rank-N tensors. If you need different behavior,
convert part of inputs to tensors with `tf.convert_to_tensor`.
infeed_queue: If not `None`, the `InfeedQueue` from which to append a tuple
of arguments as inputs to `computation`.
device_assignment: if not `None`, a `DeviceAssignment` describing the
mapping between logical cores in the computation with physical cores in
the TPU topology. May be omitted for a single-core computation, in which
case the core attached to task 0, TPU device 0 is used.
name: (Deprecated) Does nothing.
Returns:
Same data structure as if computation(*inputs) is called directly with some
exceptions for correctness. Exceptions include:
1) None output: a NoOp would be returned which control-depends on
computation.
2) Single value output: A tuple containing the value would be returned.
3) Operation-only outputs: a NoOp would be returned which
control-depends on computation.
TODO(b/121383831): Investigate into removing these special cases.
"""
# TODO(b/36647078) remove disable when pylint bug is fixed.
# pylint: disable=indexing-exception
return replicate(
computation,
None if inputs is None else [inputs],
infeed_queue=infeed_queue,
device_assignment=device_assignment,
name=name)[0] | [
"def",
"rewrite",
"(",
"computation",
",",
"inputs",
"=",
"None",
",",
"infeed_queue",
"=",
"None",
",",
"device_assignment",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"# TODO(b/36647078) remove disable when pylint bug is fixed.",
"# pylint: disable=indexing-exce... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tpu/tpu.py#L1465-L1514 | |
facebook/ThreatExchange | 31914a51820c73c8a0daffe62ccca29a6e3d359e | python-threatexchange/threatexchange/cli/cli_config.py | python | CliState.get_all_collabs | (self) | return [] | Get all collaborations | Get all collaborations | [
"Get",
"all",
"collaborations"
] | def get_all_collabs(self) -> t.List[CollaborationConfig]:
"""Get all collaborations"""
return [] | [
"def",
"get_all_collabs",
"(",
"self",
")",
"->",
"t",
".",
"List",
"[",
"CollaborationConfig",
"]",
":",
"return",
"[",
"]"
] | https://github.com/facebook/ThreatExchange/blob/31914a51820c73c8a0daffe62ccca29a6e3d359e/python-threatexchange/threatexchange/cli/cli_config.py#L48-L50 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | PhotoImage.put | (self, data, to=None) | Put row formatted colors to image starting from
position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6)) | Put row formatted colors to image starting from
position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6)) | [
"Put",
"row",
"formatted",
"colors",
"to",
"image",
"starting",
"from",
"position",
"TO",
"e",
".",
"g",
".",
"image",
".",
"put",
"(",
"{",
"red",
"green",
"}",
"{",
"blue",
"yellow",
"}",
"to",
"=",
"(",
"4",
"6",
"))"
] | def put(self, data, to=None):
"""Put row formatted colors to image starting from
position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
args = (self.name, 'put', data)
if to:
if to[0] == '-to':
to = to[1:]
args = args + ('-to',) + tuple(to)
self.tk.call(args) | [
"def",
"put",
"(",
"self",
",",
"data",
",",
"to",
"=",
"None",
")",
":",
"args",
"=",
"(",
"self",
".",
"name",
",",
"'put'",
",",
"data",
")",
"if",
"to",
":",
"if",
"to",
"[",
"0",
"]",
"==",
"'-to'",
":",
"to",
"=",
"to",
"[",
"1",
":... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L3339-L3347 | ||
dmlc/nnvm | dab5ce8ab6adbf4edd8bd2fa89f1a99f343b6e38 | python/nnvm/frontend/darknet.py | python | _darknet_reshape | (inputs, attrs) | return _darknet_get_nnvm_op(op_name)(*inputs, **new_attrs), None | Process the reshape operation. | Process the reshape operation. | [
"Process",
"the",
"reshape",
"operation",
"."
] | def _darknet_reshape(inputs, attrs):
"""Process the reshape operation."""
if _darknet_parse_bool_str(attrs, 'reverse'):
_darknet_raise_not_supported('reverse', 'reshape')
op_name, new_attrs = 'reshape', {}
new_attrs['shape'] = _darknet_required_attr(attrs, 'shape')
return _darknet_get_nnvm_op(op_name)(*inputs, **new_attrs), None | [
"def",
"_darknet_reshape",
"(",
"inputs",
",",
"attrs",
")",
":",
"if",
"_darknet_parse_bool_str",
"(",
"attrs",
",",
"'reverse'",
")",
":",
"_darknet_raise_not_supported",
"(",
"'reverse'",
",",
"'reshape'",
")",
"op_name",
",",
"new_attrs",
"=",
"'reshape'",
"... | https://github.com/dmlc/nnvm/blob/dab5ce8ab6adbf4edd8bd2fa89f1a99f343b6e38/python/nnvm/frontend/darknet.py#L248-L254 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/ExodusViewer/plugins/ClipPlugin.py | python | ClipPlugin._loadPlugin | (self) | Helper for loading plugin state. | Helper for loading plugin state. | [
"Helper",
"for",
"loading",
"plugin",
"state",
"."
] | def _loadPlugin(self):
"""
Helper for loading plugin state.
"""
self.load()
if not self.hasState():
self.setChecked(False) | [
"def",
"_loadPlugin",
"(",
"self",
")",
":",
"self",
".",
"load",
"(",
")",
"if",
"not",
"self",
".",
"hasState",
"(",
")",
":",
"self",
".",
"setChecked",
"(",
"False",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/ExodusViewer/plugins/ClipPlugin.py#L61-L67 | ||
blackberry/Boost | fc90c3fde129c62565c023f091eddc4a7ed9902b | tools/build/v2/build/feature.py | python | reset | () | Clear the module state. This is mainly for testing purposes. | Clear the module state. This is mainly for testing purposes. | [
"Clear",
"the",
"module",
"state",
".",
"This",
"is",
"mainly",
"for",
"testing",
"purposes",
"."
] | def reset ():
""" Clear the module state. This is mainly for testing purposes.
"""
global __all_attributes, __all_features, __implicit_features, __composite_properties
global __features_with_attributes, __subfeature_from_value, __all_top_features, __free_features
global __all_subfeatures
# The list with all attribute names.
__all_attributes = [ 'implicit',
'composite',
'optional',
'symmetric',
'free',
'incidental',
'path',
'dependency',
'propagated',
'link-incompatible',
'subfeature',
'order-sensitive'
]
i = 1
for a in __all_attributes:
setattr(Feature, a.upper(), i)
Feature._attribute_name_to_integer[a] = i
def probe(self, flag=i):
return getattr(self, "_attributes") & flag
setattr(Feature, a.replace("-", "_"), probe)
i = i << 1
# A map containing all features. The key is the feature name.
# The value is an instance of Feature class.
__all_features = {}
# All non-subfeatures.
__all_top_features = []
# Maps valus to the corresponding implicit feature
__implicit_features = {}
# A map containing all composite properties. The key is a Property instance,
# and the value is a list of Property instances
__composite_properties = {}
__features_with_attributes = {}
for attribute in __all_attributes:
__features_with_attributes [attribute] = []
# Maps a value to the corresponding subfeature name.
__subfeature_from_value = {}
# All free features
__free_features = []
__all_subfeatures = [] | [
"def",
"reset",
"(",
")",
":",
"global",
"__all_attributes",
",",
"__all_features",
",",
"__implicit_features",
",",
"__composite_properties",
"global",
"__features_with_attributes",
",",
"__subfeature_from_value",
",",
"__all_top_features",
",",
"__free_features",
"global"... | https://github.com/blackberry/Boost/blob/fc90c3fde129c62565c023f091eddc4a7ed9902b/tools/build/v2/build/feature.py#L81-L135 | ||
bristolcrypto/SPDZ-2 | 721abfae849625a02ea49aabc534f9cf41ca643f | Compiler/types.py | python | regint.init_secure_socket | (cls, client_id, w1, w2, w3, w4, w5, w6, w7, w8) | Use 8 register values containing client public key. | Use 8 register values containing client public key. | [
"Use",
"8",
"register",
"values",
"containing",
"client",
"public",
"key",
"."
] | def init_secure_socket(cls, client_id, w1, w2, w3, w4, w5, w6, w7, w8):
""" Use 8 register values containing client public key."""
initsecuresocket(client_id, w1, w2, w3, w4, w5, w6, w7, w8) | [
"def",
"init_secure_socket",
"(",
"cls",
",",
"client_id",
",",
"w1",
",",
"w2",
",",
"w3",
",",
"w4",
",",
"w5",
",",
"w6",
",",
"w7",
",",
"w8",
")",
":",
"initsecuresocket",
"(",
"client_id",
",",
"w1",
",",
"w2",
",",
"w3",
",",
"w4",
",",
... | https://github.com/bristolcrypto/SPDZ-2/blob/721abfae849625a02ea49aabc534f9cf41ca643f/Compiler/types.py#L649-L651 | ||
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/algorithms/action_value_vs_best_response.py | python | _transitions | (state, policies) | Returns a list of (action, prob) pairs from the specified state. | Returns a list of (action, prob) pairs from the specified state. | [
"Returns",
"a",
"list",
"of",
"(",
"action",
"prob",
")",
"pairs",
"from",
"the",
"specified",
"state",
"."
] | def _transitions(state, policies):
"""Returns a list of (action, prob) pairs from the specified state."""
if state.is_chance_node():
return state.chance_outcomes()
else:
pl = state.current_player()
return list(policies[pl].action_probabilities(state).items()) | [
"def",
"_transitions",
"(",
"state",
",",
"policies",
")",
":",
"if",
"state",
".",
"is_chance_node",
"(",
")",
":",
"return",
"state",
".",
"chance_outcomes",
"(",
")",
"else",
":",
"pl",
"=",
"state",
".",
"current_player",
"(",
")",
"return",
"list",
... | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/action_value_vs_best_response.py#L30-L36 | ||
tangzhenyu/Scene-Text-Understanding | 0f7ffc7aea5971a50cdc03d33d0a41075285948b | ctpn_crnn_ocr/CTPN/caffe/scripts/cpp_lint.py | python | _SetVerboseLevel | (level) | return _cpplint_state.SetVerboseLevel(level) | Sets the module's verbosity, and returns the previous setting. | Sets the module's verbosity, and returns the previous setting. | [
"Sets",
"the",
"module",
"s",
"verbosity",
"and",
"returns",
"the",
"previous",
"setting",
"."
] | def _SetVerboseLevel(level):
"""Sets the module's verbosity, and returns the previous setting."""
return _cpplint_state.SetVerboseLevel(level) | [
"def",
"_SetVerboseLevel",
"(",
"level",
")",
":",
"return",
"_cpplint_state",
".",
"SetVerboseLevel",
"(",
"level",
")"
] | https://github.com/tangzhenyu/Scene-Text-Understanding/blob/0f7ffc7aea5971a50cdc03d33d0a41075285948b/ctpn_crnn_ocr/CTPN/caffe/scripts/cpp_lint.py#L782-L784 | |
microsoft/onnxruntime | f92e47e95b13a240e37caf7b36577983544f98fc | onnxruntime/python/onnxruntime_inference_collection.py | python | OrtValue.numpy | (self) | return self._ortvalue.numpy() | Returns a Numpy object from the OrtValue.
Valid only for OrtValues holding Tensors. Throws for OrtValues holding non-Tensors.
Use accessors to gain a reference to non-Tensor objects such as SparseTensor | Returns a Numpy object from the OrtValue.
Valid only for OrtValues holding Tensors. Throws for OrtValues holding non-Tensors.
Use accessors to gain a reference to non-Tensor objects such as SparseTensor | [
"Returns",
"a",
"Numpy",
"object",
"from",
"the",
"OrtValue",
".",
"Valid",
"only",
"for",
"OrtValues",
"holding",
"Tensors",
".",
"Throws",
"for",
"OrtValues",
"holding",
"non",
"-",
"Tensors",
".",
"Use",
"accessors",
"to",
"gain",
"a",
"reference",
"to",
... | def numpy(self):
'''
Returns a Numpy object from the OrtValue.
Valid only for OrtValues holding Tensors. Throws for OrtValues holding non-Tensors.
Use accessors to gain a reference to non-Tensor objects such as SparseTensor
'''
return self._ortvalue.numpy() | [
"def",
"numpy",
"(",
"self",
")",
":",
"return",
"self",
".",
"_ortvalue",
".",
"numpy",
"(",
")"
] | https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/onnxruntime/python/onnxruntime_inference_collection.py#L632-L638 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/pyyaml/lib3/yaml/__init__.py | python | safe_load_all | (stream) | return load_all(stream, SafeLoader) | Parse all YAML documents in a stream
and produce corresponding Python objects.
Resolve only basic YAML tags. | Parse all YAML documents in a stream
and produce corresponding Python objects.
Resolve only basic YAML tags. | [
"Parse",
"all",
"YAML",
"documents",
"in",
"a",
"stream",
"and",
"produce",
"corresponding",
"Python",
"objects",
".",
"Resolve",
"only",
"basic",
"YAML",
"tags",
"."
] | def safe_load_all(stream):
"""
Parse all YAML documents in a stream
and produce corresponding Python objects.
Resolve only basic YAML tags.
"""
return load_all(stream, SafeLoader) | [
"def",
"safe_load_all",
"(",
"stream",
")",
":",
"return",
"load_all",
"(",
"stream",
",",
"SafeLoader",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/pyyaml/lib3/yaml/__init__.py#L96-L102 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/core.py | python | getmask | (a) | return getattr(a, '_mask', nomask) | Return the mask of a masked array, or nomask.
Return the mask of `a` as an ndarray if `a` is a `MaskedArray` and the
mask is not `nomask`, else return `nomask`. To guarantee a full array
of booleans of the same shape as a, use `getmaskarray`.
Parameters
----------
a : array_like
Input `MaskedArray` for which the mask is required.
See Also
--------
getdata : Return the data of a masked array as an ndarray.
getmaskarray : Return the mask of a masked array, or full array of False.
Examples
--------
>>> import numpy.ma as ma
>>> a = ma.masked_equal([[1,2],[3,4]], 2)
>>> a
masked_array(data =
[[1 --]
[3 4]],
mask =
[[False True]
[False False]],
fill_value=999999)
>>> ma.getmask(a)
array([[False, True],
[False, False]], dtype=bool)
Equivalently use the `MaskedArray` `mask` attribute.
>>> a.mask
array([[False, True],
[False, False]], dtype=bool)
Result when mask == `nomask`
>>> b = ma.masked_array([[1,2],[3,4]])
>>> b
masked_array(data =
[[1 2]
[3 4]],
mask =
False,
fill_value=999999)
>>> ma.nomask
False
>>> ma.getmask(b) == ma.nomask
True
>>> b.mask == ma.nomask
True | Return the mask of a masked array, or nomask. | [
"Return",
"the",
"mask",
"of",
"a",
"masked",
"array",
"or",
"nomask",
"."
] | def getmask(a):
"""
Return the mask of a masked array, or nomask.
Return the mask of `a` as an ndarray if `a` is a `MaskedArray` and the
mask is not `nomask`, else return `nomask`. To guarantee a full array
of booleans of the same shape as a, use `getmaskarray`.
Parameters
----------
a : array_like
Input `MaskedArray` for which the mask is required.
See Also
--------
getdata : Return the data of a masked array as an ndarray.
getmaskarray : Return the mask of a masked array, or full array of False.
Examples
--------
>>> import numpy.ma as ma
>>> a = ma.masked_equal([[1,2],[3,4]], 2)
>>> a
masked_array(data =
[[1 --]
[3 4]],
mask =
[[False True]
[False False]],
fill_value=999999)
>>> ma.getmask(a)
array([[False, True],
[False, False]], dtype=bool)
Equivalently use the `MaskedArray` `mask` attribute.
>>> a.mask
array([[False, True],
[False, False]], dtype=bool)
Result when mask == `nomask`
>>> b = ma.masked_array([[1,2],[3,4]])
>>> b
masked_array(data =
[[1 2]
[3 4]],
mask =
False,
fill_value=999999)
>>> ma.nomask
False
>>> ma.getmask(b) == ma.nomask
True
>>> b.mask == ma.nomask
True
"""
return getattr(a, '_mask', nomask) | [
"def",
"getmask",
"(",
"a",
")",
":",
"return",
"getattr",
"(",
"a",
",",
"'_mask'",
",",
"nomask",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/core.py#L1244-L1302 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/plan/robotoptimize.py | python | KlamptVariable.bind | (self,obj) | Binds all Variables associated with this to the value of Klamp't object obj | Binds all Variables associated with this to the value of Klamp't object obj | [
"Binds",
"all",
"Variables",
"associated",
"with",
"this",
"to",
"the",
"value",
"of",
"Klamp",
"t",
"object",
"obj"
] | def bind(self,obj):
"""Binds all Variables associated with this to the value of Klamp't object obj"""
if self.type in ['Config','Vector','Vector3','Point']:
self.variables[0].bind(obj)
elif self.type == 'Configs':
assert len(obj) == len(self.variables),"Invalid number of configs in Configs object"
for i,v in enumerate(obj):
self.variables[i].bind(v)
elif self.type == 'Rotation':
if self.encoder is None:
self.variables[0].bind(obj)
else:
self.variables[0].bind(self.encoder(obj))
elif self.type == 'RigidTransform':
if self.encoder is None:
self.variables[0].bind(obj[0])
self.variables[1].bind(obj[1])
else:
T = self.encoder(obj)
self.variables[0].bind(T[0])
self.variables[1].bind(T[1])
else:
raise ValueError("Unsupported object type "+self.type) | [
"def",
"bind",
"(",
"self",
",",
"obj",
")",
":",
"if",
"self",
".",
"type",
"in",
"[",
"'Config'",
",",
"'Vector'",
",",
"'Vector3'",
",",
"'Point'",
"]",
":",
"self",
".",
"variables",
"[",
"0",
"]",
".",
"bind",
"(",
"obj",
")",
"elif",
"self"... | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/plan/robotoptimize.py#L30-L52 | ||
fasiondog/hikyuu | 842751aa25283f9fdafc6f560ea262f79e67a307 | hikyuu/interactive.py | python | get_global_context | () | return C.getContext() | 获取当前的全局上下文
:rtype: KData | 获取当前的全局上下文 | [
"获取当前的全局上下文"
] | def get_global_context():
"""获取当前的全局上下文
:rtype: KData
"""
return C.getContext() | [
"def",
"get_global_context",
"(",
")",
":",
"return",
"C",
".",
"getContext",
"(",
")"
] | https://github.com/fasiondog/hikyuu/blob/842751aa25283f9fdafc6f560ea262f79e67a307/hikyuu/interactive.py#L193-L198 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/signal/python/ops/window_ops.py | python | _raised_cosine_window | (name, default_name, window_length, periodic,
dtype, a, b) | Helper function for computing a raised cosine window.
Args:
name: Name to use for the scope.
default_name: Default name to use for the scope.
window_length: A scalar `Tensor` or integer indicating the window length.
periodic: A bool `Tensor` indicating whether to generate a periodic or
symmetric window.
dtype: A floating point `DType`.
a: The alpha parameter to the raised cosine window.
b: The beta parameter to the raised cosine window.
Returns:
A `Tensor` of shape `[window_length]` of type `dtype`.
Raises:
ValueError: If `dtype` is not a floating point type or `window_length` is
not scalar or `periodic` is not scalar. | Helper function for computing a raised cosine window. | [
"Helper",
"function",
"for",
"computing",
"a",
"raised",
"cosine",
"window",
"."
] | def _raised_cosine_window(name, default_name, window_length, periodic,
dtype, a, b):
"""Helper function for computing a raised cosine window.
Args:
name: Name to use for the scope.
default_name: Default name to use for the scope.
window_length: A scalar `Tensor` or integer indicating the window length.
periodic: A bool `Tensor` indicating whether to generate a periodic or
symmetric window.
dtype: A floating point `DType`.
a: The alpha parameter to the raised cosine window.
b: The beta parameter to the raised cosine window.
Returns:
A `Tensor` of shape `[window_length]` of type `dtype`.
Raises:
ValueError: If `dtype` is not a floating point type or `window_length` is
not scalar or `periodic` is not scalar.
"""
if not dtype.is_floating:
raise ValueError('dtype must be a floating point type. Found %s' % dtype)
with ops.name_scope(name, default_name, [window_length, periodic]):
window_length = ops.convert_to_tensor(window_length, dtype=dtypes.int32,
name='window_length')
window_length.shape.assert_has_rank(0)
window_length_const = tensor_util.constant_value(window_length)
if window_length_const == 1:
return array_ops.ones([1], dtype=dtype)
periodic = math_ops.cast(
ops.convert_to_tensor(periodic, dtype=dtypes.bool, name='periodic'),
dtypes.int32)
periodic.shape.assert_has_rank(0)
even = 1 - math_ops.mod(window_length, 2)
n = math_ops.cast(window_length + periodic * even - 1, dtype=dtype)
count = math_ops.cast(math_ops.range(window_length), dtype)
cos_arg = constant_op.constant(2 * np.pi, dtype=dtype) * count / n
if window_length_const is not None:
return math_ops.cast(a - b * math_ops.cos(cos_arg), dtype=dtype)
return control_flow_ops.cond(
math_ops.equal(window_length, 1),
lambda: array_ops.ones([1], dtype=dtype),
lambda: math_ops.cast(a - b * math_ops.cos(cos_arg), dtype=dtype)) | [
"def",
"_raised_cosine_window",
"(",
"name",
",",
"default_name",
",",
"window_length",
",",
"periodic",
",",
"dtype",
",",
"a",
",",
"b",
")",
":",
"if",
"not",
"dtype",
".",
"is_floating",
":",
"raise",
"ValueError",
"(",
"'dtype must be a floating point type.... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/signal/python/ops/window_ops.py#L81-L127 | ||
v8/v8 | fee3bf095260bf657a3eea4d3d41f90c42c6c857 | tools/run-clang-tidy.py | python | ClangTidyRunFull | (build_folder, skip_output_filter, checks, auto_fix) | Run clang-tidy on the full codebase and print warnings. | Run clang-tidy on the full codebase and print warnings. | [
"Run",
"clang",
"-",
"tidy",
"on",
"the",
"full",
"codebase",
"and",
"print",
"warnings",
"."
] | def ClangTidyRunFull(build_folder, skip_output_filter, checks, auto_fix):
"""
Run clang-tidy on the full codebase and print warnings.
"""
extra_args = []
if auto_fix:
extra_args.append('-fix')
if checks is not None:
extra_args.append('-checks')
extra_args.append('-*, ' + checks)
with open(os.devnull, 'w') as DEVNULL:
ct_process = subprocess.Popen(
['run-clang-tidy', '-j' + str(THREADS), '-p', '.']
+ ['-header-filter'] + HEADER_REGEX + extra_args
+ FILE_REGEXS,
cwd=build_folder,
stdout=subprocess.PIPE,
stderr=DEVNULL)
removing_check_header = False
empty_lines = 0
while True:
line = ct_process.stdout.readline()
if line == '':
break
# Skip all lines after Enbale checks and before two newlines,
# i.e., skip clang-tidy check list.
if line.startswith('Enabled checks'):
removing_check_header = True
if removing_check_header and not skip_output_filter:
if line == '\n':
empty_lines += 1
if empty_lines == 2:
removing_check_header = False
continue
# Different lines get removed to ease output reading.
if not skip_output_filter and skip_line(line):
continue
# Print line, because no filter was matched.
if line != '\n':
sys.stdout.write(line) | [
"def",
"ClangTidyRunFull",
"(",
"build_folder",
",",
"skip_output_filter",
",",
"checks",
",",
"auto_fix",
")",
":",
"extra_args",
"=",
"[",
"]",
"if",
"auto_fix",
":",
"extra_args",
".",
"append",
"(",
"'-fix'",
")",
"if",
"checks",
"is",
"not",
"None",
"... | https://github.com/v8/v8/blob/fee3bf095260bf657a3eea4d3d41f90c42c6c857/tools/run-clang-tidy.py#L91-L136 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/lib/io/file_io.py | python | delete_recursively | (dirname) | Deletes everything under dirname recursively.
Args:
dirname: string, a path to a directory
Raises:
errors.OpError: If the operation fails. | Deletes everything under dirname recursively. | [
"Deletes",
"everything",
"under",
"dirname",
"recursively",
"."
] | def delete_recursively(dirname):
"""Deletes everything under dirname recursively.
Args:
dirname: string, a path to a directory
Raises:
errors.OpError: If the operation fails.
"""
with errors.raise_exception_on_not_ok_status() as status:
pywrap_tensorflow.DeleteRecursively(compat.as_bytes(dirname), status) | [
"def",
"delete_recursively",
"(",
"dirname",
")",
":",
"with",
"errors",
".",
"raise_exception_on_not_ok_status",
"(",
")",
"as",
"status",
":",
"pywrap_tensorflow",
".",
"DeleteRecursively",
"(",
"compat",
".",
"as_bytes",
"(",
"dirname",
")",
",",
"status",
")... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/lib/io/file_io.py#L429-L439 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/util.py | python | EventMixin.publish | (self, event, *args, **kwargs) | return result | Publish a event and return a list of values returned by its
subscribers.
:param event: The event to publish.
:param args: The positional arguments to pass to the event's
subscribers.
:param kwargs: The keyword arguments to pass to the event's
subscribers. | Publish a event and return a list of values returned by its
subscribers. | [
"Publish",
"a",
"event",
"and",
"return",
"a",
"list",
"of",
"values",
"returned",
"by",
"its",
"subscribers",
"."
] | def publish(self, event, *args, **kwargs):
"""
Publish a event and return a list of values returned by its
subscribers.
:param event: The event to publish.
:param args: The positional arguments to pass to the event's
subscribers.
:param kwargs: The keyword arguments to pass to the event's
subscribers.
"""
result = []
for subscriber in self.get_subscribers(event):
try:
value = subscriber(event, *args, **kwargs)
except Exception:
logger.exception('Exception during event publication')
value = None
result.append(value)
logger.debug('publish %s: args = %s, kwargs = %s, result = %s',
event, args, kwargs, result)
return result | [
"def",
"publish",
"(",
"self",
",",
"event",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"[",
"]",
"for",
"subscriber",
"in",
"self",
".",
"get_subscribers",
"(",
"event",
")",
":",
"try",
":",
"value",
"=",
"subscriber",
"(... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/util.py#L864-L885 | |
smilehao/xlua-framework | a03801538be2b0e92d39332d445b22caca1ef61f | ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/mox.py | python | Or.__init__ | (self, *args) | Initialize.
Args:
*args: One or more Mox comparators | Initialize. | [
"Initialize",
"."
] | def __init__(self, *args):
"""Initialize.
Args:
*args: One or more Mox comparators
"""
self._comparators = args | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"_comparators",
"=",
"args"
] | https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/mox.py#L1083-L1090 | ||
vesoft-inc/nebula | 25a06217ebaf169e1f0e5ff6a797ba6f0c41fc35 | .linters/cpp/cpplint.py | python | IsErrorSuppressedByNolint | (category, linenum) | return (_global_error_suppressions.get(category, False) or
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/ProcessGlobalSuppressions/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 or
global suppression. | 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/ProcessGlobalSuppressions/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 or
global suppression.
"""
return (_global_error_suppressions.get(category, False) or
linenum in _error_suppressions.get(category, set()) or
linenum in _error_suppressions.get(None, set())) | [
"def",
"IsErrorSuppressedByNolint",
"(",
"category",
",",
"linenum",
")",
":",
"return",
"(",
"_global_error_suppressions",
".",
"get",
"(",
"category",
",",
"False",
")",
"or",
"linenum",
"in",
"_error_suppressions",
".",
"get",
"(",
"category",
",",
"set",
"... | https://github.com/vesoft-inc/nebula/blob/25a06217ebaf169e1f0e5ff6a797ba6f0c41fc35/.linters/cpp/cpplint.py#L779-L794 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython-genutils/ipython_genutils/text.py | python | wrap_paragraphs | (text, ncols=80) | return out_ps | Wrap multiple paragraphs to fit a specified width.
This is equivalent to textwrap.wrap, but with support for multiple
paragraphs, as separated by empty lines.
Returns
-------
list of complete paragraphs, wrapped to fill `ncols` columns. | Wrap multiple paragraphs to fit a specified width. | [
"Wrap",
"multiple",
"paragraphs",
"to",
"fit",
"a",
"specified",
"width",
"."
] | def wrap_paragraphs(text, ncols=80):
"""Wrap multiple paragraphs to fit a specified width.
This is equivalent to textwrap.wrap, but with support for multiple
paragraphs, as separated by empty lines.
Returns
-------
list of complete paragraphs, wrapped to fill `ncols` columns.
"""
paragraph_re = re.compile(r'\n(\s*\n)+', re.MULTILINE)
text = dedent(text).strip()
paragraphs = paragraph_re.split(text)[::2] # every other entry is space
out_ps = []
indent_re = re.compile(r'\n\s+', re.MULTILINE)
for p in paragraphs:
# presume indentation that survives dedent is meaningful formatting,
# so don't fill unless text is flush.
if indent_re.search(p) is None:
# wrap paragraph
p = textwrap.fill(p, ncols)
out_ps.append(p)
return out_ps | [
"def",
"wrap_paragraphs",
"(",
"text",
",",
"ncols",
"=",
"80",
")",
":",
"paragraph_re",
"=",
"re",
".",
"compile",
"(",
"r'\\n(\\s*\\n)+'",
",",
"re",
".",
"MULTILINE",
")",
"text",
"=",
"dedent",
"(",
"text",
")",
".",
"strip",
"(",
")",
"paragraphs... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython-genutils/ipython_genutils/text.py#L90-L113 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/xml/sax/xmlreader.py | python | XMLReader.setProperty | (self, name, value) | Sets the value of a SAX2 property. | Sets the value of a SAX2 property. | [
"Sets",
"the",
"value",
"of",
"a",
"SAX2",
"property",
"."
] | def setProperty(self, name, value):
"Sets the value of a SAX2 property."
raise SAXNotRecognizedException("Property '%s' not recognized" % name) | [
"def",
"setProperty",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"raise",
"SAXNotRecognizedException",
"(",
"\"Property '%s' not recognized\"",
"%",
"name",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/xml/sax/xmlreader.py#L87-L89 | ||
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/polynomial/hermite_e.py | python | hermefit | (x, y, deg, rcond=None, full=False, w=None) | Least squares fit of Hermite series to data.
Fit a Hermite series ``p(x) = p[0] * P_{0}(x) + ... + p[deg] *
P_{deg}(x)`` of degree `deg` to points `(x, y)`. Returns a vector of
coefficients `p` that minimises the squared error.
Parameters
----------
x : array_like, shape (M,)
x-coordinates of the M sample points ``(x[i], y[i])``.
y : array_like, shape (M,) or (M, K)
y-coordinates of the sample points. Several data sets of sample
points sharing the same x-coordinates can be fitted at once by
passing in a 2D-array that contains one dataset per column.
deg : int
Degree of the fitting polynomial
rcond : float, optional
Relative condition number of the fit. Singular values smaller than
this relative to the largest singular value will be ignored. The
default value is len(x)*eps, where eps is the relative precision of
the float type, about 2e-16 in most cases.
full : bool, optional
Switch determining nature of return value. When it is False (the
default) just the coefficients are returned, when True diagnostic
information from the singular value decomposition is also returned.
w : array_like, shape (`M`,), optional
Weights. If not None, the contribution of each point
``(x[i],y[i])`` to the fit is weighted by `w[i]`. Ideally the
weights are chosen so that the errors of the products ``w[i]*y[i]``
all have the same variance. The default value is None.
Returns
-------
coef : ndarray, shape (M,) or (M, K)
Hermite coefficients ordered from low to high. If `y` was 2-D,
the coefficients for the data in column k of `y` are in column
`k`.
[residuals, rank, singular_values, rcond] : present when `full` = True
Residuals of the least-squares fit, the effective rank of the
scaled Vandermonde matrix and its singular values, and the
specified value of `rcond`. For more details, see `linalg.lstsq`.
Warns
-----
RankWarning
The rank of the coefficient matrix in the least-squares fit is
deficient. The warning is only raised if `full` = False. The
warnings can be turned off by
>>> import warnings
>>> warnings.simplefilter('ignore', RankWarning)
See Also
--------
hermeval : Evaluates a Hermite series.
hermevander : Vandermonde matrix of Hermite series.
polyfit : least squares fit using polynomials.
chebfit : least squares fit using Chebyshev series.
linalg.lstsq : Computes a least-squares fit from the matrix.
scipy.interpolate.UnivariateSpline : Computes spline fits.
Notes
-----
The solution are the coefficients ``c[i]`` of the Hermite series
``P(x)`` that minimizes the squared error
``E = \\sum_j |y_j - P(x_j)|^2``.
This problem is solved by setting up as the overdetermined matrix
equation
``V(x)*c = y``,
where ``V`` is the Vandermonde matrix of `x`, the elements of ``c`` are
the coefficients to be solved for, and the elements of `y` are the
observed values. This equation is then solved using the singular value
decomposition of ``V``.
If some of the singular values of ``V`` are so small that they are
neglected, then a `RankWarning` will be issued. This means that the
coeficient values may be poorly determined. Using a lower order fit
will usually get rid of the warning. The `rcond` parameter can also be
set to a value smaller than its default, but the resulting fit may be
spurious and have large contributions from roundoff error.
Fits using Hermite series are usually better conditioned than fits
using power series, but much can depend on the distribution of the
sample points and the smoothness of the data. If the quality of the fit
is inadequate splines may be a good alternative.
References
----------
.. [1] Wikipedia, "Curve fitting",
http://en.wikipedia.org/wiki/Curve_fitting
Examples
--------
>>> from numpy.polynomial.hermite_e import hermefit, hermeval
>>> x = np.linspace(-10, 10)
>>> err = np.random.randn(len(x))/10
>>> y = hermeval(x, [1, 2, 3]) + err
>>> hermefit(x, y, 2)
array([ 1.01690445, 1.99951418, 2.99948696]) | Least squares fit of Hermite series to data. | [
"Least",
"squares",
"fit",
"of",
"Hermite",
"series",
"to",
"data",
"."
] | def hermefit(x, y, deg, rcond=None, full=False, w=None):
"""
Least squares fit of Hermite series to data.
Fit a Hermite series ``p(x) = p[0] * P_{0}(x) + ... + p[deg] *
P_{deg}(x)`` of degree `deg` to points `(x, y)`. Returns a vector of
coefficients `p` that minimises the squared error.
Parameters
----------
x : array_like, shape (M,)
x-coordinates of the M sample points ``(x[i], y[i])``.
y : array_like, shape (M,) or (M, K)
y-coordinates of the sample points. Several data sets of sample
points sharing the same x-coordinates can be fitted at once by
passing in a 2D-array that contains one dataset per column.
deg : int
Degree of the fitting polynomial
rcond : float, optional
Relative condition number of the fit. Singular values smaller than
this relative to the largest singular value will be ignored. The
default value is len(x)*eps, where eps is the relative precision of
the float type, about 2e-16 in most cases.
full : bool, optional
Switch determining nature of return value. When it is False (the
default) just the coefficients are returned, when True diagnostic
information from the singular value decomposition is also returned.
w : array_like, shape (`M`,), optional
Weights. If not None, the contribution of each point
``(x[i],y[i])`` to the fit is weighted by `w[i]`. Ideally the
weights are chosen so that the errors of the products ``w[i]*y[i]``
all have the same variance. The default value is None.
Returns
-------
coef : ndarray, shape (M,) or (M, K)
Hermite coefficients ordered from low to high. If `y` was 2-D,
the coefficients for the data in column k of `y` are in column
`k`.
[residuals, rank, singular_values, rcond] : present when `full` = True
Residuals of the least-squares fit, the effective rank of the
scaled Vandermonde matrix and its singular values, and the
specified value of `rcond`. For more details, see `linalg.lstsq`.
Warns
-----
RankWarning
The rank of the coefficient matrix in the least-squares fit is
deficient. The warning is only raised if `full` = False. The
warnings can be turned off by
>>> import warnings
>>> warnings.simplefilter('ignore', RankWarning)
See Also
--------
hermeval : Evaluates a Hermite series.
hermevander : Vandermonde matrix of Hermite series.
polyfit : least squares fit using polynomials.
chebfit : least squares fit using Chebyshev series.
linalg.lstsq : Computes a least-squares fit from the matrix.
scipy.interpolate.UnivariateSpline : Computes spline fits.
Notes
-----
The solution are the coefficients ``c[i]`` of the Hermite series
``P(x)`` that minimizes the squared error
``E = \\sum_j |y_j - P(x_j)|^2``.
This problem is solved by setting up as the overdetermined matrix
equation
``V(x)*c = y``,
where ``V`` is the Vandermonde matrix of `x`, the elements of ``c`` are
the coefficients to be solved for, and the elements of `y` are the
observed values. This equation is then solved using the singular value
decomposition of ``V``.
If some of the singular values of ``V`` are so small that they are
neglected, then a `RankWarning` will be issued. This means that the
coeficient values may be poorly determined. Using a lower order fit
will usually get rid of the warning. The `rcond` parameter can also be
set to a value smaller than its default, but the resulting fit may be
spurious and have large contributions from roundoff error.
Fits using Hermite series are usually better conditioned than fits
using power series, but much can depend on the distribution of the
sample points and the smoothness of the data. If the quality of the fit
is inadequate splines may be a good alternative.
References
----------
.. [1] Wikipedia, "Curve fitting",
http://en.wikipedia.org/wiki/Curve_fitting
Examples
--------
>>> from numpy.polynomial.hermite_e import hermefit, hermeval
>>> x = np.linspace(-10, 10)
>>> err = np.random.randn(len(x))/10
>>> y = hermeval(x, [1, 2, 3]) + err
>>> hermefit(x, y, 2)
array([ 1.01690445, 1.99951418, 2.99948696])
"""
order = int(deg) + 1
x = np.asarray(x) + 0.0
y = np.asarray(y) + 0.0
# check arguments.
if deg < 0 :
raise ValueError, "expected deg >= 0"
if x.ndim != 1:
raise TypeError, "expected 1D vector for x"
if x.size == 0:
raise TypeError, "expected non-empty vector for x"
if y.ndim < 1 or y.ndim > 2 :
raise TypeError, "expected 1D or 2D array for y"
if len(x) != len(y):
raise TypeError, "expected x and y to have same length"
# set up the least squares matrices
lhs = hermevander(x, deg)
rhs = y
if w is not None:
w = np.asarray(w) + 0.0
if w.ndim != 1:
raise TypeError, "expected 1D vector for w"
if len(x) != len(w):
raise TypeError, "expected x and w to have same length"
# apply weights
if rhs.ndim == 2:
lhs *= w[:, np.newaxis]
rhs *= w[:, np.newaxis]
else:
lhs *= w[:, np.newaxis]
rhs *= w
# set rcond
if rcond is None :
rcond = len(x)*np.finfo(x.dtype).eps
# scale the design matrix and solve the least squares equation
scl = np.sqrt((lhs*lhs).sum(0))
c, resids, rank, s = la.lstsq(lhs/scl, rhs, rcond)
c = (c.T/scl).T
# warn on rank reduction
if rank != order and not full:
msg = "The fit may be poorly conditioned"
warnings.warn(msg, pu.RankWarning)
if full :
return c, [resids, rank, s, rcond]
else :
return c | [
"def",
"hermefit",
"(",
"x",
",",
"y",
",",
"deg",
",",
"rcond",
"=",
"None",
",",
"full",
"=",
"False",
",",
"w",
"=",
"None",
")",
":",
"order",
"=",
"int",
"(",
"deg",
")",
"+",
"1",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
")",
"+",
... | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/polynomial/hermite_e.py#L914-L1072 | ||
jeog/TDAmeritradeAPI | 91c738afd7d57b54f6231170bd64c2550fafd34d | python/tdma_api/get.py | python | HistoricalRangeGetter.get_start_msec_since_epoch | (self) | return clib.get_val(self._abi('GetStartMSecSinceEpoch'), c_ulonglong,
self._obj) | Returns milliseconds since epoch for start of range being used. | Returns milliseconds since epoch for start of range being used. | [
"Returns",
"milliseconds",
"since",
"epoch",
"for",
"start",
"of",
"range",
"being",
"used",
"."
] | def get_start_msec_since_epoch(self):
"""Returns milliseconds since epoch for start of range being used."""
return clib.get_val(self._abi('GetStartMSecSinceEpoch'), c_ulonglong,
self._obj) | [
"def",
"get_start_msec_since_epoch",
"(",
"self",
")",
":",
"return",
"clib",
".",
"get_val",
"(",
"self",
".",
"_abi",
"(",
"'GetStartMSecSinceEpoch'",
")",
",",
"c_ulonglong",
",",
"self",
".",
"_obj",
")"
] | https://github.com/jeog/TDAmeritradeAPI/blob/91c738afd7d57b54f6231170bd64c2550fafd34d/python/tdma_api/get.py#L613-L616 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/boosted_trees/python/training/functions/gbdt_batch.py | python | _get_column_by_index | (tensor, indices) | return array_ops.reshape(array_ops.gather(p_flat, i_flat), [shape[0], -1]) | Returns columns from a 2-D tensor by index. | Returns columns from a 2-D tensor by index. | [
"Returns",
"columns",
"from",
"a",
"2",
"-",
"D",
"tensor",
"by",
"index",
"."
] | def _get_column_by_index(tensor, indices):
"""Returns columns from a 2-D tensor by index."""
shape = array_ops.shape(tensor)
p_flat = array_ops.reshape(tensor, [-1])
i_flat = array_ops.reshape(
array_ops.reshape(math_ops.range(0, shape[0]) * shape[1], [-1, 1]) +
indices, [-1])
return array_ops.reshape(array_ops.gather(p_flat, i_flat), [shape[0], -1]) | [
"def",
"_get_column_by_index",
"(",
"tensor",
",",
"indices",
")",
":",
"shape",
"=",
"array_ops",
".",
"shape",
"(",
"tensor",
")",
"p_flat",
"=",
"array_ops",
".",
"reshape",
"(",
"tensor",
",",
"[",
"-",
"1",
"]",
")",
"i_flat",
"=",
"array_ops",
".... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/boosted_trees/python/training/functions/gbdt_batch.py#L62-L69 | |
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | bindings/python/cntk/axis.py | python | Axis.new_unique_dynamic_axis | (name) | return cntk_py.Axis.new_unique_dynamic_axis(name) | Creates an Axis object representing a new unique dynamic axis.
Args:
name (str): name of the dynmic axis
Returns:
:class:`Axis`: new unique dynamic axis | Creates an Axis object representing a new unique dynamic axis. | [
"Creates",
"an",
"Axis",
"object",
"representing",
"a",
"new",
"unique",
"dynamic",
"axis",
"."
] | def new_unique_dynamic_axis(name):
'''
Creates an Axis object representing a new unique dynamic axis.
Args:
name (str): name of the dynmic axis
Returns:
:class:`Axis`: new unique dynamic axis
'''
return cntk_py.Axis.new_unique_dynamic_axis(name) | [
"def",
"new_unique_dynamic_axis",
"(",
"name",
")",
":",
"return",
"cntk_py",
".",
"Axis",
".",
"new_unique_dynamic_axis",
"(",
"name",
")"
] | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/axis.py#L160-L170 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/distutils/npy_pkg_config.py | python | VariableSet.variables | (self) | return list(self._raw_data.keys()) | Return the list of variable names.
Parameters
----------
None
Returns
-------
names : list of str
The names of all variables in the `VariableSet` instance. | Return the list of variable names. | [
"Return",
"the",
"list",
"of",
"variable",
"names",
"."
] | def variables(self):
"""
Return the list of variable names.
Parameters
----------
None
Returns
-------
names : list of str
The names of all variables in the `VariableSet` instance.
"""
return list(self._raw_data.keys()) | [
"def",
"variables",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
".",
"_raw_data",
".",
"keys",
"(",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/distutils/npy_pkg_config.py#L197-L211 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/control_flow_ops.py | python | CondContext.__init__ | (self,
pred=None,
pivot=None,
branch=None,
name="cond_text",
context_def=None,
import_scope=None) | Creates a `CondContext`.
Args:
pred: The `boolean` tensor for the conditional predicate.
pivot: The predicate tensor in this branch.
branch: 0 or 1 representing this branch.
name: Name of the `CondContext` python object.
context_def: Optional `ContextDef` protocol buffer to initialize the
`CondContext` object from.
import_scope: Optional `string`. Name scope to add. Only used when
initialing from protocol buffer. | Creates a `CondContext`. | [
"Creates",
"a",
"CondContext",
"."
] | def __init__(self,
pred=None,
pivot=None,
branch=None,
name="cond_text",
context_def=None,
import_scope=None):
"""Creates a `CondContext`.
Args:
pred: The `boolean` tensor for the conditional predicate.
pivot: The predicate tensor in this branch.
branch: 0 or 1 representing this branch.
name: Name of the `CondContext` python object.
context_def: Optional `ContextDef` protocol buffer to initialize the
`CondContext` object from.
import_scope: Optional `string`. Name scope to add. Only used when
initialing from protocol buffer.
"""
self._name = ops.get_default_graph().unique_name(name)
if context_def:
self._init_from_proto(context_def, import_scope=import_scope)
else:
# Initializes the default fields.
ControlFlowContext.__init__(self)
self._pred = pred # The boolean tensor for the cond predicate
self._pivot = pivot # The predicate tensor in this branch
self._branch = branch # 0 or 1 representing this branch
# Values considered to have been already seen in this context. pred is not
# included in this context.
self._values.add(pred.name)
self._external_values[pred.name] = pred
self._values.add(pivot.name)
pivot.op._set_control_flow_context(self) | [
"def",
"__init__",
"(",
"self",
",",
"pred",
"=",
"None",
",",
"pivot",
"=",
"None",
",",
"branch",
"=",
"None",
",",
"name",
"=",
"\"cond_text\"",
",",
"context_def",
"=",
"None",
",",
"import_scope",
"=",
"None",
")",
":",
"self",
".",
"_name",
"="... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/control_flow_ops.py#L811-L846 | ||
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | src/pybind/mgr/nfs/module.py | python | Module._cmd_nfs_cluster_config_set | (self, cluster_id: str, inbuf: str) | return self.nfs.set_nfs_cluster_config(cluster_id=cluster_id, nfs_config=inbuf) | Set NFS-Ganesha config by `-i <config_file>` | Set NFS-Ganesha config by `-i <config_file>` | [
"Set",
"NFS",
"-",
"Ganesha",
"config",
"by",
"-",
"i",
"<config_file",
">"
] | def _cmd_nfs_cluster_config_set(self, cluster_id: str, inbuf: str) -> Tuple[int, str, str]:
"""Set NFS-Ganesha config by `-i <config_file>`"""
return self.nfs.set_nfs_cluster_config(cluster_id=cluster_id, nfs_config=inbuf) | [
"def",
"_cmd_nfs_cluster_config_set",
"(",
"self",
",",
"cluster_id",
":",
"str",
",",
"inbuf",
":",
"str",
")",
"->",
"Tuple",
"[",
"int",
",",
"str",
",",
"str",
"]",
":",
"return",
"self",
".",
"nfs",
".",
"set_nfs_cluster_config",
"(",
"cluster_id",
... | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/nfs/module.py#L132-L134 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/coremodules/network/network_editor.py | python | AddCrossingTool.get_optionspanel | (self, parent, size=wx.DefaultSize) | return self._optionspanel | Return tool option widgets on given parent | Return tool option widgets on given parent | [
"Return",
"tool",
"option",
"widgets",
"on",
"given",
"parent"
] | def get_optionspanel(self, parent, size=wx.DefaultSize):
"""
Return tool option widgets on given parent
"""
size = (200, -1)
buttons = [('Add', self.on_add_crossing, 'Add crossing to network.'),
('Clear', self.on_clear, 'Clear selection.'),
#('Save flows', self.on_add, 'Save OD flows to current demand.'),
#('Cancel', self.on_close, 'Close wizzard without adding flows.'),
]
defaultbuttontext = 'Add'
self._optionspanel = ObjPanel(parent, obj=self,
attrconfigs=None,
groupnames=['options'],
func_change_obj=None,
show_groupnames=False, show_title=True, is_modal=False,
mainframe=self.parent.get_mainframe(),
pos=wx.DefaultPosition, size=size, style=wx.MAXIMIZE_BOX | wx.RESIZE_BORDER,
immediate_apply=True, panelstyle='default', # 'instrumental'
buttons=buttons, defaultbutton=defaultbuttontext,
standartbuttons=[], # standartbuttons=['restore']
)
return self._optionspanel | [
"def",
"get_optionspanel",
"(",
"self",
",",
"parent",
",",
"size",
"=",
"wx",
".",
"DefaultSize",
")",
":",
"size",
"=",
"(",
"200",
",",
"-",
"1",
")",
"buttons",
"=",
"[",
"(",
"'Add'",
",",
"self",
".",
"on_add_crossing",
",",
"'Add crossing to net... | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/network/network_editor.py#L452-L475 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py | python | Decimal.from_float | (cls, f) | Converts a float to a decimal number, exactly.
Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
Since 0.1 is not exactly representable in binary floating point, the
value is stored as the nearest representable value which is
0x1.999999999999ap-4. The exact equivalent of the value in decimal
is 0.1000000000000000055511151231257827021181583404541015625.
>>> Decimal.from_float(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> Decimal.from_float(float('nan'))
Decimal('NaN')
>>> Decimal.from_float(float('inf'))
Decimal('Infinity')
>>> Decimal.from_float(-float('inf'))
Decimal('-Infinity')
>>> Decimal.from_float(-0.0)
Decimal('-0') | Converts a float to a decimal number, exactly. | [
"Converts",
"a",
"float",
"to",
"a",
"decimal",
"number",
"exactly",
"."
] | def from_float(cls, f):
"""Converts a float to a decimal number, exactly.
Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
Since 0.1 is not exactly representable in binary floating point, the
value is stored as the nearest representable value which is
0x1.999999999999ap-4. The exact equivalent of the value in decimal
is 0.1000000000000000055511151231257827021181583404541015625.
>>> Decimal.from_float(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> Decimal.from_float(float('nan'))
Decimal('NaN')
>>> Decimal.from_float(float('inf'))
Decimal('Infinity')
>>> Decimal.from_float(-float('inf'))
Decimal('-Infinity')
>>> Decimal.from_float(-0.0)
Decimal('-0')
"""
if isinstance(f, int): # handle integer inputs
sign = 0 if f >= 0 else 1
k = 0
coeff = str(abs(f))
elif isinstance(f, float):
if _math.isinf(f) or _math.isnan(f):
return cls(repr(f))
if _math.copysign(1.0, f) == 1.0:
sign = 0
else:
sign = 1
n, d = abs(f).as_integer_ratio()
k = d.bit_length() - 1
coeff = str(n*5**k)
else:
raise TypeError("argument must be int or float.")
result = _dec_from_triple(sign, coeff, -k)
if cls is Decimal:
return result
else:
return cls(result) | [
"def",
"from_float",
"(",
"cls",
",",
"f",
")",
":",
"if",
"isinstance",
"(",
"f",
",",
"int",
")",
":",
"# handle integer inputs",
"sign",
"=",
"0",
"if",
"f",
">=",
"0",
"else",
"1",
"k",
"=",
"0",
"coeff",
"=",
"str",
"(",
"abs",
"(",
"f",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py#L673-L715 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | DateSpan.__imul__ | (*args, **kwargs) | return _misc_.DateSpan___imul__(*args, **kwargs) | __imul__(self, int factor) -> DateSpan | __imul__(self, int factor) -> DateSpan | [
"__imul__",
"(",
"self",
"int",
"factor",
")",
"-",
">",
"DateSpan"
] | def __imul__(*args, **kwargs):
"""__imul__(self, int factor) -> DateSpan"""
return _misc_.DateSpan___imul__(*args, **kwargs) | [
"def",
"__imul__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateSpan___imul__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L4717-L4719 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/stc.py | python | StyledTextCtrl.CharPositionFromPointClose | (*args, **kwargs) | return _stc.StyledTextCtrl_CharPositionFromPointClose(*args, **kwargs) | CharPositionFromPointClose(self, int x, int y) -> int
Find the position of a character from a point within the window.
Return INVALID_POSITION if not close to text. | CharPositionFromPointClose(self, int x, int y) -> int | [
"CharPositionFromPointClose",
"(",
"self",
"int",
"x",
"int",
"y",
")",
"-",
">",
"int"
] | def CharPositionFromPointClose(*args, **kwargs):
"""
CharPositionFromPointClose(self, int x, int y) -> int
Find the position of a character from a point within the window.
Return INVALID_POSITION if not close to text.
"""
return _stc.StyledTextCtrl_CharPositionFromPointClose(*args, **kwargs) | [
"def",
"CharPositionFromPointClose",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_CharPositionFromPointClose",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L6031-L6038 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/symbol/numpy/_symbol.py | python | indices | (dimensions, dtype=None, ctx=None) | Return an array representing the indices of a grid.
Compute an array where the subarrays contain index values 0,1,...
varying only along the corresponding axis.
Parameters
----------
dimensions : sequence of ints
The shape of the grid.
dtype : data-type, optional
The desired data-type for the array. Default is `int64`.
ctx : device context, optional
Device context on which the memory is allocated. Default is
`mxnet.context.current_context()`.
Returns
-------
grid : _Symbol
The array of grid indices,
``grid.shape = (len(dimensions),) + tuple(dimensions)``.
Notes
-----
The output shape is obtained by prepending the number of dimensions
in front of the tuple of dimensions, i.e. if `dimensions` is a tuple
``(r0, ..., rN-1)`` of length ``N``, the output shape is
``(N,r0,...,rN-1)``.
The subarrays ``grid[k]`` contains the N-D array of indices along the
``k-th`` axis. Explicitly::
grid[k,i0,i1,...,iN-1] = ik
Examples
--------
>>> grid = np.indices((2, 3))
>>> grid.shape
(2, 2, 3)
>>> grid[0] # row indices
array([[0, 0, 0],
[1, 1, 1]], dtype=int64)
>>> grid[1] # column indices
array([[0, 0, 0],
[1, 1, 1]], dtype=int64)
The indices can be used as an index into an array.
>>> x = np.arange(20).reshape(5, 4)
>>> row, col = np.indices((2, 3))
>>> x[row, col]
array([[0., 1., 2.],
[4., 5., 6.]])
Note that it would be more straightforward in the above example to
extract the required elements directly with ``x[:2, :3]``. | Return an array representing the indices of a grid. | [
"Return",
"an",
"array",
"representing",
"the",
"indices",
"of",
"a",
"grid",
"."
] | def indices(dimensions, dtype=None, ctx=None):
"""Return an array representing the indices of a grid.
Compute an array where the subarrays contain index values 0,1,...
varying only along the corresponding axis.
Parameters
----------
dimensions : sequence of ints
The shape of the grid.
dtype : data-type, optional
The desired data-type for the array. Default is `int64`.
ctx : device context, optional
Device context on which the memory is allocated. Default is
`mxnet.context.current_context()`.
Returns
-------
grid : _Symbol
The array of grid indices,
``grid.shape = (len(dimensions),) + tuple(dimensions)``.
Notes
-----
The output shape is obtained by prepending the number of dimensions
in front of the tuple of dimensions, i.e. if `dimensions` is a tuple
``(r0, ..., rN-1)`` of length ``N``, the output shape is
``(N,r0,...,rN-1)``.
The subarrays ``grid[k]`` contains the N-D array of indices along the
``k-th`` axis. Explicitly::
grid[k,i0,i1,...,iN-1] = ik
Examples
--------
>>> grid = np.indices((2, 3))
>>> grid.shape
(2, 2, 3)
>>> grid[0] # row indices
array([[0, 0, 0],
[1, 1, 1]], dtype=int64)
>>> grid[1] # column indices
array([[0, 0, 0],
[1, 1, 1]], dtype=int64)
The indices can be used as an index into an array.
>>> x = np.arange(20).reshape(5, 4)
>>> row, col = np.indices((2, 3))
>>> x[row, col]
array([[0., 1., 2.],
[4., 5., 6.]])
Note that it would be more straightforward in the above example to
extract the required elements directly with ``x[:2, :3]``.
"""
if isinstance(dimensions, (tuple, list)):
if ctx is None:
ctx = current_context()
return _npi.indices(dimensions=dimensions, dtype=dtype, ctx=ctx)
else:
raise ValueError("The dimensions must be sequence of ints") | [
"def",
"indices",
"(",
"dimensions",
",",
"dtype",
"=",
"None",
",",
"ctx",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"dimensions",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"if",
"ctx",
"is",
"None",
":",
"ctx",
"=",
"current_context",
... | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/symbol/numpy/_symbol.py#L5194-L5256 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqt/mantidqt/widgets/sliceviewer/presenter.py | python | SliceViewer.set_axes_limits | (self, xlim, ylim, auto_transform=True) | Set the axes limits on the view.
:param xlim: Limits on the X axis in image coordinates
:param ylim: Limits on the Y axis in image coordinates
:param auto_transform: If True transform the given limits to the rectilinear
coordinate before passing to the view | Set the axes limits on the view.
:param xlim: Limits on the X axis in image coordinates
:param ylim: Limits on the Y axis in image coordinates
:param auto_transform: If True transform the given limits to the rectilinear
coordinate before passing to the view | [
"Set",
"the",
"axes",
"limits",
"on",
"the",
"view",
".",
":",
"param",
"xlim",
":",
"Limits",
"on",
"the",
"X",
"axis",
"in",
"image",
"coordinates",
":",
"param",
"ylim",
":",
"Limits",
"on",
"the",
"Y",
"axis",
"in",
"image",
"coordinates",
":",
"... | def set_axes_limits(self, xlim, ylim, auto_transform=True):
"""Set the axes limits on the view.
:param xlim: Limits on the X axis in image coordinates
:param ylim: Limits on the Y axis in image coordinates
:param auto_transform: If True transform the given limits to the rectilinear
coordinate before passing to the view
"""
data_view = self.view.data_view
if auto_transform and data_view.nonorthogonal_mode:
to_display = data_view.nonortho_transform.tr
xmin_p, ymin_p = to_display(xlim[0], ylim[0])
xmax_p, ymax_p = to_display(xlim[1], ylim[1])
xlim, ylim = (xmin_p, xmax_p), (ymin_p, ymax_p)
data_view.set_axes_limits(xlim, ylim)
self.data_limits_changed() | [
"def",
"set_axes_limits",
"(",
"self",
",",
"xlim",
",",
"ylim",
",",
"auto_transform",
"=",
"True",
")",
":",
"data_view",
"=",
"self",
".",
"view",
".",
"data_view",
"if",
"auto_transform",
"and",
"data_view",
".",
"nonorthogonal_mode",
":",
"to_display",
... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/sliceviewer/presenter.py#L241-L256 | ||
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | pygimli/physics/sNMR/mrs.py | python | MRS.loadDataCube | (self, filename='datacube.dat') | Load data cube from single ascii file (old stuff) | Load data cube from single ascii file (old stuff) | [
"Load",
"data",
"cube",
"from",
"single",
"ascii",
"file",
"(",
"old",
"stuff",
")"
] | def loadDataCube(self, filename='datacube.dat'):
"""Load data cube from single ascii file (old stuff)"""
A = np.loadtxt(filename).T
self.q = A[1:, 0]
self.t = A[0, 1:]
self.data = A[1:, 1:].ravel() | [
"def",
"loadDataCube",
"(",
"self",
",",
"filename",
"=",
"'datacube.dat'",
")",
":",
"A",
"=",
"np",
".",
"loadtxt",
"(",
"filename",
")",
".",
"T",
"self",
".",
"q",
"=",
"A",
"[",
"1",
":",
",",
"0",
"]",
"self",
".",
"t",
"=",
"A",
"[",
"... | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/sNMR/mrs.py#L257-L262 | ||
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/pyedbglib/protocols/cmsisdap.py | python | CmsisDapDebugger.write_block | (self, address, data) | Writes a block to the device memory bus
:param address: byte address
:param data: data | Writes a block to the device memory bus | [
"Writes",
"a",
"block",
"to",
"the",
"device",
"memory",
"bus"
] | def write_block(self, address, data):
"""
Writes a block to the device memory bus
:param address: byte address
:param data: data
"""
self.logger.debug("Block write of %d bytes at address 0x%08X", len(data), address)
# In chunks of (len-header)
max_payload_size_bytes = self.multiple_of_four(self.transport.get_report_size() - 5)
while data:
# Calculate write size
write_size_bytes = max_payload_size_bytes
if write_size_bytes > len(data):
write_size_bytes = len(data)
# Too large for TAR?
tar_max_chunk = self.TAR_MAX - (address - (address & (1 - self.TAR_MAX)))
if write_size_bytes > tar_max_chunk:
write_size_bytes = tar_max_chunk
# Set TAR
self.dap_write_reg(self.SWD_AP_TAR | self.DAP_TRANSFER_APnDP, address)
cmd = bytearray(2)
cmd[0] = self.ID_DAP_TransferBlock
cmd[1] = 0x00
cmd.extend(binary.pack_le16(write_size_bytes // 4))
cmd.extend([self.SWD_AP_DRW | self.DAP_TRANSFER_APnDP])
cmd.extend(data[0:write_size_bytes])
rsp = self.dap_command_response(cmd)
self._check_response(cmd, rsp)
# Shrink data buffer
data = data[write_size_bytes:]
address += write_size_bytes | [
"def",
"write_block",
"(",
"self",
",",
"address",
",",
"data",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Block write of %d bytes at address 0x%08X\"",
",",
"len",
"(",
"data",
")",
",",
"address",
")",
"# In chunks of (len-header)",
"max_payload_size... | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pyedbglib/protocols/cmsisdap.py#L404-L440 | ||
apache/impala | 8ddac48f3428c86f2cbd037ced89cfb903298b12 | bin/run-workload.py | python | split_and_strip | (input_string, delim=",") | return map(str.strip, input_string.split(delim)) | Convert a string into a list using the given delimiter | Convert a string into a list using the given delimiter | [
"Convert",
"a",
"string",
"into",
"a",
"list",
"using",
"the",
"given",
"delimiter"
] | def split_and_strip(input_string, delim=","):
"""Convert a string into a list using the given delimiter"""
if not input_string: return list()
return map(str.strip, input_string.split(delim)) | [
"def",
"split_and_strip",
"(",
"input_string",
",",
"delim",
"=",
"\",\"",
")",
":",
"if",
"not",
"input_string",
":",
"return",
"list",
"(",
")",
"return",
"map",
"(",
"str",
".",
"strip",
",",
"input_string",
".",
"split",
"(",
"delim",
")",
")"
] | https://github.com/apache/impala/blob/8ddac48f3428c86f2cbd037ced89cfb903298b12/bin/run-workload.py#L194-L197 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/slim/python/slim/summaries.py | python | add_zero_fraction_summaries | (tensors, prefix=None) | return summary_ops | Adds a scalar zero-fraction summary for each of the given tensors.
Args:
tensors: a list of variable or op tensors.
prefix: An optional prefix for the summary names.
Returns:
A list of scalar `Tensors` of type `string` whose contents are the
serialized `Summary` protocol buffer. | Adds a scalar zero-fraction summary for each of the given tensors. | [
"Adds",
"a",
"scalar",
"zero",
"-",
"fraction",
"summary",
"for",
"each",
"of",
"the",
"given",
"tensors",
"."
] | def add_zero_fraction_summaries(tensors, prefix=None):
"""Adds a scalar zero-fraction summary for each of the given tensors.
Args:
tensors: a list of variable or op tensors.
prefix: An optional prefix for the summary names.
Returns:
A list of scalar `Tensors` of type `string` whose contents are the
serialized `Summary` protocol buffer.
"""
summary_ops = []
for tensor in tensors:
summary_ops.append(add_zero_fraction_summary(tensor, prefix=prefix))
return summary_ops | [
"def",
"add_zero_fraction_summaries",
"(",
"tensors",
",",
"prefix",
"=",
"None",
")",
":",
"summary_ops",
"=",
"[",
"]",
"for",
"tensor",
"in",
"tensors",
":",
"summary_ops",
".",
"append",
"(",
"add_zero_fraction_summary",
"(",
"tensor",
",",
"prefix",
"=",
... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/slim/python/slim/summaries.py#L206-L220 | |
fifengine/fifengine | 4b62c42e85bec19893cef8e63e6855927cff2c47 | engine/python/fife/extensions/pychan/widgets/widget.py | python | Widget.isModalFocusable | (self) | return self.real_widget.isModalFocusable() | Checks if a widget is modal focusable.
True if no other widget has modal focus, false otherwise. | Checks if a widget is modal focusable.
True if no other widget has modal focus, false otherwise. | [
"Checks",
"if",
"a",
"widget",
"is",
"modal",
"focusable",
".",
"True",
"if",
"no",
"other",
"widget",
"has",
"modal",
"focus",
"false",
"otherwise",
"."
] | def isModalFocusable(self):
"""
Checks if a widget is modal focusable.
True if no other widget has modal focus, false otherwise.
"""
return self.real_widget.isModalFocusable() | [
"def",
"isModalFocusable",
"(",
"self",
")",
":",
"return",
"self",
".",
"real_widget",
".",
"isModalFocusable",
"(",
")"
] | https://github.com/fifengine/fifengine/blob/4b62c42e85bec19893cef8e63e6855927cff2c47/engine/python/fife/extensions/pychan/widgets/widget.py#L325-L330 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/polynomial/polynomial.py | python | polyint | (c, m=1, k=[], lbnd=0, scl=1, axis=0) | return c | Integrate a polynomial.
Returns the polynomial coefficients `c` integrated `m` times from
`lbnd` along `axis`. At each iteration the resulting series is
**multiplied** by `scl` and an integration constant, `k`, is added.
The scaling factor is for use in a linear change of variable. ("Buyer
beware": note that, depending on what one is doing, one may want `scl`
to be the reciprocal of what one might expect; for more information,
see the Notes section below.) The argument `c` is an array of
coefficients, from low to high degree along each axis, e.g., [1,2,3]
represents the polynomial ``1 + 2*x + 3*x**2`` while [[1,2],[1,2]]
represents ``1 + 1*x + 2*y + 2*x*y`` if axis=0 is ``x`` and axis=1 is
``y``.
Parameters
----------
c : array_like
1-D array of polynomial coefficients, ordered from low to high.
m : int, optional
Order of integration, must be positive. (Default: 1)
k : {[], list, scalar}, optional
Integration constant(s). The value of the first integral at zero
is the first value in the list, the value of the second integral
at zero is the second value, etc. If ``k == []`` (the default),
all constants are set to zero. If ``m == 1``, a single scalar can
be given instead of a list.
lbnd : scalar, optional
The lower bound of the integral. (Default: 0)
scl : scalar, optional
Following each integration the result is *multiplied* by `scl`
before the integration constant is added. (Default: 1)
axis : int, optional
Axis over which the integral is taken. (Default: 0).
.. versionadded:: 1.7.0
Returns
-------
S : ndarray
Coefficient array of the integral.
Raises
------
ValueError
If ``m < 1``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or
``np.ndim(scl) != 0``.
See Also
--------
polyder
Notes
-----
Note that the result of each integration is *multiplied* by `scl`. Why
is this important to note? Say one is making a linear change of
variable :math:`u = ax + b` in an integral relative to `x`. Then
:math:`dx = du/a`, so one will need to set `scl` equal to
:math:`1/a` - perhaps not what one would have first thought.
Examples
--------
>>> from numpy.polynomial import polynomial as P
>>> c = (1,2,3)
>>> P.polyint(c) # should return array([0, 1, 1, 1])
array([0., 1., 1., 1.])
>>> P.polyint(c,3) # should return array([0, 0, 0, 1/6, 1/12, 1/20])
array([ 0. , 0. , 0. , 0.16666667, 0.08333333, # may vary
0.05 ])
>>> P.polyint(c,k=3) # should return array([3, 1, 1, 1])
array([3., 1., 1., 1.])
>>> P.polyint(c,lbnd=-2) # should return array([6, 1, 1, 1])
array([6., 1., 1., 1.])
>>> P.polyint(c,scl=-2) # should return array([0, -2, -2, -2])
array([ 0., -2., -2., -2.]) | Integrate a polynomial. | [
"Integrate",
"a",
"polynomial",
"."
] | def polyint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
"""
Integrate a polynomial.
Returns the polynomial coefficients `c` integrated `m` times from
`lbnd` along `axis`. At each iteration the resulting series is
**multiplied** by `scl` and an integration constant, `k`, is added.
The scaling factor is for use in a linear change of variable. ("Buyer
beware": note that, depending on what one is doing, one may want `scl`
to be the reciprocal of what one might expect; for more information,
see the Notes section below.) The argument `c` is an array of
coefficients, from low to high degree along each axis, e.g., [1,2,3]
represents the polynomial ``1 + 2*x + 3*x**2`` while [[1,2],[1,2]]
represents ``1 + 1*x + 2*y + 2*x*y`` if axis=0 is ``x`` and axis=1 is
``y``.
Parameters
----------
c : array_like
1-D array of polynomial coefficients, ordered from low to high.
m : int, optional
Order of integration, must be positive. (Default: 1)
k : {[], list, scalar}, optional
Integration constant(s). The value of the first integral at zero
is the first value in the list, the value of the second integral
at zero is the second value, etc. If ``k == []`` (the default),
all constants are set to zero. If ``m == 1``, a single scalar can
be given instead of a list.
lbnd : scalar, optional
The lower bound of the integral. (Default: 0)
scl : scalar, optional
Following each integration the result is *multiplied* by `scl`
before the integration constant is added. (Default: 1)
axis : int, optional
Axis over which the integral is taken. (Default: 0).
.. versionadded:: 1.7.0
Returns
-------
S : ndarray
Coefficient array of the integral.
Raises
------
ValueError
If ``m < 1``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or
``np.ndim(scl) != 0``.
See Also
--------
polyder
Notes
-----
Note that the result of each integration is *multiplied* by `scl`. Why
is this important to note? Say one is making a linear change of
variable :math:`u = ax + b` in an integral relative to `x`. Then
:math:`dx = du/a`, so one will need to set `scl` equal to
:math:`1/a` - perhaps not what one would have first thought.
Examples
--------
>>> from numpy.polynomial import polynomial as P
>>> c = (1,2,3)
>>> P.polyint(c) # should return array([0, 1, 1, 1])
array([0., 1., 1., 1.])
>>> P.polyint(c,3) # should return array([0, 0, 0, 1/6, 1/12, 1/20])
array([ 0. , 0. , 0. , 0.16666667, 0.08333333, # may vary
0.05 ])
>>> P.polyint(c,k=3) # should return array([3, 1, 1, 1])
array([3., 1., 1., 1.])
>>> P.polyint(c,lbnd=-2) # should return array([6, 1, 1, 1])
array([6., 1., 1., 1.])
>>> P.polyint(c,scl=-2) # should return array([0, -2, -2, -2])
array([ 0., -2., -2., -2.])
"""
c = np.array(c, ndmin=1, copy=True)
if c.dtype.char in '?bBhHiIlLqQpP':
# astype doesn't preserve mask attribute.
c = c + 0.0
cdt = c.dtype
if not np.iterable(k):
k = [k]
cnt = pu._deprecate_as_int(m, "the order of integration")
iaxis = pu._deprecate_as_int(axis, "the axis")
if cnt < 0:
raise ValueError("The order of integration must be non-negative")
if len(k) > cnt:
raise ValueError("Too many integration constants")
if np.ndim(lbnd) != 0:
raise ValueError("lbnd must be a scalar.")
if np.ndim(scl) != 0:
raise ValueError("scl must be a scalar.")
iaxis = normalize_axis_index(iaxis, c.ndim)
if cnt == 0:
return c
k = list(k) + [0]*(cnt - len(k))
c = np.moveaxis(c, iaxis, 0)
for i in range(cnt):
n = len(c)
c *= scl
if n == 1 and np.all(c[0] == 0):
c[0] += k[i]
else:
tmp = np.empty((n + 1,) + c.shape[1:], dtype=cdt)
tmp[0] = c[0]*0
tmp[1] = c[0]
for j in range(1, n):
tmp[j + 1] = c[j]/(j + 1)
tmp[0] += k[i] - polyval(lbnd, tmp)
c = tmp
c = np.moveaxis(c, 0, iaxis)
return c | [
"def",
"polyint",
"(",
"c",
",",
"m",
"=",
"1",
",",
"k",
"=",
"[",
"]",
",",
"lbnd",
"=",
"0",
",",
"scl",
"=",
"1",
",",
"axis",
"=",
"0",
")",
":",
"c",
"=",
"np",
".",
"array",
"(",
"c",
",",
"ndmin",
"=",
"1",
",",
"copy",
"=",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/polynomial/polynomial.py#L545-L661 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/metrics/actions/extract_actions.py | python | AddClosedSourceActions | (actions) | Add actions that are in code which is not checked out by default
Arguments
actions: set of actions to add to. | Add actions that are in code which is not checked out by default | [
"Add",
"actions",
"that",
"are",
"in",
"code",
"which",
"is",
"not",
"checked",
"out",
"by",
"default"
] | def AddClosedSourceActions(actions):
"""Add actions that are in code which is not checked out by default
Arguments
actions: set of actions to add to.
"""
actions.add('PDF.FitToHeightButton')
actions.add('PDF.FitToWidthButton')
actions.add('PDF.LoadFailure')
actions.add('PDF.LoadSuccess')
actions.add('PDF.PreviewDocumentLoadFailure')
actions.add('PDF.PrintButton')
actions.add('PDF.PrintPage')
actions.add('PDF.SaveButton')
actions.add('PDF.ZoomFromBrowser')
actions.add('PDF.ZoomInButton')
actions.add('PDF.ZoomOutButton')
actions.add('PDF_Unsupported_3D')
actions.add('PDF_Unsupported_Attachment')
actions.add('PDF_Unsupported_Bookmarks')
actions.add('PDF_Unsupported_Digital_Signature')
actions.add('PDF_Unsupported_Movie')
actions.add('PDF_Unsupported_Portfolios_Packages')
actions.add('PDF_Unsupported_Rights_Management')
actions.add('PDF_Unsupported_Screen')
actions.add('PDF_Unsupported_Shared_Form')
actions.add('PDF_Unsupported_Shared_Review')
actions.add('PDF_Unsupported_Sound')
actions.add('PDF_Unsupported_XFA') | [
"def",
"AddClosedSourceActions",
"(",
"actions",
")",
":",
"actions",
".",
"add",
"(",
"'PDF.FitToHeightButton'",
")",
"actions",
".",
"add",
"(",
"'PDF.FitToWidthButton'",
")",
"actions",
".",
"add",
"(",
"'PDF.LoadFailure'",
")",
"actions",
".",
"add",
"(",
... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/metrics/actions/extract_actions.py#L167-L195 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/command/egg_info.py | python | FileList.recursive_include | (self, dir, pattern) | return bool(found) | Include all files anywhere in 'dir/' that match the pattern. | Include all files anywhere in 'dir/' that match the pattern. | [
"Include",
"all",
"files",
"anywhere",
"in",
"dir",
"/",
"that",
"match",
"the",
"pattern",
"."
] | def recursive_include(self, dir, pattern):
"""
Include all files anywhere in 'dir/' that match the pattern.
"""
full_pattern = os.path.join(dir, '**', pattern)
found = [f for f in glob(full_pattern, recursive=True)
if not os.path.isdir(f)]
self.extend(found)
return bool(found) | [
"def",
"recursive_include",
"(",
"self",
",",
"dir",
",",
"pattern",
")",
":",
"full_pattern",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"'**'",
",",
"pattern",
")",
"found",
"=",
"[",
"f",
"for",
"f",
"in",
"glob",
"(",
"full_pattern",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/command/egg_info.py#L423-L431 | |
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/convert/processor/conversion/de2/nyan_subprocessor.py | python | DE2NyanSubprocessor.tech_group_to_tech | (tech_group) | Creates raw API objects for a tech group.
:param tech_group: Tech group that gets converted to a tech.
:type tech_group: ..dataformat.converter_object.ConverterObjectGroup | Creates raw API objects for a tech group. | [
"Creates",
"raw",
"API",
"objects",
"for",
"a",
"tech",
"group",
"."
] | def tech_group_to_tech(tech_group):
"""
Creates raw API objects for a tech group.
:param tech_group: Tech group that gets converted to a tech.
:type tech_group: ..dataformat.converter_object.ConverterObjectGroup
"""
tech_id = tech_group.get_id()
# Skip Dark Age tech
if tech_id == 104:
return
dataset = tech_group.data
name_lookup_dict = internal_name_lookups.get_entity_lookups(dataset.game_version)
tech_lookup_dict = internal_name_lookups.get_tech_lookups(dataset.game_version)
# Start with the Tech object
tech_name = tech_lookup_dict[tech_id][0]
raw_api_object = RawAPIObject(tech_name, tech_name,
dataset.nyan_api_objects)
raw_api_object.add_raw_parent("engine.util.tech.Tech")
if isinstance(tech_group, UnitLineUpgrade):
unit_line = dataset.unit_lines[tech_group.get_line_id()]
head_unit_id = unit_line.get_head_unit_id()
obj_location = f"data/game_entity/generic/{name_lookup_dict[head_unit_id][1]}/"
else:
obj_location = f"data/tech/generic/{tech_lookup_dict[tech_id][1]}/"
raw_api_object.set_location(obj_location)
raw_api_object.set_filename(tech_lookup_dict[tech_id][1])
tech_group.add_raw_api_object(raw_api_object)
# =======================================================================
# Types
# =======================================================================
raw_api_object.add_raw_member("types", [], "engine.util.tech.Tech")
# =======================================================================
# Name
# =======================================================================
name_ref = f"{tech_name}.{tech_name}Name"
name_raw_api_object = RawAPIObject(name_ref,
f"{tech_name}Name",
dataset.nyan_api_objects)
name_raw_api_object.add_raw_parent("engine.util.language.translated.type.TranslatedString")
name_location = ForwardRef(tech_group, tech_name)
name_raw_api_object.set_location(name_location)
name_raw_api_object.add_raw_member("translations",
[],
"engine.util.language.translated.type.TranslatedString")
name_forward_ref = ForwardRef(tech_group, name_ref)
raw_api_object.add_raw_member("name", name_forward_ref, "engine.util.tech.Tech")
tech_group.add_raw_api_object(name_raw_api_object)
# =======================================================================
# Description
# =======================================================================
description_ref = f"{tech_name}.{tech_name}Description"
description_raw_api_object = RawAPIObject(description_ref,
f"{tech_name}Description",
dataset.nyan_api_objects)
description_raw_api_object.add_raw_parent("engine.util.language.translated.type.TranslatedMarkupFile")
description_location = ForwardRef(tech_group, tech_name)
description_raw_api_object.set_location(description_location)
description_raw_api_object.add_raw_member("translations",
[],
"engine.util.language.translated.type.TranslatedMarkupFile")
description_forward_ref = ForwardRef(tech_group, description_ref)
raw_api_object.add_raw_member("description",
description_forward_ref,
"engine.util.tech.Tech")
tech_group.add_raw_api_object(description_raw_api_object)
# =======================================================================
# Long description
# =======================================================================
long_description_ref = f"{tech_name}.{tech_name}LongDescription"
long_description_raw_api_object = RawAPIObject(long_description_ref,
f"{tech_name}LongDescription",
dataset.nyan_api_objects)
long_description_raw_api_object.add_raw_parent("engine.util.language.translated.type.TranslatedMarkupFile")
long_description_location = ForwardRef(tech_group, tech_name)
long_description_raw_api_object.set_location(long_description_location)
long_description_raw_api_object.add_raw_member("translations",
[],
"engine.util.language.translated.type.TranslatedMarkupFile")
long_description_forward_ref = ForwardRef(tech_group, long_description_ref)
raw_api_object.add_raw_member("long_description",
long_description_forward_ref,
"engine.util.tech.Tech")
tech_group.add_raw_api_object(long_description_raw_api_object)
# =======================================================================
# Updates
# =======================================================================
patches = []
patches.extend(DE2TechSubprocessor.get_patches(tech_group))
raw_api_object.add_raw_member("updates", patches, "engine.util.tech.Tech")
# =======================================================================
# Misc (Objects that are not used by the tech group itself, but use its values)
# =======================================================================
if tech_group.is_researchable():
AoCAuxiliarySubprocessor.get_researchable_tech(tech_group) | [
"def",
"tech_group_to_tech",
"(",
"tech_group",
")",
":",
"tech_id",
"=",
"tech_group",
".",
"get_id",
"(",
")",
"# Skip Dark Age tech",
"if",
"tech_id",
"==",
"104",
":",
"return",
"dataset",
"=",
"tech_group",
".",
"data",
"name_lookup_dict",
"=",
"internal_na... | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/processor/conversion/de2/nyan_subprocessor.py#L518-L631 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/layers/python/layers/feature_column.py | python | _WeightedSparseColumn.key | (self) | return "{}".format(self) | Returns a string which will be used as a key when we do sorting. | Returns a string which will be used as a key when we do sorting. | [
"Returns",
"a",
"string",
"which",
"will",
"be",
"used",
"as",
"a",
"key",
"when",
"we",
"do",
"sorting",
"."
] | def key(self):
"""Returns a string which will be used as a key when we do sorting."""
return "{}".format(self) | [
"def",
"key",
"(",
"self",
")",
":",
"return",
"\"{}\"",
".",
"format",
"(",
"self",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/layers/python/layers/feature_column.py#L486-L488 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/smtpd.py | python | SMTPServer.process_message | (self, peer, mailfrom, rcpttos, data) | Override this abstract method to handle messages from the client.
peer is a tuple containing (ipaddr, port) of the client that made the
socket connection to our smtp port.
mailfrom is the raw address the client claims the message is coming
from.
rcpttos is a list of raw addresses the client wishes to deliver the
message to.
data is a string containing the entire full text of the message,
headers (if supplied) and all. It has been `de-transparencied'
according to RFC 821, Section 4.5.2. In other words, a line
containing a `.' followed by other text has had the leading dot
removed.
This function should return None, for a normal `250 Ok' response;
otherwise it returns the desired response string in RFC 821 format. | Override this abstract method to handle messages from the client. | [
"Override",
"this",
"abstract",
"method",
"to",
"handle",
"messages",
"from",
"the",
"client",
"."
] | def process_message(self, peer, mailfrom, rcpttos, data):
"""Override this abstract method to handle messages from the client.
peer is a tuple containing (ipaddr, port) of the client that made the
socket connection to our smtp port.
mailfrom is the raw address the client claims the message is coming
from.
rcpttos is a list of raw addresses the client wishes to deliver the
message to.
data is a string containing the entire full text of the message,
headers (if supplied) and all. It has been `de-transparencied'
according to RFC 821, Section 4.5.2. In other words, a line
containing a `.' followed by other text has had the leading dot
removed.
This function should return None, for a normal `250 Ok' response;
otherwise it returns the desired response string in RFC 821 format.
"""
raise NotImplementedError | [
"def",
"process_message",
"(",
"self",
",",
"peer",
",",
"mailfrom",
",",
"rcpttos",
",",
"data",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/smtpd.py#L305-L327 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | Joystick.HasPOV | (*args, **kwargs) | return _misc_.Joystick_HasPOV(*args, **kwargs) | HasPOV(self) -> bool | HasPOV(self) -> bool | [
"HasPOV",
"(",
"self",
")",
"-",
">",
"bool"
] | def HasPOV(*args, **kwargs):
"""HasPOV(self) -> bool"""
return _misc_.Joystick_HasPOV(*args, **kwargs) | [
"def",
"HasPOV",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"Joystick_HasPOV",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L2274-L2276 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/src/robotsim.py | python | Geometry3D.rotate | (self, R) | return _robotsim.Geometry3D_rotate(self, R) | rotate(Geometry3D self, double const [9] R)
Rotates the geometry data. Permanently modifies the data and resets any
collision data structures. | rotate(Geometry3D self, double const [9] R) | [
"rotate",
"(",
"Geometry3D",
"self",
"double",
"const",
"[",
"9",
"]",
"R",
")"
] | def rotate(self, R):
"""
rotate(Geometry3D self, double const [9] R)
Rotates the geometry data. Permanently modifies the data and resets any
collision data structures.
"""
return _robotsim.Geometry3D_rotate(self, R) | [
"def",
"rotate",
"(",
"self",
",",
"R",
")",
":",
"return",
"_robotsim",
".",
"Geometry3D_rotate",
"(",
"self",
",",
"R",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L2197-L2207 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/signal/fir_filter_design.py | python | remez | (numtaps, bands, desired, weight=None, Hz=None, type='bandpass',
maxiter=25, grid_density=16, fs=None) | return sigtools._remez(numtaps, bands, desired, weight, tnum, fs,
maxiter, grid_density) | Calculate the minimax optimal filter using the Remez exchange algorithm.
Calculate the filter-coefficients for the finite impulse response
(FIR) filter whose transfer function minimizes the maximum error
between the desired gain and the realized gain in the specified
frequency bands using the Remez exchange algorithm.
Parameters
----------
numtaps : int
The desired number of taps in the filter. The number of taps is
the number of terms in the filter, or the filter order plus one.
bands : array_like
A monotonic sequence containing the band edges.
All elements must be non-negative and less than half the sampling
frequency as given by `fs`.
desired : array_like
A sequence half the size of bands containing the desired gain
in each of the specified bands.
weight : array_like, optional
A relative weighting to give to each band region. The length of
`weight` has to be half the length of `bands`.
Hz : scalar, optional
*Deprecated. Use `fs` instead.*
The sampling frequency in Hz. Default is 1.
type : {'bandpass', 'differentiator', 'hilbert'}, optional
The type of filter:
* 'bandpass' : flat response in bands. This is the default.
* 'differentiator' : frequency proportional response in bands.
* 'hilbert' : filter with odd symmetry, that is, type III
(for even order) or type IV (for odd order)
linear phase filters.
maxiter : int, optional
Maximum number of iterations of the algorithm. Default is 25.
grid_density : int, optional
Grid density. The dense grid used in `remez` is of size
``(numtaps + 1) * grid_density``. Default is 16.
fs : float, optional
The sampling frequency of the signal. Default is 1.
Returns
-------
out : ndarray
A rank-1 array containing the coefficients of the optimal
(in a minimax sense) filter.
See Also
--------
firls
firwin
firwin2
minimum_phase
References
----------
.. [1] J. H. McClellan and T. W. Parks, "A unified approach to the
design of optimum FIR linear phase digital filters",
IEEE Trans. Circuit Theory, vol. CT-20, pp. 697-701, 1973.
.. [2] J. H. McClellan, T. W. Parks and L. R. Rabiner, "A Computer
Program for Designing Optimum FIR Linear Phase Digital
Filters", IEEE Trans. Audio Electroacoust., vol. AU-21,
pp. 506-525, 1973.
Examples
--------
For a signal sampled at 100 Hz, we want to construct a filter with a
passband at 20-40 Hz, and stop bands at 0-10 Hz and 45-50 Hz. Note that
this means that the behavior in the frequency ranges between those bands
is unspecified and may overshoot.
>>> from scipy import signal
>>> fs = 100
>>> bpass = signal.remez(72, [0, 10, 20, 40, 45, 50], [0, 1, 0], fs=fs)
>>> freq, response = signal.freqz(bpass)
>>> import matplotlib.pyplot as plt
>>> plt.semilogy(0.5*fs*freq/np.pi, np.abs(response), 'b-')
>>> plt.grid(alpha=0.25)
>>> plt.xlabel('Frequency (Hz)')
>>> plt.ylabel('Gain')
>>> plt.show() | Calculate the minimax optimal filter using the Remez exchange algorithm. | [
"Calculate",
"the",
"minimax",
"optimal",
"filter",
"using",
"the",
"Remez",
"exchange",
"algorithm",
"."
] | def remez(numtaps, bands, desired, weight=None, Hz=None, type='bandpass',
maxiter=25, grid_density=16, fs=None):
"""
Calculate the minimax optimal filter using the Remez exchange algorithm.
Calculate the filter-coefficients for the finite impulse response
(FIR) filter whose transfer function minimizes the maximum error
between the desired gain and the realized gain in the specified
frequency bands using the Remez exchange algorithm.
Parameters
----------
numtaps : int
The desired number of taps in the filter. The number of taps is
the number of terms in the filter, or the filter order plus one.
bands : array_like
A monotonic sequence containing the band edges.
All elements must be non-negative and less than half the sampling
frequency as given by `fs`.
desired : array_like
A sequence half the size of bands containing the desired gain
in each of the specified bands.
weight : array_like, optional
A relative weighting to give to each band region. The length of
`weight` has to be half the length of `bands`.
Hz : scalar, optional
*Deprecated. Use `fs` instead.*
The sampling frequency in Hz. Default is 1.
type : {'bandpass', 'differentiator', 'hilbert'}, optional
The type of filter:
* 'bandpass' : flat response in bands. This is the default.
* 'differentiator' : frequency proportional response in bands.
* 'hilbert' : filter with odd symmetry, that is, type III
(for even order) or type IV (for odd order)
linear phase filters.
maxiter : int, optional
Maximum number of iterations of the algorithm. Default is 25.
grid_density : int, optional
Grid density. The dense grid used in `remez` is of size
``(numtaps + 1) * grid_density``. Default is 16.
fs : float, optional
The sampling frequency of the signal. Default is 1.
Returns
-------
out : ndarray
A rank-1 array containing the coefficients of the optimal
(in a minimax sense) filter.
See Also
--------
firls
firwin
firwin2
minimum_phase
References
----------
.. [1] J. H. McClellan and T. W. Parks, "A unified approach to the
design of optimum FIR linear phase digital filters",
IEEE Trans. Circuit Theory, vol. CT-20, pp. 697-701, 1973.
.. [2] J. H. McClellan, T. W. Parks and L. R. Rabiner, "A Computer
Program for Designing Optimum FIR Linear Phase Digital
Filters", IEEE Trans. Audio Electroacoust., vol. AU-21,
pp. 506-525, 1973.
Examples
--------
For a signal sampled at 100 Hz, we want to construct a filter with a
passband at 20-40 Hz, and stop bands at 0-10 Hz and 45-50 Hz. Note that
this means that the behavior in the frequency ranges between those bands
is unspecified and may overshoot.
>>> from scipy import signal
>>> fs = 100
>>> bpass = signal.remez(72, [0, 10, 20, 40, 45, 50], [0, 1, 0], fs=fs)
>>> freq, response = signal.freqz(bpass)
>>> import matplotlib.pyplot as plt
>>> plt.semilogy(0.5*fs*freq/np.pi, np.abs(response), 'b-')
>>> plt.grid(alpha=0.25)
>>> plt.xlabel('Frequency (Hz)')
>>> plt.ylabel('Gain')
>>> plt.show()
"""
if Hz is None and fs is None:
fs = 1.0
elif Hz is not None:
if fs is not None:
raise ValueError("Values cannot be given for both 'Hz' and 'fs'.")
fs = Hz
# Convert type
try:
tnum = {'bandpass': 1, 'differentiator': 2, 'hilbert': 3}[type]
except KeyError:
raise ValueError("Type must be 'bandpass', 'differentiator', "
"or 'hilbert'")
# Convert weight
if weight is None:
weight = [1] * len(desired)
bands = np.asarray(bands).copy()
return sigtools._remez(numtaps, bands, desired, weight, tnum, fs,
maxiter, grid_density) | [
"def",
"remez",
"(",
"numtaps",
",",
"bands",
",",
"desired",
",",
"weight",
"=",
"None",
",",
"Hz",
"=",
"None",
",",
"type",
"=",
"'bandpass'",
",",
"maxiter",
"=",
"25",
",",
"grid_density",
"=",
"16",
",",
"fs",
"=",
"None",
")",
":",
"if",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/signal/fir_filter_design.py#L639-L749 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | DateSpan.SetMonths | (*args, **kwargs) | return _misc_.DateSpan_SetMonths(*args, **kwargs) | SetMonths(self, int n) -> DateSpan | SetMonths(self, int n) -> DateSpan | [
"SetMonths",
"(",
"self",
"int",
"n",
")",
"-",
">",
"DateSpan"
] | def SetMonths(*args, **kwargs):
"""SetMonths(self, int n) -> DateSpan"""
return _misc_.DateSpan_SetMonths(*args, **kwargs) | [
"def",
"SetMonths",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateSpan_SetMonths",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L4657-L4659 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/framemanager.py | python | AuiPaneInfo.HasCloseButton | (self) | return self.HasFlag(self.buttonClose) | Returns ``True`` if the pane displays a button to close the pane. | Returns ``True`` if the pane displays a button to close the pane. | [
"Returns",
"True",
"if",
"the",
"pane",
"displays",
"a",
"button",
"to",
"close",
"the",
"pane",
"."
] | def HasCloseButton(self):
""" Returns ``True`` if the pane displays a button to close the pane. """
return self.HasFlag(self.buttonClose) | [
"def",
"HasCloseButton",
"(",
"self",
")",
":",
"return",
"self",
".",
"HasFlag",
"(",
"self",
".",
"buttonClose",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/framemanager.py#L794-L797 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/sets_impl.py | python | _set_operation | (a, b, set_operation, validate_indices=True) | return sparse_tensor.SparseTensor(indices, values, shape) | Compute set operation of elements in last dimension of `a` and `b`.
All but the last dimension of `a` and `b` must match.
Args:
a: `Tensor` or `SparseTensor` of the same type as `b`. If sparse, indices
must be sorted in row-major order.
b: `Tensor` or `SparseTensor` of the same type as `a`. Must be
`SparseTensor` if `a` is `SparseTensor`. If sparse, indices must be sorted
in row-major order.
set_operation: String indicating set operation. See
SetOperationOp::SetOperationFromContext for valid values.
validate_indices: Whether to validate the order and range of sparse indices
in `a` and `b`.
Returns:
A `SparseTensor` with the same rank as `a` and `b`, and all but the last
dimension the same. Elements along the last dimension contain the results
of the set operation.
Raises:
TypeError: If inputs are invalid types.
ValueError: If `a` is sparse and `b` is dense. | Compute set operation of elements in last dimension of `a` and `b`. | [
"Compute",
"set",
"operation",
"of",
"elements",
"in",
"last",
"dimension",
"of",
"a",
"and",
"b",
"."
] | def _set_operation(a, b, set_operation, validate_indices=True):
"""Compute set operation of elements in last dimension of `a` and `b`.
All but the last dimension of `a` and `b` must match.
Args:
a: `Tensor` or `SparseTensor` of the same type as `b`. If sparse, indices
must be sorted in row-major order.
b: `Tensor` or `SparseTensor` of the same type as `a`. Must be
`SparseTensor` if `a` is `SparseTensor`. If sparse, indices must be sorted
in row-major order.
set_operation: String indicating set operation. See
SetOperationOp::SetOperationFromContext for valid values.
validate_indices: Whether to validate the order and range of sparse indices
in `a` and `b`.
Returns:
A `SparseTensor` with the same rank as `a` and `b`, and all but the last
dimension the same. Elements along the last dimension contain the results
of the set operation.
Raises:
TypeError: If inputs are invalid types.
ValueError: If `a` is sparse and `b` is dense.
"""
if isinstance(a, sparse_tensor.SparseTensor):
if isinstance(b, sparse_tensor.SparseTensor):
indices, values, shape = gen_set_ops.sparse_to_sparse_set_operation(
a.indices, a.values, a.dense_shape, b.indices, b.values,
b.dense_shape, set_operation, validate_indices)
else:
raise ValueError("Sparse,Dense is not supported, but Dense,Sparse is. "
"Please flip the order of your inputs.")
elif isinstance(b, sparse_tensor.SparseTensor):
indices, values, shape = gen_set_ops.dense_to_sparse_set_operation(
a, b.indices, b.values, b.dense_shape, set_operation, validate_indices)
else:
indices, values, shape = gen_set_ops.dense_to_dense_set_operation(
a, b, set_operation, validate_indices)
return sparse_tensor.SparseTensor(indices, values, shape) | [
"def",
"_set_operation",
"(",
"a",
",",
"b",
",",
"set_operation",
",",
"validate_indices",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"a",
",",
"sparse_tensor",
".",
"SparseTensor",
")",
":",
"if",
"isinstance",
"(",
"b",
",",
"sparse_tensor",
".",
... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/sets_impl.py#L94-L133 | |
dmlc/xgboost | 2775c2a1abd4b5b759ff517617434c8b9aeb4cc0 | python-package/setup.py | python | copy_tree | (src_dir: str, target_dir: str) | Copy source tree into build directory. | Copy source tree into build directory. | [
"Copy",
"source",
"tree",
"into",
"build",
"directory",
"."
] | def copy_tree(src_dir: str, target_dir: str) -> None:
'''Copy source tree into build directory.'''
def clean_copy_tree(src: str, dst: str) -> None:
distutils.dir_util.copy_tree(src, dst)
NEED_CLEAN_TREE.add(os.path.abspath(dst))
def clean_copy_file(src: str, dst: str) -> None:
distutils.file_util.copy_file(src, dst)
NEED_CLEAN_FILE.add(os.path.abspath(dst))
src = os.path.join(src_dir, 'src')
inc = os.path.join(src_dir, 'include')
dmlc_core = os.path.join(src_dir, 'dmlc-core')
rabit = os.path.join(src_dir, 'rabit')
cmake = os.path.join(src_dir, 'cmake')
plugin = os.path.join(src_dir, 'plugin')
clean_copy_tree(src, os.path.join(target_dir, 'src'))
clean_copy_tree(inc, os.path.join(target_dir, 'include'))
clean_copy_tree(dmlc_core, os.path.join(target_dir, 'dmlc-core'))
clean_copy_tree(rabit, os.path.join(target_dir, 'rabit'))
clean_copy_tree(cmake, os.path.join(target_dir, 'cmake'))
clean_copy_tree(plugin, os.path.join(target_dir, 'plugin'))
cmake_list = os.path.join(src_dir, 'CMakeLists.txt')
clean_copy_file(cmake_list, os.path.join(target_dir, 'CMakeLists.txt'))
lic = os.path.join(src_dir, 'LICENSE')
clean_copy_file(lic, os.path.join(target_dir, 'LICENSE')) | [
"def",
"copy_tree",
"(",
"src_dir",
":",
"str",
",",
"target_dir",
":",
"str",
")",
"->",
"None",
":",
"def",
"clean_copy_tree",
"(",
"src",
":",
"str",
",",
"dst",
":",
"str",
")",
"->",
"None",
":",
"distutils",
".",
"dir_util",
".",
"copy_tree",
"... | https://github.com/dmlc/xgboost/blob/2775c2a1abd4b5b759ff517617434c8b9aeb4cc0/python-package/setup.py#L51-L78 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | PrintDialogData.GetCollate | (*args, **kwargs) | return _windows_.PrintDialogData_GetCollate(*args, **kwargs) | GetCollate(self) -> bool | GetCollate(self) -> bool | [
"GetCollate",
"(",
"self",
")",
"-",
">",
"bool"
] | def GetCollate(*args, **kwargs):
"""GetCollate(self) -> bool"""
return _windows_.PrintDialogData_GetCollate(*args, **kwargs) | [
"def",
"GetCollate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PrintDialogData_GetCollate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L5070-L5072 | |
Yijunmaverick/GenerativeFaceCompletion | f72dea0fa27c779fef7b65d2f01e82bcc23a0eb2 | tools/extra/resize_and_crop_images.py | python | PILResizeCrop.resize_and_crop_image | (self, input_file, output_file, output_side_length = 256, fit = True) | Downsample the image. | Downsample the image. | [
"Downsample",
"the",
"image",
"."
] | def resize_and_crop_image(self, input_file, output_file, output_side_length = 256, fit = True):
'''Downsample the image.
'''
img = Image.open(input_file)
box = (output_side_length, output_side_length)
#preresize image with factor 2, 4, 8 and fast algorithm
factor = 1
while img.size[0]/factor > 2*box[0] and img.size[1]*2/factor > 2*box[1]:
factor *=2
if factor > 1:
img.thumbnail((img.size[0]/factor, img.size[1]/factor), Image.NEAREST)
#calculate the cropping box and get the cropped part
if fit:
x1 = y1 = 0
x2, y2 = img.size
wRatio = 1.0 * x2/box[0]
hRatio = 1.0 * y2/box[1]
if hRatio > wRatio:
y1 = int(y2/2-box[1]*wRatio/2)
y2 = int(y2/2+box[1]*wRatio/2)
else:
x1 = int(x2/2-box[0]*hRatio/2)
x2 = int(x2/2+box[0]*hRatio/2)
img = img.crop((x1,y1,x2,y2))
#Resize the image with best quality algorithm ANTI-ALIAS
img.thumbnail(box, Image.ANTIALIAS)
#save it into a file-like object
with open(output_file, 'wb') as out:
img.save(out, 'JPEG', quality=75) | [
"def",
"resize_and_crop_image",
"(",
"self",
",",
"input_file",
",",
"output_file",
",",
"output_side_length",
"=",
"256",
",",
"fit",
"=",
"True",
")",
":",
"img",
"=",
"Image",
".",
"open",
"(",
"input_file",
")",
"box",
"=",
"(",
"output_side_length",
"... | https://github.com/Yijunmaverick/GenerativeFaceCompletion/blob/f72dea0fa27c779fef7b65d2f01e82bcc23a0eb2/tools/extra/resize_and_crop_images.py#L40-L71 | ||
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/numpy_extension/_op.py | python | arange_like | (data, start=0.0, step=1.0, repeat=1, ctx=None, axis=None) | return _mx_nd_npx.arange_like(data=data, start=start, step=step, repeat=repeat,
ctx=ctx, axis=axis) | r"""Return an array with evenly spaced values. If axis is not given, the output will
have the same shape as the input array. Otherwise, the output will be a 1-D array with size of
the specified axis in input shape.
Parameters
----------
data : NDArray
The input
start : double, optional, default=0
Start of interval. The interval includes this value. The default start value is 0.
step : double, optional, default=1
Spacing between values.
repeat : int, optional, default='1'
The repeating time of all elements.
E.g repeat=3, the element a will be repeated three times --> a, a, a.
ctx : string, optional, default=''
Context of output, in format [cpu|gpu|cpu_pinned](n).Only used for imperative calls.
axis : int or None, optional, default='None'
Arange elements according to the size of a certain axis of input array.
The negative numbers are interpreted counting from the backward.
If not provided, will arange elements according to the input shape.
Returns
-------
out : NDArray or list of NDArrays
The output of this function.
Example
-------
>>> x = np.random.uniform(0, 1, size=(3,4))
>>> x
array([[0.5488135 , 0.5928446 , 0.71518934, 0.84426576],
[0.60276335, 0.8579456 , 0.5448832 , 0.8472517 ],
[0.4236548 , 0.6235637 , 0.6458941 , 0.3843817 ]])
>>> npx.arange_like(x, start=0)
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]])
>>> npx.arange_like(x, start=0, axis=-1)
array([0., 1., 2., 3.]) | r"""Return an array with evenly spaced values. If axis is not given, the output will
have the same shape as the input array. Otherwise, the output will be a 1-D array with size of
the specified axis in input shape. | [
"r",
"Return",
"an",
"array",
"with",
"evenly",
"spaced",
"values",
".",
"If",
"axis",
"is",
"not",
"given",
"the",
"output",
"will",
"have",
"the",
"same",
"shape",
"as",
"the",
"input",
"array",
".",
"Otherwise",
"the",
"output",
"will",
"be",
"a",
"... | def arange_like(data, start=0.0, step=1.0, repeat=1, ctx=None, axis=None):
r"""Return an array with evenly spaced values. If axis is not given, the output will
have the same shape as the input array. Otherwise, the output will be a 1-D array with size of
the specified axis in input shape.
Parameters
----------
data : NDArray
The input
start : double, optional, default=0
Start of interval. The interval includes this value. The default start value is 0.
step : double, optional, default=1
Spacing between values.
repeat : int, optional, default='1'
The repeating time of all elements.
E.g repeat=3, the element a will be repeated three times --> a, a, a.
ctx : string, optional, default=''
Context of output, in format [cpu|gpu|cpu_pinned](n).Only used for imperative calls.
axis : int or None, optional, default='None'
Arange elements according to the size of a certain axis of input array.
The negative numbers are interpreted counting from the backward.
If not provided, will arange elements according to the input shape.
Returns
-------
out : NDArray or list of NDArrays
The output of this function.
Example
-------
>>> x = np.random.uniform(0, 1, size=(3,4))
>>> x
array([[0.5488135 , 0.5928446 , 0.71518934, 0.84426576],
[0.60276335, 0.8579456 , 0.5448832 , 0.8472517 ],
[0.4236548 , 0.6235637 , 0.6458941 , 0.3843817 ]])
>>> npx.arange_like(x, start=0)
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]])
>>> npx.arange_like(x, start=0, axis=-1)
array([0., 1., 2., 3.])
"""
return _mx_nd_npx.arange_like(data=data, start=start, step=step, repeat=repeat,
ctx=ctx, axis=axis) | [
"def",
"arange_like",
"(",
"data",
",",
"start",
"=",
"0.0",
",",
"step",
"=",
"1.0",
",",
"repeat",
"=",
"1",
",",
"ctx",
"=",
"None",
",",
"axis",
"=",
"None",
")",
":",
"return",
"_mx_nd_npx",
".",
"arange_like",
"(",
"data",
"=",
"data",
",",
... | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy_extension/_op.py#L1321-L1364 | |
GSORF/Visual-GPS-SLAM | 9e327108d6be3fd8dc80c8f3bcc329237bacf230 | 02_Utilities/FusionLinearKalmanFilter/01_LinearKalmanFilter_allEvaluations.py | python | test_kf_position | (_title="title", _description="description", _init_x=0.0, _init_y=0.0, _init_z=0.0, _sigma_p_gps=[1.0, 1.0], _sigma_p_dso=[5., 5., 5.], _gps_freq = 1, _sigma_x0 = 0.02, _sigma_v0 = 0.4, _sigma_w_x = 0.2, _sigma_w_v = 0.2) | print(rmse_dso[:][0])
print("now comes filtered:")
print(rmse_filtered[:][0]) | print(rmse_dso[:][0])
print("now comes filtered:")
print(rmse_filtered[:][0]) | [
"print",
"(",
"rmse_dso",
"[",
":",
"]",
"[",
"0",
"]",
")",
"print",
"(",
"now",
"comes",
"filtered",
":",
")",
"print",
"(",
"rmse_filtered",
"[",
":",
"]",
"[",
"0",
"]",
")"
] | def test_kf_position(_title="title", _description="description", _init_x=0.0, _init_y=0.0, _init_z=0.0, _sigma_p_gps=[1.0, 1.0], _sigma_p_dso=[5., 5., 5.], _gps_freq = 1, _sigma_x0 = 0.02, _sigma_v0 = 0.4, _sigma_w_x = 0.2, _sigma_w_v = 0.2):
N = frames # NumFrames Messpunkte
T = deltaT # Zeit zwischen Messungen
# Initial Velocities
vx = 0.0
vy = 0.0
vz = 0.0
#sigma_p = np.array([5., 5.])
sigma_p_gps = np.array(_sigma_p_gps) # std. deviation (x,y) of 1m was set in the VSLAM addon
sigma_p_dso = np.array(_sigma_p_dso) # std. deviation (x,y,z) is not clear yet, so set pretty high
# simulate measurements
zGPS, zDSO, x = simulate_measurements_position(N,T, vx, vy, vz)
# Kalman Init Parameter:
x0 = np.array([_init_x, vx, _init_y, vy, _init_z, vz]); # init measurements
sigma_x0 = _sigma_x0 #std.dev. for position
sigma_v0 = _sigma_v0 #std.dev. for velocity
P0 = np.diag(np.array([sigma_x0, sigma_v0, sigma_x0, sigma_v0, sigma_x0, sigma_v0])**2)
# Parameter der Systemrauschprozesse (Standardabweichungen)
sigma_w_x = _sigma_w_x #1e-4
sigma_w_v = _sigma_w_v #1e-10
# System Uebergangsmatrix
Phik = np.array([[1, T, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, T, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, T],
[0, 0, 0, 0, 0, 1]], dtype=float)
# System Rauschkovarianz
T2 = np.power(T,2)
T3 = T2 * T
Qk = np.array([[sigma_w_v*T3/3 + sigma_w_v*T, sigma_w_v*T2/2, 0, 0, 0, 0 ],
[sigma_w_v*T2/2, sigma_w_v*T, 0, 0, 0, 0 ],
[0, 0, sigma_w_v*T3/3 + sigma_w_v*T, sigma_w_v*T2/2, 0, 0 ],
[0, 0, sigma_w_v*T2/2, sigma_w_v*T, 0, 0 ],
[0, 0, 0, 0, sigma_w_v*T3/3 + sigma_w_v*T, sigma_w_v*T2/2 ],
[0, 0, 0, 0, sigma_w_v*T2/2, sigma_w_v*T ]], dtype=float)
# Messmatrix
# Only measure x and y position (GPS)
H_GPS = np.array([[1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0]], dtype=float)
# Measure x, y and z position (DSO)
H_DSO = np.array([[1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 0]], dtype=float)
# Messung Rauschkovarianz
R_GPS = np.diag(sigma_p_gps**2)
R_DSO = np.diag(sigma_p_dso**2)
kf_x = np.zeros((N, 6))
kf_x[0] = x0
kf = LinearKalmanFilter(x0, P0)
#Blender: Store initial state vector, covariance matrix and update object
bpy.types.Scene.KalmanFilter_x.append(kf.x)
bpy.types.Scene.KalmanFilter_P.append(kf.P)
objectUpdate(filteredObject, 0, kf.x[0], kf.x[2], kf.x[4]) # (obj, frame, x, y, z)
# Run Kalman filter:
for frame in np.arange(1, N):
#print("Kalman Filter step:", frame)
kf.predict(Phik, Qk, T)
if _title == "GPS":
# Only use GPS as measurements
if(frame % _gps_freq == 0):
kf.update(zGPS[frame, :], H_GPS, R_GPS)
elif _title == "DSO":
# Only use DSO raw position as measurements (indices 0, 2, 4 for x,y,z)
kf.update(zDSO[frame, 0::2], H_DSO, R_DSO)
else:
# Fuse GPS and DSO
# -> GPS: Only take new Measurements every 5th iteration:
if(frame % _gps_freq == 0):
kf.update(zGPS[frame, :], H_GPS, R_GPS)
# -> DSO: Take new raw dso position Measurements every timestep:
kf.update(zDSO[frame, 0::2], H_DSO, R_DSO)
# Speichere aktuellen Zustand
kf_x[frame, :] = kf.x
# Update filtered Blenderobject
objectUpdate(filteredObject, frame, kf.x[0], kf.x[2], kf.x[4]) # (obj, frame, x, y, z)
# Visualize Covariance Matrix
visualizeCovariance(kf.x, kf.P)
# Store P Matrix from KalmanFilter for display
bpy.types.Scene.KalmanFilter_x.append(kf.x)
bpy.types.Scene.KalmanFilter_P.append(kf.P)
# Remove all assigned handler functions:
bpy.app.handlers.frame_change_pre.clear()
# Now register a handler function to update the 3D Data Plot
bpy.app.handlers.frame_change_pre.append(frameUpdate)
# Save file for plotting via matplotlib
rmse_gps = np.zeros((N, 2))
rmse_dso = np.zeros((N, 3))
rmse_filtered = np.zeros((N, 3))
rmse_velocity = np.zeros((N, 3))
for frame in np.arange(0, N):
rmse_gps[frame][0] = zGPS[frame][0] - x[frame][0]
rmse_gps[frame][1] = zGPS[frame][1] - x[frame][2]
rmse_dso[frame][0] = zDSO[frame][0] - x[frame][0]
rmse_dso[frame][1] = zDSO[frame][2] - x[frame][2]
rmse_dso[frame][2] = zDSO[frame][4] - x[frame][4]
rmse_filtered[frame][0] = kf_x[frame][0] - x[frame][0]
rmse_filtered[frame][1] = kf_x[frame][2] - x[frame][2]
rmse_filtered[frame][2] = kf_x[frame][4] - x[frame][4]
# Velocity
rmse_velocity[frame][0] = kf_x[frame][1] - x[frame][1]
rmse_velocity[frame][1] = kf_x[frame][3] - x[frame][3]
rmse_velocity[frame][2] = kf_x[frame][5] - x[frame][5]
'''
print(rmse_dso[:][0])
print("now comes filtered:")
print(rmse_filtered[:][0])
'''
plotResults(N, x, kf_x, zGPS, zDSO, rmse_gps, rmse_dso, rmse_filtered, rmse_velocity, _title, _description, _init_x, _init_y, _init_z, _sigma_p_gps, _sigma_p_dso, _gps_freq, _sigma_x0, _sigma_v0, _sigma_w_x, _sigma_w_v)
'''
''' | [
"def",
"test_kf_position",
"(",
"_title",
"=",
"\"title\"",
",",
"_description",
"=",
"\"description\"",
",",
"_init_x",
"=",
"0.0",
",",
"_init_y",
"=",
"0.0",
",",
"_init_z",
"=",
"0.0",
",",
"_sigma_p_gps",
"=",
"[",
"1.0",
",",
"1.0",
"]",
",",
"_sig... | https://github.com/GSORF/Visual-GPS-SLAM/blob/9e327108d6be3fd8dc80c8f3bcc329237bacf230/02_Utilities/FusionLinearKalmanFilter/01_LinearKalmanFilter_allEvaluations.py#L328-L462 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.