partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
CompletionWidget.eventFilter
Reimplemented to handle keyboard input and to auto-hide when the text edit loses focus.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_widget.py
def eventFilter(self, obj, event): """ Reimplemented to handle keyboard input and to auto-hide when the text edit loses focus. """ if obj == self._text_edit: etype = event.type() if etype == QtCore.QEvent.KeyPress: key, text = event.key(), event.text() if key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter, QtCore.Qt.Key_Tab): self._complete_current() return True elif key == QtCore.Qt.Key_Escape: self.hide() return True elif key in (QtCore.Qt.Key_Up, QtCore.Qt.Key_Down, QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown, QtCore.Qt.Key_Home, QtCore.Qt.Key_End): self.keyPressEvent(event) return True elif etype == QtCore.QEvent.FocusOut: self.hide() return super(CompletionWidget, self).eventFilter(obj, event)
def eventFilter(self, obj, event): """ Reimplemented to handle keyboard input and to auto-hide when the text edit loses focus. """ if obj == self._text_edit: etype = event.type() if etype == QtCore.QEvent.KeyPress: key, text = event.key(), event.text() if key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter, QtCore.Qt.Key_Tab): self._complete_current() return True elif key == QtCore.Qt.Key_Escape: self.hide() return True elif key in (QtCore.Qt.Key_Up, QtCore.Qt.Key_Down, QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown, QtCore.Qt.Key_Home, QtCore.Qt.Key_End): self.keyPressEvent(event) return True elif etype == QtCore.QEvent.FocusOut: self.hide() return super(CompletionWidget, self).eventFilter(obj, event)
[ "Reimplemented", "to", "handle", "keyboard", "input", "and", "to", "auto", "-", "hide", "when", "the", "text", "edit", "loses", "focus", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_widget.py#L34-L59
[ "def", "eventFilter", "(", "self", ",", "obj", ",", "event", ")", ":", "if", "obj", "==", "self", ".", "_text_edit", ":", "etype", "=", "event", ".", "type", "(", ")", "if", "etype", "==", "QtCore", ".", "QEvent", ".", "KeyPress", ":", "key", ",", "text", "=", "event", ".", "key", "(", ")", ",", "event", ".", "text", "(", ")", "if", "key", "in", "(", "QtCore", ".", "Qt", ".", "Key_Return", ",", "QtCore", ".", "Qt", ".", "Key_Enter", ",", "QtCore", ".", "Qt", ".", "Key_Tab", ")", ":", "self", ".", "_complete_current", "(", ")", "return", "True", "elif", "key", "==", "QtCore", ".", "Qt", ".", "Key_Escape", ":", "self", ".", "hide", "(", ")", "return", "True", "elif", "key", "in", "(", "QtCore", ".", "Qt", ".", "Key_Up", ",", "QtCore", ".", "Qt", ".", "Key_Down", ",", "QtCore", ".", "Qt", ".", "Key_PageUp", ",", "QtCore", ".", "Qt", ".", "Key_PageDown", ",", "QtCore", ".", "Qt", ".", "Key_Home", ",", "QtCore", ".", "Qt", ".", "Key_End", ")", ":", "self", ".", "keyPressEvent", "(", "event", ")", "return", "True", "elif", "etype", "==", "QtCore", ".", "QEvent", ".", "FocusOut", ":", "self", ".", "hide", "(", ")", "return", "super", "(", "CompletionWidget", ",", "self", ")", ".", "eventFilter", "(", "obj", ",", "event", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CompletionWidget.hideEvent
Reimplemented to disconnect signal handlers and event filter.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_widget.py
def hideEvent(self, event): """ Reimplemented to disconnect signal handlers and event filter. """ super(CompletionWidget, self).hideEvent(event) self._text_edit.cursorPositionChanged.disconnect(self._update_current) self._text_edit.removeEventFilter(self)
def hideEvent(self, event): """ Reimplemented to disconnect signal handlers and event filter. """ super(CompletionWidget, self).hideEvent(event) self._text_edit.cursorPositionChanged.disconnect(self._update_current) self._text_edit.removeEventFilter(self)
[ "Reimplemented", "to", "disconnect", "signal", "handlers", "and", "event", "filter", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_widget.py#L65-L70
[ "def", "hideEvent", "(", "self", ",", "event", ")", ":", "super", "(", "CompletionWidget", ",", "self", ")", ".", "hideEvent", "(", "event", ")", "self", ".", "_text_edit", ".", "cursorPositionChanged", ".", "disconnect", "(", "self", ".", "_update_current", ")", "self", ".", "_text_edit", ".", "removeEventFilter", "(", "self", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CompletionWidget.showEvent
Reimplemented to connect signal handlers and event filter.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_widget.py
def showEvent(self, event): """ Reimplemented to connect signal handlers and event filter. """ super(CompletionWidget, self).showEvent(event) self._text_edit.cursorPositionChanged.connect(self._update_current) self._text_edit.installEventFilter(self)
def showEvent(self, event): """ Reimplemented to connect signal handlers and event filter. """ super(CompletionWidget, self).showEvent(event) self._text_edit.cursorPositionChanged.connect(self._update_current) self._text_edit.installEventFilter(self)
[ "Reimplemented", "to", "connect", "signal", "handlers", "and", "event", "filter", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_widget.py#L72-L77
[ "def", "showEvent", "(", "self", ",", "event", ")", ":", "super", "(", "CompletionWidget", ",", "self", ")", ".", "showEvent", "(", "event", ")", "self", ".", "_text_edit", ".", "cursorPositionChanged", ".", "connect", "(", "self", ".", "_update_current", ")", "self", ".", "_text_edit", ".", "installEventFilter", "(", "self", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CompletionWidget.show_items
Shows the completion widget with 'items' at the position specified by 'cursor'.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_widget.py
def show_items(self, cursor, items): """ Shows the completion widget with 'items' at the position specified by 'cursor'. """ text_edit = self._text_edit point = text_edit.cursorRect(cursor).bottomRight() point = text_edit.mapToGlobal(point) height = self.sizeHint().height() screen_rect = QtGui.QApplication.desktop().availableGeometry(self) if screen_rect.size().height() - point.y() - height < 0: point = text_edit.mapToGlobal(text_edit.cursorRect().topRight()) point.setY(point.y() - height) self.move(point) self._start_position = cursor.position() self.clear() self.addItems(items) self.setCurrentRow(0) self.show()
def show_items(self, cursor, items): """ Shows the completion widget with 'items' at the position specified by 'cursor'. """ text_edit = self._text_edit point = text_edit.cursorRect(cursor).bottomRight() point = text_edit.mapToGlobal(point) height = self.sizeHint().height() screen_rect = QtGui.QApplication.desktop().availableGeometry(self) if screen_rect.size().height() - point.y() - height < 0: point = text_edit.mapToGlobal(text_edit.cursorRect().topRight()) point.setY(point.y() - height) self.move(point) self._start_position = cursor.position() self.clear() self.addItems(items) self.setCurrentRow(0) self.show()
[ "Shows", "the", "completion", "widget", "with", "items", "at", "the", "position", "specified", "by", "cursor", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_widget.py#L83-L101
[ "def", "show_items", "(", "self", ",", "cursor", ",", "items", ")", ":", "text_edit", "=", "self", ".", "_text_edit", "point", "=", "text_edit", ".", "cursorRect", "(", "cursor", ")", ".", "bottomRight", "(", ")", "point", "=", "text_edit", ".", "mapToGlobal", "(", "point", ")", "height", "=", "self", ".", "sizeHint", "(", ")", ".", "height", "(", ")", "screen_rect", "=", "QtGui", ".", "QApplication", ".", "desktop", "(", ")", ".", "availableGeometry", "(", "self", ")", "if", "screen_rect", ".", "size", "(", ")", ".", "height", "(", ")", "-", "point", ".", "y", "(", ")", "-", "height", "<", "0", ":", "point", "=", "text_edit", ".", "mapToGlobal", "(", "text_edit", ".", "cursorRect", "(", ")", ".", "topRight", "(", ")", ")", "point", ".", "setY", "(", "point", ".", "y", "(", ")", "-", "height", ")", "self", ".", "move", "(", "point", ")", "self", ".", "_start_position", "=", "cursor", ".", "position", "(", ")", "self", ".", "clear", "(", ")", "self", ".", "addItems", "(", "items", ")", "self", ".", "setCurrentRow", "(", "0", ")", "self", ".", "show", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CompletionWidget._complete_current
Perform the completion with the currently selected item.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_widget.py
def _complete_current(self): """ Perform the completion with the currently selected item. """ self._current_text_cursor().insertText(self.currentItem().text()) self.hide()
def _complete_current(self): """ Perform the completion with the currently selected item. """ self._current_text_cursor().insertText(self.currentItem().text()) self.hide()
[ "Perform", "the", "completion", "with", "the", "currently", "selected", "item", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_widget.py#L107-L111
[ "def", "_complete_current", "(", "self", ")", ":", "self", ".", "_current_text_cursor", "(", ")", ".", "insertText", "(", "self", ".", "currentItem", "(", ")", ".", "text", "(", ")", ")", "self", ".", "hide", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CompletionWidget._current_text_cursor
Returns a cursor with text between the start position and the current position selected.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_widget.py
def _current_text_cursor(self): """ Returns a cursor with text between the start position and the current position selected. """ cursor = self._text_edit.textCursor() if cursor.position() >= self._start_position: cursor.setPosition(self._start_position, QtGui.QTextCursor.KeepAnchor) return cursor
def _current_text_cursor(self): """ Returns a cursor with text between the start position and the current position selected. """ cursor = self._text_edit.textCursor() if cursor.position() >= self._start_position: cursor.setPosition(self._start_position, QtGui.QTextCursor.KeepAnchor) return cursor
[ "Returns", "a", "cursor", "with", "text", "between", "the", "start", "position", "and", "the", "current", "position", "selected", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_widget.py#L113-L121
[ "def", "_current_text_cursor", "(", "self", ")", ":", "cursor", "=", "self", ".", "_text_edit", ".", "textCursor", "(", ")", "if", "cursor", ".", "position", "(", ")", ">=", "self", ".", "_start_position", ":", "cursor", ".", "setPosition", "(", "self", ".", "_start_position", ",", "QtGui", ".", "QTextCursor", ".", "KeepAnchor", ")", "return", "cursor" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CompletionWidget._update_current
Updates the current item based on the current text.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_widget.py
def _update_current(self): """ Updates the current item based on the current text. """ prefix = self._current_text_cursor().selection().toPlainText() if prefix: items = self.findItems(prefix, (QtCore.Qt.MatchStartsWith | QtCore.Qt.MatchCaseSensitive)) if items: self.setCurrentItem(items[0]) else: self.hide() else: self.hide()
def _update_current(self): """ Updates the current item based on the current text. """ prefix = self._current_text_cursor().selection().toPlainText() if prefix: items = self.findItems(prefix, (QtCore.Qt.MatchStartsWith | QtCore.Qt.MatchCaseSensitive)) if items: self.setCurrentItem(items[0]) else: self.hide() else: self.hide()
[ "Updates", "the", "current", "item", "based", "on", "the", "current", "text", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_widget.py#L123-L135
[ "def", "_update_current", "(", "self", ")", ":", "prefix", "=", "self", ".", "_current_text_cursor", "(", ")", ".", "selection", "(", ")", ".", "toPlainText", "(", ")", "if", "prefix", ":", "items", "=", "self", ".", "findItems", "(", "prefix", ",", "(", "QtCore", ".", "Qt", ".", "MatchStartsWith", "|", "QtCore", ".", "Qt", ".", "MatchCaseSensitive", ")", ")", "if", "items", ":", "self", ".", "setCurrentItem", "(", "items", "[", "0", "]", ")", "else", ":", "self", ".", "hide", "(", ")", "else", ":", "self", ".", "hide", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
registerAdminSite
Registers the models of the app with the given "appName" for the admin site
django_tooling/registeradmin.py
def registerAdminSite(appName, excludeModels=[]): """Registers the models of the app with the given "appName" for the admin site""" for model in apps.get_app_config(appName).get_models(): if model not in excludeModels: admin.site.register(model)
def registerAdminSite(appName, excludeModels=[]): """Registers the models of the app with the given "appName" for the admin site""" for model in apps.get_app_config(appName).get_models(): if model not in excludeModels: admin.site.register(model)
[ "Registers", "the", "models", "of", "the", "app", "with", "the", "given", "appName", "for", "the", "admin", "site" ]
seebass/django-tooling
python
https://github.com/seebass/django-tooling/blob/aaee703040b299cae560c501c94b18e0c2620f0d/django_tooling/registeradmin.py#L5-L9
[ "def", "registerAdminSite", "(", "appName", ",", "excludeModels", "=", "[", "]", ")", ":", "for", "model", "in", "apps", ".", "get_app_config", "(", "appName", ")", ".", "get_models", "(", ")", ":", "if", "model", "not", "in", "excludeModels", ":", "admin", ".", "site", ".", "register", "(", "model", ")" ]
aaee703040b299cae560c501c94b18e0c2620f0d
test
virtual_memory
System virtual memory as a namedtuple.
environment/lib/python2.7/site-packages/psutil/_psmswindows.py
def virtual_memory(): """System virtual memory as a namedtuple.""" mem = _psutil_mswindows.get_virtual_mem() totphys, availphys, totpagef, availpagef, totvirt, freevirt = mem # total = totphys avail = availphys free = availphys used = total - avail percent = usage_percent((total - avail), total, _round=1) return nt_virtmem_info(total, avail, percent, used, free)
def virtual_memory(): """System virtual memory as a namedtuple.""" mem = _psutil_mswindows.get_virtual_mem() totphys, availphys, totpagef, availpagef, totvirt, freevirt = mem # total = totphys avail = availphys free = availphys used = total - avail percent = usage_percent((total - avail), total, _round=1) return nt_virtmem_info(total, avail, percent, used, free)
[ "System", "virtual", "memory", "as", "a", "namedtuple", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psmswindows.py#L67-L77
[ "def", "virtual_memory", "(", ")", ":", "mem", "=", "_psutil_mswindows", ".", "get_virtual_mem", "(", ")", "totphys", ",", "availphys", ",", "totpagef", ",", "availpagef", ",", "totvirt", ",", "freevirt", "=", "mem", "#", "total", "=", "totphys", "avail", "=", "availphys", "free", "=", "availphys", "used", "=", "total", "-", "avail", "percent", "=", "usage_percent", "(", "(", "total", "-", "avail", ")", ",", "total", ",", "_round", "=", "1", ")", "return", "nt_virtmem_info", "(", "total", ",", "avail", ",", "percent", ",", "used", ",", "free", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
swap_memory
Swap system memory as a (total, used, free, sin, sout) tuple.
environment/lib/python2.7/site-packages/psutil/_psmswindows.py
def swap_memory(): """Swap system memory as a (total, used, free, sin, sout) tuple.""" mem = _psutil_mswindows.get_virtual_mem() total = mem[2] free = mem[3] used = total - free percent = usage_percent(used, total, _round=1) return nt_swapmeminfo(total, used, free, percent, 0, 0)
def swap_memory(): """Swap system memory as a (total, used, free, sin, sout) tuple.""" mem = _psutil_mswindows.get_virtual_mem() total = mem[2] free = mem[3] used = total - free percent = usage_percent(used, total, _round=1) return nt_swapmeminfo(total, used, free, percent, 0, 0)
[ "Swap", "system", "memory", "as", "a", "(", "total", "used", "free", "sin", "sout", ")", "tuple", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psmswindows.py#L79-L86
[ "def", "swap_memory", "(", ")", ":", "mem", "=", "_psutil_mswindows", ".", "get_virtual_mem", "(", ")", "total", "=", "mem", "[", "2", "]", "free", "=", "mem", "[", "3", "]", "used", "=", "total", "-", "free", "percent", "=", "usage_percent", "(", "used", ",", "total", ",", "_round", "=", "1", ")", "return", "nt_swapmeminfo", "(", "total", ",", "used", ",", "free", ",", "percent", ",", "0", ",", "0", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
get_disk_usage
Return disk usage associated with path.
environment/lib/python2.7/site-packages/psutil/_psmswindows.py
def get_disk_usage(path): """Return disk usage associated with path.""" try: total, free = _psutil_mswindows.get_disk_usage(path) except WindowsError: err = sys.exc_info()[1] if not os.path.exists(path): raise OSError(errno.ENOENT, "No such file or directory: '%s'" % path) raise used = total - free percent = usage_percent(used, total, _round=1) return nt_diskinfo(total, used, free, percent)
def get_disk_usage(path): """Return disk usage associated with path.""" try: total, free = _psutil_mswindows.get_disk_usage(path) except WindowsError: err = sys.exc_info()[1] if not os.path.exists(path): raise OSError(errno.ENOENT, "No such file or directory: '%s'" % path) raise used = total - free percent = usage_percent(used, total, _round=1) return nt_diskinfo(total, used, free, percent)
[ "Return", "disk", "usage", "associated", "with", "path", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psmswindows.py#L88-L99
[ "def", "get_disk_usage", "(", "path", ")", ":", "try", ":", "total", ",", "free", "=", "_psutil_mswindows", ".", "get_disk_usage", "(", "path", ")", "except", "WindowsError", ":", "err", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "OSError", "(", "errno", ".", "ENOENT", ",", "\"No such file or directory: '%s'\"", "%", "path", ")", "raise", "used", "=", "total", "-", "free", "percent", "=", "usage_percent", "(", "used", ",", "total", ",", "_round", "=", "1", ")", "return", "nt_diskinfo", "(", "total", ",", "used", ",", "free", ",", "percent", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
disk_partitions
Return disk partitions.
environment/lib/python2.7/site-packages/psutil/_psmswindows.py
def disk_partitions(all): """Return disk partitions.""" rawlist = _psutil_mswindows.get_disk_partitions(all) return [nt_partition(*x) for x in rawlist]
def disk_partitions(all): """Return disk partitions.""" rawlist = _psutil_mswindows.get_disk_partitions(all) return [nt_partition(*x) for x in rawlist]
[ "Return", "disk", "partitions", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psmswindows.py#L101-L104
[ "def", "disk_partitions", "(", "all", ")", ":", "rawlist", "=", "_psutil_mswindows", ".", "get_disk_partitions", "(", "all", ")", "return", "[", "nt_partition", "(", "*", "x", ")", "for", "x", "in", "rawlist", "]" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
get_system_cpu_times
Return system CPU times as a named tuple.
environment/lib/python2.7/site-packages/psutil/_psmswindows.py
def get_system_cpu_times(): """Return system CPU times as a named tuple.""" user, system, idle = 0, 0, 0 # computes system global times summing each processor value for cpu_time in _psutil_mswindows.get_system_cpu_times(): user += cpu_time[0] system += cpu_time[1] idle += cpu_time[2] return _cputimes_ntuple(user, system, idle)
def get_system_cpu_times(): """Return system CPU times as a named tuple.""" user, system, idle = 0, 0, 0 # computes system global times summing each processor value for cpu_time in _psutil_mswindows.get_system_cpu_times(): user += cpu_time[0] system += cpu_time[1] idle += cpu_time[2] return _cputimes_ntuple(user, system, idle)
[ "Return", "system", "CPU", "times", "as", "a", "named", "tuple", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psmswindows.py#L109-L117
[ "def", "get_system_cpu_times", "(", ")", ":", "user", ",", "system", ",", "idle", "=", "0", ",", "0", ",", "0", "# computes system global times summing each processor value", "for", "cpu_time", "in", "_psutil_mswindows", ".", "get_system_cpu_times", "(", ")", ":", "user", "+=", "cpu_time", "[", "0", "]", "system", "+=", "cpu_time", "[", "1", "]", "idle", "+=", "cpu_time", "[", "2", "]", "return", "_cputimes_ntuple", "(", "user", ",", "system", ",", "idle", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
get_system_per_cpu_times
Return system per-CPU times as a list of named tuples.
environment/lib/python2.7/site-packages/psutil/_psmswindows.py
def get_system_per_cpu_times(): """Return system per-CPU times as a list of named tuples.""" ret = [] for cpu_t in _psutil_mswindows.get_system_cpu_times(): user, system, idle = cpu_t item = _cputimes_ntuple(user, system, idle) ret.append(item) return ret
def get_system_per_cpu_times(): """Return system per-CPU times as a list of named tuples.""" ret = [] for cpu_t in _psutil_mswindows.get_system_cpu_times(): user, system, idle = cpu_t item = _cputimes_ntuple(user, system, idle) ret.append(item) return ret
[ "Return", "system", "per", "-", "CPU", "times", "as", "a", "list", "of", "named", "tuples", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psmswindows.py#L119-L126
[ "def", "get_system_per_cpu_times", "(", ")", ":", "ret", "=", "[", "]", "for", "cpu_t", "in", "_psutil_mswindows", ".", "get_system_cpu_times", "(", ")", ":", "user", ",", "system", ",", "idle", "=", "cpu_t", "item", "=", "_cputimes_ntuple", "(", "user", ",", "system", ",", "idle", ")", "ret", ".", "append", "(", "item", ")", "return", "ret" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
get_system_users
Return currently connected users as a list of namedtuples.
environment/lib/python2.7/site-packages/psutil/_psmswindows.py
def get_system_users(): """Return currently connected users as a list of namedtuples.""" retlist = [] rawlist = _psutil_mswindows.get_system_users() for item in rawlist: user, hostname, tstamp = item nt = nt_user(user, None, hostname, tstamp) retlist.append(nt) return retlist
def get_system_users(): """Return currently connected users as a list of namedtuples.""" retlist = [] rawlist = _psutil_mswindows.get_system_users() for item in rawlist: user, hostname, tstamp = item nt = nt_user(user, None, hostname, tstamp) retlist.append(nt) return retlist
[ "Return", "currently", "connected", "users", "as", "a", "list", "of", "namedtuples", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psmswindows.py#L128-L136
[ "def", "get_system_users", "(", ")", ":", "retlist", "=", "[", "]", "rawlist", "=", "_psutil_mswindows", ".", "get_system_users", "(", ")", "for", "item", "in", "rawlist", ":", "user", ",", "hostname", ",", "tstamp", "=", "item", "nt", "=", "nt_user", "(", "user", ",", "None", ",", "hostname", ",", "tstamp", ")", "retlist", ".", "append", "(", "nt", ")", "return", "retlist" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
system
Win32 version of os.system() that works with network shares. Note that this implementation returns None, as meant for use in IPython. Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- None : we explicitly do NOT return the subprocess status code, as this utility is meant to be used extensively in IPython, where any return value would trigger :func:`sys.displayhook` calls.
environment/lib/python2.7/site-packages/IPython/utils/_process_win32_controller.py
def system(cmd): """Win32 version of os.system() that works with network shares. Note that this implementation returns None, as meant for use in IPython. Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- None : we explicitly do NOT return the subprocess status code, as this utility is meant to be used extensively in IPython, where any return value would trigger :func:`sys.displayhook` calls. """ with AvoidUNCPath() as path: if path is not None: cmd = '"pushd %s &&"%s' % (path, cmd) with Win32ShellCommandController(cmd) as scc: scc.run()
def system(cmd): """Win32 version of os.system() that works with network shares. Note that this implementation returns None, as meant for use in IPython. Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- None : we explicitly do NOT return the subprocess status code, as this utility is meant to be used extensively in IPython, where any return value would trigger :func:`sys.displayhook` calls. """ with AvoidUNCPath() as path: if path is not None: cmd = '"pushd %s &&"%s' % (path, cmd) with Win32ShellCommandController(cmd) as scc: scc.run()
[ "Win32", "version", "of", "os", ".", "system", "()", "that", "works", "with", "network", "shares", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/_process_win32_controller.py#L547-L567
[ "def", "system", "(", "cmd", ")", ":", "with", "AvoidUNCPath", "(", ")", "as", "path", ":", "if", "path", "is", "not", "None", ":", "cmd", "=", "'\"pushd %s &&\"%s'", "%", "(", "path", ",", "cmd", ")", "with", "Win32ShellCommandController", "(", "cmd", ")", "as", "scc", ":", "scc", ".", "run", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Win32ShellCommandController.run
Runs the process, using the provided functions for I/O. The function stdin_func should return strings whenever a character or characters become available. The functions stdout_func and stderr_func are called whenever something is printed to stdout or stderr, respectively. These functions are called from different threads (but not concurrently, because of the GIL).
environment/lib/python2.7/site-packages/IPython/utils/_process_win32_controller.py
def run(self, stdout_func = None, stdin_func = None, stderr_func = None): """Runs the process, using the provided functions for I/O. The function stdin_func should return strings whenever a character or characters become available. The functions stdout_func and stderr_func are called whenever something is printed to stdout or stderr, respectively. These functions are called from different threads (but not concurrently, because of the GIL). """ if stdout_func == None and stdin_func == None and stderr_func == None: return self._run_stdio() if stderr_func != None and self.mergeout: raise RuntimeError("Shell command was initiated with " "merged stdin/stdout, but a separate stderr_func " "was provided to the run() method") # Create a thread for each input/output handle stdin_thread = None threads = [] if stdin_func: stdin_thread = threading.Thread(target=self._stdin_thread, args=(self.hstdin, self.piProcInfo.hProcess, stdin_func, stdout_func)) threads.append(threading.Thread(target=self._stdout_thread, args=(self.hstdout, stdout_func))) if not self.mergeout: if stderr_func == None: stderr_func = stdout_func threads.append(threading.Thread(target=self._stdout_thread, args=(self.hstderr, stderr_func))) # Start the I/O threads and the process if ResumeThread(self.piProcInfo.hThread) == 0xFFFFFFFF: raise ctypes.WinError() if stdin_thread is not None: stdin_thread.start() for thread in threads: thread.start() # Wait for the process to complete if WaitForSingleObject(self.piProcInfo.hProcess, INFINITE) == \ WAIT_FAILED: raise ctypes.WinError() # Wait for the I/O threads to complete for thread in threads: thread.join() # Wait for the stdin thread to complete if stdin_thread is not None: stdin_thread.join()
def run(self, stdout_func = None, stdin_func = None, stderr_func = None): """Runs the process, using the provided functions for I/O. The function stdin_func should return strings whenever a character or characters become available. The functions stdout_func and stderr_func are called whenever something is printed to stdout or stderr, respectively. These functions are called from different threads (but not concurrently, because of the GIL). """ if stdout_func == None and stdin_func == None and stderr_func == None: return self._run_stdio() if stderr_func != None and self.mergeout: raise RuntimeError("Shell command was initiated with " "merged stdin/stdout, but a separate stderr_func " "was provided to the run() method") # Create a thread for each input/output handle stdin_thread = None threads = [] if stdin_func: stdin_thread = threading.Thread(target=self._stdin_thread, args=(self.hstdin, self.piProcInfo.hProcess, stdin_func, stdout_func)) threads.append(threading.Thread(target=self._stdout_thread, args=(self.hstdout, stdout_func))) if not self.mergeout: if stderr_func == None: stderr_func = stdout_func threads.append(threading.Thread(target=self._stdout_thread, args=(self.hstderr, stderr_func))) # Start the I/O threads and the process if ResumeThread(self.piProcInfo.hThread) == 0xFFFFFFFF: raise ctypes.WinError() if stdin_thread is not None: stdin_thread.start() for thread in threads: thread.start() # Wait for the process to complete if WaitForSingleObject(self.piProcInfo.hProcess, INFINITE) == \ WAIT_FAILED: raise ctypes.WinError() # Wait for the I/O threads to complete for thread in threads: thread.join() # Wait for the stdin thread to complete if stdin_thread is not None: stdin_thread.join()
[ "Runs", "the", "process", "using", "the", "provided", "functions", "for", "I", "/", "O", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/_process_win32_controller.py#L393-L442
[ "def", "run", "(", "self", ",", "stdout_func", "=", "None", ",", "stdin_func", "=", "None", ",", "stderr_func", "=", "None", ")", ":", "if", "stdout_func", "==", "None", "and", "stdin_func", "==", "None", "and", "stderr_func", "==", "None", ":", "return", "self", ".", "_run_stdio", "(", ")", "if", "stderr_func", "!=", "None", "and", "self", ".", "mergeout", ":", "raise", "RuntimeError", "(", "\"Shell command was initiated with \"", "\"merged stdin/stdout, but a separate stderr_func \"", "\"was provided to the run() method\"", ")", "# Create a thread for each input/output handle", "stdin_thread", "=", "None", "threads", "=", "[", "]", "if", "stdin_func", ":", "stdin_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_stdin_thread", ",", "args", "=", "(", "self", ".", "hstdin", ",", "self", ".", "piProcInfo", ".", "hProcess", ",", "stdin_func", ",", "stdout_func", ")", ")", "threads", ".", "append", "(", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_stdout_thread", ",", "args", "=", "(", "self", ".", "hstdout", ",", "stdout_func", ")", ")", ")", "if", "not", "self", ".", "mergeout", ":", "if", "stderr_func", "==", "None", ":", "stderr_func", "=", "stdout_func", "threads", ".", "append", "(", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_stdout_thread", ",", "args", "=", "(", "self", ".", "hstderr", ",", "stderr_func", ")", ")", ")", "# Start the I/O threads and the process", "if", "ResumeThread", "(", "self", ".", "piProcInfo", ".", "hThread", ")", "==", "0xFFFFFFFF", ":", "raise", "ctypes", ".", "WinError", "(", ")", "if", "stdin_thread", "is", "not", "None", ":", "stdin_thread", ".", "start", "(", ")", "for", "thread", "in", "threads", ":", "thread", ".", "start", "(", ")", "# Wait for the process to complete", "if", "WaitForSingleObject", "(", "self", ".", "piProcInfo", ".", "hProcess", ",", "INFINITE", ")", "==", "WAIT_FAILED", ":", "raise", "ctypes", ".", "WinError", "(", ")", "# Wait for the I/O threads to complete", "for", "thread", "in", "threads", ":", "thread", ".", "join", "(", ")", "# Wait for the stdin thread to complete", "if", "stdin_thread", "is", "not", "None", ":", "stdin_thread", ".", "join", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Win32ShellCommandController._stdin_raw_nonblock
Use the raw Win32 handle of sys.stdin to do non-blocking reads
environment/lib/python2.7/site-packages/IPython/utils/_process_win32_controller.py
def _stdin_raw_nonblock(self): """Use the raw Win32 handle of sys.stdin to do non-blocking reads""" # WARNING: This is experimental, and produces inconsistent results. # It's possible for the handle not to be appropriate for use # with WaitForSingleObject, among other things. handle = msvcrt.get_osfhandle(sys.stdin.fileno()) result = WaitForSingleObject(handle, 100) if result == WAIT_FAILED: raise ctypes.WinError() elif result == WAIT_TIMEOUT: print(".", end='') return None else: data = ctypes.create_string_buffer(256) bytesRead = DWORD(0) print('?', end='') if not ReadFile(handle, data, 256, ctypes.byref(bytesRead), None): raise ctypes.WinError() # This ensures the non-blocking works with an actual console # Not checking the error, so the processing will still work with # other handle types FlushConsoleInputBuffer(handle) data = data.value data = data.replace('\r\n', '\n') data = data.replace('\r', '\n') print(repr(data) + " ", end='') return data
def _stdin_raw_nonblock(self): """Use the raw Win32 handle of sys.stdin to do non-blocking reads""" # WARNING: This is experimental, and produces inconsistent results. # It's possible for the handle not to be appropriate for use # with WaitForSingleObject, among other things. handle = msvcrt.get_osfhandle(sys.stdin.fileno()) result = WaitForSingleObject(handle, 100) if result == WAIT_FAILED: raise ctypes.WinError() elif result == WAIT_TIMEOUT: print(".", end='') return None else: data = ctypes.create_string_buffer(256) bytesRead = DWORD(0) print('?', end='') if not ReadFile(handle, data, 256, ctypes.byref(bytesRead), None): raise ctypes.WinError() # This ensures the non-blocking works with an actual console # Not checking the error, so the processing will still work with # other handle types FlushConsoleInputBuffer(handle) data = data.value data = data.replace('\r\n', '\n') data = data.replace('\r', '\n') print(repr(data) + " ", end='') return data
[ "Use", "the", "raw", "Win32", "handle", "of", "sys", ".", "stdin", "to", "do", "non", "-", "blocking", "reads" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/_process_win32_controller.py#L444-L473
[ "def", "_stdin_raw_nonblock", "(", "self", ")", ":", "# WARNING: This is experimental, and produces inconsistent results.", "# It's possible for the handle not to be appropriate for use", "# with WaitForSingleObject, among other things.", "handle", "=", "msvcrt", ".", "get_osfhandle", "(", "sys", ".", "stdin", ".", "fileno", "(", ")", ")", "result", "=", "WaitForSingleObject", "(", "handle", ",", "100", ")", "if", "result", "==", "WAIT_FAILED", ":", "raise", "ctypes", ".", "WinError", "(", ")", "elif", "result", "==", "WAIT_TIMEOUT", ":", "print", "(", "\".\"", ",", "end", "=", "''", ")", "return", "None", "else", ":", "data", "=", "ctypes", ".", "create_string_buffer", "(", "256", ")", "bytesRead", "=", "DWORD", "(", "0", ")", "print", "(", "'?'", ",", "end", "=", "''", ")", "if", "not", "ReadFile", "(", "handle", ",", "data", ",", "256", ",", "ctypes", ".", "byref", "(", "bytesRead", ")", ",", "None", ")", ":", "raise", "ctypes", ".", "WinError", "(", ")", "# This ensures the non-blocking works with an actual console", "# Not checking the error, so the processing will still work with", "# other handle types", "FlushConsoleInputBuffer", "(", "handle", ")", "data", "=", "data", ".", "value", "data", "=", "data", ".", "replace", "(", "'\\r\\n'", ",", "'\\n'", ")", "data", "=", "data", ".", "replace", "(", "'\\r'", ",", "'\\n'", ")", "print", "(", "repr", "(", "data", ")", "+", "\" \"", ",", "end", "=", "''", ")", "return", "data" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Win32ShellCommandController._stdin_raw_block
Use a blocking stdin read
environment/lib/python2.7/site-packages/IPython/utils/_process_win32_controller.py
def _stdin_raw_block(self): """Use a blocking stdin read""" # The big problem with the blocking read is that it doesn't # exit when it's supposed to in all contexts. An extra # key-press may be required to trigger the exit. try: data = sys.stdin.read(1) data = data.replace('\r', '\n') return data except WindowsError as we: if we.winerror == ERROR_NO_DATA: # This error occurs when the pipe is closed return None else: # Otherwise let the error propagate raise we
def _stdin_raw_block(self): """Use a blocking stdin read""" # The big problem with the blocking read is that it doesn't # exit when it's supposed to in all contexts. An extra # key-press may be required to trigger the exit. try: data = sys.stdin.read(1) data = data.replace('\r', '\n') return data except WindowsError as we: if we.winerror == ERROR_NO_DATA: # This error occurs when the pipe is closed return None else: # Otherwise let the error propagate raise we
[ "Use", "a", "blocking", "stdin", "read" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/_process_win32_controller.py#L475-L490
[ "def", "_stdin_raw_block", "(", "self", ")", ":", "# The big problem with the blocking read is that it doesn't", "# exit when it's supposed to in all contexts. An extra", "# key-press may be required to trigger the exit.", "try", ":", "data", "=", "sys", ".", "stdin", ".", "read", "(", "1", ")", "data", "=", "data", ".", "replace", "(", "'\\r'", ",", "'\\n'", ")", "return", "data", "except", "WindowsError", "as", "we", ":", "if", "we", ".", "winerror", "==", "ERROR_NO_DATA", ":", "# This error occurs when the pipe is closed", "return", "None", "else", ":", "# Otherwise let the error propagate", "raise", "we" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Win32ShellCommandController._stdout_raw
Writes the string to stdout
environment/lib/python2.7/site-packages/IPython/utils/_process_win32_controller.py
def _stdout_raw(self, s): """Writes the string to stdout""" print(s, end='', file=sys.stdout) sys.stdout.flush()
def _stdout_raw(self, s): """Writes the string to stdout""" print(s, end='', file=sys.stdout) sys.stdout.flush()
[ "Writes", "the", "string", "to", "stdout" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/_process_win32_controller.py#L492-L495
[ "def", "_stdout_raw", "(", "self", ",", "s", ")", ":", "print", "(", "s", ",", "end", "=", "''", ",", "file", "=", "sys", ".", "stdout", ")", "sys", ".", "stdout", ".", "flush", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Win32ShellCommandController._stderr_raw
Writes the string to stdout
environment/lib/python2.7/site-packages/IPython/utils/_process_win32_controller.py
def _stderr_raw(self, s): """Writes the string to stdout""" print(s, end='', file=sys.stderr) sys.stderr.flush()
def _stderr_raw(self, s): """Writes the string to stdout""" print(s, end='', file=sys.stderr) sys.stderr.flush()
[ "Writes", "the", "string", "to", "stdout" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/_process_win32_controller.py#L497-L500
[ "def", "_stderr_raw", "(", "self", ",", "s", ")", ":", "print", "(", "s", ",", "end", "=", "''", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "stderr", ".", "flush", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Win32ShellCommandController._run_stdio
Runs the process using the system standard I/O. IMPORTANT: stdin needs to be asynchronous, so the Python sys.stdin object is not used. Instead, msvcrt.kbhit/getwch are used asynchronously.
environment/lib/python2.7/site-packages/IPython/utils/_process_win32_controller.py
def _run_stdio(self): """Runs the process using the system standard I/O. IMPORTANT: stdin needs to be asynchronous, so the Python sys.stdin object is not used. Instead, msvcrt.kbhit/getwch are used asynchronously. """ # Disable Line and Echo mode #lpMode = DWORD() #handle = msvcrt.get_osfhandle(sys.stdin.fileno()) #if GetConsoleMode(handle, ctypes.byref(lpMode)): # set_console_mode = True # if not SetConsoleMode(handle, lpMode.value & # ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT)): # raise ctypes.WinError() if self.mergeout: return self.run(stdout_func = self._stdout_raw, stdin_func = self._stdin_raw_block) else: return self.run(stdout_func = self._stdout_raw, stdin_func = self._stdin_raw_block, stderr_func = self._stderr_raw)
def _run_stdio(self): """Runs the process using the system standard I/O. IMPORTANT: stdin needs to be asynchronous, so the Python sys.stdin object is not used. Instead, msvcrt.kbhit/getwch are used asynchronously. """ # Disable Line and Echo mode #lpMode = DWORD() #handle = msvcrt.get_osfhandle(sys.stdin.fileno()) #if GetConsoleMode(handle, ctypes.byref(lpMode)): # set_console_mode = True # if not SetConsoleMode(handle, lpMode.value & # ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT)): # raise ctypes.WinError() if self.mergeout: return self.run(stdout_func = self._stdout_raw, stdin_func = self._stdin_raw_block) else: return self.run(stdout_func = self._stdout_raw, stdin_func = self._stdin_raw_block, stderr_func = self._stderr_raw)
[ "Runs", "the", "process", "using", "the", "system", "standard", "I", "/", "O", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/_process_win32_controller.py#L502-L524
[ "def", "_run_stdio", "(", "self", ")", ":", "# Disable Line and Echo mode", "#lpMode = DWORD()", "#handle = msvcrt.get_osfhandle(sys.stdin.fileno())", "#if GetConsoleMode(handle, ctypes.byref(lpMode)):", "# set_console_mode = True", "# if not SetConsoleMode(handle, lpMode.value &", "# ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT)):", "# raise ctypes.WinError()", "if", "self", ".", "mergeout", ":", "return", "self", ".", "run", "(", "stdout_func", "=", "self", ".", "_stdout_raw", ",", "stdin_func", "=", "self", ".", "_stdin_raw_block", ")", "else", ":", "return", "self", ".", "run", "(", "stdout_func", "=", "self", ".", "_stdout_raw", ",", "stdin_func", "=", "self", ".", "_stdin_raw_block", ",", "stderr_func", "=", "self", ".", "_stderr_raw", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
MainWindow.update_tab_bar_visibility
update visibility of the tabBar depending of the number of tab 0 or 1 tab, tabBar hidden 2+ tabs, tabBar visible send a self.close if number of tab ==0 need to be called explicitly, or be connected to tabInserted/tabRemoved
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py
def update_tab_bar_visibility(self): """ update visibility of the tabBar depending of the number of tab 0 or 1 tab, tabBar hidden 2+ tabs, tabBar visible send a self.close if number of tab ==0 need to be called explicitly, or be connected to tabInserted/tabRemoved """ if self.tab_widget.count() <= 1: self.tab_widget.tabBar().setVisible(False) else: self.tab_widget.tabBar().setVisible(True) if self.tab_widget.count()==0 : self.close()
def update_tab_bar_visibility(self): """ update visibility of the tabBar depending of the number of tab 0 or 1 tab, tabBar hidden 2+ tabs, tabBar visible send a self.close if number of tab ==0 need to be called explicitly, or be connected to tabInserted/tabRemoved """ if self.tab_widget.count() <= 1: self.tab_widget.tabBar().setVisible(False) else: self.tab_widget.tabBar().setVisible(True) if self.tab_widget.count()==0 : self.close()
[ "update", "visibility", "of", "the", "tabBar", "depending", "of", "the", "number", "of", "tab" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py#L88-L103
[ "def", "update_tab_bar_visibility", "(", "self", ")", ":", "if", "self", ".", "tab_widget", ".", "count", "(", ")", "<=", "1", ":", "self", ".", "tab_widget", ".", "tabBar", "(", ")", ".", "setVisible", "(", "False", ")", "else", ":", "self", ".", "tab_widget", ".", "tabBar", "(", ")", ".", "setVisible", "(", "True", ")", "if", "self", ".", "tab_widget", ".", "count", "(", ")", "==", "0", ":", "self", ".", "close", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
MainWindow.create_tab_with_current_kernel
create a new frontend attached to the same kernel as the current tab
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py
def create_tab_with_current_kernel(self): """create a new frontend attached to the same kernel as the current tab""" current_widget = self.tab_widget.currentWidget() current_widget_index = self.tab_widget.indexOf(current_widget) current_widget_name = self.tab_widget.tabText(current_widget_index) widget = self.slave_frontend_factory(current_widget) if 'slave' in current_widget_name: # don't keep stacking slaves name = current_widget_name else: name = '(%s) slave' % current_widget_name self.add_tab_with_frontend(widget,name=name)
def create_tab_with_current_kernel(self): """create a new frontend attached to the same kernel as the current tab""" current_widget = self.tab_widget.currentWidget() current_widget_index = self.tab_widget.indexOf(current_widget) current_widget_name = self.tab_widget.tabText(current_widget_index) widget = self.slave_frontend_factory(current_widget) if 'slave' in current_widget_name: # don't keep stacking slaves name = current_widget_name else: name = '(%s) slave' % current_widget_name self.add_tab_with_frontend(widget,name=name)
[ "create", "a", "new", "frontend", "attached", "to", "the", "same", "kernel", "as", "the", "current", "tab" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py#L121-L132
[ "def", "create_tab_with_current_kernel", "(", "self", ")", ":", "current_widget", "=", "self", ".", "tab_widget", ".", "currentWidget", "(", ")", "current_widget_index", "=", "self", ".", "tab_widget", ".", "indexOf", "(", "current_widget", ")", "current_widget_name", "=", "self", ".", "tab_widget", ".", "tabText", "(", "current_widget_index", ")", "widget", "=", "self", ".", "slave_frontend_factory", "(", "current_widget", ")", "if", "'slave'", "in", "current_widget_name", ":", "# don't keep stacking slaves", "name", "=", "current_widget_name", "else", ":", "name", "=", "'(%s) slave'", "%", "current_widget_name", "self", ".", "add_tab_with_frontend", "(", "widget", ",", "name", "=", "name", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
MainWindow.close_tab
Called when you need to try to close a tab. It takes the number of the tab to be closed as argument, or a reference to the widget inside this tab
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py
def close_tab(self,current_tab): """ Called when you need to try to close a tab. It takes the number of the tab to be closed as argument, or a reference to the widget inside this tab """ # let's be sure "tab" and "closing widget" are respectively the index # of the tab to close and a reference to the frontend to close if type(current_tab) is not int : current_tab = self.tab_widget.indexOf(current_tab) closing_widget=self.tab_widget.widget(current_tab) # when trying to be closed, widget might re-send a request to be # closed again, but will be deleted when event will be processed. So # need to check that widget still exists and skip if not. One example # of this is when 'exit' is sent in a slave tab. 'exit' will be # re-sent by this function on the master widget, which ask all slave # widgets to exit if closing_widget==None: return #get a list of all slave widgets on the same kernel. slave_tabs = self.find_slave_widgets(closing_widget) keepkernel = None #Use the prompt by default if hasattr(closing_widget,'_keep_kernel_on_exit'): #set by exit magic keepkernel = closing_widget._keep_kernel_on_exit # If signal sent by exit magic (_keep_kernel_on_exit, exist and not None) # we set local slave tabs._hidden to True to avoid prompting for kernel # restart when they get the signal. and then "forward" the 'exit' # to the main window if keepkernel is not None: for tab in slave_tabs: tab._hidden = True if closing_widget in slave_tabs: try : self.find_master_tab(closing_widget).execute('exit') except AttributeError: self.log.info("Master already closed or not local, closing only current tab") self.tab_widget.removeTab(current_tab) self.update_tab_bar_visibility() return kernel_manager = closing_widget.kernel_manager if keepkernel is None and not closing_widget._confirm_exit: # don't prompt, just terminate the kernel if we own it # or leave it alone if we don't keepkernel = closing_widget._existing if keepkernel is None: #show prompt if kernel_manager and kernel_manager.channels_running: title = self.window().windowTitle() cancel = QtGui.QMessageBox.Cancel okay = QtGui.QMessageBox.Ok if closing_widget._may_close: msg = "You are closing the tab : "+'"'+self.tab_widget.tabText(current_tab)+'"' info = "Would you like to quit the Kernel and close all attached Consoles as well?" justthis = QtGui.QPushButton("&No, just this Tab", self) justthis.setShortcut('N') closeall = QtGui.QPushButton("&Yes, close all", self) closeall.setShortcut('Y') # allow ctrl-d ctrl-d exit, like in terminal closeall.setShortcut('Ctrl+D') box = QtGui.QMessageBox(QtGui.QMessageBox.Question, title, msg) box.setInformativeText(info) box.addButton(cancel) box.addButton(justthis, QtGui.QMessageBox.NoRole) box.addButton(closeall, QtGui.QMessageBox.YesRole) box.setDefaultButton(closeall) box.setEscapeButton(cancel) pixmap = QtGui.QPixmap(self._app.icon.pixmap(QtCore.QSize(64,64))) box.setIconPixmap(pixmap) reply = box.exec_() if reply == 1: # close All for slave in slave_tabs: background(slave.kernel_manager.stop_channels) self.tab_widget.removeTab(self.tab_widget.indexOf(slave)) closing_widget.execute("exit") self.tab_widget.removeTab(current_tab) background(kernel_manager.stop_channels) elif reply == 0: # close Console if not closing_widget._existing: # Have kernel: don't quit, just close the tab closing_widget.execute("exit True") self.tab_widget.removeTab(current_tab) background(kernel_manager.stop_channels) else: reply = QtGui.QMessageBox.question(self, title, "Are you sure you want to close this Console?"+ "\nThe Kernel and other Consoles will remain active.", okay|cancel, defaultButton=okay ) if reply == okay: self.tab_widget.removeTab(current_tab) elif keepkernel: #close console but leave kernel running (no prompt) self.tab_widget.removeTab(current_tab) background(kernel_manager.stop_channels) else: #close console and kernel (no prompt) self.tab_widget.removeTab(current_tab) if kernel_manager and kernel_manager.channels_running: for slave in slave_tabs: background(slave.kernel_manager.stop_channels) self.tab_widget.removeTab(self.tab_widget.indexOf(slave)) kernel_manager.shutdown_kernel() background(kernel_manager.stop_channels) self.update_tab_bar_visibility()
def close_tab(self,current_tab): """ Called when you need to try to close a tab. It takes the number of the tab to be closed as argument, or a reference to the widget inside this tab """ # let's be sure "tab" and "closing widget" are respectively the index # of the tab to close and a reference to the frontend to close if type(current_tab) is not int : current_tab = self.tab_widget.indexOf(current_tab) closing_widget=self.tab_widget.widget(current_tab) # when trying to be closed, widget might re-send a request to be # closed again, but will be deleted when event will be processed. So # need to check that widget still exists and skip if not. One example # of this is when 'exit' is sent in a slave tab. 'exit' will be # re-sent by this function on the master widget, which ask all slave # widgets to exit if closing_widget==None: return #get a list of all slave widgets on the same kernel. slave_tabs = self.find_slave_widgets(closing_widget) keepkernel = None #Use the prompt by default if hasattr(closing_widget,'_keep_kernel_on_exit'): #set by exit magic keepkernel = closing_widget._keep_kernel_on_exit # If signal sent by exit magic (_keep_kernel_on_exit, exist and not None) # we set local slave tabs._hidden to True to avoid prompting for kernel # restart when they get the signal. and then "forward" the 'exit' # to the main window if keepkernel is not None: for tab in slave_tabs: tab._hidden = True if closing_widget in slave_tabs: try : self.find_master_tab(closing_widget).execute('exit') except AttributeError: self.log.info("Master already closed or not local, closing only current tab") self.tab_widget.removeTab(current_tab) self.update_tab_bar_visibility() return kernel_manager = closing_widget.kernel_manager if keepkernel is None and not closing_widget._confirm_exit: # don't prompt, just terminate the kernel if we own it # or leave it alone if we don't keepkernel = closing_widget._existing if keepkernel is None: #show prompt if kernel_manager and kernel_manager.channels_running: title = self.window().windowTitle() cancel = QtGui.QMessageBox.Cancel okay = QtGui.QMessageBox.Ok if closing_widget._may_close: msg = "You are closing the tab : "+'"'+self.tab_widget.tabText(current_tab)+'"' info = "Would you like to quit the Kernel and close all attached Consoles as well?" justthis = QtGui.QPushButton("&No, just this Tab", self) justthis.setShortcut('N') closeall = QtGui.QPushButton("&Yes, close all", self) closeall.setShortcut('Y') # allow ctrl-d ctrl-d exit, like in terminal closeall.setShortcut('Ctrl+D') box = QtGui.QMessageBox(QtGui.QMessageBox.Question, title, msg) box.setInformativeText(info) box.addButton(cancel) box.addButton(justthis, QtGui.QMessageBox.NoRole) box.addButton(closeall, QtGui.QMessageBox.YesRole) box.setDefaultButton(closeall) box.setEscapeButton(cancel) pixmap = QtGui.QPixmap(self._app.icon.pixmap(QtCore.QSize(64,64))) box.setIconPixmap(pixmap) reply = box.exec_() if reply == 1: # close All for slave in slave_tabs: background(slave.kernel_manager.stop_channels) self.tab_widget.removeTab(self.tab_widget.indexOf(slave)) closing_widget.execute("exit") self.tab_widget.removeTab(current_tab) background(kernel_manager.stop_channels) elif reply == 0: # close Console if not closing_widget._existing: # Have kernel: don't quit, just close the tab closing_widget.execute("exit True") self.tab_widget.removeTab(current_tab) background(kernel_manager.stop_channels) else: reply = QtGui.QMessageBox.question(self, title, "Are you sure you want to close this Console?"+ "\nThe Kernel and other Consoles will remain active.", okay|cancel, defaultButton=okay ) if reply == okay: self.tab_widget.removeTab(current_tab) elif keepkernel: #close console but leave kernel running (no prompt) self.tab_widget.removeTab(current_tab) background(kernel_manager.stop_channels) else: #close console and kernel (no prompt) self.tab_widget.removeTab(current_tab) if kernel_manager and kernel_manager.channels_running: for slave in slave_tabs: background(slave.kernel_manager.stop_channels) self.tab_widget.removeTab(self.tab_widget.indexOf(slave)) kernel_manager.shutdown_kernel() background(kernel_manager.stop_channels) self.update_tab_bar_visibility()
[ "Called", "when", "you", "need", "to", "try", "to", "close", "a", "tab", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py#L134-L244
[ "def", "close_tab", "(", "self", ",", "current_tab", ")", ":", "# let's be sure \"tab\" and \"closing widget\" are respectively the index", "# of the tab to close and a reference to the frontend to close", "if", "type", "(", "current_tab", ")", "is", "not", "int", ":", "current_tab", "=", "self", ".", "tab_widget", ".", "indexOf", "(", "current_tab", ")", "closing_widget", "=", "self", ".", "tab_widget", ".", "widget", "(", "current_tab", ")", "# when trying to be closed, widget might re-send a request to be", "# closed again, but will be deleted when event will be processed. So", "# need to check that widget still exists and skip if not. One example", "# of this is when 'exit' is sent in a slave tab. 'exit' will be", "# re-sent by this function on the master widget, which ask all slave", "# widgets to exit", "if", "closing_widget", "==", "None", ":", "return", "#get a list of all slave widgets on the same kernel.", "slave_tabs", "=", "self", ".", "find_slave_widgets", "(", "closing_widget", ")", "keepkernel", "=", "None", "#Use the prompt by default", "if", "hasattr", "(", "closing_widget", ",", "'_keep_kernel_on_exit'", ")", ":", "#set by exit magic", "keepkernel", "=", "closing_widget", ".", "_keep_kernel_on_exit", "# If signal sent by exit magic (_keep_kernel_on_exit, exist and not None)", "# we set local slave tabs._hidden to True to avoid prompting for kernel", "# restart when they get the signal. and then \"forward\" the 'exit'", "# to the main window", "if", "keepkernel", "is", "not", "None", ":", "for", "tab", "in", "slave_tabs", ":", "tab", ".", "_hidden", "=", "True", "if", "closing_widget", "in", "slave_tabs", ":", "try", ":", "self", ".", "find_master_tab", "(", "closing_widget", ")", ".", "execute", "(", "'exit'", ")", "except", "AttributeError", ":", "self", ".", "log", ".", "info", "(", "\"Master already closed or not local, closing only current tab\"", ")", "self", ".", "tab_widget", ".", "removeTab", "(", "current_tab", ")", "self", ".", "update_tab_bar_visibility", "(", ")", "return", "kernel_manager", "=", "closing_widget", ".", "kernel_manager", "if", "keepkernel", "is", "None", "and", "not", "closing_widget", ".", "_confirm_exit", ":", "# don't prompt, just terminate the kernel if we own it", "# or leave it alone if we don't", "keepkernel", "=", "closing_widget", ".", "_existing", "if", "keepkernel", "is", "None", ":", "#show prompt", "if", "kernel_manager", "and", "kernel_manager", ".", "channels_running", ":", "title", "=", "self", ".", "window", "(", ")", ".", "windowTitle", "(", ")", "cancel", "=", "QtGui", ".", "QMessageBox", ".", "Cancel", "okay", "=", "QtGui", ".", "QMessageBox", ".", "Ok", "if", "closing_widget", ".", "_may_close", ":", "msg", "=", "\"You are closing the tab : \"", "+", "'\"'", "+", "self", ".", "tab_widget", ".", "tabText", "(", "current_tab", ")", "+", "'\"'", "info", "=", "\"Would you like to quit the Kernel and close all attached Consoles as well?\"", "justthis", "=", "QtGui", ".", "QPushButton", "(", "\"&No, just this Tab\"", ",", "self", ")", "justthis", ".", "setShortcut", "(", "'N'", ")", "closeall", "=", "QtGui", ".", "QPushButton", "(", "\"&Yes, close all\"", ",", "self", ")", "closeall", ".", "setShortcut", "(", "'Y'", ")", "# allow ctrl-d ctrl-d exit, like in terminal", "closeall", ".", "setShortcut", "(", "'Ctrl+D'", ")", "box", "=", "QtGui", ".", "QMessageBox", "(", "QtGui", ".", "QMessageBox", ".", "Question", ",", "title", ",", "msg", ")", "box", ".", "setInformativeText", "(", "info", ")", "box", ".", "addButton", "(", "cancel", ")", "box", ".", "addButton", "(", "justthis", ",", "QtGui", ".", "QMessageBox", ".", "NoRole", ")", "box", ".", "addButton", "(", "closeall", ",", "QtGui", ".", "QMessageBox", ".", "YesRole", ")", "box", ".", "setDefaultButton", "(", "closeall", ")", "box", ".", "setEscapeButton", "(", "cancel", ")", "pixmap", "=", "QtGui", ".", "QPixmap", "(", "self", ".", "_app", ".", "icon", ".", "pixmap", "(", "QtCore", ".", "QSize", "(", "64", ",", "64", ")", ")", ")", "box", ".", "setIconPixmap", "(", "pixmap", ")", "reply", "=", "box", ".", "exec_", "(", ")", "if", "reply", "==", "1", ":", "# close All", "for", "slave", "in", "slave_tabs", ":", "background", "(", "slave", ".", "kernel_manager", ".", "stop_channels", ")", "self", ".", "tab_widget", ".", "removeTab", "(", "self", ".", "tab_widget", ".", "indexOf", "(", "slave", ")", ")", "closing_widget", ".", "execute", "(", "\"exit\"", ")", "self", ".", "tab_widget", ".", "removeTab", "(", "current_tab", ")", "background", "(", "kernel_manager", ".", "stop_channels", ")", "elif", "reply", "==", "0", ":", "# close Console", "if", "not", "closing_widget", ".", "_existing", ":", "# Have kernel: don't quit, just close the tab", "closing_widget", ".", "execute", "(", "\"exit True\"", ")", "self", ".", "tab_widget", ".", "removeTab", "(", "current_tab", ")", "background", "(", "kernel_manager", ".", "stop_channels", ")", "else", ":", "reply", "=", "QtGui", ".", "QMessageBox", ".", "question", "(", "self", ",", "title", ",", "\"Are you sure you want to close this Console?\"", "+", "\"\\nThe Kernel and other Consoles will remain active.\"", ",", "okay", "|", "cancel", ",", "defaultButton", "=", "okay", ")", "if", "reply", "==", "okay", ":", "self", ".", "tab_widget", ".", "removeTab", "(", "current_tab", ")", "elif", "keepkernel", ":", "#close console but leave kernel running (no prompt)", "self", ".", "tab_widget", ".", "removeTab", "(", "current_tab", ")", "background", "(", "kernel_manager", ".", "stop_channels", ")", "else", ":", "#close console and kernel (no prompt)", "self", ".", "tab_widget", ".", "removeTab", "(", "current_tab", ")", "if", "kernel_manager", "and", "kernel_manager", ".", "channels_running", ":", "for", "slave", "in", "slave_tabs", ":", "background", "(", "slave", ".", "kernel_manager", ".", "stop_channels", ")", "self", ".", "tab_widget", ".", "removeTab", "(", "self", ".", "tab_widget", ".", "indexOf", "(", "slave", ")", ")", "kernel_manager", ".", "shutdown_kernel", "(", ")", "background", "(", "kernel_manager", ".", "stop_channels", ")", "self", ".", "update_tab_bar_visibility", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
MainWindow.add_tab_with_frontend
insert a tab with a given frontend in the tab bar, and give it a name
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py
def add_tab_with_frontend(self,frontend,name=None): """ insert a tab with a given frontend in the tab bar, and give it a name """ if not name: name = 'kernel %i' % self.next_kernel_id self.tab_widget.addTab(frontend,name) self.update_tab_bar_visibility() self.make_frontend_visible(frontend) frontend.exit_requested.connect(self.close_tab)
def add_tab_with_frontend(self,frontend,name=None): """ insert a tab with a given frontend in the tab bar, and give it a name """ if not name: name = 'kernel %i' % self.next_kernel_id self.tab_widget.addTab(frontend,name) self.update_tab_bar_visibility() self.make_frontend_visible(frontend) frontend.exit_requested.connect(self.close_tab)
[ "insert", "a", "tab", "with", "a", "given", "frontend", "in", "the", "tab", "bar", "and", "give", "it", "a", "name" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py#L246-L255
[ "def", "add_tab_with_frontend", "(", "self", ",", "frontend", ",", "name", "=", "None", ")", ":", "if", "not", "name", ":", "name", "=", "'kernel %i'", "%", "self", ".", "next_kernel_id", "self", ".", "tab_widget", ".", "addTab", "(", "frontend", ",", "name", ")", "self", ".", "update_tab_bar_visibility", "(", ")", "self", ".", "make_frontend_visible", "(", "frontend", ")", "frontend", ".", "exit_requested", ".", "connect", "(", "self", ".", "close_tab", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
MainWindow.find_master_tab
Try to return the frontend that owns the kernel attached to the given widget/tab. Only finds frontend owned by the current application. Selection based on port of the kernel might be inaccurate if several kernel on different ip use same port number. This function does the conversion tabNumber/widget if needed. Might return None if no master widget (non local kernel) Will crash IPython if more than 1 masterWidget When asList set to True, always return a list of widget(s) owning the kernel. The list might be empty or containing several Widget.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py
def find_master_tab(self,tab,as_list=False): """ Try to return the frontend that owns the kernel attached to the given widget/tab. Only finds frontend owned by the current application. Selection based on port of the kernel might be inaccurate if several kernel on different ip use same port number. This function does the conversion tabNumber/widget if needed. Might return None if no master widget (non local kernel) Will crash IPython if more than 1 masterWidget When asList set to True, always return a list of widget(s) owning the kernel. The list might be empty or containing several Widget. """ #convert from/to int/richIpythonWidget if needed if isinstance(tab, int): tab = self.tab_widget.widget(tab) km=tab.kernel_manager #build list of all widgets widget_list = [self.tab_widget.widget(i) for i in range(self.tab_widget.count())] # widget that are candidate to be the owner of the kernel does have all the same port of the curent widget # And should have a _may_close attribute filtered_widget_list = [ widget for widget in widget_list if widget.kernel_manager.connection_file == km.connection_file and hasattr(widget,'_may_close') ] # the master widget is the one that may close the kernel master_widget= [ widget for widget in filtered_widget_list if widget._may_close] if as_list: return master_widget assert(len(master_widget)<=1 ) if len(master_widget)==0: return None return master_widget[0]
def find_master_tab(self,tab,as_list=False): """ Try to return the frontend that owns the kernel attached to the given widget/tab. Only finds frontend owned by the current application. Selection based on port of the kernel might be inaccurate if several kernel on different ip use same port number. This function does the conversion tabNumber/widget if needed. Might return None if no master widget (non local kernel) Will crash IPython if more than 1 masterWidget When asList set to True, always return a list of widget(s) owning the kernel. The list might be empty or containing several Widget. """ #convert from/to int/richIpythonWidget if needed if isinstance(tab, int): tab = self.tab_widget.widget(tab) km=tab.kernel_manager #build list of all widgets widget_list = [self.tab_widget.widget(i) for i in range(self.tab_widget.count())] # widget that are candidate to be the owner of the kernel does have all the same port of the curent widget # And should have a _may_close attribute filtered_widget_list = [ widget for widget in widget_list if widget.kernel_manager.connection_file == km.connection_file and hasattr(widget,'_may_close') ] # the master widget is the one that may close the kernel master_widget= [ widget for widget in filtered_widget_list if widget._may_close] if as_list: return master_widget assert(len(master_widget)<=1 ) if len(master_widget)==0: return None return master_widget[0]
[ "Try", "to", "return", "the", "frontend", "that", "owns", "the", "kernel", "attached", "to", "the", "given", "widget", "/", "tab", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py#L268-L305
[ "def", "find_master_tab", "(", "self", ",", "tab", ",", "as_list", "=", "False", ")", ":", "#convert from/to int/richIpythonWidget if needed", "if", "isinstance", "(", "tab", ",", "int", ")", ":", "tab", "=", "self", ".", "tab_widget", ".", "widget", "(", "tab", ")", "km", "=", "tab", ".", "kernel_manager", "#build list of all widgets", "widget_list", "=", "[", "self", ".", "tab_widget", ".", "widget", "(", "i", ")", "for", "i", "in", "range", "(", "self", ".", "tab_widget", ".", "count", "(", ")", ")", "]", "# widget that are candidate to be the owner of the kernel does have all the same port of the curent widget", "# And should have a _may_close attribute", "filtered_widget_list", "=", "[", "widget", "for", "widget", "in", "widget_list", "if", "widget", ".", "kernel_manager", ".", "connection_file", "==", "km", ".", "connection_file", "and", "hasattr", "(", "widget", ",", "'_may_close'", ")", "]", "# the master widget is the one that may close the kernel", "master_widget", "=", "[", "widget", "for", "widget", "in", "filtered_widget_list", "if", "widget", ".", "_may_close", "]", "if", "as_list", ":", "return", "master_widget", "assert", "(", "len", "(", "master_widget", ")", "<=", "1", ")", "if", "len", "(", "master_widget", ")", "==", "0", ":", "return", "None", "return", "master_widget", "[", "0", "]" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
MainWindow.find_slave_widgets
return all the frontends that do not own the kernel attached to the given widget/tab. Only find frontends owned by the current application. Selection based on connection file of the kernel. This function does the conversion tabNumber/widget if needed.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py
def find_slave_widgets(self,tab): """return all the frontends that do not own the kernel attached to the given widget/tab. Only find frontends owned by the current application. Selection based on connection file of the kernel. This function does the conversion tabNumber/widget if needed. """ #convert from/to int/richIpythonWidget if needed if isinstance(tab, int): tab = self.tab_widget.widget(tab) km=tab.kernel_manager #build list of all widgets widget_list = [self.tab_widget.widget(i) for i in range(self.tab_widget.count())] # widget that are candidate not to be the owner of the kernel does have all the same port of the curent widget filtered_widget_list = ( widget for widget in widget_list if widget.kernel_manager.connection_file == km.connection_file) # Get a list of all widget owning the same kernel and removed it from # the previous cadidate. (better using sets ?) master_widget_list = self.find_master_tab(tab, as_list=True) slave_list = [widget for widget in filtered_widget_list if widget not in master_widget_list] return slave_list
def find_slave_widgets(self,tab): """return all the frontends that do not own the kernel attached to the given widget/tab. Only find frontends owned by the current application. Selection based on connection file of the kernel. This function does the conversion tabNumber/widget if needed. """ #convert from/to int/richIpythonWidget if needed if isinstance(tab, int): tab = self.tab_widget.widget(tab) km=tab.kernel_manager #build list of all widgets widget_list = [self.tab_widget.widget(i) for i in range(self.tab_widget.count())] # widget that are candidate not to be the owner of the kernel does have all the same port of the curent widget filtered_widget_list = ( widget for widget in widget_list if widget.kernel_manager.connection_file == km.connection_file) # Get a list of all widget owning the same kernel and removed it from # the previous cadidate. (better using sets ?) master_widget_list = self.find_master_tab(tab, as_list=True) slave_list = [widget for widget in filtered_widget_list if widget not in master_widget_list] return slave_list
[ "return", "all", "the", "frontends", "that", "do", "not", "own", "the", "kernel", "attached", "to", "the", "given", "widget", "/", "tab", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py#L307-L331
[ "def", "find_slave_widgets", "(", "self", ",", "tab", ")", ":", "#convert from/to int/richIpythonWidget if needed", "if", "isinstance", "(", "tab", ",", "int", ")", ":", "tab", "=", "self", ".", "tab_widget", ".", "widget", "(", "tab", ")", "km", "=", "tab", ".", "kernel_manager", "#build list of all widgets", "widget_list", "=", "[", "self", ".", "tab_widget", ".", "widget", "(", "i", ")", "for", "i", "in", "range", "(", "self", ".", "tab_widget", ".", "count", "(", ")", ")", "]", "# widget that are candidate not to be the owner of the kernel does have all the same port of the curent widget", "filtered_widget_list", "=", "(", "widget", "for", "widget", "in", "widget_list", "if", "widget", ".", "kernel_manager", ".", "connection_file", "==", "km", ".", "connection_file", ")", "# Get a list of all widget owning the same kernel and removed it from", "# the previous cadidate. (better using sets ?)", "master_widget_list", "=", "self", ".", "find_master_tab", "(", "tab", ",", "as_list", "=", "True", ")", "slave_list", "=", "[", "widget", "for", "widget", "in", "filtered_widget_list", "if", "widget", "not", "in", "master_widget_list", "]", "return", "slave_list" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
MainWindow.add_menu_action
Add action to menu as well as self So that when the menu bar is invisible, its actions are still available. If defer_shortcut is True, set the shortcut context to widget-only, where it will avoid conflict with shortcuts already bound to the widgets themselves.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py
def add_menu_action(self, menu, action, defer_shortcut=False): """Add action to menu as well as self So that when the menu bar is invisible, its actions are still available. If defer_shortcut is True, set the shortcut context to widget-only, where it will avoid conflict with shortcuts already bound to the widgets themselves. """ menu.addAction(action) self.addAction(action) if defer_shortcut: action.setShortcutContext(QtCore.Qt.WidgetShortcut)
def add_menu_action(self, menu, action, defer_shortcut=False): """Add action to menu as well as self So that when the menu bar is invisible, its actions are still available. If defer_shortcut is True, set the shortcut context to widget-only, where it will avoid conflict with shortcuts already bound to the widgets themselves. """ menu.addAction(action) self.addAction(action) if defer_shortcut: action.setShortcutContext(QtCore.Qt.WidgetShortcut)
[ "Add", "action", "to", "menu", "as", "well", "as", "self", "So", "that", "when", "the", "menu", "bar", "is", "invisible", "its", "actions", "are", "still", "available", ".", "If", "defer_shortcut", "is", "True", "set", "the", "shortcut", "context", "to", "widget", "-", "only", "where", "it", "will", "avoid", "conflict", "with", "shortcuts", "already", "bound", "to", "the", "widgets", "themselves", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py#L334-L347
[ "def", "add_menu_action", "(", "self", ",", "menu", ",", "action", ",", "defer_shortcut", "=", "False", ")", ":", "menu", ".", "addAction", "(", "action", ")", "self", ".", "addAction", "(", "action", ")", "if", "defer_shortcut", ":", "action", ".", "setShortcutContext", "(", "QtCore", ".", "Qt", ".", "WidgetShortcut", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
MainWindow._make_dynamic_magic
Return a function `fun` that will execute `magic` on active frontend. Parameters ---------- magic : string string that will be executed as is when the returned function is called Returns ------- fun : function function with no parameters, when called will execute `magic` on the current active frontend at call time See Also -------- populate_all_magic_menu : generate the "All Magics..." menu Notes ----- `fun` executes `magic` in active frontend at the moment it is triggered, not the active frontend at the moment it was created. This function is mostly used to create the "All Magics..." Menu at run time.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py
def _make_dynamic_magic(self,magic): """Return a function `fun` that will execute `magic` on active frontend. Parameters ---------- magic : string string that will be executed as is when the returned function is called Returns ------- fun : function function with no parameters, when called will execute `magic` on the current active frontend at call time See Also -------- populate_all_magic_menu : generate the "All Magics..." menu Notes ----- `fun` executes `magic` in active frontend at the moment it is triggered, not the active frontend at the moment it was created. This function is mostly used to create the "All Magics..." Menu at run time. """ # need two level nested function to be sure to pass magic # to active frontend **at run time**. def inner_dynamic_magic(): self.active_frontend.execute(magic) inner_dynamic_magic.__name__ = "dynamics_magic_s" return inner_dynamic_magic
def _make_dynamic_magic(self,magic): """Return a function `fun` that will execute `magic` on active frontend. Parameters ---------- magic : string string that will be executed as is when the returned function is called Returns ------- fun : function function with no parameters, when called will execute `magic` on the current active frontend at call time See Also -------- populate_all_magic_menu : generate the "All Magics..." menu Notes ----- `fun` executes `magic` in active frontend at the moment it is triggered, not the active frontend at the moment it was created. This function is mostly used to create the "All Magics..." Menu at run time. """ # need two level nested function to be sure to pass magic # to active frontend **at run time**. def inner_dynamic_magic(): self.active_frontend.execute(magic) inner_dynamic_magic.__name__ = "dynamics_magic_s" return inner_dynamic_magic
[ "Return", "a", "function", "fun", "that", "will", "execute", "magic", "on", "active", "frontend", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py#L566-L596
[ "def", "_make_dynamic_magic", "(", "self", ",", "magic", ")", ":", "# need two level nested function to be sure to pass magic", "# to active frontend **at run time**.", "def", "inner_dynamic_magic", "(", ")", ":", "self", ".", "active_frontend", ".", "execute", "(", "magic", ")", "inner_dynamic_magic", ".", "__name__", "=", "\"dynamics_magic_s\"", "return", "inner_dynamic_magic" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
MainWindow.populate_all_magic_menu
Clean "All Magics..." menu and repopulate it with `listofmagic` Parameters ---------- listofmagic : string, repr() of a list of strings, send back by the kernel Notes ----- `listofmagic`is a repr() of list because it is fed with the result of a 'user_expression'
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py
def populate_all_magic_menu(self, listofmagic=None): """Clean "All Magics..." menu and repopulate it with `listofmagic` Parameters ---------- listofmagic : string, repr() of a list of strings, send back by the kernel Notes ----- `listofmagic`is a repr() of list because it is fed with the result of a 'user_expression' """ for k,v in self._magic_menu_dict.items(): v.clear() self.all_magic_menu.clear() protected_magic = set(["more","less","load_ext","pycat","loadpy","load","save","psource"]) mlist=ast.literal_eval(listofmagic) for magic in mlist: cell = (magic['type'] == 'cell') name = magic['name'] mclass = magic['class'] if cell : prefix='%%' else : prefix='%' magic_menu = self._get_magic_menu(mclass) if name in protected_magic: suffix = '?' else : suffix = '' pmagic = '%s%s%s'%(prefix,name,suffix) xaction = QtGui.QAction(pmagic, self, triggered=self._make_dynamic_magic(pmagic) ) magic_menu.addAction(xaction) self.all_magic_menu.addAction(xaction)
def populate_all_magic_menu(self, listofmagic=None): """Clean "All Magics..." menu and repopulate it with `listofmagic` Parameters ---------- listofmagic : string, repr() of a list of strings, send back by the kernel Notes ----- `listofmagic`is a repr() of list because it is fed with the result of a 'user_expression' """ for k,v in self._magic_menu_dict.items(): v.clear() self.all_magic_menu.clear() protected_magic = set(["more","less","load_ext","pycat","loadpy","load","save","psource"]) mlist=ast.literal_eval(listofmagic) for magic in mlist: cell = (magic['type'] == 'cell') name = magic['name'] mclass = magic['class'] if cell : prefix='%%' else : prefix='%' magic_menu = self._get_magic_menu(mclass) if name in protected_magic: suffix = '?' else : suffix = '' pmagic = '%s%s%s'%(prefix,name,suffix) xaction = QtGui.QAction(pmagic, self, triggered=self._make_dynamic_magic(pmagic) ) magic_menu.addAction(xaction) self.all_magic_menu.addAction(xaction)
[ "Clean", "All", "Magics", "...", "menu", "and", "repopulate", "it", "with", "listofmagic" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py#L598-L639
[ "def", "populate_all_magic_menu", "(", "self", ",", "listofmagic", "=", "None", ")", ":", "for", "k", ",", "v", "in", "self", ".", "_magic_menu_dict", ".", "items", "(", ")", ":", "v", ".", "clear", "(", ")", "self", ".", "all_magic_menu", ".", "clear", "(", ")", "protected_magic", "=", "set", "(", "[", "\"more\"", ",", "\"less\"", ",", "\"load_ext\"", ",", "\"pycat\"", ",", "\"loadpy\"", ",", "\"load\"", ",", "\"save\"", ",", "\"psource\"", "]", ")", "mlist", "=", "ast", ".", "literal_eval", "(", "listofmagic", ")", "for", "magic", "in", "mlist", ":", "cell", "=", "(", "magic", "[", "'type'", "]", "==", "'cell'", ")", "name", "=", "magic", "[", "'name'", "]", "mclass", "=", "magic", "[", "'class'", "]", "if", "cell", ":", "prefix", "=", "'%%'", "else", ":", "prefix", "=", "'%'", "magic_menu", "=", "self", ".", "_get_magic_menu", "(", "mclass", ")", "if", "name", "in", "protected_magic", ":", "suffix", "=", "'?'", "else", ":", "suffix", "=", "''", "pmagic", "=", "'%s%s%s'", "%", "(", "prefix", ",", "name", ",", "suffix", ")", "xaction", "=", "QtGui", ".", "QAction", "(", "pmagic", ",", "self", ",", "triggered", "=", "self", ".", "_make_dynamic_magic", "(", "pmagic", ")", ")", "magic_menu", ".", "addAction", "(", "xaction", ")", "self", ".", "all_magic_menu", ".", "addAction", "(", "xaction", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
MainWindow._get_magic_menu
return a submagic menu by name, and create it if needed parameters: ----------- menulabel : str Label for the menu Will infere the menu name from the identifier at creation if menulabel not given. To do so you have too give menuidentifier as a CamelCassedString
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py
def _get_magic_menu(self,menuidentifier, menulabel=None): """return a submagic menu by name, and create it if needed parameters: ----------- menulabel : str Label for the menu Will infere the menu name from the identifier at creation if menulabel not given. To do so you have too give menuidentifier as a CamelCassedString """ menu = self._magic_menu_dict.get(menuidentifier,None) if not menu : if not menulabel: menulabel = re.sub("([a-zA-Z]+)([A-Z][a-z])","\g<1> \g<2>",menuidentifier) menu = QtGui.QMenu(menulabel,self.magic_menu) self._magic_menu_dict[menuidentifier]=menu self.magic_menu.insertMenu(self.magic_menu_separator,menu) return menu
def _get_magic_menu(self,menuidentifier, menulabel=None): """return a submagic menu by name, and create it if needed parameters: ----------- menulabel : str Label for the menu Will infere the menu name from the identifier at creation if menulabel not given. To do so you have too give menuidentifier as a CamelCassedString """ menu = self._magic_menu_dict.get(menuidentifier,None) if not menu : if not menulabel: menulabel = re.sub("([a-zA-Z]+)([A-Z][a-z])","\g<1> \g<2>",menuidentifier) menu = QtGui.QMenu(menulabel,self.magic_menu) self._magic_menu_dict[menuidentifier]=menu self.magic_menu.insertMenu(self.magic_menu_separator,menu) return menu
[ "return", "a", "submagic", "menu", "by", "name", "and", "create", "it", "if", "needed", "parameters", ":", "-----------" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py#L651-L670
[ "def", "_get_magic_menu", "(", "self", ",", "menuidentifier", ",", "menulabel", "=", "None", ")", ":", "menu", "=", "self", ".", "_magic_menu_dict", ".", "get", "(", "menuidentifier", ",", "None", ")", "if", "not", "menu", ":", "if", "not", "menulabel", ":", "menulabel", "=", "re", ".", "sub", "(", "\"([a-zA-Z]+)([A-Z][a-z])\"", ",", "\"\\g<1> \\g<2>\"", ",", "menuidentifier", ")", "menu", "=", "QtGui", ".", "QMenu", "(", "menulabel", ",", "self", ".", "magic_menu", ")", "self", ".", "_magic_menu_dict", "[", "menuidentifier", "]", "=", "menu", "self", ".", "magic_menu", ".", "insertMenu", "(", "self", ".", "magic_menu_separator", ",", "menu", ")", "return", "menu" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
MainWindow.closeEvent
Forward the close event to every tabs contained by the windows
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py
def closeEvent(self, event): """ Forward the close event to every tabs contained by the windows """ if self.tab_widget.count() == 0: # no tabs, just close event.accept() return # Do Not loop on the widget count as it change while closing title = self.window().windowTitle() cancel = QtGui.QMessageBox.Cancel okay = QtGui.QMessageBox.Ok if self.confirm_exit: if self.tab_widget.count() > 1: msg = "Close all tabs, stop all kernels, and Quit?" else: msg = "Close console, stop kernel, and Quit?" info = "Kernels not started here (e.g. notebooks) will be left alone." closeall = QtGui.QPushButton("&Quit", self) closeall.setShortcut('Q') box = QtGui.QMessageBox(QtGui.QMessageBox.Question, title, msg) box.setInformativeText(info) box.addButton(cancel) box.addButton(closeall, QtGui.QMessageBox.YesRole) box.setDefaultButton(closeall) box.setEscapeButton(cancel) pixmap = QtGui.QPixmap(self._app.icon.pixmap(QtCore.QSize(64,64))) box.setIconPixmap(pixmap) reply = box.exec_() else: reply = okay if reply == cancel: event.ignore() return if reply == okay: while self.tab_widget.count() >= 1: # prevent further confirmations: widget = self.active_frontend widget._confirm_exit = False self.close_tab(widget) event.accept()
def closeEvent(self, event): """ Forward the close event to every tabs contained by the windows """ if self.tab_widget.count() == 0: # no tabs, just close event.accept() return # Do Not loop on the widget count as it change while closing title = self.window().windowTitle() cancel = QtGui.QMessageBox.Cancel okay = QtGui.QMessageBox.Ok if self.confirm_exit: if self.tab_widget.count() > 1: msg = "Close all tabs, stop all kernels, and Quit?" else: msg = "Close console, stop kernel, and Quit?" info = "Kernels not started here (e.g. notebooks) will be left alone." closeall = QtGui.QPushButton("&Quit", self) closeall.setShortcut('Q') box = QtGui.QMessageBox(QtGui.QMessageBox.Question, title, msg) box.setInformativeText(info) box.addButton(cancel) box.addButton(closeall, QtGui.QMessageBox.YesRole) box.setDefaultButton(closeall) box.setEscapeButton(cancel) pixmap = QtGui.QPixmap(self._app.icon.pixmap(QtCore.QSize(64,64))) box.setIconPixmap(pixmap) reply = box.exec_() else: reply = okay if reply == cancel: event.ignore() return if reply == okay: while self.tab_widget.count() >= 1: # prevent further confirmations: widget = self.active_frontend widget._confirm_exit = False self.close_tab(widget) event.accept()
[ "Forward", "the", "close", "event", "to", "every", "tabs", "contained", "by", "the", "windows" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py#L931-L973
[ "def", "closeEvent", "(", "self", ",", "event", ")", ":", "if", "self", ".", "tab_widget", ".", "count", "(", ")", "==", "0", ":", "# no tabs, just close", "event", ".", "accept", "(", ")", "return", "# Do Not loop on the widget count as it change while closing", "title", "=", "self", ".", "window", "(", ")", ".", "windowTitle", "(", ")", "cancel", "=", "QtGui", ".", "QMessageBox", ".", "Cancel", "okay", "=", "QtGui", ".", "QMessageBox", ".", "Ok", "if", "self", ".", "confirm_exit", ":", "if", "self", ".", "tab_widget", ".", "count", "(", ")", ">", "1", ":", "msg", "=", "\"Close all tabs, stop all kernels, and Quit?\"", "else", ":", "msg", "=", "\"Close console, stop kernel, and Quit?\"", "info", "=", "\"Kernels not started here (e.g. notebooks) will be left alone.\"", "closeall", "=", "QtGui", ".", "QPushButton", "(", "\"&Quit\"", ",", "self", ")", "closeall", ".", "setShortcut", "(", "'Q'", ")", "box", "=", "QtGui", ".", "QMessageBox", "(", "QtGui", ".", "QMessageBox", ".", "Question", ",", "title", ",", "msg", ")", "box", ".", "setInformativeText", "(", "info", ")", "box", ".", "addButton", "(", "cancel", ")", "box", ".", "addButton", "(", "closeall", ",", "QtGui", ".", "QMessageBox", ".", "YesRole", ")", "box", ".", "setDefaultButton", "(", "closeall", ")", "box", ".", "setEscapeButton", "(", "cancel", ")", "pixmap", "=", "QtGui", ".", "QPixmap", "(", "self", ".", "_app", ".", "icon", ".", "pixmap", "(", "QtCore", ".", "QSize", "(", "64", ",", "64", ")", ")", ")", "box", ".", "setIconPixmap", "(", "pixmap", ")", "reply", "=", "box", ".", "exec_", "(", ")", "else", ":", "reply", "=", "okay", "if", "reply", "==", "cancel", ":", "event", ".", "ignore", "(", ")", "return", "if", "reply", "==", "okay", ":", "while", "self", ".", "tab_widget", ".", "count", "(", ")", ">=", "1", ":", "# prevent further confirmations:", "widget", "=", "self", ".", "active_frontend", "widget", ".", "_confirm_exit", "=", "False", "self", ".", "close_tab", "(", "widget", ")", "event", ".", "accept", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
passwd
Generate hashed password and salt for use in notebook configuration. In the notebook configuration, set `c.NotebookApp.password` to the generated string. Parameters ---------- passphrase : str Password to hash. If unspecified, the user is asked to input and verify a password. algorithm : str Hashing algorithm to use (e.g, 'sha1' or any argument supported by :func:`hashlib.new`). Returns ------- hashed_passphrase : str Hashed password, in the format 'hash_algorithm:salt:passphrase_hash'. Examples -------- In [1]: passwd('mypassword') Out[1]: 'sha1:7cf3:b7d6da294ea9592a9480c8f52e63cd42cfb9dd12'
environment/lib/python2.7/site-packages/IPython/lib/security.py
def passwd(passphrase=None, algorithm='sha1'): """Generate hashed password and salt for use in notebook configuration. In the notebook configuration, set `c.NotebookApp.password` to the generated string. Parameters ---------- passphrase : str Password to hash. If unspecified, the user is asked to input and verify a password. algorithm : str Hashing algorithm to use (e.g, 'sha1' or any argument supported by :func:`hashlib.new`). Returns ------- hashed_passphrase : str Hashed password, in the format 'hash_algorithm:salt:passphrase_hash'. Examples -------- In [1]: passwd('mypassword') Out[1]: 'sha1:7cf3:b7d6da294ea9592a9480c8f52e63cd42cfb9dd12' """ if passphrase is None: for i in range(3): p0 = getpass.getpass('Enter password: ') p1 = getpass.getpass('Verify password: ') if p0 == p1: passphrase = p0 break else: print('Passwords do not match.') else: raise UsageError('No matching passwords found. Giving up.') h = hashlib.new(algorithm) salt = ('%0' + str(salt_len) + 'x') % random.getrandbits(4 * salt_len) h.update(cast_bytes(passphrase, 'utf-8') + str_to_bytes(salt, 'ascii')) return ':'.join((algorithm, salt, h.hexdigest()))
def passwd(passphrase=None, algorithm='sha1'): """Generate hashed password and salt for use in notebook configuration. In the notebook configuration, set `c.NotebookApp.password` to the generated string. Parameters ---------- passphrase : str Password to hash. If unspecified, the user is asked to input and verify a password. algorithm : str Hashing algorithm to use (e.g, 'sha1' or any argument supported by :func:`hashlib.new`). Returns ------- hashed_passphrase : str Hashed password, in the format 'hash_algorithm:salt:passphrase_hash'. Examples -------- In [1]: passwd('mypassword') Out[1]: 'sha1:7cf3:b7d6da294ea9592a9480c8f52e63cd42cfb9dd12' """ if passphrase is None: for i in range(3): p0 = getpass.getpass('Enter password: ') p1 = getpass.getpass('Verify password: ') if p0 == p1: passphrase = p0 break else: print('Passwords do not match.') else: raise UsageError('No matching passwords found. Giving up.') h = hashlib.new(algorithm) salt = ('%0' + str(salt_len) + 'x') % random.getrandbits(4 * salt_len) h.update(cast_bytes(passphrase, 'utf-8') + str_to_bytes(salt, 'ascii')) return ':'.join((algorithm, salt, h.hexdigest()))
[ "Generate", "hashed", "password", "and", "salt", "for", "use", "in", "notebook", "configuration", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/security.py#L30-L72
[ "def", "passwd", "(", "passphrase", "=", "None", ",", "algorithm", "=", "'sha1'", ")", ":", "if", "passphrase", "is", "None", ":", "for", "i", "in", "range", "(", "3", ")", ":", "p0", "=", "getpass", ".", "getpass", "(", "'Enter password: '", ")", "p1", "=", "getpass", ".", "getpass", "(", "'Verify password: '", ")", "if", "p0", "==", "p1", ":", "passphrase", "=", "p0", "break", "else", ":", "print", "(", "'Passwords do not match.'", ")", "else", ":", "raise", "UsageError", "(", "'No matching passwords found. Giving up.'", ")", "h", "=", "hashlib", ".", "new", "(", "algorithm", ")", "salt", "=", "(", "'%0'", "+", "str", "(", "salt_len", ")", "+", "'x'", ")", "%", "random", ".", "getrandbits", "(", "4", "*", "salt_len", ")", "h", ".", "update", "(", "cast_bytes", "(", "passphrase", ",", "'utf-8'", ")", "+", "str_to_bytes", "(", "salt", ",", "'ascii'", ")", ")", "return", "':'", ".", "join", "(", "(", "algorithm", ",", "salt", ",", "h", ".", "hexdigest", "(", ")", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
passwd_check
Verify that a given passphrase matches its hashed version. Parameters ---------- hashed_passphrase : str Hashed password, in the format returned by `passwd`. passphrase : str Passphrase to validate. Returns ------- valid : bool True if the passphrase matches the hash. Examples -------- In [1]: from IPython.lib.security import passwd_check In [2]: passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', ...: 'mypassword') Out[2]: True In [3]: passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', ...: 'anotherpassword') Out[3]: False
environment/lib/python2.7/site-packages/IPython/lib/security.py
def passwd_check(hashed_passphrase, passphrase): """Verify that a given passphrase matches its hashed version. Parameters ---------- hashed_passphrase : str Hashed password, in the format returned by `passwd`. passphrase : str Passphrase to validate. Returns ------- valid : bool True if the passphrase matches the hash. Examples -------- In [1]: from IPython.lib.security import passwd_check In [2]: passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', ...: 'mypassword') Out[2]: True In [3]: passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', ...: 'anotherpassword') Out[3]: False """ try: algorithm, salt, pw_digest = hashed_passphrase.split(':', 2) except (ValueError, TypeError): return False try: h = hashlib.new(algorithm) except ValueError: return False if len(pw_digest) == 0: return False h.update(cast_bytes(passphrase, 'utf-8') + str_to_bytes(salt, 'ascii')) return h.hexdigest() == pw_digest
def passwd_check(hashed_passphrase, passphrase): """Verify that a given passphrase matches its hashed version. Parameters ---------- hashed_passphrase : str Hashed password, in the format returned by `passwd`. passphrase : str Passphrase to validate. Returns ------- valid : bool True if the passphrase matches the hash. Examples -------- In [1]: from IPython.lib.security import passwd_check In [2]: passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', ...: 'mypassword') Out[2]: True In [3]: passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', ...: 'anotherpassword') Out[3]: False """ try: algorithm, salt, pw_digest = hashed_passphrase.split(':', 2) except (ValueError, TypeError): return False try: h = hashlib.new(algorithm) except ValueError: return False if len(pw_digest) == 0: return False h.update(cast_bytes(passphrase, 'utf-8') + str_to_bytes(salt, 'ascii')) return h.hexdigest() == pw_digest
[ "Verify", "that", "a", "given", "passphrase", "matches", "its", "hashed", "version", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/security.py#L75-L118
[ "def", "passwd_check", "(", "hashed_passphrase", ",", "passphrase", ")", ":", "try", ":", "algorithm", ",", "salt", ",", "pw_digest", "=", "hashed_passphrase", ".", "split", "(", "':'", ",", "2", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "False", "try", ":", "h", "=", "hashlib", ".", "new", "(", "algorithm", ")", "except", "ValueError", ":", "return", "False", "if", "len", "(", "pw_digest", ")", "==", "0", ":", "return", "False", "h", ".", "update", "(", "cast_bytes", "(", "passphrase", ",", "'utf-8'", ")", "+", "str_to_bytes", "(", "salt", ",", "'ascii'", ")", ")", "return", "h", ".", "hexdigest", "(", ")", "==", "pw_digest" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
django_boolean_icon
Return HTML code for a nice representation of true/false.
treeeditor/admin.py
def django_boolean_icon(field_val, alt_text=None, title=None): """ Return HTML code for a nice representation of true/false. """ # Origin: contrib/admin/templatetags/admin_list.py BOOLEAN_MAPPING = {True: 'yes', False: 'no', None: 'unknown'} alt_text = alt_text or BOOLEAN_MAPPING[field_val] if title is not None: title = 'title="%s" ' % title else: title = '' return mark_safe(u'<img src="%simg/icon-%s.gif" alt="%s" %s/>' % (settings.STATIC_URL, BOOLEAN_MAPPING[field_val], alt_text, title))
def django_boolean_icon(field_val, alt_text=None, title=None): """ Return HTML code for a nice representation of true/false. """ # Origin: contrib/admin/templatetags/admin_list.py BOOLEAN_MAPPING = {True: 'yes', False: 'no', None: 'unknown'} alt_text = alt_text or BOOLEAN_MAPPING[field_val] if title is not None: title = 'title="%s" ' % title else: title = '' return mark_safe(u'<img src="%simg/icon-%s.gif" alt="%s" %s/>' % (settings.STATIC_URL, BOOLEAN_MAPPING[field_val], alt_text, title))
[ "Return", "HTML", "code", "for", "a", "nice", "representation", "of", "true", "/", "false", "." ]
20tab/twentytab-treeeditor
python
https://github.com/20tab/twentytab-treeeditor/blob/f89d459b1348961880cd488df95690e68529f96b/treeeditor/admin.py#L15-L28
[ "def", "django_boolean_icon", "(", "field_val", ",", "alt_text", "=", "None", ",", "title", "=", "None", ")", ":", "# Origin: contrib/admin/templatetags/admin_list.py", "BOOLEAN_MAPPING", "=", "{", "True", ":", "'yes'", ",", "False", ":", "'no'", ",", "None", ":", "'unknown'", "}", "alt_text", "=", "alt_text", "or", "BOOLEAN_MAPPING", "[", "field_val", "]", "if", "title", "is", "not", "None", ":", "title", "=", "'title=\"%s\" '", "%", "title", "else", ":", "title", "=", "''", "return", "mark_safe", "(", "u'<img src=\"%simg/icon-%s.gif\" alt=\"%s\" %s/>'", "%", "(", "settings", ".", "STATIC_URL", ",", "BOOLEAN_MAPPING", "[", "field_val", "]", ",", "alt_text", ",", "title", ")", ")" ]
f89d459b1348961880cd488df95690e68529f96b
test
_build_tree_structure
Build an in-memory representation of the item tree, trying to keep database accesses down to a minimum. The returned dictionary looks like this (as json dump): {"6": [7, 8, 10] "7": [12], "8": [], ... }
treeeditor/admin.py
def _build_tree_structure(cls): """ Build an in-memory representation of the item tree, trying to keep database accesses down to a minimum. The returned dictionary looks like this (as json dump): {"6": [7, 8, 10] "7": [12], "8": [], ... } """ all_nodes = {} for p_id, parent_id in cls.objects.order_by(cls._mptt_meta.tree_id_attr, cls._mptt_meta.left_attr).values_list( "pk", "%s_id" % cls._mptt_meta.parent_attr ): all_nodes[p_id] = [] if parent_id: if not all_nodes.has_key(parent_id): # This happens very rarely, but protect against parents that # we have yet to iteratove over. all_nodes[parent_id] = [] all_nodes[parent_id].append(p_id) return all_nodes
def _build_tree_structure(cls): """ Build an in-memory representation of the item tree, trying to keep database accesses down to a minimum. The returned dictionary looks like this (as json dump): {"6": [7, 8, 10] "7": [12], "8": [], ... } """ all_nodes = {} for p_id, parent_id in cls.objects.order_by(cls._mptt_meta.tree_id_attr, cls._mptt_meta.left_attr).values_list( "pk", "%s_id" % cls._mptt_meta.parent_attr ): all_nodes[p_id] = [] if parent_id: if not all_nodes.has_key(parent_id): # This happens very rarely, but protect against parents that # we have yet to iteratove over. all_nodes[parent_id] = [] all_nodes[parent_id].append(p_id) return all_nodes
[ "Build", "an", "in", "-", "memory", "representation", "of", "the", "item", "tree", "trying", "to", "keep", "database", "accesses", "down", "to", "a", "minimum", ".", "The", "returned", "dictionary", "looks", "like", "this", "(", "as", "json", "dump", ")", ":" ]
20tab/twentytab-treeeditor
python
https://github.com/20tab/twentytab-treeeditor/blob/f89d459b1348961880cd488df95690e68529f96b/treeeditor/admin.py#L31-L57
[ "def", "_build_tree_structure", "(", "cls", ")", ":", "all_nodes", "=", "{", "}", "for", "p_id", ",", "parent_id", "in", "cls", ".", "objects", ".", "order_by", "(", "cls", ".", "_mptt_meta", ".", "tree_id_attr", ",", "cls", ".", "_mptt_meta", ".", "left_attr", ")", ".", "values_list", "(", "\"pk\"", ",", "\"%s_id\"", "%", "cls", ".", "_mptt_meta", ".", "parent_attr", ")", ":", "all_nodes", "[", "p_id", "]", "=", "[", "]", "if", "parent_id", ":", "if", "not", "all_nodes", ".", "has_key", "(", "parent_id", ")", ":", "# This happens very rarely, but protect against parents that", "# we have yet to iteratove over.", "all_nodes", "[", "parent_id", "]", "=", "[", "]", "all_nodes", "[", "parent_id", "]", ".", "append", "(", "p_id", ")", "return", "all_nodes" ]
f89d459b1348961880cd488df95690e68529f96b
test
ajax_editable_boolean_cell
Generate a html snippet for showing a boolean value on the admin page. Item is an object, attr is the attribute name we should display. Text is an optional explanatory text to be included in the output. This function will emit code to produce a checkbox input with its state corresponding to the item.attr attribute if no override value is passed. This input is wired to run a JS ajax updater to toggle the value. If override is passed in, ignores the attr attribute and returns a static image for the override boolean with no user interaction possible (useful for "disabled and you can't change it" situations).
treeeditor/admin.py
def ajax_editable_boolean_cell(item, attr, text='', override=None): """ Generate a html snippet for showing a boolean value on the admin page. Item is an object, attr is the attribute name we should display. Text is an optional explanatory text to be included in the output. This function will emit code to produce a checkbox input with its state corresponding to the item.attr attribute if no override value is passed. This input is wired to run a JS ajax updater to toggle the value. If override is passed in, ignores the attr attribute and returns a static image for the override boolean with no user interaction possible (useful for "disabled and you can't change it" situations). """ if text: text = '&nbsp;(%s)' % unicode(text) if override is not None: a = [django_boolean_icon(override, text), text] else: value = getattr(item, attr) a = [ '<input type="checkbox"', value and ' checked="checked"' or '', ' onclick="return inplace_toggle_boolean(%d, \'%s\')";' % (item.id, attr), ' />', text, ] a.insert(0, '<div id="wrap_%s_%d">' % ( attr, item.id )) a.append('</div>') return unicode(''.join(a))
def ajax_editable_boolean_cell(item, attr, text='', override=None): """ Generate a html snippet for showing a boolean value on the admin page. Item is an object, attr is the attribute name we should display. Text is an optional explanatory text to be included in the output. This function will emit code to produce a checkbox input with its state corresponding to the item.attr attribute if no override value is passed. This input is wired to run a JS ajax updater to toggle the value. If override is passed in, ignores the attr attribute and returns a static image for the override boolean with no user interaction possible (useful for "disabled and you can't change it" situations). """ if text: text = '&nbsp;(%s)' % unicode(text) if override is not None: a = [django_boolean_icon(override, text), text] else: value = getattr(item, attr) a = [ '<input type="checkbox"', value and ' checked="checked"' or '', ' onclick="return inplace_toggle_boolean(%d, \'%s\')";' % (item.id, attr), ' />', text, ] a.insert(0, '<div id="wrap_%s_%d">' % ( attr, item.id )) a.append('</div>') return unicode(''.join(a))
[ "Generate", "a", "html", "snippet", "for", "showing", "a", "boolean", "value", "on", "the", "admin", "page", ".", "Item", "is", "an", "object", "attr", "is", "the", "attribute", "name", "we", "should", "display", ".", "Text", "is", "an", "optional", "explanatory", "text", "to", "be", "included", "in", "the", "output", "." ]
20tab/twentytab-treeeditor
python
https://github.com/20tab/twentytab-treeeditor/blob/f89d459b1348961880cd488df95690e68529f96b/treeeditor/admin.py#L61-L92
[ "def", "ajax_editable_boolean_cell", "(", "item", ",", "attr", ",", "text", "=", "''", ",", "override", "=", "None", ")", ":", "if", "text", ":", "text", "=", "'&nbsp;(%s)'", "%", "unicode", "(", "text", ")", "if", "override", "is", "not", "None", ":", "a", "=", "[", "django_boolean_icon", "(", "override", ",", "text", ")", ",", "text", "]", "else", ":", "value", "=", "getattr", "(", "item", ",", "attr", ")", "a", "=", "[", "'<input type=\"checkbox\"'", ",", "value", "and", "' checked=\"checked\"'", "or", "''", ",", "' onclick=\"return inplace_toggle_boolean(%d, \\'%s\\')\";'", "%", "(", "item", ".", "id", ",", "attr", ")", ",", "' />'", ",", "text", ",", "]", "a", ".", "insert", "(", "0", ",", "'<div id=\"wrap_%s_%d\">'", "%", "(", "attr", ",", "item", ".", "id", ")", ")", "a", ".", "append", "(", "'</div>'", ")", "return", "unicode", "(", "''", ".", "join", "(", "a", ")", ")" ]
f89d459b1348961880cd488df95690e68529f96b
test
ajax_editable_boolean
Convenience function: Assign the return value of this method to a variable of your ModelAdmin class and put the variable name into list_display. Example:: class MyTreeEditor(TreeEditor): list_display = ('__unicode__', 'active_toggle') active_toggle = ajax_editable_boolean('active', _('is active'))
treeeditor/admin.py
def ajax_editable_boolean(attr, short_description): """ Convenience function: Assign the return value of this method to a variable of your ModelAdmin class and put the variable name into list_display. Example:: class MyTreeEditor(TreeEditor): list_display = ('__unicode__', 'active_toggle') active_toggle = ajax_editable_boolean('active', _('is active')) """ def _fn(self, item): return ajax_editable_boolean_cell(item, attr) _fn.allow_tags = True _fn.short_description = short_description _fn.editable_boolean_field = attr return _fn
def ajax_editable_boolean(attr, short_description): """ Convenience function: Assign the return value of this method to a variable of your ModelAdmin class and put the variable name into list_display. Example:: class MyTreeEditor(TreeEditor): list_display = ('__unicode__', 'active_toggle') active_toggle = ajax_editable_boolean('active', _('is active')) """ def _fn(self, item): return ajax_editable_boolean_cell(item, attr) _fn.allow_tags = True _fn.short_description = short_description _fn.editable_boolean_field = attr return _fn
[ "Convenience", "function", ":", "Assign", "the", "return", "value", "of", "this", "method", "to", "a", "variable", "of", "your", "ModelAdmin", "class", "and", "put", "the", "variable", "name", "into", "list_display", "." ]
20tab/twentytab-treeeditor
python
https://github.com/20tab/twentytab-treeeditor/blob/f89d459b1348961880cd488df95690e68529f96b/treeeditor/admin.py#L96-L115
[ "def", "ajax_editable_boolean", "(", "attr", ",", "short_description", ")", ":", "def", "_fn", "(", "self", ",", "item", ")", ":", "return", "ajax_editable_boolean_cell", "(", "item", ",", "attr", ")", "_fn", ".", "allow_tags", "=", "True", "_fn", ".", "short_description", "=", "short_description", "_fn", ".", "editable_boolean_field", "=", "attr", "return", "_fn" ]
f89d459b1348961880cd488df95690e68529f96b
test
TreeEditor.indented_short_title
Generate a short title for an object, indent it depending on the object's depth in the hierarchy.
treeeditor/admin.py
def indented_short_title(self, item): r = "" """ Generate a short title for an object, indent it depending on the object's depth in the hierarchy. """ if hasattr(item, 'get_absolute_url'): r = '<input type="hidden" class="medialibrary_file_path" value="%s" />' % item.get_absolute_url() editable_class = '' if not getattr(item, 'feincms_editable', True): editable_class = ' tree-item-not-editable' r += '<span id="page_marker-%d" class="page_marker%s" style="width: %dpx;">&nbsp;</span>&nbsp;' % ( item.id, editable_class, 14 + item.level * 18) # r += '<span tabindex="0">' if hasattr(item, 'short_title'): r += item.short_title() else: r += unicode(item) # r += '</span>' return mark_safe(r)
def indented_short_title(self, item): r = "" """ Generate a short title for an object, indent it depending on the object's depth in the hierarchy. """ if hasattr(item, 'get_absolute_url'): r = '<input type="hidden" class="medialibrary_file_path" value="%s" />' % item.get_absolute_url() editable_class = '' if not getattr(item, 'feincms_editable', True): editable_class = ' tree-item-not-editable' r += '<span id="page_marker-%d" class="page_marker%s" style="width: %dpx;">&nbsp;</span>&nbsp;' % ( item.id, editable_class, 14 + item.level * 18) # r += '<span tabindex="0">' if hasattr(item, 'short_title'): r += item.short_title() else: r += unicode(item) # r += '</span>' return mark_safe(r)
[ "Generate", "a", "short", "title", "for", "an", "object", "indent", "it", "depending", "on", "the", "object", "s", "depth", "in", "the", "hierarchy", "." ]
20tab/twentytab-treeeditor
python
https://github.com/20tab/twentytab-treeeditor/blob/f89d459b1348961880cd488df95690e68529f96b/treeeditor/admin.py#L189-L210
[ "def", "indented_short_title", "(", "self", ",", "item", ")", ":", "r", "=", "\"\"", "if", "hasattr", "(", "item", ",", "'get_absolute_url'", ")", ":", "r", "=", "'<input type=\"hidden\" class=\"medialibrary_file_path\" value=\"%s\" />'", "%", "item", ".", "get_absolute_url", "(", ")", "editable_class", "=", "''", "if", "not", "getattr", "(", "item", ",", "'feincms_editable'", ",", "True", ")", ":", "editable_class", "=", "' tree-item-not-editable'", "r", "+=", "'<span id=\"page_marker-%d\" class=\"page_marker%s\" style=\"width: %dpx;\">&nbsp;</span>&nbsp;'", "%", "(", "item", ".", "id", ",", "editable_class", ",", "14", "+", "item", ".", "level", "*", "18", ")", "# r += '<span tabindex=\"0\">'", "if", "hasattr", "(", "item", ",", "'short_title'", ")", ":", "r", "+=", "item", ".", "short_title", "(", ")", "else", ":", "r", "+=", "unicode", "(", "item", ")", "# r += '</span>'", "return", "mark_safe", "(", "r", ")" ]
f89d459b1348961880cd488df95690e68529f96b
test
TreeEditor._collect_editable_booleans
Collect all fields marked as editable booleans. We do not want the user to be able to edit arbitrary fields by crafting an AJAX request by hand.
treeeditor/admin.py
def _collect_editable_booleans(self): """ Collect all fields marked as editable booleans. We do not want the user to be able to edit arbitrary fields by crafting an AJAX request by hand. """ if hasattr(self, '_ajax_editable_booleans'): return self._ajax_editable_booleans = {} for field in self.list_display: # The ajax_editable_boolean return value has to be assigned # to the ModelAdmin class item = getattr(self.__class__, field, None) if not item: continue attr = getattr(item, 'editable_boolean_field', None) if attr: def _fn(self, instance): return [ajax_editable_boolean_cell(instance, _fn.attr)] _fn.attr = attr result_func = getattr(item, 'editable_boolean_result', _fn) self._ajax_editable_booleans[attr] = result_func
def _collect_editable_booleans(self): """ Collect all fields marked as editable booleans. We do not want the user to be able to edit arbitrary fields by crafting an AJAX request by hand. """ if hasattr(self, '_ajax_editable_booleans'): return self._ajax_editable_booleans = {} for field in self.list_display: # The ajax_editable_boolean return value has to be assigned # to the ModelAdmin class item = getattr(self.__class__, field, None) if not item: continue attr = getattr(item, 'editable_boolean_field', None) if attr: def _fn(self, instance): return [ajax_editable_boolean_cell(instance, _fn.attr)] _fn.attr = attr result_func = getattr(item, 'editable_boolean_result', _fn) self._ajax_editable_booleans[attr] = result_func
[ "Collect", "all", "fields", "marked", "as", "editable", "booleans", ".", "We", "do", "not", "want", "the", "user", "to", "be", "able", "to", "edit", "arbitrary", "fields", "by", "crafting", "an", "AJAX", "request", "by", "hand", "." ]
20tab/twentytab-treeeditor
python
https://github.com/20tab/twentytab-treeeditor/blob/f89d459b1348961880cd488df95690e68529f96b/treeeditor/admin.py#L215-L240
[ "def", "_collect_editable_booleans", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'_ajax_editable_booleans'", ")", ":", "return", "self", ".", "_ajax_editable_booleans", "=", "{", "}", "for", "field", "in", "self", ".", "list_display", ":", "# The ajax_editable_boolean return value has to be assigned", "# to the ModelAdmin class", "item", "=", "getattr", "(", "self", ".", "__class__", ",", "field", ",", "None", ")", "if", "not", "item", ":", "continue", "attr", "=", "getattr", "(", "item", ",", "'editable_boolean_field'", ",", "None", ")", "if", "attr", ":", "def", "_fn", "(", "self", ",", "instance", ")", ":", "return", "[", "ajax_editable_boolean_cell", "(", "instance", ",", "_fn", ".", "attr", ")", "]", "_fn", ".", "attr", "=", "attr", "result_func", "=", "getattr", "(", "item", ",", "'editable_boolean_result'", ",", "_fn", ")", "self", ".", "_ajax_editable_booleans", "[", "attr", "]", "=", "result_func" ]
f89d459b1348961880cd488df95690e68529f96b
test
TreeEditor._toggle_boolean
Handle an AJAX toggle_boolean request
treeeditor/admin.py
def _toggle_boolean(self, request): """ Handle an AJAX toggle_boolean request """ try: item_id = int(request.POST.get('item_id', None)) attr = str(request.POST.get('attr', None)) except: return HttpResponseBadRequest("Malformed request") if not request.user.is_staff: logging.warning("Denied AJAX request by non-staff %s to toggle boolean %s for object #%s", request.user, attr, item_id) return HttpResponseForbidden("You do not have permission to access this object") self._collect_editable_booleans() if not self._ajax_editable_booleans.has_key(attr): return HttpResponseBadRequest("not a valid attribute %s" % attr) try: obj = self.model._default_manager.get(pk=item_id) except self.model.DoesNotExist: return HttpResponseNotFound("Object does not exist") can_change = False if hasattr(obj, "user_can") and obj.user_can(request.user, change_page=True): # Was added in c7f04dfb5d, but I've no idea what user_can is about. can_change = True else: can_change = self.has_change_permission(request, obj=obj) if not can_change: logging.warning("Denied AJAX request by %s to toggle boolean %s for object %s", request.user, attr, item_id) return HttpResponseForbidden("You do not have permission to access this object") logging.info("Processing request by %s to toggle %s on %s", request.user, attr, obj) try: before_data = self._ajax_editable_booleans[attr](self, obj) setattr(obj, attr, not getattr(obj, attr)) obj.save() self._refresh_changelist_caches() # ???: Perhaps better a post_save signal? # Construct html snippets to send back to client for status update data = self._ajax_editable_booleans[attr](self, obj) except Exception:#, e: logging.exception("Unhandled exception while toggling %s on %s", attr, obj) return HttpResponseServerError("Unable to toggle %s on %s" % (attr, obj)) # Weed out unchanged cells to keep the updates small. This assumes # that the order a possible get_descendents() returns does not change # before and after toggling this attribute. Unlikely, but still... d = [] for a, b in zip(before_data, data): if a != b: d.append(b) # TODO: Shorter: [ y for x,y in zip(a,b) if x!=y ] return HttpResponse(json.dumps(d), mimetype="application/json")
def _toggle_boolean(self, request): """ Handle an AJAX toggle_boolean request """ try: item_id = int(request.POST.get('item_id', None)) attr = str(request.POST.get('attr', None)) except: return HttpResponseBadRequest("Malformed request") if not request.user.is_staff: logging.warning("Denied AJAX request by non-staff %s to toggle boolean %s for object #%s", request.user, attr, item_id) return HttpResponseForbidden("You do not have permission to access this object") self._collect_editable_booleans() if not self._ajax_editable_booleans.has_key(attr): return HttpResponseBadRequest("not a valid attribute %s" % attr) try: obj = self.model._default_manager.get(pk=item_id) except self.model.DoesNotExist: return HttpResponseNotFound("Object does not exist") can_change = False if hasattr(obj, "user_can") and obj.user_can(request.user, change_page=True): # Was added in c7f04dfb5d, but I've no idea what user_can is about. can_change = True else: can_change = self.has_change_permission(request, obj=obj) if not can_change: logging.warning("Denied AJAX request by %s to toggle boolean %s for object %s", request.user, attr, item_id) return HttpResponseForbidden("You do not have permission to access this object") logging.info("Processing request by %s to toggle %s on %s", request.user, attr, obj) try: before_data = self._ajax_editable_booleans[attr](self, obj) setattr(obj, attr, not getattr(obj, attr)) obj.save() self._refresh_changelist_caches() # ???: Perhaps better a post_save signal? # Construct html snippets to send back to client for status update data = self._ajax_editable_booleans[attr](self, obj) except Exception:#, e: logging.exception("Unhandled exception while toggling %s on %s", attr, obj) return HttpResponseServerError("Unable to toggle %s on %s" % (attr, obj)) # Weed out unchanged cells to keep the updates small. This assumes # that the order a possible get_descendents() returns does not change # before and after toggling this attribute. Unlikely, but still... d = [] for a, b in zip(before_data, data): if a != b: d.append(b) # TODO: Shorter: [ y for x,y in zip(a,b) if x!=y ] return HttpResponse(json.dumps(d), mimetype="application/json")
[ "Handle", "an", "AJAX", "toggle_boolean", "request" ]
20tab/twentytab-treeeditor
python
https://github.com/20tab/twentytab-treeeditor/blob/f89d459b1348961880cd488df95690e68529f96b/treeeditor/admin.py#L252-L315
[ "def", "_toggle_boolean", "(", "self", ",", "request", ")", ":", "try", ":", "item_id", "=", "int", "(", "request", ".", "POST", ".", "get", "(", "'item_id'", ",", "None", ")", ")", "attr", "=", "str", "(", "request", ".", "POST", ".", "get", "(", "'attr'", ",", "None", ")", ")", "except", ":", "return", "HttpResponseBadRequest", "(", "\"Malformed request\"", ")", "if", "not", "request", ".", "user", ".", "is_staff", ":", "logging", ".", "warning", "(", "\"Denied AJAX request by non-staff %s to toggle boolean %s for object #%s\"", ",", "request", ".", "user", ",", "attr", ",", "item_id", ")", "return", "HttpResponseForbidden", "(", "\"You do not have permission to access this object\"", ")", "self", ".", "_collect_editable_booleans", "(", ")", "if", "not", "self", ".", "_ajax_editable_booleans", ".", "has_key", "(", "attr", ")", ":", "return", "HttpResponseBadRequest", "(", "\"not a valid attribute %s\"", "%", "attr", ")", "try", ":", "obj", "=", "self", ".", "model", ".", "_default_manager", ".", "get", "(", "pk", "=", "item_id", ")", "except", "self", ".", "model", ".", "DoesNotExist", ":", "return", "HttpResponseNotFound", "(", "\"Object does not exist\"", ")", "can_change", "=", "False", "if", "hasattr", "(", "obj", ",", "\"user_can\"", ")", "and", "obj", ".", "user_can", "(", "request", ".", "user", ",", "change_page", "=", "True", ")", ":", "# Was added in c7f04dfb5d, but I've no idea what user_can is about.", "can_change", "=", "True", "else", ":", "can_change", "=", "self", ".", "has_change_permission", "(", "request", ",", "obj", "=", "obj", ")", "if", "not", "can_change", ":", "logging", ".", "warning", "(", "\"Denied AJAX request by %s to toggle boolean %s for object %s\"", ",", "request", ".", "user", ",", "attr", ",", "item_id", ")", "return", "HttpResponseForbidden", "(", "\"You do not have permission to access this object\"", ")", "logging", ".", "info", "(", "\"Processing request by %s to toggle %s on %s\"", ",", "request", ".", "user", ",", "attr", ",", "obj", ")", "try", ":", "before_data", "=", "self", ".", "_ajax_editable_booleans", "[", "attr", "]", "(", "self", ",", "obj", ")", "setattr", "(", "obj", ",", "attr", ",", "not", "getattr", "(", "obj", ",", "attr", ")", ")", "obj", ".", "save", "(", ")", "self", ".", "_refresh_changelist_caches", "(", ")", "# ???: Perhaps better a post_save signal?", "# Construct html snippets to send back to client for status update", "data", "=", "self", ".", "_ajax_editable_booleans", "[", "attr", "]", "(", "self", ",", "obj", ")", "except", "Exception", ":", "#, e:", "logging", ".", "exception", "(", "\"Unhandled exception while toggling %s on %s\"", ",", "attr", ",", "obj", ")", "return", "HttpResponseServerError", "(", "\"Unable to toggle %s on %s\"", "%", "(", "attr", ",", "obj", ")", ")", "# Weed out unchanged cells to keep the updates small. This assumes", "# that the order a possible get_descendents() returns does not change", "# before and after toggling this attribute. Unlikely, but still...", "d", "=", "[", "]", "for", "a", ",", "b", "in", "zip", "(", "before_data", ",", "data", ")", ":", "if", "a", "!=", "b", ":", "d", ".", "append", "(", "b", ")", "# TODO: Shorter: [ y for x,y in zip(a,b) if x!=y ]", "return", "HttpResponse", "(", "json", ".", "dumps", "(", "d", ")", ",", "mimetype", "=", "\"application/json\"", ")" ]
f89d459b1348961880cd488df95690e68529f96b
test
TreeEditor.changelist_view
Handle the changelist view, the django view for the model instances change list/actions page.
treeeditor/admin.py
def changelist_view(self, request, extra_context=None, *args, **kwargs): """ Handle the changelist view, the django view for the model instances change list/actions page. """ if 'actions_column' not in self.list_display: self.list_display.append('actions_column') # handle common AJAX requests if request.is_ajax(): cmd = request.POST.get('__cmd') if cmd == 'toggle_boolean': return self._toggle_boolean(request) elif cmd == 'move_node': return self._move_node(request) else: return HttpResponseBadRequest('Oops. AJAX request not understood.') self._refresh_changelist_caches() extra_context = extra_context or {} extra_context['STATIC_URL'] = settings.STATIC_URL extra_context['JQUERY_LIB'] = settings.JQUERY_LIB extra_context['JQUERYUI_LIB'] = settings.JQUERYUI_LIB extra_context['tree_structure'] = mark_safe(json.dumps( _build_tree_structure(self.model))) return super(TreeEditor, self).changelist_view(request, extra_context, *args, **kwargs)
def changelist_view(self, request, extra_context=None, *args, **kwargs): """ Handle the changelist view, the django view for the model instances change list/actions page. """ if 'actions_column' not in self.list_display: self.list_display.append('actions_column') # handle common AJAX requests if request.is_ajax(): cmd = request.POST.get('__cmd') if cmd == 'toggle_boolean': return self._toggle_boolean(request) elif cmd == 'move_node': return self._move_node(request) else: return HttpResponseBadRequest('Oops. AJAX request not understood.') self._refresh_changelist_caches() extra_context = extra_context or {} extra_context['STATIC_URL'] = settings.STATIC_URL extra_context['JQUERY_LIB'] = settings.JQUERY_LIB extra_context['JQUERYUI_LIB'] = settings.JQUERYUI_LIB extra_context['tree_structure'] = mark_safe(json.dumps( _build_tree_structure(self.model))) return super(TreeEditor, self).changelist_view(request, extra_context, *args, **kwargs)
[ "Handle", "the", "changelist", "view", "the", "django", "view", "for", "the", "model", "instances", "change", "list", "/", "actions", "page", "." ]
20tab/twentytab-treeeditor
python
https://github.com/20tab/twentytab-treeeditor/blob/f89d459b1348961880cd488df95690e68529f96b/treeeditor/admin.py#L320-L348
[ "def", "changelist_view", "(", "self", ",", "request", ",", "extra_context", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'actions_column'", "not", "in", "self", ".", "list_display", ":", "self", ".", "list_display", ".", "append", "(", "'actions_column'", ")", "# handle common AJAX requests", "if", "request", ".", "is_ajax", "(", ")", ":", "cmd", "=", "request", ".", "POST", ".", "get", "(", "'__cmd'", ")", "if", "cmd", "==", "'toggle_boolean'", ":", "return", "self", ".", "_toggle_boolean", "(", "request", ")", "elif", "cmd", "==", "'move_node'", ":", "return", "self", ".", "_move_node", "(", "request", ")", "else", ":", "return", "HttpResponseBadRequest", "(", "'Oops. AJAX request not understood.'", ")", "self", ".", "_refresh_changelist_caches", "(", ")", "extra_context", "=", "extra_context", "or", "{", "}", "extra_context", "[", "'STATIC_URL'", "]", "=", "settings", ".", "STATIC_URL", "extra_context", "[", "'JQUERY_LIB'", "]", "=", "settings", ".", "JQUERY_LIB", "extra_context", "[", "'JQUERYUI_LIB'", "]", "=", "settings", ".", "JQUERYUI_LIB", "extra_context", "[", "'tree_structure'", "]", "=", "mark_safe", "(", "json", ".", "dumps", "(", "_build_tree_structure", "(", "self", ".", "model", ")", ")", ")", "return", "super", "(", "TreeEditor", ",", "self", ")", ".", "changelist_view", "(", "request", ",", "extra_context", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
f89d459b1348961880cd488df95690e68529f96b
test
TreeEditor.has_change_permission
Implement a lookup for object level permissions. Basically the same as ModelAdmin.has_change_permission, but also passes the obj parameter in.
treeeditor/admin.py
def has_change_permission(self, request, obj=None): """ Implement a lookup for object level permissions. Basically the same as ModelAdmin.has_change_permission, but also passes the obj parameter in. """ if settings.TREE_EDITOR_OBJECT_PERMISSIONS: opts = self.opts r = request.user.has_perm(opts.app_label + '.' + opts.get_change_permission(), obj) else: r = True return r and super(TreeEditor, self).has_change_permission(request, obj)
def has_change_permission(self, request, obj=None): """ Implement a lookup for object level permissions. Basically the same as ModelAdmin.has_change_permission, but also passes the obj parameter in. """ if settings.TREE_EDITOR_OBJECT_PERMISSIONS: opts = self.opts r = request.user.has_perm(opts.app_label + '.' + opts.get_change_permission(), obj) else: r = True return r and super(TreeEditor, self).has_change_permission(request, obj)
[ "Implement", "a", "lookup", "for", "object", "level", "permissions", ".", "Basically", "the", "same", "as", "ModelAdmin", ".", "has_change_permission", "but", "also", "passes", "the", "obj", "parameter", "in", "." ]
20tab/twentytab-treeeditor
python
https://github.com/20tab/twentytab-treeeditor/blob/f89d459b1348961880cd488df95690e68529f96b/treeeditor/admin.py#L350-L361
[ "def", "has_change_permission", "(", "self", ",", "request", ",", "obj", "=", "None", ")", ":", "if", "settings", ".", "TREE_EDITOR_OBJECT_PERMISSIONS", ":", "opts", "=", "self", ".", "opts", "r", "=", "request", ".", "user", ".", "has_perm", "(", "opts", ".", "app_label", "+", "'.'", "+", "opts", ".", "get_change_permission", "(", ")", ",", "obj", ")", "else", ":", "r", "=", "True", "return", "r", "and", "super", "(", "TreeEditor", ",", "self", ")", ".", "has_change_permission", "(", "request", ",", "obj", ")" ]
f89d459b1348961880cd488df95690e68529f96b
test
TreeEditor.has_delete_permission
Implement a lookup for object level permissions. Basically the same as ModelAdmin.has_delete_permission, but also passes the obj parameter in.
treeeditor/admin.py
def has_delete_permission(self, request, obj=None): """ Implement a lookup for object level permissions. Basically the same as ModelAdmin.has_delete_permission, but also passes the obj parameter in. """ if settings.TREE_EDITOR_OBJECT_PERMISSIONS: opts = self.opts r = request.user.has_perm(opts.app_label + '.' + opts.get_delete_permission(), obj) else: r = True return r and super(TreeEditor, self).has_delete_permission(request, obj)
def has_delete_permission(self, request, obj=None): """ Implement a lookup for object level permissions. Basically the same as ModelAdmin.has_delete_permission, but also passes the obj parameter in. """ if settings.TREE_EDITOR_OBJECT_PERMISSIONS: opts = self.opts r = request.user.has_perm(opts.app_label + '.' + opts.get_delete_permission(), obj) else: r = True return r and super(TreeEditor, self).has_delete_permission(request, obj)
[ "Implement", "a", "lookup", "for", "object", "level", "permissions", ".", "Basically", "the", "same", "as", "ModelAdmin", ".", "has_delete_permission", "but", "also", "passes", "the", "obj", "parameter", "in", "." ]
20tab/twentytab-treeeditor
python
https://github.com/20tab/twentytab-treeeditor/blob/f89d459b1348961880cd488df95690e68529f96b/treeeditor/admin.py#L363-L374
[ "def", "has_delete_permission", "(", "self", ",", "request", ",", "obj", "=", "None", ")", ":", "if", "settings", ".", "TREE_EDITOR_OBJECT_PERMISSIONS", ":", "opts", "=", "self", ".", "opts", "r", "=", "request", ".", "user", ".", "has_perm", "(", "opts", ".", "app_label", "+", "'.'", "+", "opts", ".", "get_delete_permission", "(", ")", ",", "obj", ")", "else", ":", "r", "=", "True", "return", "r", "and", "super", "(", "TreeEditor", ",", "self", ")", ".", "has_delete_permission", "(", "request", ",", "obj", ")" ]
f89d459b1348961880cd488df95690e68529f96b
test
random_dag
Generate a random Directed Acyclic Graph (DAG) with a given number of nodes and edges.
environment/share/doc/ipython/examples/parallel/dagdeps.py
def random_dag(nodes, edges): """Generate a random Directed Acyclic Graph (DAG) with a given number of nodes and edges.""" G = nx.DiGraph() for i in range(nodes): G.add_node(i) while edges > 0: a = randint(0,nodes-1) b=a while b==a: b = randint(0,nodes-1) G.add_edge(a,b) if nx.is_directed_acyclic_graph(G): edges -= 1 else: # we closed a loop! G.remove_edge(a,b) return G
def random_dag(nodes, edges): """Generate a random Directed Acyclic Graph (DAG) with a given number of nodes and edges.""" G = nx.DiGraph() for i in range(nodes): G.add_node(i) while edges > 0: a = randint(0,nodes-1) b=a while b==a: b = randint(0,nodes-1) G.add_edge(a,b) if nx.is_directed_acyclic_graph(G): edges -= 1 else: # we closed a loop! G.remove_edge(a,b) return G
[ "Generate", "a", "random", "Directed", "Acyclic", "Graph", "(", "DAG", ")", "with", "a", "given", "number", "of", "nodes", "and", "edges", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/dagdeps.py#L20-L36
[ "def", "random_dag", "(", "nodes", ",", "edges", ")", ":", "G", "=", "nx", ".", "DiGraph", "(", ")", "for", "i", "in", "range", "(", "nodes", ")", ":", "G", ".", "add_node", "(", "i", ")", "while", "edges", ">", "0", ":", "a", "=", "randint", "(", "0", ",", "nodes", "-", "1", ")", "b", "=", "a", "while", "b", "==", "a", ":", "b", "=", "randint", "(", "0", ",", "nodes", "-", "1", ")", "G", ".", "add_edge", "(", "a", ",", "b", ")", "if", "nx", ".", "is_directed_acyclic_graph", "(", "G", ")", ":", "edges", "-=", "1", "else", ":", "# we closed a loop!", "G", ".", "remove_edge", "(", "a", ",", "b", ")", "return", "G" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
add_children
Add children recursively to a binary tree.
environment/share/doc/ipython/examples/parallel/dagdeps.py
def add_children(G, parent, level, n=2): """Add children recursively to a binary tree.""" if level == 0: return for i in range(n): child = parent+str(i) G.add_node(child) G.add_edge(parent,child) add_children(G, child, level-1, n)
def add_children(G, parent, level, n=2): """Add children recursively to a binary tree.""" if level == 0: return for i in range(n): child = parent+str(i) G.add_node(child) G.add_edge(parent,child) add_children(G, child, level-1, n)
[ "Add", "children", "recursively", "to", "a", "binary", "tree", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/dagdeps.py#L38-L46
[ "def", "add_children", "(", "G", ",", "parent", ",", "level", ",", "n", "=", "2", ")", ":", "if", "level", "==", "0", ":", "return", "for", "i", "in", "range", "(", "n", ")", ":", "child", "=", "parent", "+", "str", "(", "i", ")", "G", ".", "add_node", "(", "child", ")", "G", ".", "add_edge", "(", "parent", ",", "child", ")", "add_children", "(", "G", ",", "child", ",", "level", "-", "1", ",", "n", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
make_bintree
Make a symmetrical binary tree with @levels
environment/share/doc/ipython/examples/parallel/dagdeps.py
def make_bintree(levels): """Make a symmetrical binary tree with @levels""" G = nx.DiGraph() root = '0' G.add_node(root) add_children(G, root, levels, 2) return G
def make_bintree(levels): """Make a symmetrical binary tree with @levels""" G = nx.DiGraph() root = '0' G.add_node(root) add_children(G, root, levels, 2) return G
[ "Make", "a", "symmetrical", "binary", "tree", "with" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/dagdeps.py#L48-L54
[ "def", "make_bintree", "(", "levels", ")", ":", "G", "=", "nx", ".", "DiGraph", "(", ")", "root", "=", "'0'", "G", ".", "add_node", "(", "root", ")", "add_children", "(", "G", ",", "root", ",", "levels", ",", "2", ")", "return", "G" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
submit_jobs
Submit jobs via client where G describes the time dependencies.
environment/share/doc/ipython/examples/parallel/dagdeps.py
def submit_jobs(view, G, jobs): """Submit jobs via client where G describes the time dependencies.""" results = {} for node in nx.topological_sort(G): with view.temp_flags(after=[ results[n] for n in G.predecessors(node) ]): results[node] = view.apply(jobs[node]) return results
def submit_jobs(view, G, jobs): """Submit jobs via client where G describes the time dependencies.""" results = {} for node in nx.topological_sort(G): with view.temp_flags(after=[ results[n] for n in G.predecessors(node) ]): results[node] = view.apply(jobs[node]) return results
[ "Submit", "jobs", "via", "client", "where", "G", "describes", "the", "time", "dependencies", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/dagdeps.py#L56-L62
[ "def", "submit_jobs", "(", "view", ",", "G", ",", "jobs", ")", ":", "results", "=", "{", "}", "for", "node", "in", "nx", ".", "topological_sort", "(", "G", ")", ":", "with", "view", ".", "temp_flags", "(", "after", "=", "[", "results", "[", "n", "]", "for", "n", "in", "G", ".", "predecessors", "(", "node", ")", "]", ")", ":", "results", "[", "node", "]", "=", "view", ".", "apply", "(", "jobs", "[", "node", "]", ")", "return", "results" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
validate_tree
Validate that jobs executed after their dependencies.
environment/share/doc/ipython/examples/parallel/dagdeps.py
def validate_tree(G, results): """Validate that jobs executed after their dependencies.""" for node in G: started = results[node].metadata.started for parent in G.predecessors(node): finished = results[parent].metadata.completed assert started > finished, "%s should have happened after %s"%(node, parent)
def validate_tree(G, results): """Validate that jobs executed after their dependencies.""" for node in G: started = results[node].metadata.started for parent in G.predecessors(node): finished = results[parent].metadata.completed assert started > finished, "%s should have happened after %s"%(node, parent)
[ "Validate", "that", "jobs", "executed", "after", "their", "dependencies", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/dagdeps.py#L64-L70
[ "def", "validate_tree", "(", "G", ",", "results", ")", ":", "for", "node", "in", "G", ":", "started", "=", "results", "[", "node", "]", ".", "metadata", ".", "started", "for", "parent", "in", "G", ".", "predecessors", "(", "node", ")", ":", "finished", "=", "results", "[", "parent", "]", ".", "metadata", ".", "completed", "assert", "started", ">", "finished", ",", "\"%s should have happened after %s\"", "%", "(", "node", ",", "parent", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
main
Generate a random graph, submit jobs, then validate that the dependency order was enforced. Finally, plot the graph, with time on the x-axis, and in-degree on the y (just for spread). All arrows must point at least slightly to the right if the graph is valid.
environment/share/doc/ipython/examples/parallel/dagdeps.py
def main(nodes, edges): """Generate a random graph, submit jobs, then validate that the dependency order was enforced. Finally, plot the graph, with time on the x-axis, and in-degree on the y (just for spread). All arrows must point at least slightly to the right if the graph is valid. """ from matplotlib import pyplot as plt from matplotlib.dates import date2num from matplotlib.cm import gist_rainbow print("building DAG") G = random_dag(nodes, edges) jobs = {} pos = {} colors = {} for node in G: jobs[node] = randomwait client = parallel.Client() view = client.load_balanced_view() print("submitting %i tasks with %i dependencies"%(nodes,edges)) results = submit_jobs(view, G, jobs) print("waiting for results") view.wait() print("done") for node in G: md = results[node].metadata start = date2num(md.started) runtime = date2num(md.completed) - start pos[node] = (start, runtime) colors[node] = md.engine_id validate_tree(G, results) nx.draw(G, pos, node_list=colors.keys(), node_color=colors.values(), cmap=gist_rainbow, with_labels=False) x,y = zip(*pos.values()) xmin,ymin = map(min, (x,y)) xmax,ymax = map(max, (x,y)) xscale = xmax-xmin yscale = ymax-ymin plt.xlim(xmin-xscale*.1,xmax+xscale*.1) plt.ylim(ymin-yscale*.1,ymax+yscale*.1) return G,results
def main(nodes, edges): """Generate a random graph, submit jobs, then validate that the dependency order was enforced. Finally, plot the graph, with time on the x-axis, and in-degree on the y (just for spread). All arrows must point at least slightly to the right if the graph is valid. """ from matplotlib import pyplot as plt from matplotlib.dates import date2num from matplotlib.cm import gist_rainbow print("building DAG") G = random_dag(nodes, edges) jobs = {} pos = {} colors = {} for node in G: jobs[node] = randomwait client = parallel.Client() view = client.load_balanced_view() print("submitting %i tasks with %i dependencies"%(nodes,edges)) results = submit_jobs(view, G, jobs) print("waiting for results") view.wait() print("done") for node in G: md = results[node].metadata start = date2num(md.started) runtime = date2num(md.completed) - start pos[node] = (start, runtime) colors[node] = md.engine_id validate_tree(G, results) nx.draw(G, pos, node_list=colors.keys(), node_color=colors.values(), cmap=gist_rainbow, with_labels=False) x,y = zip(*pos.values()) xmin,ymin = map(min, (x,y)) xmax,ymax = map(max, (x,y)) xscale = xmax-xmin yscale = ymax-ymin plt.xlim(xmin-xscale*.1,xmax+xscale*.1) plt.ylim(ymin-yscale*.1,ymax+yscale*.1) return G,results
[ "Generate", "a", "random", "graph", "submit", "jobs", "then", "validate", "that", "the", "dependency", "order", "was", "enforced", ".", "Finally", "plot", "the", "graph", "with", "time", "on", "the", "x", "-", "axis", "and", "in", "-", "degree", "on", "the", "y", "(", "just", "for", "spread", ")", ".", "All", "arrows", "must", "point", "at", "least", "slightly", "to", "the", "right", "if", "the", "graph", "is", "valid", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/dagdeps.py#L72-L113
[ "def", "main", "(", "nodes", ",", "edges", ")", ":", "from", "matplotlib", "import", "pyplot", "as", "plt", "from", "matplotlib", ".", "dates", "import", "date2num", "from", "matplotlib", ".", "cm", "import", "gist_rainbow", "print", "(", "\"building DAG\"", ")", "G", "=", "random_dag", "(", "nodes", ",", "edges", ")", "jobs", "=", "{", "}", "pos", "=", "{", "}", "colors", "=", "{", "}", "for", "node", "in", "G", ":", "jobs", "[", "node", "]", "=", "randomwait", "client", "=", "parallel", ".", "Client", "(", ")", "view", "=", "client", ".", "load_balanced_view", "(", ")", "print", "(", "\"submitting %i tasks with %i dependencies\"", "%", "(", "nodes", ",", "edges", ")", ")", "results", "=", "submit_jobs", "(", "view", ",", "G", ",", "jobs", ")", "print", "(", "\"waiting for results\"", ")", "view", ".", "wait", "(", ")", "print", "(", "\"done\"", ")", "for", "node", "in", "G", ":", "md", "=", "results", "[", "node", "]", ".", "metadata", "start", "=", "date2num", "(", "md", ".", "started", ")", "runtime", "=", "date2num", "(", "md", ".", "completed", ")", "-", "start", "pos", "[", "node", "]", "=", "(", "start", ",", "runtime", ")", "colors", "[", "node", "]", "=", "md", ".", "engine_id", "validate_tree", "(", "G", ",", "results", ")", "nx", ".", "draw", "(", "G", ",", "pos", ",", "node_list", "=", "colors", ".", "keys", "(", ")", ",", "node_color", "=", "colors", ".", "values", "(", ")", ",", "cmap", "=", "gist_rainbow", ",", "with_labels", "=", "False", ")", "x", ",", "y", "=", "zip", "(", "*", "pos", ".", "values", "(", ")", ")", "xmin", ",", "ymin", "=", "map", "(", "min", ",", "(", "x", ",", "y", ")", ")", "xmax", ",", "ymax", "=", "map", "(", "max", ",", "(", "x", ",", "y", ")", ")", "xscale", "=", "xmax", "-", "xmin", "yscale", "=", "ymax", "-", "ymin", "plt", ".", "xlim", "(", "xmin", "-", "xscale", "*", ".1", ",", "xmax", "+", "xscale", "*", ".1", ")", "plt", ".", "ylim", "(", "ymin", "-", "yscale", "*", ".1", ",", "ymax", "+", "yscale", "*", ".1", ")", "return", "G", ",", "results" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
make_color_table
Build a set of color attributes in a class. Helper function for building the *TermColors classes.
environment/lib/python2.7/site-packages/IPython/utils/coloransi.py
def make_color_table(in_class): """Build a set of color attributes in a class. Helper function for building the *TermColors classes.""" for name,value in color_templates: setattr(in_class,name,in_class._base % value)
def make_color_table(in_class): """Build a set of color attributes in a class. Helper function for building the *TermColors classes.""" for name,value in color_templates: setattr(in_class,name,in_class._base % value)
[ "Build", "a", "set", "of", "color", "attributes", "in", "a", "class", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/coloransi.py#L48-L54
[ "def", "make_color_table", "(", "in_class", ")", ":", "for", "name", ",", "value", "in", "color_templates", ":", "setattr", "(", "in_class", ",", "name", ",", "in_class", ".", "_base", "%", "value", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ColorScheme.copy
Return a full copy of the object, optionally renaming it.
environment/lib/python2.7/site-packages/IPython/utils/coloransi.py
def copy(self,name=None): """Return a full copy of the object, optionally renaming it.""" if name is None: name = self.name return ColorScheme(name, self.colors.dict())
def copy(self,name=None): """Return a full copy of the object, optionally renaming it.""" if name is None: name = self.name return ColorScheme(name, self.colors.dict())
[ "Return", "a", "full", "copy", "of", "the", "object", "optionally", "renaming", "it", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/coloransi.py#L119-L123
[ "def", "copy", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "self", ".", "name", "return", "ColorScheme", "(", "name", ",", "self", ".", "colors", ".", "dict", "(", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ColorSchemeTable.add_scheme
Add a new color scheme to the table.
environment/lib/python2.7/site-packages/IPython/utils/coloransi.py
def add_scheme(self,new_scheme): """Add a new color scheme to the table.""" if not isinstance(new_scheme,ColorScheme): raise ValueError,'ColorSchemeTable only accepts ColorScheme instances' self[new_scheme.name] = new_scheme
def add_scheme(self,new_scheme): """Add a new color scheme to the table.""" if not isinstance(new_scheme,ColorScheme): raise ValueError,'ColorSchemeTable only accepts ColorScheme instances' self[new_scheme.name] = new_scheme
[ "Add", "a", "new", "color", "scheme", "to", "the", "table", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/coloransi.py#L157-L161
[ "def", "add_scheme", "(", "self", ",", "new_scheme", ")", ":", "if", "not", "isinstance", "(", "new_scheme", ",", "ColorScheme", ")", ":", "raise", "ValueError", ",", "'ColorSchemeTable only accepts ColorScheme instances'", "self", "[", "new_scheme", ".", "name", "]", "=", "new_scheme" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ColorSchemeTable.set_active_scheme
Set the currently active scheme. Names are by default compared in a case-insensitive way, but this can be changed by setting the parameter case_sensitive to true.
environment/lib/python2.7/site-packages/IPython/utils/coloransi.py
def set_active_scheme(self,scheme,case_sensitive=0): """Set the currently active scheme. Names are by default compared in a case-insensitive way, but this can be changed by setting the parameter case_sensitive to true.""" scheme_names = self.keys() if case_sensitive: valid_schemes = scheme_names scheme_test = scheme else: valid_schemes = [s.lower() for s in scheme_names] scheme_test = scheme.lower() try: scheme_idx = valid_schemes.index(scheme_test) except ValueError: raise ValueError,'Unrecognized color scheme: ' + scheme + \ '\nValid schemes: '+str(scheme_names).replace("'', ",'') else: active = scheme_names[scheme_idx] self.active_scheme_name = active self.active_colors = self[active].colors # Now allow using '' as an index for the current active scheme self[''] = self[active]
def set_active_scheme(self,scheme,case_sensitive=0): """Set the currently active scheme. Names are by default compared in a case-insensitive way, but this can be changed by setting the parameter case_sensitive to true.""" scheme_names = self.keys() if case_sensitive: valid_schemes = scheme_names scheme_test = scheme else: valid_schemes = [s.lower() for s in scheme_names] scheme_test = scheme.lower() try: scheme_idx = valid_schemes.index(scheme_test) except ValueError: raise ValueError,'Unrecognized color scheme: ' + scheme + \ '\nValid schemes: '+str(scheme_names).replace("'', ",'') else: active = scheme_names[scheme_idx] self.active_scheme_name = active self.active_colors = self[active].colors # Now allow using '' as an index for the current active scheme self[''] = self[active]
[ "Set", "the", "currently", "active", "scheme", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/coloransi.py#L163-L186
[ "def", "set_active_scheme", "(", "self", ",", "scheme", ",", "case_sensitive", "=", "0", ")", ":", "scheme_names", "=", "self", ".", "keys", "(", ")", "if", "case_sensitive", ":", "valid_schemes", "=", "scheme_names", "scheme_test", "=", "scheme", "else", ":", "valid_schemes", "=", "[", "s", ".", "lower", "(", ")", "for", "s", "in", "scheme_names", "]", "scheme_test", "=", "scheme", ".", "lower", "(", ")", "try", ":", "scheme_idx", "=", "valid_schemes", ".", "index", "(", "scheme_test", ")", "except", "ValueError", ":", "raise", "ValueError", ",", "'Unrecognized color scheme: '", "+", "scheme", "+", "'\\nValid schemes: '", "+", "str", "(", "scheme_names", ")", ".", "replace", "(", "\"'', \"", ",", "''", ")", "else", ":", "active", "=", "scheme_names", "[", "scheme_idx", "]", "self", ".", "active_scheme_name", "=", "active", "self", ".", "active_colors", "=", "self", "[", "active", "]", ".", "colors", "# Now allow using '' as an index for the current active scheme", "self", "[", "''", "]", "=", "self", "[", "active", "]" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
home_lib
Return the lib dir under the 'home' installation scheme
environment/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/backwardcompat.py
def home_lib(home): """Return the lib dir under the 'home' installation scheme""" if hasattr(sys, 'pypy_version_info'): lib = 'site-packages' else: lib = os.path.join('lib', 'python') return os.path.join(home, lib)
def home_lib(home): """Return the lib dir under the 'home' installation scheme""" if hasattr(sys, 'pypy_version_info'): lib = 'site-packages' else: lib = os.path.join('lib', 'python') return os.path.join(home, lib)
[ "Return", "the", "lib", "dir", "under", "the", "home", "installation", "scheme" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/backwardcompat.py#L106-L112
[ "def", "home_lib", "(", "home", ")", ":", "if", "hasattr", "(", "sys", ",", "'pypy_version_info'", ")", ":", "lib", "=", "'site-packages'", "else", ":", "lib", "=", "os", ".", "path", ".", "join", "(", "'lib'", ",", "'python'", ")", "return", "os", ".", "path", ".", "join", "(", "home", ",", "lib", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
cache
usage: ``` py @cache @property def name(self): pass ```
jasily/data/prop.py
def cache(descriptor=None, *, store: IStore = None): ''' usage: ``` py @cache @property def name(self): pass ``` ''' if descriptor is None: return functools.partial(cache, store=store) hasattrs = { 'get': hasattr(descriptor, '__get__'), 'set': hasattr(descriptor, '__set__'), 'del': hasattr(descriptor, '__delete__') } descriptor_name = get_descriptor_name(descriptor) # pylint: disable=R0903,C0111 class CacheDescriptor(ICacheDescriptor): def __init__(self): if descriptor_name is not None: self.__name__ = descriptor_name cache_descriptor = CacheDescriptor() if store is None: store = FieldStore(cache_descriptor) elif not isinstance(store, IStore): raise TypeError(f'store must be a {IStore}.') if hasattrs['get']: def get(self, obj, objtype): if obj is None: return descriptor.__get__(obj, objtype) value = store.get(self, obj, defval=NOVALUE) if value is NOVALUE: value = descriptor.__get__(obj, objtype) store.set(self, obj, value) return value CacheDescriptor.__get__ = get if hasattrs['set']: def set(self, obj, value): store.pop(self, obj) descriptor.__set__(obj, value) CacheDescriptor.__set__ = set if hasattrs['del']: def delete(self, obj): store.pop(self, obj) descriptor.__delete__(obj) CacheDescriptor.__delete__ = delete return cache_descriptor
def cache(descriptor=None, *, store: IStore = None): ''' usage: ``` py @cache @property def name(self): pass ``` ''' if descriptor is None: return functools.partial(cache, store=store) hasattrs = { 'get': hasattr(descriptor, '__get__'), 'set': hasattr(descriptor, '__set__'), 'del': hasattr(descriptor, '__delete__') } descriptor_name = get_descriptor_name(descriptor) # pylint: disable=R0903,C0111 class CacheDescriptor(ICacheDescriptor): def __init__(self): if descriptor_name is not None: self.__name__ = descriptor_name cache_descriptor = CacheDescriptor() if store is None: store = FieldStore(cache_descriptor) elif not isinstance(store, IStore): raise TypeError(f'store must be a {IStore}.') if hasattrs['get']: def get(self, obj, objtype): if obj is None: return descriptor.__get__(obj, objtype) value = store.get(self, obj, defval=NOVALUE) if value is NOVALUE: value = descriptor.__get__(obj, objtype) store.set(self, obj, value) return value CacheDescriptor.__get__ = get if hasattrs['set']: def set(self, obj, value): store.pop(self, obj) descriptor.__set__(obj, value) CacheDescriptor.__set__ = set if hasattrs['del']: def delete(self, obj): store.pop(self, obj) descriptor.__delete__(obj) CacheDescriptor.__delete__ = delete return cache_descriptor
[ "usage", ":" ]
Jasily/jasily-python
python
https://github.com/Jasily/jasily-python/blob/1c821a120ebbbbc3c5761f5f1e8a73588059242a/jasily/data/prop.py#L29-L90
[ "def", "cache", "(", "descriptor", "=", "None", ",", "*", ",", "store", ":", "IStore", "=", "None", ")", ":", "if", "descriptor", "is", "None", ":", "return", "functools", ".", "partial", "(", "cache", ",", "store", "=", "store", ")", "hasattrs", "=", "{", "'get'", ":", "hasattr", "(", "descriptor", ",", "'__get__'", ")", ",", "'set'", ":", "hasattr", "(", "descriptor", ",", "'__set__'", ")", ",", "'del'", ":", "hasattr", "(", "descriptor", ",", "'__delete__'", ")", "}", "descriptor_name", "=", "get_descriptor_name", "(", "descriptor", ")", "# pylint: disable=R0903,C0111", "class", "CacheDescriptor", "(", "ICacheDescriptor", ")", ":", "def", "__init__", "(", "self", ")", ":", "if", "descriptor_name", "is", "not", "None", ":", "self", ".", "__name__", "=", "descriptor_name", "cache_descriptor", "=", "CacheDescriptor", "(", ")", "if", "store", "is", "None", ":", "store", "=", "FieldStore", "(", "cache_descriptor", ")", "elif", "not", "isinstance", "(", "store", ",", "IStore", ")", ":", "raise", "TypeError", "(", "f'store must be a {IStore}.'", ")", "if", "hasattrs", "[", "'get'", "]", ":", "def", "get", "(", "self", ",", "obj", ",", "objtype", ")", ":", "if", "obj", "is", "None", ":", "return", "descriptor", ".", "__get__", "(", "obj", ",", "objtype", ")", "value", "=", "store", ".", "get", "(", "self", ",", "obj", ",", "defval", "=", "NOVALUE", ")", "if", "value", "is", "NOVALUE", ":", "value", "=", "descriptor", ".", "__get__", "(", "obj", ",", "objtype", ")", "store", ".", "set", "(", "self", ",", "obj", ",", "value", ")", "return", "value", "CacheDescriptor", ".", "__get__", "=", "get", "if", "hasattrs", "[", "'set'", "]", ":", "def", "set", "(", "self", ",", "obj", ",", "value", ")", ":", "store", ".", "pop", "(", "self", ",", "obj", ")", "descriptor", ".", "__set__", "(", "obj", ",", "value", ")", "CacheDescriptor", ".", "__set__", "=", "set", "if", "hasattrs", "[", "'del'", "]", ":", "def", "delete", "(", "self", ",", "obj", ")", ":", "store", ".", "pop", "(", "self", ",", "obj", ")", "descriptor", ".", "__delete__", "(", "obj", ")", "CacheDescriptor", ".", "__delete__", "=", "delete", "return", "cache_descriptor" ]
1c821a120ebbbbc3c5761f5f1e8a73588059242a
test
ZMQTerminalInteractiveShell.init_completer
Initialize the completion machinery. This creates completion machinery that can be used by client code, either interactively in-process (typically triggered by the readline library), programatically (such as in test suites) or out-of-prcess (typically over the network by remote frontends).
environment/lib/python2.7/site-packages/IPython/frontend/terminal/console/interactiveshell.py
def init_completer(self): """Initialize the completion machinery. This creates completion machinery that can be used by client code, either interactively in-process (typically triggered by the readline library), programatically (such as in test suites) or out-of-prcess (typically over the network by remote frontends). """ from IPython.core.completerlib import (module_completer, magic_run_completer, cd_completer) self.Completer = ZMQCompleter(self, self.km) self.set_hook('complete_command', module_completer, str_key = 'import') self.set_hook('complete_command', module_completer, str_key = 'from') self.set_hook('complete_command', magic_run_completer, str_key = '%run') self.set_hook('complete_command', cd_completer, str_key = '%cd') # Only configure readline if we truly are using readline. IPython can # do tab-completion over the network, in GUIs, etc, where readline # itself may be absent if self.has_readline: self.set_readline_completer()
def init_completer(self): """Initialize the completion machinery. This creates completion machinery that can be used by client code, either interactively in-process (typically triggered by the readline library), programatically (such as in test suites) or out-of-prcess (typically over the network by remote frontends). """ from IPython.core.completerlib import (module_completer, magic_run_completer, cd_completer) self.Completer = ZMQCompleter(self, self.km) self.set_hook('complete_command', module_completer, str_key = 'import') self.set_hook('complete_command', module_completer, str_key = 'from') self.set_hook('complete_command', magic_run_completer, str_key = '%run') self.set_hook('complete_command', cd_completer, str_key = '%cd') # Only configure readline if we truly are using readline. IPython can # do tab-completion over the network, in GUIs, etc, where readline # itself may be absent if self.has_readline: self.set_readline_completer()
[ "Initialize", "the", "completion", "machinery", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/terminal/console/interactiveshell.py#L45-L68
[ "def", "init_completer", "(", "self", ")", ":", "from", "IPython", ".", "core", ".", "completerlib", "import", "(", "module_completer", ",", "magic_run_completer", ",", "cd_completer", ")", "self", ".", "Completer", "=", "ZMQCompleter", "(", "self", ",", "self", ".", "km", ")", "self", ".", "set_hook", "(", "'complete_command'", ",", "module_completer", ",", "str_key", "=", "'import'", ")", "self", ".", "set_hook", "(", "'complete_command'", ",", "module_completer", ",", "str_key", "=", "'from'", ")", "self", ".", "set_hook", "(", "'complete_command'", ",", "magic_run_completer", ",", "str_key", "=", "'%run'", ")", "self", ".", "set_hook", "(", "'complete_command'", ",", "cd_completer", ",", "str_key", "=", "'%cd'", ")", "# Only configure readline if we truly are using readline. IPython can", "# do tab-completion over the network, in GUIs, etc, where readline", "# itself may be absent", "if", "self", ".", "has_readline", ":", "self", ".", "set_readline_completer", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ZMQTerminalInteractiveShell.run_cell
Run a complete IPython cell. Parameters ---------- cell : str The code (including IPython code such as %magic functions) to run. store_history : bool If True, the raw and translated cell will be stored in IPython's history. For user code calling back into IPython's machinery, this should be set to False.
environment/lib/python2.7/site-packages/IPython/frontend/terminal/console/interactiveshell.py
def run_cell(self, cell, store_history=True): """Run a complete IPython cell. Parameters ---------- cell : str The code (including IPython code such as %magic functions) to run. store_history : bool If True, the raw and translated cell will be stored in IPython's history. For user code calling back into IPython's machinery, this should be set to False. """ if (not cell) or cell.isspace(): return if cell.strip() == 'exit': # explicitly handle 'exit' command return self.ask_exit() self._executing = True # flush stale replies, which could have been ignored, due to missed heartbeats while self.km.shell_channel.msg_ready(): self.km.shell_channel.get_msg() # shell_channel.execute takes 'hidden', which is the inverse of store_hist msg_id = self.km.shell_channel.execute(cell, not store_history) while not self.km.shell_channel.msg_ready() and self.km.is_alive: try: self.handle_stdin_request(timeout=0.05) except Empty: # display intermediate print statements, etc. self.handle_iopub() pass if self.km.shell_channel.msg_ready(): self.handle_execute_reply(msg_id) self._executing = False
def run_cell(self, cell, store_history=True): """Run a complete IPython cell. Parameters ---------- cell : str The code (including IPython code such as %magic functions) to run. store_history : bool If True, the raw and translated cell will be stored in IPython's history. For user code calling back into IPython's machinery, this should be set to False. """ if (not cell) or cell.isspace(): return if cell.strip() == 'exit': # explicitly handle 'exit' command return self.ask_exit() self._executing = True # flush stale replies, which could have been ignored, due to missed heartbeats while self.km.shell_channel.msg_ready(): self.km.shell_channel.get_msg() # shell_channel.execute takes 'hidden', which is the inverse of store_hist msg_id = self.km.shell_channel.execute(cell, not store_history) while not self.km.shell_channel.msg_ready() and self.km.is_alive: try: self.handle_stdin_request(timeout=0.05) except Empty: # display intermediate print statements, etc. self.handle_iopub() pass if self.km.shell_channel.msg_ready(): self.handle_execute_reply(msg_id) self._executing = False
[ "Run", "a", "complete", "IPython", "cell", ".", "Parameters", "----------", "cell", ":", "str", "The", "code", "(", "including", "IPython", "code", "such", "as", "%magic", "functions", ")", "to", "run", ".", "store_history", ":", "bool", "If", "True", "the", "raw", "and", "translated", "cell", "will", "be", "stored", "in", "IPython", "s", "history", ".", "For", "user", "code", "calling", "back", "into", "IPython", "s", "machinery", "this", "should", "be", "set", "to", "False", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/terminal/console/interactiveshell.py#L70-L104
[ "def", "run_cell", "(", "self", ",", "cell", ",", "store_history", "=", "True", ")", ":", "if", "(", "not", "cell", ")", "or", "cell", ".", "isspace", "(", ")", ":", "return", "if", "cell", ".", "strip", "(", ")", "==", "'exit'", ":", "# explicitly handle 'exit' command", "return", "self", ".", "ask_exit", "(", ")", "self", ".", "_executing", "=", "True", "# flush stale replies, which could have been ignored, due to missed heartbeats", "while", "self", ".", "km", ".", "shell_channel", ".", "msg_ready", "(", ")", ":", "self", ".", "km", ".", "shell_channel", ".", "get_msg", "(", ")", "# shell_channel.execute takes 'hidden', which is the inverse of store_hist", "msg_id", "=", "self", ".", "km", ".", "shell_channel", ".", "execute", "(", "cell", ",", "not", "store_history", ")", "while", "not", "self", ".", "km", ".", "shell_channel", ".", "msg_ready", "(", ")", "and", "self", ".", "km", ".", "is_alive", ":", "try", ":", "self", ".", "handle_stdin_request", "(", "timeout", "=", "0.05", ")", "except", "Empty", ":", "# display intermediate print statements, etc.", "self", ".", "handle_iopub", "(", ")", "pass", "if", "self", ".", "km", ".", "shell_channel", ".", "msg_ready", "(", ")", ":", "self", ".", "handle_execute_reply", "(", "msg_id", ")", "self", ".", "_executing", "=", "False" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ZMQTerminalInteractiveShell.handle_iopub
Method to procces subscribe channel's messages This method reads a message and processes the content in different outputs like stdout, stderr, pyout and status Arguments: sub_msg: message receive from kernel in the sub socket channel capture by kernel manager.
environment/lib/python2.7/site-packages/IPython/frontend/terminal/console/interactiveshell.py
def handle_iopub(self): """ Method to procces subscribe channel's messages This method reads a message and processes the content in different outputs like stdout, stderr, pyout and status Arguments: sub_msg: message receive from kernel in the sub socket channel capture by kernel manager. """ while self.km.sub_channel.msg_ready(): sub_msg = self.km.sub_channel.get_msg() msg_type = sub_msg['header']['msg_type'] parent = sub_msg["parent_header"] if (not parent) or self.session_id == parent['session']: if msg_type == 'status' : if sub_msg["content"]["execution_state"] == "busy" : pass elif msg_type == 'stream' : if sub_msg["content"]["name"] == "stdout": print(sub_msg["content"]["data"], file=io.stdout, end="") io.stdout.flush() elif sub_msg["content"]["name"] == "stderr" : print(sub_msg["content"]["data"], file=io.stderr, end="") io.stderr.flush() elif msg_type == 'pyout': self.execution_count = int(sub_msg["content"]["execution_count"]) format_dict = sub_msg["content"]["data"] # taken from DisplayHook.__call__: hook = self.displayhook hook.start_displayhook() hook.write_output_prompt() hook.write_format_data(format_dict) hook.log_output(format_dict) hook.finish_displayhook()
def handle_iopub(self): """ Method to procces subscribe channel's messages This method reads a message and processes the content in different outputs like stdout, stderr, pyout and status Arguments: sub_msg: message receive from kernel in the sub socket channel capture by kernel manager. """ while self.km.sub_channel.msg_ready(): sub_msg = self.km.sub_channel.get_msg() msg_type = sub_msg['header']['msg_type'] parent = sub_msg["parent_header"] if (not parent) or self.session_id == parent['session']: if msg_type == 'status' : if sub_msg["content"]["execution_state"] == "busy" : pass elif msg_type == 'stream' : if sub_msg["content"]["name"] == "stdout": print(sub_msg["content"]["data"], file=io.stdout, end="") io.stdout.flush() elif sub_msg["content"]["name"] == "stderr" : print(sub_msg["content"]["data"], file=io.stderr, end="") io.stderr.flush() elif msg_type == 'pyout': self.execution_count = int(sub_msg["content"]["execution_count"]) format_dict = sub_msg["content"]["data"] # taken from DisplayHook.__call__: hook = self.displayhook hook.start_displayhook() hook.write_output_prompt() hook.write_format_data(format_dict) hook.log_output(format_dict) hook.finish_displayhook()
[ "Method", "to", "procces", "subscribe", "channel", "s", "messages" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/terminal/console/interactiveshell.py#L136-L172
[ "def", "handle_iopub", "(", "self", ")", ":", "while", "self", ".", "km", ".", "sub_channel", ".", "msg_ready", "(", ")", ":", "sub_msg", "=", "self", ".", "km", ".", "sub_channel", ".", "get_msg", "(", ")", "msg_type", "=", "sub_msg", "[", "'header'", "]", "[", "'msg_type'", "]", "parent", "=", "sub_msg", "[", "\"parent_header\"", "]", "if", "(", "not", "parent", ")", "or", "self", ".", "session_id", "==", "parent", "[", "'session'", "]", ":", "if", "msg_type", "==", "'status'", ":", "if", "sub_msg", "[", "\"content\"", "]", "[", "\"execution_state\"", "]", "==", "\"busy\"", ":", "pass", "elif", "msg_type", "==", "'stream'", ":", "if", "sub_msg", "[", "\"content\"", "]", "[", "\"name\"", "]", "==", "\"stdout\"", ":", "print", "(", "sub_msg", "[", "\"content\"", "]", "[", "\"data\"", "]", ",", "file", "=", "io", ".", "stdout", ",", "end", "=", "\"\"", ")", "io", ".", "stdout", ".", "flush", "(", ")", "elif", "sub_msg", "[", "\"content\"", "]", "[", "\"name\"", "]", "==", "\"stderr\"", ":", "print", "(", "sub_msg", "[", "\"content\"", "]", "[", "\"data\"", "]", ",", "file", "=", "io", ".", "stderr", ",", "end", "=", "\"\"", ")", "io", ".", "stderr", ".", "flush", "(", ")", "elif", "msg_type", "==", "'pyout'", ":", "self", ".", "execution_count", "=", "int", "(", "sub_msg", "[", "\"content\"", "]", "[", "\"execution_count\"", "]", ")", "format_dict", "=", "sub_msg", "[", "\"content\"", "]", "[", "\"data\"", "]", "# taken from DisplayHook.__call__:", "hook", "=", "self", ".", "displayhook", "hook", ".", "start_displayhook", "(", ")", "hook", ".", "write_output_prompt", "(", ")", "hook", ".", "write_format_data", "(", "format_dict", ")", "hook", ".", "log_output", "(", "format_dict", ")", "hook", ".", "finish_displayhook", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ZMQTerminalInteractiveShell.handle_stdin_request
Method to capture raw_input
environment/lib/python2.7/site-packages/IPython/frontend/terminal/console/interactiveshell.py
def handle_stdin_request(self, timeout=0.1): """ Method to capture raw_input """ msg_rep = self.km.stdin_channel.get_msg(timeout=timeout) # in case any iopub came while we were waiting: self.handle_iopub() if self.session_id == msg_rep["parent_header"].get("session"): # wrap SIGINT handler real_handler = signal.getsignal(signal.SIGINT) def double_int(sig,frame): # call real handler (forwards sigint to kernel), # then raise local interrupt, stopping local raw_input real_handler(sig,frame) raise KeyboardInterrupt signal.signal(signal.SIGINT, double_int) try: raw_data = raw_input(msg_rep["content"]["prompt"]) except EOFError: # turn EOFError into EOF character raw_data = '\x04' except KeyboardInterrupt: sys.stdout.write('\n') return finally: # restore SIGINT handler signal.signal(signal.SIGINT, real_handler) # only send stdin reply if there *was not* another request # or execution finished while we were reading. if not (self.km.stdin_channel.msg_ready() or self.km.shell_channel.msg_ready()): self.km.stdin_channel.input(raw_data)
def handle_stdin_request(self, timeout=0.1): """ Method to capture raw_input """ msg_rep = self.km.stdin_channel.get_msg(timeout=timeout) # in case any iopub came while we were waiting: self.handle_iopub() if self.session_id == msg_rep["parent_header"].get("session"): # wrap SIGINT handler real_handler = signal.getsignal(signal.SIGINT) def double_int(sig,frame): # call real handler (forwards sigint to kernel), # then raise local interrupt, stopping local raw_input real_handler(sig,frame) raise KeyboardInterrupt signal.signal(signal.SIGINT, double_int) try: raw_data = raw_input(msg_rep["content"]["prompt"]) except EOFError: # turn EOFError into EOF character raw_data = '\x04' except KeyboardInterrupt: sys.stdout.write('\n') return finally: # restore SIGINT handler signal.signal(signal.SIGINT, real_handler) # only send stdin reply if there *was not* another request # or execution finished while we were reading. if not (self.km.stdin_channel.msg_ready() or self.km.shell_channel.msg_ready()): self.km.stdin_channel.input(raw_data)
[ "Method", "to", "capture", "raw_input" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/terminal/console/interactiveshell.py#L174-L205
[ "def", "handle_stdin_request", "(", "self", ",", "timeout", "=", "0.1", ")", ":", "msg_rep", "=", "self", ".", "km", ".", "stdin_channel", ".", "get_msg", "(", "timeout", "=", "timeout", ")", "# in case any iopub came while we were waiting:", "self", ".", "handle_iopub", "(", ")", "if", "self", ".", "session_id", "==", "msg_rep", "[", "\"parent_header\"", "]", ".", "get", "(", "\"session\"", ")", ":", "# wrap SIGINT handler", "real_handler", "=", "signal", ".", "getsignal", "(", "signal", ".", "SIGINT", ")", "def", "double_int", "(", "sig", ",", "frame", ")", ":", "# call real handler (forwards sigint to kernel),", "# then raise local interrupt, stopping local raw_input", "real_handler", "(", "sig", ",", "frame", ")", "raise", "KeyboardInterrupt", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "double_int", ")", "try", ":", "raw_data", "=", "raw_input", "(", "msg_rep", "[", "\"content\"", "]", "[", "\"prompt\"", "]", ")", "except", "EOFError", ":", "# turn EOFError into EOF character", "raw_data", "=", "'\\x04'", "except", "KeyboardInterrupt", ":", "sys", ".", "stdout", ".", "write", "(", "'\\n'", ")", "return", "finally", ":", "# restore SIGINT handler", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "real_handler", ")", "# only send stdin reply if there *was not* another request", "# or execution finished while we were reading.", "if", "not", "(", "self", ".", "km", ".", "stdin_channel", ".", "msg_ready", "(", ")", "or", "self", ".", "km", ".", "shell_channel", ".", "msg_ready", "(", ")", ")", ":", "self", ".", "km", ".", "stdin_channel", ".", "input", "(", "raw_data", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ZMQTerminalInteractiveShell.wait_for_kernel
method to wait for a kernel to be ready
environment/lib/python2.7/site-packages/IPython/frontend/terminal/console/interactiveshell.py
def wait_for_kernel(self, timeout=None): """method to wait for a kernel to be ready""" tic = time.time() self.km.hb_channel.unpause() while True: self.run_cell('1', False) if self.km.hb_channel.is_beating(): # heart failure was not the reason this returned break else: # heart failed if timeout is not None and (time.time() - tic) > timeout: return False return True
def wait_for_kernel(self, timeout=None): """method to wait for a kernel to be ready""" tic = time.time() self.km.hb_channel.unpause() while True: self.run_cell('1', False) if self.km.hb_channel.is_beating(): # heart failure was not the reason this returned break else: # heart failed if timeout is not None and (time.time() - tic) > timeout: return False return True
[ "method", "to", "wait", "for", "a", "kernel", "to", "be", "ready" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/terminal/console/interactiveshell.py#L220-L233
[ "def", "wait_for_kernel", "(", "self", ",", "timeout", "=", "None", ")", ":", "tic", "=", "time", ".", "time", "(", ")", "self", ".", "km", ".", "hb_channel", ".", "unpause", "(", ")", "while", "True", ":", "self", ".", "run_cell", "(", "'1'", ",", "False", ")", "if", "self", ".", "km", ".", "hb_channel", ".", "is_beating", "(", ")", ":", "# heart failure was not the reason this returned", "break", "else", ":", "# heart failed", "if", "timeout", "is", "not", "None", "and", "(", "time", ".", "time", "(", ")", "-", "tic", ")", ">", "timeout", ":", "return", "False", "return", "True" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ZMQTerminalInteractiveShell.interact
Closely emulate the interactive Python console.
environment/lib/python2.7/site-packages/IPython/frontend/terminal/console/interactiveshell.py
def interact(self, display_banner=None): """Closely emulate the interactive Python console.""" # batch run -> do not interact if self.exit_now: return if display_banner is None: display_banner = self.display_banner if isinstance(display_banner, basestring): self.show_banner(display_banner) elif display_banner: self.show_banner() more = False # run a non-empty no-op, so that we don't get a prompt until # we know the kernel is ready. This keeps the connection # message above the first prompt. if not self.wait_for_kernel(3): error("Kernel did not respond\n") return if self.has_readline: self.readline_startup_hook(self.pre_readline) hlen_b4_cell = self.readline.get_current_history_length() else: hlen_b4_cell = 0 # exit_now is set by a call to %Exit or %Quit, through the # ask_exit callback. while not self.exit_now: if not self.km.is_alive: # kernel died, prompt for action or exit action = "restart" if self.km.has_kernel else "wait for restart" ans = self.ask_yes_no("kernel died, %s ([y]/n)?" % action, default='y') if ans: if self.km.has_kernel: self.km.restart_kernel(True) self.wait_for_kernel(3) else: self.exit_now = True continue try: # protect prompt block from KeyboardInterrupt # when sitting on ctrl-C self.hooks.pre_prompt_hook() if more: try: prompt = self.prompt_manager.render('in2') except Exception: self.showtraceback() if self.autoindent: self.rl_do_indent = True else: try: prompt = self.separate_in + self.prompt_manager.render('in') except Exception: self.showtraceback() line = self.raw_input(prompt) if self.exit_now: # quick exit on sys.std[in|out] close break if self.autoindent: self.rl_do_indent = False except KeyboardInterrupt: #double-guard against keyboardinterrupts during kbdint handling try: self.write('\nKeyboardInterrupt\n') source_raw = self.input_splitter.source_raw_reset()[1] hlen_b4_cell = self._replace_rlhist_multiline(source_raw, hlen_b4_cell) more = False except KeyboardInterrupt: pass except EOFError: if self.autoindent: self.rl_do_indent = False if self.has_readline: self.readline_startup_hook(None) self.write('\n') self.exit() except bdb.BdbQuit: warn('The Python debugger has exited with a BdbQuit exception.\n' 'Because of how pdb handles the stack, it is impossible\n' 'for IPython to properly format this particular exception.\n' 'IPython will resume normal operation.') except: # exceptions here are VERY RARE, but they can be triggered # asynchronously by signal handlers, for example. self.showtraceback() else: self.input_splitter.push(line) more = self.input_splitter.push_accepts_more() if (self.SyntaxTB.last_syntax_error and self.autoedit_syntax): self.edit_syntax_error() if not more: source_raw = self.input_splitter.source_raw_reset()[1] hlen_b4_cell = self._replace_rlhist_multiline(source_raw, hlen_b4_cell) self.run_cell(source_raw) # Turn off the exit flag, so the mainloop can be restarted if desired self.exit_now = False
def interact(self, display_banner=None): """Closely emulate the interactive Python console.""" # batch run -> do not interact if self.exit_now: return if display_banner is None: display_banner = self.display_banner if isinstance(display_banner, basestring): self.show_banner(display_banner) elif display_banner: self.show_banner() more = False # run a non-empty no-op, so that we don't get a prompt until # we know the kernel is ready. This keeps the connection # message above the first prompt. if not self.wait_for_kernel(3): error("Kernel did not respond\n") return if self.has_readline: self.readline_startup_hook(self.pre_readline) hlen_b4_cell = self.readline.get_current_history_length() else: hlen_b4_cell = 0 # exit_now is set by a call to %Exit or %Quit, through the # ask_exit callback. while not self.exit_now: if not self.km.is_alive: # kernel died, prompt for action or exit action = "restart" if self.km.has_kernel else "wait for restart" ans = self.ask_yes_no("kernel died, %s ([y]/n)?" % action, default='y') if ans: if self.km.has_kernel: self.km.restart_kernel(True) self.wait_for_kernel(3) else: self.exit_now = True continue try: # protect prompt block from KeyboardInterrupt # when sitting on ctrl-C self.hooks.pre_prompt_hook() if more: try: prompt = self.prompt_manager.render('in2') except Exception: self.showtraceback() if self.autoindent: self.rl_do_indent = True else: try: prompt = self.separate_in + self.prompt_manager.render('in') except Exception: self.showtraceback() line = self.raw_input(prompt) if self.exit_now: # quick exit on sys.std[in|out] close break if self.autoindent: self.rl_do_indent = False except KeyboardInterrupt: #double-guard against keyboardinterrupts during kbdint handling try: self.write('\nKeyboardInterrupt\n') source_raw = self.input_splitter.source_raw_reset()[1] hlen_b4_cell = self._replace_rlhist_multiline(source_raw, hlen_b4_cell) more = False except KeyboardInterrupt: pass except EOFError: if self.autoindent: self.rl_do_indent = False if self.has_readline: self.readline_startup_hook(None) self.write('\n') self.exit() except bdb.BdbQuit: warn('The Python debugger has exited with a BdbQuit exception.\n' 'Because of how pdb handles the stack, it is impossible\n' 'for IPython to properly format this particular exception.\n' 'IPython will resume normal operation.') except: # exceptions here are VERY RARE, but they can be triggered # asynchronously by signal handlers, for example. self.showtraceback() else: self.input_splitter.push(line) more = self.input_splitter.push_accepts_more() if (self.SyntaxTB.last_syntax_error and self.autoedit_syntax): self.edit_syntax_error() if not more: source_raw = self.input_splitter.source_raw_reset()[1] hlen_b4_cell = self._replace_rlhist_multiline(source_raw, hlen_b4_cell) self.run_cell(source_raw) # Turn off the exit flag, so the mainloop can be restarted if desired self.exit_now = False
[ "Closely", "emulate", "the", "interactive", "Python", "console", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/terminal/console/interactiveshell.py#L235-L342
[ "def", "interact", "(", "self", ",", "display_banner", "=", "None", ")", ":", "# batch run -> do not interact", "if", "self", ".", "exit_now", ":", "return", "if", "display_banner", "is", "None", ":", "display_banner", "=", "self", ".", "display_banner", "if", "isinstance", "(", "display_banner", ",", "basestring", ")", ":", "self", ".", "show_banner", "(", "display_banner", ")", "elif", "display_banner", ":", "self", ".", "show_banner", "(", ")", "more", "=", "False", "# run a non-empty no-op, so that we don't get a prompt until", "# we know the kernel is ready. This keeps the connection", "# message above the first prompt.", "if", "not", "self", ".", "wait_for_kernel", "(", "3", ")", ":", "error", "(", "\"Kernel did not respond\\n\"", ")", "return", "if", "self", ".", "has_readline", ":", "self", ".", "readline_startup_hook", "(", "self", ".", "pre_readline", ")", "hlen_b4_cell", "=", "self", ".", "readline", ".", "get_current_history_length", "(", ")", "else", ":", "hlen_b4_cell", "=", "0", "# exit_now is set by a call to %Exit or %Quit, through the", "# ask_exit callback.", "while", "not", "self", ".", "exit_now", ":", "if", "not", "self", ".", "km", ".", "is_alive", ":", "# kernel died, prompt for action or exit", "action", "=", "\"restart\"", "if", "self", ".", "km", ".", "has_kernel", "else", "\"wait for restart\"", "ans", "=", "self", ".", "ask_yes_no", "(", "\"kernel died, %s ([y]/n)?\"", "%", "action", ",", "default", "=", "'y'", ")", "if", "ans", ":", "if", "self", ".", "km", ".", "has_kernel", ":", "self", ".", "km", ".", "restart_kernel", "(", "True", ")", "self", ".", "wait_for_kernel", "(", "3", ")", "else", ":", "self", ".", "exit_now", "=", "True", "continue", "try", ":", "# protect prompt block from KeyboardInterrupt", "# when sitting on ctrl-C", "self", ".", "hooks", ".", "pre_prompt_hook", "(", ")", "if", "more", ":", "try", ":", "prompt", "=", "self", ".", "prompt_manager", ".", "render", "(", "'in2'", ")", "except", "Exception", ":", "self", ".", "showtraceback", "(", ")", "if", "self", ".", "autoindent", ":", "self", ".", "rl_do_indent", "=", "True", "else", ":", "try", ":", "prompt", "=", "self", ".", "separate_in", "+", "self", ".", "prompt_manager", ".", "render", "(", "'in'", ")", "except", "Exception", ":", "self", ".", "showtraceback", "(", ")", "line", "=", "self", ".", "raw_input", "(", "prompt", ")", "if", "self", ".", "exit_now", ":", "# quick exit on sys.std[in|out] close", "break", "if", "self", ".", "autoindent", ":", "self", ".", "rl_do_indent", "=", "False", "except", "KeyboardInterrupt", ":", "#double-guard against keyboardinterrupts during kbdint handling", "try", ":", "self", ".", "write", "(", "'\\nKeyboardInterrupt\\n'", ")", "source_raw", "=", "self", ".", "input_splitter", ".", "source_raw_reset", "(", ")", "[", "1", "]", "hlen_b4_cell", "=", "self", ".", "_replace_rlhist_multiline", "(", "source_raw", ",", "hlen_b4_cell", ")", "more", "=", "False", "except", "KeyboardInterrupt", ":", "pass", "except", "EOFError", ":", "if", "self", ".", "autoindent", ":", "self", ".", "rl_do_indent", "=", "False", "if", "self", ".", "has_readline", ":", "self", ".", "readline_startup_hook", "(", "None", ")", "self", ".", "write", "(", "'\\n'", ")", "self", ".", "exit", "(", ")", "except", "bdb", ".", "BdbQuit", ":", "warn", "(", "'The Python debugger has exited with a BdbQuit exception.\\n'", "'Because of how pdb handles the stack, it is impossible\\n'", "'for IPython to properly format this particular exception.\\n'", "'IPython will resume normal operation.'", ")", "except", ":", "# exceptions here are VERY RARE, but they can be triggered", "# asynchronously by signal handlers, for example.", "self", ".", "showtraceback", "(", ")", "else", ":", "self", ".", "input_splitter", ".", "push", "(", "line", ")", "more", "=", "self", ".", "input_splitter", ".", "push_accepts_more", "(", ")", "if", "(", "self", ".", "SyntaxTB", ".", "last_syntax_error", "and", "self", ".", "autoedit_syntax", ")", ":", "self", ".", "edit_syntax_error", "(", ")", "if", "not", "more", ":", "source_raw", "=", "self", ".", "input_splitter", ".", "source_raw_reset", "(", ")", "[", "1", "]", "hlen_b4_cell", "=", "self", ".", "_replace_rlhist_multiline", "(", "source_raw", ",", "hlen_b4_cell", ")", "self", ".", "run_cell", "(", "source_raw", ")", "# Turn off the exit flag, so the mainloop can be restarted if desired", "self", ".", "exit_now", "=", "False" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
get_tokens_unprocessed
Split ``text`` into (tokentype, text) pairs. Monkeypatched to store the final stack on the object itself.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/pygments_highlighter.py
def get_tokens_unprocessed(self, text, stack=('root',)): """ Split ``text`` into (tokentype, text) pairs. Monkeypatched to store the final stack on the object itself. """ pos = 0 tokendefs = self._tokens if hasattr(self, '_saved_state_stack'): statestack = list(self._saved_state_stack) else: statestack = list(stack) statetokens = tokendefs[statestack[-1]] while 1: for rexmatch, action, new_state in statetokens: m = rexmatch(text, pos) if m: if type(action) is _TokenType: yield pos, action, m.group() else: for item in action(self, m): yield item pos = m.end() if new_state is not None: # state transition if isinstance(new_state, tuple): for state in new_state: if state == '#pop': statestack.pop() elif state == '#push': statestack.append(statestack[-1]) else: statestack.append(state) elif isinstance(new_state, int): # pop del statestack[new_state:] elif new_state == '#push': statestack.append(statestack[-1]) else: assert False, "wrong state def: %r" % new_state statetokens = tokendefs[statestack[-1]] break else: try: if text[pos] == '\n': # at EOL, reset state to "root" pos += 1 statestack = ['root'] statetokens = tokendefs['root'] yield pos, Text, u'\n' continue yield pos, Error, text[pos] pos += 1 except IndexError: break self._saved_state_stack = list(statestack)
def get_tokens_unprocessed(self, text, stack=('root',)): """ Split ``text`` into (tokentype, text) pairs. Monkeypatched to store the final stack on the object itself. """ pos = 0 tokendefs = self._tokens if hasattr(self, '_saved_state_stack'): statestack = list(self._saved_state_stack) else: statestack = list(stack) statetokens = tokendefs[statestack[-1]] while 1: for rexmatch, action, new_state in statetokens: m = rexmatch(text, pos) if m: if type(action) is _TokenType: yield pos, action, m.group() else: for item in action(self, m): yield item pos = m.end() if new_state is not None: # state transition if isinstance(new_state, tuple): for state in new_state: if state == '#pop': statestack.pop() elif state == '#push': statestack.append(statestack[-1]) else: statestack.append(state) elif isinstance(new_state, int): # pop del statestack[new_state:] elif new_state == '#push': statestack.append(statestack[-1]) else: assert False, "wrong state def: %r" % new_state statetokens = tokendefs[statestack[-1]] break else: try: if text[pos] == '\n': # at EOL, reset state to "root" pos += 1 statestack = ['root'] statetokens = tokendefs['root'] yield pos, Text, u'\n' continue yield pos, Error, text[pos] pos += 1 except IndexError: break self._saved_state_stack = list(statestack)
[ "Split", "text", "into", "(", "tokentype", "text", ")", "pairs", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/pygments_highlighter.py#L9-L63
[ "def", "get_tokens_unprocessed", "(", "self", ",", "text", ",", "stack", "=", "(", "'root'", ",", ")", ")", ":", "pos", "=", "0", "tokendefs", "=", "self", ".", "_tokens", "if", "hasattr", "(", "self", ",", "'_saved_state_stack'", ")", ":", "statestack", "=", "list", "(", "self", ".", "_saved_state_stack", ")", "else", ":", "statestack", "=", "list", "(", "stack", ")", "statetokens", "=", "tokendefs", "[", "statestack", "[", "-", "1", "]", "]", "while", "1", ":", "for", "rexmatch", ",", "action", ",", "new_state", "in", "statetokens", ":", "m", "=", "rexmatch", "(", "text", ",", "pos", ")", "if", "m", ":", "if", "type", "(", "action", ")", "is", "_TokenType", ":", "yield", "pos", ",", "action", ",", "m", ".", "group", "(", ")", "else", ":", "for", "item", "in", "action", "(", "self", ",", "m", ")", ":", "yield", "item", "pos", "=", "m", ".", "end", "(", ")", "if", "new_state", "is", "not", "None", ":", "# state transition", "if", "isinstance", "(", "new_state", ",", "tuple", ")", ":", "for", "state", "in", "new_state", ":", "if", "state", "==", "'#pop'", ":", "statestack", ".", "pop", "(", ")", "elif", "state", "==", "'#push'", ":", "statestack", ".", "append", "(", "statestack", "[", "-", "1", "]", ")", "else", ":", "statestack", ".", "append", "(", "state", ")", "elif", "isinstance", "(", "new_state", ",", "int", ")", ":", "# pop", "del", "statestack", "[", "new_state", ":", "]", "elif", "new_state", "==", "'#push'", ":", "statestack", ".", "append", "(", "statestack", "[", "-", "1", "]", ")", "else", ":", "assert", "False", ",", "\"wrong state def: %r\"", "%", "new_state", "statetokens", "=", "tokendefs", "[", "statestack", "[", "-", "1", "]", "]", "break", "else", ":", "try", ":", "if", "text", "[", "pos", "]", "==", "'\\n'", ":", "# at EOL, reset state to \"root\"", "pos", "+=", "1", "statestack", "=", "[", "'root'", "]", "statetokens", "=", "tokendefs", "[", "'root'", "]", "yield", "pos", ",", "Text", ",", "u'\\n'", "continue", "yield", "pos", ",", "Error", ",", "text", "[", "pos", "]", "pos", "+=", "1", "except", "IndexError", ":", "break", "self", ".", "_saved_state_stack", "=", "list", "(", "statestack", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PygmentsHighlighter.set_style
Sets the style to the specified Pygments style.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/pygments_highlighter.py
def set_style(self, style): """ Sets the style to the specified Pygments style. """ if isinstance(style, basestring): style = get_style_by_name(style) self._style = style self._clear_caches()
def set_style(self, style): """ Sets the style to the specified Pygments style. """ if isinstance(style, basestring): style = get_style_by_name(style) self._style = style self._clear_caches()
[ "Sets", "the", "style", "to", "the", "specified", "Pygments", "style", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/pygments_highlighter.py#L129-L135
[ "def", "set_style", "(", "self", ",", "style", ")", ":", "if", "isinstance", "(", "style", ",", "basestring", ")", ":", "style", "=", "get_style_by_name", "(", "style", ")", "self", ".", "_style", "=", "style", "self", ".", "_clear_caches", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PygmentsHighlighter._get_format
Returns a QTextCharFormat for token or None.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/pygments_highlighter.py
def _get_format(self, token): """ Returns a QTextCharFormat for token or None. """ if token in self._formats: return self._formats[token] if self._style is None: result = self._get_format_from_document(token, self._document) else: result = self._get_format_from_style(token, self._style) self._formats[token] = result return result
def _get_format(self, token): """ Returns a QTextCharFormat for token or None. """ if token in self._formats: return self._formats[token] if self._style is None: result = self._get_format_from_document(token, self._document) else: result = self._get_format_from_style(token, self._style) self._formats[token] = result return result
[ "Returns", "a", "QTextCharFormat", "for", "token", "or", "None", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/pygments_highlighter.py#L160-L172
[ "def", "_get_format", "(", "self", ",", "token", ")", ":", "if", "token", "in", "self", ".", "_formats", ":", "return", "self", ".", "_formats", "[", "token", "]", "if", "self", ".", "_style", "is", "None", ":", "result", "=", "self", ".", "_get_format_from_document", "(", "token", ",", "self", ".", "_document", ")", "else", ":", "result", "=", "self", ".", "_get_format_from_style", "(", "token", ",", "self", ".", "_style", ")", "self", ".", "_formats", "[", "token", "]", "=", "result", "return", "result" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PygmentsHighlighter._get_format_from_document
Returns a QTextCharFormat for token by
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/pygments_highlighter.py
def _get_format_from_document(self, token, document): """ Returns a QTextCharFormat for token by """ code, html = self._formatter._format_lines([(token, u'dummy')]).next() self._document.setHtml(html) return QtGui.QTextCursor(self._document).charFormat()
def _get_format_from_document(self, token, document): """ Returns a QTextCharFormat for token by """ code, html = self._formatter._format_lines([(token, u'dummy')]).next() self._document.setHtml(html) return QtGui.QTextCursor(self._document).charFormat()
[ "Returns", "a", "QTextCharFormat", "for", "token", "by" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/pygments_highlighter.py#L174-L179
[ "def", "_get_format_from_document", "(", "self", ",", "token", ",", "document", ")", ":", "code", ",", "html", "=", "self", ".", "_formatter", ".", "_format_lines", "(", "[", "(", "token", ",", "u'dummy'", ")", "]", ")", ".", "next", "(", ")", "self", ".", "_document", ".", "setHtml", "(", "html", ")", "return", "QtGui", ".", "QTextCursor", "(", "self", ".", "_document", ")", ".", "charFormat", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PygmentsHighlighter._get_format_from_style
Returns a QTextCharFormat for token by reading a Pygments style.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/pygments_highlighter.py
def _get_format_from_style(self, token, style): """ Returns a QTextCharFormat for token by reading a Pygments style. """ result = QtGui.QTextCharFormat() for key, value in style.style_for_token(token).items(): if value: if key == 'color': result.setForeground(self._get_brush(value)) elif key == 'bgcolor': result.setBackground(self._get_brush(value)) elif key == 'bold': result.setFontWeight(QtGui.QFont.Bold) elif key == 'italic': result.setFontItalic(True) elif key == 'underline': result.setUnderlineStyle( QtGui.QTextCharFormat.SingleUnderline) elif key == 'sans': result.setFontStyleHint(QtGui.QFont.SansSerif) elif key == 'roman': result.setFontStyleHint(QtGui.QFont.Times) elif key == 'mono': result.setFontStyleHint(QtGui.QFont.TypeWriter) return result
def _get_format_from_style(self, token, style): """ Returns a QTextCharFormat for token by reading a Pygments style. """ result = QtGui.QTextCharFormat() for key, value in style.style_for_token(token).items(): if value: if key == 'color': result.setForeground(self._get_brush(value)) elif key == 'bgcolor': result.setBackground(self._get_brush(value)) elif key == 'bold': result.setFontWeight(QtGui.QFont.Bold) elif key == 'italic': result.setFontItalic(True) elif key == 'underline': result.setUnderlineStyle( QtGui.QTextCharFormat.SingleUnderline) elif key == 'sans': result.setFontStyleHint(QtGui.QFont.SansSerif) elif key == 'roman': result.setFontStyleHint(QtGui.QFont.Times) elif key == 'mono': result.setFontStyleHint(QtGui.QFont.TypeWriter) return result
[ "Returns", "a", "QTextCharFormat", "for", "token", "by", "reading", "a", "Pygments", "style", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/pygments_highlighter.py#L181-L204
[ "def", "_get_format_from_style", "(", "self", ",", "token", ",", "style", ")", ":", "result", "=", "QtGui", ".", "QTextCharFormat", "(", ")", "for", "key", ",", "value", "in", "style", ".", "style_for_token", "(", "token", ")", ".", "items", "(", ")", ":", "if", "value", ":", "if", "key", "==", "'color'", ":", "result", ".", "setForeground", "(", "self", ".", "_get_brush", "(", "value", ")", ")", "elif", "key", "==", "'bgcolor'", ":", "result", ".", "setBackground", "(", "self", ".", "_get_brush", "(", "value", ")", ")", "elif", "key", "==", "'bold'", ":", "result", ".", "setFontWeight", "(", "QtGui", ".", "QFont", ".", "Bold", ")", "elif", "key", "==", "'italic'", ":", "result", ".", "setFontItalic", "(", "True", ")", "elif", "key", "==", "'underline'", ":", "result", ".", "setUnderlineStyle", "(", "QtGui", ".", "QTextCharFormat", ".", "SingleUnderline", ")", "elif", "key", "==", "'sans'", ":", "result", ".", "setFontStyleHint", "(", "QtGui", ".", "QFont", ".", "SansSerif", ")", "elif", "key", "==", "'roman'", ":", "result", ".", "setFontStyleHint", "(", "QtGui", ".", "QFont", ".", "Times", ")", "elif", "key", "==", "'mono'", ":", "result", ".", "setFontStyleHint", "(", "QtGui", ".", "QFont", ".", "TypeWriter", ")", "return", "result" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
find_command
Searches the PATH for the given command and returns its path
virtualEnvironment/lib/python2.7/site-packages/pip/utils/__init__.py
def find_command(cmd, paths=None, pathext=None): """Searches the PATH for the given command and returns its path""" if paths is None: paths = os.environ.get('PATH', '').split(os.pathsep) if isinstance(paths, six.string_types): paths = [paths] # check if there are funny path extensions for executables, e.g. Windows if pathext is None: pathext = get_pathext() pathext = [ext for ext in pathext.lower().split(os.pathsep) if len(ext)] # don't use extensions if the command ends with one of them if os.path.splitext(cmd)[1].lower() in pathext: pathext = [''] # check if we find the command on PATH for path in paths: # try without extension first cmd_path = os.path.join(path, cmd) for ext in pathext: # then including the extension cmd_path_ext = cmd_path + ext if os.path.isfile(cmd_path_ext): return cmd_path_ext if os.path.isfile(cmd_path): return cmd_path raise BadCommand('Cannot find command %r' % cmd)
def find_command(cmd, paths=None, pathext=None): """Searches the PATH for the given command and returns its path""" if paths is None: paths = os.environ.get('PATH', '').split(os.pathsep) if isinstance(paths, six.string_types): paths = [paths] # check if there are funny path extensions for executables, e.g. Windows if pathext is None: pathext = get_pathext() pathext = [ext for ext in pathext.lower().split(os.pathsep) if len(ext)] # don't use extensions if the command ends with one of them if os.path.splitext(cmd)[1].lower() in pathext: pathext = [''] # check if we find the command on PATH for path in paths: # try without extension first cmd_path = os.path.join(path, cmd) for ext in pathext: # then including the extension cmd_path_ext = cmd_path + ext if os.path.isfile(cmd_path_ext): return cmd_path_ext if os.path.isfile(cmd_path): return cmd_path raise BadCommand('Cannot find command %r' % cmd)
[ "Searches", "the", "PATH", "for", "the", "given", "command", "and", "returns", "its", "path" ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/pip/utils/__init__.py#L102-L126
[ "def", "find_command", "(", "cmd", ",", "paths", "=", "None", ",", "pathext", "=", "None", ")", ":", "if", "paths", "is", "None", ":", "paths", "=", "os", ".", "environ", ".", "get", "(", "'PATH'", ",", "''", ")", ".", "split", "(", "os", ".", "pathsep", ")", "if", "isinstance", "(", "paths", ",", "six", ".", "string_types", ")", ":", "paths", "=", "[", "paths", "]", "# check if there are funny path extensions for executables, e.g. Windows", "if", "pathext", "is", "None", ":", "pathext", "=", "get_pathext", "(", ")", "pathext", "=", "[", "ext", "for", "ext", "in", "pathext", ".", "lower", "(", ")", ".", "split", "(", "os", ".", "pathsep", ")", "if", "len", "(", "ext", ")", "]", "# don't use extensions if the command ends with one of them", "if", "os", ".", "path", ".", "splitext", "(", "cmd", ")", "[", "1", "]", ".", "lower", "(", ")", "in", "pathext", ":", "pathext", "=", "[", "''", "]", "# check if we find the command on PATH", "for", "path", "in", "paths", ":", "# try without extension first", "cmd_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "cmd", ")", "for", "ext", "in", "pathext", ":", "# then including the extension", "cmd_path_ext", "=", "cmd_path", "+", "ext", "if", "os", ".", "path", ".", "isfile", "(", "cmd_path_ext", ")", ":", "return", "cmd_path_ext", "if", "os", ".", "path", ".", "isfile", "(", "cmd_path", ")", ":", "return", "cmd_path", "raise", "BadCommand", "(", "'Cannot find command %r'", "%", "cmd", ")" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
normalize_path
Convert a path to its canonical, case-normalized, absolute version.
virtualEnvironment/lib/python2.7/site-packages/pip/utils/__init__.py
def normalize_path(path): """ Convert a path to its canonical, case-normalized, absolute version. """ return os.path.normcase(os.path.realpath(os.path.expanduser(path)))
def normalize_path(path): """ Convert a path to its canonical, case-normalized, absolute version. """ return os.path.normcase(os.path.realpath(os.path.expanduser(path)))
[ "Convert", "a", "path", "to", "its", "canonical", "case", "-", "normalized", "absolute", "version", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/pip/utils/__init__.py#L292-L297
[ "def", "normalize_path", "(", "path", ")", ":", "return", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ")", ")" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
check_nsp
Verify that namespace packages are valid
environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/dist.py
def check_nsp(dist, attr, value): """Verify that namespace packages are valid""" assert_string_list(dist,attr,value) for nsp in value: if not dist.has_contents_for(nsp): raise DistutilsSetupError( "Distribution contains no modules or packages for " + "namespace package %r" % nsp ) if '.' in nsp: parent = '.'.join(nsp.split('.')[:-1]) if parent not in value: distutils.log.warn( "%r is declared as a package namespace, but %r is not:" " please correct this in setup.py", nsp, parent )
def check_nsp(dist, attr, value): """Verify that namespace packages are valid""" assert_string_list(dist,attr,value) for nsp in value: if not dist.has_contents_for(nsp): raise DistutilsSetupError( "Distribution contains no modules or packages for " + "namespace package %r" % nsp ) if '.' in nsp: parent = '.'.join(nsp.split('.')[:-1]) if parent not in value: distutils.log.warn( "%r is declared as a package namespace, but %r is not:" " please correct this in setup.py", nsp, parent )
[ "Verify", "that", "namespace", "packages", "are", "valid" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/dist.py#L52-L67
[ "def", "check_nsp", "(", "dist", ",", "attr", ",", "value", ")", ":", "assert_string_list", "(", "dist", ",", "attr", ",", "value", ")", "for", "nsp", "in", "value", ":", "if", "not", "dist", ".", "has_contents_for", "(", "nsp", ")", ":", "raise", "DistutilsSetupError", "(", "\"Distribution contains no modules or packages for \"", "+", "\"namespace package %r\"", "%", "nsp", ")", "if", "'.'", "in", "nsp", ":", "parent", "=", "'.'", ".", "join", "(", "nsp", ".", "split", "(", "'.'", ")", "[", ":", "-", "1", "]", ")", "if", "parent", "not", "in", "value", ":", "distutils", ".", "log", ".", "warn", "(", "\"%r is declared as a package namespace, but %r is not:\"", "\" please correct this in setup.py\"", ",", "nsp", ",", "parent", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
check_extras
Verify that extras_require mapping is valid
environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/dist.py
def check_extras(dist, attr, value): """Verify that extras_require mapping is valid""" try: for k,v in value.items(): list(pkg_resources.parse_requirements(v)) except (TypeError,ValueError,AttributeError): raise DistutilsSetupError( "'extras_require' must be a dictionary whose values are " "strings or lists of strings containing valid project/version " "requirement specifiers." )
def check_extras(dist, attr, value): """Verify that extras_require mapping is valid""" try: for k,v in value.items(): list(pkg_resources.parse_requirements(v)) except (TypeError,ValueError,AttributeError): raise DistutilsSetupError( "'extras_require' must be a dictionary whose values are " "strings or lists of strings containing valid project/version " "requirement specifiers." )
[ "Verify", "that", "extras_require", "mapping", "is", "valid" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/dist.py#L69-L79
[ "def", "check_extras", "(", "dist", ",", "attr", ",", "value", ")", ":", "try", ":", "for", "k", ",", "v", "in", "value", ".", "items", "(", ")", ":", "list", "(", "pkg_resources", ".", "parse_requirements", "(", "v", ")", ")", "except", "(", "TypeError", ",", "ValueError", ",", "AttributeError", ")", ":", "raise", "DistutilsSetupError", "(", "\"'extras_require' must be a dictionary whose values are \"", "\"strings or lists of strings containing valid project/version \"", "\"requirement specifiers.\"", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
check_entry_points
Verify that entry_points map is parseable
environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/dist.py
def check_entry_points(dist, attr, value): """Verify that entry_points map is parseable""" try: pkg_resources.EntryPoint.parse_map(value) except ValueError, e: raise DistutilsSetupError(e)
def check_entry_points(dist, attr, value): """Verify that entry_points map is parseable""" try: pkg_resources.EntryPoint.parse_map(value) except ValueError, e: raise DistutilsSetupError(e)
[ "Verify", "that", "entry_points", "map", "is", "parseable" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/dist.py#L99-L104
[ "def", "check_entry_points", "(", "dist", ",", "attr", ",", "value", ")", ":", "try", ":", "pkg_resources", ".", "EntryPoint", ".", "parse_map", "(", "value", ")", "except", "ValueError", ",", "e", ":", "raise", "DistutilsSetupError", "(", "e", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Distribution.handle_display_options
If there were any non-global "display-only" options (--help-commands or the metadata display options) on the command line, display the requested info and return true; else return false.
environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/dist.py
def handle_display_options(self, option_order): """If there were any non-global "display-only" options (--help-commands or the metadata display options) on the command line, display the requested info and return true; else return false. """ import sys if sys.version_info < (3,) or self.help_commands: return _Distribution.handle_display_options(self, option_order) # Stdout may be StringIO (e.g. in tests) import io if not isinstance(sys.stdout, io.TextIOWrapper): return _Distribution.handle_display_options(self, option_order) # Don't wrap stdout if utf-8 is already the encoding. Provides # workaround for #334. if sys.stdout.encoding.lower() in ('utf-8', 'utf8'): return _Distribution.handle_display_options(self, option_order) # Print metadata in UTF-8 no matter the platform encoding = sys.stdout.encoding errors = sys.stdout.errors newline = sys.platform != 'win32' and '\n' or None line_buffering = sys.stdout.line_buffering sys.stdout = io.TextIOWrapper( sys.stdout.detach(), 'utf-8', errors, newline, line_buffering) try: return _Distribution.handle_display_options(self, option_order) finally: sys.stdout = io.TextIOWrapper( sys.stdout.detach(), encoding, errors, newline, line_buffering)
def handle_display_options(self, option_order): """If there were any non-global "display-only" options (--help-commands or the metadata display options) on the command line, display the requested info and return true; else return false. """ import sys if sys.version_info < (3,) or self.help_commands: return _Distribution.handle_display_options(self, option_order) # Stdout may be StringIO (e.g. in tests) import io if not isinstance(sys.stdout, io.TextIOWrapper): return _Distribution.handle_display_options(self, option_order) # Don't wrap stdout if utf-8 is already the encoding. Provides # workaround for #334. if sys.stdout.encoding.lower() in ('utf-8', 'utf8'): return _Distribution.handle_display_options(self, option_order) # Print metadata in UTF-8 no matter the platform encoding = sys.stdout.encoding errors = sys.stdout.errors newline = sys.platform != 'win32' and '\n' or None line_buffering = sys.stdout.line_buffering sys.stdout = io.TextIOWrapper( sys.stdout.detach(), 'utf-8', errors, newline, line_buffering) try: return _Distribution.handle_display_options(self, option_order) finally: sys.stdout = io.TextIOWrapper( sys.stdout.detach(), encoding, errors, newline, line_buffering)
[ "If", "there", "were", "any", "non", "-", "global", "display", "-", "only", "options", "(", "--", "help", "-", "commands", "or", "the", "metadata", "display", "options", ")", "on", "the", "command", "line", "display", "the", "requested", "info", "and", "return", "true", ";", "else", "return", "false", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/dist.py#L645-L678
[ "def", "handle_display_options", "(", "self", ",", "option_order", ")", ":", "import", "sys", "if", "sys", ".", "version_info", "<", "(", "3", ",", ")", "or", "self", ".", "help_commands", ":", "return", "_Distribution", ".", "handle_display_options", "(", "self", ",", "option_order", ")", "# Stdout may be StringIO (e.g. in tests)", "import", "io", "if", "not", "isinstance", "(", "sys", ".", "stdout", ",", "io", ".", "TextIOWrapper", ")", ":", "return", "_Distribution", ".", "handle_display_options", "(", "self", ",", "option_order", ")", "# Don't wrap stdout if utf-8 is already the encoding. Provides", "# workaround for #334.", "if", "sys", ".", "stdout", ".", "encoding", ".", "lower", "(", ")", "in", "(", "'utf-8'", ",", "'utf8'", ")", ":", "return", "_Distribution", ".", "handle_display_options", "(", "self", ",", "option_order", ")", "# Print metadata in UTF-8 no matter the platform", "encoding", "=", "sys", ".", "stdout", ".", "encoding", "errors", "=", "sys", ".", "stdout", ".", "errors", "newline", "=", "sys", ".", "platform", "!=", "'win32'", "and", "'\\n'", "or", "None", "line_buffering", "=", "sys", ".", "stdout", ".", "line_buffering", "sys", ".", "stdout", "=", "io", ".", "TextIOWrapper", "(", "sys", ".", "stdout", ".", "detach", "(", ")", ",", "'utf-8'", ",", "errors", ",", "newline", ",", "line_buffering", ")", "try", ":", "return", "_Distribution", ".", "handle_display_options", "(", "self", ",", "option_order", ")", "finally", ":", "sys", ".", "stdout", "=", "io", ".", "TextIOWrapper", "(", "sys", ".", "stdout", ".", "detach", "(", ")", ",", "encoding", ",", "errors", ",", "newline", ",", "line_buffering", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
last_blank
Determine if the input source ends in a blank. A blank is either a newline or a line consisting of whitespace. Parameters ---------- src : string A single or multiline string.
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def last_blank(src): """Determine if the input source ends in a blank. A blank is either a newline or a line consisting of whitespace. Parameters ---------- src : string A single or multiline string. """ if not src: return False ll = src.splitlines()[-1] return (ll == '') or ll.isspace()
def last_blank(src): """Determine if the input source ends in a blank. A blank is either a newline or a line consisting of whitespace. Parameters ---------- src : string A single or multiline string. """ if not src: return False ll = src.splitlines()[-1] return (ll == '') or ll.isspace()
[ "Determine", "if", "the", "input", "source", "ends", "in", "a", "blank", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L148-L160
[ "def", "last_blank", "(", "src", ")", ":", "if", "not", "src", ":", "return", "False", "ll", "=", "src", ".", "splitlines", "(", ")", "[", "-", "1", "]", "return", "(", "ll", "==", "''", ")", "or", "ll", ".", "isspace", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
last_two_blanks
Determine if the input source ends in two blanks. A blank is either a newline or a line consisting of whitespace. Parameters ---------- src : string A single or multiline string.
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def last_two_blanks(src): """Determine if the input source ends in two blanks. A blank is either a newline or a line consisting of whitespace. Parameters ---------- src : string A single or multiline string. """ if not src: return False # The logic here is tricky: I couldn't get a regexp to work and pass all # the tests, so I took a different approach: split the source by lines, # grab the last two and prepend '###\n' as a stand-in for whatever was in # the body before the last two lines. Then, with that structure, it's # possible to analyze with two regexps. Not the most elegant solution, but # it works. If anyone tries to change this logic, make sure to validate # the whole test suite first! new_src = '\n'.join(['###\n'] + src.splitlines()[-2:]) return (bool(last_two_blanks_re.match(new_src)) or bool(last_two_blanks_re2.match(new_src)) )
def last_two_blanks(src): """Determine if the input source ends in two blanks. A blank is either a newline or a line consisting of whitespace. Parameters ---------- src : string A single or multiline string. """ if not src: return False # The logic here is tricky: I couldn't get a regexp to work and pass all # the tests, so I took a different approach: split the source by lines, # grab the last two and prepend '###\n' as a stand-in for whatever was in # the body before the last two lines. Then, with that structure, it's # possible to analyze with two regexps. Not the most elegant solution, but # it works. If anyone tries to change this logic, make sure to validate # the whole test suite first! new_src = '\n'.join(['###\n'] + src.splitlines()[-2:]) return (bool(last_two_blanks_re.match(new_src)) or bool(last_two_blanks_re2.match(new_src)) )
[ "Determine", "if", "the", "input", "source", "ends", "in", "two", "blanks", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L166-L186
[ "def", "last_two_blanks", "(", "src", ")", ":", "if", "not", "src", ":", "return", "False", "# The logic here is tricky: I couldn't get a regexp to work and pass all", "# the tests, so I took a different approach: split the source by lines,", "# grab the last two and prepend '###\\n' as a stand-in for whatever was in", "# the body before the last two lines. Then, with that structure, it's", "# possible to analyze with two regexps. Not the most elegant solution, but", "# it works. If anyone tries to change this logic, make sure to validate", "# the whole test suite first!", "new_src", "=", "'\\n'", ".", "join", "(", "[", "'###\\n'", "]", "+", "src", ".", "splitlines", "(", ")", "[", "-", "2", ":", "]", ")", "return", "(", "bool", "(", "last_two_blanks_re", ".", "match", "(", "new_src", ")", ")", "or", "bool", "(", "last_two_blanks_re2", ".", "match", "(", "new_src", ")", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
has_comment
Indicate whether an input line has (i.e. ends in, or is) a comment. This uses tokenize, so it can distinguish comments from # inside strings. Parameters ---------- src : string A single line input string. Returns ------- Boolean: True if source has a comment.
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def has_comment(src): """Indicate whether an input line has (i.e. ends in, or is) a comment. This uses tokenize, so it can distinguish comments from # inside strings. Parameters ---------- src : string A single line input string. Returns ------- Boolean: True if source has a comment. """ readline = StringIO(src).readline toktypes = set() try: for t in tokenize.generate_tokens(readline): toktypes.add(t[0]) except tokenize.TokenError: pass return(tokenize.COMMENT in toktypes)
def has_comment(src): """Indicate whether an input line has (i.e. ends in, or is) a comment. This uses tokenize, so it can distinguish comments from # inside strings. Parameters ---------- src : string A single line input string. Returns ------- Boolean: True if source has a comment. """ readline = StringIO(src).readline toktypes = set() try: for t in tokenize.generate_tokens(readline): toktypes.add(t[0]) except tokenize.TokenError: pass return(tokenize.COMMENT in toktypes)
[ "Indicate", "whether", "an", "input", "line", "has", "(", "i", ".", "e", ".", "ends", "in", "or", "is", ")", "a", "comment", ".", "This", "uses", "tokenize", "so", "it", "can", "distinguish", "comments", "from", "#", "inside", "strings", ".", "Parameters", "----------", "src", ":", "string", "A", "single", "line", "input", "string", ".", "Returns", "-------", "Boolean", ":", "True", "if", "source", "has", "a", "comment", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L206-L227
[ "def", "has_comment", "(", "src", ")", ":", "readline", "=", "StringIO", "(", "src", ")", ".", "readline", "toktypes", "=", "set", "(", ")", "try", ":", "for", "t", "in", "tokenize", ".", "generate_tokens", "(", "readline", ")", ":", "toktypes", ".", "add", "(", "t", "[", "0", "]", ")", "except", "tokenize", ".", "TokenError", ":", "pass", "return", "(", "tokenize", ".", "COMMENT", "in", "toktypes", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
transform_assign_system
Handle the `files = !ls` syntax.
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def transform_assign_system(line): """Handle the `files = !ls` syntax.""" m = _assign_system_re.match(line) if m is not None: cmd = m.group('cmd') lhs = m.group('lhs') new_line = '%s = get_ipython().getoutput(%r)' % (lhs, cmd) return new_line return line
def transform_assign_system(line): """Handle the `files = !ls` syntax.""" m = _assign_system_re.match(line) if m is not None: cmd = m.group('cmd') lhs = m.group('lhs') new_line = '%s = get_ipython().getoutput(%r)' % (lhs, cmd) return new_line return line
[ "Handle", "the", "files", "=", "!ls", "syntax", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L543-L551
[ "def", "transform_assign_system", "(", "line", ")", ":", "m", "=", "_assign_system_re", ".", "match", "(", "line", ")", "if", "m", "is", "not", "None", ":", "cmd", "=", "m", ".", "group", "(", "'cmd'", ")", "lhs", "=", "m", ".", "group", "(", "'lhs'", ")", "new_line", "=", "'%s = get_ipython().getoutput(%r)'", "%", "(", "lhs", ",", "cmd", ")", "return", "new_line", "return", "line" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
transform_assign_magic
Handle the `a = %who` syntax.
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def transform_assign_magic(line): """Handle the `a = %who` syntax.""" m = _assign_magic_re.match(line) if m is not None: cmd = m.group('cmd') lhs = m.group('lhs') new_line = '%s = get_ipython().magic(%r)' % (lhs, cmd) return new_line return line
def transform_assign_magic(line): """Handle the `a = %who` syntax.""" m = _assign_magic_re.match(line) if m is not None: cmd = m.group('cmd') lhs = m.group('lhs') new_line = '%s = get_ipython().magic(%r)' % (lhs, cmd) return new_line return line
[ "Handle", "the", "a", "=", "%who", "syntax", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L557-L565
[ "def", "transform_assign_magic", "(", "line", ")", ":", "m", "=", "_assign_magic_re", ".", "match", "(", "line", ")", "if", "m", "is", "not", "None", ":", "cmd", "=", "m", ".", "group", "(", "'cmd'", ")", "lhs", "=", "m", ".", "group", "(", "'lhs'", ")", "new_line", "=", "'%s = get_ipython().magic(%r)'", "%", "(", "lhs", ",", "cmd", ")", "return", "new_line", "return", "line" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
transform_classic_prompt
Handle inputs that start with '>>> ' syntax.
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def transform_classic_prompt(line): """Handle inputs that start with '>>> ' syntax.""" if not line or line.isspace(): return line m = _classic_prompt_re.match(line) if m: return line[len(m.group(0)):] else: return line
def transform_classic_prompt(line): """Handle inputs that start with '>>> ' syntax.""" if not line or line.isspace(): return line m = _classic_prompt_re.match(line) if m: return line[len(m.group(0)):] else: return line
[ "Handle", "inputs", "that", "start", "with", ">>>", "syntax", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L570-L579
[ "def", "transform_classic_prompt", "(", "line", ")", ":", "if", "not", "line", "or", "line", ".", "isspace", "(", ")", ":", "return", "line", "m", "=", "_classic_prompt_re", ".", "match", "(", "line", ")", "if", "m", ":", "return", "line", "[", "len", "(", "m", ".", "group", "(", "0", ")", ")", ":", "]", "else", ":", "return", "line" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
transform_ipy_prompt
Handle inputs that start classic IPython prompt syntax.
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def transform_ipy_prompt(line): """Handle inputs that start classic IPython prompt syntax.""" if not line or line.isspace(): return line #print 'LINE: %r' % line # dbg m = _ipy_prompt_re.match(line) if m: #print 'MATCH! %r -> %r' % (line, line[len(m.group(0)):]) # dbg return line[len(m.group(0)):] else: return line
def transform_ipy_prompt(line): """Handle inputs that start classic IPython prompt syntax.""" if not line or line.isspace(): return line #print 'LINE: %r' % line # dbg m = _ipy_prompt_re.match(line) if m: #print 'MATCH! %r -> %r' % (line, line[len(m.group(0)):]) # dbg return line[len(m.group(0)):] else: return line
[ "Handle", "inputs", "that", "start", "classic", "IPython", "prompt", "syntax", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L584-L595
[ "def", "transform_ipy_prompt", "(", "line", ")", ":", "if", "not", "line", "or", "line", ".", "isspace", "(", ")", ":", "return", "line", "#print 'LINE: %r' % line # dbg", "m", "=", "_ipy_prompt_re", ".", "match", "(", "line", ")", "if", "m", ":", "#print 'MATCH! %r -> %r' % (line, line[len(m.group(0)):]) # dbg", "return", "line", "[", "len", "(", "m", ".", "group", "(", "0", ")", ")", ":", "]", "else", ":", "return", "line" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
_make_help_call
Prepares a pinfo(2)/psearch call from a target name and the escape (i.e. ? or ??)
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def _make_help_call(target, esc, lspace, next_input=None): """Prepares a pinfo(2)/psearch call from a target name and the escape (i.e. ? or ??)""" method = 'pinfo2' if esc == '??' \ else 'psearch' if '*' in target \ else 'pinfo' arg = " ".join([method, target]) if next_input is None: return '%sget_ipython().magic(%r)' % (lspace, arg) else: return '%sget_ipython().set_next_input(%r);get_ipython().magic(%r)' % \ (lspace, next_input, arg)
def _make_help_call(target, esc, lspace, next_input=None): """Prepares a pinfo(2)/psearch call from a target name and the escape (i.e. ? or ??)""" method = 'pinfo2' if esc == '??' \ else 'psearch' if '*' in target \ else 'pinfo' arg = " ".join([method, target]) if next_input is None: return '%sget_ipython().magic(%r)' % (lspace, arg) else: return '%sget_ipython().set_next_input(%r);get_ipython().magic(%r)' % \ (lspace, next_input, arg)
[ "Prepares", "a", "pinfo", "(", "2", ")", "/", "psearch", "call", "from", "a", "target", "name", "and", "the", "escape", "(", "i", ".", "e", ".", "?", "or", "??", ")" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L598-L609
[ "def", "_make_help_call", "(", "target", ",", "esc", ",", "lspace", ",", "next_input", "=", "None", ")", ":", "method", "=", "'pinfo2'", "if", "esc", "==", "'??'", "else", "'psearch'", "if", "'*'", "in", "target", "else", "'pinfo'", "arg", "=", "\" \"", ".", "join", "(", "[", "method", ",", "target", "]", ")", "if", "next_input", "is", "None", ":", "return", "'%sget_ipython().magic(%r)'", "%", "(", "lspace", ",", "arg", ")", "else", ":", "return", "'%sget_ipython().set_next_input(%r);get_ipython().magic(%r)'", "%", "(", "lspace", ",", "next_input", ",", "arg", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
transform_help_end
Translate lines with ?/?? at the end
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def transform_help_end(line): """Translate lines with ?/?? at the end""" m = _help_end_re.search(line) if m is None or has_comment(line): return line target = m.group(1) esc = m.group(3) lspace = _initial_space_re.match(line).group(0) # If we're mid-command, put it back on the next prompt for the user. next_input = line.rstrip('?') if line.strip() != m.group(0) else None return _make_help_call(target, esc, lspace, next_input)
def transform_help_end(line): """Translate lines with ?/?? at the end""" m = _help_end_re.search(line) if m is None or has_comment(line): return line target = m.group(1) esc = m.group(3) lspace = _initial_space_re.match(line).group(0) # If we're mid-command, put it back on the next prompt for the user. next_input = line.rstrip('?') if line.strip() != m.group(0) else None return _make_help_call(target, esc, lspace, next_input)
[ "Translate", "lines", "with", "?", "/", "??", "at", "the", "end" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L622-L634
[ "def", "transform_help_end", "(", "line", ")", ":", "m", "=", "_help_end_re", ".", "search", "(", "line", ")", "if", "m", "is", "None", "or", "has_comment", "(", "line", ")", ":", "return", "line", "target", "=", "m", ".", "group", "(", "1", ")", "esc", "=", "m", ".", "group", "(", "3", ")", "lspace", "=", "_initial_space_re", ".", "match", "(", "line", ")", ".", "group", "(", "0", ")", "# If we're mid-command, put it back on the next prompt for the user.", "next_input", "=", "line", ".", "rstrip", "(", "'?'", ")", "if", "line", ".", "strip", "(", ")", "!=", "m", ".", "group", "(", "0", ")", "else", "None", "return", "_make_help_call", "(", "target", ",", "esc", ",", "lspace", ",", "next_input", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InputSplitter.reset
Reset the input buffer and associated state.
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def reset(self): """Reset the input buffer and associated state.""" self.indent_spaces = 0 self._buffer[:] = [] self.source = '' self.code = None self._is_complete = False self._full_dedent = False
def reset(self): """Reset the input buffer and associated state.""" self.indent_spaces = 0 self._buffer[:] = [] self.source = '' self.code = None self._is_complete = False self._full_dedent = False
[ "Reset", "the", "input", "buffer", "and", "associated", "state", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L322-L329
[ "def", "reset", "(", "self", ")", ":", "self", ".", "indent_spaces", "=", "0", "self", ".", "_buffer", "[", ":", "]", "=", "[", "]", "self", ".", "source", "=", "''", "self", ".", "code", "=", "None", "self", ".", "_is_complete", "=", "False", "self", ".", "_full_dedent", "=", "False" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InputSplitter.push
Push one or more lines of input. This stores the given lines and returns a status code indicating whether the code forms a complete Python block or not. Any exceptions generated in compilation are swallowed, but if an exception was produced, the method returns True. Parameters ---------- lines : string One or more lines of Python input. Returns ------- is_complete : boolean True if the current input source (the result of the current input plus prior inputs) forms a complete Python execution block. Note that this value is also stored as a private attribute (``_is_complete``), so it can be queried at any time.
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def push(self, lines): """Push one or more lines of input. This stores the given lines and returns a status code indicating whether the code forms a complete Python block or not. Any exceptions generated in compilation are swallowed, but if an exception was produced, the method returns True. Parameters ---------- lines : string One or more lines of Python input. Returns ------- is_complete : boolean True if the current input source (the result of the current input plus prior inputs) forms a complete Python execution block. Note that this value is also stored as a private attribute (``_is_complete``), so it can be queried at any time. """ if self.input_mode == 'cell': self.reset() self._store(lines) source = self.source # Before calling _compile(), reset the code object to None so that if an # exception is raised in compilation, we don't mislead by having # inconsistent code/source attributes. self.code, self._is_complete = None, None # Honor termination lines properly if source.rstrip().endswith('\\'): return False self._update_indent(lines) try: self.code = self._compile(source, symbol="exec") # Invalid syntax can produce any of a number of different errors from # inside the compiler, so we have to catch them all. Syntax errors # immediately produce a 'ready' block, so the invalid Python can be # sent to the kernel for evaluation with possible ipython # special-syntax conversion. except (SyntaxError, OverflowError, ValueError, TypeError, MemoryError): self._is_complete = True else: # Compilation didn't produce any exceptions (though it may not have # given a complete code object) self._is_complete = self.code is not None return self._is_complete
def push(self, lines): """Push one or more lines of input. This stores the given lines and returns a status code indicating whether the code forms a complete Python block or not. Any exceptions generated in compilation are swallowed, but if an exception was produced, the method returns True. Parameters ---------- lines : string One or more lines of Python input. Returns ------- is_complete : boolean True if the current input source (the result of the current input plus prior inputs) forms a complete Python execution block. Note that this value is also stored as a private attribute (``_is_complete``), so it can be queried at any time. """ if self.input_mode == 'cell': self.reset() self._store(lines) source = self.source # Before calling _compile(), reset the code object to None so that if an # exception is raised in compilation, we don't mislead by having # inconsistent code/source attributes. self.code, self._is_complete = None, None # Honor termination lines properly if source.rstrip().endswith('\\'): return False self._update_indent(lines) try: self.code = self._compile(source, symbol="exec") # Invalid syntax can produce any of a number of different errors from # inside the compiler, so we have to catch them all. Syntax errors # immediately produce a 'ready' block, so the invalid Python can be # sent to the kernel for evaluation with possible ipython # special-syntax conversion. except (SyntaxError, OverflowError, ValueError, TypeError, MemoryError): self._is_complete = True else: # Compilation didn't produce any exceptions (though it may not have # given a complete code object) self._is_complete = self.code is not None return self._is_complete
[ "Push", "one", "or", "more", "lines", "of", "input", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L338-L391
[ "def", "push", "(", "self", ",", "lines", ")", ":", "if", "self", ".", "input_mode", "==", "'cell'", ":", "self", ".", "reset", "(", ")", "self", ".", "_store", "(", "lines", ")", "source", "=", "self", ".", "source", "# Before calling _compile(), reset the code object to None so that if an", "# exception is raised in compilation, we don't mislead by having", "# inconsistent code/source attributes.", "self", ".", "code", ",", "self", ".", "_is_complete", "=", "None", ",", "None", "# Honor termination lines properly", "if", "source", ".", "rstrip", "(", ")", ".", "endswith", "(", "'\\\\'", ")", ":", "return", "False", "self", ".", "_update_indent", "(", "lines", ")", "try", ":", "self", ".", "code", "=", "self", ".", "_compile", "(", "source", ",", "symbol", "=", "\"exec\"", ")", "# Invalid syntax can produce any of a number of different errors from", "# inside the compiler, so we have to catch them all. Syntax errors", "# immediately produce a 'ready' block, so the invalid Python can be", "# sent to the kernel for evaluation with possible ipython", "# special-syntax conversion.", "except", "(", "SyntaxError", ",", "OverflowError", ",", "ValueError", ",", "TypeError", ",", "MemoryError", ")", ":", "self", ".", "_is_complete", "=", "True", "else", ":", "# Compilation didn't produce any exceptions (though it may not have", "# given a complete code object)", "self", ".", "_is_complete", "=", "self", ".", "code", "is", "not", "None", "return", "self", ".", "_is_complete" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InputSplitter.push_accepts_more
Return whether a block of interactive input can accept more input. This method is meant to be used by line-oriented frontends, who need to guess whether a block is complete or not based solely on prior and current input lines. The InputSplitter considers it has a complete interactive block and will not accept more input only when either a SyntaxError is raised, or *all* of the following are true: 1. The input compiles to a complete statement. 2. The indentation level is flush-left (because if we are indented, like inside a function definition or for loop, we need to keep reading new input). 3. There is one extra line consisting only of whitespace. Because of condition #3, this method should be used only by *line-oriented* frontends, since it means that intermediate blank lines are not allowed in function definitions (or any other indented block). If the current input produces a syntax error, this method immediately returns False but does *not* raise the syntax error exception, as typically clients will want to send invalid syntax to an execution backend which might convert the invalid syntax into valid Python via one of the dynamic IPython mechanisms.
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def push_accepts_more(self): """Return whether a block of interactive input can accept more input. This method is meant to be used by line-oriented frontends, who need to guess whether a block is complete or not based solely on prior and current input lines. The InputSplitter considers it has a complete interactive block and will not accept more input only when either a SyntaxError is raised, or *all* of the following are true: 1. The input compiles to a complete statement. 2. The indentation level is flush-left (because if we are indented, like inside a function definition or for loop, we need to keep reading new input). 3. There is one extra line consisting only of whitespace. Because of condition #3, this method should be used only by *line-oriented* frontends, since it means that intermediate blank lines are not allowed in function definitions (or any other indented block). If the current input produces a syntax error, this method immediately returns False but does *not* raise the syntax error exception, as typically clients will want to send invalid syntax to an execution backend which might convert the invalid syntax into valid Python via one of the dynamic IPython mechanisms. """ # With incomplete input, unconditionally accept more if not self._is_complete: return True # If we already have complete input and we're flush left, the answer # depends. In line mode, if there hasn't been any indentation, # that's it. If we've come back from some indentation, we need # the blank final line to finish. # In cell mode, we need to check how many blocks the input so far # compiles into, because if there's already more than one full # independent block of input, then the client has entered full # 'cell' mode and is feeding lines that each is complete. In this # case we should then keep accepting. The Qt terminal-like console # does precisely this, to provide the convenience of terminal-like # input of single expressions, but allowing the user (with a # separate keystroke) to switch to 'cell' mode and type multiple # expressions in one shot. if self.indent_spaces==0: if self.input_mode=='line': if not self._full_dedent: return False else: try: code_ast = ast.parse(u''.join(self._buffer)) except Exception: return False else: if len(code_ast.body) == 1: return False # When input is complete, then termination is marked by an extra blank # line at the end. last_line = self.source.splitlines()[-1] return bool(last_line and not last_line.isspace())
def push_accepts_more(self): """Return whether a block of interactive input can accept more input. This method is meant to be used by line-oriented frontends, who need to guess whether a block is complete or not based solely on prior and current input lines. The InputSplitter considers it has a complete interactive block and will not accept more input only when either a SyntaxError is raised, or *all* of the following are true: 1. The input compiles to a complete statement. 2. The indentation level is flush-left (because if we are indented, like inside a function definition or for loop, we need to keep reading new input). 3. There is one extra line consisting only of whitespace. Because of condition #3, this method should be used only by *line-oriented* frontends, since it means that intermediate blank lines are not allowed in function definitions (or any other indented block). If the current input produces a syntax error, this method immediately returns False but does *not* raise the syntax error exception, as typically clients will want to send invalid syntax to an execution backend which might convert the invalid syntax into valid Python via one of the dynamic IPython mechanisms. """ # With incomplete input, unconditionally accept more if not self._is_complete: return True # If we already have complete input and we're flush left, the answer # depends. In line mode, if there hasn't been any indentation, # that's it. If we've come back from some indentation, we need # the blank final line to finish. # In cell mode, we need to check how many blocks the input so far # compiles into, because if there's already more than one full # independent block of input, then the client has entered full # 'cell' mode and is feeding lines that each is complete. In this # case we should then keep accepting. The Qt terminal-like console # does precisely this, to provide the convenience of terminal-like # input of single expressions, but allowing the user (with a # separate keystroke) to switch to 'cell' mode and type multiple # expressions in one shot. if self.indent_spaces==0: if self.input_mode=='line': if not self._full_dedent: return False else: try: code_ast = ast.parse(u''.join(self._buffer)) except Exception: return False else: if len(code_ast.body) == 1: return False # When input is complete, then termination is marked by an extra blank # line at the end. last_line = self.source.splitlines()[-1] return bool(last_line and not last_line.isspace())
[ "Return", "whether", "a", "block", "of", "interactive", "input", "can", "accept", "more", "input", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L393-L454
[ "def", "push_accepts_more", "(", "self", ")", ":", "# With incomplete input, unconditionally accept more", "if", "not", "self", ".", "_is_complete", ":", "return", "True", "# If we already have complete input and we're flush left, the answer", "# depends. In line mode, if there hasn't been any indentation,", "# that's it. If we've come back from some indentation, we need", "# the blank final line to finish.", "# In cell mode, we need to check how many blocks the input so far", "# compiles into, because if there's already more than one full", "# independent block of input, then the client has entered full", "# 'cell' mode and is feeding lines that each is complete. In this", "# case we should then keep accepting. The Qt terminal-like console", "# does precisely this, to provide the convenience of terminal-like", "# input of single expressions, but allowing the user (with a", "# separate keystroke) to switch to 'cell' mode and type multiple", "# expressions in one shot.", "if", "self", ".", "indent_spaces", "==", "0", ":", "if", "self", ".", "input_mode", "==", "'line'", ":", "if", "not", "self", ".", "_full_dedent", ":", "return", "False", "else", ":", "try", ":", "code_ast", "=", "ast", ".", "parse", "(", "u''", ".", "join", "(", "self", ".", "_buffer", ")", ")", "except", "Exception", ":", "return", "False", "else", ":", "if", "len", "(", "code_ast", ".", "body", ")", "==", "1", ":", "return", "False", "# When input is complete, then termination is marked by an extra blank", "# line at the end.", "last_line", "=", "self", ".", "source", ".", "splitlines", "(", ")", "[", "-", "1", "]", "return", "bool", "(", "last_line", "and", "not", "last_line", ".", "isspace", "(", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InputSplitter._find_indent
Compute the new indentation level for a single line. Parameters ---------- line : str A single new line of non-whitespace, non-comment Python input. Returns ------- indent_spaces : int New value for the indent level (it may be equal to self.indent_spaces if indentation doesn't change. full_dedent : boolean Whether the new line causes a full flush-left dedent.
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def _find_indent(self, line): """Compute the new indentation level for a single line. Parameters ---------- line : str A single new line of non-whitespace, non-comment Python input. Returns ------- indent_spaces : int New value for the indent level (it may be equal to self.indent_spaces if indentation doesn't change. full_dedent : boolean Whether the new line causes a full flush-left dedent. """ indent_spaces = self.indent_spaces full_dedent = self._full_dedent inisp = num_ini_spaces(line) if inisp < indent_spaces: indent_spaces = inisp if indent_spaces <= 0: #print 'Full dedent in text',self.source # dbg full_dedent = True if line.rstrip()[-1] == ':': indent_spaces += 4 elif dedent_re.match(line): indent_spaces -= 4 if indent_spaces <= 0: full_dedent = True # Safety if indent_spaces < 0: indent_spaces = 0 #print 'safety' # dbg return indent_spaces, full_dedent
def _find_indent(self, line): """Compute the new indentation level for a single line. Parameters ---------- line : str A single new line of non-whitespace, non-comment Python input. Returns ------- indent_spaces : int New value for the indent level (it may be equal to self.indent_spaces if indentation doesn't change. full_dedent : boolean Whether the new line causes a full flush-left dedent. """ indent_spaces = self.indent_spaces full_dedent = self._full_dedent inisp = num_ini_spaces(line) if inisp < indent_spaces: indent_spaces = inisp if indent_spaces <= 0: #print 'Full dedent in text',self.source # dbg full_dedent = True if line.rstrip()[-1] == ':': indent_spaces += 4 elif dedent_re.match(line): indent_spaces -= 4 if indent_spaces <= 0: full_dedent = True # Safety if indent_spaces < 0: indent_spaces = 0 #print 'safety' # dbg return indent_spaces, full_dedent
[ "Compute", "the", "new", "indentation", "level", "for", "a", "single", "line", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L460-L499
[ "def", "_find_indent", "(", "self", ",", "line", ")", ":", "indent_spaces", "=", "self", ".", "indent_spaces", "full_dedent", "=", "self", ".", "_full_dedent", "inisp", "=", "num_ini_spaces", "(", "line", ")", "if", "inisp", "<", "indent_spaces", ":", "indent_spaces", "=", "inisp", "if", "indent_spaces", "<=", "0", ":", "#print 'Full dedent in text',self.source # dbg", "full_dedent", "=", "True", "if", "line", ".", "rstrip", "(", ")", "[", "-", "1", "]", "==", "':'", ":", "indent_spaces", "+=", "4", "elif", "dedent_re", ".", "match", "(", "line", ")", ":", "indent_spaces", "-=", "4", "if", "indent_spaces", "<=", "0", ":", "full_dedent", "=", "True", "# Safety", "if", "indent_spaces", "<", "0", ":", "indent_spaces", "=", "0", "#print 'safety' # dbg", "return", "indent_spaces", ",", "full_dedent" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InputSplitter._store
Store one or more lines of input. If input lines are not newline-terminated, a newline is automatically appended.
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def _store(self, lines, buffer=None, store='source'): """Store one or more lines of input. If input lines are not newline-terminated, a newline is automatically appended.""" if buffer is None: buffer = self._buffer if lines.endswith('\n'): buffer.append(lines) else: buffer.append(lines+'\n') setattr(self, store, self._set_source(buffer))
def _store(self, lines, buffer=None, store='source'): """Store one or more lines of input. If input lines are not newline-terminated, a newline is automatically appended.""" if buffer is None: buffer = self._buffer if lines.endswith('\n'): buffer.append(lines) else: buffer.append(lines+'\n') setattr(self, store, self._set_source(buffer))
[ "Store", "one", "or", "more", "lines", "of", "input", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L506-L519
[ "def", "_store", "(", "self", ",", "lines", ",", "buffer", "=", "None", ",", "store", "=", "'source'", ")", ":", "if", "buffer", "is", "None", ":", "buffer", "=", "self", ".", "_buffer", "if", "lines", ".", "endswith", "(", "'\\n'", ")", ":", "buffer", ".", "append", "(", "lines", ")", "else", ":", "buffer", ".", "append", "(", "lines", "+", "'\\n'", ")", "setattr", "(", "self", ",", "store", ",", "self", ".", "_set_source", "(", "buffer", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
EscapedTransformer._tr_system
Translate lines escaped with: !
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def _tr_system(line_info): "Translate lines escaped with: !" cmd = line_info.line.lstrip().lstrip(ESC_SHELL) return '%sget_ipython().system(%r)' % (line_info.pre, cmd)
def _tr_system(line_info): "Translate lines escaped with: !" cmd = line_info.line.lstrip().lstrip(ESC_SHELL) return '%sget_ipython().system(%r)' % (line_info.pre, cmd)
[ "Translate", "lines", "escaped", "with", ":", "!" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L654-L657
[ "def", "_tr_system", "(", "line_info", ")", ":", "cmd", "=", "line_info", ".", "line", ".", "lstrip", "(", ")", ".", "lstrip", "(", "ESC_SHELL", ")", "return", "'%sget_ipython().system(%r)'", "%", "(", "line_info", ".", "pre", ",", "cmd", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
EscapedTransformer._tr_help
Translate lines escaped with: ?/??
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def _tr_help(line_info): "Translate lines escaped with: ?/??" # A naked help line should just fire the intro help screen if not line_info.line[1:]: return 'get_ipython().show_usage()' return _make_help_call(line_info.ifun, line_info.esc, line_info.pre)
def _tr_help(line_info): "Translate lines escaped with: ?/??" # A naked help line should just fire the intro help screen if not line_info.line[1:]: return 'get_ipython().show_usage()' return _make_help_call(line_info.ifun, line_info.esc, line_info.pre)
[ "Translate", "lines", "escaped", "with", ":", "?", "/", "??" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L666-L672
[ "def", "_tr_help", "(", "line_info", ")", ":", "# A naked help line should just fire the intro help screen", "if", "not", "line_info", ".", "line", "[", "1", ":", "]", ":", "return", "'get_ipython().show_usage()'", "return", "_make_help_call", "(", "line_info", ".", "ifun", ",", "line_info", ".", "esc", ",", "line_info", ".", "pre", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
EscapedTransformer._tr_magic
Translate lines escaped with: %
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def _tr_magic(line_info): "Translate lines escaped with: %" tpl = '%sget_ipython().magic(%r)' cmd = ' '.join([line_info.ifun, line_info.the_rest]).strip() return tpl % (line_info.pre, cmd)
def _tr_magic(line_info): "Translate lines escaped with: %" tpl = '%sget_ipython().magic(%r)' cmd = ' '.join([line_info.ifun, line_info.the_rest]).strip() return tpl % (line_info.pre, cmd)
[ "Translate", "lines", "escaped", "with", ":", "%" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L675-L679
[ "def", "_tr_magic", "(", "line_info", ")", ":", "tpl", "=", "'%sget_ipython().magic(%r)'", "cmd", "=", "' '", ".", "join", "(", "[", "line_info", ".", "ifun", ",", "line_info", ".", "the_rest", "]", ")", ".", "strip", "(", ")", "return", "tpl", "%", "(", "line_info", ".", "pre", ",", "cmd", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
EscapedTransformer._tr_quote
Translate lines escaped with: ,
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def _tr_quote(line_info): "Translate lines escaped with: ," return '%s%s("%s")' % (line_info.pre, line_info.ifun, '", "'.join(line_info.the_rest.split()) )
def _tr_quote(line_info): "Translate lines escaped with: ," return '%s%s("%s")' % (line_info.pre, line_info.ifun, '", "'.join(line_info.the_rest.split()) )
[ "Translate", "lines", "escaped", "with", ":" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L682-L685
[ "def", "_tr_quote", "(", "line_info", ")", ":", "return", "'%s%s(\"%s\")'", "%", "(", "line_info", ".", "pre", ",", "line_info", ".", "ifun", ",", "'\", \"'", ".", "join", "(", "line_info", ".", "the_rest", ".", "split", "(", ")", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
EscapedTransformer._tr_paren
Translate lines escaped with: /
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def _tr_paren(line_info): "Translate lines escaped with: /" return '%s%s(%s)' % (line_info.pre, line_info.ifun, ", ".join(line_info.the_rest.split()))
def _tr_paren(line_info): "Translate lines escaped with: /" return '%s%s(%s)' % (line_info.pre, line_info.ifun, ", ".join(line_info.the_rest.split()))
[ "Translate", "lines", "escaped", "with", ":", "/" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L694-L697
[ "def", "_tr_paren", "(", "line_info", ")", ":", "return", "'%s%s(%s)'", "%", "(", "line_info", ".", "pre", ",", "line_info", ".", "ifun", ",", "\", \"", ".", "join", "(", "line_info", ".", "the_rest", ".", "split", "(", ")", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonInputSplitter.reset
Reset the input buffer and associated state.
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def reset(self): """Reset the input buffer and associated state.""" super(IPythonInputSplitter, self).reset() self._buffer_raw[:] = [] self.source_raw = '' self.cell_magic_parts = [] self.processing_cell_magic = False
def reset(self): """Reset the input buffer and associated state.""" super(IPythonInputSplitter, self).reset() self._buffer_raw[:] = [] self.source_raw = '' self.cell_magic_parts = [] self.processing_cell_magic = False
[ "Reset", "the", "input", "buffer", "and", "associated", "state", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L749-L755
[ "def", "reset", "(", "self", ")", ":", "super", "(", "IPythonInputSplitter", ",", "self", ")", ".", "reset", "(", ")", "self", ".", "_buffer_raw", "[", ":", "]", "=", "[", "]", "self", ".", "source_raw", "=", "''", "self", ".", "cell_magic_parts", "=", "[", "]", "self", ".", "processing_cell_magic", "=", "False" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonInputSplitter.source_raw_reset
Return input and raw source and perform a full reset.
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def source_raw_reset(self): """Return input and raw source and perform a full reset. """ out = self.source out_r = self.source_raw self.reset() return out, out_r
def source_raw_reset(self): """Return input and raw source and perform a full reset. """ out = self.source out_r = self.source_raw self.reset() return out, out_r
[ "Return", "input", "and", "raw", "source", "and", "perform", "a", "full", "reset", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L757-L763
[ "def", "source_raw_reset", "(", "self", ")", ":", "out", "=", "self", ".", "source", "out_r", "=", "self", ".", "source_raw", "self", ".", "reset", "(", ")", "return", "out", ",", "out_r" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonInputSplitter._handle_cell_magic
Process lines when they start with %%, which marks cell magics.
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def _handle_cell_magic(self, lines): """Process lines when they start with %%, which marks cell magics. """ self.processing_cell_magic = True first, _, body = lines.partition('\n') magic_name, _, line = first.partition(' ') magic_name = magic_name.lstrip(ESC_MAGIC) # We store the body of the cell and create a call to a method that # will use this stored value. This is ugly, but it's a first cut to # get it all working, as right now changing the return API of our # methods would require major refactoring. self.cell_magic_parts = [body] tpl = 'get_ipython()._run_cached_cell_magic(%r, %r)' tlines = tpl % (magic_name, line) self._store(tlines) self._store(lines, self._buffer_raw, 'source_raw') # We can actually choose whether to allow for single blank lines here # during input for clients that use cell mode to decide when to stop # pushing input (currently only the Qt console). # My first implementation did that, and then I realized it wasn't # consistent with the terminal behavior, so I've reverted it to one # line. But I'm leaving it here so we can easily test both behaviors, # I kind of liked having full blank lines allowed in the cell magics... #self._is_complete = last_two_blanks(lines) self._is_complete = last_blank(lines) return self._is_complete
def _handle_cell_magic(self, lines): """Process lines when they start with %%, which marks cell magics. """ self.processing_cell_magic = True first, _, body = lines.partition('\n') magic_name, _, line = first.partition(' ') magic_name = magic_name.lstrip(ESC_MAGIC) # We store the body of the cell and create a call to a method that # will use this stored value. This is ugly, but it's a first cut to # get it all working, as right now changing the return API of our # methods would require major refactoring. self.cell_magic_parts = [body] tpl = 'get_ipython()._run_cached_cell_magic(%r, %r)' tlines = tpl % (magic_name, line) self._store(tlines) self._store(lines, self._buffer_raw, 'source_raw') # We can actually choose whether to allow for single blank lines here # during input for clients that use cell mode to decide when to stop # pushing input (currently only the Qt console). # My first implementation did that, and then I realized it wasn't # consistent with the terminal behavior, so I've reverted it to one # line. But I'm leaving it here so we can easily test both behaviors, # I kind of liked having full blank lines allowed in the cell magics... #self._is_complete = last_two_blanks(lines) self._is_complete = last_blank(lines) return self._is_complete
[ "Process", "lines", "when", "they", "start", "with", "%%", "which", "marks", "cell", "magics", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L771-L796
[ "def", "_handle_cell_magic", "(", "self", ",", "lines", ")", ":", "self", ".", "processing_cell_magic", "=", "True", "first", ",", "_", ",", "body", "=", "lines", ".", "partition", "(", "'\\n'", ")", "magic_name", ",", "_", ",", "line", "=", "first", ".", "partition", "(", "' '", ")", "magic_name", "=", "magic_name", ".", "lstrip", "(", "ESC_MAGIC", ")", "# We store the body of the cell and create a call to a method that", "# will use this stored value. This is ugly, but it's a first cut to", "# get it all working, as right now changing the return API of our", "# methods would require major refactoring.", "self", ".", "cell_magic_parts", "=", "[", "body", "]", "tpl", "=", "'get_ipython()._run_cached_cell_magic(%r, %r)'", "tlines", "=", "tpl", "%", "(", "magic_name", ",", "line", ")", "self", ".", "_store", "(", "tlines", ")", "self", ".", "_store", "(", "lines", ",", "self", ".", "_buffer_raw", ",", "'source_raw'", ")", "# We can actually choose whether to allow for single blank lines here", "# during input for clients that use cell mode to decide when to stop", "# pushing input (currently only the Qt console).", "# My first implementation did that, and then I realized it wasn't", "# consistent with the terminal behavior, so I've reverted it to one", "# line. But I'm leaving it here so we can easily test both behaviors,", "# I kind of liked having full blank lines allowed in the cell magics...", "#self._is_complete = last_two_blanks(lines)", "self", ".", "_is_complete", "=", "last_blank", "(", "lines", ")", "return", "self", ".", "_is_complete" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonInputSplitter._line_mode_cell_append
Append new content for a cell magic in line mode.
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def _line_mode_cell_append(self, lines): """Append new content for a cell magic in line mode. """ # Only store the raw input. Lines beyond the first one are only only # stored for history purposes; for execution the caller will grab the # magic pieces from cell_magic_parts and will assemble the cell body self._store(lines, self._buffer_raw, 'source_raw') self.cell_magic_parts.append(lines) # Find out if the last stored block has a whitespace line as its # last line and also this line is whitespace, case in which we're # done (two contiguous blank lines signal termination). Note that # the storage logic *enforces* that every stored block is # newline-terminated, so we grab everything but the last character # so we can have the body of the block alone. last_block = self.cell_magic_parts[-1] self._is_complete = last_blank(last_block) and lines.isspace() return self._is_complete
def _line_mode_cell_append(self, lines): """Append new content for a cell magic in line mode. """ # Only store the raw input. Lines beyond the first one are only only # stored for history purposes; for execution the caller will grab the # magic pieces from cell_magic_parts and will assemble the cell body self._store(lines, self._buffer_raw, 'source_raw') self.cell_magic_parts.append(lines) # Find out if the last stored block has a whitespace line as its # last line and also this line is whitespace, case in which we're # done (two contiguous blank lines signal termination). Note that # the storage logic *enforces* that every stored block is # newline-terminated, so we grab everything but the last character # so we can have the body of the block alone. last_block = self.cell_magic_parts[-1] self._is_complete = last_blank(last_block) and lines.isspace() return self._is_complete
[ "Append", "new", "content", "for", "a", "cell", "magic", "in", "line", "mode", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L798-L814
[ "def", "_line_mode_cell_append", "(", "self", ",", "lines", ")", ":", "# Only store the raw input. Lines beyond the first one are only only", "# stored for history purposes; for execution the caller will grab the", "# magic pieces from cell_magic_parts and will assemble the cell body", "self", ".", "_store", "(", "lines", ",", "self", ".", "_buffer_raw", ",", "'source_raw'", ")", "self", ".", "cell_magic_parts", ".", "append", "(", "lines", ")", "# Find out if the last stored block has a whitespace line as its", "# last line and also this line is whitespace, case in which we're", "# done (two contiguous blank lines signal termination). Note that", "# the storage logic *enforces* that every stored block is", "# newline-terminated, so we grab everything but the last character", "# so we can have the body of the block alone.", "last_block", "=", "self", ".", "cell_magic_parts", "[", "-", "1", "]", "self", ".", "_is_complete", "=", "last_blank", "(", "last_block", ")", "and", "lines", ".", "isspace", "(", ")", "return", "self", ".", "_is_complete" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonInputSplitter.transform_cell
Process and translate a cell of input.
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def transform_cell(self, cell): """Process and translate a cell of input. """ self.reset() self.push(cell) return self.source_reset()
def transform_cell(self, cell): """Process and translate a cell of input. """ self.reset() self.push(cell) return self.source_reset()
[ "Process", "and", "translate", "a", "cell", "of", "input", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L816-L821
[ "def", "transform_cell", "(", "self", ",", "cell", ")", ":", "self", ".", "reset", "(", ")", "self", ".", "push", "(", "cell", ")", "return", "self", ".", "source_reset", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPythonInputSplitter.push
Push one or more lines of IPython input. This stores the given lines and returns a status code indicating whether the code forms a complete Python block or not, after processing all input lines for special IPython syntax. Any exceptions generated in compilation are swallowed, but if an exception was produced, the method returns True. Parameters ---------- lines : string One or more lines of Python input. Returns ------- is_complete : boolean True if the current input source (the result of the current input plus prior inputs) forms a complete Python execution block. Note that this value is also stored as a private attribute (_is_complete), so it can be queried at any time.
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
def push(self, lines): """Push one or more lines of IPython input. This stores the given lines and returns a status code indicating whether the code forms a complete Python block or not, after processing all input lines for special IPython syntax. Any exceptions generated in compilation are swallowed, but if an exception was produced, the method returns True. Parameters ---------- lines : string One or more lines of Python input. Returns ------- is_complete : boolean True if the current input source (the result of the current input plus prior inputs) forms a complete Python execution block. Note that this value is also stored as a private attribute (_is_complete), so it can be queried at any time. """ if not lines: return super(IPythonInputSplitter, self).push(lines) # We must ensure all input is pure unicode lines = cast_unicode(lines, self.encoding) # If the entire input block is a cell magic, return after handling it # as the rest of the transformation logic should be skipped. if lines.startswith('%%') and not \ (len(lines.splitlines()) == 1 and lines.strip().endswith('?')): return self._handle_cell_magic(lines) # In line mode, a cell magic can arrive in separate pieces if self.input_mode == 'line' and self.processing_cell_magic: return self._line_mode_cell_append(lines) # The rest of the processing is for 'normal' content, i.e. IPython # source that we process through our transformations pipeline. lines_list = lines.splitlines() transforms = [transform_ipy_prompt, transform_classic_prompt, transform_help_end, transform_escaped, transform_assign_system, transform_assign_magic] # Transform logic # # We only apply the line transformers to the input if we have either no # input yet, or complete input, or if the last line of the buffer ends # with ':' (opening an indented block). This prevents the accidental # transformation of escapes inside multiline expressions like # triple-quoted strings or parenthesized expressions. # # The last heuristic, while ugly, ensures that the first line of an # indented block is correctly transformed. # # FIXME: try to find a cleaner approach for this last bit. # If we were in 'block' mode, since we're going to pump the parent # class by hand line by line, we need to temporarily switch out to # 'line' mode, do a single manual reset and then feed the lines one # by one. Note that this only matters if the input has more than one # line. changed_input_mode = False if self.input_mode == 'cell': self.reset() changed_input_mode = True saved_input_mode = 'cell' self.input_mode = 'line' # Store raw source before applying any transformations to it. Note # that this must be done *after* the reset() call that would otherwise # flush the buffer. self._store(lines, self._buffer_raw, 'source_raw') try: push = super(IPythonInputSplitter, self).push buf = self._buffer for line in lines_list: if self._is_complete or not buf or \ (buf and buf[-1].rstrip().endswith((':', ','))): for f in transforms: line = f(line) out = push(line) finally: if changed_input_mode: self.input_mode = saved_input_mode return out
def push(self, lines): """Push one or more lines of IPython input. This stores the given lines and returns a status code indicating whether the code forms a complete Python block or not, after processing all input lines for special IPython syntax. Any exceptions generated in compilation are swallowed, but if an exception was produced, the method returns True. Parameters ---------- lines : string One or more lines of Python input. Returns ------- is_complete : boolean True if the current input source (the result of the current input plus prior inputs) forms a complete Python execution block. Note that this value is also stored as a private attribute (_is_complete), so it can be queried at any time. """ if not lines: return super(IPythonInputSplitter, self).push(lines) # We must ensure all input is pure unicode lines = cast_unicode(lines, self.encoding) # If the entire input block is a cell magic, return after handling it # as the rest of the transformation logic should be skipped. if lines.startswith('%%') and not \ (len(lines.splitlines()) == 1 and lines.strip().endswith('?')): return self._handle_cell_magic(lines) # In line mode, a cell magic can arrive in separate pieces if self.input_mode == 'line' and self.processing_cell_magic: return self._line_mode_cell_append(lines) # The rest of the processing is for 'normal' content, i.e. IPython # source that we process through our transformations pipeline. lines_list = lines.splitlines() transforms = [transform_ipy_prompt, transform_classic_prompt, transform_help_end, transform_escaped, transform_assign_system, transform_assign_magic] # Transform logic # # We only apply the line transformers to the input if we have either no # input yet, or complete input, or if the last line of the buffer ends # with ':' (opening an indented block). This prevents the accidental # transformation of escapes inside multiline expressions like # triple-quoted strings or parenthesized expressions. # # The last heuristic, while ugly, ensures that the first line of an # indented block is correctly transformed. # # FIXME: try to find a cleaner approach for this last bit. # If we were in 'block' mode, since we're going to pump the parent # class by hand line by line, we need to temporarily switch out to # 'line' mode, do a single manual reset and then feed the lines one # by one. Note that this only matters if the input has more than one # line. changed_input_mode = False if self.input_mode == 'cell': self.reset() changed_input_mode = True saved_input_mode = 'cell' self.input_mode = 'line' # Store raw source before applying any transformations to it. Note # that this must be done *after* the reset() call that would otherwise # flush the buffer. self._store(lines, self._buffer_raw, 'source_raw') try: push = super(IPythonInputSplitter, self).push buf = self._buffer for line in lines_list: if self._is_complete or not buf or \ (buf and buf[-1].rstrip().endswith((':', ','))): for f in transforms: line = f(line) out = push(line) finally: if changed_input_mode: self.input_mode = saved_input_mode return out
[ "Push", "one", "or", "more", "lines", "of", "IPython", "input", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L823-L914
[ "def", "push", "(", "self", ",", "lines", ")", ":", "if", "not", "lines", ":", "return", "super", "(", "IPythonInputSplitter", ",", "self", ")", ".", "push", "(", "lines", ")", "# We must ensure all input is pure unicode", "lines", "=", "cast_unicode", "(", "lines", ",", "self", ".", "encoding", ")", "# If the entire input block is a cell magic, return after handling it", "# as the rest of the transformation logic should be skipped.", "if", "lines", ".", "startswith", "(", "'%%'", ")", "and", "not", "(", "len", "(", "lines", ".", "splitlines", "(", ")", ")", "==", "1", "and", "lines", ".", "strip", "(", ")", ".", "endswith", "(", "'?'", ")", ")", ":", "return", "self", ".", "_handle_cell_magic", "(", "lines", ")", "# In line mode, a cell magic can arrive in separate pieces", "if", "self", ".", "input_mode", "==", "'line'", "and", "self", ".", "processing_cell_magic", ":", "return", "self", ".", "_line_mode_cell_append", "(", "lines", ")", "# The rest of the processing is for 'normal' content, i.e. IPython", "# source that we process through our transformations pipeline.", "lines_list", "=", "lines", ".", "splitlines", "(", ")", "transforms", "=", "[", "transform_ipy_prompt", ",", "transform_classic_prompt", ",", "transform_help_end", ",", "transform_escaped", ",", "transform_assign_system", ",", "transform_assign_magic", "]", "# Transform logic", "#", "# We only apply the line transformers to the input if we have either no", "# input yet, or complete input, or if the last line of the buffer ends", "# with ':' (opening an indented block). This prevents the accidental", "# transformation of escapes inside multiline expressions like", "# triple-quoted strings or parenthesized expressions.", "#", "# The last heuristic, while ugly, ensures that the first line of an", "# indented block is correctly transformed.", "#", "# FIXME: try to find a cleaner approach for this last bit.", "# If we were in 'block' mode, since we're going to pump the parent", "# class by hand line by line, we need to temporarily switch out to", "# 'line' mode, do a single manual reset and then feed the lines one", "# by one. Note that this only matters if the input has more than one", "# line.", "changed_input_mode", "=", "False", "if", "self", ".", "input_mode", "==", "'cell'", ":", "self", ".", "reset", "(", ")", "changed_input_mode", "=", "True", "saved_input_mode", "=", "'cell'", "self", ".", "input_mode", "=", "'line'", "# Store raw source before applying any transformations to it. Note", "# that this must be done *after* the reset() call that would otherwise", "# flush the buffer.", "self", ".", "_store", "(", "lines", ",", "self", ".", "_buffer_raw", ",", "'source_raw'", ")", "try", ":", "push", "=", "super", "(", "IPythonInputSplitter", ",", "self", ")", ".", "push", "buf", "=", "self", ".", "_buffer", "for", "line", "in", "lines_list", ":", "if", "self", ".", "_is_complete", "or", "not", "buf", "or", "(", "buf", "and", "buf", "[", "-", "1", "]", ".", "rstrip", "(", ")", ".", "endswith", "(", "(", "':'", ",", "','", ")", ")", ")", ":", "for", "f", "in", "transforms", ":", "line", "=", "f", "(", "line", ")", "out", "=", "push", "(", "line", ")", "finally", ":", "if", "changed_input_mode", ":", "self", ".", "input_mode", "=", "saved_input_mode", "return", "out" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
NotificationCenter._init_observers
Initialize observer storage
environment/lib/python2.7/site-packages/IPython/utils/notification.py
def _init_observers(self): """Initialize observer storage""" self.registered_types = set() #set of types that are observed self.registered_senders = set() #set of senders that are observed self.observers = {}
def _init_observers(self): """Initialize observer storage""" self.registered_types = set() #set of types that are observed self.registered_senders = set() #set of senders that are observed self.observers = {}
[ "Initialize", "observer", "storage" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/notification.py#L49-L54
[ "def", "_init_observers", "(", "self", ")", ":", "self", ".", "registered_types", "=", "set", "(", ")", "#set of types that are observed", "self", ".", "registered_senders", "=", "set", "(", ")", "#set of senders that are observed", "self", ".", "observers", "=", "{", "}" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e