code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
log_levels = {
5: logging.NOTSET,
4: logging.DEBUG,
3: logging.INFO,
2: logging.WARNING,
1: logging.ERROR,
0: logging.CRITICAL
}
logging.captureWarnings(True)
root_logger = logging.getLogger()
if settings.CFG["debug"]:
details_format = lo... | def configure() | Load logging configuration from our own defaults. | 2.381802 | 2.327739 | 1.023226 |
'''
.. versionchanged:: 0.9.2
Add support for float exponent strings (e.g., ``3.435e-7``).
Fixes `issue #4 <https://github.com/wheeler-microfluidics/svg-model/issues/4>`.
'''
number = None
start = self.get_char('0123456789.-')
if start:
... | def get_number(self) | .. versionchanged:: 0.9.2
Add support for float exponent strings (e.g., ``3.435e-7``).
Fixes `issue #4 <https://github.com/wheeler-microfluidics/svg-model/issues/4>`. | 5.31187 | 2.344178 | 2.265983 |
'''
path_data : string, from an svg path tag's 'd' attribute, eg:
'M 46,74 L 35,12 l 53,-13 z'
returns the same data collected in a list of tuples, eg:
[ ('M', 46, 74), ('L', 35, 12), ('l', 53, -13), ('z') ],
The input data may have floats instead of ints, this wi... | def to_tuples(self, data) | path_data : string, from an svg path tag's 'd' attribute, eg:
'M 46,74 L 35,12 l 53,-13 z'
returns the same data collected in a list of tuples, eg:
[ ('M', 46, 74), ('L', 35, 12), ('l', 53, -13), ('z') ],
The input data may have floats instead of ints, this will be reflected
... | 3.302531 | 1.784417 | 1.850763 |
'''
commands : list of tuples, as output from to_tuples() method, eg:
[('M', 1, 2), ('L', 3, 4), ('L', 5, 6), ('z')]
Interprets the command characters at the start of each tuple to return
a list of loops, where each loop is a closed list of verts, and each
vert is a p... | def to_loops(self, commands) | commands : list of tuples, as output from to_tuples() method, eg:
[('M', 1, 2), ('L', 3, 4), ('L', 5, 6), ('z')]
Interprets the command characters at the start of each tuple to return
a list of loops, where each loop is a closed list of verts, and each
vert is a pair of ints or float... | 4.472128 | 1.440111 | 3.105406 |
'''
color : string, eg: '#rrggbb' or 'none'
(where rr, gg, bb are hex digits from 00 to ff)
returns a triple of unsigned bytes, eg: (0, 128, 255)
'''
if color == 'none':
return None
return (
int(color[1:3], 16),
int(color[3:5], ... | def parse_color(self, color) | color : string, eg: '#rrggbb' or 'none'
(where rr, gg, bb are hex digits from 00 to ff)
returns a triple of unsigned bytes, eg: (0, 128, 255) | 3.533987 | 1.562211 | 2.262169 |
'''
style : string, eg:
fill:#ff2a2a;fill-rule:evenodd;stroke:none;stroke-width:1px;
stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1
returns color as a triple of unsigned bytes: (r, g, b), or None
'''
style_elements = style.split(';')
wh... | def parse_style(self, style) | style : string, eg:
fill:#ff2a2a;fill-rule:evenodd;stroke:none;stroke-width:1px;
stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1
returns color as a triple of unsigned bytes: (r, g, b), or None | 4.400543 | 1.785944 | 2.463987 |
location = search_auth_file() if not location else location
a = load_json(location)
try:
section = a['dhis']
baseurl = section['baseurl']
username = section['username']
password = section['password']
assert all([baseurl, usern... | def from_auth_file(cls, location=None, api_version=None, user_agent=None) | Alternative constructor to load from JSON file.
If auth_file_path is not specified, it tries to find `dish.json` in:
- DHIS_HOME
- Home folder
:param location: authentication file path
:param api_version: see Api
:param user_agent: see Api
:return: Api instance | 3.575111 | 3.779964 | 0.945806 |
try:
response.raise_for_status()
except requests.RequestException:
raise RequestException(
code=response.status_code,
url=response.url,
description=response.text)
else:
return response | def _validate_response(response) | Return response if ok, raise RequestException if not ok
:param response: requests.response object
:return: requests.response object | 3.198443 | 2.618119 | 1.221657 |
if not isinstance(endpoint, string_types) or endpoint.strip() == '':
raise ClientException("Must submit `endpoint` for DHIS2 API")
if not isinstance(file_type, string_types) or file_type.lower() not in ('json', 'csv', 'xml', 'pdf', 'xlsx'):
raise ClientException("Invalid... | def _validate_request(endpoint, file_type='json', data=None, params=None) | Validate request before calling API
:param endpoint: API endpoint
:param file_type: file type requested
:param data: payload
:param params: HTTP parameters | 2.291491 | 2.407722 | 0.951726 |
if isinstance(kwargs.get('file_type'), string_types):
file_type = kwargs['file_type'].lower()
else:
file_type = 'json'
params = kwargs.get('params')
data = kwargs.get('data', kwargs.get('json', None))
url = '{}/{}'.format(self.api_url, endpoint)
... | def _make_request(self, method, endpoint, **kwargs) | Do the actual request with supplied HTTP method
:param method: HTTP method
:param endpoint: DHIS2 API endpoint
:param kwargs: keyword args
:return: response if ok, RequestException if not | 1.977429 | 2.008629 | 0.984467 |
return self._make_request('get', endpoint, params=params, file_type=file_type, stream=stream) | def get(self, endpoint, file_type='json', params=None, stream=False) | GET from DHIS2
:param endpoint: DHIS2 API endpoint
:param file_type: DHIS2 API File Type (json, xml, csv), defaults to JSON
:param params: HTTP parameters
:param stream: use requests' stream parameter
:return: requests.Response object | 2.864802 | 3.86737 | 0.740762 |
json = kwargs['data'] if 'data' in kwargs else json
return self._make_request('post', endpoint, data=json, params=params) | def post(self, endpoint, json=None, params=None, **kwargs) | POST to DHIS2
:param endpoint: DHIS2 API endpoint
:param json: HTTP payload
:param params: HTTP parameters
:return: requests.Response object | 3.870766 | 5.366923 | 0.721226 |
json = kwargs['data'] if 'data' in kwargs else json
return self._make_request('put', endpoint, data=json, params=params) | def put(self, endpoint, json=None, params=None, **kwargs) | PUT to DHIS2
:param endpoint: DHIS2 API endpoint
:param json: HTTP payload
:param params: HTTP parameters
:return: requests.Response object | 3.923231 | 5.404333 | 0.725942 |
json = kwargs['data'] if 'data' in kwargs else json
return self._make_request('patch', endpoint, data=json, params=params) | def patch(self, endpoint, json=None, params=None, **kwargs) | PATCH to DHIS2
:param endpoint: DHIS2 API endpoint
:param json: HTTP payload
:param params: HTTP parameters (dict)
:return: requests.Response object | 3.880428 | 5.1945 | 0.747026 |
json = kwargs['data'] if 'data' in kwargs else json
return self._make_request('delete', endpoint, data=json, params=params) | def delete(self, endpoint, json=None, params=None, **kwargs) | DELETE from DHIS2
:param endpoint: DHIS2 API endpoint
:param json: HTTP payload
:param params: HTTP parameters (dict)
:return: requests.Response object | 3.965181 | 5.619014 | 0.705672 |
try:
if not isinstance(page_size, (string_types, int)) or int(page_size) < 1:
raise ValueError
except ValueError:
raise ClientException("page_size must be > 1")
params = {} if not params else params
if 'paging' in params:
rais... | def get_paged(self, endpoint, params=None, page_size=50, merge=False) | GET with paging (for large payloads).
:param page_size: how many objects per page
:param endpoint: DHIS2 API endpoint
:param params: HTTP parameters (dict), defaults to None
:param merge: If true, return a list containing all pages instead of one page. Defaults to False.
:return:... | 3.209835 | 3.134885 | 1.023908 |
params = {}
sqlview_type = self.get('sqlViews/{}'.format(uid), params={'fields': 'type'}).json().get('type')
if sqlview_type == 'QUERY':
if not isinstance(var, dict):
raise ClientException("Use a dict to submit variables: e.g. var={'key1': 'value1', 'key2': '... | def get_sqlview(self, uid, execute=False, var=None, criteria=None, merge=False) | GET SQL View data
:param uid: sqlView UID
:param execute: materialize sqlView before downloading its data
:param var: for QUERY types, a dict of variables to query the sqlView
:param criteria: for VIEW / MATERIALIZED_VIEW types, a dict of criteria to filter the sqlView
:param mer... | 3.556383 | 3.142341 | 1.131763 |
if not isinstance(json, dict):
raise ClientException('Parameter `json` must be a dict')
if not isinstance(thresh, int) or thresh < 2:
raise ClientException("`thresh` must be integer of 2 or larger")
try:
key = next(iter(json)) # the (only) key in t... | def post_partitioned(self, endpoint, json, params=None, thresh=1000) | Post a payload in chunks to prevent 'Request Entity Too Large' Timeout errors
:param endpoint: the API endpoint to use
:param json: payload dict
:param params: request parameters
:param thresh: the maximum amount to partition into
:return: generator where __next__ is a requests.R... | 4.10236 | 3.777125 | 1.086107 |
'''
Parameters
----------
offset : pandas.Series
Cartesian ``(x, y)`` coordinate of offset origin.
scale : pandas.Series
Scaling factor for ``x`` and ``y`` dimensions.
Returns
-------
pandas.DataFrame
3x3 transformation matrix resulting in specified `x/y` offset ... | def get_transform(offset, scale) | Parameters
----------
offset : pandas.Series
Cartesian ``(x, y)`` coordinate of offset origin.
scale : pandas.Series
Scaling factor for ``x`` and ``y`` dimensions.
Returns
-------
pandas.DataFrame
3x3 transformation matrix resulting in specified `x/y` offset and
... | 6.078722 | 1.547926 | 3.927011 |
'''
Look up shape based on canvas coordinates.
'''
shape_x, shape_y, w = self.canvas_to_shapes_transform.dot([canvas_x,
canvas_y,
1])
if hasattr(s... | def find_shape(self, canvas_x, canvas_y) | Look up shape based on canvas coordinates. | 4.382719 | 4.049754 | 1.082219 |
'''
Return a `pandas.Series` indexed by `shape_i_columns` (i.e., each entry
corresponds to a single shape/polygon), containing the following columns
the area of each shape.
If `signed=True`, a positive area value corresponds to a clockwise loop,
whereas a negative area value corresponds to a co... | def get_shape_areas(df_shapes, shape_i_columns, signed=False) | Return a `pandas.Series` indexed by `shape_i_columns` (i.e., each entry
corresponds to a single shape/polygon), containing the following columns
the area of each shape.
If `signed=True`, a positive area value corresponds to a clockwise loop,
whereas a negative area value corresponds to a counter-clockw... | 2.303209 | 1.858245 | 1.239454 |
'''
Return a `pandas.DataFrame` indexed by `shape_i_columns` (i.e., each row
corresponds to a single shape/polygon), containing the following columns:
- `width`: The width of the widest part of the shape.
- `height`: The height of the tallest part of the shape.
'''
xy_groups = df_shapes.g... | def get_bounding_boxes(df_shapes, shape_i_columns) | Return a `pandas.DataFrame` indexed by `shape_i_columns` (i.e., each row
corresponds to a single shape/polygon), containing the following columns:
- `width`: The width of the widest part of the shape.
- `height`: The height of the tallest part of the shape. | 3.285581 | 1.966576 | 1.670711 |
'''
Return a `pandas.DataFrame` indexed by `shape_i_columns` (i.e., each row
corresponds to a single shape/polygon), containing the following columns:
- `area`: The area of the shape.
- `width`: The width of the widest part of the shape.
- `height`: The height of the tallest part of the shap... | def get_shape_infos(df_shapes, shape_i_columns) | Return a `pandas.DataFrame` indexed by `shape_i_columns` (i.e., each row
corresponds to a single shape/polygon), containing the following columns:
- `area`: The area of the shape.
- `width`: The width of the widest part of the shape.
- `height`: The height of the tallest part of the shape. | 3.262923 | 1.769754 | 1.843715 |
'''
Calculate the bounding box of all points in a data frame.
'''
xy_min = df_points[['x', 'y']].min()
xy_max = df_points[['x', 'y']].max()
wh = xy_max - xy_min
wh.index = 'width', 'height'
bbox = pd.concat([xy_min, wh])
bbox.name = 'bounding_box'
return bbox | def get_bounding_box(df_points) | Calculate the bounding box of all points in a data frame. | 3.005443 | 2.673017 | 1.124364 |
for k, v in dct.items():
if k in converters:
parse_func = converters[k]
dct[k] = parse_func(v)
elif isinstance(v, str):
for decode_func in str_decoders:
v = decode_func(v)
if not isinstance(v, str):
break... | def json_decoder_hook(dct, str_decoders=STRING_DECODERS,
converters=MappingProxyType(dict())) -> dict | Decoder for parsing typical objects like uuid's and dates. | 1.945957 | 1.929791 | 1.008377 |
str_decoders = tuple(chain(str_decoders, extra_str_decoders))
object_hook = partial(json_decoder_hook, str_decoders=str_decoders,
converters=converters)
return object_hook | def make_json_decoder_hook(str_decoders=STRING_DECODERS,
extra_str_decoders=tuple(),
converters=MappingProxyType(dict())) -> Callable | Customize JSON string decoder hooks.
Object hook for typical deserialization scenarios.
Notes
-----
Specifying a field in converters will ensure custom decoding/passthrough.
Parameters
----------
str_decoders: functions for decoding strings to objects.
extra_str_decoders: appends addi... | 2.661862 | 3.454564 | 0.770535 |
for jobid in report.collect('jobid'):
try:
if not Job.finished(jobid):
logging.info('waiting for SLURM job %s', jobid)
time.sleep(interval)
while not Job.finished(jobid):
time.sleep(interval)
yield Job.fromid(jo... | def wait_for_completion(report, interval=10) | Wait for asynchronous jobs stil running in the given campaign.
:param report: memory representation of a campaign report
:type campaign: ReportNode
:param interval: wait interval
:type interval: int or float
:return: list of asynchronous job identifiers | 4.000434 | 4.091075 | 0.977844 |
arguments = cli_common(__doc__, argv=argv)
report = ReportNode(arguments['CAMPAIGN-DIR'])
jobs = wait_for_completion(report, float(arguments['--interval']))
status = ReportStatus(report, jobs)
if not arguments['--silent']:
fmt = arguments['--format'] or 'log'
status.log(fmt)
... | def main(argv=None) | ben-wait entry point | 7.619848 | 7.181619 | 1.061021 |
palette = list()
if hue==None:
leadHue = randFloat(0, 1)
else:
leadHue = hue
palette.append(Color(0,0,0,1).set_HSV(leadHue, sat, val))
palette.append(Color(0,0,0,1).set_HSV((leadHue + 0.5 + spread/360) % 1, sat, val))
palette.append(Color(0,0,0,1).set_HSV((leadHue + 0.5 - spread/360) % 1, sat, val))
retur... | def getColors_Triad(hue=None, sat = 1, val = 1, spread = 60) | Create a palette with one main color and two opposite color evenly spread apart from the main one.
:param hue: A 0-1 float with the starting hue value.
:param sat: A 0-1 float with the palette saturation.
:param val: A 0-1 float with the palette value.
:param val: An int with the spread in degrees from the opposi... | 2.259316 | 2.349154 | 0.961758 |
name = ''
if not self.root.existing_campaign:
campaign_file = osp.basename(self.root.campaign_file)
campaign = osp.splitext(campaign_file)[0]
name += campaign + '/'
name += self.tag
return name | def default_job_name(self) | Slurm job name if not already specified
in the `sbatch` section | 6.09342 | 6.318818 | 0.964329 |
template = self.sbatch_template_str
if template.startswith('#!'):
# script is embedded in YAML
return jinja_environment.from_string(template)
return jinja_environment.get_template(template) | def sbatch_template(self) | :return Jinja sbatch template for the current tag | 6.486148 | 5.928625 | 1.094039 |
templates = self.campaign.process.sbatch_template
if isinstance(templates, Mapping):
# find proper template according to the tag
template = templates.get(self.tag)
if template is None:
template = templates.get('*')
if template is N... | def sbatch_template_str(self) | :return Jinja sbatch template for the current tag as string | 4.900265 | 4.353594 | 1.125568 |
properties = dict(
sbatch_arguments=self.sbatch_args, hpcbench_command=self.hpcbench_cmd
)
try:
self.sbatch_template.stream(**properties).dump(ostr)
except jinja2.exceptions.UndefinedError:
self.logger.error('Error while generating SBATCH temp... | def _create_sbatch(self, ostr) | Write sbatch template to output stream
:param ostr: opened file to write to | 3.803815 | 3.769676 | 1.009056 |
commands = self.campaign.process.get('commands', {})
sbatch = find_executable(commands.get('sbatch', 'sbatch'))
sbatch_command = [sbatch, '--parsable', self.sbatch_filename]
try:
self.logger.debug(
'Executing command: %s',
' '.join(map... | def _execute_sbatch(self) | Schedule the sbatch file using the sbatch command
:returns the slurm job id | 2.693898 | 2.663812 | 1.011294 |
arguments = cli_common(__doc__, argv=argv)
plugin = 'benchmark' if arguments['benchmark'] else None
if arguments['-g']:
template.generate_config(plugin, arguments['<FILE>'])
else:
with open(arguments['<FILE>']) as istr:
context = json.load(istr)
kwargs = dict(no... | def main(argv=None) | ben-tpl entry point | 4.706107 | 4.372403 | 1.07632 |
yield from ((k, list(g)) for k, g in groupby(sequence, key=key)) | def partition_ordered(sequence, key=None) | Partition ordered sequence by key.
Sequence is expected to already be ordered.
Parameters
----------
sequence: iterable data.
key: partition key function
Yields
-------
iterable tuple(s) of partition key, data list pairs.
Examples
--------
1. By object attributes.
Pa... | 4.396137 | 6.001708 | 0.732481 |
t1, t2 = tee(iterable)
return filterfalse(predicate, t1), filter(predicate, t2) | def partition(predicate, iterable) | Use a predicate to partition true and false entries.
Reference
---------
Python itertools documentation. | 3.687782 | 3.90108 | 0.945323 |
def run_not_supported(self, *args, **kwargs):
del args, kwargs # Unused
LOG.warning(
"Runtime testing not supported on auto-generated projects.")
return
newclass = type(
name, (BaseClass, ), {
"NAME": NAME,
"DOMAIN": DOMAIN,
... | def PortageFactory(name, NAME, DOMAIN, BaseClass=autoportage.AutoPortage) | Create a new dynamic portage project.
Auto-Generated projects can only be used for compilie-time experiments,
because there simply is no run-time test defined for it. Therefore,
we implement the run symbol as a noop (with minor logging).
This way we avoid the default implementation for run() that all ... | 6.815978 | 5.440885 | 1.252733 |
# noqa: E501
try:
from pint import UnitRegistry
ureg = UnitRegistry()
from pint.quantity import _Quantity
except ImportError:
raise ImportError('please install pint to use this module')
list_of_dicts = '__list__' if list_of_dicts else None
# flatten edict
usche... | def apply_unitschema(data, uschema, as_quantity=True,
raise_outerr=False, convert_base=False,
use_wildcards=False, list_of_dicts=False) | apply the unit schema to the data
Parameters
----------
data : dict
uschema : dict
units schema to apply
as_quantity : bool
if true, return values as pint.Quantity objects
raise_outerr : bool
raise error if a unit cannot be found in the outschema
convert_to_base : bo... | 2.673923 | 2.83548 | 0.943023 |
try:
from pint.quantity import _Quantity
except ImportError:
raise ImportError('please install pint to use this module')
list_of_dicts = '__list__' if list_of_dicts else None
data_flatten = flatten(data, list_of_dicts=list_of_dicts)
for key, val in data_flatten.items():
... | def split_quantities(data, units='units', magnitude='magnitude',
list_of_dicts=False) | split pint.Quantity objects into <unit,magnitude> pairs
Parameters
----------
data : dict
units : str
name for units key
magnitude : str
name for magnitude key
list_of_dicts: bool
treat list of dicts as additional branches
Examples
--------
>>> from pprint i... | 2.636857 | 3.202343 | 0.823415 |
# noqa: E501
try:
from pint import UnitRegistry
ureg = UnitRegistry()
except ImportError:
raise ImportError('please install pint to use this module')
list_of_dicts = '__list__' if list_of_dicts else None
data_flatten2d = flatten2d(data, list_of_dicts=list_of_dicts)
new... | def combine_quantities(data, units='units', magnitude='magnitude',
list_of_dicts=False) | combine <unit,magnitude> pairs into pint.Quantity objects
Parameters
----------
data : dict
units : str
name of units key
magnitude : str
name of magnitude key
list_of_dicts: bool
treat list of dicts as additional branches
Examples
--------
>>> from pprint i... | 2.701447 | 3.068758 | 0.880306 |
if src_file is None:
return None
tmp_dir = local.path(str(CFG["tmp_dir"]))
if tmp_dir.exists():
cache_file = tmp_dir / src_file
dir_hash = get_hash_of_dirs(cache_file)
if dir_hash is None:
return None
if len(str(dir_hash)) <= 7:
return st... | def get_version_from_cache_dir(src_file) | Creates a version for a project out of the hash.
The hash is taken from the directory of the source file.
Args:
src_file: The source file of the project using this function.
Returns:
Either returns the first 8 digits of the hash as string,
the entire hash as a string if the hash c... | 3.449129 | 3.316501 | 1.03999 |
from benchbuild.utils.cmd import git
if from_url is None:
return ""
if not path.exists(from_url):
return ""
with local.cwd(from_url):
return git("rev-parse", "HEAD", retcode=None) | def get_git_hash(from_url) | Get the git commit hash of HEAD from :from_url.
Args:
from_url: The file system url of our git repository.
Returns:
git commit hash of HEAD, or empty string. | 3.908661 | 4.438217 | 0.880683 |
from parse import parse
timings = [x for x in ins if marker in x]
res = [parse(format_s, t) for t in timings]
return [_f for _f in res if _f] | def fetch_time_output(marker, format_s, ins) | Fetch the output /usr/bin/time from a.
Args:
marker: The marker that limits the time output
format_s: The format string used to parse the timings
ins: A list of lines we look for the output.
Returns:
A list of timing tuples | 5.388974 | 6.043471 | 0.891702 |
return [elem for elem in pathstr.split(os.path.pathsep) if elem] | def path_to_list(pathstr) | Conver a path string to a list of path elements. | 4.18055 | 3.640391 | 1.14838 |
root = __file__
if os.path.islink(root):
root = os.path.realpath(root)
return os.path.dirname(os.path.abspath(root)) | def determine_path() | Borrowed from wxglade.py | 2.554348 | 2.202523 | 1.159737 |
if not os.path.isabs(path):
_path = os.path.join(determine_path(), path)
if not (os.path.exists(_path) and os.path.isdir(_path)):
return []
if not exts:
exts = []
files = os.listdir(_path)
files = [f for f in files if os.path.splitext(f)[-1] in exts]
files = [os.path... | def template_files(path, exts=None) | Return a list of filenames found at @path.
The list of filenames can be filtered by extensions.
Arguments:
path: Existing filepath we want to list.
exts: List of extensions to filter by.
Returns:
A list of filenames found in the path. | 2.096533 | 2.20355 | 0.951434 |
tmpl_file = os.path.join(determine_path(), template)
with open(tmpl_file, mode='r') as tmpl_strm:
return "".join(tmpl_strm.readlines()) | def template_str(template) | Read a template file from the resources and return it as str. | 4.639163 | 4.130471 | 1.123156 |
from benchbuild.utils.uchroot import no_args, uretry
uchroot = no_args()
uchroot = uchroot["-E", "-A", "-C", "-w", "/", "-r"]
uchroot = uchroot[os.path.abspath(root)]
uretry(uchroot["--", "/bin/touch", filepath]) | def mkfile_uchroot(filepath, root=".") | Create a file inside a uchroot env.
You will want to use this when you need to create a file with apropriate
rights inside a uchroot container with subuid/subgid handling enabled.
Args:
filepath:
The filepath that should be created. Absolute inside the
uchroot container.
... | 7.916659 | 7.567264 | 1.046172 |
from benchbuild.utils.uchroot import no_args, uretry
uchroot = no_args()
uchroot = uchroot["-E", "-A", "-C", "-w", "/", "-r"]
uchroot = uchroot[os.path.abspath(root)]
uretry(uchroot["--", "/bin/mkdir", "-p", dirpath]) | def mkdir_uchroot(dirpath, root=".") | Create a file inside a uchroot env.
You will want to use this when you need to create a file with apropriate
rights inside a uchroot container with subuid/subgid handling enabled.
Args:
dirpath:
The dirpath that should be created. Absolute inside the
uchroot container.
... | 7.591555 | 7.57356 | 1.002376 |
from benchbuild.utils.cmd import mkdir
if os.path.exists(dirpath):
return
response = ui.ask(
"The directory {dirname} does not exist yet. "
"Should I create it?".format(dirname=dirpath),
default_answer=True,
default_answer_str="yes")
if response:
mk... | def mkdir_interactive(dirpath) | Create a directory if required.
This will query the user for a confirmation.
Args:
dirname: The path to create. | 3.655311 | 3.972916 | 0.920058 |
found_flag = False
for el in root.iter():
if found_flag:
return(el)
if el.text == search:
# We want the next el
found_flag = True | def get_val_by_text(root,search) | From MeasYaps XML root find next sibling of node matching 'search'.
MeasYaps looks like:
<value>Key</value>
<value>Value</value>
Thus 'search' is the Key and we want to find the node that has the Value.
We return the node containing the desired Value.
Arguments:
root (Element) r... | 4.862866 | 5.506884 | 0.883052 |
node = root.find("ParamMap[@name='YAPS']/ParamLong[@name='%s']/value" % name)
if node is not None:
return(afun(node.text))
else:
return(default) | def get_yaps_by_name(root,name,afun=lambda x:x,default=None) | From XML root, return value of node matching attribute 'name'.
Arguments:
root (Element) Root XML node (xml.etree.ElementTree Element).
This is the root of the entire XML document, not the YAPS
subtree.
name (String) name='name' attribute of Pa... | 4.331271 | 3.669084 | 1.180477 |
'''Function run when called from command line.'''
options = { '-rfft': ['resetFFTscale',False],
'-r1': ['readOneCoil',False],
'-rp': ['readPhaseCorInfo',False],
'-rn': ['readNavigator',False],
'-skipts': ['readTimeStamp',True],
... | def main(args) | Function run when called from command line. | 14.534271 | 13.996241 | 1.038441 |
if not hasattr(jdir, 'iterdir'):
raise ValueError('jdir is not a path object; {}'.format(jdir))
key_path = [] if key_path is None else key_path
keys = []
key_found = False if key_path else True
search_key = key_path[0] if len(key_path) > 0 else None
for jsub in jdir.iterdir():
... | def _get_keys_folder(jdir, key_path=None, in_memory=True,
ignore_prefix=('.', '_')) | get json keys from directory structure
e.g.
jdir
sub_dir1
data1.json
data2.json
sub_dir2
data.json
_get_keys_folder(jdir)
=> ['sub_dir1', 'sub_dir2']
_get_keys_folder(jdir,['sub_dir1'])
=> ['data1', 'data2']
NB: json files are identifie... | 2.581985 | 2.618025 | 0.986234 |
key_path = [] if key_path is None else key_path
def eval_file(file_obj):
if not in_memory:
return _get_keys_ijson(file_obj, key_path)
else:
return _get_keys(file_obj, key_path)
if isinstance(jfile, basestring):
if not os.path.exists(jfile):
... | def jkeys(jfile, key_path=None, in_memory=True, ignore_prefix=('.', '_')) | get keys for initial json level, or at level after following key_path
Parameters
----------
jfile : str, file_like or path_like
if str, must be existing file or folder,
if file_like, must have 'read' method
if path_like, must have 'iterdir' method (see pathlib.Path)
key_path : l... | 2.10921 | 2.071289 | 1.018308 |
key_path = [] if key_path is None else key_path
try:
objs = ijson.items(file_obj, '.'.join(key_path))
except NameError:
warnings.warn('ijson package not found in environment, \
please install for on-disk key indexing', ImportWarning)
data = json.load(
file_o... | def _file_with_keys(file_obj, key_path=None, parse_decimal=False) | read json with keys
Parameters
----------
file_obj : object
object with read method
key_path : list[str]
key to index befor parsing
parse_decimal : bool
whether to parse numbers as Decimal instances (retains exact precision)
Notes
-----
ijson outputs decimals as... | 4.712484 | 4.670092 | 1.009077 |
key_path = [] if key_path is None else key_path
if not hasattr(jdir, 'iterdir'):
raise ValueError('jdir is not a path object; {}'.format(jdir))
key_found = False if key_path else True
search_key = key_path[0] if len(key_path) > 0 else None
for jsub in jdir.iterdir():
if jsub.... | def _folder_to_json(jdir, key_path=None, in_memory=True,
ignore_prefix=('.', '_'), dic={}, parse_decimal=False) | read in folder structure as json
e.g.
jdir
sub_dir1
data.json
sub_dir2
data.json
_folder_to_json(jdir)
=> {'sub_dir1':{'data':{...}},
'sub_dir2':{'data':{...}}}
NB: json files are identified with .json extension | 2.468036 | 2.590941 | 0.952564 |
items = iter(items)
for first in items:
chunk = chain((first,), islice(items, chunksize - 1))
yield chunk
deque(chunk, 0) | def chunks(items, chunksize) | Turn generator sequence into sequence of chunks. | 5.534153 | 6.153226 | 0.899391 |
from functools import wraps
def wrap_in_union_fs(func):
@wraps(func)
def wrap_in_union_fs_func(project, *args, **kwargs):
container = project.container
if container is None or in_container():
return func(project, *args, **kwarg... | def unionfs(rw='rw', ro=None, union='union') | Decorator for the UnionFS feature.
This configures a unionfs for projects. The given base_dir and/or image_dir
are layered as follows:
image_dir=RW:base_dir=RO
All writes go to the image_dir, while base_dir delivers the (read-only)
versions of the rest of the filesystem.
The unified version w... | 3.03298 | 2.891296 | 1.049004 |
cleanup_dirs = settings.CFG["cleanup_paths"].value
cleanup_dirs = set(cleanup_dirs)
cleanup_dirs.add(new_path)
cleanup_dirs = list(cleanup_dirs)
settings.CFG["cleanup_paths"] = cleanup_dirs | def __update_cleanup_paths(new_path) | Add the new path to the list of paths to clean up afterwards.
Args:
new_path: Path to the directory that need to be cleaned up. | 3.280129 | 4.307359 | 0.761518 |
bdir = project.builddir
cprefix = os.path.commonprefix([path_to_check, bdir])
return cprefix != bdir | def __is_outside_of_builddir(project, path_to_check) | Check if a project lies outside of its expected directory. | 4.402643 | 4.012778 | 1.097156 |
mount_dir.mkdir()
rw_dir.mkdir()
if not ro_dir.exists():
LOG.error("Base dir does not exist: '%s'", ro_dir)
raise ValueError("Base directory does not exist")
from benchbuild.utils.cmd import unionfs as unionfs_cmd
LOG.debug("Mounting UnionFS on %s with RO:%s RW:%s", mount_dir, ... | def __unionfs_set_up(ro_dir, rw_dir, mount_dir) | Setup a unionfs via unionfs-fuse.
Args:
ro_base: base_directory of the project
rw_image: virtual image of actual file system
mountpoint: location where ro_base and rw_image merge | 5.050845 | 5.644464 | 0.894832 |
expr = re.escape(PRECISION_FORMULA)
expr += r'=\s*(\S*)\s.*\s([A-Z]*)'
return re.compile(expr) | def get_precision_regex() | Build regular expression used to extract precision
metric from command output | 7.652649 | 7.240705 | 1.056893 |
def baseN(nodes, mpn):
return int(math.sqrt(mpn * 0.80 * nodes * 1024 * 1024 / 8))
def nFromNb(baseN, nb):
factor = int(baseN / nb)
if factor % 2 != 0:
factor -= 1
return nb * factor
def get_grid(nodes, ppn):
... | def _build_data(self) | Build HPL data from basic parameters | 4.395477 | 4.23283 | 1.038425 |
cmd = self.attributes['mpirun']
if cmd and cmd[0] != 'mpirun':
cmd = ['mpirun']
return [str(e) for e in cmd] | def mpirun(self) | Additional options passed as a list to the ``mpirun`` command | 4.883043 | 4.844851 | 1.007883 |
tpl = TemplateWithDefaults(s)
return tpl.substitute(vars or os.environ) | def expandvars(s, vars=None) | Perform variable substitution on the given string
Supported syntax:
* $VARIABLE
* ${VARIABLE}
* ${#VARIABLE}
* ${VARIABLE:-default}
:param s: message to expand
:type s: str
:param vars: dictionary of variables. Default is ``os.environ``
:type vars: dict
:return: expanded stri... | 9.743149 | 17.556746 | 0.554952 |
return cls.__eval_seqexp(obj, operator.and_, **kwargs) | def and_(cls, obj, **kwargs) | Query an object
:param obj:
object to test
:param kwargs: query specified in kwargssql
:return:
`True` if all `kwargs` expression are `True`, `False` otherwise.
:rtype: bool | 17.390635 | 34.179813 | 0.508798 |
return cls.__eval_seqexp(obj, operator.or_, **kwargs) | def or_(cls, obj, **kwargs) | Query an object
:param obj:
object to test
:param kwargs: query specified in kwargssql
:return:
`True` if at leat one `kwargs` expression is `True`,
`False` otherwise.
:rtype: bool | 18.858307 | 31.486029 | 0.598942 |
return cls.__eval_seqexp(obj, operator.xor, **kwargs) | def xor(cls, obj, **kwargs) | Query an object.
:param obj:
object to test
:param kwargs: query specified in kwargssql
:return:
`True` if exactly one `kwargs` expression is `True`,
`False` otherwise.
:rtype: bool | 17.129166 | 28.070881 | 0.610211 |
path = [p for p in path if p]
if any(path):
pathes = len(path)
i = 0
while i < pathes:
# _get_obj_attr can supersede `i` because it might
# evaluate the entire expression by itself.
obj, i = cls._get_obj_attr(ob... | def __resolve_path(cls, obj, path) | Follow a kwargsql expression starting from a given object
and return the deduced object.
:param obj: the object to start from
:param list path: list of operations to perform. It does not contain
the optional operation of a traditional kwargsql
... | 6.47446 | 7.34556 | 0.881411 |
if not any(path):
# There is no further kwargsql expression
return seq
result = []
for item in seq:
try:
result.append(cls.__resolve_path(item, path))
except (KeyError, IndexError):
pass
return resul... | def _sequence_map(cls, seq, path) | Apply a kwargsql expression to every item of a sequence,
and returns it.
:param seq: the list to transform
:param path: kwargsql expression to apply to every elements of
the given sequence. | 7.77097 | 5.280737 | 1.471569 |
def _wrap(*args, **kwargs):
return not operation(*args, **kwargs)
return _wrap | def _not(cls, operation) | not operation | 5.814296 | 4.928669 | 1.179689 |
if projects_to_filter is None:
projects_to_filter = []
import benchbuild.projects as all_projects
all_projects.discover()
prjs = ProjectRegistry.projects
if projects_to_filter:
prjs = {}
for filter_project in set(projects_to_filter):
try:
pr... | def populate(projects_to_filter=None, group=None) | Populate the list of projects that belong to this experiment.
Args:
projects_to_filter (list(Project)):
List of projects we want to assign to this experiment.
We intersect the list of projects with the list of supported
projects to get the list of projects that belong to... | 3.355184 | 3.559445 | 0.942614 |
from benchbuild.utils import cmd
cc_name = str(CFG["compiler"]["c"])
wrap_cc(cc_name, compiler(cc_name), project, detect_project=detect_project)
return cmd["./{}".format(cc_name)] | def cc(project, detect_project=False) | Return a clang that hides CFLAGS and LDFLAGS.
This will generate a wrapper script in the current directory
and return a complete plumbum command to it.
Args:
cflags: The CFLAGS we want to hide.
ldflags: The LDFLAGS we want to hide.
func (optional): A function that will be pickled a... | 7.664931 | 7.903318 | 0.969837 |
from benchbuild.utils import cmd
cxx_name = str(CFG["compiler"]["cxx"])
wrap_cc(
cxx_name, compiler(cxx_name), project, detect_project=detect_project)
return cmd["./{name}".format(name=cxx_name)] | def cxx(project, detect_project=False) | Return a clang++ that hides CFLAGS and LDFLAGS.
This will generate a wrapper script in the current directory
and return a complete plumbum command to it.
Args:
cflags: The CFLAGS we want to hide.
ldflags: The LDFLAGS we want to hide.
func (optional): A function that will be pickled... | 6.937779 | 6.712423 | 1.033573 |
pinfo = __get_paths()
_compiler = local[name]
_compiler = _compiler.setenv(
PATH=pinfo["path"], LD_LIBRARY_PATH=pinfo["ld_library_path"])
return _compiler | def compiler(name) | Get a usable clang++ plumbum command.
This searches for a usable clang++ in the llvm binary path
Returns:
plumbum Command that executes clang++ | 6.305355 | 7.827562 | 0.805532 |
if prefix is None:
return ipath
return ipath[len(prefix):] if ipath.startswith(prefix) else ipath | def strip_path_prefix(ipath, prefix) | Strip prefix from path.
Args:
ipath: input path
prefix: the prefix to remove, if it is found in :ipath:
Examples:
>>> strip_path_prefix("/foo/bar", "/bar")
'/foo/bar'
>>> strip_path_prefix("/foo/bar", "/")
'foo/bar'
>>> strip_path_prefix("/foo/bar", "/fo... | 2.718316 | 3.820914 | 0.711431 |
pickle = None
with open(pickle_file, "rb") as pickle_f:
pickle = dill.load(pickle_f)
if not pickle:
LOG.error("Could not load python object from file")
return pickle | def unpickle(pickle_file) | Unpickle a python object from the given path. | 4.446782 | 4.001723 | 1.111217 |
env = __create_jinja_env()
template = env.get_template('run_static.py.inc')
name_absolute = os.path.abspath(name)
real_f = name_absolute + PROJECT_BIN_F_EXT
if sprefix:
run(uchroot()["/bin/mv",
strip_path_prefix(name_absolute, sprefix),
strip... | def wrap(name, project, sprefix=None, python=sys.executable) | Wrap the binary :name: with the runtime extension of the project.
This module generates a python tool that replaces :name:
The function in runner only accepts the replaced binaries
name as argument. We use the cloudpickle package to
perform the serialization, make sure :runner: can be serialized
wi... | 3.869717 | 3.803935 | 1.017293 |
env = __create_jinja_env()
template = env.get_template('run_compiler.py.inc')
cc_fname = local.path(filepath).with_suffix(".benchbuild.cc", depth=0)
cc_f = persist(compiler, filename=cc_fname)
project_file = persist(project, suffix=".project")
with open(filepath, 'w') as wrapper:
... | def wrap_cc(filepath,
compiler,
project,
python=sys.executable,
detect_project=False) | Substitute a compiler with a script that hides CFLAGS & LDFLAGS.
This will generate a wrapper script in the current directory
and return a complete plumbum command to it.
Args:
filepath (str): Path to the wrapper script.
compiler (benchbuild.utils.cmd):
Real compiler command we... | 4.424239 | 4.708828 | 0.939563 |
if suffix is None:
suffix = ".pickle"
if hasattr(id_obj, 'id'):
ident = id_obj.id
else:
ident = str(id(id_obj))
if filename is None:
filename = "{obj_id}{suffix}".format(obj_id=ident, suffix=suffix)
with open(filename, 'wb') as obj_file:
dill.dump(id_ob... | def persist(id_obj, filename=None, suffix=None) | Persist an object in the filesystem.
This will generate a pickled version of the given obj in the filename path.
Objects shall provide an id() method to be able to use this persistence API.
If not, we will use the id() builtin of python to generate an identifier
for you.
The file will be created, ... | 2.290336 | 2.519573 | 0.909018 |
if not os.path.exists(filename):
LOG.error("load object - File '%s' does not exist.", filename)
return None
obj = None
with open(filename, 'rb') as obj_file:
obj = dill.load(obj_file)
return obj | def load(filename) | Load a pickled obj from the filesystem.
You better know what you expect from the given pickle, because we don't check it.
Args:
filename (str): The filename we load the object from.
Returns:
The object we were able to unpickle, else None. | 3.218926 | 3.371605 | 0.954716 |
'''
Extend shape/polygon outline away from polygon center point by absolute
distance.
'''
df_shapes_i = df_shapes.copy()
offsets = df_shapes_i[axis + '_center_offset'].copy()
offsets[offsets < 0] -= distance
offsets[offsets >= 0] += distance
df_shapes_i[axis] = df_shapes_i[axis + '_c... | def extend_shapes(df_shapes, axis, distance) | Extend shape/polygon outline away from polygon center point by absolute
distance. | 4.665514 | 2.727635 | 1.710461 |
'''
Return matrix where $a_{i,j} = 1$ indicates polygon $i$ is connected to
polygon $j$.
Also, return mapping (and reverse mapping) from original keys in
`df_connected` to zero-based integer index used for matrix rows and
columns.
'''
sorted_path_keys = np.sort(np.unique(df_connected[['... | def get_adjacency_matrix(df_connected) | Return matrix where $a_{i,j} = 1$ indicates polygon $i$ is connected to
polygon $j$.
Also, return mapping (and reverse mapping) from original keys in
`df_connected` to zero-based integer index used for matrix rows and
columns. | 3.381133 | 1.999635 | 1.690875 |
if CFG["plugins"]["autoload"]:
report_plugins = CFG["plugins"]["reports"].value
for plugin in report_plugins:
try:
importlib.import_module(plugin)
LOG.debug("Found report: %s", plugin)
except ImportError:
LOG.error("Could n... | def discover() | Import all experiments listed in *_PLUGINS_REPORTS.
Tests:
>>> from benchbuild.settings import CFG
>>> from benchbuild.reports import discover
>>> import logging as lg
>>> import sys
>>> l = lg.getLogger('benchbuild')
>>> l.setLevel(lg.DEBUG)
>>> l.handlers =... | 5.190944 | 3.540748 | 1.466059 |
es_conf = self.campaign.export.elasticsearch
return Elasticsearch(self.hosts, **es_conf.connection_params) | def es_client(self) | Get Elasticsearch client | 14.626924 | 12.249357 | 1.194097 |
fmt = self.campaign.export.elasticsearch.index_name
fields = dict(date=self.report['date'])
return fmt.format(**fields).lower() | def index_name(self) | Get Elasticsearch index name associated to the campaign | 14.236396 | 10.68118 | 1.332849 |
self.index_client.close(self.index_name)
self.index_client.delete(self.index_name) | def remove_index(self) | Remove Elasticsearch index associated to the campaign | 4.397215 | 3.541762 | 1.241533 |
from argparse import ArgumentParser
if args is None:
args = sys.argv
parser = ArgumentParser(description='Rename template project with'
'hyphen-separated <new name> (path names and in '
'files).')
parser.add_argument('new_name', help... | def parse_args(args=None) | Parses arguments, returns (options, args). | 6.711964 | 6.463418 | 1.038454 |
build_info = {}
with mkdtemp() as tempd, pushd(tempd):
proc = subprocess.Popen(
[
OBJCOPY,
DUMP_SECTION,
"{secn}={ofile}".format(secn=elf_section, ofile=BUILDINFO_FILE),
exe_path,
],
stderr=subproces... | def extract_build_info(exe_path, elf_section=ELF_SECTION) | Extracts the build information from a given executable.
The build information is expected to be in json format, which is parsed
and returned as a dictionary.
If no build information is found an empty dictionary is returned.
This assumes binutils 2.25 to work.
Args:
exe_path (str): The ful... | 4.408597 | 4.642251 | 0.949668 |
params = {
'typeid': im_type,
'timeout': timeout,
}
params.update(self.base_params)
files = {'image': ('check_code.png', im)}
r = requests.post('http://api.ruokuai.com/create.json', data=params, files=files, headers=self.headers)
return r.... | def rk_create(self, im, im_type, timeout=60) | im: 图片字节
im_type: 题目类型 | 3.57654 | 3.29196 | 1.086447 |
params = {
'id': im_id,
}
params.update(self.base_params)
r = requests.post('http://api.ruokuai.com/reporterror.json', data=params, headers=self.headers)
return r.json() | def rk_report_error(self, im_id) | im_id:报错题目的ID | 3.59643 | 3.113726 | 1.155025 |
rebased = 2 * (value - 0.5)
if rebased == 0:
return 0
elif rebased > 0:
compliment = 1.0 - rebased
score = - np.log2(compliment)
else:
compliment = 1.0 + rebased
score = np.log2(compliment)
return score | def lc_score(value) | Evaluates the accuracy of a predictive measure (e.g. r-squared)
:param value: float, between 0.0 and 1.0.
:return: | 2.970947 | 3.298746 | 0.900629 |
uchroot_cmd = with_mounts(*args, uchroot_cmd_fn=no_llvm, **kwargs)
return uchroot_cmd["--"] | def uchroot(*args, **kwargs) | Return a customizable uchroot command.
Args:
args: List of additional arguments for uchroot (typical: mounts)
Return:
chroot_cmd | 15.013271 | 17.0714 | 0.87944 |
uchroot_cmd = no_args()
uchroot_cmd = uchroot_cmd[__default_opts__(uid, gid)]
return uchroot_cmd[args] | def no_llvm(*args, uid=0, gid=0, **kwargs) | Return a customizable uchroot command.
The command will be executed inside a uchroot environment.
Args:
args: List of additional arguments for uchroot (typical: mounts)
Return:
chroot_cmd | 9.330401 | 7.893312 | 1.182064 |
from benchbuild.utils.cmd import uchroot as uchrt
prefixes = CFG["container"]["prefixes"].value
p_paths, p_libs = env(prefixes)
uchrt = run.with_env_recursive(
uchrt,
LD_LIBRARY_PATH=path.list_to_path(p_libs),
PATH=path.list_to_path(p_paths))
return uchrt | def no_args(**kwargs) | Return the uchroot command without any customizations. | 10.144411 | 8.054102 | 1.259533 |
mounts = CFG["container"]["mounts"].value
prefixes = CFG["container"]["prefixes"].value
uchroot_opts, mounts = __mounts__("mnt", mounts)
uchroot_cmd = uchroot_cmd_fn(**kwargs)
uchroot_cmd = uchroot_cmd[uchroot_opts]
uchroot_cmd = uchroot_cmd[args]
paths, libs = env(mounts)
prefix_p... | def with_mounts(*args, uchroot_cmd_fn=no_args, **kwargs) | Return a uchroot command with all mounts enabled. | 4.41134 | 4.329648 | 1.018868 |
env = uchroot_cmd["/usr/bin/env"]
__clean_env = env["-u", ",".join(varnames)]
return __clean_env | def clean_env(uchroot_cmd, varnames) | Returns a uchroot cmd that runs inside a filtered environment. | 6.371698 | 6.401813 | 0.995296 |
i = 0
mntpoints = []
for mount in __mounts:
if not isinstance(mount, dict):
mntpoint = "{0}/{1}".format(prefix, str(i))
mntpoints.append(mntpoint)
i = i + 1
return mntpoints | def mounts(prefix, __mounts) | Compute the mountpoints of the current user.
Args:
prefix: Define where the job was running if it ran on a cluster.
mounts: All mounts the user currently uses in his file system.
Return:
mntpoints | 2.971875 | 3.041691 | 0.977047 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.