repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
sequencelengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
sequencelengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
BlueBrain/hpcbench
hpcbench/campaign.py
NetworkConfig.expand
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()
python
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()
[ "def", "expand", "(", "self", ")", ":", "if", "self", ".", "slurm", ":", "self", ".", "_introspect_slurm_cluster", "(", ")", "self", ".", "network", ".", "nodes", "=", "self", ".", "_expand_nodes", "(", "self", ".", "network", ".", "nodes", ")", "self", ".", "_expand_tags", "(", ")" ]
Perform node expansion of network section.
[ "Perform", "node", "expansion", "of", "network", "section", "." ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L254-L260
BlueBrain/hpcbench
hpcbench/campaign.py
CampaignMerge.ensure_has_same_campaigns
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 = osp.join(self.rhs, 'campaign.yaml') assert osp.isfile(lhs_yaml) assert osp.isfile(rhs_yaml) assert filecmp.cmp(lhs_yaml, rhs_yaml)
python
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 = 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", ")", ":", "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", ")" ]
Ensure that the 2 campaigns to merge have been generated from the same campaign.yaml
[ "Ensure", "that", "the", "2", "campaigns", "to", "merge", "have", "been", "generated", "from", "the", "same", "campaign", ".", "yaml" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L531-L539
BlueBrain/hpcbench
hpcbench/campaign.py
ReportNode.path_context
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.strip(os.sep) attrs = self.CONTEXT_ATTRS for i, elt in enumerate(relative_path.split(os.sep)): yield attrs[i], elt yield 'path', path
python
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.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", ")", ":", "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" ]
Build of dictionary of fields extracted from the given path
[ "Build", "of", "dictionary", "of", "fields", "extracted", "from", "the", "given", "path" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L603-L612
BlueBrain/hpcbench
hpcbench/campaign.py
ReportNode.children
def children(self): """get children node referenced as `children` in the report. :rtype: dict with name (str) -> node (ReportNode) """ 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))
python
def children(self): """get children node referenced as `children` in the report. :rtype: dict with name (str) -> node (ReportNode) """ 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", ")", ":", "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", ")", ")" ]
get children node referenced as `children` in the report. :rtype: dict with name (str) -> node (ReportNode)
[ "get", "children", "node", "referenced", "as", "children", "in", "the", "report", ".", ":", "rtype", ":", "dict", "with", "name", "(", "str", ")", "-", ">", "node", "(", "ReportNode", ")" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L631-L638
BlueBrain/hpcbench
hpcbench/campaign.py
ReportNode.map
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 simply `func(self)` result. :rtype: generator """ 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
python
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 simply `func(self)` result. :rtype: generator """ 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", ")", ":", "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" ]
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 simply `func(self)` result. :rtype: generator
[ "Generator", "function", "returning", "result", "of", "func", "(", "self", ")" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L640-L657
BlueBrain/hpcbench
hpcbench/campaign.py
ReportNode.collect
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 tuple of 2 elements containing report-path and the value or simply the value. :type with_path: bool :rtype: generator providing either values or tuples of 2 elements containing report path and value depending on with_path parameter """ 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: values = values[0] if kwargs.get('with_path', False): yield self.path, values else: yield values if kwargs.get('recursive', True): for child in self.children.values(): for value in child.collect(*keys, **kwargs): yield value
python
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 tuple of 2 elements containing report-path and the value or simply the value. :type with_path: bool :rtype: generator providing either values or tuples of 2 elements containing report path and value depending on with_path parameter """ 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: values = values[0] if kwargs.get('with_path', False): yield self.path, values else: yield values if kwargs.get('recursive', True): for child in self.children.values(): for value in child.collect(*keys, **kwargs): yield value
[ "def", "collect", "(", "self", ",", "*", "keys", ",", "*", "*", "kwargs", ")", ":", "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", ":", "values", "=", "values", "[", "0", "]", "if", "kwargs", ".", "get", "(", "'with_path'", ",", "False", ")", ":", "yield", "self", ".", "path", ",", "values", "else", ":", "yield", "values", "if", "kwargs", ".", "get", "(", "'recursive'", ",", "True", ")", ":", "for", "child", "in", "self", ".", "children", ".", "values", "(", ")", ":", "for", "value", "in", "child", ".", "collect", "(", "*", "keys", ",", "*", "*", "kwargs", ")", ":", "yield", "value" ]
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 tuple of 2 elements containing report-path and the value or simply the value. :type with_path: bool :rtype: generator providing either values or tuples of 2 elements containing report path and value depending on with_path parameter
[ "Generator", "function", "traversing", "tree", "structure", "to", "collect", "values", "of", "a", "specified", "key", "." ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L659-L692
BlueBrain/hpcbench
hpcbench/campaign.py
ReportNode.collect_one
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`. """ 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 Exception('Expected exactly one value but have more')
python
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`. """ 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 Exception('Expected exactly one value but have more')
[ "def", "collect_one", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "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", "Exception", "(", "'Expected exactly one value but have more'", ")" ]
Same as `collect` but expects to have only one result. :return: the only result directly, not the generator like `collect`.
[ "Same", "as", "collect", "but", "expects", "to", "have", "only", "one", "result", "." ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/campaign.py#L694-L708
eng-tools/sfsimodels
sfsimodels/models/buildings.py
Frame.set_beam_prop
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: """ 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 not match number of bays (%i)." % self.n_bays) for ss in range(self.n_storeys): for i in range(self.n_bays): self._beams[ss][i].set_section_prop(prop, values[0][i])
python
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: """ 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 not match number of bays (%i)." % self.n_bays) for ss in range(self.n_storeys): for i in range(self.n_bays): self._beams[ss][i].set_section_prop(prop, values[0][i])
[ "def", "set_beam_prop", "(", "self", ",", "prop", ",", "values", ",", "repeat", "=", "\"up\"", ")", ":", "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 not match number of bays (%i).\"", "%", "self", ".", "n_bays", ")", "for", "ss", "in", "range", "(", "self", ".", "n_storeys", ")", ":", "for", "i", "in", "range", "(", "self", ".", "n_bays", ")", ":", "self", ".", "_beams", "[", "ss", "]", "[", "i", "]", ".", "set_section_prop", "(", "prop", ",", "values", "[", "0", "]", "[", "i", "]", ")" ]
Specify the properties of the beams :param values: :param repeat: if 'up' then duplicate up the structure :return:
[ "Specify", "the", "properties", "of", "the", "beams" ]
train
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/buildings.py#L391-L409
eng-tools/sfsimodels
sfsimodels/models/buildings.py
Frame.set_column_prop
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: """ 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 not match n_cols (%i)." % self.n_cols) for ss in range(self.n_storeys): for i in range(self.n_cols): self._columns[ss][i].set_section_prop(prop, values[0][i])
python
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: """ 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 not match n_cols (%i)." % self.n_cols) for ss in range(self.n_storeys): for i in range(self.n_cols): self._columns[ss][i].set_section_prop(prop, values[0][i])
[ "def", "set_column_prop", "(", "self", ",", "prop", ",", "values", ",", "repeat", "=", "\"up\"", ")", ":", "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 not match n_cols (%i).\"", "%", "self", ".", "n_cols", ")", "for", "ss", "in", "range", "(", "self", ".", "n_storeys", ")", ":", "for", "i", "in", "range", "(", "self", ".", "n_cols", ")", ":", "self", ".", "_columns", "[", "ss", "]", "[", "i", "]", ".", "set_section_prop", "(", "prop", ",", "values", "[", "0", "]", "[", "i", "]", ")" ]
Specify the properties of the columns :param values: :param repeat: if 'up' then duplicate up the structure :return:
[ "Specify", "the", "properties", "of", "the", "columns" ]
train
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/buildings.py#L411-L429
simonvh/norns
norns/cfg.py
Config.load
def load(self, path): """ Load yaml-formatted config file. Parameters ---------- path : str path to config file """ 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 = {}
python
def load(self, path): """ Load yaml-formatted config file. Parameters ---------- path : str path to config file """ 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", ")", ":", "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", "=", "{", "}" ]
Load yaml-formatted config file. Parameters ---------- path : str path to config file
[ "Load", "yaml", "-", "formatted", "config", "file", "." ]
train
https://github.com/simonvh/norns/blob/81db0004c558f91479176daf1918b8c9473b5ee2/norns/cfg.py#L60-L73
simonvh/norns
norns/cfg.py
Config.save
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))
python
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))
[ "def", "save", "(", "self", ")", ":", "with", "open", "(", "self", ".", "config_file", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "dump", "(", "self", ".", "config", ",", "default_flow_style", "=", "False", ")", ")" ]
Save current state of config dictionary.
[ "Save", "current", "state", "of", "config", "dictionary", "." ]
train
https://github.com/simonvh/norns/blob/81db0004c558f91479176daf1918b8c9473b5ee2/norns/cfg.py#L75-L80
Capitains/Nautilus
capitains_nautilus/flask_ext.py
FlaskNautilus.register
def register(self, extension, extension_name): """ Register an extension into the Nautilus Router :param extension: Extension :param extension_name: Name of the Extension :return: """ 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 ]) # This order allows for user defaults to overwrite extension ones self.Access_Control_Allow_Methods.update({ k: v for k, v in extension.Access_Control_Allow_Methods.items() if k not in self.Access_Control_Allow_Methods })
python
def register(self, extension, extension_name): """ Register an extension into the Nautilus Router :param extension: Extension :param extension_name: Name of the Extension :return: """ 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 ]) # This order allows for user defaults to overwrite extension ones self.Access_Control_Allow_Methods.update({ k: v for k, v in extension.Access_Control_Allow_Methods.items() if k not in self.Access_Control_Allow_Methods })
[ "def", "register", "(", "self", ",", "extension", ",", "extension_name", ")", ":", "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", "]", ")", "# This order allows for user defaults to overwrite extension ones", "self", ".", "Access_Control_Allow_Methods", ".", "update", "(", "{", "k", ":", "v", "for", "k", ",", "v", "in", "extension", ".", "Access_Control_Allow_Methods", ".", "items", "(", ")", "if", "k", "not", "in", "self", ".", "Access_Control_Allow_Methods", "}", ")" ]
Register an extension into the Nautilus Router :param extension: Extension :param extension_name: Name of the Extension :return:
[ "Register", "an", "extension", "into", "the", "Nautilus", "Router" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/flask_ext.py#L91-L113
Capitains/Nautilus
capitains_nautilus/flask_ext.py
FlaskNautilus.setLogger
def setLogger(self, logger): """ Set up the Logger for the application :param logger: logging.Logger object :return: Logger instance """ 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.setLevel(logging.INFO) stream.setFormatter(formatter) self.logger.addHandler(stream) if self.resolver: self.resolver.logger = self.logger return self.logger
python
def setLogger(self, logger): """ Set up the Logger for the application :param logger: logging.Logger object :return: Logger instance """ 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.setLevel(logging.INFO) stream.setFormatter(formatter) self.logger.addHandler(stream) if self.resolver: self.resolver.logger = self.logger return self.logger
[ "def", "setLogger", "(", "self", ",", "logger", ")", ":", "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", ".", "setLevel", "(", "logging", ".", "INFO", ")", "stream", ".", "setFormatter", "(", "formatter", ")", "self", ".", "logger", ".", "addHandler", "(", "stream", ")", "if", "self", ".", "resolver", ":", "self", ".", "resolver", ".", "logger", "=", "self", ".", "logger", "return", "self", ".", "logger" ]
Set up the Logger for the application :param logger: logging.Logger object :return: Logger instance
[ "Set", "up", "the", "Logger", "for", "the", "application" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/flask_ext.py#L119-L137
Capitains/Nautilus
capitains_nautilus/flask_ext.py
FlaskNautilus.init_app
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 """ 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__, self.flaskcache.memoize()(func) ) return self.blueprint
python
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 """ 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__, self.flaskcache.memoize()(func) ) return self.blueprint
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "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__", ",", "self", ".", "flaskcache", ".", "memoize", "(", ")", "(", "func", ")", ")", "return", "self", ".", "blueprint" ]
Initiate the extension on the application :param app: Flask Application :return: Blueprint for Flask Nautilus registered in app :rtype: Blueprint
[ "Initiate", "the", "extension", "on", "the", "application" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/flask_ext.py#L139-L158
Capitains/Nautilus
capitains_nautilus/flask_ext.py
FlaskNautilus.init_blueprint
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 """ 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: self.blueprint.add_url_rule( url, view_func=self.view(name, extension_name), endpoint=name[2:], methods=methods ) app.register_blueprint(self.blueprint) return self.blueprint
python
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 """ 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: self.blueprint.add_url_rule( url, view_func=self.view(name, extension_name), endpoint=name[2:], methods=methods ) app.register_blueprint(self.blueprint) return self.blueprint
[ "def", "init_blueprint", "(", "self", ",", "app", ")", ":", "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", ":", "self", ".", "blueprint", ".", "add_url_rule", "(", "url", ",", "view_func", "=", "self", ".", "view", "(", "name", ",", "extension_name", ")", ",", "endpoint", "=", "name", "[", "2", ":", "]", ",", "methods", "=", "methods", ")", "app", ".", "register_blueprint", "(", "self", ".", "blueprint", ")", "return", "self", ".", "blueprint" ]
Properly generates the blueprint, registering routes and filters and connecting the app and the blueprint :return: Blueprint of the extension :rtype: Blueprint
[ "Properly", "generates", "the", "blueprint", "registering", "routes", "and", "filters", "and", "connecting", "the", "app", "and", "the", "blueprint" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/flask_ext.py#L160-L183
Capitains/Nautilus
capitains_nautilus/flask_ext.py
FlaskNautilus.view
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 """ 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: d = { "Access-Control-Allow-Origin": self.Access_Control_Allow_Origin, "Access-Control-Allow-Methods": self.Access_Control_Allow_Methods[function_name] } def r(*x, **y): val = getattr(self._extensions[extension_name], function_name)(*x, **y) if isinstance(val, Response): val.headers.extend(d) return val else: val = list(val) val[2].update(d) return tuple(val) return r
python
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 """ 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: d = { "Access-Control-Allow-Origin": self.Access_Control_Allow_Origin, "Access-Control-Allow-Methods": self.Access_Control_Allow_Methods[function_name] } def r(*x, **y): val = getattr(self._extensions[extension_name], function_name)(*x, **y) if isinstance(val, Response): val.headers.extend(d) return val else: val = list(val) val[2].update(d) return tuple(val) return r
[ "def", "view", "(", "self", ",", "function_name", ",", "extension_name", ")", ":", "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", ":", "d", "=", "{", "\"Access-Control-Allow-Origin\"", ":", "self", ".", "Access_Control_Allow_Origin", ",", "\"Access-Control-Allow-Methods\"", ":", "self", ".", "Access_Control_Allow_Methods", "[", "function_name", "]", "}", "def", "r", "(", "*", "x", ",", "*", "*", "y", ")", ":", "val", "=", "getattr", "(", "self", ".", "_extensions", "[", "extension_name", "]", ",", "function_name", ")", "(", "*", "x", ",", "*", "*", "y", ")", "if", "isinstance", "(", "val", ",", "Response", ")", ":", "val", ".", "headers", ".", "extend", "(", "d", ")", "return", "val", "else", ":", "val", "=", "list", "(", "val", ")", "val", "[", "2", "]", ".", "update", "(", "d", ")", "return", "tuple", "(", "val", ")", "return", "r" ]
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
[ "Builds", "response", "according", "to", "a", "function", "name" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/flask_ext.py#L185-L212
PolyJIT/benchbuild
benchbuild/utils/slurm.py
script
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. """ 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"]: srun_args.append("--pstate-turbo=off") srun = srun[srun_args] srun = srun[benchbuild_c["run"]] return __save__(slurm_script, srun, experiment, projects)
python
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. """ 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"]: srun_args.append("--pstate-turbo=off") srun = srun[srun_args] srun = srun[benchbuild_c["run"]] return __save__(slurm_script, srun, experiment, projects)
[ "def", "script", "(", "experiment", ",", "projects", ")", ":", "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\"", "]", ":", "srun_args", ".", "append", "(", "\"--pstate-turbo=off\"", ")", "srun", "=", "srun", "[", "srun_args", "]", "srun", "=", "srun", "[", "benchbuild_c", "[", "\"run\"", "]", "]", "return", "__save__", "(", "slurm_script", ",", "srun", ",", "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.
[ "Prepare", "a", "slurm", "script", "that", "executes", "the", "experiment", "for", "a", "given", "project", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/slurm.py#L20-L42
mromanello/hucitlib
scripts/populate.py
fetch_text_structure
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 with keys "urn", "provenance", "valid_reffs", "levels" :rtype: dict """ 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 this work, pick the one in Greek or Latin try: orig_edition = next(iter( work_metadata.children[edition] for edition in work_metadata.children if suffix in str(work_metadata.children[edition].urn) )) except Exception as e: print(e) return None assert orig_edition is not None # get information about the work's citation scheme structure["levels"] = [ (n + 1, level.name.lower()) for n, level in enumerate(orig_edition.citation) ] # for each hierarchical level of the text # fetch all citable text elements for level_n, level_label in structure["levels"]: structure["valid_reffs"][level_n] = [] for ref in resolver.getReffs(urn, level=level_n): print(ref) element = { "current": "{}:{}".format(urn, ref), } if "." in ref: element["parent"] = "{}:{}".format( urn, ".".join(ref.split(".")[:level_n - 1]) ) # TODO: parallelize this bit textual_node = resolver.getTextualNode( textId=urn, subreference=ref, prevnext=True ) if textual_node.nextId is not None: element["previous"] = "{}:{}".format(urn, textual_node.nextId) if textual_node.prevId is not None: element["following"] = "{}:{}".format(urn, textual_node.prevId) structure["valid_reffs"][level_n].append(element) return structure
python
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 with keys "urn", "provenance", "valid_reffs", "levels" :rtype: dict """ 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 this work, pick the one in Greek or Latin try: orig_edition = next(iter( work_metadata.children[edition] for edition in work_metadata.children if suffix in str(work_metadata.children[edition].urn) )) except Exception as e: print(e) return None assert orig_edition is not None # get information about the work's citation scheme structure["levels"] = [ (n + 1, level.name.lower()) for n, level in enumerate(orig_edition.citation) ] # for each hierarchical level of the text # fetch all citable text elements for level_n, level_label in structure["levels"]: structure["valid_reffs"][level_n] = [] for ref in resolver.getReffs(urn, level=level_n): print(ref) element = { "current": "{}:{}".format(urn, ref), } if "." in ref: element["parent"] = "{}:{}".format( urn, ".".join(ref.split(".")[:level_n - 1]) ) # TODO: parallelize this bit textual_node = resolver.getTextualNode( textId=urn, subreference=ref, prevnext=True ) if textual_node.nextId is not None: element["previous"] = "{}:{}".format(urn, textual_node.nextId) if textual_node.prevId is not None: element["following"] = "{}:{}".format(urn, textual_node.prevId) structure["valid_reffs"][level_n].append(element) return structure
[ "def", "fetch_text_structure", "(", "urn", ",", "endpoint", "=", "\"http://cts.perseids.org/api/cts\"", ")", ":", "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 this work, pick the one in Greek or Latin", "try", ":", "orig_edition", "=", "next", "(", "iter", "(", "work_metadata", ".", "children", "[", "edition", "]", "for", "edition", "in", "work_metadata", ".", "children", "if", "suffix", "in", "str", "(", "work_metadata", ".", "children", "[", "edition", "]", ".", "urn", ")", ")", ")", "except", "Exception", "as", "e", ":", "print", "(", "e", ")", "return", "None", "assert", "orig_edition", "is", "not", "None", "# get information about the work's citation scheme", "structure", "[", "\"levels\"", "]", "=", "[", "(", "n", "+", "1", ",", "level", ".", "name", ".", "lower", "(", ")", ")", "for", "n", ",", "level", "in", "enumerate", "(", "orig_edition", ".", "citation", ")", "]", "# for each hierarchical level of the text", "# fetch all citable text elements", "for", "level_n", ",", "level_label", "in", "structure", "[", "\"levels\"", "]", ":", "structure", "[", "\"valid_reffs\"", "]", "[", "level_n", "]", "=", "[", "]", "for", "ref", "in", "resolver", ".", "getReffs", "(", "urn", ",", "level", "=", "level_n", ")", ":", "print", "(", "ref", ")", "element", "=", "{", "\"current\"", ":", "\"{}:{}\"", ".", "format", "(", "urn", ",", "ref", ")", ",", "}", "if", "\".\"", "in", "ref", ":", "element", "[", "\"parent\"", "]", "=", "\"{}:{}\"", ".", "format", "(", "urn", ",", "\".\"", ".", "join", "(", "ref", ".", "split", "(", "\".\"", ")", "[", ":", "level_n", "-", "1", "]", ")", ")", "# TODO: parallelize this bit", "textual_node", "=", "resolver", ".", "getTextualNode", "(", "textId", "=", "urn", ",", "subreference", "=", "ref", ",", "prevnext", "=", "True", ")", "if", "textual_node", ".", "nextId", "is", "not", "None", ":", "element", "[", "\"previous\"", "]", "=", "\"{}:{}\"", ".", "format", "(", "urn", ",", "textual_node", ".", "nextId", ")", "if", "textual_node", ".", "prevId", "is", "not", "None", ":", "element", "[", "\"following\"", "]", "=", "\"{}:{}\"", ".", "format", "(", "urn", ",", "textual_node", ".", "prevId", ")", "structure", "[", "\"valid_reffs\"", "]", "[", "level_n", "]", ".", "append", "(", "element", ")", "return", "structure" ]
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 with keys "urn", "provenance", "valid_reffs", "levels" :rtype: dict
[ "Fetches", "the", "text", "structure", "of", "a", "given", "work", "from", "a", "CTS", "endpoint", "." ]
train
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/scripts/populate.py#L34-L104
PolyJIT/benchbuild
benchbuild/experiments/empty.py
NoMeasurement.actions_for_project
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)
python
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)
[ "def", "actions_for_project", "(", "self", ",", "project", ")", ":", "project", ".", "runtime_extension", "=", "run", ".", "RuntimeExtension", "(", "project", ",", "self", ")", "return", "self", ".", "default_runtime_actions", "(", "project", ")" ]
Execute all actions but don't do anything as extension.
[ "Execute", "all", "actions", "but", "don", "t", "do", "anything", "as", "extension", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/experiments/empty.py#L28-L31
PolyJIT/benchbuild
benchbuild/utils/bootstrap.py
install_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['uchroot']['repo']) erlent_build = erlent_src / 'build' if not erlent_git.exists(): git("clone", erlent_repo) else: with local.cwd(erlent_src): git("pull", "--rebase") erlent_build.mkdir() with local.cwd(erlent_build): cmake("../") make() os.environ["PATH"] = os.path.pathsep.join( [erlent_build, os.environ["PATH"]]) local.env.update(PATH=os.environ["PATH"]) if not find_package("uchroot"): LOG.error('uchroot not found, after updating PATH to %s', os.environ['PATH']) sys.exit(-1) env = CFG['env'].value if 'PATH' not in env: env['PATH'] = [] env['PATH'].append(str(erlent_build))
python
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['uchroot']['repo']) erlent_build = erlent_src / 'build' if not erlent_git.exists(): git("clone", erlent_repo) else: with local.cwd(erlent_src): git("pull", "--rebase") erlent_build.mkdir() with local.cwd(erlent_build): cmake("../") make() os.environ["PATH"] = os.path.pathsep.join( [erlent_build, os.environ["PATH"]]) local.env.update(PATH=os.environ["PATH"]) if not find_package("uchroot"): LOG.error('uchroot not found, after updating PATH to %s', os.environ['PATH']) sys.exit(-1) env = CFG['env'].value if 'PATH' not in env: env['PATH'] = [] env['PATH'].append(str(erlent_build))
[ "def", "install_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", "[", "'uchroot'", "]", "[", "'repo'", "]", ")", "erlent_build", "=", "erlent_src", "/", "'build'", "if", "not", "erlent_git", ".", "exists", "(", ")", ":", "git", "(", "\"clone\"", ",", "erlent_repo", ")", "else", ":", "with", "local", ".", "cwd", "(", "erlent_src", ")", ":", "git", "(", "\"pull\"", ",", "\"--rebase\"", ")", "erlent_build", ".", "mkdir", "(", ")", "with", "local", ".", "cwd", "(", "erlent_build", ")", ":", "cmake", "(", "\"../\"", ")", "make", "(", ")", "os", ".", "environ", "[", "\"PATH\"", "]", "=", "os", ".", "path", ".", "pathsep", ".", "join", "(", "[", "erlent_build", ",", "os", ".", "environ", "[", "\"PATH\"", "]", "]", ")", "local", ".", "env", ".", "update", "(", "PATH", "=", "os", ".", "environ", "[", "\"PATH\"", "]", ")", "if", "not", "find_package", "(", "\"uchroot\"", ")", ":", "LOG", ".", "error", "(", "'uchroot not found, after updating PATH to %s'", ",", "os", ".", "environ", "[", "'PATH'", "]", ")", "sys", ".", "exit", "(", "-", "1", ")", "env", "=", "CFG", "[", "'env'", "]", ".", "value", "if", "'PATH'", "not", "in", "env", ":", "env", "[", "'PATH'", "]", "=", "[", "]", "env", "[", "'PATH'", "]", ".", "append", "(", "str", "(", "erlent_build", ")", ")" ]
Installer for erlent (contains uchroot).
[ "Installer", "for", "erlent", "(", "contains", "uchroot", ")", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/bootstrap.py#L74-L105
PolyJIT/benchbuild
benchbuild/cli/run.py
print_summary
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. """ num_failed = len(failed) print(""" Summary: {num_total} actions were in the queue. {num_failed} actions failed to execute. This run took: {elapsed_time:8.3f} seconds. """.format( num_total=num_actions, num_failed=num_failed, elapsed_time=duration))
python
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. """ num_failed = len(failed) print(""" Summary: {num_total} actions were in the queue. {num_failed} actions failed to execute. This run took: {elapsed_time:8.3f} seconds. """.format( num_total=num_actions, num_failed=num_failed, elapsed_time=duration))
[ "def", "print_summary", "(", "num_actions", ",", "failed", ",", "duration", ")", ":", "num_failed", "=", "len", "(", "failed", ")", "print", "(", "\"\"\"\nSummary:\n{num_total} actions were in the queue.\n{num_failed} actions failed to execute.\n\nThis run took: {elapsed_time:8.3f} seconds.\n \"\"\"", ".", "format", "(", "num_total", "=", "num_actions", ",", "num_failed", "=", "num_failed", ",", "elapsed_time", "=", "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.
[ "Print", "a", "small", "summary", "of", "the", "executed", "plan", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/cli/run.py#L143-L160
eng-tools/sfsimodels
sfsimodels/sensors.py
read_json_sensor_file
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(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
python
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(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", ")", ":", "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" ]
Reads the sensor file and stores it as a dictionary. :param ffp: full file path to json file :return:
[ "Reads", "the", "sensor", "file", "and", "stores", "it", "as", "a", "dictionary", "." ]
train
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/sensors.py#L4-L16
eng-tools/sfsimodels
sfsimodels/sensors.py
get_all_sensor_codes
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: """ 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_codes = [] for mtype in mtypes: for m_number in si[mtype]: if x in ["*", si[mtype][m_number]['X-CODE']] and \ y in ["*", si[mtype][m_number]['Y-CODE']] and \ z in ["*", si[mtype][m_number]['Z-CODE']]: cc = get_sensor_code_by_number(si, mtype, m_number) all_sensor_codes.append(cc) return all_sensor_codes
python
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: """ 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_codes = [] for mtype in mtypes: for m_number in si[mtype]: if x in ["*", si[mtype][m_number]['X-CODE']] and \ y in ["*", si[mtype][m_number]['Y-CODE']] and \ z in ["*", si[mtype][m_number]['Z-CODE']]: cc = get_sensor_code_by_number(si, mtype, m_number) all_sensor_codes.append(cc) return all_sensor_codes
[ "def", "get_all_sensor_codes", "(", "si", ",", "wild_sensor_code", ")", ":", "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_codes", "=", "[", "]", "for", "mtype", "in", "mtypes", ":", "for", "m_number", "in", "si", "[", "mtype", "]", ":", "if", "x", "in", "[", "\"*\"", ",", "si", "[", "mtype", "]", "[", "m_number", "]", "[", "'X-CODE'", "]", "]", "and", "y", "in", "[", "\"*\"", ",", "si", "[", "mtype", "]", "[", "m_number", "]", "[", "'Y-CODE'", "]", "]", "and", "z", "in", "[", "\"*\"", ",", "si", "[", "mtype", "]", "[", "m_number", "]", "[", "'Z-CODE'", "]", "]", ":", "cc", "=", "get_sensor_code_by_number", "(", "si", ",", "mtype", ",", "m_number", ")", "all_sensor_codes", ".", "append", "(", "cc", ")", "return", "all_sensor_codes" ]
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:
[ "Get", "all", "sensor", "sensor_codes", "that", "match", "a", "wild", "sensor", "code" ]
train
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/sensors.py#L19-L44
eng-tools/sfsimodels
sfsimodels/sensors.py
get_sensor_code_by_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 (e.g. ACCX-UB1-L2C-M) """ 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]['X-CODE'], si[mtype][sensor_number]['Y-CODE'], si[mtype][sensor_number]['Z-CODE']) except KeyError: if quiet: return None raise
python
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 (e.g. ACCX-UB1-L2C-M) """ 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]['X-CODE'], si[mtype][sensor_number]['Y-CODE'], si[mtype][sensor_number]['Z-CODE']) except KeyError: if quiet: return None raise
[ "def", "get_sensor_code_by_number", "(", "si", ",", "mtype", ",", "sensor_number", ",", "quiet", "=", "False", ")", ":", "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", "]", "[", "'X-CODE'", "]", ",", "si", "[", "mtype", "]", "[", "sensor_number", "]", "[", "'Y-CODE'", "]", ",", "si", "[", "mtype", "]", "[", "sensor_number", "]", "[", "'Z-CODE'", "]", ")", "except", "KeyError", ":", "if", "quiet", ":", "return", "None", "raise" ]
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 (e.g. ACCX-UB1-L2C-M)
[ "Given", "a", "sensor", "number", "get", "the", "full", "sensor", "code", "(", "e", ".", "g", ".", "ACCX", "-", "UB1", "-", "L2C", "-", "M", ")" ]
train
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/sensors.py#L59-L82
eng-tools/sfsimodels
sfsimodels/sensors.py
get_mtype_and_number_from_code
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: """ 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_number) if cc == sensor_code: return mtype, m_number return None, None
python
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: """ 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_number) if cc == sensor_code: return mtype, m_number return None, None
[ "def", "get_mtype_and_number_from_code", "(", "si", ",", "sensor_code", ")", ":", "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_number", ")", "if", "cc", "==", "sensor_code", ":", "return", "mtype", ",", "m_number", "return", "None", ",", "None" ]
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:
[ "Given", "a", "sensor", "sensor_code", "get", "motion", "type", "and", "sensor", "number" ]
train
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/sensors.py#L85-L102
bjodah/pycompilation
pycompilation/dist.py
PCExtension
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 """ 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 distutils extra_compile_args? 'pycompilation_compile_kwargs': {}, 'pycompilation_link_kwargs': {}, } for k, v in intercept.items(): vals[k] = kwargs.pop(k, v) intercept2 = { 'logger': None, 'only_update': True, } for k, v in intercept2.items(): vck = kwargs.pop(k, v) vck = vals['pycompilation_compile_kwargs'].pop(k, vck) vck = vck or vals['pycompilation_link_kwargs'].pop(k, vck) vals[k] = vck instance = Extension(*args, **kwargs) if vals['logger'] is True: # interpret as we should instantiate a logger import logging logging.basicConfig(level=logging.DEBUG) vals['logger'] = logging.getLogger('PCExtension') for k, v in vals.items(): setattr(instance, k, v) return instance
python
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 """ 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 distutils extra_compile_args? 'pycompilation_compile_kwargs': {}, 'pycompilation_link_kwargs': {}, } for k, v in intercept.items(): vals[k] = kwargs.pop(k, v) intercept2 = { 'logger': None, 'only_update': True, } for k, v in intercept2.items(): vck = kwargs.pop(k, v) vck = vals['pycompilation_compile_kwargs'].pop(k, vck) vck = vck or vals['pycompilation_link_kwargs'].pop(k, vck) vals[k] = vck instance = Extension(*args, **kwargs) if vals['logger'] is True: # interpret as we should instantiate a logger import logging logging.basicConfig(level=logging.DEBUG) vals['logger'] = logging.getLogger('PCExtension') for k, v in vals.items(): setattr(instance, k, v) return instance
[ "def", "PCExtension", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "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 distutils extra_compile_args?", "'pycompilation_compile_kwargs'", ":", "{", "}", ",", "'pycompilation_link_kwargs'", ":", "{", "}", ",", "}", "for", "k", ",", "v", "in", "intercept", ".", "items", "(", ")", ":", "vals", "[", "k", "]", "=", "kwargs", ".", "pop", "(", "k", ",", "v", ")", "intercept2", "=", "{", "'logger'", ":", "None", ",", "'only_update'", ":", "True", ",", "}", "for", "k", ",", "v", "in", "intercept2", ".", "items", "(", ")", ":", "vck", "=", "kwargs", ".", "pop", "(", "k", ",", "v", ")", "vck", "=", "vals", "[", "'pycompilation_compile_kwargs'", "]", ".", "pop", "(", "k", ",", "vck", ")", "vck", "=", "vck", "or", "vals", "[", "'pycompilation_link_kwargs'", "]", ".", "pop", "(", "k", ",", "vck", ")", "vals", "[", "k", "]", "=", "vck", "instance", "=", "Extension", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "vals", "[", "'logger'", "]", "is", "True", ":", "# interpret as we should instantiate a logger", "import", "logging", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "DEBUG", ")", "vals", "[", "'logger'", "]", "=", "logging", ".", "getLogger", "(", "'PCExtension'", ")", "for", "k", ",", "v", "in", "vals", ".", "items", "(", ")", ":", "setattr", "(", "instance", ",", "k", ",", "v", ")", "return", "instance" ]
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
[ "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" ]
train
https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/dist.py#L25-L71
bjodah/pycompilation
pycompilation/dist.py
_copy_or_render_source
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. """ # 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)) rw = MetaReaderWriter('.metadata_subsd') try: prev_subsd = rw.get_from_metadata_file(output_dir, f) except (FileNotFoundError, KeyError): prev_subsd = None render_callback( get_abspath(f), os.path.join(output_dir, tgt), subsd, only_update=ext.only_update, prev_subsd=prev_subsd, create_dest_dirs=True, logger=ext.logger) rw.save_to_metadata_file(output_dir, f, subsd) return tgt else: if not skip_copy: copy(f, os.path.join(output_dir, os.path.dirname(f)), only_update=ext.only_update, dest_is_dir=True, create_dest_dirs=True, logger=ext.logger) return f
python
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. """ # 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)) rw = MetaReaderWriter('.metadata_subsd') try: prev_subsd = rw.get_from_metadata_file(output_dir, f) except (FileNotFoundError, KeyError): prev_subsd = None render_callback( get_abspath(f), os.path.join(output_dir, tgt), subsd, only_update=ext.only_update, prev_subsd=prev_subsd, create_dest_dirs=True, logger=ext.logger) rw.save_to_metadata_file(output_dir, f, subsd) return tgt else: if not skip_copy: copy(f, os.path.join(output_dir, os.path.dirname(f)), only_update=ext.only_update, dest_is_dir=True, create_dest_dirs=True, logger=ext.logger) return f
[ "def", "_copy_or_render_source", "(", "ext", ",", "f", ",", "output_dir", ",", "render_callback", ",", "skip_copy", "=", "False", ")", ":", "# 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", ")", ")", "rw", "=", "MetaReaderWriter", "(", "'.metadata_subsd'", ")", "try", ":", "prev_subsd", "=", "rw", ".", "get_from_metadata_file", "(", "output_dir", ",", "f", ")", "except", "(", "FileNotFoundError", ",", "KeyError", ")", ":", "prev_subsd", "=", "None", "render_callback", "(", "get_abspath", "(", "f", ")", ",", "os", ".", "path", ".", "join", "(", "output_dir", ",", "tgt", ")", ",", "subsd", ",", "only_update", "=", "ext", ".", "only_update", ",", "prev_subsd", "=", "prev_subsd", ",", "create_dest_dirs", "=", "True", ",", "logger", "=", "ext", ".", "logger", ")", "rw", ".", "save_to_metadata_file", "(", "output_dir", ",", "f", ",", "subsd", ")", "return", "tgt", "else", ":", "if", "not", "skip_copy", ":", "copy", "(", "f", ",", "os", ".", "path", ".", "join", "(", "output_dir", ",", "os", ".", "path", ".", "dirname", "(", "f", ")", ")", ",", "only_update", "=", "ext", ".", "only_update", ",", "dest_is_dir", "=", "True", ",", "create_dest_dirs", "=", "True", ",", "logger", "=", "ext", ".", "logger", ")", "return", "f" ]
Tries to do regex match for each (pattern, target, subsd) tuple in ext.template_regexps for file f.
[ "Tries", "to", "do", "regex", "match", "for", "each", "(", "pattern", "target", "subsd", ")", "tuple", "in", "ext", ".", "template_regexps", "for", "file", "f", "." ]
train
https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/dist.py#L74-L112
bjodah/pycompilation
pycompilation/dist.py
render_python_template_to
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. """ 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.format(src)) return with open(src, 'rt') as ifh: data = ifh.read() # Don't go crazy on file size... if create_dest_dirs: dest_dir = os.path.dirname(dest) if not os.path.exists(dest_dir): make_dirs(dest_dir) with open(dest, 'wt') as ofh: ofh.write(data % subsd)
python
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. """ 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.format(src)) return with open(src, 'rt') as ifh: data = ifh.read() # Don't go crazy on file size... if create_dest_dirs: dest_dir = os.path.dirname(dest) if not os.path.exists(dest_dir): make_dirs(dest_dir) with open(dest, 'wt') as ofh: ofh.write(data % subsd)
[ "def", "render_python_template_to", "(", "src", ",", "dest", ",", "subsd", ",", "only_update", "=", "False", ",", "prev_subsd", "=", "None", ",", "create_dest_dirs", "=", "True", ",", "logger", "=", "None", ")", ":", "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", ".", "format", "(", "src", ")", ")", "return", "with", "open", "(", "src", ",", "'rt'", ")", "as", "ifh", ":", "data", "=", "ifh", ".", "read", "(", ")", "# Don't go crazy on file size...", "if", "create_dest_dirs", ":", "dest_dir", "=", "os", ".", "path", ".", "dirname", "(", "dest", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dest_dir", ")", ":", "make_dirs", "(", "dest_dir", ")", "with", "open", "(", "dest", ",", "'wt'", ")", "as", "ofh", ":", "ofh", ".", "write", "(", "data", "%", "subsd", ")" ]
Overload this function if you want to use a template engine such as e.g. mako.
[ "Overload", "this", "function", "if", "you", "want", "to", "use", "a", "template", "engine", "such", "as", "e", ".", "g", ".", "mako", "." ]
train
https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/dist.py#L115-L140
mromanello/hucitlib
knowledge_base/surfext/__init__.py
HucitAuthor.get_names
def get_names(self): """ Returns a dict where key is the language and value is the name in that language. Example: {'it':"Sofocle"} """ 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
python
def get_names(self): """ Returns a dict where key is the language and value is the name in that language. Example: {'it':"Sofocle"} """ 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", ")", ":", "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" ]
Returns a dict where key is the language and value is the name in that language. Example: {'it':"Sofocle"}
[ "Returns", "a", "dict", "where", "key", "is", "the", "language", "and", "value", "is", "the", "name", "in", "that", "language", "." ]
train
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L67-L79
mromanello/hucitlib
knowledge_base/surfext/__init__.py
HucitAuthor.add_name
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) """ 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) if lang is not None else \ Literal(name) name = [ id for id in self.ecrm_P1_is_identified_by if id.uri == surf.ns.EFRBROO['F12_Name'] ][0] try: name.rdfs_label.append(newlabel) name.update() return True except Exception as e: raise e
python
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) """ 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) if lang is not None else \ Literal(name) name = [ id for id in self.ecrm_P1_is_identified_by if id.uri == surf.ns.EFRBROO['F12_Name'] ][0] try: name.rdfs_label.append(newlabel) name.update() return True except Exception as e: raise e
[ "def", "add_name", "(", "self", ",", "name", ",", "lang", "=", "None", ")", ":", "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", ")", "if", "lang", "is", "not", "None", "else", "Literal", "(", "name", ")", "name", "=", "[", "id", "for", "id", "in", "self", ".", "ecrm_P1_is_identified_by", "if", "id", ".", "uri", "==", "surf", ".", "ns", ".", "EFRBROO", "[", "'F12_Name'", "]", "]", "[", "0", "]", "try", ":", "name", ".", "rdfs_label", ".", "append", "(", "newlabel", ")", "name", ".", "update", "(", ")", "return", "True", "except", "Exception", "as", "e", ":", "raise", "e" ]
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)
[ "Adds", "a", "new", "name", "variant", "to", "an", "author", "." ]
train
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L81-L107
mromanello/hucitlib
knowledge_base/surfext/__init__.py
HucitAuthor.add_abbreviation
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) """ 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_abbreviation = self.session.get_resource(BASE_URI_TYPES % "abbreviation" , self.session.get_class(surf.ns.ECRM['E55_Type'])) abbreviation = [abbreviation for name in self.ecrm_P1_is_identified_by for abbreviation in name.ecrm_P139_has_alternative_form if name.uri == surf.ns.EFRBROO['F12_Name'] and abbreviation.ecrm_P2_has_type.first == type_abbreviation][0] abbreviation.rdfs_label.append(Literal(new_abbreviation)) abbreviation.update() return True except IndexError as e: # means there is no abbreviation instance yet type_abbreviation = self.session.get_resource(BASE_URI_TYPES % "abbreviation" , self.session.get_class(surf.ns.ECRM['E55_Type'])) Appellation = self.session.get_class(surf.ns.ECRM['E41_Appellation']) abbreviation_uri = "%s/abbr" % str(self.subject) abbreviation = Appellation(abbreviation_uri) abbreviation.ecrm_P2_has_type = type_abbreviation abbreviation.rdfs_label.append(Literal(new_abbreviation)) abbreviation.save() name = (name for name in self.ecrm_P1_is_identified_by if name.uri == surf.ns.EFRBROO['F12_Name']).next() name.ecrm_P139_has_alternative_form = abbreviation name.update() return True except Exception as e: raise e
python
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) """ 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_abbreviation = self.session.get_resource(BASE_URI_TYPES % "abbreviation" , self.session.get_class(surf.ns.ECRM['E55_Type'])) abbreviation = [abbreviation for name in self.ecrm_P1_is_identified_by for abbreviation in name.ecrm_P139_has_alternative_form if name.uri == surf.ns.EFRBROO['F12_Name'] and abbreviation.ecrm_P2_has_type.first == type_abbreviation][0] abbreviation.rdfs_label.append(Literal(new_abbreviation)) abbreviation.update() return True except IndexError as e: # means there is no abbreviation instance yet type_abbreviation = self.session.get_resource(BASE_URI_TYPES % "abbreviation" , self.session.get_class(surf.ns.ECRM['E55_Type'])) Appellation = self.session.get_class(surf.ns.ECRM['E41_Appellation']) abbreviation_uri = "%s/abbr" % str(self.subject) abbreviation = Appellation(abbreviation_uri) abbreviation.ecrm_P2_has_type = type_abbreviation abbreviation.rdfs_label.append(Literal(new_abbreviation)) abbreviation.save() name = (name for name in self.ecrm_P1_is_identified_by if name.uri == surf.ns.EFRBROO['F12_Name']).next() name.ecrm_P139_has_alternative_form = abbreviation name.update() return True except Exception as e: raise e
[ "def", "add_abbreviation", "(", "self", ",", "new_abbreviation", ")", ":", "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_abbreviation", "=", "self", ".", "session", ".", "get_resource", "(", "BASE_URI_TYPES", "%", "\"abbreviation\"", ",", "self", ".", "session", ".", "get_class", "(", "surf", ".", "ns", ".", "ECRM", "[", "'E55_Type'", "]", ")", ")", "abbreviation", "=", "[", "abbreviation", "for", "name", "in", "self", ".", "ecrm_P1_is_identified_by", "for", "abbreviation", "in", "name", ".", "ecrm_P139_has_alternative_form", "if", "name", ".", "uri", "==", "surf", ".", "ns", ".", "EFRBROO", "[", "'F12_Name'", "]", "and", "abbreviation", ".", "ecrm_P2_has_type", ".", "first", "==", "type_abbreviation", "]", "[", "0", "]", "abbreviation", ".", "rdfs_label", ".", "append", "(", "Literal", "(", "new_abbreviation", ")", ")", "abbreviation", ".", "update", "(", ")", "return", "True", "except", "IndexError", "as", "e", ":", "# means there is no abbreviation instance yet", "type_abbreviation", "=", "self", ".", "session", ".", "get_resource", "(", "BASE_URI_TYPES", "%", "\"abbreviation\"", ",", "self", ".", "session", ".", "get_class", "(", "surf", ".", "ns", ".", "ECRM", "[", "'E55_Type'", "]", ")", ")", "Appellation", "=", "self", ".", "session", ".", "get_class", "(", "surf", ".", "ns", ".", "ECRM", "[", "'E41_Appellation'", "]", ")", "abbreviation_uri", "=", "\"%s/abbr\"", "%", "str", "(", "self", ".", "subject", ")", "abbreviation", "=", "Appellation", "(", "abbreviation_uri", ")", "abbreviation", ".", "ecrm_P2_has_type", "=", "type_abbreviation", "abbreviation", ".", "rdfs_label", ".", "append", "(", "Literal", "(", "new_abbreviation", ")", ")", "abbreviation", ".", "save", "(", ")", "name", "=", "(", "name", "for", "name", "in", "self", ".", "ecrm_P1_is_identified_by", "if", "name", ".", "uri", "==", "surf", ".", "ns", ".", "EFRBROO", "[", "'F12_Name'", "]", ")", ".", "next", "(", ")", "name", ".", "ecrm_P139_has_alternative_form", "=", "abbreviation", "name", ".", "update", "(", ")", "return", "True", "except", "Exception", "as", "e", ":", "raise", "e" ]
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)
[ "Adds", "a", "new", "name", "variant", "to", "an", "author", "." ]
train
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L121-L162
mromanello/hucitlib
knowledge_base/surfext/__init__.py
HucitAuthor.get_abbreviations
def get_abbreviations(self): """ Get abbreviations of the names of the author. :return: a list of strings (empty list if no abbreviations available). """ abbreviations = [] try: type_abbreviation = self.session.get_resource(BASE_URI_TYPES % "abbreviation" , self.session.get_class(surf.ns.ECRM['E55_Type'])) abbreviations = [unicode(label) for name in self.ecrm_P1_is_identified_by for abbreviation in name.ecrm_P139_has_alternative_form for label in abbreviation.rdfs_label if name.uri == surf.ns.EFRBROO['F12_Name'] and abbreviation.ecrm_P2_has_type.first == type_abbreviation] except Exception as e: logger.debug("Exception raised when getting abbreviations for %a"%self) finally: return abbreviations
python
def get_abbreviations(self): """ Get abbreviations of the names of the author. :return: a list of strings (empty list if no abbreviations available). """ abbreviations = [] try: type_abbreviation = self.session.get_resource(BASE_URI_TYPES % "abbreviation" , self.session.get_class(surf.ns.ECRM['E55_Type'])) abbreviations = [unicode(label) for name in self.ecrm_P1_is_identified_by for abbreviation in name.ecrm_P139_has_alternative_form for label in abbreviation.rdfs_label if name.uri == surf.ns.EFRBROO['F12_Name'] and abbreviation.ecrm_P2_has_type.first == type_abbreviation] except Exception as e: logger.debug("Exception raised when getting abbreviations for %a"%self) finally: return abbreviations
[ "def", "get_abbreviations", "(", "self", ")", ":", "abbreviations", "=", "[", "]", "try", ":", "type_abbreviation", "=", "self", ".", "session", ".", "get_resource", "(", "BASE_URI_TYPES", "%", "\"abbreviation\"", ",", "self", ".", "session", ".", "get_class", "(", "surf", ".", "ns", ".", "ECRM", "[", "'E55_Type'", "]", ")", ")", "abbreviations", "=", "[", "unicode", "(", "label", ")", "for", "name", "in", "self", ".", "ecrm_P1_is_identified_by", "for", "abbreviation", "in", "name", ".", "ecrm_P139_has_alternative_form", "for", "label", "in", "abbreviation", ".", "rdfs_label", "if", "name", ".", "uri", "==", "surf", ".", "ns", ".", "EFRBROO", "[", "'F12_Name'", "]", "and", "abbreviation", ".", "ecrm_P2_has_type", ".", "first", "==", "type_abbreviation", "]", "except", "Exception", "as", "e", ":", "logger", ".", "debug", "(", "\"Exception raised when getting abbreviations for %a\"", "%", "self", ")", "finally", ":", "return", "abbreviations" ]
Get abbreviations of the names of the author. :return: a list of strings (empty list if no abbreviations available).
[ "Get", "abbreviations", "of", "the", "names", "of", "the", "author", "." ]
train
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L164-L183
mromanello/hucitlib
knowledge_base/surfext/__init__.py
HucitAuthor.get_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" , self.session.get_class(surf.ns.ECRM['E55_Type'])) urn = [CTS_URN(urnstring.rdfs_label.one) for urnstring in self.ecrm_P1_is_identified_by if urnstring.uri == surf.ns.ECRM['E42_Identifier'] and urnstring.ecrm_P2_has_type.first == type_ctsurn][0] return urn except Exception as e: return None
python
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" , self.session.get_class(surf.ns.ECRM['E55_Type'])) urn = [CTS_URN(urnstring.rdfs_label.one) for urnstring in self.ecrm_P1_is_identified_by if urnstring.uri == surf.ns.ECRM['E42_Identifier'] and urnstring.ecrm_P2_has_type.first == type_ctsurn][0] return urn except Exception as e: return None
[ "def", "get_urn", "(", "self", ")", ":", "# 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", "urnstring", "in", "self", ".", "ecrm_P1_is_identified_by", "if", "urnstring", ".", "uri", "==", "surf", ".", "ns", ".", "ECRM", "[", "'E42_Identifier'", "]", "and", "urnstring", ".", "ecrm_P2_has_type", ".", "first", "==", "type_ctsurn", "]", "[", "0", "]", "return", "urn", "except", "Exception", "as", "e", ":", "return", "None" ]
Assumes that each HucitAuthor has only one CTS URN.
[ "Assumes", "that", "each", "HucitAuthor", "has", "only", "one", "CTS", "URN", "." ]
train
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L185-L199
mromanello/hucitlib
knowledge_base/surfext/__init__.py
HucitAuthor.set_urn
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.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 = Type(BASE_URI_TYPES % "CTS_URN") id.save() return True except Exception, e: raise e
python
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.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 = Type(BASE_URI_TYPES % "CTS_URN") id.save() return True except Exception, e: raise e
[ "def", "set_urn", "(", "self", ",", "urn", ")", ":", "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", "=", "Type", "(", "BASE_URI_TYPES", "%", "\"CTS_URN\"", ")", "id", ".", "save", "(", ")", "return", "True", "except", "Exception", ",", "e", ":", "raise", "e" ]
Change the CTS URN of the author or adds a new one (if no URN is assigned).
[ "Change", "the", "CTS", "URN", "of", "the", "author", "or", "adds", "a", "new", "one", "(", "if", "no", "URN", "is", "assigned", ")", "." ]
train
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L201-L215
mromanello/hucitlib
knowledge_base/surfext/__init__.py
HucitAuthor.to_json
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": [ { "urn": "urn:cts:greekLit:tlg0012.tlg001", "titles": [ { "language": "it", "label": "Iliade" }, { "language": "la", "label": "Ilias" }, { "language": "en", "label": "Iliad" }, { "language": "de", "label": "Ilias" }, { "language": "fr", "label": "L'Iliade" } ], "uri": "http://purl.org/hucit/kb/works/2815", "title_abbreviations": [ "Il." ] }, { "urn": "urn:cts:greekLit:tlg0012.tlg002", "titles": [ { "language": "en", "label": "Odyssey" }, { "language": "fr", "label": "L'Odyss\u00e9e" }, { "language": "it", "label": "Odissea" }, { "language": "la", "label": "Odyssea" }, { "language": "de", "label": "Odyssee" } ], "uri": "http://purl.org/hucit/kb/works/2816", "title_abbreviations": [ "Od." ] }, { "urn": "urn:cts:cwkb:927.2814", "titles": [ { "language": "la", "label": "Epigrammata" } ], "uri": "http://purl.org/hucit/kb/works/2814", "title_abbreviations": [ "Epigr." ] } ], "uri": "http://purl.org/hucit/kb/authors/927", "names": [ { "language": "fr", "label": "Hom\u00e8re" }, { "language": "la", "label": "Homerus" }, { "language": null, "label": "Homeros" }, { "language": "en", "label": "Homer" }, { "language": "it", "label": "Omero" } ] } """ 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() , "works" : [json.loads(work.to_json()) for work in self.get_works()] }, indent=2)
python
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": [ { "urn": "urn:cts:greekLit:tlg0012.tlg001", "titles": [ { "language": "it", "label": "Iliade" }, { "language": "la", "label": "Ilias" }, { "language": "en", "label": "Iliad" }, { "language": "de", "label": "Ilias" }, { "language": "fr", "label": "L'Iliade" } ], "uri": "http://purl.org/hucit/kb/works/2815", "title_abbreviations": [ "Il." ] }, { "urn": "urn:cts:greekLit:tlg0012.tlg002", "titles": [ { "language": "en", "label": "Odyssey" }, { "language": "fr", "label": "L'Odyss\u00e9e" }, { "language": "it", "label": "Odissea" }, { "language": "la", "label": "Odyssea" }, { "language": "de", "label": "Odyssee" } ], "uri": "http://purl.org/hucit/kb/works/2816", "title_abbreviations": [ "Od." ] }, { "urn": "urn:cts:cwkb:927.2814", "titles": [ { "language": "la", "label": "Epigrammata" } ], "uri": "http://purl.org/hucit/kb/works/2814", "title_abbreviations": [ "Epigr." ] } ], "uri": "http://purl.org/hucit/kb/authors/927", "names": [ { "language": "fr", "label": "Hom\u00e8re" }, { "language": "la", "label": "Homerus" }, { "language": null, "label": "Homeros" }, { "language": "en", "label": "Homer" }, { "language": "it", "label": "Omero" } ] } """ 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() , "works" : [json.loads(work.to_json()) for work in self.get_works()] }, indent=2)
[ "def", "to_json", "(", "self", ")", ":", "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", "(", ")", ",", "\"works\"", ":", "[", "json", ".", "loads", "(", "work", ".", "to_json", "(", ")", ")", "for", "work", "in", "self", ".", "get_works", "(", ")", "]", "}", ",", "indent", "=", "2", ")" ]
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": [ { "urn": "urn:cts:greekLit:tlg0012.tlg001", "titles": [ { "language": "it", "label": "Iliade" }, { "language": "la", "label": "Ilias" }, { "language": "en", "label": "Iliad" }, { "language": "de", "label": "Ilias" }, { "language": "fr", "label": "L'Iliade" } ], "uri": "http://purl.org/hucit/kb/works/2815", "title_abbreviations": [ "Il." ] }, { "urn": "urn:cts:greekLit:tlg0012.tlg002", "titles": [ { "language": "en", "label": "Odyssey" }, { "language": "fr", "label": "L'Odyss\u00e9e" }, { "language": "it", "label": "Odissea" }, { "language": "la", "label": "Odyssea" }, { "language": "de", "label": "Odyssee" } ], "uri": "http://purl.org/hucit/kb/works/2816", "title_abbreviations": [ "Od." ] }, { "urn": "urn:cts:cwkb:927.2814", "titles": [ { "language": "la", "label": "Epigrammata" } ], "uri": "http://purl.org/hucit/kb/works/2814", "title_abbreviations": [ "Epigr." ] } ], "uri": "http://purl.org/hucit/kb/authors/927", "names": [ { "language": "fr", "label": "Hom\u00e8re" }, { "language": "la", "label": "Homerus" }, { "language": null, "label": "Homeros" }, { "language": "en", "label": "Homer" }, { "language": "it", "label": "Omero" } ] }
[ "Serialises", "a", "HucitAuthor", "to", "a", "JSON", "formatted", "string", "." ]
train
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L225-L343
mromanello/hucitlib
knowledge_base/surfext/__init__.py
HucitWork.get_titles
def get_titles(self): """TODO""" return [(label.language, unicode(label)) for label in self.efrbroo_P102_has_title.first.rdfs_label]
python
def get_titles(self): """TODO""" return [(label.language, unicode(label)) for label in self.efrbroo_P102_has_title.first.rdfs_label]
[ "def", "get_titles", "(", "self", ")", ":", "return", "[", "(", "label", ".", "language", ",", "unicode", "(", "label", ")", ")", "for", "label", "in", "self", ".", "efrbroo_P102_has_title", ".", "first", ".", "rdfs_label", "]" ]
TODO
[ "TODO" ]
train
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L373-L375
mromanello/hucitlib
knowledge_base/surfext/__init__.py
HucitWork.get_abbreviations
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). """ abbreviations = [] try: type_abbreviation = self.session.get_resource(BASE_URI_TYPES % "abbreviation" , self.session.get_class(surf.ns.ECRM['E55_Type'])) abbreviations = [unicode(label) for title in self.efrbroo_P102_has_title for abbreviation in title.ecrm_P139_has_alternative_form for label in abbreviation.rdfs_label if title.uri == surf.ns.EFRBROO['E35_Title'] and abbreviation.ecrm_P2_has_type.first == type_abbreviation] if (combine and len(abbreviations)>0 and len(self.author.get_abbreviations())>=1): abbreviations = ["%s %s"%(author_abbrev, work_abbrev) for author_abbrev, work_abbrev in itertools.product(self.author.get_abbreviations() , self.get_abbreviations())] except Exception as e: logger.debug("Exception raised when getting abbreviations for %a"%self) finally: return abbreviations
python
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). """ abbreviations = [] try: type_abbreviation = self.session.get_resource(BASE_URI_TYPES % "abbreviation" , self.session.get_class(surf.ns.ECRM['E55_Type'])) abbreviations = [unicode(label) for title in self.efrbroo_P102_has_title for abbreviation in title.ecrm_P139_has_alternative_form for label in abbreviation.rdfs_label if title.uri == surf.ns.EFRBROO['E35_Title'] and abbreviation.ecrm_P2_has_type.first == type_abbreviation] if (combine and len(abbreviations)>0 and len(self.author.get_abbreviations())>=1): abbreviations = ["%s %s"%(author_abbrev, work_abbrev) for author_abbrev, work_abbrev in itertools.product(self.author.get_abbreviations() , self.get_abbreviations())] except Exception as e: logger.debug("Exception raised when getting abbreviations for %a"%self) finally: return abbreviations
[ "def", "get_abbreviations", "(", "self", ",", "combine", "=", "False", ")", ":", "abbreviations", "=", "[", "]", "try", ":", "type_abbreviation", "=", "self", ".", "session", ".", "get_resource", "(", "BASE_URI_TYPES", "%", "\"abbreviation\"", ",", "self", ".", "session", ".", "get_class", "(", "surf", ".", "ns", ".", "ECRM", "[", "'E55_Type'", "]", ")", ")", "abbreviations", "=", "[", "unicode", "(", "label", ")", "for", "title", "in", "self", ".", "efrbroo_P102_has_title", "for", "abbreviation", "in", "title", ".", "ecrm_P139_has_alternative_form", "for", "label", "in", "abbreviation", ".", "rdfs_label", "if", "title", ".", "uri", "==", "surf", ".", "ns", ".", "EFRBROO", "[", "'E35_Title'", "]", "and", "abbreviation", ".", "ecrm_P2_has_type", ".", "first", "==", "type_abbreviation", "]", "if", "(", "combine", "and", "len", "(", "abbreviations", ")", ">", "0", "and", "len", "(", "self", ".", "author", ".", "get_abbreviations", "(", ")", ")", ">=", "1", ")", ":", "abbreviations", "=", "[", "\"%s %s\"", "%", "(", "author_abbrev", ",", "work_abbrev", ")", "for", "author_abbrev", ",", "work_abbrev", "in", "itertools", ".", "product", "(", "self", ".", "author", ".", "get_abbreviations", "(", ")", ",", "self", ".", "get_abbreviations", "(", ")", ")", "]", "except", "Exception", "as", "e", ":", "logger", ".", "debug", "(", "\"Exception raised when getting abbreviations for %a\"", "%", "self", ")", "finally", ":", "return", "abbreviations" ]
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).
[ "TODO", ":", "if", "combine", "==", "True", "concatenate", "with", "author", "abbreviation", "(", "s", ")" ]
train
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L377-L403
mromanello/hucitlib
knowledge_base/surfext/__init__.py
HucitWork.add_text_structure
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['TextStructure'])) ts.rdfs_label.append(Literal(label)) ts.save() self.hucit_has_structure = ts self.update() return self.hucit_has_structure.one
python
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['TextStructure'])) ts.rdfs_label.append(Literal(label)) ts.save() self.hucit_has_structure = ts self.update() return self.hucit_has_structure.one
[ "def", "add_text_structure", "(", "self", ",", "label", ")", ":", "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", "self", ".", "hucit_has_structure", ".", "one" ]
Adds a citable text structure to the work.
[ "Adds", "a", "citable", "text", "structure", "to", "the", "work", "." ]
train
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L487-L498
mromanello/hucitlib
knowledge_base/surfext/__init__.py
HucitWork.remove_text_structure
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.pop(idx) ts.remove() self.update() return
python
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.pop(idx) ts.remove() self.update() return
[ "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.
[ "Remove", "any", "citable", "text", "structure", "to", "the", "work", "." ]
train
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L500-L508
mromanello/hucitlib
knowledge_base/surfext/__init__.py
HucitWork._get_opus_maximum
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_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")) logger.debug("Created a new opus maximum type instance") opmax.save() return opmax
python
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_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")) logger.debug("Created a new opus maximum type instance") opmax.save() return opmax
[ "def", "_get_opus_maximum", "(", "self", ")", ":", "label", "=", "\"\"\"The opux maximum of a given author\n that is, the only preserved work by that\n author or the most known one.\"\"\"", "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\"", ")", ")", "logger", ".", "debug", "(", "\"Created a new opus maximum type instance\"", ")", "opmax", ".", "save", "(", ")", "return", "opmax" ]
Instantiate an opus maximum type.
[ "Instantiate", "an", "opus", "maximum", "type", "." ]
train
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L510-L526
mromanello/hucitlib
knowledge_base/surfext/__init__.py
HucitWork.set_as_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_type = opmax self.update() return True
python
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_type = opmax self.update() return True
[ "def", "set_as_opus_maximum", "(", "self", ")", ":", "# TODO: test", "if", "self", ".", "is_opus_maximum", "(", ")", ":", "return", "False", "else", ":", "opmax", "=", "self", ".", "_get_opus_maximum", "(", ")", "self", ".", "ecrm_P2_has_type", "=", "opmax", "self", ".", "update", "(", ")", "return", "True" ]
Mark explicitly the work as the author's opus maximum.
[ "Mark", "explicitly", "the", "work", "as", "the", "author", "s", "opus", "maximum", "." ]
train
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L528-L536
mromanello/hucitlib
knowledge_base/surfext/__init__.py
HucitWork.is_opus_maximum
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 """ 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
python
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 """ 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", ")", ":", "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" ]
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
[ "Check", "whether", "the", "work", "is", "the", "author", "s", "opus", "maximum", "." ]
train
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L538-L556
mromanello/hucitlib
knowledge_base/surfext/__init__.py
HucitWork.author
def author(self): """ Returns the author to whom the work is attributed. :return: an instance of `HucitWork` # TODO: check that's the case """ 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).first()
python
def author(self): """ Returns the author to whom the work is attributed. :return: an instance of `HucitWork` # TODO: check that's the case """ 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).first()
[ "def", "author", "(", "self", ")", ":", "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", ")", ".", "first", "(", ")" ]
Returns the author to whom the work is attributed. :return: an instance of `HucitWork` # TODO: check that's the case
[ "Returns", "the", "author", "to", "whom", "the", "work", "is", "attributed", "." ]
train
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L566-L575
mromanello/hucitlib
knowledge_base/surfext/__init__.py
HucitWork.to_json
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()) , "titles" : [{"language":lang, "label":label} for lang, label in titles] , "title_abbreviations" : self.get_abbreviations() }, indent=2)
python
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()) , "titles" : [{"language":lang, "label":label} for lang, label in titles] , "title_abbreviations" : self.get_abbreviations() }, indent=2)
[ "def", "to_json", "(", "self", ")", ":", "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", "(", ")", "}", ",", "indent", "=", "2", ")" ]
Serialises a HucitWork to a JSON formatted string.
[ "Serialises", "a", "HucitWork", "to", "a", "JSON", "formatted", "string", "." ]
train
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L583-L594
mromanello/hucitlib
knowledge_base/surfext/__init__.py
HucitTextElement.get_urn
def get_urn(self): """ TODO """ urn = self.ecrm_P1_is_identified_by.one try: return CTS_URN(urn) except Exception, e: raise e
python
def get_urn(self): """ TODO """ urn = self.ecrm_P1_is_identified_by.one try: return CTS_URN(urn) except Exception, e: raise e
[ "def", "get_urn", "(", "self", ")", ":", "urn", "=", "self", ".", "ecrm_P1_is_identified_by", ".", "one", "try", ":", "return", "CTS_URN", "(", "urn", ")", "except", "Exception", ",", "e", ":", "raise", "e" ]
TODO
[ "TODO" ]
train
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/surfext/__init__.py#L637-L645
BlueBrain/hpcbench
hpcbench/driver/campaign.py
Network.nodes
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))) definitions = self.campaign.network.tags.get(tag) if definitions is None: return [] nodes = set() for definition in definitions: if len(definition.items()) == 0: continue mode, value = list(definition.items())[0] if mode == 'match': nodes = nodes.union( set( [ node for node in self.campaign.network.nodes if value.match(node) ] ) ) elif mode == 'constraint': slurm_nodes = os.environ.get('SLURM_JOB_NODELIST') if slurm_nodes: nodes = NodeSet(slurm_nodes) else: return ConstraintTag(tag, value) else: assert mode == 'nodes' nodes = nodes.union(set(value)) return sorted(list(nodes))
python
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))) definitions = self.campaign.network.tags.get(tag) if definitions is None: return [] nodes = set() for definition in definitions: if len(definition.items()) == 0: continue mode, value = list(definition.items())[0] if mode == 'match': nodes = nodes.union( set( [ node for node in self.campaign.network.nodes if value.match(node) ] ) ) elif mode == 'constraint': slurm_nodes = os.environ.get('SLURM_JOB_NODELIST') if slurm_nodes: nodes = NodeSet(slurm_nodes) else: return ConstraintTag(tag, value) else: assert mode == 'nodes' nodes = nodes.union(set(value)) return sorted(list(nodes))
[ "def", "nodes", "(", "self", ",", "tag", ")", ":", "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", ":", "continue", "mode", ",", "value", "=", "list", "(", "definition", ".", "items", "(", ")", ")", "[", "0", "]", "if", "mode", "==", "'match'", ":", "nodes", "=", "nodes", ".", "union", "(", "set", "(", "[", "node", "for", "node", "in", "self", ".", "campaign", ".", "network", ".", "nodes", "if", "value", ".", "match", "(", "node", ")", "]", ")", ")", "elif", "mode", "==", "'constraint'", ":", "slurm_nodes", "=", "os", ".", "environ", ".", "get", "(", "'SLURM_JOB_NODELIST'", ")", "if", "slurm_nodes", ":", "nodes", "=", "NodeSet", "(", "slurm_nodes", ")", "else", ":", "return", "ConstraintTag", "(", "tag", ",", "value", ")", "else", ":", "assert", "mode", "==", "'nodes'", "nodes", "=", "nodes", ".", "union", "(", "set", "(", "value", ")", ")", "return", "sorted", "(", "list", "(", "nodes", ")", ")" ]
get nodes that belong to a tag :param tag: tag name :rtype: list of string
[ "get", "nodes", "that", "belong", "to", "a", "tag", ":", "param", "tag", ":", "tag", "name", ":", "rtype", ":", "list", "of", "string" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/campaign.py#L41-L75
BlueBrain/hpcbench
hpcbench/driver/campaign.py
CampaignDriver.execution_cls
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: '%s'" % name)
python
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: '%s'" % name)
[ "def", "execution_cls", "(", "self", ")", ":", "name", "=", "self", ".", "campaign", ".", "process", ".", "type", "for", "clazz", "in", "[", "ExecutionDriver", ",", "SrunExecutionDriver", "]", ":", "if", "name", "==", "clazz", ".", "name", ":", "return", "clazz", "raise", "NameError", "(", "\"Unknown execution layer: '%s'\"", "%", "name", ")" ]
Get execution layer class
[ "Get", "execution", "layer", "class" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/campaign.py#L146-L153
BlueBrain/hpcbench
hpcbench/driver/campaign.py
HostDriver.children
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 for tag, configs in network_tags.items(): for config in configs: for mode, kconfig in config.items(): if mode == 'match': if kconfig.match(self.name) or kconfig.match(LOCALHOST): tags.add(tag) break elif mode == 'nodes': if self.name in kconfig or LOCALHOST in kconfig: tags.add(tag) break elif mode == 'constraint': tags.add(tag) break if tag in tags: break return tags
python
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 for tag, configs in network_tags.items(): for config in configs: for mode, kconfig in config.items(): if mode == 'match': if kconfig.match(self.name) or kconfig.match(LOCALHOST): tags.add(tag) break elif mode == 'nodes': if self.name in kconfig or LOCALHOST in kconfig: tags.add(tag) break elif mode == 'constraint': tags.add(tag) break if tag in tags: break return tags
[ "def", "children", "(", "self", ")", ":", "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", "config", ".", "items", "(", ")", ":", "if", "mode", "==", "'match'", ":", "if", "kconfig", ".", "match", "(", "self", ".", "name", ")", "or", "kconfig", ".", "match", "(", "LOCALHOST", ")", ":", "tags", ".", "add", "(", "tag", ")", "break", "elif", "mode", "==", "'nodes'", ":", "if", "self", ".", "name", "in", "kconfig", "or", "LOCALHOST", "in", "kconfig", ":", "tags", ".", "add", "(", "tag", ")", "break", "elif", "mode", "==", "'constraint'", ":", "tags", ".", "add", "(", "tag", ")", "break", "if", "tag", "in", "tags", ":", "break", "return", "tags" ]
Retrieve tags associated to the current node
[ "Retrieve", "tags", "associated", "to", "the", "current", "node" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/campaign.py#L164-L187
KelSolaar/Manager
manager/component.py
Component.activated
def activated(self, value): """ Setter for **self.__activated** attribute. :param value: Attribute value. :type value: bool """ if value is not None: assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("activated", value) self.__activated = value
python
def activated(self, value): """ Setter for **self.__activated** attribute. :param value: Attribute value. :type value: bool """ 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", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "is", "bool", ",", "\"'{0}' attribute: '{1}' type is not 'bool'!\"", ".", "format", "(", "\"activated\"", ",", "value", ")", "self", ".", "__activated", "=", "value" ]
Setter for **self.__activated** attribute. :param value: Attribute value. :type value: bool
[ "Setter", "for", "**", "self", ".", "__activated", "**", "attribute", "." ]
train
https://github.com/KelSolaar/Manager/blob/39c8153fc021fc8a76e345a6e336ec2644f089d1/manager/component.py#L105-L115
KelSolaar/Manager
manager/component.py
Component.initialized
def initialized(self, value): """ Setter for **self.__initialized** attribute. :param value: Attribute value. :type value: bool """ if value is not None: assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("initialized", value) self.__initialized = value
python
def initialized(self, value): """ Setter for **self.__initialized** attribute. :param value: Attribute value. :type value: bool """ 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", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "is", "bool", ",", "\"'{0}' attribute: '{1}' type is not 'bool'!\"", ".", "format", "(", "\"initialized\"", ",", "value", ")", "self", ".", "__initialized", "=", "value" ]
Setter for **self.__initialized** attribute. :param value: Attribute value. :type value: bool
[ "Setter", "for", "**", "self", ".", "__initialized", "**", "attribute", "." ]
train
https://github.com/KelSolaar/Manager/blob/39c8153fc021fc8a76e345a6e336ec2644f089d1/manager/component.py#L140-L150
KelSolaar/Manager
manager/component.py
Component.activate
def activate(self): """ Sets Component activation state. :return: Method success. :rtype: bool """ raise NotImplementedError("{0} | '{1}' must be implemented by '{2}' subclasses!".format( self.__class__.__name__, self.activate.__name__, self.__class__.__name__))
python
def activate(self): """ Sets Component activation state. :return: Method success. :rtype: bool """ raise NotImplementedError("{0} | '{1}' must be implemented by '{2}' subclasses!".format( self.__class__.__name__, self.activate.__name__, self.__class__.__name__))
[ "def", "activate", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "\"{0} | '{1}' must be implemented by '{2}' subclasses!\"", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ",", "self", ".", "activate", ".", "__name__", ",", "self", ".", "__class__", ".", "__name__", ")", ")" ]
Sets Component activation state. :return: Method success. :rtype: bool
[ "Sets", "Component", "activation", "state", "." ]
train
https://github.com/KelSolaar/Manager/blob/39c8153fc021fc8a76e345a6e336ec2644f089d1/manager/component.py#L198-L207
BlueBrain/hpcbench
hpcbench/toolbox/slurm/cluster.py
SlurmCluster.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 it: rsv = Reservation.from_sinfo(line) yield rsv.name, rsv
python
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 it: rsv = Reservation.from_sinfo(line) yield rsv.name, rsv
[ "def", "reservations", "(", "self", ")", ":", "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" ]
get nodes of every reservations
[ "get", "nodes", "of", "every", "reservations" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/slurm/cluster.py#L57-L66
eng-tools/sfsimodels
sfsimodels/models/abstract_models.py
PhysicalObject.set
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])
python
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])
[ "def", "set", "(", "self", ",", "values", ")", ":", "if", "hasattr", "(", "self", ",", "\"inputs\"", ")", ":", "for", "item", "in", "self", ".", "inputs", ":", "if", "hasattr", "(", "self", ",", "item", ")", ":", "setattr", "(", "self", ",", "item", ",", "values", "[", "item", "]", ")" ]
Set the object parameters using a dictionary
[ "Set", "the", "object", "parameters", "using", "a", "dictionary" ]
train
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/abstract_models.py#L44-L51
PolyJIT/benchbuild
benchbuild/utils/tasks.py
execute_plan
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. """ results = [action() for action in plan] return [result for result in results if actns.step_has_failed(result)]
python
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. """ results = [action() for action in plan] return [result for result in results if actns.step_has_failed(result)]
[ "def", "execute_plan", "(", "plan", ")", ":", "results", "=", "[", "action", "(", ")", "for", "action", "in", "plan", "]", "return", "[", "result", "for", "result", "in", "results", "if", "actns", ".", "step_has_failed", "(", "result", ")", "]" ]
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.
[ "Execute", "the", "plan", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/tasks.py#L7-L17
davidhuser/dhis2.py
dhis2/logger.py
_set_log_format
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 """ 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, color_end, time, message, caller) else: return '{}{}{} {} {}'.format(color_start, level_name, color_end, time, message) else: if include_caller: return '{} {} {} {}'.format(level_name, time, message, caller) else: return '{} {} {}'.format(level_name, time, message)
python
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 """ 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, color_end, time, message, caller) else: return '{}{}{} {} {}'.format(color_start, level_name, color_end, time, message) else: if include_caller: return '{} {} {} {}'.format(level_name, time, message, caller) else: return '{} {} {}'.format(level_name, time, message)
[ "def", "_set_log_format", "(", "color", ",", "include_caller", ")", ":", "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", ",", "color_end", ",", "time", ",", "message", ",", "caller", ")", "else", ":", "return", "'{}{}{} {} {}'", ".", "format", "(", "color_start", ",", "level_name", ",", "color_end", ",", "time", ",", "message", ")", "else", ":", "if", "include_caller", ":", "return", "'{} {} {} {}'", ".", "format", "(", "level_name", ",", "time", ",", "message", ",", "caller", ")", "else", ":", "return", "'{} {} {}'", ".", "format", "(", "level_name", ",", "time", ",", "message", ")" ]
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
[ "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" ]
train
https://github.com/davidhuser/dhis2.py/blob/78cbf1985506db21acdfa0f2e624bc397e455c82/dhis2/logger.py#L14-L37
davidhuser/dhis2.py
dhis2/logger.py
setup_logger
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. [script:123] """ 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, include_caller=True), datefmt='%Y-%m-%d %H:%M:%S') logzero.logfile(logfile, formatter=formatter, loglevel=log_level, maxBytes=int(1e7), backupCount=backup_count)
python
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. [script:123] """ 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, include_caller=True), datefmt='%Y-%m-%d %H:%M:%S') logzero.logfile(logfile, formatter=formatter, loglevel=log_level, maxBytes=int(1e7), backupCount=backup_count)
[ "def", "setup_logger", "(", "logfile", "=", "None", ",", "backup_count", "=", "20", ",", "log_level", "=", "logging", ".", "INFO", ",", "include_caller", "=", "True", ")", ":", "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", ",", "include_caller", "=", "True", ")", ",", "datefmt", "=", "'%Y-%m-%d %H:%M:%S'", ")", "logzero", ".", "logfile", "(", "logfile", ",", "formatter", "=", "formatter", ",", "loglevel", "=", "log_level", ",", "maxBytes", "=", "int", "(", "1e7", ")", ",", "backupCount", "=", "backup_count", ")" ]
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. [script:123]
[ "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", ".", "[", "script", ":", "123", "]" ]
train
https://github.com/davidhuser/dhis2.py/blob/78cbf1985506db21acdfa0f2e624bc397e455c82/dhis2/logger.py#L40-L58
portfoliome/foil
foil/formatters.py
format_repr
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}({1})".format(obj.__class__.__qualname__, attribute_repr)
python
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}({1})".format(obj.__class__.__qualname__, attribute_repr)
[ "def", "format_repr", "(", "obj", ",", "attributes", ")", "->", "str", ":", "attribute_repr", "=", "', '", ".", "join", "(", "(", "'{}={}'", ".", "format", "(", "attr", ",", "repr", "(", "getattr", "(", "obj", ",", "attr", ")", ")", ")", "for", "attr", "in", "attributes", ")", ")", "return", "\"{0}({1})\"", ".", "format", "(", "obj", ".", "__class__", ".", "__qualname__", ",", "attribute_repr", ")" ]
Format an object's repr method with specific attributes.
[ "Format", "an", "object", "s", "repr", "method", "with", "specific", "attributes", "." ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/formatters.py#L6-L11
eng-tools/sfsimodels
sfsimodels/build_model_descriptions.py
build_parameter_descriptions
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: """ 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") plist = obj.inputs p_dict = {} if hasattr(obj, 'ancestor_types'): bt = obj.ancestor_types for otype in bt: # cycles from lowest class, so descriptions get overridden if otype in vp: for item in vp[otype]: p_dict[item] = vp[otype][item] for item in user_p: # user defined definitions override base ones p_dict[item] = user_p[item] else: p_dict = user_p for item in plist: if show_none is False and getattr(obj, item) is None: continue if item in ignore: continue if item in p_dict: para.append([item, p_dict[item][1], p_dict[item][0]]) else: para.append([item, "", ""]) if output == "csv": out_obj = [] for i in range(len(para)): out_obj.append(",".join(para[i])) elif output == "list": out_obj = para elif output == "dict": out_obj = OrderedDict() for i in range(len(para)): out_obj[para[i][0]] = {"description": para[i][2], "units": para[i][1]} else: raise ValueError("output must be either: 'csv', 'dict' or 'list'.") return out_obj
python
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: """ 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") plist = obj.inputs p_dict = {} if hasattr(obj, 'ancestor_types'): bt = obj.ancestor_types for otype in bt: # cycles from lowest class, so descriptions get overridden if otype in vp: for item in vp[otype]: p_dict[item] = vp[otype][item] for item in user_p: # user defined definitions override base ones p_dict[item] = user_p[item] else: p_dict = user_p for item in plist: if show_none is False and getattr(obj, item) is None: continue if item in ignore: continue if item in p_dict: para.append([item, p_dict[item][1], p_dict[item][0]]) else: para.append([item, "", ""]) if output == "csv": out_obj = [] for i in range(len(para)): out_obj.append(",".join(para[i])) elif output == "list": out_obj = para elif output == "dict": out_obj = OrderedDict() for i in range(len(para)): out_obj[para[i][0]] = {"description": para[i][2], "units": para[i][1]} else: raise ValueError("output must be either: 'csv', 'dict' or 'list'.") return out_obj
[ "def", "build_parameter_descriptions", "(", "obj", ",", "user_p", "=", "None", ",", "output", "=", "\"csv\"", ",", "show_none", "=", "True", ",", "ignore", "=", "None", ",", "plist", "=", "None", ")", ":", "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\"", ")", "plist", "=", "obj", ".", "inputs", "p_dict", "=", "{", "}", "if", "hasattr", "(", "obj", ",", "'ancestor_types'", ")", ":", "bt", "=", "obj", ".", "ancestor_types", "for", "otype", "in", "bt", ":", "# cycles from lowest class, so descriptions get overridden", "if", "otype", "in", "vp", ":", "for", "item", "in", "vp", "[", "otype", "]", ":", "p_dict", "[", "item", "]", "=", "vp", "[", "otype", "]", "[", "item", "]", "for", "item", "in", "user_p", ":", "# user defined definitions override base ones", "p_dict", "[", "item", "]", "=", "user_p", "[", "item", "]", "else", ":", "p_dict", "=", "user_p", "for", "item", "in", "plist", ":", "if", "show_none", "is", "False", "and", "getattr", "(", "obj", ",", "item", ")", "is", "None", ":", "continue", "if", "item", "in", "ignore", ":", "continue", "if", "item", "in", "p_dict", ":", "para", ".", "append", "(", "[", "item", ",", "p_dict", "[", "item", "]", "[", "1", "]", ",", "p_dict", "[", "item", "]", "[", "0", "]", "]", ")", "else", ":", "para", ".", "append", "(", "[", "item", ",", "\"\"", ",", "\"\"", "]", ")", "if", "output", "==", "\"csv\"", ":", "out_obj", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "para", ")", ")", ":", "out_obj", ".", "append", "(", "\",\"", ".", "join", "(", "para", "[", "i", "]", ")", ")", "elif", "output", "==", "\"list\"", ":", "out_obj", "=", "para", "elif", "output", "==", "\"dict\"", ":", "out_obj", "=", "OrderedDict", "(", ")", "for", "i", "in", "range", "(", "len", "(", "para", ")", ")", ":", "out_obj", "[", "para", "[", "i", "]", "[", "0", "]", "]", "=", "{", "\"description\"", ":", "para", "[", "i", "]", "[", "2", "]", ",", "\"units\"", ":", "para", "[", "i", "]", "[", "1", "]", "}", "else", ":", "raise", "ValueError", "(", "\"output must be either: 'csv', 'dict' or 'list'.\"", ")", "return", "out_obj" ]
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:
[ "Creates", "a", "list", "of", "the", "decription", "of", "all", "the", "inputs", "of", "an", "object" ]
train
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/build_model_descriptions.py#L8-L61
eng-tools/sfsimodels
sfsimodels/build_model_descriptions.py
all_descriptions
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()) + [",,\n"] para += build_parameter_descriptions(models.Foundation()) + [",,\n"] para += build_parameter_descriptions(models.PadFoundation()) + [",,\n"] para += build_parameter_descriptions(models.SDOFBuilding()) + [",,\n"] para += build_parameter_descriptions(models.FrameBuilding2D(1, 1)) return para
python
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()) + [",,\n"] para += build_parameter_descriptions(models.Foundation()) + [",,\n"] para += build_parameter_descriptions(models.PadFoundation()) + [",,\n"] para += build_parameter_descriptions(models.SDOFBuilding()) + [",,\n"] para += build_parameter_descriptions(models.FrameBuilding2D(1, 1)) return para
[ "def", "all_descriptions", "(", ")", ":", "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", "+=", "build_parameter_descriptions", "(", "models", ".", "SDOFBuilding", "(", ")", ")", "+", "[", "\",,\\n\"", "]", "para", "+=", "build_parameter_descriptions", "(", "models", ".", "FrameBuilding2D", "(", "1", ",", "1", ")", ")", "return", "para" ]
Generates a list of descriptions of all the models :return:
[ "Generates", "a", "list", "of", "descriptions", "of", "all", "the", "models" ]
train
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/build_model_descriptions.py#L64-L78
sci-bots/svg-model
svg_model/plot.py
plot_shapes
def plot_shapes(df_shapes, shape_i_columns, axis=None, autoxlim=True, autoylim=True, **kwargs): ''' 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 81.679949 286.51788 2 0 2 102.87004 286.51788 3 0 3 102.87004 264.69306 4 1 0 103.11417 264.40011 5 1 1 103.11417 242.72177 6 1 2 81.435824 242.72177 7 1 3 81.435824 264.40011 8 2 0 124.84134 264.69306 9 2 1 103.65125 264.69306 10 2 2 103.65125 286.37141 11 2 3 124.84134 286.37141 This dataframe corresponds to three shapes, with (ordered) shape vertices grouped by `shape_i`. Note that the column `vertex_i` is not required. ''' if axis is None: fig, axis = plt.subplots() props = itertools.cycle(mpl.rcParams['axes.prop_cycle']) color = kwargs.pop('fc', None) # Cycle through default colors to set face color, unless face color was set # explicitly. patches = [Polygon(df_shape_i[['x', 'y']].values, fc=props.next()['color'] if color is None else color, **kwargs) for shape_i, df_shape_i in df_shapes.groupby(shape_i_columns)] collection = PatchCollection(patches) axis.add_collection(collection) xy_stats = df_shapes[['x', 'y']].describe() if autoxlim: axis.set_xlim(*xy_stats.x.loc[['min', 'max']]) if autoylim: axis.set_ylim(*xy_stats.y.loc[['min', 'max']]) return axis
python
def plot_shapes(df_shapes, shape_i_columns, axis=None, autoxlim=True, autoylim=True, **kwargs): ''' 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 81.679949 286.51788 2 0 2 102.87004 286.51788 3 0 3 102.87004 264.69306 4 1 0 103.11417 264.40011 5 1 1 103.11417 242.72177 6 1 2 81.435824 242.72177 7 1 3 81.435824 264.40011 8 2 0 124.84134 264.69306 9 2 1 103.65125 264.69306 10 2 2 103.65125 286.37141 11 2 3 124.84134 286.37141 This dataframe corresponds to three shapes, with (ordered) shape vertices grouped by `shape_i`. Note that the column `vertex_i` is not required. ''' if axis is None: fig, axis = plt.subplots() props = itertools.cycle(mpl.rcParams['axes.prop_cycle']) color = kwargs.pop('fc', None) # Cycle through default colors to set face color, unless face color was set # explicitly. patches = [Polygon(df_shape_i[['x', 'y']].values, fc=props.next()['color'] if color is None else color, **kwargs) for shape_i, df_shape_i in df_shapes.groupby(shape_i_columns)] collection = PatchCollection(patches) axis.add_collection(collection) xy_stats = df_shapes[['x', 'y']].describe() if autoxlim: axis.set_xlim(*xy_stats.x.loc[['min', 'max']]) if autoylim: axis.set_ylim(*xy_stats.y.loc[['min', 'max']]) return axis
[ "def", "plot_shapes", "(", "df_shapes", ",", "shape_i_columns", ",", "axis", "=", "None", ",", "autoxlim", "=", "True", ",", "autoylim", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "axis", "is", "None", ":", "fig", ",", "axis", "=", "plt", ".", "subplots", "(", ")", "props", "=", "itertools", ".", "cycle", "(", "mpl", ".", "rcParams", "[", "'axes.prop_cycle'", "]", ")", "color", "=", "kwargs", ".", "pop", "(", "'fc'", ",", "None", ")", "# Cycle through default colors to set face color, unless face color was set", "# explicitly.", "patches", "=", "[", "Polygon", "(", "df_shape_i", "[", "[", "'x'", ",", "'y'", "]", "]", ".", "values", ",", "fc", "=", "props", ".", "next", "(", ")", "[", "'color'", "]", "if", "color", "is", "None", "else", "color", ",", "*", "*", "kwargs", ")", "for", "shape_i", ",", "df_shape_i", "in", "df_shapes", ".", "groupby", "(", "shape_i_columns", ")", "]", "collection", "=", "PatchCollection", "(", "patches", ")", "axis", ".", "add_collection", "(", "collection", ")", "xy_stats", "=", "df_shapes", "[", "[", "'x'", ",", "'y'", "]", "]", ".", "describe", "(", ")", "if", "autoxlim", ":", "axis", ".", "set_xlim", "(", "*", "xy_stats", ".", "x", ".", "loc", "[", "[", "'min'", ",", "'max'", "]", "]", ")", "if", "autoylim", ":", "axis", ".", "set_ylim", "(", "*", "xy_stats", ".", "y", ".", "loc", "[", "[", "'min'", ",", "'max'", "]", "]", ")", "return", "axis" ]
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 81.679949 286.51788 2 0 2 102.87004 286.51788 3 0 3 102.87004 264.69306 4 1 0 103.11417 264.40011 5 1 1 103.11417 242.72177 6 1 2 81.435824 242.72177 7 1 3 81.435824 264.40011 8 2 0 124.84134 264.69306 9 2 1 103.65125 264.69306 10 2 2 103.65125 286.37141 11 2 3 124.84134 286.37141 This dataframe corresponds to three shapes, with (ordered) shape vertices grouped by `shape_i`. Note that the column `vertex_i` is not required.
[ "Plot", "shapes", "from", "table", "/", "data", "-", "frame", "where", "each", "row", "corresponds", "to", "a", "vertex", "of", "a", "shape", ".", "Shape", "vertices", "are", "grouped", "by", "shape_i_columns", "." ]
train
https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/plot.py#L14-L59
sci-bots/svg-model
svg_model/plot.py
plot_shapes_heat_map
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 by `'id'`. These values are used to look up color in the color map. axis : A matplotlib axis. If `None`, an axis is created. vmin : Minimum value to clip values at. vmax : Maximum value to clip values at. color_map : A matplotlib color map (see `matplotlib.cm`). Returns ------- (tuple) : First element is heat map axis, second element is colorbar axis. ''' df_shapes = df_shapes.copy() # Matplotlib draws from bottom to top, so invert `y` coordinates. df_shapes.loc[:, 'y'] = df_shapes.y.max() - df_shapes.y.copy().values aspect_ratio = ((df_shapes.x.max() - df_shapes.x.min()) / (df_shapes.y.max() - df_shapes.y.min())) if vmin is not None or vmax is not None: norm = mpl.colors.Normalize(vmin=vmin or min(values), vmax=vmax or max(values)) else: norm = None if axis is None: fig, axis = plt.subplots(figsize=(10, 10 * aspect_ratio)) else: fig = axis.get_figure() patches = OrderedDict([(id, Polygon(df_shape_i[['x', 'y']].values)) for id, df_shape_i in df_shapes.groupby(shape_i_columns)]) patches = pd.Series(patches) collection = PatchCollection(patches.values, cmap=color_map, norm=norm) collection.set_array(values.ix[patches.index]) axis.add_collection(collection) axis_divider = make_axes_locatable(axis) # Append color axis to the right of `axis`, with 10% width of `axis`. color_axis = axis_divider.append_axes("right", size="10%", pad=0.05) colorbar = fig.colorbar(collection, format=value_formatter, cax=color_axis) tick_labels = colorbar.ax.get_yticklabels() if vmin is not None: tick_labels[0] = '$\leq$%s' % tick_labels[0].get_text() if vmax is not None: tick_labels[-1] = '$\geq$%s' % tick_labels[-1].get_text() colorbar.ax.set_yticklabels(tick_labels) axis.set_xlim(df_shapes.x.min(), df_shapes.x.max()) axis.set_ylim(df_shapes.y.min(), df_shapes.y.max()) return axis, colorbar
python
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 by `'id'`. These values are used to look up color in the color map. axis : A matplotlib axis. If `None`, an axis is created. vmin : Minimum value to clip values at. vmax : Maximum value to clip values at. color_map : A matplotlib color map (see `matplotlib.cm`). Returns ------- (tuple) : First element is heat map axis, second element is colorbar axis. ''' df_shapes = df_shapes.copy() # Matplotlib draws from bottom to top, so invert `y` coordinates. df_shapes.loc[:, 'y'] = df_shapes.y.max() - df_shapes.y.copy().values aspect_ratio = ((df_shapes.x.max() - df_shapes.x.min()) / (df_shapes.y.max() - df_shapes.y.min())) if vmin is not None or vmax is not None: norm = mpl.colors.Normalize(vmin=vmin or min(values), vmax=vmax or max(values)) else: norm = None if axis is None: fig, axis = plt.subplots(figsize=(10, 10 * aspect_ratio)) else: fig = axis.get_figure() patches = OrderedDict([(id, Polygon(df_shape_i[['x', 'y']].values)) for id, df_shape_i in df_shapes.groupby(shape_i_columns)]) patches = pd.Series(patches) collection = PatchCollection(patches.values, cmap=color_map, norm=norm) collection.set_array(values.ix[patches.index]) axis.add_collection(collection) axis_divider = make_axes_locatable(axis) # Append color axis to the right of `axis`, with 10% width of `axis`. color_axis = axis_divider.append_axes("right", size="10%", pad=0.05) colorbar = fig.colorbar(collection, format=value_formatter, cax=color_axis) tick_labels = colorbar.ax.get_yticklabels() if vmin is not None: tick_labels[0] = '$\leq$%s' % tick_labels[0].get_text() if vmax is not None: tick_labels[-1] = '$\geq$%s' % tick_labels[-1].get_text() colorbar.ax.set_yticklabels(tick_labels) axis.set_xlim(df_shapes.x.min(), df_shapes.x.max()) axis.set_ylim(df_shapes.y.min(), df_shapes.y.max()) return axis, colorbar
[ "def", "plot_shapes_heat_map", "(", "df_shapes", ",", "shape_i_columns", ",", "values", ",", "axis", "=", "None", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ",", "value_formatter", "=", "None", ",", "color_map", "=", "None", ")", ":", "df_shapes", "=", "df_shapes", ".", "copy", "(", ")", "# Matplotlib draws from bottom to top, so invert `y` coordinates.", "df_shapes", ".", "loc", "[", ":", ",", "'y'", "]", "=", "df_shapes", ".", "y", ".", "max", "(", ")", "-", "df_shapes", ".", "y", ".", "copy", "(", ")", ".", "values", "aspect_ratio", "=", "(", "(", "df_shapes", ".", "x", ".", "max", "(", ")", "-", "df_shapes", ".", "x", ".", "min", "(", ")", ")", "/", "(", "df_shapes", ".", "y", ".", "max", "(", ")", "-", "df_shapes", ".", "y", ".", "min", "(", ")", ")", ")", "if", "vmin", "is", "not", "None", "or", "vmax", "is", "not", "None", ":", "norm", "=", "mpl", ".", "colors", ".", "Normalize", "(", "vmin", "=", "vmin", "or", "min", "(", "values", ")", ",", "vmax", "=", "vmax", "or", "max", "(", "values", ")", ")", "else", ":", "norm", "=", "None", "if", "axis", "is", "None", ":", "fig", ",", "axis", "=", "plt", ".", "subplots", "(", "figsize", "=", "(", "10", ",", "10", "*", "aspect_ratio", ")", ")", "else", ":", "fig", "=", "axis", ".", "get_figure", "(", ")", "patches", "=", "OrderedDict", "(", "[", "(", "id", ",", "Polygon", "(", "df_shape_i", "[", "[", "'x'", ",", "'y'", "]", "]", ".", "values", ")", ")", "for", "id", ",", "df_shape_i", "in", "df_shapes", ".", "groupby", "(", "shape_i_columns", ")", "]", ")", "patches", "=", "pd", ".", "Series", "(", "patches", ")", "collection", "=", "PatchCollection", "(", "patches", ".", "values", ",", "cmap", "=", "color_map", ",", "norm", "=", "norm", ")", "collection", ".", "set_array", "(", "values", ".", "ix", "[", "patches", ".", "index", "]", ")", "axis", ".", "add_collection", "(", "collection", ")", "axis_divider", "=", "make_axes_locatable", "(", "axis", ")", "# Append color axis to the right of `axis`, with 10% width of `axis`.", "color_axis", "=", "axis_divider", ".", "append_axes", "(", "\"right\"", ",", "size", "=", "\"10%\"", ",", "pad", "=", "0.05", ")", "colorbar", "=", "fig", ".", "colorbar", "(", "collection", ",", "format", "=", "value_formatter", ",", "cax", "=", "color_axis", ")", "tick_labels", "=", "colorbar", ".", "ax", ".", "get_yticklabels", "(", ")", "if", "vmin", "is", "not", "None", ":", "tick_labels", "[", "0", "]", "=", "'$\\leq$%s'", "%", "tick_labels", "[", "0", "]", ".", "get_text", "(", ")", "if", "vmax", "is", "not", "None", ":", "tick_labels", "[", "-", "1", "]", "=", "'$\\geq$%s'", "%", "tick_labels", "[", "-", "1", "]", ".", "get_text", "(", ")", "colorbar", ".", "ax", ".", "set_yticklabels", "(", "tick_labels", ")", "axis", ".", "set_xlim", "(", "df_shapes", ".", "x", ".", "min", "(", ")", ",", "df_shapes", ".", "x", ".", "max", "(", ")", ")", "axis", ".", "set_ylim", "(", "df_shapes", ".", "y", ".", "min", "(", ")", ",", "df_shapes", ".", "y", ".", "max", "(", ")", ")", "return", "axis", ",", "colorbar" ]
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 by `'id'`. These values are used to look up color in the color map. axis : A matplotlib axis. If `None`, an axis is created. vmin : Minimum value to clip values at. vmax : Maximum value to clip values at. color_map : A matplotlib color map (see `matplotlib.cm`). Returns ------- (tuple) : First element is heat map axis, second element is colorbar axis.
[ "Plot", "polygon", "shapes", "colored", "based", "on", "values", "mapped", "onto", "a", "colormap", "." ]
train
https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/plot.py#L62-L135
sci-bots/svg-model
svg_model/plot.py
plot_color_map_bars
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. vmax : Maximum value to clip values at. color_map : A matplotlib color map (see `matplotlib.cm`). **kwargs : Extra keyword arguments to pass to `values.plot`. Returns ------- (axis) : Bar plot axis. ''' if axis is None: fig, axis = plt.subplots() norm = mpl.colors.Normalize(vmin=vmin or min(values), vmax=vmax or max(values), clip=True) if color_map is None: color_map = mpl.rcParams['image.cmap'] colors = color_map(norm(values.values).filled()) values.plot(kind='bar', ax=axis, color=colors, **kwargs) return axis
python
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. vmax : Maximum value to clip values at. color_map : A matplotlib color map (see `matplotlib.cm`). **kwargs : Extra keyword arguments to pass to `values.plot`. Returns ------- (axis) : Bar plot axis. ''' if axis is None: fig, axis = plt.subplots() norm = mpl.colors.Normalize(vmin=vmin or min(values), vmax=vmax or max(values), clip=True) if color_map is None: color_map = mpl.rcParams['image.cmap'] colors = color_map(norm(values.values).filled()) values.plot(kind='bar', ax=axis, color=colors, **kwargs) return axis
[ "def", "plot_color_map_bars", "(", "values", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ",", "color_map", "=", "None", ",", "axis", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "axis", "is", "None", ":", "fig", ",", "axis", "=", "plt", ".", "subplots", "(", ")", "norm", "=", "mpl", ".", "colors", ".", "Normalize", "(", "vmin", "=", "vmin", "or", "min", "(", "values", ")", ",", "vmax", "=", "vmax", "or", "max", "(", "values", ")", ",", "clip", "=", "True", ")", "if", "color_map", "is", "None", ":", "color_map", "=", "mpl", ".", "rcParams", "[", "'image.cmap'", "]", "colors", "=", "color_map", "(", "norm", "(", "values", ".", "values", ")", ".", "filled", "(", ")", ")", "values", ".", "plot", "(", "kind", "=", "'bar'", ",", "ax", "=", "axis", ",", "color", "=", "colors", ",", "*", "*", "kwargs", ")", "return", "axis" ]
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. vmax : Maximum value to clip values at. color_map : A matplotlib color map (see `matplotlib.cm`). **kwargs : Extra keyword arguments to pass to `values.plot`. Returns ------- (axis) : Bar plot axis.
[ "Plot", "bar", "for", "each", "value", "in", "values", "colored", "based", "on", "values", "mapped", "onto", "the", "specified", "color", "map", "." ]
train
https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/plot.py#L138-L169
BlueBrain/hpcbench
hpcbench/toolbox/process.py
find_in_paths
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 """ 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
python
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 """ 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", ")", ":", "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" ]
Find an executable is a list of directories :return: absolute path to the first location where the executable is found, ``None`` otherwise. :rtype: string
[ "Find", "an", "executable", "is", "a", "list", "of", "directories", ":", "return", ":", "absolute", "path", "to", "the", "first", "location", "where", "the", "executable", "is", "found", "None", "otherwise", ".", ":", "rtype", ":", "string" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/process.py#L14-L25
BlueBrain/hpcbench
hpcbench/toolbox/process.py
find_executable
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 returns name if the program is not found. """ 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(_name, paths) if eax: return eax if required: raise NameError('Could not find %s executable' % name) else: return name
python
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 returns name if the program is not found. """ 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(_name, paths) if eax: return eax if required: raise NameError('Could not find %s executable' % name) else: return name
[ "def", "find_executable", "(", "name", ",", "names", "=", "None", ",", "required", "=", "True", ")", ":", "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", "(", "_name", ",", "paths", ")", "if", "eax", ":", "return", "eax", "if", "required", ":", "raise", "NameError", "(", "'Could not find %s executable'", "%", "name", ")", "else", ":", "return", "name" ]
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 returns name if the program is not found.
[ "Utility", "function", "to", "find", "an", "executable", "in", "PATH", "name", ":", "program", "to", "find", ".", "Use", "given", "value", "if", "absolute", "path" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/process.py#L28-L54
BlueBrain/hpcbench
hpcbench/toolbox/process.py
physical_cpus
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': 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 id'): sockets.add(line.split(':')[-1].strip()) return len(sockets)
python
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': 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 id'): sockets.add(line.split(':')[-1].strip()) return len(sockets)
[ "def", "physical_cpus", "(", ")", ":", "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 id'", ")", ":", "sockets", ".", "add", "(", "line", ".", "split", "(", "':'", ")", "[", "-", "1", "]", ".", "strip", "(", ")", ")", "return", "len", "(", "sockets", ")" ]
Get cpus identifiers, for instance set(["0", "1", "2", "3"]) :return Number of physical CPUs available :rtype: int
[ "Get", "cpus", "identifiers", "for", "instance", "set", "(", "[", "0", "1", "2", "3", "]", ")" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/process.py#L57-L74
elkiwy/paynter
paynter/layer.py
Layer.showLayer
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. """ 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)
python
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. """ 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", "=", "''", ")", ":", "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", ")" ]
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.
[ "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", "." ]
train
https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/layer.py#L65-L78
portfoliome/foil
foil/parsers.py
make_converters
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': float, 'grade': Grade) -> {'student_name': passthrough, 'score': parse_float, 'grade': Grade) """ return {k: TYPE_CASTERS.get(v, v) for k, v in data_types.items()}
python
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': float, 'grade': Grade) -> {'student_name': passthrough, 'score': parse_float, 'grade': Grade) """ return {k: TYPE_CASTERS.get(v, v) for k, v in data_types.items()}
[ "def", "make_converters", "(", "data_types", ")", "->", "dict", ":", "return", "{", "k", ":", "TYPE_CASTERS", ".", "get", "(", "v", ",", "v", ")", "for", "k", ",", "v", "in", "data_types", ".", "items", "(", ")", "}" ]
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': float, 'grade': Grade) -> {'student_name': passthrough, 'score': parse_float, 'grade': Grade)
[ "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", ":", "float", "grade", ":", "Grade", ")", "-", ">", "{", "student_name", ":", "passthrough", "score", ":", "parse_float", "grade", ":", "Grade", ")" ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/parsers.py#L104-L118
portfoliome/foil
foil/parsers.py
parse_broken_json
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. """ # Add spacing between Key and Value to prevent parsing error json_text = json_text.replace(":", ": ") json_dict = yaml.load(json_text) return json_dict
python
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. """ # 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", ":", "# Add spacing between Key and Value to prevent parsing error", "json_text", "=", "json_text", ".", "replace", "(", "\":\"", ",", "\": \"", ")", "json_dict", "=", "yaml", ".", "load", "(", "json_text", ")", "return", "json_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.
[ "Parses", "broken", "JSON", "that", "the", "standard", "Python", "JSON", "module", "cannot", "parse", "." ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/parsers.py#L121-L135
BlueBrain/hpcbench
hpcbench/driver/executor.py
ExecutionDriver._executor_script
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) 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
python
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) 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", ")", ":", "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" ]
Create shell-script in charge of executing the benchmark and return its path.
[ "Create", "shell", "-", "script", "in", "charge", "of", "executing", "the", "benchmark", "and", "return", "its", "path", "." ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/executor.py#L56-L66
BlueBrain/hpcbench
hpcbench/driver/executor.py
ExecutionDriver._jinja_executor_template
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) else: return jinja_environment.get_template(template)
python
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) else: return jinja_environment.get_template(template)
[ "def", "_jinja_executor_template", "(", "self", ")", ":", "template", "=", "self", ".", "campaign", ".", "process", ".", "executor_template", "if", "template", ".", "startswith", "(", "'#!'", ")", ":", "return", "jinja_environment", ".", "from_string", "(", "template", ")", "else", ":", "return", "jinja_environment", ".", "get_template", "(", "template", ")" ]
:return Jinja template of the shell-script executor
[ ":", "return", "Jinja", "template", "of", "the", "shell", "-", "script", "executor" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/executor.py#L69-L75
BlueBrain/hpcbench
hpcbench/driver/executor.py
ExecutionDriver._write_executor_script
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 environment but got ' msg += str(type(environment)) raise Exception(msg) escaped_environment = dict( (var, six.moves.shlex_quote(str(value))) for var, value in environment.items() ) modules = self.execution.get('modules') or [] properties = dict( command=self.command, cwd=os.getcwd(), modules=modules, environment=escaped_environment, ) self._jinja_executor_template.stream(**properties).dump(ostr)
python
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 environment but got ' msg += str(type(environment)) raise Exception(msg) escaped_environment = dict( (var, six.moves.shlex_quote(str(value))) for var, value in environment.items() ) modules = self.execution.get('modules') or [] properties = dict( command=self.command, cwd=os.getcwd(), modules=modules, environment=escaped_environment, ) self._jinja_executor_template.stream(**properties).dump(ostr)
[ "def", "_write_executor_script", "(", "self", ",", "ostr", ")", ":", "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", ".", "shlex_quote", "(", "str", "(", "value", ")", ")", ")", "for", "var", ",", "value", "in", "environment", ".", "items", "(", ")", ")", "modules", "=", "self", ".", "execution", ".", "get", "(", "'modules'", ")", "or", "[", "]", "properties", "=", "dict", "(", "command", "=", "self", ".", "command", ",", "cwd", "=", "os", ".", "getcwd", "(", ")", ",", "modules", "=", "modules", ",", "environment", "=", "escaped_environment", ",", ")", "self", ".", "_jinja_executor_template", ".", "stream", "(", "*", "*", "properties", ")", ".", "dump", "(", "ostr", ")" ]
Write shell script in charge of executing the command
[ "Write", "shell", "script", "in", "charge", "of", "executing", "the", "command" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/executor.py#L77-L95
BlueBrain/hpcbench
hpcbench/driver/executor.py
ExecutionDriver.command
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): command = [arg.format(**self.command_expansion_vars) for arg in command] else: command = command.format(**self.command_expansion_vars) if self.execution.get('shell', False): if not isinstance(exec_prefix, six.string_types): exec_prefix = ' '.join(exec_prefix) if not isinstance(command, six.string_types): msg = "Expected string for shell command, not {type}: {value}" msg = msg.format(type=type(command).__name__, value=repr(command)) raise Exception(msg) eax = [exec_prefix + command] else: if not isinstance(exec_prefix, SEQUENCES): exec_prefix = shlex.split(exec_prefix) if not isinstance(command, SEQUENCES): eax = exec_prefix + shlex.split(command) else: eax = exec_prefix + command eax = [six.moves.shlex_quote(arg) for arg in eax] return eax
python
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): command = [arg.format(**self.command_expansion_vars) for arg in command] else: command = command.format(**self.command_expansion_vars) if self.execution.get('shell', False): if not isinstance(exec_prefix, six.string_types): exec_prefix = ' '.join(exec_prefix) if not isinstance(command, six.string_types): msg = "Expected string for shell command, not {type}: {value}" msg = msg.format(type=type(command).__name__, value=repr(command)) raise Exception(msg) eax = [exec_prefix + command] else: if not isinstance(exec_prefix, SEQUENCES): exec_prefix = shlex.split(exec_prefix) if not isinstance(command, SEQUENCES): eax = exec_prefix + shlex.split(command) else: eax = exec_prefix + command eax = [six.moves.shlex_quote(arg) for arg in eax] return eax
[ "def", "command", "(", "self", ")", ":", "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", ".", "command_expansion_vars", ")", "if", "self", ".", "execution", ".", "get", "(", "'shell'", ",", "False", ")", ":", "if", "not", "isinstance", "(", "exec_prefix", ",", "six", ".", "string_types", ")", ":", "exec_prefix", "=", "' '", ".", "join", "(", "exec_prefix", ")", "if", "not", "isinstance", "(", "command", ",", "six", ".", "string_types", ")", ":", "msg", "=", "\"Expected string for shell command, not {type}: {value}\"", "msg", "=", "msg", ".", "format", "(", "type", "=", "type", "(", "command", ")", ".", "__name__", ",", "value", "=", "repr", "(", "command", ")", ")", "raise", "Exception", "(", "msg", ")", "eax", "=", "[", "exec_prefix", "+", "command", "]", "else", ":", "if", "not", "isinstance", "(", "exec_prefix", ",", "SEQUENCES", ")", ":", "exec_prefix", "=", "shlex", ".", "split", "(", "exec_prefix", ")", "if", "not", "isinstance", "(", "command", ",", "SEQUENCES", ")", ":", "eax", "=", "exec_prefix", "+", "shlex", ".", "split", "(", "command", ")", "else", ":", "eax", "=", "exec_prefix", "+", "command", "eax", "=", "[", "six", ".", "moves", ".", "shlex_quote", "(", "arg", ")", "for", "arg", "in", "eax", "]", "return", "eax" ]
:return command to execute inside the generated shell-script
[ ":", "return", "command", "to", "execute", "inside", "the", "generated", "shell", "-", "script" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/executor.py#L98-L122
BlueBrain/hpcbench
hpcbench/driver/executor.py
ExecutionDriver.command_str
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.moves.shlex_quote, self.command))
python
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.moves.shlex_quote, self.command))
[ "def", "command_str", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "command", ",", "six", ".", "string_types", ")", ":", "return", "self", ".", "command", "return", "' '", ".", "join", "(", "map", "(", "six", ".", "moves", ".", "shlex_quote", ",", "self", ".", "command", ")", ")" ]
get command to execute as string properly escaped :return: string
[ "get", "command", "to", "execute", "as", "string", "properly", "escaped" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/executor.py#L125-L132
BlueBrain/hpcbench
hpcbench/driver/executor.py
ExecutionDriver.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, stderr=stderr)
python
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, stderr=stderr)
[ "def", "popen", "(", "self", ",", "stdout", ",", "stderr", ")", ":", "self", ".", "logger", ".", "info", "(", "'Executing command: %s'", ",", "self", ".", "command_str", ")", "return", "subprocess", ".", "Popen", "(", "[", "self", ".", "_executor_script", "]", ",", "stdout", "=", "stdout", ",", "stderr", "=", "stderr", ")" ]
Build popen object to run :rtype: subprocess.Popen
[ "Build", "popen", "object", "to", "run" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/executor.py#L134-L140
BlueBrain/hpcbench
hpcbench/driver/executor.py
SrunExecutionDriver.srun_cartesian_product
def srun_cartesian_product(cls, campaign, config): """ :param campaign: global YAML configuration :param config: benchmark YAML configuration """ 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]) return [dict(combination) for combination in itertools.product(*options_tuple)]
python
def srun_cartesian_product(cls, campaign, config): """ :param campaign: global YAML configuration :param config: benchmark YAML configuration """ 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]) return [dict(combination) for combination in itertools.product(*options_tuple)]
[ "def", "srun_cartesian_product", "(", "cls", ",", "campaign", ",", "config", ")", ":", "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", "]", ")", "return", "[", "dict", "(", "combination", ")", "for", "combination", "in", "itertools", ".", "product", "(", "*", "options_tuple", ")", "]" ]
:param campaign: global YAML configuration :param config: benchmark YAML configuration
[ ":", "param", "campaign", ":", "global", "YAML", "configuration", ":", "param", "config", ":", "benchmark", "YAML", "configuration" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/executor.py#L202-L214
BlueBrain/hpcbench
hpcbench/driver/executor.py
SrunExecutionDriver.srun
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('utf-8') return srun
python
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('utf-8') return srun
[ "def", "srun", "(", "self", ")", ":", "commands", "=", "self", ".", "campaign", ".", "process", ".", "get", "(", "'commands'", ",", "{", "}", ")", "srun", "=", "find_executable", "(", "commands", ".", "get", "(", "'srun'", ",", "'srun'", ")", ")", "if", "six", ".", "PY2", ":", "srun", "=", "srun", ".", "encode", "(", "'utf-8'", ")", "return", "srun" ]
Get path to srun executable :rtype: string
[ "Get", "path", "to", "srun", "executable" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/executor.py#L217-L226
BlueBrain/hpcbench
hpcbench/driver/executor.py
SrunExecutionDriver.common_srun_options
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.stdout', error='slurm-%N-%t.error') return default
python
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.stdout', error='slurm-%N-%t.error') return default
[ "def", "common_srun_options", "(", "cls", ",", "campaign", ")", ":", "default", "=", "dict", "(", "campaign", ".", "process", ".", "get", "(", "'srun'", ")", "or", "{", "}", ")", "default", ".", "update", "(", "output", "=", "'slurm-%N-%t.stdout'", ",", "error", "=", "'slurm-%N-%t.error'", ")", "return", "default" ]
Get options to be given to all srun commands :rtype: list of string
[ "Get", "options", "to", "be", "given", "to", "all", "srun", "commands" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/executor.py#L229-L236
BlueBrain/hpcbench
hpcbench/driver/executor.py
SrunExecutionDriver.command
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): pargs = parse_constraint_in_args(srun_optlist) self.command_expansion_vars['process_count'] = pargs.ntasks if not pargs.constraint: # Expand nodelist if --constraint option is not specified # in srun options srun_optlist += [ '--nodelist=' + ','.join(self.srun_nodes), '--nodes=' + str(len(self.srun_nodes)), ] command = super(SrunExecutionDriver, self).command return [self.srun] + srun_optlist + command
python
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): pargs = parse_constraint_in_args(srun_optlist) self.command_expansion_vars['process_count'] = pargs.ntasks if not pargs.constraint: # Expand nodelist if --constraint option is not specified # in srun options srun_optlist += [ '--nodelist=' + ','.join(self.srun_nodes), '--nodes=' + str(len(self.srun_nodes)), ] command = super(SrunExecutionDriver, self).command return [self.srun] + srun_optlist + command
[ "def", "command", "(", "self", ")", ":", "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", ".", "constraint", ":", "# Expand nodelist if --constraint option is not specified", "# in srun options", "srun_optlist", "+=", "[", "'--nodelist='", "+", "','", ".", "join", "(", "self", ".", "srun_nodes", ")", ",", "'--nodes='", "+", "str", "(", "len", "(", "self", ".", "srun_nodes", ")", ")", ",", "]", "command", "=", "super", "(", "SrunExecutionDriver", ",", "self", ")", ".", "command", "return", "[", "self", ".", "srun", "]", "+", "srun_optlist", "+", "command" ]
get command to execute :return: list of string
[ "get", "command", "to", "execute" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/executor.py#L243-L260
BlueBrain/hpcbench
hpcbench/driver/executor.py
SrunExecutionDriver.srun_nodes
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, SEQUENCES): return count else: assert isinstance(count, int) tag = self.tag nodes = self._srun_nodes(tag, count) if 'srun_nodes' in self.execution: self.execution['srun_nodes'] = nodes self.execution['srun_nodes_count'] = len(nodes) return nodes
python
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, SEQUENCES): return count else: assert isinstance(count, int) tag = self.tag nodes = self._srun_nodes(tag, count) if 'srun_nodes' in self.execution: self.execution['srun_nodes'] = nodes self.execution['srun_nodes_count'] = len(nodes) return nodes
[ "def", "srun_nodes", "(", "self", ")", ":", "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", "=", "self", ".", "_srun_nodes", "(", "tag", ",", "count", ")", "if", "'srun_nodes'", "in", "self", ".", "execution", ":", "self", ".", "execution", "[", "'srun_nodes'", "]", "=", "nodes", "self", ".", "execution", "[", "'srun_nodes_count'", "]", "=", "len", "(", "nodes", ")", "return", "nodes" ]
Get list of nodes where to execute the command
[ "Get", "list", "of", "nodes", "where", "to", "execute", "the", "command" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/executor.py#L263-L279
Capitains/Nautilus
capitains_nautilus/collections/sparql.py
clear_graph
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(identifier) try: graph.close() except: warn("Unable to close the Graph")
python
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(identifier) try: graph.close() except: warn("Unable to close the Graph")
[ "def", "clear_graph", "(", "identifier", "=", "None", ")", ":", "graph", "=", "get_graph", "(", ")", "if", "identifier", ":", "graph", ".", "destroy", "(", "identifier", ")", "try", ":", "graph", ".", "close", "(", ")", "except", ":", "warn", "(", "\"Unable to close the Graph\"", ")" ]
Clean up a graph by removing it :param identifier: Root identifier of the graph :return:
[ "Clean", "up", "a", "graph", "by", "removing", "it" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/collections/sparql.py#L13-L25
Capitains/Nautilus
capitains_nautilus/collections/sparql.py
generate_alchemy_graph
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 """ 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 == "": prefix = "cts" # Fix until ALchemy Store accepts empty prefixes graph.bind(prefix, ns) return graph, identifier, uri
python
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 """ 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 == "": prefix = "cts" # Fix until ALchemy Store accepts empty prefixes graph.bind(prefix, ns) return graph, identifier, uri
[ "def", "generate_alchemy_graph", "(", "alchemy_uri", ",", "prefixes", "=", "None", ",", "identifier", "=", "\"NautilusSparql\"", ")", ":", "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", "==", "\"\"", ":", "prefix", "=", "\"cts\"", "# Fix until ALchemy Store accepts empty prefixes", "graph", ".", "bind", "(", "prefix", ",", "ns", ")", "return", "graph", ",", "identifier", ",", "uri" ]
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
[ "Generate", "a", "graph", "and", "change", "the", "global", "graph", "to", "this", "one" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/collections/sparql.py#L28-L47
Capitains/Nautilus
capitains_nautilus/collections/sparql.py
generate_sleepy_cat_graph
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 """ 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 graph.bind(prefix, ns) return graph, identifier, filepath
python
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 """ 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 graph.bind(prefix, ns) return graph, identifier, filepath
[ "def", "generate_sleepy_cat_graph", "(", "filepath", ",", "prefixes", "=", "None", ",", "identifier", "=", "\"NautilusSparql\"", ")", ":", "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", "graph", ".", "bind", "(", "prefix", ",", "ns", ")", "return", "graph", ",", "identifier", ",", "filepath" ]
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
[ "Generate", "a", "graph", "and", "change", "the", "global", "graph", "to", "this", "one" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/collections/sparql.py#L50-L67
Capitains/Nautilus
capitains_nautilus/collections/sparql.py
SparqlNavigatedCollection.set_label
def set_label(self, label, lang): """ Add the label of the collection in given lang :param label: Label Value :param lang: Language code """ 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
python
def set_label(self, label, lang): """ Add the label of the collection in given lang :param label: Label Value :param lang: Language code """ 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", ")", ":", "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" ]
Add the label of the collection in given lang :param label: Label Value :param lang: Language code
[ "Add", "the", "label", "of", "the", "collection", "in", "given", "lang" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/collections/sparql.py#L92-L104
Capitains/Nautilus
capitains_nautilus/collections/sparql.py
SparqlNavigatedCollection.members
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.parent, self.asNode()) ] )
python
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.parent, self.asNode()) ] )
[ "def", "members", "(", "self", ")", ":", "return", "list", "(", "[", "self", ".", "children_class", "(", "child", ")", "for", "child", "in", "self", ".", "graph", ".", "subjects", "(", "RDF_NAMESPACES", ".", "DTS", ".", "parent", ",", "self", ".", "asNode", "(", ")", ")", "]", ")" ]
Children of the collection's item :rtype: [Collection]
[ "Children", "of", "the", "collection", "s", "item" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/collections/sparql.py#L130-L140
Capitains/Nautilus
capitains_nautilus/collections/sparql.py
SparqlNavigatedCollection.parent
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
python
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
[ "def", "parent", "(", "self", ")", ":", "parent", "=", "list", "(", "self", ".", "graph", ".", "objects", "(", "self", ".", "asNode", "(", ")", ",", "RDF_NAMESPACES", ".", "DTS", ".", "parent", ")", ")", "if", "parent", ":", "return", "self", ".", "parent_class", "(", "parent", "[", "0", "]", ")", "return", "None" ]
Parent of current object :rtype: Collection
[ "Parent", "of", "current", "object" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/collections/sparql.py#L186-L194
PolyJIT/benchbuild
benchbuild/experiments/raw.py
RawRuntime.actions_for_project
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)) return self.default_runtime_actions(project)
python
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)) return self.default_runtime_actions(project)
[ "def", "actions_for_project", "(", "self", ",", "project", ")", ":", "project", ".", "cflags", "=", "[", "\"-O3\"", ",", "\"-fno-omit-frame-pointer\"", "]", "project", ".", "runtime_extension", "=", "time", ".", "RunWithTime", "(", "run", ".", "RuntimeExtension", "(", "project", ",", "self", ")", ")", "return", "self", ".", "default_runtime_actions", "(", "project", ")" ]
Compile & Run the experiment with -O3 enabled.
[ "Compile", "&", "Run", "the", "experiment", "with", "-", "O3", "enabled", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/experiments/raw.py#L27-L32
PolyJIT/benchbuild
benchbuild/utils/actions.py
to_step_result
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 list. Args: func: The function to wrap. """ @ft.wraps(func) def wrapper(*args, **kwargs): """Wrapper stub.""" res = func(*args, **kwargs) if not res: res = [StepResult.OK] if not hasattr(res, "__iter__"): res = [res] return res return wrapper
python
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 list. Args: func: The function to wrap. """ @ft.wraps(func) def wrapper(*args, **kwargs): """Wrapper stub.""" 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", ")", ":", "@", "ft", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Wrapper stub.\"\"\"", "res", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "not", "res", ":", "res", "=", "[", "StepResult", ".", "OK", "]", "if", "not", "hasattr", "(", "res", ",", "\"__iter__\"", ")", ":", "res", "=", "[", "res", "]", "return", "res", "return", "wrapper" ]
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 list. Args: func: The function to wrap.
[ "Convert", "a", "function", "return", "to", "a", "list", "of", "StepResults", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/actions.py#L64-L90
PolyJIT/benchbuild
benchbuild/utils/actions.py
prepend_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: res = "[{status}]".format(status=self.status.name) + res return res return wrapper
python
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: res = "[{status}]".format(status=self.status.name) + res return res return wrapper
[ "def", "prepend_status", "(", "func", ")", ":", "@", "ft", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Wrapper stub.\"\"\"", "res", "=", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "if", "self", ".", "status", "is", "not", "StepResult", ".", "UNSET", ":", "res", "=", "\"[{status}]\"", ".", "format", "(", "status", "=", "self", ".", "status", ".", "name", ")", "+", "res", "return", "res", "return", "wrapper" ]
Prepends the output of `func` with the status.
[ "Prepends", "the", "output", "of", "func", "with", "the", "status", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/actions.py#L93-L104
PolyJIT/benchbuild
benchbuild/utils/actions.py
notify_step_begin_end
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.ON_STEP_END for begin_listener in on_step_begin: begin_listener(self) res = func(self, *args, **kwargs) for end_listener in on_step_end: end_listener(self, func) return res return wrapper
python
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.ON_STEP_END for begin_listener in on_step_begin: begin_listener(self) res = func(self, *args, **kwargs) for end_listener in on_step_end: end_listener(self, func) return res return wrapper
[ "def", "notify_step_begin_end", "(", "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", ".", "ON_STEP_END", "for", "begin_listener", "in", "on_step_begin", ":", "begin_listener", "(", "self", ")", "res", "=", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "for", "end_listener", "in", "on_step_end", ":", "end_listener", "(", "self", ",", "func", ")", "return", "res", "return", "wrapper" ]
Print the beginning and the end of a `func`.
[ "Print", "the", "beginning", "and", "the", "end", "of", "a", "func", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/actions.py#L107-L126
PolyJIT/benchbuild
benchbuild/utils/actions.py
log_before_after
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.info("\n%s - %s", name, desc) res = f(*args, **kwargs) if StepResult.ERROR not in res: LOG.info("%s - OK\n", name) else: LOG.error("%s - ERROR\n", name) return res return wrapper return func_decorator
python
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.info("\n%s - %s", name, desc) res = f(*args, **kwargs) if StepResult.ERROR not in res: LOG.info("%s - OK\n", name) else: LOG.error("%s - ERROR\n", name) return res return wrapper return func_decorator
[ "def", "log_before_after", "(", "name", ":", "str", ",", "desc", ":", "str", ")", ":", "def", "func_decorator", "(", "f", ")", ":", "\"\"\"Wrapper stub.\"\"\"", "@", "ft", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Wrapper stub.\"\"\"", "LOG", ".", "info", "(", "\"\\n%s - %s\"", ",", "name", ",", "desc", ")", "res", "=", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "StepResult", ".", "ERROR", "not", "in", "res", ":", "LOG", ".", "info", "(", "\"%s - OK\\n\"", ",", "name", ")", "else", ":", "LOG", ".", "error", "(", "\"%s - ERROR\\n\"", ",", "name", ")", "return", "res", "return", "wrapper", "return", "func_decorator" ]
Log customized stirng before & after running func.
[ "Log", "customized", "stirng", "before", "&", "after", "running", "func", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/actions.py#L129-L148
mckib2/rawdatarinator
rawdatarinator/quickview.py
quickview
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) Display k-space data, log magnitude and phase plots. ''' if filename.endswith('.npz'): data = np.load(filename) elif filename.endswith('.dat'): from rawdatarinator.readMeasDataVB15 import readMeasDataVB15 as rmd data = rmd(filename) elif filename.endswith('.mat'): import scipy.io data = scipy.io.loadmat('file.mat') else: data = h5py.File(filename,'r') if 'kSpace' in data: key = 'kSpace' else: key = 'imSpace' noIFFT = not noIFFT # Average over all the averages, use first coil coil = 0 num_avgs = data[key].shape[2] avg = (np.squeeze(np.sum(data[key],axis=2))/num_avgs)[:,:,coil] if noIFFT is False: imData = np.fft.ifftshift(np.fft.ifft2(avg)) plt.imshow(np.absolute(imData),cmap='gray') plt.title('Image Data') else: mag = np.log(np.absolute(avg)) phase = np.angle(avg) f,(ax1,ax2) = plt.subplots(1,2,sharey=True) ax1.imshow(mag,cmap='gray') ax2.imshow(phase,cmap='gray') ax1.set_title('log(Magnitude)') ax2.set_title('Phase') plt.show()
python
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) Display k-space data, log magnitude and phase plots. ''' if filename.endswith('.npz'): data = np.load(filename) elif filename.endswith('.dat'): from rawdatarinator.readMeasDataVB15 import readMeasDataVB15 as rmd data = rmd(filename) elif filename.endswith('.mat'): import scipy.io data = scipy.io.loadmat('file.mat') else: data = h5py.File(filename,'r') if 'kSpace' in data: key = 'kSpace' else: key = 'imSpace' noIFFT = not noIFFT # Average over all the averages, use first coil coil = 0 num_avgs = data[key].shape[2] avg = (np.squeeze(np.sum(data[key],axis=2))/num_avgs)[:,:,coil] if noIFFT is False: imData = np.fft.ifftshift(np.fft.ifft2(avg)) plt.imshow(np.absolute(imData),cmap='gray') plt.title('Image Data') else: mag = np.log(np.absolute(avg)) phase = np.angle(avg) f,(ax1,ax2) = plt.subplots(1,2,sharey=True) ax1.imshow(mag,cmap='gray') ax2.imshow(phase,cmap='gray') ax1.set_title('log(Magnitude)') ax2.set_title('Phase') plt.show()
[ "def", "quickview", "(", "filename", ",", "noIFFT", "=", "False", ")", ":", "if", "filename", ".", "endswith", "(", "'.npz'", ")", ":", "data", "=", "np", ".", "load", "(", "filename", ")", "elif", "filename", ".", "endswith", "(", "'.dat'", ")", ":", "from", "rawdatarinator", ".", "readMeasDataVB15", "import", "readMeasDataVB15", "as", "rmd", "data", "=", "rmd", "(", "filename", ")", "elif", "filename", ".", "endswith", "(", "'.mat'", ")", ":", "import", "scipy", ".", "io", "data", "=", "scipy", ".", "io", ".", "loadmat", "(", "'file.mat'", ")", "else", ":", "data", "=", "h5py", ".", "File", "(", "filename", ",", "'r'", ")", "if", "'kSpace'", "in", "data", ":", "key", "=", "'kSpace'", "else", ":", "key", "=", "'imSpace'", "noIFFT", "=", "not", "noIFFT", "# Average over all the averages, use first coil", "coil", "=", "0", "num_avgs", "=", "data", "[", "key", "]", ".", "shape", "[", "2", "]", "avg", "=", "(", "np", ".", "squeeze", "(", "np", ".", "sum", "(", "data", "[", "key", "]", ",", "axis", "=", "2", ")", ")", "/", "num_avgs", ")", "[", ":", ",", ":", ",", "coil", "]", "if", "noIFFT", "is", "False", ":", "imData", "=", "np", ".", "fft", ".", "ifftshift", "(", "np", ".", "fft", ".", "ifft2", "(", "avg", ")", ")", "plt", ".", "imshow", "(", "np", ".", "absolute", "(", "imData", ")", ",", "cmap", "=", "'gray'", ")", "plt", ".", "title", "(", "'Image Data'", ")", "else", ":", "mag", "=", "np", ".", "log", "(", "np", ".", "absolute", "(", "avg", ")", ")", "phase", "=", "np", ".", "angle", "(", "avg", ")", "f", ",", "(", "ax1", ",", "ax2", ")", "=", "plt", ".", "subplots", "(", "1", ",", "2", ",", "sharey", "=", "True", ")", "ax1", ".", "imshow", "(", "mag", ",", "cmap", "=", "'gray'", ")", "ax2", ".", "imshow", "(", "phase", ",", "cmap", "=", "'gray'", ")", "ax1", ".", "set_title", "(", "'log(Magnitude)'", ")", "ax2", ".", "set_title", "(", "'Phase'", ")", "plt", ".", "show", "(", ")" ]
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) Display k-space data, log magnitude and phase plots.
[ "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", ")", "." ]
train
https://github.com/mckib2/rawdatarinator/blob/03a85fd8f5e380b424027d28e97972bd7a6a3f1b/rawdatarinator/quickview.py#L7-L53
lazygunner/xunleipy
xunleipy/rsa_lib.py
euclid
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
python
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
[ "def", "euclid", "(", "a", ",", "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 the Greatest Common Divisor of a and b
[ "returns", "the", "Greatest", "Common", "Divisor", "of", "a", "and", "b" ]
train
https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/rsa_lib.py#L13-L21
lazygunner/xunleipy
xunleipy/rsa_lib.py
coPrime
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 return True
python
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 return True
[ "def", "coPrime", "(", "l", ")", ":", "for", "i", ",", "j", "in", "combinations", "(", "l", ",", "2", ")", ":", "if", "euclid", "(", "i", ",", "j", ")", "!=", "1", ":", "return", "False", "return", "True" ]
returns 'True' if the values in the list L are all co-prime otherwise, it returns 'False'.
[ "returns", "True", "if", "the", "values", "in", "the", "list", "L", "are", "all", "co", "-", "prime", "otherwise", "it", "returns", "False", "." ]
train
https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/rsa_lib.py#L24-L30
lazygunner/xunleipy
xunleipy/rsa_lib.py
extendedEuclid
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 = extendedEuclid(b % a, a) return g, x - (b // a) * y, y
python
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 = extendedEuclid(b % a, a) return g, x - (b // a) * y, y
[ "def", "extendedEuclid", "(", "a", ",", "b", ")", ":", "if", "a", "==", "0", ":", "return", "b", ",", "0", ",", "1", "else", ":", "g", ",", "y", ",", "x", "=", "extendedEuclid", "(", "b", "%", "a", ",", "a", ")", "return", "g", ",", "x", "-", "(", "b", "//", "a", ")", "*", "y", ",", "y" ]
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
[ "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" ]
train
https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/rsa_lib.py#L33-L40
lazygunner/xunleipy
xunleipy/rsa_lib.py
modInv
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]): linearCombination = extendedEuclid(a, m) return linearCombination[1] % m else: return 0
python
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]): linearCombination = extendedEuclid(a, m) return linearCombination[1] % m else: return 0
[ "def", "modInv", "(", "a", ",", "m", ")", ":", "# 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" ]
returns the multiplicative inverse of a in modulo m as a positive value between zero and m-1
[ "returns", "the", "multiplicative", "inverse", "of", "a", "in", "modulo", "m", "as", "a", "positive", "value", "between", "zero", "and", "m", "-", "1" ]
train
https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/rsa_lib.py#L43-L51
lazygunner/xunleipy
xunleipy/rsa_lib.py
extractTwos
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). 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
python
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). 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", ")", ":", "# 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" ]
m is a positive integer. A tuple (s, d) of integers is returned such that m = (2 ** s) * d.
[ "m", "is", "a", "positive", "integer", ".", "A", "tuple", "(", "s", "d", ")", "of", "integers", "is", "returned", "such", "that", "m", "=", "(", "2", "**", "s", ")", "*", "d", "." ]
train
https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/rsa_lib.py#L54-L64
lazygunner/xunleipy
xunleipy/rsa_lib.py
int2baseTwo
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 = [] while x != 0: bitInverse.append(x & 1) x >>= 1 return bitInverse
python
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 = [] while x != 0: bitInverse.append(x & 1) x >>= 1 return bitInverse
[ "def", "int2baseTwo", "(", "x", ")", ":", "# 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" ]
x is a positive integer. Convert it to base two as a list of integers in reverse order as a list.
[ "x", "is", "a", "positive", "integer", ".", "Convert", "it", "to", "base", "two", "as", "a", "list", "of", "integers", "in", "reverse", "order", "as", "a", "list", "." ]
train
https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/rsa_lib.py#L67-L76
lazygunner/xunleipy
xunleipy/rsa_lib.py
modExp
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: modArray.append((modArray[i - 2] ** 2) % n) for i in range(0, base2DLength): if base2D[i] == 1: result *= base2D[i] * modArray[i] return result % n
python
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: modArray.append((modArray[i - 2] ** 2) % n) for i in range(0, base2DLength): if base2D[i] == 1: result *= base2D[i] * modArray[i] return result % n
[ "def", "modExp", "(", "a", ",", "d", ",", "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", ":", "modArray", ".", "append", "(", "(", "modArray", "[", "i", "-", "2", "]", "**", "2", ")", "%", "n", ")", "for", "i", "in", "range", "(", "0", ",", "base2DLength", ")", ":", "if", "base2D", "[", "i", "]", "==", "1", ":", "result", "*=", "base2D", "[", "i", "]", "*", "modArray", "[", "i", "]", "return", "result", "%", "n" ]
returns a ** d (mod n)
[ "returns", "a", "**", "d", "(", "mod", "n", ")" ]
train
https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/rsa_lib.py#L79-L95
lazygunner/xunleipy
xunleipy/rsa_lib.py
millerRabin
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 """ 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 bigger than 2 extract2 = extractTwos(n - 1) s = extract2[0] d = extract2[1] assert 2 ** s * d == n - 1 def tryComposite(a): """Inner function which will inspect whether a given witness will reveal the true identity of n. Will only be called within millerRabin""" x = modExp(a, d, n) if x == 1 or x == n - 1: return None else: for j in range(1, s): x = modExp(x, 2, n) if x == 1: return False elif x == n - 1: return None return False for i in range(0, k): a = random.randint(2, n - 2) if tryComposite(a) == False: return False return True
python
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 """ 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 bigger than 2 extract2 = extractTwos(n - 1) s = extract2[0] d = extract2[1] assert 2 ** s * d == n - 1 def tryComposite(a): """Inner function which will inspect whether a given witness will reveal the true identity of n. Will only be called within millerRabin""" x = modExp(a, d, n) if x == 1 or x == n - 1: return None else: for j in range(1, s): x = modExp(x, 2, n) if x == 1: return False elif x == n - 1: return None return False for i in range(0, k): a = random.randint(2, n - 2) if tryComposite(a) == False: return False return True
[ "def", "millerRabin", "(", "n", ",", "k", ")", ":", "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 bigger than 2", "extract2", "=", "extractTwos", "(", "n", "-", "1", ")", "s", "=", "extract2", "[", "0", "]", "d", "=", "extract2", "[", "1", "]", "assert", "2", "**", "s", "*", "d", "==", "n", "-", "1", "def", "tryComposite", "(", "a", ")", ":", "\"\"\"Inner function which will inspect whether a given witness\n will reveal the true identity of n. Will only be called within\n millerRabin\"\"\"", "x", "=", "modExp", "(", "a", ",", "d", ",", "n", ")", "if", "x", "==", "1", "or", "x", "==", "n", "-", "1", ":", "return", "None", "else", ":", "for", "j", "in", "range", "(", "1", ",", "s", ")", ":", "x", "=", "modExp", "(", "x", ",", "2", ",", "n", ")", "if", "x", "==", "1", ":", "return", "False", "elif", "x", "==", "n", "-", "1", ":", "return", "None", "return", "False", "for", "i", "in", "range", "(", "0", ",", "k", ")", ":", "a", "=", "random", ".", "randint", "(", "2", ",", "n", "-", "2", ")", "if", "tryComposite", "(", "a", ")", "==", "False", ":", "return", "False", "return", "True" ]
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
[ "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" ]
train
https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/rsa_lib.py#L98-L144
lazygunner/xunleipy
xunleipy/rsa_lib.py
primeSieve
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""" def isPrime(n): """return True is given number n is absolutely prime, return False is otherwise.""" 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 result
python
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""" def isPrime(n): """return True is given number n is absolutely prime, return False is otherwise.""" 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 result
[ "def", "primeSieve", "(", "k", ")", ":", "def", "isPrime", "(", "n", ")", ":", "\"\"\"return True is given number n is absolutely prime,\n return False is otherwise.\"\"\"", "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", "result" ]
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
[ "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" ]
train
https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/rsa_lib.py#L147-L164