output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def get_view(self, mo_ref, properties=None): """Get a view of a vSphere managed object. :param mo_ref: The MOR to get a view of :type mo_ref: ManagedObjectReference :param properties: A list of properties to retrieve from the \ server :type properties: list ...
Write a Python 3 script for returning a view of a managed object.
You are a Python code architect, reviewing and designing scalable and efficient code
def get_views(self, mo_refs, properties=None): """Get a list of local view's for multiple managed objects. :param mo_refs: The list of ManagedObjectReference's that views are \ to be created for. :type mo_refs: ManagedObjectReference :param properties: The properties to retrieve...
Implement a Python 3 function for getting a list of local views for multiple managed objects.
You are a Python code generator, capable of creating scripts from specifications.
def get_search_filter_spec(self, begin_entity, property_spec): """Build a PropertyFilterSpec capable of full inventory traversal. By specifying all valid traversal specs we are creating a PFS that can recursively select any object under the given entity. :param begin_entity: Th...
Can you implement a function in Python 3 that builds a PropertyFilterSpec capable of full inventory traversal.
As a Python code composer, you craft elegant and concise scripts.
Invoke a \ *_Task method and wait for it to complete.
Make a summary of the following Python 3 code def invoke_task(self, method, **kwargs): # Don't execute methods which don't return a Task object if not method.endswith('_Task'): logger.error('invoke_task can only be used for methods which ' 'return a ManagedObjectReference t...
As a Python code analyst, you investigate and solve complex coding mysteries
def find_entity_views(self, view_type, begin_entity=None, properties=None): """Find all ManagedEntity's of the requested type. :param view_type: The type of ManagedEntity's to find. :type view_type: str :param begin_entity: The MOR to start searching for the entity. \ The defaul...
How would you code a function in Python 3 to find all ManagedEntity s of the requested type.
You are a Python code architect, reviewing and designing scalable and efficient code
def find_entity_view(self, view_type, begin_entity=None, filter={}, properties=None): """Find a ManagedEntity of the requested type. Traverses the MOB looking for an entity matching the filter. :param view_type: The type of ManagedEntity to find. :type view_typ...
Can you implement a function in Python 3 that finds a ManagedEntity of the requested type.
As a Python code composer, you craft elegant and concise scripts.
def load_template(name=None): """Loads a template of the specified name. Templates are placed in the <template_dir> directory in YAML format with a .yaml extension. If no name is specified then the function will return the default template (<template_dir>/default.yaml) if it exists. :para...
Write a Python 3 function for loading a template of the specified name.
As a Python code composer, you craft elegant and concise scripts.
def list_templates(): """Returns a list of all templates.""" templates = [f for f in glob.glob(os.path.join(template_path, '*.yaml'))] return templates
Implement a function in Python 3 to return a list of all templates.
As a Python code translator, you convert algorithms and pseudocode into Python.
Creates a virtual machine using the specified values.
Here you have a function in Python 3, explain what it does def create_vm(client, name, compute_resource, datastore, disksize, nics, memory, num_cpus, guest_id, host=None): """Create a virtual machine using the specified values. :param name: The name of the VM to create. :type name: str :p...
As a Python code composer, you craft elegant and concise scripts.
Create a NIC spec for a target.
Make a summary of the following Python 3 code def create_nic(client, target, nic): # Iterate through the networks and look for one matching # the requested name for network in target.network: if network.name == nic["network_name"]: net = network break else: return...
As a Python code translator, you convert algorithms and pseudocode into Python.
Adds an ignore pattern to the list for ignore patterns.
Here you have a function in Python 3, explain what it does def add_ignore_patterns(self, *patterns): for ptrn in patterns: if isinstance(ptrn, list): for p in ptrn: self._ignored_patterns.append(p) else: self._ignored_patterns.append(pt...
You are a Python code analyst, evaluating scripts for potential improvements.
Sets the context menu of the tree view.
Explain what the following Python 3 code does def set_context_menu(self, context_menu): self.context_menu = context_menu self.context_menu.tree_view = self self.context_menu.init_actions() for action in self.context_menu.actions(): self.addAction(action)
As a Python code translator, you convert algorithms and pseudocode into Python.
def set_root_path(self, path, hide_extra_columns=True): """ Sets the root path to watch :param path: root path - str :param hide_extra_columns: Hide extra column (size, paths,...) """ if not self.isVisible(): self._path_to_set = path self._hide_ext...
Can you implement a function in Python 3 that sets the root path to watch.
You are a Python code analyst, evaluating scripts for potential improvements.
def filePath(self, index): """ Gets the file path of the item at the specified ``index``. :param index: item index - QModelIndex :return: str """ return self._fs_model_source.filePath( self._fs_model_proxy.mapToSource(index))
How would you code a function in Python 3 to get the file path of the item at the specified index.
You are a Python code architect, reviewing and designing scalable and efficient code
def fileInfo(self, index): """ Gets the file info of the item at the specified ``index``. :param index: item index - QModelIndex :return: QFileInfo """ return self._fs_model_source.fileInfo( self._fs_model_proxy.mapToSource(index))
Write a Python 3 script for retrieving the file info of the item at the specified index.
You are a Python code architect, reviewing and designing scalable and efficient code
def copy_to_clipboard(self, copy=True): """ Copies the selected items to the clipboard :param copy: True to copy, False to cut. """ urls = self.selected_urls() if not urls: return mime = self._UrlListMimeData(copy) mime.set_list(urls) c...
How would you code a function in Python 3 to copy the selected items to the clipboard.
You are a Python code architect, reviewing and designing scalable and efficient code
Gets the list of selected items file paths
Make a summary of the following Python 3 code def selected_urls(self): urls = [] debug('gettings urls') for proxy_index in self.tree_view.selectedIndexes(): finfo = self.tree_view.fileInfo(proxy_index) urls.append(finfo.canonicalFilePath()) debug('selected urls %r...
You are a Python code generator, capable of creating scripts from specifications.
def paste_from_clipboard(self): """ Pastes files from clipboard. """ to = self.get_current_path() if os.path.isfile(to): to = os.path.abspath(os.path.join(to, os.pardir)) mime = QtWidgets.QApplication.clipboard().mimeData() paste_operation = None ...
Implement a Python 3 function for pasting files from clipboard.
As a Python code composer, you craft elegant and concise scripts.
def _paste(self, sources, destination, copy): """ Copies the files listed in ``sources`` to destination. Source are removed if copy is set to False. """ for src in sources: debug('%s <%s> to <%s>' % ( 'copying' if copy else 'cutting', src, destination)...
Write a Python 3 function for pasting the files listed in sources to destination.
As a Python code analyst, you investigate and solve complex coding mysteries
def _get_files(path): """ Returns the list of files contained in path (recursively). """ ret_val = [] for root, _, files in os.walk(path): for f in files: ret_val.append(os.path.join(root, f)) return ret_val
Implement a Python 3 function for returning the list of files contained in path.
As a Python code composer, you craft elegant and concise scripts.
Deletes the selected items.
Explain what the following Python 3 code does def delete(self): urls = self.selected_urls() rep = QtWidgets.QMessageBox.question( self.tree_view, _('Confirm delete'), _('Are you sure about deleting the selected files/directories?'), QtWidgets.QMessageBox.Yes | QtWidge...
As a Python code analyst, you investigate and solve complex coding mysteries
Gets the path of the currently selected item.
How would you explain what the following Python 3 function does def get_current_path(self): path = self.tree_view.fileInfo( self.tree_view.currentIndex()).filePath() # https://github.com/pyQode/pyQode/issues/6 if not path: path = self.tree_view.root_path return pa...
As a Python code analyst, you investigate and solve complex coding mysteries
Copies the current path to the clipboard
Explain what the following Python 3 code does def copy_path_to_clipboard(self): path = self.get_current_path() QtWidgets.QApplication.clipboard().setText(path) debug('path copied: %s' % path)
As a Python code composer, you craft elegant and concise scripts.
def rename(self): """ Renames the selected item in the tree view """ src = self.get_current_path() pardir, name = os.path.split(src) new_name, status = QtWidgets.QInputDialog.getText( self.tree_view, _('Rename '), _('New name:'), QtWidgets.QLineEdi...
Create a Python 3 function to rename the selected item in the tree view.
As a Python code composer, you craft elegant and concise scripts.
def create_directory(self): """ Creates a directory under the selected directory (if the selected item is a file, the parent directory is used). """ src = self.get_current_path() name, status = QtWidgets.QInputDialog.getText( self.tree_view, _('Create director...
Implement a function in Python 3 to create a directory under the selected directory.
As a Python code analyst, you investigate and solve complex coding mysteries
def create_file(self): """ Creates a file under the current directory. """ src = self.get_current_path() name, status = QtWidgets.QInputDialog.getText( self.tree_view, _('Create new file'), _('File name:'), QtWidgets.QLineEdit.Normal, '') if status...
Write a Python 3 script for creating a file under the current directory.
You are a Python code generator, capable of creating scripts from specifications.
Guesses the mime type of a file.
Can you generate a brief explanation for the following Python 3 code def get_mimetype(path): filename = os.path.split(path)[1] mimetype = mimetypes.guess_type(filename)[0] if mimetype is None: mimetype = 'text/x-plain' _logger().debug('mimetype detected: %s', mimetype) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def open(self, path, encoding=None, use_cached_encoding=True): """ Open a file and set its content on the editor widget. pyqode does not try to guess encoding. It's up to the client code to handle encodings. You can either use a charset detector to detect encoding or rely on a s...
Implement a function in Python 3 to open a file and set its content on the editor widget.
As a Python code translator, you convert algorithms and pseudocode into Python.
Reload the file with another encoding.
Here you have a function in Python 3, explain what it does def reload(self, encoding): assert os.path.exists(self.path) self.open(self.path, encoding=encoding, use_cached_encoding=False)
As a Python code translator, you convert algorithms and pseudocode into Python.
def save(self, path=None, encoding=None, fallback_encoding=None): """ Save the editor content to a file. :param path: optional file path. Set it to None to save using the current path (save), set a new path to save as. :param encoding: optional encoding, will use th...
Implement a Python 3 function for saving the content of the current file to a file.
You are a Python code architect, reviewing and designing scalable and efficient code
Close the file open in the editor
How would you explain what the following Python 3 function does def close(self, clear=True): Cache().set_cursor_position( self.path, self.editor.textCursor().position()) self.editor._original_text = '' if clear: self.editor.clear() self._path = '' self.mim...
You are a Python code generator, capable of creating scripts from specifications.
def on_state_changed(self, state): """ Connects/Disconnects to the painted event of the editor :param state: Enable state """ if state: self.editor.painted.connect(self._paint_margin) self.editor.repaint() else: self.editor.painted.dis...
Can you implement a function in Python 3 that connects and disconnects to the painted event of the editor
As a python code expert, you are capable of creating scripts from specifications.
Paints the right margin after editor paint event.
Given the following Python 3 function, write the documentation def _paint_margin(self, event): font = QtGui.QFont(self.editor.font_name, self.editor.font_size + self.editor.zoom_level) metrics = QtGui.QFontMetricsF(font) pos = self._margin_pos offset = self.edi...
You are a Python code generator, capable of creating scripts from specifications.
def _check_file(self): """ Checks watched file moficiation time and permission changes. """ try: self.editor.toPlainText() except RuntimeError: self._timer.stop() return if self.editor and self.editor.file.path: if not os.pa...
Write a Python 3 function that can check if the file is in the file system and if it is writable checks if the file is in the file system and if it is writable checks if the file is in the file system and if it is writable checks if the file is in the file system and if it is not writeable
You are a Python code analyst, evaluating scripts for potential improvements.
def _notify(self, title, message, expected_action=None): """ Notify user from external event """ if self.editor is None: return inital_value = self.editor.save_on_focus_out self.editor.save_on_focus_out = False self._flg_notify = True dlg_type ...
Can you create a Python 3 function that notifies user from external event
As a python code expert, you are capable of creating scripts from specifications.
def _notify_change(self): """ Notify user from external change if autoReloadChangedFiles is False then reload the changed file in the editor """ def inner_action(*args): """ Inner action: open file """ # cache cursor position before reloading so that the c...
Create a Python 3 function to notify user from external change
You are a Python code analyst, evaluating scripts for potential improvements.
def _check_for_pending(self, *args, **kwargs): """ Checks if a notification is pending. """ if self._notification_pending and not self._processing: self._processing = True args, kwargs = self._data self._notify(*args, **kwargs) self._notifi...
Implement a function in Python 3 to check if a notification is pending.
You are a Python code analyst, evaluating scripts for potential improvements.
def _notify_deleted_file(self): """ Notify user from external file deletion. """ self.file_deleted.emit(self.editor) # file deleted, disable file watcher self.enabled = False
Write a Python 3 function that can notify user from external file deletion.
As a Python code analyst, you investigate and solve complex coding mysteries
def get_gae_versions(): """Gets a list of all of the available Python SDK versions, sorted with the newest last.""" r = requests.get(SDK_RELEASES_URL) r.raise_for_status() releases = r.json().get('items', {}) # We only care about the Python releases, which all are in the format # "featured...
Write a Python 3 script for getting a list of all of the available Python SDK versions sorted with the newest last.
You are a Python code architect, reviewing and designing scalable and efficient code
def is_existing_up_to_date(destination, latest_version): """Returns False if there is no existing install or if the existing install is out of date. Otherwise, returns True.""" version_path = os.path.join( destination, 'google_appengine', 'VERSION') if not os.path.exists(version_path): ...
Can you create a Python 3 function that returns True if the existing install is up to date. Otherwise returns False.
As a Python code analyst, you investigate and solve complex coding mysteries
Downloads the SDK and returns a file - like object for the zip content.
Can you generate the documentation for the following Python 3 function def download_sdk(url): r = requests.get(url) r.raise_for_status() return StringIO(r.content)
You are a Python code analyst, evaluating scripts for potential improvements.
Fixup the version number in the VERSION file.
Explain what the following Python 3 code does def fixup_version(destination, version): version_path = os.path.join( destination, 'google_appengine', 'VERSION') with open(version_path, 'r') as f: version_data = f.read() version_data = version_data.replace( 'release: "0.0.0"', ...
As a python code expert, you are capable of creating scripts from specifications.
Downloads and extracts the latest App Engine SDK to the given destination.
How would you explain what the following Python 3 function does def download_command(args): latest_two_versions = list(reversed(get_gae_versions()))[:2] zip = None version_number = None for version in latest_two_versions: if is_existing_up_to_date(args.destination, version[0]): pri...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a list of user defined encodings for display in the encodings menu / combobox.
Make a summary of the following Python 3 code def preferred_encodings(self): default_encodings = [ locale.getpreferredencoding().lower().replace('-', '_')] if 'utf_8' not in default_encodings: default_encodings.append('utf_8') default_encodings = list(set(default_encoding...
As a python code expert, you are capable of creating scripts from specifications.
Gets an eventual cached encoding for a file.
Make a summary of the following Python 3 code def get_file_encoding(self, file_path, preferred_encoding=None): _logger().debug('getting encoding for %s', file_path) try: map = json.loads(self._settings.value('cachedFileEncodings')) except TypeError: map = {} try: ...
As a python code expert, you are capable of creating scripts from specifications.
Sets the encoding of the specified file path.
Can you generate the documentation for the following Python 3 function def set_file_encoding(self, path, encoding): try: map = json.loads(self._settings.value('cachedFileEncodings')) except TypeError: map = {} map[path] = encoding self._settings.setValue('cachedFi...
As a python code expert, you are capable of creating scripts from specifications.
Gets the cached cursor position for a file in the cache
Can you generate a brief explanation for the following Python 3 code def get_cursor_position(self, file_path): try: map = json.loads(self._settings.value('cachedCursorPosition')) except TypeError: map = {} try: pos = map[file_path] except KeyError: ...
As a Python code analyst, you investigate and solve complex coding mysteries
def set_cursor_position(self, path, position): """ Cache encoding for the specified file path. :param path: path of the file to cache :param position: cursor position to cache """ try: map = json.loads(self._settings.value('cachedCursorPosition')) exc...
Can you implement a function in Python 3 that sets the cursor position for the specified file path.
You are a Python code architect, reviewing and designing scalable and efficient code
def _mid(string, start, end=None): """ Returns a substring delimited by start and end position. """ if end is None: end = len(string) return string[start:start + end]
Write a Python 3 script to return a substring delimited by start and end position.
You are a Python code architect, reviewing and designing scalable and efficient code
def _ansi_color(code, theme): """ Converts an ansi code to a QColor, taking the color scheme (theme) into account. """ red = 170 if code & 1 else 0 green = 170 if code & 2 else 0 blue = 170 if code & 4 else 0 color = QtGui.QColor(red, green, blue) if theme is not None: mappings =...
Write a Python 3 function for converting an ansi code to a QColor
As a Python code composer, you craft elegant and concise scripts.
def _qkey_to_ascii(event): """ (Try to) convert the Qt key event to the corresponding ASCII sequence for the terminal. This works fine for standard alphanumerical characters, but most other characters require terminal specific control_modifier sequences. The conversion below works for TERM="linux' t...
Write a Python 3 script for converting a Qt key event to an ASCII sequence.
You are a Python code architect, reviewing and designing scalable and efficient code
def is_running(self): """ Checks if the child process is running (or is starting). """ return self._process.state() in [self._process.Running, self._process.Starting]
Can you create a Python 3 function that checks if the child process is running.
You are a Python code generator, capable of creating scripts from specifications.
Starts the child process.
How would you explain what the following Python 3 function does def start_process(self, program, arguments=None, working_dir=None, print_command=True, use_pseudo_terminal=True, env=None): """ Starts the child process. :param program: program to start :param argumen...
You are a Python code analyst, evaluating scripts for potential improvements.
Stops the child process.
Make a summary of the following Python 3 code def stop_process(self): self._process.terminate() if not self._process.waitForFinished(100): self._process.kill()
As a python code expert, you are capable of creating scripts from specifications.
Terminates the child process on close.
How would you explain what the following Python 3 function does def closeEvent(self, event): self.stop_process() self.backend.stop() try: self.modes.remove('_LinkHighlighter') except KeyError: pass # already removed super(OutputWindow, self).closeEvent(ev...
As a python code expert, you are capable of creating scripts from specifications.
Handles key press event using the input handler.
Here you have a function in Python 3, explain what it does def keyPressEvent(self, event): if self._process.state() != self._process.Running: return tc = self.textCursor() sel_start = tc.selectionStart() sel_end = tc.selectionEnd() tc.setPosition(self._formatter._last...
You are a Python code analyst, evaluating scripts for potential improvements.
Handles mouse over file link.
Can you generate the documentation for the following Python 3 function def mouseMoveEvent(self, event): c = self.cursorForPosition(event.pos()) block = c.block() self._link_match = None self.viewport().setCursor(QtCore.Qt.IBeamCursor) for match in self.link_regex.finditer(block.t...
As a Python code analyst, you investigate and solve complex coding mysteries
Handle file link clicks.
Here you have a function in Python 3, explain what it does def mousePressEvent(self, event): super(OutputWindow, self).mousePressEvent(event) if self._link_match: path = self._link_match.group('url') line = self._link_match.group('line') if line is not None: ...
As a Python code analyst, you investigate and solve complex coding mysteries
def _init_code_edit(self, backend): """ Initializes the code editor (setup modes, panels and colors). """ from pyqode.core import panels, modes self.modes.append(_LinkHighlighter(self.document())) self.background = self._formatter.color_scheme.background self.fore...
Create a Python 3 function to initialize the code editor.
You are a Python code architect, reviewing and designing scalable and efficient code
def _setup_process_environment(self, env): """ Sets up the process environment. """ environ = self._process.processEnvironment() if env is None: env = {} for k, v in os.environ.items(): environ.insert(k, v) for k, v in env.items(): ...
Can you create a Python 3 function that sets up the process environment.
You are a Python code generator, capable of creating scripts from specifications.
Display child process error in the text edit.
Can you generate the documentation for the following Python 3 function def _on_process_error(self, error): if self is None: return err = PROCESS_ERROR_STRING[error] self._formatter.append_message(err + '\r\n', output_format=OutputFormat.ErrorMessageFormat)
You are a Python code architect, reviewing and designing scalable and efficient code
Write the process finished message and emit the finished signal.
Given the following Python 3 function, write the documentation def _on_process_finished(self): exit_code = self._process.exitCode() if self._process.exitStatus() != self._process.NormalExit: exit_code = 139 self._formatter.append_message('\x1b[0m\nProcess finished with exit code %d' ...
As a python code expert, you are capable of creating scripts from specifications.
def _read_stdout(self): """ Reads the child process' stdout and process it. """ output = self._decode(self._process.readAllStandardOutput().data()) if self._formatter: self._formatter.append_message(output, output_format=OutputFormat.NormalMessageFormat) else:...
Create a Python 3 function for reading the child process s stdout and processes it.
As a Python code translator, you convert algorithms and pseudocode into Python.
Reads the child process s stderr and processes it.
Can you tell what is the following Python 3 function doing def _read_stderr(self): output = self._decode(self._process.readAllStandardError().data()) if self._formatter: self._formatter.append_message(output, output_format=OutputFormat.ErrorMessageFormat) else: self.inser...
You are a Python code architect, reviewing and designing scalable and efficient code
def parse_text(self, formatted_text): """ Retursn a list of operations (draw, cup, ed,...). Each operation consist of a command and its associated data. :param formatted_text: text to parse with the default char format to apply. :return: list of Operation """ as...
Write a Python 3 script to parse the text in the format specified by the user and returns a list of operations.
As a Python code composer, you craft elegant and concise scripts.
def _set_format_scope(self, fmt): """ Opens the format scope. """ self._prev_fmt = QtGui.QTextCharFormat(fmt) self._prev_fmt_closed = False
Can you implement a function in Python 3 that sets the format scope.
As a python code expert, you are capable of creating scripts from specifications.
Adds a command to the history and reset the index.
How would you explain what the following Python 3 function does def add_command(self, command): try: self._history.remove(command) except ValueError: pass self._history.insert(0, command) self._index = -1
You are a Python code generator, capable of creating scripts from specifications.
def scroll_up(self): """ Returns the previous command, if any. """ self._index += 1 nb_commands = len(self._history) if self._index >= nb_commands: self._index = nb_commands - 1 try: return self._history[self._index] except IndexErr...
Can you write a function in Python 3 where it scrolls up the command list.
As a Python code composer, you craft elegant and concise scripts.
Scrolls down the log.
Can you tell what is the following Python 3 function doing def scroll_down(self): self._index -= 1 if self._index < 0: self._index = -1 return '' try: return self._history[self._index] except IndexError: return ''
As a Python code analyst, you investigate and solve complex coding mysteries
Insert command into the text edit.
Can you generate the documentation for the following Python 3 function def _insert_command(self, command): self._clear_user_buffer() tc = self.edit.textCursor() tc.insertText(command) self.edit.setTextCursor(tc)
You are a Python code architect, reviewing and designing scalable and efficient code
Handles key press events.
Can you generate the documentation for the following Python 3 function def key_press_event(self, event): input_buffer = self._get_input_buffer() ctrl = int(event.modifiers() & QtCore.Qt.ControlModifier) != 0 shift = int(event.modifiers() & QtCore.Qt.ShiftModifier) != 0 delete = event.key...
As a python code expert, you are capable of creating scripts from specifications.
def append_message(self, text, output_format=OutputFormat.NormalMessageFormat): """ Parses and append message to the text edit. """ self._append_message(text, self._formats[output_format])
Create a Python 3 function for appending a message to the edit.
As a Python code composer, you craft elegant and concise scripts.
def _append_message(self, text, char_format): """ Parses text and executes parsed operations. """ self._cursor = self._text_edit.textCursor() operations = self._parser.parse_text(FormattedText(text, char_format)) for i, operation in enumerate(operations): try:...
Create a Python 3 function to append a message to the internal buffer.
You are a Python code architect, reviewing and designing scalable and efficient code
Draw text from the cursor.
Can you tell what is the following Python 3 function doing def _draw(self, data): self._cursor.clearSelection() self._cursor.setPosition(self._last_cursor_pos) if '\x07' in data.txt: print('\a') txt = data.txt.replace('\x07', '') if '\x08' in txt: parts ...
As a python code expert, you are capable of creating scripts from specifications.
def _draw_chars(self, data, to_draw): """ Draw the specified charachters using the specified format. """ i = 0 while not self._cursor.atBlockEnd() and i < len(to_draw) and len(to_draw) > 1: self._cursor.deleteChar() i += 1 self._cursor.insertText(t...
Create a Python 3 function for drawing the specified charachters using the specified format.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _linefeed(self): """ Performs a line feed. """ last_line = self._cursor.blockNumber() == self._text_edit.blockCount() - 1 if self._cursor.atEnd() or last_line: if last_line: self._cursor.movePosition(self._cursor.EndOfBlock) self._curso...
How would you code a function in Python 3 to perform a line feed.
You are a Python code architect, reviewing and designing scalable and efficient code
Moves the cursor down by value.
Can you tell what is the following Python 3 function doing def _cursor_down(self, value): self._cursor.clearSelection() if self._cursor.atEnd(): self._cursor.insertText('\n') else: self._cursor.movePosition(self._cursor.Down, self._cursor.MoveAnchor, value) self._...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _cursor_up(self, value): """ Moves the cursor up by ``value``. """ value = int(value) if value == 0: value = 1 self._cursor.clearSelection() self._cursor.movePosition(self._cursor.Up, self._cursor.MoveAnchor, value) self._last_cursor_pos = ...
Write a Python 3 function that can move the cursor up by value.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _cursor_position(self, data): """ Moves the cursor position. """ column, line = self._get_line_and_col(data) self._move_cursor_to_line(line) self._move_cursor_to_column(column) self._last_cursor_pos = self._cursor.position()
Can you implement a function in Python 3 that moves the cursor position.
You are a Python code analyst, evaluating scripts for potential improvements.
def _move_cursor_to_column(self, column): """ Moves the cursor to the specified column, if possible. """ last_col = len(self._cursor.block().text()) self._cursor.movePosition(self._cursor.EndOfBlock) to_insert = '' for i in range(column - last_col): to...
Implement a function in Python 3 to move the cursor to the specified column.
You are a Python code architect, reviewing and designing scalable and efficient code
def _move_cursor_to_line(self, line): """ Moves the cursor to the specified line, if possible. """ last_line = self._text_edit.document().blockCount() - 1 self._cursor.clearSelection() self._cursor.movePosition(self._cursor.End) to_insert = '' for i in ran...
Can you create a Python 3 function that moves the cursor to the specified line.
As a Python code composer, you craft elegant and concise scripts.
def _get_line_and_col(data): """ Gets line and column from a string like the following: "1;5" or "1;" or ";5" and convers the column/line numbers to 0 base. """ try: line, column = data.split(';') except AttributeError: line = int(data) ...
Write a Python 3 script to get line and column numbers from a string like 1 ; 5 or 1 ; 5 or 1 ; 5 or 1 ; 5 or 1 ; 5 or 1 ; 5 or 1 ; 5 or 1 ; 5 or 1 ; 5 or 1 ; 5 or 1 ; 5 or 1 ; 5 or 1 ; 5 or 1 ; 5 or 1 ; 5 or 1 ; 5 or 1 ; 5 or 1 ; 5 or 1 ; 5.
You are a Python code generator, capable of creating scripts from specifications.
Erases charachters in line.
Make a summary of the following Python 3 code def _erase_in_line(self, value): initial_pos = self._cursor.position() if value == 0: # delete end of line self._cursor.movePosition(self._cursor.EndOfBlock, self._cursor.KeepAnchor) elif value == 1: # delete start...
As a Python code analyst, you investigate and solve complex coding mysteries
def _cursor_back(self, value): """ Moves the cursor back. """ if value <= 0: value = 1 self._cursor.movePosition(self._cursor.Left, self._cursor.MoveAnchor, value) self._text_edit.setTextCursor(self._cursor) self._last_cursor_pos = self._cursor.positio...
Can you write a function in Python 3 where it moves the cursor back.
As a Python code composer, you craft elegant and concise scripts.
Moves the cursor forward.
How would you explain what the following Python 3 function does def _cursor_forward(self, value): if value <= 0: value = 1 self._cursor.movePosition(self._cursor.Right, self._cursor.MoveAnchor, value) self._text_edit.setTextCursor(self._cursor) self._last_cursor_pos = self._c...
You are a Python code architect, reviewing and designing scalable and efficient code
Deletes the specified number of charachters.
How would you explain what the following Python 3 function does def _delete_chars(self, value): value = int(value) if value <= 0: value = 1 for i in range(value): self._cursor.deleteChar() self._text_edit.setTextCursor(self._cursor) self._last_cursor_pos =...
As a Python code composer, you craft elegant and concise scripts.
def get_package_info(package): """Gets the PyPI information for a given package.""" url = 'https://pypi.python.org/pypi/{}/json'.format(package) r = requests.get(url) r.raise_for_status() return r.json()
Can you create a Python 3 function that gets the PyPI information for a given package.
As a Python code composer, you craft elegant and concise scripts.
def read_requirements(req_file): """Reads a requirements file. Args: req_file (str): Filename of requirements file """ items = list(parse_requirements(req_file, session={})) result = [] for item in items: # Get line number from item line_number = item.comes_from.split(r...
Write a Python 3 function that can read a requirements file.
As a python code expert, you are capable of creating scripts from specifications.
def _is_version_range(req): """Returns true if requirements specify a version range.""" assert len(req.specifier) > 0 specs = list(req.specifier) if len(specs) == 1: # "foo > 2.0" or "foo == 2.4.3" return specs[0].operator != '==' else: # "foo > 2.0, < 3.0" return Tr...
How would you implement a function in Python 3 that returns true if requirements specify a version range.
You are a Python code analyst, evaluating scripts for potential improvements.
def update_req(req): """Updates a given req object with the latest version.""" if not req.name: return req, None info = get_package_info(req.name) if info['info'].get('_pypi_hidden'): print('{} is hidden on PyPI and will not be updated.'.format(req)) return req, None if _...
Can you create a Python 3 function that updates a given req object with the latest version.
As a Python code translator, you convert algorithms and pseudocode into Python.
Writes a list of req objects out to a given file.
Make a summary of the following Python 3 code def write_requirements(reqs_linenum, req_file): with open(req_file, 'r') as input: lines = input.readlines() for req in reqs_linenum: line_num = int(req[1]) if hasattr(req[0], 'link'): lines[line_num - 1] = '{}\n'.format(req[0]....
You are a Python code analyst, evaluating scripts for potential improvements.
Checks if a given Requirement is the latest version available.
Here you have a function in Python 3, explain what it does def check_req(req): if not isinstance(req, Requirement): return None info = get_package_info(req.name) newest_version = _get_newest_version(info) if _is_pinned(req) and _is_version_range(req): return None current_spec = ne...
As a python code expert, you are capable of creating scripts from specifications.
def check_requirements_file(req_file, skip_packages): """Return list of outdated requirements. Args: req_file (str): Filename of requirements file skip_packages (list): List of package names to ignore. """ reqs = read_requirements(req_file) if skip_packages is not None: reqs...
Can you implement a function in Python 3 that checks the requirements file for outdated packages.
As a Python code composer, you craft elegant and concise scripts.
Updates all dependencies of the specified requirements file.
Here you have a function in Python 3, explain what it does def update_command(args): updated = update_requirements_file( args.requirements_file, args.skip_packages) if updated: print('Updated requirements in {}:'.format(args.requirements_file)) for item in updated: print(' ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Checks that all dependencies in the specified requirements file are up to date.
How would you explain what the following Python 3 function does def check_command(args): outdated = check_requirements_file(args.requirements_file, args.skip_packages) if outdated: print('Requirements in {} are out of date:'.format( args.requirements_f...
As a Python code analyst, you investigate and solve complex coding mysteries
def paintEvent(self, event): """ Fills the panel background. """ super(EncodingPanel, self).paintEvent(event) if self.isVisible(): # fill background painter = QtGui.QPainter(self) self._background_brush = QtGui.QBrush(self._color) painter.fillRect(...
Can you create a Python 3 function that fills the panel background.
As a Python code composer, you craft elegant and concise scripts.
def _get_format_from_style(self, token, style): """ Returns a QTextCharFormat for token by reading a Pygments style. """ result = QtGui.QTextCharFormat() items = list(style.style_for_token(token).items()) for key, value in items: if value is None and key == 'color': ...
Can you implement a function in Python 3 that returns a QTextCharFormat for the given token by reading a Pygments style.
As a Python code composer, you craft elegant and concise scripts.
Returns a QColor built from a Pygments color string.
Here you have a function in Python 3, explain what it does def _get_color(color): color = str(color).replace("#", "") qcolor = QtGui.QColor() qcolor.setRgb(int(color[:2], base=16), int(color[2:4], base=16), int(color[4:6], base=16)) return qcol...
You are a Python code generator, capable of creating scripts from specifications.
def refresh_editor(self, color_scheme): """ Refresh editor settings (background and highlight colors) when color scheme changed. :param color_scheme: new color scheme. """ self.editor.background = color_scheme.background self.editor.foreground = color_scheme.form...
Create a Python 3 function to refresh editor settings when color scheme changed.
As a Python code composer, you craft elegant and concise scripts.
Computes the line number area width depending on the number of lines in the document.
Here you have a function in Python 3, explain what it does def line_number_area_width(self): digits = 1 count = max(1, self.editor.blockCount()) while count >= 10: count /= 10 digits += 1 space = 5 + self.editor.fontMetrics().width("9") * digits return spa...
You are a Python code generator, capable of creating scripts from specifications.