code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
logger.debug("Querying server for uncached data object %s", name) # This will retrieve the value and inject it into the cache self.update_view_data(properties=[name]) return self._cache[name][0]
def _get_dataobject(self, name, multivalued)
This function only gets called if the decorated property doesn't have a value in the cache.
12.414571
9.660229
1.285122
logger.debug("Querying server for uncached MOR %s", name) # This will retrieve the value and inject it into the cache logger.debug("Getting view for MOR") self.update(properties=[name]) return self._cache[name][0]
def _get_mor(self, name, multivalued)
This function only gets called if the decorated property doesn't have a value in the cache.
12.660263
10.282818
1.231206
if hasattr(self, '_cache'): if properties is None: del(self._cache) else: for prop in properties: if prop in self._cache: del(self._cache[prop])
def flush_cache(self, properties=None)
Flushes the cache being held for this instance. :param properties: The list of properties to flush from the cache. :type properties: list or None (default). If None, flush entire cache.
2.302109
2.607587
0.88285
if properties is None: try: self.update_view_data(properties=list(self._cache.keys())) except AttributeError: # We end up here and ignore it self._cache doesn't exist pass else: self.update_view_data(properties=...
def update(self, properties=None)
Updates the properties being held for this instance. :param properties: The list of properties to update. :type properties: list or None (default). If None, update all currently cached properties.
6.221822
6.31321
0.985524
if properties is None: properties = [] logger.info("Updating view data for object of type %s", self._mo_ref._type) property_spec = self._client.create('PropertySpec') property_spec.type = str(self._mo_ref._type) # Determine which propertie...
def update_view_data(self, properties=None)
Update the local object from the server-side object. >>> vm = VirtualMachine.find_one(client, filter={"name": "genesis"}) >>> # Update all properties >>> vm.update_view_data() >>> # Update the config and summary properties >>> vm.update_view_data(properties=["config", "s...
3.068538
3.093812
0.991831
if properties is None: raise ValueError("You must specify some properties to preload. To" " preload all properties use the string \"all\".") # Don't do anything if the attribute contains an empty list if not getattr(self, name): retur...
def preload(self, name, properties=None)
Pre-loads the requested properties for each object in the "name" attribute. :param name: The name of the attribute containing the list to preload. :type name: str :param properties: The properties to preload on the objects or the string all to preload all properties. ...
6.518537
6.209918
1.049698
# A debugging convenience, allows inspection of the object_content # that was used to create the object logger.info("Setting view data for a %s", self.__class__) self._object_content = object_content for dynprop in object_content.propSet: # If the class hasn...
def _set_view_data(self, object_content)
Update the local object from the passed in object_content.
4.433335
4.406889
1.006001
LOGGER.info("Initializing repository cache") # Initialize Repo Cache repo_cache = {} # Get all repos from Elasticsearch for hit in GitRepo.search().query("match_all").scan(): # TODO (fschmidt): Maybe we can use this list as cache for the whole # scraper-webhook part. # ...
def _initialize_repo_cache()
Initialize the repository cache used for scraping. Retrieves a list of repositories with their provider and last scraping time from Elasticsearch. This list can be used to check which repos need to be scraped (e.g. after a specific amount of time).
9.615324
8.684189
1.107222
client = Client(server=options.server, username=options.username, password=options.password) print('Successfully connected to %s' % client.server) lm_info = client.sc.licenseManager.QuerySupportedFeatures() for feature in lm_info: print('%s: %s' % (feature.featureName, f...
def main(options)
Obtains supported features from the license manager
4.690273
3.765849
1.245476
_logger().log(5, 'adding mode %r', mode.name) self._modes[mode.name] = mode mode.on_install(self.editor) return mode
def append(self, mode)
Adds a mode to the editor. :param mode: The mode instance to append.
7.391412
6.481871
1.140321
_logger().log(5, 'removing mode %r', name_or_klass) mode = self.get(name_or_klass) mode.on_uninstall() self._modes.pop(mode.name) return mode
def remove(self, name_or_klass)
Removes a mode from the editor. :param name_or_klass: The name (or class) of the mode to remove. :returns: The removed mode.
5.055822
4.140154
1.221168
if not isinstance(name_or_klass, str): name_or_klass = name_or_klass.__name__ return self._modes[name_or_klass]
def get(self, name_or_klass)
Gets a mode by name (or class) :param name_or_klass: The name or the class of the mode to get :type name_or_klass: str or type :rtype: pyqode.core.api.Mode
2.577225
2.715776
0.948983
Mode.on_install(self, editor) self.setParent(editor) self.setPalette(QtWidgets.QApplication.instance().palette()) self.setFont(QtWidgets.QApplication.instance().font()) self.editor.panels.refresh() self._background_brush = QtGui.QBrush(QtGui.QColor( s...
def on_install(self, editor)
Extends :meth:`pyqode.core.api.Mode.on_install` method to set the editor instance as the parent widget. .. warning:: Don't forget to call **super** if you override this method! :param editor: editor instance :type editor: pyqode.core.api.CodeEdit
3.339874
3.367132
0.991905
_logger().log(5, '%s visibility changed', self.name) super(Panel, self).setVisible(visible) if self.editor: self.editor.panels.refresh()
def setVisible(self, visible)
Shows/Hides the panel Automatically call CodeEdit.refresh_panels. :param visible: Visible state
9.155562
8.593575
1.065396
if decoration not in self._decorations: self._decorations.append(decoration) self._decorations = sorted( self._decorations, key=lambda sel: sel.draw_order) self.editor.setExtraSelections(self._decorations) return True return False
def append(self, decoration)
Adds a text decoration on a CodeEdit instance :param decoration: Text decoration to add :type decoration: pyqode.core.api.TextDecoration
3.509502
3.807625
0.921704
try: self._decorations.remove(decoration) self.editor.setExtraSelections(self._decorations) return True except ValueError: return False
def remove(self, decoration)
Removes a text decoration from the editor. :param decoration: Text decoration to remove :type decoration: pyqode.core.api.TextDecoration
3.973952
4.353206
0.912879
self._decorations[:] = [] try: self.editor.setExtraSelections(self._decorations) except RuntimeError: pass
def clear(self)
Removes all text decoration from the editor.
8.582958
6.181224
1.388553
if (int(event.modifiers()) & QtCore.Qt.ControlModifier > 0 and not int(event.modifiers()) & QtCore.Qt.ShiftModifier): if event.key() == QtCore.Qt.Key_0: self.editor.reset_zoom() event.accept() if event.key() == QtCore.Qt.Key_Plus: ...
def _on_key_pressed(self, event)
Resets editor font size to the default font size :param event: wheelEvent :type event: QKeyEvent
2.043057
1.962181
1.041217
try: delta = event.angleDelta().y() except AttributeError: # PyQt4/PySide delta = event.delta() if int(event.modifiers()) & QtCore.Qt.ControlModifier > 0: if delta < self.prev_delta: self.editor.zoom_out() e...
def _on_wheel_event(self, event)
Increments or decrements editor fonts settings on mouse wheel event if ctrl modifier is on. :param event: wheel event :type event: QWheelEvent
3.118432
3.080094
1.012447
if self._writer != writer and self._writer: self._writer = None if writer: self._writer = writer
def set_writer(self, writer)
Changes the writer function to handle writing to the text edit. A writer function must have the following prototype: .. code-block:: python def write(text_edit, text, color) :param writer: write function as described above.
4.316982
6.213921
0.694728
self.setReadOnly(False) if env is None: env = {} if args is None: args = [] if not self._running: self.process = QProcess() self.process.finished.connect(self._on_process_finished) self.process.started.connect(self.proc...
def start_process(self, process, args=None, cwd=None, env=None)
Starts a process interactively. :param process: Process to run :type process: str :param args: List of arguments (list of str) :type args: list :param cwd: Working directory :type cwd: str :param env: environment variables (dict).
2.513024
2.622968
0.958084
if self.process is not None: self._user_stop = True self.process.kill() self.setReadOnly(True) self._running = False
def stop_process(self)
Stop the process (by killing it).
5.835335
5.408558
1.078908
try: text_edit.moveCursor(QTextCursor.End) text_edit.setTextColor(color) text_edit.insertPlainText(text) text_edit.moveCursor(QTextCursor.End) except RuntimeError: pass
def write(text_edit, text, color)
Default write function. Move the cursor to the end and insert text with the specified color. :param text_edit: QInteractiveConsole instance :type text_edit: pyqode.widgets.QInteractiveConsole :param text: Text to write :type text: str :param color: Desired text color ...
1.95599
2.217889
0.881915
self.stdout_color = color_scheme.formats['normal'].foreground().color() self.stdin_color = color_scheme.formats['number'].foreground().color() self.app_msg_color = color_scheme.formats[ 'string'].foreground().color() self.background_color = color_scheme.background ...
def apply_color_scheme(self, color_scheme)
Apply a pygments color scheme to the console. As there is not a 1 to 1 mapping between color scheme formats and console formats, we decided to make the following mapping (it usually looks good for most of the available pygments styles): - stdout_color = normal color - s...
4.122459
2.388721
1.725802
if not value: # fallback to utf-8 value = 'UTF-8' # UTF-8 -> utf_8 converted = value.replace('-', '_').lower() # fix some corner cases, see https://github.com/pyQode/pyQode/issues/11 all_aliases = { 'ascii': [ 'us_ascii', 'us', 'ansi_x...
def convert_to_codec_key(value)
Normalize code key value (encoding codecs must be lower case and must not contain any dashes). :param value: value to convert.
2.48453
2.486102
0.999368
prev_fold_level = TextBlockHelper.get_fold_lvl(previous_block) if text.strip() == '': # blank line always have the same level as the previous line fold_level = prev_fold_level else: fold_level = self.detect_fold_level( previous_block, ...
def process_block(self, current_block, previous_block, text)
Processes a block and setup its folding info. This method call ``detect_fold_level`` and handles most of the tricky corner cases so that all you have to do is focus on getting the proper fold level foreach meaningful block, skipping the blank ones. :param current_block: current block t...
3.878243
3.747885
1.034782
text = block.text() # round down to previous indentation guide to ensure contiguous block # fold level evolution. return (len(text) - len(text.lstrip())) // self.editor.tab_length
def detect_fold_level(self, prev_block, block)
Detects fold level by looking at the block indentation. :param prev_block: previous text block :param block: current block to highlight
20.892591
20.055883
1.041719
file_obj = io.StringIO(contents) config = six.moves.configparser.ConfigParser() config.readfp(file_obj) return config
def read_config(contents)
Reads pylintrc config into native ConfigParser object. Args: contents (str): The contents of the file containing the INI config. Returns: ConfigParser.ConfigParser: The parsed configuration.
2.961909
3.870147
0.765322
if not filename: return imp.new_module('local_pylint_config') module = imp.load_source('local_pylint_config', filename) return module
def load_local_config(filename)
Loads the pylint.config.py file. Args: filename (str): The python file containing the local configuration. Returns: module: The loaded Python module.
4.474432
3.988061
1.121957
config = Config( DEFAULT_LIBRARY_RC_ADDITIONS, DEFAULT_LIBRARY_RC_REPLACEMENTS, DEFAULT_TEST_RC_ADDITIONS, DEFAULT_TEST_RC_REPLACEMENTS) for field in config._fields: if hasattr(config_module, field): config = config._replace(**{field: getattr(config_module, field)}) ...
def determine_final_config(config_module)
Determines the final additions and replacements. Combines the config module with the defaults. Args: config_module: The loaded local configuration module. Returns: Config: the final configuration.
3.845168
3.879292
0.991204
try: rc_filename = kwargs['rc_filename'] description = kwargs['description'] if len(kwargs) != 2: raise KeyError except KeyError: raise KeyError(_LINT_FILESET_MSG) pylint_shell_command = ['pylint', '--rcfile', rc_filename] pylint_shell_command.extend(dir...
def lint_fileset(*dirnames, **kwargs)
Lints a group of files using a given rcfile. Keyword arguments are * ``rc_filename`` (``str``): The name of the Pylint config RC file. * ``description`` (``str``): A description of the files and configuration currently being run. Args: dirnames (tuple): Direct...
2.949788
2.447541
1.205204
# Set-up the mutable default values. if additions is None: additions = {} if replacements is None: replacements = {} # Create fresh config, which must extend the base one. new_cfg = six.moves.configparser.ConfigParser() # pylint: disable=protected-access new_cfg._sectio...
def make_rc(base_cfg, target_filename, additions=None, replacements=None)
Combines a base rc and additions into single file. Args: base_cfg (ConfigParser.ConfigParser): The configuration we are merging into. target_filename (str): The filename where the new configuration will be saved. additions (dict): (Optional) The values added to the c...
2.968203
3.035575
0.977806
library_rc = 'pylintrc' test_rc = 'pylintrc.test' if os.path.exists(library_rc): os.remove(library_rc) if os.path.exists(test_rc): os.remove(test_rc) default_config = read_config(get_default_config()) user_config = load_local_config(args.config) configuration = determ...
def run_command(args)
Script entry point. Lints both sets of files.
2.96674
2.731422
1.086152
tm = self.options.timeout url = build_opener(HTTPSClientAuthHandler(self.context)) if self.u2ver() < 2.6: socket.setdefaulttimeout(tm) return url.open(u2request) else: return url.open(u2request, timeout=tm)
def u2open(self, u2request)
Open a connection. @param u2request: A urllib2 request. @type u2request: urllib2.Requet. @return: The opened file-like urllib2 object. @rtype: fp
5.255199
5.57783
0.942158
if username is None: username = self.username if password is None: password = self.password logger.debug("Logging into server") self.sc.sessionManager.Login(userName=username, password=password) self._logged_in = True
def login(self, username=None, password=None)
Login to a vSphere server. >>> client.login(username='Administrator', password='strongpass') :param username: The username to authenticate as. :type username: str :param password: The password to authenticate with. :type password: str
4.202551
4.182415
1.004815
if self._logged_in is True: self.si.flush_cache() self.sc.sessionManager.Logout() self._logged_in = False
def logout(self)
Logout of a vSphere server.
8.955739
5.809669
1.541523
if (self._logged_in is False and method not in ["Login", "RetrieveServiceContent"]): logger.critical("Cannot exec %s unless logged in", method) raise NotLoggedInError("Cannot exec %s unless logged in" % method) for kwarg in kwargs: kwargs[kwarg] ...
def invoke(self, method, _this, **kwargs)
Invoke a method on the server. >>> client.invoke('CurrentTime', client.si) :param method: The method to invoke, as found in the SDK. :type method: str :param _this: The managed object reference against which to invoke \ the method. :type _this: ManagedObject :pa...
4.942113
5.00715
0.987011
kls = classmapper(mo_ref._type) new_object = kls(mo_ref, self) return new_object
def _mor_to_pobject(self, mo_ref)
Converts a MOR to a psphere object.
9.60165
8.261259
1.16225
logger.debug("Checking if %s needs to be marshalled", obj) if isinstance(obj, ManagedObject): logger.debug("obj is a psphere object, converting to MOR") return obj._mo_ref if isinstance(obj, list): logger.debug("obj is a list, recursing it") ...
def _marshal(self, obj)
Walks an object and marshals any psphere object into MORs.
3.349786
2.871254
1.166663
if isinstance(obj, suds.sudsobject.Object) is False: logger.debug("%s is not a suds instance, skipping", obj) return obj logger.debug("Processing:") logger.debug(obj) logger.debug("...with keylist:") logger.debug(obj.__keylist__) # If the...
def _unmarshal(self, obj)
Walks an object and unmarshals any MORs into psphere objects.
2.611536
2.42309
1.077771
obj = self.factory.create("ns0:%s" % type_) for key, value in kwargs.items(): setattr(obj, key, value) return obj
def create(self, type_, **kwargs)
Create a SOAP object of the requested type. >>> client.create('VirtualE1000') :param type_: The type of SOAP object to create. :type type_: str :param kwargs: TODO :type kwargs: TODO
3.323261
3.776265
0.880039
# This maps the mo_ref into a psphere class and then instantiates it kls = classmapper(mo_ref._type) view = kls(mo_ref, self) # Update the requested properties of the instance #view.update_view_data(properties=properties) return view
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 :returns: A view representing the ManagedObjectRefere...
11.888714
13.506807
0.880202
property_specs = [] for mo_ref in mo_refs: property_spec = self.create('PropertySpec') property_spec.type = str(mo_ref._type) if properties is None: properties = [] else: # Only retrieve the requested properties ...
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 in the views. :type properties: list :ret...
2.607543
2.648625
0.984489
# The selection spec for additional objects we want to filter ss_strings = ['resource_pool_traversal_spec', 'resource_pool_vm_traversal_spec', 'folder_traversal_spec', 'datacenter_host_traversal_spec', 'data...
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: The place in the MOB to start the search. :type begin_entity: Manage...
1.784565
1.757408
1.015453
# 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 to a Task.') return None task_mo_ref = self.invoke(method=...
def invoke_task(self, method, **kwargs)
Execute a \*_Task method and wait for it to complete. :param method: The \*_Task method to invoke. :type method: str :param kwargs: The arguments to pass to the method. :type kwargs: TODO
5.444236
5.447398
0.999419
if properties is None: properties = [] # Start the search at the root folder if no begin_entity was given if not begin_entity: begin_entity = self.sc.rootFolder._mo_ref property_spec = self.create('PropertySpec') property_spec.type = view_type ...
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 default is to start the search at the root folder. :type begin_entity: ManagedObjectR...
3.852132
3.905034
0.986453
if properties is None: properties = [] kls = classmapper(view_type) # Start the search at the root folder if no begin_entity was given if not begin_entity: begin_entity = self.sc.rootFolder._mo_ref logger.debug("Using %s", self.sc.rootFolder....
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_type: str :param begin_entity: The MOR to start searching for the entity. \ The default is to start the searc...
3.521331
3.468621
1.015196
if name is None: name = "default" logger.info("Loading template with name %s", name) try: template_file = open("%s/%s.yaml" % (template_path, name)) except IOError: raise TemplateNotFoundError template = yaml.safe_load(template_file) template_file.close() if "e...
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. :param name: The name of the template to l...
2.530184
2.693955
0.939208
templates = [f for f in glob.glob(os.path.join(template_path, '*.yaml'))] return templates
def list_templates()
Returns a list of all templates.
3.755097
3.46758
1.082916
# 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 None # Success! Create a nic attached to this network backing = clie...
def create_nic(client, target, nic)
Return a NIC spec
3.385474
3.368056
1.005172
server = config._config_value("general", "server", options.server) if server is None: raise ValueError("server must be supplied on command line" " or in configuration file.") username = config._config_value("general", "username", options.username) if username is Non...
def main(name, options)
The main method for this script. :param name: The name of the VM to create. :type name: str :param template_name: The name of the template to use for creating \ the VM. :type template_name: str
2.265509
2.29387
0.987636
for ptrn in patterns: if isinstance(ptrn, list): for p in ptrn: self._ignored_patterns.append(p) else: self._ignored_patterns.append(ptrn)
def add_ignore_patterns(self, *patterns)
Adds an ignore pattern to the list for ignore patterns. Ignore patterns are used to filter out unwanted files or directories from the file system model. A pattern is a Unix shell-style wildcards. See :mod:`fnmatch` for a deeper explanation about the shell-style wildcards.
2.73423
3.229536
0.846632
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)
def set_context_menu(self, context_menu)
Sets the context menu of the tree view. :param context_menu: QMenu
2.90004
3.102728
0.934674
if not self.isVisible(): self._path_to_set = path self._hide_extra_colums = hide_extra_columns return if sys.platform == 'win32' and os.path.splitunc(path)[0]: mdl = QtGui.QStandardItemModel(1, 1) item = QtGui.QStandardItem( ...
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,...)
2.988027
3.084516
0.968718
return self._fs_model_source.filePath( self._fs_model_proxy.mapToSource(index))
def filePath(self, index)
Gets the file path of the item at the specified ``index``. :param index: item index - QModelIndex :return: str
9.60554
12.0706
0.79578
return self._fs_model_source.fileInfo( self._fs_model_proxy.mapToSource(index))
def fileInfo(self, index)
Gets the file info of the item at the specified ``index``. :param index: item index - QModelIndex :return: QFileInfo
10.179094
14.790982
0.688196
urls = self.selected_urls() if not urls: return mime = self._UrlListMimeData(copy) mime.set_list(urls) clipboard = QtWidgets.QApplication.clipboard() clipboard.setMimeData(mime)
def copy_to_clipboard(self, copy=True)
Copies the selected items to the clipboard :param copy: True to copy, False to cut.
4.900238
5.205805
0.941303
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' % [str(url) for url in urls]) return urls
def selected_urls(self)
Gets the list of selected items file path (url)
5.834785
5.369958
1.086561
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 if mime.hasFormat(self._UrlListMimeData.format(copy=True)): paste_op...
def paste_from_clipboard(self)
Pastes files from clipboard.
3.43182
3.396909
1.010277
for src in sources: debug('%s <%s> to <%s>' % ( 'copying' if copy else 'cutting', src, destination)) perform_copy = True ext = os.path.splitext(src)[1] original = os.path.splitext(os.path.split(src)[1])[0] filename, status = Qt...
def _paste(self, sources, destination, copy)
Copies the files listed in ``sources`` to destination. Source are removed if copy is set to False.
2.461915
2.469566
0.996902
ret_val = [] for root, _, files in os.walk(path): for f in files: ret_val.append(os.path.join(root, f)) return ret_val
def _get_files(path)
Returns the list of files contained in path (recursively).
2.251972
2.037489
1.105268
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 | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.Ye...
def delete(self)
Deletes the selected items.
2.589097
2.525827
1.02505
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 path
def get_current_path(self)
Gets the path of the currently selected item.
4.97258
4.410465
1.12745
path = self.get_current_path() QtWidgets.QApplication.clipboard().setText(path) debug('path copied: %s' % path)
def copy_path_to_clipboard(self)
Copies the file path to the clipboard
4.405947
4.580072
0.961982
src = self.get_current_path() pardir, name = os.path.split(src) new_name, status = QtWidgets.QInputDialog.getText( self.tree_view, _('Rename '), _('New name:'), QtWidgets.QLineEdit.Normal, name) if status: dest = os.path.join(pardir, new_name)...
def rename(self)
Renames the selected item in the tree view
2.082568
2.058547
1.011669
src = self.get_current_path() name, status = QtWidgets.QInputDialog.getText( self.tree_view, _('Create directory'), _('Name:'), QtWidgets.QLineEdit.Normal, '') if status: fatal_names = ['.', '..'] for i in fatal_names: if i...
def create_directory(self)
Creates a directory under the selected directory (if the selected item is a file, the parent directory is used).
2.73339
2.627269
1.040392
src = self.get_current_path() name, status = QtWidgets.QInputDialog.getText( self.tree_view, _('Create new file'), _('File name:'), QtWidgets.QLineEdit.Normal, '') if status: fatal_names = ['.', '..', os.sep] for i in fatal_names: ...
def create_file(self)
Creates a file under the current directory.
2.780688
2.726915
1.019719
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) return mimetype
def get_mimetype(path)
Guesses the mime type of a file. If mime type cannot be detected, plain text is assumed. :param path: path of the file :return: the corresponding mime type.
2.856795
3.052946
0.93575
ret_val = False if encoding is None: encoding = locale.getpreferredencoding() self.opening = True settings = Cache() self._path = path # get encoding from cache if use_cached_encoding: try: cached_encoding = setting...
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 settings in your application. It is also up to you to handle UnicodeDecodeEr...
3.720562
3.55089
1.047783
assert os.path.exists(self.path) self.open(self.path, encoding=encoding, use_cached_encoding=False)
def reload(self, encoding)
Reload the file with another encoding. :param encoding: the new encoding to use to reload the file.
6.271257
6.520542
0.961769
if not self.editor.dirty and \ (encoding is None and encoding == self.encoding) and \ (path is None and path == self.path): # avoid saving if editor not dirty or if encoding or path did not # change return if fallback_encoding ...
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 the current file encoding if None. :param fallback_enco...
3.617635
3.642509
0.993171
Cache().set_cursor_position( self.path, self.editor.textCursor().position()) self.editor._original_text = '' if clear: self.editor.clear() self._path = '' self.mimetype = '' self._encoding = locale.getpreferredencoding()
def close(self, clear=True)
Close the file open in the editor: - clear editor content - reset file attributes to their default values :param clear: True to clear the editor content. Default is True.
8.221507
7.286333
1.128346
if state: self.editor.painted.connect(self._paint_margin) self.editor.repaint() else: self.editor.painted.disconnect(self._paint_margin) self.editor.repaint()
def on_state_changed(self, state)
Connects/Disconnects to the painted event of the editor :param state: Enable state
3.655802
3.198658
1.142918
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.editor.contentOffset().x() + \ self.editor.document().documentMargin() ...
def _paint_margin(self, event)
Paints the right margin after editor paint event.
3.820463
3.58481
1.065736
try: self._mtime = os.path.getmtime(self.editor.file.path) except OSError: # file_path does not exists. self._mtime = 0 self._timer.stop() except (TypeError, AttributeError): # file path is none, this happen if you use setPlain...
def _update_mtime(self)
Updates modif time
6.560821
6.602212
0.993731
try: self.editor.toPlainText() except RuntimeError: self._timer.stop() return if self.editor and self.editor.file.path: if not os.path.exists(self.editor.file.path) and self._mtime: self._notify_deleted_file() e...
def _check_file(self)
Checks watched file moficiation time and permission changes.
3.299256
2.878902
1.146012
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 = (QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) expected_action = ( lambda *x: None...
def _notify(self, title, message, expected_action=None)
Notify user from external event
3.968819
3.912776
1.014323
def inner_action(*args): # cache cursor position before reloading so that the cursor # position is restored automatically after reload has finished. # See OpenCobolIDE/OpenCobolIDE#97 Cache().set_cursor_position( self.editor.f...
def _notify_change(self)
Notify user from external change if autoReloadChangedFiles is False then reload the changed file in the editor
5.595254
5.286101
1.058484
if self._notification_pending and not self._processing: self._processing = True args, kwargs = self._data self._notify(*args, **kwargs) self._notification_pending = False self._processing = False
def _check_for_pending(self, *args, **kwargs)
Checks if a notification is pending.
4.04056
3.318489
1.21759
self.file_deleted.emit(self.editor) # file deleted, disable file watcher self.enabled = False
def _notify_deleted_file(self)
Notify user from external file deletion.
13.637635
11.022303
1.237276
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/google_appengine_{version}.zip". We'll extract the version # number so we can sort the list by version, and finall...
def get_gae_versions()
Gets a list of all of the available Python SDK versions, sorted with the newest last.
4.221573
4.113657
1.026234
version_path = os.path.join( destination, 'google_appengine', 'VERSION') if not os.path.exists(version_path): return False with open(version_path, 'r') as f: version_line = f.readline() match = SDK_RELEASE_RE.match(version_line) if not match: prin...
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.
2.871386
2.796774
1.026678
r = requests.get(url) r.raise_for_status() return StringIO(r.content)
def download_sdk(url)
Downloads the SDK and returns a file-like object for the zip content.
2.879771
2.73266
1.053835
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"', 'release: "{}"'.format('.'.join(str(x) for x in version))) with open(versio...
def fixup_version(destination, version)
Newer releases of the SDK do not have the version number set correctly in the VERSION file. Fix it up.
2.360141
2.271063
1.039223
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]): print( 'App Engine SDK already exists and is up to date ' ...
def download_command(args)
Downloads and extracts the latest App Engine SDK to the given destination.
3.353987
3.083136
1.087849
default_encodings = [ locale.getpreferredencoding().lower().replace('-', '_')] if 'utf_8' not in default_encodings: default_encodings.append('utf_8') default_encodings = list(set(default_encodings)) return json.loads(self._settings.value( 'use...
def preferred_encodings(self)
The list of user defined encodings, for display in the encodings menu/combobox.
3.645614
3.308446
1.101911
_logger().debug('getting encoding for %s', file_path) try: map = json.loads(self._settings.value('cachedFileEncodings')) except TypeError: map = {} try: return map[file_path] except KeyError: encodings = self.preferred_enco...
def get_file_encoding(self, file_path, preferred_encoding=None)
Gets an eventual cached encoding for file_path. Raises a KeyError if no encoding were cached for the specified file path. :param file_path: path of the file to look up :returns: The cached encoding.
2.830771
2.593125
1.091645
try: map = json.loads(self._settings.value('cachedFileEncodings')) except TypeError: map = {} map[path] = encoding self._settings.setValue('cachedFileEncodings', json.dumps(map))
def set_file_encoding(self, path, encoding)
Cache encoding for the specified file path. :param path: path of the file to cache :param encoding: encoding to cache
3.943252
4.338317
0.908936
try: map = json.loads(self._settings.value('cachedCursorPosition')) except TypeError: map = {} try: pos = map[file_path] except KeyError: pos = 0 if isinstance(pos, list): # changed in pyqode 2.6.3, now we store...
def get_cursor_position(self, file_path)
Gets the cached cursor position for file_path :param file_path: path of the file in the cache :return: Cached cursor position or (0, 0)
6.685146
6.965896
0.959697
try: map = json.loads(self._settings.value('cachedCursorPosition')) except TypeError: map = {} map[path] = position self._settings.setValue('cachedCursorPosition', json.dumps(map))
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
4.081747
4.267222
0.956535
if end is None: end = len(string) return string[start:start + end]
def _mid(string, start, end=None)
Returns a substring delimited by start and end position.
3.100187
2.843964
1.090094
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 = { '#aa0000': theme.red, '#00aa00': theme.green, '#aaaa00': theme.yellow, '#00...
def _ansi_color(code, theme)
Converts an ansi code to a QColor, taking the color scheme (theme) into account.
2.144729
2.031913
1.055522
return self._process.state() in [self._process.Running, self._process.Starting]
def is_running(self)
Checks if the child process is running (or is starting).
7.377571
4.915778
1.500794
# clear previous output self.clear() self.setReadOnly(False) if arguments is None: arguments = [] if sys.platform != 'win32' and use_pseudo_terminal: pgm = sys.executable args = [pty_wrapper.__file__, program] + arguments s...
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 arguments: list of program arguments :param working_dir: working directory of the child process :param print_command: True to print the full command (pgm + arguments) as the first line of the output window ...
4.038969
4.067785
0.992916
self._process.terminate() if not self._process.waitForFinished(100): self._process.kill()
def stop_process(self)
Stops the child process.
4.034256
3.529281
1.143082
if background is None: background = qApp.palette().base().color() if foreground is None: foreground = qApp.palette().text().color() is_light = background.lightness() >= 128 if error is None: if is_light: error = QColor('dark re...
def create_color_scheme(background=None, foreground=None, error=None, custom=None, red=None, green=None, yellow=None, blue=None, magenta=None, cyan=None)
Utility function that creates a color scheme instance, with default values. The default colors are chosen based on the current palette. :param background: background color :param foreground: foreground color :param error: color of error messages (stderr) :param custom: color of...
1.643788
1.678199
0.979495
self.stop_process() self.backend.stop() try: self.modes.remove('_LinkHighlighter') except KeyError: pass # already removed super(OutputWindow, self).closeEvent(event)
def closeEvent(self, event)
Terminates the child process on close.
10.421625
9.541451
1.092247
if self._process.state() != self._process.Running: return tc = self.textCursor() sel_start = tc.selectionStart() sel_end = tc.selectionEnd() tc.setPosition(self._formatter._last_cursor_pos) self.setTextCursor(tc) if self.input_handler.key_pres...
def keyPressEvent(self, event)
Handle key press event using the defined input handler.
2.930817
2.714889
1.079535
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.text()): if not match: continue start, end = match.span(...
def mouseMoveEvent(self, event)
Handle mouse over file link.
3.318548
2.946279
1.126352
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: line = int(line) - 1 else: line = 0 s...
def mousePressEvent(self, event)
Handle file link clicks.
3.594447
2.931085
1.22632