Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def redirect_stds(self):
if not self.debug:
sys.stdout = self.stdout_write
sys.stderr = self.stderr_write
sys.stdin = self.stdin_read | [
"Redirects stds"
] |
Please provide a description of the function:def restore_stds(self):
if not self.debug:
sys.stdout = self.initial_stdout
sys.stderr = self.initial_stderr
sys.stdin = self.initial_stdin | [
"Restore stds"
] |
Please provide a description of the function:def raw_input_replacement(self, prompt=''):
self.widget_proxy.wait_input(prompt)
self.input_condition.acquire()
while not self.widget_proxy.data_available():
self.input_condition.wait()
inp = self.widget_proxy.input_... | [
"For raw_input builtin function emulation"
] |
Please provide a description of the function:def help_replacement(self, text=None, interactive=False):
if text is not None and not interactive:
return pydoc.help(text)
elif text is None:
pyver = "%d.%d" % (sys.version_info[0], sys.version_info[1])
self.... | [
"For help builtin function emulation",
"\r\nWelcome to Python %s! This is the online help utility.\r\n\r\nIf this is your first time using Python, you should definitely check out\r\nthe tutorial on the Internet at https://www.python.org/about/gettingstarted/\r\n\r\nEnter the name of any module, keyword, or topic... |
Please provide a description of the function:def run_command(self, cmd, new_prompt=True):
if cmd == 'exit()':
self.exit_flag = True
self.write('\n')
return
# -- Special commands type I
# (transformed into commands executed in the interpreter... | [
"Run command in interpreter"
] |
Please provide a description of the function:def get_thread_id(self):
if self._id is None:
for thread_id, obj in list(threading._active.items()):
if obj is self:
self._id = thread_id
return self._id | [
"Return thread id"
] |
Please provide a description of the function:def execfile(self, filename):
source = open(filename, 'r').read()
try:
try:
name = filename.encode('ascii')
except UnicodeEncodeError:
name = '<executed_script>'
code = compi... | [
"Exec filename"
] |
Please provide a description of the function:def runfile(self, filename, args=None):
if args is not None and not is_text_string(args):
raise TypeError("expected a character buffer object")
self.namespace['__file__'] = filename
sys.argv = [filename]
if args is n... | [
"\r\n Run filename\r\n args: command line arguments (string)\r\n "
] |
Please provide a description of the function:def eval(self, text):
assert is_text_string(text)
try:
return eval(text, self.locals), True
except:
return None, False | [
"\r\n Evaluate text and return (obj, valid)\r\n where *obj* is the object represented by *text*\r\n and *valid* is True if object evaluation did not raise any exception\r\n "
] |
Please provide a description of the function:def is_defined(self, objtxt, force_import=False):
return isdefined(objtxt, force_import=force_import,
namespace=self.locals) | [
"Return True if object is defined"
] |
Please provide a description of the function:def text_changed(self):
# Save text as bytes, if it was initially bytes
if self.is_binary:
self.text = to_binary_string(self.edit.toPlainText(), 'utf8')
else:
self.text = to_text_string(self.edit.toPlainText())
... | [
"Text has changed"
] |
Please provide a description of the function:def logger_init(level):
levellist = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
handler = logging.StreamHandler()
fmt = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) '
'-35s %(lineno) -5d: %(message)s')
handler.set... | [
"\n Initialize the logger for this thread.\n\n Sets the log level to ERROR (0), WARNING (1), INFO (2), or DEBUG (3),\n depending on the argument `level`.\n "
] |
Please provide a description of the function:def restore(self):
signal.signal(signal.SIGINT, self.original_sigint)
signal.signal(signal.SIGTERM, self.original_sigterm)
if os.name == 'nt':
signal.signal(signal.SIGBREAK, self.original_sigbreak) | [
"Restore signal handlers to their original settings."
] |
Please provide a description of the function:def show_warning(message):
try:
# If Tkinter is installed (highly probable), showing an error pop-up
import Tkinter, tkMessageBox
root = Tkinter.Tk()
root.withdraw()
tkMessageBox.showerror("Spyder", message)
except... | [
"Show warning using Tkinter if available"
] |
Please provide a description of the function:def check_path():
dirname = osp.abspath(osp.join(osp.dirname(__file__), osp.pardir))
if dirname not in sys.path:
show_warning("Spyder must be installed properly "
"(e.g. from source: 'python setup.py install'),\n"
... | [
"Check sys.path: is Spyder properly installed?"
] |
Please provide a description of the function:def check_qt():
qt_infos = dict(pyqt5=("PyQt5", "5.6"))
try:
import qtpy
package_name, required_ver = qt_infos[qtpy.API]
actual_ver = qtpy.PYQT_VERSION
if LooseVersion(actual_ver) < LooseVersion(required_ver):
... | [
"Check Qt binding requirements"
] |
Please provide a description of the function:def check_spyder_kernels():
try:
import spyder_kernels
required_ver = '1.0.0'
actual_ver = spyder_kernels.__version__
if LooseVersion(actual_ver) < LooseVersion(required_ver):
show_warning("Please check Spyder insta... | [
"Check spyder-kernel requirement."
] |
Please provide a description of the function:def register_plugin(self):
self.breakpoints.edit_goto.connect(self.main.editor.load)
#self.redirect_stdio.connect(self.main.redirect_internalshell_stdio)
self.breakpoints.clear_all_breakpoints.connect(
... | [
"Register plugin in Spyder's main window"
] |
Please provide a description of the function:def isLocked(name):
l = FilesystemLock(name)
result = None
try:
result = l.lock()
finally:
if result:
l.unlock()
return not result | [
"Determine if the lock of the given name is held or not.\r\n\r\n @type name: C{str}\r\n @param name: The filesystem path to the lock to test\r\n\r\n @rtype: C{bool}\r\n @return: True if the lock is held, False otherwise.\r\n "
] |
Please provide a description of the function:def lock(self):
clean = True
while True:
try:
symlink(str(os.getpid()), self.name)
except OSError as e:
if _windows and e.errno in (errno.EACCES, errno.EIO):
# The lo... | [
"\r\n Acquire this lock.\r\n\r\n @rtype: C{bool}\r\n @return: True if the lock is acquired, false otherwise.\r\n\r\n @raise: Any exception os.symlink() may raise, other than\r\n EEXIST.\r\n "
] |
Please provide a description of the function:def unlock(self):
pid = readlink(self.name)
if int(pid) != os.getpid():
raise ValueError("Lock %r not owned by this process" % (self.name,))
rmlink(self.name)
self.locked = False | [
"\r\n Release this lock.\r\n\r\n This deletes the directory with the given name.\r\n\r\n @raise: Any exception os.readlink() may raise, or\r\n ValueError if the lock is not owned by this process.\r\n "
] |
Please provide a description of the function:def render(self, doc, context=None, math_option=False, img_path='',
css_path=CSS_PATH):
# If the thread is already running wait for it to finish before
# starting it again.
if self.wait():
self.doc = doc
... | [
"Start thread to render a given documentation"
] |
Please provide a description of the function:def sortByName(self):
self.servers = sorted(self.servers, key=lambda x: x.language)
self.reset() | [
"Qt Override."
] |
Please provide a description of the function:def data(self, index, role=Qt.DisplayRole):
row = index.row()
if not index.isValid() or not (0 <= row < len(self.servers)):
return to_qvariant()
server = self.servers[row]
column = index.column()
if role == Qt.Di... | [
"Qt Override."
] |
Please provide a description of the function:def headerData(self, section, orientation, role=Qt.DisplayRole):
if role == Qt.TextAlignmentRole:
if orientation == Qt.Horizontal:
return to_qvariant(int(Qt.AlignHCenter | Qt.AlignVCenter))
return to_qvariant(int(Qt.Al... | [
"Qt Override."
] |
Please provide a description of the function:def focusInEvent(self, e):
super(LSPServerTable, self).focusInEvent(e)
self.selectRow(self.currentIndex().row()) | [
"Qt Override."
] |
Please provide a description of the function:def selection(self, index):
self.update()
self.isActiveWindow()
self._parent.delete_btn.setEnabled(True) | [
"Update selected row."
] |
Please provide a description of the function:def adjust_cells(self):
self.resizeColumnsToContents()
fm = self.horizontalHeader().fontMetrics()
names = [fm.width(s.cmd) for s in self.source_model.servers]
if names:
self.setColumnWidth(CMD, max(names))
self.hor... | [
"Adjust column size based on contents."
] |
Please provide a description of the function:def next_row(self):
row = self.currentIndex().row()
rows = self.source_model.rowCount()
if row + 1 == rows:
row = -1
self.selectRow(row + 1) | [
"Move to next row from currently selected row."
] |
Please provide a description of the function:def previous_row(self):
row = self.currentIndex().row()
rows = self.source_model.rowCount()
if row == 0:
row = rows
self.selectRow(row - 1) | [
"Move to previous row from currently selected row."
] |
Please provide a description of the function:def keyPressEvent(self, event):
key = event.key()
if key in [Qt.Key_Enter, Qt.Key_Return]:
self.show_editor()
elif key in [Qt.Key_Backtab]:
self.parent().reset_btn.setFocus()
elif key in [Qt.Key_Up, Qt.Key_Down... | [
"Qt Override."
] |
Please provide a description of the function:def setup_docstring_style_convention(self, text):
if text == 'Custom':
self.docstring_style_select.label.setText(
_("Show the following errors:"))
self.docstring_style_ignore.label.setText(
_("Ignore th... | [
"Handle convention changes."
] |
Please provide a description of the function:def add_external_path(self, path):
if not osp.exists(path):
return
self.removeItem(self.findText(path))
self.addItem(path)
self.setItemData(self.count() - 1, path, Qt.ToolTipRole)
while self.count() > MAX_PA... | [
"\r\n Adds an external path to the combobox if it exists on the file system.\r\n If the path is already listed in the combobox, it is removed from its\r\n current position and added back at the end. If the maximum number of\r\n paths is reached, the oldest external path is removed from t... |
Please provide a description of the function:def get_external_paths(self):
return [to_text_string(self.itemText(i))
for i in range(EXTERNAL_PATHS, self.count())] | [
"Returns a list of the external paths listed in the combobox."
] |
Please provide a description of the function:def get_current_searchpath(self):
idx = self.currentIndex()
if idx == CWD:
return self.path
elif idx == PROJECT:
return self.project_path
elif idx == FILE_PATH:
return self.file_path
... | [
"\r\n Returns the path corresponding to the currently selected item\r\n in the combobox.\r\n "
] |
Please provide a description of the function:def path_selection_changed(self):
idx = self.currentIndex()
if idx == SELECT_OTHER:
external_path = self.select_directory()
if len(external_path) > 0:
self.add_external_path(external_path)
... | [
"Handles when the current index of the combobox changes."
] |
Please provide a description of the function:def select_directory(self):
self.__redirect_stdio_emit(False)
directory = getexistingdirectory(
self, _("Select directory"), self.path)
if directory:
directory = to_unicode_from_fs(osp.abspath(directory))
... | [
"Select directory"
] |
Please provide a description of the function:def set_project_path(self, path):
if path is None:
self.project_path = None
self.model().item(PROJECT, 0).setEnabled(False)
if self.currentIndex() == PROJECT:
self.setCurrentIndex(CWD)
else:
... | [
"\r\n Sets the project path and disables the project search in the combobox\r\n if the value of path is None.\r\n "
] |
Please provide a description of the function:def eventFilter(self, widget, event):
if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Delete:
index = self.view().currentIndex().row()
if index >= EXTERNAL_PATHS:
# Remove item and update the view.
... | [
"Used to handle key events on the QListView of the combobox."
] |
Please provide a description of the function:def __redirect_stdio_emit(self, value):
parent = self.parent()
while parent is not None:
try:
parent.redirect_stdio.emit(value)
except AttributeError:
parent = parent.parent()
... | [
"\r\n Searches through the parent tree to see if it is possible to emit the\r\n redirect_stdio signal.\r\n This logic allows to test the SearchInComboBox select_directory method\r\n outside of the FindInFiles plugin.\r\n "
] |
Please provide a description of the function:def get_options(self, to_save=False):
text_re = self.edit_regexp.isChecked()
exclude_re = self.exclude_regexp.isChecked()
case_sensitive = self.case_button.isChecked()
# Return current options for them to be saved when closing
... | [
"Get options"
] |
Please provide a description of the function:def keyPressEvent(self, event):
ctrl = event.modifiers() & Qt.ControlModifier
shift = event.modifiers() & Qt.ShiftModifier
if event.key() in (Qt.Key_Enter, Qt.Key_Return):
self.find.emit()
elif event.key() == Qt.Key_... | [
"Reimplemented to handle key events"
] |
Please provide a description of the function:def activated(self, item):
itemdata = self.data.get(id(self.currentItem()))
if itemdata is not None:
filename, lineno, colno = itemdata
self.sig_edit_goto.emit(filename, lineno, self.search_text) | [
"Double-click event"
] |
Please provide a description of the function:def set_sorting(self, flag):
self.sorting['status'] = flag
self.header().setSectionsClickable(flag == ON) | [
"Enable result sorting after search is complete."
] |
Please provide a description of the function:def append_result(self, results, num_matches):
filename, lineno, colno, match_end, line = results
if filename not in self.files:
file_item = FileMatchItem(self, filename, self.sorting,
self.tex... | [
"Real-time update of search results"
] |
Please provide a description of the function:def showEvent(self, event):
QWidget.showEvent(self, event)
self.spinner.start() | [
"Override show event to start waiting spinner."
] |
Please provide a description of the function:def hideEvent(self, event):
QWidget.hideEvent(self, event)
self.spinner.stop() | [
"Override hide event to stop waiting spinner."
] |
Please provide a description of the function:def find(self):
options = self.find_options.get_options()
if options is None:
return
self.stop_and_reset_thread(ignore_results=True)
self.search_thread = SearchThread(self)
self.search_thread.sig_finished.co... | [
"Call the find function"
] |
Please provide a description of the function:def stop_and_reset_thread(self, ignore_results=False):
if self.search_thread is not None:
if self.search_thread.isRunning():
if ignore_results:
self.search_thread.sig_finished.disconnect(
... | [
"Stop current search thread and clean-up"
] |
Please provide a description of the function:def search_complete(self, completed):
self.result_browser.set_sorting(ON)
self.find_options.ok_button.setEnabled(True)
self.find_options.stop_button.setEnabled(False)
self.status_bar.hide()
self.result_browser.expandAll(... | [
"Current search thread has finished"
] |
Please provide a description of the function:def _get_credentials_from_settings(self):
remember_me = CONF.get('main', 'report_error/remember_me')
remember_token = CONF.get('main', 'report_error/remember_token')
username = CONF.get('main', 'report_error/username', '')
if not reme... | [
"Get the stored credentials if any."
] |
Please provide a description of the function:def _store_credentials(self, username, password, remember=False):
if username and password and remember:
CONF.set('main', 'report_error/username', username)
try:
keyring.set_password('github', username, password)
... | [
"Store credentials for future use."
] |
Please provide a description of the function:def _store_token(self, token, remember=False):
if token and remember:
try:
keyring.set_password('github', 'token', token)
except Exception:
if self._show_msgbox:
QMessageBox.warning(... | [
"Store token for future use."
] |
Please provide a description of the function:def get_user_credentials(self):
password = None
token = None
(username, remember_me,
remember_token) = self._get_credentials_from_settings()
valid_py_os = not (PY2 and sys.platform.startswith('linux'))
if username and... | [
"Get user credentials with the login dialog."
] |
Please provide a description of the function:def show_tip(self, point, tip):
# Don't attempt to show it if it's already visible and the text
# to be displayed is the same as the one displayed before.
if self.isVisible():
if self.tip == tip:
return True
... | [
"\n Attempts to show the specified tip at the current cursor location.\n "
] |
Please provide a description of the function:def leaveEvent(self, event):
super(ToolTipWidget, self).leaveEvent(event)
self.hide() | [
"Override Qt method to hide the tooltip on leave."
] |
Please provide a description of the function:def eventFilter(self, obj, event):
if obj == self._text_edit:
etype = event.type()
if etype == QEvent.KeyPress:
key = event.key()
cursor = self._text_edit.textCursor()
prev_char = self.... | [
" Reimplemented to hide on certain key presses and on text edit focus\n changes.\n "
] |
Please provide a description of the function:def timerEvent(self, event):
if event.timerId() == self._hide_timer.timerId():
self._hide_timer.stop()
self.hide() | [
" Reimplemented to hide the widget when the hide timer fires.\n "
] |
Please provide a description of the function:def enterEvent(self, event):
super(CallTipWidget, self).enterEvent(event)
if self.as_tooltip:
self.hide()
if (self._hide_timer.isActive() and
self.app.topLevelAt(QCursor.pos()) == self):
self._hide_timer.sto... | [
" Reimplemented to cancel the hide timer.\n "
] |
Please provide a description of the function:def hideEvent(self, event):
super(CallTipWidget, self).hideEvent(event)
self._text_edit.cursorPositionChanged.disconnect(
self._cursor_position_changed)
self._text_edit.removeEventFilter(self) | [
" Reimplemented to disconnect signal handlers and event filter.\n "
] |
Please provide a description of the function:def leaveEvent(self, event):
super(CallTipWidget, self).leaveEvent(event)
self._leave_event_hide() | [
" Reimplemented to start the hide timer.\n "
] |
Please provide a description of the function:def showEvent(self, event):
super(CallTipWidget, self).showEvent(event)
self._text_edit.cursorPositionChanged.connect(
self._cursor_position_changed)
self._text_edit.installEventFilter(self) | [
" Reimplemented to connect signal handlers and event filter.\n "
] |
Please provide a description of the function:def show_tip(self, point, tip, wrapped_tiplines):
# Don't attempt to show it if it's already visible and the text
# to be displayed is the same as the one displayed before.
if self.isVisible():
if self.tip == tip:
... | [
" Attempts to show the specified tip at the current cursor location.\n "
] |
Please provide a description of the function:def _leave_event_hide(self):
if (self.hide_timer_on and not self._hide_timer.isActive() and
# If Enter events always came after Leave events, we wouldn't need
# this check. But on Mac OS, it sometimes happens the other way
... | [
" Hides the tooltip after some time has passed (assuming the cursor is\n not over the tooltip).\n "
] |
Please provide a description of the function:def _cursor_position_changed(self):
cursor = self._text_edit.textCursor()
position = cursor.position()
document = self._text_edit.document()
char = to_text_string(document.characterAt(position - 1))
if position <= self._start_... | [
" Updates the tip based on user cursor movement.\n "
] |
Please provide a description of the function:def has_mixed_eol_chars(text):
eol_chars = get_eol_chars(text)
if eol_chars is None:
return False
correct_text = eol_chars.join((text+eol_chars).splitlines())
return repr(correct_text) != repr(text) | [
"Detect if text has mixed EOL characters"
] |
Please provide a description of the function:def normalize_eols(text, eol='\n'):
for eol_char, _ in EOL_CHARS:
if eol_char != eol:
text = text.replace(eol_char, eol)
return text | [
"Use the same eol's in text"
] |
Please provide a description of the function:def is_builtin(text):
from spyder.py3compat import builtins
return text in [str(name) for name in dir(builtins)
if not name.startswith('_')] | [
"Test if passed string is the name of a Python builtin object"
] |
Please provide a description of the function:def get_primary_at(source_code, offset, retry=True):
obj = ''
left = re.split(r"[^0-9a-zA-Z_.]", source_code[:offset])
if left and left[-1]:
obj = left[-1]
right = re.split(r"\W", source_code[offset:])
if right and right[0]:
o... | [
"Return Python object in *source_code* at *offset*\r\n Periods to the left of the cursor are carried forward \r\n e.g. 'functools.par^tial' would yield 'functools.partial'\r\n Retry prevents infinite recursion: retry only once\r\n "
] |
Please provide a description of the function:def split_source(source_code):
'''Split source code into lines
'''
eol_chars = get_eol_chars(source_code)
if eol_chars:
return source_code.split(eol_chars)
else:
return [source_code] | [] |
Please provide a description of the function:def get_identifiers(source_code):
'''Split source code into python identifier-like tokens'''
tokens = set(re.split(r"[^0-9a-zA-Z_.]", source_code))
valid = re.compile(r'[a-zA-Z_]')
return [token for token in tokens if re.match(valid, token)] | [] |
Please provide a description of the function:def path_components(path):
components = []
# The loop guarantees that the returned components can be
# os.path.joined with the path separator and point to the same
# location:
while True:
(new_path, tail) = os.path.split(path) # W... | [
"\r\n Return the individual components of a given file path\r\n string (for the local operating system).\r\n\r\n Taken from https://stackoverflow.com/q/21498939/438386\r\n "
] |
Please provide a description of the function:def differentiate_prefix(path_components0, path_components1):
longest_prefix = []
root_comparison = False
common_elmt = None
for index, (elmt0, elmt1) in enumerate(zip(path_components0, path_components1)):
if elmt0 != elmt1:
if... | [
"\r\n Return the differentiated prefix of the given two iterables. \r\n \r\n Taken from https://stackoverflow.com/q/21498939/438386\r\n "
] |
Please provide a description of the function:def disambiguate_fname(files_path_list, filename):
fname = os.path.basename(filename)
same_name_files = get_same_name_files(files_path_list, fname)
if len(same_name_files) > 1:
compare_path = shortest_path(same_name_files)
if compare_pa... | [
"Get tab title without ambiguation."
] |
Please provide a description of the function:def get_same_name_files(files_path_list, filename):
same_name_files = []
for fname in files_path_list:
if filename == os.path.basename(fname):
same_name_files.append(path_components(fname))
return same_name_files | [
"Get a list of the path components of the files with the same name."
] |
Please provide a description of the function:def add(self, decorations):
added = 0
if isinstance(decorations, list):
not_repeated = set(decorations) - set(self._decorations)
self._decorations.extend(list(not_repeated))
added = len(not_repeated)
elif d... | [
"\n Add text decorations on a CodeEditor instance.\n\n Don't add duplicated decorations, and order decorations according\n draw_order and the size of the selection.\n\n Args:\n decorations (sourcecode.api.TextDecoration) (could be a list)\n Returns:\n int: Am... |
Please provide a description of the function:def remove(self, decoration):
try:
self._decorations.remove(decoration)
self.update()
return True
except ValueError:
return False
except RuntimeError:
# This is needed to fix issue 9... | [
"\n Removes a text decoration from the editor.\n\n :param decoration: Text decoration to remove\n :type decoration: spyder.api.TextDecoration\n "
] |
Please provide a description of the function:def update(self):
font = self.editor.font()
for decoration in self._decorations:
try:
decoration.format.setFont(
font, QTextCharFormat.FontPropertiesSpecifiedOnly)
except (TypeError, Att... | [
"Update editor extra selections with added decorations.\n\n NOTE: Update TextDecorations to use editor font, using a different\n font family and point size could cause unwanted behaviors.\n "
] |
Please provide a description of the function:def _order_decorations(self):
def order_function(sel):
end = sel.cursor.selectionEnd()
start = sel.cursor.selectionStart()
return sel.draw_order, -(end - start)
self._decorations = sorted(self._decorations,
... | [
"Order decorations according draw_order and size of selection.\n\n Highest draw_order will appear on top of the lowest values.\n\n If draw_order is equal,smaller selections are draw in top of\n bigger selections.\n "
] |
Please provide a description of the function:def get_signature(self, content):
data = content.get('data', {})
text = data.get('text/plain', '')
if text:
text = ANSI_OR_SPECIAL_PATTERN.sub('', text)
self._control.current_prompt_pos = self._prompt_pos
l... | [
"Get signature from inspect reply content"
] |
Please provide a description of the function:def is_defined(self, objtxt, force_import=False):
if self._reading:
return
wait_loop = QEventLoop()
self.sig_got_reply.connect(wait_loop.quit)
self.silent_exec_method(
"get_ipython().kernel.is_defined('%s', for... | [
"Return True if object is defined"
] |
Please provide a description of the function:def get_doc(self, objtxt):
if self._reading:
return
wait_loop = QEventLoop()
self.sig_got_reply.connect(wait_loop.quit)
self.silent_exec_method("get_ipython().kernel.get_doc('%s')" % objtxt)
wait_loop.exec_()
... | [
"Get object documentation dictionary"
] |
Please provide a description of the function:def _handle_inspect_reply(self, rep):
cursor = self._get_cursor()
info = self._request_info.get('call_tip')
if info and info.id == rep['parent_header']['msg_id'] and \
info.pos == cursor.position():
content = rep['conten... | [
"\n Reimplement call tips to only show signatures, using the same\n style from our Editor and External Console too\n "
] |
Please provide a description of the function:def _encode_params(kw):
'''
Encode parameters.
'''
args = []
for k, v in kw.items():
try:
# Python 2
qv = v.encode('utf-8') if isinstance(v, unicode) else str(v)
except:
qv = v
args.append('%s=%s... | [] |
Please provide a description of the function:def _encode_json(obj):
'''
Encode object as json str.
'''
def _dump_obj(obj):
if isinstance(obj, dict):
return obj
d = dict()
for k in dir(obj):
if not k.startswith('_'):
d[k] = getattr(obj, k)
... | [] |
Please provide a description of the function:def authorize_url(self, state=None):
'''
Generate authorize_url.
>>> GitHub(client_id='3ebf94c5776d565bcf75').authorize_url()
'https://github.com/login/oauth/authorize?client_id=3ebf94c5776d565bcf75'
'''
if not self._client_id... | [] |
Please provide a description of the function:def get_access_token(self, code, state=None):
'''
In callback url: http://host/callback?code=123&state=xyz
use code and state to get an access token.
'''
kw = dict(client_id=self._client_id, client_secret=self._client_secret, code=cod... | [] |
Please provide a description of the function:def send_request(req=None, method=None, requires_response=True):
if req is None:
return functools.partial(send_request, method=method,
requires_response=requires_response)
@functools.wraps(req)
def wrapper(self, *arg... | [
"Call function req and then send its results via ZMQ."
] |
Please provide a description of the function:def class_register(cls):
cls.handler_registry = {}
cls.sender_registry = {}
for method_name in dir(cls):
method = getattr(cls, method_name)
if hasattr(method, '_handle'):
cls.handler_registry.update({method._handle: method_name})
... | [
"Class decorator that allows to map LSP method names to class methods."
] |
Please provide a description of the function:def set_data(self, data, coll_filter=None):
self._data = data
data_type = get_type_string(data)
if coll_filter is not None and not self.remote and \
isinstance(data, (tuple, list, dict, set)):
data = coll_filter(... | [
"Set model data"
] |
Please provide a description of the function:def sort(self, column, order=Qt.AscendingOrder):
reverse = (order==Qt.DescendingOrder)
if column == 0:
self.sizes = sort_against(self.sizes, self.keys, reverse)
self.types = sort_against(self.types, self.keys, reverse)
... | [
"Overriding sort method"
] |
Please provide a description of the function:def rowCount(self, index=QModelIndex()):
if self.total_rows <= self.rows_loaded:
return self.total_rows
else:
return self.rows_loaded | [
"Array row number"
] |
Please provide a description of the function:def get_value(self, index):
if index.column() == 0:
return self.keys[ index.row() ]
elif index.column() == 1:
return self.types[ index.row() ]
elif index.column() == 2:
return self.sizes[ index.row()... | [
"Return current value"
] |
Please provide a description of the function:def get_bgcolor(self, index):
if index.column() == 0:
color = QColor(Qt.lightGray)
color.setAlphaF(.05)
elif index.column() < 3:
color = QColor(Qt.lightGray)
color.setAlphaF(.2)
else:
... | [
"Background color depending on value"
] |
Please provide a description of the function:def data(self, index, role=Qt.DisplayRole):
if not index.isValid():
return to_qvariant()
value = self.get_value(index)
if index.column() == 3 and self.remote:
value = value['view']
if index.column() == 3... | [
"Cell content"
] |
Please provide a description of the function:def headerData(self, section, orientation, role=Qt.DisplayRole):
if role != Qt.DisplayRole:
return to_qvariant()
i_column = int(section)
if orientation == Qt.Horizontal:
headers = (self.header0, _("Type"), _("Siz... | [
"Overriding method headerData"
] |
Please provide a description of the function:def flags(self, index):
# This method was implemented in CollectionsModel only, but to enable
# tuple exploration (even without editing), this method was moved here
if not index.isValid():
return Qt.ItemIsEnabled
ret... | [
"Overriding method flags"
] |
Please provide a description of the function:def set_value(self, index, value):
self._data[ self.keys[index.row()] ] = value
self.showndata[ self.keys[index.row()] ] = value
self.sizes[index.row()] = get_size(value)
self.types[index.row()] = get_human_readable_type(value)
... | [
"Set value"
] |
Please provide a description of the function:def get_bgcolor(self, index):
value = self.get_value(index)
if index.column() < 3:
color = ReadOnlyCollectionsModel.get_bgcolor(self, index)
else:
if self.remote:
color_name = value['color']
... | [
"Background color depending on value"
] |
Please provide a description of the function:def setData(self, index, value, role=Qt.EditRole):
if not index.isValid():
return False
if index.column() < 3:
return False
value = display_to_value(value, self.get_value(index),
... | [
"Cell content change"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.