signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def __del__(self):
self.setInactive()<EOL>
disconnect from output and error signal
f7772:c0:m6
def contextMenuEvent(self, event):
menu = QtWidgets.QTextEdit.createStandardContextMenu(self)<EOL>w = QtWidgets.QWidget()<EOL>l = QtWidgets.QHBoxLayout()<EOL>w.setLayout(l)<EOL>e = QtWidgets.QSpinBox()<EOL>e.setRange(<NUM_LIT:1>, <NUM_LIT>)<EOL>e.setValue(self.MAXLINES)<EOL>e.valueChanged.connect(self.document().setMaximumBlockCount)<EOL>l.addWidget(QtWidgets.QLabel('<STR_LIT>'))<EOL>l.addWidget(e)<EOL>a = QtWidgets.QWidgetAction(self)<EOL>a.setDefaultWidget(w)<EOL>menu.addAction(a)<EOL>menu.exec_(event.globalPos())<EOL>
Add menu action: * 'Show line numbers' * 'Save to file'
f7772:c0:m7
def findMenu(self, title):
<EOL>for menu in self.iter_menus():<EOL><INDENT>if menu.title() == title:<EOL><INDENT>return menu<EOL><DEDENT>for innerMenu in self.iter_inner_menus(menu):<EOL><INDENT>if innerMenu.title() == title:<EOL><INDENT>return innerMenu<EOL><DEDENT><DEDENT><DEDENT>
find a menu with a given title @type title: string @param title: English title of the menu @rtype: QMenu @return: None if no menu was found, else the menu with title
f7774:c0:m3
def insertMenuBefore(self, before_menu, new_menu):
if isinstance(before_menu, string_types):<EOL><INDENT>before_menu = self.findMenu(before_menu)<EOL><DEDENT>before_action = self.actionForMenu(before_menu)<EOL>new_action = self.insertMenu(before_action, new_menu)<EOL>return new_action<EOL>
Insert a menu after another menu in the menubar @type: before_menu QMenu instance or title string of menu @param before_menu: menu which should be after the newly inserted menu @rtype: QAction instance @return: action for inserted menu
f7774:c0:m5
def addEmptyTab(self, text='<STR_LIT>'):
tab = self.defaultTabWidget()<EOL>c = self.count()<EOL>self.addTab(tab, text)<EOL>self.setCurrentIndex(c)<EOL>if not text:<EOL><INDENT>self.tabBar().editTab(c)<EOL><DEDENT>self.sigTabAdded.emit(tab)<EOL>return tab<EOL>
Add a new DEFAULT_TAB_WIDGET, open editor to set text if no text is given
f7775:c0:m3
def _mkAddBtnVisible(self):
if not self._btn_add_height:<EOL><INDENT>self._btn_add_height = self.cornerWidget().height()<EOL>
Ensure that the Add button is visible also when there are no tabs
f7775:c0:m4
def removeTab(self, tab):
if not isinstance(tab, int):<EOL><INDENT>tab = self.indexOf(tab)<EOL><DEDENT>return super(FwTabWidget, self).removeTab(tab)<EOL>
allows to remove a tab directly -not only by giving its index
f7775:c0:m8
def tabText(self, tab):
if not isinstance(tab, int):<EOL><INDENT>tab = self.indexOf(tab)<EOL><DEDENT>return super(FwTabWidget, self).tabText(tab)<EOL>
allow index or tab widget instance
f7775:c0:m9
def addGlobals(self, g):
self.editor._globals.update(g)<EOL>pass<EOL>
g ==> {name:description,...}
f7776:c0:m1
def contextMenuEvent(self, event):
menu = QtWidgets.QPlainTextEdit.createStandardContextMenu(self)<EOL>mg = self.getGlobalsMenu()<EOL>a0 = menu.actions()[<NUM_LIT:0>]<EOL>menu.insertMenu(a0, mg)<EOL>menu.insertSeparator(a0)<EOL>menu.addSeparator()<EOL>a = QtWidgets.QAction('<STR_LIT>', menu)<EOL>l = self.codeEditor.lineNumbers<EOL>a.setCheckable(True)<EOL>a.setChecked(l.isVisible())<EOL>a.triggered.connect(lambda checked: l.show() if checked else l.hide())<EOL>menu.addAction(a)<EOL>menu.addSeparator()<EOL>a = QtWidgets.QAction('<STR_LIT>', menu)<EOL>a.triggered.connect(self.saveToFile)<EOL>menu.addAction(a)<EOL>menu.exec_(event.globalPos())<EOL>
Add menu action: * 'Show line numbers' * 'Save to file'
f7776:c1:m9
def saveToFile(self):
filename = self.codeEditor.dialog.getSaveFileName()<EOL>if filename and filename != '<STR_LIT:.>':<EOL><INDENT>with open(filename, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(self.toPlainText())<EOL><DEDENT>print('<STR_LIT>' % filename)<EOL><DEDENT>
Save the current text to file
f7776:c1:m10
def toPlainText(self):
txt = QtWidgets.QPlainTextEdit.toPlainText(self)<EOL>return txt.replace('<STR_LIT:\t>', '<STR_LIT:U+0020>')<EOL>
replace [tab] with 4 spaces
f7776:c1:m11
def _syncHScrollBar(self, val):
self.verticalScrollBar().setValue(val)<EOL>
Synchronize the view with the code editor
f7776:c2:m1
def _updateNumbers(self, linenumers):
b = self.blockCount()<EOL>c = b - linenumers<EOL>if c > <NUM_LIT:0>:<EOL><INDENT>for _ in range(c):<EOL><INDENT>self.setFocus()<EOL>storeCursorPos = self.textCursor()<EOL>self.moveCursor(<EOL>QtGui.QTextCursor.End,<EOL>QtGui.QTextCursor.MoveAnchor)<EOL>self.moveCursor(<EOL>QtGui.QTextCursor.StartOfLine,<EOL>QtGui.QTextCursor.MoveAnchor)<EOL>self.moveCursor(<EOL>QtGui.QTextCursor.End,<EOL>QtGui.QTextCursor.KeepAnchor)<EOL>self.textCursor().removeSelectedText()<EOL>self.textCursor().deletePreviousChar()<EOL>self.setTextCursor(storeCursorPos)<EOL><DEDENT><DEDENT>elif c < <NUM_LIT:0>:<EOL><INDENT>for i in range(-c):<EOL><INDENT>self.appendPlainText(str(b + i + <NUM_LIT:1>))<EOL><DEDENT><DEDENT>
add/remove line numbers
f7776:c2:m2
def save(self):
self.saveAs(self._path)<EOL>
save to file - override last saved file
f7777:c0:m4
def saveAs(self, path):
if not path:<EOL><INDENT>path = self._dialogs.getSaveFileName(filter='<STR_LIT>')<EOL><DEDENT>if path:<EOL><INDENT>self._setPath(path)<EOL>with open(str(self._path), '<STR_LIT:wb>') as stream:<EOL><INDENT>writer = csv.writer(stream)<EOL>table = self.table()<EOL>for row in table:<EOL><INDENT>writer.writerow(row)<EOL><DEDENT><DEDENT><DEDENT>
save to file under given name
f7777:c0:m6
def _textToTable(self, text, separator='<STR_LIT:\t>'):
table = None<EOL>if text.startswith('<STR_LIT>') or text.startswith('<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>t = eval(text)<EOL>if isinstance(t, list) and isinstance(t[<NUM_LIT:0>], list):<EOL><INDENT>table = t<EOL><DEDENT><DEDENT>except SyntaxError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if not table:<EOL><INDENT>table = text.split('<STR_LIT:\n>')<EOL>n = <NUM_LIT:0><EOL>while n < len(table):<EOL><INDENT>sline = table[n].split(separator)<EOL>if sline != ['<STR_LIT>']:<EOL><INDENT>table[n] = sline<EOL><DEDENT>else:<EOL><INDENT>table.pop(n)<EOL>n -= <NUM_LIT:1><EOL><DEDENT>n += <NUM_LIT:1><EOL><DEDENT><DEDENT>return table<EOL>
format csv, [[...]], ((..)) strings to a 2d table
f7777:c0:m17
def __init__(self, title, argdict, stayOpen=False, saveLoadButton=False,<EOL>savePath='<STR_LIT>', loadPath='<STR_LIT>',<EOL>introduction=None, unpackDict=False):
QtWidgets.QDialog.__init__(self)<EOL>self._wantToClose = False<EOL>self.unpackDict = unpackDict<EOL>if stayOpen:<EOL><INDENT>self.finished.connect(self.stayOpen)<EOL><DEDENT>self.setWindowTitle(title)<EOL>layout = QtWidgets.QGridLayout()<EOL>self.setLayout(layout)<EOL>if introduction:<EOL><INDENT>pass<EOL><DEDENT>self.values = []<EOL>self.args = {}<EOL>for row, (name, val) in enumerate(argdict.items()):<EOL><INDENT>limits = val.get('<STR_LIT>', None)<EOL>value = str(val.get('<STR_LIT:value>', '<STR_LIT>'))<EOL>unit = val.get('<STR_LIT>', None)<EOL>dtype = val.get('<STR_LIT>', None)<EOL>tip = val.get('<STR_LIT>', None)<EOL>nameLabel = QtWidgets.QLabel(name)<EOL>layout.addWidget(nameLabel, row, <NUM_LIT:0>)<EOL>if dtype == '<STR_LIT>':<EOL><INDENT>nameLabel.setText('<STR_LIT>' % nameLabel.text())<EOL>line = QtWidgets.QFrame()<EOL>line.setFrameStyle(<EOL>QtWidgets.QFrame.HLine | QtWidgets.QFrame.Raised)<EOL>layout.addWidget(line, row, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:3>)<EOL><DEDENT>elif dtype in ('<STR_LIT:file>', '<STR_LIT>'):<EOL><INDENT>wl = QtWidgets.QHBoxLayout()<EOL>q = QtWidgets.QLineEdit(value)<EOL>btn = QtWidgets.QPushButton()<EOL>if dtype == '<STR_LIT:file>':<EOL><INDENT>fn = self._getFile<EOL>btn.setIcon(<EOL>QtWidgets.QApplication.style().standardIcon(<EOL>QtWidgets.QStyle.SP_FileIcon))<EOL><DEDENT>else:<EOL><INDENT>fn = self._getFolder<EOL>btn.setIcon(<EOL>QtWidgets.QApplication.style().standardIcon(<EOL>QtWidgets.QStyle.SP_DirIcon))<EOL><DEDENT>btn.clicked.connect(<EOL>lambda checked, fn=fn, lineEdit=q: fn(lineEdit))<EOL>wl.addWidget(q)<EOL>wl.addWidget(btn)<EOL>layout.addLayout(wl, row, <NUM_LIT:1>)<EOL>self.values.append((name, q, str))<EOL><DEDENT>else:<EOL><INDENT>if type(limits) in (list, tuple):<EOL><INDENT>q = QtWidgets.QComboBox()<EOL>q.text = q.currentText<EOL>for n, l in enumerate(limits):<EOL><INDENT>limits[n] = str(l)<EOL><DEDENT>if value:<EOL><INDENT>if value in limits:<EOL><INDENT>limits.remove(value)<EOL><DEDENT>limits.insert(<NUM_LIT:0>, value)<EOL><DEDENT>q.addItems(limits)<EOL><DEDENT>else:<EOL><INDENT>q = QtWidgets.QLineEdit(value)<EOL>if dtype and dtype in self.validators:<EOL><INDENT>q.setValidator(self.validators[dtype]())<EOL><DEDENT><DEDENT>if tip:<EOL><INDENT>q.setToolTip(tip)<EOL><DEDENT>layout.addWidget(q, row, <NUM_LIT:1>)<EOL>if unit:<EOL><INDENT>layout.addWidget(QtWidgets.QLabel(str(unit)), row, <NUM_LIT:2>)<EOL><DEDENT>self.values.append((name, q, dtype))<EOL><DEDENT><DEDENT>if saveLoadButton:<EOL><INDENT>box = QtWidgets.QGroupBox('<STR_LIT>')<EOL>bLayout = QtWidgets.QGridLayout()<EOL>box.setLayout(bLayout)<EOL>btn_load = QtWidgets.QPushButton('<STR_LIT>')<EOL>self.label_load = QtWidgets.QLineEdit(loadPath)<EOL>btn_change_load = QtWidgets.QPushButton()<EOL>btn_change_load.setIcon(<EOL>QtWidgets.QApplication.style().standardIcon(<EOL>QtWidgets.QStyle.SP_DirIcon))<EOL>btn_change_load.clicked.connect(self._setLoadPath)<EOL>btn_load.clicked.connect(self._loadPreferences)<EOL>btn_save = QtWidgets.QPushButton('<STR_LIT>')<EOL>self.label_save = QtWidgets.QLineEdit(savePath)<EOL>btn_change_save = QtWidgets.QPushButton()<EOL>btn_change_save.setIcon(<EOL>QtWidgets.QApplication.style().standardIcon(<EOL>QtWidgets.QStyle.SP_DirIcon))<EOL>btn_change_save.clicked.connect(self._setSavePath)<EOL>btn_save.clicked.connect(self._savePreferences)<EOL>bLayout.addWidget(btn_load, <NUM_LIT:0>, <NUM_LIT:0>)<EOL>bLayout.addWidget(self.label_load, <NUM_LIT:0>, <NUM_LIT:1>)<EOL>bLayout.addWidget(btn_change_load, <NUM_LIT:0>, <NUM_LIT:2>)<EOL>bLayout.addWidget(btn_save, <NUM_LIT:1>, <NUM_LIT:0>)<EOL>bLayout.addWidget(self.label_save, <NUM_LIT:1>, <NUM_LIT:1>)<EOL>bLayout.addWidget(btn_change_save, <NUM_LIT:1>, <NUM_LIT:2>)<EOL>row += <NUM_LIT:1><EOL>layout.addWidget(box, row, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:3>)<EOL><DEDENT>self.btn_done = QtWidgets.QPushButton('<STR_LIT>')<EOL>self.btn_done.clicked.connect(self.check)<EOL>layout.addWidget(self.btn_done, row + <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:3>)<EOL>
==================== ========================================================= Argument Comment ==================== ========================================================= title title of the window argdict a dict of all arguments to set up: e.g. {'arg1: {'value':1, 'limits':range(0,10)}, ...} valid keywords are: 'value' -> the value of the argument 'limits' -> [list, tuple] if only specific values are valid 'unit' -> show a unit after the value 'tip' -> show a tool-tip 'dtype' -> the data-type of the value * int, str, float, bool * file, dir -> for selecting a file or folder * line -> to add a horizontal separation line for ordered entries use OrderedDict stayOpen True -> dialog stays open after it is finished useful if values should still be changeable saveLoadButton True -> add 2 buttons to save and load these preferences savePath Default save path loadPath Default load path unpackDict True, False | True: ==================== =========================================================
f7781:c0:m0
def show(self):
self.btn_done.clicked.connect(lambda: self.btn_done.setText('<STR_LIT>'))<EOL>QtWidgets.QDialog.show(self)<EOL>
if the dialog is showed again or is not started with exec_ naming the done button to 'update' make more sense because now the dialog doesn't block (anymore)
f7781:c0:m7
def check(self):
for name, valItem, dtype in self.values:<EOL><INDENT>val = valItem.text()<EOL>if dtype:<EOL><INDENT>try:<EOL><INDENT>val = dtype(val)<EOL><DEDENT>except:<EOL><INDENT>msgBox = QtWidgets.QMessageBox()<EOL>msgBox.setText(<EOL>'<STR_LIT>' %<EOL>(name, str(dtype)))<EOL>msgBox.exec_()<EOL><DEDENT><DEDENT>self.args[name] = val<EOL><DEDENT>self.accept()<EOL>
check whether all attributes are setted and have the right dtype
f7781:c0:m10
def done(self, result):
self._geometry = self.geometry()<EOL>QtWidgets.QDialog.done(self, result)<EOL>
save the geometry before dialog is close to restore it later
f7781:c0:m12
def stayOpen(self):
if not self._wantToClose:<EOL><INDENT>self.show()<EOL>self.setGeometry(self._geometry)<EOL><DEDENT>
optional dialog restore
f7781:c0:m13
def saveState(self):
<INDENT>p = PathStr(path).join('<STR_LIT>')<EOL>with open(p, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(str(self.opts))<EOL><DEDENT><DEDENT>return self.opts<EOL>
save options to file 'dialogs.conf'
f7782:c0:m1
def restoreState(self, state):
<INDENT>p = PathStr(path).join('<STR_LIT>')<EOL>with open(p, '<STR_LIT:r>') as f:<EOL><DEDENT>self.opts.update(state)<EOL>
restore options from file 'dialogs.conf'
f7782:c0:m2
def getSaveFileName(self, *args, **kwargs):
if '<STR_LIT>' not in kwargs:<EOL><INDENT>if self.opts['<STR_LIT>']:<EOL><INDENT>if self.opts['<STR_LIT>']:<EOL><INDENT>kwargs['<STR_LIT>'] = self.opts['<STR_LIT>']<EOL><DEDENT><DEDENT><DEDENT>fname = QtWidgets.QFileDialog.getSaveFileName(**kwargs)<EOL>if fname:<EOL><INDENT>if type(fname) == tuple:<EOL><INDENT>if not fname[<NUM_LIT:0>]:<EOL><INDENT>return<EOL><DEDENT>p = PathStr(fname[<NUM_LIT:0>])<EOL>if not p.filetype():<EOL><INDENT>ftyp = self._extractFtype(fname[<NUM_LIT:1>]) <EOL>p = p.setFiletype(ftyp)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>p = PathStr(fname)<EOL><DEDENT>self.opts['<STR_LIT>'] = p.dirname()<EOL>if self.opts['<STR_LIT>'] is None:<EOL><INDENT>self.opts['<STR_LIT>'] = self.opts['<STR_LIT>']<EOL><DEDENT>return p<EOL><DEDENT>
analogue to QtWidgets.QFileDialog.getSaveFileNameAndFilter but returns the filename + chosen file ending even if not typed in gui
f7782:c0:m3
def highlightBlock(self, text):
<EOL>cb = self.currentBlock()<EOL>p = cb.position()<EOL>text = str(self.document().toPlainText()) + '<STR_LIT:\n>'<EOL>highlight(text, self.lexer, self.formatter)<EOL>for i in range(len(str(text))):<EOL><INDENT>try:<EOL><INDENT>self.setFormat(i, <NUM_LIT:1>, self.formatter.data[p + i])<EOL><DEDENT>except IndexError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>self.tstamp = time.time()<EOL>
Takes a block, applies format to the document. according to what's in it.
f7783:c1:m1
def setWidget(self, widget, index=<NUM_LIT:0>, row=None,<EOL>col=<NUM_LIT:0>, rowspan=<NUM_LIT:1>, colspan=<NUM_LIT:1>):
if row is None:<EOL><INDENT>row = self.currentRow<EOL><DEDENT>self.currentRow = max(row + <NUM_LIT:1>, self.currentRow)<EOL>if index > len(self.widgets) - <NUM_LIT:1>:<EOL><INDENT>self.widgets.append(widget)<EOL><DEDENT>else: <EOL><INDENT>self.layout.removeWidget(self.widgets[index])<EOL>self.widgets[index] = widget<EOL><DEDENT>self.layout.addWidget(widget, row, col, rowspan, colspan)<EOL>self.raiseOverlay()<EOL>
Add new widget inside dock, remove old one if existent
f7788:c0:m5
def makeWidget(self):
opts = self.param.opts<EOL>t = opts['<STR_LIT:type>']<EOL>if t == '<STR_LIT:int>':<EOL><INDENT>defs = {<EOL>'<STR_LIT:value>': <NUM_LIT:0>, '<STR_LIT>': None, '<STR_LIT>': None, '<STR_LIT:int>': True,<EOL>'<STR_LIT>': <NUM_LIT:1.0>, '<STR_LIT>': <NUM_LIT:1.0>, '<STR_LIT>': False,<EOL>'<STR_LIT>': False, '<STR_LIT>': '<STR_LIT>'<EOL>}<EOL>defs.update(opts)<EOL>if '<STR_LIT>' in opts:<EOL><INDENT>defs['<STR_LIT>'] = opts['<STR_LIT>']<EOL><DEDENT>w = SpinBox()<EOL>w.setOpts(**defs)<EOL>w.sigChanged = w.sigValueChanged<EOL>w.sigChanging = w.sigValueChanging<EOL><DEDENT>elif t == '<STR_LIT:float>':<EOL><INDENT>defs = {<EOL>'<STR_LIT:value>': <NUM_LIT:0>, '<STR_LIT>': None, '<STR_LIT>': None,<EOL>'<STR_LIT>': <NUM_LIT:1.0>, '<STR_LIT>': False,<EOL>'<STR_LIT>': False, '<STR_LIT>': '<STR_LIT>'<EOL>}<EOL>defs.update(opts)<EOL>if '<STR_LIT>' in opts:<EOL><INDENT>defs['<STR_LIT>'] = opts['<STR_LIT>']<EOL><DEDENT>w = SpinBox()<EOL>w.setOpts(**defs)<EOL>w.sigChanged = w.sigValueChanged<EOL>w.sigChanging = w.sigValueChanging<EOL><DEDENT>elif t == '<STR_LIT:bool>':<EOL><INDENT>w = QtWidgets.QCheckBox()<EOL>w.sigChanged = w.toggled<EOL>w.value = w.isChecked<EOL>w.setValue = w.setChecked<EOL>w.setEnabled(not opts.get('<STR_LIT>', False))<EOL>self.hideWidget = False<EOL><DEDENT>elif t == '<STR_LIT:str>':<EOL><INDENT>w = QtWidgets.QLineEdit()<EOL>w.sigChanged = w.editingFinished<EOL>w.value = lambda: asUnicode(w.text())<EOL>w.setValue = lambda v: w.setText(asUnicode(v))<EOL>w.sigChanging = w.textChanged<EOL><DEDENT>elif t == '<STR_LIT>':<EOL><INDENT>w = ColorButton()<EOL>w.sigChanged = w.sigColorChanged<EOL>w.sigChanging = w.sigColorChanging<EOL>w.value = w.color<EOL>w.setValue = w.setColor<EOL>self.hideWidget = False<EOL>w.setFlat(True)<EOL>w.setEnabled(not opts.get('<STR_LIT>', False))<EOL><DEDENT>elif t == '<STR_LIT>':<EOL><INDENT>w = GradientWidget(orientation='<STR_LIT>')<EOL>w.sigChanged = w.sigGradientChangeFinished<EOL>w.sigChanging = w.sigGradientChanged<EOL>w.value = w.colorMap<EOL>w.setValue = w.setColorMap<EOL>self.hideWidget = False<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>" % asUnicode(t))<EOL><DEDENT>return w<EOL>
Return a single widget that should be placed in the second tree column. The widget must be given three attributes: ========== ============================================================ sigChanged a signal that is emitted when the widget's value is changed value a function that returns the value setValue a function that sets the value ========== ============================================================ This is a good function to override in subclasses.
f7793:c0:m1
def updateDisplayLabel(self, value=None):
if value is None:<EOL><INDENT>value = self.param.value()<EOL><DEDENT>opts = self.param.opts<EOL>if isinstance(self.widget, QtWidgets.QAbstractSpinBox):<EOL><INDENT>text = asUnicode(self.widget.lineEdit().text())<EOL><DEDENT>elif isinstance(self.widget, QtWidgets.QComboBox):<EOL><INDENT>text = self.widget.currentText()<EOL><DEDENT>else:<EOL><INDENT>text = asUnicode(value)<EOL><DEDENT>self.displayLabel.setText(text)<EOL>
Update the display label to reflect the value of the parameter.
f7793:c0:m7
def widgetValueChanging(self, *args):
<EOL>self.param.sigValueChanging.emit(self.param, args[-<NUM_LIT:1>])<EOL>
Called when the widget's value is changing, but not finalized. For example: editing text before pressing enter or changing focus.
f7793:c0:m9
def selected(self, sel):
ParameterItem.selected(self, sel)<EOL>if self.widget is None:<EOL><INDENT>return<EOL><DEDENT>if sel and self.param.writable():<EOL><INDENT>self.showEditor()<EOL><DEDENT>elif self.hideWidget:<EOL><INDENT>self.hideEditor()<EOL><DEDENT>
Called when this item has been selected (sel=True) OR deselected (sel=False)
f7793:c0:m10
def limitsChanged(self, param, limits):
ParameterItem.limitsChanged(self, param, limits)<EOL>t = self.param.opts['<STR_LIT:type>']<EOL>if t == '<STR_LIT:int>' or t == '<STR_LIT:float>':<EOL><INDENT>self.widget.setOpts(bounds=limits)<EOL><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT>
Called when the parameter's limits have changed
f7793:c0:m13
def treeWidgetChanged(self):
ParameterItem.treeWidgetChanged(self)<EOL>if self.widget is not None:<EOL><INDENT>tree = self.treeWidget()<EOL>if tree is None:<EOL><INDENT>return<EOL><DEDENT>tree.setItemWidget(self, <NUM_LIT:1>, self.layoutWidget)<EOL>self.displayLabel.hide()<EOL>self.selected(False)<EOL><DEDENT>
Called when this item is added or removed from a tree.
f7793:c0:m15
def optsChanged(self, param, opts):
<EOL>ParameterItem.optsChanged(self, param, opts)<EOL>w = self.widget<EOL>if '<STR_LIT>' in opts:<EOL><INDENT>self.updateDefaultBtn()<EOL>if isinstance(w, (QtWidgets.QCheckBox, ColorButton)):<EOL><INDENT>w.setEnabled(not opts['<STR_LIT>'])<EOL><DEDENT><DEDENT>if isinstance(self.widget, SpinBox):<EOL><INDENT>if '<STR_LIT>' in opts and '<STR_LIT>' not in opts:<EOL><INDENT>opts['<STR_LIT>'] = opts['<STR_LIT>']<EOL><DEDENT>w.setOpts(**opts)<EOL>self.updateDisplayLabel()<EOL><DEDENT>
Called when any options are changed that are not name, value, default, or limits
f7793:c0:m17
def addClicked(self):
self.param.addNew()<EOL>
Called when "add new" button is clicked The parameter MUST have an 'addNew' method defined.
f7793:c3:m2
def addChanged(self):
if self.addWidget.currentIndex() == <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>typ = asUnicode(self.addWidget.currentText())<EOL>self.param.addNew(typ)<EOL>self.addWidget.setCurrentIndex(<NUM_LIT:0>)<EOL>
Called when "add new" combo is changed The parameter MUST have an 'addNew' method defined.
f7793:c3:m3
def addNew(self, typ=None):
raise Exception("<STR_LIT>")<EOL>
This method is called when the user has requested to add a new item to the group.
f7793:c4:m0
def setAddList(self, vals):
self.setOpts(addList=vals)<EOL>
Change the list of options available for the user to add to the group.
f7793:c4:m1
def nameChanged(self, name):
pass<EOL>
Pass method, otherwise name is additionally set in tableView
f7793:c7:m1
def blockSignals(self, boolean):
pgParameter.blockSignals(self, boolean)<EOL>try:<EOL><INDENT>item = self.items[<NUM_LIT:0>]<EOL>if item.key:<EOL><INDENT>item.key.blockSignals(boolean)<EOL><DEDENT><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>
add block/unblock of keyboard shortcut
f7796:c0:m2
def replaceWith(self, param):
i = self.parent().children().index(self)<EOL>p = self.parent()<EOL>self.parent().removeChild(self)<EOL>p.insertChild(i, param)<EOL>self = param<EOL>
replace this parameter with another
f7796:c0:m5
def read(*paths):
try:<EOL><INDENT>f_name = os.path.join(*paths)<EOL>with open(f_name, '<STR_LIT:r>') as f:<EOL><INDENT>return f.read()<EOL><DEDENT><DEDENT>except IOError:<EOL><INDENT>print('<STR_LIT>' % f_name)<EOL>return '<STR_LIT>'<EOL><DEDENT>
Build a file path from *paths* and return the contents.
f7801:m0
def template_to_base_path(template, google_songs):
if template == os.getcwd() or template == '<STR_LIT>':<EOL><INDENT>base_path = os.getcwd()<EOL><DEDENT>else:<EOL><INDENT>template = os.path.abspath(template)<EOL>song_paths = [template_to_filepath(template, song) for song in google_songs]<EOL>base_path = os.path.dirname(os.path.commonprefix(song_paths))<EOL><DEDENT>return base_path<EOL>
Get base output path for a list of songs for download.
f7803:m0
@classmethod<EOL><INDENT>def _connect(cls):<DEDENT>
return connect(**cls._conn_info)<EOL>
Connects to vertica. :return: a connection to vertica.
f7818:c0:m2
@classmethod<EOL><INDENT>def _get_node_num(cls):<DEDENT>
with cls._connect() as conn:<EOL><INDENT>cur = conn.cursor()<EOL>cur.execute("<STR_LIT>")<EOL>return cur.fetchone()[<NUM_LIT:0>]<EOL><DEDENT>
Executes a query to get the number of nodes in the database :return: the number of database nodes
f7818:c0:m3
def _query_and_fetchall(self, query):
with self._connect() as conn:<EOL><INDENT>cur = conn.cursor()<EOL>cur.execute(query)<EOL>results = cur.fetchall()<EOL><DEDENT>return results<EOL>
Creates a new connection, executes a query and fetches all the results. :param query: query to execute :return: all fetched results as returned by cursor.fetchall()
f7818:c0:m5
def _query_and_fetchone(self, query):
with self._connect() as conn:<EOL><INDENT>cur = conn.cursor()<EOL>cur.execute(query)<EOL>result = cur.fetchone()<EOL><DEDENT>return result<EOL>
Creates a new connection, executes a query and fetches one result. :param query: query to execute :return: the first result fetched by cursor.fetchone()
f7818:c0:m6
def as_bytes(bytes_or_text, encoding='<STR_LIT:utf-8>'):
if isinstance(bytes_or_text, _six.text_type):<EOL><INDENT>return bytes_or_text.encode(encoding)<EOL><DEDENT>elif isinstance(bytes_or_text, bytes):<EOL><INDENT>return bytes_or_text<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>' %<EOL>(bytes_or_text,))<EOL><DEDENT>
Converts either bytes or unicode to `bytes`, using utf-8 encoding for text. Args: bytes_or_text: A `bytes`, `str`, or `unicode` object. encoding: A string indicating the charset for encoding unicode. Returns: A `bytes` object. Raises: TypeError: If `bytes_or_text` is not a binary or unicode string.
f7825:m0
def as_text(bytes_or_text, encoding='<STR_LIT:utf-8>'):
if isinstance(bytes_or_text, _six.text_type):<EOL><INDENT>return bytes_or_text<EOL><DEDENT>elif isinstance(bytes_or_text, bytes):<EOL><INDENT>return bytes_or_text.decode(encoding)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>' % bytes_or_text)<EOL><DEDENT>
Returns the given argument as a unicode string. Args: bytes_or_text: A `bytes`, `str, or `unicode` object. encoding: A string indicating the charset for decoding unicode. Returns: A `unicode` (Python 2) or `str` (Python 3) object. Raises: TypeError: If `bytes_or_text` is not a binary or unicode string.
f7825:m1
def as_str_any(value):
if isinstance(value, bytes):<EOL><INDENT>return as_str(value)<EOL><DEDENT>else:<EOL><INDENT>return str(value)<EOL><DEDENT>
Converts to `str` as `str(value)`, but use `as_str` for `bytes`. Args: value: A object that can be converted to `str`. Returns: A `str` object.
f7825:m2
def getTypeName(data_type_oid, type_modifier):
if data_type_oid == VerticaType.BOOL:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif data_type_oid == VerticaType.INT8:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif data_type_oid == VerticaType.FLOAT8:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif data_type_oid == VerticaType.CHAR:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif data_type_oid in (VerticaType.VARCHAR, VerticaType.UNKNOWN):<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif data_type_oid == VerticaType.LONGVARCHAR:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif data_type_oid == VerticaType.DATE:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif data_type_oid == VerticaType.TIME:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif data_type_oid == VerticaType.TIMETZ:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif data_type_oid == VerticaType.TIMESTAMP:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif data_type_oid == VerticaType.TIMESTAMPTZ:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif data_type_oid in (VerticaType.INTERVAL, VerticaType.INTERVALYM):<EOL><INDENT>return "<STR_LIT>" + getIntervalRange(data_type_oid, type_modifier)<EOL><DEDENT>elif data_type_oid == VerticaType.BINARY:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif data_type_oid == VerticaType.VARBINARY:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif data_type_oid == VerticaType.LONGVARBINARY:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif data_type_oid == VerticaType.NUMERIC:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif data_type_oid == VerticaType.UUID:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>
Returns the base type name according to data_type_oid and type_modifier
f7826:m7
def getIntervalRange(data_type_oid, type_modifier):
if data_type_oid not in (VerticaType.INTERVAL, VerticaType.INTERVALYM):<EOL><INDENT>raise ValueError("<STR_LIT>".format(data_type_oid))<EOL><DEDENT>if type_modifier == -<NUM_LIT:1>: <EOL><INDENT>if data_type_oid == VerticaType.INTERVALYM:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif data_type_oid == VerticaType.INTERVAL:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT><DEDENT>if data_type_oid == VerticaType.INTERVALYM: <EOL><INDENT>if (type_modifier & INTERVAL_MASK_YEAR2MONTH) == INTERVAL_MASK_YEAR2MONTH:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif (type_modifier & INTERVAL_MASK_YEAR) == INTERVAL_MASK_YEAR:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif (type_modifier & INTERVAL_MASK_MONTH) == INTERVAL_MASK_MONTH:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT><DEDENT>if data_type_oid == VerticaType.INTERVAL: <EOL><INDENT>if (type_modifier & INTERVAL_MASK_DAY2SEC) == INTERVAL_MASK_DAY2SEC:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif (type_modifier & INTERVAL_MASK_DAY2MIN) == INTERVAL_MASK_DAY2MIN:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif (type_modifier & INTERVAL_MASK_DAY2HOUR) == INTERVAL_MASK_DAY2HOUR:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif (type_modifier & INTERVAL_MASK_DAY) == INTERVAL_MASK_DAY:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif (type_modifier & INTERVAL_MASK_HOUR2SEC) == INTERVAL_MASK_HOUR2SEC:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif (type_modifier & INTERVAL_MASK_HOUR2MIN) == INTERVAL_MASK_HOUR2MIN:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif (type_modifier & INTERVAL_MASK_HOUR) == INTERVAL_MASK_HOUR:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif (type_modifier & INTERVAL_MASK_MIN2SEC) == INTERVAL_MASK_MIN2SEC:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif (type_modifier & INTERVAL_MASK_MINUTE) == INTERVAL_MASK_MINUTE:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif (type_modifier & INTERVAL_MASK_SECOND) == INTERVAL_MASK_SECOND:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT><DEDENT>
Extracts an interval's range from the bits set in its type_modifier
f7826:m8
def getIntervalLeadingPrecision(data_type_oid, type_modifier):
interval_range = getIntervalRange(data_type_oid, type_modifier)<EOL>if interval_range in ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif interval_range == "<STR_LIT>":<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif interval_range in ("<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return <NUM_LIT:9><EOL><DEDENT>elif interval_range in ("<STR_LIT>", "<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return <NUM_LIT:10><EOL><DEDENT>elif interval_range in ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return <NUM_LIT:12><EOL><DEDENT>elif interval_range == "<STR_LIT>":<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>".format(interval_range))<EOL><DEDENT>
Returns the leading precision for an interval, which is the largest number of digits that can fit in the leading field of the interval. All Year/Month intervals are defined in terms of months, even if the type_modifier forbids months to be specified (i.e. INTERVAL YEAR). Similarly, all Day/Time intervals are defined as a number of microseconds. Because of this, interval types with shorter ranges will have a larger leading precision. For example, an INTERVAL DAY's leading precision is ((2^63)-1)/MICROSECS_PER_DAY, while an INTERVAL HOUR's leading precision is ((2^63)-1)/MICROSECS_PER_HOUR
f7826:m9
def getPrecision(data_type_oid, type_modifier):
if data_type_oid == VerticaType.NUMERIC:<EOL><INDENT>if type_modifier == -<NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>return ((type_modifier - <NUM_LIT:4>) >> <NUM_LIT:16>) & <NUM_LIT><EOL><DEDENT>elif data_type_oid in (VerticaType.TIME, VerticaType.TIMETZ,<EOL>VerticaType.TIMESTAMP, VerticaType.TIMESTAMPTZ,<EOL>VerticaType.INTERVAL, VerticaType.INTERVALYM):<EOL><INDENT>if type_modifier == -<NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:6><EOL><DEDENT>return type_modifier & <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>
Returns the precision for the given Vertica type with consideration of the type modifier. For numerics, precision is the total number of digits (in base 10) that can fit in the type. For intervals, time and timestamps, precision is the number of digits to the right of the decimal point in the seconds portion of the time. The type modifier of -1 is used when the size of a type is unknown. In those cases we assume the maximum possible size.
f7826:m10
def getScale(data_type_oid, type_modifier):
if data_type_oid == VerticaType.NUMERIC:<EOL><INDENT>return <NUM_LIT:15> if type_modifier == -<NUM_LIT:1> else (type_modifier - <NUM_LIT:4>) & <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>
Returns the scale for the given Vertica type with consideration of the type modifier.
f7826:m11
def getDisplaySize(data_type_oid, type_modifier):
if data_type_oid == VerticaType.BOOL:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>elif data_type_oid == VerticaType.INT8:<EOL><INDENT>return <NUM_LIT:20><EOL><DEDENT>elif data_type_oid == VerticaType.FLOAT8:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif data_type_oid == VerticaType.NUMERIC:<EOL><INDENT>return getPrecision(data_type_oid, type_modifier) + <NUM_LIT:2><EOL><DEDENT>elif data_type_oid == VerticaType.DATE:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif data_type_oid == VerticaType.TIME:<EOL><INDENT>seconds_precision = getPrecision(data_type_oid, type_modifier)<EOL>if seconds_precision == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:8><EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:9> + seconds_precision<EOL><DEDENT><DEDENT>elif data_type_oid == VerticaType.TIMETZ:<EOL><INDENT>seconds_precision = getPrecision(data_type_oid, type_modifier)<EOL>if seconds_precision == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:15> + seconds_precision<EOL><DEDENT><DEDENT>elif data_type_oid == VerticaType.TIMESTAMP:<EOL><INDENT>seconds_precision = getPrecision(data_type_oid, type_modifier)<EOL>if seconds_precision == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT> + seconds_precision<EOL><DEDENT><DEDENT>elif data_type_oid == VerticaType.TIMESTAMPTZ:<EOL><INDENT>seconds_precision = getPrecision(data_type_oid, type_modifier)<EOL>if seconds_precision == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT> + seconds_precision<EOL><DEDENT><DEDENT>elif data_type_oid in (VerticaType.INTERVAL, VerticaType.INTERVALYM):<EOL><INDENT>leading_precision = getIntervalLeadingPrecision(data_type_oid, type_modifier)<EOL>seconds_precision = getPrecision(data_type_oid, type_modifier)<EOL>interval_range = getIntervalRange(data_type_oid, type_modifier)<EOL>if interval_range in ("<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return <NUM_LIT:1> + leading_precision<EOL><DEDENT>elif interval_range in ("<STR_LIT>", "<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return <NUM_LIT:1> + leading_precision + <NUM_LIT:3><EOL><DEDENT>elif interval_range == "<STR_LIT>":<EOL><INDENT>return <NUM_LIT:1> + leading_precision + <NUM_LIT:6><EOL><DEDENT>elif interval_range == "<STR_LIT>":<EOL><INDENT>if seconds_precision == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:1> + leading_precision<EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:1> + leading_precision + <NUM_LIT:1> + seconds_precision<EOL><DEDENT><DEDENT>elif interval_range == "<STR_LIT>":<EOL><INDENT>if seconds_precision == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:1> + leading_precision + <NUM_LIT:9><EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:1> + leading_precision + <NUM_LIT:10> + seconds_precision<EOL><DEDENT><DEDENT>elif interval_range == "<STR_LIT>":<EOL><INDENT>if seconds_precision == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:1> + leading_precision + <NUM_LIT:6><EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:1> + leading_precision + <NUM_LIT:7> + seconds_precision<EOL><DEDENT><DEDENT>elif interval_range == "<STR_LIT>":<EOL><INDENT>if seconds_precision == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:1> + leading_precision + <NUM_LIT:3><EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:1> + leading_precision + <NUM_LIT:4> + seconds_precision<EOL><DEDENT><DEDENT><DEDENT>elif data_type_oid == VerticaType.UUID:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif data_type_oid in (VerticaType.CHAR,<EOL>VerticaType.VARCHAR,<EOL>VerticaType.BINARY,<EOL>VerticaType.VARBINARY,<EOL>VerticaType.UNKNOWN):<EOL><INDENT>return MAX_STRING_LEN if type_modifier <= -<NUM_LIT:1> else (type_modifier - <NUM_LIT:4>)<EOL><DEDENT>elif data_type_oid in (VerticaType.LONGVARCHAR,<EOL>VerticaType.LONGVARBINARY):<EOL><INDENT>return MAX_LONG_STRING_LEN if type_modifier <= -<NUM_LIT:1> else (type_modifier - <NUM_LIT:4>)<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>
Returns the column display size for the given Vertica type with consideration of the type modifier. The display size of a column is the maximum number of characters needed to display data in character form.
f7826:m12
def connect(**kwargs):
return Connection(kwargs)<EOL>
Opens a new connection to a Vertica database.
f7828:m0
def __init__(self, host, port, backup_nodes, logger):
self._logger = logger<EOL>self.address_deque = deque()<EOL>self._append(host, port)<EOL>if not isinstance(backup_nodes, list):<EOL><INDENT>err_msg = '<STR_LIT>'<EOL>self._logger.error(err_msg)<EOL>raise TypeError(err_msg)<EOL><DEDENT>for node in backup_nodes:<EOL><INDENT>if isinstance(node, string_types):<EOL><INDENT>self._append(node, DEFAULT_PORT)<EOL><DEDENT>elif isinstance(node, tuple) and len(node) == <NUM_LIT:2>:<EOL><INDENT>self._append(node[<NUM_LIT:0>], node[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>err_msg = ('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>self._logger.error(err_msg)<EOL>raise TypeError(err_msg)<EOL><DEDENT><DEDENT>self._logger.debug('<STR_LIT>'.format(list(self.address_deque)))<EOL>
Creates a new deque with the primary host first, followed by any backup hosts
f7828:c0:m0
@classmethod<EOL><INDENT>def ensure_dir_exists(cls, filepath):<DEDENT>
directory = os.path.dirname(filepath)<EOL>if directory != '<STR_LIT>' and not os.path.exists(directory):<EOL><INDENT>try:<EOL><INDENT>os.makedirs(directory)<EOL><DEDENT>except OSError as e:<EOL><INDENT>if e.errno != errno.EEXIST:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT>
Ensure that a directory exists If it doesn't exist, try to create it and protect against a race condition if another process is doing the same.
f7829:c0:m1
def date_parse(s):
s = as_str(s)<EOL>if s.endswith('<STR_LIT>'):<EOL><INDENT>raise errors.NotSupportedError('<STR_LIT>'.format(s))<EOL><DEDENT>return date(*map(lambda x: min(int(x), <NUM_LIT>), s.split('<STR_LIT:->')))<EOL>
Parses value of a DATE type. :param s: string to parse into date :return: an instance of datetime.date :raises NotSupportedError when a date Before Christ is encountered
f7830:m4
def nextset(self):
<EOL>self.flush_to_end_of_result()<EOL>if self._message is None:<EOL><INDENT>return False<EOL><DEDENT>elif isinstance(self._message, END_OF_RESULT_RESPONSES):<EOL><INDENT>self._message = self.connection.read_message()<EOL>if isinstance(self._message, messages.RowDescription):<EOL><INDENT>self.description = [Column(fd, self.unicode_error) for fd in self._message.fields]<EOL>self._message = self.connection.read_message()<EOL>return True<EOL><DEDENT>elif isinstance(self._message, messages.BindComplete):<EOL><INDENT>self._message = self.connection.read_message()<EOL>return True<EOL><DEDENT>elif isinstance(self._message, messages.ReadyForQuery):<EOL><INDENT>return False<EOL><DEDENT>elif isinstance(self._message, END_OF_RESULT_RESPONSES):<EOL><INDENT>return True<EOL><DEDENT>elif isinstance(self._message, messages.ErrorResponse):<EOL><INDENT>raise errors.QueryError.from_error_response(self._message, self.operation)<EOL><DEDENT>else:<EOL><INDENT>raise errors.MessageError(<EOL>'<STR_LIT>'.format(self._message))<EOL><DEDENT><DEDENT>elif isinstance(self._message, messages.ReadyForQuery):<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>raise errors.MessageError('<STR_LIT>'.format(self._message))<EOL><DEDENT>
Skip to the next available result set, discarding any remaining rows from the current result set. If there are no more result sets, this method returns False. Otherwise, it returns a True and subsequent calls to the fetch*() methods will return rows from the next result set.
f7831:c0:m12
def copy(self, sql, data, **kwargs):
sql = as_text(sql)<EOL>if self.closed():<EOL><INDENT>raise errors.InterfaceError('<STR_LIT>')<EOL><DEDENT>self.flush_to_query_ready()<EOL>if isinstance(data, binary_type):<EOL><INDENT>stream = BytesIO(data)<EOL><DEDENT>elif isinstance(data, text_type):<EOL><INDENT>stream = StringIO(data)<EOL><DEDENT>elif isinstance(data, file_type):<EOL><INDENT>stream = data<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>".format(type(data)))<EOL><DEDENT>self.connection.write(messages.Query(sql))<EOL>while True:<EOL><INDENT>message = self.connection.read_message()<EOL>self._message = message<EOL>if isinstance(message, messages.ErrorResponse):<EOL><INDENT>raise errors.QueryError.from_error_response(message, sql)<EOL><DEDENT>self.connection.process_message(message=message)<EOL>if isinstance(message, messages.ReadyForQuery):<EOL><INDENT>break<EOL><DEDENT>elif isinstance(message, messages.CopyInResponse):<EOL><INDENT>self.connection.write(messages.CopyStream(stream, **kwargs))<EOL>self.connection.write(messages.CopyDone())<EOL><DEDENT><DEDENT>if self.error is not None:<EOL><INDENT>raise self.error<EOL><DEDENT>
EXAMPLE: >> with open("/tmp/file.csv", "rb") as fs: >> cursor.copy("COPY table(field1,field2) FROM STDIN DELIMITER ',' ENCLOSED BY ''''", >> fs, buffer_size=65536)
f7831:c0:m17
def _execute_simple_query(self, query):
self._logger.info(u'<STR_LIT>'.format(query))<EOL>self.connection.write(messages.Query(query))<EOL>self._message = self.connection.read_message()<EOL>if isinstance(self._message, messages.ErrorResponse):<EOL><INDENT>raise errors.QueryError.from_error_response(self._message, query)<EOL><DEDENT>elif isinstance(self._message, messages.RowDescription):<EOL><INDENT>self.description = [Column(fd, self.unicode_error) for fd in self._message.fields]<EOL>self._message = self.connection.read_message()<EOL>if isinstance(self._message, messages.ErrorResponse):<EOL><INDENT>raise errors.QueryError.from_error_response(self._message, query)<EOL><DEDENT><DEDENT>
Send the query to the server using the simple query protocol. Return True if this query contained no SQL (e.g. the string "--comment")
f7831:c0:m24
def _prepare(self, query):
self._logger.info(u'<STR_LIT>'.format(query))<EOL>self.connection.write(messages.Parse(self.prepared_name, query, param_types=()))<EOL>self.connection.write(messages.Describe('<STR_LIT>', self.prepared_name))<EOL>self.connection.write(messages.Flush())<EOL>self._message = self.connection.read_expected_message(messages.ParseComplete, self._error_handler)<EOL>self._message = self.connection.read_expected_message(messages.ParameterDescription, self._error_handler)<EOL>self._param_metadata = self._message.parameters<EOL>self._message = self.connection.read_expected_message(<EOL>(messages.RowDescription, messages.NoData), self._error_handler)<EOL>if isinstance(self._message, messages.NoData):<EOL><INDENT>self.description = None <EOL><DEDENT>else:<EOL><INDENT>self.description = [Column(fd, self.unicode_error) for fd in self._message.fields]<EOL><DEDENT>self._message = self.connection.read_expected_message(messages.CommandDescription, self._error_handler)<EOL>if len(self._message.command_tag) == <NUM_LIT:0>:<EOL><INDENT>msg = '<STR_LIT>'<EOL>self._logger.error(msg)<EOL>self.connection.write(messages.Sync())<EOL>raise errors.EmptyQueryError(msg)<EOL><DEDENT>self._logger.info('<STR_LIT>')<EOL>
Send the query to be prepared to the server. The server will parse the query and return some metadata.
f7831:c0:m26
def _execute_prepared_statement(self, list_of_parameter_values):
portal_name = "<STR_LIT>"<EOL>parameter_type_oids = [metadata['<STR_LIT>'] for metadata in self._param_metadata]<EOL>parameter_count = len(self._param_metadata)<EOL>try:<EOL><INDENT>if len(list_of_parameter_values) == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>for parameter_values in list_of_parameter_values:<EOL><INDENT>if parameter_values is None:<EOL><INDENT>parameter_values = ()<EOL><DEDENT>self._logger.info(u'<STR_LIT>'.format(parameter_values))<EOL>if len(parameter_values) != parameter_count:<EOL><INDENT>msg = ("<STR_LIT>"<EOL>.format(parameter_values, len(parameter_values), parameter_count))<EOL>raise ValueError(msg)<EOL><DEDENT>self.connection.write(messages.Bind(portal_name, self.prepared_name,<EOL>parameter_values, parameter_type_oids))<EOL>self.connection.write(messages.Execute(portal_name, <NUM_LIT:0>))<EOL><DEDENT>self.connection.write(messages.Sync())<EOL><DEDENT>except Exception as e:<EOL><INDENT>self._logger.error(str(e))<EOL>self.connection.write(messages.Sync())<EOL>self._message = self.connection.read_message()<EOL>raise<EOL><DEDENT>self.connection.write(messages.Flush())<EOL>self.connection.read_expected_message(messages.BindComplete)<EOL>self._message = self.connection.read_message()<EOL>if isinstance(self._message, messages.ErrorResponse):<EOL><INDENT>raise errors.QueryError.from_error_response(self._message, self.prepared_sql)<EOL><DEDENT>
Send multiple statement parameter sets to the server using the extended query protocol. The server would bind and execute each set of parameter values. This function should not be called without first calling _prepare() to prepare a statement.
f7831:c0:m27
def _close_prepared_statement(self):
self.prepared_sql = None<EOL>self.flush_to_query_ready()<EOL>self.connection.write(messages.Close('<STR_LIT>', self.prepared_name))<EOL>self.connection.write(messages.Flush())<EOL>self._message = self.connection.read_expected_message(messages.CloseComplete)<EOL>self.connection.write(messages.Sync())<EOL>
Close the prepared statement on the server.
f7831:c0:m28
def fetch_message(self):
raise NotImplementedError("<STR_LIT>")<EOL>
Generator for getting the message's content
f7854:c2:m0
def __setkey(key):
global C, D, KS, E<EOL>shifts = (<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT:1>)<EOL>for i in range(<NUM_LIT>):<EOL><INDENT>C[i] = key[PC1_C[i] - <NUM_LIT:1>]<EOL>D[i] = key[PC1_D[i] - <NUM_LIT:1>]<EOL><DEDENT>for i in range(<NUM_LIT:16>):<EOL><INDENT>for k in range(shifts[i]):<EOL><INDENT>temp = C[<NUM_LIT:0>]<EOL>for j in range(<NUM_LIT>):<EOL><INDENT>C[j] = C[j + <NUM_LIT:1>]<EOL><DEDENT>C[<NUM_LIT>] = temp<EOL>temp = D[<NUM_LIT:0>]<EOL>for j in range(<NUM_LIT>):<EOL><INDENT>D[j] = D[j + <NUM_LIT:1>]<EOL><DEDENT>D[<NUM_LIT>] = temp<EOL><DEDENT>for j in range(<NUM_LIT>):<EOL><INDENT>KS[i][j] = C[PC2_C[j] - <NUM_LIT:1>]<EOL>KS[i][j + <NUM_LIT>] = D[PC2_D[j] - <NUM_LIT> - <NUM_LIT:1>]<EOL><DEDENT><DEDENT>for i in range(<NUM_LIT>):<EOL><INDENT>E[i] = e2[i]<EOL><DEDENT>
Set up the key schedule from the encryption key.
f7870:m0
@fixture<EOL>def environ():
current_environ = os.environ.copy()<EOL>yield os.environ<EOL>os.environ = current_environ<EOL>
Enforce restoration of current shell environment after modifications. Yields the ``os.environ`` dict after snapshotting it; restores the original value (wholesale) during fixture teardown.
f7879:m0
def transform_name(self, name):
<EOL>name = re.sub(TEST_PREFIX, "<STR_LIT>", name)<EOL>name = re.sub(TEST_SUFFIX, "<STR_LIT>", name)<EOL>name = name.replace("<STR_LIT:_>", "<STR_LIT:U+0020>")<EOL>return name<EOL>
Take a test class/module/function name and make it human-presentable.
f7880:c0:m5
def trap(func):
@wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>sys.stdall = CarbonCopy()<EOL>my_stdout, sys.stdout = sys.stdout, CarbonCopy(cc=sys.stdall)<EOL>my_stderr, sys.stderr = sys.stderr, CarbonCopy(cc=sys.stdall)<EOL>try:<EOL><INDENT>return func(*args, **kwargs)<EOL><DEDENT>finally:<EOL><INDENT>sys.stdout = my_stdout<EOL>sys.stderr = my_stderr<EOL>del sys.stdall<EOL><DEDENT><DEDENT>return wrapper<EOL>
Replace sys.std(out|err) with a wrapper during execution, restored after. In addition, a new combined-streams output (another wrapper) will appear at ``sys.stdall``. This stream will resemble what a user sees at a terminal, i.e. both out/err streams intermingled.
f7882:m0
def __init__(self, buffer=b"<STR_LIT>", cc=None):
IO.__init__(self, buffer)<EOL>if cc is None:<EOL><INDENT>cc = []<EOL><DEDENT>elif hasattr(cc, "<STR_LIT>"):<EOL><INDENT>cc = [cc]<EOL><DEDENT>self.cc = cc<EOL>
If ``cc`` is given and is a file-like object or an iterable of same, it/they will be written to whenever this instance is written to.
f7882:c0:m0
@task<EOL>def coverage(c, html=True):
<EOL>c.run("<STR_LIT>")<EOL>if html:<EOL><INDENT>c.run("<STR_LIT>")<EOL>c.run("<STR_LIT>")<EOL><DEDENT>
Run coverage with coverage.py.
f7887:m0
def data_source_from_info(info):
if info.db:<EOL><INDENT>return "<STR_LIT>" % info.db<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>" % info.logdir<EOL><DEDENT>
Format the data location for the given TensorBoardInfo. Args: info: A TensorBoardInfo value. Returns: A human-readable string describing the logdir or database connection used by the server: e.g., "logdir /tmp/logs".
f7891:m0
def _info_to_string(info):
for key in _TENSORBOARD_INFO_FIELDS:<EOL><INDENT>field_type = _TENSORBOARD_INFO_FIELDS[key]<EOL>if not isinstance(getattr(info, key), field_type.runtime_type):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" %<EOL>(key, field_type.runtime_type, getattr(info, key))<EOL>)<EOL><DEDENT><DEDENT>if info.version != version.VERSION:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" %<EOL>(version.VERSION, info.version)<EOL>)<EOL><DEDENT>json_value = {<EOL>k: _TENSORBOARD_INFO_FIELDS[k].serialize(getattr(info, k))<EOL>for k in _TENSORBOARD_INFO_FIELDS<EOL>}<EOL>return json.dumps(json_value, sort_keys=True, indent=<NUM_LIT:4>)<EOL>
Convert a `TensorBoardInfo` to string form to be stored on disk. The format returned by this function is opaque and should only be interpreted by `_info_from_string`. Args: info: A valid `TensorBoardInfo` object. Raises: ValueError: If any field on `info` is not of the correct type. Returns: A string representation of the provided `TensorBoardInfo`.
f7891:m1
def _info_from_string(info_string):
try:<EOL><INDENT>json_value = json.loads(info_string)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValueError("<STR_LIT>" % (info_string,))<EOL><DEDENT>if not isinstance(json_value, dict):<EOL><INDENT>raise ValueError("<STR_LIT>" % (json_value,))<EOL><DEDENT>if json_value.get("<STR_LIT:version>") != version.VERSION:<EOL><INDENT>raise ValueError("<STR_LIT>" % (json_value,))<EOL><DEDENT>expected_keys = frozenset(_TENSORBOARD_INFO_FIELDS)<EOL>actual_keys = frozenset(json_value)<EOL>if expected_keys != actual_keys:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>% (expected_keys - actual_keys, actual_keys - expected_keys)<EOL>)<EOL><DEDENT>for key in _TENSORBOARD_INFO_FIELDS:<EOL><INDENT>field_type = _TENSORBOARD_INFO_FIELDS[key]<EOL>if not isinstance(json_value[key], field_type.serialized_type):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" %<EOL>(key, field_type.serialized_type, json_value[key])<EOL>)<EOL><DEDENT>json_value[key] = field_type.deserialize(json_value[key])<EOL><DEDENT>return TensorBoardInfo(**json_value)<EOL>
Parse a `TensorBoardInfo` object from its string representation. Args: info_string: A string representation of a `TensorBoardInfo`, as produced by a previous call to `_info_to_string`. Returns: A `TensorBoardInfo` value. Raises: ValueError: If the provided string is not valid JSON, or if it does not represent a JSON object with a "version" field whose value is `tensorboard.version.VERSION`, or if it has the wrong set of fields, or if at least one field is of invalid type.
f7891:m2
def cache_key(working_directory, arguments, configure_kwargs):
if not isinstance(arguments, (list, tuple)):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% (arguments,)<EOL>)<EOL><DEDENT>datum = {<EOL>"<STR_LIT>": working_directory,<EOL>"<STR_LIT>": arguments,<EOL>"<STR_LIT>": configure_kwargs,<EOL>}<EOL>raw = base64.b64encode(<EOL>json.dumps(datum, sort_keys=True, separators=("<STR_LIT:U+002C>", "<STR_LIT::>")).encode("<STR_LIT:utf-8>")<EOL>)<EOL>return str(raw.decode("<STR_LIT:ascii>"))<EOL>
Compute a `TensorBoardInfo.cache_key` field. The format returned by this function is opaque. Clients may only inspect it by comparing it for equality with other results from this function. Args: working_directory: The directory from which TensorBoard was launched and relative to which paths like `--logdir` and `--db` are resolved. arguments: The command-line args to TensorBoard, as `sys.argv[1:]`. Should be a list (or tuple), not an unparsed string. If you have a raw shell command, use `shlex.split` before passing it to this function. configure_kwargs: A dictionary of additional argument values to override the textual `arguments`, with the same semantics as in `tensorboard.program.TensorBoard.configure`. May be an empty dictionary. Returns: A string such that if two (prospective or actual) TensorBoard invocations have the same cache key then it is safe to use one in place of the other. The converse is not guaranteed: it is often safe to change the order of TensorBoard arguments, or to explicitly set them to their default values, or to move them between `arguments` and `configure_kwargs`, but such invocations may yield distinct cache keys.
f7891:m3
def _get_info_dir():
path = os.path.join(tempfile.gettempdir(), "<STR_LIT>")<EOL>try:<EOL><INDENT>os.makedirs(path)<EOL><DEDENT>except OSError as e:<EOL><INDENT>if e.errno == errno.EEXIST and os.path.isdir(path):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>else:<EOL><INDENT>os.chmod(path, <NUM_LIT>)<EOL><DEDENT>return path<EOL>
Get path to directory in which to store info files. The directory returned by this function is "owned" by this module. If the contents of the directory are modified other than via the public functions of this module, subsequent behavior is undefined. The directory will be created if it does not exist.
f7891:m4
def _get_info_file_path():
return os.path.join(_get_info_dir(), "<STR_LIT>" % os.getpid())<EOL>
Get path to info file for the current process. As with `_get_info_dir`, the info directory will be created if it does not exist.
f7891:m5
def write_info_file(tensorboard_info):
payload = "<STR_LIT>" % _info_to_string(tensorboard_info)<EOL>with open(_get_info_file_path(), "<STR_LIT:w>") as outfile:<EOL><INDENT>outfile.write(payload)<EOL><DEDENT>
Write TensorBoardInfo to the current process's info file. This should be called by `main` once the server is ready. When the server shuts down, `remove_info_file` should be called. Args: tensorboard_info: A valid `TensorBoardInfo` object. Raises: ValueError: If any field on `info` is not of the correct type.
f7891:m6
def remove_info_file():
try:<EOL><INDENT>os.unlink(_get_info_file_path())<EOL><DEDENT>except OSError as e:<EOL><INDENT>if e.errno == errno.ENOENT:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>
Remove the current process's TensorBoardInfo file, if it exists. If the file does not exist, no action is taken and no error is raised.
f7891:m7
def get_all():
info_dir = _get_info_dir()<EOL>results = []<EOL>for filename in os.listdir(info_dir):<EOL><INDENT>filepath = os.path.join(info_dir, filename)<EOL>try:<EOL><INDENT>with open(filepath) as infile:<EOL><INDENT>contents = infile.read()<EOL><DEDENT><DEDENT>except IOError as e:<EOL><INDENT>if e.errno == errno.EACCES:<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>try:<EOL><INDENT>info = _info_from_string(contents)<EOL><DEDENT>except ValueError:<EOL><INDENT>tb_logging.get_logger().warning(<EOL>"<STR_LIT>",<EOL>filepath,<EOL>exc_info=True,<EOL>)<EOL><DEDENT>else:<EOL><INDENT>results.append(info)<EOL><DEDENT><DEDENT>return results<EOL>
Return TensorBoardInfo values for running TensorBoard processes. This function may not provide a perfect snapshot of the set of running processes. Its result set may be incomplete if the user has cleaned their /tmp/ directory while TensorBoard processes are running. It may contain extraneous entries if TensorBoard processes exited uncleanly (e.g., with SIGKILL or SIGQUIT). Returns: A fresh list of `TensorBoardInfo` objects.
f7891:m8
def start(arguments, timeout=datetime.timedelta(seconds=<NUM_LIT>)):
match = _find_matching_instance(<EOL>cache_key(<EOL>working_directory=os.getcwd(),<EOL>arguments=arguments,<EOL>configure_kwargs={},<EOL>),<EOL>)<EOL>if match:<EOL><INDENT>return StartReused(info=match)<EOL><DEDENT>(stdout_fd, stdout_path) = tempfile.mkstemp(prefix="<STR_LIT>")<EOL>(stderr_fd, stderr_path) = tempfile.mkstemp(prefix="<STR_LIT>")<EOL>start_time_seconds = time.time()<EOL>try:<EOL><INDENT>p = subprocess.Popen(<EOL>["<STR_LIT>"] + arguments,<EOL>stdout=stdout_fd,<EOL>stderr=stderr_fd,<EOL>)<EOL><DEDENT>finally:<EOL><INDENT>os.close(stdout_fd)<EOL>os.close(stderr_fd)<EOL><DEDENT>poll_interval_seconds = <NUM_LIT:0.5><EOL>end_time_seconds = start_time_seconds + timeout.total_seconds()<EOL>while time.time() < end_time_seconds:<EOL><INDENT>time.sleep(poll_interval_seconds)<EOL>subprocess_result = p.poll()<EOL>if subprocess_result is not None:<EOL><INDENT>return StartFailed(<EOL>exit_code=subprocess_result,<EOL>stdout=_maybe_read_file(stdout_path),<EOL>stderr=_maybe_read_file(stderr_path),<EOL>)<EOL><DEDENT>for info in get_all():<EOL><INDENT>if info.pid == p.pid and info.start_time >= start_time_seconds:<EOL><INDENT>return StartLaunched(info=info)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>return StartTimedOut(pid=p.pid)<EOL><DEDENT>
Start a new TensorBoard instance, or reuse a compatible one. If the cache key determined by the provided arguments and the current working directory (see `cache_key`) matches the cache key of a running TensorBoard process (see `get_all`), that process will be reused. Otherwise, a new TensorBoard process will be spawned with the provided arguments, using the `tensorboard` binary from the system path. Args: arguments: List of strings to be passed as arguments to `tensorboard`. (If you have a raw command-line string, see `shlex.split`.) timeout: `datetime.timedelta` object describing how long to wait for the subprocess to initialize a TensorBoard server and write its `TensorBoardInfo` file. If the info file is not written within this time period, `start` will assume that the subprocess is stuck in a bad state, and will give up on waiting for it and return a `StartTimedOut` result. Note that in such a case the subprocess will not be killed. Default value is 60 seconds. Returns: A `StartReused`, `StartLaunched`, `StartFailed`, or `StartTimedOut` object.
f7891:m9
def _find_matching_instance(cache_key):
infos = get_all()<EOL>candidates = [info for info in infos if info.cache_key == cache_key]<EOL>for candidate in sorted(candidates, key=lambda x: x.port):<EOL><INDENT>return candidate<EOL><DEDENT>return None<EOL>
Find a running TensorBoard instance compatible with the cache key. Returns: A `TensorBoardInfo` object, or `None` if none matches the cache key.
f7891:m10
def _maybe_read_file(filename):
try:<EOL><INDENT>with open(filename) as infile:<EOL><INDENT>return infile.read()<EOL><DEDENT><DEDENT>except IOError as e:<EOL><INDENT>if e.errno == errno.ENOENT:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>
Read the given file, if it exists. Args: filename: A path to a file. Returns: A string containing the file contents, or `None` if the file does not exist.
f7891:m11
def setup_environment():
absl.logging.set_verbosity(absl.logging.WARNING)<EOL>serving.WSGIRequestHandler.protocol_version = '<STR_LIT>'<EOL>
Makes recommended modifications to the environment. This functions changes global state in the Python process. Calling this function is a good idea, but it can't appropriately be called from library routines.
f7897:m0
def get_default_assets_zip_provider():
path = os.path.join(os.path.dirname(inspect.getfile(sys._getframe(<NUM_LIT:1>))),<EOL>'<STR_LIT>')<EOL>if not os.path.exists(path):<EOL><INDENT>logger.warning('<STR_LIT>', path)<EOL>return None<EOL><DEDENT>return lambda: open(path, '<STR_LIT:rb>')<EOL>
Opens stock TensorBoard web assets collection. Returns: Returns function that returns a newly opened file handle to zip file containing static assets for stock TensorBoard, or None if webfiles.zip could not be found. The value the callback returns must be closed. The paths inside the zip file are considered absolute paths on the web server.
f7897:m1
def with_port_scanning(cls):
def init(wsgi_app, flags):<EOL><INDENT>should_scan = flags.port is None<EOL>base_port = core_plugin.DEFAULT_PORT if flags.port is None else flags.port<EOL>max_attempts = <NUM_LIT:10> if should_scan else <NUM_LIT:1><EOL>if base_port > <NUM_LIT>:<EOL><INDENT>raise TensorBoardServerException(<EOL>'<STR_LIT>' % (base_port, <NUM_LIT>)<EOL>)<EOL><DEDENT>max_attempts = <NUM_LIT:10> if should_scan else <NUM_LIT:1><EOL>base_port = min(base_port + max_attempts, <NUM_LIT>) - max_attempts<EOL>for port in xrange(base_port, base_port + max_attempts):<EOL><INDENT>subflags = argparse.Namespace(**vars(flags))<EOL>subflags.port = port<EOL>try:<EOL><INDENT>return cls(wsgi_app=wsgi_app, flags=subflags)<EOL><DEDENT>except TensorBoardPortInUseError:<EOL><INDENT>if not should_scan:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT>raise TensorBoardServerException(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>% (base_port, max_attempts))<EOL><DEDENT>return init<EOL>
Create a server factory that performs port scanning. This function returns a callable whose signature matches the specification of `TensorBoardServer.__init__`, using `cls` as an underlying implementation. It passes through `flags` unchanged except in the case that `flags.port is None`, in which case it repeatedly instantiates the underlying server with new port suggestions. Args: cls: A valid implementation of `TensorBoardServer`. This class's initializer should raise a `TensorBoardPortInUseError` upon failing to bind to a port when it is expected that binding to another nearby port might succeed. The initializer for `cls` will only ever be invoked with `flags` such that `flags.port is not None`. Returns: A function that implements the `__init__` contract of `TensorBoardServer`.
f7897:m2
def __init__(self,<EOL>plugins=None,<EOL>assets_zip_provider=None,<EOL>server_class=None):
if plugins is None:<EOL><INDENT>from tensorboard import default<EOL>plugins = default.get_plugins()<EOL><DEDENT>if assets_zip_provider is None:<EOL><INDENT>assets_zip_provider = get_default_assets_zip_provider()<EOL><DEDENT>if server_class is None:<EOL><INDENT>server_class = create_port_scanning_werkzeug_server<EOL><DEDENT>def make_loader(plugin):<EOL><INDENT>if isinstance(plugin, base_plugin.TBLoader):<EOL><INDENT>return plugin<EOL><DEDENT>if issubclass(plugin, base_plugin.TBPlugin):<EOL><INDENT>return base_plugin.BasicLoader(plugin)<EOL><DEDENT>raise ValueError("<STR_LIT>" % plugin)<EOL><DEDENT>self.plugin_loaders = [make_loader(p) for p in plugins]<EOL>self.assets_zip_provider = assets_zip_provider<EOL>self.server_class = server_class<EOL>self.flags = None<EOL>
Creates new instance. Args: plugins: A list of TensorBoard plugins to load, as TBLoader instances or TBPlugin classes. If not specified, defaults to first-party plugins. assets_zip_provider: Delegates to TBContext or uses default if None. server_class: An optional factory for a `TensorBoardServer` to use for serving the TensorBoard WSGI app. If provided, its callable signature should match that of `TensorBoardServer.__init__`. :type plugins: list[Union[base_plugin.TBLoader, Type[base_plugin.TBPlugin]]] :type assets_zip_provider: () -> file :type server_class: class
f7897:c0:m0
def configure(self, argv=('<STR_LIT>',), **kwargs):
parser = argparse_flags.ArgumentParser(<EOL>prog='<STR_LIT>',<EOL>description=('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'))<EOL>for loader in self.plugin_loaders:<EOL><INDENT>loader.define_flags(parser)<EOL><DEDENT>arg0 = argv[<NUM_LIT:0>] if argv else '<STR_LIT>'<EOL>flags = parser.parse_args(argv[<NUM_LIT:1>:]) <EOL>self.cache_key = manager.cache_key(<EOL>working_directory=os.getcwd(),<EOL>arguments=argv[<NUM_LIT:1>:],<EOL>configure_kwargs=kwargs,<EOL>)<EOL>if absl_flags and arg0:<EOL><INDENT>for flag in set(absl_flags.FLAGS.get_key_flags_for_module(arg0)):<EOL><INDENT>if hasattr(flags, flag.name):<EOL><INDENT>raise ValueError('<STR_LIT>' % flag.name)<EOL><DEDENT>setattr(flags, flag.name, flag.value)<EOL><DEDENT><DEDENT>for k, v in kwargs.items():<EOL><INDENT>if not hasattr(flags, k):<EOL><INDENT>raise ValueError('<STR_LIT>' % k)<EOL><DEDENT>setattr(flags, k, v)<EOL><DEDENT>for loader in self.plugin_loaders:<EOL><INDENT>loader.fix_flags(flags)<EOL><DEDENT>self.flags = flags<EOL>return [arg0]<EOL>
Configures TensorBoard behavior via flags. This method will populate the "flags" property with an argparse.Namespace representing flag values parsed from the provided argv list, overridden by explicit flags from remaining keyword arguments. Args: argv: Can be set to CLI args equivalent to sys.argv; the first arg is taken to be the name of the path being executed. kwargs: Additional arguments will override what was parsed from argv. They must be passed as Python data structures, e.g. `foo=1` rather than `foo="1"`. Returns: Either argv[:1] if argv was non-empty, or [''] otherwise, as a mechanism for absl.app.run() compatibility. Raises: ValueError: If flag values are invalid.
f7897:c0:m1
def main(self, ignored_argv=('<STR_LIT>',)):
self._install_signal_handler(signal.SIGTERM, "<STR_LIT>")<EOL>if self.flags.inspect:<EOL><INDENT>logger.info('<STR_LIT>')<EOL>event_file = os.path.expanduser(self.flags.event_file)<EOL>efi.inspect(self.flags.logdir, event_file, self.flags.tag)<EOL>return <NUM_LIT:0><EOL><DEDENT>if self.flags.version_tb:<EOL><INDENT>print(version.VERSION)<EOL>return <NUM_LIT:0><EOL><DEDENT>try:<EOL><INDENT>server = self._make_server()<EOL>sys.stderr.write('<STR_LIT>' %<EOL>(version.VERSION, server.get_url()))<EOL>sys.stderr.flush()<EOL>self._register_info(server)<EOL>server.serve_forever()<EOL>return <NUM_LIT:0><EOL><DEDENT>except TensorBoardServerException as e:<EOL><INDENT>logger.error(e.msg)<EOL>sys.stderr.write('<STR_LIT>' % e.msg)<EOL>sys.stderr.flush()<EOL>return -<NUM_LIT:1><EOL><DEDENT>
Blocking main function for TensorBoard. This method is called by `tensorboard.main.run_main`, which is the standard entrypoint for the tensorboard command line program. The configure() method must be called first. Args: ignored_argv: Do not pass. Required for Abseil compatibility. Returns: Process exit code, i.e. 0 if successful or non-zero on failure. In practice, an exception will most likely be raised instead of returning non-zero. :rtype: int
f7897:c0:m2
def launch(self):
<EOL>server = self._make_server()<EOL>thread = threading.Thread(target=server.serve_forever, name='<STR_LIT>')<EOL>thread.daemon = True<EOL>thread.start()<EOL>return server.get_url()<EOL>
Python API for launching TensorBoard. This method is the same as main() except it launches TensorBoard in a separate permanent thread. The configure() method must be called first. Returns: The URL of the TensorBoard web server. :rtype: str
f7897:c0:m3
def _register_info(self, server):
server_url = urllib.parse.urlparse(server.get_url())<EOL>info = manager.TensorBoardInfo(<EOL>version=version.VERSION,<EOL>start_time=int(time.time()),<EOL>port=server_url.port,<EOL>pid=os.getpid(),<EOL>path_prefix=self.flags.path_prefix,<EOL>logdir=self.flags.logdir,<EOL>db=self.flags.db,<EOL>cache_key=self.cache_key,<EOL>)<EOL>atexit.register(manager.remove_info_file)<EOL>manager.write_info_file(info)<EOL>
Write a TensorBoardInfo file and arrange for its cleanup. Args: server: The result of `self._make_server()`.
f7897:c0:m4
def _install_signal_handler(self, signal_number, signal_name):
old_signal_handler = None <EOL>def handler(handled_signal_number, frame):<EOL><INDENT>signal.signal(signal_number, signal.SIG_DFL)<EOL>sys.stderr.write("<STR_LIT>" % signal_name)<EOL>if old_signal_handler not in (signal.SIG_IGN, signal.SIG_DFL):<EOL><INDENT>old_signal_handler(handled_signal_number, frame)<EOL><DEDENT>sys.exit(<NUM_LIT:0>)<EOL><DEDENT>old_signal_handler = signal.signal(signal_number, handler)<EOL>
Set a signal handler to gracefully exit on the given signal. When this process receives the given signal, it will run `atexit` handlers and then exit with `0`. Args: signal_number: The numeric code for the signal to handle, like `signal.SIGTERM`. signal_name: The human-readable signal name.
f7897:c0:m5
def _make_server(self):
app = application.standard_tensorboard_wsgi(self.flags,<EOL>self.plugin_loaders,<EOL>self.assets_zip_provider)<EOL>return self.server_class(app, self.flags)<EOL>
Constructs the TensorBoard WSGI app and instantiates the server.
f7897:c0:m6
@abstractmethod<EOL><INDENT>def __init__(self, wsgi_app, flags):<DEDENT>
raise NotImplementedError()<EOL>
Create a flag-configured HTTP server for TensorBoard's WSGI app. Args: wsgi_app: The TensorBoard WSGI application to create a server for. flags: argparse.Namespace instance of TensorBoard flags.
f7897:c1:m0
@abstractmethod<EOL><INDENT>def serve_forever(self):<DEDENT>
raise NotImplementedError()<EOL>
Blocking call to start serving the TensorBoard server.
f7897:c1:m1
@abstractmethod<EOL><INDENT>def get_url(self):<DEDENT>
raise NotImplementedError()<EOL>
Returns a URL at which this server should be reachable.
f7897:c1:m2
def _get_wildcard_address(self, port):
fallback_address = '<STR_LIT>' if socket.has_ipv6 else '<STR_LIT>'<EOL>if hasattr(socket, '<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>addrinfos = socket.getaddrinfo(None, port, socket.AF_UNSPEC,<EOL>socket.SOCK_STREAM, socket.IPPROTO_TCP,<EOL>socket.AI_PASSIVE)<EOL><DEDENT>except socket.gaierror as e:<EOL><INDENT>logger.warn('<STR_LIT>',<EOL>fallback_address, str(e))<EOL>return fallback_address<EOL><DEDENT>addrs_by_family = defaultdict(list)<EOL>for family, _, _, _, sockaddr in addrinfos:<EOL><INDENT>addrs_by_family[family].append(sockaddr[<NUM_LIT:0>])<EOL><DEDENT>if hasattr(socket, '<STR_LIT>') and addrs_by_family[socket.AF_INET6]:<EOL><INDENT>return addrs_by_family[socket.AF_INET6][<NUM_LIT:0>]<EOL><DEDENT>if hasattr(socket, '<STR_LIT>') and addrs_by_family[socket.AF_INET]:<EOL><INDENT>return addrs_by_family[socket.AF_INET][<NUM_LIT:0>]<EOL><DEDENT><DEDENT>logger.warn('<STR_LIT>',<EOL>fallback_address)<EOL>return fallback_address<EOL>
Returns a wildcard address for the port in question. This will attempt to follow the best practice of calling getaddrinfo() with a null host and AI_PASSIVE to request a server-side socket wildcard address. If that succeeds, this returns the first IPv6 address found, or if none, then returns the first IPv4 address. If that fails, then this returns the hardcoded address "::" if socket.has_ipv6 is True, else "0.0.0.0".
f7897:c4:m1
def server_bind(self):
socket_is_v6 = (<EOL>hasattr(socket, '<STR_LIT>') and self.socket.family == socket.AF_INET6)<EOL>has_v6only_option = (<EOL>hasattr(socket, '<STR_LIT>') and hasattr(socket, '<STR_LIT>'))<EOL>if self._auto_wildcard and socket_is_v6 and has_v6only_option:<EOL><INDENT>try:<EOL><INDENT>self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, <NUM_LIT:0>)<EOL><DEDENT>except socket.error as e:<EOL><INDENT>if hasattr(errno, '<STR_LIT>') and e.errno != errno.EAFNOSUPPORT:<EOL><INDENT>logger.warn('<STR_LIT>', str(e))<EOL><DEDENT><DEDENT><DEDENT>super(WerkzeugServer, self).server_bind()<EOL>
Override to enable IPV4 mapping for IPV6 sockets when desired. The main use case for this is so that when no host is specified, TensorBoard can listen on all interfaces for both IPv4 and IPv6 connections, rather than having to choose v4 or v6 and hope the browser didn't choose the other one.
f7897:c4:m2