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
sequence | function
stringlengths 34
151k
| function_tokens
sequence | url
stringlengths 90
278
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2class.py | python | uCSIsCatL | (code) | return ret | Check whether the character is part of L UCS Category | Check whether the character is part of L UCS Category | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"L",
"UCS",
"Category"
] | def uCSIsCatL(code):
"""Check whether the character is part of L UCS Category """
ret = libxml2mod.xmlUCSIsCatL(code)
return ret | [
"def",
"uCSIsCatL",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsCatL",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L1483-L1486 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/xrc.py | python | XmlResourceHandler.GetNodeContent | (*args, **kwargs) | return _xrc.XmlResourceHandler_GetNodeContent(*args, **kwargs) | GetNodeContent(self, XmlNode node) -> String | GetNodeContent(self, XmlNode node) -> String | [
"GetNodeContent",
"(",
"self",
"XmlNode",
"node",
")",
"-",
">",
"String"
] | def GetNodeContent(*args, **kwargs):
"""GetNodeContent(self, XmlNode node) -> String"""
return _xrc.XmlResourceHandler_GetNodeContent(*args, **kwargs) | [
"def",
"GetNodeContent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_xrc",
".",
"XmlResourceHandler_GetNodeContent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/xrc.py#L631-L633 |
|
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/requests/requests/models.py | python | Response.iter_content | (self, chunk_size=1, decode_unicode=False) | return chunks | Iterates over the response data. When stream=True is set on the
request, this avoids reading the content at once into memory for
large responses. The chunk size is the number of bytes it should
read into memory. This is not necessarily the length of each item
returned as decoding can take place.
If decode_unicode is True, content will be decoded using the best
available encoding based on the response. | Iterates over the response data. When stream=True is set on the
request, this avoids reading the content at once into memory for
large responses. The chunk size is the number of bytes it should
read into memory. This is not necessarily the length of each item
returned as decoding can take place. | [
"Iterates",
"over",
"the",
"response",
"data",
".",
"When",
"stream",
"=",
"True",
"is",
"set",
"on",
"the",
"request",
"this",
"avoids",
"reading",
"the",
"content",
"at",
"once",
"into",
"memory",
"for",
"large",
"responses",
".",
"The",
"chunk",
"size",
"is",
"the",
"number",
"of",
"bytes",
"it",
"should",
"read",
"into",
"memory",
".",
"This",
"is",
"not",
"necessarily",
"the",
"length",
"of",
"each",
"item",
"returned",
"as",
"decoding",
"can",
"take",
"place",
"."
] | def iter_content(self, chunk_size=1, decode_unicode=False):
"""Iterates over the response data. When stream=True is set on the
request, this avoids reading the content at once into memory for
large responses. The chunk size is the number of bytes it should
read into memory. This is not necessarily the length of each item
returned as decoding can take place.
If decode_unicode is True, content will be decoded using the best
available encoding based on the response.
"""
def generate():
try:
# Special case for urllib3.
try:
for chunk in self.raw.stream(chunk_size, decode_content=True):
yield chunk
except ProtocolError as e:
raise ChunkedEncodingError(e)
except DecodeError as e:
raise ContentDecodingError(e)
except ReadTimeoutError as e:
raise ConnectionError(e)
except AttributeError:
# Standard file-like object.
while True:
chunk = self.raw.read(chunk_size)
if not chunk:
break
yield chunk
self._content_consumed = True
if self._content_consumed and isinstance(self._content, bool):
raise StreamConsumedError()
# simulate reading small chunks of the content
reused_chunks = iter_slices(self._content, chunk_size)
stream_chunks = generate()
chunks = reused_chunks if self._content_consumed else stream_chunks
if decode_unicode:
chunks = stream_decode_response_unicode(chunks, self)
return chunks | [
"def",
"iter_content",
"(",
"self",
",",
"chunk_size",
"=",
"1",
",",
"decode_unicode",
"=",
"False",
")",
":",
"def",
"generate",
"(",
")",
":",
"try",
":",
"# Special case for urllib3.",
"try",
":",
"for",
"chunk",
"in",
"self",
".",
"raw",
".",
"stream",
"(",
"chunk_size",
",",
"decode_content",
"=",
"True",
")",
":",
"yield",
"chunk",
"except",
"ProtocolError",
"as",
"e",
":",
"raise",
"ChunkedEncodingError",
"(",
"e",
")",
"except",
"DecodeError",
"as",
"e",
":",
"raise",
"ContentDecodingError",
"(",
"e",
")",
"except",
"ReadTimeoutError",
"as",
"e",
":",
"raise",
"ConnectionError",
"(",
"e",
")",
"except",
"AttributeError",
":",
"# Standard file-like object.",
"while",
"True",
":",
"chunk",
"=",
"self",
".",
"raw",
".",
"read",
"(",
"chunk_size",
")",
"if",
"not",
"chunk",
":",
"break",
"yield",
"chunk",
"self",
".",
"_content_consumed",
"=",
"True",
"if",
"self",
".",
"_content_consumed",
"and",
"isinstance",
"(",
"self",
".",
"_content",
",",
"bool",
")",
":",
"raise",
"StreamConsumedError",
"(",
")",
"# simulate reading small chunks of the content",
"reused_chunks",
"=",
"iter_slices",
"(",
"self",
".",
"_content",
",",
"chunk_size",
")",
"stream_chunks",
"=",
"generate",
"(",
")",
"chunks",
"=",
"reused_chunks",
"if",
"self",
".",
"_content_consumed",
"else",
"stream_chunks",
"if",
"decode_unicode",
":",
"chunks",
"=",
"stream_decode_response_unicode",
"(",
"chunks",
",",
"self",
")",
"return",
"chunks"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/requests/requests/models.py#L641-L685 |
|
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/convert/entity_object/conversion/converter_object.py | python | RawMemberPush.__init__ | (self, forward_ref, member_name, member_origin, push_value) | Creates a new member push.
:param forward_ref: forward reference of the RawAPIObject.
:type forward_ref: ForwardRef
:param member_name: Name of the member that is extended.
:type member_name: str
:param member_origin: Fqon of the object the member was inherited from.
:type member_origin: str
:param push_value: Value that extends the existing member value.
:type push_value: list | Creates a new member push. | [
"Creates",
"a",
"new",
"member",
"push",
"."
] | def __init__(self, forward_ref, member_name, member_origin, push_value):
"""
Creates a new member push.
:param forward_ref: forward reference of the RawAPIObject.
:type forward_ref: ForwardRef
:param member_name: Name of the member that is extended.
:type member_name: str
:param member_origin: Fqon of the object the member was inherited from.
:type member_origin: str
:param push_value: Value that extends the existing member value.
:type push_value: list
"""
self.forward_ref = forward_ref
self.member_name = member_name
self.member_origin = member_origin
self.push_value = push_value | [
"def",
"__init__",
"(",
"self",
",",
"forward_ref",
",",
"member_name",
",",
"member_origin",
",",
"push_value",
")",
":",
"self",
".",
"forward_ref",
"=",
"forward_ref",
"self",
".",
"member_name",
"=",
"member_name",
"self",
".",
"member_origin",
"=",
"member_origin",
"self",
".",
"push_value",
"=",
"push_value"
] | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/entity_object/conversion/converter_object.py#L619-L635 |
||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBProcess.GetNumQueues | (self) | return _lldb.SBProcess_GetNumQueues(self) | GetNumQueues(self) -> uint32_t | GetNumQueues(self) -> uint32_t | [
"GetNumQueues",
"(",
"self",
")",
"-",
">",
"uint32_t"
] | def GetNumQueues(self):
"""GetNumQueues(self) -> uint32_t"""
return _lldb.SBProcess_GetNumQueues(self) | [
"def",
"GetNumQueues",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBProcess_GetNumQueues",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L7084-L7086 |
|
ApolloAuto/apollo | 463fb82f9e979d02dcb25044e60931293ab2dba0 | modules/tools/localization/evaluate_compare.py | python | get_angle_stat2_from_data | (data) | return stat | Find the max number of continuous frames when yaw error is lager
than 1.0d, 0.6d and 0.3d
Arguments:
data: error array
Returns:
stat: array of max number of continuous frames | Find the max number of continuous frames when yaw error is lager
than 1.0d, 0.6d and 0.3d | [
"Find",
"the",
"max",
"number",
"of",
"continuous",
"frames",
"when",
"yaw",
"error",
"is",
"lager",
"than",
"1",
".",
"0d",
"0",
".",
"6d",
"and",
"0",
".",
"3d"
] | def get_angle_stat2_from_data(data):
"""Find the max number of continuous frames when yaw error is lager
than 1.0d, 0.6d and 0.3d
Arguments:
data: error array
Returns:
stat: array of max number of continuous frames
"""
max_con_frame_num_1_0 = 0
max_con_frame_num_0_6 = 0
max_con_frame_num_0_3 = 0
tem_con_frame_num_1_0 = 0
tem_con_frame_num_0_6 = 0
tem_con_frame_num_0_3 = 0
for d in data:
if(d > 0.3):
tem_con_frame_num_0_3 += 1
if(d > 0.6):
tem_con_frame_num_0_6 += 1
if(d > 1.0):
tem_con_frame_num_1_0 += 1
else:
if tem_con_frame_num_1_0 > max_con_frame_num_1_0:
max_con_frame_num_1_0 = tem_con_frame_num_1_0
tem_con_frame_num_1_0 = 0
else:
if tem_con_frame_num_0_6 > max_con_frame_num_0_6:
max_con_frame_num_0_6 = tem_con_frame_num_0_6
tem_con_frame_num_0_6 = 0
else:
if tem_con_frame_num_0_3 > max_con_frame_num_0_3:
max_con_frame_num_0_3 = tem_con_frame_num_0_3
tem_con_frame_num_0_3 = 0
stat = [max_con_frame_num_1_0, max_con_frame_num_0_6, max_con_frame_num_0_3]
return stat | [
"def",
"get_angle_stat2_from_data",
"(",
"data",
")",
":",
"max_con_frame_num_1_0",
"=",
"0",
"max_con_frame_num_0_6",
"=",
"0",
"max_con_frame_num_0_3",
"=",
"0",
"tem_con_frame_num_1_0",
"=",
"0",
"tem_con_frame_num_0_6",
"=",
"0",
"tem_con_frame_num_0_3",
"=",
"0",
"for",
"d",
"in",
"data",
":",
"if",
"(",
"d",
">",
"0.3",
")",
":",
"tem_con_frame_num_0_3",
"+=",
"1",
"if",
"(",
"d",
">",
"0.6",
")",
":",
"tem_con_frame_num_0_6",
"+=",
"1",
"if",
"(",
"d",
">",
"1.0",
")",
":",
"tem_con_frame_num_1_0",
"+=",
"1",
"else",
":",
"if",
"tem_con_frame_num_1_0",
">",
"max_con_frame_num_1_0",
":",
"max_con_frame_num_1_0",
"=",
"tem_con_frame_num_1_0",
"tem_con_frame_num_1_0",
"=",
"0",
"else",
":",
"if",
"tem_con_frame_num_0_6",
">",
"max_con_frame_num_0_6",
":",
"max_con_frame_num_0_6",
"=",
"tem_con_frame_num_0_6",
"tem_con_frame_num_0_6",
"=",
"0",
"else",
":",
"if",
"tem_con_frame_num_0_3",
">",
"max_con_frame_num_0_3",
":",
"max_con_frame_num_0_3",
"=",
"tem_con_frame_num_0_3",
"tem_con_frame_num_0_3",
"=",
"0",
"stat",
"=",
"[",
"max_con_frame_num_1_0",
",",
"max_con_frame_num_0_6",
",",
"max_con_frame_num_0_3",
"]",
"return",
"stat"
] | https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/modules/tools/localization/evaluate_compare.py#L67-L105 |
|
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | example/gluon/lipnet/utils/download_data.py | python | download_align | (from_idx, to_idx, _params) | return (succ, fail) | download aligns | download aligns | [
"download",
"aligns"
] | def download_align(from_idx, to_idx, _params):
"""
download aligns
"""
succ = set()
fail = set()
for idx in range(from_idx, to_idx):
name = 's' + str(idx)
if idx == 0:
continue
script = "http://spandh.dcs.shef.ac.uk/gridcorpus/{nm}/align/{nm}.tar".format(nm=name)
down_sc = 'cd {align_path} && wget {script} && \
tar -xvf {nm}.tar'.format(script=script,
nm=name,
align_path=_params['align_path'])
try:
print(down_sc)
os.system(down_sc)
succ.add(idx)
except OSError as error:
print(error)
fail.add(idx)
return (succ, fail) | [
"def",
"download_align",
"(",
"from_idx",
",",
"to_idx",
",",
"_params",
")",
":",
"succ",
"=",
"set",
"(",
")",
"fail",
"=",
"set",
"(",
")",
"for",
"idx",
"in",
"range",
"(",
"from_idx",
",",
"to_idx",
")",
":",
"name",
"=",
"'s'",
"+",
"str",
"(",
"idx",
")",
"if",
"idx",
"==",
"0",
":",
"continue",
"script",
"=",
"\"http://spandh.dcs.shef.ac.uk/gridcorpus/{nm}/align/{nm}.tar\"",
".",
"format",
"(",
"nm",
"=",
"name",
")",
"down_sc",
"=",
"'cd {align_path} && wget {script} && \\\n tar -xvf {nm}.tar'",
".",
"format",
"(",
"script",
"=",
"script",
",",
"nm",
"=",
"name",
",",
"align_path",
"=",
"_params",
"[",
"'align_path'",
"]",
")",
"try",
":",
"print",
"(",
"down_sc",
")",
"os",
".",
"system",
"(",
"down_sc",
")",
"succ",
".",
"add",
"(",
"idx",
")",
"except",
"OSError",
"as",
"error",
":",
"print",
"(",
"error",
")",
"fail",
".",
"add",
"(",
"idx",
")",
"return",
"(",
"succ",
",",
"fail",
")"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/gluon/lipnet/utils/download_data.py#L55-L77 |
|
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqt/mantidqt/widgets/sliceviewer/peaksviewer/model.py | python | PeaksViewerModel.slicepoint | (self, selected_index, slice_info, frame) | return slicepoint | Return the value of the center in the slice dimension for the peak at the given index
:param selected_index: Index of a peak in the table
:param slice_info: Information on the current slice | Return the value of the center in the slice dimension for the peak at the given index
:param selected_index: Index of a peak in the table
:param slice_info: Information on the current slice | [
"Return",
"the",
"value",
"of",
"the",
"center",
"in",
"the",
"slice",
"dimension",
"for",
"the",
"peak",
"at",
"the",
"given",
"index",
":",
"param",
"selected_index",
":",
"Index",
"of",
"a",
"peak",
"in",
"the",
"table",
":",
"param",
"slice_info",
":",
"Information",
"on",
"the",
"current",
"slice"
] | def slicepoint(self, selected_index, slice_info, frame):
"""
Return the value of the center in the slice dimension for the peak at the given index
:param selected_index: Index of a peak in the table
:param slice_info: Information on the current slice
"""
frame_to_slice_fn = self._frame_to_slice_fn(frame)
peak = self.ws.getPeak(selected_index)
slicepoint = slice_info.slicepoint
slicepoint[slice_info.z_index] = getattr(peak, frame_to_slice_fn)()[slice_info.z_index]
return slicepoint | [
"def",
"slicepoint",
"(",
"self",
",",
"selected_index",
",",
"slice_info",
",",
"frame",
")",
":",
"frame_to_slice_fn",
"=",
"self",
".",
"_frame_to_slice_fn",
"(",
"frame",
")",
"peak",
"=",
"self",
".",
"ws",
".",
"getPeak",
"(",
"selected_index",
")",
"slicepoint",
"=",
"slice_info",
".",
"slicepoint",
"slicepoint",
"[",
"slice_info",
".",
"z_index",
"]",
"=",
"getattr",
"(",
"peak",
",",
"frame_to_slice_fn",
")",
"(",
")",
"[",
"slice_info",
".",
"z_index",
"]",
"return",
"slicepoint"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/sliceviewer/peaksviewer/model.py#L117-L128 |
|
chromiumembedded/cef | 80caf947f3fe2210e5344713c5281d8af9bdc295 | tools/automate/automate-git.py | python | read_file | (path) | Read a file. | Read a file. | [
"Read",
"a",
"file",
"."
] | def read_file(path):
""" Read a file. """
if os.path.exists(path):
with open(path, 'r', encoding='utf-8') as fp:
return fp.read()
else:
raise Exception("Path does not exist: %s" % (path)) | [
"def",
"read_file",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"fp",
":",
"return",
"fp",
".",
"read",
"(",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Path does not exist: %s\"",
"%",
"(",
"path",
")",
")"
] | https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/automate/automate-git.py#L219-L225 |
||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/mailbox.py | python | MaildirMessage.remove_flag | (self, flag) | Unset the given string flag(s) without changing others. | Unset the given string flag(s) without changing others. | [
"Unset",
"the",
"given",
"string",
"flag",
"(",
"s",
")",
"without",
"changing",
"others",
"."
] | def remove_flag(self, flag):
"""Unset the given string flag(s) without changing others."""
if self.get_flags() != '':
self.set_flags(''.join(set(self.get_flags()) - set(flag))) | [
"def",
"remove_flag",
"(",
"self",
",",
"flag",
")",
":",
"if",
"self",
".",
"get_flags",
"(",
")",
"!=",
"''",
":",
"self",
".",
"set_flags",
"(",
"''",
".",
"join",
"(",
"set",
"(",
"self",
".",
"get_flags",
"(",
")",
")",
"-",
"set",
"(",
"flag",
")",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/mailbox.py#L1507-L1510 |
||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/distributed/elastic/rendezvous/etcd_server.py | python | EtcdServer.stop | (self) | Stops the server and cleans up auto generated resources (e.g. data dir) | Stops the server and cleans up auto generated resources (e.g. data dir) | [
"Stops",
"the",
"server",
"and",
"cleans",
"up",
"auto",
"generated",
"resources",
"(",
"e",
".",
"g",
".",
"data",
"dir",
")"
] | def stop(self) -> None:
"""
Stops the server and cleans up auto generated resources (e.g. data dir)
"""
log.info("EtcdServer stop method called")
stop_etcd(self._etcd_proc, self._base_data_dir) | [
"def",
"stop",
"(",
"self",
")",
"->",
"None",
":",
"log",
".",
"info",
"(",
"\"EtcdServer stop method called\"",
")",
"stop_etcd",
"(",
"self",
".",
"_etcd_proc",
",",
"self",
".",
"_base_data_dir",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/elastic/rendezvous/etcd_server.py#L258-L263 |
||
dmlc/treelite | df56babb6a4a2d7c29d719c28ce53acfa7dbab3c | runtime/python/treelite_runtime/predictor.py | python | Predictor.predict | (self, dmat, verbose=False, pred_margin=False) | return res | Perform batch prediction with a 2D sparse data matrix. Worker threads will
internally divide up work for batch prediction. **Note that this function
may be called by only one thread at a time.**
Parameters
----------
dmat: object of type :py:class:`DMatrix`
batch of rows for which predictions will be made
verbose : :py:class:`bool <python:bool>`, optional
Whether to print extra messages during prediction
pred_margin: :py:class:`bool <python:bool>`, optional
whether to produce raw margins rather than transformed probabilities | Perform batch prediction with a 2D sparse data matrix. Worker threads will
internally divide up work for batch prediction. **Note that this function
may be called by only one thread at a time.** | [
"Perform",
"batch",
"prediction",
"with",
"a",
"2D",
"sparse",
"data",
"matrix",
".",
"Worker",
"threads",
"will",
"internally",
"divide",
"up",
"work",
"for",
"batch",
"prediction",
".",
"**",
"Note",
"that",
"this",
"function",
"may",
"be",
"called",
"by",
"only",
"one",
"thread",
"at",
"a",
"time",
".",
"**"
] | def predict(self, dmat, verbose=False, pred_margin=False):
"""
Perform batch prediction with a 2D sparse data matrix. Worker threads will
internally divide up work for batch prediction. **Note that this function
may be called by only one thread at a time.**
Parameters
----------
dmat: object of type :py:class:`DMatrix`
batch of rows for which predictions will be made
verbose : :py:class:`bool <python:bool>`, optional
Whether to print extra messages during prediction
pred_margin: :py:class:`bool <python:bool>`, optional
whether to produce raw margins rather than transformed probabilities
"""
if not isinstance(dmat, DMatrix):
raise TreeliteRuntimeError('dmat must be of type DMatrix')
result_size = ctypes.c_size_t()
_check_call(_LIB.TreelitePredictorQueryResultSize(
self.handle,
dmat.handle,
ctypes.byref(result_size)))
result_type = ctypes.c_char_p()
_check_call(_LIB.TreelitePredictorQueryLeafOutputType(
self.handle,
ctypes.byref(result_type)))
result_type = py_str(result_type.value)
out_result = np.zeros(result_size.value,
dtype=type_info_to_numpy_type(result_type),
order='C')
out_result_size = ctypes.c_size_t()
_check_call(_LIB.TreelitePredictorPredictBatch(
self.handle,
dmat.handle,
ctypes.c_int(1 if verbose else 0),
ctypes.c_int(1 if pred_margin else 0),
out_result.ctypes.data_as(ctypes.POINTER(type_info_to_ctypes_type(result_type))),
ctypes.byref(out_result_size)))
idx = int(out_result_size.value)
res = out_result[0:idx].reshape((dmat.shape[0], -1)).squeeze()
if self.num_class_ > 1 and dmat.shape[0] != idx:
res = res.reshape((-1, self.num_class_))
return res | [
"def",
"predict",
"(",
"self",
",",
"dmat",
",",
"verbose",
"=",
"False",
",",
"pred_margin",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"dmat",
",",
"DMatrix",
")",
":",
"raise",
"TreeliteRuntimeError",
"(",
"'dmat must be of type DMatrix'",
")",
"result_size",
"=",
"ctypes",
".",
"c_size_t",
"(",
")",
"_check_call",
"(",
"_LIB",
".",
"TreelitePredictorQueryResultSize",
"(",
"self",
".",
"handle",
",",
"dmat",
".",
"handle",
",",
"ctypes",
".",
"byref",
"(",
"result_size",
")",
")",
")",
"result_type",
"=",
"ctypes",
".",
"c_char_p",
"(",
")",
"_check_call",
"(",
"_LIB",
".",
"TreelitePredictorQueryLeafOutputType",
"(",
"self",
".",
"handle",
",",
"ctypes",
".",
"byref",
"(",
"result_type",
")",
")",
")",
"result_type",
"=",
"py_str",
"(",
"result_type",
".",
"value",
")",
"out_result",
"=",
"np",
".",
"zeros",
"(",
"result_size",
".",
"value",
",",
"dtype",
"=",
"type_info_to_numpy_type",
"(",
"result_type",
")",
",",
"order",
"=",
"'C'",
")",
"out_result_size",
"=",
"ctypes",
".",
"c_size_t",
"(",
")",
"_check_call",
"(",
"_LIB",
".",
"TreelitePredictorPredictBatch",
"(",
"self",
".",
"handle",
",",
"dmat",
".",
"handle",
",",
"ctypes",
".",
"c_int",
"(",
"1",
"if",
"verbose",
"else",
"0",
")",
",",
"ctypes",
".",
"c_int",
"(",
"1",
"if",
"pred_margin",
"else",
"0",
")",
",",
"out_result",
".",
"ctypes",
".",
"data_as",
"(",
"ctypes",
".",
"POINTER",
"(",
"type_info_to_ctypes_type",
"(",
"result_type",
")",
")",
")",
",",
"ctypes",
".",
"byref",
"(",
"out_result_size",
")",
")",
")",
"idx",
"=",
"int",
"(",
"out_result_size",
".",
"value",
")",
"res",
"=",
"out_result",
"[",
"0",
":",
"idx",
"]",
".",
"reshape",
"(",
"(",
"dmat",
".",
"shape",
"[",
"0",
"]",
",",
"-",
"1",
")",
")",
".",
"squeeze",
"(",
")",
"if",
"self",
".",
"num_class_",
">",
"1",
"and",
"dmat",
".",
"shape",
"[",
"0",
"]",
"!=",
"idx",
":",
"res",
"=",
"res",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"self",
".",
"num_class_",
")",
")",
"return",
"res"
] | https://github.com/dmlc/treelite/blob/df56babb6a4a2d7c29d719c28ce53acfa7dbab3c/runtime/python/treelite_runtime/predictor.py#L162-L204 |
|
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBBreakpoint.GetNumBreakpointLocationsFromEvent | (*args) | return _lldb.SBBreakpoint_GetNumBreakpointLocationsFromEvent(*args) | GetNumBreakpointLocationsFromEvent(SBEvent event_sp) -> uint32_t | GetNumBreakpointLocationsFromEvent(SBEvent event_sp) -> uint32_t | [
"GetNumBreakpointLocationsFromEvent",
"(",
"SBEvent",
"event_sp",
")",
"-",
">",
"uint32_t"
] | def GetNumBreakpointLocationsFromEvent(*args):
"""GetNumBreakpointLocationsFromEvent(SBEvent event_sp) -> uint32_t"""
return _lldb.SBBreakpoint_GetNumBreakpointLocationsFromEvent(*args) | [
"def",
"GetNumBreakpointLocationsFromEvent",
"(",
"*",
"args",
")",
":",
"return",
"_lldb",
".",
"SBBreakpoint_GetNumBreakpointLocationsFromEvent",
"(",
"*",
"args",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L1648-L1650 |
|
wenwei202/caffe | f54a74abaf6951d8485cbdcfa1d74a4c37839466 | scripts/cpp_lint.py | python | FindStartOfExpressionInLine | (line, endpos, depth, startchar, endchar) | return (-1, depth) | Find position at the matching startchar.
This is almost the reverse of FindEndOfExpressionInLine, but note
that the input position and returned position differs by 1.
Args:
line: a CleansedLines line.
endpos: start searching at this position.
depth: nesting level at endpos.
startchar: expression opening character.
endchar: expression closing character.
Returns:
On finding matching startchar: (index at matching startchar, 0)
Otherwise: (-1, new depth at beginning of this line) | Find position at the matching startchar. | [
"Find",
"position",
"at",
"the",
"matching",
"startchar",
"."
] | def FindStartOfExpressionInLine(line, endpos, depth, startchar, endchar):
"""Find position at the matching startchar.
This is almost the reverse of FindEndOfExpressionInLine, but note
that the input position and returned position differs by 1.
Args:
line: a CleansedLines line.
endpos: start searching at this position.
depth: nesting level at endpos.
startchar: expression opening character.
endchar: expression closing character.
Returns:
On finding matching startchar: (index at matching startchar, 0)
Otherwise: (-1, new depth at beginning of this line)
"""
for i in xrange(endpos, -1, -1):
if line[i] == endchar:
depth += 1
elif line[i] == startchar:
depth -= 1
if depth == 0:
return (i, 0)
return (-1, depth) | [
"def",
"FindStartOfExpressionInLine",
"(",
"line",
",",
"endpos",
",",
"depth",
",",
"startchar",
",",
"endchar",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"endpos",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"if",
"line",
"[",
"i",
"]",
"==",
"endchar",
":",
"depth",
"+=",
"1",
"elif",
"line",
"[",
"i",
"]",
"==",
"startchar",
":",
"depth",
"-=",
"1",
"if",
"depth",
"==",
"0",
":",
"return",
"(",
"i",
",",
"0",
")",
"return",
"(",
"-",
"1",
",",
"depth",
")"
] | https://github.com/wenwei202/caffe/blob/f54a74abaf6951d8485cbdcfa1d74a4c37839466/scripts/cpp_lint.py#L1300-L1324 |
|
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/client/timeline.py | python | Timeline._alloc_pid | (self) | return pid | Allocate a process Id. | Allocate a process Id. | [
"Allocate",
"a",
"process",
"Id",
"."
] | def _alloc_pid(self):
"""Allocate a process Id."""
pid = self._next_pid
self._next_pid += 1
return pid | [
"def",
"_alloc_pid",
"(",
"self",
")",
":",
"pid",
"=",
"self",
".",
"_next_pid",
"self",
".",
"_next_pid",
"+=",
"1",
"return",
"pid"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/client/timeline.py#L374-L378 |
|
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | Wrapping/Python/paraview/simple.py | python | OpenDataFile | (filename, **extraArgs) | return reader | Creates a reader to read the give file, if possible.
This uses extension matching to determine the best reader possible.
If a reader cannot be identified, then this returns None. | Creates a reader to read the give file, if possible.
This uses extension matching to determine the best reader possible.
If a reader cannot be identified, then this returns None. | [
"Creates",
"a",
"reader",
"to",
"read",
"the",
"give",
"file",
"if",
"possible",
".",
"This",
"uses",
"extension",
"matching",
"to",
"determine",
"the",
"best",
"reader",
"possible",
".",
"If",
"a",
"reader",
"cannot",
"be",
"identified",
"then",
"this",
"returns",
"None",
"."
] | def OpenDataFile(filename, **extraArgs):
"""Creates a reader to read the give file, if possible.
This uses extension matching to determine the best reader possible.
If a reader cannot be identified, then this returns None."""
session = servermanager.ActiveConnection.Session
reader_factor = servermanager.vtkSMProxyManager.GetProxyManager().GetReaderFactory()
if reader_factor.GetNumberOfRegisteredPrototypes() == 0:
reader_factor.UpdateAvailableReaders()
first_file = filename
if type(filename) == list:
first_file = filename[0]
if not reader_factor.TestFileReadability(first_file, session):
msg = "File not readable: %s " % first_file
raise RuntimeError (msg)
if not reader_factor.CanReadFile(first_file, session):
msg = "File not readable. No reader found for '%s' " % first_file
raise RuntimeError (msg)
prototype = servermanager.ProxyManager().GetPrototypeProxy(
reader_factor.GetReaderGroup(), reader_factor.GetReaderName())
xml_name = paraview.make_name_valid(prototype.GetXMLLabel())
reader_func = _create_func(xml_name, servermanager.sources)
pname = servermanager.vtkSMCoreUtilities.GetFileNameProperty(prototype)
if pname:
extraArgs[pname] = filename
reader = reader_func(**extraArgs)
return reader | [
"def",
"OpenDataFile",
"(",
"filename",
",",
"*",
"*",
"extraArgs",
")",
":",
"session",
"=",
"servermanager",
".",
"ActiveConnection",
".",
"Session",
"reader_factor",
"=",
"servermanager",
".",
"vtkSMProxyManager",
".",
"GetProxyManager",
"(",
")",
".",
"GetReaderFactory",
"(",
")",
"if",
"reader_factor",
".",
"GetNumberOfRegisteredPrototypes",
"(",
")",
"==",
"0",
":",
"reader_factor",
".",
"UpdateAvailableReaders",
"(",
")",
"first_file",
"=",
"filename",
"if",
"type",
"(",
"filename",
")",
"==",
"list",
":",
"first_file",
"=",
"filename",
"[",
"0",
"]",
"if",
"not",
"reader_factor",
".",
"TestFileReadability",
"(",
"first_file",
",",
"session",
")",
":",
"msg",
"=",
"\"File not readable: %s \"",
"%",
"first_file",
"raise",
"RuntimeError",
"(",
"msg",
")",
"if",
"not",
"reader_factor",
".",
"CanReadFile",
"(",
"first_file",
",",
"session",
")",
":",
"msg",
"=",
"\"File not readable. No reader found for '%s' \"",
"%",
"first_file",
"raise",
"RuntimeError",
"(",
"msg",
")",
"prototype",
"=",
"servermanager",
".",
"ProxyManager",
"(",
")",
".",
"GetPrototypeProxy",
"(",
"reader_factor",
".",
"GetReaderGroup",
"(",
")",
",",
"reader_factor",
".",
"GetReaderName",
"(",
")",
")",
"xml_name",
"=",
"paraview",
".",
"make_name_valid",
"(",
"prototype",
".",
"GetXMLLabel",
"(",
")",
")",
"reader_func",
"=",
"_create_func",
"(",
"xml_name",
",",
"servermanager",
".",
"sources",
")",
"pname",
"=",
"servermanager",
".",
"vtkSMCoreUtilities",
".",
"GetFileNameProperty",
"(",
"prototype",
")",
"if",
"pname",
":",
"extraArgs",
"[",
"pname",
"]",
"=",
"filename",
"reader",
"=",
"reader_func",
"(",
"*",
"*",
"extraArgs",
")",
"return",
"reader"
] | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/simple.py#L1190-L1215 |
|
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/data_flow_ops.py | python | StagingArea.put | (self, values, name=None) | Create an op that places a value into the staging area.
This operation will block if the `StagingArea` has reached
its capacity.
Args:
values: A single tensor, a list or tuple of tensors, or a dictionary with
tensor values. The number of elements must match the length of the
list provided to the dtypes argument when creating the StagingArea.
name: A name for the operation (optional).
Returns:
The created op.
Raises:
ValueError: If the number or type of inputs don't match the staging area. | Create an op that places a value into the staging area. | [
"Create",
"an",
"op",
"that",
"places",
"a",
"value",
"into",
"the",
"staging",
"area",
"."
] | def put(self, values, name=None):
"""Create an op that places a value into the staging area.
This operation will block if the `StagingArea` has reached
its capacity.
Args:
values: A single tensor, a list or tuple of tensors, or a dictionary with
tensor values. The number of elements must match the length of the
list provided to the dtypes argument when creating the StagingArea.
name: A name for the operation (optional).
Returns:
The created op.
Raises:
ValueError: If the number or type of inputs don't match the staging area.
"""
with ops.name_scope(name, "%s_put" % self._name,
self._scope_vals(values)) as scope:
if not isinstance(values, (list, tuple, dict)):
values = [values]
# Hard-code indices for this staging area
indices = list(six.moves.range(len(values)))
vals, _ = self._check_put_dtypes(values, indices)
with ops.colocate_with(self._coloc_op):
op = gen_data_flow_ops.stage(
values=vals,
shared_name=self._name,
name=scope,
capacity=self._capacity,
memory_limit=self._memory_limit)
return op | [
"def",
"put",
"(",
"self",
",",
"values",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"%s_put\"",
"%",
"self",
".",
"_name",
",",
"self",
".",
"_scope_vals",
"(",
"values",
")",
")",
"as",
"scope",
":",
"if",
"not",
"isinstance",
"(",
"values",
",",
"(",
"list",
",",
"tuple",
",",
"dict",
")",
")",
":",
"values",
"=",
"[",
"values",
"]",
"# Hard-code indices for this staging area",
"indices",
"=",
"list",
"(",
"six",
".",
"moves",
".",
"range",
"(",
"len",
"(",
"values",
")",
")",
")",
"vals",
",",
"_",
"=",
"self",
".",
"_check_put_dtypes",
"(",
"values",
",",
"indices",
")",
"with",
"ops",
".",
"colocate_with",
"(",
"self",
".",
"_coloc_op",
")",
":",
"op",
"=",
"gen_data_flow_ops",
".",
"stage",
"(",
"values",
"=",
"vals",
",",
"shared_name",
"=",
"self",
".",
"_name",
",",
"name",
"=",
"scope",
",",
"capacity",
"=",
"self",
".",
"_capacity",
",",
"memory_limit",
"=",
"self",
".",
"_memory_limit",
")",
"return",
"op"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/data_flow_ops.py#L1848-L1884 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/flatnotebook.py | python | FlatNotebook.GetGradientColourBorder | (self) | return self._pages._colorBorder | Gets the tab border colour. | Gets the tab border colour. | [
"Gets",
"the",
"tab",
"border",
"colour",
"."
] | def GetGradientColourBorder(self):
""" Gets the tab border colour. """
return self._pages._colorBorder | [
"def",
"GetGradientColourBorder",
"(",
"self",
")",
":",
"return",
"self",
".",
"_pages",
".",
"_colorBorder"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/flatnotebook.py#L3658-L3661 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py3/prompt_toolkit/input/win32_pipe.py | python | Win32PipeInput.attach | (self, input_ready_callback: Callable[[], None]) | return attach_win32_input(self, input_ready_callback) | Return a context manager that makes this input active in the current
event loop. | Return a context manager that makes this input active in the current
event loop. | [
"Return",
"a",
"context",
"manager",
"that",
"makes",
"this",
"input",
"active",
"in",
"the",
"current",
"event",
"loop",
"."
] | def attach(self, input_ready_callback: Callable[[], None]) -> ContextManager[None]:
"""
Return a context manager that makes this input active in the current
event loop.
"""
return attach_win32_input(self, input_ready_callback) | [
"def",
"attach",
"(",
"self",
",",
"input_ready_callback",
":",
"Callable",
"[",
"[",
"]",
",",
"None",
"]",
")",
"->",
"ContextManager",
"[",
"None",
"]",
":",
"return",
"attach_win32_input",
"(",
"self",
",",
"input_ready_callback",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/win32_pipe.py#L68-L73 |
|
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/math_ops.py | python | not_equal | (x, y, name=None) | return gen_math_ops.not_equal(x, y, name=name) | Returns the truth value of (x != y) element-wise.
Performs a [broadcast](
https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) with the
arguments and then an element-wise inequality comparison, returning a Tensor
of boolean values.
For example:
>>> x = tf.constant([2, 4])
>>> y = tf.constant(2)
>>> tf.math.not_equal(x, y)
<tf.Tensor: shape=(2,), dtype=bool, numpy=array([False, True])>
>>> x = tf.constant([2, 4])
>>> y = tf.constant([2, 4])
>>> tf.math.not_equal(x, y)
<tf.Tensor: shape=(2,), dtype=bool, numpy=array([False, False])>
Args:
x: A `tf.Tensor` or `tf.sparse.SparseTensor` or `tf.IndexedSlices`.
y: A `tf.Tensor` or `tf.sparse.SparseTensor` or `tf.IndexedSlices`.
name: A name for the operation (optional).
Returns:
A `tf.Tensor` of type bool with the same size as that of x or y.
Raises:
`tf.errors.InvalidArgumentError`: If shapes of arguments are incompatible | Returns the truth value of (x != y) element-wise. | [
"Returns",
"the",
"truth",
"value",
"of",
"(",
"x",
"!",
"=",
"y",
")",
"element",
"-",
"wise",
"."
] | def not_equal(x, y, name=None):
"""Returns the truth value of (x != y) element-wise.
Performs a [broadcast](
https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) with the
arguments and then an element-wise inequality comparison, returning a Tensor
of boolean values.
For example:
>>> x = tf.constant([2, 4])
>>> y = tf.constant(2)
>>> tf.math.not_equal(x, y)
<tf.Tensor: shape=(2,), dtype=bool, numpy=array([False, True])>
>>> x = tf.constant([2, 4])
>>> y = tf.constant([2, 4])
>>> tf.math.not_equal(x, y)
<tf.Tensor: shape=(2,), dtype=bool, numpy=array([False, False])>
Args:
x: A `tf.Tensor` or `tf.sparse.SparseTensor` or `tf.IndexedSlices`.
y: A `tf.Tensor` or `tf.sparse.SparseTensor` or `tf.IndexedSlices`.
name: A name for the operation (optional).
Returns:
A `tf.Tensor` of type bool with the same size as that of x or y.
Raises:
`tf.errors.InvalidArgumentError`: If shapes of arguments are incompatible
"""
return gen_math_ops.not_equal(x, y, name=name) | [
"def",
"not_equal",
"(",
"x",
",",
"y",
",",
"name",
"=",
"None",
")",
":",
"return",
"gen_math_ops",
".",
"not_equal",
"(",
"x",
",",
"y",
",",
"name",
"=",
"name",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/math_ops.py#L1928-L1959 |
|
bitconch/bitconch-core | 5537f3215b3e3b76f6720d6f908676a6c34bc5db | deploy-morgan.py | python | add_submodules | () | Add submodule into vendor | Add submodule into vendor | [
"Add",
"submodule",
"into",
"vendor"
] | def add_submodules():
"""
Add submodule into vendor
"""
if not os.path.exists(f"vendor/morgan"):
prnt_run("Use git to add the submodules")
execute_shell("git submodule add https://github.com/luhuimao/morgan.git", silent=False, cwd="vendor") | [
"def",
"add_submodules",
"(",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"f\"vendor/morgan\"",
")",
":",
"prnt_run",
"(",
"\"Use git to add the submodules\"",
")",
"execute_shell",
"(",
"\"git submodule add https://github.com/luhuimao/morgan.git\"",
",",
"silent",
"=",
"False",
",",
"cwd",
"=",
"\"vendor\"",
")"
] | https://github.com/bitconch/bitconch-core/blob/5537f3215b3e3b76f6720d6f908676a6c34bc5db/deploy-morgan.py#L98-L104 |
||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/ops/rnn_cell.py | python | OutputProjectionWrapper.__init__ | (self, cell, output_size) | Create a cell with output projection.
Args:
cell: an RNNCell, a projection to output_size is added to it.
output_size: integer, the size of the output after projection.
Raises:
TypeError: if cell is not an RNNCell.
ValueError: if output_size is not positive. | Create a cell with output projection. | [
"Create",
"a",
"cell",
"with",
"output",
"projection",
"."
] | def __init__(self, cell, output_size):
"""Create a cell with output projection.
Args:
cell: an RNNCell, a projection to output_size is added to it.
output_size: integer, the size of the output after projection.
Raises:
TypeError: if cell is not an RNNCell.
ValueError: if output_size is not positive.
"""
if not isinstance(cell, RNNCell):
raise TypeError("The parameter cell is not RNNCell.")
if output_size < 1:
raise ValueError("Parameter output_size must be > 0: %d." % output_size)
self._cell = cell
self._output_size = output_size | [
"def",
"__init__",
"(",
"self",
",",
"cell",
",",
"output_size",
")",
":",
"if",
"not",
"isinstance",
"(",
"cell",
",",
"RNNCell",
")",
":",
"raise",
"TypeError",
"(",
"\"The parameter cell is not RNNCell.\"",
")",
"if",
"output_size",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"Parameter output_size must be > 0: %d.\"",
"%",
"output_size",
")",
"self",
".",
"_cell",
"=",
"cell",
"self",
".",
"_output_size",
"=",
"output_size"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/rnn_cell.py#L558-L574 |
||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/io/matlab/mio5_params.py | python | _convert_codecs | (template, byte_order) | return codecs.copy() | Convert codec template mapping to byte order
Set codecs not on this system to None
Parameters
----------
template : mapping
key, value are respectively codec name, and root name for codec
(without byte order suffix)
byte_order : {'<', '>'}
code for little or big endian
Returns
-------
codecs : dict
key, value are name, codec (as in .encode(codec)) | Convert codec template mapping to byte order | [
"Convert",
"codec",
"template",
"mapping",
"to",
"byte",
"order"
] | def _convert_codecs(template, byte_order):
''' Convert codec template mapping to byte order
Set codecs not on this system to None
Parameters
----------
template : mapping
key, value are respectively codec name, and root name for codec
(without byte order suffix)
byte_order : {'<', '>'}
code for little or big endian
Returns
-------
codecs : dict
key, value are name, codec (as in .encode(codec))
'''
codecs = {}
postfix = byte_order == '<' and '_le' or '_be'
for k, v in template.items():
codec = v['codec']
try:
" ".encode(codec)
except LookupError:
codecs[k] = None
continue
if v['width'] > 1:
codec += postfix
codecs[k] = codec
return codecs.copy() | [
"def",
"_convert_codecs",
"(",
"template",
",",
"byte_order",
")",
":",
"codecs",
"=",
"{",
"}",
"postfix",
"=",
"byte_order",
"==",
"'<'",
"and",
"'_le'",
"or",
"'_be'",
"for",
"k",
",",
"v",
"in",
"template",
".",
"items",
"(",
")",
":",
"codec",
"=",
"v",
"[",
"'codec'",
"]",
"try",
":",
"\" \"",
".",
"encode",
"(",
"codec",
")",
"except",
"LookupError",
":",
"codecs",
"[",
"k",
"]",
"=",
"None",
"continue",
"if",
"v",
"[",
"'width'",
"]",
">",
"1",
":",
"codec",
"+=",
"postfix",
"codecs",
"[",
"k",
"]",
"=",
"codec",
"return",
"codecs",
".",
"copy",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/io/matlab/mio5_params.py#L171-L201 |
|
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBAddress.OffsetAddress | (self, offset) | return _lldb.SBAddress_OffsetAddress(self, offset) | OffsetAddress(SBAddress self, lldb::addr_t offset) -> bool | OffsetAddress(SBAddress self, lldb::addr_t offset) -> bool | [
"OffsetAddress",
"(",
"SBAddress",
"self",
"lldb",
"::",
"addr_t",
"offset",
")",
"-",
">",
"bool"
] | def OffsetAddress(self, offset):
"""OffsetAddress(SBAddress self, lldb::addr_t offset) -> bool"""
return _lldb.SBAddress_OffsetAddress(self, offset) | [
"def",
"OffsetAddress",
"(",
"self",
",",
"offset",
")",
":",
"return",
"_lldb",
".",
"SBAddress_OffsetAddress",
"(",
"self",
",",
"offset",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L914-L916 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/cgitb.py | python | enable | (display=1, logdir=None, context=5, format="html") | Install an exception handler that formats tracebacks as HTML.
The optional argument 'display' can be set to 0 to suppress sending the
traceback to the browser, and 'logdir' can be set to a directory to cause
tracebacks to be written to files there. | Install an exception handler that formats tracebacks as HTML. | [
"Install",
"an",
"exception",
"handler",
"that",
"formats",
"tracebacks",
"as",
"HTML",
"."
] | def enable(display=1, logdir=None, context=5, format="html"):
"""Install an exception handler that formats tracebacks as HTML.
The optional argument 'display' can be set to 0 to suppress sending the
traceback to the browser, and 'logdir' can be set to a directory to cause
tracebacks to be written to files there."""
sys.excepthook = Hook(display=display, logdir=logdir,
context=context, format=format) | [
"def",
"enable",
"(",
"display",
"=",
"1",
",",
"logdir",
"=",
"None",
",",
"context",
"=",
"5",
",",
"format",
"=",
"\"html\"",
")",
":",
"sys",
".",
"excepthook",
"=",
"Hook",
"(",
"display",
"=",
"display",
",",
"logdir",
"=",
"logdir",
",",
"context",
"=",
"context",
",",
"format",
"=",
"format",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/cgitb.py#L314-L321 |
||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/packages/chardet/chardistribution.py | python | CharDistributionAnalysis.get_confidence | (self) | return SURE_YES | return confidence based on existing data | return confidence based on existing data | [
"return",
"confidence",
"based",
"on",
"existing",
"data"
] | def get_confidence(self):
"""return confidence based on existing data"""
# if we didn't receive any character in our consideration range,
# return negative answer
if self._mTotalChars <= 0 or self._mFreqChars <= MINIMUM_DATA_THRESHOLD:
return SURE_NO
if self._mTotalChars != self._mFreqChars:
r = (self._mFreqChars / ((self._mTotalChars - self._mFreqChars)
* self._mTypicalDistributionRatio))
if r < SURE_YES:
return r
# normalize confidence (we don't want to be 100% sure)
return SURE_YES | [
"def",
"get_confidence",
"(",
"self",
")",
":",
"# if we didn't receive any character in our consideration range,",
"# return negative answer",
"if",
"self",
".",
"_mTotalChars",
"<=",
"0",
"or",
"self",
".",
"_mFreqChars",
"<=",
"MINIMUM_DATA_THRESHOLD",
":",
"return",
"SURE_NO",
"if",
"self",
".",
"_mTotalChars",
"!=",
"self",
".",
"_mFreqChars",
":",
"r",
"=",
"(",
"self",
".",
"_mFreqChars",
"/",
"(",
"(",
"self",
".",
"_mTotalChars",
"-",
"self",
".",
"_mFreqChars",
")",
"*",
"self",
".",
"_mTypicalDistributionRatio",
")",
")",
"if",
"r",
"<",
"SURE_YES",
":",
"return",
"r",
"# normalize confidence (we don't want to be 100% sure)",
"return",
"SURE_YES"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/packages/chardet/chardistribution.py#L82-L96 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/calendar.py | python | CalendarCtrlBase.GetHeaderColourFg | (*args, **kwargs) | return _calendar.CalendarCtrlBase_GetHeaderColourFg(*args, **kwargs) | GetHeaderColourFg(self) -> Colour
Header colours are used for painting the weekdays at the top. | GetHeaderColourFg(self) -> Colour | [
"GetHeaderColourFg",
"(",
"self",
")",
"-",
">",
"Colour"
] | def GetHeaderColourFg(*args, **kwargs):
"""
GetHeaderColourFg(self) -> Colour
Header colours are used for painting the weekdays at the top.
"""
return _calendar.CalendarCtrlBase_GetHeaderColourFg(*args, **kwargs) | [
"def",
"GetHeaderColourFg",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_calendar",
".",
"CalendarCtrlBase_GetHeaderColourFg",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/calendar.py#L403-L409 |
|
wheybags/freeablo | 921ac20be95828460ccc184a9de11eca5c7c0519 | extern/SDL_image/external/libwebp-0.3.0/swig/libwebp.py | python | WebPDecodeRGB | (*args) | return _libwebp.WebPDecodeRGB(*args) | WebPDecodeRGB(uint8_t data) -> (rgb, width, height) | WebPDecodeRGB(uint8_t data) -> (rgb, width, height) | [
"WebPDecodeRGB",
"(",
"uint8_t",
"data",
")",
"-",
">",
"(",
"rgb",
"width",
"height",
")"
] | def WebPDecodeRGB(*args):
"""WebPDecodeRGB(uint8_t data) -> (rgb, width, height)"""
return _libwebp.WebPDecodeRGB(*args) | [
"def",
"WebPDecodeRGB",
"(",
"*",
"args",
")",
":",
"return",
"_libwebp",
".",
"WebPDecodeRGB",
"(",
"*",
"args",
")"
] | https://github.com/wheybags/freeablo/blob/921ac20be95828460ccc184a9de11eca5c7c0519/extern/SDL_image/external/libwebp-0.3.0/swig/libwebp.py#L79-L81 |
|
envoyproxy/envoy-wasm | ab5d9381fdf92a1efa0b87cff80036b5b3e81198 | tools/proto_format/proto_sync.py | python | GetImportDeps | (proto_path) | return imports | Obtain the Bazel dependencies for the import paths from a .proto file.
Args:
proto_path: path to .proto.
Returns:
A list of Bazel targets reflecting the imports in the .proto at proto_path. | Obtain the Bazel dependencies for the import paths from a .proto file. | [
"Obtain",
"the",
"Bazel",
"dependencies",
"for",
"the",
"import",
"paths",
"from",
"a",
".",
"proto",
"file",
"."
] | def GetImportDeps(proto_path):
"""Obtain the Bazel dependencies for the import paths from a .proto file.
Args:
proto_path: path to .proto.
Returns:
A list of Bazel targets reflecting the imports in the .proto at proto_path.
"""
imports = []
with open(proto_path, 'r', encoding='utf8') as f:
for line in f:
match = re.match(IMPORT_REGEX, line)
if match:
import_path = match.group(1)
# We can ignore imports provided implicitly by api_proto_package().
if any(import_path.startswith(p) for p in API_BUILD_SYSTEM_IMPORT_PREFIXES):
continue
# Special case handling for UDPA annotations.
if import_path.startswith('udpa/annotations/'):
imports.append('@com_github_cncf_udpa//udpa/annotations:pkg')
continue
# Special case handling for UDPA core.
if import_path.startswith('udpa/core/v1/'):
imports.append('@com_github_cncf_udpa//udpa/core/v1:pkg')
continue
# Explicit remapping for external deps, compute paths for envoy/*.
if import_path in external_proto_deps.EXTERNAL_PROTO_IMPORT_BAZEL_DEP_MAP:
imports.append(external_proto_deps.EXTERNAL_PROTO_IMPORT_BAZEL_DEP_MAP[import_path])
continue
if import_path.startswith('envoy/'):
# Ignore package internal imports.
if os.path.dirname(proto_path).endswith(os.path.dirname(import_path)):
continue
imports.append('//%s:pkg' % os.path.dirname(import_path))
continue
raise ProtoSyncError(
'Unknown import path mapping for %s, please update the mappings in tools/proto_format/proto_sync.py.\n'
% import_path)
return imports | [
"def",
"GetImportDeps",
"(",
"proto_path",
")",
":",
"imports",
"=",
"[",
"]",
"with",
"open",
"(",
"proto_path",
",",
"'r'",
",",
"encoding",
"=",
"'utf8'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"match",
"=",
"re",
".",
"match",
"(",
"IMPORT_REGEX",
",",
"line",
")",
"if",
"match",
":",
"import_path",
"=",
"match",
".",
"group",
"(",
"1",
")",
"# We can ignore imports provided implicitly by api_proto_package().",
"if",
"any",
"(",
"import_path",
".",
"startswith",
"(",
"p",
")",
"for",
"p",
"in",
"API_BUILD_SYSTEM_IMPORT_PREFIXES",
")",
":",
"continue",
"# Special case handling for UDPA annotations.",
"if",
"import_path",
".",
"startswith",
"(",
"'udpa/annotations/'",
")",
":",
"imports",
".",
"append",
"(",
"'@com_github_cncf_udpa//udpa/annotations:pkg'",
")",
"continue",
"# Special case handling for UDPA core.",
"if",
"import_path",
".",
"startswith",
"(",
"'udpa/core/v1/'",
")",
":",
"imports",
".",
"append",
"(",
"'@com_github_cncf_udpa//udpa/core/v1:pkg'",
")",
"continue",
"# Explicit remapping for external deps, compute paths for envoy/*.",
"if",
"import_path",
"in",
"external_proto_deps",
".",
"EXTERNAL_PROTO_IMPORT_BAZEL_DEP_MAP",
":",
"imports",
".",
"append",
"(",
"external_proto_deps",
".",
"EXTERNAL_PROTO_IMPORT_BAZEL_DEP_MAP",
"[",
"import_path",
"]",
")",
"continue",
"if",
"import_path",
".",
"startswith",
"(",
"'envoy/'",
")",
":",
"# Ignore package internal imports.",
"if",
"os",
".",
"path",
".",
"dirname",
"(",
"proto_path",
")",
".",
"endswith",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"import_path",
")",
")",
":",
"continue",
"imports",
".",
"append",
"(",
"'//%s:pkg'",
"%",
"os",
".",
"path",
".",
"dirname",
"(",
"import_path",
")",
")",
"continue",
"raise",
"ProtoSyncError",
"(",
"'Unknown import path mapping for %s, please update the mappings in tools/proto_format/proto_sync.py.\\n'",
"%",
"import_path",
")",
"return",
"imports"
] | https://github.com/envoyproxy/envoy-wasm/blob/ab5d9381fdf92a1efa0b87cff80036b5b3e81198/tools/proto_format/proto_sync.py#L184-L223 |
|
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/_extends/parse/standard_method.py | python | getitem | (data, index) | return data.__getitem__(index) | Implementation of `getitem`. | Implementation of `getitem`. | [
"Implementation",
"of",
"getitem",
"."
] | def getitem(data, index):
"""Implementation of `getitem`."""
return data.__getitem__(index) | [
"def",
"getitem",
"(",
"data",
",",
"index",
")",
":",
"return",
"data",
".",
"__getitem__",
"(",
"index",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/parse/standard_method.py#L1408-L1410 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/calendar.py | python | HTMLCalendar.formatmonth | (self, theyear, themonth, withyear=True) | return ''.join(v) | Return a formatted month as a table. | Return a formatted month as a table. | [
"Return",
"a",
"formatted",
"month",
"as",
"a",
"table",
"."
] | def formatmonth(self, theyear, themonth, withyear=True):
"""
Return a formatted month as a table.
"""
v = []
a = v.append
a('<table border="0" cellpadding="0" cellspacing="0" class="month">')
a('\n')
a(self.formatmonthname(theyear, themonth, withyear=withyear))
a('\n')
a(self.formatweekheader())
a('\n')
for week in self.monthdays2calendar(theyear, themonth):
a(self.formatweek(week))
a('\n')
a('</table>')
a('\n')
return ''.join(v) | [
"def",
"formatmonth",
"(",
"self",
",",
"theyear",
",",
"themonth",
",",
"withyear",
"=",
"True",
")",
":",
"v",
"=",
"[",
"]",
"a",
"=",
"v",
".",
"append",
"a",
"(",
"'<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"month\">'",
")",
"a",
"(",
"'\\n'",
")",
"a",
"(",
"self",
".",
"formatmonthname",
"(",
"theyear",
",",
"themonth",
",",
"withyear",
"=",
"withyear",
")",
")",
"a",
"(",
"'\\n'",
")",
"a",
"(",
"self",
".",
"formatweekheader",
"(",
")",
")",
"a",
"(",
"'\\n'",
")",
"for",
"week",
"in",
"self",
".",
"monthdays2calendar",
"(",
"theyear",
",",
"themonth",
")",
":",
"a",
"(",
"self",
".",
"formatweek",
"(",
"week",
")",
")",
"a",
"(",
"'\\n'",
")",
"a",
"(",
"'</table>'",
")",
"a",
"(",
"'\\n'",
")",
"return",
"''",
".",
"join",
"(",
"v",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/calendar.py#L424-L441 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/monkey.py | python | patch_func | (replacement, target_mod, func_name) | Patch func_name in target_mod with replacement
Important - original must be resolved by name to avoid
patching an already patched function. | Patch func_name in target_mod with replacement | [
"Patch",
"func_name",
"in",
"target_mod",
"with",
"replacement"
] | def patch_func(replacement, target_mod, func_name):
"""
Patch func_name in target_mod with replacement
Important - original must be resolved by name to avoid
patching an already patched function.
"""
original = getattr(target_mod, func_name)
# set the 'unpatched' attribute on the replacement to
# point to the original.
vars(replacement).setdefault('unpatched', original)
# replace the function in the original module
setattr(target_mod, func_name, replacement) | [
"def",
"patch_func",
"(",
"replacement",
",",
"target_mod",
",",
"func_name",
")",
":",
"original",
"=",
"getattr",
"(",
"target_mod",
",",
"func_name",
")",
"# set the 'unpatched' attribute on the replacement to",
"# point to the original.",
"vars",
"(",
"replacement",
")",
".",
"setdefault",
"(",
"'unpatched'",
",",
"original",
")",
"# replace the function in the original module",
"setattr",
"(",
"target_mod",
",",
"func_name",
",",
"replacement",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/monkey.py#L109-L123 |
||
sigmaai/self-driving-golf-cart | 8d891600af3d851add27a10ae45cf3c2108bb87c | ros/src/ros_carla_bridge/carla_ros_bridge/src/carla_ros_bridge/ego_vehicle.py | python | EgoVehicle.__init__ | (self, carla_actor, parent, communication, vehicle_control_applied_callback) | Constructor
:param carla_actor: carla actor object
:type carla_actor: carla.Actor
:param parent: the parent of this
:type parent: carla_ros_bridge.Parent
:param communication: communication-handle
:type communication: carla_ros_bridge.communication | Constructor | [
"Constructor"
] | def __init__(self, carla_actor, parent, communication, vehicle_control_applied_callback):
"""
Constructor
:param carla_actor: carla actor object
:type carla_actor: carla.Actor
:param parent: the parent of this
:type parent: carla_ros_bridge.Parent
:param communication: communication-handle
:type communication: carla_ros_bridge.communication
"""
super(EgoVehicle, self).__init__(carla_actor=carla_actor,
parent=parent,
communication=communication,
prefix=carla_actor.attributes.get('role_name'))
self.vehicle_info_published = False
self.vehicle_control_override = False
self._vehicle_control_applied_callback = vehicle_control_applied_callback
self.control_subscriber = rospy.Subscriber(
self.get_topic_prefix() + "/vehicle_control_cmd",
CarlaEgoVehicleControl,
lambda data: self.control_command_updated(data, manual_override=False))
self.manual_control_subscriber = rospy.Subscriber(
self.get_topic_prefix() + "/vehicle_control_cmd_manual",
CarlaEgoVehicleControl,
lambda data: self.control_command_updated(data, manual_override=True))
self.control_override_subscriber = rospy.Subscriber(
self.get_topic_prefix() + "/vehicle_control_manual_override",
Bool, self.control_command_override)
self.enable_autopilot_subscriber = rospy.Subscriber(
self.get_topic_prefix() + "/enable_autopilot",
Bool, self.enable_autopilot_updated)
self.twist_control_subscriber = rospy.Subscriber(
self.get_topic_prefix() + "/twist_cmd",
Twist, self.twist_command_updated) | [
"def",
"__init__",
"(",
"self",
",",
"carla_actor",
",",
"parent",
",",
"communication",
",",
"vehicle_control_applied_callback",
")",
":",
"super",
"(",
"EgoVehicle",
",",
"self",
")",
".",
"__init__",
"(",
"carla_actor",
"=",
"carla_actor",
",",
"parent",
"=",
"parent",
",",
"communication",
"=",
"communication",
",",
"prefix",
"=",
"carla_actor",
".",
"attributes",
".",
"get",
"(",
"'role_name'",
")",
")",
"self",
".",
"vehicle_info_published",
"=",
"False",
"self",
".",
"vehicle_control_override",
"=",
"False",
"self",
".",
"_vehicle_control_applied_callback",
"=",
"vehicle_control_applied_callback",
"self",
".",
"control_subscriber",
"=",
"rospy",
".",
"Subscriber",
"(",
"self",
".",
"get_topic_prefix",
"(",
")",
"+",
"\"/vehicle_control_cmd\"",
",",
"CarlaEgoVehicleControl",
",",
"lambda",
"data",
":",
"self",
".",
"control_command_updated",
"(",
"data",
",",
"manual_override",
"=",
"False",
")",
")",
"self",
".",
"manual_control_subscriber",
"=",
"rospy",
".",
"Subscriber",
"(",
"self",
".",
"get_topic_prefix",
"(",
")",
"+",
"\"/vehicle_control_cmd_manual\"",
",",
"CarlaEgoVehicleControl",
",",
"lambda",
"data",
":",
"self",
".",
"control_command_updated",
"(",
"data",
",",
"manual_override",
"=",
"True",
")",
")",
"self",
".",
"control_override_subscriber",
"=",
"rospy",
".",
"Subscriber",
"(",
"self",
".",
"get_topic_prefix",
"(",
")",
"+",
"\"/vehicle_control_manual_override\"",
",",
"Bool",
",",
"self",
".",
"control_command_override",
")",
"self",
".",
"enable_autopilot_subscriber",
"=",
"rospy",
".",
"Subscriber",
"(",
"self",
".",
"get_topic_prefix",
"(",
")",
"+",
"\"/enable_autopilot\"",
",",
"Bool",
",",
"self",
".",
"enable_autopilot_updated",
")",
"self",
".",
"twist_control_subscriber",
"=",
"rospy",
".",
"Subscriber",
"(",
"self",
".",
"get_topic_prefix",
"(",
")",
"+",
"\"/twist_cmd\"",
",",
"Twist",
",",
"self",
".",
"twist_command_updated",
")"
] | https://github.com/sigmaai/self-driving-golf-cart/blob/8d891600af3d851add27a10ae45cf3c2108bb87c/ros/src/ros_carla_bridge/carla_ros_bridge/src/carla_ros_bridge/ego_vehicle.py#L37-L77 |
||
google/or-tools | 2cb85b4eead4c38e1c54b48044f92087cf165bce | ortools/sat/python/cp_model.py | python | CpModel.ClearHints | (self) | Remove any solution hint from the model. | Remove any solution hint from the model. | [
"Remove",
"any",
"solution",
"hint",
"from",
"the",
"model",
"."
] | def ClearHints(self):
"""Remove any solution hint from the model."""
self.__model.ClearField('solution_hint') | [
"def",
"ClearHints",
"(",
"self",
")",
":",
"self",
".",
"__model",
".",
"ClearField",
"(",
"'solution_hint'",
")"
] | https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/ortools/sat/python/cp_model.py#L1994-L1996 |
||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | python/mozbuild/mozbuild/compilation/warnings.py | python | WarningsCollector.process_line | (self, line) | return warning | Take a line of text and process it for a warning. | Take a line of text and process it for a warning. | [
"Take",
"a",
"line",
"of",
"text",
"and",
"process",
"it",
"for",
"a",
"warning",
"."
] | def process_line(self, line):
"""Take a line of text and process it for a warning."""
filtered = RE_STRIP_COLORS.sub('', line)
# Clang warnings in files included from the one(s) being compiled will
# start with "In file included from /path/to/file:line:". Here, we
# record those.
if filtered.startswith(IN_FILE_INCLUDED_FROM):
included_from = filtered[len(IN_FILE_INCLUDED_FROM):]
parts = included_from.split(':')
self.included_from.append(parts[0])
return
warning = CompilerWarning()
filename = None
# TODO make more efficient so we run minimal regexp matches.
match_clang = RE_CLANG_WARNING.match(filtered)
match_msvc = RE_MSVC_WARNING.match(filtered)
if match_clang:
d = match_clang.groupdict()
filename = d['file']
warning['line'] = int(d['line'])
warning['column'] = int(d['column'])
warning['flag'] = d['flag']
warning['message'] = d['message'].rstrip()
elif match_msvc:
d = match_msvc.groupdict()
filename = d['file']
warning['line'] = int(d['line'])
warning['flag'] = d['flag']
warning['message'] = d['message'].rstrip()
else:
self.included_from = []
return None
filename = os.path.normpath(filename)
# Sometimes we get relative includes. These typically point to files in
# the object directory. We try to resolve the relative path.
if not os.path.isabs(filename):
filename = self._normalize_relative_path(filename)
if not os.path.exists(filename) and self.resolve_files:
raise Exception('Could not find file containing warning: %s' %
filename)
warning['filename'] = filename
self.database.insert(warning, compute_hash=self.resolve_files)
return warning | [
"def",
"process_line",
"(",
"self",
",",
"line",
")",
":",
"filtered",
"=",
"RE_STRIP_COLORS",
".",
"sub",
"(",
"''",
",",
"line",
")",
"# Clang warnings in files included from the one(s) being compiled will",
"# start with \"In file included from /path/to/file:line:\". Here, we",
"# record those.",
"if",
"filtered",
".",
"startswith",
"(",
"IN_FILE_INCLUDED_FROM",
")",
":",
"included_from",
"=",
"filtered",
"[",
"len",
"(",
"IN_FILE_INCLUDED_FROM",
")",
":",
"]",
"parts",
"=",
"included_from",
".",
"split",
"(",
"':'",
")",
"self",
".",
"included_from",
".",
"append",
"(",
"parts",
"[",
"0",
"]",
")",
"return",
"warning",
"=",
"CompilerWarning",
"(",
")",
"filename",
"=",
"None",
"# TODO make more efficient so we run minimal regexp matches.",
"match_clang",
"=",
"RE_CLANG_WARNING",
".",
"match",
"(",
"filtered",
")",
"match_msvc",
"=",
"RE_MSVC_WARNING",
".",
"match",
"(",
"filtered",
")",
"if",
"match_clang",
":",
"d",
"=",
"match_clang",
".",
"groupdict",
"(",
")",
"filename",
"=",
"d",
"[",
"'file'",
"]",
"warning",
"[",
"'line'",
"]",
"=",
"int",
"(",
"d",
"[",
"'line'",
"]",
")",
"warning",
"[",
"'column'",
"]",
"=",
"int",
"(",
"d",
"[",
"'column'",
"]",
")",
"warning",
"[",
"'flag'",
"]",
"=",
"d",
"[",
"'flag'",
"]",
"warning",
"[",
"'message'",
"]",
"=",
"d",
"[",
"'message'",
"]",
".",
"rstrip",
"(",
")",
"elif",
"match_msvc",
":",
"d",
"=",
"match_msvc",
".",
"groupdict",
"(",
")",
"filename",
"=",
"d",
"[",
"'file'",
"]",
"warning",
"[",
"'line'",
"]",
"=",
"int",
"(",
"d",
"[",
"'line'",
"]",
")",
"warning",
"[",
"'flag'",
"]",
"=",
"d",
"[",
"'flag'",
"]",
"warning",
"[",
"'message'",
"]",
"=",
"d",
"[",
"'message'",
"]",
".",
"rstrip",
"(",
")",
"else",
":",
"self",
".",
"included_from",
"=",
"[",
"]",
"return",
"None",
"filename",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"filename",
")",
"# Sometimes we get relative includes. These typically point to files in",
"# the object directory. We try to resolve the relative path.",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"filename",
")",
":",
"filename",
"=",
"self",
".",
"_normalize_relative_path",
"(",
"filename",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
"and",
"self",
".",
"resolve_files",
":",
"raise",
"Exception",
"(",
"'Could not find file containing warning: %s'",
"%",
"filename",
")",
"warning",
"[",
"'filename'",
"]",
"=",
"filename",
"self",
".",
"database",
".",
"insert",
"(",
"warning",
",",
"compute_hash",
"=",
"self",
".",
"resolve_files",
")",
"return",
"warning"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/mozbuild/mozbuild/compilation/warnings.py#L299-L357 |
|
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_op_impl/tbe/in_top_k.py | python | _in_top_k_tbe | () | return | InTopK TBE register | InTopK TBE register | [
"InTopK",
"TBE",
"register"
] | def _in_top_k_tbe():
"""InTopK TBE register"""
return | [
"def",
"_in_top_k_tbe",
"(",
")",
":",
"return"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/in_top_k.py#L35-L37 |
|
protocolbuffers/protobuf | b5ab0b7a18b7336c60130f4ddb2d97c51792f896 | python/google/protobuf/descriptor.py | python | EnumDescriptor.__init__ | (self, name, full_name, filename, values,
containing_type=None, options=None,
serialized_options=None, file=None, # pylint: disable=redefined-builtin
serialized_start=None, serialized_end=None, create_key=None) | Arguments are as described in the attribute description above.
Note that filename is an obsolete argument, that is not used anymore.
Please use file.name to access this as an attribute. | Arguments are as described in the attribute description above. | [
"Arguments",
"are",
"as",
"described",
"in",
"the",
"attribute",
"description",
"above",
"."
] | def __init__(self, name, full_name, filename, values,
containing_type=None, options=None,
serialized_options=None, file=None, # pylint: disable=redefined-builtin
serialized_start=None, serialized_end=None, create_key=None):
"""Arguments are as described in the attribute description above.
Note that filename is an obsolete argument, that is not used anymore.
Please use file.name to access this as an attribute.
"""
if create_key is not _internal_create_key:
_Deprecated('EnumDescriptor')
super(EnumDescriptor, self).__init__(
options, 'EnumOptions', name, full_name, file,
containing_type, serialized_start=serialized_start,
serialized_end=serialized_end, serialized_options=serialized_options)
self.values = values
for value in self.values:
value.type = self
self.values_by_name = dict((v.name, v) for v in values)
# Values are reversed to ensure that the first alias is retained.
self.values_by_number = dict((v.number, v) for v in reversed(values)) | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"full_name",
",",
"filename",
",",
"values",
",",
"containing_type",
"=",
"None",
",",
"options",
"=",
"None",
",",
"serialized_options",
"=",
"None",
",",
"file",
"=",
"None",
",",
"# pylint: disable=redefined-builtin",
"serialized_start",
"=",
"None",
",",
"serialized_end",
"=",
"None",
",",
"create_key",
"=",
"None",
")",
":",
"if",
"create_key",
"is",
"not",
"_internal_create_key",
":",
"_Deprecated",
"(",
"'EnumDescriptor'",
")",
"super",
"(",
"EnumDescriptor",
",",
"self",
")",
".",
"__init__",
"(",
"options",
",",
"'EnumOptions'",
",",
"name",
",",
"full_name",
",",
"file",
",",
"containing_type",
",",
"serialized_start",
"=",
"serialized_start",
",",
"serialized_end",
"=",
"serialized_end",
",",
"serialized_options",
"=",
"serialized_options",
")",
"self",
".",
"values",
"=",
"values",
"for",
"value",
"in",
"self",
".",
"values",
":",
"value",
".",
"type",
"=",
"self",
"self",
".",
"values_by_name",
"=",
"dict",
"(",
"(",
"v",
".",
"name",
",",
"v",
")",
"for",
"v",
"in",
"values",
")",
"# Values are reversed to ensure that the first alias is retained.",
"self",
".",
"values_by_number",
"=",
"dict",
"(",
"(",
"v",
".",
"number",
",",
"v",
")",
"for",
"v",
"in",
"reversed",
"(",
"values",
")",
")"
] | https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/google/protobuf/descriptor.py#L675-L697 |
||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozpack/packager/__init__.py | python | SimpleManifestSink.add | (self, component, pattern) | Add files with the given pattern in the given component. | Add files with the given pattern in the given component. | [
"Add",
"files",
"with",
"the",
"given",
"pattern",
"in",
"the",
"given",
"component",
"."
] | def add(self, component, pattern):
'''
Add files with the given pattern in the given component.
'''
assert not self._closed
added = False
for p, f in self._finder.find(pattern):
added = True
if is_manifest(p):
self._manifests.add(p)
dest = mozpath.join(component.destdir, SimpleManifestSink.normalize_path(p))
self.packager.add(dest, f)
if not added:
errors.error('Missing file(s): %s' % pattern) | [
"def",
"add",
"(",
"self",
",",
"component",
",",
"pattern",
")",
":",
"assert",
"not",
"self",
".",
"_closed",
"added",
"=",
"False",
"for",
"p",
",",
"f",
"in",
"self",
".",
"_finder",
".",
"find",
"(",
"pattern",
")",
":",
"added",
"=",
"True",
"if",
"is_manifest",
"(",
"p",
")",
":",
"self",
".",
"_manifests",
".",
"add",
"(",
"p",
")",
"dest",
"=",
"mozpath",
".",
"join",
"(",
"component",
".",
"destdir",
",",
"SimpleManifestSink",
".",
"normalize_path",
"(",
"p",
")",
")",
"self",
".",
"packager",
".",
"add",
"(",
"dest",
",",
"f",
")",
"if",
"not",
"added",
":",
"errors",
".",
"error",
"(",
"'Missing file(s): %s'",
"%",
"pattern",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozpack/packager/__init__.py#L353-L366 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pkg_resources/__init__.py | python | safe_name | (name) | return re.sub('[^A-Za-z0-9.]+', '-', name) | Convert an arbitrary string to a standard distribution name
Any runs of non-alphanumeric/. characters are replaced with a single '-'. | Convert an arbitrary string to a standard distribution name | [
"Convert",
"an",
"arbitrary",
"string",
"to",
"a",
"standard",
"distribution",
"name"
] | def safe_name(name):
"""Convert an arbitrary string to a standard distribution name
Any runs of non-alphanumeric/. characters are replaced with a single '-'.
"""
return re.sub('[^A-Za-z0-9.]+', '-', name) | [
"def",
"safe_name",
"(",
"name",
")",
":",
"return",
"re",
".",
"sub",
"(",
"'[^A-Za-z0-9.]+'",
",",
"'-'",
",",
"name",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pkg_resources/__init__.py#L1319-L1324 |
|
apache/qpid-proton | 6bcdfebb55ea3554bc29b1901422532db331a591 | python/proton/_transport.py | python | SSL.get_cert_organization_unit | (self) | return self.get_cert_subject_subfield(SSL.CERT_ORGANIZATION_UNIT) | A convenience method to get a string that contains the :const:`CERT_ORGANIZATION_UNIT`
sub field of the subject field in the ssl certificate.
:return: A string containing the :const:`CERT_ORGANIZATION_UNIT` sub field. | A convenience method to get a string that contains the :const:`CERT_ORGANIZATION_UNIT`
sub field of the subject field in the ssl certificate. | [
"A",
"convenience",
"method",
"to",
"get",
"a",
"string",
"that",
"contains",
"the",
":",
"const",
":",
"CERT_ORGANIZATION_UNIT",
"sub",
"field",
"of",
"the",
"subject",
"field",
"in",
"the",
"ssl",
"certificate",
"."
] | def get_cert_organization_unit(self) -> str:
"""
A convenience method to get a string that contains the :const:`CERT_ORGANIZATION_UNIT`
sub field of the subject field in the ssl certificate.
:return: A string containing the :const:`CERT_ORGANIZATION_UNIT` sub field.
"""
return self.get_cert_subject_subfield(SSL.CERT_ORGANIZATION_UNIT) | [
"def",
"get_cert_organization_unit",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"get_cert_subject_subfield",
"(",
"SSL",
".",
"CERT_ORGANIZATION_UNIT",
")"
] | https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_transport.py#L995-L1002 |
|
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/check_ops.py | python | assert_less | (x, y, data=None, summarize=None, message=None, name=None) | Assert the condition `x < y` holds element-wise.
Example of adding a dependency to an operation:
```python
with tf.control_dependencies([tf.assert_less(x, y)]):
output = tf.reduce_sum(x)
```
Example of adding dependency to the tensor being checked:
```python
x = tf.with_dependencies([tf.assert_less(x, y)], x)
```
This condition holds if for every pair of (possibly broadcast) elements
`x[i]`, `y[i]`, we have `x[i] < y[i]`.
If both `x` and `y` are empty, this is trivially satisfied.
Args:
x: Numeric `Tensor`.
y: Numeric `Tensor`, same dtype as and broadcastable to `x`.
data: The tensors to print out if the condition is False. Defaults to
error message and first few entries of `x`, `y`.
summarize: Print this many entries of each tensor.
message: A string to prefix to the default message.
name: A name for this operation (optional). Defaults to "assert_less".
Returns:
Op that raises `InvalidArgumentError` if `x < y` is False. | Assert the condition `x < y` holds element-wise. | [
"Assert",
"the",
"condition",
"x",
"<",
"y",
"holds",
"element",
"-",
"wise",
"."
] | def assert_less(x, y, data=None, summarize=None, message=None, name=None):
"""Assert the condition `x < y` holds element-wise.
Example of adding a dependency to an operation:
```python
with tf.control_dependencies([tf.assert_less(x, y)]):
output = tf.reduce_sum(x)
```
Example of adding dependency to the tensor being checked:
```python
x = tf.with_dependencies([tf.assert_less(x, y)], x)
```
This condition holds if for every pair of (possibly broadcast) elements
`x[i]`, `y[i]`, we have `x[i] < y[i]`.
If both `x` and `y` are empty, this is trivially satisfied.
Args:
x: Numeric `Tensor`.
y: Numeric `Tensor`, same dtype as and broadcastable to `x`.
data: The tensors to print out if the condition is False. Defaults to
error message and first few entries of `x`, `y`.
summarize: Print this many entries of each tensor.
message: A string to prefix to the default message.
name: A name for this operation (optional). Defaults to "assert_less".
Returns:
Op that raises `InvalidArgumentError` if `x < y` is False.
"""
message = message or ''
with ops.op_scope([x, y, data], name, 'assert_less'):
x = ops.convert_to_tensor(x, name='x')
y = ops.convert_to_tensor(y, name='y')
if data is None:
data = [
message,
'Condition x < y did not hold element-wise: x = ', x.name, x, 'y = ',
y.name, y
]
condition = math_ops.reduce_all(math_ops.less(x, y))
return logging_ops.Assert(condition, data, summarize=summarize) | [
"def",
"assert_less",
"(",
"x",
",",
"y",
",",
"data",
"=",
"None",
",",
"summarize",
"=",
"None",
",",
"message",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"message",
"=",
"message",
"or",
"''",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"x",
",",
"y",
",",
"data",
"]",
",",
"name",
",",
"'assert_less'",
")",
":",
"x",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"x",
",",
"name",
"=",
"'x'",
")",
"y",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"y",
",",
"name",
"=",
"'y'",
")",
"if",
"data",
"is",
"None",
":",
"data",
"=",
"[",
"message",
",",
"'Condition x < y did not hold element-wise: x = '",
",",
"x",
".",
"name",
",",
"x",
",",
"'y = '",
",",
"y",
".",
"name",
",",
"y",
"]",
"condition",
"=",
"math_ops",
".",
"reduce_all",
"(",
"math_ops",
".",
"less",
"(",
"x",
",",
"y",
")",
")",
"return",
"logging_ops",
".",
"Assert",
"(",
"condition",
",",
"data",
",",
"summarize",
"=",
"summarize",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/check_ops.py#L311-L354 |
||
GoSSIP-SJTU/Armariris | ad5d868482956b2194a77b39c8d543c7c2318200 | tools/clang/tools/scan-build-py/libear/__init__.py | python | Toolset.set_language_standard | (self, standard) | part of public interface | part of public interface | [
"part",
"of",
"public",
"interface"
] | def set_language_standard(self, standard):
""" part of public interface """
self.c_flags.append('-std=' + standard) | [
"def",
"set_language_standard",
"(",
"self",
",",
"standard",
")",
":",
"self",
".",
"c_flags",
".",
"append",
"(",
"'-std='",
"+",
"standard",
")"
] | https://github.com/GoSSIP-SJTU/Armariris/blob/ad5d868482956b2194a77b39c8d543c7c2318200/tools/clang/tools/scan-build-py/libear/__init__.py#L91-L93 |
||
tkn-tub/ns3-gym | 19bfe0a583e641142609939a090a09dfc63a095f | src/visualizer/visualizer/core.py | python | Node._get_selected | (self) | return self._selected | !
Get selected function.
@param self: class object.
@return selected status | !
Get selected function. | [
"!",
"Get",
"selected",
"function",
"."
] | def _get_selected(self):
"""!
Get selected function.
@param self: class object.
@return selected status
"""
return self._selected | [
"def",
"_get_selected",
"(",
"self",
")",
":",
"return",
"self",
".",
"_selected"
] | https://github.com/tkn-tub/ns3-gym/blob/19bfe0a583e641142609939a090a09dfc63a095f/src/visualizer/visualizer/core.py#L313-L320 |
|
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/SConsign.py | python | File | (name, dbm_module=None) | Arrange for all signatures to be stored in a global .sconsign.db*
file. | Arrange for all signatures to be stored in a global .sconsign.db*
file. | [
"Arrange",
"for",
"all",
"signatures",
"to",
"be",
"stored",
"in",
"a",
"global",
".",
"sconsign",
".",
"db",
"*",
"file",
"."
] | def File(name, dbm_module=None):
"""
Arrange for all signatures to be stored in a global .sconsign.db*
file.
"""
global ForDirectory, DB_Name, DB_Module
if name is None:
ForDirectory = DirFile
DB_Module = None
else:
ForDirectory = DB
DB_Name = name
if not dbm_module is None:
DB_Module = dbm_module | [
"def",
"File",
"(",
"name",
",",
"dbm_module",
"=",
"None",
")",
":",
"global",
"ForDirectory",
",",
"DB_Name",
",",
"DB_Module",
"if",
"name",
"is",
"None",
":",
"ForDirectory",
"=",
"DirFile",
"DB_Module",
"=",
"None",
"else",
":",
"ForDirectory",
"=",
"DB",
"DB_Name",
"=",
"name",
"if",
"not",
"dbm_module",
"is",
"None",
":",
"DB_Module",
"=",
"dbm_module"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/SConsign.py#L394-L407 |
||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/stateless_random_ops.py | python | stateless_random_normal | (shape,
seed,
mean=0.0,
stddev=1.0,
dtype=dtypes.float32,
name=None,
alg="auto_select") | Outputs deterministic pseudorandom values from a normal distribution.
This is a stateless version of `tf.random.normal`: if run twice with the
same seeds and shapes, it will produce the same pseudorandom numbers. The
output is consistent across multiple runs on the same hardware (and between
CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU
hardware.
Args:
shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
seed: A shape [2] Tensor, the seed to the random number generator. Must have
dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.)
mean: A 0-D Tensor or Python value of type `dtype`. The mean of the normal
distribution.
stddev: A 0-D Tensor or Python value of type `dtype`. The standard deviation
of the normal distribution.
dtype: The float type of the output: `float16`, `bfloat16`, `float32`,
`float64`. Defaults to `float32`.
name: A name for the operation (optional).
alg: The RNG algorithm used to generate the random numbers. See
`tf.random.stateless_uniform` for a detailed explanation.
Returns:
A tensor of the specified shape filled with random normal values. | Outputs deterministic pseudorandom values from a normal distribution. | [
"Outputs",
"deterministic",
"pseudorandom",
"values",
"from",
"a",
"normal",
"distribution",
"."
] | def stateless_random_normal(shape,
seed,
mean=0.0,
stddev=1.0,
dtype=dtypes.float32,
name=None,
alg="auto_select"):
"""Outputs deterministic pseudorandom values from a normal distribution.
This is a stateless version of `tf.random.normal`: if run twice with the
same seeds and shapes, it will produce the same pseudorandom numbers. The
output is consistent across multiple runs on the same hardware (and between
CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU
hardware.
Args:
shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
seed: A shape [2] Tensor, the seed to the random number generator. Must have
dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.)
mean: A 0-D Tensor or Python value of type `dtype`. The mean of the normal
distribution.
stddev: A 0-D Tensor or Python value of type `dtype`. The standard deviation
of the normal distribution.
dtype: The float type of the output: `float16`, `bfloat16`, `float32`,
`float64`. Defaults to `float32`.
name: A name for the operation (optional).
alg: The RNG algorithm used to generate the random numbers. See
`tf.random.stateless_uniform` for a detailed explanation.
Returns:
A tensor of the specified shape filled with random normal values.
"""
with ops.name_scope(name, "stateless_random_normal",
[shape, seed, mean, stddev]) as name:
shape = tensor_util.shape_tensor(shape)
mean = ops.convert_to_tensor(mean, dtype=dtype, name="mean")
stddev = ops.convert_to_tensor(stddev, dtype=dtype, name="stddev")
key, counter, alg = _get_key_counter_alg(seed, alg)
rnd = gen_stateless_random_ops_v2.stateless_random_normal_v2(
shape, key=key, counter=counter, dtype=dtype, alg=alg)
result = math_ops.add(rnd * stddev, mean, name=name)
tensor_util.maybe_set_static_shape(result, shape)
return result | [
"def",
"stateless_random_normal",
"(",
"shape",
",",
"seed",
",",
"mean",
"=",
"0.0",
",",
"stddev",
"=",
"1.0",
",",
"dtype",
"=",
"dtypes",
".",
"float32",
",",
"name",
"=",
"None",
",",
"alg",
"=",
"\"auto_select\"",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"stateless_random_normal\"",
",",
"[",
"shape",
",",
"seed",
",",
"mean",
",",
"stddev",
"]",
")",
"as",
"name",
":",
"shape",
"=",
"tensor_util",
".",
"shape_tensor",
"(",
"shape",
")",
"mean",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"mean",
",",
"dtype",
"=",
"dtype",
",",
"name",
"=",
"\"mean\"",
")",
"stddev",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"stddev",
",",
"dtype",
"=",
"dtype",
",",
"name",
"=",
"\"stddev\"",
")",
"key",
",",
"counter",
",",
"alg",
"=",
"_get_key_counter_alg",
"(",
"seed",
",",
"alg",
")",
"rnd",
"=",
"gen_stateless_random_ops_v2",
".",
"stateless_random_normal_v2",
"(",
"shape",
",",
"key",
"=",
"key",
",",
"counter",
"=",
"counter",
",",
"dtype",
"=",
"dtype",
",",
"alg",
"=",
"alg",
")",
"result",
"=",
"math_ops",
".",
"add",
"(",
"rnd",
"*",
"stddev",
",",
"mean",
",",
"name",
"=",
"name",
")",
"tensor_util",
".",
"maybe_set_static_shape",
"(",
"result",
",",
"shape",
")",
"return",
"result"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/stateless_random_ops.py#L602-L644 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing.py | python | ParseResults.asList | ( self ) | return [res.asList() if isinstance(res,ParseResults) else res for res in self.__toklist] | Returns the parse results as a nested list of matching tokens, all converted to strings.
Example::
patt = OneOrMore(Word(alphas))
result = patt.parseString("sldkj lsdkj sldkj")
# even though the result prints in string-like form, it is actually a pyparsing ParseResults
print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj']
# Use asList() to create an actual list
result_list = result.asList()
print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj'] | Returns the parse results as a nested list of matching tokens, all converted to strings. | [
"Returns",
"the",
"parse",
"results",
"as",
"a",
"nested",
"list",
"of",
"matching",
"tokens",
"all",
"converted",
"to",
"strings",
"."
] | def asList( self ):
"""
Returns the parse results as a nested list of matching tokens, all converted to strings.
Example::
patt = OneOrMore(Word(alphas))
result = patt.parseString("sldkj lsdkj sldkj")
# even though the result prints in string-like form, it is actually a pyparsing ParseResults
print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj']
# Use asList() to create an actual list
result_list = result.asList()
print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj']
"""
return [res.asList() if isinstance(res,ParseResults) else res for res in self.__toklist] | [
"def",
"asList",
"(",
"self",
")",
":",
"return",
"[",
"res",
".",
"asList",
"(",
")",
"if",
"isinstance",
"(",
"res",
",",
"ParseResults",
")",
"else",
"res",
"for",
"res",
"in",
"self",
".",
"__toklist",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing.py#L704-L718 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/html2.py | python | WebViewHistoryItem.GetUrl | (*args, **kwargs) | return _html2.WebViewHistoryItem_GetUrl(*args, **kwargs) | GetUrl(self) -> String | GetUrl(self) -> String | [
"GetUrl",
"(",
"self",
")",
"-",
">",
"String"
] | def GetUrl(*args, **kwargs):
"""GetUrl(self) -> String"""
return _html2.WebViewHistoryItem_GetUrl(*args, **kwargs) | [
"def",
"GetUrl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html2",
".",
"WebViewHistoryItem_GetUrl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/html2.py#L93-L95 |
|
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | xmlNs.newNodeEatName | (self, name) | return __tmp | Creation of a new node element. @ns is optional (None). | Creation of a new node element. | [
"Creation",
"of",
"a",
"new",
"node",
"element",
"."
] | def newNodeEatName(self, name):
"""Creation of a new node element. @ns is optional (None). """
ret = libxml2mod.xmlNewNodeEatName(self._o, name)
if ret is None:raise treeError('xmlNewNodeEatName() failed')
__tmp = xmlNode(_obj=ret)
return __tmp | [
"def",
"newNodeEatName",
"(",
"self",
",",
"name",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNewNodeEatName",
"(",
"self",
".",
"_o",
",",
"name",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlNewNodeEatName() failed'",
")",
"__tmp",
"=",
"xmlNode",
"(",
"_obj",
"=",
"ret",
")",
"return",
"__tmp"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L5896-L5901 |
|
moflow/moflow | 2dfb27c799c90c6caf1477508eca3eec616ef7d2 | bap/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/type_checkers.py | python | GetTypeChecker | (cpp_type, field_type) | return _VALUE_CHECKERS[cpp_type] | Returns a type checker for a message field of the specified types.
Args:
cpp_type: C++ type of the field (see descriptor.py).
field_type: Protocol message field type (see descriptor.py).
Returns:
An instance of TypeChecker which can be used to verify the types
of values assigned to a field of the specified type. | Returns a type checker for a message field of the specified types. | [
"Returns",
"a",
"type",
"checker",
"for",
"a",
"message",
"field",
"of",
"the",
"specified",
"types",
"."
] | def GetTypeChecker(cpp_type, field_type):
"""Returns a type checker for a message field of the specified types.
Args:
cpp_type: C++ type of the field (see descriptor.py).
field_type: Protocol message field type (see descriptor.py).
Returns:
An instance of TypeChecker which can be used to verify the types
of values assigned to a field of the specified type.
"""
if (cpp_type == _FieldDescriptor.CPPTYPE_STRING and
field_type == _FieldDescriptor.TYPE_STRING):
return UnicodeValueChecker()
return _VALUE_CHECKERS[cpp_type] | [
"def",
"GetTypeChecker",
"(",
"cpp_type",
",",
"field_type",
")",
":",
"if",
"(",
"cpp_type",
"==",
"_FieldDescriptor",
".",
"CPPTYPE_STRING",
"and",
"field_type",
"==",
"_FieldDescriptor",
".",
"TYPE_STRING",
")",
":",
"return",
"UnicodeValueChecker",
"(",
")",
"return",
"_VALUE_CHECKERS",
"[",
"cpp_type",
"]"
] | https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/type_checkers.py#L56-L70 |
|
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml.py | python | _xmlTextReaderErrorFunc | (xxx_todo_changeme,msg,severity,locator) | return f(arg,msg,severity,xmlTextReaderLocator(locator)) | Intermediate callback to wrap the locator | Intermediate callback to wrap the locator | [
"Intermediate",
"callback",
"to",
"wrap",
"the",
"locator"
] | def _xmlTextReaderErrorFunc(xxx_todo_changeme,msg,severity,locator):
"""Intermediate callback to wrap the locator"""
(f,arg) = xxx_todo_changeme
return f(arg,msg,severity,xmlTextReaderLocator(locator)) | [
"def",
"_xmlTextReaderErrorFunc",
"(",
"xxx_todo_changeme",
",",
"msg",
",",
"severity",
",",
"locator",
")",
":",
"(",
"f",
",",
"arg",
")",
"=",
"xxx_todo_changeme",
"return",
"f",
"(",
"arg",
",",
"msg",
",",
"severity",
",",
"xmlTextReaderLocator",
"(",
"locator",
")",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml.py#L713-L716 |
|
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_grad.py | python | _DigammaGrad | (op, grad) | Compute gradient of the digamma function with respect to its argument. | Compute gradient of the digamma function with respect to its argument. | [
"Compute",
"gradient",
"of",
"the",
"digamma",
"function",
"with",
"respect",
"to",
"its",
"argument",
"."
] | def _DigammaGrad(op, grad):
"""Compute gradient of the digamma function with respect to its argument."""
x = op.inputs[0]
with ops.control_dependencies([grad]):
x = math_ops.conj(x)
partial_x = math_ops.polygamma(array_ops.constant(1, dtype=x.dtype), x)
if compat.forward_compatible(2019, 9, 14):
return math_ops.mul_no_nan(partial_x, grad)
else:
return grad * partial_x | [
"def",
"_DigammaGrad",
"(",
"op",
",",
"grad",
")",
":",
"x",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
"with",
"ops",
".",
"control_dependencies",
"(",
"[",
"grad",
"]",
")",
":",
"x",
"=",
"math_ops",
".",
"conj",
"(",
"x",
")",
"partial_x",
"=",
"math_ops",
".",
"polygamma",
"(",
"array_ops",
".",
"constant",
"(",
"1",
",",
"dtype",
"=",
"x",
".",
"dtype",
")",
",",
"x",
")",
"if",
"compat",
".",
"forward_compatible",
"(",
"2019",
",",
"9",
",",
"14",
")",
":",
"return",
"math_ops",
".",
"mul_no_nan",
"(",
"partial_x",
",",
"grad",
")",
"else",
":",
"return",
"grad",
"*",
"partial_x"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_grad.py#L792-L801 |
||
swift/swift | 12d031cf8177fdec0137f9aa7e2912fa23c4416b | 3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/as.py | python | generate | (env) | Add Builders and construction variables for as to an Environment. | Add Builders and construction variables for as to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"as",
"to",
"an",
"Environment",
"."
] | def generate(env):
"""Add Builders and construction variables for as to an Environment."""
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in ASSuffixes:
static_obj.add_action(suffix, SCons.Defaults.ASAction)
shared_obj.add_action(suffix, SCons.Defaults.ASAction)
static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)
shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter)
for suffix in ASPPSuffixes:
static_obj.add_action(suffix, SCons.Defaults.ASPPAction)
shared_obj.add_action(suffix, SCons.Defaults.ASPPAction)
static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)
shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter)
env['AS'] = env.Detect(assemblers) or 'as'
env['ASFLAGS'] = SCons.Util.CLVar('')
env['ASCOM'] = '$AS $ASFLAGS -o $TARGET $SOURCES'
env['ASPPFLAGS'] = '$ASFLAGS'
env['ASPPCOM'] = '$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o $TARGET $SOURCES' | [
"def",
"generate",
"(",
"env",
")",
":",
"static_obj",
",",
"shared_obj",
"=",
"SCons",
".",
"Tool",
".",
"createObjBuilders",
"(",
"env",
")",
"for",
"suffix",
"in",
"ASSuffixes",
":",
"static_obj",
".",
"add_action",
"(",
"suffix",
",",
"SCons",
".",
"Defaults",
".",
"ASAction",
")",
"shared_obj",
".",
"add_action",
"(",
"suffix",
",",
"SCons",
".",
"Defaults",
".",
"ASAction",
")",
"static_obj",
".",
"add_emitter",
"(",
"suffix",
",",
"SCons",
".",
"Defaults",
".",
"StaticObjectEmitter",
")",
"shared_obj",
".",
"add_emitter",
"(",
"suffix",
",",
"SCons",
".",
"Defaults",
".",
"SharedObjectEmitter",
")",
"for",
"suffix",
"in",
"ASPPSuffixes",
":",
"static_obj",
".",
"add_action",
"(",
"suffix",
",",
"SCons",
".",
"Defaults",
".",
"ASPPAction",
")",
"shared_obj",
".",
"add_action",
"(",
"suffix",
",",
"SCons",
".",
"Defaults",
".",
"ASPPAction",
")",
"static_obj",
".",
"add_emitter",
"(",
"suffix",
",",
"SCons",
".",
"Defaults",
".",
"StaticObjectEmitter",
")",
"shared_obj",
".",
"add_emitter",
"(",
"suffix",
",",
"SCons",
".",
"Defaults",
".",
"SharedObjectEmitter",
")",
"env",
"[",
"'AS'",
"]",
"=",
"env",
".",
"Detect",
"(",
"assemblers",
")",
"or",
"'as'",
"env",
"[",
"'ASFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"''",
")",
"env",
"[",
"'ASCOM'",
"]",
"=",
"'$AS $ASFLAGS -o $TARGET $SOURCES'",
"env",
"[",
"'ASPPFLAGS'",
"]",
"=",
"'$ASFLAGS'",
"env",
"[",
"'ASPPCOM'",
"]",
"=",
"'$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o $TARGET $SOURCES'"
] | https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/as.py#L49-L69 |
||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/email/encoders.py | python | encode_quopri | (msg) | Encode the message's payload in quoted-printable.
Also, add an appropriate Content-Transfer-Encoding header. | Encode the message's payload in quoted-printable. | [
"Encode",
"the",
"message",
"s",
"payload",
"in",
"quoted",
"-",
"printable",
"."
] | def encode_quopri(msg):
"""Encode the message's payload in quoted-printable.
Also, add an appropriate Content-Transfer-Encoding header.
"""
orig = msg.get_payload()
encdata = _qencode(orig)
msg.set_payload(encdata)
msg['Content-Transfer-Encoding'] = 'quoted-printable' | [
"def",
"encode_quopri",
"(",
"msg",
")",
":",
"orig",
"=",
"msg",
".",
"get_payload",
"(",
")",
"encdata",
"=",
"_qencode",
"(",
"orig",
")",
"msg",
".",
"set_payload",
"(",
"encdata",
")",
"msg",
"[",
"'Content-Transfer-Encoding'",
"]",
"=",
"'quoted-printable'"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/email/encoders.py#L51-L59 |
||
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/ogr.py | python | Layer.GetFeature | (self, *args) | return _ogr.Layer_GetFeature(self, *args) | r"""
GetFeature(Layer self, GIntBig fid) -> Feature
OGRFeatureH
OGR_L_GetFeature(OGRLayerH hLayer, GIntBig nFeatureId)
Fetch a feature by its identifier.
This function will attempt to read the identified feature. The nFID
value cannot be OGRNullFID. Success or failure of this operation is
unaffected by the spatial or attribute filters (and specialized
implementations in drivers should make sure that they do not take into
account spatial or attribute filters).
If this function returns a non-NULL feature, it is guaranteed that its
feature id ( OGR_F_GetFID()) will be the same as nFID.
Use OGR_L_TestCapability(OLCRandomRead) to establish if this layer
supports efficient random access reading via OGR_L_GetFeature();
however, the call should always work if the feature exists as a
fallback implementation just scans all the features in the layer
looking for the desired feature.
Sequential reads (with OGR_L_GetNextFeature()) are generally
considered interrupted by a OGR_L_GetFeature() call.
The returned feature should be free with OGR_F_Destroy().
This function is the same as the C++ method OGRLayer::GetFeature( ).
Parameters:
-----------
hLayer: handle to the layer that owned the feature.
nFeatureId: the feature id of the feature to read.
a handle to a feature now owned by the caller, or NULL on failure. | r"""
GetFeature(Layer self, GIntBig fid) -> Feature
OGRFeatureH
OGR_L_GetFeature(OGRLayerH hLayer, GIntBig nFeatureId) | [
"r",
"GetFeature",
"(",
"Layer",
"self",
"GIntBig",
"fid",
")",
"-",
">",
"Feature",
"OGRFeatureH",
"OGR_L_GetFeature",
"(",
"OGRLayerH",
"hLayer",
"GIntBig",
"nFeatureId",
")"
] | def GetFeature(self, *args):
r"""
GetFeature(Layer self, GIntBig fid) -> Feature
OGRFeatureH
OGR_L_GetFeature(OGRLayerH hLayer, GIntBig nFeatureId)
Fetch a feature by its identifier.
This function will attempt to read the identified feature. The nFID
value cannot be OGRNullFID. Success or failure of this operation is
unaffected by the spatial or attribute filters (and specialized
implementations in drivers should make sure that they do not take into
account spatial or attribute filters).
If this function returns a non-NULL feature, it is guaranteed that its
feature id ( OGR_F_GetFID()) will be the same as nFID.
Use OGR_L_TestCapability(OLCRandomRead) to establish if this layer
supports efficient random access reading via OGR_L_GetFeature();
however, the call should always work if the feature exists as a
fallback implementation just scans all the features in the layer
looking for the desired feature.
Sequential reads (with OGR_L_GetNextFeature()) are generally
considered interrupted by a OGR_L_GetFeature() call.
The returned feature should be free with OGR_F_Destroy().
This function is the same as the C++ method OGRLayer::GetFeature( ).
Parameters:
-----------
hLayer: handle to the layer that owned the feature.
nFeatureId: the feature id of the feature to read.
a handle to a feature now owned by the caller, or NULL on failure.
"""
return _ogr.Layer_GetFeature(self, *args) | [
"def",
"GetFeature",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_ogr",
".",
"Layer_GetFeature",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L1306-L1345 |
|
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Source/ThirdParty/CEF3/cef_source/tools/automate/automate-ue4.py | python | is_git_checkout | (path) | return os.path.exists(os.path.join(path, '.git')) | Returns true if the path represents a git checkout. | Returns true if the path represents a git checkout. | [
"Returns",
"true",
"if",
"the",
"path",
"represents",
"a",
"git",
"checkout",
"."
] | def is_git_checkout(path):
""" Returns true if the path represents a git checkout. """
return os.path.exists(os.path.join(path, '.git')) | [
"def",
"is_git_checkout",
"(",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'.git'",
")",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/cef_source/tools/automate/automate-ue4.py#L118-L120 |
|
PlatformLab/RAMCloud | b1866af19124325a6dfd8cbc267e2e3ef1f965d1 | scripts/upload.py | python | AbstractRpcServer._GetAuthCookie | (self, auth_token) | Fetches authentication cookies for an authentication token.
Args:
auth_token: The authentication token returned by ClientLogin.
Raises:
HTTPError: If there was an error fetching the authentication cookies. | Fetches authentication cookies for an authentication token. | [
"Fetches",
"authentication",
"cookies",
"for",
"an",
"authentication",
"token",
"."
] | def _GetAuthCookie(self, auth_token):
"""Fetches authentication cookies for an authentication token.
Args:
auth_token: The authentication token returned by ClientLogin.
Raises:
HTTPError: If there was an error fetching the authentication cookies.
"""
# This is a dummy value to allow us to identify when we're successful.
continue_location = "http://localhost/"
args = {"continue": continue_location, "auth": auth_token}
req = self._CreateRequest("%s/_ah/login?%s" %
(self.host, urllib.urlencode(args)))
try:
response = self.opener.open(req)
except urllib2.HTTPError, e:
response = e
if (response.code != 302 or
response.info()["location"] != continue_location):
raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg,
response.headers, response.fp)
self.authenticated = True | [
"def",
"_GetAuthCookie",
"(",
"self",
",",
"auth_token",
")",
":",
"# This is a dummy value to allow us to identify when we're successful.",
"continue_location",
"=",
"\"http://localhost/\"",
"args",
"=",
"{",
"\"continue\"",
":",
"continue_location",
",",
"\"auth\"",
":",
"auth_token",
"}",
"req",
"=",
"self",
".",
"_CreateRequest",
"(",
"\"%s/_ah/login?%s\"",
"%",
"(",
"self",
".",
"host",
",",
"urllib",
".",
"urlencode",
"(",
"args",
")",
")",
")",
"try",
":",
"response",
"=",
"self",
".",
"opener",
".",
"open",
"(",
"req",
")",
"except",
"urllib2",
".",
"HTTPError",
",",
"e",
":",
"response",
"=",
"e",
"if",
"(",
"response",
".",
"code",
"!=",
"302",
"or",
"response",
".",
"info",
"(",
")",
"[",
"\"location\"",
"]",
"!=",
"continue_location",
")",
":",
"raise",
"urllib2",
".",
"HTTPError",
"(",
"req",
".",
"get_full_url",
"(",
")",
",",
"response",
".",
"code",
",",
"response",
".",
"msg",
",",
"response",
".",
"headers",
",",
"response",
".",
"fp",
")",
"self",
".",
"authenticated",
"=",
"True"
] | https://github.com/PlatformLab/RAMCloud/blob/b1866af19124325a6dfd8cbc267e2e3ef1f965d1/scripts/upload.py#L339-L361 |
||
ValveSoftware/source-sdk-2013 | 0d8dceea4310fde5706b3ce1c70609d72a38efdf | mp/src/thirdparty/protobuf-2.3.0/python/mox.py | python | SameElementsAs.equals | (self, actual_seq) | return expected == actual | Check to see whether actual_seq has same elements as expected_seq.
Args:
actual_seq: sequence
Returns:
bool | Check to see whether actual_seq has same elements as expected_seq. | [
"Check",
"to",
"see",
"whether",
"actual_seq",
"has",
"same",
"elements",
"as",
"expected_seq",
"."
] | def equals(self, actual_seq):
"""Check to see whether actual_seq has same elements as expected_seq.
Args:
actual_seq: sequence
Returns:
bool
"""
try:
expected = dict([(element, None) for element in self._expected_seq])
actual = dict([(element, None) for element in actual_seq])
except TypeError:
# Fall back to slower list-compare if any of the objects are unhashable.
expected = list(self._expected_seq)
actual = list(actual_seq)
expected.sort()
actual.sort()
return expected == actual | [
"def",
"equals",
"(",
"self",
",",
"actual_seq",
")",
":",
"try",
":",
"expected",
"=",
"dict",
"(",
"[",
"(",
"element",
",",
"None",
")",
"for",
"element",
"in",
"self",
".",
"_expected_seq",
"]",
")",
"actual",
"=",
"dict",
"(",
"[",
"(",
"element",
",",
"None",
")",
"for",
"element",
"in",
"actual_seq",
"]",
")",
"except",
"TypeError",
":",
"# Fall back to slower list-compare if any of the objects are unhashable.",
"expected",
"=",
"list",
"(",
"self",
".",
"_expected_seq",
")",
"actual",
"=",
"list",
"(",
"actual_seq",
")",
"expected",
".",
"sort",
"(",
")",
"actual",
".",
"sort",
"(",
")",
"return",
"expected",
"==",
"actual"
] | https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/mp/src/thirdparty/protobuf-2.3.0/python/mox.py#L1021-L1040 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/aui.py | python | AuiPaneInfo.IsToolbar | (*args, **kwargs) | return _aui.AuiPaneInfo_IsToolbar(*args, **kwargs) | IsToolbar(self) -> bool | IsToolbar(self) -> bool | [
"IsToolbar",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsToolbar(*args, **kwargs):
"""IsToolbar(self) -> bool"""
return _aui.AuiPaneInfo_IsToolbar(*args, **kwargs) | [
"def",
"IsToolbar",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiPaneInfo_IsToolbar",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L261-L263 |
|
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/ops/array_ops.py | python | edit_distance | (hypothesis, truth, normalize=True, name="edit_distance") | return gen_array_ops._edit_distance(hypothesis.indices,
hypothesis.values,
hypothesis.shape,
truth.indices,
truth.values,
truth.shape,
normalize=normalize,
name=name) | Computes the Levenshtein distance between sequences.
This operation takes variable-length sequences (`hypothesis` and `truth`),
each provided as a `SparseTensor`, and computes the Levenshtein distance.
You can normalize the edit distance by length of `truth` by setting
`normalize` to true.
For example, given the following input:
```python
# 'hypothesis' is a tensor of shape `[2, 1]` with variable-length values:
# (0,0) = ["a"]
# (1,0) = ["b"]
hypothesis = tf.SparseTensor(
[[0, 0, 0],
[1, 0, 0]],
["a", "b"]
(2, 1, 1))
# 'truth' is a tensor of shape `[2, 2]` with variable-length values:
# (0,0) = []
# (0,1) = ["a"]
# (1,0) = ["b", "c"]
# (1,1) = ["a"]
truth = tf.SparseTensor(
[[0, 1, 0],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0]]
["a", "b", "c", "a"],
(2, 2, 2))
normalize = True
```
This operation would return the following:
```python
# 'output' is a tensor of shape `[2, 2]` with edit distances normalized
# by 'truth' lengths.
output ==> [[inf, 1.0], # (0,0): no truth, (0,1): no hypothesis
[0.5, 1.0]] # (1,0): addition, (1,1): no hypothesis
```
Args:
hypothesis: A `SparseTensor` containing hypothesis sequences.
truth: A `SparseTensor` containing truth sequences.
normalize: A `bool`. If `True`, normalizes the Levenshtein distance by
length of `truth.`
name: A name for the operation (optional).
Returns:
A dense `Tensor` with rank `R - 1`, where R is the rank of the
`SparseTensor` inputs `hypothesis` and `truth`.
Raises:
TypeError: If either `hypothesis` or `truth` are not a `SparseTensor`. | Computes the Levenshtein distance between sequences. | [
"Computes",
"the",
"Levenshtein",
"distance",
"between",
"sequences",
"."
] | def edit_distance(hypothesis, truth, normalize=True, name="edit_distance"):
"""Computes the Levenshtein distance between sequences.
This operation takes variable-length sequences (`hypothesis` and `truth`),
each provided as a `SparseTensor`, and computes the Levenshtein distance.
You can normalize the edit distance by length of `truth` by setting
`normalize` to true.
For example, given the following input:
```python
# 'hypothesis' is a tensor of shape `[2, 1]` with variable-length values:
# (0,0) = ["a"]
# (1,0) = ["b"]
hypothesis = tf.SparseTensor(
[[0, 0, 0],
[1, 0, 0]],
["a", "b"]
(2, 1, 1))
# 'truth' is a tensor of shape `[2, 2]` with variable-length values:
# (0,0) = []
# (0,1) = ["a"]
# (1,0) = ["b", "c"]
# (1,1) = ["a"]
truth = tf.SparseTensor(
[[0, 1, 0],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0]]
["a", "b", "c", "a"],
(2, 2, 2))
normalize = True
```
This operation would return the following:
```python
# 'output' is a tensor of shape `[2, 2]` with edit distances normalized
# by 'truth' lengths.
output ==> [[inf, 1.0], # (0,0): no truth, (0,1): no hypothesis
[0.5, 1.0]] # (1,0): addition, (1,1): no hypothesis
```
Args:
hypothesis: A `SparseTensor` containing hypothesis sequences.
truth: A `SparseTensor` containing truth sequences.
normalize: A `bool`. If `True`, normalizes the Levenshtein distance by
length of `truth.`
name: A name for the operation (optional).
Returns:
A dense `Tensor` with rank `R - 1`, where R is the rank of the
`SparseTensor` inputs `hypothesis` and `truth`.
Raises:
TypeError: If either `hypothesis` or `truth` are not a `SparseTensor`.
"""
if not isinstance(hypothesis, (ops.SparseTensor, ops.SparseTensorValue)):
raise TypeError("Hypothesis must be a SparseTensor.")
if not isinstance(truth, (ops.SparseTensor, ops.SparseTensorValue)):
raise TypeError("Truth must be a SparseTensor.")
return gen_array_ops._edit_distance(hypothesis.indices,
hypothesis.values,
hypothesis.shape,
truth.indices,
truth.values,
truth.shape,
normalize=normalize,
name=name) | [
"def",
"edit_distance",
"(",
"hypothesis",
",",
"truth",
",",
"normalize",
"=",
"True",
",",
"name",
"=",
"\"edit_distance\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"hypothesis",
",",
"(",
"ops",
".",
"SparseTensor",
",",
"ops",
".",
"SparseTensorValue",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Hypothesis must be a SparseTensor.\"",
")",
"if",
"not",
"isinstance",
"(",
"truth",
",",
"(",
"ops",
".",
"SparseTensor",
",",
"ops",
".",
"SparseTensorValue",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Truth must be a SparseTensor.\"",
")",
"return",
"gen_array_ops",
".",
"_edit_distance",
"(",
"hypothesis",
".",
"indices",
",",
"hypothesis",
".",
"values",
",",
"hypothesis",
".",
"shape",
",",
"truth",
".",
"indices",
",",
"truth",
".",
"values",
",",
"truth",
".",
"shape",
",",
"normalize",
"=",
"normalize",
",",
"name",
"=",
"name",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/array_ops.py#L1818-L1889 |
|
Samsung/veles | 95ed733c2e49bc011ad98ccf2416ecec23fbf352 | veles/external/progressbar/progressbar.py | python | ProgressBar.start | (self) | return self | Starts measuring time, and prints the bar at 0%.
It returns self so you can use it like this:
>>> pbar = ProgressBar().start()
>>> for i in range(100):
... # do something
... pbar.update(i+1)
...
>>> pbar.finish() | Starts measuring time, and prints the bar at 0%. | [
"Starts",
"measuring",
"time",
"and",
"prints",
"the",
"bar",
"at",
"0%",
"."
] | def start(self):
"""Starts measuring time, and prints the bar at 0%.
It returns self so you can use it like this:
>>> pbar = ProgressBar().start()
>>> for i in range(100):
... # do something
... pbar.update(i+1)
...
>>> pbar.finish()
"""
if self.maxval is None:
self.maxval = self._DEFAULT_MAXVAL
self.num_intervals = max(100, self.term_width)
self.next_update = 0
if self.maxval is not UnknownLength:
if self.maxval < 0:
raise ValueError('Value out of range')
self.update_interval = self.maxval / self.num_intervals
self.start_time = self.last_update_time = time.time()
self.update(0)
return self | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"maxval",
"is",
"None",
":",
"self",
".",
"maxval",
"=",
"self",
".",
"_DEFAULT_MAXVAL",
"self",
".",
"num_intervals",
"=",
"max",
"(",
"100",
",",
"self",
".",
"term_width",
")",
"self",
".",
"next_update",
"=",
"0",
"if",
"self",
".",
"maxval",
"is",
"not",
"UnknownLength",
":",
"if",
"self",
".",
"maxval",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'Value out of range'",
")",
"self",
".",
"update_interval",
"=",
"self",
".",
"maxval",
"/",
"self",
".",
"num_intervals",
"self",
".",
"start_time",
"=",
"self",
".",
"last_update_time",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"update",
"(",
"0",
")",
"return",
"self"
] | https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/external/progressbar/progressbar.py#L273-L299 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/linalg/special_matrices.py | python | toeplitz | (c, r=None) | return as_strided(vals[len(c)-1:], shape=out_shp, strides=(-n, n)).copy() | Construct a Toeplitz matrix.
The Toeplitz matrix has constant diagonals, with c as its first column
and r as its first row. If r is not given, ``r == conjugate(c)`` is
assumed.
Parameters
----------
c : array_like
First column of the matrix. Whatever the actual shape of `c`, it
will be converted to a 1-D array.
r : array_like, optional
First row of the matrix. If None, ``r = conjugate(c)`` is assumed;
in this case, if c[0] is real, the result is a Hermitian matrix.
r[0] is ignored; the first row of the returned matrix is
``[c[0], r[1:]]``. Whatever the actual shape of `r`, it will be
converted to a 1-D array.
Returns
-------
A : (len(c), len(r)) ndarray
The Toeplitz matrix. Dtype is the same as ``(c[0] + r[0]).dtype``.
See Also
--------
circulant : circulant matrix
hankel : Hankel matrix
solve_toeplitz : Solve a Toeplitz system.
Notes
-----
The behavior when `c` or `r` is a scalar, or when `c` is complex and
`r` is None, was changed in version 0.8.0. The behavior in previous
versions was undocumented and is no longer supported.
Examples
--------
>>> from scipy.linalg import toeplitz
>>> toeplitz([1,2,3], [1,4,5,6])
array([[1, 4, 5, 6],
[2, 1, 4, 5],
[3, 2, 1, 4]])
>>> toeplitz([1.0, 2+3j, 4-1j])
array([[ 1.+0.j, 2.-3.j, 4.+1.j],
[ 2.+3.j, 1.+0.j, 2.-3.j],
[ 4.-1.j, 2.+3.j, 1.+0.j]]) | Construct a Toeplitz matrix. | [
"Construct",
"a",
"Toeplitz",
"matrix",
"."
] | def toeplitz(c, r=None):
"""
Construct a Toeplitz matrix.
The Toeplitz matrix has constant diagonals, with c as its first column
and r as its first row. If r is not given, ``r == conjugate(c)`` is
assumed.
Parameters
----------
c : array_like
First column of the matrix. Whatever the actual shape of `c`, it
will be converted to a 1-D array.
r : array_like, optional
First row of the matrix. If None, ``r = conjugate(c)`` is assumed;
in this case, if c[0] is real, the result is a Hermitian matrix.
r[0] is ignored; the first row of the returned matrix is
``[c[0], r[1:]]``. Whatever the actual shape of `r`, it will be
converted to a 1-D array.
Returns
-------
A : (len(c), len(r)) ndarray
The Toeplitz matrix. Dtype is the same as ``(c[0] + r[0]).dtype``.
See Also
--------
circulant : circulant matrix
hankel : Hankel matrix
solve_toeplitz : Solve a Toeplitz system.
Notes
-----
The behavior when `c` or `r` is a scalar, or when `c` is complex and
`r` is None, was changed in version 0.8.0. The behavior in previous
versions was undocumented and is no longer supported.
Examples
--------
>>> from scipy.linalg import toeplitz
>>> toeplitz([1,2,3], [1,4,5,6])
array([[1, 4, 5, 6],
[2, 1, 4, 5],
[3, 2, 1, 4]])
>>> toeplitz([1.0, 2+3j, 4-1j])
array([[ 1.+0.j, 2.-3.j, 4.+1.j],
[ 2.+3.j, 1.+0.j, 2.-3.j],
[ 4.-1.j, 2.+3.j, 1.+0.j]])
"""
c = np.asarray(c).ravel()
if r is None:
r = c.conjugate()
else:
r = np.asarray(r).ravel()
# Form a 1D array containing a reversed c followed by r[1:] that could be
# strided to give us toeplitz matrix.
vals = np.concatenate((c[::-1], r[1:]))
out_shp = len(c), len(r)
n = vals.strides[0]
return as_strided(vals[len(c)-1:], shape=out_shp, strides=(-n, n)).copy() | [
"def",
"toeplitz",
"(",
"c",
",",
"r",
"=",
"None",
")",
":",
"c",
"=",
"np",
".",
"asarray",
"(",
"c",
")",
".",
"ravel",
"(",
")",
"if",
"r",
"is",
"None",
":",
"r",
"=",
"c",
".",
"conjugate",
"(",
")",
"else",
":",
"r",
"=",
"np",
".",
"asarray",
"(",
"r",
")",
".",
"ravel",
"(",
")",
"# Form a 1D array containing a reversed c followed by r[1:] that could be",
"# strided to give us toeplitz matrix.",
"vals",
"=",
"np",
".",
"concatenate",
"(",
"(",
"c",
"[",
":",
":",
"-",
"1",
"]",
",",
"r",
"[",
"1",
":",
"]",
")",
")",
"out_shp",
"=",
"len",
"(",
"c",
")",
",",
"len",
"(",
"r",
")",
"n",
"=",
"vals",
".",
"strides",
"[",
"0",
"]",
"return",
"as_strided",
"(",
"vals",
"[",
"len",
"(",
"c",
")",
"-",
"1",
":",
"]",
",",
"shape",
"=",
"out_shp",
",",
"strides",
"=",
"(",
"-",
"n",
",",
"n",
")",
")",
".",
"copy",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/linalg/special_matrices.py#L143-L203 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/asyncio/protocols.py | python | BufferedProtocol.eof_received | (self) | Called when the other end calls write_eof() or equivalent.
If this returns a false value (including None), the transport
will close itself. If it returns a true value, closing the
transport is up to the protocol. | Called when the other end calls write_eof() or equivalent. | [
"Called",
"when",
"the",
"other",
"end",
"calls",
"write_eof",
"()",
"or",
"equivalent",
"."
] | def eof_received(self):
"""Called when the other end calls write_eof() or equivalent.
If this returns a false value (including None), the transport
will close itself. If it returns a true value, closing the
transport is up to the protocol.
""" | [
"def",
"eof_received",
"(",
"self",
")",
":"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/asyncio/protocols.py#L151-L157 |
||
floatlazer/semantic_slam | 657814a1ba484de6b7f6f9d07c564566c8121f13 | semantic_cloud/src/semantic_cloud.py | python | SemanticCloud.color_depth_callback | (self, color_img_ros, depth_img_ros) | Callback function to produce point cloud registered with semantic class color based on input color image and depth image
\param color_img_ros (sensor_msgs.Image) the input color image (bgr8)
\param depth_img_ros (sensor_msgs.Image) the input depth image (registered to the color image frame) (float32) values are in meters | Callback function to produce point cloud registered with semantic class color based on input color image and depth image
\param color_img_ros (sensor_msgs.Image) the input color image (bgr8)
\param depth_img_ros (sensor_msgs.Image) the input depth image (registered to the color image frame) (float32) values are in meters | [
"Callback",
"function",
"to",
"produce",
"point",
"cloud",
"registered",
"with",
"semantic",
"class",
"color",
"based",
"on",
"input",
"color",
"image",
"and",
"depth",
"image",
"\\",
"param",
"color_img_ros",
"(",
"sensor_msgs",
".",
"Image",
")",
"the",
"input",
"color",
"image",
"(",
"bgr8",
")",
"\\",
"param",
"depth_img_ros",
"(",
"sensor_msgs",
".",
"Image",
")",
"the",
"input",
"depth",
"image",
"(",
"registered",
"to",
"the",
"color",
"image",
"frame",
")",
"(",
"float32",
")",
"values",
"are",
"in",
"meters"
] | def color_depth_callback(self, color_img_ros, depth_img_ros):
"""
Callback function to produce point cloud registered with semantic class color based on input color image and depth image
\param color_img_ros (sensor_msgs.Image) the input color image (bgr8)
\param depth_img_ros (sensor_msgs.Image) the input depth image (registered to the color image frame) (float32) values are in meters
"""
# Convert ros Image message to numpy array
try:
color_img = self.bridge.imgmsg_to_cv2(color_img_ros, "bgr8")
depth_img = self.bridge.imgmsg_to_cv2(depth_img_ros, "32FC1")
except CvBridgeError as e:
print(e)
# Resize depth
if depth_img.shape[0] is not self.img_height or depth_img.shape[1] is not self.img_width:
depth_img = resize(depth_img, (self.img_height, self.img_width), order = 0, mode = 'reflect', anti_aliasing=False, preserve_range = True) # order = 0, nearest neighbour
depth_img = depth_img.astype(np.float32)
if self.point_type is PointType.COLOR:
cloud_ros = self.cloud_generator.generate_cloud_color(color_img, depth_img, color_img_ros.header.stamp)
else:
# Do semantic segmantation
if self.point_type is PointType.SEMANTICS_MAX:
semantic_color, pred_confidence = self.predict_max(color_img)
cloud_ros = self.cloud_generator.generate_cloud_semantic_max(color_img, depth_img, semantic_color, pred_confidence, color_img_ros.header.stamp)
elif self.point_type is PointType.SEMANTICS_BAYESIAN:
self.predict_bayesian(color_img)
# Produce point cloud with rgb colors, semantic colors and confidences
cloud_ros = self.cloud_generator.generate_cloud_semantic_bayesian(color_img, depth_img, self.semantic_colors, self.confidences, color_img_ros.header.stamp)
# Publish semantic image
if self.sem_img_pub.get_num_connections() > 0:
if self.point_type is PointType.SEMANTICS_MAX:
semantic_color_msg = self.bridge.cv2_to_imgmsg(semantic_color, encoding="bgr8")
else:
semantic_color_msg = self.bridge.cv2_to_imgmsg(self.semantic_colors[0], encoding="bgr8")
self.sem_img_pub.publish(semantic_color_msg)
# Publish point cloud
self.pcl_pub.publish(cloud_ros) | [
"def",
"color_depth_callback",
"(",
"self",
",",
"color_img_ros",
",",
"depth_img_ros",
")",
":",
"# Convert ros Image message to numpy array",
"try",
":",
"color_img",
"=",
"self",
".",
"bridge",
".",
"imgmsg_to_cv2",
"(",
"color_img_ros",
",",
"\"bgr8\"",
")",
"depth_img",
"=",
"self",
".",
"bridge",
".",
"imgmsg_to_cv2",
"(",
"depth_img_ros",
",",
"\"32FC1\"",
")",
"except",
"CvBridgeError",
"as",
"e",
":",
"print",
"(",
"e",
")",
"# Resize depth",
"if",
"depth_img",
".",
"shape",
"[",
"0",
"]",
"is",
"not",
"self",
".",
"img_height",
"or",
"depth_img",
".",
"shape",
"[",
"1",
"]",
"is",
"not",
"self",
".",
"img_width",
":",
"depth_img",
"=",
"resize",
"(",
"depth_img",
",",
"(",
"self",
".",
"img_height",
",",
"self",
".",
"img_width",
")",
",",
"order",
"=",
"0",
",",
"mode",
"=",
"'reflect'",
",",
"anti_aliasing",
"=",
"False",
",",
"preserve_range",
"=",
"True",
")",
"# order = 0, nearest neighbour",
"depth_img",
"=",
"depth_img",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"if",
"self",
".",
"point_type",
"is",
"PointType",
".",
"COLOR",
":",
"cloud_ros",
"=",
"self",
".",
"cloud_generator",
".",
"generate_cloud_color",
"(",
"color_img",
",",
"depth_img",
",",
"color_img_ros",
".",
"header",
".",
"stamp",
")",
"else",
":",
"# Do semantic segmantation",
"if",
"self",
".",
"point_type",
"is",
"PointType",
".",
"SEMANTICS_MAX",
":",
"semantic_color",
",",
"pred_confidence",
"=",
"self",
".",
"predict_max",
"(",
"color_img",
")",
"cloud_ros",
"=",
"self",
".",
"cloud_generator",
".",
"generate_cloud_semantic_max",
"(",
"color_img",
",",
"depth_img",
",",
"semantic_color",
",",
"pred_confidence",
",",
"color_img_ros",
".",
"header",
".",
"stamp",
")",
"elif",
"self",
".",
"point_type",
"is",
"PointType",
".",
"SEMANTICS_BAYESIAN",
":",
"self",
".",
"predict_bayesian",
"(",
"color_img",
")",
"# Produce point cloud with rgb colors, semantic colors and confidences",
"cloud_ros",
"=",
"self",
".",
"cloud_generator",
".",
"generate_cloud_semantic_bayesian",
"(",
"color_img",
",",
"depth_img",
",",
"self",
".",
"semantic_colors",
",",
"self",
".",
"confidences",
",",
"color_img_ros",
".",
"header",
".",
"stamp",
")",
"# Publish semantic image",
"if",
"self",
".",
"sem_img_pub",
".",
"get_num_connections",
"(",
")",
">",
"0",
":",
"if",
"self",
".",
"point_type",
"is",
"PointType",
".",
"SEMANTICS_MAX",
":",
"semantic_color_msg",
"=",
"self",
".",
"bridge",
".",
"cv2_to_imgmsg",
"(",
"semantic_color",
",",
"encoding",
"=",
"\"bgr8\"",
")",
"else",
":",
"semantic_color_msg",
"=",
"self",
".",
"bridge",
".",
"cv2_to_imgmsg",
"(",
"self",
".",
"semantic_colors",
"[",
"0",
"]",
",",
"encoding",
"=",
"\"bgr8\"",
")",
"self",
".",
"sem_img_pub",
".",
"publish",
"(",
"semantic_color_msg",
")",
"# Publish point cloud",
"self",
".",
"pcl_pub",
".",
"publish",
"(",
"cloud_ros",
")"
] | https://github.com/floatlazer/semantic_slam/blob/657814a1ba484de6b7f6f9d07c564566c8121f13/semantic_cloud/src/semantic_cloud.py#L184-L222 |
||
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/ivy_parser.py | python | p_tterm_term | (p) | tterm : tapp | tterm : tapp | [
"tterm",
":",
"tapp"
] | def p_tterm_term(p):
'tterm : tapp'
p[0] = p[1] | [
"def",
"p_tterm_term",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]"
] | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_parser.py#L1420-L1422 |
||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/aui.py | python | AuiMDIParentFrame.SetChildMenuBar | (*args, **kwargs) | return _aui.AuiMDIParentFrame_SetChildMenuBar(*args, **kwargs) | SetChildMenuBar(self, AuiMDIChildFrame pChild) | SetChildMenuBar(self, AuiMDIChildFrame pChild) | [
"SetChildMenuBar",
"(",
"self",
"AuiMDIChildFrame",
"pChild",
")"
] | def SetChildMenuBar(*args, **kwargs):
"""SetChildMenuBar(self, AuiMDIChildFrame pChild)"""
return _aui.AuiMDIParentFrame_SetChildMenuBar(*args, **kwargs) | [
"def",
"SetChildMenuBar",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiMDIParentFrame_SetChildMenuBar",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L1453-L1455 |
|
moflow/moflow | 2dfb27c799c90c6caf1477508eca3eec616ef7d2 | bap/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/python_message.py | python | _AddEnumValues | (descriptor, cls) | Sets class-level attributes for all enum fields defined in this message.
Also exporting a class-level object that can name enum values.
Args:
descriptor: Descriptor object for this message type.
cls: Class we're constructing for this message type. | Sets class-level attributes for all enum fields defined in this message. | [
"Sets",
"class",
"-",
"level",
"attributes",
"for",
"all",
"enum",
"fields",
"defined",
"in",
"this",
"message",
"."
] | def _AddEnumValues(descriptor, cls):
"""Sets class-level attributes for all enum fields defined in this message.
Also exporting a class-level object that can name enum values.
Args:
descriptor: Descriptor object for this message type.
cls: Class we're constructing for this message type.
"""
for enum_type in descriptor.enum_types:
setattr(cls, enum_type.name, enum_type_wrapper.EnumTypeWrapper(enum_type))
for enum_value in enum_type.values:
setattr(cls, enum_value.name, enum_value.number) | [
"def",
"_AddEnumValues",
"(",
"descriptor",
",",
"cls",
")",
":",
"for",
"enum_type",
"in",
"descriptor",
".",
"enum_types",
":",
"setattr",
"(",
"cls",
",",
"enum_type",
".",
"name",
",",
"enum_type_wrapper",
".",
"EnumTypeWrapper",
"(",
"enum_type",
")",
")",
"for",
"enum_value",
"in",
"enum_type",
".",
"values",
":",
"setattr",
"(",
"cls",
",",
"enum_value",
".",
"name",
",",
"enum_value",
".",
"number",
")"
] | https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/python_message.py#L233-L245 |
||
etotheipi/BitcoinArmory | 2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98 | armoryengine/Networking.py | python | ArmoryClient.dataReceived | (self, data) | Called by the reactor when data is received over the connection.
This method will do nothing if we don't receive a full message. | Called by the reactor when data is received over the connection.
This method will do nothing if we don't receive a full message. | [
"Called",
"by",
"the",
"reactor",
"when",
"data",
"is",
"received",
"over",
"the",
"connection",
".",
"This",
"method",
"will",
"do",
"nothing",
"if",
"we",
"don",
"t",
"receive",
"a",
"full",
"message",
"."
] | def dataReceived(self, data):
"""
Called by the reactor when data is received over the connection.
This method will do nothing if we don't receive a full message.
"""
#print '\n\nData Received:',
#pprintHex(binary_to_hex(data), withAddr=False)
# Put the current buffer into an unpacker, process until empty
self.recvData += data
buf = BinaryUnpacker(self.recvData)
messages = []
while True:
try:
# recvData is only modified if the unserialize succeeds
# Had a serious issue with references, so I had to convert
# messages to strings to guarantee that copies were being
# made! (yes, hacky...)
thisMsg = PyMessage().unserialize(buf)
messages.append( thisMsg.serialize() )
self.recvData = buf.getRemainingString()
except NetworkIDError:
LOGERROR('Message for a different network!' )
if BLOCKCHAINS.has_key(self.recvData[:4]):
LOGERROR( '(for network: %s)', BLOCKCHAINS[self.recvData[:4]])
# Before raising the error, we should've finished reading the msg
# So pop it off the front of the buffer
self.recvData = buf.getRemainingString()
return
except UnknownNetworkPayload:
return
except UnpackerError:
# Expect this error when buffer isn't full enough for a whole msg
break
# We might've gotten here without anything to process -- if so, bail
if len(messages)==0:
return
# Finally, we have some message to process, let's do it
for msgStr in messages:
msg = PyMessage().unserialize(msgStr)
cmd = msg.cmd
# Log the message if netlog option
if CLI_OPTIONS.netlog:
LOGDEBUG( 'DataReceived: %s', msg.payload.command)
if msg.payload.command == 'tx':
LOGDEBUG('\t' + binary_to_hex(msg.payload.tx.thisHash))
elif msg.payload.command == 'block':
LOGDEBUG('\t' + msg.payload.header.getHashHex())
elif msg.payload.command == 'inv':
for inv in msg.payload.invList:
LOGDEBUG(('\tBLOCK: ' if inv[0]==2 else '\tTX : ') + \
binary_to_hex(inv[1]))
# We process version and verackk only if we haven't yet
if cmd=='version' and not self.sentVerack:
self.peerInfo = {}
self.peerInfo['version'] = msg.payload.version
self.peerInfo['subver'] = msg.payload.subver
self.peerInfo['time'] = msg.payload.time
self.peerInfo['height'] = msg.payload.height0
LOGINFO('Received version message from peer:')
LOGINFO(' Version: %s', str(self.peerInfo['version']))
LOGINFO(' SubVersion: %s', str(self.peerInfo['subver']))
LOGINFO(' TimeStamp: %s', str(self.peerInfo['time']))
LOGINFO(' StartHeight: %s', str(self.peerInfo['height']))
self.sentVerack = True
self.sendMessage( PayloadVerack() )
elif cmd=='verack':
self.gotVerack = True
self.factory.handshakeFinished(self)
#self.startHeaderDL()
####################################################################
# Don't process any other messages unless the handshake is finished
if self.gotVerack and self.sentVerack:
self.processMessage(msg) | [
"def",
"dataReceived",
"(",
"self",
",",
"data",
")",
":",
"#print '\\n\\nData Received:',",
"#pprintHex(binary_to_hex(data), withAddr=False)",
"# Put the current buffer into an unpacker, process until empty",
"self",
".",
"recvData",
"+=",
"data",
"buf",
"=",
"BinaryUnpacker",
"(",
"self",
".",
"recvData",
")",
"messages",
"=",
"[",
"]",
"while",
"True",
":",
"try",
":",
"# recvData is only modified if the unserialize succeeds",
"# Had a serious issue with references, so I had to convert ",
"# messages to strings to guarantee that copies were being ",
"# made! (yes, hacky...)",
"thisMsg",
"=",
"PyMessage",
"(",
")",
".",
"unserialize",
"(",
"buf",
")",
"messages",
".",
"append",
"(",
"thisMsg",
".",
"serialize",
"(",
")",
")",
"self",
".",
"recvData",
"=",
"buf",
".",
"getRemainingString",
"(",
")",
"except",
"NetworkIDError",
":",
"LOGERROR",
"(",
"'Message for a different network!'",
")",
"if",
"BLOCKCHAINS",
".",
"has_key",
"(",
"self",
".",
"recvData",
"[",
":",
"4",
"]",
")",
":",
"LOGERROR",
"(",
"'(for network: %s)'",
",",
"BLOCKCHAINS",
"[",
"self",
".",
"recvData",
"[",
":",
"4",
"]",
"]",
")",
"# Before raising the error, we should've finished reading the msg",
"# So pop it off the front of the buffer",
"self",
".",
"recvData",
"=",
"buf",
".",
"getRemainingString",
"(",
")",
"return",
"except",
"UnknownNetworkPayload",
":",
"return",
"except",
"UnpackerError",
":",
"# Expect this error when buffer isn't full enough for a whole msg",
"break",
"# We might've gotten here without anything to process -- if so, bail",
"if",
"len",
"(",
"messages",
")",
"==",
"0",
":",
"return",
"# Finally, we have some message to process, let's do it",
"for",
"msgStr",
"in",
"messages",
":",
"msg",
"=",
"PyMessage",
"(",
")",
".",
"unserialize",
"(",
"msgStr",
")",
"cmd",
"=",
"msg",
".",
"cmd",
"# Log the message if netlog option",
"if",
"CLI_OPTIONS",
".",
"netlog",
":",
"LOGDEBUG",
"(",
"'DataReceived: %s'",
",",
"msg",
".",
"payload",
".",
"command",
")",
"if",
"msg",
".",
"payload",
".",
"command",
"==",
"'tx'",
":",
"LOGDEBUG",
"(",
"'\\t'",
"+",
"binary_to_hex",
"(",
"msg",
".",
"payload",
".",
"tx",
".",
"thisHash",
")",
")",
"elif",
"msg",
".",
"payload",
".",
"command",
"==",
"'block'",
":",
"LOGDEBUG",
"(",
"'\\t'",
"+",
"msg",
".",
"payload",
".",
"header",
".",
"getHashHex",
"(",
")",
")",
"elif",
"msg",
".",
"payload",
".",
"command",
"==",
"'inv'",
":",
"for",
"inv",
"in",
"msg",
".",
"payload",
".",
"invList",
":",
"LOGDEBUG",
"(",
"(",
"'\\tBLOCK: '",
"if",
"inv",
"[",
"0",
"]",
"==",
"2",
"else",
"'\\tTX : '",
")",
"+",
"binary_to_hex",
"(",
"inv",
"[",
"1",
"]",
")",
")",
"# We process version and verackk only if we haven't yet",
"if",
"cmd",
"==",
"'version'",
"and",
"not",
"self",
".",
"sentVerack",
":",
"self",
".",
"peerInfo",
"=",
"{",
"}",
"self",
".",
"peerInfo",
"[",
"'version'",
"]",
"=",
"msg",
".",
"payload",
".",
"version",
"self",
".",
"peerInfo",
"[",
"'subver'",
"]",
"=",
"msg",
".",
"payload",
".",
"subver",
"self",
".",
"peerInfo",
"[",
"'time'",
"]",
"=",
"msg",
".",
"payload",
".",
"time",
"self",
".",
"peerInfo",
"[",
"'height'",
"]",
"=",
"msg",
".",
"payload",
".",
"height0",
"LOGINFO",
"(",
"'Received version message from peer:'",
")",
"LOGINFO",
"(",
"' Version: %s'",
",",
"str",
"(",
"self",
".",
"peerInfo",
"[",
"'version'",
"]",
")",
")",
"LOGINFO",
"(",
"' SubVersion: %s'",
",",
"str",
"(",
"self",
".",
"peerInfo",
"[",
"'subver'",
"]",
")",
")",
"LOGINFO",
"(",
"' TimeStamp: %s'",
",",
"str",
"(",
"self",
".",
"peerInfo",
"[",
"'time'",
"]",
")",
")",
"LOGINFO",
"(",
"' StartHeight: %s'",
",",
"str",
"(",
"self",
".",
"peerInfo",
"[",
"'height'",
"]",
")",
")",
"self",
".",
"sentVerack",
"=",
"True",
"self",
".",
"sendMessage",
"(",
"PayloadVerack",
"(",
")",
")",
"elif",
"cmd",
"==",
"'verack'",
":",
"self",
".",
"gotVerack",
"=",
"True",
"self",
".",
"factory",
".",
"handshakeFinished",
"(",
"self",
")",
"#self.startHeaderDL()",
"####################################################################",
"# Don't process any other messages unless the handshake is finished",
"if",
"self",
".",
"gotVerack",
"and",
"self",
".",
"sentVerack",
":",
"self",
".",
"processMessage",
"(",
"msg",
")"
] | https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/armoryengine/Networking.py#L88-L171 |
||
liuzechun/Bi-Real-net | f58aa4d1fa730fcd2e33c3745fcd6c479d7f42e3 | pytorch_implementation/BiReal_50/birealnet.py | python | binaryconv3x3 | (in_planes, out_planes, stride=1) | return HardBinaryConv(in_planes, out_planes, kernel_size=3, stride=stride, padding=1) | 3x3 convolution with padding | 3x3 convolution with padding | [
"3x3",
"convolution",
"with",
"padding"
] | def binaryconv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return HardBinaryConv(in_planes, out_planes, kernel_size=3, stride=stride, padding=1) | [
"def",
"binaryconv3x3",
"(",
"in_planes",
",",
"out_planes",
",",
"stride",
"=",
"1",
")",
":",
"return",
"HardBinaryConv",
"(",
"in_planes",
",",
"out_planes",
",",
"kernel_size",
"=",
"3",
",",
"stride",
"=",
"stride",
",",
"padding",
"=",
"1",
")"
] | https://github.com/liuzechun/Bi-Real-net/blob/f58aa4d1fa730fcd2e33c3745fcd6c479d7f42e3/pytorch_implementation/BiReal_50/birealnet.py#L18-L20 |
|
bryanyzhu/Hidden-Two-Stream | f7f684adbdacb6df6b1cf196c3a476cd23484a0f | scripts/cpp_lint.py | python | _IncludeState.IsInAlphabeticalOrder | (self, clean_lines, linenum, header_path) | return True | Check if a header is in alphabetical order with the previous header.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
header_path: Canonicalized header to be checked.
Returns:
Returns true if the header is in alphabetical order. | Check if a header is in alphabetical order with the previous header. | [
"Check",
"if",
"a",
"header",
"is",
"in",
"alphabetical",
"order",
"with",
"the",
"previous",
"header",
"."
] | def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):
"""Check if a header is in alphabetical order with the previous header.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
header_path: Canonicalized header to be checked.
Returns:
Returns true if the header is in alphabetical order.
"""
# If previous section is different from current section, _last_header will
# be reset to empty string, so it's always less than current header.
#
# If previous line was a blank line, assume that the headers are
# intentionally sorted the way they are.
if (self._last_header > header_path and
not Match(r'^\s*$', clean_lines.elided[linenum - 1])):
return False
return True | [
"def",
"IsInAlphabeticalOrder",
"(",
"self",
",",
"clean_lines",
",",
"linenum",
",",
"header_path",
")",
":",
"# If previous section is different from current section, _last_header will",
"# be reset to empty string, so it's always less than current header.",
"#",
"# If previous line was a blank line, assume that the headers are",
"# intentionally sorted the way they are.",
"if",
"(",
"self",
".",
"_last_header",
">",
"header_path",
"and",
"not",
"Match",
"(",
"r'^\\s*$'",
",",
"clean_lines",
".",
"elided",
"[",
"linenum",
"-",
"1",
"]",
")",
")",
":",
"return",
"False",
"return",
"True"
] | https://github.com/bryanyzhu/Hidden-Two-Stream/blob/f7f684adbdacb6df6b1cf196c3a476cd23484a0f/scripts/cpp_lint.py#L612-L631 |
|
acado/acado | b4e28f3131f79cadfd1a001e9fff061f361d3a0f | misc/cpplint.py | python | CheckBraces | (filename, clean_lines, linenum, error) | Looks for misplaced braces (e.g. at the end of line).
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Looks for misplaced braces (e.g. at the end of line). | [
"Looks",
"for",
"misplaced",
"braces",
"(",
"e",
".",
"g",
".",
"at",
"the",
"end",
"of",
"line",
")",
"."
] | def CheckBraces(filename, clean_lines, linenum, error):
"""Looks for misplaced braces (e.g. at the end of line).
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum] # get rid of comments and strings
if Match(r'\s*{\s*$', line):
# We allow an open brace to start a line in the case where someone is using
# braces in a block to explicitly create a new scope, which is commonly used
# to control the lifetime of stack-allocated variables. Braces are also
# used for brace initializers inside function calls. We don't detect this
# perfectly: we just don't complain if the last non-whitespace character on
# the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
# previous line starts a preprocessor block.
prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
if (not Search(r'[,;:}{(]\s*$', prevline) and
not Match(r'\s*#', prevline)):
error(filename, linenum, 'whitespace/braces', 4,
'{ should almost always be at the end of the previous line')
# An else clause should be on the same line as the preceding closing brace.
if Match(r'\s*else\s*', line):
prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
if Match(r'\s*}\s*$', prevline):
error(filename, linenum, 'whitespace/newline', 4,
'An else should appear on the same line as the preceding }')
# If braces come on one side of an else, they should be on both.
# However, we have to worry about "else if" that spans multiple lines!
if Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
if Search(r'}\s*else if([^{]*)$', line): # could be multi-line if
# find the ( after the if
pos = line.find('else if')
pos = line.find('(', pos)
if pos > 0:
(endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
if endline[endpos:].find('{') == -1: # must be brace after if
error(filename, linenum, 'readability/braces', 5,
'If an else has a brace on one side, it should have it on both')
else: # common case: else not followed by a multi-line if
error(filename, linenum, 'readability/braces', 5,
'If an else has a brace on one side, it should have it on both')
# Likewise, an else should never have the else clause on the same line
if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
error(filename, linenum, 'whitespace/newline', 4,
'Else clause should never be on same line as else (use 2 lines)')
# In the same way, a do/while should never be on one line
if Match(r'\s*do [^\s{]', line):
error(filename, linenum, 'whitespace/newline', 4,
'do/while clauses should not be on a single line')
# Block bodies should not be followed by a semicolon. Due to C++11
# brace initialization, there are more places where semicolons are
# required than not, so we use a whitelist approach to check these
# rather than a blacklist. These are the places where "};" should
# be replaced by just "}":
# 1. Some flavor of block following closing parenthesis:
# for (;;) {};
# while (...) {};
# switch (...) {};
# Function(...) {};
# if (...) {};
# if (...) else if (...) {};
#
# 2. else block:
# if (...) else {};
#
# 3. const member function:
# Function(...) const {};
#
# 4. Block following some statement:
# x = 42;
# {};
#
# 5. Block at the beginning of a function:
# Function(...) {
# {};
# }
#
# Note that naively checking for the preceding "{" will also match
# braces inside multi-dimensional arrays, but this is fine since
# that expression will not contain semicolons.
#
# 6. Block following another block:
# while (true) {}
# {};
#
# 7. End of namespaces:
# namespace {};
#
# These semicolons seems far more common than other kinds of
# redundant semicolons, possibly due to people converting classes
# to namespaces. For now we do not warn for this case.
#
# Try matching case 1 first.
match = Match(r'^(.*\)\s*)\{', line)
if match:
# Matched closing parenthesis (case 1). Check the token before the
# matching opening parenthesis, and don't warn if it looks like a
# macro. This avoids these false positives:
# - macro that defines a base class
# - multi-line macro that defines a base class
# - macro that defines the whole class-head
#
# But we still issue warnings for macros that we know are safe to
# warn, specifically:
# - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
# - TYPED_TEST
# - INTERFACE_DEF
# - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
#
# We implement a whitelist of safe macros instead of a blacklist of
# unsafe macros, even though the latter appears less frequently in
# google code and would have been easier to implement. This is because
# the downside for getting the whitelist wrong means some extra
# semicolons, while the downside for getting the blacklist wrong
# would result in compile errors.
#
# In addition to macros, we also don't want to warn on compound
# literals.
closing_brace_pos = match.group(1).rfind(')')
opening_parenthesis = ReverseCloseExpression(
clean_lines, linenum, closing_brace_pos)
if opening_parenthesis[2] > -1:
line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]
macro = Search(r'\b([A-Z_]+)\s*$', line_prefix)
if ((macro and
macro.group(1) not in (
'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',
'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',
'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or
Search(r'\s+=\s*$', line_prefix)):
match = None
else:
# Try matching cases 2-3.
match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)
if not match:
# Try matching cases 4-6. These are always matched on separate lines.
#
# Note that we can't simply concatenate the previous line to the
# current line and do a single match, otherwise we may output
# duplicate warnings for the blank line case:
# if (cond) {
# // blank line
# }
prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
if prevline and Search(r'[;{}]\s*$', prevline):
match = Match(r'^(\s*)\{', line)
# Check matching closing brace
if match:
(endline, endlinenum, endpos) = CloseExpression(
clean_lines, linenum, len(match.group(1)))
if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
# Current {} pair is eligible for semicolon check, and we have found
# the redundant semicolon, output warning here.
#
# Note: because we are scanning forward for opening braces, and
# outputting warnings for the matching closing brace, if there are
# nested blocks with trailing semicolons, we will get the error
# messages in reversed order.
error(filename, endlinenum, 'readability/braces', 4,
"You don't need a ; after a }") | [
"def",
"CheckBraces",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# get rid of comments and strings",
"if",
"Match",
"(",
"r'\\s*{\\s*$'",
",",
"line",
")",
":",
"# We allow an open brace to start a line in the case where someone is using",
"# braces in a block to explicitly create a new scope, which is commonly used",
"# to control the lifetime of stack-allocated variables. Braces are also",
"# used for brace initializers inside function calls. We don't detect this",
"# perfectly: we just don't complain if the last non-whitespace character on",
"# the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the",
"# previous line starts a preprocessor block.",
"prevline",
"=",
"GetPreviousNonBlankLine",
"(",
"clean_lines",
",",
"linenum",
")",
"[",
"0",
"]",
"if",
"(",
"not",
"Search",
"(",
"r'[,;:}{(]\\s*$'",
",",
"prevline",
")",
"and",
"not",
"Match",
"(",
"r'\\s*#'",
",",
"prevline",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/braces'",
",",
"4",
",",
"'{ should almost always be at the end of the previous line'",
")",
"# An else clause should be on the same line as the preceding closing brace.",
"if",
"Match",
"(",
"r'\\s*else\\s*'",
",",
"line",
")",
":",
"prevline",
"=",
"GetPreviousNonBlankLine",
"(",
"clean_lines",
",",
"linenum",
")",
"[",
"0",
"]",
"if",
"Match",
"(",
"r'\\s*}\\s*$'",
",",
"prevline",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/newline'",
",",
"4",
",",
"'An else should appear on the same line as the preceding }'",
")",
"# If braces come on one side of an else, they should be on both.",
"# However, we have to worry about \"else if\" that spans multiple lines!",
"if",
"Search",
"(",
"r'}\\s*else[^{]*$'",
",",
"line",
")",
"or",
"Match",
"(",
"r'[^}]*else\\s*{'",
",",
"line",
")",
":",
"if",
"Search",
"(",
"r'}\\s*else if([^{]*)$'",
",",
"line",
")",
":",
"# could be multi-line if",
"# find the ( after the if",
"pos",
"=",
"line",
".",
"find",
"(",
"'else if'",
")",
"pos",
"=",
"line",
".",
"find",
"(",
"'('",
",",
"pos",
")",
"if",
"pos",
">",
"0",
":",
"(",
"endline",
",",
"_",
",",
"endpos",
")",
"=",
"CloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"pos",
")",
"if",
"endline",
"[",
"endpos",
":",
"]",
".",
"find",
"(",
"'{'",
")",
"==",
"-",
"1",
":",
"# must be brace after if",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/braces'",
",",
"5",
",",
"'If an else has a brace on one side, it should have it on both'",
")",
"else",
":",
"# common case: else not followed by a multi-line if",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/braces'",
",",
"5",
",",
"'If an else has a brace on one side, it should have it on both'",
")",
"# Likewise, an else should never have the else clause on the same line",
"if",
"Search",
"(",
"r'\\belse [^\\s{]'",
",",
"line",
")",
"and",
"not",
"Search",
"(",
"r'\\belse if\\b'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/newline'",
",",
"4",
",",
"'Else clause should never be on same line as else (use 2 lines)'",
")",
"# In the same way, a do/while should never be on one line",
"if",
"Match",
"(",
"r'\\s*do [^\\s{]'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/newline'",
",",
"4",
",",
"'do/while clauses should not be on a single line'",
")",
"# Block bodies should not be followed by a semicolon. Due to C++11",
"# brace initialization, there are more places where semicolons are",
"# required than not, so we use a whitelist approach to check these",
"# rather than a blacklist. These are the places where \"};\" should",
"# be replaced by just \"}\":",
"# 1. Some flavor of block following closing parenthesis:",
"# for (;;) {};",
"# while (...) {};",
"# switch (...) {};",
"# Function(...) {};",
"# if (...) {};",
"# if (...) else if (...) {};",
"#",
"# 2. else block:",
"# if (...) else {};",
"#",
"# 3. const member function:",
"# Function(...) const {};",
"#",
"# 4. Block following some statement:",
"# x = 42;",
"# {};",
"#",
"# 5. Block at the beginning of a function:",
"# Function(...) {",
"# {};",
"# }",
"#",
"# Note that naively checking for the preceding \"{\" will also match",
"# braces inside multi-dimensional arrays, but this is fine since",
"# that expression will not contain semicolons.",
"#",
"# 6. Block following another block:",
"# while (true) {}",
"# {};",
"#",
"# 7. End of namespaces:",
"# namespace {};",
"#",
"# These semicolons seems far more common than other kinds of",
"# redundant semicolons, possibly due to people converting classes",
"# to namespaces. For now we do not warn for this case.",
"#",
"# Try matching case 1 first.",
"match",
"=",
"Match",
"(",
"r'^(.*\\)\\s*)\\{'",
",",
"line",
")",
"if",
"match",
":",
"# Matched closing parenthesis (case 1). Check the token before the",
"# matching opening parenthesis, and don't warn if it looks like a",
"# macro. This avoids these false positives:",
"# - macro that defines a base class",
"# - multi-line macro that defines a base class",
"# - macro that defines the whole class-head",
"#",
"# But we still issue warnings for macros that we know are safe to",
"# warn, specifically:",
"# - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P",
"# - TYPED_TEST",
"# - INTERFACE_DEF",
"# - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:",
"#",
"# We implement a whitelist of safe macros instead of a blacklist of",
"# unsafe macros, even though the latter appears less frequently in",
"# google code and would have been easier to implement. This is because",
"# the downside for getting the whitelist wrong means some extra",
"# semicolons, while the downside for getting the blacklist wrong",
"# would result in compile errors.",
"#",
"# In addition to macros, we also don't want to warn on compound",
"# literals.",
"closing_brace_pos",
"=",
"match",
".",
"group",
"(",
"1",
")",
".",
"rfind",
"(",
"')'",
")",
"opening_parenthesis",
"=",
"ReverseCloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"closing_brace_pos",
")",
"if",
"opening_parenthesis",
"[",
"2",
"]",
">",
"-",
"1",
":",
"line_prefix",
"=",
"opening_parenthesis",
"[",
"0",
"]",
"[",
"0",
":",
"opening_parenthesis",
"[",
"2",
"]",
"]",
"macro",
"=",
"Search",
"(",
"r'\\b([A-Z_]+)\\s*$'",
",",
"line_prefix",
")",
"if",
"(",
"(",
"macro",
"and",
"macro",
".",
"group",
"(",
"1",
")",
"not",
"in",
"(",
"'TEST'",
",",
"'TEST_F'",
",",
"'MATCHER'",
",",
"'MATCHER_P'",
",",
"'TYPED_TEST'",
",",
"'EXCLUSIVE_LOCKS_REQUIRED'",
",",
"'SHARED_LOCKS_REQUIRED'",
",",
"'LOCKS_EXCLUDED'",
",",
"'INTERFACE_DEF'",
")",
")",
"or",
"Search",
"(",
"r'\\s+=\\s*$'",
",",
"line_prefix",
")",
")",
":",
"match",
"=",
"None",
"else",
":",
"# Try matching cases 2-3.",
"match",
"=",
"Match",
"(",
"r'^(.*(?:else|\\)\\s*const)\\s*)\\{'",
",",
"line",
")",
"if",
"not",
"match",
":",
"# Try matching cases 4-6. These are always matched on separate lines.",
"#",
"# Note that we can't simply concatenate the previous line to the",
"# current line and do a single match, otherwise we may output",
"# duplicate warnings for the blank line case:",
"# if (cond) {",
"# // blank line",
"# }",
"prevline",
"=",
"GetPreviousNonBlankLine",
"(",
"clean_lines",
",",
"linenum",
")",
"[",
"0",
"]",
"if",
"prevline",
"and",
"Search",
"(",
"r'[;{}]\\s*$'",
",",
"prevline",
")",
":",
"match",
"=",
"Match",
"(",
"r'^(\\s*)\\{'",
",",
"line",
")",
"# Check matching closing brace",
"if",
"match",
":",
"(",
"endline",
",",
"endlinenum",
",",
"endpos",
")",
"=",
"CloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"len",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
")",
"if",
"endpos",
">",
"-",
"1",
"and",
"Match",
"(",
"r'^\\s*;'",
",",
"endline",
"[",
"endpos",
":",
"]",
")",
":",
"# Current {} pair is eligible for semicolon check, and we have found",
"# the redundant semicolon, output warning here.",
"#",
"# Note: because we are scanning forward for opening braces, and",
"# outputting warnings for the matching closing brace, if there are",
"# nested blocks with trailing semicolons, we will get the error",
"# messages in reversed order.",
"error",
"(",
"filename",
",",
"endlinenum",
",",
"'readability/braces'",
",",
"4",
",",
"\"You don't need a ; after a }\"",
")"
] | https://github.com/acado/acado/blob/b4e28f3131f79cadfd1a001e9fff061f361d3a0f/misc/cpplint.py#L2961-L3132 |
||
psnonis/FinBERT | c0c555d833a14e2316a3701e59c0b5156f804b4e | data/prep/tokenization.py | python | _is_whitespace | (char) | return False | Checks whether `chars` is a whitespace character. | Checks whether `chars` is a whitespace character. | [
"Checks",
"whether",
"chars",
"is",
"a",
"whitespace",
"character",
"."
] | def _is_whitespace(char):
"""Checks whether `chars` is a whitespace character."""
# \t, \n, and \r are technically contorl characters but we treat them
# as whitespace since they are generally considered as such.
if char == " " or char == "\t" or char == "\n" or char == "\r":
return True
cat = unicodedata.category(char)
if cat == "Zs":
return True
return False | [
"def",
"_is_whitespace",
"(",
"char",
")",
":",
"# \\t, \\n, and \\r are technically contorl characters but we treat them",
"# as whitespace since they are generally considered as such.",
"if",
"char",
"==",
"\" \"",
"or",
"char",
"==",
"\"\\t\"",
"or",
"char",
"==",
"\"\\n\"",
"or",
"char",
"==",
"\"\\r\"",
":",
"return",
"True",
"cat",
"=",
"unicodedata",
".",
"category",
"(",
"char",
")",
"if",
"cat",
"==",
"\"Zs\"",
":",
"return",
"True",
"return",
"False"
] | https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/data/prep/tokenization.py#L362-L371 |
|
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/max-chunks-to-make-sorted-ii.py | python | Solution2.maxChunksToSorted | (self, arr) | return result | :type arr: List[int]
:rtype: int | :type arr: List[int]
:rtype: int | [
":",
"type",
"arr",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"int"
] | def maxChunksToSorted(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
def compare(i1, i2):
return arr[i1]-arr[i2] if arr[i1] != arr[i2] else i1-i2
idxs = [i for i in xrange(len(arr))]
result, max_i = 0, 0
for i, v in enumerate(sorted(idxs, cmp=compare)):
max_i = max(max_i, v)
if max_i == i:
result += 1
return result | [
"def",
"maxChunksToSorted",
"(",
"self",
",",
"arr",
")",
":",
"def",
"compare",
"(",
"i1",
",",
"i2",
")",
":",
"return",
"arr",
"[",
"i1",
"]",
"-",
"arr",
"[",
"i2",
"]",
"if",
"arr",
"[",
"i1",
"]",
"!=",
"arr",
"[",
"i2",
"]",
"else",
"i1",
"-",
"i2",
"idxs",
"=",
"[",
"i",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"arr",
")",
")",
"]",
"result",
",",
"max_i",
"=",
"0",
",",
"0",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"sorted",
"(",
"idxs",
",",
"cmp",
"=",
"compare",
")",
")",
":",
"max_i",
"=",
"max",
"(",
"max_i",
",",
"v",
")",
"if",
"max_i",
"==",
"i",
":",
"result",
"+=",
"1",
"return",
"result"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/max-chunks-to-make-sorted-ii.py#L23-L37 |
|
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/plat-riscos/riscospath.py | python | isfile | (p) | Test whether a path is a file, including image files. | Test whether a path is a file, including image files. | [
"Test",
"whether",
"a",
"path",
"is",
"a",
"file",
"including",
"image",
"files",
"."
] | def isfile(p):
"""
Test whether a path is a file, including image files.
"""
try:
return swi.swi('OS_File', '5s;i', p) in [1, 3]
except swi.error:
return 0 | [
"def",
"isfile",
"(",
"p",
")",
":",
"try",
":",
"return",
"swi",
".",
"swi",
"(",
"'OS_File'",
",",
"'5s;i'",
",",
"p",
")",
"in",
"[",
"1",
",",
"3",
"]",
"except",
"swi",
".",
"error",
":",
"return",
"0"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/plat-riscos/riscospath.py#L227-L234 |
||
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/agilepy/lib_wx/toolbox.py | python | ToolsPanel.unselect_tool | (self) | Unselect currently selected tool. | Unselect currently selected tool. | [
"Unselect",
"currently",
"selected",
"tool",
"."
] | def unselect_tool(self):
"""
Unselect currently selected tool.
"""
self._toolspalett.unselect() | [
"def",
"unselect_tool",
"(",
"self",
")",
":",
"self",
".",
"_toolspalett",
".",
"unselect",
"(",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_wx/toolbox.py#L540-L544 |
||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py | python | Misc.grid_location | (self, x, y) | return self._getints(
self.tk.call(
'grid', 'location', self._w, x, y)) or None | Return a tuple of column and row which identify the cell
at which the pixel at position X and Y inside the master
widget is located. | Return a tuple of column and row which identify the cell
at which the pixel at position X and Y inside the master
widget is located. | [
"Return",
"a",
"tuple",
"of",
"column",
"and",
"row",
"which",
"identify",
"the",
"cell",
"at",
"which",
"the",
"pixel",
"at",
"position",
"X",
"and",
"Y",
"inside",
"the",
"master",
"widget",
"is",
"located",
"."
] | def grid_location(self, x, y):
"""Return a tuple of column and row which identify the cell
at which the pixel at position X and Y inside the master
widget is located."""
return self._getints(
self.tk.call(
'grid', 'location', self._w, x, y)) or None | [
"def",
"grid_location",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"return",
"self",
".",
"_getints",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"'grid'",
",",
"'location'",
",",
"self",
".",
"_w",
",",
"x",
",",
"y",
")",
")",
"or",
"None"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L1607-L1613 |
|
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/maximum-product-of-two-elements-in-an-array.py | python | Solution.maxProduct | (self, nums) | return (m1-1)*(m2-1) | :type nums: List[int]
:rtype: int | :type nums: List[int]
:rtype: int | [
":",
"type",
"nums",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"int"
] | def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
m1 = m2 = 0
for num in nums:
if num > m1:
m1, m2 = num, m1
elif num > m2:
m2 = num
return (m1-1)*(m2-1) | [
"def",
"maxProduct",
"(",
"self",
",",
"nums",
")",
":",
"m1",
"=",
"m2",
"=",
"0",
"for",
"num",
"in",
"nums",
":",
"if",
"num",
">",
"m1",
":",
"m1",
",",
"m2",
"=",
"num",
",",
"m1",
"elif",
"num",
">",
"m2",
":",
"m2",
"=",
"num",
"return",
"(",
"m1",
"-",
"1",
")",
"*",
"(",
"m2",
"-",
"1",
")"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/maximum-product-of-two-elements-in-an-array.py#L5-L16 |
|
moflow/moflow | 2dfb27c799c90c6caf1477508eca3eec616ef7d2 | bap/libtracewrap/libtrace/protobuf/python/google/protobuf/text_format.py | python | _Tokenizer.ConsumeUint64 | (self) | return result | Consumes an unsigned 64bit integer number.
Returns:
The integer parsed.
Raises:
ParseError: If an unsigned 64bit integer couldn't be consumed. | Consumes an unsigned 64bit integer number. | [
"Consumes",
"an",
"unsigned",
"64bit",
"integer",
"number",
"."
] | def ConsumeUint64(self):
"""Consumes an unsigned 64bit integer number.
Returns:
The integer parsed.
Raises:
ParseError: If an unsigned 64bit integer couldn't be consumed.
"""
try:
result = ParseInteger(self.token, is_signed=False, is_long=True)
except ValueError, e:
raise self._ParseError(str(e))
self.NextToken()
return result | [
"def",
"ConsumeUint64",
"(",
"self",
")",
":",
"try",
":",
"result",
"=",
"ParseInteger",
"(",
"self",
".",
"token",
",",
"is_signed",
"=",
"False",
",",
"is_long",
"=",
"True",
")",
"except",
"ValueError",
",",
"e",
":",
"raise",
"self",
".",
"_ParseError",
"(",
"str",
"(",
"e",
")",
")",
"self",
".",
"NextToken",
"(",
")",
"return",
"result"
] | https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/google/protobuf/text_format.py#L443-L457 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | TextEntryBase.AutoComplete | (*args, **kwargs) | return _core_.TextEntryBase_AutoComplete(*args, **kwargs) | AutoComplete(self, wxArrayString choices) -> bool | AutoComplete(self, wxArrayString choices) -> bool | [
"AutoComplete",
"(",
"self",
"wxArrayString",
"choices",
")",
"-",
">",
"bool"
] | def AutoComplete(*args, **kwargs):
"""AutoComplete(self, wxArrayString choices) -> bool"""
return _core_.TextEntryBase_AutoComplete(*args, **kwargs) | [
"def",
"AutoComplete",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"TextEntryBase_AutoComplete",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L13320-L13322 |
|
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/Chem/Pharm2D/SigFactory.py | python | SigFactory.GetBitInfo | (self, idx) | return nPts, combo, scaffold | returns information about the given bit
**Arguments**
- idx: the bit index to be considered
**Returns**
a 3-tuple:
1) the number of points in the pharmacophore
2) the proto-pharmacophore (tuple of pattern indices)
3) the scaffold (tuple of distance indices) | returns information about the given bit | [
"returns",
"information",
"about",
"the",
"given",
"bit"
] | def GetBitInfo(self, idx):
""" returns information about the given bit
**Arguments**
- idx: the bit index to be considered
**Returns**
a 3-tuple:
1) the number of points in the pharmacophore
2) the proto-pharmacophore (tuple of pattern indices)
3) the scaffold (tuple of distance indices)
"""
if idx >= self._sigSize:
raise IndexError(f'bad index ({idx}) queried. {self._sigSize} is the max')
# first figure out how many points are in the p'cophore
nPts = self.minPointCount
while nPts < self.maxPointCount and self._starts[nPts + 1] <= idx:
nPts += 1
# how far are we in from the start point?
offsetFromStart = idx - self._starts[nPts]
if _verbose:
print(f'\t {nPts} Points, {offsetFromStart} offset')
# lookup the number of scaffolds
nDists = len(Utils.nPointDistDict[nPts])
scaffolds = self._scaffolds[nDists]
nScaffolds = len(scaffolds)
# figure out to which proto-pharmacophore we belong:
protoIdx = offsetFromStart // nScaffolds
indexCombos = Utils.GetIndexCombinations(self._nFeats, nPts)
combo = tuple(indexCombos[protoIdx])
if _verbose:
print(f'\t combo: {str(combo)}')
# and which scaffold:
scaffoldIdx = offsetFromStart % nScaffolds
scaffold = scaffolds[scaffoldIdx]
if _verbose:
print(f'\t scaffold: {str(scaffold)}')
return nPts, combo, scaffold | [
"def",
"GetBitInfo",
"(",
"self",
",",
"idx",
")",
":",
"if",
"idx",
">=",
"self",
".",
"_sigSize",
":",
"raise",
"IndexError",
"(",
"f'bad index ({idx}) queried. {self._sigSize} is the max'",
")",
"# first figure out how many points are in the p'cophore",
"nPts",
"=",
"self",
".",
"minPointCount",
"while",
"nPts",
"<",
"self",
".",
"maxPointCount",
"and",
"self",
".",
"_starts",
"[",
"nPts",
"+",
"1",
"]",
"<=",
"idx",
":",
"nPts",
"+=",
"1",
"# how far are we in from the start point?",
"offsetFromStart",
"=",
"idx",
"-",
"self",
".",
"_starts",
"[",
"nPts",
"]",
"if",
"_verbose",
":",
"print",
"(",
"f'\\t {nPts} Points, {offsetFromStart} offset'",
")",
"# lookup the number of scaffolds",
"nDists",
"=",
"len",
"(",
"Utils",
".",
"nPointDistDict",
"[",
"nPts",
"]",
")",
"scaffolds",
"=",
"self",
".",
"_scaffolds",
"[",
"nDists",
"]",
"nScaffolds",
"=",
"len",
"(",
"scaffolds",
")",
"# figure out to which proto-pharmacophore we belong:",
"protoIdx",
"=",
"offsetFromStart",
"//",
"nScaffolds",
"indexCombos",
"=",
"Utils",
".",
"GetIndexCombinations",
"(",
"self",
".",
"_nFeats",
",",
"nPts",
")",
"combo",
"=",
"tuple",
"(",
"indexCombos",
"[",
"protoIdx",
"]",
")",
"if",
"_verbose",
":",
"print",
"(",
"f'\\t combo: {str(combo)}'",
")",
"# and which scaffold:",
"scaffoldIdx",
"=",
"offsetFromStart",
"%",
"nScaffolds",
"scaffold",
"=",
"scaffolds",
"[",
"scaffoldIdx",
"]",
"if",
"_verbose",
":",
"print",
"(",
"f'\\t scaffold: {str(scaffold)}'",
")",
"return",
"nPts",
",",
"combo",
",",
"scaffold"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Chem/Pharm2D/SigFactory.py#L253-L301 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/command/install_lib.py | python | install_lib._all_packages | (pkg_name) | >>> list(install_lib._all_packages('foo.bar.baz'))
['foo.bar.baz', 'foo.bar', 'foo'] | >>> list(install_lib._all_packages('foo.bar.baz'))
['foo.bar.baz', 'foo.bar', 'foo'] | [
">>>",
"list",
"(",
"install_lib",
".",
"_all_packages",
"(",
"foo",
".",
"bar",
".",
"baz",
"))",
"[",
"foo",
".",
"bar",
".",
"baz",
"foo",
".",
"bar",
"foo",
"]"
] | def _all_packages(pkg_name):
"""
>>> list(install_lib._all_packages('foo.bar.baz'))
['foo.bar.baz', 'foo.bar', 'foo']
"""
while pkg_name:
yield pkg_name
pkg_name, sep, child = pkg_name.rpartition('.') | [
"def",
"_all_packages",
"(",
"pkg_name",
")",
":",
"while",
"pkg_name",
":",
"yield",
"pkg_name",
"pkg_name",
",",
"sep",
",",
"child",
"=",
"pkg_name",
".",
"rpartition",
"(",
"'.'",
")"
] | 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/install_lib.py#L40-L47 |
||
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | snapx/snapx/utils/decorator.py | python | FunctionMaker.create | (cls, obj, body, evaldict, defaults=None,
doc=None, module=None, addsource=True, **attrs) | return self.make(body, evaldict, addsource, **attrs) | Create a function from the strings name, signature and body.
evaldict is the evaluation dictionary. If addsource is true an
attribute __source__ is added to the result. The attributes attrs
are added, if any. | Create a function from the strings name, signature and body.
evaldict is the evaluation dictionary. If addsource is true an
attribute __source__ is added to the result. The attributes attrs
are added, if any. | [
"Create",
"a",
"function",
"from",
"the",
"strings",
"name",
"signature",
"and",
"body",
".",
"evaldict",
"is",
"the",
"evaluation",
"dictionary",
".",
"If",
"addsource",
"is",
"true",
"an",
"attribute",
"__source__",
"is",
"added",
"to",
"the",
"result",
".",
"The",
"attributes",
"attrs",
"are",
"added",
"if",
"any",
"."
] | def create(cls, obj, body, evaldict, defaults=None,
doc=None, module=None, addsource=True, **attrs):
"""
Create a function from the strings name, signature and body.
evaldict is the evaluation dictionary. If addsource is true an
attribute __source__ is added to the result. The attributes attrs
are added, if any.
"""
if isinstance(obj, str): # "name(signature)"
name, rest = obj.strip().split('(', 1)
signature = rest[:-1] # strip a right parens
func = None
else: # a function
name = None
signature = None
func = obj
self = cls(func, name, signature, defaults, doc, module)
ibody = '\n'.join(' ' + line for line in body.splitlines())
caller = evaldict.get('_call_') # when called from `decorate`
if caller and iscoroutinefunction(caller):
body = ('async def %(name)s(%(signature)s):\n' + ibody).replace(
'return', 'return await')
else:
body = 'def %(name)s(%(signature)s):\n' + ibody
return self.make(body, evaldict, addsource, **attrs) | [
"def",
"create",
"(",
"cls",
",",
"obj",
",",
"body",
",",
"evaldict",
",",
"defaults",
"=",
"None",
",",
"doc",
"=",
"None",
",",
"module",
"=",
"None",
",",
"addsource",
"=",
"True",
",",
"*",
"*",
"attrs",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"# \"name(signature)\"",
"name",
",",
"rest",
"=",
"obj",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'('",
",",
"1",
")",
"signature",
"=",
"rest",
"[",
":",
"-",
"1",
"]",
"# strip a right parens",
"func",
"=",
"None",
"else",
":",
"# a function",
"name",
"=",
"None",
"signature",
"=",
"None",
"func",
"=",
"obj",
"self",
"=",
"cls",
"(",
"func",
",",
"name",
",",
"signature",
",",
"defaults",
",",
"doc",
",",
"module",
")",
"ibody",
"=",
"'\\n'",
".",
"join",
"(",
"' '",
"+",
"line",
"for",
"line",
"in",
"body",
".",
"splitlines",
"(",
")",
")",
"caller",
"=",
"evaldict",
".",
"get",
"(",
"'_call_'",
")",
"# when called from `decorate`",
"if",
"caller",
"and",
"iscoroutinefunction",
"(",
"caller",
")",
":",
"body",
"=",
"(",
"'async def %(name)s(%(signature)s):\\n'",
"+",
"ibody",
")",
".",
"replace",
"(",
"'return'",
",",
"'return await'",
")",
"else",
":",
"body",
"=",
"'def %(name)s(%(signature)s):\\n'",
"+",
"ibody",
"return",
"self",
".",
"make",
"(",
"body",
",",
"evaldict",
",",
"addsource",
",",
"*",
"*",
"attrs",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/snapx/snapx/utils/decorator.py#L197-L221 |
|
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/polynomial/hermite.py | python | hermroots | (cs) | return roots | Compute the roots of a Hermite series.
Return the roots (a.k.a "zeros") of the Hermite series represented by
`cs`, which is the sequence of coefficients from lowest order "term"
to highest, e.g., [1,2,3] is the series ``L_0 + 2*L_1 + 3*L_2``.
Parameters
----------
cs : array_like
1-d array of Hermite series coefficients ordered from low to high.
Returns
-------
out : ndarray
Array of the roots. If all the roots are real, then so is the
dtype of ``out``; otherwise, ``out``'s dtype is complex.
See Also
--------
polyroots
chebroots
Notes
-----
Algorithm(s) used:
Remember: because the Hermite series basis set is different from the
"standard" basis set, the results of this function *may* not be what
one is expecting.
Examples
--------
>>> from numpy.polynomial.hermite import hermroots, hermfromroots
>>> coef = hermfromroots([-1, 0, 1])
>>> coef
array([ 0. , 0.25 , 0. , 0.125])
>>> hermroots(coef)
array([ -1.00000000e+00, -1.38777878e-17, 1.00000000e+00]) | Compute the roots of a Hermite series. | [
"Compute",
"the",
"roots",
"of",
"a",
"Hermite",
"series",
"."
] | def hermroots(cs):
"""
Compute the roots of a Hermite series.
Return the roots (a.k.a "zeros") of the Hermite series represented by
`cs`, which is the sequence of coefficients from lowest order "term"
to highest, e.g., [1,2,3] is the series ``L_0 + 2*L_1 + 3*L_2``.
Parameters
----------
cs : array_like
1-d array of Hermite series coefficients ordered from low to high.
Returns
-------
out : ndarray
Array of the roots. If all the roots are real, then so is the
dtype of ``out``; otherwise, ``out``'s dtype is complex.
See Also
--------
polyroots
chebroots
Notes
-----
Algorithm(s) used:
Remember: because the Hermite series basis set is different from the
"standard" basis set, the results of this function *may* not be what
one is expecting.
Examples
--------
>>> from numpy.polynomial.hermite import hermroots, hermfromroots
>>> coef = hermfromroots([-1, 0, 1])
>>> coef
array([ 0. , 0.25 , 0. , 0.125])
>>> hermroots(coef)
array([ -1.00000000e+00, -1.38777878e-17, 1.00000000e+00])
"""
# cs is a trimmed copy
[cs] = pu.as_series([cs])
if len(cs) <= 1 :
return np.array([], dtype=cs.dtype)
if len(cs) == 2 :
return np.array([-.5*cs[0]/cs[1]])
n = len(cs) - 1
cs /= cs[-1]
cmat = np.zeros((n,n), dtype=cs.dtype)
cmat[1, 0] = .5
for i in range(1, n):
cmat[i - 1, i] = i
if i != n - 1:
cmat[i + 1, i] = .5
else:
cmat[:, i] -= cs[:-1]*.5
roots = la.eigvals(cmat)
roots.sort()
return roots | [
"def",
"hermroots",
"(",
"cs",
")",
":",
"# cs is a trimmed copy",
"[",
"cs",
"]",
"=",
"pu",
".",
"as_series",
"(",
"[",
"cs",
"]",
")",
"if",
"len",
"(",
"cs",
")",
"<=",
"1",
":",
"return",
"np",
".",
"array",
"(",
"[",
"]",
",",
"dtype",
"=",
"cs",
".",
"dtype",
")",
"if",
"len",
"(",
"cs",
")",
"==",
"2",
":",
"return",
"np",
".",
"array",
"(",
"[",
"-",
".5",
"*",
"cs",
"[",
"0",
"]",
"/",
"cs",
"[",
"1",
"]",
"]",
")",
"n",
"=",
"len",
"(",
"cs",
")",
"-",
"1",
"cs",
"/=",
"cs",
"[",
"-",
"1",
"]",
"cmat",
"=",
"np",
".",
"zeros",
"(",
"(",
"n",
",",
"n",
")",
",",
"dtype",
"=",
"cs",
".",
"dtype",
")",
"cmat",
"[",
"1",
",",
"0",
"]",
"=",
".5",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"n",
")",
":",
"cmat",
"[",
"i",
"-",
"1",
",",
"i",
"]",
"=",
"i",
"if",
"i",
"!=",
"n",
"-",
"1",
":",
"cmat",
"[",
"i",
"+",
"1",
",",
"i",
"]",
"=",
".5",
"else",
":",
"cmat",
"[",
":",
",",
"i",
"]",
"-=",
"cs",
"[",
":",
"-",
"1",
"]",
"*",
".5",
"roots",
"=",
"la",
".",
"eigvals",
"(",
"cmat",
")",
"roots",
".",
"sort",
"(",
")",
"return",
"roots"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/polynomial/hermite.py#L1079-L1140 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/propgrid.py | python | PropertyGridManager.GetPageRoot | (*args, **kwargs) | return _propgrid.PropertyGridManager_GetPageRoot(*args, **kwargs) | GetPageRoot(self, int index) -> PGProperty | GetPageRoot(self, int index) -> PGProperty | [
"GetPageRoot",
"(",
"self",
"int",
"index",
")",
"-",
">",
"PGProperty"
] | def GetPageRoot(*args, **kwargs):
"""GetPageRoot(self, int index) -> PGProperty"""
return _propgrid.PropertyGridManager_GetPageRoot(*args, **kwargs) | [
"def",
"GetPageRoot",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGridManager_GetPageRoot",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L3504-L3506 |
|
RoboJackets/robocup-software | bce13ce53ddb2ecb9696266d980722c34617dc15 | rj_gameplay/stp/role/__init__.py | python | Role.is_done | (self, world_state: stp.rc.WorldState) | True if Role is done; False otherwise. | True if Role is done; False otherwise. | [
"True",
"if",
"Role",
"is",
"done",
";",
"False",
"otherwise",
"."
] | def is_done(self, world_state: stp.rc.WorldState) -> bool:
"""True if Role is done; False otherwise."""
... | [
"def",
"is_done",
"(",
"self",
",",
"world_state",
":",
"stp",
".",
"rc",
".",
"WorldState",
")",
"->",
"bool",
":",
"..."
] | https://github.com/RoboJackets/robocup-software/blob/bce13ce53ddb2ecb9696266d980722c34617dc15/rj_gameplay/stp/role/__init__.py#L30-L32 |
||
OpenLightingProject/ola | d1433a1bed73276fbe55ce18c03b1c208237decc | python/ola/RDMAPI.py | python | RDMAPI.Set | (self, universe, uid, sub_device, pid, callback, args=[],
include_frames=False) | return self._SendRequest(universe, uid, sub_device, pid, callback, args,
PidStore.RDM_SET, include_frames) | Send a RDM Set message.
Args:
universe: The universe to send the request on.
uid: The UID to address the request to.
sub_device: The Sub Device to send the request to.
pid: A PID object that describes the format of the request.
callback: The callback to run when the request completes.
args: The args to pack into the param data section.
include_frames: True if the response should include the raw frame data.
Return:
True if sent ok, False otherwise. | Send a RDM Set message. | [
"Send",
"a",
"RDM",
"Set",
"message",
"."
] | def Set(self, universe, uid, sub_device, pid, callback, args=[],
include_frames=False):
"""Send a RDM Set message.
Args:
universe: The universe to send the request on.
uid: The UID to address the request to.
sub_device: The Sub Device to send the request to.
pid: A PID object that describes the format of the request.
callback: The callback to run when the request completes.
args: The args to pack into the param data section.
include_frames: True if the response should include the raw frame data.
Return:
True if sent ok, False otherwise.
"""
return self._SendRequest(universe, uid, sub_device, pid, callback, args,
PidStore.RDM_SET, include_frames) | [
"def",
"Set",
"(",
"self",
",",
"universe",
",",
"uid",
",",
"sub_device",
",",
"pid",
",",
"callback",
",",
"args",
"=",
"[",
"]",
",",
"include_frames",
"=",
"False",
")",
":",
"return",
"self",
".",
"_SendRequest",
"(",
"universe",
",",
"uid",
",",
"sub_device",
",",
"pid",
",",
"callback",
",",
"args",
",",
"PidStore",
".",
"RDM_SET",
",",
"include_frames",
")"
] | https://github.com/OpenLightingProject/ola/blob/d1433a1bed73276fbe55ce18c03b1c208237decc/python/ola/RDMAPI.py#L137-L154 |
|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/aui.py | python | AuiToolBar.GetToolBarFits | (*args, **kwargs) | return _aui.AuiToolBar_GetToolBarFits(*args, **kwargs) | GetToolBarFits(self) -> bool | GetToolBarFits(self) -> bool | [
"GetToolBarFits",
"(",
"self",
")",
"-",
">",
"bool"
] | def GetToolBarFits(*args, **kwargs):
"""GetToolBarFits(self) -> bool"""
return _aui.AuiToolBar_GetToolBarFits(*args, **kwargs) | [
"def",
"GetToolBarFits",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiToolBar_GetToolBarFits",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L2110-L2112 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/tix.py | python | Grid.anchor_set | (self, x, y) | Set the selection anchor to the cell at (x, y). | Set the selection anchor to the cell at (x, y). | [
"Set",
"the",
"selection",
"anchor",
"to",
"the",
"cell",
"at",
"(",
"x",
"y",
")",
"."
] | def anchor_set(self, x, y):
"""Set the selection anchor to the cell at (x, y)."""
self.tk.call(self, 'anchor', 'set', x, y) | [
"def",
"anchor_set",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
",",
"'anchor'",
",",
"'set'",
",",
"x",
",",
"y",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/tix.py#L1805-L1807 |
||
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Source/bindings/scripts/v8_types.py | python | v8_conversion_type | (idl_type, extended_attributes) | return 'DOMWrapper' | Returns V8 conversion type, adding any additional includes.
The V8 conversion type is used to select the C++ -> V8 conversion function
or v8SetReturnValue* function; it can be an idl_type, a cpp_type, or a
separate name for the type of conversion (e.g., 'DOMWrapper'). | Returns V8 conversion type, adding any additional includes. | [
"Returns",
"V8",
"conversion",
"type",
"adding",
"any",
"additional",
"includes",
"."
] | def v8_conversion_type(idl_type, extended_attributes):
"""Returns V8 conversion type, adding any additional includes.
The V8 conversion type is used to select the C++ -> V8 conversion function
or v8SetReturnValue* function; it can be an idl_type, a cpp_type, or a
separate name for the type of conversion (e.g., 'DOMWrapper').
"""
extended_attributes = extended_attributes or {}
# Nullable dictionaries need to be handled differently than either
# non-nullable dictionaries or unions.
if idl_type.is_dictionary and idl_type.is_nullable:
return 'NullableDictionary'
if idl_type.is_dictionary or idl_type.is_union_type:
return 'DictionaryOrUnion'
# Array or sequence types
native_array_element_type = idl_type.native_array_element_type
if native_array_element_type:
return 'array'
# Simple types
base_idl_type = idl_type.base_type
# Basic types, without additional includes
if base_idl_type in CPP_INT_TYPES:
return 'int'
if base_idl_type in CPP_UNSIGNED_TYPES:
return 'unsigned'
if idl_type.is_string_type:
if idl_type.is_nullable:
return 'StringOrNull'
if 'TreatReturnedNullStringAs' not in extended_attributes:
return base_idl_type
treat_returned_null_string_as = extended_attributes['TreatReturnedNullStringAs']
if treat_returned_null_string_as == 'Null':
return 'StringOrNull'
if treat_returned_null_string_as == 'Undefined':
return 'StringOrUndefined'
raise 'Unrecognized TreatReturnedNullStringAs value: "%s"' % treat_returned_null_string_as
if idl_type.is_basic_type or base_idl_type == 'ScriptValue':
return base_idl_type
# Generic dictionary type
if base_idl_type == 'Dictionary':
return 'Dictionary'
# Data type with potential additional includes
if base_idl_type in V8_SET_RETURN_VALUE: # Special v8SetReturnValue treatment
return base_idl_type
# Pointer type
return 'DOMWrapper' | [
"def",
"v8_conversion_type",
"(",
"idl_type",
",",
"extended_attributes",
")",
":",
"extended_attributes",
"=",
"extended_attributes",
"or",
"{",
"}",
"# Nullable dictionaries need to be handled differently than either",
"# non-nullable dictionaries or unions.",
"if",
"idl_type",
".",
"is_dictionary",
"and",
"idl_type",
".",
"is_nullable",
":",
"return",
"'NullableDictionary'",
"if",
"idl_type",
".",
"is_dictionary",
"or",
"idl_type",
".",
"is_union_type",
":",
"return",
"'DictionaryOrUnion'",
"# Array or sequence types",
"native_array_element_type",
"=",
"idl_type",
".",
"native_array_element_type",
"if",
"native_array_element_type",
":",
"return",
"'array'",
"# Simple types",
"base_idl_type",
"=",
"idl_type",
".",
"base_type",
"# Basic types, without additional includes",
"if",
"base_idl_type",
"in",
"CPP_INT_TYPES",
":",
"return",
"'int'",
"if",
"base_idl_type",
"in",
"CPP_UNSIGNED_TYPES",
":",
"return",
"'unsigned'",
"if",
"idl_type",
".",
"is_string_type",
":",
"if",
"idl_type",
".",
"is_nullable",
":",
"return",
"'StringOrNull'",
"if",
"'TreatReturnedNullStringAs'",
"not",
"in",
"extended_attributes",
":",
"return",
"base_idl_type",
"treat_returned_null_string_as",
"=",
"extended_attributes",
"[",
"'TreatReturnedNullStringAs'",
"]",
"if",
"treat_returned_null_string_as",
"==",
"'Null'",
":",
"return",
"'StringOrNull'",
"if",
"treat_returned_null_string_as",
"==",
"'Undefined'",
":",
"return",
"'StringOrUndefined'",
"raise",
"'Unrecognized TreatReturnedNullStringAs value: \"%s\"'",
"%",
"treat_returned_null_string_as",
"if",
"idl_type",
".",
"is_basic_type",
"or",
"base_idl_type",
"==",
"'ScriptValue'",
":",
"return",
"base_idl_type",
"# Generic dictionary type",
"if",
"base_idl_type",
"==",
"'Dictionary'",
":",
"return",
"'Dictionary'",
"# Data type with potential additional includes",
"if",
"base_idl_type",
"in",
"V8_SET_RETURN_VALUE",
":",
"# Special v8SetReturnValue treatment",
"return",
"base_idl_type",
"# Pointer type",
"return",
"'DOMWrapper'"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Source/bindings/scripts/v8_types.py#L720-L771 |
|
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | mlir/python/mlir/dialects/linalg/opdsl/lang/affine.py | python | AffineExprDef.build | (self, state: Optional[AffineBuildState] = None) | return expr | Builds the corresponding _ir.AffineExpr from the definitions. | Builds the corresponding _ir.AffineExpr from the definitions. | [
"Builds",
"the",
"corresponding",
"_ir",
".",
"AffineExpr",
"from",
"the",
"definitions",
"."
] | def build(self, state: Optional[AffineBuildState] = None) -> _ir.AffineExpr:
"""Builds the corresponding _ir.AffineExpr from the definitions.
"""
state = AffineBuildState() if state is None else state
expr = self._create(state)
return expr | [
"def",
"build",
"(",
"self",
",",
"state",
":",
"Optional",
"[",
"AffineBuildState",
"]",
"=",
"None",
")",
"->",
"_ir",
".",
"AffineExpr",
":",
"state",
"=",
"AffineBuildState",
"(",
")",
"if",
"state",
"is",
"None",
"else",
"state",
"expr",
"=",
"self",
".",
"_create",
"(",
"state",
")",
"return",
"expr"
] | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/mlir/python/mlir/dialects/linalg/opdsl/lang/affine.py#L152-L157 |
|
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | python | _CamelCaseToSnakeCase | (path_name) | return ''.join(result) | Converts a field name from camelCase to snake_case. | Converts a field name from camelCase to snake_case. | [
"Converts",
"a",
"field",
"name",
"from",
"camelCase",
"to",
"snake_case",
"."
] | def _CamelCaseToSnakeCase(path_name):
"""Converts a field name from camelCase to snake_case."""
result = []
for c in path_name:
if c == '_':
raise ParseError('Fail to parse FieldMask: Path name '
'{0} must not contain "_"s.'.format(path_name))
if c.isupper():
result += '_'
result += c.lower()
else:
result += c
return ''.join(result) | [
"def",
"_CamelCaseToSnakeCase",
"(",
"path_name",
")",
":",
"result",
"=",
"[",
"]",
"for",
"c",
"in",
"path_name",
":",
"if",
"c",
"==",
"'_'",
":",
"raise",
"ParseError",
"(",
"'Fail to parse FieldMask: Path name '",
"'{0} must not contain \"_\"s.'",
".",
"format",
"(",
"path_name",
")",
")",
"if",
"c",
".",
"isupper",
"(",
")",
":",
"result",
"+=",
"'_'",
"result",
"+=",
"c",
".",
"lower",
"(",
")",
"else",
":",
"result",
"+=",
"c",
"return",
"''",
".",
"join",
"(",
"result",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L521-L533 |
|
htcondor/htcondor | 4829724575176d1d6c936e4693dfd78a728569b0 | src/condor_scripts/adstash/utils.py | python | set_up_logging | (args) | Configure root logger | Configure root logger | [
"Configure",
"root",
"logger"
] | def set_up_logging(args):
"""Configure root logger"""
logger = logging.getLogger()
# Get the log level from the config
log_level = getattr(logging, args.log_level.upper(), None)
if not isinstance(log_level, int):
logging.error(f"Invalid log level: {log_level}")
sys.exit(1)
logger.setLevel(log_level)
# Determine format
fmt = "%(asctime)s %(message)s"
datefmt = "%m/%d/%y %H:%M:%S"
if "debug_levels" in args:
fmts = config.debug2fmt(args.debug_levels)
fmt = fmts["fmt"]
datefmt = fmts["datefmt"]
# Check if we're logging to a file
if args.log_file is not None:
log_path = Path(args.log_file)
# Make sure the parent directory exists
if not log_path.parent.exists():
logging.debug(f"Attempting to create {log_path.parent}")
try:
log_path.parent.mkdir(parents=True)
except Exception:
logging.exception(
f"Error while creating log file directory {log_path.parent}"
)
sys.exit(1)
filehandler = logging.handlers.RotatingFileHandler(
args.log_file, maxBytes=100000
)
filehandler.setFormatter(logging.Formatter(fmt=fmt, datefmt=datefmt))
logger.addHandler(filehandler)
# Check if logging to stdout is worthwhile
if os.isatty(sys.stdout.fileno()):
streamhandler = logging.StreamHandler(stream=sys.stdout)
streamhandler.setFormatter(logging.Formatter(fmt=fmt, datefmt=datefmt))
logger.addHandler(streamhandler) | [
"def",
"set_up_logging",
"(",
"args",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"# Get the log level from the config",
"log_level",
"=",
"getattr",
"(",
"logging",
",",
"args",
".",
"log_level",
".",
"upper",
"(",
")",
",",
"None",
")",
"if",
"not",
"isinstance",
"(",
"log_level",
",",
"int",
")",
":",
"logging",
".",
"error",
"(",
"f\"Invalid log level: {log_level}\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"logger",
".",
"setLevel",
"(",
"log_level",
")",
"# Determine format",
"fmt",
"=",
"\"%(asctime)s %(message)s\"",
"datefmt",
"=",
"\"%m/%d/%y %H:%M:%S\"",
"if",
"\"debug_levels\"",
"in",
"args",
":",
"fmts",
"=",
"config",
".",
"debug2fmt",
"(",
"args",
".",
"debug_levels",
")",
"fmt",
"=",
"fmts",
"[",
"\"fmt\"",
"]",
"datefmt",
"=",
"fmts",
"[",
"\"datefmt\"",
"]",
"# Check if we're logging to a file",
"if",
"args",
".",
"log_file",
"is",
"not",
"None",
":",
"log_path",
"=",
"Path",
"(",
"args",
".",
"log_file",
")",
"# Make sure the parent directory exists",
"if",
"not",
"log_path",
".",
"parent",
".",
"exists",
"(",
")",
":",
"logging",
".",
"debug",
"(",
"f\"Attempting to create {log_path.parent}\"",
")",
"try",
":",
"log_path",
".",
"parent",
".",
"mkdir",
"(",
"parents",
"=",
"True",
")",
"except",
"Exception",
":",
"logging",
".",
"exception",
"(",
"f\"Error while creating log file directory {log_path.parent}\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"filehandler",
"=",
"logging",
".",
"handlers",
".",
"RotatingFileHandler",
"(",
"args",
".",
"log_file",
",",
"maxBytes",
"=",
"100000",
")",
"filehandler",
".",
"setFormatter",
"(",
"logging",
".",
"Formatter",
"(",
"fmt",
"=",
"fmt",
",",
"datefmt",
"=",
"datefmt",
")",
")",
"logger",
".",
"addHandler",
"(",
"filehandler",
")",
"# Check if logging to stdout is worthwhile",
"if",
"os",
".",
"isatty",
"(",
"sys",
".",
"stdout",
".",
"fileno",
"(",
")",
")",
":",
"streamhandler",
"=",
"logging",
".",
"StreamHandler",
"(",
"stream",
"=",
"sys",
".",
"stdout",
")",
"streamhandler",
".",
"setFormatter",
"(",
"logging",
".",
"Formatter",
"(",
"fmt",
"=",
"fmt",
",",
"datefmt",
"=",
"datefmt",
")",
")",
"logger",
".",
"addHandler",
"(",
"streamhandler",
")"
] | https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_scripts/adstash/utils.py#L129-L173 |
||
opencv/opencv | 76aff8478883858f0e46746044348ebb16dc3c67 | samples/dnn/person_reid.py | python | topk | (query_feat, gallery_feat, topk = 5) | return [i[0:int(topk)] for i in index] | Return the index of top K gallery images most similar to the query images
:param query_feat: array of feature vectors of query images
:param gallery_feat: array of feature vectors of gallery images
:param topk: number of gallery images to return | Return the index of top K gallery images most similar to the query images
:param query_feat: array of feature vectors of query images
:param gallery_feat: array of feature vectors of gallery images
:param topk: number of gallery images to return | [
"Return",
"the",
"index",
"of",
"top",
"K",
"gallery",
"images",
"most",
"similar",
"to",
"the",
"query",
"images",
":",
"param",
"query_feat",
":",
"array",
"of",
"feature",
"vectors",
"of",
"query",
"images",
":",
"param",
"gallery_feat",
":",
"array",
"of",
"feature",
"vectors",
"of",
"gallery",
"images",
":",
"param",
"topk",
":",
"number",
"of",
"gallery",
"images",
"to",
"return"
] | def topk(query_feat, gallery_feat, topk = 5):
"""
Return the index of top K gallery images most similar to the query images
:param query_feat: array of feature vectors of query images
:param gallery_feat: array of feature vectors of gallery images
:param topk: number of gallery images to return
"""
sim = similarity(query_feat, gallery_feat)
index = np.argsort(-sim, axis = 1)
return [i[0:int(topk)] for i in index] | [
"def",
"topk",
"(",
"query_feat",
",",
"gallery_feat",
",",
"topk",
"=",
"5",
")",
":",
"sim",
"=",
"similarity",
"(",
"query_feat",
",",
"gallery_feat",
")",
"index",
"=",
"np",
".",
"argsort",
"(",
"-",
"sim",
",",
"axis",
"=",
"1",
")",
"return",
"[",
"i",
"[",
"0",
":",
"int",
"(",
"topk",
")",
"]",
"for",
"i",
"in",
"index",
"]"
] | https://github.com/opencv/opencv/blob/76aff8478883858f0e46746044348ebb16dc3c67/samples/dnn/person_reid.py#L139-L148 |
|
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/tracking/base.py | python | Trackable._single_restoration_from_checkpoint_position | (self, checkpoint_position,
visit_queue) | return restore_ops, tensor_saveables, python_saveables | Restore this object, and either queue its dependencies or defer them. | Restore this object, and either queue its dependencies or defer them. | [
"Restore",
"this",
"object",
"and",
"either",
"queue",
"its",
"dependencies",
"or",
"defer",
"them",
"."
] | def _single_restoration_from_checkpoint_position(self, checkpoint_position,
visit_queue):
"""Restore this object, and either queue its dependencies or defer them."""
self._maybe_initialize_trackable()
checkpoint = checkpoint_position.checkpoint
# If the UID of this restore is lower than our current update UID, we don't
# need to actually restore the object. However, we should pass the
# restoration on to our dependencies.
if checkpoint.restore_uid > self._self_update_uid:
restore_ops, tensor_saveables, python_saveables = (
checkpoint_position.gather_ops_or_named_saveables())
self._self_update_uid = checkpoint.restore_uid
else:
restore_ops = ()
tensor_saveables = {}
python_saveables = ()
for child in checkpoint_position.object_proto.children:
child_position = CheckpointPosition(
checkpoint=checkpoint, proto_id=child.node_id)
local_object = self._lookup_dependency(child.local_name)
if local_object is None:
# We don't yet have a dependency registered with this name. Save it
# in case we do.
self._deferred_dependencies.setdefault(child.local_name,
[]).append(child_position)
else:
if child_position.bind_object(trackable=local_object):
# This object's correspondence is new, so dependencies need to be
# visited. Delay doing it so that we get a breadth-first dependency
# resolution order (shallowest paths first). The caller is responsible
# for emptying visit_queue.
visit_queue.append(child_position)
return restore_ops, tensor_saveables, python_saveables | [
"def",
"_single_restoration_from_checkpoint_position",
"(",
"self",
",",
"checkpoint_position",
",",
"visit_queue",
")",
":",
"self",
".",
"_maybe_initialize_trackable",
"(",
")",
"checkpoint",
"=",
"checkpoint_position",
".",
"checkpoint",
"# If the UID of this restore is lower than our current update UID, we don't",
"# need to actually restore the object. However, we should pass the",
"# restoration on to our dependencies.",
"if",
"checkpoint",
".",
"restore_uid",
">",
"self",
".",
"_self_update_uid",
":",
"restore_ops",
",",
"tensor_saveables",
",",
"python_saveables",
"=",
"(",
"checkpoint_position",
".",
"gather_ops_or_named_saveables",
"(",
")",
")",
"self",
".",
"_self_update_uid",
"=",
"checkpoint",
".",
"restore_uid",
"else",
":",
"restore_ops",
"=",
"(",
")",
"tensor_saveables",
"=",
"{",
"}",
"python_saveables",
"=",
"(",
")",
"for",
"child",
"in",
"checkpoint_position",
".",
"object_proto",
".",
"children",
":",
"child_position",
"=",
"CheckpointPosition",
"(",
"checkpoint",
"=",
"checkpoint",
",",
"proto_id",
"=",
"child",
".",
"node_id",
")",
"local_object",
"=",
"self",
".",
"_lookup_dependency",
"(",
"child",
".",
"local_name",
")",
"if",
"local_object",
"is",
"None",
":",
"# We don't yet have a dependency registered with this name. Save it",
"# in case we do.",
"self",
".",
"_deferred_dependencies",
".",
"setdefault",
"(",
"child",
".",
"local_name",
",",
"[",
"]",
")",
".",
"append",
"(",
"child_position",
")",
"else",
":",
"if",
"child_position",
".",
"bind_object",
"(",
"trackable",
"=",
"local_object",
")",
":",
"# This object's correspondence is new, so dependencies need to be",
"# visited. Delay doing it so that we get a breadth-first dependency",
"# resolution order (shallowest paths first). The caller is responsible",
"# for emptying visit_queue.",
"visit_queue",
".",
"append",
"(",
"child_position",
")",
"return",
"restore_ops",
",",
"tensor_saveables",
",",
"python_saveables"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/tracking/base.py#L877-L909 |
|
livecode/livecode | 4606a10ea10b16d5071d0f9f263ccdd7ede8b31d | gyp/pylib/gyp/generator/msvs.py | python | _MapFileToMsBuildSourceType | (source, rule_dependencies,
extension_to_rule_name) | return (group, element) | Returns the group and element type of the source file.
Arguments:
source: The source file name.
extension_to_rule_name: A dictionary mapping file extensions to rules.
Returns:
A pair of (group this file should be part of, the label of element) | Returns the group and element type of the source file. | [
"Returns",
"the",
"group",
"and",
"element",
"type",
"of",
"the",
"source",
"file",
"."
] | def _MapFileToMsBuildSourceType(source, rule_dependencies,
extension_to_rule_name):
"""Returns the group and element type of the source file.
Arguments:
source: The source file name.
extension_to_rule_name: A dictionary mapping file extensions to rules.
Returns:
A pair of (group this file should be part of, the label of element)
"""
_, ext = os.path.splitext(source)
if ext in extension_to_rule_name:
group = 'rule'
element = extension_to_rule_name[ext]
elif ext in ['.cc', '.cpp', '.c', '.cxx']:
group = 'compile'
element = 'ClCompile'
elif ext in ['.h', '.hxx']:
group = 'include'
element = 'ClInclude'
elif ext == '.rc':
group = 'resource'
element = 'ResourceCompile'
elif ext == '.asm':
group = 'masm'
element = 'MASM'
elif ext == '.idl':
group = 'midl'
element = 'Midl'
elif source in rule_dependencies:
group = 'rule_dependency'
element = 'CustomBuild'
else:
group = 'none'
element = 'None'
return (group, element) | [
"def",
"_MapFileToMsBuildSourceType",
"(",
"source",
",",
"rule_dependencies",
",",
"extension_to_rule_name",
")",
":",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"source",
")",
"if",
"ext",
"in",
"extension_to_rule_name",
":",
"group",
"=",
"'rule'",
"element",
"=",
"extension_to_rule_name",
"[",
"ext",
"]",
"elif",
"ext",
"in",
"[",
"'.cc'",
",",
"'.cpp'",
",",
"'.c'",
",",
"'.cxx'",
"]",
":",
"group",
"=",
"'compile'",
"element",
"=",
"'ClCompile'",
"elif",
"ext",
"in",
"[",
"'.h'",
",",
"'.hxx'",
"]",
":",
"group",
"=",
"'include'",
"element",
"=",
"'ClInclude'",
"elif",
"ext",
"==",
"'.rc'",
":",
"group",
"=",
"'resource'",
"element",
"=",
"'ResourceCompile'",
"elif",
"ext",
"==",
"'.asm'",
":",
"group",
"=",
"'masm'",
"element",
"=",
"'MASM'",
"elif",
"ext",
"==",
"'.idl'",
":",
"group",
"=",
"'midl'",
"element",
"=",
"'Midl'",
"elif",
"source",
"in",
"rule_dependencies",
":",
"group",
"=",
"'rule_dependency'",
"element",
"=",
"'CustomBuild'",
"else",
":",
"group",
"=",
"'none'",
"element",
"=",
"'None'",
"return",
"(",
"group",
",",
"element",
")"
] | https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/generator/msvs.py#L2087-L2123 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/config_key.py | python | GetKeysDialog.toggle_level | (self) | Toggle between basic and advanced keys. | Toggle between basic and advanced keys. | [
"Toggle",
"between",
"basic",
"and",
"advanced",
"keys",
"."
] | def toggle_level(self):
"Toggle between basic and advanced keys."
if self.button_level.cget('text').startswith('Advanced'):
self.clear_key_seq()
self.button_level.config(text='<< Basic Key Binding Entry')
self.frame_keyseq_advanced.lift()
self.frame_help_advanced.lift()
self.advanced_keys.focus_set()
self.advanced = True
else:
self.clear_key_seq()
self.button_level.config(text='Advanced Key Binding Entry >>')
self.frame_keyseq_basic.lift()
self.frame_controls_basic.lift()
self.advanced = False | [
"def",
"toggle_level",
"(",
"self",
")",
":",
"if",
"self",
".",
"button_level",
".",
"cget",
"(",
"'text'",
")",
".",
"startswith",
"(",
"'Advanced'",
")",
":",
"self",
".",
"clear_key_seq",
"(",
")",
"self",
".",
"button_level",
".",
"config",
"(",
"text",
"=",
"'<< Basic Key Binding Entry'",
")",
"self",
".",
"frame_keyseq_advanced",
".",
"lift",
"(",
")",
"self",
".",
"frame_help_advanced",
".",
"lift",
"(",
")",
"self",
".",
"advanced_keys",
".",
"focus_set",
"(",
")",
"self",
".",
"advanced",
"=",
"True",
"else",
":",
"self",
".",
"clear_key_seq",
"(",
")",
"self",
".",
"button_level",
".",
"config",
"(",
"text",
"=",
"'Advanced Key Binding Entry >>'",
")",
"self",
".",
"frame_keyseq_basic",
".",
"lift",
"(",
")",
"self",
".",
"frame_controls_basic",
".",
"lift",
"(",
")",
"self",
".",
"advanced",
"=",
"False"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/config_key.py#L216-L230 |
||
microsoft/clang | 86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5 | bindings/python/clang/cindex.py | python | Cursor.raw_comment | (self) | return conf.lib.clang_Cursor_getRawCommentText(self) | Returns the raw comment text associated with that Cursor | Returns the raw comment text associated with that Cursor | [
"Returns",
"the",
"raw",
"comment",
"text",
"associated",
"with",
"that",
"Cursor"
] | def raw_comment(self):
"""Returns the raw comment text associated with that Cursor"""
return conf.lib.clang_Cursor_getRawCommentText(self) | [
"def",
"raw_comment",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_Cursor_getRawCommentText",
"(",
"self",
")"
] | https://github.com/microsoft/clang/blob/86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5/bindings/python/clang/cindex.py#L1778-L1780 |
|
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/robotsim.py | python | RobotModel.reduce | (self, robot: "RobotModel") | return _robotsim.RobotModel_reduce(self, robot) | r"""
Sets self to a reduced version of robot, where all fixed DOFs are eliminated.
The return value is a map from the original robot DOF indices to the reduced
DOFs.
Args:
robot (:class:`~klampt.RobotModel`)
Note that any geometries fixed to the world will disappear. | r"""
Sets self to a reduced version of robot, where all fixed DOFs are eliminated.
The return value is a map from the original robot DOF indices to the reduced
DOFs. | [
"r",
"Sets",
"self",
"to",
"a",
"reduced",
"version",
"of",
"robot",
"where",
"all",
"fixed",
"DOFs",
"are",
"eliminated",
".",
"The",
"return",
"value",
"is",
"a",
"map",
"from",
"the",
"original",
"robot",
"DOF",
"indices",
"to",
"the",
"reduced",
"DOFs",
"."
] | def reduce(self, robot: "RobotModel") ->None:
r"""
Sets self to a reduced version of robot, where all fixed DOFs are eliminated.
The return value is a map from the original robot DOF indices to the reduced
DOFs.
Args:
robot (:class:`~klampt.RobotModel`)
Note that any geometries fixed to the world will disappear.
"""
return _robotsim.RobotModel_reduce(self, robot) | [
"def",
"reduce",
"(",
"self",
",",
"robot",
":",
"\"RobotModel\"",
")",
"->",
"None",
":",
"return",
"_robotsim",
".",
"RobotModel_reduce",
"(",
"self",
",",
"robot",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L5208-L5220 |
|
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBValue.GetValueForExpressionPath | (self, expr_path) | return _lldb.SBValue_GetValueForExpressionPath(self, expr_path) | GetValueForExpressionPath(SBValue self, char const * expr_path) -> SBValue
Expands nested expressions like .a->b[0].c[1]->d. | GetValueForExpressionPath(SBValue self, char const * expr_path) -> SBValue | [
"GetValueForExpressionPath",
"(",
"SBValue",
"self",
"char",
"const",
"*",
"expr_path",
")",
"-",
">",
"SBValue"
] | def GetValueForExpressionPath(self, expr_path):
"""
GetValueForExpressionPath(SBValue self, char const * expr_path) -> SBValue
Expands nested expressions like .a->b[0].c[1]->d.
"""
return _lldb.SBValue_GetValueForExpressionPath(self, expr_path) | [
"def",
"GetValueForExpressionPath",
"(",
"self",
",",
"expr_path",
")",
":",
"return",
"_lldb",
".",
"SBValue_GetValueForExpressionPath",
"(",
"self",
",",
"expr_path",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L14507-L14513 |
|
POV-Ray/povray | 76a804d18a30a1dbb0afbc0070b62526715571eb | tools/meta-make/bluenoise/BlueNoise.py | python | GetBayerPattern | (Log2Width) | return Result | Creates a two-dimensional Bayer pattern with a width and height of
2**Log2Width. | Creates a two-dimensional Bayer pattern with a width and height of
2**Log2Width. | [
"Creates",
"a",
"two",
"-",
"dimensional",
"Bayer",
"pattern",
"with",
"a",
"width",
"and",
"height",
"of",
"2",
"**",
"Log2Width",
"."
] | def GetBayerPattern(Log2Width):
"""Creates a two-dimensional Bayer pattern with a width and height of
2**Log2Width."""
X,Y=np.meshgrid(range(2**Log2Width),range(2**Log2Width));
Result=np.zeros_like(X);
for i in range(Log2Width):
StripesY=np.where(np.bitwise_and(Y,2**(Log2Width-1-i))!=0,1,0);
StripesX=np.where(np.bitwise_and(X,2**(Log2Width-1-i))!=0,1,0);
Checker=np.bitwise_xor(StripesX,StripesY);
Result+=np.bitwise_or(StripesY*2**(2*i),Checker*2**(2*i+1));
return Result; | [
"def",
"GetBayerPattern",
"(",
"Log2Width",
")",
":",
"X",
",",
"Y",
"=",
"np",
".",
"meshgrid",
"(",
"range",
"(",
"2",
"**",
"Log2Width",
")",
",",
"range",
"(",
"2",
"**",
"Log2Width",
")",
")",
"Result",
"=",
"np",
".",
"zeros_like",
"(",
"X",
")",
"for",
"i",
"in",
"range",
"(",
"Log2Width",
")",
":",
"StripesY",
"=",
"np",
".",
"where",
"(",
"np",
".",
"bitwise_and",
"(",
"Y",
",",
"2",
"**",
"(",
"Log2Width",
"-",
"1",
"-",
"i",
")",
")",
"!=",
"0",
",",
"1",
",",
"0",
")",
"StripesX",
"=",
"np",
".",
"where",
"(",
"np",
".",
"bitwise_and",
"(",
"X",
",",
"2",
"**",
"(",
"Log2Width",
"-",
"1",
"-",
"i",
")",
")",
"!=",
"0",
",",
"1",
",",
"0",
")",
"Checker",
"=",
"np",
".",
"bitwise_xor",
"(",
"StripesX",
",",
"StripesY",
")",
"Result",
"+=",
"np",
".",
"bitwise_or",
"(",
"StripesY",
"*",
"2",
"**",
"(",
"2",
"*",
"i",
")",
",",
"Checker",
"*",
"2",
"**",
"(",
"2",
"*",
"i",
"+",
"1",
")",
")",
"return",
"Result"
] | https://github.com/POV-Ray/povray/blob/76a804d18a30a1dbb0afbc0070b62526715571eb/tools/meta-make/bluenoise/BlueNoise.py#L21-L31 |
|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/idna/core.py | python | uts46_remap | (domain, std3_rules=True, transitional=False) | Re-map the characters in the string according to UTS46 processing. | Re-map the characters in the string according to UTS46 processing. | [
"Re",
"-",
"map",
"the",
"characters",
"in",
"the",
"string",
"according",
"to",
"UTS46",
"processing",
"."
] | def uts46_remap(domain, std3_rules=True, transitional=False):
"""Re-map the characters in the string according to UTS46 processing."""
from .uts46data import uts46data
output = u""
try:
for pos, char in enumerate(domain):
code_point = ord(char)
uts46row = uts46data[code_point if code_point < 256 else
bisect.bisect_left(uts46data, (code_point, "Z")) - 1]
status = uts46row[1]
replacement = uts46row[2] if len(uts46row) == 3 else None
if (status == "V" or
(status == "D" and not transitional) or
(status == "3" and std3_rules and replacement is None)):
output += char
elif replacement is not None and (status == "M" or
(status == "3" and std3_rules) or
(status == "D" and transitional)):
output += replacement
elif status != "I":
raise IndexError()
return unicodedata.normalize("NFC", output)
except IndexError:
raise InvalidCodepoint(
"Codepoint {0} not allowed at position {1} in {2}".format(
_unot(code_point), pos + 1, repr(domain))) | [
"def",
"uts46_remap",
"(",
"domain",
",",
"std3_rules",
"=",
"True",
",",
"transitional",
"=",
"False",
")",
":",
"from",
".",
"uts46data",
"import",
"uts46data",
"output",
"=",
"u\"\"",
"try",
":",
"for",
"pos",
",",
"char",
"in",
"enumerate",
"(",
"domain",
")",
":",
"code_point",
"=",
"ord",
"(",
"char",
")",
"uts46row",
"=",
"uts46data",
"[",
"code_point",
"if",
"code_point",
"<",
"256",
"else",
"bisect",
".",
"bisect_left",
"(",
"uts46data",
",",
"(",
"code_point",
",",
"\"Z\"",
")",
")",
"-",
"1",
"]",
"status",
"=",
"uts46row",
"[",
"1",
"]",
"replacement",
"=",
"uts46row",
"[",
"2",
"]",
"if",
"len",
"(",
"uts46row",
")",
"==",
"3",
"else",
"None",
"if",
"(",
"status",
"==",
"\"V\"",
"or",
"(",
"status",
"==",
"\"D\"",
"and",
"not",
"transitional",
")",
"or",
"(",
"status",
"==",
"\"3\"",
"and",
"std3_rules",
"and",
"replacement",
"is",
"None",
")",
")",
":",
"output",
"+=",
"char",
"elif",
"replacement",
"is",
"not",
"None",
"and",
"(",
"status",
"==",
"\"M\"",
"or",
"(",
"status",
"==",
"\"3\"",
"and",
"std3_rules",
")",
"or",
"(",
"status",
"==",
"\"D\"",
"and",
"transitional",
")",
")",
":",
"output",
"+=",
"replacement",
"elif",
"status",
"!=",
"\"I\"",
":",
"raise",
"IndexError",
"(",
")",
"return",
"unicodedata",
".",
"normalize",
"(",
"\"NFC\"",
",",
"output",
")",
"except",
"IndexError",
":",
"raise",
"InvalidCodepoint",
"(",
"\"Codepoint {0} not allowed at position {1} in {2}\"",
".",
"format",
"(",
"_unot",
"(",
"code_point",
")",
",",
"pos",
"+",
"1",
",",
"repr",
"(",
"domain",
")",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/idna/core.py#L307-L332 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.