INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Returns True if the type is elementary - not versioned: param elem_type:: return: | def is_elementary_type(elem_type):
"""
Returns True if the type is elementary - not versioned
:param elem_type:
:return:
"""
if not oh.is_type(elem_type, bt.XmrType):
return False
if oh.is_type(elem_type, (bt.UVarintType, bt.IntType, mt.UnicodeType)):
... |
Copy one or more source directory ( s ) below a destination directory. Parts of the destination directory path are created if needed. Similar to the UNIX command: cp - R srcdir destdir | def command_copytree(args):
"""
Copy one or more source directory(s) below a destination directory.
Parts of the destination directory path are created if needed.
Similar to the UNIX command: 'cp -R srcdir destdir'
"""
for srcdir in args.srcdirs:
basename = os.path.basename(srcdir)
... |
Copy one or more source - files ( s ) to a destpath ( destfile or destdir ). Destdir mode is used if: * More than one srcfile is provided * Last parameter ends with a slash (/ ). * Last parameter is an existing directory | def command_copy(args):
"""
Copy one or more source-files(s) to a destpath (destfile or destdir).
Destdir mode is used if:
* More than one srcfile is provided
* Last parameter ends with a slash ("/").
* Last parameter is an existing directory
Destination directory path is created if n... |
Create a non - existing directory ( or more... ). If the directory exists the step is skipped. Similar to the UNIX command: mkdir - p dir | def command_mkdir(args):
"""
Create a non-existing directory (or more ...).
If the directory exists, the step is skipped.
Similar to the UNIX command: 'mkdir -p dir'
"""
errors = 0
for directory in args.dirs:
if os.path.exists(directory):
if not os.path.isdir(directory):
... |
Apply 2to3 tool ( Python2 to Python3 conversion tool ) to Python sources. | def command_py2to3(args):
"""
Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources.
"""
from lib2to3.main import main
sys.exit(main("lib2to3.fixes", args=args.sources)) |
Command util with subcommands for tox environments. | def toxcmd_main(args=None):
"""Command util with subcommands for tox environments."""
usage = "USAGE: %(prog)s [OPTIONS] COMMAND args..."
if args is None:
args = sys.argv[1:]
# -- STEP: Build command-line parser.
parser = argparse.ArgumentParser(description=inspect.getdoc(toxcmd_main),
... |
Gathers discharge macaroons for all the third party caveats in m ( and any subsequent caveats required by those ) using get_discharge to acquire each discharge macaroon. The local_key parameter may optionally hold the key of the client in which case it will be used to discharge any third party caveats with the special ... | def discharge_all(m, get_discharge, local_key=None):
'''Gathers discharge macaroons for all the third party caveats in m
(and any subsequent caveats required by those) using get_discharge to
acquire each discharge macaroon.
The local_key parameter may optionally hold the key of the client, in
which ... |
Creates a macaroon to discharge a third party caveat. | def discharge(ctx, id, caveat, key, checker, locator):
''' Creates a macaroon to discharge a third party caveat.
The given parameters specify the caveat and how it should be checked.
The condition implicit in the caveat is checked for validity using checker.
If it is valid, a new macaroon is returned w... |
Returns a third - party caveat that when added to a macaroon with add_caveat results in a caveat with the location local encrypted with the given PublicKey. This can be automatically discharged by discharge_all passing a local key. | def local_third_party_caveat(key, version):
''' Returns a third-party caveat that, when added to a macaroon with
add_caveat, results in a caveat with the location "local", encrypted with
the given PublicKey.
This can be automatically discharged by discharge_all passing a local key.
'''
if versio... |
Deserialize a Namespace object. | def deserialize_namespace(data):
''' Deserialize a Namespace object.
:param data: bytes or str
:return: namespace
'''
if isinstance(data, bytes):
data = data.decode('utf-8')
kvs = data.split()
uri_to_prefix = {}
for kv in kvs:
i = kv.rfind(':')
if i == -1:
... |
Returns a serialized form of the Namepace. | def serialize_text(self):
'''Returns a serialized form of the Namepace.
All the elements in the namespace are sorted by
URI, joined to the associated prefix with a colon and
separated with spaces.
:return: bytes
'''
if self._uri_to_prefix is None or len(self._uri... |
Registers the given URI and associates it with the given prefix. | def register(self, uri, prefix):
'''Registers the given URI and associates it with the given prefix.
If the URI has already been registered, this is a no-op.
:param uri: string
:param prefix: string
'''
if not is_valid_schema_uri(uri):
raise KeyError(
... |
Resolves the given caveat ( string ) by using resolve to map from its schema namespace to the appropriate prefix. If there is no registered prefix for the namespace it returns an error caveat. If cav. namespace is empty or cav. location is non - empty it returns cav unchanged. | def resolve_caveat(self, cav):
''' Resolves the given caveat(string) by using resolve to map from its
schema namespace to the appropriate prefix.
If there is no registered prefix for the namespace, it returns an error
caveat.
If cav.namespace is empty or cav.location is non-empty... |
Return a copy of the AuthContext object with the given key and value added. | def with_value(self, key, val):
''' Return a copy of the AuthContext object with the given key and
value added.
'''
new_dict = dict(self._dict)
new_dict[key] = val
return AuthContext(new_dict) |
Save figures. Parameters ---------- filename - str Name of output file fig_IDs - int numpy. array list optional default None A list of open figure IDs or a figure ID that will be saved to a pdf/ png file respectively. ** kwargs - Extra keyword arguments passed into matplotlib. pyplot. savefig. | def save_figures(filename, fig_IDs=None, **kwargs):
"""
Save figures.
Parameters
----------
filename - str
Name of output file
fig_IDs - int, numpy.array, list, optional, default None
A list of open figure IDs or a figure ID that will be saved to a
pdf/png f... |
Executes the command. | def execute(self):
"""
Executes the command.
"""
from vsgen.util.logger import VSGLogger
VSGLogger.info(self._logname, self._message)
start = time.clock()
for i in self._registerables:
i.register()
end = time.clock()
VSGLogger.info(sel... |
Make pattern for a data type with the specified cardinality. | def make_pattern(self, pattern, listsep=','):
"""Make pattern for a data type with the specified cardinality.
.. code-block:: python
yes_no_pattern = r"yes|no"
many_yes_no = Cardinality.one_or_more.make_pattern(yes_no_pattern)
:param pattern: Regular expression for ty... |
Compute the number of regexp match groups when the pattern is provided to the: func: Cardinality. make_pattern () method. | def compute_group_count(self, pattern):
"""Compute the number of regexp match groups when the pattern is provided
to the :func:`Cardinality.make_pattern()` method.
:param pattern: Item regexp pattern (as string).
:return: Number of regexp match groups in the cardinality pattern.
... |
Creates a type converter for the specified cardinality by using the type converter for T. | def with_cardinality(cls, cardinality, converter, pattern=None,
listsep=','):
"""Creates a type converter for the specified cardinality
by using the type converter for T.
:param cardinality: Cardinality to use (0..1, 0..*, 1..*).
:param converter: Type converter... |
Creates a type converter for a T with 0.. 1 times by using the type converter for one item of T. | def with_zero_or_one(cls, converter, pattern=None):
"""Creates a type converter for a T with 0..1 times
by using the type converter for one item of T.
:param converter: Type converter (function) for data type T.
:param pattern: Regexp pattern for an item (=converter.pattern).
:... |
Creates a type converter function for a list<T > with 0.. N items by using the type converter for one item of T. | def with_zero_or_more(cls, converter, pattern=None, listsep=","):
"""Creates a type converter function for a list<T> with 0..N items
by using the type converter for one item of T.
:param converter: Type converter (function) for data type T.
:param pattern: Regexp pattern for an item (=... |
Creates a type converter function for a list<T > with 1.. N items by using the type converter for one item of T. | def with_one_or_more(cls, converter, pattern=None, listsep=","):
"""Creates a type converter function for a list<T> with 1..N items
by using the type converter for one item of T.
:param converter: Type converter (function) for data type T.
:param pattern: Regexp pattern for an item (=c... |
Alias for: py: meth: with_one_or_more () method. | def with_many(cls, converter, pattern=None, listsep=','):
"""Alias for :py:meth:`with_one_or_more()` method."""
return cls.with_one_or_more(converter, pattern, listsep) |
Alias for: py: meth: with_zero_or_more () method. | def with_many0(cls, converter, pattern=None, listsep=','):
"""Alias for :py:meth:`with_zero_or_more()` method."""
return cls.with_zero_or_more(converter, pattern, listsep) |
Compares objects with __slots__ defined: param l:: param r:: return: | def eq_obj_slots(l, r):
"""
Compares objects with __slots__ defined
:param l:
:param r:
:return:
"""
for f in l.__slots__:
if getattr(l, f, None) != getattr(r, f, None):
return False
return True |
Compares object contents supports slots: param l:: param r:: return: | def eq_obj_contents(l, r):
"""
Compares object contents, supports slots
:param l:
:param r:
:return:
"""
if l.__class__ is not r.__class__:
return False
if hasattr(l, "__slots__"):
return eq_obj_slots(l, r)
else:
return l.__dict__ == r.__dict__ |
Builds dict for o with __slots__ defined: param o:: return: | def slot_obj_dict(o):
"""
Builds dict for o with __slots__ defined
:param o:
:return:
"""
d = {}
for f in o.__slots__:
d[f] = getattr(o, f, None)
return d |
Returns true if x is of type in types tuple: param x:: param types:: param full:: return: | def is_type(x, types, full=False):
"""
Returns true if x is of type in types tuple
:param x:
:param types:
:param full:
:return:
"""
types = types if isinstance(types, tuple) else (types,)
ins = isinstance(x, types)
sub = False
try:
sub = issubclass(x, types)
exce... |
Handler for serving static files. | def server_static(filepath):
"""Handler for serving static files."""
mimetype = "image/svg+xml" if filepath.endswith(".svg") else "auto"
return bottle.static_file(filepath, root=conf.StaticPath, mimetype=mimetype) |
Handler for showing mouse statistics for specified type and day. | def mouse(table, day=None):
"""Handler for showing mouse statistics for specified type and day."""
where = (("day", day),) if day else ()
events = db.fetch(table, where=where, order="day")
for e in events: e["dt"] = datetime.datetime.fromtimestamp(e["stamp"])
stats, positions, events = stats_mo... |
Handler for showing the keyboard statistics page. | def keyboard(table, day=None):
"""Handler for showing the keyboard statistics page."""
cols, group = "realkey AS key, COUNT(*) AS count", "realkey"
where = (("day", day),) if day else ()
counts_display = counts = db.fetch(table, cols, where, group, "count DESC")
if "combos" == table:
c... |
Handler for showing keyboard or mouse page with day and total links. | def inputindex(input):
"""Handler for showing keyboard or mouse page with day and total links."""
stats = {}
countminmax = "SUM(count) AS count, MIN(day) AS first, MAX(day) AS last"
tables = ("moves", "clicks", "scrolls") if "mouse" == input else ("keys", "combos")
for table in tables:
... |
Handler for showing the GUI index page. | def index():
"""Handler for showing the GUI index page."""
stats = dict((k, {"count": 0}) for k, tt in conf.InputTables)
countminmax = "SUM(count) AS count, MIN(day) AS first, MAX(day) AS last"
for input, table in [(x, t) for x, tt in conf.InputTables for t in tt]:
row = db.fetchone("counts... |
Return statistics and collated events for keyboard events. | def stats_keyboard(events, table):
"""Return statistics and collated events for keyboard events."""
if len(events) < 2: return [], []
deltas, prev_dt = [], None
sessions, session = [], None
UNBROKEN_DELTA = datetime.timedelta(seconds=conf.KeyboardSessionMaxDelta)
blank = collections.defaul... |
Returns statistics positions and rescaled events for mouse events. | def stats_mouse(events, table):
"""Returns statistics, positions and rescaled events for mouse events."""
if not events: return [], [], []
distance, last, deltas = 0, None, []
HS = conf.MouseHeatmapSize
SC = dict(("xy"[i], conf.DefaultScreenSize[i] / float(HS[i])) for i in [0, 1])
xymap = ... |
Returns the total timedelta duration in seconds. | def timedelta_seconds(timedelta):
"""Returns the total timedelta duration in seconds."""
return (timedelta.total_seconds() if hasattr(timedelta, "total_seconds")
else timedelta.days * 24 * 3600 + timedelta.seconds +
timedelta.microseconds / 1000000.) |
Initialize configuration and web application. | def init():
"""Initialize configuration and web application."""
global app
if app: return app
conf.init(), db.init(conf.DbPath, conf.DbStatements)
bottle.TEMPLATE_PATH.insert(0, conf.TemplatePath)
app = bottle.default_app()
bottle.BaseTemplate.defaults.update(get_url=app.get_url)
... |
Starts the web server. | def start():
"""Starts the web server."""
global app
bottle.run(app, host=conf.WebHost, port=conf.WebPort,
debug=conf.WebAutoReload, reloader=conf.WebAutoReload,
quiet=conf.WebQuiet) |
Handle the download of an URL using the proxy currently set in \: mod: socks. | def _download_helper(url):
"""
Handle the download of an URL, using the proxy currently set in \
:mod:`socks`.
:param url: The URL to download.
:returns: A tuple of the raw content of the downloaded data and its \
associated content-type. Returns None if it was \
una... |
Download a PDF or DJVU document from a url eventually using proxies. | def download(url, proxies=None):
"""
Download a PDF or DJVU document from a url, eventually using proxies.
:params url: The URL to the PDF/DJVU document to fetch.
:params proxies: An optional list of proxies to use. Proxies will be \
used sequentially. Proxies should be a list of proxy stri... |
Build format string from a format specification. | def make_format(format_spec):
"""Build format string from a format specification.
:param format_spec: Format specification (as FormatSpec object).
:return: Composed format (as string).
"""
fill = ''
align = ''
zero = ''
width = format_spec.width
... |
Pull apart the format: [[ fill ] align ] [ 0 ] [ width ] [. precision ] [ type ] | def extract_format_spec(cls, format):
"""Pull apart the format: [[fill]align][0][width][.precision][type]"""
# -- BASED-ON: parse.extract_format()
# pylint: disable=redefined-builtin, unsubscriptable-object
if not format:
raise ValueError("INVALID-FORMAT: %s (empty-string)" %... |
Extract fields in a parse expression schema. | def extract_fields(cls, schema):
"""Extract fields in a parse expression schema.
:param schema: Parse expression schema/format to use (as string).
:return: Generator for fields in schema (as Field objects).
"""
# -- BASED-ON: parse.Parser._generate_expression()
for part ... |
Extract types ( names ) for typed fields ( with format/ type part ). | def extract_types(cls, schema):
"""Extract types (names) for typed fields (with format/type part).
:param schema: Parser schema/format to use.
:return: Generator for type names (as string).
"""
for field in cls.extract_fields(schema):
if field.has_format:
... |
Registers a handler. | def _registerHandler(self, handler):
"""
Registers a handler.
:param handler: A handler object.
"""
self._logger.addHandler(handler)
self._handlers.append(handler) |
Unregisters the logging handler. | def _unregisterHandler(self, handler, shutdown=True):
"""
Unregisters the logging handler.
:param handler: A handler previously registered with this loggger.
:param shutdown: Flag to shutdown the handler.
"""
if handler in self._handlers:
self._handlers.remo... |
Retrieves the Python native logger | def getLogger(cls, name=None):
"""
Retrieves the Python native logger
:param name: The name of the logger instance in the VSG namespace (VSG.<name>); a None value will use the VSG root.
:return: The instacne of the Python logger object.
"""
return logging.getLo... |
Convenience function to log a message at the DEBUG level. | def debug(cls, name, message, *args):
"""
Convenience function to log a message at the DEBUG level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into m... |
Convenience function to log a message at the INFO level. | def info(cls, name, message, *args):
"""
Convenience function to log a message at the INFO level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into msg... |
Convenience function to log a message at the WARNING level. | def warning(cls, name, message, *args):
"""
Convenience function to log a message at the WARNING level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged in... |
Convenience function to log a message at the ERROR level. | def error(cls, name, message, *args):
"""
Convenience function to log a message at the ERROR level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into m... |
Convenience function to log a message at the CRITICAL level. | def critical(cls, name, message, *args):
"""
Convenience function to log a message at the CRITICAL level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged ... |
Convenience function to log a message at the ERROR level with additonal exception information. | def exception(cls, name, message, *args):
"""
Convenience function to log a message at the ERROR level with additonal exception information.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: ... |
Checks that the authorizer s request is authorized to perform all the given operations. Note that allow does not check first party caveats - if there is more than one macaroon that may authorize the request it will choose the first one that does regardless. | def allow(self, ctx, ops):
''' Checks that the authorizer's request is authorized to
perform all the given operations. Note that allow does not check
first party caveats - if there is more than one macaroon that may
authorize the request, it will choose the first one that does
re... |
like allow except that it will authorize as many of the operations as possible without requiring any to be authorized. If all the operations succeeded the array will be nil. | def allow_any(self, ctx, ops):
''' like allow except that it will authorize as many of the
operations as possible without requiring any to be authorized. If all
the operations succeeded, the array will be nil.
If any the operations failed, the returned error will be the same
tha... |
Checks that the user is allowed to perform all the given operations. If not a discharge error will be raised. If allow_capability succeeds it returns a list of first party caveat conditions that must be applied to any macaroon granting capability to execute the operations. Those caveat conditions will not include any d... | def allow_capability(self, ctx, ops):
'''Checks that the user is allowed to perform all the
given operations. If not, a discharge error will be raised.
If allow_capability succeeds, it returns a list of first party caveat
conditions that must be applied to any macaroon granting capabilit... |
Deactivates/ unregisters all recipes of the current plugin if this plugin gets deactivated. | def __deactivate_recipes(self, plugin, *args, **kwargs):
"""
Deactivates/unregisters all recipes of the current plugin, if this plugin gets deactivated.
"""
recipes = self.get()
for recipe in recipes.keys():
self.unregister(recipe) |
Registers a new recipe in the context of the current plugin. | def register(self, name, path, description, final_words=None):
"""
Registers a new recipe in the context of the current plugin.
:param name: Name of the recipe
:param path: Absolute path of the recipe folder
:param description: A meaningful description of the recipe
:par... |
Gets a list of all recipes which are registered by the current plugin. If a name is provided only the requested recipe is returned or None. | def get(self, name=None):
"""
Gets a list of all recipes, which are registered by the current plugin.
If a name is provided, only the requested recipe is returned or None.
:param: name: Name of the recipe
"""
return self.__app.recipes.get(name, self._plugin) |
Builds a recipe | def build(self, recipe):
"""
Builds a recipe
:param recipe: Name of the recipe to build.
"""
return self.__app.recipes.build(recipe, self._plugin) |
Registers a new recipe. | def register(self, name, path, plugin, description=None, final_words=None):
"""
Registers a new recipe.
"""
if name in self.recipes.keys():
raise RecipeExistsException("Recipe %s was already registered by %s" %
(name, self.recipes["name... |
Unregisters an existing recipe so that this recipe is no longer available. | def unregister(self, recipe):
"""
Unregisters an existing recipe, so that this recipe is no longer available.
This function is mainly used during plugin deactivation.
:param recipe: Name of the recipe
"""
if recipe not in self.recipes.keys():
self.__log.warn... |
Get one or more recipes. | def get(self, recipe=None, plugin=None):
"""
Get one or more recipes.
:param recipe: Name of the recipe
:type recipe: str
:param plugin: Plugin object, under which the recipe was registered
:type plugin: GwBasePattern
"""
if plugin is not None:
... |
Execute a recipe and creates new folder and files. | def build(self, recipe, plugin=None):
"""
Execute a recipe and creates new folder and files.
:param recipe: Name of the recipe
:param plugin: Name of the plugin, to which the recipe must belong.
"""
if recipe not in self.recipes.keys():
raise RecipeMissingExc... |
Buildes the recipe and creates needed folder and files. May ask the user for some parameter inputs. | def build(self, output_dir=None, **kwargs):
"""
Buildes the recipe and creates needed folder and files.
May ask the user for some parameter inputs.
:param output_dir: Path, where the recipe shall be build. Default is the current working directory
:return: location of the install... |
Run CERMINE <https:// github. com/ CeON/ CERMINE > _ to extract metadata from \ the given PDF file to retrieve citations ( and more ) from the \ provided PDF file. This function returns the raw output of \ CERMINE call. | def cermine(pdf_file, force_api=False, override_local=None):
"""
Run `CERMINE <https://github.com/CeON/CERMINE>`_ to extract metadata from \
the given PDF file, to retrieve citations (and more) from the \
provided PDF file. This function returns the raw output of \
CERMINE ca... |
Run CERMINE <https:// github. com/ CeON/ CERMINE > _ to extract DOIs of cited \ papers from a PDF file. | def cermine_dois(pdf_file, force_api=False, override_local=None):
"""
Run `CERMINE <https://github.com/CeON/CERMINE>`_ to extract DOIs of cited \
papers from a PDF file.
.. note::
Try to use a local CERMINE JAR file, and falls back to using the API. \
JAR file is expect... |
Run Grobid <https:// github. com/ kermitt2/ grobid > _ on a given folder to \ extract references. | def grobid(pdf_folder, grobid_home=None, grobid_jar=None):
"""
Run `Grobid <https://github.com/kermitt2/grobid>`_ on a given folder to \
extract references.
.. note::
Before using this function, you have to download and build Grobid on \
your system. See \
... |
Extract DOIs of references using \ pdfextract <https:// github. com/ CrossRef/ pdfextract > _. | def pdfextract_dois(pdf_file):
"""
Extract DOIs of references using \
`pdfextract <https://github.com/CrossRef/pdfextract>`_.
.. note::
See ``libbmc.citations.pdf.pdfextract`` function as this one is just \
a wrapper around it.
See ``libbmc.citations.plaintext.g... |
high level function that can estimate where user is based on predefined setups. | def where_am_i():
"""
high level function that can estimate where user is based
on predefined setups.
"""
locations = {'Work':0, 'Home':0}
for ssid in scan_for_ssids():
#print('checking scanned_ssid ', ssid)
for l in logged_ssids:
#print('checking logged_ssid ', l)
... |
prints all attributes and returns them as a dictionary ( mainly for testing how it will all integrate ) | def dump_all(self, silent='NO'):
"""
prints all attributes and returns them as a dictionary
(mainly for testing how it will all integrate)
"""
all_params = []
all_params.append(dict(name='phone', val=self.transport))
all_params.append(dict(name='username', val=s... |
extrapolate a human readable summary of the contexts | def summarise(self):
"""
extrapolate a human readable summary of the contexts
"""
res = ''
if self.user == 'Developer':
if self.host == 'Home PC':
res += 'At Home'
else:
res += 'Away from PC'
elif self.user == 'Us... |
returns the host computer running this program | def get_host(self):
"""
returns the host computer running this program
"""
import socket
host_name = socket.gethostname()
for h in hosts:
if h['name'] == host_name:
return h['type'], h['name']
return dict(type='Unknown', name=host_nam... |
returns the username on this computer | def get_user(self):
"""
returns the username on this computer
"""
for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
user = os.environ.get(name)
if user:
break
for u in users:
if u['name'] == user:
retu... |
FUNCTION STUB - TODO The intention is to get data from the mobile in the format: gps_lat = 137. 000 gps_lng = 100. 000 moving = True | False move_dist_10_sc = 0 move_dist_2_mn = 4 move_dist_10_mn = 4 move_dist_2_hr = 4 screen_saver = True | False on_charge = True | False | def inspect_phone(self, gps_lat_long = [137.0000,100.0000], moving = False, move_dist_2_mn = 4, on_charge = True, screen_saver = False):
"""
FUNCTION STUB - TODO
The intention is to get data from the mobile in the format:
gps_lat = 137.000
gps_lng = 100.00... |
get details of CPU RAM usage of this PC | def get_host_usage(self):
"""
get details of CPU, RAM usage of this PC
"""
import psutil
process_names = [proc.name for proc in psutil.process_iter()]
cpu_pct = psutil.cpu_percent(interval=1)
mem = psutil.virtual_memory()
return str(cpu_pct), str(len(pro... |
Provide schema for shell configuration. | def schema():
"""Provide schema for shell configuration."""
return Schema({
'script': And(Or(type(' '), type(u' ')), len),
Optional('title', default=''): str,
Optional('model', default={}): {Optional(And(str, len)): object},
Optional('env', default={}): {O... |
Sets the key/ value pairs in the given dict as attributes of this result object. | def _transform_to_attrs(self, response):
"""Sets the key/value pairs in the given dict as
attributes of this result object.
"""
response_dict = self._desiarialize_response(response)
self.__dict__.update(response_dict) |
Modifies the given dict into a flat dict consisting of only key/ value pairs. | def _flatten_dict(self, dict_):
"""Modifies the given dict into a flat dict consisting of only
key/value pairs.
"""
flattened_dict = {}
for (key, value) in dict_.iteritems():
if isinstance(value, dict):
flattened_dict.update(self._flatten_dict(value))
... |
returns an object Project which matches name | def get_by_name(self, name):
""" returns an object Project which matches name """
for p in self.project_list:
if p.nme == name:
return p
return None |
handles the data sources used in projects mainly as an abstract to call the data sources in/ lib and/ dataTools | def add_source(self, name, location, schedule='Daily', op=''):
"""
handles the data sources used in projects, mainly as an
abstract to call the data sources in /lib and /dataTools
"""
if op == '':
op = name + '.log'
self.data_sources.append([name, location, s... |
run execute on all tasks IFF prior task is successful | def execute_tasks(self):
"""
run execute on all tasks IFF prior task is successful
"""
for t in self.tasks:
print('RUNNING ' + str(t.task_id) + ' = ' + t.name)
t.execute()
if t.success != '__IGNORE__RESULT__':
print(t)
p... |
create a report showing all project details | def build_report(self, op_file, tpe='md'):
"""
create a report showing all project details
"""
if tpe == 'md':
res = self.get_report_md()
elif tpe == 'rst':
res = self.get_report_rst()
elif tpe == 'html':
res = self.get_report_html()
... |
formats the project into a report in RST format | def get_report_rst(self):
"""
formats the project into a report in RST format
"""
res = ''
res += '-----------------------------------\n'
res += self.nme + '\n'
res += '-----------------------------------\n\n'
res += self.desc + '\n'
res += self.... |
formats the project into a report in MD format - WARNING - tables missing BR | def get_report_html(self):
"""
formats the project into a report in MD format - WARNING - tables missing BR
"""
res = '<h2>Project:' + self.nme + '</h2>'
res += '<p>' + self.desc + '</p>'
res += '<p>' + self.fldr + '</p>'
res += '<BR><h3>TABLES</h3>'
... |
adds parameters as key value pairs | def add_param(self, param_key, param_val):
"""
adds parameters as key value pairs
"""
self.params.append([param_key, param_val])
if param_key == '__success_test':
self.success = param_val |
executes all automatic tasks in order of task id | def execute(self):
"""
executes all automatic tasks in order of task id
"""
func_params = []
exec_str = self.func.__name__ + '('
for p in self.params:
if p[0][0:2] != '__': # ignore custom param names
exec_str += p[0] + '="' + self._force_st... |
Read all annotations from the specified file. >>> annotations = read_annotations ( path_or_file separator ) >>> colnames = annotations [ Column Name ] >>> types = annotations [ Type ] >>> annot_row = annotations [ Annot. row name ] | def read_annotations(path_or_file, separator='\t', reset=True):
"""
Read all annotations from the specified file.
>>> annotations = read_annotations(path_or_file, separator)
>>> colnames = annotations['Column Name']
>>> types = annotations['Type']
>>> annot_row = annotations['Annot. row nam... |
Helper function to extract N: and C: rows from annotations and pad their values | def annotation_rows(prefix, annotations):
"""
Helper function to extract N: and C: rows from annotations and pad their values
"""
ncol = len(annotations['Column Name'])
return {name.replace(prefix, '', 1) : values + [''] * (ncol - len(values))
for name, values in annotations.items() if n... |
Create a pd. MultiIndex using the column names and any categorical rows. Note that also non - main columns will be assigned a default category. | def create_column_index(annotations):
"""
Create a pd.MultiIndex using the column names and any categorical rows.
Note that also non-main columns will be assigned a default category ''.
"""
_column_index = OrderedDict({'Column Name' : annotations['Column Name']})
categorical_rows = annotation_ro... |
Read a Perseus - formatted matrix into a pd. DataFrame. Annotation rows will be converted into a multi - index. | def read_perseus(path_or_file, **kwargs):
"""
Read a Perseus-formatted matrix into a pd.DataFrame.
Annotation rows will be converted into a multi-index.
By monkey-patching the returned pd.DataFrame a `to_perseus`
method for exporting the pd.DataFrame is made available.
:param path_or_file: Fil... |
Save pd. DataFrame to Perseus text format. | def to_perseus(df, path_or_file, main_columns=None,
separator=separator,
convert_bool_to_category=True,
numerical_annotation_rows = set([])):
"""
Save pd.DataFrame to Perseus text format.
:param df: pd.DataFrame.
:param path_or_file: File name or file-like object.
:param mai... |
All numeric columns up - until the first non - numeric column are considered main columns.: param df: The pd. DataFrame: param index_level: Name of the index level of the column names. Default Column Name: param numeric_dtypes: Set of numpy. dtype containing all numeric types. Default int/ float.: returns: The names of... | def _infer_main_columns(df, index_level='Column Name', numeric_dtypes=_numeric_dtypes):
"""
All numeric columns up-until the first non-numeric column are considered main columns.
:param df: The pd.DataFrame
:param index_level: Name of the index level of the column names. Default 'Column Name'
:param... |
formats the entire search result in a table output | def get_page(search_text):
"""
formats the entire search result in a table output
"""
lst = search_aikif(search_text)
txt = '<table class="as-table as-table-zebra as-table-horizontal">'
for result in lst:
txt += '<TR><TD>' + result + '</TD></TR>'
txt += '</TABLE>\n\n'
return txt |
search for text - currently this looks in all folders in the root of AIKIF but that also contains binaries so will need to use the agent_filelist. py to specify the list of folders. NOTE - this needs to use indexes rather than full search each time | def search_aikif(txt, formatHTML=True):
"""
search for text - currently this looks in all folders in the
root of AIKIF but that also contains binaries so will need to
use the agent_filelist.py to specify the list of folders.
NOTE - this needs to use indexes rather than full search each time
... |
highlight the search result | def format_result(line, line_num, txt):
""" highlight the search result """
return ' ' + str(line_num) + ': ' + line.replace(txt, '<span style="background-color: #FFFF00">' + txt + '</span>') |
Modules for testing happiness of persons in worlds based on simplistic preferences. Just a toy - dont take seriously | def TEST():
"""
Modules for testing happiness of 'persons' in 'worlds'
based on simplistic preferences. Just a toy - dont take seriously
----- WORLD SUMMARY for : Mars -----
population = 0
tax_rate = 0.0
tradition = 0.9
equity = 0.0
Preferences for Rov... |
find the best world to make people happy | def solve(self, max_worlds=10000, silent=False):
"""
find the best world to make people happy
"""
self.num_worlds = 0
num_unhappy = 0
for tax_rate in range(self.tax_range[0],self.tax_range[1]):
for equity in range(self.equity_range[0],self.equity_range[1]):
... |
extended print details of happiness parameters | def show_details(self):
"""
extended print details of happiness parameters
"""
res = str(self)
res += '\nDETAILS\n'
for f in self.factors:
res += str(f)
return res |
calculates the estimated happiness of a person living in a world self. _update_pref ( self. person. prefs [ tax_min ] self. person. prefs [ tax_max ] self. world. tax_rate ) self. _update_pref ( self. person. prefs [ tradition ] self. person. prefs [ tradition ] self. world. tradition ) self. _update_pref ( self. perso... | def calculate(self):
"""
calculates the estimated happiness of a person
living in a world
self._update_pref(self.person.prefs['tax_min'], self.person.prefs['tax_max'], self.world.tax_rate)
self._update_pref(self.person.prefs['tradition'], self.person.prefs['tradition'], self.worl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.