id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
31,100
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
ShellBaseWidget.set_font
def set_font(self, font): """Set shell styles font""" self.setFont(font) self.set_pythonshell_font(font) cursor = self.textCursor() cursor.select(QTextCursor.Document) charformat = QTextCharFormat() charformat.setFontFamily(font.family()) charformat.setFontPointSize(font.pointSize()) cursor.mergeCharFormat(charformat)
python
def set_font(self, font): """Set shell styles font""" self.setFont(font) self.set_pythonshell_font(font) cursor = self.textCursor() cursor.select(QTextCursor.Document) charformat = QTextCharFormat() charformat.setFontFamily(font.family()) charformat.setFontPointSize(font.pointSize()) cursor.mergeCharFormat(charformat)
[ "def", "set_font", "(", "self", ",", "font", ")", ":", "self", ".", "setFont", "(", "font", ")", "self", ".", "set_pythonshell_font", "(", "font", ")", "cursor", "=", "self", ".", "textCursor", "(", ")", "cursor", ".", "select", "(", "QTextCursor", "."...
Set shell styles font
[ "Set", "shell", "styles", "font" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L108-L117
31,101
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
ShellBaseWidget.setup_context_menu
def setup_context_menu(self): """Setup shell context menu""" self.menu = QMenu(self) self.cut_action = create_action(self, _("Cut"), shortcut=keybinding('Cut'), icon=ima.icon('editcut'), triggered=self.cut) self.copy_action = create_action(self, _("Copy"), shortcut=keybinding('Copy'), icon=ima.icon('editcopy'), triggered=self.copy) paste_action = create_action(self, _("Paste"), shortcut=keybinding('Paste'), icon=ima.icon('editpaste'), triggered=self.paste) save_action = create_action(self, _("Save history log..."), icon=ima.icon('filesave'), tip=_("Save current history log (i.e. all " "inputs and outputs) in a text file"), triggered=self.save_historylog) self.delete_action = create_action(self, _("Delete"), shortcut=keybinding('Delete'), icon=ima.icon('editdelete'), triggered=self.delete) selectall_action = create_action(self, _("Select All"), shortcut=keybinding('SelectAll'), icon=ima.icon('selectall'), triggered=self.selectAll) add_actions(self.menu, (self.cut_action, self.copy_action, paste_action, self.delete_action, None, selectall_action, None, save_action) )
python
def setup_context_menu(self): """Setup shell context menu""" self.menu = QMenu(self) self.cut_action = create_action(self, _("Cut"), shortcut=keybinding('Cut'), icon=ima.icon('editcut'), triggered=self.cut) self.copy_action = create_action(self, _("Copy"), shortcut=keybinding('Copy'), icon=ima.icon('editcopy'), triggered=self.copy) paste_action = create_action(self, _("Paste"), shortcut=keybinding('Paste'), icon=ima.icon('editpaste'), triggered=self.paste) save_action = create_action(self, _("Save history log..."), icon=ima.icon('filesave'), tip=_("Save current history log (i.e. all " "inputs and outputs) in a text file"), triggered=self.save_historylog) self.delete_action = create_action(self, _("Delete"), shortcut=keybinding('Delete'), icon=ima.icon('editdelete'), triggered=self.delete) selectall_action = create_action(self, _("Select All"), shortcut=keybinding('SelectAll'), icon=ima.icon('selectall'), triggered=self.selectAll) add_actions(self.menu, (self.cut_action, self.copy_action, paste_action, self.delete_action, None, selectall_action, None, save_action) )
[ "def", "setup_context_menu", "(", "self", ")", ":", "self", ".", "menu", "=", "QMenu", "(", "self", ")", "self", ".", "cut_action", "=", "create_action", "(", "self", ",", "_", "(", "\"Cut\"", ")", ",", "shortcut", "=", "keybinding", "(", "'Cut'", ")",...
Setup shell context menu
[ "Setup", "shell", "context", "menu" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L121-L151
31,102
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
ShellBaseWidget._set_input_buffer
def _set_input_buffer(self, text): """Set input buffer""" if self.current_prompt_pos is not None: self.replace_text(self.current_prompt_pos, 'eol', text) else: self.insert(text) self.set_cursor_position('eof')
python
def _set_input_buffer(self, text): """Set input buffer""" if self.current_prompt_pos is not None: self.replace_text(self.current_prompt_pos, 'eol', text) else: self.insert(text) self.set_cursor_position('eof')
[ "def", "_set_input_buffer", "(", "self", ",", "text", ")", ":", "if", "self", ".", "current_prompt_pos", "is", "not", "None", ":", "self", ".", "replace_text", "(", "self", ".", "current_prompt_pos", ",", "'eol'", ",", "text", ")", "else", ":", "self", "...
Set input buffer
[ "Set", "input", "buffer" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L185-L191
31,103
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
ShellBaseWidget._get_input_buffer
def _get_input_buffer(self): """Return input buffer""" input_buffer = '' if self.current_prompt_pos is not None: input_buffer = self.get_text(self.current_prompt_pos, 'eol') input_buffer = input_buffer.replace(os.linesep, '\n') return input_buffer
python
def _get_input_buffer(self): """Return input buffer""" input_buffer = '' if self.current_prompt_pos is not None: input_buffer = self.get_text(self.current_prompt_pos, 'eol') input_buffer = input_buffer.replace(os.linesep, '\n') return input_buffer
[ "def", "_get_input_buffer", "(", "self", ")", ":", "input_buffer", "=", "''", "if", "self", ".", "current_prompt_pos", "is", "not", "None", ":", "input_buffer", "=", "self", ".", "get_text", "(", "self", ".", "current_prompt_pos", ",", "'eol'", ")", "input_b...
Return input buffer
[ "Return", "input", "buffer" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L193-L199
31,104
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
ShellBaseWidget.copy
def copy(self): """Copy text to clipboard... or keyboard interrupt""" if self.has_selected_text(): ConsoleBaseWidget.copy(self) elif not sys.platform == 'darwin': self.interrupt()
python
def copy(self): """Copy text to clipboard... or keyboard interrupt""" if self.has_selected_text(): ConsoleBaseWidget.copy(self) elif not sys.platform == 'darwin': self.interrupt()
[ "def", "copy", "(", "self", ")", ":", "if", "self", ".", "has_selected_text", "(", ")", ":", "ConsoleBaseWidget", ".", "copy", "(", "self", ")", "elif", "not", "sys", ".", "platform", "==", "'darwin'", ":", "self", ".", "interrupt", "(", ")" ]
Copy text to clipboard... or keyboard interrupt
[ "Copy", "text", "to", "clipboard", "...", "or", "keyboard", "interrupt" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L230-L235
31,105
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
ShellBaseWidget.on_new_line
def on_new_line(self): """On new input line""" self.set_cursor_position('eof') self.current_prompt_pos = self.get_position('cursor') self.new_input_line = False
python
def on_new_line(self): """On new input line""" self.set_cursor_position('eof') self.current_prompt_pos = self.get_position('cursor') self.new_input_line = False
[ "def", "on_new_line", "(", "self", ")", ":", "self", ".", "set_cursor_position", "(", "'eof'", ")", "self", ".", "current_prompt_pos", "=", "self", ".", "get_position", "(", "'cursor'", ")", "self", ".", "new_input_line", "=", "False" ]
On new input line
[ "On", "new", "input", "line" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L283-L287
31,106
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
ShellBaseWidget.load_history
def load_history(self): """Load history from a .py file in user home directory""" if osp.isfile(self.history_filename): rawhistory, _ = encoding.readlines(self.history_filename) rawhistory = [line.replace('\n', '') for line in rawhistory] if rawhistory[1] != self.INITHISTORY[1]: rawhistory[1] = self.INITHISTORY[1] else: rawhistory = self.INITHISTORY history = [line for line in rawhistory \ if line and not line.startswith('#')] # Truncating history to X entries: while len(history) >= CONF.get('historylog', 'max_entries'): del history[0] while rawhistory[0].startswith('#'): del rawhistory[0] del rawhistory[0] # Saving truncated history: try: encoding.writelines(rawhistory, self.history_filename) except EnvironmentError: pass return history
python
def load_history(self): """Load history from a .py file in user home directory""" if osp.isfile(self.history_filename): rawhistory, _ = encoding.readlines(self.history_filename) rawhistory = [line.replace('\n', '') for line in rawhistory] if rawhistory[1] != self.INITHISTORY[1]: rawhistory[1] = self.INITHISTORY[1] else: rawhistory = self.INITHISTORY history = [line for line in rawhistory \ if line and not line.startswith('#')] # Truncating history to X entries: while len(history) >= CONF.get('historylog', 'max_entries'): del history[0] while rawhistory[0].startswith('#'): del rawhistory[0] del rawhistory[0] # Saving truncated history: try: encoding.writelines(rawhistory, self.history_filename) except EnvironmentError: pass return history
[ "def", "load_history", "(", "self", ")", ":", "if", "osp", ".", "isfile", "(", "self", ".", "history_filename", ")", ":", "rawhistory", ",", "_", "=", "encoding", ".", "readlines", "(", "self", ".", "history_filename", ")", "rawhistory", "=", "[", "line"...
Load history from a .py file in user home directory
[ "Load", "history", "from", "a", ".", "py", "file", "in", "user", "home", "directory" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L495-L520
31,107
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
ShellBaseWidget.write
def write(self, text, flush=False, error=False, prompt=False): """Simulate stdout and stderr""" if prompt: self.flush() if not is_string(text): # This test is useful to discriminate QStrings from decoded str text = to_text_string(text) self.__buffer.append(text) ts = time.time() if flush or prompt: self.flush(error=error, prompt=prompt) elif ts - self.__timestamp > 0.05: self.flush(error=error) self.__timestamp = ts # Timer to flush strings cached by last write() operation in series self.__flushtimer.start(50)
python
def write(self, text, flush=False, error=False, prompt=False): """Simulate stdout and stderr""" if prompt: self.flush() if not is_string(text): # This test is useful to discriminate QStrings from decoded str text = to_text_string(text) self.__buffer.append(text) ts = time.time() if flush or prompt: self.flush(error=error, prompt=prompt) elif ts - self.__timestamp > 0.05: self.flush(error=error) self.__timestamp = ts # Timer to flush strings cached by last write() operation in series self.__flushtimer.start(50)
[ "def", "write", "(", "self", ",", "text", ",", "flush", "=", "False", ",", "error", "=", "False", ",", "prompt", "=", "False", ")", ":", "if", "prompt", ":", "self", ".", "flush", "(", ")", "if", "not", "is_string", "(", "text", ")", ":", "# This...
Simulate stdout and stderr
[ "Simulate", "stdout", "and", "stderr" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L530-L545
31,108
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
ShellBaseWidget.flush
def flush(self, error=False, prompt=False): """Flush buffer, write text to console""" # Fix for Issue 2452 if PY3: try: text = "".join(self.__buffer) except TypeError: text = b"".join(self.__buffer) try: text = text.decode( locale.getdefaultlocale()[1] ) except: pass else: text = "".join(self.__buffer) self.__buffer = [] self.insert_text(text, at_end=True, error=error, prompt=prompt) QCoreApplication.processEvents() self.repaint() # Clear input buffer: self.new_input_line = True
python
def flush(self, error=False, prompt=False): """Flush buffer, write text to console""" # Fix for Issue 2452 if PY3: try: text = "".join(self.__buffer) except TypeError: text = b"".join(self.__buffer) try: text = text.decode( locale.getdefaultlocale()[1] ) except: pass else: text = "".join(self.__buffer) self.__buffer = [] self.insert_text(text, at_end=True, error=error, prompt=prompt) QCoreApplication.processEvents() self.repaint() # Clear input buffer: self.new_input_line = True
[ "def", "flush", "(", "self", ",", "error", "=", "False", ",", "prompt", "=", "False", ")", ":", "# Fix for Issue 2452 \r", "if", "PY3", ":", "try", ":", "text", "=", "\"\"", ".", "join", "(", "self", ".", "__buffer", ")", "except", "TypeError", ":", ...
Flush buffer, write text to console
[ "Flush", "buffer", "write", "text", "to", "console" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L547-L567
31,109
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
ShellBaseWidget.insert_text
def insert_text(self, text, at_end=False, error=False, prompt=False): """ Insert text at the current cursor position or at the end of the command line """ if at_end: # Insert text at the end of the command line self.append_text_to_shell(text, error, prompt) else: # Insert text at current cursor position ConsoleBaseWidget.insert_text(self, text)
python
def insert_text(self, text, at_end=False, error=False, prompt=False): """ Insert text at the current cursor position or at the end of the command line """ if at_end: # Insert text at the end of the command line self.append_text_to_shell(text, error, prompt) else: # Insert text at current cursor position ConsoleBaseWidget.insert_text(self, text)
[ "def", "insert_text", "(", "self", ",", "text", ",", "at_end", "=", "False", ",", "error", "=", "False", ",", "prompt", "=", "False", ")", ":", "if", "at_end", ":", "# Insert text at the end of the command line\r", "self", ".", "append_text_to_shell", "(", "te...
Insert text at the current cursor position or at the end of the command line
[ "Insert", "text", "at", "the", "current", "cursor", "position", "or", "at", "the", "end", "of", "the", "command", "line" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L571-L581
31,110
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
ShellBaseWidget.dropEvent
def dropEvent(self, event): """Drag and Drop - Drop event""" if (event.mimeData().hasFormat("text/plain")): text = to_text_string(event.mimeData().text()) if self.new_input_line: self.on_new_line() self.insert_text(text, at_end=True) self.setFocus() event.setDropAction(Qt.MoveAction) event.accept() else: event.ignore()
python
def dropEvent(self, event): """Drag and Drop - Drop event""" if (event.mimeData().hasFormat("text/plain")): text = to_text_string(event.mimeData().text()) if self.new_input_line: self.on_new_line() self.insert_text(text, at_end=True) self.setFocus() event.setDropAction(Qt.MoveAction) event.accept() else: event.ignore()
[ "def", "dropEvent", "(", "self", ",", "event", ")", ":", "if", "(", "event", ".", "mimeData", "(", ")", ".", "hasFormat", "(", "\"text/plain\"", ")", ")", ":", "text", "=", "to_text_string", "(", "event", ".", "mimeData", "(", ")", ".", "text", "(", ...
Drag and Drop - Drop event
[ "Drag", "and", "Drop", "-", "Drop", "event" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L607-L618
31,111
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
PythonShellWidget.copy_without_prompts
def copy_without_prompts(self): """Copy text to clipboard without prompts""" text = self.get_selected_text() lines = text.split(os.linesep) for index, line in enumerate(lines): if line.startswith('>>> ') or line.startswith('... '): lines[index] = line[4:] text = os.linesep.join(lines) QApplication.clipboard().setText(text)
python
def copy_without_prompts(self): """Copy text to clipboard without prompts""" text = self.get_selected_text() lines = text.split(os.linesep) for index, line in enumerate(lines): if line.startswith('>>> ') or line.startswith('... '): lines[index] = line[4:] text = os.linesep.join(lines) QApplication.clipboard().setText(text)
[ "def", "copy_without_prompts", "(", "self", ")", ":", "text", "=", "self", ".", "get_selected_text", "(", ")", "lines", "=", "text", ".", "split", "(", "os", ".", "linesep", ")", "for", "index", ",", "line", "in", "enumerate", "(", "lines", ")", ":", ...
Copy text to clipboard without prompts
[ "Copy", "text", "to", "clipboard", "without", "prompts" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L702-L710
31,112
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
PythonShellWidget.postprocess_keyevent
def postprocess_keyevent(self, event): """Process keypress event""" ShellBaseWidget.postprocess_keyevent(self, event) if QToolTip.isVisible(): _event, _text, key, _ctrl, _shift = restore_keyevent(event) self.hide_tooltip_if_necessary(key)
python
def postprocess_keyevent(self, event): """Process keypress event""" ShellBaseWidget.postprocess_keyevent(self, event) if QToolTip.isVisible(): _event, _text, key, _ctrl, _shift = restore_keyevent(event) self.hide_tooltip_if_necessary(key)
[ "def", "postprocess_keyevent", "(", "self", ",", "event", ")", ":", "ShellBaseWidget", ".", "postprocess_keyevent", "(", "self", ",", "event", ")", "if", "QToolTip", ".", "isVisible", "(", ")", ":", "_event", ",", "_text", ",", "key", ",", "_ctrl", ",", ...
Process keypress event
[ "Process", "keypress", "event" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L714-L719
31,113
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
PythonShellWidget._key_backspace
def _key_backspace(self, cursor_position): """Action for Backspace key""" if self.has_selected_text(): self.check_selection() self.remove_selected_text() elif self.current_prompt_pos == cursor_position: # Avoid deleting prompt return elif self.is_cursor_on_last_line(): self.stdkey_backspace() if self.is_completion_widget_visible(): # Removing only last character because if there was a selection # the completion widget would have been canceled self.completion_text = self.completion_text[:-1]
python
def _key_backspace(self, cursor_position): """Action for Backspace key""" if self.has_selected_text(): self.check_selection() self.remove_selected_text() elif self.current_prompt_pos == cursor_position: # Avoid deleting prompt return elif self.is_cursor_on_last_line(): self.stdkey_backspace() if self.is_completion_widget_visible(): # Removing only last character because if there was a selection # the completion widget would have been canceled self.completion_text = self.completion_text[:-1]
[ "def", "_key_backspace", "(", "self", ",", "cursor_position", ")", ":", "if", "self", ".", "has_selected_text", "(", ")", ":", "self", ".", "check_selection", "(", ")", "self", ".", "remove_selected_text", "(", ")", "elif", "self", ".", "current_prompt_pos", ...
Action for Backspace key
[ "Action", "for", "Backspace", "key" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L726-L739
31,114
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
PythonShellWidget._key_tab
def _key_tab(self): """Action for TAB key""" if self.is_cursor_on_last_line(): empty_line = not self.get_current_line_to_cursor().strip() if empty_line: self.stdkey_tab() else: self.show_code_completion()
python
def _key_tab(self): """Action for TAB key""" if self.is_cursor_on_last_line(): empty_line = not self.get_current_line_to_cursor().strip() if empty_line: self.stdkey_tab() else: self.show_code_completion()
[ "def", "_key_tab", "(", "self", ")", ":", "if", "self", ".", "is_cursor_on_last_line", "(", ")", ":", "empty_line", "=", "not", "self", ".", "get_current_line_to_cursor", "(", ")", ".", "strip", "(", ")", "if", "empty_line", ":", "self", ".", "stdkey_tab",...
Action for TAB key
[ "Action", "for", "TAB", "key" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L741-L748
31,115
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
PythonShellWidget._key_question
def _key_question(self, text): """Action for '?'""" if self.get_current_line_to_cursor(): last_obj = self.get_last_obj() if last_obj and not last_obj.isdigit(): self.show_object_info(last_obj) self.insert_text(text) # In case calltip and completion are shown at the same time: if self.is_completion_widget_visible(): self.completion_text += '?'
python
def _key_question(self, text): """Action for '?'""" if self.get_current_line_to_cursor(): last_obj = self.get_last_obj() if last_obj and not last_obj.isdigit(): self.show_object_info(last_obj) self.insert_text(text) # In case calltip and completion are shown at the same time: if self.is_completion_widget_visible(): self.completion_text += '?'
[ "def", "_key_question", "(", "self", ",", "text", ")", ":", "if", "self", ".", "get_current_line_to_cursor", "(", ")", ":", "last_obj", "=", "self", ".", "get_last_obj", "(", ")", "if", "last_obj", "and", "not", "last_obj", ".", "isdigit", "(", ")", ":",...
Action for '?
[ "Action", "for", "?" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L768-L777
31,116
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
PythonShellWidget._key_period
def _key_period(self, text): """Action for '.'""" self.insert_text(text) if self.codecompletion_auto: # Enable auto-completion only if last token isn't a float last_obj = self.get_last_obj() if last_obj and not last_obj.isdigit(): self.show_code_completion()
python
def _key_period(self, text): """Action for '.'""" self.insert_text(text) if self.codecompletion_auto: # Enable auto-completion only if last token isn't a float last_obj = self.get_last_obj() if last_obj and not last_obj.isdigit(): self.show_code_completion()
[ "def", "_key_period", "(", "self", ",", "text", ")", ":", "self", ".", "insert_text", "(", "text", ")", "if", "self", ".", "codecompletion_auto", ":", "# Enable auto-completion only if last token isn't a float\r", "last_obj", "=", "self", ".", "get_last_obj", "(", ...
Action for '.
[ "Action", "for", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L790-L797
31,117
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
PythonShellWidget.paste
def paste(self): """Reimplemented slot to handle multiline paste action""" text = to_text_string(QApplication.clipboard().text()) if len(text.splitlines()) > 1: # Multiline paste if self.new_input_line: self.on_new_line() self.remove_selected_text() # Remove selection, eventually end = self.get_current_line_from_cursor() lines = self.get_current_line_to_cursor() + text + end self.clear_line() self.execute_lines(lines) self.move_cursor(-len(end)) else: # Standard paste ShellBaseWidget.paste(self)
python
def paste(self): """Reimplemented slot to handle multiline paste action""" text = to_text_string(QApplication.clipboard().text()) if len(text.splitlines()) > 1: # Multiline paste if self.new_input_line: self.on_new_line() self.remove_selected_text() # Remove selection, eventually end = self.get_current_line_from_cursor() lines = self.get_current_line_to_cursor() + text + end self.clear_line() self.execute_lines(lines) self.move_cursor(-len(end)) else: # Standard paste ShellBaseWidget.paste(self)
[ "def", "paste", "(", "self", ")", ":", "text", "=", "to_text_string", "(", "QApplication", ".", "clipboard", "(", ")", ".", "text", "(", ")", ")", "if", "len", "(", "text", ".", "splitlines", "(", ")", ")", ">", "1", ":", "# Multiline paste\r", "if",...
Reimplemented slot to handle multiline paste action
[ "Reimplemented", "slot", "to", "handle", "multiline", "paste", "action" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L801-L816
31,118
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
PythonShellWidget.show_completion_list
def show_completion_list(self, completions, completion_text=""): """Display the possible completions""" if not completions: return if not isinstance(completions[0], tuple): completions = [(c, '') for c in completions] if len(completions) == 1 and completions[0][0] == completion_text: return self.completion_text = completion_text # Sorting completion list (entries starting with underscore are # put at the end of the list): underscore = set([(comp, t) for (comp, t) in completions if comp.startswith('_')]) completions = sorted(set(completions) - underscore, key=lambda x: str_lower(x[0])) completions += sorted(underscore, key=lambda x: str_lower(x[0])) self.show_completion_widget(completions)
python
def show_completion_list(self, completions, completion_text=""): """Display the possible completions""" if not completions: return if not isinstance(completions[0], tuple): completions = [(c, '') for c in completions] if len(completions) == 1 and completions[0][0] == completion_text: return self.completion_text = completion_text # Sorting completion list (entries starting with underscore are # put at the end of the list): underscore = set([(comp, t) for (comp, t) in completions if comp.startswith('_')]) completions = sorted(set(completions) - underscore, key=lambda x: str_lower(x[0])) completions += sorted(underscore, key=lambda x: str_lower(x[0])) self.show_completion_widget(completions)
[ "def", "show_completion_list", "(", "self", ",", "completions", ",", "completion_text", "=", "\"\"", ")", ":", "if", "not", "completions", ":", "return", "if", "not", "isinstance", "(", "completions", "[", "0", "]", ",", "tuple", ")", ":", "completions", "...
Display the possible completions
[ "Display", "the", "possible", "completions" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L858-L875
31,119
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
PythonShellWidget.show_code_completion
def show_code_completion(self): """Display a completion list based on the current line""" # Note: unicode conversion is needed only for ExternalShellBase text = to_text_string(self.get_current_line_to_cursor()) last_obj = self.get_last_obj() if not text: return obj_dir = self.get_dir(last_obj) if last_obj and obj_dir and text.endswith('.'): self.show_completion_list(obj_dir) return # Builtins and globals if not text.endswith('.') and last_obj \ and re.match(r'[a-zA-Z_0-9]*$', last_obj): b_k_g = dir(builtins)+self.get_globals_keys()+keyword.kwlist for objname in b_k_g: if objname.startswith(last_obj) and objname != last_obj: self.show_completion_list(b_k_g, completion_text=last_obj) return else: return # Looking for an incomplete completion if last_obj is None: last_obj = text dot_pos = last_obj.rfind('.') if dot_pos != -1: if dot_pos == len(last_obj)-1: completion_text = "" else: completion_text = last_obj[dot_pos+1:] last_obj = last_obj[:dot_pos] completions = self.get_dir(last_obj) if completions is not None: self.show_completion_list(completions, completion_text=completion_text) return # Looking for ' or ": filename completion q_pos = max([text.rfind("'"), text.rfind('"')]) if q_pos != -1: completions = self.get_cdlistdir() if completions: self.show_completion_list(completions, completion_text=text[q_pos+1:]) return
python
def show_code_completion(self): """Display a completion list based on the current line""" # Note: unicode conversion is needed only for ExternalShellBase text = to_text_string(self.get_current_line_to_cursor()) last_obj = self.get_last_obj() if not text: return obj_dir = self.get_dir(last_obj) if last_obj and obj_dir and text.endswith('.'): self.show_completion_list(obj_dir) return # Builtins and globals if not text.endswith('.') and last_obj \ and re.match(r'[a-zA-Z_0-9]*$', last_obj): b_k_g = dir(builtins)+self.get_globals_keys()+keyword.kwlist for objname in b_k_g: if objname.startswith(last_obj) and objname != last_obj: self.show_completion_list(b_k_g, completion_text=last_obj) return else: return # Looking for an incomplete completion if last_obj is None: last_obj = text dot_pos = last_obj.rfind('.') if dot_pos != -1: if dot_pos == len(last_obj)-1: completion_text = "" else: completion_text = last_obj[dot_pos+1:] last_obj = last_obj[:dot_pos] completions = self.get_dir(last_obj) if completions is not None: self.show_completion_list(completions, completion_text=completion_text) return # Looking for ' or ": filename completion q_pos = max([text.rfind("'"), text.rfind('"')]) if q_pos != -1: completions = self.get_cdlistdir() if completions: self.show_completion_list(completions, completion_text=text[q_pos+1:]) return
[ "def", "show_code_completion", "(", "self", ")", ":", "# Note: unicode conversion is needed only for ExternalShellBase\r", "text", "=", "to_text_string", "(", "self", ".", "get_current_line_to_cursor", "(", ")", ")", "last_obj", "=", "self", ".", "get_last_obj", "(", ")...
Display a completion list based on the current line
[ "Display", "a", "completion", "list", "based", "on", "the", "current", "line" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L877-L924
31,120
spyder-ide/spyder
spyder/plugins/console/widgets/shell.py
PythonShellWidget.drop_pathlist
def drop_pathlist(self, pathlist): """Drop path list""" if pathlist: files = ["r'%s'" % path for path in pathlist] if len(files) == 1: text = files[0] else: text = "[" + ", ".join(files) + "]" if self.new_input_line: self.on_new_line() self.insert_text(text) self.setFocus()
python
def drop_pathlist(self, pathlist): """Drop path list""" if pathlist: files = ["r'%s'" % path for path in pathlist] if len(files) == 1: text = files[0] else: text = "[" + ", ".join(files) + "]" if self.new_input_line: self.on_new_line() self.insert_text(text) self.setFocus()
[ "def", "drop_pathlist", "(", "self", ",", "pathlist", ")", ":", "if", "pathlist", ":", "files", "=", "[", "\"r'%s'\"", "%", "path", "for", "path", "in", "pathlist", "]", "if", "len", "(", "files", ")", "==", "1", ":", "text", "=", "files", "[", "0"...
Drop path list
[ "Drop", "path", "list" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L934-L945
31,121
spyder-ide/spyder
spyder/plugins/ipythonconsole/utils/kernelspec.py
SpyderKernelSpec.argv
def argv(self): """Command to start kernels""" # Python interpreter used to start kernels if CONF.get('main_interpreter', 'default'): pyexec = get_python_executable() else: # Avoid IPython adding the virtualenv on which Spyder is running # to the kernel sys.path os.environ.pop('VIRTUAL_ENV', None) pyexec = CONF.get('main_interpreter', 'executable') if not is_python_interpreter(pyexec): pyexec = get_python_executable() CONF.set('main_interpreter', 'executable', '') CONF.set('main_interpreter', 'default', True) CONF.set('main_interpreter', 'custom', False) # Fixes Issue #3427 if os.name == 'nt': dir_pyexec = osp.dirname(pyexec) pyexec_w = osp.join(dir_pyexec, 'pythonw.exe') if osp.isfile(pyexec_w): pyexec = pyexec_w # Command used to start kernels kernel_cmd = [ pyexec, '-m', 'spyder_kernels.console', '-f', '{connection_file}' ] return kernel_cmd
python
def argv(self): """Command to start kernels""" # Python interpreter used to start kernels if CONF.get('main_interpreter', 'default'): pyexec = get_python_executable() else: # Avoid IPython adding the virtualenv on which Spyder is running # to the kernel sys.path os.environ.pop('VIRTUAL_ENV', None) pyexec = CONF.get('main_interpreter', 'executable') if not is_python_interpreter(pyexec): pyexec = get_python_executable() CONF.set('main_interpreter', 'executable', '') CONF.set('main_interpreter', 'default', True) CONF.set('main_interpreter', 'custom', False) # Fixes Issue #3427 if os.name == 'nt': dir_pyexec = osp.dirname(pyexec) pyexec_w = osp.join(dir_pyexec, 'pythonw.exe') if osp.isfile(pyexec_w): pyexec = pyexec_w # Command used to start kernels kernel_cmd = [ pyexec, '-m', 'spyder_kernels.console', '-f', '{connection_file}' ] return kernel_cmd
[ "def", "argv", "(", "self", ")", ":", "# Python interpreter used to start kernels", "if", "CONF", ".", "get", "(", "'main_interpreter'", ",", "'default'", ")", ":", "pyexec", "=", "get_python_executable", "(", ")", "else", ":", "# Avoid IPython adding the virtualenv o...
Command to start kernels
[ "Command", "to", "start", "kernels" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/utils/kernelspec.py#L41-L73
31,122
spyder-ide/spyder
spyder/plugins/ipythonconsole/utils/kernelspec.py
SpyderKernelSpec.env
def env(self): """Env vars for kernels""" # Add our PYTHONPATH to the kernel pathlist = CONF.get('main', 'spyder_pythonpath', default=[]) default_interpreter = CONF.get('main_interpreter', 'default') pypath = add_pathlist_to_PYTHONPATH([], pathlist, ipyconsole=True, drop_env=False) # Environment variables that we need to pass to our sitecustomize umr_namelist = CONF.get('main_interpreter', 'umr/namelist') if PY2: original_list = umr_namelist[:] for umr_n in umr_namelist: try: umr_n.encode('utf-8') except UnicodeDecodeError: umr_namelist.remove(umr_n) if original_list != umr_namelist: CONF.set('main_interpreter', 'umr/namelist', umr_namelist) env_vars = { 'SPY_EXTERNAL_INTERPRETER': not default_interpreter, 'SPY_UMR_ENABLED': CONF.get('main_interpreter', 'umr/enabled'), 'SPY_UMR_VERBOSE': CONF.get('main_interpreter', 'umr/verbose'), 'SPY_UMR_NAMELIST': ','.join(umr_namelist), 'SPY_RUN_LINES_O': CONF.get('ipython_console', 'startup/run_lines'), 'SPY_PYLAB_O': CONF.get('ipython_console', 'pylab'), 'SPY_BACKEND_O': CONF.get('ipython_console', 'pylab/backend'), 'SPY_AUTOLOAD_PYLAB_O': CONF.get('ipython_console', 'pylab/autoload'), 'SPY_FORMAT_O': CONF.get('ipython_console', 'pylab/inline/figure_format'), 'SPY_BBOX_INCHES_O': CONF.get('ipython_console', 'pylab/inline/bbox_inches'), 'SPY_RESOLUTION_O': CONF.get('ipython_console', 'pylab/inline/resolution'), 'SPY_WIDTH_O': CONF.get('ipython_console', 'pylab/inline/width'), 'SPY_HEIGHT_O': CONF.get('ipython_console', 'pylab/inline/height'), 'SPY_USE_FILE_O': CONF.get('ipython_console', 'startup/use_run_file'), 'SPY_RUN_FILE_O': CONF.get('ipython_console', 'startup/run_file'), 'SPY_AUTOCALL_O': CONF.get('ipython_console', 'autocall'), 'SPY_GREEDY_O': CONF.get('ipython_console', 'greedy_completer'), 'SPY_JEDI_O': CONF.get('ipython_console', 'jedi_completer'), 'SPY_SYMPY_O': CONF.get('ipython_console', 'symbolic_math'), 'SPY_TESTING': running_under_pytest() or SAFE_MODE, 'SPY_HIDE_CMD': CONF.get('ipython_console', 'hide_cmd_windows') } if self.is_pylab is True: env_vars['SPY_AUTOLOAD_PYLAB_O'] = True env_vars['SPY_SYMPY_O'] = False env_vars['SPY_RUN_CYTHON'] = False if self.is_sympy is True: env_vars['SPY_AUTOLOAD_PYLAB_O'] = False env_vars['SPY_SYMPY_O'] = True env_vars['SPY_RUN_CYTHON'] = False if self.is_cython is True: env_vars['SPY_AUTOLOAD_PYLAB_O'] = False env_vars['SPY_SYMPY_O'] = False env_vars['SPY_RUN_CYTHON'] = True # Add our PYTHONPATH to env_vars env_vars.update(pypath) # Making all env_vars strings for key,var in iteritems(env_vars): if PY2: # Try to convert vars first to utf-8. try: unicode_var = to_text_string(var) except UnicodeDecodeError: # If that fails, try to use the file system # encoding because one of our vars is our # PYTHONPATH, and that contains file system # directories try: unicode_var = to_unicode_from_fs(var) except: # If that also fails, make the var empty # to be able to start Spyder. # See https://stackoverflow.com/q/44506900/438386 # for details. unicode_var = '' env_vars[key] = to_binary_string(unicode_var, encoding='utf-8') else: env_vars[key] = to_text_string(var) return env_vars
python
def env(self): """Env vars for kernels""" # Add our PYTHONPATH to the kernel pathlist = CONF.get('main', 'spyder_pythonpath', default=[]) default_interpreter = CONF.get('main_interpreter', 'default') pypath = add_pathlist_to_PYTHONPATH([], pathlist, ipyconsole=True, drop_env=False) # Environment variables that we need to pass to our sitecustomize umr_namelist = CONF.get('main_interpreter', 'umr/namelist') if PY2: original_list = umr_namelist[:] for umr_n in umr_namelist: try: umr_n.encode('utf-8') except UnicodeDecodeError: umr_namelist.remove(umr_n) if original_list != umr_namelist: CONF.set('main_interpreter', 'umr/namelist', umr_namelist) env_vars = { 'SPY_EXTERNAL_INTERPRETER': not default_interpreter, 'SPY_UMR_ENABLED': CONF.get('main_interpreter', 'umr/enabled'), 'SPY_UMR_VERBOSE': CONF.get('main_interpreter', 'umr/verbose'), 'SPY_UMR_NAMELIST': ','.join(umr_namelist), 'SPY_RUN_LINES_O': CONF.get('ipython_console', 'startup/run_lines'), 'SPY_PYLAB_O': CONF.get('ipython_console', 'pylab'), 'SPY_BACKEND_O': CONF.get('ipython_console', 'pylab/backend'), 'SPY_AUTOLOAD_PYLAB_O': CONF.get('ipython_console', 'pylab/autoload'), 'SPY_FORMAT_O': CONF.get('ipython_console', 'pylab/inline/figure_format'), 'SPY_BBOX_INCHES_O': CONF.get('ipython_console', 'pylab/inline/bbox_inches'), 'SPY_RESOLUTION_O': CONF.get('ipython_console', 'pylab/inline/resolution'), 'SPY_WIDTH_O': CONF.get('ipython_console', 'pylab/inline/width'), 'SPY_HEIGHT_O': CONF.get('ipython_console', 'pylab/inline/height'), 'SPY_USE_FILE_O': CONF.get('ipython_console', 'startup/use_run_file'), 'SPY_RUN_FILE_O': CONF.get('ipython_console', 'startup/run_file'), 'SPY_AUTOCALL_O': CONF.get('ipython_console', 'autocall'), 'SPY_GREEDY_O': CONF.get('ipython_console', 'greedy_completer'), 'SPY_JEDI_O': CONF.get('ipython_console', 'jedi_completer'), 'SPY_SYMPY_O': CONF.get('ipython_console', 'symbolic_math'), 'SPY_TESTING': running_under_pytest() or SAFE_MODE, 'SPY_HIDE_CMD': CONF.get('ipython_console', 'hide_cmd_windows') } if self.is_pylab is True: env_vars['SPY_AUTOLOAD_PYLAB_O'] = True env_vars['SPY_SYMPY_O'] = False env_vars['SPY_RUN_CYTHON'] = False if self.is_sympy is True: env_vars['SPY_AUTOLOAD_PYLAB_O'] = False env_vars['SPY_SYMPY_O'] = True env_vars['SPY_RUN_CYTHON'] = False if self.is_cython is True: env_vars['SPY_AUTOLOAD_PYLAB_O'] = False env_vars['SPY_SYMPY_O'] = False env_vars['SPY_RUN_CYTHON'] = True # Add our PYTHONPATH to env_vars env_vars.update(pypath) # Making all env_vars strings for key,var in iteritems(env_vars): if PY2: # Try to convert vars first to utf-8. try: unicode_var = to_text_string(var) except UnicodeDecodeError: # If that fails, try to use the file system # encoding because one of our vars is our # PYTHONPATH, and that contains file system # directories try: unicode_var = to_unicode_from_fs(var) except: # If that also fails, make the var empty # to be able to start Spyder. # See https://stackoverflow.com/q/44506900/438386 # for details. unicode_var = '' env_vars[key] = to_binary_string(unicode_var, encoding='utf-8') else: env_vars[key] = to_text_string(var) return env_vars
[ "def", "env", "(", "self", ")", ":", "# Add our PYTHONPATH to the kernel", "pathlist", "=", "CONF", ".", "get", "(", "'main'", ",", "'spyder_pythonpath'", ",", "default", "=", "[", "]", ")", "default_interpreter", "=", "CONF", ".", "get", "(", "'main_interpret...
Env vars for kernels
[ "Env", "vars", "for", "kernels" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/utils/kernelspec.py#L76-L166
31,123
spyder-ide/spyder
spyder/plugins/projects/widgets/explorer.py
ExplorerTreeWidget.toggle_hscrollbar
def toggle_hscrollbar(self, checked): """Toggle horizontal scrollbar""" self.parent_widget.sig_option_changed.emit('show_hscrollbar', checked) self.show_hscrollbar = checked self.header().setStretchLastSection(not checked) self.header().setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel) try: self.header().setSectionResizeMode(QHeaderView.ResizeToContents) except: # support for qtpy<1.2.0 self.header().setResizeMode(QHeaderView.ResizeToContents)
python
def toggle_hscrollbar(self, checked): """Toggle horizontal scrollbar""" self.parent_widget.sig_option_changed.emit('show_hscrollbar', checked) self.show_hscrollbar = checked self.header().setStretchLastSection(not checked) self.header().setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel) try: self.header().setSectionResizeMode(QHeaderView.ResizeToContents) except: # support for qtpy<1.2.0 self.header().setResizeMode(QHeaderView.ResizeToContents)
[ "def", "toggle_hscrollbar", "(", "self", ",", "checked", ")", ":", "self", ".", "parent_widget", ".", "sig_option_changed", ".", "emit", "(", "'show_hscrollbar'", ",", "checked", ")", "self", ".", "show_hscrollbar", "=", "checked", "self", ".", "header", "(", ...
Toggle horizontal scrollbar
[ "Toggle", "horizontal", "scrollbar" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/projects/widgets/explorer.py#L60-L69
31,124
spyder-ide/spyder
spyder/plugins/projects/widgets/explorer.py
ProjectExplorerWidget.set_project_dir
def set_project_dir(self, directory): """Set the project directory""" if directory is not None: self.treewidget.set_root_path(osp.dirname(directory)) self.treewidget.set_folder_names([osp.basename(directory)]) self.treewidget.setup_project_view() try: self.treewidget.setExpanded(self.treewidget.get_index(directory), True) except TypeError: pass
python
def set_project_dir(self, directory): """Set the project directory""" if directory is not None: self.treewidget.set_root_path(osp.dirname(directory)) self.treewidget.set_folder_names([osp.basename(directory)]) self.treewidget.setup_project_view() try: self.treewidget.setExpanded(self.treewidget.get_index(directory), True) except TypeError: pass
[ "def", "set_project_dir", "(", "self", ",", "directory", ")", ":", "if", "directory", "is", "not", "None", ":", "self", ".", "treewidget", ".", "set_root_path", "(", "osp", ".", "dirname", "(", "directory", ")", ")", "self", ".", "treewidget", ".", "set_...
Set the project directory
[ "Set", "the", "project", "directory" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/projects/widgets/explorer.py#L208-L218
31,125
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.start_interpreter
def start_interpreter(self, namespace): """Start Python interpreter""" self.clear() if self.interpreter is not None: self.interpreter.closing() self.interpreter = Interpreter(namespace, self.exitfunc, SysOutput, WidgetProxy, get_debug_level()) self.interpreter.stdout_write.data_avail.connect(self.stdout_avail) self.interpreter.stderr_write.data_avail.connect(self.stderr_avail) self.interpreter.widget_proxy.sig_set_readonly.connect(self.setReadOnly) self.interpreter.widget_proxy.sig_new_prompt.connect(self.new_prompt) self.interpreter.widget_proxy.sig_edit.connect(self.edit_script) self.interpreter.widget_proxy.sig_wait_input.connect(self.wait_input) if self.multithreaded: self.interpreter.start() # Interpreter banner banner = create_banner(self.message) self.write(banner, prompt=True) # Initial commands for cmd in self.commands: self.run_command(cmd, history=False, new_prompt=False) # First prompt self.new_prompt(self.interpreter.p1) self.refresh.emit() return self.interpreter
python
def start_interpreter(self, namespace): """Start Python interpreter""" self.clear() if self.interpreter is not None: self.interpreter.closing() self.interpreter = Interpreter(namespace, self.exitfunc, SysOutput, WidgetProxy, get_debug_level()) self.interpreter.stdout_write.data_avail.connect(self.stdout_avail) self.interpreter.stderr_write.data_avail.connect(self.stderr_avail) self.interpreter.widget_proxy.sig_set_readonly.connect(self.setReadOnly) self.interpreter.widget_proxy.sig_new_prompt.connect(self.new_prompt) self.interpreter.widget_proxy.sig_edit.connect(self.edit_script) self.interpreter.widget_proxy.sig_wait_input.connect(self.wait_input) if self.multithreaded: self.interpreter.start() # Interpreter banner banner = create_banner(self.message) self.write(banner, prompt=True) # Initial commands for cmd in self.commands: self.run_command(cmd, history=False, new_prompt=False) # First prompt self.new_prompt(self.interpreter.p1) self.refresh.emit() return self.interpreter
[ "def", "start_interpreter", "(", "self", ",", "namespace", ")", ":", "self", ".", "clear", "(", ")", "if", "self", ".", "interpreter", "is", "not", "None", ":", "self", ".", "interpreter", ".", "closing", "(", ")", "self", ".", "interpreter", "=", "Int...
Start Python interpreter
[ "Start", "Python", "interpreter" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L180-L210
31,126
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.stdout_avail
def stdout_avail(self): """Data is available in stdout, let's empty the queue and write it!""" data = self.interpreter.stdout_write.empty_queue() if data: self.write(data)
python
def stdout_avail(self): """Data is available in stdout, let's empty the queue and write it!""" data = self.interpreter.stdout_write.empty_queue() if data: self.write(data)
[ "def", "stdout_avail", "(", "self", ")", ":", "data", "=", "self", ".", "interpreter", ".", "stdout_write", ".", "empty_queue", "(", ")", "if", "data", ":", "self", ".", "write", "(", "data", ")" ]
Data is available in stdout, let's empty the queue and write it!
[ "Data", "is", "available", "in", "stdout", "let", "s", "empty", "the", "queue", "and", "write", "it!" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L226-L230
31,127
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.stderr_avail
def stderr_avail(self): """Data is available in stderr, let's empty the queue and write it!""" data = self.interpreter.stderr_write.empty_queue() if data: self.write(data, error=True) self.flush(error=True)
python
def stderr_avail(self): """Data is available in stderr, let's empty the queue and write it!""" data = self.interpreter.stderr_write.empty_queue() if data: self.write(data, error=True) self.flush(error=True)
[ "def", "stderr_avail", "(", "self", ")", ":", "data", "=", "self", ".", "interpreter", ".", "stderr_write", ".", "empty_queue", "(", ")", "if", "data", ":", "self", ".", "write", "(", "data", ",", "error", "=", "True", ")", "self", ".", "flush", "(",...
Data is available in stderr, let's empty the queue and write it!
[ "Data", "is", "available", "in", "stderr", "let", "s", "empty", "the", "queue", "and", "write", "it!" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L232-L237
31,128
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.end_input
def end_input(self, cmd): """End of wait_input mode""" self.input_mode = False self.input_loop.exit() self.interpreter.widget_proxy.end_input(cmd)
python
def end_input(self, cmd): """End of wait_input mode""" self.input_mode = False self.input_loop.exit() self.interpreter.widget_proxy.end_input(cmd)
[ "def", "end_input", "(", "self", ",", "cmd", ")", ":", "self", ".", "input_mode", "=", "False", "self", ".", "input_loop", ".", "exit", "(", ")", "self", ".", "interpreter", ".", "widget_proxy", ".", "end_input", "(", "cmd", ")" ]
End of wait_input mode
[ "End", "of", "wait_input", "mode" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L250-L254
31,129
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.setup_context_menu
def setup_context_menu(self): """Reimplement PythonShellWidget method""" PythonShellWidget.setup_context_menu(self) self.help_action = create_action(self, _("Help..."), icon=ima.icon('DialogHelpButton'), triggered=self.help) self.menu.addAction(self.help_action)
python
def setup_context_menu(self): """Reimplement PythonShellWidget method""" PythonShellWidget.setup_context_menu(self) self.help_action = create_action(self, _("Help..."), icon=ima.icon('DialogHelpButton'), triggered=self.help) self.menu.addAction(self.help_action)
[ "def", "setup_context_menu", "(", "self", ")", ":", "PythonShellWidget", ".", "setup_context_menu", "(", "self", ")", "self", ".", "help_action", "=", "create_action", "(", "self", ",", "_", "(", "\"Help...\"", ")", ",", "icon", "=", "ima", ".", "icon", "(...
Reimplement PythonShellWidget method
[ "Reimplement", "PythonShellWidget", "method" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L258-L264
31,130
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.__flush_eventqueue
def __flush_eventqueue(self): """Flush keyboard event queue""" while self.eventqueue: past_event = self.eventqueue.pop(0) self.postprocess_keyevent(past_event)
python
def __flush_eventqueue(self): """Flush keyboard event queue""" while self.eventqueue: past_event = self.eventqueue.pop(0) self.postprocess_keyevent(past_event)
[ "def", "__flush_eventqueue", "(", "self", ")", ":", "while", "self", ".", "eventqueue", ":", "past_event", "=", "self", ".", "eventqueue", ".", "pop", "(", "0", ")", "self", ".", "postprocess_keyevent", "(", "past_event", ")" ]
Flush keyboard event queue
[ "Flush", "keyboard", "event", "queue" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L353-L357
31,131
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.keyboard_interrupt
def keyboard_interrupt(self): """Simulate keyboard interrupt""" if self.multithreaded: self.interpreter.raise_keyboard_interrupt() else: if self.interpreter.more: self.write_error("\nKeyboardInterrupt\n") self.interpreter.more = False self.new_prompt(self.interpreter.p1) self.interpreter.resetbuffer() else: self.interrupted = True
python
def keyboard_interrupt(self): """Simulate keyboard interrupt""" if self.multithreaded: self.interpreter.raise_keyboard_interrupt() else: if self.interpreter.more: self.write_error("\nKeyboardInterrupt\n") self.interpreter.more = False self.new_prompt(self.interpreter.p1) self.interpreter.resetbuffer() else: self.interrupted = True
[ "def", "keyboard_interrupt", "(", "self", ")", ":", "if", "self", ".", "multithreaded", ":", "self", ".", "interpreter", ".", "raise_keyboard_interrupt", "(", ")", "else", ":", "if", "self", ".", "interpreter", ".", "more", ":", "self", ".", "write_error", ...
Simulate keyboard interrupt
[ "Simulate", "keyboard", "interrupt" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L360-L371
31,132
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.iscallable
def iscallable(self, objtxt): """Is object callable?""" obj, valid = self._eval(objtxt) if valid: return callable(obj)
python
def iscallable(self, objtxt): """Is object callable?""" obj, valid = self._eval(objtxt) if valid: return callable(obj)
[ "def", "iscallable", "(", "self", ",", "objtxt", ")", ":", "obj", ",", "valid", "=", "self", ".", "_eval", "(", "objtxt", ")", "if", "valid", ":", "return", "callable", "(", "obj", ")" ]
Is object callable?
[ "Is", "object", "callable?" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L443-L447
31,133
spyder-ide/spyder
spyder/plugins/editor/panels/edgeline.py
EdgeLine.set_columns
def set_columns(self, columns): """Set edge line columns values.""" if isinstance(columns, tuple): self.columns = columns elif is_text_string(columns): self.columns = tuple(int(e) for e in columns.split(',')) self.update()
python
def set_columns(self, columns): """Set edge line columns values.""" if isinstance(columns, tuple): self.columns = columns elif is_text_string(columns): self.columns = tuple(int(e) for e in columns.split(',')) self.update()
[ "def", "set_columns", "(", "self", ",", "columns", ")", ":", "if", "isinstance", "(", "columns", ",", "tuple", ")", ":", "self", ".", "columns", "=", "columns", "elif", "is_text_string", "(", "columns", ")", ":", "self", ".", "columns", "=", "tuple", "...
Set edge line columns values.
[ "Set", "edge", "line", "columns", "values", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/edgeline.py#L49-L56
31,134
spyder-ide/spyder
spyder/utils/stringmatching.py
get_search_regex
def get_search_regex(query, ignore_case=True): """Returns a compiled regex pattern to search for query letters in order. Parameters ---------- query : str String to search in another string (in order of character occurrence). ignore_case : True Optional value perform a case insensitive search (True by default). Returns ------- pattern : SRE_Pattern Notes ----- This function adds '.*' between the query characters and compiles the resulting regular expression. """ regex_text = [char for char in query if char != ' '] regex_text = '.*'.join(regex_text) regex = r'({0})'.format(regex_text) if ignore_case: pattern = re.compile(regex, re.IGNORECASE) else: pattern = re.compile(regex) return pattern
python
def get_search_regex(query, ignore_case=True): """Returns a compiled regex pattern to search for query letters in order. Parameters ---------- query : str String to search in another string (in order of character occurrence). ignore_case : True Optional value perform a case insensitive search (True by default). Returns ------- pattern : SRE_Pattern Notes ----- This function adds '.*' between the query characters and compiles the resulting regular expression. """ regex_text = [char for char in query if char != ' '] regex_text = '.*'.join(regex_text) regex = r'({0})'.format(regex_text) if ignore_case: pattern = re.compile(regex, re.IGNORECASE) else: pattern = re.compile(regex) return pattern
[ "def", "get_search_regex", "(", "query", ",", "ignore_case", "=", "True", ")", ":", "regex_text", "=", "[", "char", "for", "char", "in", "query", "if", "char", "!=", "' '", "]", "regex_text", "=", "'.*'", ".", "join", "(", "regex_text", ")", "regex", "...
Returns a compiled regex pattern to search for query letters in order. Parameters ---------- query : str String to search in another string (in order of character occurrence). ignore_case : True Optional value perform a case insensitive search (True by default). Returns ------- pattern : SRE_Pattern Notes ----- This function adds '.*' between the query characters and compiles the resulting regular expression.
[ "Returns", "a", "compiled", "regex", "pattern", "to", "search", "for", "query", "letters", "in", "order", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/stringmatching.py#L18-L47
31,135
spyder-ide/spyder
spyder/utils/stringmatching.py
get_search_scores
def get_search_scores(query, choices, ignore_case=True, template='{}', valid_only=False, sort=False): """Search for query inside choices and return a list of tuples. Returns a list of tuples of text with the enriched text (if a template is provided) and a score for the match. Lower scores imply a better match. Parameters ---------- query : str String with letters to search in each choice (in order of appearance). choices : list of str List of sentences/words in which to search for the 'query' letters. ignore_case : bool, optional Optional value perform a case insensitive search (True by default). template : str, optional Optional template string to surround letters found in choices. This is useful when using a rich text editor ('{}' by default). Examples: '<b>{}</b>', '<code>{}</code>', '<i>{}</i>' Returns ------- results : list of tuples List of tuples where the first item is the text (enriched if a template was used) and a search score. Lower scores means better match. """ # First remove spaces from query query = query.replace(' ', '') pattern = get_search_regex(query, ignore_case) results = [] for choice in choices: r = re.search(pattern, choice) if query and r: result = get_search_score(query, choice, ignore_case=ignore_case, apply_regex=False, template=template) else: if query: result = (choice, choice, NOT_FOUND_SCORE) else: result = (choice, choice, NO_SCORE) if valid_only: if result[-1] != NOT_FOUND_SCORE: results.append(result) else: results.append(result) if sort: results = sorted(results, key=lambda row: row[-1]) return results
python
def get_search_scores(query, choices, ignore_case=True, template='{}', valid_only=False, sort=False): """Search for query inside choices and return a list of tuples. Returns a list of tuples of text with the enriched text (if a template is provided) and a score for the match. Lower scores imply a better match. Parameters ---------- query : str String with letters to search in each choice (in order of appearance). choices : list of str List of sentences/words in which to search for the 'query' letters. ignore_case : bool, optional Optional value perform a case insensitive search (True by default). template : str, optional Optional template string to surround letters found in choices. This is useful when using a rich text editor ('{}' by default). Examples: '<b>{}</b>', '<code>{}</code>', '<i>{}</i>' Returns ------- results : list of tuples List of tuples where the first item is the text (enriched if a template was used) and a search score. Lower scores means better match. """ # First remove spaces from query query = query.replace(' ', '') pattern = get_search_regex(query, ignore_case) results = [] for choice in choices: r = re.search(pattern, choice) if query and r: result = get_search_score(query, choice, ignore_case=ignore_case, apply_regex=False, template=template) else: if query: result = (choice, choice, NOT_FOUND_SCORE) else: result = (choice, choice, NO_SCORE) if valid_only: if result[-1] != NOT_FOUND_SCORE: results.append(result) else: results.append(result) if sort: results = sorted(results, key=lambda row: row[-1]) return results
[ "def", "get_search_scores", "(", "query", ",", "choices", ",", "ignore_case", "=", "True", ",", "template", "=", "'{}'", ",", "valid_only", "=", "False", ",", "sort", "=", "False", ")", ":", "# First remove spaces from query", "query", "=", "query", ".", "re...
Search for query inside choices and return a list of tuples. Returns a list of tuples of text with the enriched text (if a template is provided) and a score for the match. Lower scores imply a better match. Parameters ---------- query : str String with letters to search in each choice (in order of appearance). choices : list of str List of sentences/words in which to search for the 'query' letters. ignore_case : bool, optional Optional value perform a case insensitive search (True by default). template : str, optional Optional template string to surround letters found in choices. This is useful when using a rich text editor ('{}' by default). Examples: '<b>{}</b>', '<code>{}</code>', '<i>{}</i>' Returns ------- results : list of tuples List of tuples where the first item is the text (enriched if a template was used) and a search score. Lower scores means better match.
[ "Search", "for", "query", "inside", "choices", "and", "return", "a", "list", "of", "tuples", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/stringmatching.py#L179-L230
31,136
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
is_start_of_function
def is_start_of_function(text): """Return True if text is the beginning of the function definition.""" if isinstance(text, str) or isinstance(text, unicode): function_prefix = ['def', 'async def'] text = text.lstrip() for prefix in function_prefix: if text.startswith(prefix): return True return False
python
def is_start_of_function(text): """Return True if text is the beginning of the function definition.""" if isinstance(text, str) or isinstance(text, unicode): function_prefix = ['def', 'async def'] text = text.lstrip() for prefix in function_prefix: if text.startswith(prefix): return True return False
[ "def", "is_start_of_function", "(", "text", ")", ":", "if", "isinstance", "(", "text", ",", "str", ")", "or", "isinstance", "(", "text", ",", "unicode", ")", ":", "function_prefix", "=", "[", "'def'", ",", "'async def'", "]", "text", "=", "text", ".", ...
Return True if text is the beginning of the function definition.
[ "Return", "True", "if", "text", "is", "the", "beginning", "of", "the", "function", "definition", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L23-L33
31,137
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
DocstringWriterExtension.get_function_definition_from_first_line
def get_function_definition_from_first_line(self): """Get func def when the cursor is located on the first def line.""" document = self.code_editor.document() cursor = QTextCursor( document.findBlockByLineNumber(self.line_number_cursor - 1)) func_text = '' func_indent = '' is_first_line = True line_number = cursor.blockNumber() + 1 number_of_lines = self.code_editor.blockCount() remain_lines = number_of_lines - line_number + 1 number_of_lines_of_function = 0 for __ in range(min(remain_lines, 20)): cur_text = to_text_string(cursor.block().text()).rstrip() if is_first_line: if not is_start_of_function(cur_text): return None func_indent = get_indent(cur_text) is_first_line = False else: cur_indent = get_indent(cur_text) if cur_indent <= func_indent: return None if is_start_of_function(cur_text): return None if cur_text.strip == '': return None if cur_text[-1] == '\\': cur_text = cur_text[:-1] func_text += cur_text number_of_lines_of_function += 1 if cur_text.endswith(':'): return func_text, number_of_lines_of_function cursor.movePosition(QTextCursor.NextBlock) return None
python
def get_function_definition_from_first_line(self): """Get func def when the cursor is located on the first def line.""" document = self.code_editor.document() cursor = QTextCursor( document.findBlockByLineNumber(self.line_number_cursor - 1)) func_text = '' func_indent = '' is_first_line = True line_number = cursor.blockNumber() + 1 number_of_lines = self.code_editor.blockCount() remain_lines = number_of_lines - line_number + 1 number_of_lines_of_function = 0 for __ in range(min(remain_lines, 20)): cur_text = to_text_string(cursor.block().text()).rstrip() if is_first_line: if not is_start_of_function(cur_text): return None func_indent = get_indent(cur_text) is_first_line = False else: cur_indent = get_indent(cur_text) if cur_indent <= func_indent: return None if is_start_of_function(cur_text): return None if cur_text.strip == '': return None if cur_text[-1] == '\\': cur_text = cur_text[:-1] func_text += cur_text number_of_lines_of_function += 1 if cur_text.endswith(':'): return func_text, number_of_lines_of_function cursor.movePosition(QTextCursor.NextBlock) return None
[ "def", "get_function_definition_from_first_line", "(", "self", ")", ":", "document", "=", "self", ".", "code_editor", ".", "document", "(", ")", "cursor", "=", "QTextCursor", "(", "document", ".", "findBlockByLineNumber", "(", "self", ".", "line_number_cursor", "-...
Get func def when the cursor is located on the first def line.
[ "Get", "func", "def", "when", "the", "cursor", "is", "located", "on", "the", "first", "def", "line", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L70-L115
31,138
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
DocstringWriterExtension.get_function_definition_from_below_last_line
def get_function_definition_from_below_last_line(self): """Get func def when the cursor is located below the last def line.""" cursor = self.code_editor.textCursor() func_text = '' is_first_line = True line_number = cursor.blockNumber() + 1 number_of_lines_of_function = 0 for idx in range(min(line_number, 20)): if cursor.block().blockNumber() == 0: return None cursor.movePosition(QTextCursor.PreviousBlock) prev_text = to_text_string(cursor.block().text()).rstrip() if is_first_line: if not prev_text.endswith(':'): return None is_first_line = False elif prev_text.endswith(':') or prev_text == '': return None if prev_text[-1] == '\\': prev_text = prev_text[:-1] func_text = prev_text + func_text number_of_lines_of_function += 1 if is_start_of_function(prev_text): return func_text, number_of_lines_of_function return None
python
def get_function_definition_from_below_last_line(self): """Get func def when the cursor is located below the last def line.""" cursor = self.code_editor.textCursor() func_text = '' is_first_line = True line_number = cursor.blockNumber() + 1 number_of_lines_of_function = 0 for idx in range(min(line_number, 20)): if cursor.block().blockNumber() == 0: return None cursor.movePosition(QTextCursor.PreviousBlock) prev_text = to_text_string(cursor.block().text()).rstrip() if is_first_line: if not prev_text.endswith(':'): return None is_first_line = False elif prev_text.endswith(':') or prev_text == '': return None if prev_text[-1] == '\\': prev_text = prev_text[:-1] func_text = prev_text + func_text number_of_lines_of_function += 1 if is_start_of_function(prev_text): return func_text, number_of_lines_of_function return None
[ "def", "get_function_definition_from_below_last_line", "(", "self", ")", ":", "cursor", "=", "self", ".", "code_editor", ".", "textCursor", "(", ")", "func_text", "=", "''", "is_first_line", "=", "True", "line_number", "=", "cursor", ".", "blockNumber", "(", ")"...
Get func def when the cursor is located below the last def line.
[ "Get", "func", "def", "when", "the", "cursor", "is", "located", "below", "the", "last", "def", "line", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L117-L148
31,139
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
DocstringWriterExtension.get_function_body
def get_function_body(self, func_indent): """Get the function body text.""" cursor = self.code_editor.textCursor() line_number = cursor.blockNumber() + 1 number_of_lines = self.code_editor.blockCount() body_list = [] for idx in range(number_of_lines - line_number + 1): text = to_text_string(cursor.block().text()) text_indent = get_indent(text) if text.strip() == '': pass elif len(text_indent) <= len(func_indent): break body_list.append(text) cursor.movePosition(QTextCursor.NextBlock) return '\n'.join(body_list)
python
def get_function_body(self, func_indent): """Get the function body text.""" cursor = self.code_editor.textCursor() line_number = cursor.blockNumber() + 1 number_of_lines = self.code_editor.blockCount() body_list = [] for idx in range(number_of_lines - line_number + 1): text = to_text_string(cursor.block().text()) text_indent = get_indent(text) if text.strip() == '': pass elif len(text_indent) <= len(func_indent): break body_list.append(text) cursor.movePosition(QTextCursor.NextBlock) return '\n'.join(body_list)
[ "def", "get_function_body", "(", "self", ",", "func_indent", ")", ":", "cursor", "=", "self", ".", "code_editor", ".", "textCursor", "(", ")", "line_number", "=", "cursor", ".", "blockNumber", "(", ")", "+", "1", "number_of_lines", "=", "self", ".", "code_...
Get the function body text.
[ "Get", "the", "function", "body", "text", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L150-L170
31,140
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
DocstringWriterExtension.write_docstring
def write_docstring(self): """Write docstring to editor.""" line_to_cursor = self.code_editor.get_text('sol', 'cursor') if self.is_beginning_triple_quotes(line_to_cursor): cursor = self.code_editor.textCursor() prev_pos = cursor.position() quote = line_to_cursor[-1] docstring_type = CONF.get('editor', 'docstring_type') docstring = self._generate_docstring(docstring_type, quote) if docstring: self.code_editor.insert_text(docstring) cursor = self.code_editor.textCursor() cursor.setPosition(prev_pos, QTextCursor.KeepAnchor) cursor.movePosition(QTextCursor.NextBlock) cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor) cursor.clearSelection() self.code_editor.setTextCursor(cursor) return True return False
python
def write_docstring(self): """Write docstring to editor.""" line_to_cursor = self.code_editor.get_text('sol', 'cursor') if self.is_beginning_triple_quotes(line_to_cursor): cursor = self.code_editor.textCursor() prev_pos = cursor.position() quote = line_to_cursor[-1] docstring_type = CONF.get('editor', 'docstring_type') docstring = self._generate_docstring(docstring_type, quote) if docstring: self.code_editor.insert_text(docstring) cursor = self.code_editor.textCursor() cursor.setPosition(prev_pos, QTextCursor.KeepAnchor) cursor.movePosition(QTextCursor.NextBlock) cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor) cursor.clearSelection() self.code_editor.setTextCursor(cursor) return True return False
[ "def", "write_docstring", "(", "self", ")", ":", "line_to_cursor", "=", "self", ".", "code_editor", ".", "get_text", "(", "'sol'", ",", "'cursor'", ")", "if", "self", ".", "is_beginning_triple_quotes", "(", "line_to_cursor", ")", ":", "cursor", "=", "self", ...
Write docstring to editor.
[ "Write", "docstring", "to", "editor", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L172-L195
31,141
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
DocstringWriterExtension.write_docstring_for_shortcut
def write_docstring_for_shortcut(self): """Write docstring to editor by shortcut of code editor.""" # cursor placed below function definition result = self.get_function_definition_from_below_last_line() if result is not None: __, number_of_lines_of_function = result cursor = self.code_editor.textCursor() for __ in range(number_of_lines_of_function): cursor.movePosition(QTextCursor.PreviousBlock) self.code_editor.setTextCursor(cursor) cursor = self.code_editor.textCursor() self.line_number_cursor = cursor.blockNumber() + 1 self.write_docstring_at_first_line_of_function()
python
def write_docstring_for_shortcut(self): """Write docstring to editor by shortcut of code editor.""" # cursor placed below function definition result = self.get_function_definition_from_below_last_line() if result is not None: __, number_of_lines_of_function = result cursor = self.code_editor.textCursor() for __ in range(number_of_lines_of_function): cursor.movePosition(QTextCursor.PreviousBlock) self.code_editor.setTextCursor(cursor) cursor = self.code_editor.textCursor() self.line_number_cursor = cursor.blockNumber() + 1 self.write_docstring_at_first_line_of_function()
[ "def", "write_docstring_for_shortcut", "(", "self", ")", ":", "# cursor placed below function definition\r", "result", "=", "self", ".", "get_function_definition_from_below_last_line", "(", ")", "if", "result", "is", "not", "None", ":", "__", ",", "number_of_lines_of_func...
Write docstring to editor by shortcut of code editor.
[ "Write", "docstring", "to", "editor", "by", "shortcut", "of", "code", "editor", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L222-L237
31,142
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
DocstringWriterExtension._generate_numpy_doc
def _generate_numpy_doc(self, func_info): """Generate a docstring of numpy type.""" numpy_doc = '' arg_names = func_info.arg_name_list arg_types = func_info.arg_type_list arg_values = func_info.arg_value_list if len(arg_names) > 0 and arg_names[0] == 'self': del arg_names[0] del arg_types[0] del arg_values[0] indent1 = func_info.func_indent + self.code_editor.indent_chars indent2 = func_info.func_indent + self.code_editor.indent_chars * 2 numpy_doc += '\n{}\n'.format(indent1) if len(arg_names) > 0: numpy_doc += '\n{}Parameters'.format(indent1) numpy_doc += '\n{}----------\n'.format(indent1) arg_text = '' for arg_name, arg_type, arg_value in zip(arg_names, arg_types, arg_values): arg_text += '{}{} : '.format(indent1, arg_name) if arg_type: arg_text += '{}'.format(arg_type) else: arg_text += 'TYPE' if arg_value: arg_text += ', optional' arg_text += '\n{}DESCRIPTION.'.format(indent2) if arg_value: arg_value = arg_value.replace(self.quote3, self.quote3_other) arg_text += ' The default is {}.'.format(arg_value) arg_text += '\n' numpy_doc += arg_text if func_info.raise_list: numpy_doc += '\n{}Raises'.format(indent1) numpy_doc += '\n{}------'.format(indent1) for raise_type in func_info.raise_list: numpy_doc += '\n{}{}'.format(indent1, raise_type) numpy_doc += '\n{}DESCRIPTION.'.format(indent2) numpy_doc += '\n' numpy_doc += '\n' if func_info.has_yield: header = '{0}Yields\n{0}------\n'.format(indent1) else: header = '{0}Returns\n{0}-------\n'.format(indent1) return_type_annotated = func_info.return_type_annotated if return_type_annotated: return_section = '{}{}{}'.format(header, indent1, return_type_annotated) return_section += '\n{}DESCRIPTION.'.format(indent2) else: return_element_type = indent1 + '{return_type}\n' + indent2 + \ 'DESCRIPTION.' placeholder = return_element_type.format(return_type='TYPE') return_element_name = indent1 + '{return_name} : ' + \ placeholder.lstrip() try: return_section = self._generate_docstring_return_section( func_info.return_value_in_body, header, return_element_name, return_element_type, placeholder, indent1) except (ValueError, IndexError): return_section = '{}{}None.'.format(header, indent1) numpy_doc += return_section numpy_doc += '\n\n{}{}'.format(indent1, self.quote3) return numpy_doc
python
def _generate_numpy_doc(self, func_info): """Generate a docstring of numpy type.""" numpy_doc = '' arg_names = func_info.arg_name_list arg_types = func_info.arg_type_list arg_values = func_info.arg_value_list if len(arg_names) > 0 and arg_names[0] == 'self': del arg_names[0] del arg_types[0] del arg_values[0] indent1 = func_info.func_indent + self.code_editor.indent_chars indent2 = func_info.func_indent + self.code_editor.indent_chars * 2 numpy_doc += '\n{}\n'.format(indent1) if len(arg_names) > 0: numpy_doc += '\n{}Parameters'.format(indent1) numpy_doc += '\n{}----------\n'.format(indent1) arg_text = '' for arg_name, arg_type, arg_value in zip(arg_names, arg_types, arg_values): arg_text += '{}{} : '.format(indent1, arg_name) if arg_type: arg_text += '{}'.format(arg_type) else: arg_text += 'TYPE' if arg_value: arg_text += ', optional' arg_text += '\n{}DESCRIPTION.'.format(indent2) if arg_value: arg_value = arg_value.replace(self.quote3, self.quote3_other) arg_text += ' The default is {}.'.format(arg_value) arg_text += '\n' numpy_doc += arg_text if func_info.raise_list: numpy_doc += '\n{}Raises'.format(indent1) numpy_doc += '\n{}------'.format(indent1) for raise_type in func_info.raise_list: numpy_doc += '\n{}{}'.format(indent1, raise_type) numpy_doc += '\n{}DESCRIPTION.'.format(indent2) numpy_doc += '\n' numpy_doc += '\n' if func_info.has_yield: header = '{0}Yields\n{0}------\n'.format(indent1) else: header = '{0}Returns\n{0}-------\n'.format(indent1) return_type_annotated = func_info.return_type_annotated if return_type_annotated: return_section = '{}{}{}'.format(header, indent1, return_type_annotated) return_section += '\n{}DESCRIPTION.'.format(indent2) else: return_element_type = indent1 + '{return_type}\n' + indent2 + \ 'DESCRIPTION.' placeholder = return_element_type.format(return_type='TYPE') return_element_name = indent1 + '{return_name} : ' + \ placeholder.lstrip() try: return_section = self._generate_docstring_return_section( func_info.return_value_in_body, header, return_element_name, return_element_type, placeholder, indent1) except (ValueError, IndexError): return_section = '{}{}None.'.format(header, indent1) numpy_doc += return_section numpy_doc += '\n\n{}{}'.format(indent1, self.quote3) return numpy_doc
[ "def", "_generate_numpy_doc", "(", "self", ",", "func_info", ")", ":", "numpy_doc", "=", "''", "arg_names", "=", "func_info", ".", "arg_name_list", "arg_types", "=", "func_info", ".", "arg_type_list", "arg_values", "=", "func_info", ".", "arg_value_list", "if", ...
Generate a docstring of numpy type.
[ "Generate", "a", "docstring", "of", "numpy", "type", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L268-L349
31,143
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
DocstringWriterExtension.find_top_level_bracket_locations
def find_top_level_bracket_locations(string_toparse): """Get the locations of top-level brackets in a string.""" bracket_stack = [] replace_args_list = [] bracket_type = None literal_type = '' brackets = {'(': ')', '[': ']', '{': '}'} for idx, character in enumerate(string_toparse): if (not bracket_stack and character in brackets.keys() or character == bracket_type): bracket_stack.append(idx) bracket_type = character elif bracket_type and character == brackets[bracket_type]: begin_idx = bracket_stack.pop() if not bracket_stack: if not literal_type: if bracket_type == '(': literal_type = '(None)' elif bracket_type == '[': literal_type = '[list]' elif bracket_type == '{': if idx - begin_idx <= 1: literal_type = '{dict}' else: literal_type = '{set}' replace_args_list.append( (string_toparse[begin_idx:idx + 1], literal_type, 1)) bracket_type = None literal_type = '' elif len(bracket_stack) == 1: if bracket_type == '(' and character == ',': literal_type = '(tuple)' elif bracket_type == '{' and character == ':': literal_type = '{dict}' elif bracket_type == '(' and character == ':': literal_type = '[slice]' if bracket_stack: raise IndexError('Bracket mismatch') for replace_args in replace_args_list: string_toparse = string_toparse.replace(*replace_args) return string_toparse
python
def find_top_level_bracket_locations(string_toparse): """Get the locations of top-level brackets in a string.""" bracket_stack = [] replace_args_list = [] bracket_type = None literal_type = '' brackets = {'(': ')', '[': ']', '{': '}'} for idx, character in enumerate(string_toparse): if (not bracket_stack and character in brackets.keys() or character == bracket_type): bracket_stack.append(idx) bracket_type = character elif bracket_type and character == brackets[bracket_type]: begin_idx = bracket_stack.pop() if not bracket_stack: if not literal_type: if bracket_type == '(': literal_type = '(None)' elif bracket_type == '[': literal_type = '[list]' elif bracket_type == '{': if idx - begin_idx <= 1: literal_type = '{dict}' else: literal_type = '{set}' replace_args_list.append( (string_toparse[begin_idx:idx + 1], literal_type, 1)) bracket_type = None literal_type = '' elif len(bracket_stack) == 1: if bracket_type == '(' and character == ',': literal_type = '(tuple)' elif bracket_type == '{' and character == ':': literal_type = '{dict}' elif bracket_type == '(' and character == ':': literal_type = '[slice]' if bracket_stack: raise IndexError('Bracket mismatch') for replace_args in replace_args_list: string_toparse = string_toparse.replace(*replace_args) return string_toparse
[ "def", "find_top_level_bracket_locations", "(", "string_toparse", ")", ":", "bracket_stack", "=", "[", "]", "replace_args_list", "=", "[", "]", "bracket_type", "=", "None", "literal_type", "=", "''", "brackets", "=", "{", "'('", ":", "')'", ",", "'['", ":", ...
Get the locations of top-level brackets in a string.
[ "Get", "the", "locations", "of", "top", "-", "level", "brackets", "in", "a", "string", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L434-L476
31,144
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
DocstringWriterExtension.parse_return_elements
def parse_return_elements(return_vals_group, return_element_name, return_element_type, placeholder): """Return the appropriate text for a group of return elements.""" all_eq = (return_vals_group.count(return_vals_group[0]) == len(return_vals_group)) if all([{'[list]', '(tuple)', '{dict}', '{set}'}.issuperset( return_vals_group)]) and all_eq: return return_element_type.format( return_type=return_vals_group[0][1:-1]) # Output placeholder if special Python chars present in name py_chars = {' ', '+', '-', '*', '/', '%', '@', '<', '>', '&', '|', '^', '~', '=', ',', ':', ';', '#', '(', '[', '{', '}', ']', ')', } if any([any([py_char in return_val for py_char in py_chars]) for return_val in return_vals_group]): return placeholder # Output str type and no name if only string literals if all(['"' in return_val or '\'' in return_val for return_val in return_vals_group]): return return_element_type.format(return_type='str') # Output bool type and no name if only bool literals if {'True', 'False'}.issuperset(return_vals_group): return return_element_type.format(return_type='bool') # Output numeric types and no name if only numeric literals try: [float(return_val) for return_val in return_vals_group] num_not_int = 0 for return_val in return_vals_group: try: int(return_val) except ValueError: # If not an integer (EAFP) num_not_int = num_not_int + 1 if num_not_int == 0: return return_element_type.format(return_type='int') elif num_not_int == len(return_vals_group): return return_element_type.format(return_type='float') else: return return_element_type.format(return_type='numeric') except ValueError: # Not a numeric if float conversion didn't work pass # If names are not equal, don't contain "." or are a builtin if ({'self', 'cls', 'None'}.isdisjoint(return_vals_group) and all_eq and all(['.' not in return_val for return_val in return_vals_group])): return return_element_name.format(return_name=return_vals_group[0]) return placeholder
python
def parse_return_elements(return_vals_group, return_element_name, return_element_type, placeholder): """Return the appropriate text for a group of return elements.""" all_eq = (return_vals_group.count(return_vals_group[0]) == len(return_vals_group)) if all([{'[list]', '(tuple)', '{dict}', '{set}'}.issuperset( return_vals_group)]) and all_eq: return return_element_type.format( return_type=return_vals_group[0][1:-1]) # Output placeholder if special Python chars present in name py_chars = {' ', '+', '-', '*', '/', '%', '@', '<', '>', '&', '|', '^', '~', '=', ',', ':', ';', '#', '(', '[', '{', '}', ']', ')', } if any([any([py_char in return_val for py_char in py_chars]) for return_val in return_vals_group]): return placeholder # Output str type and no name if only string literals if all(['"' in return_val or '\'' in return_val for return_val in return_vals_group]): return return_element_type.format(return_type='str') # Output bool type and no name if only bool literals if {'True', 'False'}.issuperset(return_vals_group): return return_element_type.format(return_type='bool') # Output numeric types and no name if only numeric literals try: [float(return_val) for return_val in return_vals_group] num_not_int = 0 for return_val in return_vals_group: try: int(return_val) except ValueError: # If not an integer (EAFP) num_not_int = num_not_int + 1 if num_not_int == 0: return return_element_type.format(return_type='int') elif num_not_int == len(return_vals_group): return return_element_type.format(return_type='float') else: return return_element_type.format(return_type='numeric') except ValueError: # Not a numeric if float conversion didn't work pass # If names are not equal, don't contain "." or are a builtin if ({'self', 'cls', 'None'}.isdisjoint(return_vals_group) and all_eq and all(['.' not in return_val for return_val in return_vals_group])): return return_element_name.format(return_name=return_vals_group[0]) return placeholder
[ "def", "parse_return_elements", "(", "return_vals_group", ",", "return_element_name", ",", "return_element_type", ",", "placeholder", ")", ":", "all_eq", "=", "(", "return_vals_group", ".", "count", "(", "return_vals_group", "[", "0", "]", ")", "==", "len", "(", ...
Return the appropriate text for a group of return elements.
[ "Return", "the", "appropriate", "text", "for", "a", "group", "of", "return", "elements", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L479-L524
31,145
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
FunctionInfo.is_char_in_pairs
def is_char_in_pairs(pos_char, pairs): """Return True if the charactor is in pairs of brackets or quotes.""" for pos_left, pos_right in pairs.items(): if pos_left < pos_char < pos_right: return True return False
python
def is_char_in_pairs(pos_char, pairs): """Return True if the charactor is in pairs of brackets or quotes.""" for pos_left, pos_right in pairs.items(): if pos_left < pos_char < pos_right: return True return False
[ "def", "is_char_in_pairs", "(", "pos_char", ",", "pairs", ")", ":", "for", "pos_left", ",", "pos_right", "in", "pairs", ".", "items", "(", ")", ":", "if", "pos_left", "<", "pos_char", "<", "pos_right", ":", "return", "True", "return", "False" ]
Return True if the charactor is in pairs of brackets or quotes.
[ "Return", "True", "if", "the", "charactor", "is", "in", "pairs", "of", "brackets", "or", "quotes", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L610-L616
31,146
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
FunctionInfo._find_quote_position
def _find_quote_position(text): """Return the start and end position of pairs of quotes.""" pos = {} is_found_left_quote = False for idx, character in enumerate(text): if is_found_left_quote is False: if character == "'" or character == '"': is_found_left_quote = True quote = character left_pos = idx else: if character == quote and text[idx - 1] != '\\': pos[left_pos] = idx is_found_left_quote = False if is_found_left_quote: raise IndexError("No matching close quote at: " + str(left_pos)) return pos
python
def _find_quote_position(text): """Return the start and end position of pairs of quotes.""" pos = {} is_found_left_quote = False for idx, character in enumerate(text): if is_found_left_quote is False: if character == "'" or character == '"': is_found_left_quote = True quote = character left_pos = idx else: if character == quote and text[idx - 1] != '\\': pos[left_pos] = idx is_found_left_quote = False if is_found_left_quote: raise IndexError("No matching close quote at: " + str(left_pos)) return pos
[ "def", "_find_quote_position", "(", "text", ")", ":", "pos", "=", "{", "}", "is_found_left_quote", "=", "False", "for", "idx", ",", "character", "in", "enumerate", "(", "text", ")", ":", "if", "is_found_left_quote", "is", "False", ":", "if", "character", "...
Return the start and end position of pairs of quotes.
[ "Return", "the", "start", "and", "end", "position", "of", "pairs", "of", "quotes", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L619-L638
31,147
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
FunctionInfo.split_arg_to_name_type_value
def split_arg_to_name_type_value(self, args_list): """Split argument text to name, type, value.""" for arg in args_list: arg_type = None arg_value = None has_type = False has_value = False pos_colon = arg.find(':') pos_equal = arg.find('=') if pos_equal > -1: has_value = True if pos_colon > -1: if not has_value: has_type = True elif pos_equal > pos_colon: # exception for def foo(arg1=":") has_type = True if has_value and has_type: arg_name = arg[0:pos_colon].strip() arg_type = arg[pos_colon + 1:pos_equal].strip() arg_value = arg[pos_equal + 1:].strip() elif not has_value and has_type: arg_name = arg[0:pos_colon].strip() arg_type = arg[pos_colon + 1:].strip() elif has_value and not has_type: arg_name = arg[0:pos_equal].strip() arg_value = arg[pos_equal + 1:].strip() else: arg_name = arg.strip() self.arg_name_list.append(arg_name) self.arg_type_list.append(arg_type) self.arg_value_list.append(arg_value)
python
def split_arg_to_name_type_value(self, args_list): """Split argument text to name, type, value.""" for arg in args_list: arg_type = None arg_value = None has_type = False has_value = False pos_colon = arg.find(':') pos_equal = arg.find('=') if pos_equal > -1: has_value = True if pos_colon > -1: if not has_value: has_type = True elif pos_equal > pos_colon: # exception for def foo(arg1=":") has_type = True if has_value and has_type: arg_name = arg[0:pos_colon].strip() arg_type = arg[pos_colon + 1:pos_equal].strip() arg_value = arg[pos_equal + 1:].strip() elif not has_value and has_type: arg_name = arg[0:pos_colon].strip() arg_type = arg[pos_colon + 1:].strip() elif has_value and not has_type: arg_name = arg[0:pos_equal].strip() arg_value = arg[pos_equal + 1:].strip() else: arg_name = arg.strip() self.arg_name_list.append(arg_name) self.arg_type_list.append(arg_type) self.arg_value_list.append(arg_value)
[ "def", "split_arg_to_name_type_value", "(", "self", ",", "args_list", ")", ":", "for", "arg", "in", "args_list", ":", "arg_type", "=", "None", "arg_value", "=", "None", "has_type", "=", "False", "has_value", "=", "False", "pos_colon", "=", "arg", ".", "find"...
Split argument text to name, type, value.
[ "Split", "argument", "text", "to", "name", "type", "value", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L667-L703
31,148
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
FunctionInfo.split_args_text_to_list
def split_args_text_to_list(self, args_text): """Split the text including multiple arguments to list. This function uses a comma to separate arguments and ignores a comma in brackets ans quotes. """ args_list = [] idx_find_start = 0 idx_arg_start = 0 try: pos_quote = self._find_quote_position(args_text) pos_round = self._find_bracket_position(args_text, '(', ')', pos_quote) pos_curly = self._find_bracket_position(args_text, '{', '}', pos_quote) pos_square = self._find_bracket_position(args_text, '[', ']', pos_quote) except IndexError: return None while True: pos_comma = args_text.find(',', idx_find_start) if pos_comma == -1: break idx_find_start = pos_comma + 1 if self.is_char_in_pairs(pos_comma, pos_round) or \ self.is_char_in_pairs(pos_comma, pos_curly) or \ self.is_char_in_pairs(pos_comma, pos_square) or \ self.is_char_in_pairs(pos_comma, pos_quote): continue args_list.append(args_text[idx_arg_start:pos_comma]) idx_arg_start = pos_comma + 1 if idx_arg_start < len(args_text): args_list.append(args_text[idx_arg_start:]) return args_list
python
def split_args_text_to_list(self, args_text): """Split the text including multiple arguments to list. This function uses a comma to separate arguments and ignores a comma in brackets ans quotes. """ args_list = [] idx_find_start = 0 idx_arg_start = 0 try: pos_quote = self._find_quote_position(args_text) pos_round = self._find_bracket_position(args_text, '(', ')', pos_quote) pos_curly = self._find_bracket_position(args_text, '{', '}', pos_quote) pos_square = self._find_bracket_position(args_text, '[', ']', pos_quote) except IndexError: return None while True: pos_comma = args_text.find(',', idx_find_start) if pos_comma == -1: break idx_find_start = pos_comma + 1 if self.is_char_in_pairs(pos_comma, pos_round) or \ self.is_char_in_pairs(pos_comma, pos_curly) or \ self.is_char_in_pairs(pos_comma, pos_square) or \ self.is_char_in_pairs(pos_comma, pos_quote): continue args_list.append(args_text[idx_arg_start:pos_comma]) idx_arg_start = pos_comma + 1 if idx_arg_start < len(args_text): args_list.append(args_text[idx_arg_start:]) return args_list
[ "def", "split_args_text_to_list", "(", "self", ",", "args_text", ")", ":", "args_list", "=", "[", "]", "idx_find_start", "=", "0", "idx_arg_start", "=", "0", "try", ":", "pos_quote", "=", "self", ".", "_find_quote_position", "(", "args_text", ")", "pos_round",...
Split the text including multiple arguments to list. This function uses a comma to separate arguments and ignores a comma in brackets ans quotes.
[ "Split", "the", "text", "including", "multiple", "arguments", "to", "list", ".", "This", "function", "uses", "a", "comma", "to", "separate", "arguments", "and", "ignores", "a", "comma", "in", "brackets", "ans", "quotes", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L705-L746
31,149
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
FunctionInfo.parse_def
def parse_def(self, text): """Parse the function definition text.""" self.__init__() if not is_start_of_function(text): return self.func_indent = get_indent(text) text = text.strip() text = text.replace('\r\n', '') text = text.replace('\n', '') return_type_re = re.search(r'->[ ]*([a-zA-Z0-9_,()\[\] ]*):$', text) if return_type_re: self.return_type_annotated = return_type_re.group(1) text_end = text.rfind(return_type_re.group(0)) else: self.return_type_annotated = None text_end = len(text) pos_args_start = text.find('(') + 1 pos_args_end = text.rfind(')', pos_args_start, text_end) self.args_text = text[pos_args_start:pos_args_end] args_list = self.split_args_text_to_list(self.args_text) if args_list is not None: self.has_info = True self.split_arg_to_name_type_value(args_list)
python
def parse_def(self, text): """Parse the function definition text.""" self.__init__() if not is_start_of_function(text): return self.func_indent = get_indent(text) text = text.strip() text = text.replace('\r\n', '') text = text.replace('\n', '') return_type_re = re.search(r'->[ ]*([a-zA-Z0-9_,()\[\] ]*):$', text) if return_type_re: self.return_type_annotated = return_type_re.group(1) text_end = text.rfind(return_type_re.group(0)) else: self.return_type_annotated = None text_end = len(text) pos_args_start = text.find('(') + 1 pos_args_end = text.rfind(')', pos_args_start, text_end) self.args_text = text[pos_args_start:pos_args_end] args_list = self.split_args_text_to_list(self.args_text) if args_list is not None: self.has_info = True self.split_arg_to_name_type_value(args_list)
[ "def", "parse_def", "(", "self", ",", "text", ")", ":", "self", ".", "__init__", "(", ")", "if", "not", "is_start_of_function", "(", "text", ")", ":", "return", "self", ".", "func_indent", "=", "get_indent", "(", "text", ")", "text", "=", "text", ".", ...
Parse the function definition text.
[ "Parse", "the", "function", "definition", "text", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L748-L777
31,150
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
FunctionInfo.parse_body
def parse_body(self, text): """Parse the function body text.""" re_raise = re.findall(r'[ \t]raise ([a-zA-Z0-9_]*)', text) if len(re_raise) > 0: self.raise_list = [x.strip() for x in re_raise] # remove duplicates from list while keeping it in the order # in python 2.7 # stackoverflow.com/questions/7961363/removing-duplicates-in-lists self.raise_list = list(OrderedDict.fromkeys(self.raise_list)) re_yield = re.search(r'[ \t]yield ', text) if re_yield: self.has_yield = True # get return value pattern_return = r'return |yield ' line_list = text.split('\n') is_found_return = False line_return_tmp = '' for line in line_list: line = line.strip() if is_found_return is False: if re.match(pattern_return, line): is_found_return = True if is_found_return: line_return_tmp += line # check the integrity of line try: pos_quote = self._find_quote_position(line_return_tmp) if line_return_tmp[-1] == '\\': line_return_tmp = line_return_tmp[:-1] continue self._find_bracket_position(line_return_tmp, '(', ')', pos_quote) self._find_bracket_position(line_return_tmp, '{', '}', pos_quote) self._find_bracket_position(line_return_tmp, '[', ']', pos_quote) except IndexError: continue return_value = re.sub(pattern_return, '', line_return_tmp) self.return_value_in_body.append(return_value) is_found_return = False line_return_tmp = ''
python
def parse_body(self, text): """Parse the function body text.""" re_raise = re.findall(r'[ \t]raise ([a-zA-Z0-9_]*)', text) if len(re_raise) > 0: self.raise_list = [x.strip() for x in re_raise] # remove duplicates from list while keeping it in the order # in python 2.7 # stackoverflow.com/questions/7961363/removing-duplicates-in-lists self.raise_list = list(OrderedDict.fromkeys(self.raise_list)) re_yield = re.search(r'[ \t]yield ', text) if re_yield: self.has_yield = True # get return value pattern_return = r'return |yield ' line_list = text.split('\n') is_found_return = False line_return_tmp = '' for line in line_list: line = line.strip() if is_found_return is False: if re.match(pattern_return, line): is_found_return = True if is_found_return: line_return_tmp += line # check the integrity of line try: pos_quote = self._find_quote_position(line_return_tmp) if line_return_tmp[-1] == '\\': line_return_tmp = line_return_tmp[:-1] continue self._find_bracket_position(line_return_tmp, '(', ')', pos_quote) self._find_bracket_position(line_return_tmp, '{', '}', pos_quote) self._find_bracket_position(line_return_tmp, '[', ']', pos_quote) except IndexError: continue return_value = re.sub(pattern_return, '', line_return_tmp) self.return_value_in_body.append(return_value) is_found_return = False line_return_tmp = ''
[ "def", "parse_body", "(", "self", ",", "text", ")", ":", "re_raise", "=", "re", ".", "findall", "(", "r'[ \\t]raise ([a-zA-Z0-9_]*)'", ",", "text", ")", "if", "len", "(", "re_raise", ")", ">", "0", ":", "self", ".", "raise_list", "=", "[", "x", ".", ...
Parse the function body text.
[ "Parse", "the", "function", "body", "text", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L779-L829
31,151
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
QMenuOnlyForEnter.keyPressEvent
def keyPressEvent(self, event): """Close the instance if key is not enter key.""" key = event.key() if key not in (Qt.Key_Enter, Qt.Key_Return): self.code_editor.keyPressEvent(event) self.close() else: super(QMenuOnlyForEnter, self).keyPressEvent(event)
python
def keyPressEvent(self, event): """Close the instance if key is not enter key.""" key = event.key() if key not in (Qt.Key_Enter, Qt.Key_Return): self.code_editor.keyPressEvent(event) self.close() else: super(QMenuOnlyForEnter, self).keyPressEvent(event)
[ "def", "keyPressEvent", "(", "self", ",", "event", ")", ":", "key", "=", "event", ".", "key", "(", ")", "if", "key", "not", "in", "(", "Qt", ".", "Key_Enter", ",", "Qt", ".", "Key_Return", ")", ":", "self", ".", "code_editor", ".", "keyPressEvent", ...
Close the instance if key is not enter key.
[ "Close", "the", "instance", "if", "key", "is", "not", "enter", "key", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L844-L851
31,152
spyder-ide/spyder
spyder/app/restart.py
_is_pid_running_on_windows
def _is_pid_running_on_windows(pid): """Check if a process is running on windows systems based on the pid.""" pid = str(pid) # Hide flashing command prompt startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW process = subprocess.Popen(r'tasklist /fi "PID eq {0}"'.format(pid), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupinfo) stdoutdata, stderrdata = process.communicate() stdoutdata = to_text_string(stdoutdata) process.kill() check = pid in stdoutdata return check
python
def _is_pid_running_on_windows(pid): """Check if a process is running on windows systems based on the pid.""" pid = str(pid) # Hide flashing command prompt startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW process = subprocess.Popen(r'tasklist /fi "PID eq {0}"'.format(pid), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupinfo) stdoutdata, stderrdata = process.communicate() stdoutdata = to_text_string(stdoutdata) process.kill() check = pid in stdoutdata return check
[ "def", "_is_pid_running_on_windows", "(", "pid", ")", ":", "pid", "=", "str", "(", "pid", ")", "# Hide flashing command prompt\r", "startupinfo", "=", "subprocess", ".", "STARTUPINFO", "(", ")", "startupinfo", ".", "dwFlags", "|=", "subprocess", ".", "STARTF_USESH...
Check if a process is running on windows systems based on the pid.
[ "Check", "if", "a", "process", "is", "running", "on", "windows", "systems", "based", "on", "the", "pid", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/restart.py#L42-L59
31,153
spyder-ide/spyder
spyder/app/restart.py
Restarter._show_message
def _show_message(self, text): """Show message on splash screen.""" self.splash.showMessage(text, Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.white))
python
def _show_message(self, text): """Show message on splash screen.""" self.splash.showMessage(text, Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.white))
[ "def", "_show_message", "(", "self", ",", "text", ")", ":", "self", ".", "splash", ".", "showMessage", "(", "text", ",", "Qt", ".", "AlignBottom", "|", "Qt", ".", "AlignCenter", "|", "Qt", ".", "AlignAbsolute", ",", "QColor", "(", "Qt", ".", "white", ...
Show message on splash screen.
[ "Show", "message", "on", "splash", "screen", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/restart.py#L106-L109
31,154
spyder-ide/spyder
spyder/app/restart.py
Restarter.animate_ellipsis
def animate_ellipsis(self): """Animate dots at the end of the splash screen message.""" ellipsis = self.ellipsis.pop(0) text = ' '*len(ellipsis) + self.splash_text + ellipsis self.ellipsis.append(ellipsis) self._show_message(text)
python
def animate_ellipsis(self): """Animate dots at the end of the splash screen message.""" ellipsis = self.ellipsis.pop(0) text = ' '*len(ellipsis) + self.splash_text + ellipsis self.ellipsis.append(ellipsis) self._show_message(text)
[ "def", "animate_ellipsis", "(", "self", ")", ":", "ellipsis", "=", "self", ".", "ellipsis", ".", "pop", "(", "0", ")", "text", "=", "' '", "*", "len", "(", "ellipsis", ")", "+", "self", ".", "splash_text", "+", "ellipsis", "self", ".", "ellipsis", "....
Animate dots at the end of the splash screen message.
[ "Animate", "dots", "at", "the", "end", "of", "the", "splash", "screen", "message", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/restart.py#L111-L116
31,155
spyder-ide/spyder
spyder/app/restart.py
Restarter.set_splash_message
def set_splash_message(self, text): """Sets the text in the bottom of the Splash screen.""" self.splash_text = text self._show_message(text) self.timer_ellipsis.start(500)
python
def set_splash_message(self, text): """Sets the text in the bottom of the Splash screen.""" self.splash_text = text self._show_message(text) self.timer_ellipsis.start(500)
[ "def", "set_splash_message", "(", "self", ",", "text", ")", ":", "self", ".", "splash_text", "=", "text", "self", ".", "_show_message", "(", "text", ")", "self", ".", "timer_ellipsis", ".", "start", "(", "500", ")" ]
Sets the text in the bottom of the Splash screen.
[ "Sets", "the", "text", "in", "the", "bottom", "of", "the", "Splash", "screen", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/restart.py#L118-L122
31,156
spyder-ide/spyder
spyder/plugins/history/plugin.py
HistoryLog.add_history
def add_history(self, filename): """ Add new history tab Slot for add_history signal emitted by shell instance """ filename = encoding.to_unicode_from_fs(filename) if filename in self.filenames: return editor = codeeditor.CodeEditor(self) if osp.splitext(filename)[1] == '.py': language = 'py' else: language = 'bat' editor.setup_editor(linenumbers=self.get_option('line_numbers'), language=language, scrollflagarea=False) editor.focus_changed.connect(lambda: self.focus_changed.emit()) editor.setReadOnly(True) color_scheme = self.get_color_scheme() editor.set_font( self.get_plugin_font(), color_scheme ) editor.toggle_wrap_mode( self.get_option('wrap') ) # Avoid a possible error when reading the history file try: text, _ = encoding.read(filename) except (IOError, OSError): text = "# Previous history could not be read from disk, sorry\n\n" text = normalize_eols(text) linebreaks = [m.start() for m in re.finditer('\n', text)] maxNline = self.get_option('max_entries') if len(linebreaks) > maxNline: text = text[linebreaks[-maxNline - 1] + 1:] # Avoid an error when trying to write the trimmed text to # disk. # See issue 9093 try: encoding.write(text, filename) except (IOError, OSError): pass editor.set_text(text) editor.set_cursor_position('eof') self.editors.append(editor) self.filenames.append(filename) index = self.tabwidget.addTab(editor, osp.basename(filename)) self.find_widget.set_editor(editor) self.tabwidget.setTabToolTip(index, filename) self.tabwidget.setCurrentIndex(index)
python
def add_history(self, filename): """ Add new history tab Slot for add_history signal emitted by shell instance """ filename = encoding.to_unicode_from_fs(filename) if filename in self.filenames: return editor = codeeditor.CodeEditor(self) if osp.splitext(filename)[1] == '.py': language = 'py' else: language = 'bat' editor.setup_editor(linenumbers=self.get_option('line_numbers'), language=language, scrollflagarea=False) editor.focus_changed.connect(lambda: self.focus_changed.emit()) editor.setReadOnly(True) color_scheme = self.get_color_scheme() editor.set_font( self.get_plugin_font(), color_scheme ) editor.toggle_wrap_mode( self.get_option('wrap') ) # Avoid a possible error when reading the history file try: text, _ = encoding.read(filename) except (IOError, OSError): text = "# Previous history could not be read from disk, sorry\n\n" text = normalize_eols(text) linebreaks = [m.start() for m in re.finditer('\n', text)] maxNline = self.get_option('max_entries') if len(linebreaks) > maxNline: text = text[linebreaks[-maxNline - 1] + 1:] # Avoid an error when trying to write the trimmed text to # disk. # See issue 9093 try: encoding.write(text, filename) except (IOError, OSError): pass editor.set_text(text) editor.set_cursor_position('eof') self.editors.append(editor) self.filenames.append(filename) index = self.tabwidget.addTab(editor, osp.basename(filename)) self.find_widget.set_editor(editor) self.tabwidget.setTabToolTip(index, filename) self.tabwidget.setCurrentIndex(index)
[ "def", "add_history", "(", "self", ",", "filename", ")", ":", "filename", "=", "encoding", ".", "to_unicode_from_fs", "(", "filename", ")", "if", "filename", "in", "self", ".", "filenames", ":", "return", "editor", "=", "codeeditor", ".", "CodeEditor", "(", ...
Add new history tab Slot for add_history signal emitted by shell instance
[ "Add", "new", "history", "tab", "Slot", "for", "add_history", "signal", "emitted", "by", "shell", "instance" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/history/plugin.py#L181-L228
31,157
spyder-ide/spyder
spyder/plugins/history/plugin.py
HistoryLog.toggle_line_numbers
def toggle_line_numbers(self, checked): """Toggle line numbers.""" if self.tabwidget is None: return for editor in self.editors: editor.toggle_line_numbers(linenumbers=checked, markers=False) self.set_option('line_numbers', checked)
python
def toggle_line_numbers(self, checked): """Toggle line numbers.""" if self.tabwidget is None: return for editor in self.editors: editor.toggle_line_numbers(linenumbers=checked, markers=False) self.set_option('line_numbers', checked)
[ "def", "toggle_line_numbers", "(", "self", ",", "checked", ")", ":", "if", "self", ".", "tabwidget", "is", "None", ":", "return", "for", "editor", "in", "self", ".", "editors", ":", "editor", ".", "toggle_line_numbers", "(", "linenumbers", "=", "checked", ...
Toggle line numbers.
[ "Toggle", "line", "numbers", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/history/plugin.py#L265-L271
31,158
spyder-ide/spyder
spyder/widgets/browser.py
WebPage.acceptNavigationRequest
def acceptNavigationRequest(self, url, navigation_type, isMainFrame): """ Overloaded method to handle links ourselves """ if navigation_type == QWebEnginePage.NavigationTypeLinkClicked: self.linkClicked.emit(url) return False return True
python
def acceptNavigationRequest(self, url, navigation_type, isMainFrame): """ Overloaded method to handle links ourselves """ if navigation_type == QWebEnginePage.NavigationTypeLinkClicked: self.linkClicked.emit(url) return False return True
[ "def", "acceptNavigationRequest", "(", "self", ",", "url", ",", "navigation_type", ",", "isMainFrame", ")", ":", "if", "navigation_type", "==", "QWebEnginePage", ".", "NavigationTypeLinkClicked", ":", "self", ".", "linkClicked", ".", "emit", "(", "url", ")", "re...
Overloaded method to handle links ourselves
[ "Overloaded", "method", "to", "handle", "links", "ourselves" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/browser.py#L43-L50
31,159
spyder-ide/spyder
spyder/widgets/browser.py
WebView.apply_zoom_factor
def apply_zoom_factor(self): """Apply zoom factor""" if hasattr(self, 'setZoomFactor'): # Assuming Qt >=v4.5 self.setZoomFactor(self.zoom_factor) else: # Qt v4.4 self.setTextSizeMultiplier(self.zoom_factor)
python
def apply_zoom_factor(self): """Apply zoom factor""" if hasattr(self, 'setZoomFactor'): # Assuming Qt >=v4.5 self.setZoomFactor(self.zoom_factor) else: # Qt v4.4 self.setTextSizeMultiplier(self.zoom_factor)
[ "def", "apply_zoom_factor", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'setZoomFactor'", ")", ":", "# Assuming Qt >=v4.5\r", "self", ".", "setZoomFactor", "(", "self", ".", "zoom_factor", ")", "else", ":", "# Qt v4.4\r", "self", ".", "setTextSi...
Apply zoom factor
[ "Apply", "zoom", "factor" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/browser.py#L135-L142
31,160
spyder-ide/spyder
spyder/widgets/browser.py
WebBrowser.url_combo_activated
def url_combo_activated(self, valid): """Load URL from combo box first item""" text = to_text_string(self.url_combo.currentText()) self.go_to(self.text_to_url(text))
python
def url_combo_activated(self, valid): """Load URL from combo box first item""" text = to_text_string(self.url_combo.currentText()) self.go_to(self.text_to_url(text))
[ "def", "url_combo_activated", "(", "self", ",", "valid", ")", ":", "text", "=", "to_text_string", "(", "self", ".", "url_combo", ".", "currentText", "(", ")", ")", "self", ".", "go_to", "(", "self", ".", "text_to_url", "(", "text", ")", ")" ]
Load URL from combo box first item
[ "Load", "URL", "from", "combo", "box", "first", "item" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/browser.py#L301-L304
31,161
spyder-ide/spyder
spyder/api/plugins.py
PluginWidget.register_shortcut
def register_shortcut(self, qaction_or_qshortcut, context, name, add_sc_to_tip=False): """ Register QAction or QShortcut to Spyder main application. if add_sc_to_tip is True, the shortcut is added to the action's tooltip """ self.main.register_shortcut(qaction_or_qshortcut, context, name, add_sc_to_tip)
python
def register_shortcut(self, qaction_or_qshortcut, context, name, add_sc_to_tip=False): """ Register QAction or QShortcut to Spyder main application. if add_sc_to_tip is True, the shortcut is added to the action's tooltip """ self.main.register_shortcut(qaction_or_qshortcut, context, name, add_sc_to_tip)
[ "def", "register_shortcut", "(", "self", ",", "qaction_or_qshortcut", ",", "context", ",", "name", ",", "add_sc_to_tip", "=", "False", ")", ":", "self", ".", "main", ".", "register_shortcut", "(", "qaction_or_qshortcut", ",", "context", ",", "name", ",", "add_...
Register QAction or QShortcut to Spyder main application. if add_sc_to_tip is True, the shortcut is added to the action's tooltip
[ "Register", "QAction", "or", "QShortcut", "to", "Spyder", "main", "application", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/plugins.py#L121-L130
31,162
spyder-ide/spyder
spyder/api/plugins.py
PluginWidget.register_widget_shortcuts
def register_widget_shortcuts(self, widget): """ Register widget shortcuts. Widget interface must have a method called 'get_shortcut_data' """ for qshortcut, context, name in widget.get_shortcut_data(): self.register_shortcut(qshortcut, context, name)
python
def register_widget_shortcuts(self, widget): """ Register widget shortcuts. Widget interface must have a method called 'get_shortcut_data' """ for qshortcut, context, name in widget.get_shortcut_data(): self.register_shortcut(qshortcut, context, name)
[ "def", "register_widget_shortcuts", "(", "self", ",", "widget", ")", ":", "for", "qshortcut", ",", "context", ",", "name", "in", "widget", ".", "get_shortcut_data", "(", ")", ":", "self", ".", "register_shortcut", "(", "qshortcut", ",", "context", ",", "name...
Register widget shortcuts. Widget interface must have a method called 'get_shortcut_data'
[ "Register", "widget", "shortcuts", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/plugins.py#L132-L139
31,163
spyder-ide/spyder
spyder/api/plugins.py
PluginWidget.visibility_changed
def visibility_changed(self, enable): """ Dock widget visibility has changed. """ if self.dockwidget is None: return if enable: self.dockwidget.raise_() widget = self.get_focus_widget() if widget is not None and self.undocked_window is not None: widget.setFocus() visible = self.dockwidget.isVisible() or self.ismaximized if self.DISABLE_ACTIONS_WHEN_HIDDEN: toggle_actions(self.plugin_actions, visible) self.isvisible = enable and visible if self.isvisible: self.refresh_plugin()
python
def visibility_changed(self, enable): """ Dock widget visibility has changed. """ if self.dockwidget is None: return if enable: self.dockwidget.raise_() widget = self.get_focus_widget() if widget is not None and self.undocked_window is not None: widget.setFocus() visible = self.dockwidget.isVisible() or self.ismaximized if self.DISABLE_ACTIONS_WHEN_HIDDEN: toggle_actions(self.plugin_actions, visible) self.isvisible = enable and visible if self.isvisible: self.refresh_plugin()
[ "def", "visibility_changed", "(", "self", ",", "enable", ")", ":", "if", "self", ".", "dockwidget", "is", "None", ":", "return", "if", "enable", ":", "self", ".", "dockwidget", ".", "raise_", "(", ")", "widget", "=", "self", ".", "get_focus_widget", "(",...
Dock widget visibility has changed.
[ "Dock", "widget", "visibility", "has", "changed", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/plugins.py#L141-L157
31,164
spyder-ide/spyder
spyder/api/plugins.py
PluginWidget.set_option
def set_option(self, option, value): """ Set a plugin option in configuration file. Note: Use sig_option_changed to call it from widgets of the same or another plugin. """ CONF.set(self.CONF_SECTION, str(option), value)
python
def set_option(self, option, value): """ Set a plugin option in configuration file. Note: Use sig_option_changed to call it from widgets of the same or another plugin. """ CONF.set(self.CONF_SECTION, str(option), value)
[ "def", "set_option", "(", "self", ",", "option", ",", "value", ")", ":", "CONF", ".", "set", "(", "self", ".", "CONF_SECTION", ",", "str", "(", "option", ")", ",", "value", ")" ]
Set a plugin option in configuration file. Note: Use sig_option_changed to call it from widgets of the same or another plugin.
[ "Set", "a", "plugin", "option", "in", "configuration", "file", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/plugins.py#L159-L166
31,165
spyder-ide/spyder
spyder/api/plugins.py
PluginWidget.starting_long_process
def starting_long_process(self, message): """ Showing message in main window's status bar. This also changes mouse cursor to Qt.WaitCursor """ self.show_message(message) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents()
python
def starting_long_process(self, message): """ Showing message in main window's status bar. This also changes mouse cursor to Qt.WaitCursor """ self.show_message(message) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents()
[ "def", "starting_long_process", "(", "self", ",", "message", ")", ":", "self", ".", "show_message", "(", "message", ")", "QApplication", ".", "setOverrideCursor", "(", "QCursor", "(", "Qt", ".", "WaitCursor", ")", ")", "QApplication", ".", "processEvents", "("...
Showing message in main window's status bar. This also changes mouse cursor to Qt.WaitCursor
[ "Showing", "message", "in", "main", "window", "s", "status", "bar", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/plugins.py#L174-L182
31,166
spyder-ide/spyder
spyder/api/plugins.py
PluginWidget.ending_long_process
def ending_long_process(self, message=""): """ Clear main window's status bar and restore mouse cursor. """ QApplication.restoreOverrideCursor() self.show_message(message, timeout=2000) QApplication.processEvents()
python
def ending_long_process(self, message=""): """ Clear main window's status bar and restore mouse cursor. """ QApplication.restoreOverrideCursor() self.show_message(message, timeout=2000) QApplication.processEvents()
[ "def", "ending_long_process", "(", "self", ",", "message", "=", "\"\"", ")", ":", "QApplication", ".", "restoreOverrideCursor", "(", ")", "self", ".", "show_message", "(", "message", ",", "timeout", "=", "2000", ")", "QApplication", ".", "processEvents", "(", ...
Clear main window's status bar and restore mouse cursor.
[ "Clear", "main", "window", "s", "status", "bar", "and", "restore", "mouse", "cursor", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/plugins.py#L184-L190
31,167
spyder-ide/spyder
spyder/api/plugins.py
PluginWidget.show_compatibility_message
def show_compatibility_message(self, message): """ Show compatibility message. """ messageBox = QMessageBox(self) messageBox.setWindowModality(Qt.NonModal) messageBox.setAttribute(Qt.WA_DeleteOnClose) messageBox.setWindowTitle('Compatibility Check') messageBox.setText(message) messageBox.setStandardButtons(QMessageBox.Ok) messageBox.show()
python
def show_compatibility_message(self, message): """ Show compatibility message. """ messageBox = QMessageBox(self) messageBox.setWindowModality(Qt.NonModal) messageBox.setAttribute(Qt.WA_DeleteOnClose) messageBox.setWindowTitle('Compatibility Check') messageBox.setText(message) messageBox.setStandardButtons(QMessageBox.Ok) messageBox.show()
[ "def", "show_compatibility_message", "(", "self", ",", "message", ")", ":", "messageBox", "=", "QMessageBox", "(", "self", ")", "messageBox", ".", "setWindowModality", "(", "Qt", ".", "NonModal", ")", "messageBox", ".", "setAttribute", "(", "Qt", ".", "WA_Dele...
Show compatibility message.
[ "Show", "compatibility", "message", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/plugins.py#L198-L208
31,168
spyder-ide/spyder
spyder/api/plugins.py
PluginWidget.refresh_actions
def refresh_actions(self): """ Create options menu. """ self.options_menu.clear() # Decide what additional actions to show if self.undocked_window is None: additional_actions = [MENU_SEPARATOR, self.undock_action, self.close_plugin_action] else: additional_actions = [MENU_SEPARATOR, self.dock_action] # Create actions list self.plugin_actions = self.get_plugin_actions() + additional_actions add_actions(self.options_menu, self.plugin_actions)
python
def refresh_actions(self): """ Create options menu. """ self.options_menu.clear() # Decide what additional actions to show if self.undocked_window is None: additional_actions = [MENU_SEPARATOR, self.undock_action, self.close_plugin_action] else: additional_actions = [MENU_SEPARATOR, self.dock_action] # Create actions list self.plugin_actions = self.get_plugin_actions() + additional_actions add_actions(self.options_menu, self.plugin_actions)
[ "def", "refresh_actions", "(", "self", ")", ":", "self", ".", "options_menu", ".", "clear", "(", ")", "# Decide what additional actions to show", "if", "self", ".", "undocked_window", "is", "None", ":", "additional_actions", "=", "[", "MENU_SEPARATOR", ",", "self"...
Create options menu.
[ "Create", "options", "menu", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/plugins.py#L210-L227
31,169
spyder-ide/spyder
spyder/widgets/shortcutssummary.py
ShortcutsSummaryDialog.get_screen_resolution
def get_screen_resolution(self): """Return the screen resolution of the primary screen.""" widget = QDesktopWidget() geometry = widget.availableGeometry(widget.primaryScreen()) return geometry.width(), geometry.height()
python
def get_screen_resolution(self): """Return the screen resolution of the primary screen.""" widget = QDesktopWidget() geometry = widget.availableGeometry(widget.primaryScreen()) return geometry.width(), geometry.height()
[ "def", "get_screen_resolution", "(", "self", ")", ":", "widget", "=", "QDesktopWidget", "(", ")", "geometry", "=", "widget", ".", "availableGeometry", "(", "widget", ".", "primaryScreen", "(", ")", ")", "return", "geometry", ".", "width", "(", ")", ",", "g...
Return the screen resolution of the primary screen.
[ "Return", "the", "screen", "resolution", "of", "the", "primary", "screen", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/shortcutssummary.py#L147-L151
31,170
spyder-ide/spyder
spyder/plugins/plots/plugin.py
Plots.set_current_widget
def set_current_widget(self, fig_browser): """ Set the currently visible fig_browser in the stack widget, refresh the actions of the cog menu button and move it to the layout of the new fig_browser. """ self.stack.setCurrentWidget(fig_browser) # We update the actions of the options button (cog menu) and # we move it to the layout of the current widget. self.refresh_actions() fig_browser.setup_options_button()
python
def set_current_widget(self, fig_browser): """ Set the currently visible fig_browser in the stack widget, refresh the actions of the cog menu button and move it to the layout of the new fig_browser. """ self.stack.setCurrentWidget(fig_browser) # We update the actions of the options button (cog menu) and # we move it to the layout of the current widget. self.refresh_actions() fig_browser.setup_options_button()
[ "def", "set_current_widget", "(", "self", ",", "fig_browser", ")", ":", "self", ".", "stack", ".", "setCurrentWidget", "(", "fig_browser", ")", "# We update the actions of the options button (cog menu) and", "# we move it to the layout of the current widget.", "self", ".", "r...
Set the currently visible fig_browser in the stack widget, refresh the actions of the cog menu button and move it to the layout of the new fig_browser.
[ "Set", "the", "currently", "visible", "fig_browser", "in", "the", "stack", "widget", "refresh", "the", "actions", "of", "the", "cog", "menu", "button", "and", "move", "it", "to", "the", "layout", "of", "the", "new", "fig_browser", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/plugin.py#L53-L63
31,171
spyder-ide/spyder
spyder/plugins/plots/plugin.py
Plots.add_shellwidget
def add_shellwidget(self, shellwidget): """ Register shell with figure explorer. This function opens a new FigureBrowser for browsing the figures in the shell. """ shellwidget_id = id(shellwidget) if shellwidget_id not in self.shellwidgets: self.options_button.setVisible(True) fig_browser = FigureBrowser( self, options_button=self.options_button, background_color=MAIN_BG_COLOR) fig_browser.set_shellwidget(shellwidget) fig_browser.setup(**self.get_settings()) fig_browser.sig_option_changed.connect( self.sig_option_changed.emit) fig_browser.thumbnails_sb.redirect_stdio.connect( self.main.redirect_internalshell_stdio) self.register_widget_shortcuts(fig_browser) self.add_widget(fig_browser) self.shellwidgets[shellwidget_id] = fig_browser self.set_shellwidget_from_id(shellwidget_id) return fig_browser
python
def add_shellwidget(self, shellwidget): """ Register shell with figure explorer. This function opens a new FigureBrowser for browsing the figures in the shell. """ shellwidget_id = id(shellwidget) if shellwidget_id not in self.shellwidgets: self.options_button.setVisible(True) fig_browser = FigureBrowser( self, options_button=self.options_button, background_color=MAIN_BG_COLOR) fig_browser.set_shellwidget(shellwidget) fig_browser.setup(**self.get_settings()) fig_browser.sig_option_changed.connect( self.sig_option_changed.emit) fig_browser.thumbnails_sb.redirect_stdio.connect( self.main.redirect_internalshell_stdio) self.register_widget_shortcuts(fig_browser) self.add_widget(fig_browser) self.shellwidgets[shellwidget_id] = fig_browser self.set_shellwidget_from_id(shellwidget_id) return fig_browser
[ "def", "add_shellwidget", "(", "self", ",", "shellwidget", ")", ":", "shellwidget_id", "=", "id", "(", "shellwidget", ")", "if", "shellwidget_id", "not", "in", "self", ".", "shellwidgets", ":", "self", ".", "options_button", ".", "setVisible", "(", "True", "...
Register shell with figure explorer. This function opens a new FigureBrowser for browsing the figures in the shell.
[ "Register", "shell", "with", "figure", "explorer", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/plugin.py#L78-L101
31,172
spyder-ide/spyder
spyder/preferences/layoutdialog.py
LayoutSaveDialog.check_text
def check_text(self, text): """Disable empty layout name possibility""" if to_text_string(text) == u'': self.button_ok.setEnabled(False) else: self.button_ok.setEnabled(True)
python
def check_text(self, text): """Disable empty layout name possibility""" if to_text_string(text) == u'': self.button_ok.setEnabled(False) else: self.button_ok.setEnabled(True)
[ "def", "check_text", "(", "self", ",", "text", ")", ":", "if", "to_text_string", "(", "text", ")", "==", "u''", ":", "self", ".", "button_ok", ".", "setEnabled", "(", "False", ")", "else", ":", "self", ".", "button_ok", ".", "setEnabled", "(", "True", ...
Disable empty layout name possibility
[ "Disable", "empty", "layout", "name", "possibility" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/layoutdialog.py#L156-L161
31,173
spyder-ide/spyder
spyder/utils/bsdsocket.py
communicate
def communicate(sock, command, settings=[]): """Communicate with monitor""" try: COMMUNICATE_LOCK.acquire() write_packet(sock, command) for option in settings: write_packet(sock, option) return read_packet(sock) finally: COMMUNICATE_LOCK.release()
python
def communicate(sock, command, settings=[]): """Communicate with monitor""" try: COMMUNICATE_LOCK.acquire() write_packet(sock, command) for option in settings: write_packet(sock, option) return read_packet(sock) finally: COMMUNICATE_LOCK.release()
[ "def", "communicate", "(", "sock", ",", "command", ",", "settings", "=", "[", "]", ")", ":", "try", ":", "COMMUNICATE_LOCK", ".", "acquire", "(", ")", "write_packet", "(", "sock", ",", "command", ")", "for", "option", "in", "settings", ":", "write_packet...
Communicate with monitor
[ "Communicate", "with", "monitor" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/bsdsocket.py#L100-L109
31,174
spyder-ide/spyder
spyder/plugins/profiler/widgets/profilergui.py
ProfilerDataTree.initialize_view
def initialize_view(self): """Clean the tree and view parameters""" self.clear() self.item_depth = 0 # To be use for collapsing/expanding one level self.item_list = [] # To be use for collapsing/expanding one level self.items_to_be_shown = {} self.current_view_depth = 0
python
def initialize_view(self): """Clean the tree and view parameters""" self.clear() self.item_depth = 0 # To be use for collapsing/expanding one level self.item_list = [] # To be use for collapsing/expanding one level self.items_to_be_shown = {} self.current_view_depth = 0
[ "def", "initialize_view", "(", "self", ")", ":", "self", ".", "clear", "(", ")", "self", ".", "item_depth", "=", "0", "# To be use for collapsing/expanding one level\r", "self", ".", "item_list", "=", "[", "]", "# To be use for collapsing/expanding one level\r", "self...
Clean the tree and view parameters
[ "Clean", "the", "tree", "and", "view", "parameters" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/profiler/widgets/profilergui.py#L477-L483
31,175
spyder-ide/spyder
spyder/plugins/profiler/widgets/profilergui.py
ProfilerDataTree.find_root
def find_root(self): """Find a function without a caller""" self.profdata.sort_stats("cumulative") for func in self.profdata.fcn_list: if ('~', 0) != func[0:2] and not func[2].startswith( '<built-in method exec>'): # This skips the profiler function at the top of the list # it does only occur in Python 3 return func
python
def find_root(self): """Find a function without a caller""" self.profdata.sort_stats("cumulative") for func in self.profdata.fcn_list: if ('~', 0) != func[0:2] and not func[2].startswith( '<built-in method exec>'): # This skips the profiler function at the top of the list # it does only occur in Python 3 return func
[ "def", "find_root", "(", "self", ")", ":", "self", ".", "profdata", ".", "sort_stats", "(", "\"cumulative\"", ")", "for", "func", "in", "self", ".", "profdata", ".", "fcn_list", ":", "if", "(", "'~'", ",", "0", ")", "!=", "func", "[", "0", ":", "2"...
Find a function without a caller
[ "Find", "a", "function", "without", "a", "caller" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/profiler/widgets/profilergui.py#L520-L528
31,176
spyder-ide/spyder
spyder/plugins/profiler/widgets/profilergui.py
ProfilerDataTree.show_tree
def show_tree(self): """Populate the tree with profiler data and display it.""" self.initialize_view() # Clear before re-populating self.setItemsExpandable(True) self.setSortingEnabled(False) rootkey = self.find_root() # This root contains profiler overhead if rootkey: self.populate_tree(self, self.find_callees(rootkey)) self.resizeColumnToContents(0) self.setSortingEnabled(True) self.sortItems(1, Qt.AscendingOrder) # FIXME: hardcoded index self.change_view(1)
python
def show_tree(self): """Populate the tree with profiler data and display it.""" self.initialize_view() # Clear before re-populating self.setItemsExpandable(True) self.setSortingEnabled(False) rootkey = self.find_root() # This root contains profiler overhead if rootkey: self.populate_tree(self, self.find_callees(rootkey)) self.resizeColumnToContents(0) self.setSortingEnabled(True) self.sortItems(1, Qt.AscendingOrder) # FIXME: hardcoded index self.change_view(1)
[ "def", "show_tree", "(", "self", ")", ":", "self", ".", "initialize_view", "(", ")", "# Clear before re-populating\r", "self", ".", "setItemsExpandable", "(", "True", ")", "self", ".", "setSortingEnabled", "(", "False", ")", "rootkey", "=", "self", ".", "find_...
Populate the tree with profiler data and display it.
[ "Populate", "the", "tree", "with", "profiler", "data", "and", "display", "it", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/profiler/widgets/profilergui.py#L536-L547
31,177
spyder-ide/spyder
spyder/plugins/profiler/widgets/profilergui.py
ProfilerDataTree.function_info
def function_info(self, functionKey): """Returns processed information about the function's name and file.""" node_type = 'function' filename, line_number, function_name = functionKey if function_name == '<module>': modulePath, moduleName = osp.split(filename) node_type = 'module' if moduleName == '__init__.py': modulePath, moduleName = osp.split(modulePath) function_name = '<' + moduleName + '>' if not filename or filename == '~': file_and_line = '(built-in)' node_type = 'builtin' else: if function_name == '__init__': node_type = 'constructor' file_and_line = '%s : %d' % (filename, line_number) return filename, line_number, function_name, file_and_line, node_type
python
def function_info(self, functionKey): """Returns processed information about the function's name and file.""" node_type = 'function' filename, line_number, function_name = functionKey if function_name == '<module>': modulePath, moduleName = osp.split(filename) node_type = 'module' if moduleName == '__init__.py': modulePath, moduleName = osp.split(modulePath) function_name = '<' + moduleName + '>' if not filename or filename == '~': file_and_line = '(built-in)' node_type = 'builtin' else: if function_name == '__init__': node_type = 'constructor' file_and_line = '%s : %d' % (filename, line_number) return filename, line_number, function_name, file_and_line, node_type
[ "def", "function_info", "(", "self", ",", "functionKey", ")", ":", "node_type", "=", "'function'", "filename", ",", "line_number", ",", "function_name", "=", "functionKey", "if", "function_name", "==", "'<module>'", ":", "modulePath", ",", "moduleName", "=", "os...
Returns processed information about the function's name and file.
[ "Returns", "processed", "information", "about", "the", "function", "s", "name", "and", "file", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/profiler/widgets/profilergui.py#L549-L566
31,178
spyder-ide/spyder
spyder/plugins/profiler/widgets/profilergui.py
ProfilerDataTree.format_measure
def format_measure(measure): """Get format and units for data coming from profiler task.""" # Convert to a positive value. measure = abs(measure) # For number of calls if isinstance(measure, int): return to_text_string(measure) # For time measurements if 1.e-9 < measure <= 1.e-6: measure = u"{0:.2f} ns".format(measure / 1.e-9) elif 1.e-6 < measure <= 1.e-3: measure = u"{0:.2f} us".format(measure / 1.e-6) elif 1.e-3 < measure <= 1: measure = u"{0:.2f} ms".format(measure / 1.e-3) elif 1 < measure <= 60: measure = u"{0:.2f} sec".format(measure) elif 60 < measure <= 3600: m, s = divmod(measure, 3600) if s > 60: m, s = divmod(measure, 60) s = to_text_string(s).split(".")[-1] measure = u"{0:.0f}.{1:.2s} min".format(m, s) else: h, m = divmod(measure, 3600) if m > 60: m /= 60 measure = u"{0:.0f}h:{1:.0f}min".format(h, m) return measure
python
def format_measure(measure): """Get format and units for data coming from profiler task.""" # Convert to a positive value. measure = abs(measure) # For number of calls if isinstance(measure, int): return to_text_string(measure) # For time measurements if 1.e-9 < measure <= 1.e-6: measure = u"{0:.2f} ns".format(measure / 1.e-9) elif 1.e-6 < measure <= 1.e-3: measure = u"{0:.2f} us".format(measure / 1.e-6) elif 1.e-3 < measure <= 1: measure = u"{0:.2f} ms".format(measure / 1.e-3) elif 1 < measure <= 60: measure = u"{0:.2f} sec".format(measure) elif 60 < measure <= 3600: m, s = divmod(measure, 3600) if s > 60: m, s = divmod(measure, 60) s = to_text_string(s).split(".")[-1] measure = u"{0:.0f}.{1:.2s} min".format(m, s) else: h, m = divmod(measure, 3600) if m > 60: m /= 60 measure = u"{0:.0f}h:{1:.0f}min".format(h, m) return measure
[ "def", "format_measure", "(", "measure", ")", ":", "# Convert to a positive value.\r", "measure", "=", "abs", "(", "measure", ")", "# For number of calls\r", "if", "isinstance", "(", "measure", ",", "int", ")", ":", "return", "to_text_string", "(", "measure", ")",...
Get format and units for data coming from profiler task.
[ "Get", "format", "and", "units", "for", "data", "coming", "from", "profiler", "task", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/profiler/widgets/profilergui.py#L569-L598
31,179
spyder-ide/spyder
spyder/plugins/profiler/widgets/profilergui.py
ProfilerDataTree.is_recursive
def is_recursive(self, child_item): """Returns True is a function is a descendant of itself.""" ancestor = child_item.parent() # FIXME: indexes to data should be defined by a dictionary on init while ancestor: if (child_item.data(0, Qt.DisplayRole ) == ancestor.data(0, Qt.DisplayRole) and child_item.data(7, Qt.DisplayRole ) == ancestor.data(7, Qt.DisplayRole)): return True else: ancestor = ancestor.parent() return False
python
def is_recursive(self, child_item): """Returns True is a function is a descendant of itself.""" ancestor = child_item.parent() # FIXME: indexes to data should be defined by a dictionary on init while ancestor: if (child_item.data(0, Qt.DisplayRole ) == ancestor.data(0, Qt.DisplayRole) and child_item.data(7, Qt.DisplayRole ) == ancestor.data(7, Qt.DisplayRole)): return True else: ancestor = ancestor.parent() return False
[ "def", "is_recursive", "(", "self", ",", "child_item", ")", ":", "ancestor", "=", "child_item", ".", "parent", "(", ")", "# FIXME: indexes to data should be defined by a dictionary on init\r", "while", "ancestor", ":", "if", "(", "child_item", ".", "data", "(", "0",...
Returns True is a function is a descendant of itself.
[ "Returns", "True", "is", "a", "function", "is", "a", "descendant", "of", "itself", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/profiler/widgets/profilergui.py#L710-L722
31,180
spyder-ide/spyder
spyder/plugins/profiler/widgets/profilergui.py
ProfilerDataTree.get_items
def get_items(self, maxlevel): """Return all items with a level <= `maxlevel`""" itemlist = [] def add_to_itemlist(item, maxlevel, level=1): level += 1 for index in range(item.childCount()): citem = item.child(index) itemlist.append(citem) if level <= maxlevel: add_to_itemlist(citem, maxlevel, level) for tlitem in self.get_top_level_items(): itemlist.append(tlitem) if maxlevel > 0: add_to_itemlist(tlitem, maxlevel=maxlevel) return itemlist
python
def get_items(self, maxlevel): """Return all items with a level <= `maxlevel`""" itemlist = [] def add_to_itemlist(item, maxlevel, level=1): level += 1 for index in range(item.childCount()): citem = item.child(index) itemlist.append(citem) if level <= maxlevel: add_to_itemlist(citem, maxlevel, level) for tlitem in self.get_top_level_items(): itemlist.append(tlitem) if maxlevel > 0: add_to_itemlist(tlitem, maxlevel=maxlevel) return itemlist
[ "def", "get_items", "(", "self", ",", "maxlevel", ")", ":", "itemlist", "=", "[", "]", "def", "add_to_itemlist", "(", "item", ",", "maxlevel", ",", "level", "=", "1", ")", ":", "level", "+=", "1", "for", "index", "in", "range", "(", "item", ".", "c...
Return all items with a level <= `maxlevel`
[ "Return", "all", "items", "with", "a", "level", "<", "=", "maxlevel" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/profiler/widgets/profilergui.py#L728-L742
31,181
spyder-ide/spyder
spyder/plugins/profiler/widgets/profilergui.py
ProfilerDataTree.change_view
def change_view(self, change_in_depth): """Change the view depth by expand or collapsing all same-level nodes""" self.current_view_depth += change_in_depth if self.current_view_depth < 0: self.current_view_depth = 0 self.collapseAll() if self.current_view_depth > 0: for item in self.get_items(maxlevel=self.current_view_depth-1): item.setExpanded(True)
python
def change_view(self, change_in_depth): """Change the view depth by expand or collapsing all same-level nodes""" self.current_view_depth += change_in_depth if self.current_view_depth < 0: self.current_view_depth = 0 self.collapseAll() if self.current_view_depth > 0: for item in self.get_items(maxlevel=self.current_view_depth-1): item.setExpanded(True)
[ "def", "change_view", "(", "self", ",", "change_in_depth", ")", ":", "self", ".", "current_view_depth", "+=", "change_in_depth", "if", "self", ".", "current_view_depth", "<", "0", ":", "self", ".", "current_view_depth", "=", "0", "self", ".", "collapseAll", "(...
Change the view depth by expand or collapsing all same-level nodes
[ "Change", "the", "view", "depth", "by", "expand", "or", "collapsing", "all", "same", "-", "level", "nodes" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/profiler/widgets/profilergui.py#L744-L752
31,182
spyder-ide/spyder
spyder/plugins/ipythonconsole/utils/style.py
create_qss_style
def create_qss_style(color_scheme): """Returns a QSS stylesheet with Spyder color scheme settings. The stylesheet can contain classes for: Qt: QPlainTextEdit, QFrame, QWidget, etc Pygments: .c, .k, .o, etc. (see PygmentsHighlighter) IPython: .error, .in-prompt, .out-prompt, etc """ def give_font_weight(is_bold): if is_bold: return 'bold' else: return 'normal' def give_font_style(is_italic): if is_italic: return 'italic' else: return 'normal' color_scheme = get_color_scheme(color_scheme) fon_c, fon_fw, fon_fs = color_scheme['normal'] font_color = fon_c if dark_color(font_color): in_prompt_color = 'navy' out_prompt_color = 'darkred' else: in_prompt_color = 'lime' out_prompt_color = 'red' background_color = color_scheme['background'] error_color = 'red' in_prompt_number_font_weight = 'bold' out_prompt_number_font_weight = 'bold' inverted_background_color = font_color inverted_font_color = background_color sheet = """QPlainTextEdit, QTextEdit, ControlWidget {{ color: {} ; background-color: {}; }} .error {{ color: {}; }} .in-prompt {{ color: {}; }} .in-prompt-number {{ color: {}; font-weight: {}; }} .out-prompt {{ color: {}; }} .out-prompt-number {{ color: {}; font-weight: {}; }} .inverted {{ color: {}; background-color: {}; }} """ sheet_formatted = sheet.format(font_color, background_color, error_color, in_prompt_color, in_prompt_color, in_prompt_number_font_weight, out_prompt_color, out_prompt_color, out_prompt_number_font_weight, inverted_background_color, inverted_font_color) return (sheet_formatted, dark_color(font_color))
python
def create_qss_style(color_scheme): """Returns a QSS stylesheet with Spyder color scheme settings. The stylesheet can contain classes for: Qt: QPlainTextEdit, QFrame, QWidget, etc Pygments: .c, .k, .o, etc. (see PygmentsHighlighter) IPython: .error, .in-prompt, .out-prompt, etc """ def give_font_weight(is_bold): if is_bold: return 'bold' else: return 'normal' def give_font_style(is_italic): if is_italic: return 'italic' else: return 'normal' color_scheme = get_color_scheme(color_scheme) fon_c, fon_fw, fon_fs = color_scheme['normal'] font_color = fon_c if dark_color(font_color): in_prompt_color = 'navy' out_prompt_color = 'darkred' else: in_prompt_color = 'lime' out_prompt_color = 'red' background_color = color_scheme['background'] error_color = 'red' in_prompt_number_font_weight = 'bold' out_prompt_number_font_weight = 'bold' inverted_background_color = font_color inverted_font_color = background_color sheet = """QPlainTextEdit, QTextEdit, ControlWidget {{ color: {} ; background-color: {}; }} .error {{ color: {}; }} .in-prompt {{ color: {}; }} .in-prompt-number {{ color: {}; font-weight: {}; }} .out-prompt {{ color: {}; }} .out-prompt-number {{ color: {}; font-weight: {}; }} .inverted {{ color: {}; background-color: {}; }} """ sheet_formatted = sheet.format(font_color, background_color, error_color, in_prompt_color, in_prompt_color, in_prompt_number_font_weight, out_prompt_color, out_prompt_color, out_prompt_number_font_weight, inverted_background_color, inverted_font_color) return (sheet_formatted, dark_color(font_color))
[ "def", "create_qss_style", "(", "color_scheme", ")", ":", "def", "give_font_weight", "(", "is_bold", ")", ":", "if", "is_bold", ":", "return", "'bold'", "else", ":", "return", "'normal'", "def", "give_font_style", "(", "is_italic", ")", ":", "if", "is_italic",...
Returns a QSS stylesheet with Spyder color scheme settings. The stylesheet can contain classes for: Qt: QPlainTextEdit, QFrame, QWidget, etc Pygments: .c, .k, .o, etc. (see PygmentsHighlighter) IPython: .error, .in-prompt, .out-prompt, etc
[ "Returns", "a", "QSS", "stylesheet", "with", "Spyder", "color", "scheme", "settings", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/utils/style.py#L22-L80
31,183
spyder-ide/spyder
spyder/plugins/ipythonconsole/utils/style.py
create_pygments_dict
def create_pygments_dict(color_scheme_name): """ Create a dictionary that saves the given color scheme as a Pygments style. """ def give_font_weight(is_bold): if is_bold: return 'bold' else: return '' def give_font_style(is_italic): if is_italic: return 'italic' else: return '' color_scheme = get_color_scheme(color_scheme_name) fon_c, fon_fw, fon_fs = color_scheme['normal'] font_color = fon_c font_font_weight = give_font_weight(fon_fw) font_font_style = give_font_style(fon_fs) key_c, key_fw, key_fs = color_scheme['keyword'] keyword_color = key_c keyword_font_weight = give_font_weight(key_fw) keyword_font_style = give_font_style(key_fs) bui_c, bui_fw, bui_fs = color_scheme['builtin'] builtin_color = bui_c builtin_font_weight = give_font_weight(bui_fw) builtin_font_style = give_font_style(bui_fs) str_c, str_fw, str_fs = color_scheme['string'] string_color = str_c string_font_weight = give_font_weight(str_fw) string_font_style = give_font_style(str_fs) num_c, num_fw, num_fs = color_scheme['number'] number_color = num_c number_font_weight = give_font_weight(num_fw) number_font_style = give_font_style(num_fs) com_c, com_fw, com_fs = color_scheme['comment'] comment_color = com_c comment_font_weight = give_font_weight(com_fw) comment_font_style = give_font_style(com_fs) def_c, def_fw, def_fs = color_scheme['definition'] definition_color = def_c definition_font_weight = give_font_weight(def_fw) definition_font_style = give_font_style(def_fs) ins_c, ins_fw, ins_fs = color_scheme['instance'] instance_color = ins_c instance_font_weight = give_font_weight(ins_fw) instance_font_style = give_font_style(ins_fs) font_token = font_font_style + ' ' + font_font_weight + ' ' + font_color definition_token = (definition_font_style + ' ' + definition_font_weight + ' ' + definition_color) builtin_token = (builtin_font_style + ' ' + builtin_font_weight + ' ' + builtin_color) instance_token = (instance_font_style + ' ' + instance_font_weight + ' ' + instance_color) keyword_token = (keyword_font_style + ' ' + keyword_font_weight + ' ' + keyword_color) comment_token = (comment_font_style + ' ' + comment_font_weight + ' ' + comment_color) string_token = (string_font_style + ' ' + string_font_weight + ' ' + string_color) number_token = (number_font_style + ' ' + number_font_weight + ' ' + number_color) syntax_style_dic = {Name: font_token.strip(), Name.Class: definition_token.strip(), Name.Function: definition_token.strip(), Name.Builtin: builtin_token.strip(), Name.Builtin.Pseudo: instance_token.strip(), Keyword: keyword_token.strip(), Keyword.Type: builtin_token.strip(), Comment: comment_token.strip(), String: string_token.strip(), Number: number_token.strip(), Punctuation: font_token.strip(), Operator.Word: keyword_token.strip()} return syntax_style_dic
python
def create_pygments_dict(color_scheme_name): """ Create a dictionary that saves the given color scheme as a Pygments style. """ def give_font_weight(is_bold): if is_bold: return 'bold' else: return '' def give_font_style(is_italic): if is_italic: return 'italic' else: return '' color_scheme = get_color_scheme(color_scheme_name) fon_c, fon_fw, fon_fs = color_scheme['normal'] font_color = fon_c font_font_weight = give_font_weight(fon_fw) font_font_style = give_font_style(fon_fs) key_c, key_fw, key_fs = color_scheme['keyword'] keyword_color = key_c keyword_font_weight = give_font_weight(key_fw) keyword_font_style = give_font_style(key_fs) bui_c, bui_fw, bui_fs = color_scheme['builtin'] builtin_color = bui_c builtin_font_weight = give_font_weight(bui_fw) builtin_font_style = give_font_style(bui_fs) str_c, str_fw, str_fs = color_scheme['string'] string_color = str_c string_font_weight = give_font_weight(str_fw) string_font_style = give_font_style(str_fs) num_c, num_fw, num_fs = color_scheme['number'] number_color = num_c number_font_weight = give_font_weight(num_fw) number_font_style = give_font_style(num_fs) com_c, com_fw, com_fs = color_scheme['comment'] comment_color = com_c comment_font_weight = give_font_weight(com_fw) comment_font_style = give_font_style(com_fs) def_c, def_fw, def_fs = color_scheme['definition'] definition_color = def_c definition_font_weight = give_font_weight(def_fw) definition_font_style = give_font_style(def_fs) ins_c, ins_fw, ins_fs = color_scheme['instance'] instance_color = ins_c instance_font_weight = give_font_weight(ins_fw) instance_font_style = give_font_style(ins_fs) font_token = font_font_style + ' ' + font_font_weight + ' ' + font_color definition_token = (definition_font_style + ' ' + definition_font_weight + ' ' + definition_color) builtin_token = (builtin_font_style + ' ' + builtin_font_weight + ' ' + builtin_color) instance_token = (instance_font_style + ' ' + instance_font_weight + ' ' + instance_color) keyword_token = (keyword_font_style + ' ' + keyword_font_weight + ' ' + keyword_color) comment_token = (comment_font_style + ' ' + comment_font_weight + ' ' + comment_color) string_token = (string_font_style + ' ' + string_font_weight + ' ' + string_color) number_token = (number_font_style + ' ' + number_font_weight + ' ' + number_color) syntax_style_dic = {Name: font_token.strip(), Name.Class: definition_token.strip(), Name.Function: definition_token.strip(), Name.Builtin: builtin_token.strip(), Name.Builtin.Pseudo: instance_token.strip(), Keyword: keyword_token.strip(), Keyword.Type: builtin_token.strip(), Comment: comment_token.strip(), String: string_token.strip(), Number: number_token.strip(), Punctuation: font_token.strip(), Operator.Word: keyword_token.strip()} return syntax_style_dic
[ "def", "create_pygments_dict", "(", "color_scheme_name", ")", ":", "def", "give_font_weight", "(", "is_bold", ")", ":", "if", "is_bold", ":", "return", "'bold'", "else", ":", "return", "''", "def", "give_font_style", "(", "is_italic", ")", ":", "if", "is_itali...
Create a dictionary that saves the given color scheme as a Pygments style.
[ "Create", "a", "dictionary", "that", "saves", "the", "given", "color", "scheme", "as", "a", "Pygments", "style", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/utils/style.py#L83-L165
31,184
spyder-ide/spyder
spyder/utils/misc.py
__remove_pyc_pyo
def __remove_pyc_pyo(fname): """Eventually remove .pyc and .pyo files associated to a Python script""" if osp.splitext(fname)[1] == '.py': for ending in ('c', 'o'): if osp.exists(fname+ending): os.remove(fname+ending)
python
def __remove_pyc_pyo(fname): """Eventually remove .pyc and .pyo files associated to a Python script""" if osp.splitext(fname)[1] == '.py': for ending in ('c', 'o'): if osp.exists(fname+ending): os.remove(fname+ending)
[ "def", "__remove_pyc_pyo", "(", "fname", ")", ":", "if", "osp", ".", "splitext", "(", "fname", ")", "[", "1", "]", "==", "'.py'", ":", "for", "ending", "in", "(", "'c'", ",", "'o'", ")", ":", "if", "osp", ".", "exists", "(", "fname", "+", "ending...
Eventually remove .pyc and .pyo files associated to a Python script
[ "Eventually", "remove", ".", "pyc", "and", ".", "pyo", "files", "associated", "to", "a", "Python", "script" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/misc.py#L24-L29
31,185
spyder-ide/spyder
spyder/utils/misc.py
select_port
def select_port(default_port=20128): """Find and return a non used port""" import socket while True: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) # sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind( ("127.0.0.1", default_port) ) except socket.error as _msg: # analysis:ignore default_port += 1 else: break finally: sock.close() sock = None return default_port
python
def select_port(default_port=20128): """Find and return a non used port""" import socket while True: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) # sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind( ("127.0.0.1", default_port) ) except socket.error as _msg: # analysis:ignore default_port += 1 else: break finally: sock.close() sock = None return default_port
[ "def", "select_port", "(", "default_port", "=", "20128", ")", ":", "import", "socket", "while", "True", ":", "try", ":", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ",", "socket", ".", "IPPROTO_...
Find and return a non used port
[ "Find", "and", "return", "a", "non", "used", "port" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/misc.py#L76-L93
31,186
spyder-ide/spyder
spyder/utils/misc.py
get_common_path
def get_common_path(pathlist): """Return common path for all paths in pathlist""" common = osp.normpath(osp.commonprefix(pathlist)) if len(common) > 1: if not osp.isdir(common): return abspardir(common) else: for path in pathlist: if not osp.isdir(osp.join(common, path[len(common)+1:])): # `common` is not the real common prefix return abspardir(common) else: return osp.abspath(common)
python
def get_common_path(pathlist): """Return common path for all paths in pathlist""" common = osp.normpath(osp.commonprefix(pathlist)) if len(common) > 1: if not osp.isdir(common): return abspardir(common) else: for path in pathlist: if not osp.isdir(osp.join(common, path[len(common)+1:])): # `common` is not the real common prefix return abspardir(common) else: return osp.abspath(common)
[ "def", "get_common_path", "(", "pathlist", ")", ":", "common", "=", "osp", ".", "normpath", "(", "osp", ".", "commonprefix", "(", "pathlist", ")", ")", "if", "len", "(", "common", ")", ">", "1", ":", "if", "not", "osp", ".", "isdir", "(", "common", ...
Return common path for all paths in pathlist
[ "Return", "common", "path", "for", "all", "paths", "in", "pathlist" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/misc.py#L210-L222
31,187
spyder-ide/spyder
spyder/utils/misc.py
regexp_error_msg
def regexp_error_msg(pattern): """ Return None if the pattern is a valid regular expression or a string describing why the pattern is invalid. """ try: re.compile(pattern) except re.error as e: return str(e) return None
python
def regexp_error_msg(pattern): """ Return None if the pattern is a valid regular expression or a string describing why the pattern is invalid. """ try: re.compile(pattern) except re.error as e: return str(e) return None
[ "def", "regexp_error_msg", "(", "pattern", ")", ":", "try", ":", "re", ".", "compile", "(", "pattern", ")", "except", "re", ".", "error", "as", "e", ":", "return", "str", "(", "e", ")", "return", "None" ]
Return None if the pattern is a valid regular expression or a string describing why the pattern is invalid.
[ "Return", "None", "if", "the", "pattern", "is", "a", "valid", "regular", "expression", "or", "a", "string", "describing", "why", "the", "pattern", "is", "invalid", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/misc.py#L289-L298
31,188
spyder-ide/spyder
spyder/plugins/editor/utils/folding.py
FoldScope.fold
def fold(self): """Folds the region.""" start, end = self.get_range() TextBlockHelper.set_collapsed(self._trigger, True) block = self._trigger.next() while block.blockNumber() <= end and block.isValid(): block.setVisible(False) block = block.next()
python
def fold(self): """Folds the region.""" start, end = self.get_range() TextBlockHelper.set_collapsed(self._trigger, True) block = self._trigger.next() while block.blockNumber() <= end and block.isValid(): block.setVisible(False) block = block.next()
[ "def", "fold", "(", "self", ")", ":", "start", ",", "end", "=", "self", ".", "get_range", "(", ")", "TextBlockHelper", ".", "set_collapsed", "(", "self", ".", "_trigger", ",", "True", ")", "block", "=", "self", ".", "_trigger", ".", "next", "(", ")",...
Folds the region.
[ "Folds", "the", "region", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/folding.py#L102-L109
31,189
spyder-ide/spyder
spyder/plugins/editor/utils/folding.py
FoldScope.unfold
def unfold(self): """Unfolds the region.""" # set all direct child blocks which are not triggers to be visible self._trigger.setVisible(True) TextBlockHelper.set_collapsed(self._trigger, False) for block in self.blocks(ignore_blank_lines=False): block.setVisible(True) if TextBlockHelper.is_fold_trigger(block): TextBlockHelper.set_collapsed(block, False)
python
def unfold(self): """Unfolds the region.""" # set all direct child blocks which are not triggers to be visible self._trigger.setVisible(True) TextBlockHelper.set_collapsed(self._trigger, False) for block in self.blocks(ignore_blank_lines=False): block.setVisible(True) if TextBlockHelper.is_fold_trigger(block): TextBlockHelper.set_collapsed(block, False)
[ "def", "unfold", "(", "self", ")", ":", "# set all direct child blocks which are not triggers to be visible", "self", ".", "_trigger", ".", "setVisible", "(", "True", ")", "TextBlockHelper", ".", "set_collapsed", "(", "self", ".", "_trigger", ",", "False", ")", "for...
Unfolds the region.
[ "Unfolds", "the", "region", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/folding.py#L111-L119
31,190
spyder-ide/spyder
spyder/plugins/editor/utils/folding.py
FoldScope.blocks
def blocks(self, ignore_blank_lines=True): """ This generator generates the list of blocks directly under the fold region. This list does not contain blocks from child regions. :param ignore_blank_lines: True to ignore last blank lines. """ start, end = self.get_range(ignore_blank_lines=ignore_blank_lines) block = self._trigger.next() while block.blockNumber() <= end and block.isValid(): yield block block = block.next()
python
def blocks(self, ignore_blank_lines=True): """ This generator generates the list of blocks directly under the fold region. This list does not contain blocks from child regions. :param ignore_blank_lines: True to ignore last blank lines. """ start, end = self.get_range(ignore_blank_lines=ignore_blank_lines) block = self._trigger.next() while block.blockNumber() <= end and block.isValid(): yield block block = block.next()
[ "def", "blocks", "(", "self", ",", "ignore_blank_lines", "=", "True", ")", ":", "start", ",", "end", "=", "self", ".", "get_range", "(", "ignore_blank_lines", "=", "ignore_blank_lines", ")", "block", "=", "self", ".", "_trigger", ".", "next", "(", ")", "...
This generator generates the list of blocks directly under the fold region. This list does not contain blocks from child regions. :param ignore_blank_lines: True to ignore last blank lines.
[ "This", "generator", "generates", "the", "list", "of", "blocks", "directly", "under", "the", "fold", "region", ".", "This", "list", "does", "not", "contain", "blocks", "from", "child", "regions", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/folding.py#L121-L132
31,191
spyder-ide/spyder
spyder/plugins/editor/utils/folding.py
FoldScope.child_regions
def child_regions(self): """This generator generates the list of direct child regions.""" start, end = self.get_range() block = self._trigger.next() ref_lvl = self.scope_level while block.blockNumber() <= end and block.isValid(): lvl = TextBlockHelper.get_fold_lvl(block) trigger = TextBlockHelper.is_fold_trigger(block) if lvl == ref_lvl and trigger: yield FoldScope(block) block = block.next()
python
def child_regions(self): """This generator generates the list of direct child regions.""" start, end = self.get_range() block = self._trigger.next() ref_lvl = self.scope_level while block.blockNumber() <= end and block.isValid(): lvl = TextBlockHelper.get_fold_lvl(block) trigger = TextBlockHelper.is_fold_trigger(block) if lvl == ref_lvl and trigger: yield FoldScope(block) block = block.next()
[ "def", "child_regions", "(", "self", ")", ":", "start", ",", "end", "=", "self", ".", "get_range", "(", ")", "block", "=", "self", ".", "_trigger", ".", "next", "(", ")", "ref_lvl", "=", "self", ".", "scope_level", "while", "block", ".", "blockNumber",...
This generator generates the list of direct child regions.
[ "This", "generator", "generates", "the", "list", "of", "direct", "child", "regions", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/folding.py#L134-L144
31,192
spyder-ide/spyder
spyder/plugins/editor/utils/folding.py
FoldScope.parent
def parent(self): """ Return the parent scope. :return: FoldScope or None """ if TextBlockHelper.get_fold_lvl(self._trigger) > 0 and \ self._trigger.blockNumber(): block = self._trigger.previous() ref_lvl = self.trigger_level - 1 while (block.blockNumber() and (not TextBlockHelper.is_fold_trigger(block) or TextBlockHelper.get_fold_lvl(block) > ref_lvl)): block = block.previous() try: return FoldScope(block) except ValueError: return None return None
python
def parent(self): """ Return the parent scope. :return: FoldScope or None """ if TextBlockHelper.get_fold_lvl(self._trigger) > 0 and \ self._trigger.blockNumber(): block = self._trigger.previous() ref_lvl = self.trigger_level - 1 while (block.blockNumber() and (not TextBlockHelper.is_fold_trigger(block) or TextBlockHelper.get_fold_lvl(block) > ref_lvl)): block = block.previous() try: return FoldScope(block) except ValueError: return None return None
[ "def", "parent", "(", "self", ")", ":", "if", "TextBlockHelper", ".", "get_fold_lvl", "(", "self", ".", "_trigger", ")", ">", "0", "and", "self", ".", "_trigger", ".", "blockNumber", "(", ")", ":", "block", "=", "self", ".", "_trigger", ".", "previous"...
Return the parent scope. :return: FoldScope or None
[ "Return", "the", "parent", "scope", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/folding.py#L146-L164
31,193
spyder-ide/spyder
spyder/plugins/editor/utils/folding.py
FoldScope.text
def text(self, max_lines=sys.maxsize): """ Get the scope text, with a possible maximum number of lines. :param max_lines: limit the number of lines returned to a maximum. :return: str """ ret_val = [] block = self._trigger.next() _, end = self.get_range() while (block.isValid() and block.blockNumber() <= end and len(ret_val) < max_lines): ret_val.append(block.text()) block = block.next() return '\n'.join(ret_val)
python
def text(self, max_lines=sys.maxsize): """ Get the scope text, with a possible maximum number of lines. :param max_lines: limit the number of lines returned to a maximum. :return: str """ ret_val = [] block = self._trigger.next() _, end = self.get_range() while (block.isValid() and block.blockNumber() <= end and len(ret_val) < max_lines): ret_val.append(block.text()) block = block.next() return '\n'.join(ret_val)
[ "def", "text", "(", "self", ",", "max_lines", "=", "sys", ".", "maxsize", ")", ":", "ret_val", "=", "[", "]", "block", "=", "self", ".", "_trigger", ".", "next", "(", ")", "_", ",", "end", "=", "self", ".", "get_range", "(", ")", "while", "(", ...
Get the scope text, with a possible maximum number of lines. :param max_lines: limit the number of lines returned to a maximum. :return: str
[ "Get", "the", "scope", "text", "with", "a", "possible", "maximum", "number", "of", "lines", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/folding.py#L166-L180
31,194
spyder-ide/spyder
spyder/plugins/editor/extensions/manager.py
EditorExtensionsManager.add
def add(self, extension): """ Add a extension to the editor. :param extension: The extension instance to add. """ logger.debug('adding extension {}'.format(extension.name)) self._extensions[extension.name] = extension extension.on_install(self.editor) return extension
python
def add(self, extension): """ Add a extension to the editor. :param extension: The extension instance to add. """ logger.debug('adding extension {}'.format(extension.name)) self._extensions[extension.name] = extension extension.on_install(self.editor) return extension
[ "def", "add", "(", "self", ",", "extension", ")", ":", "logger", ".", "debug", "(", "'adding extension {}'", ".", "format", "(", "extension", ".", "name", ")", ")", "self", ".", "_extensions", "[", "extension", ".", "name", "]", "=", "extension", "extens...
Add a extension to the editor. :param extension: The extension instance to add.
[ "Add", "a", "extension", "to", "the", "editor", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/manager.py#L37-L47
31,195
spyder-ide/spyder
spyder/plugins/editor/extensions/manager.py
EditorExtensionsManager.remove
def remove(self, name_or_klass): """ Remove a extension from the editor. :param name_or_klass: The name (or class) of the extension to remove. :returns: The removed extension. """ logger.debug('removing extension {}'.format(name_or_klass)) extension = self.get(name_or_klass) extension.on_uninstall() self._extensions.pop(extension.name) return extension
python
def remove(self, name_or_klass): """ Remove a extension from the editor. :param name_or_klass: The name (or class) of the extension to remove. :returns: The removed extension. """ logger.debug('removing extension {}'.format(name_or_klass)) extension = self.get(name_or_klass) extension.on_uninstall() self._extensions.pop(extension.name) return extension
[ "def", "remove", "(", "self", ",", "name_or_klass", ")", ":", "logger", ".", "debug", "(", "'removing extension {}'", ".", "format", "(", "name_or_klass", ")", ")", "extension", "=", "self", ".", "get", "(", "name_or_klass", ")", "extension", ".", "on_uninst...
Remove a extension from the editor. :param name_or_klass: The name (or class) of the extension to remove. :returns: The removed extension.
[ "Remove", "a", "extension", "from", "the", "editor", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/manager.py#L49-L60
31,196
spyder-ide/spyder
spyder/plugins/editor/extensions/manager.py
EditorExtensionsManager.clear
def clear(self): """ Remove all extensions from the editor. All extensions are removed fromlist and deleted. """ while len(self._extensions): key = sorted(list(self._extensions.keys()))[0] self.remove(key)
python
def clear(self): """ Remove all extensions from the editor. All extensions are removed fromlist and deleted. """ while len(self._extensions): key = sorted(list(self._extensions.keys()))[0] self.remove(key)
[ "def", "clear", "(", "self", ")", ":", "while", "len", "(", "self", ".", "_extensions", ")", ":", "key", "=", "sorted", "(", "list", "(", "self", ".", "_extensions", ".", "keys", "(", ")", ")", ")", "[", "0", "]", "self", ".", "remove", "(", "k...
Remove all extensions from the editor. All extensions are removed fromlist and deleted.
[ "Remove", "all", "extensions", "from", "the", "editor", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/manager.py#L62-L70
31,197
spyder-ide/spyder
spyder/plugins/console/widgets/console.py
insert_text_to
def insert_text_to(cursor, text, fmt): """Helper to print text, taking into account backspaces""" while True: index = text.find(chr(8)) # backspace if index == -1: break cursor.insertText(text[:index], fmt) if cursor.positionInBlock() > 0: cursor.deletePreviousChar() text = text[index+1:] cursor.insertText(text, fmt)
python
def insert_text_to(cursor, text, fmt): """Helper to print text, taking into account backspaces""" while True: index = text.find(chr(8)) # backspace if index == -1: break cursor.insertText(text[:index], fmt) if cursor.positionInBlock() > 0: cursor.deletePreviousChar() text = text[index+1:] cursor.insertText(text, fmt)
[ "def", "insert_text_to", "(", "cursor", ",", "text", ",", "fmt", ")", ":", "while", "True", ":", "index", "=", "text", ".", "find", "(", "chr", "(", "8", ")", ")", "# backspace", "if", "index", "==", "-", "1", ":", "break", "cursor", ".", "insertTe...
Helper to print text, taking into account backspaces
[ "Helper", "to", "print", "text", "taking", "into", "account", "backspaces" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/console.py#L35-L45
31,198
spyder-ide/spyder
spyder/plugins/console/widgets/console.py
ConsoleBaseWidget.insert_text
def insert_text(self, text): """Reimplement TextEditBaseWidget method""" # Eventually this maybe should wrap to insert_text_to if # backspace-handling is required self.textCursor().insertText(text, self.default_style.format)
python
def insert_text(self, text): """Reimplement TextEditBaseWidget method""" # Eventually this maybe should wrap to insert_text_to if # backspace-handling is required self.textCursor().insertText(text, self.default_style.format)
[ "def", "insert_text", "(", "self", ",", "text", ")", ":", "# Eventually this maybe should wrap to insert_text_to if", "# backspace-handling is required", "self", ".", "textCursor", "(", ")", ".", "insertText", "(", "text", ",", "self", ".", "default_style", ".", "form...
Reimplement TextEditBaseWidget method
[ "Reimplement", "TextEditBaseWidget", "method" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/console.py#L215-L219
31,199
spyder-ide/spyder
spyder/plugins/console/widgets/console.py
ConsoleBaseWidget.append_text_to_shell
def append_text_to_shell(self, text, error, prompt): """ Append text to Python shell In a way, this method overrides the method 'insert_text' when text is inserted at the end of the text widget for a Python shell Handles error messages and show blue underlined links Handles ANSI color sequences Handles ANSI FF sequence """ cursor = self.textCursor() cursor.movePosition(QTextCursor.End) if '\r' in text: # replace \r\n with \n text = text.replace('\r\n', '\n') text = text.replace('\r', '\n') while True: index = text.find(chr(12)) if index == -1: break text = text[index+1:] self.clear() if error: is_traceback = False for text in text.splitlines(True): if (text.startswith(' File') and not text.startswith(' File "<')): is_traceback = True # Show error links in blue underlined text cursor.insertText(' ', self.default_style.format) cursor.insertText(text[2:], self.traceback_link_style.format) else: # Show error/warning messages in red cursor.insertText(text, self.error_style.format) self.exception_occurred.emit(text, is_traceback) elif prompt: # Show prompt in green insert_text_to(cursor, text, self.prompt_style.format) else: # Show other outputs in black last_end = 0 for match in self.COLOR_PATTERN.finditer(text): insert_text_to(cursor, text[last_end:match.start()], self.default_style.format) last_end = match.end() try: for code in [int(_c) for _c in match.group(1).split(';')]: self.ansi_handler.set_code(code) except ValueError: pass self.default_style.format = self.ansi_handler.get_format() insert_text_to(cursor, text[last_end:], self.default_style.format) # # Slower alternative: # segments = self.COLOR_PATTERN.split(text) # cursor.insertText(segments.pop(0), self.default_style.format) # if segments: # for ansi_tags, text in zip(segments[::2], segments[1::2]): # for ansi_tag in ansi_tags.split(';'): # self.ansi_handler.set_code(int(ansi_tag)) # self.default_style.format = self.ansi_handler.get_format() # cursor.insertText(text, self.default_style.format) self.set_cursor_position('eof') self.setCurrentCharFormat(self.default_style.format)
python
def append_text_to_shell(self, text, error, prompt): """ Append text to Python shell In a way, this method overrides the method 'insert_text' when text is inserted at the end of the text widget for a Python shell Handles error messages and show blue underlined links Handles ANSI color sequences Handles ANSI FF sequence """ cursor = self.textCursor() cursor.movePosition(QTextCursor.End) if '\r' in text: # replace \r\n with \n text = text.replace('\r\n', '\n') text = text.replace('\r', '\n') while True: index = text.find(chr(12)) if index == -1: break text = text[index+1:] self.clear() if error: is_traceback = False for text in text.splitlines(True): if (text.startswith(' File') and not text.startswith(' File "<')): is_traceback = True # Show error links in blue underlined text cursor.insertText(' ', self.default_style.format) cursor.insertText(text[2:], self.traceback_link_style.format) else: # Show error/warning messages in red cursor.insertText(text, self.error_style.format) self.exception_occurred.emit(text, is_traceback) elif prompt: # Show prompt in green insert_text_to(cursor, text, self.prompt_style.format) else: # Show other outputs in black last_end = 0 for match in self.COLOR_PATTERN.finditer(text): insert_text_to(cursor, text[last_end:match.start()], self.default_style.format) last_end = match.end() try: for code in [int(_c) for _c in match.group(1).split(';')]: self.ansi_handler.set_code(code) except ValueError: pass self.default_style.format = self.ansi_handler.get_format() insert_text_to(cursor, text[last_end:], self.default_style.format) # # Slower alternative: # segments = self.COLOR_PATTERN.split(text) # cursor.insertText(segments.pop(0), self.default_style.format) # if segments: # for ansi_tags, text in zip(segments[::2], segments[1::2]): # for ansi_tag in ansi_tags.split(';'): # self.ansi_handler.set_code(int(ansi_tag)) # self.default_style.format = self.ansi_handler.get_format() # cursor.insertText(text, self.default_style.format) self.set_cursor_position('eof') self.setCurrentCharFormat(self.default_style.format)
[ "def", "append_text_to_shell", "(", "self", ",", "text", ",", "error", ",", "prompt", ")", ":", "cursor", "=", "self", ".", "textCursor", "(", ")", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "End", ")", "if", "'\\r'", "in", "text", ":", "#...
Append text to Python shell In a way, this method overrides the method 'insert_text' when text is inserted at the end of the text widget for a Python shell Handles error messages and show blue underlined links Handles ANSI color sequences Handles ANSI FF sequence
[ "Append", "text", "to", "Python", "shell", "In", "a", "way", "this", "method", "overrides", "the", "method", "insert_text", "when", "text", "is", "inserted", "at", "the", "end", "of", "the", "text", "widget", "for", "a", "Python", "shell" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/console.py#L227-L289