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
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/robotsim.py
python
ContactQueryResult.__init__
(self)
__init__(ContactQueryResult self) -> ContactQueryResult The result from a contact query of :class:`~klampt.Geometry3D`. The number of contacts n is variable. Attributes: depths (list of n floats): penetration depths for each contact point. The depth is measured with respect to the padded geometry, and must be nonnegative. A value of 0 indicates that depth cannot be determined accurately. points1, points2 (list of n lists of floats): contact points on self vs other, The top level list has n entries, and each entry is a 3-list expressed in world coordinates. If an object is padded, these points are on the surface of the padded geometry. normals (list of n lists of floats): the outward-facing contact normal from this to other at each contact point, given in world coordinates. Each entry is a 3-list, and can be a unit vector, or [0,0,0] if the the normal cannot be computed properly. elems1, elems2 (list of n ints): for compound objects, these are the element indices corresponding to each contact. C++ includes: geometry.h
__init__(ContactQueryResult self) -> ContactQueryResult
[ "__init__", "(", "ContactQueryResult", "self", ")", "-", ">", "ContactQueryResult" ]
def __init__(self): """ __init__(ContactQueryResult self) -> ContactQueryResult The result from a contact query of :class:`~klampt.Geometry3D`. The number of contacts n is variable. Attributes: depths (list of n floats): penetration depths for each contact point. The depth is measured with respect to the padded geometry, and must be nonnegative. A value of 0 indicates that depth cannot be determined accurately. points1, points2 (list of n lists of floats): contact points on self vs other, The top level list has n entries, and each entry is a 3-list expressed in world coordinates. If an object is padded, these points are on the surface of the padded geometry. normals (list of n lists of floats): the outward-facing contact normal from this to other at each contact point, given in world coordinates. Each entry is a 3-list, and can be a unit vector, or [0,0,0] if the the normal cannot be computed properly. elems1, elems2 (list of n ints): for compound objects, these are the element indices corresponding to each contact. C++ includes: geometry.h """ this = _robotsim.new_ContactQueryResult() try: self.this.append(this) except Exception: self.this = this
[ "def", "__init__", "(", "self", ")", ":", "this", "=", "_robotsim", ".", "new_ContactQueryResult", "(", ")", "try", ":", "self", ".", "this", ".", "append", "(", "this", ")", "except", "Exception", ":", "self", ".", "this", "=", "this" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L1794-L1827
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/richtext.py
python
RichTextBuffer.GetStyleStackSize
(*args, **kwargs)
return _richtext.RichTextBuffer_GetStyleStackSize(*args, **kwargs)
GetStyleStackSize(self) -> size_t
GetStyleStackSize(self) -> size_t
[ "GetStyleStackSize", "(", "self", ")", "-", ">", "size_t" ]
def GetStyleStackSize(*args, **kwargs): """GetStyleStackSize(self) -> size_t""" return _richtext.RichTextBuffer_GetStyleStackSize(*args, **kwargs)
[ "def", "GetStyleStackSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextBuffer_GetStyleStackSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L2329-L2331
naver/sling
5671cd445a2caae0b4dd0332299e4cfede05062c
webkit/Tools/Scripts/webkitpy/common/system/filesystem.py
python
FileSystem.files_under
(self, path, dirs_to_skip=[], file_filter=None)
return files
Return the list of all files under the given path in topdown order. Args: dirs_to_skip: a list of directories to skip over during the traversal (e.g., .svn, resources, etc.) file_filter: if not None, the filter will be invoked with the filesystem object and the dirname and basename of each file found. The file is included in the result if the callback returns True.
Return the list of all files under the given path in topdown order.
[ "Return", "the", "list", "of", "all", "files", "under", "the", "given", "path", "in", "topdown", "order", "." ]
def files_under(self, path, dirs_to_skip=[], file_filter=None): """Return the list of all files under the given path in topdown order. Args: dirs_to_skip: a list of directories to skip over during the traversal (e.g., .svn, resources, etc.) file_filter: if not None, the filter will be invoked with the filesystem object and the dirname and basename of each file found. The file is included in the result if the callback returns True. """ def filter_all(fs, dirpath, basename): return True file_filter = file_filter or filter_all files = [] if self.isfile(path): if file_filter(self, self.dirname(path), self.basename(path)): files.append(path) return files if self.basename(path) in dirs_to_skip: return [] for (dirpath, dirnames, filenames) in os.walk(path): for d in dirs_to_skip: if d in dirnames: dirnames.remove(d) for filename in filenames: if file_filter(self, dirpath, filename): files.append(self.join(dirpath, filename)) return files
[ "def", "files_under", "(", "self", ",", "path", ",", "dirs_to_skip", "=", "[", "]", ",", "file_filter", "=", "None", ")", ":", "def", "filter_all", "(", "fs", ",", "dirpath", ",", "basename", ")", ":", "return", "True", "file_filter", "=", "file_filter", "or", "filter_all", "files", "=", "[", "]", "if", "self", ".", "isfile", "(", "path", ")", ":", "if", "file_filter", "(", "self", ",", "self", ".", "dirname", "(", "path", ")", ",", "self", ".", "basename", "(", "path", ")", ")", ":", "files", ".", "append", "(", "path", ")", "return", "files", "if", "self", ".", "basename", "(", "path", ")", "in", "dirs_to_skip", ":", "return", "[", "]", "for", "(", "dirpath", ",", "dirnames", ",", "filenames", ")", "in", "os", ".", "walk", "(", "path", ")", ":", "for", "d", "in", "dirs_to_skip", ":", "if", "d", "in", "dirnames", ":", "dirnames", ".", "remove", "(", "d", ")", "for", "filename", "in", "filenames", ":", "if", "file_filter", "(", "self", ",", "dirpath", ",", "filename", ")", ":", "files", ".", "append", "(", "self", ".", "join", "(", "dirpath", ",", "filename", ")", ")", "return", "files" ]
https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/common/system/filesystem.py#L108-L140
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
catboost/python-package/catboost/metrics.py
python
BuiltinMetric.eval
(self, label, approx, weight=None, group_id=None, group_weight=None, subgroup_id=None, pairs=None, thread_count=-1)
return _catboost._eval_metric_util( label, approx, str(self), weight, group_id, group_weight, subgroup_id, pairs, thread_count )
Evaluate the metric with raw approxes and labels. Parameters ---------- label : list or numpy.ndarrays or pandas.DataFrame or pandas.Series Object labels. approx : list or numpy.ndarrays or pandas.DataFrame or pandas.Series Object approxes. weight : list or numpy.ndarray or pandas.DataFrame or pandas.Series, optional (default=None) Object weights. group_id : list or numpy.ndarray or pandas.DataFrame or pandas.Series, optional (default=None) Object group ids. group_weight : list or numpy.ndarray or pandas.DataFrame or pandas.Series, optional (default=None) Group weights. subgroup_id : list or numpy.ndarray, optional (default=None) subgroup id for each instance. If not None, giving 1 dimensional array like data. pairs : list or numpy.ndarray or pandas.DataFrame or string or pathlib.Path The pairs description. If list or numpy.ndarrays or pandas.DataFrame, giving 2 dimensional. The shape should be Nx2, where N is the pairs' count. The first element of the pair is the index of winner object in the training set. The second element of the pair is the index of loser object in the training set. If string or pathlib.Path, giving the path to the file with pairs description. thread_count : int, optional (default=-1) Number of threads to work with. If -1, then the number of threads is set to the number of CPU cores. Returns ------- metric results : list with metric values.
Evaluate the metric with raw approxes and labels.
[ "Evaluate", "the", "metric", "with", "raw", "approxes", "and", "labels", "." ]
def eval(self, label, approx, weight=None, group_id=None, group_weight=None, subgroup_id=None, pairs=None, thread_count=-1): """ Evaluate the metric with raw approxes and labels. Parameters ---------- label : list or numpy.ndarrays or pandas.DataFrame or pandas.Series Object labels. approx : list or numpy.ndarrays or pandas.DataFrame or pandas.Series Object approxes. weight : list or numpy.ndarray or pandas.DataFrame or pandas.Series, optional (default=None) Object weights. group_id : list or numpy.ndarray or pandas.DataFrame or pandas.Series, optional (default=None) Object group ids. group_weight : list or numpy.ndarray or pandas.DataFrame or pandas.Series, optional (default=None) Group weights. subgroup_id : list or numpy.ndarray, optional (default=None) subgroup id for each instance. If not None, giving 1 dimensional array like data. pairs : list or numpy.ndarray or pandas.DataFrame or string or pathlib.Path The pairs description. If list or numpy.ndarrays or pandas.DataFrame, giving 2 dimensional. The shape should be Nx2, where N is the pairs' count. The first element of the pair is the index of winner object in the training set. The second element of the pair is the index of loser object in the training set. If string or pathlib.Path, giving the path to the file with pairs description. thread_count : int, optional (default=-1) Number of threads to work with. If -1, then the number of threads is set to the number of CPU cores. Returns ------- metric results : list with metric values. """ if len(label) > 0 and not isinstance(label[0], _ARRAY_TYPES): label = [label] if len(approx) == 0: approx = [[]] if not isinstance(approx[0], _ARRAY_TYPES): approx = [approx] return _catboost._eval_metric_util( label, approx, str(self), weight, group_id, group_weight, subgroup_id, pairs, thread_count )
[ "def", "eval", "(", "self", ",", "label", ",", "approx", ",", "weight", "=", "None", ",", "group_id", "=", "None", ",", "group_weight", "=", "None", ",", "subgroup_id", "=", "None", ",", "pairs", "=", "None", ",", "thread_count", "=", "-", "1", ")", ":", "if", "len", "(", "label", ")", ">", "0", "and", "not", "isinstance", "(", "label", "[", "0", "]", ",", "_ARRAY_TYPES", ")", ":", "label", "=", "[", "label", "]", "if", "len", "(", "approx", ")", "==", "0", ":", "approx", "=", "[", "[", "]", "]", "if", "not", "isinstance", "(", "approx", "[", "0", "]", ",", "_ARRAY_TYPES", ")", ":", "approx", "=", "[", "approx", "]", "return", "_catboost", ".", "_eval_metric_util", "(", "label", ",", "approx", ",", "str", "(", "self", ")", ",", "weight", ",", "group_id", ",", "group_weight", ",", "subgroup_id", ",", "pairs", ",", "thread_count", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/catboost/python-package/catboost/metrics.py#L56-L113
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/stata.py
python
StataStrLWriter.generate_blob
(self, gso_table)
return bio.read()
Generates the binary blob of GSOs that is written to the dta file. Parameters ---------- gso_table : dict Ordered dictionary (str, vo) Returns ------- gso : bytes Binary content of dta file to be placed between strl tags Notes ----- Output format depends on dta version. 117 uses two uint32s to express v and o while 118+ uses a uint32 for v and a uint64 for o.
Generates the binary blob of GSOs that is written to the dta file.
[ "Generates", "the", "binary", "blob", "of", "GSOs", "that", "is", "written", "to", "the", "dta", "file", "." ]
def generate_blob(self, gso_table): """ Generates the binary blob of GSOs that is written to the dta file. Parameters ---------- gso_table : dict Ordered dictionary (str, vo) Returns ------- gso : bytes Binary content of dta file to be placed between strl tags Notes ----- Output format depends on dta version. 117 uses two uint32s to express v and o while 118+ uses a uint32 for v and a uint64 for o. """ # Format information # Length includes null term # 117 # GSOvvvvooootllllxxxxxxxxxxxxxxx...x # 3 u4 u4 u1 u4 string + null term # # 118, 119 # GSOvvvvooooooootllllxxxxxxxxxxxxxxx...x # 3 u4 u8 u1 u4 string + null term bio = BytesIO() gso = bytes("GSO", "ascii") gso_type = struct.pack(self._byteorder + "B", 130) null = struct.pack(self._byteorder + "B", 0) v_type = self._byteorder + self._gso_v_type o_type = self._byteorder + self._gso_o_type len_type = self._byteorder + "I" for strl, vo in gso_table.items(): if vo == (0, 0): continue v, o = vo # GSO bio.write(gso) # vvvv bio.write(struct.pack(v_type, v)) # oooo / oooooooo bio.write(struct.pack(o_type, o)) # t bio.write(gso_type) # llll utf8_string = bytes(strl, "utf-8") bio.write(struct.pack(len_type, len(utf8_string) + 1)) # xxx...xxx bio.write(utf8_string) bio.write(null) bio.seek(0) return bio.read()
[ "def", "generate_blob", "(", "self", ",", "gso_table", ")", ":", "# Format information", "# Length includes null term", "# 117", "# GSOvvvvooootllllxxxxxxxxxxxxxxx...x", "# 3 u4 u4 u1 u4 string + null term", "#", "# 118, 119", "# GSOvvvvooooooootllllxxxxxxxxxxxxxxx...x", "# 3 u4 u8 u1 u4 string + null term", "bio", "=", "BytesIO", "(", ")", "gso", "=", "bytes", "(", "\"GSO\"", ",", "\"ascii\"", ")", "gso_type", "=", "struct", ".", "pack", "(", "self", ".", "_byteorder", "+", "\"B\"", ",", "130", ")", "null", "=", "struct", ".", "pack", "(", "self", ".", "_byteorder", "+", "\"B\"", ",", "0", ")", "v_type", "=", "self", ".", "_byteorder", "+", "self", ".", "_gso_v_type", "o_type", "=", "self", ".", "_byteorder", "+", "self", ".", "_gso_o_type", "len_type", "=", "self", ".", "_byteorder", "+", "\"I\"", "for", "strl", ",", "vo", "in", "gso_table", ".", "items", "(", ")", ":", "if", "vo", "==", "(", "0", ",", "0", ")", ":", "continue", "v", ",", "o", "=", "vo", "# GSO", "bio", ".", "write", "(", "gso", ")", "# vvvv", "bio", ".", "write", "(", "struct", ".", "pack", "(", "v_type", ",", "v", ")", ")", "# oooo / oooooooo", "bio", ".", "write", "(", "struct", ".", "pack", "(", "o_type", ",", "o", ")", ")", "# t", "bio", ".", "write", "(", "gso_type", ")", "# llll", "utf8_string", "=", "bytes", "(", "strl", ",", "\"utf-8\"", ")", "bio", ".", "write", "(", "struct", ".", "pack", "(", "len_type", ",", "len", "(", "utf8_string", ")", "+", "1", ")", ")", "# xxx...xxx", "bio", ".", "write", "(", "utf8_string", ")", "bio", ".", "write", "(", "null", ")", "bio", ".", "seek", "(", "0", ")", "return", "bio", ".", "read", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/stata.py#L2750-L2812
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aquabutton.py
python
AquaButton.DoGetBestSize
(self)
return wx.Size(retWidth+constant, retHeight+constant)
Overridden base class virtual. Determines the best size of the button based on the label and bezel size. :return: An instance of :class:`Size`. :note: Overridden from :class:`PyControl`.
Overridden base class virtual. Determines the best size of the button based on the label and bezel size.
[ "Overridden", "base", "class", "virtual", ".", "Determines", "the", "best", "size", "of", "the", "button", "based", "on", "the", "label", "and", "bezel", "size", "." ]
def DoGetBestSize(self): """ Overridden base class virtual. Determines the best size of the button based on the label and bezel size. :return: An instance of :class:`Size`. :note: Overridden from :class:`PyControl`. """ label = self.GetLabel() if not label: return wx.Size(112, 48) dc = wx.ClientDC(self) dc.SetFont(self.GetFont()) retWidth, retHeight = dc.GetTextExtent(label) bmpWidth = bmpHeight = 0 constant = 24 if self._bitmap: bmpWidth, bmpHeight = self._bitmap.GetWidth()+10, self._bitmap.GetHeight() retWidth += bmpWidth retHeight = max(bmpHeight, retHeight) constant = 24 return wx.Size(retWidth+constant, retHeight+constant)
[ "def", "DoGetBestSize", "(", "self", ")", ":", "label", "=", "self", ".", "GetLabel", "(", ")", "if", "not", "label", ":", "return", "wx", ".", "Size", "(", "112", ",", "48", ")", "dc", "=", "wx", ".", "ClientDC", "(", "self", ")", "dc", ".", "SetFont", "(", "self", ".", "GetFont", "(", ")", ")", "retWidth", ",", "retHeight", "=", "dc", ".", "GetTextExtent", "(", "label", ")", "bmpWidth", "=", "bmpHeight", "=", "0", "constant", "=", "24", "if", "self", ".", "_bitmap", ":", "bmpWidth", ",", "bmpHeight", "=", "self", ".", "_bitmap", ".", "GetWidth", "(", ")", "+", "10", ",", "self", ".", "_bitmap", ".", "GetHeight", "(", ")", "retWidth", "+=", "bmpWidth", "retHeight", "=", "max", "(", "bmpHeight", ",", "retHeight", ")", "constant", "=", "24", "return", "wx", ".", "Size", "(", "retWidth", "+", "constant", ",", "retHeight", "+", "constant", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aquabutton.py#L645-L671
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/convert/tool/subtool/acquire_sourcedir.py
python
set_custom_wineprefix
()
Allow the customization of the WINEPREFIX environment variable.
Allow the customization of the WINEPREFIX environment variable.
[ "Allow", "the", "customization", "of", "the", "WINEPREFIX", "environment", "variable", "." ]
def set_custom_wineprefix(): """ Allow the customization of the WINEPREFIX environment variable. """ print("The WINEPREFIX is a separate 'container' for windows " "software installations.") current_wineprefix = os.environ.get("WINEPREFIX") if current_wineprefix: print(f"Currently: WINEPREFIX='{current_wineprefix}'") print("Enter a custom value or leave empty to keep it as-is:") while True: new_wineprefix = input("WINEPREFIX=") if not new_wineprefix: break new_wineprefix = expand_relative_path(new_wineprefix) # test if it probably is a wineprefix if (Path(new_wineprefix) / "drive_c").is_dir(): # pylint: disable=no-member break print("This does not appear to be a valid WINEPREFIX.") print("Enter a valid one, or leave it empty to skip.") # store the updated env variable for the wine subprocess if new_wineprefix: os.environ["WINEPREFIX"] = new_wineprefix
[ "def", "set_custom_wineprefix", "(", ")", ":", "print", "(", "\"The WINEPREFIX is a separate 'container' for windows \"", "\"software installations.\"", ")", "current_wineprefix", "=", "os", ".", "environ", ".", "get", "(", "\"WINEPREFIX\"", ")", "if", "current_wineprefix", ":", "print", "(", "f\"Currently: WINEPREFIX='{current_wineprefix}'\"", ")", "print", "(", "\"Enter a custom value or leave empty to keep it as-is:\"", ")", "while", "True", ":", "new_wineprefix", "=", "input", "(", "\"WINEPREFIX=\"", ")", "if", "not", "new_wineprefix", ":", "break", "new_wineprefix", "=", "expand_relative_path", "(", "new_wineprefix", ")", "# test if it probably is a wineprefix", "if", "(", "Path", "(", "new_wineprefix", ")", "/", "\"drive_c\"", ")", ".", "is_dir", "(", ")", ":", "# pylint: disable=no-member", "break", "print", "(", "\"This does not appear to be a valid WINEPREFIX.\"", ")", "print", "(", "\"Enter a valid one, or leave it empty to skip.\"", ")", "# store the updated env variable for the wine subprocess", "if", "new_wineprefix", ":", "os", ".", "environ", "[", "\"WINEPREFIX\"", "]", "=", "new_wineprefix" ]
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/tool/subtool/acquire_sourcedir.py#L86-L116
mavlink/mavros
a32232d57a5e91abf6737e454d4199cae29b369c
mavros/mavros/cmd/system.py
python
rate
( ctx, client, all, raw_sensors, ext_status, rc_channels, raw_controller, position, extra1, extra2, extra3, stream_id, )
Set stream rate.
Set stream rate.
[ "Set", "stream", "rate", "." ]
def rate( ctx, client, all, raw_sensors, ext_status, rc_channels, raw_controller, position, extra1, extra2, extra3, stream_id, ): """Set stream rate.""" _ = 1 # yapf def set_rate(rate_arg: typing.Optional[int], id_: int): if rate_arg is None: return req = StreamRate.Request( stream_id=id_, message_rate=rate_arg, on_off=(rate_arg != 0), ) client.system.cli_set_stream_rate.call(req) set_rate(all, StreamRate.Request.STREAM_ALL) set_rate(raw_sensors, StreamRate.Request.STREAM_RAW_SENSORS) set_rate(ext_status, StreamRate.Request.STREAM_EXTENDED_STATUS) set_rate(rc_channels, StreamRate.Request.STREAM_RC_CHANNELS) set_rate(raw_controller, StreamRate.Request.STREAM_RAW_CONTROLLER) set_rate(position, StreamRate.Request.STREAM_POSITION) set_rate(extra1, StreamRate.Request.STREAM_EXTRA1) set_rate(extra2, StreamRate.Request.STREAM_EXTRA2) set_rate(extra3, StreamRate.Request.STREAM_EXTRA3) if stream_id: set_rate(stream_id[1], stream_id[0])
[ "def", "rate", "(", "ctx", ",", "client", ",", "all", ",", "raw_sensors", ",", "ext_status", ",", "rc_channels", ",", "raw_controller", ",", "position", ",", "extra1", ",", "extra2", ",", "extra3", ",", "stream_id", ",", ")", ":", "_", "=", "1", "# yapf", "def", "set_rate", "(", "rate_arg", ":", "typing", ".", "Optional", "[", "int", "]", ",", "id_", ":", "int", ")", ":", "if", "rate_arg", "is", "None", ":", "return", "req", "=", "StreamRate", ".", "Request", "(", "stream_id", "=", "id_", ",", "message_rate", "=", "rate_arg", ",", "on_off", "=", "(", "rate_arg", "!=", "0", ")", ",", ")", "client", ".", "system", ".", "cli_set_stream_rate", ".", "call", "(", "req", ")", "set_rate", "(", "all", ",", "StreamRate", ".", "Request", ".", "STREAM_ALL", ")", "set_rate", "(", "raw_sensors", ",", "StreamRate", ".", "Request", ".", "STREAM_RAW_SENSORS", ")", "set_rate", "(", "ext_status", ",", "StreamRate", ".", "Request", ".", "STREAM_EXTENDED_STATUS", ")", "set_rate", "(", "rc_channels", ",", "StreamRate", ".", "Request", ".", "STREAM_RC_CHANNELS", ")", "set_rate", "(", "raw_controller", ",", "StreamRate", ".", "Request", ".", "STREAM_RAW_CONTROLLER", ")", "set_rate", "(", "position", ",", "StreamRate", ".", "Request", ".", "STREAM_POSITION", ")", "set_rate", "(", "extra1", ",", "StreamRate", ".", "Request", ".", "STREAM_EXTRA1", ")", "set_rate", "(", "extra2", ",", "StreamRate", ".", "Request", ".", "STREAM_EXTRA2", ")", "set_rate", "(", "extra3", ",", "StreamRate", ".", "Request", ".", "STREAM_EXTRA3", ")", "if", "stream_id", ":", "set_rate", "(", "stream_id", "[", "1", "]", ",", "stream_id", "[", "0", "]", ")" ]
https://github.com/mavlink/mavros/blob/a32232d57a5e91abf6737e454d4199cae29b369c/mavros/mavros/cmd/system.py#L107-L146
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/winpython/wppm.py
python
Distribution.find_package
(self, name)
Find installed package
Find installed package
[ "Find", "installed", "package" ]
def find_package(self, name): """Find installed package""" for pack in self.get_installed_packages(): if pack.name == name: return pack
[ "def", "find_package", "(", "self", ",", "name", ")", ":", "for", "pack", "in", "self", ".", "get_installed_packages", "(", ")", ":", "if", "pack", ".", "name", "==", "name", ":", "return", "pack" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/winpython/wppm.py#L305-L309
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/Paste/paste/auth/form.py
python
make_form
(app, global_conf, realm, authfunc, **kw)
return AuthFormHandler(app, authfunc, template)
Grant access via form authentication Config looks like this:: [filter:grant] use = egg:Paste#auth_form realm=myrealm authfunc=somepackage.somemodule:somefunction
Grant access via form authentication
[ "Grant", "access", "via", "form", "authentication" ]
def make_form(app, global_conf, realm, authfunc, **kw): """ Grant access via form authentication Config looks like this:: [filter:grant] use = egg:Paste#auth_form realm=myrealm authfunc=somepackage.somemodule:somefunction """ from paste.util.import_string import eval_import import types authfunc = eval_import(authfunc) assert isinstance(authfunc, types.FunctionType), "authfunc must resolve to a function" template = kw.get('template') if template is not None: template = eval_import(template) assert isinstance(template, str), "template must resolve to a string" return AuthFormHandler(app, authfunc, template)
[ "def", "make_form", "(", "app", ",", "global_conf", ",", "realm", ",", "authfunc", ",", "*", "*", "kw", ")", ":", "from", "paste", ".", "util", ".", "import_string", "import", "eval_import", "import", "types", "authfunc", "=", "eval_import", "(", "authfunc", ")", "assert", "isinstance", "(", "authfunc", ",", "types", ".", "FunctionType", ")", ",", "\"authfunc must resolve to a function\"", "template", "=", "kw", ".", "get", "(", "'template'", ")", "if", "template", "is", "not", "None", ":", "template", "=", "eval_import", "(", "template", ")", "assert", "isinstance", "(", "template", ",", "str", ")", ",", "\"template must resolve to a string\"", "return", "AuthFormHandler", "(", "app", ",", "authfunc", ",", "template", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/Paste/paste/auth/form.py#L124-L145
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/core/android_action_runner.py
python
AndroidActionRunner.InputTap
(self, x_coord, y_coord)
Perform a tap input at the given coordinates. Args: x_coord: The x coordinate of the tap event. y_coord: The y coordinate of the tap event.
Perform a tap input at the given coordinates.
[ "Perform", "a", "tap", "input", "at", "the", "given", "coordinates", "." ]
def InputTap(self, x_coord, y_coord): """Perform a tap input at the given coordinates. Args: x_coord: The x coordinate of the tap event. y_coord: The y coordinate of the tap event. """ self._platform_backend.device.RunShellCommand('input tap %s %s' % (x_coord, y_coord))
[ "def", "InputTap", "(", "self", ",", "x_coord", ",", "y_coord", ")", ":", "self", ".", "_platform_backend", ".", "device", ".", "RunShellCommand", "(", "'input tap %s %s'", "%", "(", "x_coord", ",", "y_coord", ")", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/core/android_action_runner.py#L81-L89
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/nn/modules/container.py
python
ModuleDict.keys
(self)
return self._modules.keys()
r"""Return an iterable of the ModuleDict keys.
r"""Return an iterable of the ModuleDict keys.
[ "r", "Return", "an", "iterable", "of", "the", "ModuleDict", "keys", "." ]
def keys(self) -> Iterable[str]: r"""Return an iterable of the ModuleDict keys. """ return self._modules.keys()
[ "def", "keys", "(", "self", ")", "->", "Iterable", "[", "str", "]", ":", "return", "self", ".", "_modules", ".", "keys", "(", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/nn/modules/container.py#L364-L367
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBTypeSynthetic.GetData
(self)
return _lldb.SBTypeSynthetic_GetData(self)
GetData(SBTypeSynthetic self) -> char const *
GetData(SBTypeSynthetic self) -> char const *
[ "GetData", "(", "SBTypeSynthetic", "self", ")", "-", ">", "char", "const", "*" ]
def GetData(self): """GetData(SBTypeSynthetic self) -> char const *""" return _lldb.SBTypeSynthetic_GetData(self)
[ "def", "GetData", "(", "self", ")", ":", "return", "_lldb", ".", "SBTypeSynthetic_GetData", "(", "self", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L14019-L14021
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/labeled_tensor/python/ops/core.py
python
LabeledTensor._as_graph_element
(self)
return self.tensor
Support tf.Graph.as_graph_element on LabeledTensor objects. This allows operations such as tf.name_scope to take labeled tensors. Returns: self.tensor
Support tf.Graph.as_graph_element on LabeledTensor objects.
[ "Support", "tf", ".", "Graph", ".", "as_graph_element", "on", "LabeledTensor", "objects", "." ]
def _as_graph_element(self): """Support tf.Graph.as_graph_element on LabeledTensor objects. This allows operations such as tf.name_scope to take labeled tensors. Returns: self.tensor """ return self.tensor
[ "def", "_as_graph_element", "(", "self", ")", ":", "return", "self", ".", "tensor" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/labeled_tensor/python/ops/core.py#L344-L352
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py2/IPython/utils/_process_win32_controller.py
python
Win32ShellCommandController.__init__
(self, cmd, mergeout = True)
Initializes the shell command controller. The cmd is the program to execute, and mergeout is whether to blend stdout and stderr into one output in stdout. Merging them together in this fashion more reliably keeps stdout and stderr in the correct order especially for interactive shell usage.
Initializes the shell command controller.
[ "Initializes", "the", "shell", "command", "controller", "." ]
def __init__(self, cmd, mergeout = True): """Initializes the shell command controller. The cmd is the program to execute, and mergeout is whether to blend stdout and stderr into one output in stdout. Merging them together in this fashion more reliably keeps stdout and stderr in the correct order especially for interactive shell usage. """ self.cmd = cmd self.mergeout = mergeout
[ "def", "__init__", "(", "self", ",", "cmd", ",", "mergeout", "=", "True", ")", ":", "self", ".", "cmd", "=", "cmd", "self", ".", "mergeout", "=", "mergeout" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/utils/_process_win32_controller.py#L221-L231
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2class.py
python
uCSIsPrivateUseArea
(code)
return ret
Check whether the character is part of PrivateUseArea UCS Block
Check whether the character is part of PrivateUseArea UCS Block
[ "Check", "whether", "the", "character", "is", "part", "of", "PrivateUseArea", "UCS", "Block" ]
def uCSIsPrivateUseArea(code): """Check whether the character is part of PrivateUseArea UCS Block """ ret = libxml2mod.xmlUCSIsPrivateUseArea(code) return ret
[ "def", "uCSIsPrivateUseArea", "(", "code", ")", ":", "ret", "=", "libxml2mod", ".", "xmlUCSIsPrivateUseArea", "(", "code", ")", "return", "ret" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L2040-L2044
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
DataObject.IsSupported
(*args, **kwargs)
return _misc_.DataObject_IsSupported(*args, **kwargs)
IsSupported(self, DataFormat format, int dir=Get) -> bool Returns True if this format is supported.
IsSupported(self, DataFormat format, int dir=Get) -> bool
[ "IsSupported", "(", "self", "DataFormat", "format", "int", "dir", "=", "Get", ")", "-", ">", "bool" ]
def IsSupported(*args, **kwargs): """ IsSupported(self, DataFormat format, int dir=Get) -> bool Returns True if this format is supported. """ return _misc_.DataObject_IsSupported(*args, **kwargs)
[ "def", "IsSupported", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "DataObject_IsSupported", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L4949-L4955
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/timeseries/python/timeseries/state_space_models/state_space_model.py
python
StateSpaceModel.get_prior_covariance
(self)
Constructs a variable prior covariance with data-based initialization. Models should wrap any variables defined here in the model's variable scope. Returns: A two-dimensional [state dimension, state dimension] floating point Tensor with a (positive definite) prior state covariance matrix.
Constructs a variable prior covariance with data-based initialization.
[ "Constructs", "a", "variable", "prior", "covariance", "with", "data", "-", "based", "initialization", "." ]
def get_prior_covariance(self): """Constructs a variable prior covariance with data-based initialization. Models should wrap any variables defined here in the model's variable scope. Returns: A two-dimensional [state dimension, state dimension] floating point Tensor with a (positive definite) prior state covariance matrix. """ with variable_scope.variable_scope(self._variable_scope): state_dimension = ops.convert_to_tensor( self.get_state_transition()).get_shape()[0].value if self._configuration.trainable_start_state: base_covariance = math_utils.variable_covariance_matrix( state_dimension, "prior_state_var", dtype=self.dtype) else: return linalg_ops.eye(state_dimension, dtype=self.dtype) if self._input_statistics is not None: # Make sure initial latent value uncertainty is at least on the same # scale as noise in the data. covariance_multiplier = math_ops.reduce_max( self._scale_variance( self._input_statistics.series_start_moments.variance)) return base_covariance * gen_math_ops.maximum( covariance_multiplier, 1.0) else: return base_covariance
[ "def", "get_prior_covariance", "(", "self", ")", ":", "with", "variable_scope", ".", "variable_scope", "(", "self", ".", "_variable_scope", ")", ":", "state_dimension", "=", "ops", ".", "convert_to_tensor", "(", "self", ".", "get_state_transition", "(", ")", ")", ".", "get_shape", "(", ")", "[", "0", "]", ".", "value", "if", "self", ".", "_configuration", ".", "trainable_start_state", ":", "base_covariance", "=", "math_utils", ".", "variable_covariance_matrix", "(", "state_dimension", ",", "\"prior_state_var\"", ",", "dtype", "=", "self", ".", "dtype", ")", "else", ":", "return", "linalg_ops", ".", "eye", "(", "state_dimension", ",", "dtype", "=", "self", ".", "dtype", ")", "if", "self", ".", "_input_statistics", "is", "not", "None", ":", "# Make sure initial latent value uncertainty is at least on the same", "# scale as noise in the data.", "covariance_multiplier", "=", "math_ops", ".", "reduce_max", "(", "self", ".", "_scale_variance", "(", "self", ".", "_input_statistics", ".", "series_start_moments", ".", "variance", ")", ")", "return", "base_covariance", "*", "gen_math_ops", ".", "maximum", "(", "covariance_multiplier", ",", "1.0", ")", "else", ":", "return", "base_covariance" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/timeseries/python/timeseries/state_space_models/state_space_model.py#L704-L731
livecode/livecode
4606a10ea10b16d5071d0f9f263ccdd7ede8b31d
gyp/pylib/gyp/MSVSProject.py
python
Tool._GetSpecification
(self)
return ['Tool', self._attrs]
Creates an element for the tool. Returns: A new xml.dom.Element for the tool.
Creates an element for the tool.
[ "Creates", "an", "element", "for", "the", "tool", "." ]
def _GetSpecification(self): """Creates an element for the tool. Returns: A new xml.dom.Element for the tool. """ return ['Tool', self._attrs]
[ "def", "_GetSpecification", "(", "self", ")", ":", "return", "[", "'Tool'", ",", "self", ".", "_attrs", "]" ]
https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/MSVSProject.py#L26-L32
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Pygments/py3/pygments/util.py
python
duplicates_removed
(it, already_seen=())
return lst
Returns a list with duplicates removed from the iterable `it`. Order is preserved.
Returns a list with duplicates removed from the iterable `it`.
[ "Returns", "a", "list", "with", "duplicates", "removed", "from", "the", "iterable", "it", "." ]
def duplicates_removed(it, already_seen=()): """ Returns a list with duplicates removed from the iterable `it`. Order is preserved. """ lst = [] seen = set() for i in it: if i in seen or i in already_seen: continue lst.append(i) seen.add(i) return lst
[ "def", "duplicates_removed", "(", "it", ",", "already_seen", "=", "(", ")", ")", ":", "lst", "=", "[", "]", "seen", "=", "set", "(", ")", "for", "i", "in", "it", ":", "if", "i", "in", "seen", "or", "i", "in", "already_seen", ":", "continue", "lst", ".", "append", "(", "i", ")", "seen", ".", "add", "(", "i", ")", "return", "lst" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Pygments/py3/pygments/util.py#L233-L246
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/composite/base.py
python
_Grad.__init__
(self, get_by_list=False, sens_param=False, get_by_position=False)
Initialize _Grad.
Initialize _Grad.
[ "Initialize", "_Grad", "." ]
def __init__(self, get_by_list=False, sens_param=False, get_by_position=False): """Initialize _Grad.""" if not isinstance(get_by_position, bool): raise TypeError(f"For '_Grad', the 'get_by_position' should be bool, " f"but got {type(get_by_position).__name__}") if not isinstance(get_by_list, bool): raise TypeError(f"For '_Grad', the 'get_by_list' should be bool, " f"but got {type(get_by_list).__name__}") if not isinstance(sens_param, bool): raise TypeError(f"For '_Grad', the 'sens_param' should be bool, " f"but got {type(sens_param).__name__}") self.get_by_position = get_by_position self.get_by_list = get_by_list self.sens_param = sens_param GradOperation_.__init__(self, 'grad', False, get_by_list, sens_param, get_by_position) self.grad_fn = None self.fn = None self.pynative_ = False self.grad_position = None
[ "def", "__init__", "(", "self", ",", "get_by_list", "=", "False", ",", "sens_param", "=", "False", ",", "get_by_position", "=", "False", ")", ":", "if", "not", "isinstance", "(", "get_by_position", ",", "bool", ")", ":", "raise", "TypeError", "(", "f\"For '_Grad', the 'get_by_position' should be bool, \"", "f\"but got {type(get_by_position).__name__}\"", ")", "if", "not", "isinstance", "(", "get_by_list", ",", "bool", ")", ":", "raise", "TypeError", "(", "f\"For '_Grad', the 'get_by_list' should be bool, \"", "f\"but got {type(get_by_list).__name__}\"", ")", "if", "not", "isinstance", "(", "sens_param", ",", "bool", ")", ":", "raise", "TypeError", "(", "f\"For '_Grad', the 'sens_param' should be bool, \"", "f\"but got {type(sens_param).__name__}\"", ")", "self", ".", "get_by_position", "=", "get_by_position", "self", ".", "get_by_list", "=", "get_by_list", "self", ".", "sens_param", "=", "sens_param", "GradOperation_", ".", "__init__", "(", "self", ",", "'grad'", ",", "False", ",", "get_by_list", ",", "sens_param", ",", "get_by_position", ")", "self", ".", "grad_fn", "=", "None", "self", ".", "fn", "=", "None", "self", ".", "pynative_", "=", "False", "self", ".", "grad_position", "=", "None" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/composite/base.py#L408-L426
BertaBescos/DynaSLAM
8f894a8b9d63c0a608fd871d63c10796491b9312
src/python/model.py
python
identity_block
(input_tensor, kernel_size, filters, stage, block, use_bias=True)
return x
The identity_block is the block that has no conv layer at shortcut # Arguments input_tensor: input tensor kernel_size: defualt 3, the kernel size of middle conv layer at main path filters: list of integers, the nb_filters of 3 conv layer at main path stage: integer, current stage label, used for generating layer names block: 'a','b'..., current block label, used for generating layer names
The identity_block is the block that has no conv layer at shortcut # Arguments input_tensor: input tensor kernel_size: defualt 3, the kernel size of middle conv layer at main path filters: list of integers, the nb_filters of 3 conv layer at main path stage: integer, current stage label, used for generating layer names block: 'a','b'..., current block label, used for generating layer names
[ "The", "identity_block", "is", "the", "block", "that", "has", "no", "conv", "layer", "at", "shortcut", "#", "Arguments", "input_tensor", ":", "input", "tensor", "kernel_size", ":", "defualt", "3", "the", "kernel", "size", "of", "middle", "conv", "layer", "at", "main", "path", "filters", ":", "list", "of", "integers", "the", "nb_filters", "of", "3", "conv", "layer", "at", "main", "path", "stage", ":", "integer", "current", "stage", "label", "used", "for", "generating", "layer", "names", "block", ":", "a", "b", "...", "current", "block", "label", "used", "for", "generating", "layer", "names" ]
def identity_block(input_tensor, kernel_size, filters, stage, block, use_bias=True): """The identity_block is the block that has no conv layer at shortcut # Arguments input_tensor: input tensor kernel_size: defualt 3, the kernel size of middle conv layer at main path filters: list of integers, the nb_filters of 3 conv layer at main path stage: integer, current stage label, used for generating layer names block: 'a','b'..., current block label, used for generating layer names """ nb_filter1, nb_filter2, nb_filter3 = filters conv_name_base = 'res' + str(stage) + block + '_branch' bn_name_base = 'bn' + str(stage) + block + '_branch' x = KL.Conv2D(nb_filter1, (1, 1), name=conv_name_base + '2a', use_bias=use_bias)(input_tensor) x = BatchNorm(axis=3, name=bn_name_base + '2a')(x) x = KL.Activation('relu')(x) x = KL.Conv2D(nb_filter2, (kernel_size, kernel_size), padding='same', name=conv_name_base + '2b', use_bias=use_bias)(x) x = BatchNorm(axis=3, name=bn_name_base + '2b')(x) x = KL.Activation('relu')(x) x = KL.Conv2D(nb_filter3, (1, 1), name=conv_name_base + '2c', use_bias=use_bias)(x) x = BatchNorm(axis=3, name=bn_name_base + '2c')(x) x = KL.Add()([x, input_tensor]) x = KL.Activation('relu', name='res'+str(stage)+block+'_out')(x) return x
[ "def", "identity_block", "(", "input_tensor", ",", "kernel_size", ",", "filters", ",", "stage", ",", "block", ",", "use_bias", "=", "True", ")", ":", "nb_filter1", ",", "nb_filter2", ",", "nb_filter3", "=", "filters", "conv_name_base", "=", "'res'", "+", "str", "(", "stage", ")", "+", "block", "+", "'_branch'", "bn_name_base", "=", "'bn'", "+", "str", "(", "stage", ")", "+", "block", "+", "'_branch'", "x", "=", "KL", ".", "Conv2D", "(", "nb_filter1", ",", "(", "1", ",", "1", ")", ",", "name", "=", "conv_name_base", "+", "'2a'", ",", "use_bias", "=", "use_bias", ")", "(", "input_tensor", ")", "x", "=", "BatchNorm", "(", "axis", "=", "3", ",", "name", "=", "bn_name_base", "+", "'2a'", ")", "(", "x", ")", "x", "=", "KL", ".", "Activation", "(", "'relu'", ")", "(", "x", ")", "x", "=", "KL", ".", "Conv2D", "(", "nb_filter2", ",", "(", "kernel_size", ",", "kernel_size", ")", ",", "padding", "=", "'same'", ",", "name", "=", "conv_name_base", "+", "'2b'", ",", "use_bias", "=", "use_bias", ")", "(", "x", ")", "x", "=", "BatchNorm", "(", "axis", "=", "3", ",", "name", "=", "bn_name_base", "+", "'2b'", ")", "(", "x", ")", "x", "=", "KL", ".", "Activation", "(", "'relu'", ")", "(", "x", ")", "x", "=", "KL", ".", "Conv2D", "(", "nb_filter3", ",", "(", "1", ",", "1", ")", ",", "name", "=", "conv_name_base", "+", "'2c'", ",", "use_bias", "=", "use_bias", ")", "(", "x", ")", "x", "=", "BatchNorm", "(", "axis", "=", "3", ",", "name", "=", "bn_name_base", "+", "'2c'", ")", "(", "x", ")", "x", "=", "KL", ".", "Add", "(", ")", "(", "[", "x", ",", "input_tensor", "]", ")", "x", "=", "KL", ".", "Activation", "(", "'relu'", ",", "name", "=", "'res'", "+", "str", "(", "stage", ")", "+", "block", "+", "'_out'", ")", "(", "x", ")", "return", "x" ]
https://github.com/BertaBescos/DynaSLAM/blob/8f894a8b9d63c0a608fd871d63c10796491b9312/src/python/model.py#L75-L105
albertz/openlierox
d316c14a8eb57848ef56e9bfa7b23a56f694a51b
tools/DedicatedServerVideo/gdata/docs/service.py
python
DocsService._UploadFile
(self, media_source, title, category, folder_or_uri=None)
return entry
Uploads a file to the Document List feed. Args: media_source: A gdata.MediaSource object containing the file to be uploaded. title: string The title of the document on the server after being uploaded. category: An atom.Category object specifying the appropriate document type. folder_or_uri: DocumentListEntry or string (optional) An object with a link to a folder or a uri to a folder to upload to. Note: A valid uri for a folder is of the form: /feeds/folders/private/full/folder%3Afolder_id Returns: A DocumentListEntry containing information about the document created on the Google Documents service.
Uploads a file to the Document List feed.
[ "Uploads", "a", "file", "to", "the", "Document", "List", "feed", "." ]
def _UploadFile(self, media_source, title, category, folder_or_uri=None): """Uploads a file to the Document List feed. Args: media_source: A gdata.MediaSource object containing the file to be uploaded. title: string The title of the document on the server after being uploaded. category: An atom.Category object specifying the appropriate document type. folder_or_uri: DocumentListEntry or string (optional) An object with a link to a folder or a uri to a folder to upload to. Note: A valid uri for a folder is of the form: /feeds/folders/private/full/folder%3Afolder_id Returns: A DocumentListEntry containing information about the document created on the Google Documents service. """ if folder_or_uri: try: uri = folder_or_uri.content.src except AttributeError: uri = folder_or_uri else: uri = '/feeds/documents/private/full' entry = gdata.docs.DocumentListEntry() entry.title = atom.Title(text=title) if category is not None: entry.category.append(category) entry = self.Post(entry, uri, media_source=media_source, extra_headers={'Slug': media_source.file_name}, converter=gdata.docs.DocumentListEntryFromString) return entry
[ "def", "_UploadFile", "(", "self", ",", "media_source", ",", "title", ",", "category", ",", "folder_or_uri", "=", "None", ")", ":", "if", "folder_or_uri", ":", "try", ":", "uri", "=", "folder_or_uri", ".", "content", ".", "src", "except", "AttributeError", ":", "uri", "=", "folder_or_uri", "else", ":", "uri", "=", "'/feeds/documents/private/full'", "entry", "=", "gdata", ".", "docs", ".", "DocumentListEntry", "(", ")", "entry", ".", "title", "=", "atom", ".", "Title", "(", "text", "=", "title", ")", "if", "category", "is", "not", "None", ":", "entry", ".", "category", ".", "append", "(", "category", ")", "entry", "=", "self", ".", "Post", "(", "entry", ",", "uri", ",", "media_source", "=", "media_source", ",", "extra_headers", "=", "{", "'Slug'", ":", "media_source", ".", "file_name", "}", ",", "converter", "=", "gdata", ".", "docs", ".", "DocumentListEntryFromString", ")", "return", "entry" ]
https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/docs/service.py#L127-L161
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/mhlib.py
python
Folder.getsequences
(self)
return sequences
Return the set of sequences for the folder.
Return the set of sequences for the folder.
[ "Return", "the", "set", "of", "sequences", "for", "the", "folder", "." ]
def getsequences(self): """Return the set of sequences for the folder.""" sequences = {} fullname = self.getsequencesfilename() try: f = open(fullname, 'r') except IOError: return sequences while 1: line = f.readline() if not line: break fields = line.split(':') if len(fields) != 2: self.error('bad sequence in %s: %s' % (fullname, line.strip())) key = fields[0].strip() value = IntSet(fields[1].strip(), ' ').tolist() sequences[key] = value return sequences
[ "def", "getsequences", "(", "self", ")", ":", "sequences", "=", "{", "}", "fullname", "=", "self", ".", "getsequencesfilename", "(", ")", "try", ":", "f", "=", "open", "(", "fullname", ",", "'r'", ")", "except", "IOError", ":", "return", "sequences", "while", "1", ":", "line", "=", "f", ".", "readline", "(", ")", "if", "not", "line", ":", "break", "fields", "=", "line", ".", "split", "(", "':'", ")", "if", "len", "(", "fields", ")", "!=", "2", ":", "self", ".", "error", "(", "'bad sequence in %s: %s'", "%", "(", "fullname", ",", "line", ".", "strip", "(", ")", ")", ")", "key", "=", "fields", "[", "0", "]", ".", "strip", "(", ")", "value", "=", "IntSet", "(", "fields", "[", "1", "]", ".", "strip", "(", ")", ",", "' '", ")", ".", "tolist", "(", ")", "sequences", "[", "key", "]", "=", "value", "return", "sequences" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/mhlib.py#L297-L315
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/Blast/3rdParty/assimp/port/PyAssimp/scripts/transformations.py
python
vector_norm
(data, axis=None, out=None)
Return length, i.e. eucledian norm, of ndarray along axis. >>> v = numpy.random.random(3) >>> n = vector_norm(v) >>> numpy.allclose(n, numpy.linalg.norm(v)) True >>> v = numpy.random.rand(6, 5, 3) >>> n = vector_norm(v, axis=-1) >>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=2))) True >>> n = vector_norm(v, axis=1) >>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=1))) True >>> v = numpy.random.rand(5, 4, 3) >>> n = numpy.empty((5, 3), dtype=numpy.float64) >>> vector_norm(v, axis=1, out=n) >>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=1))) True >>> vector_norm([]) 0.0 >>> vector_norm([1.0]) 1.0
Return length, i.e. eucledian norm, of ndarray along axis.
[ "Return", "length", "i", ".", "e", ".", "eucledian", "norm", "of", "ndarray", "along", "axis", "." ]
def vector_norm(data, axis=None, out=None): """Return length, i.e. eucledian norm, of ndarray along axis. >>> v = numpy.random.random(3) >>> n = vector_norm(v) >>> numpy.allclose(n, numpy.linalg.norm(v)) True >>> v = numpy.random.rand(6, 5, 3) >>> n = vector_norm(v, axis=-1) >>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=2))) True >>> n = vector_norm(v, axis=1) >>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=1))) True >>> v = numpy.random.rand(5, 4, 3) >>> n = numpy.empty((5, 3), dtype=numpy.float64) >>> vector_norm(v, axis=1, out=n) >>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=1))) True >>> vector_norm([]) 0.0 >>> vector_norm([1.0]) 1.0 """ data = numpy.array(data, dtype=numpy.float64, copy=True) if out is None: if data.ndim == 1: return math.sqrt(numpy.dot(data, data)) data *= data out = numpy.atleast_1d(numpy.sum(data, axis=axis)) numpy.sqrt(out, out) return out else: data *= data numpy.sum(data, axis=axis, out=out) numpy.sqrt(out, out)
[ "def", "vector_norm", "(", "data", ",", "axis", "=", "None", ",", "out", "=", "None", ")", ":", "data", "=", "numpy", ".", "array", "(", "data", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "True", ")", "if", "out", "is", "None", ":", "if", "data", ".", "ndim", "==", "1", ":", "return", "math", ".", "sqrt", "(", "numpy", ".", "dot", "(", "data", ",", "data", ")", ")", "data", "*=", "data", "out", "=", "numpy", ".", "atleast_1d", "(", "numpy", ".", "sum", "(", "data", ",", "axis", "=", "axis", ")", ")", "numpy", ".", "sqrt", "(", "out", ",", "out", ")", "return", "out", "else", ":", "data", "*=", "data", "numpy", ".", "sum", "(", "data", ",", "axis", "=", "axis", ",", "out", "=", "out", ")", "numpy", ".", "sqrt", "(", "out", ",", "out", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/Blast/3rdParty/assimp/port/PyAssimp/scripts/transformations.py#L1535-L1571
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/configHandler.py
python
IdleConf.CurrentTheme
(self)
return self.GetOption('main','Theme','name',default='')
Returns the name of the currently active theme
Returns the name of the currently active theme
[ "Returns", "the", "name", "of", "the", "currently", "active", "theme" ]
def CurrentTheme(self): """ Returns the name of the currently active theme """ return self.GetOption('main','Theme','name',default='')
[ "def", "CurrentTheme", "(", "self", ")", ":", "return", "self", ".", "GetOption", "(", "'main'", ",", "'Theme'", ",", "'name'", ",", "default", "=", "''", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/configHandler.py#L388-L392
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/SimpleHTTPServer.py
python
SimpleHTTPRequestHandler.send_head
(self)
return f
Common code for GET and HEAD commands. This sends the response code and MIME headers. Return value is either a file object (which has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all circumstances), or None, in which case the caller has nothing further to do.
Common code for GET and HEAD commands.
[ "Common", "code", "for", "GET", "and", "HEAD", "commands", "." ]
def send_head(self): """Common code for GET and HEAD commands. This sends the response code and MIME headers. Return value is either a file object (which has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all circumstances), or None, in which case the caller has nothing further to do. """ path = self.translate_path(self.path) f = None if os.path.isdir(path): if not self.path.endswith('/'): # redirect browser - doing basically what apache does self.send_response(301) self.send_header("Location", self.path + "/") self.end_headers() return None for index in "index.html", "index.htm": index = os.path.join(path, index) if os.path.exists(index): path = index break else: return self.list_directory(path) ctype = self.guess_type(path) try: # Always read in binary mode. Opening files in text mode may cause # newline translations, making the actual size of the content # transmitted *less* than the content-length! f = open(path, 'rb') except IOError: self.send_error(404, "File not found") return None self.send_response(200) self.send_header("Content-type", ctype) fs = os.fstat(f.fileno()) self.send_header("Content-Length", str(fs[6])) self.send_header("Last-Modified", self.date_time_string(fs.st_mtime)) self.end_headers() return f
[ "def", "send_head", "(", "self", ")", ":", "path", "=", "self", ".", "translate_path", "(", "self", ".", "path", ")", "f", "=", "None", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "if", "not", "self", ".", "path", ".", "endswith", "(", "'/'", ")", ":", "# redirect browser - doing basically what apache does", "self", ".", "send_response", "(", "301", ")", "self", ".", "send_header", "(", "\"Location\"", ",", "self", ".", "path", "+", "\"/\"", ")", "self", ".", "end_headers", "(", ")", "return", "None", "for", "index", "in", "\"index.html\"", ",", "\"index.htm\"", ":", "index", "=", "os", ".", "path", ".", "join", "(", "path", ",", "index", ")", "if", "os", ".", "path", ".", "exists", "(", "index", ")", ":", "path", "=", "index", "break", "else", ":", "return", "self", ".", "list_directory", "(", "path", ")", "ctype", "=", "self", ".", "guess_type", "(", "path", ")", "try", ":", "# Always read in binary mode. Opening files in text mode may cause", "# newline translations, making the actual size of the content", "# transmitted *less* than the content-length!", "f", "=", "open", "(", "path", ",", "'rb'", ")", "except", "IOError", ":", "self", ".", "send_error", "(", "404", ",", "\"File not found\"", ")", "return", "None", "self", ".", "send_response", "(", "200", ")", "self", ".", "send_header", "(", "\"Content-type\"", ",", "ctype", ")", "fs", "=", "os", ".", "fstat", "(", "f", ".", "fileno", "(", ")", ")", "self", ".", "send_header", "(", "\"Content-Length\"", ",", "str", "(", "fs", "[", "6", "]", ")", ")", "self", ".", "send_header", "(", "\"Last-Modified\"", ",", "self", ".", "date_time_string", "(", "fs", ".", "st_mtime", ")", ")", "self", ".", "end_headers", "(", ")", "return", "f" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/SimpleHTTPServer.py#L54-L96
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/operator.py
python
ilshift
(a, b)
return a
Same as a <<= b.
Same as a <<= b.
[ "Same", "as", "a", "<<", "=", "b", "." ]
def ilshift(a, b): "Same as a <<= b." a <<= b return a
[ "def", "ilshift", "(", "a", ",", "b", ")", ":", "a", "<<=", "b", "return", "a" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/operator.py#L360-L363
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/configparser.py
python
RawConfigParser._convert_to_boolean
(self, value)
return self.BOOLEAN_STATES[value.lower()]
Return a boolean value translating from other types if necessary.
Return a boolean value translating from other types if necessary.
[ "Return", "a", "boolean", "value", "translating", "from", "other", "types", "if", "necessary", "." ]
def _convert_to_boolean(self, value): """Return a boolean value translating from other types if necessary. """ if value.lower() not in self.BOOLEAN_STATES: raise ValueError('Not a boolean: %s' % value) return self.BOOLEAN_STATES[value.lower()]
[ "def", "_convert_to_boolean", "(", "self", ",", "value", ")", ":", "if", "value", ".", "lower", "(", ")", "not", "in", "self", ".", "BOOLEAN_STATES", ":", "raise", "ValueError", "(", "'Not a boolean: %s'", "%", "value", ")", "return", "self", ".", "BOOLEAN_STATES", "[", "value", ".", "lower", "(", ")", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/configparser.py#L1162-L1167
tensorflow/deepmath
b5b721f54de1d5d6a02d78f5da5995237f9995f9
deepmath/deephol/prover.py
python
NoBacktrackProver.prove_one
(self, tree: proof_search_tree.ProofSearchTree, task: proof_assistant_pb2.ProverTask)
Searches for a proof without backtracking. Args: tree: Search tree with a single goal node to be proved. task: ProverTask to be performed. Returns: None on success and error message on failure.
Searches for a proof without backtracking.
[ "Searches", "for", "a", "proof", "without", "backtracking", "." ]
def prove_one(self, tree: proof_search_tree.ProofSearchTree, task: proof_assistant_pb2.ProverTask) -> Optional[Text]: """Searches for a proof without backtracking. Args: tree: Search tree with a single goal node to be proved. task: ProverTask to be performed. Returns: None on success and error message on failure. """ root = tree.nodes[0] budget = NO_BACKTRACK_SEARCH_NODES cur_index = 0 while not root.closed and not self.timed_out(): if cur_index >= len(tree.nodes): # This situation can happen only if the tactics succeed, but end up # reconstructing an earlier node. return 'NoBacktrack: Loop.' node = tree.nodes[cur_index] cur_index += 1 prover_util.try_tactics(node, budget, 0, 1, task.premise_set, self.action_gen, self.prover_options.tactic_timeout_ms) if not node.successful_attempts: return ('NoBacktrack: No successful tactic applications within ' 'limit %d' % budget) else: if len(node.successful_attempts) != 1: tf.logging.info('%d successful attempts.', len(node.successful_attempts)) for tac_app in node.successful_attempts: tf.logging.info('attempt: %s', tac_app.tactic) assert len(node.successful_attempts) == 1 budget -= len(node.failed_attempts) + 1 if not root.closed: if self.timed_out(): return 'Timed out.' else: return 'NoBacktrack: Could not find proof.'
[ "def", "prove_one", "(", "self", ",", "tree", ":", "proof_search_tree", ".", "ProofSearchTree", ",", "task", ":", "proof_assistant_pb2", ".", "ProverTask", ")", "->", "Optional", "[", "Text", "]", ":", "root", "=", "tree", ".", "nodes", "[", "0", "]", "budget", "=", "NO_BACKTRACK_SEARCH_NODES", "cur_index", "=", "0", "while", "not", "root", ".", "closed", "and", "not", "self", ".", "timed_out", "(", ")", ":", "if", "cur_index", ">=", "len", "(", "tree", ".", "nodes", ")", ":", "# This situation can happen only if the tactics succeed, but end up", "# reconstructing an earlier node.", "return", "'NoBacktrack: Loop.'", "node", "=", "tree", ".", "nodes", "[", "cur_index", "]", "cur_index", "+=", "1", "prover_util", ".", "try_tactics", "(", "node", ",", "budget", ",", "0", ",", "1", ",", "task", ".", "premise_set", ",", "self", ".", "action_gen", ",", "self", ".", "prover_options", ".", "tactic_timeout_ms", ")", "if", "not", "node", ".", "successful_attempts", ":", "return", "(", "'NoBacktrack: No successful tactic applications within '", "'limit %d'", "%", "budget", ")", "else", ":", "if", "len", "(", "node", ".", "successful_attempts", ")", "!=", "1", ":", "tf", ".", "logging", ".", "info", "(", "'%d successful attempts.'", ",", "len", "(", "node", ".", "successful_attempts", ")", ")", "for", "tac_app", "in", "node", ".", "successful_attempts", ":", "tf", ".", "logging", ".", "info", "(", "'attempt: %s'", ",", "tac_app", ".", "tactic", ")", "assert", "len", "(", "node", ".", "successful_attempts", ")", "==", "1", "budget", "-=", "len", "(", "node", ".", "failed_attempts", ")", "+", "1", "if", "not", "root", ".", "closed", ":", "if", "self", ".", "timed_out", "(", ")", ":", "return", "'Timed out.'", "else", ":", "return", "'NoBacktrack: Could not find proof.'" ]
https://github.com/tensorflow/deepmath/blob/b5b721f54de1d5d6a02d78f5da5995237f9995f9/deepmath/deephol/prover.py#L198-L237
NREL/EnergyPlus
fadc5973b85c70e8cc923efb69c144e808a26078
third_party/EP-Launch-Lite/EPLaunchLite/EPLaunchLiteWindow.py
python
Window.gui_build_body
(self)
return vbox
This function builds out the specific widgets on the GUI * Returns: A gtk.VBox suitable for adding directly onto the main gtk.Window
This function builds out the specific widgets on the GUI
[ "This", "function", "builds", "out", "the", "specific", "widgets", "on", "the", "GUI" ]
def gui_build_body(self): """ This function builds out the specific widgets on the GUI * Returns: A gtk.VBox suitable for adding directly onto the main gtk.Window """ # create a vbox here first vbox = gtk.VBox(False, self.box_spacing) # create the menu bar itself to hold the menus mb = gtk.MenuBar() # create the actual actionable items under the file menu menu_item_file_about = gtk.MenuItem(_("About...")) menu_item_file_about.connect("activate", self.about_dialog) menu_item_file_about.show() menu_item_file_exit = gtk.MenuItem(_("Exit")) menu_item_file_exit.connect("activate", self.quit) menu_item_file_exit.show() # create the actual actionable items under the language menu menu_item_english = gtk.MenuItem("Language: English") menu_item_english.connect("activate", self.switch_language, Languages.English) menu_item_english.show() if self.settings[Keys.language] == Languages.English: menu_item_english.set_sensitive(False) menu_item_spanish = gtk.MenuItem("Idioma: Espanol") menu_item_spanish.connect("activate", self.switch_language, Languages.Spanish) menu_item_spanish.show() if self.settings[Keys.language] == Languages.Spanish: menu_item_spanish.set_sensitive(False) menu_item_french = gtk.MenuItem("Langue: Francais") menu_item_french.connect("activate", self.switch_language, Languages.French) menu_item_french.show() if self.settings[Keys.language] == Languages.French: menu_item_french.set_sensitive(False) # create the list of items that will eventually be dropped down, and append items in the right order filemenu = gtk.Menu() filemenu.append(menu_item_file_about) filemenu.append(gtk.SeparatorMenuItem()) filemenu.append(menu_item_file_exit) langmenu = gtk.Menu() langmenu.append(menu_item_english) langmenu.append(menu_item_spanish) langmenu.append(menu_item_french) # create the root drop-down-able menu items, and assign their submenus to the lists above menu_item_file = gtk.MenuItem(_("File")) menu_item_file.set_submenu(filemenu) menu_item_lang = gtk.MenuItem("Language/Idioma/Langue") menu_item_lang.set_submenu(langmenu) # attach the root menus to the main menu bar mb.append(menu_item_file) mb.append(menu_item_lang) # and finally attach the main menu bar to the window vbox.pack_start(mb, False) # create the input file button and textbox section hbox1 = gtk.HBox(False, self.box_spacing) button1 = gtk.Button(_("Choose Input File..")) button1.connect("clicked", self.select_input_file, FileTypes.IDF) alignment = gtk.Alignment(xalign=1.0, yalign=0.5, xscale=1.0, yscale=0.5) alignment.add(button1) hbox1.pack_start(alignment, True, True, self.box_spacing) self.input_file_path = gtk.Entry() self.input_file_path.connect("changed", self.check_file_paths) self.input_file_path.set_text(self.settings['last_idf']) # "/tmp/RefBldgHospitalNew2004_Chicago.idf") self.input_file_path.set_size_request(width=500, height=-1) alignment = gtk.Alignment(xalign=1.0, yalign=0.5, xscale=1.0, yscale=0.5) alignment.add(self.input_file_path) hbox1.pack_start(alignment, True, True, self.box_spacing) self.edit_idf_button = gtk.Button(_("Edit Input File..")) self.edit_idf_button.connect("clicked", self.open_input_file) alignment = gtk.Alignment(xalign=1.0, yalign=0.5, xscale=1.0, yscale=0.5) alignment.add(self.edit_idf_button) hbox1.pack_start(alignment, True, True, self.box_spacing) vbox.pack_start(self.framed(hbox1), True, True, 0) # create the weather file button and textbox section hbox2 = gtk.HBox(False, self.box_spacing) button1 = gtk.Button(_("Choose Weather File..")) button1.connect("clicked", self.select_input_file, FileTypes.EPW) alignment = gtk.Alignment(xalign=1.0, yalign=0.5, xscale=1.0, yscale=0.5) alignment.add(button1) hbox2.pack_start(alignment, True, True, self.box_spacing) self.weather_file_path = gtk.Entry() self.weather_file_path.connect("changed", self.check_file_paths) self.weather_file_path.set_text( self.settings['last_epw']) # '"/Users/elee/EnergyPlus/repos/2eplus/weather/CZ06RV2.epw") self.weather_file_path.set_size_request(width=500, height=-1) alignment = gtk.Alignment(xalign=1.0, yalign=0.5, xscale=1.0, yscale=0.5) alignment.add(self.weather_file_path) hbox2.pack_start(alignment, True, True, self.box_spacing) vbox.pack_start(self.framed(hbox2), True, True, 0) # separator vbox.pack_start(self.framed(gtk.HSeparator()), False) # create the simulate/cancel button section hbox3 = gtk.HBox(False, self.box_spacing) self.button_sim = gtk.Button(_("Simulate")) self.button_sim.connect("clicked", self.run_simulation) alignment = gtk.Alignment(xalign=0.5, yalign=0.5, xscale=0.5, yscale=0.5) alignment.add(self.button_sim) hbox3.pack_start(alignment, True, True, self.box_spacing) self.button_cancel = gtk.Button(_("Cancel")) self.button_cancel.connect("clicked", self.cancel_simulation) alignment = gtk.Alignment(xalign=0.5, yalign=0.5, xscale=0.5, yscale=0.5) alignment.add(self.button_cancel) self.update_run_buttons(running=False) hbox3.pack_start(alignment, True, True, self.box_spacing) # self.button_language = gtk.Button(_("Switch language")) # self.button_language.connect("clicked", self.switch_language) # alignment = gtk.Alignment(xalign=0.5, yalign=0.5, xscale=0.5, yscale=0.5) # alignment.add(self.button_language) # hbox3.pack_start(alignment, True, True, self.box_spacing) vbox.pack_start(self.framed(hbox3), True, True, 0) # separator vbox.pack_start(self.framed(gtk.HSeparator()), False) # create the status bar hbox = gtk.HBox(False, self.box_spacing) self.ep_version_label = gtk.Label() self.ep_version_label.set_text(_("E+ Version")) aligner = gtk.Alignment(1, 0.5, 1, 1) aligner.add(self.ep_version_label) hbox.pack_start(self.framed(gtk.VSeparator()), False) hbox.pack_start(aligner, False, True, 0) self.status_bar = gtk.Statusbar() self.status_bar.set_has_resize_grip(False) self.status_bar_context_id = self.status_bar.get_context_id("Statusbar example") self.status_bar.push(self.status_bar_context_id, _("Ready for launch")) aligner = gtk.Alignment(1, 1, 1, 0) aligner.add(self.status_bar) hbox.pack_start(self.framed(gtk.VSeparator()), False) hbox.pack_start(aligner) vbox.pack_end(self.framed(hbox), False, True, 0) hbox.pack_start(self.framed(gtk.VSeparator()), False) # return the vbox return vbox
[ "def", "gui_build_body", "(", "self", ")", ":", "# create a vbox here first", "vbox", "=", "gtk", ".", "VBox", "(", "False", ",", "self", ".", "box_spacing", ")", "# create the menu bar itself to hold the menus", "mb", "=", "gtk", ".", "MenuBar", "(", ")", "# create the actual actionable items under the file menu", "menu_item_file_about", "=", "gtk", ".", "MenuItem", "(", "_", "(", "\"About...\"", ")", ")", "menu_item_file_about", ".", "connect", "(", "\"activate\"", ",", "self", ".", "about_dialog", ")", "menu_item_file_about", ".", "show", "(", ")", "menu_item_file_exit", "=", "gtk", ".", "MenuItem", "(", "_", "(", "\"Exit\"", ")", ")", "menu_item_file_exit", ".", "connect", "(", "\"activate\"", ",", "self", ".", "quit", ")", "menu_item_file_exit", ".", "show", "(", ")", "# create the actual actionable items under the language menu", "menu_item_english", "=", "gtk", ".", "MenuItem", "(", "\"Language: English\"", ")", "menu_item_english", ".", "connect", "(", "\"activate\"", ",", "self", ".", "switch_language", ",", "Languages", ".", "English", ")", "menu_item_english", ".", "show", "(", ")", "if", "self", ".", "settings", "[", "Keys", ".", "language", "]", "==", "Languages", ".", "English", ":", "menu_item_english", ".", "set_sensitive", "(", "False", ")", "menu_item_spanish", "=", "gtk", ".", "MenuItem", "(", "\"Idioma: Espanol\"", ")", "menu_item_spanish", ".", "connect", "(", "\"activate\"", ",", "self", ".", "switch_language", ",", "Languages", ".", "Spanish", ")", "menu_item_spanish", ".", "show", "(", ")", "if", "self", ".", "settings", "[", "Keys", ".", "language", "]", "==", "Languages", ".", "Spanish", ":", "menu_item_spanish", ".", "set_sensitive", "(", "False", ")", "menu_item_french", "=", "gtk", ".", "MenuItem", "(", "\"Langue: Francais\"", ")", "menu_item_french", ".", "connect", "(", "\"activate\"", ",", "self", ".", "switch_language", ",", "Languages", ".", "French", ")", "menu_item_french", ".", "show", "(", ")", "if", "self", ".", "settings", "[", "Keys", ".", "language", "]", "==", "Languages", ".", "French", ":", "menu_item_french", ".", "set_sensitive", "(", "False", ")", "# create the list of items that will eventually be dropped down, and append items in the right order", "filemenu", "=", "gtk", ".", "Menu", "(", ")", "filemenu", ".", "append", "(", "menu_item_file_about", ")", "filemenu", ".", "append", "(", "gtk", ".", "SeparatorMenuItem", "(", ")", ")", "filemenu", ".", "append", "(", "menu_item_file_exit", ")", "langmenu", "=", "gtk", ".", "Menu", "(", ")", "langmenu", ".", "append", "(", "menu_item_english", ")", "langmenu", ".", "append", "(", "menu_item_spanish", ")", "langmenu", ".", "append", "(", "menu_item_french", ")", "# create the root drop-down-able menu items, and assign their submenus to the lists above", "menu_item_file", "=", "gtk", ".", "MenuItem", "(", "_", "(", "\"File\"", ")", ")", "menu_item_file", ".", "set_submenu", "(", "filemenu", ")", "menu_item_lang", "=", "gtk", ".", "MenuItem", "(", "\"Language/Idioma/Langue\"", ")", "menu_item_lang", ".", "set_submenu", "(", "langmenu", ")", "# attach the root menus to the main menu bar", "mb", ".", "append", "(", "menu_item_file", ")", "mb", ".", "append", "(", "menu_item_lang", ")", "# and finally attach the main menu bar to the window", "vbox", ".", "pack_start", "(", "mb", ",", "False", ")", "# create the input file button and textbox section", "hbox1", "=", "gtk", ".", "HBox", "(", "False", ",", "self", ".", "box_spacing", ")", "button1", "=", "gtk", ".", "Button", "(", "_", "(", "\"Choose Input File..\"", ")", ")", "button1", ".", "connect", "(", "\"clicked\"", ",", "self", ".", "select_input_file", ",", "FileTypes", ".", "IDF", ")", "alignment", "=", "gtk", ".", "Alignment", "(", "xalign", "=", "1.0", ",", "yalign", "=", "0.5", ",", "xscale", "=", "1.0", ",", "yscale", "=", "0.5", ")", "alignment", ".", "add", "(", "button1", ")", "hbox1", ".", "pack_start", "(", "alignment", ",", "True", ",", "True", ",", "self", ".", "box_spacing", ")", "self", ".", "input_file_path", "=", "gtk", ".", "Entry", "(", ")", "self", ".", "input_file_path", ".", "connect", "(", "\"changed\"", ",", "self", ".", "check_file_paths", ")", "self", ".", "input_file_path", ".", "set_text", "(", "self", ".", "settings", "[", "'last_idf'", "]", ")", "# \"/tmp/RefBldgHospitalNew2004_Chicago.idf\")", "self", ".", "input_file_path", ".", "set_size_request", "(", "width", "=", "500", ",", "height", "=", "-", "1", ")", "alignment", "=", "gtk", ".", "Alignment", "(", "xalign", "=", "1.0", ",", "yalign", "=", "0.5", ",", "xscale", "=", "1.0", ",", "yscale", "=", "0.5", ")", "alignment", ".", "add", "(", "self", ".", "input_file_path", ")", "hbox1", ".", "pack_start", "(", "alignment", ",", "True", ",", "True", ",", "self", ".", "box_spacing", ")", "self", ".", "edit_idf_button", "=", "gtk", ".", "Button", "(", "_", "(", "\"Edit Input File..\"", ")", ")", "self", ".", "edit_idf_button", ".", "connect", "(", "\"clicked\"", ",", "self", ".", "open_input_file", ")", "alignment", "=", "gtk", ".", "Alignment", "(", "xalign", "=", "1.0", ",", "yalign", "=", "0.5", ",", "xscale", "=", "1.0", ",", "yscale", "=", "0.5", ")", "alignment", ".", "add", "(", "self", ".", "edit_idf_button", ")", "hbox1", ".", "pack_start", "(", "alignment", ",", "True", ",", "True", ",", "self", ".", "box_spacing", ")", "vbox", ".", "pack_start", "(", "self", ".", "framed", "(", "hbox1", ")", ",", "True", ",", "True", ",", "0", ")", "# create the weather file button and textbox section", "hbox2", "=", "gtk", ".", "HBox", "(", "False", ",", "self", ".", "box_spacing", ")", "button1", "=", "gtk", ".", "Button", "(", "_", "(", "\"Choose Weather File..\"", ")", ")", "button1", ".", "connect", "(", "\"clicked\"", ",", "self", ".", "select_input_file", ",", "FileTypes", ".", "EPW", ")", "alignment", "=", "gtk", ".", "Alignment", "(", "xalign", "=", "1.0", ",", "yalign", "=", "0.5", ",", "xscale", "=", "1.0", ",", "yscale", "=", "0.5", ")", "alignment", ".", "add", "(", "button1", ")", "hbox2", ".", "pack_start", "(", "alignment", ",", "True", ",", "True", ",", "self", ".", "box_spacing", ")", "self", ".", "weather_file_path", "=", "gtk", ".", "Entry", "(", ")", "self", ".", "weather_file_path", ".", "connect", "(", "\"changed\"", ",", "self", ".", "check_file_paths", ")", "self", ".", "weather_file_path", ".", "set_text", "(", "self", ".", "settings", "[", "'last_epw'", "]", ")", "# '\"/Users/elee/EnergyPlus/repos/2eplus/weather/CZ06RV2.epw\")", "self", ".", "weather_file_path", ".", "set_size_request", "(", "width", "=", "500", ",", "height", "=", "-", "1", ")", "alignment", "=", "gtk", ".", "Alignment", "(", "xalign", "=", "1.0", ",", "yalign", "=", "0.5", ",", "xscale", "=", "1.0", ",", "yscale", "=", "0.5", ")", "alignment", ".", "add", "(", "self", ".", "weather_file_path", ")", "hbox2", ".", "pack_start", "(", "alignment", ",", "True", ",", "True", ",", "self", ".", "box_spacing", ")", "vbox", ".", "pack_start", "(", "self", ".", "framed", "(", "hbox2", ")", ",", "True", ",", "True", ",", "0", ")", "# separator", "vbox", ".", "pack_start", "(", "self", ".", "framed", "(", "gtk", ".", "HSeparator", "(", ")", ")", ",", "False", ")", "# create the simulate/cancel button section", "hbox3", "=", "gtk", ".", "HBox", "(", "False", ",", "self", ".", "box_spacing", ")", "self", ".", "button_sim", "=", "gtk", ".", "Button", "(", "_", "(", "\"Simulate\"", ")", ")", "self", ".", "button_sim", ".", "connect", "(", "\"clicked\"", ",", "self", ".", "run_simulation", ")", "alignment", "=", "gtk", ".", "Alignment", "(", "xalign", "=", "0.5", ",", "yalign", "=", "0.5", ",", "xscale", "=", "0.5", ",", "yscale", "=", "0.5", ")", "alignment", ".", "add", "(", "self", ".", "button_sim", ")", "hbox3", ".", "pack_start", "(", "alignment", ",", "True", ",", "True", ",", "self", ".", "box_spacing", ")", "self", ".", "button_cancel", "=", "gtk", ".", "Button", "(", "_", "(", "\"Cancel\"", ")", ")", "self", ".", "button_cancel", ".", "connect", "(", "\"clicked\"", ",", "self", ".", "cancel_simulation", ")", "alignment", "=", "gtk", ".", "Alignment", "(", "xalign", "=", "0.5", ",", "yalign", "=", "0.5", ",", "xscale", "=", "0.5", ",", "yscale", "=", "0.5", ")", "alignment", ".", "add", "(", "self", ".", "button_cancel", ")", "self", ".", "update_run_buttons", "(", "running", "=", "False", ")", "hbox3", ".", "pack_start", "(", "alignment", ",", "True", ",", "True", ",", "self", ".", "box_spacing", ")", "# self.button_language = gtk.Button(_(\"Switch language\"))", "# self.button_language.connect(\"clicked\", self.switch_language)", "# alignment = gtk.Alignment(xalign=0.5, yalign=0.5, xscale=0.5, yscale=0.5)", "# alignment.add(self.button_language)", "# hbox3.pack_start(alignment, True, True, self.box_spacing)", "vbox", ".", "pack_start", "(", "self", ".", "framed", "(", "hbox3", ")", ",", "True", ",", "True", ",", "0", ")", "# separator", "vbox", ".", "pack_start", "(", "self", ".", "framed", "(", "gtk", ".", "HSeparator", "(", ")", ")", ",", "False", ")", "# create the status bar", "hbox", "=", "gtk", ".", "HBox", "(", "False", ",", "self", ".", "box_spacing", ")", "self", ".", "ep_version_label", "=", "gtk", ".", "Label", "(", ")", "self", ".", "ep_version_label", ".", "set_text", "(", "_", "(", "\"E+ Version\"", ")", ")", "aligner", "=", "gtk", ".", "Alignment", "(", "1", ",", "0.5", ",", "1", ",", "1", ")", "aligner", ".", "add", "(", "self", ".", "ep_version_label", ")", "hbox", ".", "pack_start", "(", "self", ".", "framed", "(", "gtk", ".", "VSeparator", "(", ")", ")", ",", "False", ")", "hbox", ".", "pack_start", "(", "aligner", ",", "False", ",", "True", ",", "0", ")", "self", ".", "status_bar", "=", "gtk", ".", "Statusbar", "(", ")", "self", ".", "status_bar", ".", "set_has_resize_grip", "(", "False", ")", "self", ".", "status_bar_context_id", "=", "self", ".", "status_bar", ".", "get_context_id", "(", "\"Statusbar example\"", ")", "self", ".", "status_bar", ".", "push", "(", "self", ".", "status_bar_context_id", ",", "_", "(", "\"Ready for launch\"", ")", ")", "aligner", "=", "gtk", ".", "Alignment", "(", "1", ",", "1", ",", "1", ",", "0", ")", "aligner", ".", "add", "(", "self", ".", "status_bar", ")", "hbox", ".", "pack_start", "(", "self", ".", "framed", "(", "gtk", ".", "VSeparator", "(", ")", ")", ",", "False", ")", "hbox", ".", "pack_start", "(", "aligner", ")", "vbox", ".", "pack_end", "(", "self", ".", "framed", "(", "hbox", ")", ",", "False", ",", "True", ",", "0", ")", "hbox", ".", "pack_start", "(", "self", ".", "framed", "(", "gtk", ".", "VSeparator", "(", ")", ")", ",", "False", ")", "# return the vbox", "return", "vbox" ]
https://github.com/NREL/EnergyPlus/blob/fadc5973b85c70e8cc923efb69c144e808a26078/third_party/EP-Launch-Lite/EPLaunchLite/EPLaunchLiteWindow.py#L106-L251
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
build/android/buildbot/bb_device_steps.py
python
UploadHTML
(options, gs_base_dir, dir_to_upload, link_text, link_rel_path='index.html', gs_url=GS_URL)
Uploads directory at |dir_to_upload| to Google Storage and output a link. Args: options: Command line options. gs_base_dir: The Google Storage base directory (e.g. 'chromium-code-coverage/java') dir_to_upload: Absolute path to the directory to be uploaded. link_text: Link text to be displayed on the step. link_rel_path: Link path relative to |dir_to_upload|. gs_url: Google storage URL.
Uploads directory at |dir_to_upload| to Google Storage and output a link.
[ "Uploads", "directory", "at", "|dir_to_upload|", "to", "Google", "Storage", "and", "output", "a", "link", "." ]
def UploadHTML(options, gs_base_dir, dir_to_upload, link_text, link_rel_path='index.html', gs_url=GS_URL): """Uploads directory at |dir_to_upload| to Google Storage and output a link. Args: options: Command line options. gs_base_dir: The Google Storage base directory (e.g. 'chromium-code-coverage/java') dir_to_upload: Absolute path to the directory to be uploaded. link_text: Link text to be displayed on the step. link_rel_path: Link path relative to |dir_to_upload|. gs_url: Google storage URL. """ revision = _GetRevision(options) bot_id = options.build_properties.get('buildername', 'testing') randhash = hashlib.sha1(str(random.random())).hexdigest() gs_path = '%s/%s/%s/%s' % (gs_base_dir, bot_id, revision, randhash) RunCmd([bb_utils.GSUTIL_PATH, 'cp', '-R', dir_to_upload, 'gs://%s' % gs_path]) bb_annotations.PrintLink(link_text, '%s/%s/%s' % (gs_url, gs_path, link_rel_path))
[ "def", "UploadHTML", "(", "options", ",", "gs_base_dir", ",", "dir_to_upload", ",", "link_text", ",", "link_rel_path", "=", "'index.html'", ",", "gs_url", "=", "GS_URL", ")", ":", "revision", "=", "_GetRevision", "(", "options", ")", "bot_id", "=", "options", ".", "build_properties", ".", "get", "(", "'buildername'", ",", "'testing'", ")", "randhash", "=", "hashlib", ".", "sha1", "(", "str", "(", "random", ".", "random", "(", ")", ")", ")", ".", "hexdigest", "(", ")", "gs_path", "=", "'%s/%s/%s/%s'", "%", "(", "gs_base_dir", ",", "bot_id", ",", "revision", ",", "randhash", ")", "RunCmd", "(", "[", "bb_utils", ".", "GSUTIL_PATH", ",", "'cp'", ",", "'-R'", ",", "dir_to_upload", ",", "'gs://%s'", "%", "gs_path", "]", ")", "bb_annotations", ".", "PrintLink", "(", "link_text", ",", "'%s/%s/%s'", "%", "(", "gs_url", ",", "gs_path", ",", "link_rel_path", ")", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/android/buildbot/bb_device_steps.py#L489-L508
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py2/google/protobuf/internal/decoder.py
python
MessageSetItemDecoder
(descriptor)
return DecodeItem
Returns a decoder for a MessageSet item. The parameter is the message Descriptor. The message set message looks like this: message MessageSet { repeated group Item = 1 { required int32 type_id = 2; required string message = 3; } }
Returns a decoder for a MessageSet item.
[ "Returns", "a", "decoder", "for", "a", "MessageSet", "item", "." ]
def MessageSetItemDecoder(descriptor): """Returns a decoder for a MessageSet item. The parameter is the message Descriptor. The message set message looks like this: message MessageSet { repeated group Item = 1 { required int32 type_id = 2; required string message = 3; } } """ type_id_tag_bytes = encoder.TagBytes(2, wire_format.WIRETYPE_VARINT) message_tag_bytes = encoder.TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED) item_end_tag_bytes = encoder.TagBytes(1, wire_format.WIRETYPE_END_GROUP) local_ReadTag = ReadTag local_DecodeVarint = _DecodeVarint local_SkipField = SkipField def DecodeItem(buffer, pos, end, message, field_dict): """Decode serialized message set to its value and new position. Args: buffer: memoryview of the serialized bytes. pos: int, position in the memory view to start at. end: int, end position of serialized data message: Message object to store unknown fields in field_dict: Map[Descriptor, Any] to store decoded values in. Returns: int, new position in serialized data. """ message_set_item_start = pos type_id = -1 message_start = -1 message_end = -1 # Technically, type_id and message can appear in any order, so we need # a little loop here. while 1: (tag_bytes, pos) = local_ReadTag(buffer, pos) if tag_bytes == type_id_tag_bytes: (type_id, pos) = local_DecodeVarint(buffer, pos) elif tag_bytes == message_tag_bytes: (size, message_start) = local_DecodeVarint(buffer, pos) pos = message_end = message_start + size elif tag_bytes == item_end_tag_bytes: break else: pos = SkipField(buffer, pos, end, tag_bytes) if pos == -1: raise _DecodeError('Missing group end tag.') if pos > end: raise _DecodeError('Truncated message.') if type_id == -1: raise _DecodeError('MessageSet item missing type_id.') if message_start == -1: raise _DecodeError('MessageSet item missing message.') extension = message.Extensions._FindExtensionByNumber(type_id) # pylint: disable=protected-access if extension is not None: value = field_dict.get(extension) if value is None: message_type = extension.message_type if not hasattr(message_type, '_concrete_class'): # pylint: disable=protected-access message._FACTORY.GetPrototype(message_type) value = field_dict.setdefault( extension, message_type._concrete_class()) if value._InternalParse(buffer, message_start,message_end) != message_end: # The only reason _InternalParse would return early is if it encountered # an end-group tag. raise _DecodeError('Unexpected end-group tag.') else: if not message._unknown_fields: message._unknown_fields = [] message._unknown_fields.append( (MESSAGE_SET_ITEM_TAG, buffer[message_set_item_start:pos].tobytes())) if message._unknown_field_set is None: message._unknown_field_set = containers.UnknownFieldSet() message._unknown_field_set._add( type_id, wire_format.WIRETYPE_LENGTH_DELIMITED, buffer[message_start:message_end].tobytes()) # pylint: enable=protected-access return pos return DecodeItem
[ "def", "MessageSetItemDecoder", "(", "descriptor", ")", ":", "type_id_tag_bytes", "=", "encoder", ".", "TagBytes", "(", "2", ",", "wire_format", ".", "WIRETYPE_VARINT", ")", "message_tag_bytes", "=", "encoder", ".", "TagBytes", "(", "3", ",", "wire_format", ".", "WIRETYPE_LENGTH_DELIMITED", ")", "item_end_tag_bytes", "=", "encoder", ".", "TagBytes", "(", "1", ",", "wire_format", ".", "WIRETYPE_END_GROUP", ")", "local_ReadTag", "=", "ReadTag", "local_DecodeVarint", "=", "_DecodeVarint", "local_SkipField", "=", "SkipField", "def", "DecodeItem", "(", "buffer", ",", "pos", ",", "end", ",", "message", ",", "field_dict", ")", ":", "\"\"\"Decode serialized message set to its value and new position.\n\n Args:\n buffer: memoryview of the serialized bytes.\n pos: int, position in the memory view to start at.\n end: int, end position of serialized data\n message: Message object to store unknown fields in\n field_dict: Map[Descriptor, Any] to store decoded values in.\n\n Returns:\n int, new position in serialized data.\n \"\"\"", "message_set_item_start", "=", "pos", "type_id", "=", "-", "1", "message_start", "=", "-", "1", "message_end", "=", "-", "1", "# Technically, type_id and message can appear in any order, so we need", "# a little loop here.", "while", "1", ":", "(", "tag_bytes", ",", "pos", ")", "=", "local_ReadTag", "(", "buffer", ",", "pos", ")", "if", "tag_bytes", "==", "type_id_tag_bytes", ":", "(", "type_id", ",", "pos", ")", "=", "local_DecodeVarint", "(", "buffer", ",", "pos", ")", "elif", "tag_bytes", "==", "message_tag_bytes", ":", "(", "size", ",", "message_start", ")", "=", "local_DecodeVarint", "(", "buffer", ",", "pos", ")", "pos", "=", "message_end", "=", "message_start", "+", "size", "elif", "tag_bytes", "==", "item_end_tag_bytes", ":", "break", "else", ":", "pos", "=", "SkipField", "(", "buffer", ",", "pos", ",", "end", ",", "tag_bytes", ")", "if", "pos", "==", "-", "1", ":", "raise", "_DecodeError", "(", "'Missing group end tag.'", ")", "if", "pos", ">", "end", ":", "raise", "_DecodeError", "(", "'Truncated message.'", ")", "if", "type_id", "==", "-", "1", ":", "raise", "_DecodeError", "(", "'MessageSet item missing type_id.'", ")", "if", "message_start", "==", "-", "1", ":", "raise", "_DecodeError", "(", "'MessageSet item missing message.'", ")", "extension", "=", "message", ".", "Extensions", ".", "_FindExtensionByNumber", "(", "type_id", ")", "# pylint: disable=protected-access", "if", "extension", "is", "not", "None", ":", "value", "=", "field_dict", ".", "get", "(", "extension", ")", "if", "value", "is", "None", ":", "message_type", "=", "extension", ".", "message_type", "if", "not", "hasattr", "(", "message_type", ",", "'_concrete_class'", ")", ":", "# pylint: disable=protected-access", "message", ".", "_FACTORY", ".", "GetPrototype", "(", "message_type", ")", "value", "=", "field_dict", ".", "setdefault", "(", "extension", ",", "message_type", ".", "_concrete_class", "(", ")", ")", "if", "value", ".", "_InternalParse", "(", "buffer", ",", "message_start", ",", "message_end", ")", "!=", "message_end", ":", "# The only reason _InternalParse would return early is if it encountered", "# an end-group tag.", "raise", "_DecodeError", "(", "'Unexpected end-group tag.'", ")", "else", ":", "if", "not", "message", ".", "_unknown_fields", ":", "message", ".", "_unknown_fields", "=", "[", "]", "message", ".", "_unknown_fields", ".", "append", "(", "(", "MESSAGE_SET_ITEM_TAG", ",", "buffer", "[", "message_set_item_start", ":", "pos", "]", ".", "tobytes", "(", ")", ")", ")", "if", "message", ".", "_unknown_field_set", "is", "None", ":", "message", ".", "_unknown_field_set", "=", "containers", ".", "UnknownFieldSet", "(", ")", "message", ".", "_unknown_field_set", ".", "_add", "(", "type_id", ",", "wire_format", ".", "WIRETYPE_LENGTH_DELIMITED", ",", "buffer", "[", "message_start", ":", "message_end", "]", ".", "tobytes", "(", ")", ")", "# pylint: enable=protected-access", "return", "pos", "return", "DecodeItem" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/internal/decoder.py#L766-L860
DeepGraphLearning/graphvite
e067c59146f676e3eee3eee6106dce7ccc7cf9e4
python/graphvite/application/application.py
python
GraphApplication.node_classification
(self, X=None, Y=None, file_name=None, portions=(0.02,), normalization=False, times=1, patience=100)
return metrics
Evaluate node embeddings on node classification task. Parameters: X (list of str, optional): names of nodes Y (list, optional): labels of nodes file_name (str, optional): file of nodes & labels portions (tuple of float, optional): how much data for training normalization (bool, optional): normalize the embeddings or not times (int, optional): number of trials patience (int, optional): patience on loss convergence Returns: dict: macro-F1 & micro-F1 averaged over all trials
Evaluate node embeddings on node classification task.
[ "Evaluate", "node", "embeddings", "on", "node", "classification", "task", "." ]
def node_classification(self, X=None, Y=None, file_name=None, portions=(0.02,), normalization=False, times=1, patience=100): """ Evaluate node embeddings on node classification task. Parameters: X (list of str, optional): names of nodes Y (list, optional): labels of nodes file_name (str, optional): file of nodes & labels portions (tuple of float, optional): how much data for training normalization (bool, optional): normalize the embeddings or not times (int, optional): number of trials patience (int, optional): patience on loss convergence Returns: dict: macro-F1 & micro-F1 averaged over all trials """ import scipy.sparse as sp self.solver.clear() if file_name: if not (X is None and Y is None): raise ValueError("Evaluation data and file should not be provided at the same time") X = [] Y = [] with open(file_name, "r") as fin: for line in fin: tokens = self.tokenize(line) if len(tokens) == 0: continue x, y = tokens X.append(x) Y.append(y) if X is None or Y is None: raise ValueError("Either evaluataion data (X, Y) or a file name should be provided") name2id = self.graph.name2id class2id = {c:i for i, c in enumerate(np.unique(Y))} new_X, new_Y = self.name_map((name2id, class2id), (X, Y)) logger.info("effective labels: %d / %d" % (len(new_X), len(X))) X = np.asarray(new_X) Y = np.asarray(new_Y) labels = sp.coo_matrix((np.ones_like(X), (X, Y)), dtype=np.int32).todense() indexes, _ = np.where(np.sum(labels, axis=1) > 0) # discard non-labeled nodes labels = labels[indexes] vertex_embeddings = SharedNDArray(self.solver.vertex_embeddings[indexes]) settings = [] for portion in portions: settings.append((vertex_embeddings, labels, portion, normalization, times, patience)) results = self.gpu_map(linear_classification, settings) metrics = {} for result in results: metrics.update(result) return metrics
[ "def", "node_classification", "(", "self", ",", "X", "=", "None", ",", "Y", "=", "None", ",", "file_name", "=", "None", ",", "portions", "=", "(", "0.02", ",", ")", ",", "normalization", "=", "False", ",", "times", "=", "1", ",", "patience", "=", "100", ")", ":", "import", "scipy", ".", "sparse", "as", "sp", "self", ".", "solver", ".", "clear", "(", ")", "if", "file_name", ":", "if", "not", "(", "X", "is", "None", "and", "Y", "is", "None", ")", ":", "raise", "ValueError", "(", "\"Evaluation data and file should not be provided at the same time\"", ")", "X", "=", "[", "]", "Y", "=", "[", "]", "with", "open", "(", "file_name", ",", "\"r\"", ")", "as", "fin", ":", "for", "line", "in", "fin", ":", "tokens", "=", "self", ".", "tokenize", "(", "line", ")", "if", "len", "(", "tokens", ")", "==", "0", ":", "continue", "x", ",", "y", "=", "tokens", "X", ".", "append", "(", "x", ")", "Y", ".", "append", "(", "y", ")", "if", "X", "is", "None", "or", "Y", "is", "None", ":", "raise", "ValueError", "(", "\"Either evaluataion data (X, Y) or a file name should be provided\"", ")", "name2id", "=", "self", ".", "graph", ".", "name2id", "class2id", "=", "{", "c", ":", "i", "for", "i", ",", "c", "in", "enumerate", "(", "np", ".", "unique", "(", "Y", ")", ")", "}", "new_X", ",", "new_Y", "=", "self", ".", "name_map", "(", "(", "name2id", ",", "class2id", ")", ",", "(", "X", ",", "Y", ")", ")", "logger", ".", "info", "(", "\"effective labels: %d / %d\"", "%", "(", "len", "(", "new_X", ")", ",", "len", "(", "X", ")", ")", ")", "X", "=", "np", ".", "asarray", "(", "new_X", ")", "Y", "=", "np", ".", "asarray", "(", "new_Y", ")", "labels", "=", "sp", ".", "coo_matrix", "(", "(", "np", ".", "ones_like", "(", "X", ")", ",", "(", "X", ",", "Y", ")", ")", ",", "dtype", "=", "np", ".", "int32", ")", ".", "todense", "(", ")", "indexes", ",", "_", "=", "np", ".", "where", "(", "np", ".", "sum", "(", "labels", ",", "axis", "=", "1", ")", ">", "0", ")", "# discard non-labeled nodes", "labels", "=", "labels", "[", "indexes", "]", "vertex_embeddings", "=", "SharedNDArray", "(", "self", ".", "solver", ".", "vertex_embeddings", "[", "indexes", "]", ")", "settings", "=", "[", "]", "for", "portion", "in", "portions", ":", "settings", ".", "append", "(", "(", "vertex_embeddings", ",", "labels", ",", "portion", ",", "normalization", ",", "times", ",", "patience", ")", ")", "results", "=", "self", ".", "gpu_map", "(", "linear_classification", ",", "settings", ")", "metrics", "=", "{", "}", "for", "result", "in", "results", ":", "metrics", ".", "update", "(", "result", ")", "return", "metrics" ]
https://github.com/DeepGraphLearning/graphvite/blob/e067c59146f676e3eee3eee6106dce7ccc7cf9e4/python/graphvite/application/application.py#L293-L351
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py
python
ExFileObject.readlines
(self)
return result
Return a list with all remaining lines.
Return a list with all remaining lines.
[ "Return", "a", "list", "with", "all", "remaining", "lines", "." ]
def readlines(self): """Return a list with all remaining lines. """ result = [] while True: line = self.readline() if not line: break result.append(line) return result
[ "def", "readlines", "(", "self", ")", ":", "result", "=", "[", "]", "while", "True", ":", "line", "=", "self", ".", "readline", "(", ")", "if", "not", "line", ":", "break", "result", ".", "append", "(", "line", ")", "return", "result" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L866-L874
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/train/summary/_summary_adapter.py
python
package_summary_event
(data_list, step, wall_time)
return summary_event
Package the summary to event protobuffer. Args: data_list (list): Summary data list. step (Number): The recode step index. wall_time (float): The wall time. Returns: Summary, the summary event.
Package the summary to event protobuffer.
[ "Package", "the", "summary", "to", "event", "protobuffer", "." ]
def package_summary_event(data_list, step, wall_time): """ Package the summary to event protobuffer. Args: data_list (list): Summary data list. step (Number): The recode step index. wall_time (float): The wall time. Returns: Summary, the summary event. """ # create the event of summary summary_event = Event() summary = summary_event.summary summary_event.wall_time = wall_time summary_event.step = int(step) for value in data_list: summary_type = value["_type"] data = value["data"] tag = value["name"] logger.debug(f"Now process {summary_type} summary, tag = {tag}") summary_value = summary.value.add() summary_value.tag = tag # get the summary type and parse the tag if summary_type == 'Scalar': if not _fill_scalar_summary(tag, data, summary_value): del summary.value[-1] elif summary_type == 'Tensor': _fill_tensor_summary(tag, data, summary_value.tensor) elif summary_type == 'Image': if not _fill_image_summary(tag, data, summary_value.image, MS_IMAGE_TENSOR_FORMAT): del summary.value[-1] elif summary_type == 'Histogram': _fill_histogram_summary(tag, data, summary_value.histogram) elif summary_type == 'Landscape': summary_value.loss_landscape.ParseFromString(data) else: # The data is invalid ,jump the data logger.error(f"Summary type({summary_type}) is error, tag = {tag}") del summary.value[-1] return summary_event
[ "def", "package_summary_event", "(", "data_list", ",", "step", ",", "wall_time", ")", ":", "# create the event of summary", "summary_event", "=", "Event", "(", ")", "summary", "=", "summary_event", ".", "summary", "summary_event", ".", "wall_time", "=", "wall_time", "summary_event", ".", "step", "=", "int", "(", "step", ")", "for", "value", "in", "data_list", ":", "summary_type", "=", "value", "[", "\"_type\"", "]", "data", "=", "value", "[", "\"data\"", "]", "tag", "=", "value", "[", "\"name\"", "]", "logger", ".", "debug", "(", "f\"Now process {summary_type} summary, tag = {tag}\"", ")", "summary_value", "=", "summary", ".", "value", ".", "add", "(", ")", "summary_value", ".", "tag", "=", "tag", "# get the summary type and parse the tag", "if", "summary_type", "==", "'Scalar'", ":", "if", "not", "_fill_scalar_summary", "(", "tag", ",", "data", ",", "summary_value", ")", ":", "del", "summary", ".", "value", "[", "-", "1", "]", "elif", "summary_type", "==", "'Tensor'", ":", "_fill_tensor_summary", "(", "tag", ",", "data", ",", "summary_value", ".", "tensor", ")", "elif", "summary_type", "==", "'Image'", ":", "if", "not", "_fill_image_summary", "(", "tag", ",", "data", ",", "summary_value", ".", "image", ",", "MS_IMAGE_TENSOR_FORMAT", ")", ":", "del", "summary", ".", "value", "[", "-", "1", "]", "elif", "summary_type", "==", "'Histogram'", ":", "_fill_histogram_summary", "(", "tag", ",", "data", ",", "summary_value", ".", "histogram", ")", "elif", "summary_type", "==", "'Landscape'", ":", "summary_value", ".", "loss_landscape", ".", "ParseFromString", "(", "data", ")", "else", ":", "# The data is invalid ,jump the data", "logger", ".", "error", "(", "f\"Summary type({summary_type}) is error, tag = {tag}\"", ")", "del", "summary", ".", "value", "[", "-", "1", "]", "return", "summary_event" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/train/summary/_summary_adapter.py#L106-L151
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/distutils/ccompiler.py
python
CCompiler._fix_compile_args
(self, output_dir, macros, include_dirs)
return output_dir, macros, include_dirs
Typecheck and fix-up some of the arguments to the 'compile()' method, and return fixed-up values. Specifically: if 'output_dir' is None, replaces it with 'self.output_dir'; ensures that 'macros' is a list, and augments it with 'self.macros'; ensures that 'include_dirs' is a list, and augments it with 'self.include_dirs'. Guarantees that the returned values are of the correct type, i.e. for 'output_dir' either string or None, and for 'macros' and 'include_dirs' either list or None.
Typecheck and fix-up some of the arguments to the 'compile()' method, and return fixed-up values. Specifically: if 'output_dir' is None, replaces it with 'self.output_dir'; ensures that 'macros' is a list, and augments it with 'self.macros'; ensures that 'include_dirs' is a list, and augments it with 'self.include_dirs'. Guarantees that the returned values are of the correct type, i.e. for 'output_dir' either string or None, and for 'macros' and 'include_dirs' either list or None.
[ "Typecheck", "and", "fix", "-", "up", "some", "of", "the", "arguments", "to", "the", "compile", "()", "method", "and", "return", "fixed", "-", "up", "values", ".", "Specifically", ":", "if", "output_dir", "is", "None", "replaces", "it", "with", "self", ".", "output_dir", ";", "ensures", "that", "macros", "is", "a", "list", "and", "augments", "it", "with", "self", ".", "macros", ";", "ensures", "that", "include_dirs", "is", "a", "list", "and", "augments", "it", "with", "self", ".", "include_dirs", ".", "Guarantees", "that", "the", "returned", "values", "are", "of", "the", "correct", "type", "i", ".", "e", ".", "for", "output_dir", "either", "string", "or", "None", "and", "for", "macros", "and", "include_dirs", "either", "list", "or", "None", "." ]
def _fix_compile_args(self, output_dir, macros, include_dirs): """Typecheck and fix-up some of the arguments to the 'compile()' method, and return fixed-up values. Specifically: if 'output_dir' is None, replaces it with 'self.output_dir'; ensures that 'macros' is a list, and augments it with 'self.macros'; ensures that 'include_dirs' is a list, and augments it with 'self.include_dirs'. Guarantees that the returned values are of the correct type, i.e. for 'output_dir' either string or None, and for 'macros' and 'include_dirs' either list or None. """ if output_dir is None: output_dir = self.output_dir elif not isinstance(output_dir, str): raise TypeError, "'output_dir' must be a string or None" if macros is None: macros = self.macros elif isinstance(macros, list): macros = macros + (self.macros or []) else: raise TypeError, "'macros' (if supplied) must be a list of tuples" if include_dirs is None: include_dirs = self.include_dirs elif isinstance(include_dirs, (list, tuple)): include_dirs = list (include_dirs) + (self.include_dirs or []) else: raise TypeError, \ "'include_dirs' (if supplied) must be a list of strings" return output_dir, macros, include_dirs
[ "def", "_fix_compile_args", "(", "self", ",", "output_dir", ",", "macros", ",", "include_dirs", ")", ":", "if", "output_dir", "is", "None", ":", "output_dir", "=", "self", ".", "output_dir", "elif", "not", "isinstance", "(", "output_dir", ",", "str", ")", ":", "raise", "TypeError", ",", "\"'output_dir' must be a string or None\"", "if", "macros", "is", "None", ":", "macros", "=", "self", ".", "macros", "elif", "isinstance", "(", "macros", ",", "list", ")", ":", "macros", "=", "macros", "+", "(", "self", ".", "macros", "or", "[", "]", ")", "else", ":", "raise", "TypeError", ",", "\"'macros' (if supplied) must be a list of tuples\"", "if", "include_dirs", "is", "None", ":", "include_dirs", "=", "self", ".", "include_dirs", "elif", "isinstance", "(", "include_dirs", ",", "(", "list", ",", "tuple", ")", ")", ":", "include_dirs", "=", "list", "(", "include_dirs", ")", "+", "(", "self", ".", "include_dirs", "or", "[", "]", ")", "else", ":", "raise", "TypeError", ",", "\"'include_dirs' (if supplied) must be a list of strings\"", "return", "output_dir", ",", "macros", ",", "include_dirs" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/distutils/ccompiler.py#L382-L412
etotheipi/BitcoinArmory
2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98
armoryengine/ArmoryUtils.py
python
hex_to_int
(h, endIn=LITTLEENDIAN)
return( int(hstr, 16) )
Convert hex-string to integer (or long). Default behavior is to interpret hex string as little-endian
Convert hex-string to integer (or long). Default behavior is to interpret hex string as little-endian
[ "Convert", "hex", "-", "string", "to", "integer", "(", "or", "long", ")", ".", "Default", "behavior", "is", "to", "interpret", "hex", "string", "as", "little", "-", "endian" ]
def hex_to_int(h, endIn=LITTLEENDIAN): """ Convert hex-string to integer (or long). Default behavior is to interpret hex string as little-endian """ hstr = h.replace(' ','') # copies data, no references if endIn==LITTLEENDIAN: hstr = hex_switchEndian(hstr) return( int(hstr, 16) )
[ "def", "hex_to_int", "(", "h", ",", "endIn", "=", "LITTLEENDIAN", ")", ":", "hstr", "=", "h", ".", "replace", "(", "' '", ",", "''", ")", "# copies data, no references", "if", "endIn", "==", "LITTLEENDIAN", ":", "hstr", "=", "hex_switchEndian", "(", "hstr", ")", "return", "(", "int", "(", "hstr", ",", "16", ")", ")" ]
https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/armoryengine/ArmoryUtils.py#L1918-L1926
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/rnn/python/ops/core_rnn_cell.py
python
InputProjectionWrapper.call
(self, inputs, state)
return self._cell(projected, state)
Run the input projection and then the cell.
Run the input projection and then the cell.
[ "Run", "the", "input", "projection", "and", "then", "the", "cell", "." ]
def call(self, inputs, state): """Run the input projection and then the cell.""" # Default scope: "InputProjectionWrapper" projected = _linear(inputs, self._num_proj, True) if self._activation: projected = self._activation(projected) return self._cell(projected, state)
[ "def", "call", "(", "self", ",", "inputs", ",", "state", ")", ":", "# Default scope: \"InputProjectionWrapper\"", "projected", "=", "_linear", "(", "inputs", ",", "self", ".", "_num_proj", ",", "True", ")", "if", "self", ".", "_activation", ":", "projected", "=", "self", ".", "_activation", "(", "projected", ")", "return", "self", ".", "_cell", "(", "projected", ",", "state", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/rnn/python/ops/core_rnn_cell.py#L170-L176
OAID/Caffe-HRT
aae71e498ab842c6f92bcc23fc668423615a4d65
scripts/cpp_lint.py
python
CheckForNonConstReference
(filename, clean_lines, linenum, nesting_state, error)
Check for non-const references. Separate from CheckLanguage since it scans backwards from current line, instead of scanning forward. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found.
Check for non-const references.
[ "Check", "for", "non", "-", "const", "references", "." ]
def CheckForNonConstReference(filename, clean_lines, linenum, nesting_state, error): """Check for non-const references. Separate from CheckLanguage since it scans backwards from current line, instead of scanning forward. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Do nothing if there is no '&' on current line. line = clean_lines.elided[linenum] if '&' not in line: return # Long type names may be broken across multiple lines, usually in one # of these forms: # LongType # ::LongTypeContinued &identifier # LongType:: # LongTypeContinued &identifier # LongType< # ...>::LongTypeContinued &identifier # # If we detected a type split across two lines, join the previous # line to current line so that we can match const references # accordingly. # # Note that this only scans back one line, since scanning back # arbitrary number of lines would be expensive. If you have a type # that spans more than 2 lines, please use a typedef. if linenum > 1: previous = None if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line): # previous_line\n + ::current_line previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$', clean_lines.elided[linenum - 1]) elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line): # previous_line::\n + current_line previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$', clean_lines.elided[linenum - 1]) if previous: line = previous.group(1) + line.lstrip() else: # Check for templated parameter that is split across multiple lines endpos = line.rfind('>') if endpos > -1: (_, startline, startpos) = ReverseCloseExpression( clean_lines, linenum, endpos) if startpos > -1 and startline < linenum: # Found the matching < on an earlier line, collect all # pieces up to current line. line = '' for i in xrange(startline, linenum + 1): line += clean_lines.elided[i].strip() # Check for non-const references in function parameters. A single '&' may # found in the following places: # inside expression: binary & for bitwise AND # inside expression: unary & for taking the address of something # inside declarators: reference parameter # We will exclude the first two cases by checking that we are not inside a # function body, including one that was just introduced by a trailing '{'. # TODO(unknwon): Doesn't account for preprocessor directives. # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare]. check_params = False if not nesting_state.stack: check_params = True # top level elif (isinstance(nesting_state.stack[-1], _ClassInfo) or isinstance(nesting_state.stack[-1], _NamespaceInfo)): check_params = True # within class or namespace elif Match(r'.*{\s*$', line): if (len(nesting_state.stack) == 1 or isinstance(nesting_state.stack[-2], _ClassInfo) or isinstance(nesting_state.stack[-2], _NamespaceInfo)): check_params = True # just opened global/class/namespace block # We allow non-const references in a few standard places, like functions # called "swap()" or iostream operators like "<<" or ">>". Do not check # those function parameters. # # We also accept & in static_assert, which looks like a function but # it's actually a declaration expression. whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|' r'operator\s*[<>][<>]|' r'static_assert|COMPILE_ASSERT' r')\s*\(') if Search(whitelisted_functions, line): check_params = False elif not Search(r'\S+\([^)]*$', line): # Don't see a whitelisted function on this line. Actually we # didn't see any function name on this line, so this is likely a # multi-line parameter list. Try a bit harder to catch this case. for i in xrange(2): if (linenum > i and Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])): check_params = False break if check_params: decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls): if not Match(_RE_PATTERN_CONST_REF_PARAM, parameter): error(filename, linenum, 'runtime/references', 2, 'Is this a non-const reference? ' 'If so, make const or use a pointer: ' + ReplaceAll(' *<', '<', parameter))
[ "def", "CheckForNonConstReference", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "# Do nothing if there is no '&' on current line.", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "'&'", "not", "in", "line", ":", "return", "# Long type names may be broken across multiple lines, usually in one", "# of these forms:", "# LongType", "# ::LongTypeContinued &identifier", "# LongType::", "# LongTypeContinued &identifier", "# LongType<", "# ...>::LongTypeContinued &identifier", "#", "# If we detected a type split across two lines, join the previous", "# line to current line so that we can match const references", "# accordingly.", "#", "# Note that this only scans back one line, since scanning back", "# arbitrary number of lines would be expensive. If you have a type", "# that spans more than 2 lines, please use a typedef.", "if", "linenum", ">", "1", ":", "previous", "=", "None", "if", "Match", "(", "r'\\s*::(?:[\\w<>]|::)+\\s*&\\s*\\S'", ",", "line", ")", ":", "# previous_line\\n + ::current_line", "previous", "=", "Search", "(", "r'\\b((?:const\\s*)?(?:[\\w<>]|::)+[\\w<>])\\s*$'", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "1", "]", ")", "elif", "Match", "(", "r'\\s*[a-zA-Z_]([\\w<>]|::)+\\s*&\\s*\\S'", ",", "line", ")", ":", "# previous_line::\\n + current_line", "previous", "=", "Search", "(", "r'\\b((?:const\\s*)?(?:[\\w<>]|::)+::)\\s*$'", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "1", "]", ")", "if", "previous", ":", "line", "=", "previous", ".", "group", "(", "1", ")", "+", "line", ".", "lstrip", "(", ")", "else", ":", "# Check for templated parameter that is split across multiple lines", "endpos", "=", "line", ".", "rfind", "(", "'>'", ")", "if", "endpos", ">", "-", "1", ":", "(", "_", ",", "startline", ",", "startpos", ")", "=", "ReverseCloseExpression", "(", "clean_lines", ",", "linenum", ",", "endpos", ")", "if", "startpos", ">", "-", "1", "and", "startline", "<", "linenum", ":", "# Found the matching < on an earlier line, collect all", "# pieces up to current line.", "line", "=", "''", "for", "i", "in", "xrange", "(", "startline", ",", "linenum", "+", "1", ")", ":", "line", "+=", "clean_lines", ".", "elided", "[", "i", "]", ".", "strip", "(", ")", "# Check for non-const references in function parameters. A single '&' may", "# found in the following places:", "# inside expression: binary & for bitwise AND", "# inside expression: unary & for taking the address of something", "# inside declarators: reference parameter", "# We will exclude the first two cases by checking that we are not inside a", "# function body, including one that was just introduced by a trailing '{'.", "# TODO(unknwon): Doesn't account for preprocessor directives.", "# TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].", "check_params", "=", "False", "if", "not", "nesting_state", ".", "stack", ":", "check_params", "=", "True", "# top level", "elif", "(", "isinstance", "(", "nesting_state", ".", "stack", "[", "-", "1", "]", ",", "_ClassInfo", ")", "or", "isinstance", "(", "nesting_state", ".", "stack", "[", "-", "1", "]", ",", "_NamespaceInfo", ")", ")", ":", "check_params", "=", "True", "# within class or namespace", "elif", "Match", "(", "r'.*{\\s*$'", ",", "line", ")", ":", "if", "(", "len", "(", "nesting_state", ".", "stack", ")", "==", "1", "or", "isinstance", "(", "nesting_state", ".", "stack", "[", "-", "2", "]", ",", "_ClassInfo", ")", "or", "isinstance", "(", "nesting_state", ".", "stack", "[", "-", "2", "]", ",", "_NamespaceInfo", ")", ")", ":", "check_params", "=", "True", "# just opened global/class/namespace block", "# We allow non-const references in a few standard places, like functions", "# called \"swap()\" or iostream operators like \"<<\" or \">>\". Do not check", "# those function parameters.", "#", "# We also accept & in static_assert, which looks like a function but", "# it's actually a declaration expression.", "whitelisted_functions", "=", "(", "r'(?:[sS]wap(?:<\\w:+>)?|'", "r'operator\\s*[<>][<>]|'", "r'static_assert|COMPILE_ASSERT'", "r')\\s*\\('", ")", "if", "Search", "(", "whitelisted_functions", ",", "line", ")", ":", "check_params", "=", "False", "elif", "not", "Search", "(", "r'\\S+\\([^)]*$'", ",", "line", ")", ":", "# Don't see a whitelisted function on this line. Actually we", "# didn't see any function name on this line, so this is likely a", "# multi-line parameter list. Try a bit harder to catch this case.", "for", "i", "in", "xrange", "(", "2", ")", ":", "if", "(", "linenum", ">", "i", "and", "Search", "(", "whitelisted_functions", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "i", "-", "1", "]", ")", ")", ":", "check_params", "=", "False", "break", "if", "check_params", ":", "decls", "=", "ReplaceAll", "(", "r'{[^}]*}'", ",", "' '", ",", "line", ")", "# exclude function body", "for", "parameter", "in", "re", ".", "findall", "(", "_RE_PATTERN_REF_PARAM", ",", "decls", ")", ":", "if", "not", "Match", "(", "_RE_PATTERN_CONST_REF_PARAM", ",", "parameter", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/references'", ",", "2", ",", "'Is this a non-const reference? '", "'If so, make const or use a pointer: '", "+", "ReplaceAll", "(", "' *<'", ",", "'<'", ",", "parameter", ")", ")" ]
https://github.com/OAID/Caffe-HRT/blob/aae71e498ab842c6f92bcc23fc668423615a4d65/scripts/cpp_lint.py#L4134-L4244
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/externals.py
python
set_fnclex
(context, c_helpers)
return library
Install fnclex before fmod calls. Workaround for https://support.microsoft.com/en-us/kb/982107
Install fnclex before fmod calls. Workaround for https://support.microsoft.com/en-us/kb/982107
[ "Install", "fnclex", "before", "fmod", "calls", ".", "Workaround", "for", "https", ":", "//", "support", ".", "microsoft", ".", "com", "/", "en", "-", "us", "/", "kb", "/", "982107" ]
def set_fnclex(context, c_helpers): """ Install fnclex before fmod calls. Workaround for https://support.microsoft.com/en-us/kb/982107 """ ptr_set_fnclex = c_helpers['set_fnclex'] fn = ctypes.CFUNCTYPE(None, ctypes.c_void_p)(ptr_set_fnclex) library = compile_fnclex(context) fnclex_ptr = library.get_pointer_to_function('fnclex') fn(fnclex_ptr) return library
[ "def", "set_fnclex", "(", "context", ",", "c_helpers", ")", ":", "ptr_set_fnclex", "=", "c_helpers", "[", "'set_fnclex'", "]", "fn", "=", "ctypes", ".", "CFUNCTYPE", "(", "None", ",", "ctypes", ".", "c_void_p", ")", "(", "ptr_set_fnclex", ")", "library", "=", "compile_fnclex", "(", "context", ")", "fnclex_ptr", "=", "library", ".", "get_pointer_to_function", "(", "'fnclex'", ")", "fn", "(", "fnclex_ptr", ")", "return", "library" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/externals.py#L169-L181
GJDuck/LowFat
ecf6a0f0fa1b73a27a626cf493cc39e477b6faea
llvm-4.0.0.src/tools/clang/tools/scan-build-py/libscanbuild/report.py
python
report_directory
(hint, keep)
Responsible for the report directory. hint -- could specify the parent directory of the output directory. keep -- a boolean value to keep or delete the empty report directory.
Responsible for the report directory.
[ "Responsible", "for", "the", "report", "directory", "." ]
def report_directory(hint, keep): """ Responsible for the report directory. hint -- could specify the parent directory of the output directory. keep -- a boolean value to keep or delete the empty report directory. """ stamp_format = 'scan-build-%Y-%m-%d-%H-%M-%S-%f-' stamp = datetime.datetime.now().strftime(stamp_format) parentdir = os.path.abspath(hint) if not os.path.exists(parentdir): os.makedirs(parentdir) name = tempfile.mkdtemp(prefix=stamp, dir=parentdir) logging.info('Report directory created: %s', name) try: yield name finally: if os.listdir(name): msg = "Run 'scan-view %s' to examine bug reports." keep = True else: if keep: msg = "Report directory '%s' contans no report, but kept." else: msg = "Removing directory '%s' because it contains no report." logging.warning(msg, name) if not keep: os.rmdir(name)
[ "def", "report_directory", "(", "hint", ",", "keep", ")", ":", "stamp_format", "=", "'scan-build-%Y-%m-%d-%H-%M-%S-%f-'", "stamp", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "stamp_format", ")", "parentdir", "=", "os", ".", "path", ".", "abspath", "(", "hint", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "parentdir", ")", ":", "os", ".", "makedirs", "(", "parentdir", ")", "name", "=", "tempfile", ".", "mkdtemp", "(", "prefix", "=", "stamp", ",", "dir", "=", "parentdir", ")", "logging", ".", "info", "(", "'Report directory created: %s'", ",", "name", ")", "try", ":", "yield", "name", "finally", ":", "if", "os", ".", "listdir", "(", "name", ")", ":", "msg", "=", "\"Run 'scan-view %s' to examine bug reports.\"", "keep", "=", "True", "else", ":", "if", "keep", ":", "msg", "=", "\"Report directory '%s' contans no report, but kept.\"", "else", ":", "msg", "=", "\"Removing directory '%s' because it contains no report.\"", "logging", ".", "warning", "(", "msg", ",", "name", ")", "if", "not", "keep", ":", "os", ".", "rmdir", "(", "name", ")" ]
https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/tools/clang/tools/scan-build-py/libscanbuild/report.py#L32-L63
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/stc.py
python
StyledTextCtrl.GetSearchFlags
(*args, **kwargs)
return _stc.StyledTextCtrl_GetSearchFlags(*args, **kwargs)
GetSearchFlags(self) -> int Get the search flags used by SearchInTarget.
GetSearchFlags(self) -> int
[ "GetSearchFlags", "(", "self", ")", "-", ">", "int" ]
def GetSearchFlags(*args, **kwargs): """ GetSearchFlags(self) -> int Get the search flags used by SearchInTarget. """ return _stc.StyledTextCtrl_GetSearchFlags(*args, **kwargs)
[ "def", "GetSearchFlags", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_GetSearchFlags", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L3788-L3794
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
MenuItem.SetOwnerDrawn
(*args, **kwargs)
return _core_.MenuItem_SetOwnerDrawn(*args, **kwargs)
SetOwnerDrawn(self, bool ownerDrawn=True)
SetOwnerDrawn(self, bool ownerDrawn=True)
[ "SetOwnerDrawn", "(", "self", "bool", "ownerDrawn", "=", "True", ")" ]
def SetOwnerDrawn(*args, **kwargs): """SetOwnerDrawn(self, bool ownerDrawn=True)""" return _core_.MenuItem_SetOwnerDrawn(*args, **kwargs)
[ "def", "SetOwnerDrawn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "MenuItem_SetOwnerDrawn", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L12606-L12608
apiaryio/snowcrash
b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3
tools/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings._TargetConfig
(self, config)
return config
Returns the target-specific configuration.
Returns the target-specific configuration.
[ "Returns", "the", "target", "-", "specific", "configuration", "." ]
def _TargetConfig(self, config): """Returns the target-specific configuration.""" # There's two levels of architecture/platform specification in VS. The # first level is globally for the configuration (this is what we consider # "the" config at the gyp level, which will be something like 'Debug' or # 'Release_x64'), and a second target-specific configuration, which is an # override for the global one. |config| is remapped here to take into # account the local target-specific overrides to the global configuration. arch = self.GetArch(config) if arch == 'x64' and not config.endswith('_x64'): config += '_x64' if arch == 'x86' and config.endswith('_x64'): config = config.rsplit('_', 1)[0] return config
[ "def", "_TargetConfig", "(", "self", ",", "config", ")", ":", "# There's two levels of architecture/platform specification in VS. The", "# first level is globally for the configuration (this is what we consider", "# \"the\" config at the gyp level, which will be something like 'Debug' or", "# 'Release_x64'), and a second target-specific configuration, which is an", "# override for the global one. |config| is remapped here to take into", "# account the local target-specific overrides to the global configuration.", "arch", "=", "self", ".", "GetArch", "(", "config", ")", "if", "arch", "==", "'x64'", "and", "not", "config", ".", "endswith", "(", "'_x64'", ")", ":", "config", "+=", "'_x64'", "if", "arch", "==", "'x86'", "and", "config", ".", "endswith", "(", "'_x64'", ")", ":", "config", "=", "config", ".", "rsplit", "(", "'_'", ",", "1", ")", "[", "0", "]", "return", "config" ]
https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/msvs_emulation.py#L304-L317
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ultimatelistctrl.py
python
UltimateListMainWindow.SetGradientStyle
(self, vertical=0)
Sets the gradient style for gradient-style selections. :param `vertical`: 0 for horizontal gradient-style selections, 1 for vertical gradient-style selections.
Sets the gradient style for gradient-style selections.
[ "Sets", "the", "gradient", "style", "for", "gradient", "-", "style", "selections", "." ]
def SetGradientStyle(self, vertical=0): """ Sets the gradient style for gradient-style selections. :param `vertical`: 0 for horizontal gradient-style selections, 1 for vertical gradient-style selections. """ # 0 = Horizontal, 1 = Vertical self._gradientstyle = vertical if self._usegradients: self.RefreshSelected()
[ "def", "SetGradientStyle", "(", "self", ",", "vertical", "=", "0", ")", ":", "# 0 = Horizontal, 1 = Vertical", "self", ".", "_gradientstyle", "=", "vertical", "if", "self", ".", "_usegradients", ":", "self", ".", "RefreshSelected", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L10659-L10671
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Path/PathScripts/PathToolLibraryEditor.py
python
EditorPanel.loadTable
(self, name)
loads the tools for the selected tool table
loads the tools for the selected tool table
[ "loads", "the", "tools", "for", "the", "selected", "tool", "table" ]
def loadTable(self, name): """loads the tools for the selected tool table""" tooldata = self.TLM.getTools(name) if tooldata: self.form.ToolsList.setModel(tooldata) self.form.ToolsList.resizeColumnsToContents() self.form.ToolsList.horizontalHeader().setResizeMode( self.form.ToolsList.model().columnCount() - 1, QtGui.QHeaderView.Stretch ) self.setCurrentToolTableByName(name)
[ "def", "loadTable", "(", "self", ",", "name", ")", ":", "tooldata", "=", "self", ".", "TLM", ".", "getTools", "(", "name", ")", "if", "tooldata", ":", "self", ".", "form", ".", "ToolsList", ".", "setModel", "(", "tooldata", ")", "self", ".", "form", ".", "ToolsList", ".", "resizeColumnsToContents", "(", ")", "self", ".", "form", ".", "ToolsList", ".", "horizontalHeader", "(", ")", ".", "setResizeMode", "(", "self", ".", "form", ".", "ToolsList", ".", "model", "(", ")", ".", "columnCount", "(", ")", "-", "1", ",", "QtGui", ".", "QHeaderView", ".", "Stretch", ")", "self", ".", "setCurrentToolTableByName", "(", "name", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathToolLibraryEditor.py#L319-L328
microsoft/ELL
a1d6bacc37a14879cc025d9be2ba40b1a0632315
tools/importers/CNTK/lib/cntk_layers.py
python
MaxPoolingLayer.clone_cntk_layer
(self, feature)
return MaxPooling(filterShape, strides=(stride, stride), pad=pad)(feature)
Returns a clone of the CNTK layer for per-layer forward prop validation
Returns a clone of the CNTK layer for per-layer forward prop validation
[ "Returns", "a", "clone", "of", "the", "CNTK", "layer", "for", "per", "-", "layer", "forward", "prop", "validation" ]
def clone_cntk_layer(self, feature): """Returns a clone of the CNTK layer for per-layer forward prop validation""" pad, filterShape, stride = self.get_cntk_parameters() return MaxPooling(filterShape, strides=(stride, stride), pad=pad)(feature)
[ "def", "clone_cntk_layer", "(", "self", ",", "feature", ")", ":", "pad", ",", "filterShape", ",", "stride", "=", "self", ".", "get_cntk_parameters", "(", ")", "return", "MaxPooling", "(", "filterShape", ",", "strides", "=", "(", "stride", ",", "stride", ")", ",", "pad", "=", "pad", ")", "(", "feature", ")" ]
https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/importers/CNTK/lib/cntk_layers.py#L608-L612
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/model/robotinfo.py
python
RobotInfo.klamptModel
(self)
return self.robotModel
Returns the Klamp't RobotModel associated with this robot, either by the ``robotModel`` object or loading from the given filename ``self.modelFile``. The results are cached so this can be called many times without a performance hit.
Returns the Klamp't RobotModel associated with this robot, either by the ``robotModel`` object or loading from the given filename ``self.modelFile``.
[ "Returns", "the", "Klamp", "t", "RobotModel", "associated", "with", "this", "robot", "either", "by", "the", "robotModel", "object", "or", "loading", "from", "the", "given", "filename", "self", ".", "modelFile", "." ]
def klamptModel(self) -> RobotModel: """Returns the Klamp't RobotModel associated with this robot, either by the ``robotModel`` object or loading from the given filename ``self.modelFile``. The results are cached so this can be called many times without a performance hit. """ if self.robotModel is not None: return self.robotModel if self.modelFile is None: raise RuntimeError("Can't load robot model for {}, no file given".format(self.name)) self._worldTemp = WorldModel() def doload(fn): self.robotModel = self._worldTemp.loadRobot(fn) return self.robotModel.index >= 0 if not self._tryload(self.modelFile,doload): raise IOError("Unable to load robot from file {}".format(self.modelFile)) self.robotModel.setName(self.name) #apply calibration for (k,file) in self.calibrationFiles.items(): if k == 'kinematics': def docalib(fn): try: with open(fn,'r') as f: jsonobj = json.load(f) except IOError: return False for k,items in jsonobj.items(): link = self.robotModel.link(k) if link.index < 0: raise ValueError("Calibration file refers to invalid link {}".format(k)) for key,value in items.items(): if key == 'axis': link.setAxis(value) elif key == 'Tparent': link.setParentTransform(value) else: raise KeyError("Invalid calibration item {}".format(key)) return True if not self._tryload(file,docalib): raise IOError("Unable to load kinematics calibration from file "+file) else: s = self.robotModel.sensor(k) if s.getName(): self.configureSensor(s) else: warnings.warn("Calibration item {} doesn't refer to a sensor or kinematics".format(k)) return self.robotModel
[ "def", "klamptModel", "(", "self", ")", "->", "RobotModel", ":", "if", "self", ".", "robotModel", "is", "not", "None", ":", "return", "self", ".", "robotModel", "if", "self", ".", "modelFile", "is", "None", ":", "raise", "RuntimeError", "(", "\"Can't load robot model for {}, no file given\"", ".", "format", "(", "self", ".", "name", ")", ")", "self", ".", "_worldTemp", "=", "WorldModel", "(", ")", "def", "doload", "(", "fn", ")", ":", "self", ".", "robotModel", "=", "self", ".", "_worldTemp", ".", "loadRobot", "(", "fn", ")", "return", "self", ".", "robotModel", ".", "index", ">=", "0", "if", "not", "self", ".", "_tryload", "(", "self", ".", "modelFile", ",", "doload", ")", ":", "raise", "IOError", "(", "\"Unable to load robot from file {}\"", ".", "format", "(", "self", ".", "modelFile", ")", ")", "self", ".", "robotModel", ".", "setName", "(", "self", ".", "name", ")", "#apply calibration", "for", "(", "k", ",", "file", ")", "in", "self", ".", "calibrationFiles", ".", "items", "(", ")", ":", "if", "k", "==", "'kinematics'", ":", "def", "docalib", "(", "fn", ")", ":", "try", ":", "with", "open", "(", "fn", ",", "'r'", ")", "as", "f", ":", "jsonobj", "=", "json", ".", "load", "(", "f", ")", "except", "IOError", ":", "return", "False", "for", "k", ",", "items", "in", "jsonobj", ".", "items", "(", ")", ":", "link", "=", "self", ".", "robotModel", ".", "link", "(", "k", ")", "if", "link", ".", "index", "<", "0", ":", "raise", "ValueError", "(", "\"Calibration file refers to invalid link {}\"", ".", "format", "(", "k", ")", ")", "for", "key", ",", "value", "in", "items", ".", "items", "(", ")", ":", "if", "key", "==", "'axis'", ":", "link", ".", "setAxis", "(", "value", ")", "elif", "key", "==", "'Tparent'", ":", "link", ".", "setParentTransform", "(", "value", ")", "else", ":", "raise", "KeyError", "(", "\"Invalid calibration item {}\"", ".", "format", "(", "key", ")", ")", "return", "True", "if", "not", "self", ".", "_tryload", "(", "file", ",", "docalib", ")", ":", "raise", "IOError", "(", "\"Unable to load kinematics calibration from file \"", "+", "file", ")", "else", ":", "s", "=", "self", ".", "robotModel", ".", "sensor", "(", "k", ")", "if", "s", ".", "getName", "(", ")", ":", "self", ".", "configureSensor", "(", "s", ")", "else", ":", "warnings", ".", "warn", "(", "\"Calibration item {} doesn't refer to a sensor or kinematics\"", ".", "format", "(", "k", ")", ")", "return", "self", ".", "robotModel" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/model/robotinfo.py#L170-L218
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2class.py
python
xpathParserContext.xpathErr
(self, error)
Handle an XPath error
Handle an XPath error
[ "Handle", "an", "XPath", "error" ]
def xpathErr(self, error): """Handle an XPath error """ libxml2mod.xmlXPathErr(self._o, error)
[ "def", "xpathErr", "(", "self", ",", "error", ")", ":", "libxml2mod", ".", "xmlXPathErr", "(", "self", ".", "_o", ",", "error", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L6715-L6717
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
Button_GetClassDefaultAttributes
(*args, **kwargs)
return _controls_.Button_GetClassDefaultAttributes(*args, **kwargs)
Button_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this.
Button_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
[ "Button_GetClassDefaultAttributes", "(", "int", "variant", "=", "WINDOW_VARIANT_NORMAL", ")", "-", ">", "VisualAttributes" ]
def Button_GetClassDefaultAttributes(*args, **kwargs): """ Button_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.Button_GetClassDefaultAttributes(*args, **kwargs)
[ "def", "Button_GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "Button_GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L269-L284
Atarity/Lightpack
4dee73a443cba4c4073291febe450e6c1941f3af
Software/apiexamples/liOSC/OSC.py
python
OSCMultiClient.hasOSCTarget
(self, address, prefix=None)
return False
Return True if the given OSCTarget exists in the Client's dict. the 'address' argument can be a ((host, port) tuple), or a hostname. If the 'prefix' argument is given, the return-value is only True if the address and prefix match.
Return True if the given OSCTarget exists in the Client's dict. the 'address' argument can be a ((host, port) tuple), or a hostname. If the 'prefix' argument is given, the return-value is only True if the address and prefix match.
[ "Return", "True", "if", "the", "given", "OSCTarget", "exists", "in", "the", "Client", "s", "dict", ".", "the", "address", "argument", "can", "be", "a", "((", "host", "port", ")", "tuple", ")", "or", "a", "hostname", ".", "If", "the", "prefix", "argument", "is", "given", "the", "return", "-", "value", "is", "only", "True", "if", "the", "address", "and", "prefix", "match", "." ]
def hasOSCTarget(self, address, prefix=None): """Return True if the given OSCTarget exists in the Client's dict. the 'address' argument can be a ((host, port) tuple), or a hostname. If the 'prefix' argument is given, the return-value is only True if the address and prefix match. """ if type(address) in types.StringTypes: address = self._searchHostAddr(address) if type(address) == types.TupleType: (host, port) = address[:2] try: host = socket.gethostbyname(host) except socket.error: pass address = (host, port) if address in self.targets.keys(): if prefix == None: return True elif prefix == self.targets[address][0]: return True return False
[ "def", "hasOSCTarget", "(", "self", ",", "address", ",", "prefix", "=", "None", ")", ":", "if", "type", "(", "address", ")", "in", "types", ".", "StringTypes", ":", "address", "=", "self", ".", "_searchHostAddr", "(", "address", ")", "if", "type", "(", "address", ")", "==", "types", ".", "TupleType", ":", "(", "host", ",", "port", ")", "=", "address", "[", ":", "2", "]", "try", ":", "host", "=", "socket", ".", "gethostbyname", "(", "host", ")", "except", "socket", ".", "error", ":", "pass", "address", "=", "(", "host", ",", "port", ")", "if", "address", "in", "self", ".", "targets", ".", "keys", "(", ")", ":", "if", "prefix", "==", "None", ":", "return", "True", "elif", "prefix", "==", "self", ".", "targets", "[", "address", "]", "[", "0", "]", ":", "return", "True", "return", "False" ]
https://github.com/Atarity/Lightpack/blob/4dee73a443cba4c4073291febe450e6c1941f3af/Software/apiexamples/liOSC/OSC.py#L1373-L1395
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
3rdParty/SCons/scons-3.0.1/engine/SCons/Node/FS.py
python
File.retrieve_from_cache
(self)
return self.get_build_env().get_CacheDir().retrieve(self)
Try to retrieve the node's content from a cache This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in built(). Returns true if the node was successfully retrieved.
Try to retrieve the node's content from a cache
[ "Try", "to", "retrieve", "the", "node", "s", "content", "from", "a", "cache" ]
def retrieve_from_cache(self): """Try to retrieve the node's content from a cache This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in built(). Returns true if the node was successfully retrieved. """ if self.nocache: return None if not self.is_derived(): return None return self.get_build_env().get_CacheDir().retrieve(self)
[ "def", "retrieve_from_cache", "(", "self", ")", ":", "if", "self", ".", "nocache", ":", "return", "None", "if", "not", "self", ".", "is_derived", "(", ")", ":", "return", "None", "return", "self", ".", "get_build_env", "(", ")", ".", "get_CacheDir", "(", ")", ".", "retrieve", "(", "self", ")" ]
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Node/FS.py#L2912-L2925
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ast.py
python
copy_location
(new_node, old_node)
return new_node
Copy source location (`lineno` and `col_offset` attributes) from *old_node* to *new_node* if possible, and return *new_node*.
Copy source location (`lineno` and `col_offset` attributes) from *old_node* to *new_node* if possible, and return *new_node*.
[ "Copy", "source", "location", "(", "lineno", "and", "col_offset", "attributes", ")", "from", "*", "old_node", "*", "to", "*", "new_node", "*", "if", "possible", "and", "return", "*", "new_node", "*", "." ]
def copy_location(new_node, old_node): """ Copy source location (`lineno` and `col_offset` attributes) from *old_node* to *new_node* if possible, and return *new_node*. """ for attr in 'lineno', 'col_offset': if attr in old_node._attributes and attr in new_node._attributes \ and hasattr(old_node, attr): setattr(new_node, attr, getattr(old_node, attr)) return new_node
[ "def", "copy_location", "(", "new_node", ",", "old_node", ")", ":", "for", "attr", "in", "'lineno'", ",", "'col_offset'", ":", "if", "attr", "in", "old_node", ".", "_attributes", "and", "attr", "in", "new_node", ".", "_attributes", "and", "hasattr", "(", "old_node", ",", "attr", ")", ":", "setattr", "(", "new_node", ",", "attr", ",", "getattr", "(", "old_node", ",", "attr", ")", ")", "return", "new_node" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ast.py#L133-L142
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/autograph/impl/conversion.py
python
is_unsupported
(o)
return False
Checks whether an entity is supported by AutoGraph at all.
Checks whether an entity is supported by AutoGraph at all.
[ "Checks", "whether", "an", "entity", "is", "supported", "by", "AutoGraph", "at", "all", "." ]
def is_unsupported(o): """Checks whether an entity is supported by AutoGraph at all.""" # TODO(b/122265385): Remove this bypass. if (_is_known_loaded_type(o, 'wrapt', 'FunctionWrapper') or _is_known_loaded_type(o, 'wrapt', 'BoundFunctionWrapper')): logging.warning( '{} appears to be decorated by wrapt, which is not yet supported' ' by AutoGraph. The function will run as-is.' ' You may still apply AutoGraph before the wrapt decorator.'.format(o)) logging.log(2, 'Permanently allowed: %s: wrapt decorated', o) return True if _is_known_loaded_type(o, 'functools', '_lru_cache_wrapper'): logging.log(2, 'Permanently allowed: %s: lru_cache', o) return True # Constructors are permanently allowed. # TODO(mdan): Toggle as experimental feature instead. # TODO(b/124016764): Remove this limitation. if inspect_utils.isconstructor(o): logging.log(2, 'Permanently allowed: %s: constructor', o) return True # Other built-in modules are permanently allowed. # TODO(mdan): Figure out how to do this consistently for all stdlib modules. if any( _is_of_known_loaded_module(o, m) for m in ('collections', 'pdb', 'copy', 'inspect', 're')): logging.log(2, 'Permanently allowed: %s: part of builtin module', o) return True # Custom ops and kernels are also permanently allowed. # See tensorflow.framework.load_library. if (hasattr(o, '__module__') and hasattr(o.__module__, '_IS_TENSORFLOW_PLUGIN')): logging.log(2, 'Permanently allowed: %s: TensorFlow plugin', o) return True return False
[ "def", "is_unsupported", "(", "o", ")", ":", "# TODO(b/122265385): Remove this bypass.", "if", "(", "_is_known_loaded_type", "(", "o", ",", "'wrapt'", ",", "'FunctionWrapper'", ")", "or", "_is_known_loaded_type", "(", "o", ",", "'wrapt'", ",", "'BoundFunctionWrapper'", ")", ")", ":", "logging", ".", "warning", "(", "'{} appears to be decorated by wrapt, which is not yet supported'", "' by AutoGraph. The function will run as-is.'", "' You may still apply AutoGraph before the wrapt decorator.'", ".", "format", "(", "o", ")", ")", "logging", ".", "log", "(", "2", ",", "'Permanently allowed: %s: wrapt decorated'", ",", "o", ")", "return", "True", "if", "_is_known_loaded_type", "(", "o", ",", "'functools'", ",", "'_lru_cache_wrapper'", ")", ":", "logging", ".", "log", "(", "2", ",", "'Permanently allowed: %s: lru_cache'", ",", "o", ")", "return", "True", "# Constructors are permanently allowed.", "# TODO(mdan): Toggle as experimental feature instead.", "# TODO(b/124016764): Remove this limitation.", "if", "inspect_utils", ".", "isconstructor", "(", "o", ")", ":", "logging", ".", "log", "(", "2", ",", "'Permanently allowed: %s: constructor'", ",", "o", ")", "return", "True", "# Other built-in modules are permanently allowed.", "# TODO(mdan): Figure out how to do this consistently for all stdlib modules.", "if", "any", "(", "_is_of_known_loaded_module", "(", "o", ",", "m", ")", "for", "m", "in", "(", "'collections'", ",", "'pdb'", ",", "'copy'", ",", "'inspect'", ",", "'re'", ")", ")", ":", "logging", ".", "log", "(", "2", ",", "'Permanently allowed: %s: part of builtin module'", ",", "o", ")", "return", "True", "# Custom ops and kernels are also permanently allowed.", "# See tensorflow.framework.load_library.", "if", "(", "hasattr", "(", "o", ",", "'__module__'", ")", "and", "hasattr", "(", "o", ".", "__module__", ",", "'_IS_TENSORFLOW_PLUGIN'", ")", ")", ":", "logging", ".", "log", "(", "2", ",", "'Permanently allowed: %s: TensorFlow plugin'", ",", "o", ")", "return", "True", "return", "False" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/autograph/impl/conversion.py#L69-L108
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
ListCtrl.GetItem
(*args, **kwargs)
return val
GetItem(self, long itemId, int col=0) -> ListItem
GetItem(self, long itemId, int col=0) -> ListItem
[ "GetItem", "(", "self", "long", "itemId", "int", "col", "=", "0", ")", "-", ">", "ListItem" ]
def GetItem(*args, **kwargs): """GetItem(self, long itemId, int col=0) -> ListItem""" val = _controls_.ListCtrl_GetItem(*args, **kwargs) if val is not None: val.thisown = 1 return val
[ "def", "GetItem", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "val", "=", "_controls_", ".", "ListCtrl_GetItem", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "val", "is", "not", "None", ":", "val", ".", "thisown", "=", "1", "return", "val" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L4509-L4513
TimoSaemann/caffe-segnet-cudnn5
abcf30dca449245e101bf4ced519f716177f0885
scripts/cpp_lint.py
python
CheckForMultilineCommentsAndStrings
(filename, clean_lines, linenum, error)
Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Logs an error if we see /* ... */ or "..." that extend past one line.
[ "Logs", "an", "error", "if", "we", "see", "/", "*", "...", "*", "/", "or", "...", "that", "extend", "past", "one", "line", "." ]
def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error): """Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Remove all \\ (escaped backslashes) from the line. They are OK, and the # second (escaped) slash may trigger later \" detection erroneously. line = line.replace('\\\\', '') if line.count('/*') > line.count('*/'): error(filename, linenum, 'readability/multiline_comment', 5, 'Complex multi-line /*...*/-style comment found. ' 'Lint may give bogus warnings. ' 'Consider replacing these with //-style comments, ' 'with #if 0...#endif, ' 'or with more clearly structured multi-line comments.') if (line.count('"') - line.count('\\"')) % 2: error(filename, linenum, 'readability/multiline_string', 5, 'Multi-line string ("...") found. This lint script doesn\'t ' 'do well with such strings, and may give bogus warnings. ' 'Use C++11 raw strings or concatenation instead.')
[ "def", "CheckForMultilineCommentsAndStrings", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Remove all \\\\ (escaped backslashes) from the line. They are OK, and the", "# second (escaped) slash may trigger later \\\" detection erroneously.", "line", "=", "line", ".", "replace", "(", "'\\\\\\\\'", ",", "''", ")", "if", "line", ".", "count", "(", "'/*'", ")", ">", "line", ".", "count", "(", "'*/'", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/multiline_comment'", ",", "5", ",", "'Complex multi-line /*...*/-style comment found. '", "'Lint may give bogus warnings. '", "'Consider replacing these with //-style comments, '", "'with #if 0...#endif, '", "'or with more clearly structured multi-line comments.'", ")", "if", "(", "line", ".", "count", "(", "'\"'", ")", "-", "line", ".", "count", "(", "'\\\\\"'", ")", ")", "%", "2", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/multiline_string'", ",", "5", ",", "'Multi-line string (\"...\") found. This lint script doesn\\'t '", "'do well with such strings, and may give bogus warnings. '", "'Use C++11 raw strings or concatenation instead.'", ")" ]
https://github.com/TimoSaemann/caffe-segnet-cudnn5/blob/abcf30dca449245e101bf4ced519f716177f0885/scripts/cpp_lint.py#L1526-L1561
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
buildscripts/cpplint.py
python
_SetFilters
(filters)
Sets the module's error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die.
Sets the module's error-message filters.
[ "Sets", "the", "module", "s", "error", "-", "message", "filters", "." ]
def _SetFilters(filters): """Sets the module's error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die. """ _cpplint_state.SetFilters(filters)
[ "def", "_SetFilters", "(", "filters", ")", ":", "_cpplint_state", ".", "SetFilters", "(", "filters", ")" ]
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/buildscripts/cpplint.py#L876-L886
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/tree.py
python
TreeItem.__init__
(self)
Constructor. Do whatever you need to do.
Constructor. Do whatever you need to do.
[ "Constructor", ".", "Do", "whatever", "you", "need", "to", "do", "." ]
def __init__(self): """Constructor. Do whatever you need to do."""
[ "def", "__init__", "(", "self", ")", ":" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/tree.py#L342-L343
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/network/lazy_wheel.py
python
LazyZipOverHTTP.writable
(self)
return False
Return False.
Return False.
[ "Return", "False", "." ]
def writable(self): # type: () -> bool """Return False.""" return False
[ "def", "writable", "(", "self", ")", ":", "# type: () -> bool", "return", "False" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/network/lazy_wheel.py#L146-L149
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/math/symbolic.py
python
is_scalar
(v,value=None)
Returns True if v evaluates to a scalar. If value is provided, then returns True only if v evaluates to be equal to value
Returns True if v evaluates to a scalar. If value is provided, then returns True only if v evaluates to be equal to value
[ "Returns", "True", "if", "v", "evaluates", "to", "a", "scalar", ".", "If", "value", "is", "provided", "then", "returns", "True", "only", "if", "v", "evaluates", "to", "be", "equal", "to", "value" ]
def is_scalar(v,value=None): """Returns True if v evaluates to a scalar. If value is provided, then returns True only if v evaluates to be equal to value""" if isinstance(v,Variable): if not v.type.is_scalar(): return False return value is None or v.value == value elif isinstance(v,ConstantExpression): return is_scalar(v.value,value) elif isinstance(v,Expression): rt = v.returnType() if rt is None: return False if not rt.is_scalar(): return False return value is None else: if not (isinstance(v,(bool,)+_PY_NUMERIC_TYPES) or (hasattr(v,'shape') and v.shape == ())): return False return value is None or v == value
[ "def", "is_scalar", "(", "v", ",", "value", "=", "None", ")", ":", "if", "isinstance", "(", "v", ",", "Variable", ")", ":", "if", "not", "v", ".", "type", ".", "is_scalar", "(", ")", ":", "return", "False", "return", "value", "is", "None", "or", "v", ".", "value", "==", "value", "elif", "isinstance", "(", "v", ",", "ConstantExpression", ")", ":", "return", "is_scalar", "(", "v", ".", "value", ",", "value", ")", "elif", "isinstance", "(", "v", ",", "Expression", ")", ":", "rt", "=", "v", ".", "returnType", "(", ")", "if", "rt", "is", "None", ":", "return", "False", "if", "not", "rt", ".", "is_scalar", "(", ")", ":", "return", "False", "return", "value", "is", "None", "else", ":", "if", "not", "(", "isinstance", "(", "v", ",", "(", "bool", ",", ")", "+", "_PY_NUMERIC_TYPES", ")", "or", "(", "hasattr", "(", "v", ",", "'shape'", ")", "and", "v", ".", "shape", "==", "(", ")", ")", ")", ":", "return", "False", "return", "value", "is", "None", "or", "v", "==", "value" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/math/symbolic.py#L4463-L4478
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/site_compare/command_line.py
python
Command.AddArgument
(self, names, helptext, type="string", metaname=None, required=False, default=None, positional=False)
return arg
Command-line argument to a command. Args: names: argument name, or list of synonyms helptext: brief description of the argument type: type of the argument metaname: Name to display for value in help, inferred if not required: True if argument must be specified default: Default value if not specified positional: Argument specified by location, not name Raises: ValueError: the argument already exists or is invalid Returns: The newly-created argument
Command-line argument to a command.
[ "Command", "-", "line", "argument", "to", "a", "command", "." ]
def AddArgument(self, names, helptext, type="string", metaname=None, required=False, default=None, positional=False): """Command-line argument to a command. Args: names: argument name, or list of synonyms helptext: brief description of the argument type: type of the argument metaname: Name to display for value in help, inferred if not required: True if argument must be specified default: Default value if not specified positional: Argument specified by location, not name Raises: ValueError: the argument already exists or is invalid Returns: The newly-created argument """ if IsString(names): names = [names] names = [name.lower() for name in names] for name in names: if name in self.arg_dict: raise ValueError("%s is already an argument"%name) if (positional and required and [arg for arg in self.args if arg.positional] and not [arg for arg in self.args if arg.positional][-1].required): raise ValueError( "A required positional argument may not follow an optional one.") arg = Command.Argument(names, helptext, type, metaname, required, default, positional) self.args.append(arg) for name in names: self.arg_dict[name] = arg return arg
[ "def", "AddArgument", "(", "self", ",", "names", ",", "helptext", ",", "type", "=", "\"string\"", ",", "metaname", "=", "None", ",", "required", "=", "False", ",", "default", "=", "None", ",", "positional", "=", "False", ")", ":", "if", "IsString", "(", "names", ")", ":", "names", "=", "[", "names", "]", "names", "=", "[", "name", ".", "lower", "(", ")", "for", "name", "in", "names", "]", "for", "name", "in", "names", ":", "if", "name", "in", "self", ".", "arg_dict", ":", "raise", "ValueError", "(", "\"%s is already an argument\"", "%", "name", ")", "if", "(", "positional", "and", "required", "and", "[", "arg", "for", "arg", "in", "self", ".", "args", "if", "arg", ".", "positional", "]", "and", "not", "[", "arg", "for", "arg", "in", "self", ".", "args", "if", "arg", ".", "positional", "]", "[", "-", "1", "]", ".", "required", ")", ":", "raise", "ValueError", "(", "\"A required positional argument may not follow an optional one.\"", ")", "arg", "=", "Command", ".", "Argument", "(", "names", ",", "helptext", ",", "type", ",", "metaname", ",", "required", ",", "default", ",", "positional", ")", "self", ".", "args", ".", "append", "(", "arg", ")", "for", "name", "in", "names", ":", "self", ".", "arg_dict", "[", "name", "]", "=", "arg", "return", "arg" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/site_compare/command_line.py#L180-L221
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftobjects/draftlink.py
python
DraftLink.canLinkProperties
(self, _obj)
return False
Link properties. TODO: add more explanation. Overrides a C++ method?
Link properties.
[ "Link", "properties", "." ]
def canLinkProperties(self, _obj): """Link properties. TODO: add more explanation. Overrides a C++ method? """ return False
[ "def", "canLinkProperties", "(", "self", ",", "_obj", ")", ":", "return", "False" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftobjects/draftlink.py#L85-L90
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/_vendor/ordered_set.py
python
OrderedSet.__reversed__
(self)
return reversed(self.items)
Example: >>> list(reversed(OrderedSet([1, 2, 3]))) [3, 2, 1]
Example: >>> list(reversed(OrderedSet([1, 2, 3]))) [3, 2, 1]
[ "Example", ":", ">>>", "list", "(", "reversed", "(", "OrderedSet", "(", "[", "1", "2", "3", "]", ")))", "[", "3", "2", "1", "]" ]
def __reversed__(self): """ Example: >>> list(reversed(OrderedSet([1, 2, 3]))) [3, 2, 1] """ return reversed(self.items)
[ "def", "__reversed__", "(", "self", ")", ":", "return", "reversed", "(", "self", ".", "items", ")" ]
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/_vendor/ordered_set.py#L267-L273
javafxports/openjdk-jfx
6eabc8c84f698c04548395826a8bb738087666b5
modules/javafx.web/src/main/native/Source/JavaScriptCore/disassembler/udis86/ud_opcode.py
python
UdOpcodeTables.walk
(self, tbl, opcodes)
return e
Walk down the opcode trie, starting at a given opcode table, given a string of opcodes. Return None if unable to walk, the object at the leaf otherwise.
Walk down the opcode trie, starting at a given opcode table, given a string of opcodes. Return None if unable to walk, the object at the leaf otherwise.
[ "Walk", "down", "the", "opcode", "trie", "starting", "at", "a", "given", "opcode", "table", "given", "a", "string", "of", "opcodes", ".", "Return", "None", "if", "unable", "to", "walk", "the", "object", "at", "the", "leaf", "otherwise", "." ]
def walk(self, tbl, opcodes): """Walk down the opcode trie, starting at a given opcode table, given a string of opcodes. Return None if unable to walk, the object at the leaf otherwise. """ opc = opcodes[0] e = tbl.lookup(opc) if e is None: return None elif isinstance(e, UdOpcodeTable) and len(opcodes[1:]): return self.walk(e, opcodes[1:]) return e
[ "def", "walk", "(", "self", ",", "tbl", ",", "opcodes", ")", ":", "opc", "=", "opcodes", "[", "0", "]", "e", "=", "tbl", ".", "lookup", "(", "opc", ")", "if", "e", "is", "None", ":", "return", "None", "elif", "isinstance", "(", "e", ",", "UdOpcodeTable", ")", "and", "len", "(", "opcodes", "[", "1", ":", "]", ")", ":", "return", "self", ".", "walk", "(", "e", ",", "opcodes", "[", "1", ":", "]", ")", "return", "e" ]
https://github.com/javafxports/openjdk-jfx/blob/6eabc8c84f698c04548395826a8bb738087666b5/modules/javafx.web/src/main/native/Source/JavaScriptCore/disassembler/udis86/ud_opcode.py#L279-L290
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/stc.py
python
StyledTextCtrl.AutoCompComplete
(*args, **kwargs)
return _stc.StyledTextCtrl_AutoCompComplete(*args, **kwargs)
AutoCompComplete(self) User has selected an item so remove the list and insert the selection.
AutoCompComplete(self)
[ "AutoCompComplete", "(", "self", ")" ]
def AutoCompComplete(*args, **kwargs): """ AutoCompComplete(self) User has selected an item so remove the list and insert the selection. """ return _stc.StyledTextCtrl_AutoCompComplete(*args, **kwargs)
[ "def", "AutoCompComplete", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_AutoCompComplete", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L3062-L3068
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/pathlib.py
python
Path.touch
(self, mode=0o666, exist_ok=True)
Create this file with the given access mode, if it doesn't exist.
Create this file with the given access mode, if it doesn't exist.
[ "Create", "this", "file", "with", "the", "given", "access", "mode", "if", "it", "doesn", "t", "exist", "." ]
def touch(self, mode=0o666, exist_ok=True): """ Create this file with the given access mode, if it doesn't exist. """ if self._closed: self._raise_closed() if exist_ok: # First try to bump modification time # Implementation note: GNU touch uses the UTIME_NOW option of # the utimensat() / futimens() functions. try: self._accessor.utime(self, None) except OSError: # Avoid exception chaining pass else: return flags = os.O_CREAT | os.O_WRONLY if not exist_ok: flags |= os.O_EXCL fd = self._raw_open(flags, mode) os.close(fd)
[ "def", "touch", "(", "self", ",", "mode", "=", "0o666", ",", "exist_ok", "=", "True", ")", ":", "if", "self", ".", "_closed", ":", "self", ".", "_raise_closed", "(", ")", "if", "exist_ok", ":", "# First try to bump modification time", "# Implementation note: GNU touch uses the UTIME_NOW option of", "# the utimensat() / futimens() functions.", "try", ":", "self", ".", "_accessor", ".", "utime", "(", "self", ",", "None", ")", "except", "OSError", ":", "# Avoid exception chaining", "pass", "else", ":", "return", "flags", "=", "os", ".", "O_CREAT", "|", "os", ".", "O_WRONLY", "if", "not", "exist_ok", ":", "flags", "|=", "os", ".", "O_EXCL", "fd", "=", "self", ".", "_raw_open", "(", "flags", ",", "mode", ")", "os", ".", "close", "(", "fd", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/pathlib.py#L1243-L1264
QMCPACK/qmcpack
d0948ab455e38364458740cc8e2239600a14c5cd
utils/afqmctools/afqmctools/utils/qe_driver.py
python
gen_qe_gto
(qe_info,bset,x=[], fname='pyscf.orbitals.h5',prec=1e-12)
return nao
Writes periodic AO basis set in real space to hdf5 file. This routine constructs a new gaussian basis set from a OptimizableBasisSet object and an array of optimizable parameters. With the resulting basis set, a new gto.Cell object is constructed consistent with the QE calculation and used to generate the periodic AO basis set. Parameters ---------- qe_info: Python Dictionary. Dictionary with information from QE calculation, generated by qe_driver_init. bset: Object of type OptimizableBasisSet. Contains information about a (possibly dynamic) basis set. x: fp array. Default: [] (no variable parameters in bset) Array with variational parameters in the bset object. fname: string. Default: 'pyscf.orbitals.h5' Name of hdf5 file. prec: floating point number. Default: 1e-12 Precision used to generate AO orbitals in real space. Controls sum over periodic images. Returns ------- nao: integer Number of atomic orbitals generates.
Writes periodic AO basis set in real space to hdf5 file. This routine constructs a new gaussian basis set from a OptimizableBasisSet object and an array of optimizable parameters. With the resulting basis set, a new gto.Cell object is constructed consistent with the QE calculation and used to generate the periodic AO basis set.
[ "Writes", "periodic", "AO", "basis", "set", "in", "real", "space", "to", "hdf5", "file", ".", "This", "routine", "constructs", "a", "new", "gaussian", "basis", "set", "from", "a", "OptimizableBasisSet", "object", "and", "an", "array", "of", "optimizable", "parameters", ".", "With", "the", "resulting", "basis", "set", "a", "new", "gto", ".", "Cell", "object", "is", "constructed", "consistent", "with", "the", "QE", "calculation", "and", "used", "to", "generate", "the", "periodic", "AO", "basis", "set", "." ]
def gen_qe_gto(qe_info,bset,x=[], fname='pyscf.orbitals.h5',prec=1e-12): """ Writes periodic AO basis set in real space to hdf5 file. This routine constructs a new gaussian basis set from a OptimizableBasisSet object and an array of optimizable parameters. With the resulting basis set, a new gto.Cell object is constructed consistent with the QE calculation and used to generate the periodic AO basis set. Parameters ---------- qe_info: Python Dictionary. Dictionary with information from QE calculation, generated by qe_driver_init. bset: Object of type OptimizableBasisSet. Contains information about a (possibly dynamic) basis set. x: fp array. Default: [] (no variable parameters in bset) Array with variational parameters in the bset object. fname: string. Default: 'pyscf.orbitals.h5' Name of hdf5 file. prec: floating point number. Default: 1e-12 Precision used to generate AO orbitals in real space. Controls sum over periodic images. Returns ------- nao: integer Number of atomic orbitals generates. """ assert(len(x) == bset.number_of_params) basis = {} for I, atm in enumerate(qe_info['species']): basis.update({atm: molgto.parse( bset.basis_str(atm,x) )}) cell = make_cell(qe_info['latt'], qe_info['species'], qe_info['at_id'], qe_info['at_pos'], basis_=basis, mesh=qe_info['mesh'],prec=prec) nao = cell.nao_nr() write_esh5_orbitals(cell, qe_info['outdir']+fname, kpts=qe_info['kpts']) return nao
[ "def", "gen_qe_gto", "(", "qe_info", ",", "bset", ",", "x", "=", "[", "]", ",", "fname", "=", "'pyscf.orbitals.h5'", ",", "prec", "=", "1e-12", ")", ":", "assert", "(", "len", "(", "x", ")", "==", "bset", ".", "number_of_params", ")", "basis", "=", "{", "}", "for", "I", ",", "atm", "in", "enumerate", "(", "qe_info", "[", "'species'", "]", ")", ":", "basis", ".", "update", "(", "{", "atm", ":", "molgto", ".", "parse", "(", "bset", ".", "basis_str", "(", "atm", ",", "x", ")", ")", "}", ")", "cell", "=", "make_cell", "(", "qe_info", "[", "'latt'", "]", ",", "qe_info", "[", "'species'", "]", ",", "qe_info", "[", "'at_id'", "]", ",", "qe_info", "[", "'at_pos'", "]", ",", "basis_", "=", "basis", ",", "mesh", "=", "qe_info", "[", "'mesh'", "]", ",", "prec", "=", "prec", ")", "nao", "=", "cell", ".", "nao_nr", "(", ")", "write_esh5_orbitals", "(", "cell", ",", "qe_info", "[", "'outdir'", "]", "+", "fname", ",", "kpts", "=", "qe_info", "[", "'kpts'", "]", ")", "return", "nao" ]
https://github.com/QMCPACK/qmcpack/blob/d0948ab455e38364458740cc8e2239600a14c5cd/utils/afqmctools/afqmctools/utils/qe_driver.py#L270-L309
facebookincubator/katran
192eb988c398afc673620254097defb7035d669e
build/fbcode_builder/getdeps/copytree.py
python
copytree
(src_dir, dest_dir, ignore=None)
return shutil.copytree(src_dir, dest_dir, ignore=ignore)
Recursively copy the src_dir to the dest_dir, filtering out entries using the ignore lambda. The behavior of the ignore lambda must match that described by `shutil.copytree`. This `copytree` function knows how to prefetch data when running in an eden repo. TODO: I'd like to either extend this or add a variant that uses watchman to mirror src_dir into dest_dir.
Recursively copy the src_dir to the dest_dir, filtering out entries using the ignore lambda. The behavior of the ignore lambda must match that described by `shutil.copytree`. This `copytree` function knows how to prefetch data when running in an eden repo. TODO: I'd like to either extend this or add a variant that uses watchman to mirror src_dir into dest_dir.
[ "Recursively", "copy", "the", "src_dir", "to", "the", "dest_dir", "filtering", "out", "entries", "using", "the", "ignore", "lambda", ".", "The", "behavior", "of", "the", "ignore", "lambda", "must", "match", "that", "described", "by", "shutil", ".", "copytree", ".", "This", "copytree", "function", "knows", "how", "to", "prefetch", "data", "when", "running", "in", "an", "eden", "repo", ".", "TODO", ":", "I", "d", "like", "to", "either", "extend", "this", "or", "add", "a", "variant", "that", "uses", "watchman", "to", "mirror", "src_dir", "into", "dest_dir", "." ]
def copytree(src_dir, dest_dir, ignore=None): """Recursively copy the src_dir to the dest_dir, filtering out entries using the ignore lambda. The behavior of the ignore lambda must match that described by `shutil.copytree`. This `copytree` function knows how to prefetch data when running in an eden repo. TODO: I'd like to either extend this or add a variant that uses watchman to mirror src_dir into dest_dir. """ prefetch_dir_if_eden(src_dir) return shutil.copytree(src_dir, dest_dir, ignore=ignore)
[ "def", "copytree", "(", "src_dir", ",", "dest_dir", ",", "ignore", "=", "None", ")", ":", "prefetch_dir_if_eden", "(", "src_dir", ")", "return", "shutil", ".", "copytree", "(", "src_dir", ",", "dest_dir", ",", "ignore", "=", "ignore", ")" ]
https://github.com/facebookincubator/katran/blob/192eb988c398afc673620254097defb7035d669e/build/fbcode_builder/getdeps/copytree.py#L68-L78
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
lldb/third_party/Python/module/pexpect-2.4/pxssh.py
python
pxssh.login
( self, server, username, password='', terminal_type='ansi', original_prompt=r"[#$]", login_timeout=10, port=None, auto_prompt_reset=True)
return True
This logs the user into the given server. It uses the 'original_prompt' to try to find the prompt right after login. When it finds the prompt it immediately tries to reset the prompt to something more easily matched. The default 'original_prompt' is very optimistic and is easily fooled. It's more reliable to try to match the original prompt as exactly as possible to prevent false matches by server strings such as the "Message Of The Day". On many systems you can disable the MOTD on the remote server by creating a zero-length file called "~/.hushlogin" on the remote server. If a prompt cannot be found then this will not necessarily cause the login to fail. In the case of a timeout when looking for the prompt we assume that the original prompt was so weird that we could not match it, so we use a few tricks to guess when we have reached the prompt. Then we hope for the best and blindly try to reset the prompt to something more unique. If that fails then login() raises an ExceptionPxssh exception. In some situations it is not possible or desirable to reset the original prompt. In this case, set 'auto_prompt_reset' to False to inhibit setting the prompt to the UNIQUE_PROMPT. Remember that pxssh uses a unique prompt in the prompt() method. If the original prompt is not reset then this will disable the prompt() method unless you manually set the PROMPT attribute.
This logs the user into the given server. It uses the 'original_prompt' to try to find the prompt right after login. When it finds the prompt it immediately tries to reset the prompt to something more easily matched. The default 'original_prompt' is very optimistic and is easily fooled. It's more reliable to try to match the original prompt as exactly as possible to prevent false matches by server strings such as the "Message Of The Day". On many systems you can disable the MOTD on the remote server by creating a zero-length file called "~/.hushlogin" on the remote server. If a prompt cannot be found then this will not necessarily cause the login to fail. In the case of a timeout when looking for the prompt we assume that the original prompt was so weird that we could not match it, so we use a few tricks to guess when we have reached the prompt. Then we hope for the best and blindly try to reset the prompt to something more unique. If that fails then login() raises an ExceptionPxssh exception.
[ "This", "logs", "the", "user", "into", "the", "given", "server", ".", "It", "uses", "the", "original_prompt", "to", "try", "to", "find", "the", "prompt", "right", "after", "login", ".", "When", "it", "finds", "the", "prompt", "it", "immediately", "tries", "to", "reset", "the", "prompt", "to", "something", "more", "easily", "matched", ".", "The", "default", "original_prompt", "is", "very", "optimistic", "and", "is", "easily", "fooled", ".", "It", "s", "more", "reliable", "to", "try", "to", "match", "the", "original", "prompt", "as", "exactly", "as", "possible", "to", "prevent", "false", "matches", "by", "server", "strings", "such", "as", "the", "Message", "Of", "The", "Day", ".", "On", "many", "systems", "you", "can", "disable", "the", "MOTD", "on", "the", "remote", "server", "by", "creating", "a", "zero", "-", "length", "file", "called", "~", "/", ".", "hushlogin", "on", "the", "remote", "server", ".", "If", "a", "prompt", "cannot", "be", "found", "then", "this", "will", "not", "necessarily", "cause", "the", "login", "to", "fail", ".", "In", "the", "case", "of", "a", "timeout", "when", "looking", "for", "the", "prompt", "we", "assume", "that", "the", "original", "prompt", "was", "so", "weird", "that", "we", "could", "not", "match", "it", "so", "we", "use", "a", "few", "tricks", "to", "guess", "when", "we", "have", "reached", "the", "prompt", ".", "Then", "we", "hope", "for", "the", "best", "and", "blindly", "try", "to", "reset", "the", "prompt", "to", "something", "more", "unique", ".", "If", "that", "fails", "then", "login", "()", "raises", "an", "ExceptionPxssh", "exception", "." ]
def login( self, server, username, password='', terminal_type='ansi', original_prompt=r"[#$]", login_timeout=10, port=None, auto_prompt_reset=True): """This logs the user into the given server. It uses the 'original_prompt' to try to find the prompt right after login. When it finds the prompt it immediately tries to reset the prompt to something more easily matched. The default 'original_prompt' is very optimistic and is easily fooled. It's more reliable to try to match the original prompt as exactly as possible to prevent false matches by server strings such as the "Message Of The Day". On many systems you can disable the MOTD on the remote server by creating a zero-length file called "~/.hushlogin" on the remote server. If a prompt cannot be found then this will not necessarily cause the login to fail. In the case of a timeout when looking for the prompt we assume that the original prompt was so weird that we could not match it, so we use a few tricks to guess when we have reached the prompt. Then we hope for the best and blindly try to reset the prompt to something more unique. If that fails then login() raises an ExceptionPxssh exception. In some situations it is not possible or desirable to reset the original prompt. In this case, set 'auto_prompt_reset' to False to inhibit setting the prompt to the UNIQUE_PROMPT. Remember that pxssh uses a unique prompt in the prompt() method. If the original prompt is not reset then this will disable the prompt() method unless you manually set the PROMPT attribute. """ ssh_options = '-q' if self.force_password: ssh_options = ssh_options + ' ' + self.SSH_OPTS if port is not None: ssh_options = ssh_options + ' -p %s' % (str(port)) cmd = "ssh %s -l %s %s" % (ssh_options, username, server) # This does not distinguish between a remote server 'password' prompt # and a local ssh 'passphrase' prompt (for unlocking a private key). spawn._spawn(self, cmd) i = self.expect( [ "(?i)are you sure you want to continue connecting", original_prompt, "(?i)(?:password)|(?:passphrase for key)", "(?i)permission denied", "(?i)terminal type", TIMEOUT, "(?i)connection closed by remote host"], timeout=login_timeout) # First phase if i == 0: # New certificate -- always accept it. # This is what you get if SSH does not have the remote host's # public key stored in the 'known_hosts' cache. self.sendline("yes") i = self.expect( [ "(?i)are you sure you want to continue connecting", original_prompt, "(?i)(?:password)|(?:passphrase for key)", "(?i)permission denied", "(?i)terminal type", TIMEOUT]) if i == 2: # password or passphrase self.sendline(password) i = self.expect( [ "(?i)are you sure you want to continue connecting", original_prompt, "(?i)(?:password)|(?:passphrase for key)", "(?i)permission denied", "(?i)terminal type", TIMEOUT]) if i == 4: self.sendline(terminal_type) i = self.expect( [ "(?i)are you sure you want to continue connecting", original_prompt, "(?i)(?:password)|(?:passphrase for key)", "(?i)permission denied", "(?i)terminal type", TIMEOUT]) # Second phase if i == 0: # This is weird. This should not happen twice in a row. self.close() raise ExceptionPxssh( 'Weird error. Got "are you sure" prompt twice.') elif i == 1: # can occur if you have a public key pair set to authenticate. # TODO: May NOT be OK if expect() got tricked and matched a false # prompt. pass elif i == 2: # password prompt again # For incorrect passwords, some ssh servers will # ask for the password again, others return 'denied' right away. # If we get the password prompt again then this means # we didn't get the password right the first time. self.close() raise ExceptionPxssh('password refused') elif i == 3: # permission denied -- password was bad. self.close() raise ExceptionPxssh('permission denied') elif i == 4: # terminal type again? WTF? self.close() raise ExceptionPxssh( 'Weird error. Got "terminal type" prompt twice.') elif i == 5: # Timeout # This is tricky... I presume that we are at the command-line prompt. # It may be that the shell prompt was so weird that we couldn't match # it. Or it may be that we couldn't log in for some other reason. I # can't be sure, but it's safe to guess that we did login because if # I presume wrong and we are not logged in then this should be caught # later when I try to set the shell prompt. pass elif i == 6: # Connection closed by remote host self.close() raise ExceptionPxssh('connection closed') else: # Unexpected self.close() raise ExceptionPxssh('unexpected login response') if not self.sync_original_prompt(): self.close() raise ExceptionPxssh('could not synchronize with original prompt') # We appear to be in. # set shell prompt to something unique. if auto_prompt_reset: if not self.set_unique_prompt(): self.close() raise ExceptionPxssh( 'could not set shell prompt\n' + self.before) return True
[ "def", "login", "(", "self", ",", "server", ",", "username", ",", "password", "=", "''", ",", "terminal_type", "=", "'ansi'", ",", "original_prompt", "=", "r\"[#$]\"", ",", "login_timeout", "=", "10", ",", "port", "=", "None", ",", "auto_prompt_reset", "=", "True", ")", ":", "ssh_options", "=", "'-q'", "if", "self", ".", "force_password", ":", "ssh_options", "=", "ssh_options", "+", "' '", "+", "self", ".", "SSH_OPTS", "if", "port", "is", "not", "None", ":", "ssh_options", "=", "ssh_options", "+", "' -p %s'", "%", "(", "str", "(", "port", ")", ")", "cmd", "=", "\"ssh %s -l %s %s\"", "%", "(", "ssh_options", ",", "username", ",", "server", ")", "# This does not distinguish between a remote server 'password' prompt", "# and a local ssh 'passphrase' prompt (for unlocking a private key).", "spawn", ".", "_spawn", "(", "self", ",", "cmd", ")", "i", "=", "self", ".", "expect", "(", "[", "\"(?i)are you sure you want to continue connecting\"", ",", "original_prompt", ",", "\"(?i)(?:password)|(?:passphrase for key)\"", ",", "\"(?i)permission denied\"", ",", "\"(?i)terminal type\"", ",", "TIMEOUT", ",", "\"(?i)connection closed by remote host\"", "]", ",", "timeout", "=", "login_timeout", ")", "# First phase", "if", "i", "==", "0", ":", "# New certificate -- always accept it.", "# This is what you get if SSH does not have the remote host's", "# public key stored in the 'known_hosts' cache.", "self", ".", "sendline", "(", "\"yes\"", ")", "i", "=", "self", ".", "expect", "(", "[", "\"(?i)are you sure you want to continue connecting\"", ",", "original_prompt", ",", "\"(?i)(?:password)|(?:passphrase for key)\"", ",", "\"(?i)permission denied\"", ",", "\"(?i)terminal type\"", ",", "TIMEOUT", "]", ")", "if", "i", "==", "2", ":", "# password or passphrase", "self", ".", "sendline", "(", "password", ")", "i", "=", "self", ".", "expect", "(", "[", "\"(?i)are you sure you want to continue connecting\"", ",", "original_prompt", ",", "\"(?i)(?:password)|(?:passphrase for key)\"", ",", "\"(?i)permission denied\"", ",", "\"(?i)terminal type\"", ",", "TIMEOUT", "]", ")", "if", "i", "==", "4", ":", "self", ".", "sendline", "(", "terminal_type", ")", "i", "=", "self", ".", "expect", "(", "[", "\"(?i)are you sure you want to continue connecting\"", ",", "original_prompt", ",", "\"(?i)(?:password)|(?:passphrase for key)\"", ",", "\"(?i)permission denied\"", ",", "\"(?i)terminal type\"", ",", "TIMEOUT", "]", ")", "# Second phase", "if", "i", "==", "0", ":", "# This is weird. This should not happen twice in a row.", "self", ".", "close", "(", ")", "raise", "ExceptionPxssh", "(", "'Weird error. Got \"are you sure\" prompt twice.'", ")", "elif", "i", "==", "1", ":", "# can occur if you have a public key pair set to authenticate.", "# TODO: May NOT be OK if expect() got tricked and matched a false", "# prompt.", "pass", "elif", "i", "==", "2", ":", "# password prompt again", "# For incorrect passwords, some ssh servers will", "# ask for the password again, others return 'denied' right away.", "# If we get the password prompt again then this means", "# we didn't get the password right the first time.", "self", ".", "close", "(", ")", "raise", "ExceptionPxssh", "(", "'password refused'", ")", "elif", "i", "==", "3", ":", "# permission denied -- password was bad.", "self", ".", "close", "(", ")", "raise", "ExceptionPxssh", "(", "'permission denied'", ")", "elif", "i", "==", "4", ":", "# terminal type again? WTF?", "self", ".", "close", "(", ")", "raise", "ExceptionPxssh", "(", "'Weird error. Got \"terminal type\" prompt twice.'", ")", "elif", "i", "==", "5", ":", "# Timeout", "# This is tricky... I presume that we are at the command-line prompt.", "# It may be that the shell prompt was so weird that we couldn't match", "# it. Or it may be that we couldn't log in for some other reason. I", "# can't be sure, but it's safe to guess that we did login because if", "# I presume wrong and we are not logged in then this should be caught", "# later when I try to set the shell prompt.", "pass", "elif", "i", "==", "6", ":", "# Connection closed by remote host", "self", ".", "close", "(", ")", "raise", "ExceptionPxssh", "(", "'connection closed'", ")", "else", ":", "# Unexpected", "self", ".", "close", "(", ")", "raise", "ExceptionPxssh", "(", "'unexpected login response'", ")", "if", "not", "self", ".", "sync_original_prompt", "(", ")", ":", "self", ".", "close", "(", ")", "raise", "ExceptionPxssh", "(", "'could not synchronize with original prompt'", ")", "# We appear to be in.", "# set shell prompt to something unique.", "if", "auto_prompt_reset", ":", "if", "not", "self", ".", "set_unique_prompt", "(", ")", ":", "self", ".", "close", "(", ")", "raise", "ExceptionPxssh", "(", "'could not set shell prompt\\n'", "+", "self", ".", "before", ")", "return", "True" ]
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/third_party/Python/module/pexpect-2.4/pxssh.py#L178-L315
plaidml/plaidml
f3c6681db21460e5fdc11ae651d6d7b6c27f8262
cmake/git-clang-format.py
python
extract_lines
(patch_file)
return matches
Extract the changed lines in `patch_file`. The return value is a dictionary mapping filename to a list of (start_line, line_count) pairs. The input must have been produced with ``-U0``, meaning unidiff format with zero lines of context. The return value is a dict mapping filename to a list of line `Range`s.
Extract the changed lines in `patch_file`.
[ "Extract", "the", "changed", "lines", "in", "patch_file", "." ]
def extract_lines(patch_file): """Extract the changed lines in `patch_file`. The return value is a dictionary mapping filename to a list of (start_line, line_count) pairs. The input must have been produced with ``-U0``, meaning unidiff format with zero lines of context. The return value is a dict mapping filename to a list of line `Range`s.""" matches = {} for line in patch_file: line = convert_string(line) match = re.search(r'^\+\+\+\ [^/]+/(.*)', line) if match: filename = match.group(1).rstrip('\r\n') match = re.search(r'^@@ -[0-9,]+ \+(\d+)(,(\d+))?', line) if match: start_line = int(match.group(1)) line_count = 1 if match.group(3): line_count = int(match.group(3)) if line_count > 0: matches.setdefault(filename, []).append(Range(start_line, line_count)) return matches
[ "def", "extract_lines", "(", "patch_file", ")", ":", "matches", "=", "{", "}", "for", "line", "in", "patch_file", ":", "line", "=", "convert_string", "(", "line", ")", "match", "=", "re", ".", "search", "(", "r'^\\+\\+\\+\\ [^/]+/(.*)'", ",", "line", ")", "if", "match", ":", "filename", "=", "match", ".", "group", "(", "1", ")", ".", "rstrip", "(", "'\\r\\n'", ")", "match", "=", "re", ".", "search", "(", "r'^@@ -[0-9,]+ \\+(\\d+)(,(\\d+))?'", ",", "line", ")", "if", "match", ":", "start_line", "=", "int", "(", "match", ".", "group", "(", "1", ")", ")", "line_count", "=", "1", "if", "match", ".", "group", "(", "3", ")", ":", "line_count", "=", "int", "(", "match", ".", "group", "(", "3", ")", ")", "if", "line_count", ">", "0", ":", "matches", ".", "setdefault", "(", "filename", ",", "[", "]", ")", ".", "append", "(", "Range", "(", "start_line", ",", "line_count", ")", ")", "return", "matches" ]
https://github.com/plaidml/plaidml/blob/f3c6681db21460e5fdc11ae651d6d7b6c27f8262/cmake/git-clang-format.py#L304-L327
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/google_appengine_cloudstorage/cloudstorage/cloudstorage_api.py
python
_Bucket._next_file_gen
(self, root)
Generator for next file element in the document. Args: root: root element of the XML tree. Yields: GCSFileStat for the next file.
Generator for next file element in the document.
[ "Generator", "for", "next", "file", "element", "in", "the", "document", "." ]
def _next_file_gen(self, root): """Generator for next file element in the document. Args: root: root element of the XML tree. Yields: GCSFileStat for the next file. """ for e in root.getiterator(common._T_CONTENTS): st_ctime, size, etag, key = None, None, None, None for child in e.getiterator('*'): if child.tag == common._T_LAST_MODIFIED: st_ctime = common.dt_str_to_posix(child.text) elif child.tag == common._T_ETAG: etag = child.text elif child.tag == common._T_SIZE: size = child.text elif child.tag == common._T_KEY: key = child.text yield common.GCSFileStat(self._path + '/' + key, size, etag, st_ctime) e.clear() yield None
[ "def", "_next_file_gen", "(", "self", ",", "root", ")", ":", "for", "e", "in", "root", ".", "getiterator", "(", "common", ".", "_T_CONTENTS", ")", ":", "st_ctime", ",", "size", ",", "etag", ",", "key", "=", "None", ",", "None", ",", "None", ",", "None", "for", "child", "in", "e", ".", "getiterator", "(", "'*'", ")", ":", "if", "child", ".", "tag", "==", "common", ".", "_T_LAST_MODIFIED", ":", "st_ctime", "=", "common", ".", "dt_str_to_posix", "(", "child", ".", "text", ")", "elif", "child", ".", "tag", "==", "common", ".", "_T_ETAG", ":", "etag", "=", "child", ".", "text", "elif", "child", ".", "tag", "==", "common", ".", "_T_SIZE", ":", "size", "=", "child", ".", "text", "elif", "child", ".", "tag", "==", "common", ".", "_T_KEY", ":", "key", "=", "child", ".", "text", "yield", "common", ".", "GCSFileStat", "(", "self", ".", "_path", "+", "'/'", "+", "key", ",", "size", ",", "etag", ",", "st_ctime", ")", "e", ".", "clear", "(", ")", "yield", "None" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/google_appengine_cloudstorage/cloudstorage/cloudstorage_api.py#L358-L381
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/layers/python/layers/layers.py
python
fully_connected
(inputs, num_outputs, activation_fn=nn.relu, normalizer_fn=None, normalizer_params=None, weights_initializer=initializers.xavier_initializer(), weights_regularizer=None, biases_initializer=init_ops.zeros_initializer, biases_regularizer=None, reuse=None, variables_collections=None, outputs_collections=None, trainable=True, scope=None)
Adds a fully connected layer. `fully_connected` creates a variable called `weights`, representing a fully connected weight matrix, which is multiplied by the `inputs` to produce a `Tensor` of hidden units. If a `normalizer_fn` is provided (such as `batch_norm`), it is then applied. Otherwise, if `normalizer_fn` is None and a `biases_initializer` is provided then a `biases` variable would be created and added the hidden units. Finally, if `activation_fn` is not `None`, it is applied to the hidden units as well. Note: that if `inputs` have a rank greater than 2, then `inputs` is flattened prior to the initial matrix multiply by `weights`. Args: inputs: A tensor of with at least rank 2 and value for the last dimension, i.e. `[batch_size, depth]`, `[None, None, None, channels]`. num_outputs: Integer or long, the number of output units in the layer. activation_fn: activation function, set to None to skip it and maintain a linear activation. normalizer_fn: normalization function to use instead of `biases`. If `normalizer_fn` is provided then `biases_initializer` and `biases_regularizer` are ignored and `biases` are not created nor added. default set to None for no normalizer function normalizer_params: normalization function parameters. weights_initializer: An initializer for the weights. weights_regularizer: Optional regularizer for the weights. biases_initializer: An initializer for the biases. If None skip biases. biases_regularizer: Optional regularizer for the biases. reuse: whether or not the layer and its variables should be reused. To be able to reuse the layer scope must be given. variables_collections: Optional list of collections for all the variables or a dictionary containing a different list of collections per variable. outputs_collections: collection to add the outputs. trainable: If `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable). scope: Optional scope for variable_scope. Returns: the tensor variable representing the result of the series of operations. Raises: ValueError: if x has rank less than 2 or if its last dimension is not set.
Adds a fully connected layer.
[ "Adds", "a", "fully", "connected", "layer", "." ]
def fully_connected(inputs, num_outputs, activation_fn=nn.relu, normalizer_fn=None, normalizer_params=None, weights_initializer=initializers.xavier_initializer(), weights_regularizer=None, biases_initializer=init_ops.zeros_initializer, biases_regularizer=None, reuse=None, variables_collections=None, outputs_collections=None, trainable=True, scope=None): """Adds a fully connected layer. `fully_connected` creates a variable called `weights`, representing a fully connected weight matrix, which is multiplied by the `inputs` to produce a `Tensor` of hidden units. If a `normalizer_fn` is provided (such as `batch_norm`), it is then applied. Otherwise, if `normalizer_fn` is None and a `biases_initializer` is provided then a `biases` variable would be created and added the hidden units. Finally, if `activation_fn` is not `None`, it is applied to the hidden units as well. Note: that if `inputs` have a rank greater than 2, then `inputs` is flattened prior to the initial matrix multiply by `weights`. Args: inputs: A tensor of with at least rank 2 and value for the last dimension, i.e. `[batch_size, depth]`, `[None, None, None, channels]`. num_outputs: Integer or long, the number of output units in the layer. activation_fn: activation function, set to None to skip it and maintain a linear activation. normalizer_fn: normalization function to use instead of `biases`. If `normalizer_fn` is provided then `biases_initializer` and `biases_regularizer` are ignored and `biases` are not created nor added. default set to None for no normalizer function normalizer_params: normalization function parameters. weights_initializer: An initializer for the weights. weights_regularizer: Optional regularizer for the weights. biases_initializer: An initializer for the biases. If None skip biases. biases_regularizer: Optional regularizer for the biases. reuse: whether or not the layer and its variables should be reused. To be able to reuse the layer scope must be given. variables_collections: Optional list of collections for all the variables or a dictionary containing a different list of collections per variable. outputs_collections: collection to add the outputs. trainable: If `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable). scope: Optional scope for variable_scope. Returns: the tensor variable representing the result of the series of operations. Raises: ValueError: if x has rank less than 2 or if its last dimension is not set. """ if not (isinstance(num_outputs, int) or isinstance(num_outputs, long)): raise ValueError('num_outputs should be int or long, got %s.', num_outputs) with variable_scope.variable_scope(scope, 'fully_connected', [inputs], reuse=reuse) as sc: inputs = ops.convert_to_tensor(inputs) dtype = inputs.dtype.base_dtype inputs_shape = inputs.get_shape() num_input_units = utils.last_dimension(inputs_shape, min_rank=2) static_shape = inputs_shape.as_list() static_shape[-1] = num_outputs out_shape = array_ops.unpack(array_ops.shape(inputs)) out_shape[-1] = num_outputs weights_shape = [num_input_units, num_outputs] weights_collections = utils.get_variable_collections( variables_collections, 'weights') weights = variables.model_variable('weights', shape=weights_shape, dtype=dtype, initializer=weights_initializer, regularizer=weights_regularizer, collections=weights_collections, trainable=trainable) if len(static_shape) > 2: # Reshape inputs inputs = array_ops.reshape(inputs, [-1, num_input_units]) outputs = standard_ops.matmul(inputs, weights) if normalizer_fn is not None: normalizer_params = normalizer_params or {} outputs = normalizer_fn(outputs, **normalizer_params) else: if biases_initializer is not None: biases_collections = utils.get_variable_collections( variables_collections, 'biases') biases = variables.model_variable('biases', shape=[num_outputs,], dtype=dtype, initializer=biases_initializer, regularizer=biases_regularizer, collections=biases_collections, trainable=trainable) outputs = nn.bias_add(outputs, biases) if activation_fn is not None: outputs = activation_fn(outputs) if len(static_shape) > 2: # Reshape back outputs outputs = array_ops.reshape(outputs, array_ops.pack(out_shape)) outputs.set_shape(static_shape) return utils.collect_named_outputs(outputs_collections, sc.original_name_scope, outputs)
[ "def", "fully_connected", "(", "inputs", ",", "num_outputs", ",", "activation_fn", "=", "nn", ".", "relu", ",", "normalizer_fn", "=", "None", ",", "normalizer_params", "=", "None", ",", "weights_initializer", "=", "initializers", ".", "xavier_initializer", "(", ")", ",", "weights_regularizer", "=", "None", ",", "biases_initializer", "=", "init_ops", ".", "zeros_initializer", ",", "biases_regularizer", "=", "None", ",", "reuse", "=", "None", ",", "variables_collections", "=", "None", ",", "outputs_collections", "=", "None", ",", "trainable", "=", "True", ",", "scope", "=", "None", ")", ":", "if", "not", "(", "isinstance", "(", "num_outputs", ",", "int", ")", "or", "isinstance", "(", "num_outputs", ",", "long", ")", ")", ":", "raise", "ValueError", "(", "'num_outputs should be int or long, got %s.'", ",", "num_outputs", ")", "with", "variable_scope", ".", "variable_scope", "(", "scope", ",", "'fully_connected'", ",", "[", "inputs", "]", ",", "reuse", "=", "reuse", ")", "as", "sc", ":", "inputs", "=", "ops", ".", "convert_to_tensor", "(", "inputs", ")", "dtype", "=", "inputs", ".", "dtype", ".", "base_dtype", "inputs_shape", "=", "inputs", ".", "get_shape", "(", ")", "num_input_units", "=", "utils", ".", "last_dimension", "(", "inputs_shape", ",", "min_rank", "=", "2", ")", "static_shape", "=", "inputs_shape", ".", "as_list", "(", ")", "static_shape", "[", "-", "1", "]", "=", "num_outputs", "out_shape", "=", "array_ops", ".", "unpack", "(", "array_ops", ".", "shape", "(", "inputs", ")", ")", "out_shape", "[", "-", "1", "]", "=", "num_outputs", "weights_shape", "=", "[", "num_input_units", ",", "num_outputs", "]", "weights_collections", "=", "utils", ".", "get_variable_collections", "(", "variables_collections", ",", "'weights'", ")", "weights", "=", "variables", ".", "model_variable", "(", "'weights'", ",", "shape", "=", "weights_shape", ",", "dtype", "=", "dtype", ",", "initializer", "=", "weights_initializer", ",", "regularizer", "=", "weights_regularizer", ",", "collections", "=", "weights_collections", ",", "trainable", "=", "trainable", ")", "if", "len", "(", "static_shape", ")", ">", "2", ":", "# Reshape inputs", "inputs", "=", "array_ops", ".", "reshape", "(", "inputs", ",", "[", "-", "1", ",", "num_input_units", "]", ")", "outputs", "=", "standard_ops", ".", "matmul", "(", "inputs", ",", "weights", ")", "if", "normalizer_fn", "is", "not", "None", ":", "normalizer_params", "=", "normalizer_params", "or", "{", "}", "outputs", "=", "normalizer_fn", "(", "outputs", ",", "*", "*", "normalizer_params", ")", "else", ":", "if", "biases_initializer", "is", "not", "None", ":", "biases_collections", "=", "utils", ".", "get_variable_collections", "(", "variables_collections", ",", "'biases'", ")", "biases", "=", "variables", ".", "model_variable", "(", "'biases'", ",", "shape", "=", "[", "num_outputs", ",", "]", ",", "dtype", "=", "dtype", ",", "initializer", "=", "biases_initializer", ",", "regularizer", "=", "biases_regularizer", ",", "collections", "=", "biases_collections", ",", "trainable", "=", "trainable", ")", "outputs", "=", "nn", ".", "bias_add", "(", "outputs", ",", "biases", ")", "if", "activation_fn", "is", "not", "None", ":", "outputs", "=", "activation_fn", "(", "outputs", ")", "if", "len", "(", "static_shape", ")", ">", "2", ":", "# Reshape back outputs", "outputs", "=", "array_ops", ".", "reshape", "(", "outputs", ",", "array_ops", ".", "pack", "(", "out_shape", ")", ")", "outputs", ".", "set_shape", "(", "static_shape", ")", "return", "utils", ".", "collect_named_outputs", "(", "outputs_collections", ",", "sc", ".", "original_name_scope", ",", "outputs", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/layers/python/layers/layers.py#L854-L962
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/linter/git.py
python
get_files_to_check_from_patch
(patches, filter_function)
return valid_files
Take a patch file generated by git diff, and scan the patch for a list of files to check.
Take a patch file generated by git diff, and scan the patch for a list of files to check.
[ "Take", "a", "patch", "file", "generated", "by", "git", "diff", "and", "scan", "the", "patch", "for", "a", "list", "of", "files", "to", "check", "." ]
def get_files_to_check_from_patch(patches, filter_function): # type: (List[str], Callable[[str], bool]) -> List[str] """Take a patch file generated by git diff, and scan the patch for a list of files to check.""" candidates = [] # type: List[str] # Get a list of candidate_files check = re.compile(r"^diff --git a\/([\w\/\.\-]+) b\/[\w\/\.\-]+") lines = [] # type: List[str] for patch in patches: with open(patch, "rb") as infile: lines += infile.readlines() candidates = [check.match(line).group(1) for line in lines if check.match(line)] repos = get_repos() valid_files = list( itertools.chain.from_iterable( [r.get_candidates(candidates, filter_function) for r in repos])) return valid_files
[ "def", "get_files_to_check_from_patch", "(", "patches", ",", "filter_function", ")", ":", "# type: (List[str], Callable[[str], bool]) -> List[str]", "candidates", "=", "[", "]", "# type: List[str]", "# Get a list of candidate_files", "check", "=", "re", ".", "compile", "(", "r\"^diff --git a\\/([\\w\\/\\.\\-]+) b\\/[\\w\\/\\.\\-]+\"", ")", "lines", "=", "[", "]", "# type: List[str]", "for", "patch", "in", "patches", ":", "with", "open", "(", "patch", ",", "\"rb\"", ")", "as", "infile", ":", "lines", "+=", "infile", ".", "readlines", "(", ")", "candidates", "=", "[", "check", ".", "match", "(", "line", ")", ".", "group", "(", "1", ")", "for", "line", "in", "lines", "if", "check", ".", "match", "(", "line", ")", "]", "repos", "=", "get_repos", "(", ")", "valid_files", "=", "list", "(", "itertools", ".", "chain", ".", "from_iterable", "(", "[", "r", ".", "get_candidates", "(", "candidates", ",", "filter_function", ")", "for", "r", "in", "repos", "]", ")", ")", "return", "valid_files" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/linter/git.py#L168-L189
nasa/astrobee
9241e67e6692810d6e275abb3165b6d02f4ca5ef
scripts/git/cpplint.py
python
_FunctionState.End
(self)
Stop analyzing function body.
Stop analyzing function body.
[ "Stop", "analyzing", "function", "body", "." ]
def End(self): """Stop analyzing function body.""" self.in_a_function = False
[ "def", "End", "(", "self", ")", ":", "self", ".", "in_a_function", "=", "False" ]
https://github.com/nasa/astrobee/blob/9241e67e6692810d6e275abb3165b6d02f4ca5ef/scripts/git/cpplint.py#L1004-L1006
google-ar/WebARonTango
e86965d2cbc652156b480e0fcf77c716745578cd
chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py
python
Function.WriteGLES2ImplementationHeader
(self, f)
Writes the GLES2 Implemention declaration.
Writes the GLES2 Implemention declaration.
[ "Writes", "the", "GLES2", "Implemention", "declaration", "." ]
def WriteGLES2ImplementationHeader(self, f): """Writes the GLES2 Implemention declaration.""" self.type_handler.WriteGLES2ImplementationHeader(self, f)
[ "def", "WriteGLES2ImplementationHeader", "(", "self", ",", "f", ")", ":", "self", ".", "type_handler", ".", "WriteGLES2ImplementationHeader", "(", "self", ",", "f", ")" ]
https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L9643-L9645
KhronosGroup/SPIR
f33c27876d9f3d5810162b60fa89cc13d2b55725
bindings/python/clang/cindex.py
python
SourceLocation.offset
(self)
return self._get_instantiation()[3]
Get the file offset represented by this source location.
Get the file offset represented by this source location.
[ "Get", "the", "file", "offset", "represented", "by", "this", "source", "location", "." ]
def offset(self): """Get the file offset represented by this source location.""" return self._get_instantiation()[3]
[ "def", "offset", "(", "self", ")", ":", "return", "self", ".", "_get_instantiation", "(", ")", "[", "3", "]" ]
https://github.com/KhronosGroup/SPIR/blob/f33c27876d9f3d5810162b60fa89cc13d2b55725/bindings/python/clang/cindex.py#L213-L215
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/numarray/session.py
python
_callers_modules
()
return mods
returns a list containing the names of all the modules in the caller's global namespace.
returns a list containing the names of all the modules in the caller's global namespace.
[ "returns", "a", "list", "containing", "the", "names", "of", "all", "the", "modules", "in", "the", "caller", "s", "global", "namespace", "." ]
def _callers_modules(): """returns a list containing the names of all the modules in the caller's global namespace.""" g = _callers_globals() mods = [] for k,v in g.items(): if type(v) == type(sys): mods.append(getattr(v,"__name__")) return mods
[ "def", "_callers_modules", "(", ")", ":", "g", "=", "_callers_globals", "(", ")", "mods", "=", "[", "]", "for", "k", ",", "v", "in", "g", ".", "items", "(", ")", ":", "if", "type", "(", "v", ")", "==", "type", "(", "sys", ")", ":", "mods", ".", "append", "(", "getattr", "(", "v", ",", "\"__name__\"", ")", ")", "return", "mods" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/numarray/session.py#L116-L124
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/reduce4circleGUI.py
python
MainWindow.do_sync_ub
(self)
Purpose: synchronize UB matrix in use with UB matrix calculated. Requirements: One of these must be given 1. a valid UB matrix from tableWidget_ubMatrix 2. an ascii file that contains 9 float 3. from text edit :return:
Purpose: synchronize UB matrix in use with UB matrix calculated. Requirements: One of these must be given 1. a valid UB matrix from tableWidget_ubMatrix 2. an ascii file that contains 9 float 3. from text edit :return:
[ "Purpose", ":", "synchronize", "UB", "matrix", "in", "use", "with", "UB", "matrix", "calculated", ".", "Requirements", ":", "One", "of", "these", "must", "be", "given", "1", ".", "a", "valid", "UB", "matrix", "from", "tableWidget_ubMatrix", "2", ".", "an", "ascii", "file", "that", "contains", "9", "float", "3", ".", "from", "text", "edit", ":", "return", ":" ]
def do_sync_ub(self): """ Purpose: synchronize UB matrix in use with UB matrix calculated. Requirements: One of these must be given 1. a valid UB matrix from tableWidget_ubMatrix 2. an ascii file that contains 9 float 3. from text edit :return: """ # get the radio button that is checked if self.ui.radioButton_ubFromTab1.isChecked(): # get ub matrix from tab 'Calculate UB Matrix' ub_matrix = self.ui.tableWidget_ubMatrix.get_matrix() # elif self.ui.radioButton_loadUBmatrix.isChecked(): # # load ub matrix from a file # ISSUE 001 VZ-FUTURE: Implement this next! # raise NotImplementedError('This tab is not implemented, because the file format has not been decided.') elif self.ui.radioButton_ubFromList.isChecked(): # load ub matrix from text editor ub_matrix = self.get_ub_from_text() else: raise RuntimeError('None radio button is selected for UB') # set to in-use UB matrix and control self.ui.tableWidget_ubInUse.set_from_matrix(ub_matrix) exp_no = int(str(self.ui.lineEdit_exp.text())) self._myControl.set_ub_matrix(exp_number=exp_no, ub_matrix=ub_matrix)
[ "def", "do_sync_ub", "(", "self", ")", ":", "# get the radio button that is checked", "if", "self", ".", "ui", ".", "radioButton_ubFromTab1", ".", "isChecked", "(", ")", ":", "# get ub matrix from tab 'Calculate UB Matrix'", "ub_matrix", "=", "self", ".", "ui", ".", "tableWidget_ubMatrix", ".", "get_matrix", "(", ")", "# elif self.ui.radioButton_loadUBmatrix.isChecked():", "# # load ub matrix from a file", "# ISSUE 001 VZ-FUTURE: Implement this next!", "# raise NotImplementedError('This tab is not implemented, because the file format has not been decided.')", "elif", "self", ".", "ui", ".", "radioButton_ubFromList", ".", "isChecked", "(", ")", ":", "# load ub matrix from text editor", "ub_matrix", "=", "self", ".", "get_ub_from_text", "(", ")", "else", ":", "raise", "RuntimeError", "(", "'None radio button is selected for UB'", ")", "# set to in-use UB matrix and control", "self", ".", "ui", ".", "tableWidget_ubInUse", ".", "set_from_matrix", "(", "ub_matrix", ")", "exp_no", "=", "int", "(", "str", "(", "self", ".", "ui", ".", "lineEdit_exp", ".", "text", "(", ")", ")", ")", "self", ".", "_myControl", ".", "set_ub_matrix", "(", "exp_number", "=", "exp_no", ",", "ub_matrix", "=", "ub_matrix", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/reduce4circleGUI.py#L3052-L3081
nnrg/opennero
43e12a1bcba6e228639db3886fec1dc47ddc24cb
mods/NERO/agent.py
python
NEATAgent.__init__
(self, team_type, *args)
Create an agent brain
Create an agent brain
[ "Create", "an", "agent", "brain" ]
def __init__(self, team_type, *args): """ Create an agent brain """ # this line is crucial, otherwise the class is not recognized as an # AgentBrainPtr by C++ OpenNero.AgentBrain.__init__(self) NeroAgent.__init__(self, team_type) self.omit_friend_sensors = False if len(args) > 0: stream = io.BytesIO(string.join(args, '\n').encode('utf-8')) self.org = OpenNero.Organism(stream) else: NEATAgent.count += 1 genome = self.base_genome.clone(NEATAgent.count, 1) self.org = OpenNero.Organism(0, genome, 1)
[ "def", "__init__", "(", "self", ",", "team_type", ",", "*", "args", ")", ":", "# this line is crucial, otherwise the class is not recognized as an", "# AgentBrainPtr by C++", "OpenNero", ".", "AgentBrain", ".", "__init__", "(", "self", ")", "NeroAgent", ".", "__init__", "(", "self", ",", "team_type", ")", "self", ".", "omit_friend_sensors", "=", "False", "if", "len", "(", "args", ")", ">", "0", ":", "stream", "=", "io", ".", "BytesIO", "(", "string", ".", "join", "(", "args", ",", "'\\n'", ")", ".", "encode", "(", "'utf-8'", ")", ")", "self", ".", "org", "=", "OpenNero", ".", "Organism", "(", "stream", ")", "else", ":", "NEATAgent", ".", "count", "+=", "1", "genome", "=", "self", ".", "base_genome", ".", "clone", "(", "NEATAgent", ".", "count", ",", "1", ")", "self", ".", "org", "=", "OpenNero", ".", "Organism", "(", "0", ",", "genome", ",", "1", ")" ]
https://github.com/nnrg/opennero/blob/43e12a1bcba6e228639db3886fec1dc47ddc24cb/mods/NERO/agent.py#L44-L62
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib2to3/pytree.py
python
WildcardPattern.generate_matches
(self, nodes)
Generator yielding matches for a sequence of nodes. Args: nodes: sequence of nodes Yields: (count, results) tuples where: count: the match comprises nodes[:count]; results: dict containing named submatches.
Generator yielding matches for a sequence of nodes.
[ "Generator", "yielding", "matches", "for", "a", "sequence", "of", "nodes", "." ]
def generate_matches(self, nodes): """ Generator yielding matches for a sequence of nodes. Args: nodes: sequence of nodes Yields: (count, results) tuples where: count: the match comprises nodes[:count]; results: dict containing named submatches. """ if self.content is None: # Shortcut for special case (see __init__.__doc__) for count in xrange(self.min, 1 + min(len(nodes), self.max)): r = {} if self.name: r[self.name] = nodes[:count] yield count, r elif self.name == "bare_name": yield self._bare_name_matches(nodes) else: # The reason for this is that hitting the recursion limit usually # results in some ugly messages about how RuntimeErrors are being # ignored. We don't do this on non-CPython implementation because # they don't have this problem. if hasattr(sys, "getrefcount"): save_stderr = sys.stderr sys.stderr = StringIO() try: for count, r in self._recursive_matches(nodes, 0): if self.name: r[self.name] = nodes[:count] yield count, r except RuntimeError: # We fall back to the iterative pattern matching scheme if the recursive # scheme hits the recursion limit. for count, r in self._iterative_matches(nodes): if self.name: r[self.name] = nodes[:count] yield count, r finally: if hasattr(sys, "getrefcount"): sys.stderr = save_stderr
[ "def", "generate_matches", "(", "self", ",", "nodes", ")", ":", "if", "self", ".", "content", "is", "None", ":", "# Shortcut for special case (see __init__.__doc__)", "for", "count", "in", "xrange", "(", "self", ".", "min", ",", "1", "+", "min", "(", "len", "(", "nodes", ")", ",", "self", ".", "max", ")", ")", ":", "r", "=", "{", "}", "if", "self", ".", "name", ":", "r", "[", "self", ".", "name", "]", "=", "nodes", "[", ":", "count", "]", "yield", "count", ",", "r", "elif", "self", ".", "name", "==", "\"bare_name\"", ":", "yield", "self", ".", "_bare_name_matches", "(", "nodes", ")", "else", ":", "# The reason for this is that hitting the recursion limit usually", "# results in some ugly messages about how RuntimeErrors are being", "# ignored. We don't do this on non-CPython implementation because", "# they don't have this problem.", "if", "hasattr", "(", "sys", ",", "\"getrefcount\"", ")", ":", "save_stderr", "=", "sys", ".", "stderr", "sys", ".", "stderr", "=", "StringIO", "(", ")", "try", ":", "for", "count", ",", "r", "in", "self", ".", "_recursive_matches", "(", "nodes", ",", "0", ")", ":", "if", "self", ".", "name", ":", "r", "[", "self", ".", "name", "]", "=", "nodes", "[", ":", "count", "]", "yield", "count", ",", "r", "except", "RuntimeError", ":", "# We fall back to the iterative pattern matching scheme if the recursive", "# scheme hits the recursion limit.", "for", "count", ",", "r", "in", "self", ".", "_iterative_matches", "(", "nodes", ")", ":", "if", "self", ".", "name", ":", "r", "[", "self", ".", "name", "]", "=", "nodes", "[", ":", "count", "]", "yield", "count", ",", "r", "finally", ":", "if", "hasattr", "(", "sys", ",", "\"getrefcount\"", ")", ":", "sys", ".", "stderr", "=", "save_stderr" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib2to3/pytree.py#L722-L765
apache/kudu
90895ce76590f10730ad7aac3613b69d89ff5422
src/kudu/scripts/parse_metrics_log.py
python
cache_hit_ratio
(aggregated_prev, aggregated_cur)
return cache_ratio
Calculate the cache hit ratio between the two samples. If there were no cache hits or misses, this returns NaN.
Calculate the cache hit ratio between the two samples. If there were no cache hits or misses, this returns NaN.
[ "Calculate", "the", "cache", "hit", "ratio", "between", "the", "two", "samples", ".", "If", "there", "were", "no", "cache", "hits", "or", "misses", "this", "returns", "NaN", "." ]
def cache_hit_ratio(aggregated_prev, aggregated_cur): """ Calculate the cache hit ratio between the two samples. If there were no cache hits or misses, this returns NaN. """ delta_hits = delta(aggregated_prev, aggregated_cur, 'server.block_cache_hits_caching') delta_misses = delta(aggregated_prev, aggregated_cur, 'server.block_cache_misses_caching') if delta_hits + delta_misses > 0: cache_ratio = float(delta_hits) / (delta_hits + delta_misses) else: cache_ratio = NaN return cache_ratio
[ "def", "cache_hit_ratio", "(", "aggregated_prev", ",", "aggregated_cur", ")", ":", "delta_hits", "=", "delta", "(", "aggregated_prev", ",", "aggregated_cur", ",", "'server.block_cache_hits_caching'", ")", "delta_misses", "=", "delta", "(", "aggregated_prev", ",", "aggregated_cur", ",", "'server.block_cache_misses_caching'", ")", "if", "delta_hits", "+", "delta_misses", ">", "0", ":", "cache_ratio", "=", "float", "(", "delta_hits", ")", "/", "(", "delta_hits", "+", "delta_misses", ")", "else", ":", "cache_ratio", "=", "NaN", "return", "cache_ratio" ]
https://github.com/apache/kudu/blob/90895ce76590f10730ad7aac3613b69d89ff5422/src/kudu/scripts/parse_metrics_log.py#L199-L210
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/network/download.py
python
sanitize_content_filename
(filename)
return os.path.basename(filename)
Sanitize the "filename" value from a Content-Disposition header.
Sanitize the "filename" value from a Content-Disposition header.
[ "Sanitize", "the", "filename", "value", "from", "a", "Content", "-", "Disposition", "header", "." ]
def sanitize_content_filename(filename): # type: (str) -> str """ Sanitize the "filename" value from a Content-Disposition header. """ return os.path.basename(filename)
[ "def", "sanitize_content_filename", "(", "filename", ")", ":", "# type: (str) -> str", "return", "os", ".", "path", ".", "basename", "(", "filename", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/network/download.py#L81-L86
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/richtext.py
python
RichTextPrintout.GetRichTextBuffer
(*args, **kwargs)
return _richtext.RichTextPrintout_GetRichTextBuffer(*args, **kwargs)
GetRichTextBuffer(self) -> RichTextBuffer
GetRichTextBuffer(self) -> RichTextBuffer
[ "GetRichTextBuffer", "(", "self", ")", "-", ">", "RichTextBuffer" ]
def GetRichTextBuffer(*args, **kwargs): """GetRichTextBuffer(self) -> RichTextBuffer""" return _richtext.RichTextPrintout_GetRichTextBuffer(*args, **kwargs)
[ "def", "GetRichTextBuffer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextPrintout_GetRichTextBuffer", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L4461-L4463
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/variables.py
python
RefVariable.scatter_max
(self, sparse_delta, use_locking=False, name=None)
return gen_state_ops.scatter_max( self._variable, sparse_delta.indices, sparse_delta.values, use_locking=use_locking, name=name)
Updates this variable with the max of `tf.IndexedSlices` and itself. Args: sparse_delta: `tf.IndexedSlices` to use as an argument of max with this variable. use_locking: If `True`, use locking during the operation. name: the name of the operation. Returns: A `Tensor` that will hold the new value of this variable after the scattered maximization has completed. Raises: TypeError: if `sparse_delta` is not an `IndexedSlices`.
Updates this variable with the max of `tf.IndexedSlices` and itself.
[ "Updates", "this", "variable", "with", "the", "max", "of", "tf", ".", "IndexedSlices", "and", "itself", "." ]
def scatter_max(self, sparse_delta, use_locking=False, name=None): """Updates this variable with the max of `tf.IndexedSlices` and itself. Args: sparse_delta: `tf.IndexedSlices` to use as an argument of max with this variable. use_locking: If `True`, use locking during the operation. name: the name of the operation. Returns: A `Tensor` that will hold the new value of this variable after the scattered maximization has completed. Raises: TypeError: if `sparse_delta` is not an `IndexedSlices`. """ if not isinstance(sparse_delta, indexed_slices.IndexedSlices): raise TypeError("sparse_delta is not IndexedSlices: %s" % sparse_delta) return gen_state_ops.scatter_max( self._variable, sparse_delta.indices, sparse_delta.values, use_locking=use_locking, name=name)
[ "def", "scatter_max", "(", "self", ",", "sparse_delta", ",", "use_locking", "=", "False", ",", "name", "=", "None", ")", ":", "if", "not", "isinstance", "(", "sparse_delta", ",", "indexed_slices", ".", "IndexedSlices", ")", ":", "raise", "TypeError", "(", "\"sparse_delta is not IndexedSlices: %s\"", "%", "sparse_delta", ")", "return", "gen_state_ops", ".", "scatter_max", "(", "self", ".", "_variable", ",", "sparse_delta", ".", "indices", ",", "sparse_delta", ".", "values", ",", "use_locking", "=", "use_locking", ",", "name", "=", "name", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/variables.py#L2147-L2170
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/dataset/engine/validators.py
python
check_celebadataset
(method)
return new_method
A wrapper that wraps a parameter checker around the original Dataset(CelebADataset).
A wrapper that wraps a parameter checker around the original Dataset(CelebADataset).
[ "A", "wrapper", "that", "wraps", "a", "parameter", "checker", "around", "the", "original", "Dataset", "(", "CelebADataset", ")", "." ]
def check_celebadataset(method): """A wrapper that wraps a parameter checker around the original Dataset(CelebADataset).""" @wraps(method) def new_method(self, *args, **kwargs): _, param_dict = parse_user_args(method, *args, **kwargs) nreq_param_int = ['num_samples', 'num_parallel_workers', 'num_shards', 'shard_id'] nreq_param_bool = ['shuffle', 'decode'] nreq_param_list = ['extensions'] nreq_param_str = ['dataset_type'] dataset_dir = param_dict.get('dataset_dir') check_dir(dataset_dir) validate_dataset_param_value(nreq_param_int, param_dict, int) validate_dataset_param_value(nreq_param_bool, param_dict, bool) validate_dataset_param_value(nreq_param_list, param_dict, list) validate_dataset_param_value(nreq_param_str, param_dict, str) usage = param_dict.get('usage') if usage is not None and usage not in ('all', 'train', 'valid', 'test'): raise ValueError("usage should be 'all', 'train', 'valid' or 'test'.") check_sampler_shuffle_shard_options(param_dict) sampler = param_dict.get('sampler') if sampler is not None and isinstance(sampler, samplers.PKSampler): raise ValueError("CelebADataset doesn't support PKSampler.") cache = param_dict.get('cache') check_cache_option(cache) return method(self, *args, **kwargs) return new_method
[ "def", "check_celebadataset", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "def", "new_method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_", ",", "param_dict", "=", "parse_user_args", "(", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", "nreq_param_int", "=", "[", "'num_samples'", ",", "'num_parallel_workers'", ",", "'num_shards'", ",", "'shard_id'", "]", "nreq_param_bool", "=", "[", "'shuffle'", ",", "'decode'", "]", "nreq_param_list", "=", "[", "'extensions'", "]", "nreq_param_str", "=", "[", "'dataset_type'", "]", "dataset_dir", "=", "param_dict", ".", "get", "(", "'dataset_dir'", ")", "check_dir", "(", "dataset_dir", ")", "validate_dataset_param_value", "(", "nreq_param_int", ",", "param_dict", ",", "int", ")", "validate_dataset_param_value", "(", "nreq_param_bool", ",", "param_dict", ",", "bool", ")", "validate_dataset_param_value", "(", "nreq_param_list", ",", "param_dict", ",", "list", ")", "validate_dataset_param_value", "(", "nreq_param_str", ",", "param_dict", ",", "str", ")", "usage", "=", "param_dict", ".", "get", "(", "'usage'", ")", "if", "usage", "is", "not", "None", "and", "usage", "not", "in", "(", "'all'", ",", "'train'", ",", "'valid'", ",", "'test'", ")", ":", "raise", "ValueError", "(", "\"usage should be 'all', 'train', 'valid' or 'test'.\"", ")", "check_sampler_shuffle_shard_options", "(", "param_dict", ")", "sampler", "=", "param_dict", ".", "get", "(", "'sampler'", ")", "if", "sampler", "is", "not", "None", "and", "isinstance", "(", "sampler", ",", "samplers", ".", "PKSampler", ")", ":", "raise", "ValueError", "(", "\"CelebADataset doesn't support PKSampler.\"", ")", "cache", "=", "param_dict", ".", "get", "(", "'cache'", ")", "check_cache_option", "(", "cache", ")", "return", "method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "new_method" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/engine/validators.py#L632-L668
telefonicaid/fiware-orion
27c3202b9ddcfb9e3635a0af8d373f76e89b1d24
scripts/cpplint.py
python
GetPreviousNonBlankLine
(clean_lines, linenum)
return ('', -1)
Return the most recent non-blank line and its line number. Args: clean_lines: A CleansedLines instance containing the file contents. linenum: The number of the line to check. Returns: A tuple with two elements. The first element is the contents of the last non-blank line before the current line, or the empty string if this is the first non-blank line. The second is the line number of that line, or -1 if this is the first non-blank line.
Return the most recent non-blank line and its line number.
[ "Return", "the", "most", "recent", "non", "-", "blank", "line", "and", "its", "line", "number", "." ]
def GetPreviousNonBlankLine(clean_lines, linenum): """Return the most recent non-blank line and its line number. Args: clean_lines: A CleansedLines instance containing the file contents. linenum: The number of the line to check. Returns: A tuple with two elements. The first element is the contents of the last non-blank line before the current line, or the empty string if this is the first non-blank line. The second is the line number of that line, or -1 if this is the first non-blank line. """ prevlinenum = linenum - 1 while prevlinenum >= 0: prevline = clean_lines.elided[prevlinenum] if not IsBlankLine(prevline): # if not a blank line... return (prevline, prevlinenum) prevlinenum -= 1 return ('', -1)
[ "def", "GetPreviousNonBlankLine", "(", "clean_lines", ",", "linenum", ")", ":", "prevlinenum", "=", "linenum", "-", "1", "while", "prevlinenum", ">=", "0", ":", "prevline", "=", "clean_lines", ".", "elided", "[", "prevlinenum", "]", "if", "not", "IsBlankLine", "(", "prevline", ")", ":", "# if not a blank line...", "return", "(", "prevline", ",", "prevlinenum", ")", "prevlinenum", "-=", "1", "return", "(", "''", ",", "-", "1", ")" ]
https://github.com/telefonicaid/fiware-orion/blob/27c3202b9ddcfb9e3635a0af8d373f76e89b1d24/scripts/cpplint.py#L1970-L1990
bundy-dns/bundy
3d41934996b82b0cd2fe22dd74d2abc1daba835d
src/lib/python/bundy/bundy/component.py
python
BaseComponent.set_restart_time
(self)
Calculates and sets the time this component should be restarted. Currently, it uses a very basic algorithm; start time + RESTART_DELAY (10 seconds). This algorithm may be improved upon in the future.
Calculates and sets the time this component should be restarted. Currently, it uses a very basic algorithm; start time + RESTART_DELAY (10 seconds). This algorithm may be improved upon in the future.
[ "Calculates", "and", "sets", "the", "time", "this", "component", "should", "be", "restarted", ".", "Currently", "it", "uses", "a", "very", "basic", "algorithm", ";", "start", "time", "+", "RESTART_DELAY", "(", "10", "seconds", ")", ".", "This", "algorithm", "may", "be", "improved", "upon", "in", "the", "future", "." ]
def set_restart_time(self): """Calculates and sets the time this component should be restarted. Currently, it uses a very basic algorithm; start time + RESTART_DELAY (10 seconds). This algorithm may be improved upon in the future. """ self._restart_at = self.__start_time + COMPONENT_RESTART_DELAY
[ "def", "set_restart_time", "(", "self", ")", ":", "self", ".", "_restart_at", "=", "self", ".", "__start_time", "+", "COMPONENT_RESTART_DELAY" ]
https://github.com/bundy-dns/bundy/blob/3d41934996b82b0cd2fe22dd74d2abc1daba835d/src/lib/python/bundy/bundy/component.py#L267-L273
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/distutils/text_file.py
python
TextFile.unreadline
(self, line)
Push 'line' (a string) onto an internal buffer that will be checked by future 'readline()' calls. Handy for implementing a parser with line-at-a-time lookahead.
Push 'line' (a string) onto an internal buffer that will be checked by future 'readline()' calls. Handy for implementing a parser with line-at-a-time lookahead.
[ "Push", "line", "(", "a", "string", ")", "onto", "an", "internal", "buffer", "that", "will", "be", "checked", "by", "future", "readline", "()", "calls", ".", "Handy", "for", "implementing", "a", "parser", "with", "line", "-", "at", "-", "a", "-", "time", "lookahead", "." ]
def unreadline (self, line): """Push 'line' (a string) onto an internal buffer that will be checked by future 'readline()' calls. Handy for implementing a parser with line-at-a-time lookahead.""" self.linebuf.append (line)
[ "def", "unreadline", "(", "self", ",", "line", ")", ":", "self", ".", "linebuf", ".", "append", "(", "line", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/distutils/text_file.py#L299-L304
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/interpolate/interpolate.py
python
_do_extrapolate
(fill_value)
return (isinstance(fill_value, string_types) and fill_value == 'extrapolate')
Helper to check if fill_value == "extrapolate" without warnings
Helper to check if fill_value == "extrapolate" without warnings
[ "Helper", "to", "check", "if", "fill_value", "==", "extrapolate", "without", "warnings" ]
def _do_extrapolate(fill_value): """Helper to check if fill_value == "extrapolate" without warnings""" return (isinstance(fill_value, string_types) and fill_value == 'extrapolate')
[ "def", "_do_extrapolate", "(", "fill_value", ")", ":", "return", "(", "isinstance", "(", "fill_value", ",", "string_types", ")", "and", "fill_value", "==", "'extrapolate'", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/interpolate/interpolate.py#L339-L342
shedskin/shedskin
ae88dbca7b1d9671cd8be448cb0b497122758936
examples/block.py
python
findprobs
(f=0.01,N=6)
return answer
Find probabilities of all the events 000000 000001 ... 111111 <-N -> >>> print findprobs(0.1,3) # doctest:+ELLIPSIS [('000', 0.7...),..., ('111', 0.001...)]
Find probabilities of all the events 000000 000001 ... 111111 <-N -> >>> print findprobs(0.1,3) # doctest:+ELLIPSIS [('000', 0.7...),..., ('111', 0.001...)]
[ "Find", "probabilities", "of", "all", "the", "events", "000000", "000001", "...", "111111", "<", "-", "N", "-", ">", ">>>", "print", "findprobs", "(", "0", ".", "1", "3", ")", "#", "doctest", ":", "+", "ELLIPSIS", "[", "(", "000", "0", ".", "7", "...", ")", "...", "(", "111", "0", ".", "001", "...", ")", "]" ]
def findprobs(f=0.01,N=6): """ Find probabilities of all the events 000000 000001 ... 111111 <-N -> >>> print findprobs(0.1,3) # doctest:+ELLIPSIS [('000', 0.7...),..., ('111', 0.001...)] """ answer = [] for n in range(2**N): s = dec_to_bin(n,N) (w0,w1) = weight(s) if verbose and 0 : print s,w0,w1 answer.append( (s, f**w1 * (1-f)**w0 ) ) pass assert ( len(answer) == 2**N ) return answer
[ "def", "findprobs", "(", "f", "=", "0.01", ",", "N", "=", "6", ")", ":", "answer", "=", "[", "]", "for", "n", "in", "range", "(", "2", "**", "N", ")", ":", "s", "=", "dec_to_bin", "(", "n", ",", "N", ")", "(", "w0", ",", "w1", ")", "=", "weight", "(", "s", ")", "if", "verbose", "and", "0", ":", "print", "s", ",", "w0", ",", "w1", "answer", ".", "append", "(", "(", "s", ",", "f", "**", "w1", "*", "(", "1", "-", "f", ")", "**", "w0", ")", ")", "pass", "assert", "(", "len", "(", "answer", ")", "==", "2", "**", "N", ")", "return", "answer" ]
https://github.com/shedskin/shedskin/blob/ae88dbca7b1d9671cd8be448cb0b497122758936/examples/block.py#L265-L284
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/_vendor/ordered_set.py
python
OrderedSet.union
(self, *sets)
return cls(items)
Combines all unique items. Each items order is defined by its first appearance. Example: >>> oset = OrderedSet.union(OrderedSet([3, 1, 4, 1, 5]), [1, 3], [2, 0]) >>> print(oset) OrderedSet([3, 1, 4, 5, 2, 0]) >>> oset.union([8, 9]) OrderedSet([3, 1, 4, 5, 2, 0, 8, 9]) >>> oset | {10} OrderedSet([3, 1, 4, 5, 2, 0, 10])
Combines all unique items. Each items order is defined by its first appearance.
[ "Combines", "all", "unique", "items", ".", "Each", "items", "order", "is", "defined", "by", "its", "first", "appearance", "." ]
def union(self, *sets): """ Combines all unique items. Each items order is defined by its first appearance. Example: >>> oset = OrderedSet.union(OrderedSet([3, 1, 4, 1, 5]), [1, 3], [2, 0]) >>> print(oset) OrderedSet([3, 1, 4, 5, 2, 0]) >>> oset.union([8, 9]) OrderedSet([3, 1, 4, 5, 2, 0, 8, 9]) >>> oset | {10} OrderedSet([3, 1, 4, 5, 2, 0, 10]) """ cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet containers = map(list, it.chain([self], sets)) items = it.chain.from_iterable(containers) return cls(items)
[ "def", "union", "(", "self", ",", "*", "sets", ")", ":", "cls", "=", "self", ".", "__class__", "if", "isinstance", "(", "self", ",", "OrderedSet", ")", "else", "OrderedSet", "containers", "=", "map", "(", "list", ",", "it", ".", "chain", "(", "[", "self", "]", ",", "sets", ")", ")", "items", "=", "it", ".", "chain", ".", "from_iterable", "(", "containers", ")", "return", "cls", "(", "items", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/_vendor/ordered_set.py#L310-L327
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/scripts/exomerge2.py
python
ExodusModel.get_side_set_ids
(self)
return sorted(self.side_sets.keys())
Return a list of all side set ids. Example: >>> model.get_side_set_ids()
Return a list of all side set ids.
[ "Return", "a", "list", "of", "all", "side", "set", "ids", "." ]
def get_side_set_ids(self): """ Return a list of all side set ids. Example: >>> model.get_side_set_ids() """ return sorted(self.side_sets.keys())
[ "def", "get_side_set_ids", "(", "self", ")", ":", "return", "sorted", "(", "self", ".", "side_sets", ".", "keys", "(", ")", ")" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge2.py#L3310-L3318
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/http/server.py
python
BaseHTTPRequestHandler.handle_one_request
(self)
Handle a single HTTP request. You normally don't need to override this method; see the class __doc__ string for information on how to handle specific HTTP commands such as GET and POST.
Handle a single HTTP request.
[ "Handle", "a", "single", "HTTP", "request", "." ]
def handle_one_request(self): """Handle a single HTTP request. You normally don't need to override this method; see the class __doc__ string for information on how to handle specific HTTP commands such as GET and POST. """ try: self.raw_requestline = self.rfile.readline(65537) if len(self.raw_requestline) > 65536: self.requestline = '' self.request_version = '' self.command = '' self.send_error(HTTPStatus.REQUEST_URI_TOO_LONG) return if not self.raw_requestline: self.close_connection = True return if not self.parse_request(): # An error code has been sent, just exit return mname = 'do_' + self.command if not hasattr(self, mname): self.send_error( HTTPStatus.NOT_IMPLEMENTED, "Unsupported method (%r)" % self.command) return method = getattr(self, mname) method() self.wfile.flush() #actually send the response if not already done. except socket.timeout as e: #a read or a write timed out. Discard this connection self.log_error("Request timed out: %r", e) self.close_connection = True return
[ "def", "handle_one_request", "(", "self", ")", ":", "try", ":", "self", ".", "raw_requestline", "=", "self", ".", "rfile", ".", "readline", "(", "65537", ")", "if", "len", "(", "self", ".", "raw_requestline", ")", ">", "65536", ":", "self", ".", "requestline", "=", "''", "self", ".", "request_version", "=", "''", "self", ".", "command", "=", "''", "self", ".", "send_error", "(", "HTTPStatus", ".", "REQUEST_URI_TOO_LONG", ")", "return", "if", "not", "self", ".", "raw_requestline", ":", "self", ".", "close_connection", "=", "True", "return", "if", "not", "self", ".", "parse_request", "(", ")", ":", "# An error code has been sent, just exit", "return", "mname", "=", "'do_'", "+", "self", ".", "command", "if", "not", "hasattr", "(", "self", ",", "mname", ")", ":", "self", ".", "send_error", "(", "HTTPStatus", ".", "NOT_IMPLEMENTED", ",", "\"Unsupported method (%r)\"", "%", "self", ".", "command", ")", "return", "method", "=", "getattr", "(", "self", ",", "mname", ")", "method", "(", ")", "self", ".", "wfile", ".", "flush", "(", ")", "#actually send the response if not already done.", "except", "socket", ".", "timeout", "as", "e", ":", "#a read or a write timed out. Discard this connection", "self", ".", "log_error", "(", "\"Request timed out: %r\"", ",", "e", ")", "self", ".", "close_connection", "=", "True", "return" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/http/server.py#L386-L421
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/qcdb/dbwrap.py
python
Database.compute_statistics
(self, modelchem, benchmark='default', sset='default', failoninc=True, verbose=False, returnindiv=False)
Computes summary statistics and, if *returnindiv* True, individual errors for single model chemistry *modelchem* versus *benchmark* over subset *sset* over all component databases. Particularly, imposes cross-database definitions for sset and modelchem. #Returns error if model chemistries are missing #for any reaction in subset unless *failoninc* set to False, #whereupon returns partial statistics. Returns dictionary of #statistics labels and values.
Computes summary statistics and, if *returnindiv* True, individual errors for single model chemistry *modelchem* versus *benchmark* over subset *sset* over all component databases. Particularly, imposes cross-database definitions for sset and modelchem. #Returns error if model chemistries are missing #for any reaction in subset unless *failoninc* set to False, #whereupon returns partial statistics. Returns dictionary of #statistics labels and values.
[ "Computes", "summary", "statistics", "and", "if", "*", "returnindiv", "*", "True", "individual", "errors", "for", "single", "model", "chemistry", "*", "modelchem", "*", "versus", "*", "benchmark", "*", "over", "subset", "*", "sset", "*", "over", "all", "component", "databases", ".", "Particularly", "imposes", "cross", "-", "database", "definitions", "for", "sset", "and", "modelchem", ".", "#Returns", "error", "if", "model", "chemistries", "are", "missing", "#for", "any", "reaction", "in", "subset", "unless", "*", "failoninc", "*", "set", "to", "False", "#whereupon", "returns", "partial", "statistics", ".", "Returns", "dictionary", "of", "#statistics", "labels", "and", "values", "." ]
def compute_statistics(self, modelchem, benchmark='default', sset='default', failoninc=True, verbose=False, returnindiv=False): """Computes summary statistics and, if *returnindiv* True, individual errors for single model chemistry *modelchem* versus *benchmark* over subset *sset* over all component databases. Particularly, imposes cross-database definitions for sset and modelchem. #Returns error if model chemistries are missing #for any reaction in subset unless *failoninc* set to False, #whereupon returns partial statistics. Returns dictionary of #statistics labels and values. """ errors = OrderedDict() indiv = OrderedDict() actvdb = [] for db, odb in self.dbdict.items(): dbix = self.dbdict.keys().index(db) if self.sset[sset][dbix] is None: errors[db], indiv[db] = (None, None) else: errors[db], indiv[db] = odb.compute_statistics(self.mcs[modelchem][dbix], sset=self.sset[sset][dbix], benchmark='ZEROS' if benchmark == 'ZEROS' else self.mcs[benchmark][dbix], failoninc=failoninc, verbose=verbose, returnindiv=True) actvdb.append(errors[db]) errors[self.dbse] = average_errors(*actvdb) if returnindiv: return errors, indiv else: return errors
[ "def", "compute_statistics", "(", "self", ",", "modelchem", ",", "benchmark", "=", "'default'", ",", "sset", "=", "'default'", ",", "failoninc", "=", "True", ",", "verbose", "=", "False", ",", "returnindiv", "=", "False", ")", ":", "errors", "=", "OrderedDict", "(", ")", "indiv", "=", "OrderedDict", "(", ")", "actvdb", "=", "[", "]", "for", "db", ",", "odb", "in", "self", ".", "dbdict", ".", "items", "(", ")", ":", "dbix", "=", "self", ".", "dbdict", ".", "keys", "(", ")", ".", "index", "(", "db", ")", "if", "self", ".", "sset", "[", "sset", "]", "[", "dbix", "]", "is", "None", ":", "errors", "[", "db", "]", ",", "indiv", "[", "db", "]", "=", "(", "None", ",", "None", ")", "else", ":", "errors", "[", "db", "]", ",", "indiv", "[", "db", "]", "=", "odb", ".", "compute_statistics", "(", "self", ".", "mcs", "[", "modelchem", "]", "[", "dbix", "]", ",", "sset", "=", "self", ".", "sset", "[", "sset", "]", "[", "dbix", "]", ",", "benchmark", "=", "'ZEROS'", "if", "benchmark", "==", "'ZEROS'", "else", "self", ".", "mcs", "[", "benchmark", "]", "[", "dbix", "]", ",", "failoninc", "=", "failoninc", ",", "verbose", "=", "verbose", ",", "returnindiv", "=", "True", ")", "actvdb", ".", "append", "(", "errors", "[", "db", "]", ")", "errors", "[", "self", ".", "dbse", "]", "=", "average_errors", "(", "*", "actvdb", ")", "if", "returnindiv", ":", "return", "errors", ",", "indiv", "else", ":", "return", "errors" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/dbwrap.py#L1659-L1690
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBStream.write
(self, *args)
return _lldb.SBStream_write(self, *args)
write(self, str str)
write(self, str str)
[ "write", "(", "self", "str", "str", ")" ]
def write(self, *args): """write(self, str str)""" return _lldb.SBStream_write(self, *args)
[ "def", "write", "(", "self", ",", "*", "args", ")", ":", "return", "_lldb", ".", "SBStream_write", "(", "self", ",", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L7965-L7967
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/contrib/onnx/mx2onnx/_op_translations.py
python
convert_concat
(node, **kwargs)
return [concat_node]
Map MXNet's Concat operator attributes to onnx's Concat operator and return the created node.
Map MXNet's Concat operator attributes to onnx's Concat operator and return the created node.
[ "Map", "MXNet", "s", "Concat", "operator", "attributes", "to", "onnx", "s", "Concat", "operator", "and", "return", "the", "created", "node", "." ]
def convert_concat(node, **kwargs): """Map MXNet's Concat operator attributes to onnx's Concat operator and return the created node. """ name, input_nodes, attrs = get_inputs(node, kwargs) axis = int(attrs.get("dim", 1)) concat_node = onnx.helper.make_node( "Concat", input_nodes, [name], axis=axis, name=name ) return [concat_node]
[ "def", "convert_concat", "(", "node", ",", "*", "*", "kwargs", ")", ":", "name", ",", "input_nodes", ",", "attrs", "=", "get_inputs", "(", "node", ",", "kwargs", ")", "axis", "=", "int", "(", "attrs", ".", "get", "(", "\"dim\"", ",", "1", ")", ")", "concat_node", "=", "onnx", ".", "helper", ".", "make_node", "(", "\"Concat\"", ",", "input_nodes", ",", "[", "name", "]", ",", "axis", "=", "axis", ",", "name", "=", "name", ")", "return", "[", "concat_node", "]" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/contrib/onnx/mx2onnx/_op_translations.py#L851-L865
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/platform.py
python
version
()
return uname().version
Returns the system's release version, e.g. '#3 on degas' An empty string is returned if the value cannot be determined.
Returns the system's release version, e.g. '#3 on degas'
[ "Returns", "the", "system", "s", "release", "version", "e", ".", "g", ".", "#3", "on", "degas" ]
def version(): """ Returns the system's release version, e.g. '#3 on degas' An empty string is returned if the value cannot be determined. """ return uname().version
[ "def", "version", "(", ")", ":", "return", "uname", "(", ")", ".", "version" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/platform.py#L1089-L1096
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/logging/__init__.py
python
_StderrHandler.__init__
(self, level=NOTSET)
Initialize the handler.
Initialize the handler.
[ "Initialize", "the", "handler", "." ]
def __init__(self, level=NOTSET): """ Initialize the handler. """ Handler.__init__(self, level)
[ "def", "__init__", "(", "self", ",", "level", "=", "NOTSET", ")", ":", "Handler", ".", "__init__", "(", "self", ",", "level", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/logging/__init__.py#L1200-L1204
modm-io/modm
845840ec08566a3aa9c04167b1a18a56255afa4f
tools/xpcc_generator/builder/generate_include_graph.py
python
IncludePathBuilder.find_includes
(self, file, include_path)
return files
Find include directives in an XML file
Find include directives in an XML file
[ "Find", "include", "directives", "in", "an", "XML", "file" ]
def find_includes(self, file, include_path): """ Find include directives in an XML file """ includeExpression = re.compile(r'<include>(\S+)</include>', re.M) files = [] line_count = 0 for line in open(file).readlines(): line_count = line_count + 1 match = includeExpression.search(line) if match: try: filename = Parser.find_include_file( match.group(1), os.path.abspath(file), self.include_paths, str(line_count)) except ParserException as e: raise builder_base.BuilderException(e.message) files.append(filename) return files
[ "def", "find_includes", "(", "self", ",", "file", ",", "include_path", ")", ":", "includeExpression", "=", "re", ".", "compile", "(", "r'<include>(\\S+)</include>'", ",", "re", ".", "M", ")", "files", "=", "[", "]", "line_count", "=", "0", "for", "line", "in", "open", "(", "file", ")", ".", "readlines", "(", ")", ":", "line_count", "=", "line_count", "+", "1", "match", "=", "includeExpression", ".", "search", "(", "line", ")", "if", "match", ":", "try", ":", "filename", "=", "Parser", ".", "find_include_file", "(", "match", ".", "group", "(", "1", ")", ",", "os", ".", "path", ".", "abspath", "(", "file", ")", ",", "self", ".", "include_paths", ",", "str", "(", "line_count", ")", ")", "except", "ParserException", "as", "e", ":", "raise", "builder_base", ".", "BuilderException", "(", "e", ".", "message", ")", "files", ".", "append", "(", "filename", ")", "return", "files" ]
https://github.com/modm-io/modm/blob/845840ec08566a3aa9c04167b1a18a56255afa4f/tools/xpcc_generator/builder/generate_include_graph.py#L89-L108