sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def by_lookup(self, style_key, style_value): """Return a processor that extracts the style from `mapping`. Parameters ---------- style_key : str A style key. style_value : dict A dictionary with a "lookup" key whose value is a "mapping" style ...
Return a processor that extracts the style from `mapping`. Parameters ---------- style_key : str A style key. style_value : dict A dictionary with a "lookup" key whose value is a "mapping" style value that maps a field value to either a style attribut...
entailment
def by_re_lookup(self, style_key, style_value, re_flags=0): """Return a processor for a "re_lookup" style value. Parameters ---------- style_key : str A style key. style_value : dict A dictionary with a "re_lookup" style value that consists of a ...
Return a processor for a "re_lookup" style value. Parameters ---------- style_key : str A style key. style_value : dict A dictionary with a "re_lookup" style value that consists of a sequence of items where each item should have the form `(regexp, ...
entailment
def by_interval_lookup(self, style_key, style_value): """Return a processor for an "interval" style value. Parameters ---------- style_key : str A style key. style_value : dict A dictionary with an "interval" key whose value consists of a sequ...
Return a processor for an "interval" style value. Parameters ---------- style_key : str A style key. style_value : dict A dictionary with an "interval" key whose value consists of a sequence of tuples where each tuple should have the form `(start, ...
entailment
def post_from_style(self, column_style): """Yield post-format processors based on `column_style`. Parameters ---------- column_style : dict A style where the top-level keys correspond to style attributes such as "bold" or "color". Returns -------...
Yield post-format processors based on `column_style`. Parameters ---------- column_style : dict A style where the top-level keys correspond to style attributes such as "bold" or "color". Returns ------- A generator object.
entailment
def split_flanks(self, _, result): """Return `result` without flanking whitespace. """ if not result.strip(): self.left, self.right = "", "" return result match = self.flank_re.match(result) assert match, "This regexp should always match" self.lef...
Return `result` without flanking whitespace.
entailment
def render(self, style_attr, value): """Prepend terminal code for `key` to `value`. Parameters ---------- style_attr : str A style attribute (e.g., "bold" or "blue"). value : str The value to render. Returns ------- The code for `...
Prepend terminal code for `key` to `value`. Parameters ---------- style_attr : str A style attribute (e.g., "bold" or "blue"). value : str The value to render. Returns ------- The code for `key` (e.g., "\x1b[1m" for bold) plus the ...
entailment
def post_from_style(self, column_style): """A Terminal-specific reset to StyleProcessors.post_from_style. """ for proc in super(TermProcessors, self).post_from_style(column_style): if proc.__name__ == "join_flanks": # Reset any codes before adding back whitespace. ...
A Terminal-specific reset to StyleProcessors.post_from_style.
entailment
def connect(self, cback): "See signal" return self.signal.connect(cback, subscribers=self.subscribers, instance=self.instance)
See signal
entailment
def disconnect(self, cback): "See signal" return self.signal.disconnect(cback, subscribers=self.subscribers, instance=self.instance)
See signal
entailment
def get_subscribers(self): """Get per-instance subscribers from the signal. """ data = self.signal.instance_subscribers if self.instance not in data: data[self.instance] = MethodAwareWeakList() return data[self.instance]
Get per-instance subscribers from the signal.
entailment
def notify(self, *args, **kwargs): "See signal" loop = kwargs.pop('loop', self.loop) return self.signal.prepare_notification( subscribers=self.subscribers, instance=self.instance, loop=loop).run(*args, **kwargs)
See signal
entailment
def notify_prepared(self, args=None, kwargs=None, **opts): """Like notify allows to pass more options to the underlying `Signal.prepare_notification()` method. The allowed options are: notify_external : bool a flag indicating if the notification should also include the ...
Like notify allows to pass more options to the underlying `Signal.prepare_notification()` method. The allowed options are: notify_external : bool a flag indicating if the notification should also include the registered `~.external.ExternalSignaller` in the notification. It'...
entailment
def connect(self, cback, subscribers=None, instance=None): """Add a function or a method as an handler of this signal. Any handler added can be a coroutine. :param cback: the callback (or *handler*) to be added to the set :returns: ``None`` or the value returned by the corresponding wr...
Add a function or a method as an handler of this signal. Any handler added can be a coroutine. :param cback: the callback (or *handler*) to be added to the set :returns: ``None`` or the value returned by the corresponding wrapper
entailment
def disconnect(self, cback, subscribers=None, instance=None): """Remove a previously added function or method from the set of the signal's handlers. :param cback: the callback (or *handler*) to be added to the set :returns: ``None`` or the value returned by the corresponding wrapper ...
Remove a previously added function or method from the set of the signal's handlers. :param cback: the callback (or *handler*) to be added to the set :returns: ``None`` or the value returned by the corresponding wrapper
entailment
def ext_publish(self, instance, loop, *args, **kwargs): """If 'external_signaller' is defined, calls it's publish method to notify external event systems. This is for internal usage only, but it's doumented because it's part of the interface with external notification systems. "...
If 'external_signaller' is defined, calls it's publish method to notify external event systems. This is for internal usage only, but it's doumented because it's part of the interface with external notification systems.
entailment
def prepare_notification(self, *, subscribers=None, instance=None, loop=None, notify_external=True): """Sets up a and configures an `~.utils.Executor`:class: instance.""" # merge callbacks added to the class level with those added to the # instance, giving the former...
Sets up a and configures an `~.utils.Executor`:class: instance.
entailment
def configure_logging( filename=None, filemode="a", datefmt=FMT_DATE, fmt=FMT, stdout_fmt=FMT_STDOUT, level=logging.DEBUG, stdout_level=logging.WARNING, initial_file_message="", max_size=1048576, rotations_number=5, remove_handlers=True, ): """Configure logging module. ...
Configure logging module. Args: filename (str): Specifies a filename to log to. filemode (str): Specifies the mode to open the log file. Values: ``'a'``, ``'w'``. *Default:* ``a``. datefmt (str): Use the specified date/time format. fmt (str): Format string for the file h...
entailment
def create_plan(existing_users=None, proposed_users=None, purge_undefined=None, protected_users=None, allow_non_unique_id=None, manage_home=True, manage_keys=True): """Determine what changes are required. args: existing_users (Users): List of discovered users proposed_users (Use...
Determine what changes are required. args: existing_users (Users): List of discovered users proposed_users (Users): List of proposed users purge_undefined (bool): Remove discovered users that have not been defined in proposed users list protected_users (list): List of users' names t...
entailment
def execute_plan(plan=None): """Create, Modify or Delete, depending on plan item.""" execution_result = list() for task in plan: action = task['action'] if action == 'delete': command = generate_delete_user_command(username=task.get('username'), manage_home=task['manage_home']) ...
Create, Modify or Delete, depending on plan item.
entailment
def get(self, variable_path: str, default: t.Optional[t.Any] = None, coerce_type: t.Optional[t.Type] = None, coercer: t.Optional[t.Callable] = None, **kwargs): """ Reads a value of ``variable_path`` from environment. If ``coerce_type``...
Reads a value of ``variable_path`` from environment. If ``coerce_type`` is ``bool`` and no ``coercer`` specified, ``coerces`` forced to be :func:`~django_docker_helpers.utils.coerce_str_to_bool` :param variable_path: a delimiter-separated path to a nested value :param default: default ...
entailment
def unzip(archive, destination, filenames=None): """Unzip a zip archive into destination directory. It unzips either the whole archive or specific file(s) from the archive. Usage: >>> output = os.path.join(os.getcwd(), 'output') >>> # Archive can be an instance of a ZipFile class >...
Unzip a zip archive into destination directory. It unzips either the whole archive or specific file(s) from the archive. Usage: >>> output = os.path.join(os.getcwd(), 'output') >>> # Archive can be an instance of a ZipFile class >>> archive = zipfile.ZipFile('test.zip', 'r') >>...
entailment
def mkzip(archive, items, mode="w", save_full_paths=False): """Recursively zip a directory. Args: archive (zipfile.ZipFile or str): ZipFile object add to or path to the output zip archive. items (str or list of str): Single item or list of items (files and directories) t...
Recursively zip a directory. Args: archive (zipfile.ZipFile or str): ZipFile object add to or path to the output zip archive. items (str or list of str): Single item or list of items (files and directories) to be added to zipfile. mode (str): w for create new and wri...
entailment
def seven_zip(archive, items, self_extracting=False): """Create a 7z archive.""" if not isinstance(items, (list, tuple)): items = [items] if self_extracting: return er(_get_sz(), "a", "-ssw", "-sfx", archive, *items) else: return er(_get_sz(), "a", "-ssw", archive, *items)
Create a 7z archive.
entailment
def ensure_caches_alive(max_retries: int = 100, retry_timeout: int = 5, exit_on_failure: bool = True) -> bool: """ Checks every cache backend alias in ``settings.CACHES`` until it becomes available. After ``max_retries`` attempts to reach any backend are faile...
Checks every cache backend alias in ``settings.CACHES`` until it becomes available. After ``max_retries`` attempts to reach any backend are failed it returns ``False``. If ``exit_on_failure`` is set it shuts down with ``exit(1)``. It sets the ``django-docker-helpers:available-check`` key for every cache ba...
entailment
def ensure_databases_alive(max_retries: int = 100, retry_timeout: int = 5, exit_on_failure: bool = True) -> bool: """ Checks every database alias in ``settings.DATABASES`` until it becomes available. After ``max_retries`` attempts to reach any backend ar...
Checks every database alias in ``settings.DATABASES`` until it becomes available. After ``max_retries`` attempts to reach any backend are failed it returns ``False``. If ``exit_on_failure`` is set it shuts down with ``exit(1)``. For every database alias it tries to ``SELECT 1``. If no errors raised it chec...
entailment
def migrate(*argv) -> bool: """ Runs Django migrate command. :return: always ``True`` """ wf('Applying migrations... ', False) execute_from_command_line(['./manage.py', 'migrate'] + list(argv)) wf('[+]\n') return True
Runs Django migrate command. :return: always ``True``
entailment
def output(self, output, accepts, set_http_code, set_content_type): """ Formats a response from a WSGI app to handle any RDF graphs If a view function returns a single RDF graph, serialize it based on Accept header If it's not an RDF graph, return it without any special handling """ graph = Decorator...
Formats a response from a WSGI app to handle any RDF graphs If a view function returns a single RDF graph, serialize it based on Accept header If it's not an RDF graph, return it without any special handling
entailment
def decorate(self, app): """ Wraps a WSGI application to return formatted RDF graphs Uses content negotiation to serialize the graph to the client-preferred format Passes other content through unmodified """ from functools import wraps @wraps(app) def decorated(environ, start_response): # capt...
Wraps a WSGI application to return formatted RDF graphs Uses content negotiation to serialize the graph to the client-preferred format Passes other content through unmodified
entailment
def is_handler(cls, name, value): """Detect an handler and return its wanted signal name.""" signal_name = False config = None if callable(value) and hasattr(value, SPEC_CONTAINER_MEMBER_NAME): spec = getattr(value, SPEC_CONTAINER_MEMBER_NAME) if spec['kin...
Detect an handler and return its wanted signal name.
entailment
def _build_inheritance_chain(cls, bases, *names, merge=False): """For all of the names build a ChainMap containing a map for every base class.""" result = [] for name in names: maps = [] for base in bases: bmap = getattr(base, name, None) ...
For all of the names build a ChainMap containing a map for every base class.
entailment
def _build_instance_handler_mapping(cls, instance, handle_d): """For every unbound handler, get the bound version.""" res = {} for member_name, sig_name in handle_d.items(): if sig_name in res: sig_handlers = res[sig_name] else: sig_handler...
For every unbound handler, get the bound version.
entailment
def _check_local_handlers(cls, signals, handlers, namespace, configs): """For every marked handler, see if there is a suitable signal. If not, raise an error.""" for aname, sig_name in handlers.items(): # WARN: this code doesn't take in account the case where a new # meth...
For every marked handler, see if there is a suitable signal. If not, raise an error.
entailment
def _find_local_signals(cls, signals, namespace): """Add name info to every "local" (present in the body of this class) signal and add it to the mapping. Also complete signal initialization as member of the class by injecting its name. """ from . import Signal signaller...
Add name info to every "local" (present in the body of this class) signal and add it to the mapping. Also complete signal initialization as member of the class by injecting its name.
entailment
def _find_local_handlers(cls, handlers, namespace, configs): """Add name info to every "local" (present in the body of this class) handler and add it to the mapping. """ for aname, avalue in namespace.items(): sig_name, config = cls._is_handler(aname, avalue) if ...
Add name info to every "local" (present in the body of this class) handler and add it to the mapping.
entailment
def _get_class_handlers(cls, signal_name, instance): """Returns the handlers registered at class level. """ handlers = cls._signal_handlers_sorted[signal_name] return [getattr(instance, hname) for hname in handlers]
Returns the handlers registered at class level.
entailment
def _sort_handlers(cls, signals, handlers, configs): """Sort class defined handlers to give precedence to those declared at lower level. ``config`` can contain two keys ``begin`` or ``end`` that will further reposition the handler at the two extremes. """ def macro_precedence_sor...
Sort class defined handlers to give precedence to those declared at lower level. ``config`` can contain two keys ``begin`` or ``end`` that will further reposition the handler at the two extremes.
entailment
def instance_signals_and_handlers(cls, instance): """Calculate per-instance signals and handlers.""" isignals = cls._signals.copy() ihandlers = cls._build_instance_handler_mapping( instance, cls._signal_handlers ) return isignals, ihandlers
Calculate per-instance signals and handlers.
entailment
def add(self, src): """ :param src: file path :return: checksum value """ checksum = get_checksum(src) filename = self.get_filename(checksum) if not filename: new_name = self._get_new_name() new_realpath = self._storage_dir + '/' + new_...
:param src: file path :return: checksum value
entailment
def get_filename(self, checksum): """ :param checksum: checksum :return: filename no storage base part """ filename = None for _filename, metadata in self._log.items(): if metadata['checksum'] == checksum: filename = _filename b...
:param checksum: checksum :return: filename no storage base part
entailment
def __retrieve(self, key): ''' Retrieve file location from cache DB ''' with self.get_conn() as conn: try: c = conn.cursor() if key is None: c.execute("SELECT value FROM cache_entries WHERE key IS NULL") else: ...
Retrieve file location from cache DB
entailment
def __insert(self, key, value): ''' Insert a new key to database ''' if key in self: getLogger().warning("Cache entry exists, cannot insert a new entry with key='{key}'".format(key=key)) return False with self.get_conn() as conn: try: ...
Insert a new key to database
entailment
def __delete(self, key): ''' Delete file key from database ''' with self.get_conn() as conn: try: c = conn.cursor() c.execute("DELETE FROM cache_entries WHERE key = ?", (key,)) conn.commit() except: getLogger...
Delete file key from database
entailment
def __insert_internal_blob(self, key, blob, compressed=True): ''' This method will insert blob data to blob table ''' with self.get_conn() as conn: conn.isolation_level = None c = conn.cursor() try: compressed_flag = 1 if compressed else 0 ...
This method will insert blob data to blob table
entailment
def __delete_internal_blob(self, key): ''' This method will insert blob data to blob table ''' with self.get_conn() as conn: conn.isolation_level = None try: c = conn.cursor() c.execute("BEGIN") if key is None: ...
This method will insert blob data to blob table
entailment
def __retrieve_internal_blob(self, key): ''' Retrieve file location from cache DB ''' logger = getLogger() with self.get_conn() as conn: try: c = conn.cursor() if key is None: c.execute("SELECT compressed, blob_data FROM blo...
Retrieve file location from cache DB
entailment
def retrieve_blob(self, key, encoding=None): ''' Retrieve blob in binary format (or string format if encoding is provided) ''' blob_key = self.__retrieve(key) if blob_key is None: return None if not blob_key: raise Exception("Invalid blob_key") elif blob_k...
Retrieve blob in binary format (or string format if encoding is provided)
entailment
def summarize(self, rows): """Return summary rows for `rows`. Parameters ---------- rows : list of dicts Normalized rows to summarize. Returns ------- A list of summary rows. Each row is a tuple where the first item is the data and the secon...
Return summary rows for `rows`. Parameters ---------- rows : list of dicts Normalized rows to summarize. Returns ------- A list of summary rows. Each row is a tuple where the first item is the data and the second is a dict of keyword arguments that ...
entailment
def _init(self, style, streamer, processors=None): """Do writer-specific setup. Parameters ---------- style : dict Style, as passed to __init__. streamer : interface.Stream A stream interface that takes __init__'s `stream` and `interactive` ar...
Do writer-specific setup. Parameters ---------- style : dict Style, as passed to __init__. streamer : interface.Stream A stream interface that takes __init__'s `stream` and `interactive` arguments into account. processors : field.StyleProcesso...
entailment
def ids(self): """A list of unique IDs used to identify a row. If not explicitly set, it defaults to the first column name. """ if self._ids is None: if self._columns: if isinstance(self._columns, OrderedDict): return [list(self._columns.k...
A list of unique IDs used to identify a row. If not explicitly set, it defaults to the first column name.
entailment
def wait(self): """Wait for asynchronous calls to return. """ if self._pool is None: return self._pool.close() self._pool.join()
Wait for asynchronous calls to return.
entailment
def _write_lock(self): """Acquire and release the lock around output calls. This should allow multiple threads or processes to write output reliably. Code that modifies the `_content` attribute should also do so within this context. """ if self._lock: lgr.de...
Acquire and release the lock around output calls. This should allow multiple threads or processes to write output reliably. Code that modifies the `_content` attribute should also do so within this context.
entailment
def _start_callables(self, row, callables): """Start running `callables` asynchronously. """ id_vals = {c: row[c] for c in self.ids} def callback(tab, cols, result): if isinstance(result, Mapping): pass elif isinstance(result, tuple): ...
Start running `callables` asynchronously.
entailment
def schemas(self): """ Get a listing of all non-system schemas (prefixed with 'pg_') that exist in the database. """ sql = """SELECT schema_name FROM information_schema.schemata ORDER BY schema_name""" schemas = self.query(sql).fetchall() return [...
Get a listing of all non-system schemas (prefixed with 'pg_') that exist in the database.
entailment
def tables(self): """ Get a listing of all tables - if schema specified on connect, return unqualifed table names in that schema - in no schema specified on connect, return all tables, with schema prefixes """ if self.schema: return...
Get a listing of all tables - if schema specified on connect, return unqualifed table names in that schema - in no schema specified on connect, return all tables, with schema prefixes
entailment
def _valid_table_name(self, table): """Check if the table name is obviously invalid. """ if table is None or not len(table.strip()): raise ValueError("Invalid table name: %r" % table) return table.strip()
Check if the table name is obviously invalid.
entailment
def build_query(self, sql, lookup): """ Modify table and field name variables in a sql string with a dict. This seems to be discouraged by psycopg2 docs but it makes small adjustments to large sql strings much easier, making prepped queries much more versatile. USAGE ...
Modify table and field name variables in a sql string with a dict. This seems to be discouraged by psycopg2 docs but it makes small adjustments to large sql strings much easier, making prepped queries much more versatile. USAGE sql = 'SELECT $myInputField FROM $myInputTable' ...
entailment
def tables_in_schema(self, schema): """Get a listing of all tables in given schema """ sql = """SELECT table_name FROM information_schema.tables WHERE table_schema = %s""" return [t[0] for t in self.query(sql, (schema,)).fetchall()]
Get a listing of all tables in given schema
entailment
def parse_table_name(self, table): """Parse schema qualified table name """ if "." in table: schema, table = table.split(".") else: schema = None return (schema, table)
Parse schema qualified table name
entailment
def load_table(self, table): """Loads a table. Returns None if the table does not already exist in db """ table = self._valid_table_name(table) schema, table = self.parse_table_name(table) if not schema: schema = self.schema tables = self.tables el...
Loads a table. Returns None if the table does not already exist in db
entailment
def mogrify(self, sql, params): """Return the query string with parameters added """ conn = self.engine.raw_connection() cursor = conn.cursor() return cursor.mogrify(sql, params)
Return the query string with parameters added
entailment
def execute(self, sql, params=None): """Just a pointer to engine.execute """ # wrap in a transaction to ensure things are committed # https://github.com/smnorris/pgdata/issues/3 with self.engine.begin() as conn: result = conn.execute(sql, params) return result
Just a pointer to engine.execute
entailment
def query_one(self, sql, params=None): """Grab just one record """ r = self.engine.execute(sql, params) return r.fetchone()
Grab just one record
entailment
def create_schema(self, schema): """Create specified schema if it does not already exist """ if schema not in self.schemas: sql = "CREATE SCHEMA " + schema self.execute(sql)
Create specified schema if it does not already exist
entailment
def drop_schema(self, schema, cascade=False): """Drop specified schema """ if schema in self.schemas: sql = "DROP SCHEMA " + schema if cascade: sql = sql + " CASCADE" self.execute(sql)
Drop specified schema
entailment
def create_table(self, table, columns): """Creates a table """ schema, table = self.parse_table_name(table) table = self._valid_table_name(table) if not schema: schema = self.schema if table in self.tables: return Table(self, schema, table) ...
Creates a table
entailment
def ogr2pg( self, in_file, in_layer=None, out_layer=None, schema="public", s_srs=None, t_srs="EPSG:3005", sql=None, dim=2, cmd_only=False, index=True ): """ Load a layer to provided pgdata database connection usi...
Load a layer to provided pgdata database connection using OGR2OGR -sql option is like an ESRI where_clause or the ogr2ogr -where option, but to increase flexibility, it is in SQLITE dialect: SELECT * FROM <in_layer> WHERE <sql>
entailment
def pg2ogr( self, sql, driver, outfile, outlayer=None, column_remap=None, s_srs="EPSG:3005", t_srs=None, geom_type=None, append=False, ): """ A wrapper around ogr2ogr, for quickly dumping a postgis query to file. ...
A wrapper around ogr2ogr, for quickly dumping a postgis query to file. Suppported formats are ["ESRI Shapefile", "GeoJSON", "FileGDB", "GPKG"] - for GeoJSON, transforms to EPSG:4326 - for Shapefile, consider supplying a column_remap dict - for FileGDB, geom_type is required ...
entailment
def setup_logging(filename, log_dir=None, force_setup=False): ''' Try to load logging configuration from a file. Set level to INFO if failed. ''' if not force_setup and ChirpCLI.SETUP_COMPLETED: logging.debug("Master logging has been setup. This call will be ignored.") return if log_dir ...
Try to load logging configuration from a file. Set level to INFO if failed.
entailment
def config_logging(args): ''' Override root logger's level ''' if args.quiet: logging.getLogger().setLevel(logging.CRITICAL) elif args.verbose: logging.getLogger().setLevel(logging.DEBUG)
Override root logger's level
entailment
def add_task(self, task, func=None, **kwargs): ''' Add a task parser ''' if not self.__tasks: raise Exception("Tasks subparsers is disabled") if 'help' not in kwargs: if func.__doc__: kwargs['help'] = func.__doc__ task_parser = self.__tasks.add_par...
Add a task parser
entailment
def add_vq(self, parser): ''' Add verbose & quiet options ''' group = parser.add_mutually_exclusive_group() group.add_argument("-v", "--verbose", action="store_true") group.add_argument("-q", "--quiet", action="store_true")
Add verbose & quiet options
entailment
def add_version_func(self, show_version): ''' Enable --version and -V to show version information ''' if callable(show_version): self.__show_version_func = show_version else: self.__show_version_func = lambda cli, args: print(show_version) self.parser.add_argument...
Enable --version and -V to show version information
entailment
def logger(self): ''' Lazy logger ''' if self.__logger is None: self.__logger = logging.getLogger(self.__name) return self.__logger
Lazy logger
entailment
def run(self, func=None): ''' Run the app ''' args = self.parser.parse_args() if self.__add_vq is not None and self.__config_logging: self.__config_logging(args) if self.__show_version_func and args.version and callable(self.__show_version_func): self.__show_versi...
Run the app
entailment
def header(*msg, level='h1', separator=" ", print_out=print): ''' Print header block in text mode ''' out_string = separator.join(str(x) for x in msg) if level == 'h0': # box_len = 80 if len(msg) < 80 else len(msg) box_len = 80 print_out('+' + '-' * (box_len + 2)) print_o...
Print header block in text mode
entailment
def fetch(self, value_obj=None): ''' Fetch the next two values ''' val = None try: val = next(self.__iterable) except StopIteration: return None if value_obj is None: value_obj = Value(value=val) else: value_obj.value = val ...
Fetch the next two values
entailment
def get_report_order(self): ''' Keys are sorted based on report order (i.e. some keys to be shown first) Related: see sorted_by_count ''' order_list = [] for x in self.__priority: order_list.append([x, self[x]]) for x in sorted(list(self.keys())): ...
Keys are sorted based on report order (i.e. some keys to be shown first) Related: see sorted_by_count
entailment
def content(self): ''' Return report content as a string if mode == STRINGIO else an empty string ''' if isinstance(self.__report_file, io.StringIO): return self.__report_file.getvalue() else: return ''
Return report content as a string if mode == STRINGIO else an empty string
entailment
def format(self): ''' Format table to print out ''' self.max_lengths = [] for row in self.rows: if len(self.max_lengths) < len(row): self.max_lengths += [0] * (len(row) - len(self.max_lengths)) for idx, val in enumerate(row): len_ce...
Format table to print out
entailment
def getfullfilename(file_path): ''' Get full filename (with extension) ''' warnings.warn("getfullfilename() is deprecated and will be removed in near future. Use chirptext.io.write_file() instead", DeprecationWarning) if file_path: return os.path.basename(file_path) e...
Get full filename (with extension)
entailment
def replace_ext(file_path, ext): ''' Change extension of a file_path to something else (provide None to remove) ''' if not file_path: raise Exception("File path cannot be empty") dirname = os.path.dirname(file_path) filename = FileHelper.getfilename(file_path) if ext:...
Change extension of a file_path to something else (provide None to remove)
entailment
def replace_name(file_path, new_name): ''' Change the file name in a path but keep the extension ''' if not file_path: raise Exception("File path cannot be empty") elif not new_name: raise Exception("New name cannot be empty") dirname = os.path.dirname(file_path) ...
Change the file name in a path but keep the extension
entailment
def get_child_folders(path): ''' Get all child folders of a folder ''' path = FileHelper.abspath(path) return [dirname for dirname in os.listdir(path) if os.path.isdir(os.path.join(path, dirname))]
Get all child folders of a folder
entailment
def get_child_files(path): ''' Get all child files of a folder ''' path = FileHelper.abspath(path) return [filename for filename in os.listdir(path) if os.path.isfile(os.path.join(path, filename))]
Get all child files of a folder
entailment
def remove_file(filepath): ''' Delete a file ''' try: os.remove(os.path.abspath(os.path.expanduser(filepath))) except OSError as e: if e.errno != errno.ENOENT: raise
Delete a file
entailment
def _ptn2fn(self, pattern): ''' Pattern to filename ''' return [pattern.format(wd=self.working_dir, n=self.__name, mode=self.__mode), pattern.format(wd=self.working_dir, n='{}.{}'.format(self.__name, self.__mode), mode=self.__mode)]
Pattern to filename
entailment
def add_potential(self, *patterns): ''' Add a potential config file pattern ''' for ptn in patterns: self.__potential.extend(self._ptn2fn(ptn))
Add a potential config file pattern
entailment
def locate_config(self): ''' Locate config file ''' for f in self.__potential: f = FileHelper.abspath(f) if os.path.isfile(f): return f return None
Locate config file
entailment
def config(self): ''' Read config automatically if required ''' if self.__config is None: config_path = self.locate_config() if config_path: self.__config = self.read_file(config_path) self.__config_path = config_path return self.__config
Read config automatically if required
entailment
def read_file(self, file_path): ''' Read a configuration file and return configuration data ''' getLogger().info("Loading app config from {} file: {}".format(self.__mode, file_path)) if self.__mode == AppConfig.JSON: return json.loads(FileHelper.read(file_path), object_pairs_hook=Ord...
Read a configuration file and return configuration data
entailment
def load(self, file_path): ''' Load configuration from a specific file ''' self.clear() self.__config = self.read_file(file_path)
Load configuration from a specific file
entailment
def get_processes(sort_by_name=True): """Retrieve a list of processes sorted by name. Args: sort_by_name (bool): Sort the list by name or by process ID's. Returns: list of (int, str) or list of (int, str, str): List of process id, process name and optional cmdline tuple...
Retrieve a list of processes sorted by name. Args: sort_by_name (bool): Sort the list by name or by process ID's. Returns: list of (int, str) or list of (int, str, str): List of process id, process name and optional cmdline tuples.
entailment
def find(name, arg=None): """Find process by name or by argument in command line. Args: name (str): Process name to search for. arg (str): Command line argument for a process to search for. Returns: tea.process.base.IProcess: Process object if found. """ for p in ...
Find process by name or by argument in command line. Args: name (str): Process name to search for. arg (str): Command line argument for a process to search for. Returns: tea.process.base.IProcess: Process object if found.
entailment
def execute(command, *args, **kwargs): """Execute a command with arguments and wait for output. Arguments should not be quoted! Keyword arguments: env (dict): Dictionary of additional environment variables. wait (bool): Wait for the process to finish. Example:: >>>...
Execute a command with arguments and wait for output. Arguments should not be quoted! Keyword arguments: env (dict): Dictionary of additional environment variables. wait (bool): Wait for the process to finish. Example:: >>> code = 'import sys;sys.stdout.write('out');sys...
entailment
def execute_and_report(command, *args, **kwargs): """Execute a command with arguments and wait for output. If execution was successful function will return True, if not, it will log the output using standard logging and return False. """ logging.info("Execute: %s %s" % (command, " ".join(args...
Execute a command with arguments and wait for output. If execution was successful function will return True, if not, it will log the output using standard logging and return False.
entailment
def read_authorized_keys(username=None): """Read public keys from specified user's authorized_keys file. args: username (str): username. returns: list: Authorised keys for the specified user. """ authorized_keys_path = '{0}/.ssh/authorized_keys'.format(os.path.expanduser('~{0}'.for...
Read public keys from specified user's authorized_keys file. args: username (str): username. returns: list: Authorised keys for the specified user.
entailment
def write_authorized_keys(user=None): """Write public keys back to authorized_keys file. Create keys directory if it doesn't already exist. args: user (User): Instance of User containing keys. returns: list: Authorised keys for the specified user. """ authorized_keys = list() a...
Write public keys back to authorized_keys file. Create keys directory if it doesn't already exist. args: user (User): Instance of User containing keys. returns: list: Authorised keys for the specified user.
entailment
def b64encoded(self): """Return a base64 encoding of the key. returns: str: base64 encoding of the public key """ if self._b64encoded: return text_type(self._b64encoded).strip("\r\n") else: return base64encode(self.raw)
Return a base64 encoding of the key. returns: str: base64 encoding of the public key
entailment
def raw(self): """Return raw key. returns: str: raw key """ if self._raw: return text_type(self._raw).strip("\r\n") else: return text_type(base64decode(self._b64encoded)).strip("\r\n")
Return raw key. returns: str: raw key
entailment
def inner_parser(self) -> BaseParser: """ Prepares inner config parser for config stored at ``endpoint``. :return: an instance of :class:`~django_docker_helpers.config.backends.base.BaseParser` :raises config.exceptions.KVStorageKeyDoestNotExist: if specified ``endpoint`` does not exis...
Prepares inner config parser for config stored at ``endpoint``. :return: an instance of :class:`~django_docker_helpers.config.backends.base.BaseParser` :raises config.exceptions.KVStorageKeyDoestNotExist: if specified ``endpoint`` does not exists :raises config.exceptions.KVStorageValueIsEmpt...
entailment