text
stringlengths
81
112k
Perform node expansion of network section. def expand(self): """Perform node expansion of network section. """ if self.slurm: self._introspect_slurm_cluster() self.network.nodes = self._expand_nodes(self.network.nodes) self._expand_tags()
Ensure that the 2 campaigns to merge have been generated from the same campaign.yaml def ensure_has_same_campaigns(self): """Ensure that the 2 campaigns to merge have been generated from the same campaign.yaml """ lhs_yaml = osp.join(self.lhs, 'campaign.yaml') rhs_yaml =...
Build of dictionary of fields extracted from the given path def path_context(self, path): """Build of dictionary of fields extracted from the given path""" prefix = os.path.commonprefix([path, self._path]) relative_path = path[len(prefix) :] relative_path = relative_path...
get children node referenced as `children` in the report. :rtype: dict with name (str) -> node (ReportNode) def children(self): """get children node referenced as `children` in the report. :rtype: dict with name (str) -> node (ReportNode) """ for child in self.da...
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...
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...
Same as `collect` but expects to have only one result. :return: the only result directly, not the generator like `collect`. 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`. ...
Specify the properties of the beams :param values: :param repeat: if 'up' then duplicate up the structure :return: def set_beam_prop(self, prop, values, repeat="up"): """ Specify the properties of the beams :param values: :param repeat: if 'up' then duplicate u...
Specify the properties of the columns :param values: :param repeat: if 'up' then duplicate up the structure :return: def set_column_prop(self, prop, values, repeat="up"): """ Specify the properties of the columns :param values: :param repeat: if 'up' then dupli...
Load yaml-formatted config file. Parameters ---------- path : str path to config file def load(self, path): """ Load yaml-formatted config file. Parameters ---------- path : str path to config file """ with open(...
Save current state of config dictionary. def save(self): """ Save current state of config dictionary. """ with open(self.config_file, "w") as f: f.write(dump(self.config, default_flow_style=False))
Register an extension into the Nautilus Router :param extension: Extension :param extension_name: Name of the Extension :return: def register(self, extension, extension_name): """ Register an extension into the Nautilus Router :param extension: Extension :param extensi...
Set up the Logger for the application :param logger: logging.Logger object :return: Logger instance def setLogger(self, logger): """ Set up the Logger for the application :param logger: logging.Logger object :return: Logger instance """ self.logger = logger ...
Initiate the extension on the application :param app: Flask Application :return: Blueprint for Flask Nautilus registered in app :rtype: Blueprint def init_app(self, app): """ Initiate the extension on the application :param app: Flask Application :return: Blueprint for...
Properly generates the blueprint, registering routes and filters and connecting the app and the blueprint :return: Blueprint of the extension :rtype: Blueprint def init_blueprint(self, app): """ Properly generates the blueprint, registering routes and filters and connecting the app and the blu...
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 def view(self, function_name, extension_name): """ Builds response according to a function name :pa...
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. def script(experiment, projects): """ Prepare a slurm script that executes the experiment for a given project. ...
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...
Execute all actions but don't do anything as extension. def actions_for_project(self, project): """Execute all actions but don't do anything as extension.""" project.runtime_extension = run.RuntimeExtension(project, self) return self.default_runtime_actions(project)
Installer for erlent (contains uchroot). def install_uchroot(_): """Installer for erlent (contains uchroot).""" 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['uchr...
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. def print_summary(num_actions, failed, duration): """ Print a small...
Reads the sensor file and stores it as a dictionary. :param ffp: full file path to json file :return: 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: """ sensor_path = ffp si = json.load(open...
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: def get_all_sensor_codes(si, wild_sensor_code): """ Get all sensor sensor_codes that match a wild ...
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 (...
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: def get_mtype_and_number_from_code(si, sensor_code): """ Given a sensor sensor_code, get motion type and sensor number ...
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 def PCExtension(*args, **kwargs): """ Parameters ...
Tries to do regex match for each (pattern, target, subsd) tuple in ext.template_regexps for file f. 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 fo...
Overload this function if you want to use a template engine such as e.g. mako. def render_python_template_to(src, dest, subsd, only_update=False, prev_subsd=None, create_dest_dirs=True, logger=None): """ Overload this function if you w...
Returns a dict where key is the language and value is the name in that language. Example: {'it':"Sofocle"} def get_names(self): """ Returns a dict where key is the language and value is the name in that language. Example: {'it':"Sofocle"} """ na...
Adds a new name variant to an author. :param name: the name to be added :param lang: the language of the name variant :return: `True` if the name is added, `False` otherwise (the name is a duplicate) def add_name(self, name, lang=None): """ Adds a new name variant to an author....
Adds a new name variant to an author. :param new_abbreviation: the abbreviation to be added :return: `True` if the abbreviation is added, `False` otherwise (the abbreviation is a duplicate) def add_abbreviation(self, new_abbreviation): """ Adds a new name variant to an author. ...
Get abbreviations of the names of the author. :return: a list of strings (empty list if no abbreviations available). def get_abbreviations(self): """ Get abbreviations of the names of the author. :return: a list of strings (empty list if no abbreviations available). """ ...
Assumes that each HucitAuthor has only one CTS URN. def get_urn(self): """ Assumes that each HucitAuthor has only one CTS URN. """ # TODO: check type try: type_ctsurn = self.session.get_resource(BASE_URI_TYPES % "CTS_URN" ...
Change the CTS URN of the author or adds a new one (if no URN is assigned). def set_urn(self,urn): """ Change the CTS URN of the author or adds a new one (if no URN is assigned). """ Type = self.session.get_class(surf.ns.ECRM['E55_Type']) Identifier = self.session.get_class(surf...
Serialises a HucitAuthor to a JSON formatted string. Example: >> homer = kb.get_resource_by_urn("urn:cts:greekLit:tlg0012") >> homer.to_json() { "name_abbreviations": [ "Hom." ], "urn": "urn:cts:greekLit:tlg0012", "works": [ ...
TODO def get_titles(self): """TODO""" return [(label.language, unicode(label)) for label in self.efrbroo_P102_has_title.first.rdfs_label]
TODO: if `combine==True`, concatenate with author abbreviation(s) Get abbreviations of the titles of the work. :return: a list of strings (empty list if no abbreviations available). def get_abbreviations(self, combine=False): """ TODO: if `combine==True`, concatenate with author abbre...
Adds a citable text structure to the work. def add_text_structure(self, label): """ Adds a citable text structure to the work. """ ts = self.session.get_resource("%s/text_structure" % self.subject , self.session.get_class(surf.ns.HUCIT['TextStructu...
Remove any citable text structure to the work. def remove_text_structure(self, text_structure): # TODO: delete also TextElements one by one """ Remove any citable text structure to the work. """ idx = self.hucit_has_structure.index(text_structure) ts = self.hucit_has_structure.p...
Instantiate an opus maximum type. def _get_opus_maximum(self): """Instantiate an opus maximum type.""" label = """The opux maximum of a given author that is, the only preserved work by that author or the most known one.""" opmax = self.session.get_resour...
Mark explicitly the work as the author's opus maximum. def set_as_opus_maximum(self): # TODO: test """Mark explicitly the work as the author's opus maximum.""" if self.is_opus_maximum(): return False else: opmax = self._get_opus_maximum() self.ecrm_P2_has_ty...
Check whether the work is the author's opus maximum. Two cases: 1. the work is flagged as opus max 2. there is only one work by this author :return: boolean def is_opus_maximum(self): """Check whether the work is the author's opus maximum. Two cases: 1. the wo...
Returns the author to whom the work is attributed. :return: an instance of `HucitWork` # TODO: check that's the case def author(self): """ Returns the author to whom the work is attributed. :return: an instance of `HucitWork` # TODO: check that's the case """ CreationE...
Serialises a HucitWork to a JSON formatted string. def to_json(self): """ Serialises a HucitWork to a JSON formatted string. """ titles = self.get_titles() return json.dumps({ "uri" : self.subject , "urn" : str(self.get_urn()) , "t...
TODO def get_urn(self): """ TODO """ urn = self.ecrm_P1_is_identified_by.one try: return CTS_URN(urn) except Exception, e: raise e
get nodes that belong to a tag :param tag: tag name :rtype: list of string def nodes(self, tag): """get nodes that belong to a tag :param tag: tag name :rtype: list of string """ if tag == '*': return sorted(list(set(self.campaign.network.nodes))) ...
Get execution layer class def execution_cls(self): """Get execution layer class """ name = self.campaign.process.type for clazz in [ExecutionDriver, SrunExecutionDriver]: if name == clazz.name: return clazz raise NameError("Unknown execution layer: '%...
Retrieve tags associated to the current node def children(self): """Retrieve tags associated to the current node""" tags = {'*'} if self.tag: network_tags = {self.tag: self.campaign.network.tags[self.tag]} else: network_tags = self.campaign.network.tags f...
Setter for **self.__activated** attribute. :param value: Attribute value. :type value: bool def activated(self, value): """ Setter for **self.__activated** attribute. :param value: Attribute value. :type value: bool """ if value is not None: ...
Setter for **self.__initialized** attribute. :param value: Attribute value. :type value: bool def initialized(self, value): """ Setter for **self.__initialized** attribute. :param value: Attribute value. :type value: bool """ if value is not None: ...
Sets Component activation state. :return: Method success. :rtype: bool def activate(self): """ Sets Component activation state. :return: Method success. :rtype: bool """ raise NotImplementedError("{0} | '{1}' must be implemented by '{2}' subclasses!".f...
get nodes of every reservations def reservations(self): """get nodes of every reservations""" command = [SINFO, '--reservation'] output = subprocess.check_output(command, env=SINFO_ENV) output = output.decode() it = iter(output.splitlines()) next(it) for line in ...
Set the object parameters using a dictionary def set(self, values): """ Set the object parameters using a dictionary """ if hasattr(self, "inputs"): for item in self.inputs: if hasattr(self, item): setattr(self, item, values[item])
Execute the plan. Args: plan (:obj:`list` of :obj:`actions.Step`): The plan we want to execute. Returns: (:obj:`list` of :obj:`actions.Step`): A list of failed actions. def execute_plan(plan): """"Execute the plan. Args: plan (:obj:`list` of :obj:`actions.Step`): The plan we ...
Set log format :param color: Log message is colored :param include_caller: At the end, put a [caller:line-of-code], e.g. [script:123] :return: string of log format def _set_log_format(color, include_caller): """ Set log format :param color: Log message is colored :param include_caller: At t...
Setup logzero logger. if logfile is specified, create additional file logger :param logfile: path to log file destination :param backup_count: number of rotating files :param log_level: min. log level FOR FILE LOGGING :param include_caller: whether to include the caller in the log output to STDOUT, e.g....
Format an object's repr method with specific attributes. def format_repr(obj, attributes) -> str: """Format an object's repr method with specific attributes.""" attribute_repr = ', '.join(('{}={}'.format(attr, repr(getattr(obj, attr))) for attr in attributes)) return "{0}({...
Creates a list of the decription of all the inputs of an object :param obj: object, that has parameters :param user_p: dict, user defined parameter descriptions :param show_none: if false, only shows descriptions of parameters that are not None :param ignore: list of parameters to not build :return...
Generates a list of descriptions of all the models :return: def all_descriptions(): """ Generates a list of descriptions of all the models :return: """ para = [] para += build_parameter_descriptions(models.Soil()) + [",,\n"] para += build_parameter_descriptions(models.SoilProfile()) +...
Plot shapes from table/data-frame where each row corresponds to a vertex of a shape. Shape vertices are grouped by `shape_i_columns`. For example, consider the following dataframe: shape_i vertex_i x y 0 0 0 81.679949 264.69306 1 0 1 8...
Plot polygon shapes, colored based on values mapped onto a colormap. Args ---- df_shapes (pandas.DataFrame) : Polygon table containing the columns `'id', 'x', 'y'`. Coordinates must be ordered to be grouped by `'id'`. values (pandas.Series) : Numeric values indexed...
Plot bar for each value in `values`, colored based on values mapped onto the specified color map. Args ---- values (pandas.Series) : Numeric values to plot one bar per value. axis : A matplotlib axis. If `None`, an axis is created. vmin : Minimum value to clip values at. v...
Find an executable is a list of directories :return: absolute path to the first location where the executable is found, ``None`` otherwise. :rtype: string def find_in_paths(name, paths): """Find an executable is a list of directories :return: absolute path to the first location where the executable...
Utility function to find an executable in PATH name: program to find. Use given value if absolute path names: list of additional names. For instance >>> find_executable('sed', names=['gsed']) required: If True, then the function raises an Exception if the program is not found else the function...
Get cpus identifiers, for instance set(["0", "1", "2", "3"]) :return Number of physical CPUs available :rtype: int def physical_cpus(): """Get cpus identifiers, for instance set(["0", "1", "2", "3"]) :return Number of physical CPUs available :rtype: int """ if platform.system() == 'Darwin...
Shows the single layer. :param title: A string with the title of the window where to render the image. :param debugText: A string with some text to render over the image. :rtype: Nothing. def showLayer(self, title='', debugText=''): """ Shows the single layer. :param title: A string with the title of...
Return a mapping between data type names, and casting functions, or class definitions to convert text into its Python object. Parameters ---------- data_types: dict-like data field name str: python primitive type or class. Example ------- >> make_converters({'student': str, 'score': ...
Parses broken JSON that the standard Python JSON module cannot parse. Ex: {success:true} Keys do not contain quotes and the JSON cannot be parsed using the regular json encoder. YAML happens to be a superset of JSON and can parse json without quotes. def parse_broken_json(json_text: str) -> dict: """...
Create shell-script in charge of executing the benchmark and return its path. def _executor_script(self): """Create shell-script in charge of executing the benchmark and return its path. """ fd, path = tempfile.mkstemp(suffix='.sh', dir=os.getcwd()) os.close(fd) ...
:return Jinja template of the shell-script executor def _jinja_executor_template(self): """:return Jinja template of the shell-script executor""" template = self.campaign.process.executor_template if template.startswith('#!'): return jinja_environment.from_string(template) e...
Write shell script in charge of executing the command def _write_executor_script(self, ostr): """Write shell script in charge of executing the command""" environment = self.execution.get('environment') or {} if not isinstance(environment, Mapping): msg = 'Expected mapping for enviro...
:return command to execute inside the generated shell-script def command(self): """:return command to execute inside the generated shell-script""" exec_prefix = self.parent.parent.parent.config.get('exec_prefix', []) command = self.execution['command'] if isinstance(command, SEQUENCES):...
get command to execute as string properly escaped :return: string def command_str(self): """get command to execute as string properly escaped :return: string """ if isinstance(self.command, six.string_types): return self.command return ' '.join(map(six.move...
Build popen object to run :rtype: subprocess.Popen def popen(self, stdout, stderr): """Build popen object to run :rtype: subprocess.Popen """ self.logger.info('Executing command: %s', self.command_str) return subprocess.Popen([self._executor_script], stdout=stdout, std...
:param campaign: global YAML configuration :param config: benchmark YAML configuration def srun_cartesian_product(cls, campaign, config): """ :param campaign: global YAML configuration :param config: benchmark YAML configuration """ options = copy.copy(cls.common_srun_op...
Get path to srun executable :rtype: string def srun(self): """Get path to srun executable :rtype: string """ commands = self.campaign.process.get('commands', {}) srun = find_executable(commands.get('srun', 'srun')) if six.PY2: srun = srun.encode('ut...
Get options to be given to all srun commands :rtype: list of string def common_srun_options(cls, campaign): """Get options to be given to all srun commands :rtype: list of string """ default = dict(campaign.process.get('srun') or {}) default.update(output='slurm-%N-%t....
get command to execute :return: list of string def command(self): """get command to execute :return: list of string """ srun_optlist = build_slurm_arguments(self.parent.command.srun or {}) if not isinstance(self.root.network.nodes(self.tag), ConstraintTag): ...
Get list of nodes where to execute the command def srun_nodes(self): """Get list of nodes where to execute the command """ count = self.execution.get('srun_nodes', 0) if isinstance(count, six.string_types): tag = count count = 0 elif isinstance(count, SEQ...
Clean up a graph by removing it :param identifier: Root identifier of the graph :return: def clear_graph(identifier=None): """ Clean up a graph by removing it :param identifier: Root identifier of the graph :return: """ graph = get_graph() if identifier: graph.destroy(identifi...
Generate a graph and change the global graph to this one :param alchemy_uri: A Uri for the graph :param prefixes: A dictionary of prefixes and namespaces to bind to the graph :param identifier: An identifier that will identify the Graph root def generate_alchemy_graph(alchemy_uri, prefixes=None, identifie...
Generate a graph and change the global graph to this one :param filepath: A Uri for the graph :param prefixes: A dictionary of prefixes and namespaces to bind to the graph :param identifier: An identifier that will identify the Graph root def generate_sleepy_cat_graph(filepath, prefixes=None, identifier="...
Add the label of the collection in given lang :param label: Label Value :param lang: Language code def set_label(self, label, lang): """ Add the label of the collection in given lang :param label: Label Value :param lang: Language code """ try: se...
Children of the collection's item :rtype: [Collection] def members(self): """ Children of the collection's item :rtype: [Collection] """ return list( [ self.children_class(child) for child in self.graph.subjects(RDF_NAMESPACES.DTS.pa...
Parent of current object :rtype: Collection def parent(self): """ Parent of current object :rtype: Collection """ parent = list(self.graph.objects(self.asNode(), RDF_NAMESPACES.DTS.parent)) if parent: return self.parent_class(parent[0]) return None
Compile & Run the experiment with -O3 enabled. def actions_for_project(self, project): """Compile & Run the experiment with -O3 enabled.""" project.cflags = ["-O3", "-fno-omit-frame-pointer"] project.runtime_extension = time.RunWithTime( run.RuntimeExtension(project, self)) ...
Convert a function return to a list of StepResults. All Step subclasses automatically wrap the result of their __call__ method's result with this wrapper. If the result is not a list of StepResult values, one will be generated. result of `[StepResult.OK]`, or convert the given result into a li...
Prepends the output of `func` with the status. def prepend_status(func): """Prepends the output of `func` with the status.""" @ft.wraps(func) def wrapper(self, *args, **kwargs): """Wrapper stub.""" res = func(self, *args, **kwargs) if self.status is not StepResult.UNSET: ...
Print the beginning and the end of a `func`. def notify_step_begin_end(func): """Print the beginning and the end of a `func`.""" @ft.wraps(func) def wrapper(self, *args, **kwargs): """Wrapper stub.""" cls = self.__class__ on_step_begin = cls.ON_STEP_BEGIN on_step_end = cls....
Log customized stirng before & after running func. def log_before_after(name: str, desc: str): """Log customized stirng before & after running func.""" def func_decorator(f): """Wrapper stub.""" @ft.wraps(f) def wrapper(*args, **kwargs): """Wrapper stub.""" LOG...
Display processed MRI data from `.hdf5`, `.npz`, or `.dat` files. No arguments displays the IFFT of the k-space data. The type of file is guessed by the file extension (i.e., if extension is `.dat` then readMeasData15 will be run to get the data). Command-line Options: -nifft (no IFFT) Displ...
returns the Greatest Common Divisor of a and b def euclid(a, b): """returns the Greatest Common Divisor of a and b""" a = abs(a) b = abs(b) if a < b: a, b = b, a while b != 0: a, b = b, a % b return a
returns 'True' if the values in the list L are all co-prime otherwise, it returns 'False'. def coPrime(l): """returns 'True' if the values in the list L are all co-prime otherwise, it returns 'False'. """ for i, j in combinations(l, 2): if euclid(i, j) != 1: return False r...
return a tuple of three values: x, y and z, such that x is the GCD of a and b, and x = y * a + z * b def extendedEuclid(a, b): """return a tuple of three values: x, y and z, such that x is the GCD of a and b, and x = y * a + z * b""" if a == 0: return b, 0, 1 else: g, y, x = extende...
returns the multiplicative inverse of a in modulo m as a positive value between zero and m-1 def modInv(a, m): """returns the multiplicative inverse of a in modulo m as a positive value between zero and m-1""" # notice that a and m need to co-prime to each other. if coPrime([a, m]): l...
m is a positive integer. A tuple (s, d) of integers is returned such that m = (2 ** s) * d. def extractTwos(m): """m is a positive integer. A tuple (s, d) of integers is returned such that m = (2 ** s) * d.""" # the problem can be break down to count how many '0's are there in # the end of bin(m). ...
x is a positive integer. Convert it to base two as a list of integers in reverse order as a list. def int2baseTwo(x): """x is a positive integer. Convert it to base two as a list of integers in reverse order as a list.""" # repeating x >>= 1 and x & 1 will do the trick assert x >= 0 bitInverse ...
returns a ** d (mod n) def modExp(a, d, n): """returns a ** d (mod n)""" assert d >= 0 assert n >= 0 base2D = int2baseTwo(d) base2DLength = len(base2D) modArray = [] result = 1 for i in range(1, base2DLength + 1): if i == 1: modArray.append(a % n) else: ...
Miller Rabin pseudo-prime test return True means likely a prime, (how sure about that, depending on k) return False means definitely a composite. Raise assertion error when n, k are not positive integers and n is not 1 def millerRabin(n, k): """ Miller Rabin pseudo-prime test return True me...
return a list with length k + 1, showing if list[i] == 1, i is a prime else if list[i] == 0, i is a composite, if list[i] == -1, not defined def primeSieve(k): """return a list with length k + 1, showing if list[i] == 1, i is a prime else if list[i] == 0, i is a composite, if list[i] == -1, not defined""" ...