code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
f_mounts = [m.strip("/") for m in mounts]
root = local.path("/")
ld_libs = [root / m / "lib" for m in f_mounts]
ld_libs.extend([root / m / "lib64" for m in f_mounts])
paths = [root / m / "bin" for m in f_mounts]
paths.extend([root / m / "sbin" for m in f_mounts])
paths.extend([root /... | def env(mounts) | Compute the environment of the change root for the user.
Args:
mounts: The mountpoints of the current user.
Return:
paths
ld_libs | 2.617145 | 2.506305 | 1.044224 |
return {"%s$$n%i" % (author.get_urn(), i): abbrev
for author in kb.get_authors()
for i, abbrev in enumerate(author.get_abbreviations())
if author.get_urn() is not None} | def get_abbreviations(kb) | For the sake of profiling. | 6.277184 | 5.711639 | 1.099016 |
return {"%s$$n%i" % (author.get_urn(), i): name[1]
for author in self.get_authors()
for i, name in enumerate(author.get_names())
if author.get_urn() is not None} | def author_names(self) | Returns a dictionary like this:
{
"urn:cts:greekLit:tlg0012$$n1" : "Homer"
, "urn:cts:greekLit:tlg0012$$n2" : "Omero"
, ...
} | 6.583294 | 3.742678 | 1.758979 |
search_query = % urn
# check type of the input URN
try:
assert isinstance(urn, CTS_URN)
except Exception as e:
# convert to pyCTS.CTS_URN if it's a string
urn = CTS_URN(urn)
logger.debug('Converted the input urn from string to %s'... | def get_resource_by_urn(self, urn) | Fetch the resource corresponding to the input CTS URN.
Currently supports
only HucitAuthor and HucitWork.
:param urn: the CTS URN of the resource to fetch
:return: either an instance of `HucitAuthor` or of `HucitWork` | 4.227673 | 4.005097 | 1.055573 |
query = % search_string
response = self._session.default_store.execute_sparql(query)
results = [(result['s']['value'], result['label']['value'], result['type']['value'])
for result in response["results"]["bindings"]]
r... | def search(self, search_string) | Searches for a given string through the resources' labels.
:param search_string:
:return: an instance of `HucitAuthor` or `HucitWork`. | 2.910653 | 2.930018 | 0.993391 |
Person = self._session.get_class(surf.ns.EFRBROO['F10_Person'])
return list(Person.all()) | def get_authors(self) | Returns the authors in the Knowledge Base.
:return: a list of `HucitAuthor` instances. | 57.268158 | 73.102074 | 0.7834 |
Work = self._session.get_class(surf.ns.EFRBROO['F1_Work'])
return list(Work.all()) | def get_works(self) | Return the author's works.
:return: a list of `HucitWork` instances. | 52.440098 | 74.499611 | 0.703898 |
author = self.get_resource_by_urn(urn)
names = author.get_names()
en_names = sorted([name[1] for name in names if name[0] == "en"], key=len)
try:
assert len(en_names) > 0
return en_names[0]
except Exception as e:
none_names = sorted([n... | def get_author_label(self, urn) | Get the label corresponding to the author identified by the CTS URN.
try to get an lang=en label (if multiple labels in this lang pick the shortest)
try to get a lang=la label (if multiple labels in this lang exist pick the shortest)
try to get a lang=None label (if multiple labels in this lang... | 2.167835 | 1.978138 | 1.095897 |
statistics = {
"number_authors": 0,
"number_author_names": 0,
"number_author_abbreviations": 0,
"number_works": 0,
"number_work_titles": 0,
"number_title_abbreviations": 0,
"number_opus_maximum":0,
}
for... | def get_statistics(self) | Gather basic stats about the Knowledge Base and its contents.
:return: a dictionary | 2.245089 | 2.365348 | 0.949158 |
author = self.get_resource_by_urn(author_cts_urn)
assert author is not None
works = author.get_works()
if len(works) > 1:
for work in works:
if work.is_opus_maximum():
return work
elif len(works) == 1:
return w... | def get_opus_maximum_of(self, author_cts_urn) | Return the author's opux maximum (None otherwise).
Given the CTS URN of an author, this method returns its opus maximum.
If not available returns None.
:param author_cts_urn: the author's CTS URN.
:return: an instance of `surfext.HucitWork` or None | 2.744115 | 2.750443 | 0.997699 |
return json.dumps({
"statistics": self.get_statistics()
, "authors": [json.loads(author.to_json()) for author in self.get_authors()]
}, indent=2) | def to_json(self) | Serialises the content of the KnowledgeBase as JSON.
:return: TODO | 5.133185 | 5.816263 | 0.882557 |
@wraps(func)
def _wrapper(*args, **kwargs):
now = datetime.datetime.now()
with Timer() as timer:
data = func(*args, **kwargs)
if isinstance(data, (SEQUENCES, types.GeneratorType)):
report = dict(children=list(map(str, data)))
elif isinsta... | def write_yaml_report(func) | Decorator used in campaign node post-processing | 3.401645 | 3.4415 | 0.988419 |
@wraps(func)
def _wrap(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except Exception:
self.logger.exception('While executing benchmark')
if not (self.catch_child_exception or False):
... | def call_decorator(cls, func) | class function that MUST be specified as decorator
to the `__call__` method overriden by sub-classes. | 4.472528 | 4.232778 | 1.056641 |
builder = self.child_builder
for child in self._children:
with pushd(str(child)):
yield child, builder(child) | def traverse(self) | Enumerate children and build associated objects | 10.179432 | 8.468078 | 1.202095 |
d_values = []
for i in range(self.n_pads_l):
d_values.append(self.pad_position_l(i))
d_values = np.array(d_values) - self.length / 2
area_d_sqrd = sum(self.pad_area * d_values ** 2) * self.n_pads_w
i_second = self.pad_i_ww * self.n_pads
return area_d_... | def i_ww(self) | Second moment of inertia around the width axis.
:return: | 5.327318 | 4.637148 | 1.148835 |
d_values = []
for i in range(self.n_pads_w):
d_values.append(self.pad_position_w(i))
d_values = np.array(d_values) - self.width / 2
area_d_sqrd = sum(self.pad_area * d_values ** 2) * self.n_pads_l
i_second = self.pad_i_ll * self.n_pads
return area_d_s... | def i_ll(self) | Second moment of inertia around the length axis.
:return: | 5.367748 | 4.666766 | 1.150207 |
if i >= self.n_pads_l:
raise ModelError("pad index out-of-bounds")
return (self.length - self.pad_length) / (self.n_pads_l - 1) * i + self.pad_length / 2 | def pad_position_l(self, i) | Determines the position of the ith pad in the length direction.
Assumes equally spaced pads.
:param i: ith number of pad in length direction (0-indexed)
:return: | 4.102569 | 3.576483 | 1.147096 |
if i >= self.n_pads_w:
raise ModelError("pad index out-of-bounds")
return (self.width - self.pad_width) / (self.n_pads_w - 1) * i + self.pad_width / 2 | def pad_position_w(self, i) | Determines the position of the ith pad in the width direction.
Assumes equally spaced pads.
:param i: ith number of pad in width direction (0-indexed)
:return: | 3.883834 | 3.504655 | 1.108193 |
'''
Adds paths to the given batch object. They are all added as
GL_TRIANGLES, so the batch will aggregate them all into a single OpenGL
primitive.
'''
for name in self.paths:
svg_path = self.paths[name]
svg_path.add_to_batch(batch) | def add_to_batch(self, batch) | Adds paths to the given batch object. They are all added as
GL_TRIANGLES, so the batch will aggregate them all into a single OpenGL
primitive. | 8.518602 | 2.41909 | 3.521408 |
return [int(c) if c.isdigit() else c for c in _RE_INT.split(s)] | def alphanum_key(s) | Turn a string into a list of string and number chunks.
"z23a" -> ["z", 23, "a"] | 6.810427 | 5.738331 | 1.186831 |
if CFG["plugins"]["autoload"]:
experiment_plugins = CFG["plugins"]["experiments"].value
for exp_plugin in experiment_plugins:
try:
importlib.import_module(exp_plugin)
except ImportError as import_error:
LOG.error("Could not find '%s'", exp... | def discover() | Import all experiments listed in PLUGINS_EXPERIMENTS.
Tests:
>>> from benchbuild.settings import CFG
>>> from benchbuild.experiments import discover
>>> import logging as lg
>>> import sys
>>> l = lg.getLogger('benchbuild')
>>> lg.getLogger('benchbuild').setLevel(lg.... | 4.376189 | 3.422437 | 1.278676 |
grouped_by = {}
if not projects:
print(
"Your selection didn't include any projects for this experiment.")
return
for name in projects:
prj = projects[name]
if prj.GROUP not in grouped_by:
grouped_by[prj.GROUP] = []
grouped_by[prj.GROUP... | def print_projects(projects=None) | Print a list of projects registered for that experiment.
Args:
exp: The experiment to print all projects for. | 2.912949 | 2.957626 | 0.984894 |
if cache == "redis":
nautilus_cache = RedisCache(redis)
cache_type = "redis"
elif cache == "filesystem":
nautilus_cache = FileSystemCache(cache_path)
cache_type = "simple"
else:
nautilus_cache = NullCache()
cache_type = "simple"
app = Flask("Nautilu... | def _commandline(repositories,
port=8000, host="127.0.0.1", debug=False,
cache=None, cache_path="./cache", redis=None) | Run a CTS API from command line.
.. warning:: This function should not be used in the production context
:param repositories:
:param port:
:param ip:
:param debug:
:param cache:
:param cache_path:
:return: | 3.976311 | 3.888312 | 1.022632 |
conv = {
'&': r'\&',
'%': r'\%',
'$': r'\$',
'#': r'\#',
'_': r'\_',
'{': r'\{',
'}': r'\}',
'~': r'\textasciitilde{}',
'^': r'\^{}',
'\\': r'\textbackslash{}',
'<': r'\textless ',
'>': r'\textgreater ',
}
r... | def tex_escape(text) | Escape string for LaTeX usage
:param text: a plain text message
:return: the message escaped to appear correctly in LaTeX | 1.522098 | 1.576201 | 0.965675 |
jinja_environment.filters['texscape'] = tex_escape
template = template or DEFAULT_TEMPLATE
ostr = ostr or sys.stdout
jinja_template = jinja_environment.get_template(template)
jinja_template.stream(**kwargs).dump(ostr) | def render(template=None, ostr=None, **kwargs) | Generate report from a campaign
:param template: Jinja template to use, ``DEFAULT_TEMPLATE`` is used
if not specified
:param ostr: output file or filename. Default is standard output | 3.114853 | 3.585202 | 0.868808 |
'''
Return two-ple containing:
- A `pymunk.Space` instance.
- A `pandas.Series` mapping each `pymunk.Body` object in the `Space` to a
shape index.
The `Body` to shape index mapping makes it possible to, for example, look
up the index of the convex shape associated with a `Body` return... | def get_shapes_pymunk_space(df_convex_shapes, shape_i_columns) | Return two-ple containing:
- A `pymunk.Space` instance.
- A `pandas.Series` mapping each `pymunk.Body` object in the `Space` to a
shape index.
The `Body` to shape index mapping makes it possible to, for example, look
up the index of the convex shape associated with a `Body` returned by a
... | 3.81834 | 2.496604 | 1.529414 |
data = json.load(open(ffp))
return ecp_dict_to_objects(data, custom, verbose=verbose) | def load_json(ffp, custom=None, verbose=0) | Given a json file it creates a dictionary of sfsi objects
:param ffp: str, Full file path to json file
:param custom: dict, used to load custom objects, {model type: custom object}
:param verbose: int, console output
:return: dict | 6.159756 | 8.984648 | 0.685587 |
data = json.loads(p_str)
if meta:
md = {}
for item in data:
if item != "models":
md[item] = data[item]
return ecp_dict_to_objects(data, custom, verbose=verbose), md
else:
return ecp_dict_to_objects(data, custom, verbose=verbose) | def loads_json(p_str, custom=None, meta=False, verbose=0) | Given a json string it creates a dictionary of sfsi objects
:param ffp: str, Full file path to json file
:param custom: dict, used to load custom objects, {model type: custom object}
:param meta: bool, if true then also return all ecp meta data in separate dict
:param verbose: int, console output
:... | 3.056999 | 3.00052 | 1.018823 |
objs, meta_data = load_json_and_meta(in_ffp)
ecp_output = Output()
for m_type in objs:
for instance in objs[m_type]:
ecp_output.add_to_dict(objs[m_type][instance])
ecp_output.name = meta_data["name"]
ecp_output.units = meta_data["units"]
ecp_output.comments = meta_data["... | def migrate_ecp(in_ffp, out_ffp) | Migrates and ECP file to the current version of sfsimodels | 3.238459 | 2.894658 | 1.118771 |
if an_object.id is None:
raise ModelError("id must be set on object before adding to output.")
if hasattr(an_object, "base_type"):
mtype = an_object.base_type
elif hasattr(an_object, "type"):
if an_object.type in standard_types:
mtype ... | def add_to_dict(self, an_object, extras=None) | Convert models to json serialisable output
:param an_object: An instance of a model object
:param extras: A dictionary of extra variables that should be
:return: | 2.758925 | 2.762184 | 0.99882 |
if mtype not in self.unordered_models:
self.unordered_models[mtype] = OrderedDict()
self.unordered_models[mtype][m_id] = serialisable_dict | def add_to_output(self, mtype, m_id, serialisable_dict) | Can add additional objects or dictionaries to output file that don't conform to standard objects.
:param mtype:
:param m_id:
:param serialisable_dict:
:return: | 2.535983 | 3.093466 | 0.819787 |
models_dict = OrderedDict()
collected = []
for item in standard_types:
if item in self.unordered_models:
new_dict, replacement_dict = unhash_dict(self.unordered_models[item])
models_dict[item] = new_dict
collected.append(item)
... | def models(self) | Unhashed | 3.247698 | 2.994362 | 1.084604 |
# cpuset
# cpuset may restrict the number of *available* processors
try:
match = re.search(r'(?m)^Cpus_allowed:\s*(.*)$',
open('/proc/self/status').read())
if match:
res = bin(int(match.group(1).replace(',', ''), 16)).count('1')
if res ... | def available_cpu_count() -> int | Get the number of available CPUs.
Number of available virtual or physical CPUs on this system, i.e.
user/real as output by time(1) when called with an optimally scaling
userspace-only program.
Returns:
Number of avaialable CPUs. | 2.392318 | 2.288468 | 1.04538 |
escape_list = [char for char in raw_str if char in ['!', '{', '[']]
if len(escape_list) == 0:
return raw_str
str_quotes = '"'
i_str_quotes = "'"
if str_quotes in raw_str and str_quotes not in raw_str[1:-1]:
return raw_str
if str_quotes in raw_str[1:-1]:
raw_str = i... | def escape_yaml(raw_str: str) -> str | Shell-Escape a yaml input string.
Args:
raw_str: The unescaped string. | 2.990606 | 3.059359 | 0.977527 |
stream = yaml.io.StringIO()
dumper = ConfigDumper(stream, default_flow_style=True, width=sys.maxsize)
val = None
try:
dumper.open()
dumper.represent(value)
val = stream.getvalue().strip()
dumper.close()
finally:
dumper.dispose()
return val | def to_yaml(value) -> str | Convert a given value to a YAML string. | 4.233831 | 3.786689 | 1.118083 |
val = to_yaml(value)
ret_val = "%s=%s" % (env_var, escape_yaml(val))
return ret_val | def to_env_var(env_var: str, value) -> str | Create an environment variable from a name and a value.
This generates a shell-compatible representation of an
environment variable that is assigned a YAML representation of
a value.
Args:
env_var (str): Name of the environment variable.
value (Any): A value we convert from. | 6.550232 | 6.808825 | 0.962021 |
if defaults is None:
defaults = [".benchbuild.yml", ".benchbuild.yaml"]
def walk_rec(cur_path, root):
cur_path = local.path(root) / test_file
if cur_path.exists():
return cur_path
new_root = local.path(root) / os.pardir
return walk_rec(cur_path, new_roo... | def find_config(test_file=None, defaults=None, root=os.curdir) | Find the path to the default config file.
We look at :root: for the :default: config file. If we can't find it
there we start looking at the parent directory recursively until we
find a file named :default: and return the absolute path to it.
If we can't find anything, we return None.
Args:
... | 2.678094 | 2.934813 | 0.912526 |
if env_var_name is None:
env_var_name = "BB_CONFIG_FILE"
config_path = os.getenv(env_var_name, None)
if not config_path:
config_path = find_config(defaults=config_filenames)
if config_path:
cfg.load(config_path)
cfg["config_file"] = os.path.abspath(config_path)
... | def setup_config(cfg, config_filenames=None, env_var_name=None) | This will initialize the given configuration object.
The following resources are available in the same order:
1) Default settings.
2) Config file.
3) Environment variables.
WARNING: Environment variables do _not_ take precedence over the config
file right now. (init_from_e... | 2.680517 | 3.000293 | 0.893419 |
db_node = cfg["db"]
old_db_elems = ["host", "name", "port", "pass", "user", "dialect"]
has_old_db_elems = [x in db_node for x in old_db_elems]
if any(has_old_db_elems):
print("Old database configuration found. "
"Converting to new connect_string. "
"This will *n... | def upgrade(cfg) | Provide forward migration for configuration files. | 2.962476 | 2.902955 | 1.020504 |
value = loader.construct_scalar(node)
return uuid.UUID(value) | def uuid_constructor(loader, node) | Construct a uuid.UUID object form a scalar YAML node.
Tests:
>>> yaml.add_constructor("!uuid", uuid_constructor, Loader=yaml.SafeLoader)
>>> yaml.safe_load("{'test': !uuid 'cc3702ca-699a-4aa6-8226-4c938f294d9b'}")
{'test': UUID('cc3702ca-699a-4aa6-8226-4c938f294d9b')} | 4.351088 | 6.55521 | 0.66376 |
uuid_regex = r'^\b[a-f0-9]{8}-\b[a-f0-9]{4}-\b[a-f0-9]{4}-\b[a-f0-9]{4}-\b[a-f0-9]{12}$'
pattern = re.compile(uuid_regex)
yaml.add_implicit_resolver('!uuid', pattern, Loader=Loader, Dumper=Dumper) | def uuid_add_implicit_resolver(Loader=ConfigLoader, Dumper=ConfigDumper) | Attach an implicit pattern resolver for UUID objects.
Tests:
>>> class TestDumper(yaml.SafeDumper): pass
>>> class TestLoader(yaml.SafeLoader): pass
>>> TUUID = 'cc3702ca-699a-4aa6-8226-4c938f294d9b'
>>> IN = {'test': uuid.UUID(TUUID)}
>>> OUT = '{test: cc3702ca-699a-4aa6-82... | 1.86509 | 2.266663 | 0.822835 |
selfcopy = copy.deepcopy(self)
selfcopy.filter_exports()
with open(config_file, 'w') as outf:
yaml.dump(
selfcopy.node,
outf,
width=80,
indent=4,
default_flow_style=False,
Dumpe... | def store(self, config_file) | Store the configuration dictionary to a file. | 4.461769 | 4.167869 | 1.070516 |
def load_rec(inode, config):
for k in config:
if isinstance(config[k], dict) and \
k not in ['value', 'default']:
if k in inode:
load_rec(inode[k], config[k])
else:
... | def load(self, _from) | Load the configuration dictionary from file. | 4.872578 | 4.361619 | 1.117149 |
if 'default' in self.node:
env_var = self.__to_env_var__().upper()
if self.has_value():
env_val = self.node['value']
else:
env_val = self.node['default']
env_val = os.getenv(env_var, to_yaml(env_val))
try:
... | def init_from_env(self) | Initialize this node from environment.
If we're a leaf node, i.e., a node containing a dictionary that
consist of a 'default' key, compute our env variable and initialize
our value from the environment.
Otherwise, init our children. | 3.440943 | 2.917008 | 1.179614 |
def validate(node_value):
if hasattr(node_value, 'validate'):
node_value.validate()
return node_value
if 'value' in self.node:
return validate(self.node['value'])
return self | def value(self) | Return the node value, if we're a leaf node.
Examples:
>>> c = Configuration("test")
>>> c['x'] = { "y" : { "value" : None }, "z" : { "value" : 2 }}
>>> c['x']['y'].value == None
True
>>> c['x']['z'].value
2
>>> c['x'].value
... | 4.882209 | 3.651272 | 1.337126 |
entries = {}
if self.has_value():
return {self.__to_env_var__(): self.node['value']}
if self.has_default():
return {self.__to_env_var__(): self.node['default']}
for k in self.node:
entries.update(self[k].to_env_dict())
return entries | def to_env_dict(self) | Convert configuration object to a flat dictionary. | 4.14528 | 3.812928 | 1.087165 |
new_record = dict()
for k, v in record.items():
key = key_map[k] if k in key_map else k
new_record[key] = v
return new_record | def rename_keys(record: Mapping, key_map: Mapping) -> dict | New record with same keys or renamed keys if key found in key_map. | 2.282794 | 2.118969 | 1.077314 |
return {key_map[k]: v for k, v in record.items() if k in key_map} | def replace_keys(record: Mapping, key_map: Mapping) -> dict | New record with renamed keys including keys only found in key_map. | 3.06408 | 2.192092 | 1.397788 |
record = dict()
for field in field_names:
record[field] = data.get(field, None)
return record | def inject_nulls(data: Mapping, field_names) -> dict | Insert None as value for missing fields. | 3.991465 | 3.325108 | 1.200402 |
line = fstream.readline().strip()
fragments = line.split(",")
fragments = [x for x in fragments if x is not None]
partition = dict()
if not len(fragments) >= 3:
return None
partition["struct"] = fragments[0]
partition["info"] = fragments[1]
partition["num_lines"] = fragment... | def read_struct(fstream) | Read a likwid struct from the text stream.
Args:
fstream: Likwid's filestream.
Returns (dict(str: str)):
A dict containing all likwid's struct info as key/value pairs. | 3.609568 | 3.882193 | 0.929775 |
pos = fstream.tell()
line = fstream.readline().strip()
fragments = line.split(",")
fragments = [x for x in fragments if x is not None]
partition = dict()
if not len(fragments) >= 4:
return None
partition["table"] = fragments[0]
partition["group"] = fragments[1]
partitio... | def read_table(fstream) | Read a likwid table info from the text stream.
Args:
fstream: Likwid's filestream.
Returns (dict(str: str)):
A dict containing likwid's table info as key/value pairs. | 3.277091 | 3.417759 | 0.958842 |
struct = read_struct(fstream)
while struct is not None:
yield struct
struct = read_struct(fstream) | def read_structs(fstream) | Read all structs from likwid's file stream.
Args:
fstream: Likwid's output file stream.
Returns:
A generator that can be used to iterate over all structs in the
fstream. | 2.608725 | 4.090096 | 0.637815 |
table = read_table(fstream)
while table is not None:
yield table
table = read_table(fstream) | def read_tables(fstream) | Read all tables from likwid's file stream.
Args:
fstream: Likwid's output file stream.
Returns:
A generator that can be used to iterate over all tables in the fstream. | 2.876339 | 3.637419 | 0.790764 |
measurements = []
clean_core_info = [x for x in core_info if x]
cores = len(clean_core_info)
for k in data:
if k not in ["1", "Region Info", "Event", "Metric", "CPU clock"]:
slot = data[k]
for i in range(cores):
core = core_info[i]
idx... | def get_measurements(region, core_info, data, extra_offset=0) | Get the complete measurement info from likwid's region info.
Args:
region: The region we took a measurement in.
core_info: The core information.
data: The raw data.
extra_offset (int): default = 0
Returns (list((region, metric, core, value))):
A list of measurement tupl... | 4.922132 | 5.06485 | 0.971822 |
measurements = []
with open(infile, 'r') as in_file:
read_struct(in_file)
for region_struct in read_structs(in_file):
region = region_struct["1"][1]
core_info = region_struct["Region Info"]
measurements += \
get_measurements(region, core_i... | def perfcounters(infile) | Get a complete list of all measurements.
Args:
infile: The filestream containing all likwid output.
Returns:
A list of all measurements extracted from likwid's file stream. | 3.567583 | 3.603907 | 0.989921 |
level = logging.WARNING
if verbose == 1:
level = logging.INFO
elif verbose > 1:
level = logging.DEBUG
if logfile:
logging.basicConfig(filename=logfile, level=level, format=LOGGING_FORMAT)
else:
logging.basicConfig(level=level, format=LOGGING_FORMAT) | def setup_logger(verbose, logfile) | Prepare root logger
:param verbose: integer greater than 0 to indicate verbosity level | 1.719553 | 2.031961 | 0.846253 |
arguments = docopt(doc, version='hpcbench ' + __version__, **kwargs)
setup_logger(arguments['-v'], arguments['--log'])
load_components()
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('PS')
return arguments | def cli_common(doc, **kwargs) | Program initialization for all provided executables | 6.140887 | 5.2919 | 1.160431 |
'''
Parameters
----------
svg_path_d : str
``"d"`` attribute of SVG ``path`` element.
Returns
-------
list
List of coordinates of points found in SVG path.
Each point is represented by a dictionary with keys ``x`` and ``y``.
'''
# TODO Add support for relati... | def shape_path_points(svg_path_d) | Parameters
----------
svg_path_d : str
``"d"`` attribute of SVG ``path`` element.
Returns
-------
list
List of coordinates of points found in SVG path.
Each point is represented by a dictionary with keys ``x`` and ``y``. | 3.750698 | 3.290168 | 1.139972 |
'''
Construct a data frame with one row per vertex for all shapes (e.g.,
``svg:path``, ``svg:polygon``) in :data:`svg_source``.
Arguments
---------
svg_source : str or file-like
A file path, URI, or file-like object.
xpath : str, optional
XPath path expression to select shap... | def svg_polygons_to_df(svg_source, xpath='//svg:polygon',
namespaces=INKSCAPE_NSMAP) | Construct a data frame with one row per vertex for all shapes (e.g.,
``svg:path``, ``svg:polygon``) in :data:`svg_source``.
Arguments
---------
svg_source : str or file-like
A file path, URI, or file-like object.
xpath : str, optional
XPath path expression to select shape nodes.
... | 3.352659 | 1.301936 | 2.575134 |
'''
Compute the center point of each polygon shape, and the offset of each
vertex to the corresponding polygon center point.
Parameters
----------
df_shapes : pandas.DataFrame
Table of polygon shape vertices (one row per vertex).
Must have at least the following columns:
... | def compute_shape_centers(df_shapes, shape_i_column, inplace=False) | Compute the center point of each polygon shape, and the offset of each
vertex to the corresponding polygon center point.
Parameters
----------
df_shapes : pandas.DataFrame
Table of polygon shape vertices (one row per vertex).
Must have at least the following columns:
- ``verte... | 3.302804 | 1.642182 | 2.011229 |
'''
Translate points such that bounding box is anchored at (0, 0) and scale
``x`` and ``y`` columns of input frame by specified :data:`scale`.
Parameters
----------
df_points : pandas.DataFrame
Table of ``x``/``y`` point positions.
Must have at least the following columns:
... | def scale_points(df_points, scale=INKSCAPE_PPmm.magnitude, inplace=False) | Translate points such that bounding box is anchored at (0, 0) and scale
``x`` and ``y`` columns of input frame by specified :data:`scale`.
Parameters
----------
df_points : pandas.DataFrame
Table of ``x``/``y`` point positions.
Must have at least the following columns:
- ``x``... | 3.910925 | 1.460763 | 2.677317 |
'''
Return scale factor (scalar float) to fit `a_shape` into `b_shape` while
maintaining aspect ratio.
Arguments
---------
a_shape, b_shape : pandas.Series
Input shapes containing numeric `width` and `height` values.
Returns
-------
float
Scale factor to fit :data:`... | def scale_to_fit_a_in_b(a_shape, b_shape) | Return scale factor (scalar float) to fit `a_shape` into `b_shape` while
maintaining aspect ratio.
Arguments
---------
a_shape, b_shape : pandas.Series
Input shapes containing numeric `width` and `height` values.
Returns
-------
float
Scale factor to fit :data:`a_shape` int... | 2.476867 | 1.631831 | 1.517845 |
'''
Return data frame with ``x``, ``y`` columns scaled to fit points from
:data:`df_points` to fill :data:`bounding_box` while maintaining aspect
ratio.
Arguments
---------
df_points : pandas.DataFrame
A frame with at least the columns ``x`` and ``y``, containing one row
per... | def fit_points_in_bounding_box(df_points, bounding_box, padding_fraction=0) | Return data frame with ``x``, ``y`` columns scaled to fit points from
:data:`df_points` to fill :data:`bounding_box` while maintaining aspect
ratio.
Arguments
---------
df_points : pandas.DataFrame
A frame with at least the columns ``x`` and ``y``, containing one row
per point.
... | 3.62182 | 1.521127 | 2.381012 |
'''
Return offset and scale factor to scale ``x``, ``y`` columns of
:data:`df_points` to fill :data:`bounding_box` while maintaining aspect
ratio.
Arguments
---------
df_points : pandas.DataFrame
A frame with at least the columns ``x`` and ``y``, containing one row
per point... | def fit_points_in_bounding_box_params(df_points, bounding_box,
padding_fraction=0) | Return offset and scale factor to scale ``x``, ``y`` columns of
:data:`df_points` to fill :data:`bounding_box` while maintaining aspect
ratio.
Arguments
---------
df_points : pandas.DataFrame
A frame with at least the columns ``x`` and ``y``, containing one row
per point.
boundi... | 3.758142 | 1.75022 | 2.14724 |
'''
Remove layer(s) from SVG document.
Arguments
---------
svg_source : str or file-like
A file path, URI, or file-like object.
layer_name : str or list
Layer name or list of layer names to remove from SVG document.
Returns
-------
StringIO.StringIO
File-lik... | def remove_layer(svg_source, layer_name) | Remove layer(s) from SVG document.
Arguments
---------
svg_source : str or file-like
A file path, URI, or file-like object.
layer_name : str or list
Layer name or list of layer names to remove from SVG document.
Returns
-------
StringIO.StringIO
File-like object con... | 2.817894 | 2.186768 | 1.288611 |
def _load_eggs():
distributions, errors = working_set.find_plugins(Environment())
for dist in distributions:
# pylint: disable=unsupported-membership-test
if dist not in working_set:
LOGGER.debug('Adding plugin %s from %s', dist, dist.location)
... | def load_eggs(entry_point_name) | Loader that loads any eggs in `sys.path`. | 2.604914 | 2.513469 | 1.036382 |
for refsDecl in self.graph.objects(self.asNode(), RDF_NAMESPACES.TEI.replacementPattern):
return str(refsDecl) | def refsDecl(self) | ResfDecl expression of the citation scheme
:rtype: str
:Example: /tei:TEI/tei:text/tei:body/tei:div//tei:l[@n='$1'] | 27.634148 | 21.60898 | 1.278827 |
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format("file", value)
self.__file = value | def file(self, value) | Setter for **self.__file** attribute.
:param value: Attribute value.
:type value: unicode | 6.086665 | 4.295906 | 1.416852 |
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"directory", value)
assert os.path.exists(value), "'{0}' attribute: '{1}' directory doesn't exists!".format("directory", value)
self.__directory ... | def directory(self, value) | Setter for **self.__directory** attribute.
:param value: Attribute value.
:type value: unicode | 3.656242 | 2.950618 | 1.239145 |
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"attribute", value)
self.__attribute = value | def attribute(self, value) | Setter for **self.__attribute** attribute.
:param value: Attribute value.
:type value: unicode | 5.912099 | 4.811778 | 1.228673 |
if value is not None:
assert type(value) in (tuple, list), "'{0}' attribute: '{1}' type is not 'tuple' or 'list'!".format(
"require", value)
self.__require = value | def require(self, value) | Setter for **self.__require** attribute.
:param value: Attribute value.
:type value: tuple or list | 4.902532 | 4.065665 | 1.205838 |
if value is not None:
assert type(value) is type(sys), "'{0}' attribute: '{1}' type is not 'module'!".format("module", value)
self.__module = value | def module(self, value) | Setter for **self.__module** attribute.
:param value: Attribute value.
:type value: ModuleType | 6.828869 | 5.571179 | 1.225749 |
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"category", value)
self.__category = value | def category(self, value) | Setter for **self.__category** attribute.
:param value: Attribute value.
:type value: unicode | 6.091074 | 4.335799 | 1.404833 |
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"title", value)
self.__title = value | def title(self, value) | Setter for **self.__title** attribute.
:param value: Attribute value.
:type value: unicode | 5.924175 | 4.334468 | 1.36676 |
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"package", value)
self.__package = value | def package(self, value) | Setter for **self.__package** attribute.
:param value: Attribute value.
:type value: unicode | 6.163321 | 4.409224 | 1.397825 |
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"version", value)
self.__version = value | def version(self, value) | Setter for **self.__version** attribute.
:param value: Attribute value.
:type value: unicode | 6.177695 | 4.424939 | 1.396109 |
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"author", value)
self.__author = value | def author(self, value) | Setter for **self.__author** attribute.
:param value: Attribute value.
:type value: unicode | 6.223348 | 4.43175 | 1.404264 |
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"email", value)
self.__email = value | def email(self, value) | Setter for **self.__email** attribute.
:param value: Attribute value.
:type value: unicode | 6.025891 | 4.363871 | 1.380859 |
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"url", value)
self.__url = value | def url(self, value) | Setter for **self.__url** attribute.
:param value: Attribute value.
:type value: unicode | 5.969244 | 4.377594 | 1.36359 |
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"description", value)
self.__description = value | def description(self, value) | Setter for **self.__description** attribute.
:param value: Attribute value.
:type value: unicode | 5.909939 | 4.283116 | 1.379822 |
LOGGER.debug("> Building '{0}' profile.".format(self.__file))
sections_file_parser = SectionsFileParser(self.__file)
sections_file_parser.parse()
if sections_file_parser.sections:
fileStructureParsingError = lambda attribute: foundations.exceptions.FileStructurePa... | def initializeProfile(self) | Initializes the Component Profile.
:return: Method success.
:rtype: bool | 2.231209 | 2.211539 | 1.008894 |
if value is not None:
assert type(value) in (tuple, list), "'{0}' attribute: '{1}' type is not 'tuple' or 'list'!".format(
"paths", value)
for path in value:
assert type(path) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
... | def paths(self, value) | Setter for **self.__paths** attribute.
:param value: Attribute value.
:type value: tuple or list | 2.581403 | 2.389135 | 1.080476 |
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"extension", value)
self.__extension = value | def extension(self, value) | Setter for **self.__extension** attribute.
:param value: Attribute value.
:type value: unicode | 6.094389 | 4.372715 | 1.393731 |
if value is not None:
assert type(value) is dict, "'{0}' attribute: '{1}' type is not 'dict'!".format("categories", value)
for key in value:
assert type(key) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"categories", ke... | def categories(self, value) | Setter for **self.__categories** attribute.
:param value: Attribute value.
:type value: dict | 3.081976 | 2.756159 | 1.118214 |
component = foundations.strings.get_splitext_basename(path)
LOGGER.debug("> Current Component: '{0}'.".format(component))
profile = Profile(file=path)
if profile.initializeProfile():
if os.path.isfile(os.path.join(profile.directory, profile.package) + ".py") or \
... | def register_component(self, path) | Registers a Component using given path.
Usage::
>>> manager = Manager()
>>> manager.register_component("tests_component_a.rc")
True
>>> manager.components
{u'core.tests_component_a': <manager.components_manager.Profile object at 0x11c9eb0>}
... | 4.877853 | 4.556952 | 1.07042 |
unregistered_components = []
for path in self.paths:
for file in foundations.walkers.files_walker(path, ("\.{0}$".format(self.__extension),), ("\._",)):
if not self.register_component(file):
unregistered_components.append(file)
if not un... | def register_components(self) | Registers the Components.
Usage::
>>> manager = Manager(("./manager/tests/tests_manager/resources/components/core",))
>>> manager.register_components()
True
>>> manager.components.keys()
[u'core.tests_component_a', u'core.tests_component_b']
... | 6.233484 | 5.588331 | 1.115447 |
profile = self.__components[component]
callback and callback(profile)
LOGGER.debug("> Current Component: '{0}'.".format(component))
if os.path.isfile(os.path.join(profile.directory, profile.package) + ".py") or \
os.path.isdir(os.path.join(profile.directory, p... | def instantiate_component(self, component, callback=None) | Instantiates given Component.
Usage::
>>> manager = Manager()
>>> manager.register_component("tests_component_a.rc")
True
>>> manager.instantiate_component("core.tests_component_a")
True
>>> manager.get_interface("core.tests_component_a")... | 3.89268 | 3.831083 | 1.016078 |
uninstantiated_components = [component
for component in self.list_components()
if not self.instantiate_component(component, callback)]
if not uninstantiated_components:
return True
else:
r... | def instantiate_components(self, callback=None) | Instantiates the Components.
Usage::
>>> manager = Manager((tests_manager,))
>>> manager.register_components()
True
>>> manager.instantiate_components()
True
>>> manager.get_interface("core.tests_component_a")
<tests_component... | 4.202091 | 4.205762 | 0.999127 |
dependents = list(reversed(self.list_dependents(component)))
dependents.append(component)
for dependent in dependents:
profile = self.__components[dependent]
module = __import__(profile.package)
reload(module)
object = profile.attribute ... | def reload_component(self, component) | Reload given Component module.
Usage::
>>> manager = Manager()
>>> manager.register_component("tests_component_a.rc")
True
>>> manager.instantiate_component("core.tests_component_a")
True
>>> manager.get_interface("core.tests_component_a"... | 4.847605 | 4.620408 | 1.049173 |
if dependency_order:
return list(itertools.chain.from_iterable([sorted(list(batch)) for batch in
foundations.common.dependency_resolver(
dict((key, value.require) for (key, val... | def list_components(self, dependency_order=True) | Lists the Components by dependency resolving.
Usage::
>>> manager = Manager(("./manager/tests/tests_manager/resources/components/core",))
>>> manager.register_components()
True
>>> manager.list_components()
[u'core.tests_component_a', u'core.tests_co... | 6.570056 | 7.348072 | 0.89412 |
dependents = set() if dependents is None else dependents
for name, profile in self:
if not component in profile.require:
continue
dependents.add(name)
self.list_dependents(name, dependents)
return sorted(list(dependents), key=(self.... | def list_dependents(self, component, dependents=None) | Lists given Component dependents Components.
Usage::
>>> manager = Manager(("./manager/tests/tests_manager/resources/components/core",))
>>> manager.register_components()
True
>>> manager.list_dependents("core.tests_component_a")
[u'core.tests_compon... | 4.645314 | 5.695751 | 0.815575 |
filtered_components = []
for component, profile in self:
if category:
if profile.category != category:
continue
if re.search(pattern, component):
filtered_components.append(component)
return filtered_component... | def filter_components(self, pattern, category=None) | Filters the Components using given regex pattern.
Usage::
>>> manager = Manager(("./manager/tests/tests_manager/resources/components/core",))
>>> manager.register_components()
True
>>> manager.filter_components("\w+A$")
[u'core.tests_component_a']
... | 3.065787 | 4.143128 | 0.739969 |
components = self.filter_components(r"^{0}$".format(component))
if components != []:
return self.__components[foundations.common.get_first_item(components)] | def get_profile(self, component) | Gets given Component profile.
Usage::
>>> manager = Manager()
>>> manager.register_component("tests_component_a.rc")
True
>>> manager.get_profile("core.tests_component_a")
<manager.components_manager.Profile object at 0x10258ef10>
:param com... | 11.939136 | 14.085228 | 0.847635 |
profile = self.get_profile(component)
if profile:
return profile.interface | def get_interface(self, component) | Gets given Component interface.
Usage::
>>> manager = Manager()
>>> manager.register_component("tests_component_a.rc")
True
>>> manager.get_interface("core.tests_component_a")
<tests_component_a.TestsComponentA object at 0x17b0d70>
:param co... | 6.342823 | 9.795142 | 0.647548 |
search = re.search(r"(?P<category>\w+)\.(?P<name>\w+)", component)
if search:
name = "{0}{1}{2}".format(
search.group("category"), search.group("name")[0].upper(), search.group("name")[1:])
LOGGER.debug("> Component name: '{0}' to attribute name Active_Q... | def get_component_attribute_name(component) | Gets given Component attribute name.
Usage::
>>> Manager.get_component_attribute_name("factory.components_manager_ui")
u'factoryComponentsManagerUi'
:param component: Component to get the attribute name.
:type component: unicode
:return: Component attribute nam... | 4.954662 | 4.765091 | 1.039783 |
para = ""
property_list = []
if olist == 'inputs':
property_list = obj.inputs
elif olist == 'all':
for item in obj.__dict__:
if "_" != item[0]:
property_list.append(item)
for item in property_list:
if hasattr(obj, item):
value = ge... | def output_to_table(obj, olist='inputs', oformat='latex', table_ends=False, prefix="") | Compile the properties to a table.
:param olist: list, Names of the parameters to be in the output table
:param oformat: str, The type of table to be output
:param table_ends: bool, Add ends to the table
:param prefix: str, A string to be added to the start of each parameter name
:return: para, str... | 2.687705 | 2.685178 | 1.000941 |
if isinstance(value, str):
return value
elif isinstance(value, list) or isinstance(value, np.ndarray):
value = list(value)
for i in range(len(value)):
vv = format_value(value[i])
value[i] = vv
return "[" + ", ".join(value) + "]"
elif value is No... | def format_value(value, sf=3) | convert a parameter value into a formatted string with certain significant figures
:param value: the value to be formatted
:param sf: number of significant figures
:return: str | 2.277822 | 2.325161 | 0.979641 |
fpara = ""
if oformat == 'latex':
fpara += "\\begin{table}[H]\n"
fpara += "\\centering\n"
fpara += "\\begin{tabular}{cc}\n"
fpara += "\\toprule\n"
fpara += "Parameter & Value \\\\\n"
fpara += "\\midrule\n"
fpara += para
fpara += "\\bottomrule\... | def add_table_ends(para, oformat='latex', caption="caption-text", label="table") | Adds the latex table ends
:param para:
:param oformat:
:param caption:
:param label:
:return: | 1.913437 | 1.940686 | 0.985959 |
'''
Draw lines defined by endpoint coordinates as a layer in a SVG file.
Args:
df_endpoints (pandas.DataFrame) : Each row corresponds to the endpoints
of a single line, encoded through the columns: ``x_source``,
``y_source``, ``x_target``, and ``y_target``.
layer_na... | def draw_lines_svg_layer(df_endpoints, layer_name, layer_number=1) | Draw lines defined by endpoint coordinates as a layer in a SVG file.
Args:
df_endpoints (pandas.DataFrame) : Each row corresponds to the endpoints
of a single line, encoded through the columns: ``x_source``,
``y_source``, ``x_target``, and ``y_target``.
layer_name (str) : N... | 3.418729 | 2.184213 | 1.565199 |
self.nautilus_extension.logger.info("DTS error thrown {} for {} ({})".format(
error_name, request.path, message
))
j = jsonify({
"error": error_name,
"message": message
})
j.status_code = 404
return j | def dts_error(self, error_name, message=None) | Create a DTS Error reply
:param error_name: Name of the error
:param message: Message of the Error
:return: DTS Error Response with information (JSON) | 5.830549 | 6.372495 | 0.914955 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.