code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if only_update: if subsd == prev_subsd: if not missing_or_other_newer(dest, src): if logger: msg = ("Did not re-render {}. " "(destination newer + same dict)") logger.info(msg....
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 want to use a template engine such as e.g. mako.
3.632871
3.685977
0.985592
names = [id for id in self.ecrm_P1_is_identified_by if id.uri == surf.ns.EFRBROO['F12_Name']] self.names = [] for name in names: for variant in name.rdfs_label: self.names.append((variant.language,variant.title())) return self.names
def get_names(self)
Returns a dict where key is the language and value is the name in that language. Example: {'it':"Sofocle"}
14.978591
16.393106
0.913713
try: assert (lang, name) not in self.get_names() except Exception as e: # TODO: raise a custom exception logger.warning("Duplicate name detected while adding \"%s (lang=%s)\""%(name, lang)) return False newlabel = Literal(name, lang=lang) ...
def add_name(self, name, lang=None)
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)
8.498577
8.319743
1.021495
try: assert new_abbreviation not in self.get_abbreviations() except Exception as e: # TODO: raise a custom exception logger.warning("Duplicate abbreviation detected while adding \"%s\""%new_abbreviation) return False try: type...
def add_abbreviation(self, new_abbreviation)
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)
3.781004
3.730672
1.013491
abbreviations = [] try: type_abbreviation = self.session.get_resource(BASE_URI_TYPES % "abbreviation" , self.session.get_class(surf.ns.ECRM['E55_Type'])) abbreviations = [unicode(label) ...
def get_abbreviations(self)
Get abbreviations of the names of the author. :return: a list of strings (empty list if no abbreviations available).
10.31546
10.496014
0.982798
# TODO: check type try: type_ctsurn = self.session.get_resource(BASE_URI_TYPES % "CTS_URN" , self.session.get_class(surf.ns.ECRM['E55_Type'])) urn = [CTS_URN(urnstring.rdfs_label.one) for...
def get_urn(self)
Assumes that each HucitAuthor has only one CTS URN.
14.437103
13.328203
1.0832
Type = self.session.get_class(surf.ns.ECRM['E55_Type']) Identifier = self.session.get_class(surf.ns.ECRM['E42_Identifier']) id_uri = "%s/cts_urn"%str(self.subject) try: id = Identifier(id_uri) id.rdfs_label = Literal(urn) id.ecrm_P2_has_type =...
def set_urn(self,urn)
Change the CTS URN of the author or adds a new one (if no URN is assigned).
7.896543
7.667679
1.029848
names = self.get_names() return json.dumps({ "uri" : self.subject , "urn" : str(self.get_urn()) , "names" : [{"language":lang, "label":label} for lang, label in names] , "name_abbreviations" : self.get_abbreviations...
def to_json(self)
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": [ ...
4.312383
2.959973
1.456899
return [(label.language, unicode(label)) for label in self.efrbroo_P102_has_title.first.rdfs_label]
def get_titles(self)
TODO
33.642464
28.099854
1.197247
abbreviations = [] try: type_abbreviation = self.session.get_resource(BASE_URI_TYPES % "abbreviation" , self.session.get_class(surf.ns.ECRM['E55_Type'])) abbreviations = [unicode(label) ...
def get_abbreviations(self, combine=False)
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).
7.318643
7.431236
0.984849
ts = self.session.get_resource("%s/text_structure" % self.subject , self.session.get_class(surf.ns.HUCIT['TextStructure'])) ts.rdfs_label.append(Literal(label)) ts.save() self.hucit_has_structure = ts self.update() return se...
def add_text_structure(self, label)
Adds a citable text structure to the work.
11.679231
10.590438
1.102809
def remove_text_structure(self, text_structure): # TODO: delete also TextElements one by one idx = self.hucit_has_structure.index(text_structure) ts = self.hucit_has_structure.pop(idx) ts.remove() self.update() return
Remove any citable text structure to the work.
null
null
null
label = opmax = self.session.get_resource( BASE_URI_TYPES % "opmax", self.session.get_class(surf.ns.ECRM['E55_Type']) ) if opmax.is_present(): return opmax else: opmax.rdfs_label.append(Literal(label, "en")) l...
def _get_opus_maximum(self)
Instantiate an opus maximum type.
18.087223
12.82559
1.410245
return False else: opmax = self._get_opus_maximum() self.ecrm_P2_has_type = opmax self.update() return True
def set_as_opus_maximum(self): # TODO: test if self.is_opus_maximum()
Mark explicitly the work as the author's opus maximum.
17.274094
14.607799
1.182525
opmax = self._get_opus_maximum() types = self.ecrm_P2_has_type if opmax in types: return True else: if len(self.author.get_works()) == 1: return True else: return False
def is_opus_maximum(self)
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
10.913321
9.124479
1.196049
CreationEvent = self.session.get_class(surf.ns.EFRBROO['F27_Work_Conception']) Person = self.session.get_class(surf.ns.EFRBROO['F10_Person']) creation_event = CreationEvent.get_by(efrbroo_R16_initiated=self).first() return Person.get_by(efrbroo_P14i_performed = creation_event)....
def author(self)
Returns the author to whom the work is attributed. :return: an instance of `HucitWork` # TODO: check that's the case
12.300091
11.160747
1.102085
titles = self.get_titles() return json.dumps({ "uri" : self.subject , "urn" : str(self.get_urn()) , "titles" : [{"language":lang, "label":label} for lang, label in titles] , "title_abbreviations" : self.get_abbreviations() ...
def to_json(self)
Serialises a HucitWork to a JSON formatted string.
5.651783
5.294619
1.067458
urn = self.ecrm_P1_is_identified_by.one try: return CTS_URN(urn) except Exception, e: raise e
def get_urn(self)
TODO
23.952108
20.728685
1.155505
if tag == '*': return sorted(list(set(self.campaign.network.nodes))) definitions = self.campaign.network.tags.get(tag) if definitions is None: return [] nodes = set() for definition in definitions: if len(definition.items()) == 0: ...
def nodes(self, tag)
get nodes that belong to a tag :param tag: tag name :rtype: list of string
3.263711
3.273374
0.997048
name = self.campaign.process.type for clazz in [ExecutionDriver, SrunExecutionDriver]: if name == clazz.name: return clazz raise NameError("Unknown execution layer: '%s'" % name)
def execution_cls(self)
Get execution layer class
12.284157
9.322717
1.317658
tags = {'*'} if self.tag: network_tags = {self.tag: self.campaign.network.tags[self.tag]} else: network_tags = self.campaign.network.tags for tag, configs in network_tags.items(): for config in configs: for mode, kconfig in con...
def children(self)
Retrieve tags associated to the current node
3.884398
3.596943
1.079917
if value is not None: assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("activated", value) self.__activated = value
def activated(self, value)
Setter for **self.__activated** attribute. :param value: Attribute value. :type value: bool
5.300961
4.420485
1.199181
if value is not None: assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("initialized", value) self.__initialized = value
def initialized(self, value)
Setter for **self.__initialized** attribute. :param value: Attribute value. :type value: bool
5.215832
4.480818
1.164036
raise NotImplementedError("{0} | '{1}' must be implemented by '{2}' subclasses!".format( self.__class__.__name__, self.activate.__name__, self.__class__.__name__))
def activate(self)
Sets Component activation state. :return: Method success. :rtype: bool
7.151988
7.27249
0.98343
command = [SINFO, '--reservation'] output = subprocess.check_output(command, env=SINFO_ENV) output = output.decode() it = iter(output.splitlines()) next(it) for line in it: rsv = Reservation.from_sinfo(line) yield rsv.name, rsv
def reservations(self)
get nodes of every reservations
4.397207
4.048446
1.086147
if hasattr(self, "inputs"): for item in self.inputs: if hasattr(self, item): setattr(self, item, values[item])
def set(self, values)
Set the object parameters using a dictionary
3.500865
3.34564
1.046396
results = [action() for action in plan] return [result for result in results if actns.step_has_failed(result)]
def execute_plan(plan)
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.
12.886495
12.099877
1.06501
level_name = '* %(levelname)1s' time = '%(asctime)s,%(msecs)03d' message = '%(message)s' color_start = '%(color)s' color_end = '%(end_color)s' caller = '[%(module)s:%(lineno)d]' if color: if include_caller: return '{}{}{} {} {} {}'.format(color_start, level_name, ...
def _set_log_format(color, include_caller)
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
2.023632
2.012706
1.005428
formatter = logzero.LogFormatter( fmt=_set_log_format(color=True, include_caller=include_caller), datefmt='%Y-%m-%d %H:%M:%S' ) logzero.setup_default_logger(formatter=formatter) if logfile: formatter = logzero.LogFormatter( fmt=_set_log_format(color=False, inclu...
def setup_logger(logfile=None, backup_count=20, log_level=logging.INFO, include_caller=True)
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....
2.098036
2.2487
0.932999
attribute_repr = ', '.join(('{}={}'.format(attr, repr(getattr(obj, attr))) for attr in attributes)) return "{0}({1})".format(obj.__class__.__qualname__, attribute_repr)
def format_repr(obj, attributes) -> str
Format an object's repr method with specific attributes.
3.422055
3.127985
1.094013
if user_p is None: user_p = {} if ignore is None: ignore = [] para = [[obj.__class__.__name__ + " inputs:", "", ""]] if plist is None: if not hasattr(obj, 'inputs'): raise exceptions.ModelError("Object must contain parameter 'inputs' or set plist as an input") ...
def build_parameter_descriptions(obj, user_p=None, output="csv", show_none=True, ignore=None, plist=None)
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...
3.045591
2.988935
1.018955
para = [] para += build_parameter_descriptions(models.Soil()) + [",,\n"] para += build_parameter_descriptions(models.SoilProfile()) + [",,\n"] para += build_parameter_descriptions(models.Foundation()) + [",,\n"] para += build_parameter_descriptions(models.PadFoundation()) + [",,\n"] para +=...
def all_descriptions()
Generates a list of descriptions of all the models :return:
4.476442
4.637012
0.965372
''' 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 va...
def plot_shapes_heat_map(df_shapes, shape_i_columns, values, axis=None, vmin=None, vmax=None, value_formatter=None, color_map=None)
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...
2.63957
1.816969
1.452733
''' 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 a...
def plot_color_map_bars(values, vmin=None, vmax=None, color_map=None, axis=None, **kwargs)
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...
3.389328
1.666345
2.033989
for path in paths: file_ = osp.join(path, name) if osp.exists(file_) and not osp.isdir(file_): abs_file = osp.abspath(file_) if os.access(file_, os.X_OK): return abs_file
def find_in_paths(name, paths)
Find an executable is a list of directories :return: absolute path to the first location where the executable is found, ``None`` otherwise. :rtype: string
2.387703
2.567665
0.929912
path_from_env = os.environ.get(name.upper()) if path_from_env is not None: return path_from_env names = [name] + (names or []) for _name in names: if osp.isabs(_name): return _name paths = os.environ.get('PATH', '').split(os.pathsep) eax = find_in_paths(_...
def find_executable(name, names=None, required=True)
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...
2.756888
2.90335
0.949554
if platform.system() == 'Darwin': ncores = subprocess.check_output( ['/usr/sbin/sysctl', '-n', 'hw.ncpu'], shell=False ) return int(ncores.strip()) sockets = set() with open('/proc/cpuinfo') as istr: for line in istr: if line.startswith('physical...
def physical_cpus()
Get cpus identifiers, for instance set(["0", "1", "2", "3"]) :return Number of physical CPUs available :rtype: int
2.710822
2.778898
0.975503
img = PIL.Image.fromarray(self.data, 'RGBA') if debugText!='': draw = PIL.ImageDraw.Draw(img) font = PIL.ImageFont.truetype("DejaVuSansMono.ttf", 24) draw.text((0, 0),debugText,(255,255,255),font=font) img.show(title=title)
def showLayer(self, title='', debugText='')
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.
2.093568
2.319213
0.902706
return {k: TYPE_CASTERS.get(v, v) for k, v in data_types.items()}
def make_converters(data_types) -> dict
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': ...
5.775543
5.0723
1.138644
# Add spacing between Key and Value to prevent parsing error json_text = json_text.replace(":", ": ") json_dict = yaml.load(json_text) return json_dict
def parse_broken_json(json_text: str) -> dict
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.
6.915802
7.107954
0.972967
fd, path = tempfile.mkstemp(suffix='.sh', dir=os.getcwd()) os.close(fd) with open(path, 'w') as ostr: self._write_executor_script(ostr) mode = os.stat(path).st_mode os.chmod(path, mode | stat.S_IEXEC | stat.S_IRGRP | stat.S_IRUSR) return path
def _executor_script(self)
Create shell-script in charge of executing the benchmark and return its path.
2.374514
2.389674
0.993656
template = self.campaign.process.executor_template if template.startswith('#!'): return jinja_environment.from_string(template) else: return jinja_environment.get_template(template)
def _jinja_executor_template(self)
:return Jinja template of the shell-script executor
4.746168
4.541302
1.045112
environment = self.execution.get('environment') or {} if not isinstance(environment, Mapping): msg = 'Expected mapping for environment but got ' msg += str(type(environment)) raise Exception(msg) escaped_environment = dict( (var, six.moves...
def _write_executor_script(self, ostr)
Write shell script in charge of executing the command
3.794018
3.646406
1.040481
exec_prefix = self.parent.parent.parent.config.get('exec_prefix', []) command = self.execution['command'] if isinstance(command, SEQUENCES): command = [arg.format(**self.command_expansion_vars) for arg in command] else: command = command.format(**self.com...
def command(self)
:return command to execute inside the generated shell-script
2.8731
2.805237
1.024192
if isinstance(self.command, six.string_types): return self.command return ' '.join(map(six.moves.shlex_quote, self.command))
def command_str(self)
get command to execute as string properly escaped :return: string
3.211485
3.675636
0.873722
self.logger.info('Executing command: %s', self.command_str) return subprocess.Popen([self._executor_script], stdout=stdout, stderr=stderr)
def popen(self, stdout, stderr)
Build popen object to run :rtype: subprocess.Popen
5.715835
6.096843
0.937507
options = copy.copy(cls.common_srun_options(campaign)) options.update(config.get('srun') or {}) options_tuple = [] for k, v in options.items(): if not isinstance(v, SEQUENCES): v = [v] options_tuple.append([(k, e) for e in v]) retu...
def srun_cartesian_product(cls, campaign, config)
:param campaign: global YAML configuration :param config: benchmark YAML configuration
3.721335
4.016175
0.926587
commands = self.campaign.process.get('commands', {}) srun = find_executable(commands.get('srun', 'srun')) if six.PY2: srun = srun.encode('utf-8') return srun
def srun(self)
Get path to srun executable :rtype: string
5.079738
5.056255
1.004644
default = dict(campaign.process.get('srun') or {}) default.update(output='slurm-%N-%t.stdout', error='slurm-%N-%t.error') return default
def common_srun_options(cls, campaign)
Get options to be given to all srun commands :rtype: list of string
9.767545
12.803095
0.762905
srun_optlist = build_slurm_arguments(self.parent.command.srun or {}) if not isinstance(self.root.network.nodes(self.tag), ConstraintTag): pargs = parse_constraint_in_args(srun_optlist) self.command_expansion_vars['process_count'] = pargs.ntasks if not pargs.c...
def command(self)
get command to execute :return: list of string
8.440931
8.728139
0.967094
count = self.execution.get('srun_nodes', 0) if isinstance(count, six.string_types): tag = count count = 0 elif isinstance(count, SEQUENCES): return count else: assert isinstance(count, int) tag = self.tag nodes ...
def srun_nodes(self)
Get list of nodes where to execute the command
3.327152
3.216702
1.034336
graph = get_graph() if identifier: graph.destroy(identifier) try: graph.close() except: warn("Unable to close the Graph")
def clear_graph(identifier=None)
Clean up a graph by removing it :param identifier: Root identifier of the graph :return:
5.559806
6.657495
0.83512
registerplugins() ident = URIRef(identifier) uri = Literal(alchemy_uri) store = plugin.get("SQLAlchemy", Store)(identifier=ident) graph = Graph(store, identifier=ident) graph.open(uri, create=True) for prefix, ns in (prefixes or GRAPH_BINDINGS).items(): if prefix == "": ...
def generate_alchemy_graph(alchemy_uri, prefixes=None, identifier="NautilusSparql")
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
8.51059
9.572505
0.889066
registerplugins() ident = URIRef(identifier) graph = Graph('Sleepycat', identifier=ident) graph.open(filepath, create=True) for prefix, ns in (prefixes or GRAPH_BINDINGS).items(): if prefix == "": prefix = "cts" # Fix until ALchemy Store accepts empty prefixes grap...
def generate_sleepy_cat_graph(filepath, prefixes=None, identifier="NautilusSparql")
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
11.903405
12.22975
0.973316
try: self.metadata.add(SKOS.prefLabel, Literal(label, lang=lang)) self.graph.addN([ (self.asNode(), RDFS.label, Literal(label, lang=lang), self.graph), ]) except Exception as E: pass
def set_label(self, label, lang)
Add the label of the collection in given lang :param label: Label Value :param lang: Language code
5.120252
5.447845
0.939867
return list( [ self.children_class(child) for child in self.graph.subjects(RDF_NAMESPACES.DTS.parent, self.asNode()) ] )
def members(self)
Children of the collection's item :rtype: [Collection]
13.142998
12.111699
1.085149
parent = list(self.graph.objects(self.asNode(), RDF_NAMESPACES.DTS.parent)) if parent: return self.parent_class(parent[0]) return None
def parent(self)
Parent of current object :rtype: Collection
9.454066
10.866755
0.869999
project.cflags = ["-O3", "-fno-omit-frame-pointer"] project.runtime_extension = time.RunWithTime( run.RuntimeExtension(project, self)) return self.default_runtime_actions(project)
def actions_for_project(self, project)
Compile & Run the experiment with -O3 enabled.
12.768813
10.174963
1.254925
@ft.wraps(func) def wrapper(*args, **kwargs): res = func(*args, **kwargs) if not res: res = [StepResult.OK] if not hasattr(res, "__iter__"): res = [res] return res return wrapper
def to_step_result(func)
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...
3.458159
2.91719
1.185442
@ft.wraps(func) def wrapper(self, *args, **kwargs): res = func(self, *args, **kwargs) if self.status is not StepResult.UNSET: res = "[{status}]".format(status=self.status.name) + res return res return wrapper
def prepend_status(func)
Prepends the output of `func` with the status.
3.92476
3.617406
1.084966
@ft.wraps(func) def wrapper(self, *args, **kwargs): cls = self.__class__ on_step_begin = cls.ON_STEP_BEGIN on_step_end = cls.ON_STEP_END for begin_listener in on_step_begin: begin_listener(self) res = func(self, *args, **kwargs) for e...
def notify_step_begin_end(func)
Print the beginning and the end of a `func`.
2.517808
2.470861
1.019
def func_decorator(f): @ft.wraps(f) def wrapper(*args, **kwargs): LOG.info("\n%s - %s", name, desc) res = f(*args, **kwargs) if StepResult.ERROR not in res: LOG.info("%s - OK\n", name) else: ...
def log_before_after(name: str, desc: str)
Log customized stirng before & after running func.
3.72123
3.370086
1.104194
''' 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) ...
def quickview(filename, noIFFT=False)
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...
4.515924
2.450566
1.842808
a = abs(a) b = abs(b) if a < b: a, b = b, a while b != 0: a, b = b, a % b return a
def euclid(a, b)
returns the Greatest Common Divisor of a and b
2.094076
1.703798
1.229064
for i, j in combinations(l, 2): if euclid(i, j) != 1: return False return True
def coPrime(l)
returns 'True' if the values in the list L are all co-prime otherwise, it returns 'False'.
2.92468
3.099229
0.94368
if a == 0: return b, 0, 1 else: g, y, x = extendedEuclid(b % a, a) return g, x - (b // a) * y, y
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
1.535665
1.911504
0.80338
# notice that a and m need to co-prime to each other. if coPrime([a, m]): linearCombination = extendedEuclid(a, m) return linearCombination[1] % m else: return 0
def modInv(a, m)
returns the multiplicative inverse of a in modulo m as a positive value between zero and m-1
8.434438
8.313709
1.014522
# the problem can be break down to count how many '0's are there in # the end of bin(m). This can be done this way: m & a stretch of '1's # which can be represent as (2 ** n) - 1. assert m >= 0 i = 0 while m & (2 ** i) == 0: i += 1 return i, m >> i
def extractTwos(m)
m is a positive integer. A tuple (s, d) of integers is returned such that m = (2 ** s) * d.
10.000742
8.695951
1.150046
# repeating x >>= 1 and x & 1 will do the trick assert x >= 0 bitInverse = [] while x != 0: bitInverse.append(x & 1) x >>= 1 return bitInverse
def int2baseTwo(x)
x is a positive integer. Convert it to base two as a list of integers in reverse order as a list.
5.98722
5.700286
1.050337
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: modArray.append((modArray[i - 2] ** 2) % n) for i in range(0, ...
def modExp(a, d, n)
returns a ** d (mod n)
2.624103
2.716619
0.965944
assert n >= 1 # ensure n is bigger than 1 assert k > 0 # ensure k is a positive integer so everything down here makes sense if n == 2: return True # make sure to return True if n == 2 if n % 2 == 0: return False # immediately return False for all the even numbers b...
def millerRabin(n, k)
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
3.34317
3.347149
0.998811
def isPrime(n): for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True result = [-1] * (k + 1) for i in range(2, int(k + 1)): if isPrime(i): result[i] = 1 else: result[i] = 0 return ...
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
2.113662
1.95209
1.082769
x = random.randint(a, b) for i in range(0, int(10 * math.log(x) + 3)): if millerRabin(x, k): return x else: x += 1 raise ValueError
def findAPrime(a, b, k)
Return a pseudo prime number roughly between a and b, (could be larger than b). Raise ValueError if cannot find a pseudo prime after 10 * ln(x) + 3 tries.
3.876532
2.386209
1.624557
try: p = findAPrime(a, b, k) while True: q = findAPrime(a, b, k) if q != p: break except: raise ValueError n = p * q m = (p - 1) * (q - 1) while True: e = random.randint(1, m) if coPrime([e, m]): break...
def newKey(a, b, k)
Try to find two large pseudo primes roughly between a and b. Generate public and private keys for RSA encryption. Raises ValueError if it fails to find one
3.083284
2.820792
1.093056
# Note that ASCII printable characters range is 0x20 - 0x7E returnList = [] toProcess = copy.copy(l) ''' copy message ascii list''' if len(toProcess) % n != 0: for i in range(0, n - len(toProcess) % n): ''' append rand str to list''' toProcess.append(random.randi...
def numList2blocks(l, n)
Take a list of integers(each between 0 and 127), and combines them into block size n using base 256. If len(L) % n != 0, use some random junk to fill L to make it.
4.54207
4.297902
1.056811
toProcess = copy.copy(blocks) returnList = [] for numBlock in toProcess: inner = [] for i in range(0, n): inner.append(numBlock % 256) numBlock >>= 8 inner.reverse() returnList.extend(inner) return returnList
def blocks2numList(blocks, n)
inverse function of numList2blocks.
3.461128
3.261788
1.061114
numList = string2numList(message) numBlocks = numList2blocks(numList, blockSize) # only one block message = numBlocks[0] # return [modExp(blocks, e, modN) for blocks in numBlocks] return modExp(message, e, modN)
def encrypt(message, modN, e, blockSize)
given a string message, public keys and blockSize, encrypt using RSA algorithms.
5.667502
5.47303
1.035533
numBlocks = [modExp(blocks, d, modN) for blocks in secret] numList = blocks2numList(numBlocks, blockSize) return numList2string(numList)
def decrypt(secret, modN, d, blockSize)
reverse function of encrypt
5.993644
6.568221
0.912522
for name in files: if re.match(pattern, name): yield name
def match_files(files, pattern: Pattern)
Yields file name if matches a regular expression pattern.
6.728431
3.152062
2.134612
with ZipFile(zipfile_path, mode='r') as zfile: members = zfile.namelist() yield from match_files(members, pattern)
def match_zipfile_members(zipfile_path: str, pattern: Pattern)
Match files to a pattern within a zip file's content.
4.635446
3.370709
1.375214
for entry in os.scandir(path): if not entry.name.startswith('.') and entry.is_file(): yield entry.name
def directory_files(path)
Yield directory file names.
2.711505
2.178131
1.244877
return sha256(''.join(sorted(listing_paths)).encode('utf-8')).hexdigest()
def get_file_listing_sha(listing_paths: Iterable) -> str
Return sha256 string for group of FTP listings.
5.365421
3.473006
1.544893
assert self.finger_count > 0, 'This device does not support tapping' return self._libinput.libinput_device_config_tap_set_button_map( self._handle, button_map)
def set_button_map(self, button_map)
Set the finger number to button number mapping for tap-to-click. The default mapping on most devices is to have a 1, 2 and 3 finger tap to map to the left, right and middle button, respectively. A device may permit changing the button mapping but disallow specific maps. In this case :attr:`~libinput.constant.C...
6.675639
4.289656
1.556218
matrix = (c_float * 6)(*matrix) return self._libinput.libinput_device_config_calibration_set_matrix( self._handle, matrix)
def set_matrix(self, matrix)
Apply the 3x3 transformation matrix to absolute device coordinates. This matrix has no effect on relative events. Given a 6-element array [a, b, c, d, e, f], the matrix is applied as :: [ a b c ] [ x ] [ d e f ] * [ y ] [ 0 0 1 ] [ 1 ] The translation component (c, f) is expected to be no...
6.299662
6.53174
0.964469
matrix = (c_float * 6)() rc = self._libinput.libinput_device_config_calibration_get_matrix( self._handle, matrix) return rc, tuple(matrix)
def matrix(self)
The current calibration matrix for this device. Returns: (bool, (float, float, float, float, float, float)): :obj:`False` if no calibration is set and the returned matrix is the identity matrix, :obj:`True` otherwise. :obj:`tuple` representing the first two rows of a 3x3 matrix as described in :meth:`...
7.303635
6.246284
1.169277
matrix = (c_float * 6)() rc = self._libinput \ .libinput_device_config_calibration_get_default_matrix( self._handle, matrix) return rc, tuple(matrix)
def default_matrix(self)
The default calibration matrix for this device. On most devices, this is the identity matrix. If the udev property ``LIBINPUT_CALIBRATION_MATRIX`` is set on the respective udev device, that property's value becomes the default matrix, see `Static device configuration via udev`_. Returns: (bool, (float, f...
7.564281
5.566737
1.358836
pchar = self._libinput.libinput_device_get_sysname(self._handle) return string_at(pchar).decode()
def sysname(self)
The system name of the device. To get the descriptive device name, use :attr:`name`. Returns: str: System name of the device.
8.433743
7.029684
1.199733
pchar = self._libinput.libinput_device_get_name(self._handle) return string_at(pchar).decode()
def name(self)
The descriptive device name as advertised by the kernel and/or the hardware itself. To get the sysname for this device, use :attr:`sysname`. Returns: str: The device name.
9.274091
6.960418
1.332404
rc = self._libinput.libinput_device_set_seat_logical_name( self._handle, seat.encode()) assert rc == 0, 'Cannot assign device to {}'.format(seat)
def set_seat_logical_name(self, seat)
Change the logical seat associated with this device by removing the device and adding it to the new seat. This command is identical to physically unplugging the device, then re-plugging it as a member of the new seat. libinput will generate a :attr:`~libinput.constant.EventType.DEVICE_REMOVED` event and this ...
6.771885
5.209009
1.300033
caps = [] for cap in DeviceCapability: if self._libinput.libinput_device_has_capability(self._handle, cap): caps.append(cap) return tuple(caps)
def capabilities(self)
A tuple of capabilities this device supports. Returns: (~libinput.constant.DeviceCapability): Device capabilities.
4.971451
3.23484
1.536846
width = c_double(0) height = c_double(0) rc = self._libinput.libinput_device_get_size( self._handle, byref(width), byref(height)) assert rc == 0, 'This device does not provide size information' return width.value, height.value
def size(self)
The physical size of a device in mm, where meaningful. This property is only valid on devices with the required data, i.e. tablets, touchpads and touchscreens. For other devices this property raises :exc:`AssertionError`. Returns: (float, float): (Width, Height) in mm. Raises: AssertionError
3.651859
3.309073
1.10359
rc = self._libinput.libinput_device_pointer_has_button( self._handle, button) assert rc >= 0, 'This device is not a pointer device' return bool(rc)
def has_button(self, button)
Check if this device has a given button. Args: button (int): Button to check for, see ``input.h`` for button definitions. Returns: bool: :obj:`True` if the device has this button, :obj:`False` if it does not. Raises: AssertionError
7.183272
6.676902
1.075839
rc = self._libinput.libinput_device_keyboard_has_key(self._handle, key) assert rc >= 0, 'This device is not a keyboard device' return bool(rc)
def has_key(self, key)
Check if a :attr:`~libinput.constant.DeviceCapability.KEYBOARD` device has a given key. Args: key (int): Key to check for, see ``input.h`` for key definitions. Returns: bool: :obj:`True` if the device has this key, :obj:`False` if it does not. Raises: AssertionError
5.963141
4.795918
1.243378
num = self._libinput.libinput_device_tablet_pad_get_num_buttons( self._handle) if num < 0: raise AttributeError('This device is not a tablet pad device') return num
def num_buttons(self)
The number of buttons on a device with the :attr:`~libinput.constant.DeviceCapability.TABLET_PAD` capability. Buttons on a pad device are numbered sequentially, see `Tablet pad button numbers`_ for details. Returns: int: The number of buttons supported by the device. Raises: AttributeError
6.541585
4.243887
1.541413
num = self._libinput.libinput_device_tablet_pad_get_num_rings( self._handle) if num < 0: raise AttributeError('This device is not a tablet pad device') return num
def num_rings(self)
The number of rings a device with the :attr:`~libinput.constant.DeviceCapability.TABLET_PAD` capability provides. Returns: int: The number of rings or 0 if the device has no rings. Raises: AttributeError
6.722628
3.893075
1.726817
num = self._libinput.libinput_device_tablet_pad_get_num_strips( self._handle) if num < 0: raise AttributeError('This device is not a tablet pad device') return num
def num_strips(self)
The number of strips a device with the :attr:`~libinput.constant.DeviceCapability.TABLET_PAD` capability provides. Returns: int: The number of strips or 0 if the device has no strips. Raises: AttributeError
6.79449
3.977683
1.708153
num = self._libinput.libinput_device_tablet_pad_get_num_mode_groups( self._handle) if num < 0: raise AttributeError('This device is not a tablet pad device') return num
def num_mode_groups(self)
Most devices only provide a single mode group, however devices such as the Wacom Cintiq 22HD provide two mode groups. If multiple mode groups are available, a caller should use :meth:`~libinput.define.TabletPadModeGroup.has_button`, :meth:`~libinput.define.TabletPadModeGroup.has_ring` and :meth:`~libinput.de...
6.692043
4.141901
1.615693
hmodegroup = self._libinput.libinput_device_tablet_pad_get_mode_group( self._handle, group) if hmodegroup: return TabletPadModeGroup(hmodegroup, self._libinput) return None
def get_mode_group(self, group)
While a reference is kept by the caller, the returned mode group will compare equal with mode group returned by each subsequent call of this method with the same index and mode group returned from :attr:`~libinput.event.TabletPadEvent.mode_group`, provided the event was generated by this mode group. Args: ...
5.257491
2.877768
1.826933
pchar = self._libinput.libinput_seat_get_physical_name(self._handle) return string_at(pchar).decode()
def physical_name(self)
The physical name of the seat. For libinput contexts created from udev, this is always the same value as passed into :meth:`~libinput.LibInputUdev.assign_seat` and all seats from that context will have the same physical name. The physical name of the seat is one that is usually set by the system or lower le...
11.087798
5.91885
1.873303
pchar = self._libinput.libinput_seat_get_logical_name(self._handle) return string_at(pchar).decode()
def logical_name(self)
The logical name of the seat. This is an identifier to group sets of devices within the compositor. Returns: str: The logical name of this seat.
11.592825
8.466692
1.369227