code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
paths = set() for loader in self.get_loaders(): try: module = import_module(loader.__module__) get_template_sources = getattr( module, 'get_template_sources', loader.get_template_sources) template_sources = get_temp...
def find_templates(self)
Look for templates and extract the nodes containing the SASS file.
3.009801
3.001488
1.00277
compile_kwargs = { 'filename': sass_filename, 'include_paths': SassProcessor.include_paths + APPS_INCLUDE_DIRS, 'custom_functions': get_custom_functions(), } if self.sass_precision: compile_kwargs['precision'] = self.sass_precision ...
def compile_sass(self, sass_filename, sass_fileurl)
Compile the given SASS file into CSS
2.798906
2.818488
0.993052
if self.use_static_root: destpath = os.path.join(self.static_root, os.path.splitext(sass_fileurl)[0] + '.css') else: destpath = os.path.splitext(sass_filename)[0] + '.css' if os.path.isfile(destpath): os.remove(destpath) self.processed_fil...
def delete_file(self, sass_filename, sass_fileurl)
Delete a *.css file, but only if it has been generated through a SASS/SCSS file.
2.397057
2.363651
1.014133
try: # try with django-compressor<2.1 nodelist = self.parser.get_nodelist(node, original=original) except TypeError: nodelist = self.parser.get_nodelist(node, original=original, context=None) for node in nodelist: if isinstance(node, SassS...
def walk_nodes(self, node, original)
Iterate over the nodes recursively yielding the templatetag 'sass_src'
3.825614
3.254719
1.175406
def get_setting(*args): try: return getattr(settings, args[0]) except AttributeError as e: raise TemplateSyntaxError(str(e)) if hasattr(get_custom_functions, '_custom_functions'): return get_custom_functions._custom_functions get_custom_functions._custom...
def get_custom_functions()
Return a dict of function names, to be used from inside SASS
2.385624
2.34684
1.016526
df = load_datasets() if number > -1: row = df.iloc[[number]] elif name: row = df.loc[df["Name"] == name] url = ''.join(row.URL) if not url: print('The word vector you specified was not found. Please specify correct name.') widgets = ['Test: ', Percentage(), ' ', B...
def download(number=-1, name="", save_dir='./')
Download pre-trained word vector :param number: integer, default ``None`` :param save_dir: str, default './' :return: file path for downloaded file
2.61664
2.622287
0.997846
df = load_datasets() if lang == '': print(df[['Name', 'Dimension', 'Corpus', 'VocabularySize', 'Method', 'Language', 'Author']]) else: rows = df[df.Language==lang] print(rows[['Name', 'Dimension', 'Corpus', 'VocabularySize', 'Method', 'Language', 'Author']])
def search(lang='')
Search pre-trained word vectors by their language :param lang: str, default '' :return: None print search result as pandas DataFrame
3.774585
3.944093
0.957022
business_path = BUSINESS_PATH.format(business_id=business_id) response = self.client._make_request(business_path, url_params=url_params) return Business(response)
def get_by_id(self, business_id, **url_params)
Make a request to the business details endpoint. More info at https://www.yelp.com/developers/documentation/v3/business Args: business_id (str): The business alias (i.e. yelp-san-francisco) or ID (i.e. 4kMBvIEWPxWkWKFN__8SxQ. **url_params: Dict corresponding to b...
3.541843
3.899704
0.908234
json_response = raw_response.json() error_info = json_response["error"] code = error_info["code"] try: error_cls = _error_map[code] except KeyError: raise NotImplementedError( "Unknown error code '{}' returned in Yelp API response...
def from_response(raw_response)
The Yelp Fusion API returns error messages with a json body like: { 'error': { 'code': 'ALL_CAPS_CODE', 'description': 'Human readable description.' } } Some errors may have additional fields. For example, a validation erro...
3.575453
3.416196
1.046618
pin = pin if is_differential else pin + 0x04 return self._read(pin)
def read(self, pin, is_differential=False)
I2C Interface for ADS1x15-based ADCs reads. params: :param pin: individual or differential pin. :param bool is_differential: single-ended or differential read.
5.889837
8.850366
0.665491
config = _ADS1X15_CONFIG_OS_SINGLE config |= (pin & 0x07) << _ADS1X15_CONFIG_MUX_OFFSET config |= _ADS1X15_CONFIG_GAIN[self.gain] config |= self.mode config |= self.rate_config[self.data_rate] config |= _ADS1X15_CONFIG_COMP_QUE_DISABLE self._write_registe...
def _read(self, pin)
Perform an ADC read. Returns the signed integer result of the read.
3.176577
3.001554
1.058311
self.buf[0] = reg self.buf[1] = (value >> 8) & 0xFF self.buf[2] = value & 0xFF with self.i2c_device as i2c: i2c.write(self.buf)
def _write_register(self, reg, value)
Write 16 bit value to register.
2.054473
1.833171
1.120721
self.buf[0] = reg with self.i2c_device as i2c: i2c.write(self.buf, end=1, stop=False) i2c.readinto(self.buf, end=2) return self.buf[0] << 8 | self.buf[1]
def _read_register(self, reg)
Read 16 bit register value.
2.159737
1.937687
1.114595
return self._ads.read(self._pin_setting, is_differential=self.is_differential)
def value(self)
Returns the value of an ADC pin as an integer.
22.29599
12.423217
1.794703
raw = self.value volts = raw * (_ADS1X15_PGA_RANGE[self._ads.gain] / (2**(self._ads.bits-1) - 1)) return volts
def voltage(self)
Returns the voltage from the ADC pin as a floating point value.
8.663602
7.744204
1.118721
if client.client_id not in self._sequential_ids: id_ = sequential_id("e:{0}:users".format(self.name), client.client_id) self._sequential_ids[client.client_id] = id_ return self._sequential_ids[client.client_id]
def sequential_id(self, client)
Return the sequential id for this test for the passed in client
3.772659
3.708878
1.017197
if self.is_archived() or self.is_paused(): return self.control if self.is_client_excluded(client): return self.control chosen_alternative = self.existing_alternative(client) if not chosen_alternative: chosen_alternative, participate = self....
def get_alternative(self, client, dt=None, prefetch=False)
Returns and records an alternative according to the following precedence: 1. An existing alternative 2. A server-chosen alternative
4.653794
4.356222
1.06831
if dt is None: date = datetime.now() else: date = dt experiment_key = self.experiment.name pipe = self.redis.pipeline() pipe.sadd(_key("p:{0}:years".format(experiment_key)), date.strftime('%Y')) pipe.sadd(_key("p:{0}:months".format(expe...
def record_participation(self, client, dt=None)
Record a user's participation in a test along with a given variation
2.005418
2.018281
0.993627
key = _key(k) return int(monotonic_zadd(keys=[key], args=[identifier]))
def sequential_id(k, identifier)
Map an arbitrary string identifier to a set of sequential ids
19.344812
19.415228
0.996373
registry = Registry() registry.add_binding(Keys.ControlX, Keys.ControlE, filter=EmacsMode() & ~HasSelection())( get_by_name('edit-and-execute-command')) return registry
def load_emacs_open_in_editor_bindings()
Pressing C-X C-E will open the buffer in an external editor.
13.997669
11.896982
1.176573
registry = ConditionalRegistry(Registry(), EmacsMode()) handle = registry.add_binding handle(Keys.ControlV)(scroll_page_down) handle(Keys.PageDown)(scroll_page_down) handle(Keys.Escape, 'v')(scroll_page_up) handle(Keys.PageUp)(scroll_page_up) return registry
def load_extra_emacs_page_navigation_bindings()
Key bindings, for scrolling up and down through pages. This are separate bindings, because GNU readline doesn't have them.
5.03956
4.723698
1.066868
for match_variable in match.end_nodes(): varname = match_variable.varname start = match_variable.start completer = self.completers.get(varname) if completer: text = match_variable.value # Unwrap text. unw...
def _get_completions_for_match(self, match, complete_event)
Yield all the possible completions for this input string. (The completer assumes that the cursor position was at the end of the input string.)
4.237385
4.148358
1.021461
result = [] for i in items: if i not in result: result.append(i) return result
def _remove_duplicates(self, items)
Remove duplicates, while keeping the order. (Sometimes we have duplicates, because the there several matches of the same grammar, each yielding similar completions.)
2.604449
2.218605
1.173913
assert style_dict is None or isinstance(style_dict, dict) assert style_cls is None or issubclass(style_cls, pygments_Style) styles_dict = {} if style_cls is not None: styles_dict.update(style_cls.styles) if style_dict is not None: styles_dict.update(style_dict) return st...
def style_from_pygments(style_cls=pygments_DefaultStyle, style_dict=None, include_defaults=True)
Shortcut to create a :class:`.Style` instance from a Pygments style class and a style dictionary. Example:: from prompt_toolkit.styles.from_pygments import style_from_pygments from pygments.styles import get_style_by_name style = style_from_pygments(get_style_by_name('monokai')) :...
1.841041
2.213892
0.831586
" Deprecated. " return style_from_pygments( style_cls=pygments_style_cls, style_dict=style_dict, include_defaults=include_extensions)
def from_defaults(cls, style_dict=None, pygments_style_cls=pygments_DefaultStyle, include_extensions=True)
Deprecated.
5.765607
5.048484
1.142047
arrtype = HANDLE * len(handles) handle_array = arrtype(*handles) ret = windll.kernel32.WaitForMultipleObjects( len(handle_array), handle_array, BOOL(False), DWORD(timeout)) if ret == WAIT_TIMEOUT: return None else: h = handle_array[ret] return h
def _wait_for_handles(handles, timeout=-1)
Waits for multiple handles. (Similar to 'select') Returns the handle which is ready. Returns `None` on timeout. http://msdn.microsoft.com/en-us/library/windows/desktop/ms687025(v=vs.85).aspx
3.133105
3.147524
0.995419
return windll.kernel32.CreateEventA(pointer(SECURITY_ATTRIBUTES()), BOOL(True), BOOL(False), None)
def _create_event()
Creates a Win32 unnamed Event . http://msdn.microsoft.com/en-us/library/windows/desktop/ms682396(v=vs.85).aspx
7.504528
5.689472
1.31902
handles = [self._event, self._console_input_reader.handle] handles.extend(self._read_fds.keys()) return _wait_for_handles(handles, timeout)
def _ready_for_reading(self, timeout=None)
Return the handle that is ready for reading or `None` on timeout.
7.952047
6.361577
1.250012
# Append to list of pending callbacks. self._calls_from_executor.append(callback) # Set Windows event. windll.kernel32.SetEvent(self._event)
def call_from_executor(self, callback, _max_postpone_until=None)
Call this function in the main event loop. Similar to Twisted's ``callFromThread``.
7.594365
7.7974
0.973961
" Start watching the file descriptor for read availability. " h = msvcrt.get_osfhandle(fd) self._read_fds[h] = callback
def add_reader(self, fd, callback)
Start watching the file descriptor for read availability.
9.613029
5.981134
1.607225
" Stop watching the file descriptor for read availability. " h = msvcrt.get_osfhandle(fd) if h in self._read_fds: del self._read_fds[h]
def remove_reader(self, fd)
Stop watching the file descriptor for read availability.
6.305904
4.614396
1.366572
current_row = buffer.document.cursor_position_row line_range = range(from_row, to_row) # Apply transformation. new_text = buffer.transform_lines(line_range, lambda l: ' ' * count + l) buffer.document = Document( new_text, Document(new_text).translate_row_col_to_index(current...
def indent(buffer, from_row, to_row, count=1)
Indent text of a :class:`.Buffer` object.
3.513752
3.427304
1.025224
current_row = buffer.document.cursor_position_row line_range = range(from_row, to_row) def transform(text): remove = ' ' * count if text.startswith(remove): return text[len(remove):] else: return text.lstrip() # Apply transformation. new_text...
def unindent(buffer, from_row, to_row, count=1)
Unindent text of a :class:`.Buffer` object.
3.314995
3.332924
0.994621
lines = buffer.text.splitlines(True) lines_before = lines[:from_row] lines_after = lines[to_row + 1:] lines_to_reformat = lines[from_row:to_row + 1] if lines_to_reformat: # Take indentation from the first line. length = re.search(r'^\s*', lines_to_reformat[0]).end() ind...
def reshape_text(buffer, from_row, to_row)
Reformat text, taking the width into account. `to_row` is included. (Vi 'gq' operator.)
2.376552
2.370608
1.002507
def _handler(cli, buffer): cli.run_in_terminal(lambda: handler(cli, buffer), render_cli_done=render_cli_done) return AcceptAction(handler=_handler)
def run_in_terminal(cls, handler, render_cli_done=False)
Create an :class:`.AcceptAction` that runs the given handler in the terminal. :param render_cli_done: When True, render the interface in the 'Done' state first, then execute the function. If False, erase the interface instead.
6.288141
5.007276
1.255801
if buffer.validate(): if self.handler: self.handler(cli, buffer) buffer.append_to_history()
def validate_and_handle(self, cli, buffer)
Validate buffer and handle the accept action.
7.447022
6.267721
1.188155
return CompletionState(self.original_document, self.current_completions, complete_index=index)
def go_to_index(self, index)
Create a new :class:`.CompletionState` object with the new index.
19.007662
7.832496
2.42677
if self.complete_index is None: return self.original_document.text, self.original_document.cursor_position else: original_text_before_cursor = self.original_document.text_before_cursor original_text_after_cursor = self.original_document.text_after_cursor ...
def new_text_and_position(self)
Return (new_text, new_cursor_position) for this completion.
2.267662
1.985817
1.141929
assert initial_document is None or isinstance(initial_document, Document) if append_to_history: self.append_to_history() initial_document = initial_document or Document() self.__cursor_position = initial_document.cursor_position # `ValidationError` instan...
def reset(self, initial_document=None, append_to_history=False)
:param append_to_history: Append current input to history first.
6.891005
6.821626
1.01017
working_index = self.working_index working_lines = self._working_lines original_value = working_lines[working_index] working_lines[working_index] = value # Return True when this text has been changed. if len(value) != len(original_value): # For Pyth...
def _set_text(self, value)
set text at current working_index. Return whether it changed.
6.894087
6.008198
1.147447
original_position = self.__cursor_position self.__cursor_position = max(0, value) return value != original_position
def _set_cursor_position(self, value)
Set cursor position. Return whether it changed.
6.612969
4.793636
1.379531
assert isinstance(value, six.text_type), 'Got %r' % value assert self.cursor_position <= len(value) # Don't allow editing of read-only buffers. if self.read_only(): raise EditReadOnlyBuffer() changed = self._set_text(value) if changed: ...
def text(self, value)
Setting text. (When doing this, make sure that the cursor_position is valid for this text. text/cursor_position should be consistent at any time, otherwise set a Document instead.)
5.338372
4.807059
1.110528
assert isinstance(value, int) assert value <= len(self.text) changed = self._set_cursor_position(value) if changed: self._cursor_position_changed()
def cursor_position(self, value)
Setting cursor position.
4.258545
4.207578
1.012113
return self._document_cache[ self.text, self.cursor_position, self.selection_state]
def document(self)
Return :class:`~prompt_toolkit.document.Document` instance from the current text, cursor position and selection state.
13.915237
5.979327
2.327225
assert isinstance(value, Document) # Don't allow editing of read-only buffers. if not bypass_readonly and self.read_only(): raise EditReadOnlyBuffer() # Set text and cursor position first. text_changed = self._set_text(value.text) cursor_position_ch...
def set_document(self, value, bypass_readonly=False)
Set :class:`~prompt_toolkit.document.Document` instance. Like the ``document`` property, but accept an ``bypass_readonly`` argument. :param bypass_readonly: When True, don't raise an :class:`.EditReadOnlyBuffer` exception, even when the bu...
3.918383
3.450055
1.135745
# Safe if the text is different from the text at the top of the stack # is different. If the text is the same, just update the cursor position. if self._undo_stack and self._undo_stack[-1][0] == self.text: self._undo_stack[-1] = (self._undo_stack[-1][0], self.cursor_position...
def save_to_undo_stack(self, clear_redo_stack=True)
Safe current state (input text and cursor position), so that we can restore it by calling undo.
2.984449
2.794093
1.068128
# Split lines lines = self.text.split('\n') # Apply transformation for index in line_index_iterator: try: lines[index] = transform_callback(lines[index]) except IndexError: pass return '\n'.join(lines)
def transform_lines(self, line_index_iterator, transform_callback)
Transforms the text on a range of lines. When the iterator yield an index not in the range of lines that the document contains, it skips them silently. To uppercase some lines:: new_text = transform_lines(range(5,10), lambda text: text.upper()) :param line_index_iterator: ...
2.86228
3.357715
0.852449
document = self.document a = document.cursor_position + document.get_start_of_line_position() b = document.cursor_position + document.get_end_of_line_position() self.text = ( document.text[:a] + transform_callback(document.text[a:b]) + documen...
def transform_current_line(self, transform_callback)
Apply the given transformation function to the current line. :param transform_callback: callable that takes a string and return a new string.
2.804049
2.89067
0.970034
assert from_ < to self.text = ''.join([ self.text[:from_] + transform_callback(self.text[from_:to]) + self.text[to:] ])
def transform_region(self, from_, to, transform_callback)
Transform a part of the input string. :param from_: (int) start position. :param to: (int) end position. :param transform_callback: Callable which accepts a string and returns the transformed string.
3.355039
3.346968
1.002412
original_column = self.preferred_column or self.document.cursor_position_col self.cursor_position += self.document.get_cursor_up_position( count=count, preferred_column=original_column) # Remember the original column for the next up/down movement. self.preferred_col...
def cursor_up(self, count=1)
(for multiline edit). Move cursor to the previous line.
5.536909
4.643679
1.192354
original_column = self.preferred_column or self.document.cursor_position_col self.cursor_position += self.document.get_cursor_down_position( count=count, preferred_column=original_column) # Remember the original column for the next up/down movement. self.preferred_c...
def cursor_down(self, count=1)
(for multiline edit). Move cursor to the next line.
5.591929
4.783225
1.169071
if self.complete_state: self.complete_previous(count=count) elif self.document.cursor_position_row > 0: self.cursor_up(count=count) elif not self.selection_state: self.history_backward(count=count) # Go to the start of the line? ...
def auto_up(self, count=1, go_to_start_of_line_if_history_changes=False)
If we're not on the first line (of a multiline input) go a line up, otherwise go back in history. (If nothing is selected.)
3.053856
2.756234
1.107981
if self.complete_state: self.complete_next(count=count) elif self.document.cursor_position_row < self.document.line_count - 1: self.cursor_down(count=count) elif not self.selection_state: self.history_forward(count=count) # Go to the star...
def auto_down(self, count=1, go_to_start_of_line_if_history_changes=False)
If we're not on the last line (of a multiline input) go a line down, otherwise go forward in history. (If nothing is selected.)
2.936874
2.638226
1.1132
assert count >= 0 deleted = '' if self.cursor_position > 0: deleted = self.text[self.cursor_position - count:self.cursor_position] new_text = self.text[:self.cursor_position - count] + self.text[self.cursor_position:] new_cursor_position = self.curs...
def delete_before_cursor(self, count=1)
Delete specified number of characters before cursor and return the deleted text.
2.914019
2.862136
1.018128
if self.cursor_position < len(self.text): deleted = self.document.text_after_cursor[:count] self.text = self.text[:self.cursor_position] + \ self.text[self.cursor_position + len(deleted):] return deleted else: return ''
def delete(self, count=1)
Delete specified number of characters and Return the deleted text.
3.086661
2.708498
1.139621
if not self.document.on_last_line: self.cursor_position += self.document.get_end_of_line_position() self.delete() # Remove spaces. self.text = (self.document.text_before_cursor + separator + self.document.text_after_cursor.lstrip...
def join_next_line(self, separator=' ')
Join the next line to the current one by deleting the line ending after the current line.
5.115054
4.601035
1.111718
assert self.selection_state # Get lines. from_, to = sorted([self.cursor_position, self.selection_state.original_cursor_position]) before = self.text[:from_] lines = self.text[from_:to].splitlines() after = self.text[to:] # Replace leading spaces with ...
def join_selected_lines(self, separator=' ')
Join the selected lines.
3.918531
3.793503
1.032958
pos = self.cursor_position if pos >= 2: a = self.text[pos - 2] b = self.text[pos - 1] self.text = self.text[:pos-2] + b + a + self.text[pos:]
def swap_characters_before_cursor(self)
Swap the last two characters before the cursor.
2.520977
2.267565
1.111755
if index < len(self._working_lines): self.working_index = index self.cursor_position = len(self.text)
def go_to_history(self, index)
Go to this item in the history.
6.822362
6.234735
1.094251
if self.complete_state: completions_count = len(self.complete_state.current_completions) if self.complete_state.complete_index is None: index = 0 elif self.complete_state.complete_index == completions_count - 1: index = None ...
def complete_next(self, count=1, disable_wrap_around=False)
Browse to the next completions. (Does nothing if there are no completion.)
2.906862
2.650987
1.096521
if self.complete_state: if self.complete_state.complete_index == 0: index = None if disable_wrap_around: return elif self.complete_state.complete_index is None: index = len(self.complete_state.current_completio...
def complete_previous(self, count=1, disable_wrap_around=False)
Browse to the previous completions. (Does nothing if there are no completion.)
2.99307
2.608763
1.147314
assert not (go_to_first and go_to_last) # Generate list of all completions. if completions is None: if self.completer: completions = list(self.completer.get_completions( self.document, CompleteEvent(completion_requeste...
def set_completions(self, completions, go_to_first=True, go_to_last=False)
Start completions. (Generate list of completions and initialize.)
2.491054
2.397691
1.038939
found_completions = set() completions = [] # For every line of the whole history, find matches with the current line. current_line = self.document.current_line_before_cursor.lstrip() for i, string in enumerate(self._working_lines): for j, l in enumerate(str...
def start_history_lines_completion(self)
Start a completion based on all the other lines in the document and the history.
3.388073
3.339862
1.014435
assert index is None or isinstance(index, int) assert self.complete_state # Set new completion state = self.complete_state.go_to_index(index) # Set text/cursor position new_text, new_cursor_position = state.new_text_and_position() self.document = Docume...
def go_to_completion(self, index)
Select a completion from the list of current completions.
5.209245
5.072391
1.02698
assert isinstance(completion, Completion) # If there was already a completion active, cancel that one. if self.complete_state: self.go_to_completion(None) self.complete_state = None # Insert text from the given completion. self.delete_before_cursor(...
def apply_completion(self, completion)
Insert a given completion.
5.613108
5.112276
1.097967
if self.enable_history_search(): if self.history_search_text is None: self.history_search_text = self.document.text_before_cursor else: self.history_search_text = None
def _set_history_search(self)
Set `history_search_text`.
3.347142
2.688776
1.244858
return (self.history_search_text is None or self._working_lines[i].startswith(self.history_search_text))
def _history_matches(self, i)
True when the current entry matches the history search. (when we don't have history search, it's also True.)
7.850138
4.620221
1.699083
self._set_history_search() # Go forward in history. found_something = False for i in range(self.working_index + 1, len(self._working_lines)): if self._history_matches(i): self.working_index = i count -= 1 found_someth...
def history_forward(self, count=1)
Move forwards through the history. :param count: Amount of items to move forward.
4.003173
4.295058
0.932042
self._set_history_search() # Go back in history. found_something = False for i in range(self.working_index - 1, -1, -1): if self._history_matches(i): self.working_index = i count -= 1 found_something = True ...
def history_backward(self, count=1)
Move backwards through history.
4.510936
4.161162
1.084057
assert n is None or isinstance(n, int) if not len(self.history): return # Make sure we have a `YankNthArgState`. if self.yank_nth_arg_state is None: state = YankNthArgState(n=-1 if _yank_last_arg else 1) else: state = self.yank_nth_a...
def yank_nth_arg(self, n=None, _yank_last_arg=False)
Pick nth word from previous history entry (depending on current `yank_nth_arg_state`) and insert it at current position. Rotate through history if called repeatedly. If no `n` has been given, take the first argument. (The second word.) :param n: (None or int), The index of the word from...
3.103639
2.897579
1.071115
self.selection_state = SelectionState(self.cursor_position, selection_type)
def start_selection(self, selection_type=SelectionType.CHARACTERS)
Take the current cursor position as the start of this selection.
6.270576
4.25056
1.475235
new_document, clipboard_data = self.document.cut_selection() if _cut: self.document = new_document self.selection_state = None return clipboard_data
def copy_selection(self, _cut=False)
Copy selected text and return :class:`.ClipboardData` instance.
6.095995
4.618227
1.319986
assert isinstance(data, ClipboardData) assert paste_mode in (PasteMode.VI_BEFORE, PasteMode.VI_AFTER, PasteMode.EMACS) original_document = self.document self.document = self.document.paste_clipboard_data(data, paste_mode=paste_mode, count=count) # Remember original doc...
def paste_clipboard_data(self, data, paste_mode=PasteMode.EMACS, count=1)
Insert the data from the clipboard.
4.299321
4.160561
1.033351
if copy_margin: self.insert_text('\n' + self.document.leading_whitespace_in_current_line) else: self.insert_text('\n')
def newline(self, copy_margin=True)
Insert a line ending at the current position.
4.491732
3.837907
1.17036
if copy_margin: insert = self.document.leading_whitespace_in_current_line + '\n' else: insert = '\n' self.cursor_position += self.document.get_start_of_line_position() self.insert_text(insert) self.cursor_position -= 1
def insert_line_above(self, copy_margin=True)
Insert a new line above the current one.
3.562657
3.386284
1.052085
if copy_margin: insert = '\n' + self.document.leading_whitespace_in_current_line else: insert = '\n' self.cursor_position += self.document.get_end_of_line_position() self.insert_text(insert)
def insert_line_below(self, copy_margin=True)
Insert a new line below the current one.
3.858293
3.670837
1.051066
# Original text & cursor position. otext = self.text ocpos = self.cursor_position # In insert/text mode. if overwrite: # Don't overwrite the newline itself. Just before the line ending, # it should act like insert mode. overwritten_te...
def insert_text(self, data, overwrite=False, move_cursor=True, fire_event=True)
Insert characters at cursor position. :param fire_event: Fire `on_text_insert` event. This is mainly used to trigger autocompletion while typing.
3.235568
3.238836
0.998991
# Don't call the validator again, if it was already called for the # current input. if self.validation_state != ValidationState.UNKNOWN: return self.validation_state == ValidationState.VALID # Validate first. If not valid, set validation exception. if self.v...
def validate(self)
Returns `True` if valid.
3.65458
3.458324
1.056749
# Validate first. If not valid, set validation exception. if not self.validate(): return # Save at the tail of the history. (But don't if the last entry the # history is already the same.) if self.text and (not len(self.history) or self.history[-1] != self.t...
def append_to_history(self)
Append the current input to the history. (Only if valid input.)
7.163072
6.26654
1.143067
assert isinstance(search_state, SearchState) assert isinstance(count, int) and count > 0 text = search_state.text direction = search_state.direction ignore_case = search_state.ignore_case() def search_once(working_index, document): if d...
def _search(self, search_state, include_current_position=False, count=1)
Execute search. Return (working_index, cursor_position) tuple when this search is applied. Returns `None` when this text cannot be found.
2.432217
2.352975
1.033677
search_result = self._search(search_state, include_current_position=True) if search_result is None: return self.document else: working_index, cursor_position = search_result # Keep selection, when `working_index` was not changed. if work...
def document_for_search(self, search_state)
Return a :class:`~prompt_toolkit.document.Document` instance that has the text/cursor position for this search, if we would apply it. This will be used in the :class:`~prompt_toolkit.layout.controls.BufferControl` to display feedback while searching.
4.47011
4.247327
1.052453
search_result = self._search( search_state, include_current_position=include_current_position, count=count) if search_result is None: return self.cursor_position else: working_index, cursor_position = search_result return cursor_position
def get_search_position(self, search_state, include_current_position=True, count=1)
Get the cursor position for this search. (This operation won't change the `working_index`. It's won't go through the history. Vi text objects can't span multiple items.)
3.403858
2.511692
1.355205
if self.read_only(): raise EditReadOnlyBuffer() # Write to temporary file descriptor, filename = tempfile.mkstemp(self.tempfile_suffix) os.write(descriptor, self.text.encode('utf-8')) os.close(descriptor) # Open in editor # (We need to use `...
def open_in_editor(self, cli)
Open code in editor. :param cli: :class:`~prompt_toolkit.interface.CommandLineInterface` instance.
4.451326
4.28844
1.037983
# If the 'VISUAL' or 'EDITOR' environment variable has been set, use that. # Otherwise, fall back to the first available editor that we can find. visual = os.environ.get('VISUAL') editor = os.environ.get('EDITOR') editors = [ visual, editor, ...
def _open_file_in_editor(self, filename)
Call editor executable. Return True when we received a zero return code.
3.492577
3.3693
1.036588
# Note: We cannot use "yield from", because this package also # installs on Python 2. assert isinstance(callbacks, EventLoopCallbacks) if self.closed: raise Exception('Event loop already closed.') timeout = AsyncioTimeout(INPUT_TIMEOUT, callbacks.inpu...
def run_as_coroutine(self, stdin, callbacks)
The input 'event loop'.
6.067854
5.735118
1.058017
# Cache, because this one is reused very often. if self._cache.lines is None: self._cache.lines = _ImmutableLineList(self.text.split('\n')) return self._cache.lines
def lines(self)
Array of all the lines.
8.825977
8.104761
1.088987
# Cache, because this is often reused. (If it is used, it's often used # many times. And this has to be fast for editing big documents!) if self._cache.line_indexes is None: # Create list of line lengths. line_lengths = map(len, self.lines) # Calcula...
def _line_start_indexes(self)
Array pointing to the start indexes of all the lines.
5.623251
5.39821
1.041688
current_line = self.current_line length = len(current_line) - len(current_line.lstrip()) return current_line[:length]
def leading_whitespace_in_current_line(self)
The leading whitespace in the left margin of the current line.
3.068158
2.46315
1.245624
# (Don't use self.text_before_cursor to calculate this. Creating # substrings and doing rsplit is too expensive for getting the cursor # position.) _, line_start_index = self._find_line_start_index(self.cursor_position) return self.cursor_position - line_start_index
def cursor_position_col(self)
Current column. (0-based.)
9.098372
8.695313
1.046354
indexes = self._line_start_indexes pos = bisect.bisect_right(indexes, index) - 1 return pos, indexes[pos]
def _find_line_start_index(self, index)
For the index of a character at a certain line, calculate the index of the first character on that line. Return (row, index) tuple.
5.154681
5.370384
0.959835
# Find start of this line. row, row_index = self._find_line_start_index(index) col = index - row_index return row, col
def translate_index_to_position(self, index)
Given an index for the text, return the corresponding (row, col) tuple. (0-based. Returns (0, 0) for index=0.)
6.767431
4.514558
1.499024
try: result = self._line_start_indexes[row] line = self.lines[row] except IndexError: if row < 0: result = self._line_start_indexes[0] line = self.lines[0] else: result = self._line_start_indexes[-1]...
def translate_row_col_to_index(self, row, col)
Given a (row, col) tuple, return the corresponding index. (Row and col params are 0-based.) Negative row/col values are turned into zero.
3.571857
3.476476
1.027436
return self.text.find(sub, self.cursor_position) == self.cursor_position
def has_match_at_current_position(self, sub)
`True` when this substring is found at the cursor position.
4.954324
3.748143
1.321808
assert isinstance(ignore_case, bool) if in_current_line: text = self.current_line_after_cursor else: text = self.text_after_cursor if not include_current_position: if len(text) == 0: return # (Otherwise, we always get a matc...
def find(self, sub, in_current_line=False, include_current_position=False, ignore_case=False, count=1)
Find `text` after the cursor, return position relative to the cursor position. Return `None` if nothing was found. :param count: Find the n-th occurance.
2.745114
2.78927
0.984169
flags = re.IGNORECASE if ignore_case else 0 return [a.start() for a in re.finditer(re.escape(sub), self.text, flags)]
def find_all(self, sub, ignore_case=False)
Find all occurances of the substring. Return a list of absolute positions in the document.
2.49013
2.464592
1.010362
if in_current_line: before_cursor = self.current_line_before_cursor[::-1] else: before_cursor = self.text_before_cursor[::-1] flags = re.IGNORECASE if ignore_case else 0 iterator = re.finditer(re.escape(sub[::-1]), before_cursor, flags) try: ...
def find_backwards(self, sub, in_current_line=False, ignore_case=False, count=1)
Find `text` before the cursor, return position relative to the cursor position. Return `None` if nothing was found. :param count: Find the n-th occurance.
2.679794
2.564982
1.044761
if self.text_before_cursor[-1:].isspace(): return '' else: return self.text_before_cursor[self.find_start_of_previous_word(WORD=WORD):]
def get_word_before_cursor(self, WORD=False)
Give the word before the cursor. If we have whitespace before the cursor this returns an empty string.
3.837114
3.53759
1.084669
# Reverse the text before the cursor, in order to do an efficient # backwards search. text_before_cursor = self.text_before_cursor[::-1] regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE iterator = regex.finditer(text_before_cursor) try: for i, m...
def find_start_of_previous_word(self, count=1, WORD=False)
Return an index relative to the cursor position pointing to the start of the previous word. Return `None` if nothing was found.
4.767371
4.321896
1.103074
text_before_cursor = self.current_line_before_cursor[::-1] text_after_cursor = self.current_line_after_cursor def get_regex(include_whitespace): return { (False, False): _FIND_CURRENT_WORD_RE, (False, True): _FIND_CURRENT_WORD_INCLUDE_TRAILIN...
def find_boundaries_of_current_word(self, WORD=False, include_leading_whitespace=False, include_trailing_whitespace=False)
Return the relative boundaries (startpos, endpos) of the current word under the cursor. (This is at the current line, because line boundaries obviously don't belong to any word.) If not on a word, this returns (0,0)
2.745028
2.73328
1.004298
start, end = self.find_boundaries_of_current_word(WORD=WORD) return self.text[self.cursor_position + start: self.cursor_position + end]
def get_word_under_cursor(self, WORD=False)
Return the word, currently below the cursor. This returns an empty string when the cursor is on a whitespace region.
3.995656
3.525816
1.133257