code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
tc = self.doc.get_term_class(term.lower()) c = tc(term, str(value) if value is not None else None, parent=self, doc=self.doc, section=self.section).new_children(**kwargs) c.term_value_name = self.doc.decl_terms.get(c.join, {}).get('termvaluename', c.term_value_name) ...
def new_child(self, term, value, **kwargs)
Create a new term and add it to this term as a child. Creates grandchildren from the kwargs. :param term: term name. Just the record term :param term: Value to assign to the term :param term: Term properties, which create children of the child term.
7.851012
8.271949
0.949113
assert isinstance(child, Term) self.children.remove(child) self.doc.remove_term(child)
def remove_child(self, child)
Remove the term from this term's children.
5.14664
3.549417
1.449996
for k, v in kwargs.items(): self.new_child(k, v) return self
def new_children(self, **kwargs)
Create new children from kwargs
3.819071
3.131766
1.219462
assert self.section is not None for t in self.children: t.parent = self t._section = self.section t.doc = self.doc t.set_ownership()
def set_ownership(self)
Recursivelt set the parent, section and doc for a children
6.193132
3.540414
1.749268
if '.' in term: parent, term = term.split('.') assert parent.lower() == self.record_term_lc, (parent.lower(), self.record_term_lc) for c in self.children: if c.record_term_lc == term.lower(): if value is False or c.value == value: ...
def find(self, term, value=False)
Return a terms by name. If the name is not qualified, use this term's record name for the parent. The method will yield all terms with a matching qualified name.
4.318294
3.599801
1.199592
pt, rt = self.split_term(term) term = self.record_term + '.' + rt c = self.find_first(rt) if c is None: tc = self.doc.get_term_class(term.lower()) c = tc(term, value, parent=self, doc=self.doc, section=self.section).new_children(**kwargs) ...
def get_or_new_child(self, term, value=False, **kwargs)
Find a term, using find_first, and set it's value and properties, if it exists. If it does not, create a new term and children.
5.072823
4.654171
1.089952
try: return self[item].value except (AttributeError, KeyError) as e: return default
def get_value(self, item, default=None)
Get the value of a child
4.326076
4.288147
1.008845
assert self.parent is not None or self.parent_term_lc == 'root' if self.parent: return self.parent.record_term_lc + '.' + self.record_term_lc else: return 'root.' + self.record_term_lc
def qualified_term(self)
Return the fully qualified term name. The parent will be 'root' if there is no parent term defined.
5.004977
3.549382
1.410098
if isinstance(v, str): if '.' not in v: v = 'root.' + v v_p, v_r = self.split_term_lower(v) if self.join_lc == v.lower(): return True elif v_r == '*' and v_p == self.parent_term_lc: return True ...
def term_is(self, v)
Return True if the fully qualified name of the term is the same as the argument. If the argument is a list or tuple, return True if any of the term names match. Either the parent or the record term can be '*' ( 'Table.*' or '*.Name' ) to match any value for either the parent or record term.
3.611783
2.868949
1.258922
d = dict(zip([str(e).lower() for e in self.section.property_names], self.args)) # print({ c.record_term_lc:c.value for c in self.children}) d[self.term_value_name.lower()] = self.value return d
def arg_props(self)
Return the value and scalar properties as a dictionary. Returns only argumnet properties, properties declared on the same row as a term. It will return an entry for all of the args declared by the term's section. Use props to get values of all children and arg props combined
11.50212
9.482749
1.212952
d = self.arg_props d.update(self.props) return d
def all_props(self)
Return a dictionary with the values of all children, and place holders for all of the section argumemts. It combines props and arg_props
14.686448
5.152264
2.850484
from collections import OrderedDict if not term: return None if term.children: d = OrderedDict() for c in term.children: if c.child_property_type == 'scalar': d[c.record_term_lc] = cls._convert_to_dict(c, repl...
def _convert_to_dict(cls, term, replace_value_names=True)
Converts a record heirarchy to nested dicts. :param term: Root term at which to start conversion
2.345955
2.337777
1.003498
# Translate the term value name so it can be assigned to a parameter. tvm = self.section.doc.decl_terms.get(self.qualified_term, {}).get('termvaluename', '@value') assert tvm # Terminal children have no arguments, just a value. Here we put the terminal children # in a p...
def rows(self)
Yield rows for the term, for writing terms to a CSV file.
11.849978
10.273186
1.153486
for c in self.children: yield c for d in c.descendents: yield d
def descendents(self)
Iterate over all descendent terms
4.323224
4.002531
1.080123
t.doc = None t.terms = [] t.__class__ = SectionTerm return t
def subclass(cls, t)
Change a term into a Section Term
15.556298
7.360162
2.113581
self.args = [arg_.strip() for arg_ in self.args if arg_.strip()] if arg.title() not in self.args: if prepend: self.args = [arg.title()] + self.args else: self.args.append(arg.title())
def add_arg(self,arg, prepend=False)
Append an arg to the arg list
2.952036
2.811797
1.049875
self.args = [arg_.strip() for arg_ in self.args if arg_.strip()] for arg_ in list(self.args): if arg_.lower() == arg.lower(): self.args.remove(arg_)
def remove_arg(self, arg)
Remove an arg to the arg list
3.52341
3.129264
1.125955
if t not in self.terms: if t.parent_term_lc == 'root': self.terms.append(t) self.doc.add_term(t, add_section=False) t.set_ownership() else: raise GenerateError("Can only add or move root-level terms. Term '{}' pa...
def add_term(self, t)
Add a term to this section and set it's ownership. Should only be used on root level terms
8.814348
6.806924
1.294909
tc = self.doc.get_term_class(term.lower()) t = tc(term, value, doc=self.doc, parent=None, section=self).new_children(**kwargs) self.doc.add_term(t) return t
def new_term(self, term, value, **kwargs)
Create a new root-level term in this section
6.243175
5.243519
1.190646
return self.doc.find_first(term, value=value, section=self.name)
def get_term(self, term, value=False)
Synonym for find_first, restructed to this section
10.691424
5.556549
1.924112
for t in terms: self.add_term(t) for k,v in kw_terms.items(): try: value, props = v except (ValueError, TypeError) as e: value, props = v,{} self.new_term(k,value,**props)
def set_terms(self,*terms, **kw_terms)
Create or set top level terms in the section. After python 3.6.0, the terms entries should maintain the same order as the argument list. The term arguments can have any of these forms: * For position argument, a Term object * For kw arguments: - 'TermName=TermValue' - 'T...
3.361109
3.340423
1.006193
try: self.terms.remove(term) except ValueError: pass if remove_from_doc: self.doc.remove_term(term)
def remove_term(self, term, remove_from_doc=True)
Remove a term from the terms. Must be the identical term, the same object
2.40556
2.697502
0.891773
terms = list(self) for t in terms: self.doc.remove_term(t)
def clean(self)
Remove all of the terms from the section, and also remove them from the document
10.960209
5.091573
2.152618
if order is None: self.terms = sorted(self.terms, key=lambda e: e.join_lc) else: all_terms = list(self.terms) sorted_terms = [] for tn in order: for t in list(all_terms): if t.term_is(tn): ...
def sort_by_term(self, order=None)
Sort the terms in the section. :param order: If specified, a list of qualified, lowercased term names. These names will appear first in the section, and the remaining terms will be sorted alphabetically. If not specified, all terms are alphabetized. :return:
2.819159
2.745492
1.026832
# Get the term value name, the property name that should be assigned to the term value. tvm = self.doc.decl_terms.get(term, {}).get('termvaluename', '@value') # Convert the keys to lower case lower_d = {k.lower(): v for k, v in d.items()} args = [] for n in [...
def _args(self, term, d)
Extract the chldren of a term that are arg-children from those that are row-children.
6.382909
6.234288
1.023839
for t in self.terms: for row in t.rows: term, value = row # Value can either be a string, or a dict if isinstance(value, dict): # Dict is for properties, which might be arg-children term, args, remain = self._args(term, value) ...
def rows(self)
Yield rows for the section
11.041464
10.096916
1.093548
# Yield the section header if self.name != 'Root': yield ('Section', '|'.join([self.value] + self.property_names)) # Yield all of the rows for terms in the section for row in self.rows: term, value = row if not isinstance(value, (list, tupl...
def lines(self)
Iterate over all of the rows as text lines
6.279399
5.762289
1.08974
old_children = self.children self.children = self.terms d = super(SectionTerm, self).as_dict(replace_value_names) self.children = old_children return d
def as_dict(self, replace_value_names=True)
Return the whole section as a dict
4.574669
3.835518
1.192712
cwd = cwd or '.' metadir = metadir or '.' metadir = os.path.join(cwd, metadir) used_metafile = False if not preferred_vendor and use_meta: try: preferred_vendor = cls.get_from_metadata_file( metadir, 'vendor') ...
def find_compiler(cls, preferred_vendor, metadir, cwd, use_meta=True)
Identify a suitable C/fortran/other compiler When it is possible that the user (un)installs a compiler inbetween compilations of object files we want to catch that. This method allows compiler choice to be stored in a pickled metadata file. Provide metadir a dirpath to make the...
2.998021
2.854182
1.050396
cmd = ( [self.compiler_binary] + self.flags + ['-U'+x for x in self.undef] + ['-D'+x for x in self.define] + ['-I'+x for x in self.include_dirs] + self.sources ) if self.run_linker: cmd += (['-L'+x for x...
def cmd(self)
The command below covers most cases, if you need someting more complex subclass this.
3.102241
3.063646
1.012598
start = time.time() #Downsample the coordinates x1 = int(x1/config.DOWNSAMPLING) x2 = int(x2/config.DOWNSAMPLING) y1 = int(y1/config.DOWNSAMPLING) y2 = int(y2/config.DOWNSAMPLING) if not silent : print('drawing line from: '+str((x1,y1))+' to: '+str((x2,y2))) #Calculate the direction and the leng...
def drawLine(self, x1, y1, x2, y2, silent=False)
Draws a line on the current :py:class:`Layer` with the current :py:class:`Brush`. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param x1: Starting X coordinate. :param y1: Starting Y coordinate. :param x2: End X coordinate. :param y2: End Y coordinate. :rtype: Nothing.
3.845387
3.837172
1.002141
start = time.time() #Downsample the coordinates x = int(x/config.DOWNSAMPLING) y = int(y/config.DOWNSAMPLING) #Apply the dab with or without source caching if self.brush.usesSourceCaching: applyMirroredDab_jit(self.mirrorMode, self.image.getActiveLayer().data, int(x-self.brush.brushSize*0.5), int(y-...
def drawPoint(self, x, y, silent=True)
Draws a point on the current :py:class:`Layer` with the current :py:class:`Brush`. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param x1: Point X coordinate. :param y1: Point Y coordinate. :rtype: Nothing.
6.097693
6.113626
0.997394
self.drawLine(pointList[0][0], pointList[0][1], pointList[1][0], pointList[1][1]) i = 1 while i<len(pointList)-1: self.drawLine(pointList[i][0], pointList[i][1], pointList[i+1][0], pointList[i+1][1]) i+=1
def drawPath(self, pointList)
Draws a series of lines on the current :py:class:`Layer` with the current :py:class:`Brush`. No interpolation is applied to these point and :py:meth:`drawLine` will be used to connect all the points lineraly. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param pointList: A ...
1.511619
1.797997
0.840724
self.drawLine(pointList[0][0], pointList[0][1], pointList[1][0], pointList[1][1]) i = 1 while i<len(pointList)-1: self.drawLine(pointList[i][0], pointList[i][1], pointList[i+1][0], pointList[i+1][1]) i+=1 self.drawLine(pointList[-1][0], pointList[-1][1], pointList[0][0], pointList[0][1])
def drawClosedPath(self, pointList)
Draws a closed series of lines on the current :py:class:`Layer` with the current :py:class:`Brush`. No interpolation is applied to these point and :py:meth:`drawLine` will be used to connect all the points lineraly. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param pointL...
1.381362
1.523074
0.906957
vertices = [[x1,y1],[x2,y1],[x2,y2],[x1,y2],] rotatedVertices = rotateMatrix(vertices, (x1+x2)*0.5, (y1+y2)*0.5, angle) self.drawClosedPath(rotatedVertices)
def drawRect(self, x1, y1, x2, y2, angle=0)
Draws a rectangle on the current :py:class:`Layer` with the current :py:class:`Brush`. Coordinates are relative to the original layer size WITHOUT downsampling applied. :param x1: The X of the top-left corner of the rectangle. :param y1: The Y of the top-left corner of the rectangle. :param x2: The X of the ...
2.763214
3.092167
0.893617
layer = self.image.getActiveLayer().data colorRGBA = color.get_0_255() layer[:,:,0] = colorRGBA[0] layer[:,:,1] = colorRGBA[1] layer[:,:,2] = colorRGBA[2] layer[:,:,3] = colorRGBA[3]
def fillLayerWithColor(self, color)
Fills the current :py:class:`Layer` with the current :py:class:`Color`. :param color: The :py:class:`Color` to apply to the layer. :rtype: Nothing.
2.996165
3.546838
0.844742
width = int(width/config.DOWNSAMPLING) if color==None: color = self.color layer = self.image.getActiveLayer().data colorRGBA = color.get_0_255() print('adding border'+str(colorRGBA)+str(width)+str(layer.shape)) layer[0:width,:,0] = colorRGBA[0] layer[0:width,:,1] = colorRGBA[1] layer[0:width,:,2] ...
def addBorder(self, width, color=None)
Add a border to the current :py:class:`Layer`. :param width: The width of the border. :param color: The :py:class:`Color` of the border, current :py:class:`Color` is the default value. :rtype: Nothing.
1.583656
1.643794
0.963415
self.color = color if self.brush and self.brush.doesUseSourceCaching(): self.brush.cacheBrush(color)
def setColor(self, color)
Sets the current :py:class:`Color` to use. :param color: The :py:class:`Color` to use. :rtype: Nothing.
9.919446
13.743309
0.721765
if fixed!=None: self.color.set_alpha(fixed) elif proportional!=None: self.color.set_alpha(self.color.get_alpha()*proportional)
def setColorAlpha(self, fixed=None, proportional=None)
Change the alpha of the current :py:class:`Color`. :param fixed: Set the absolute 0-1 value of the alpha. :param proportional: Set the relative value of the alpha (Es: If the current alpha is 0.8, a proportional value of 0.5 will set the final value to 0.4). :rtype: Nothing.
2.130297
2.477833
0.859742
rgba = self.color.get_0_255() self.color = self.secondColor self.secondColor = Color(rgba, '0-255')
def swapColors(self)
Swaps the current :py:class:`Color` with the secondary :py:class:`Color`. :rtype: Nothing.
6.664065
7.38411
0.902487
if proportional!=None: resize = int(self.brush.brushSize*0.5) b.resizeBrush(resize) #If resize=0 it reset to its default size self.brush = b if self.brush and self.brush.doesUseSourceCaching(): self.brush.cacheBrush(self.color)
def setBrush(self, b, resize=0, proportional=None)
Sets the size of the current :py:class:`Brush`. :param brush: The :py:class:`Brush` object to use as a brush. :param resize: An optional absolute value to resize the brush before using it. :param proportional: An optional relative float 0-1 value to resize the brush before using it. :rtype: Nothing.
8.86478
9.879272
0.897311
assert (mirror=='' or mirror=='h' or mirror=='v' or mirror=='hv'or mirror=='vh'), 'setMirrorMode: wrong mirror mode, got '+str(mirror)+' expected one of ["","h","v","hv"]' #Round up all the coordinates and convert them to int if mirror=='': mirror = 0 elif mirror=='h': mirror = 1 elif mirror=='v': ...
def setMirrorMode(self, mirror)
Sets the mirror mode to use in the next operation. :param mirror: A string object with one of these values : '', 'h', 'v', 'hv'. "h" stands for horizontal mirroring, while "v" stands for vertical mirroring. "hv" sets both at the same time. :rtype: Nothing.
3.666192
3.536907
1.036553
#Merge all the layers to apply blending modes resultLayer = self.image.mergeAllLayers() #Show and save the results img = PIL.Image.fromarray(resultLayer.data, 'RGBA') if show: img.show() if output!='': img.save(output, 'PNG')
def renderImage(self, output='', show=True)
Renders the :py:class:`Image` and outputs the final PNG file. :param output: A string with the output file path, can be empty if you don't want to save the final image. :param show: A boolean telling the system to display the final image after the rendering is done. :rtype: Nothing.
5.309211
5.700545
0.931351
self.image.layers[self.image.activeLayer].effect = effect
def setActiveLayerEffect(self, effect)
Changes the effect of the current active :py:class:`Layer`. :param output: A string with the one of the blend modes listed in :py:meth:`newLayer`. :rtype: Nothing.
6.234038
8.813548
0.707324
import hashlib sha = hashlib.sha512() if not os.path.exists(directory): return -1 for root, _, files in os.walk(directory): for name in files: filepath = local.path(root) / name if filepath.exists(): with open(filepath, 'rb') as next_file: ...
def get_hash_of_dirs(directory)
Recursively hash the contents of the given directory. Args: directory (str): The root directory we want to hash. Returns: A hash of all the contents in the directory.
2.80305
2.92587
0.958023
if not src_file.exists(): return True required = True hash_file = src_file.with_suffix(".hash", depth=0) LOG.debug("Hash file location: %s", hash_file) if hash_file.exists(): new_hash = get_hash_of_dirs(src_file) with open(hash_file, 'r') as h_file: old_hash...
def source_required(src_file)
Check, if a download is required. Args: src_file: The filename to check for. src_root: The path we find the file in. Returns: True, if we need to download something, False otherwise.
3.256939
3.470254
0.93853
hash_file = local.path(src_file) + ".hash" new_hash = 0 with open(hash_file, 'w') as h_file: new_hash = get_hash_of_dirs(src_file) h_file.write(str(new_hash)) return new_hash
def update_hash(src_file)
Update the hash for the given file. Args: src: The file name. root: The path of the given file.
3.158163
4.17629
0.756213
from benchbuild.utils.cmd import cp cp("-ar", "--reflink=auto", From, To)
def Copy(From, To)
Small copy wrapper. Args: From (str): Path to the SOURCE. To (str): Path to the TARGET.
10.072216
12.81155
0.786182
if root is None: root = str(CFG["tmp_dir"]) src_path = local.path(root) / src if src_path.exists(): Copy(src_path, '.') return True return False
def CopyNoFail(src, root=None)
Just copy fName into the current working directory, if it exists. No action is executed, if fName does not exist. No Hash is checked. Args: src: The filename we want to copy to '.'. root: The optional source dir we should pull fName from. Defaults to benchbuild.settings.CFG["tmpdir...
4.959054
4.276943
1.159486
if tgt_root is None: tgt_root = str(CFG["tmp_dir"]) from benchbuild.utils.cmd import wget tgt_file = local.path(tgt_root) / tgt_name if not source_required(tgt_file): Copy(tgt_file, ".") return wget(src_url, "-O", tgt_file) update_hash(tgt_file) Copy(tgt_file,...
def Wget(src_url, tgt_name, tgt_root=None)
Download url, if required. Args: src_url (str): Our SOURCE url. tgt_name (str): The filename we want to have on disk. tgt_root (str): The TARGET directory for the download. Defaults to ``CFG["tmpdir"]``.
4.869529
4.676353
1.041309
def wget_decorator(cls): def download_impl(self): t_file = target_file if target_file else self.SRC_FILE t_version = url_dict[self.version] Wget(t_version, t_file) @staticmethod def versions_impl(): return list(...
def with_wget(url_dict=None, target_file=None)
Decorate a project class with wget-based version information. This adds two attributes to a project class: - A `versions` method that returns a list of available versions for this project. - A `repository` attribute that provides a repository string to download from later. W...
4.779182
3.349502
1.426833
repository_loc = str(prefix) if prefix is None: repository_loc = str(CFG["tmp_dir"]) from benchbuild.utils.cmd import git src_dir = local.path(repository_loc) / directory if not source_required(src_dir): Copy(src_dir, ".") return extra_param = [] if shallow_cl...
def Git(repository, directory, rev=None, prefix=None, shallow_clone=True)
Get a clone of the given repo Args: repository (str): Git URL of the SOURCE repo. directory (str): Name of the repo folder on disk. tgt_root (str): TARGET folder for the git repo. Defaults to ``CFG["tmpdir"]`` shallow_clone (bool): Only clone the repository shallow ...
3.952429
4.208469
0.939161
if not rev_list_args: rev_list_args = [] def git_decorator(cls): from benchbuild.utils.cmd import git @staticmethod def versions_impl(): directory = cls.SRC_FILE if target_dir is None else target_dir repo_prefix = local.path(str(CFG["tm...
def with_git(repo, target_dir=None, limit=None, refspec="HEAD", clone=True, rev_list_args=None, version_filter=lambda version: True)
Decorate a project class with git-based version information. This adds two attributes to a project class: - A `versions` method that returns a list of available versions for this project. - A `repository` attribute that provides a repository string to download from later. We...
3.487255
3.191044
1.092826
if to is None: to = str(CFG["tmp_dir"]) src_dir = local.path(to) / fname if not source_required(src_dir): Copy(src_dir, ".") return from benchbuild.utils.cmd import svn svn("co", url, src_dir) update_hash(src_dir) Copy(src_dir, ".")
def Svn(url, fname, to=None)
Checkout the SVN repo. Args: url (str): The SVN SOURCE repo. fname (str): The name of the repo on disk. to (str): The name of the TARGET folder on disk. Defaults to ``CFG["tmpdir"]``
6.04655
5.529062
1.093594
if tgt_root is None: tgt_root = str(CFG["tmp_dir"]) from benchbuild.utils.cmd import rsync tgt_dir = local.path(tgt_root) / tgt_name if not source_required(tgt_dir): Copy(tgt_dir, ".") return rsync("-a", url, tgt_dir) update_hash(tgt_dir) Copy(tgt_dir, ".")
def Rsync(url, tgt_name, tgt_root=None)
RSync a folder. Args: url (str): The url of the SOURCE location. fname (str): The name of the TARGET. to (str): Path of the target location. Defaults to ``CFG["tmpdir"]``.
4.886323
4.985744
0.980059
return CAMEL_CASE_RE.sub(r'_\1', s).strip().lower()
def camel_to_snake(s: str) -> str
Convert string from camel case to snake case.
8.70999
6.294324
1.383785
fragments = s.split('_') return fragments[0] + ''.join(x.title() for x in fragments[1:])
def snake_to_camel(s: str) -> str
Convert string from snake case to camel case.
4.419508
3.408807
1.296497
metrics_dict = {} # group entries by `category` attribute (default is "standard") for metric, config in six.iteritems(metrics): category = config.get('category', StdBenchmark.DEFAULT_CATEGORY) metrics_dict.setdefault(category, {})[metric] = config # creat...
def _create_extractors(cls, metrics)
Build metrics extractors according to the `metrics` config :param metrics: Benchmark `metrics` configuration section
6.032343
5.879871
1.025931
return dict( (name, getattr(Metrics, config['type'])) for name, config in six.iteritems(self._metrics) )
def metrics(self)
:return: Description of metrics extracted by this class
8.84923
8.532859
1.037077
eax = {} for name, config in six.iteritems(self._metrics): from_ = self._get_property(config, 'from', default=self.stdout) eax.setdefault(from_, {})[name] = config return eax
def froms(self)
Group metrics according to the `from` property.
11.03481
6.855884
1.609539
''' Tesselate each shape path into one or more triangles. Parameters ---------- df_shapes : pandas.DataFrame Table containing vertices of shapes, one row per vertex, with the *at least* the following columns: - ``x``: The x-coordinate of the vertex. - ``y``: The y-...
def tesselate_shapes_frame(df_shapes, shape_i_columns)
Tesselate each shape path into one or more triangles. Parameters ---------- df_shapes : pandas.DataFrame Table containing vertices of shapes, one row per vertex, with the *at least* the following columns: - ``x``: The x-coordinate of the vertex. - ``y``: The y-coordinate o...
3.507612
1.888971
1.85689
stdout = sys.stdout sys.stdout = six.moves.cStringIO() try: yield sys.stdout finally: sys.stdout = stdout
def capture_stdout()
Intercept standard output in a with-context :return: cStringIO instance >>> with capture_stdout() as stdout: ... print stdout.getvalue()
2.72422
4.002268
0.680669
cwd = os.getcwd() exists = osp.exists(path) if mkdir and not exists: os.makedirs(path) os.chdir(path) try: yield path finally: os.chdir(cwd) if not exists and cleanup: # NB: should we be checking for rmtree.avoids_symlink_attacks ? shu...
def pushd(path, mkdir=True, cleanup=False)
Change current working directory in a with-context :param mkdir: If True, then directory is created if it does not exist :param cleanup: If True and no pre-existing directory, the directory is cleaned up at the end
3.790575
4.313459
0.878778
remove = kwargs.pop('remove', True) path = tempfile.mkdtemp(*args, **kwargs) try: yield path finally: if remove: shutil.rmtree(path)
def mkdtemp(*args, **kwargs)
Create a temporary directory in a with-context keyword remove: Remove the directory when leaving the context if True. Default is True. other keywords arguments are given to the tempfile.mkdtemp function.
2.278622
2.66325
0.85558
if self.end is None: return self() - self.end return self.end - self.start
def elapsed(self)
:return: duration in seconds spent in the context. :rtype: float
9.488071
8.446852
1.123267
import re import unicodedata value = str(value) value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('utf8').strip().lower() value = re.sub(r'[^\w\s\-\.]', '', value) value = re.sub(r'[-\s]+', '-', value) return value
def slugify(value)
Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens.type(
1.725575
1.749701
0.986212
" Import an obect as either a fully qualified, dotted name, " if isinstance(name, str): # for "a.b.c.d" -> [ 'a.b.c', 'd' ] module_name, object_name = name.rsplit('.',1) # __import__ loads the multi-level of module, but returns # the top level, which we have to descend into ...
def import_name_or_class(name)
Import an obect as either a fully qualified, dotted name,
6.3823
5.063924
1.260347
version = version or hpcbench.__version__ version = str(version) if '.dev' in version: git_rev = 'master' if 'TRAVIS_BRANCH' in os.environ: git_rev = version.split('+', 1)[-1] if '.' in git_rev: # get rid of date suffix git_rev = git_rev.split('....
def pip_installer_url(version=None)
Get argument to give to ``pip`` to install HPCBench.
3.746686
3.238939
1.156763
realpath = osp.realpath(campaign_file) if osp.isdir(realpath): campaign_file = osp.join(campaign_file, YAML_CAMPAIGN_FILE) campaign = Configuration.from_file(campaign_file) return default_campaign(campaign, **kwargs)
def from_file(campaign_file, **kwargs)
Load campaign from YAML file :return: memory representation of the YAML file :rtype: dictionary
3.985864
4.556065
0.874848
campaign = campaign or nameddict() def _merger(_camp, _deft): for key in _deft.keys(): if ( key in _camp and isinstance(_camp[key], dict) and isinstance(_deft[key], collections.Mapping) ): _merger(_camp[key], _...
def default_campaign( campaign=None, expandcampvars=True, exclude_nodes=None, frozen=True )
Fill an existing campaign with default values for optional keys :param campaign: dictionary :type campaign: str :param exclude_nodes: node set to exclude from allocations :type exclude_nodes: str :param expandcampvars: should env variables be expanded? True by default :type expandcampvars: ...
3.027021
3.253504
0.930388
for benchmarks in campaign.benchmarks.values(): for name, benchmark in benchmarks.items(): if name != 'sbatch': # exclude special sbatch name yield benchmark.type
def get_benchmark_types(campaign)
Get of benchmarks referenced in the configuration :return: benchmarks :rtype: string generator
8.195248
8.823177
0.928832
if top and campaign.process.type == 'slurm': for path, _ in report.collect('jobid', with_path=True): for child in ReportNode(path).children.values(): for metrics in get_metrics(campaign, child, top=False): yield metrics else: def metrics_node...
def get_metrics(campaign, report, top=True)
Extract metrics from existing campaign :param campaign: campaign loaded with `hpcbench.campaign.from_file` :param report: instance of `hpcbench.campaign.ReportNode` :param top: this function is recursive. This parameter help distinguishing top-call.
4.799615
4.595156
1.044495
render( self.template, file, benchmarks=self.benchmarks, hostname=socket.gethostname(), )
def write(self, file)
Write YAML campaign template to the given open file
9.722324
10.855211
0.895637
if self.slurm: self._introspect_slurm_cluster() self.network.nodes = self._expand_nodes(self.network.nodes) self._expand_tags()
def expand(self)
Perform node expansion of network section.
9.354709
7.285761
1.283971
lhs_yaml = osp.join(self.lhs, 'campaign.yaml') rhs_yaml = osp.join(self.rhs, 'campaign.yaml') assert osp.isfile(lhs_yaml) assert osp.isfile(rhs_yaml) assert filecmp.cmp(lhs_yaml, rhs_yaml)
def ensure_has_same_campaigns(self)
Ensure that the 2 campaigns to merge have been generated from the same campaign.yaml
2.787882
2.227333
1.251668
prefix = os.path.commonprefix([path, self._path]) relative_path = path[len(prefix) :] relative_path = relative_path.strip(os.sep) attrs = self.CONTEXT_ATTRS for i, elt in enumerate(relative_path.split(os.sep)): yield attrs[i], elt yield 'path', path
def path_context(self, path)
Build of dictionary of fields extracted from the given path
4.057899
4.129652
0.982625
for child in self.data.get('children', []): if osp.exists(osp.join(self.path, child, YAML_REPORT_FILE)): yield child, self.__class__(osp.join(self.path, child))
def children(self)
get children node referenced as `children` in the report. :rtype: dict with name (str) -> node (ReportNode)
4.507988
4.153183
1.08543
if kwargs.get('with_path', False): yield self.path, func(self) if kwargs.get('recursive', True): for child in self.children.values(): for value in child.map(func, **kwargs): yield value
def map(self, func, **kwargs)
Generator function returning result of `func(self)` :param func: callable object :keyword recursive: if True, then apply map to every children nodes :keyword with_path: whether the yield values is a tuple of 2 elements containing report-path and `func(self)` result or si...
3.305311
2.867992
1.152483
if not keys: raise Exception('Missing key') has_values = functools.reduce( operator.__and__, [key in self.data for key in keys], True ) if has_values: values = tuple([self.data[key] for key in keys]) if len(values) == 1: ...
def collect(self, *keys, **kwargs)
Generator function traversing tree structure to collect values of a specified key. :param keys: the keys to look for in the report :type key: str :keyword recursive: look for key in children nodes :type recursive: bool :keyword with_path: whether the yield values is a tu...
2.642476
2.614893
1.010548
generator = self.collect(*args, **kwargs) try: value = next(generator) except StopIteration: raise Exception("Expected exactly one value don't have any") try: next(generator) except StopIteration: return value raise...
def collect_one(self, *args, **kwargs)
Same as `collect` but expects to have only one result. :return: the only result directly, not the generator like `collect`.
3.798039
3.499445
1.085326
values = np.array(values) if repeat == "up": assert len(values.shape) == 1 values = [values for ss in range(self.n_storeys)] else: assert len(values.shape) == 2 if len(values[0]) != self.n_bays: raise ModelError("beam depths does n...
def set_beam_prop(self, prop, values, repeat="up")
Specify the properties of the beams :param values: :param repeat: if 'up' then duplicate up the structure :return:
3.132813
3.346853
0.936047
values = np.array(values) if repeat == "up": assert len(values.shape) == 1 values = [values for ss in range(self.n_storeys)] else: assert len(values.shape) == 2 if len(values[0]) != self.n_cols: raise ModelError("column props does ...
def set_column_prop(self, prop, values, repeat="up")
Specify the properties of the columns :param values: :param repeat: if 'up' then duplicate up the structure :return:
3.175332
3.424753
0.927171
with open(path) as f: self.config = full_load(f) if self.config is None: sys.stderr.write("Warning: config file is empty!\n") self.config = {}
def load(self, path)
Load yaml-formatted config file. Parameters ---------- path : str path to config file
3.878097
4.02494
0.963517
with open(self.config_file, "w") as f: f.write(dump(self.config, default_flow_style=False))
def save(self)
Save current state of config dictionary.
3.104908
2.727695
1.13829
self._extensions[extension_name] = extension self.ROUTES.extend([ tuple(list(t) + [extension_name]) for t in extension.ROUTES ]) self.CACHED.extend([ (f_name, extension_name) for f_name in extension.CACHED ]) # Thi...
def register(self, extension, extension_name)
Register an extension into the Nautilus Router :param extension: Extension :param extension_name: Name of the Extension :return:
4.085293
4.498795
0.908086
self.logger = logger if logger is None: self.logger = logging.getLogger("capitains_nautilus") formatter = logging.Formatter("[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s") stream = FlaskNautilus.LoggingHandler() stream.setLe...
def setLogger(self, logger)
Set up the Logger for the application :param logger: logging.Logger object :return: Logger instance
3.365943
3.424654
0.982856
self.init_blueprint(app) if self.flaskcache is not None: for func, extension_name in self.CACHED: func = getattr(self._extensions[extension_name], func) setattr( self._extensions[extension_name], func.__name__...
def init_app(self, app)
Initiate the extension on the application :param app: Flask Application :return: Blueprint for Flask Nautilus registered in app :rtype: Blueprint
5.688128
5.634618
1.009497
self.blueprint = Blueprint( self.name, self.name, template_folder=resource_filename("capitains_nautilus", "data/templates"), url_prefix=self.prefix ) # Register routes for url, name, methods, extension_name in self.ROUTES: ...
def init_blueprint(self, app)
Properly generates the blueprint, registering routes and filters and connecting the app and the blueprint :return: Blueprint of the extension :rtype: Blueprint
3.739248
3.70495
1.009257
if isinstance(self.Access_Control_Allow_Origin, dict): d = { "Access-Control-Allow-Origin": self.Access_Control_Allow_Origin[function_name], "Access-Control-Allow-Methods": self.Access_Control_Allow_Methods[function_name] } else: ...
def view(self, function_name, extension_name)
Builds response according to a function name :param function_name: Route name / function name :param extension_name: Name of the extension holding the function :return: Function
2.241264
2.282449
0.981956
benchbuild_c = local[local.path(sys.argv[0])] slurm_script = local.cwd / experiment.name + "-" + str( CFG['slurm']['script']) srun = local["srun"] srun_args = [] if not CFG["slurm"]["multithread"]: srun_args.append("--hint=nomultithread") if not CFG["slurm"]["turbo"]: ...
def script(experiment, projects)
Prepare a slurm script that executes the experiment for a given project. Args: experiment: The experiment we want to execute projects: All projects we generate an array job for.
5.87263
6.474451
0.907047
structure = { "urn": urn, "provenance": endpoint, "valid_reffs": {} } orig_edition = None suffix = 'grc' if 'greekLit' in urn else 'lat' resolver = HttpCtsResolver(HttpCtsRetriever(endpoint)) work_metadata = resolver.getMetadata(urn) # among all editions for t...
def fetch_text_structure(urn, endpoint="http://cts.perseids.org/api/cts")
Fetches the text structure of a given work from a CTS endpoint. :param urn: the work's CTS URN (at the work-level!, e.g."urn:cts:greekLit:tlg0012.tlg001") :type urn: string :param endpoint: the URL of the CTS endpoint to use (defaults to Perseids') :type endpoint: string :return: a dict wit...
4.56712
4.053251
1.126779
project.runtime_extension = run.RuntimeExtension(project, self) return self.default_runtime_actions(project)
def actions_for_project(self, project)
Execute all actions but don't do anything as extension.
15.902797
14.30547
1.111658
builddir = local.path(str(CFG["build_dir"].value)) with local.cwd(builddir): erlent_src = local.path('erlent') erlent_git = erlent_src / '.git' erlent_repo = str(CFG['uchroot']['repo']) erlent_build = erlent_src / 'build' if not erlent_git.exists(): git("...
def install_uchroot(_)
Installer for erlent (contains uchroot).
3.265451
3.070529
1.063482
num_failed = len(failed) print(.format( num_total=num_actions, num_failed=num_failed, elapsed_time=duration))
def print_summary(num_actions, failed, duration)
Print a small summary of the executed plan. Args: num_actions (int): Total size of the executed plan. failed (:obj:`list` of :obj:`actions.Step`): List of failed actions. duration: Time we spent executing the plan.
6.199757
7.296389
0.849702
sensor_path = ffp si = json.load(open(sensor_path)) for m_type in si: # Convert keys from strings to integers si[m_type] = {int(k): v for k, v in si[m_type].items()} return si
def read_json_sensor_file(ffp)
Reads the sensor file and stores it as a dictionary. :param ffp: full file path to json file :return:
3.613245
4.056591
0.89071
mtype_and_ory, x, y, z = wild_sensor_code.split("-") if mtype_and_ory == "*": mtypes = list(si) elif mtype_and_ory[-1] in "XYZ" and "ACCX" not in si: # Need to support old sensor_file.json files. mtypes = [mtype_and_ory[:-1]] else: mtypes = [mtype_and_ory] all_sensor_c...
def get_all_sensor_codes(si, wild_sensor_code)
Get all sensor sensor_codes that match a wild sensor code :param si: dict, sensor index json dictionary :param wild_sensor_code: str, a sensor code with "*" for wildcards (e.g. ACCX-*-L2C-*) :return:
3.266208
3.088017
1.057704
try: if 'Orientation' in si[mtype][sensor_number]: orientation = si[mtype][sensor_number]['Orientation'] else: orientation = "" return "%s%s-%s-%s-%s" % (mtype, orientation, si[mtype][sensor_number][...
def get_sensor_code_by_number(si, mtype, sensor_number, quiet=False)
Given a sensor number, get the full sensor code (e.g. ACCX-UB1-L2C-M) :param si: dict, sensor index json dictionary :param mtype: str, sensor type :param sensor_number: int, number of sensor :param quiet: bool, if true then return None if not found :return: str or None, sensor_code: a sensor code (...
2.583072
2.350428
1.098979
mtype_and_ory, x, y, z = sensor_code.split("-") if mtype_and_ory[-1] in "XYZ" and "ACCX" not in si: # Need to support old sensor_file.json files. mtype = mtype_and_ory[:-1] else: mtype = mtype_and_ory for m_number in si[mtype]: cc = get_sensor_code_by_number(si, mtype, m_nu...
def get_mtype_and_number_from_code(si, sensor_code)
Given a sensor sensor_code, get motion type and sensor number :param si: dict, sensor index json dictionary :param sensor_code: str, a sensor code (e.g. ACCX-UB1-L2C-M) :return:
4.789797
4.468401
1.071926
vals = {} intercept = { 'build_callbacks': (), # tuple of (callback, args, kwargs) 'link_ext': True, 'build_files': (), 'dist_files': (), # work around stackoverflow.com/questions/2994396/ 'template_regexps': [], 'pass_extra_compile_args': False, # use di...
def PCExtension(*args, **kwargs)
Parameters ========== template_regexps: list of 3-tuples e.g. [(pattern1, target1, subsd1), ...], used to generate templated code pass_extra_compile_args: bool should ext.extra_compile_args be passed along? default: False
4.492595
4.020853
1.117324
# Either render a template or copy the source dirname = os.path.dirname(f) filename = os.path.basename(f) for pattern, target, subsd in ext.template_regexps: if re.match(pattern, filename): tgt = os.path.join(dirname, re.sub( pattern, target, filename)) ...
def _copy_or_render_source(ext, f, output_dir, render_callback, skip_copy=False)
Tries to do regex match for each (pattern, target, subsd) tuple in ext.template_regexps for file f.
3.316475
2.868131
1.156319