text
stringlengths
18
773k
def get_gtf_db(gtf, in_memory=False): """ create a gffutils DB """ db_file = gtf + '.db' if gtf.endswith('.gz'): db_file = gtf[:-3] + '.db' if file_exists(db_file): return gffutils.FeatureDB(db_file) db_file = ':memory:' if in_memory else db_file if in_memory or not file_...
def gtf_to_bed(gtf, alt_out_dir=None): """ create a BED file of transcript-level features with attached gene name or gene ids """ out_file = os.path.splitext(gtf)[0] + '.bed' if file_exists(out_file): return out_file if not os.access(os.path.dirname(out_file), os.W_OK | os.X_OK): ...
def tx2genefile(gtf, out_file=None): """ write out a file of transcript->gene mappings. use the installed tx2gene.csv if it exists, else write a new one out """ installed_tx2gene = os.path.join(os.path.dirname(gtf), "tx2gene.csv") if file_exists(installed_tx2gene): return installed_tx2ge...
def transcript_to_gene(gtf): """ return a dictionary keyed by transcript_id of the associated gene_id """ gene_lookup = {} for feature in complete_features(get_gtf_db(gtf)): gene_id = feature.attributes.get('gene_id', [None])[0] transcript_id = feature.attributes.get('transcript_id',...
def set_freq(self, fout, freq): """ Sets new output frequency, required parameters are real current frequency at output and new required frequency. """ hsdiv_tuple = (4, 5, 6, 7, 9, 11) # possible dividers n1div_tuple = (1,) + tuple(range(2,129,2)) # fdco_min =...
def _get_file_alignment_for_new_binary_file(self, file: File) -> int: """Detects alignment requirements for binary files with new nn::util::BinaryFileHeader.""" if len(file.data) <= 0x20: return 0 bom = file.data[0xc:0xc+2] if bom != b'\xff\xfe' and bom != b'\xfe\xff': ...
def check_folders(name): """Only checks and asks questions. Nothing is written to disk.""" if os.getcwd().endswith('analyses'): correct = input('You are in an analyses folder. This will create ' 'another analyses folder inside this one. Do ' 'you want to ...
def create_analyses(name, kernel=None): """Create an analysis with given name and suffix. If it does not exist already, it creates the top level analyses folder and it's __init__.py and index.yaml file. """ if not os.path.exists(os.path.join(os.getcwd(), 'analyses')): os.system("mkdir anal...
def create_analysis(name, kernel, src_dir, scaffold_name): """Create analysis files.""" # analysis folder folder = os.path.join(os.getcwd(), 'analyses', name) if not os.path.exists(folder): os.makedirs(folder) else: log.warning('Analysis folder {} already exists.'.format(folder)) ...
def crsConvert(crsIn, crsOut): """ convert between different types of spatial references Parameters ---------- crsIn: int, str or :osgeo:class:`osr.SpatialReference` the input CRS crsOut: {'wkt', 'proj4', 'epsg', 'osr', 'opengis' or 'prettyWkt'} the output CRS type Returns ...
def haversine(lat1, lon1, lat2, lon2): """ compute the distance in meters between two points in latlon Parameters ---------- lat1: int or float the latitude of point 1 lon1: int or float the longitude of point 1 lat2: int or float the latitude of point 2 lon2: in...
def gdalwarp(src, dst, options): """ a simple wrapper for :osgeo:func:`gdal.Warp` Parameters ---------- src: str, :osgeo:class:`ogr.DataSource` or :osgeo:class:`gdal.Dataset` the input data set dst: str the output data set options: dict additional parameters passed t...
def gdalbuildvrt(src, dst, options=None, void=True): """ a simple wrapper for :osgeo:func:`gdal.BuildVRT` Parameters ---------- src: str, list, :osgeo:class:`ogr.DataSource` or :osgeo:class:`gdal.Dataset` the input data set(s) dst: str the output data set options: dict ...
def gdal_translate(src, dst, options): """ a simple wrapper for `gdal.Translate <https://gdal.org/python/osgeo.gdal-module.html#Translate>`_ Parameters ---------- src: str, :osgeo:class:`ogr.DataSource` or :osgeo:class:`gdal.Dataset` the input data set dst: str the output data s...
def ogr2ogr(src, dst, options): """ a simple wrapper for gdal.VectorTranslate aka `ogr2ogr <https://www.gdal.org/ogr2ogr.html>`_ Parameters ---------- src: str or :osgeo:class:`ogr.DataSource` the input data set dst: str the output data set options: dict additional p...
def gdal_rasterize(src, dst, options): """ a simple wrapper for gdal.Rasterize Parameters ---------- src: str or :osgeo:class:`ogr.DataSource` the input data set dst: str the output data set options: dict additional parameters passed to gdal.Rasterize; see :osgeo:fun...
def coordinate_reproject(x, y, s_crs, t_crs): """ reproject a coordinate from one CRS to another Parameters ---------- x: int or float the X coordinate component y: int or float the Y coordinate component s_crs: int, str or :osgeo:class:`osr.SpatialReference` the...
def set_up_dirs(proc_name, output_dir=None, work_dir=None, log_dir=None): """ Creates output_dir, work_dir, and sets up log """ output_dir = safe_mkdir(adjust_path(output_dir or join(os.getcwd(), proc_name)), 'output_dir') debug('Saving results into ' + output_dir) work_dir = safe_mkdir(work_dir or...
def _iter_content_generator(response, decode_unicode): """Generator used to yield 100 KiB chunks for a given response.""" for chunk in response.iter_content(100 * 1024, decode_unicode=decode_unicode): if decode_unicode: # Replace CRLF newlines with LF, Python will handle # platfo...
def _iter_lines_generator(response, decode_unicode): """Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The function is taken from :meth:`requests.models.Response.iter_lines`, but ...
def _raise_for_status(response): """Raises stored :class:`HTTPError`, if one occurred. This is the :meth:`requests.models.Response.raise_for_status` method, modified to add the response from Space-Track, if given. """ http_error_msg = '' if 400 <= response.status_code < 500: http_erro...
def generic_request(self, class_, iter_lines=False, iter_content=False, controller=None, parse_types=False, **kwargs): r"""Generic Space-Track query. The request class methods use this method internally; the public API is as follows: .. code-block:: python ...
def _ratelimited_get(self, *args, **kwargs): """Perform get request, handling rate limiting.""" with self._ratelimiter: resp = self.session.get(*args, **kwargs) # It's possible that Space-Track will return HTTP status 500 with a # query rate limit violation. This can happen ...
def _find_controller(self, class_): """Find first controller that matches given request class. Order is specified by the keys of ``SpaceTrackClient.request_controllers`` (:class:`~collections.OrderedDict`) """ for controller, classes in self.request_controllers.items(): ...
def _download_predicate_data(self, class_, controller): """Get raw predicate information for given request class, and cache for subsequent calls. """ self.authenticate() url = ('{0}{1}/modeldef/class/{2}' .format(self.base_url, controller, class_)) logger...
def get_predicates(self, class_, controller=None): """Get full predicate information for given request class, and cache for subsequent calls. """ if class_ not in self._predicates: if controller is None: controller = self._find_controller(class_) e...
def get_predicates(self, class_): """Proxy ``get_predicates`` to client with stored request controller. """ return self.client.get_predicates( class_=class_, controller=self.controller)
def on_install(self, editor): """ Add the folding menu to the editor, on install. :param editor: editor instance on which the mode has been installed to. """ super(FoldingPanel, self).on_install(editor) self.context_menu = QtWidgets.QMenu(_('Folding'), self.editor) ...
def _draw_rect(self, rect, painter): """ Draw the background rectangle using the current style primitive color or foldIndicatorBackground if nativeFoldingIndicator is true. :param rect: The fold zone rect to draw :param painter: The widget's painter. """ c = sel...
def get_system_bck_color(): """ Gets a system color for drawing the fold scope background. """ def merged_colors(colorA, colorB, factor): maxFactor = 100 colorA = QtGui.QColor(colorA) colorB = QtGui.QColor(colorB) tmp = colorA t...
def _draw_fold_indicator(self, top, mouse_over, collapsed, painter): """ Draw the fold indicator/trigger (arrow). :param top: Top position :param mouse_over: Whether the mouse is over the indicator :param collapsed: Whether the trigger is collapsed or not. :param painter...
def _get_scope_highlight_color(self): """ Gets the base scope highlight color (derivated from the editor background) """ color = self.editor.background if color.lightness() < 128: color = drift_color(color, 130) else: color = drift_color(c...
def _add_scope_deco(self, start, end, parent_start, parent_end, base_color, factor): """ Adds a scope decoration that enclose the current scope :param start: Start of the current scope :param end: End of the current scope :param parent_start: Start of the ...
def _add_scope_decorations(self, block, start, end): """ Show a scope decoration on the editor widget :param start: Start line :param end: End line """ try: parent = FoldScope(block).parent() except ValueError: parent = None if Tex...
def _highlight_surrounding_scopes(self, block): """ Highlights the scopes surrounding the current fold scope. :param block: Block that starts the current fold scope. """ scope = FoldScope(block) if (self._current_scope is None or self._current_scope.get_r...
def leaveEvent(self, event): """ Removes scope decorations and background from the editor and the panel if highlight_caret_scope, else simply update the scope decorations to match the caret scope. """ super(FoldingPanel, self).leaveEvent(event) QtWidgets.QApplica...
def _add_fold_decoration(self, block, region): """ Add fold decorations (boxes arround a folded block in the editor widget). """ deco = TextDecoration(block) deco.signals.clicked.connect(self._on_fold_deco_clicked) deco.tooltip = region.text(max_lines=25) ...
def toggle_fold_trigger(self, block): """ Toggle a fold trigger block (expand or collapse it). :param block: The QTextBlock to expand/collapse """ if not TextBlockHelper.is_fold_trigger(block): return region = FoldScope(block) if region.collapsed: ...
def on_state_changed(self, state): """ On state changed we (dis)connect to the cursorPositionChanged signal """ if state: self.editor.key_pressed.connect(self._on_key_pressed) if self._highlight_caret: self.editor.cursorPositionChanged.connect( ...
def _on_key_pressed(self, event): """ Override key press to select the current scope if the user wants to deleted a folded scope (without selecting it). """ delete_request = event.key() in [QtCore.Qt.Key_Backspace, QtCore.Qt.Key_Delete] ...
def _on_key_pressed(self, event): """ Auto indent if the released key is the return key. :param event: the key event """ if not event.isAccepted(): if event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter: cursor = self.editor.textCursor() ...
def verify_signature(self, payload, headers): """Verify that the payload was sent from our GitHub instance.""" github_signature = headers.get("x-hub-signature") if not github_signature: json_abort(401, "X-Hub-Signature header missing.") gh_webhook_secret = current_app.config...
def get_options(self): """Get the options that have been set. Called after the user has added all their own options and is ready to use the variables. """ (options, args) = self.parser.parse_args() # Set values from .visdkrc, but only if they haven't already been set ...
def parse_job_files(self): """Check for job definitions in known zuul files.""" repo_jobs = [] for rel_job_file_path, job_info in self.job_files.items(): LOGGER.debug("Checking for job definitions in %s", rel_job_file_path) jobs = self.parse_job_definitions(rel_job_file_p...
def change_directory(self, directory): """ Changes the current directory. Change is made by running a "cd" command followed by a "clear" command. :param directory: :return: """ self._process.write(('cd %s\n' % directory).encode()) if sys.platform == 'win3...
def icon(self): """ Gets the icon file name. Read-only. """ if isinstance(self._icon, str): if QtGui.QIcon.hasThemeIcon(self._icon): return QtGui.QIcon.fromTheme(self._icon) else: return QtGui.QIcon(self._icon) elif isinstan...
def add_marker(self, marker): """ Adds the marker to the panel. :param marker: Marker to add :type marker: pyqode.core.modes.Marker """ self._markers.append(marker) doc = self.editor.document() assert isinstance(doc, QtGui.QTextDocument) block = d...
def remove_marker(self, marker): """ Removes a marker from the panel :param marker: Marker to remove :type marker: pyqode.core.Marker """ self._markers.remove(marker) self._to_remove.append(marker) if hasattr(marker, 'decoration'): self.editor...
def marker_for_line(self, line): """ Returns the marker that is displayed at the specified line number if any. :param line: The marker line. :return: Marker of None :rtype: pyqode.core.Marker """ markers = [] for marker in self._markers: ...
def _display_tooltip(self, tooltip, top): """ Display tooltip at the specified top position. """ QtWidgets.QToolTip.showText(self.mapToGlobal(QtCore.QPoint( self.sizeHint().width(), top)), tooltip, self)
def finditer_noregex(string, sub, whole_word): """ Search occurrences using str.find instead of regular expressions. :param string: string to parse :param sub: search string :param whole_word: True to select whole words only """ start = 0 while True: start = string.find(sub, sta...
def findalliter(string, sub, regex=False, case_sensitive=False, whole_word=False): """ Generator that finds all occurrences of ``sub`` in ``string`` :param string: string to parse :param sub: string to search :param regex: True to search using regex :param case_sensitive: True t...
def findall(data): """ Worker that finds all occurrences of a given string (or regex) in a given text. :param data: Request data dict:: { 'string': string to search in text 'sub': input text 'regex': True to consider string as a regular expression ...
def split(txt, seps): """ Splits a text in a meaningful list of words based on a list of word separators (define in pyqode.core.settings) :param txt: Text to split :param seps: List of words separators :return: A **set** of words found in the document (excluding ...
def complete(self, code, *args): """ Provides completions based on the document words. :param code: code to complete :param args: additional (unused) arguments. """ completions = [] for word in self.split(code, self.separators): completions.append({'n...
def status_to_string(cls, status): """ Converts a message status to a string. :param status: Status to convert (p yqode.core.modes.CheckerMessages) :return: The status string. :rtype: str """ strings = {CheckerMessages.INFO: "Info", CheckerMess...
def add_messages(self, messages): """ Adds a message or a list of message. :param messages: A list of messages or a single message """ # remove old messages if len(messages) > self.limit: messages = messages[:self.limit] _logger(self.__class__).log(5,...
def remove_message(self, message): """ Removes a message. :param message: Message to remove """ import time _logger(self.__class__).log(5, 'removing message %s' % message) t = time.time() usd = message.block.userData() if usd: try: ...
def clear_messages(self): """ Clears all messages. """ while len(self._messages): msg = self._messages.pop(0) usd = msg.block.userData() if usd and hasattr(usd, 'messages'): usd.messages[:] = [] if msg.decoration: ...
def _on_work_finished(self, results): """ Display results. :param status: Response status :param results: Response data, messages. """ messages = [] for msg in results: msg = CheckerMessage(*msg) if msg.line >= self.editor.blockCount(): ...
def request_analysis(self): """ Requests an analysis. """ if self._finished: _logger(self.__class__).log(5, 'running analysis') self._job_runner.request_job(self._request) elif self.editor: # retry later _logger(self.__class__).log(...
def _request(self): """ Requests a checking of the editor content. """ try: self.editor.toPlainText() except (TypeError, RuntimeError): return try: max_line_length = self.editor.modes.get( 'RightMarginMode').position except KeyE...
def openpty(): """openpty() -> (master_fd, slave_fd) Open a pty master/slave pair, using os.openpty() if possible.""" try: return os.openpty() except (AttributeError, OSError): pass master_fd, slave_name = _open_terminal() slave_fd = slave_open(slave_name) return master_fd, ...
def master_open(): """master_open() -> (master_fd, slave_name) Open a pty master and return the fd, and the filename of the slave end. Deprecated, use openpty() instead.""" try: master_fd, slave_fd = os.openpty() except (AttributeError, OSError): pass else: slave_name = ...
def _open_terminal(): """Open pty master and return (master_fd, tty_name).""" for x in 'pqrstuvwxyzPQRST': for y in '0123456789abcdef': pty_name = '/dev/pty' + x + y try: fd = os.open(pty_name, os.O_RDWR) except OSError: continue ...
def slave_open(tty_name): """slave_open(tty_name) -> slave_fd Open the pty slave and acquire the controlling terminal, returning opened filedescriptor. Deprecated, use openpty() instead.""" result = os.open(tty_name, os.O_RDWR) try: from fcntl import ioctl, I_PUSH except ImportError...
def fork(): """fork() -> (pid, master_fd) Fork and make the child a session leader with a controlling terminal.""" try: pid, fd = os.forkpty() except (AttributeError, OSError): pass else: if pid == CHILD: try: os.setsid() except OSErro...
def _writen(fd, data): """Write all the data to a descriptor.""" while data: n = os.write(fd, data) data = data[n:]
def _copy(master_fd, master_read=_read, stdin_read=_read): """Parent copy loop. Copies pty master -> standard output (master_read) standard input -> pty master (stdin_read)""" fds = [master_fd, STDIN_FILENO] while True: rfds, wfds, xfds = select(fds, [], []) ...
def spawn(argv, master_read=_read, stdin_read=_read): """Create a spawned process.""" if type(argv) == type(''): argv = (argv,) pid, master_fd = fork() if pid == CHILD: try: os.execlp(argv[0], *argv) except: # If we wanted to be really clever, we would use...
def _get_dataobject(self, name, multivalued): """This function only gets called if the decorated property doesn't have a value in the cache.""" logger.debug("Querying server for uncached data object %s", name) # This will retrieve the value and inject it into the cache self.updat...
def _get_mor(self, name, multivalued): """This function only gets called if the decorated property doesn't have a value in the cache.""" logger.debug("Querying server for uncached MOR %s", name) # This will retrieve the value and inject it into the cache logger.debug("Getting vie...
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. """ if hasattr(self, '_cache'): if pr...
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. """ if properties is None: ...
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 ...
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 ...
def _set_view_data(self, object_content): """Update the local object from the passed in object_content.""" # 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._objec...
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). """ LOGGE...
def main(options): """Obtains supported features from the license manager""" client = Client(server=options.server, username=options.username, password=options.password) print('Successfully connected to %s' % client.server) lm_info = client.sc.licenseManager.QuerySupportedFeatures() ...
def append(self, mode): """ Adds a mode to the editor. :param mode: The mode instance to append. """ _logger().log(5, 'adding mode %r', mode.name) self._modes[mode.name] = mode mode.on_install(self.editor) 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. """ _logger().log(5, 'removing mode %r', name_or_klass) mode = self.get(name_or_klass) mode.o...
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 """ if not isinstance(name_or_klass, str): name_or_klass = na...
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: py...
def setVisible(self, visible): """ Shows/Hides the panel Automatically call CodeEdit.refresh_panels. :param visible: Visible state """ _logger().log(5, '%s visibility changed', self.name) super(Panel, self).setVisible(visible) if self.editor: ...
def append(self, decoration): """ Adds a text decoration on a CodeEdit instance :param decoration: Text decoration to add :type decoration: pyqode.core.api.TextDecoration """ if decoration not in self._decorations: self._decorations.append(decoration) ...
def remove(self, decoration): """ Removes a text decoration from the editor. :param decoration: Text decoration to remove :type decoration: pyqode.core.api.TextDecoration """ try: self._decorations.remove(decoration) self.editor.setExtraSelections...
def clear(self): """ Removes all text decoration from the editor. """ self._decorations[:] = [] try: self.editor.setExtraSelections(self._decorations) except RuntimeError: pass
def _on_key_pressed(self, event): """ Resets editor font size to the default font size :param event: wheelEvent :type event: QKeyEvent """ if (int(event.modifiers()) & QtCore.Qt.ControlModifier > 0 and not int(event.modifiers()) & QtCore.Qt.ShiftModifier)...
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 """ try: delta = event.angleDelta().y() except AttributeError:...
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. ...
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:...
def stop_process(self): """ Stop the process (by killing it). """ if self.process is not None: self._user_stop = True self.process.kill() self.setReadOnly(True) self._running = False
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 :typ...
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 sty...
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. """ if not value: # fallback to utf-8 value = 'UTF-8' # UTF-8 -> utf_8 converted = value.replace('-', '_')....
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 meaning...
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 """ text = block.text() # round down to previous indentation guide to ensur...
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. """ file_obj = io.StringIO(contents) config = six.moves.c...
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. """ if not filename: return imp.new_module('local_pylint_config') module = imp.load_...
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. """ config = Config( DEFAU...