id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
27,300
ARMmbed/icetea
icetea_lib/tools/file/SessionFiles.py
JsonFile.write_values
def write_values(self, data, filepath=None, filename=None, indent=None, keys_to_write=None): """ Tries to write extra content to a JSON file. Creates filename.temp with updated content, removes the old file and finally renames the .temp to match the old file. This is in effort to preserve the data in case of some weird errors cause problems. :param filepath: Path to file :param filename: Name of file :param data: Data to write as a dictionary :param indent: indent level for pretty printing the resulting file :param keys_to_write: array of keys that are to be picked from data and written to file. Default is None, when all data is written to file. :return: Path to file used :raises EnvironmentError ValueError """ name = filename if filename else self.filename path = filepath if filepath else self.filepath name = self._ends_with(name, ".json") path = self._ends_with(path, os.path.sep) if not os.path.isfile(path + name): try: return self.write_file(data, path, name, indent, keys_to_write) except EnvironmentError as error: self.logger.error("Error while opening or writing to file: {}".format(error)) raise except ValueError: raise if keys_to_write: data_to_write = {} for key in keys_to_write: data_to_write[key] = data[key] else: data_to_write = data try: with open(path + name, 'r') as fil: output = json.load(fil) self.logger.info("Read contents of {}".format(filename)) for key in data_to_write: try: output[key] = data_to_write[key] except TypeError as error: self.logger.error( "File contents could not be serialized into a dict. {}".format(error)) raise self._write_json(path, name + ".temp", "w", output, indent) FileUtils.remove_file(name, path) FileUtils.rename_file(name + '.temp', name, path) return os.path.join(path, name) except EnvironmentError as error: self.logger.error( "Error while writing to, opening or reading the file: {}".format(error)) raise except ValueError as error: self.logger.error( "File could not be decoded to JSON. It might be empty? {}".format(error)) try: self._write_json(path, name, "w", data_to_write, indent) return os.path.join(path, name) except EnvironmentError: raise
python
def write_values(self, data, filepath=None, filename=None, indent=None, keys_to_write=None): name = filename if filename else self.filename path = filepath if filepath else self.filepath name = self._ends_with(name, ".json") path = self._ends_with(path, os.path.sep) if not os.path.isfile(path + name): try: return self.write_file(data, path, name, indent, keys_to_write) except EnvironmentError as error: self.logger.error("Error while opening or writing to file: {}".format(error)) raise except ValueError: raise if keys_to_write: data_to_write = {} for key in keys_to_write: data_to_write[key] = data[key] else: data_to_write = data try: with open(path + name, 'r') as fil: output = json.load(fil) self.logger.info("Read contents of {}".format(filename)) for key in data_to_write: try: output[key] = data_to_write[key] except TypeError as error: self.logger.error( "File contents could not be serialized into a dict. {}".format(error)) raise self._write_json(path, name + ".temp", "w", output, indent) FileUtils.remove_file(name, path) FileUtils.rename_file(name + '.temp', name, path) return os.path.join(path, name) except EnvironmentError as error: self.logger.error( "Error while writing to, opening or reading the file: {}".format(error)) raise except ValueError as error: self.logger.error( "File could not be decoded to JSON. It might be empty? {}".format(error)) try: self._write_json(path, name, "w", data_to_write, indent) return os.path.join(path, name) except EnvironmentError: raise
[ "def", "write_values", "(", "self", ",", "data", ",", "filepath", "=", "None", ",", "filename", "=", "None", ",", "indent", "=", "None", ",", "keys_to_write", "=", "None", ")", ":", "name", "=", "filename", "if", "filename", "else", "self", ".", "filen...
Tries to write extra content to a JSON file. Creates filename.temp with updated content, removes the old file and finally renames the .temp to match the old file. This is in effort to preserve the data in case of some weird errors cause problems. :param filepath: Path to file :param filename: Name of file :param data: Data to write as a dictionary :param indent: indent level for pretty printing the resulting file :param keys_to_write: array of keys that are to be picked from data and written to file. Default is None, when all data is written to file. :return: Path to file used :raises EnvironmentError ValueError
[ "Tries", "to", "write", "extra", "content", "to", "a", "JSON", "file", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/file/SessionFiles.py#L123-L188
27,301
ARMmbed/icetea
icetea_lib/tools/file/SessionFiles.py
JsonFile._write_json
def _write_json(self, filepath, filename, writemode, content, indent): """ Helper for writing content to a file. :param filepath: path to file :param filename: name of file :param writemode: writemode used :param content: content to write :param indent: value for dump indent parameter. :return: Norhing """ with open(os.path.join(filepath, filename), writemode) as fil: json.dump(content, fil, indent=indent) self.logger.info("Wrote content to file {}".format(filename))
python
def _write_json(self, filepath, filename, writemode, content, indent): with open(os.path.join(filepath, filename), writemode) as fil: json.dump(content, fil, indent=indent) self.logger.info("Wrote content to file {}".format(filename))
[ "def", "_write_json", "(", "self", ",", "filepath", ",", "filename", ",", "writemode", ",", "content", ",", "indent", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "filepath", ",", "filename", ")", ",", "writemode", ")", "as", "...
Helper for writing content to a file. :param filepath: path to file :param filename: name of file :param writemode: writemode used :param content: content to write :param indent: value for dump indent parameter. :return: Norhing
[ "Helper", "for", "writing", "content", "to", "a", "file", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/file/SessionFiles.py#L190-L203
27,302
ARMmbed/icetea
icetea_lib/tools/file/SessionFiles.py
JsonFile._read_json
def _read_json(self, path, name): """ Load a json into a dictionary from a file. :param path: path to file :param name: name of file :return: dict """ with open(os.path.join(path, name), 'r') as fil: output = json.load(fil) self.logger.info("Read contents of {}".format(name)) return output
python
def _read_json(self, path, name): with open(os.path.join(path, name), 'r') as fil: output = json.load(fil) self.logger.info("Read contents of {}".format(name)) return output
[ "def", "_read_json", "(", "self", ",", "path", ",", "name", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "path", ",", "name", ")", ",", "'r'", ")", "as", "fil", ":", "output", "=", "json", ".", "load", "(", "fil", ")", ...
Load a json into a dictionary from a file. :param path: path to file :param name: name of file :return: dict
[ "Load", "a", "json", "into", "a", "dictionary", "from", "a", "file", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/file/SessionFiles.py#L205-L216
27,303
ARMmbed/icetea
icetea_lib/tools/file/SessionFiles.py
JsonFile._ends_with
def _ends_with(self, string_to_edit, end): # pylint: disable=no-self-use """ Check if string ends with characters in end, if not merge end to string. :param string_to_edit: string to check and edit. :param end: str :return: string_to_edit or string_to_edit + end """ if not string_to_edit.endswith(end): return string_to_edit + end return string_to_edit
python
def _ends_with(self, string_to_edit, end): # pylint: disable=no-self-use if not string_to_edit.endswith(end): return string_to_edit + end return string_to_edit
[ "def", "_ends_with", "(", "self", ",", "string_to_edit", ",", "end", ")", ":", "# pylint: disable=no-self-use", "if", "not", "string_to_edit", ".", "endswith", "(", "end", ")", ":", "return", "string_to_edit", "+", "end", "return", "string_to_edit" ]
Check if string ends with characters in end, if not merge end to string. :param string_to_edit: string to check and edit. :param end: str :return: string_to_edit or string_to_edit + end
[ "Check", "if", "string", "ends", "with", "characters", "in", "end", "if", "not", "merge", "end", "to", "string", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/file/SessionFiles.py#L218-L228
27,304
ARMmbed/icetea
icetea_lib/CliResponseParser.py
ParserManager.parse
def parse(self, *args, **kwargs): # pylint: disable=unused-argument """ Parse response. :param args: List. 2 first items used as parser name and response to parse :param kwargs: dict, not used :return: dictionary or return value of called callable from parser. """ # pylint: disable=W0703 cmd = args[0] resp = args[1] if cmd in self.parsers: try: return self.parsers[cmd](resp) except Exception as err: print(err) return {}
python
def parse(self, *args, **kwargs): # pylint: disable=unused-argument # pylint: disable=W0703 cmd = args[0] resp = args[1] if cmd in self.parsers: try: return self.parsers[cmd](resp) except Exception as err: print(err) return {}
[ "def", "parse", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "# pylint: disable=W0703", "cmd", "=", "args", "[", "0", "]", "resp", "=", "args", "[", "1", "]", "if", "cmd", "in", "self", ".", "pa...
Parse response. :param args: List. 2 first items used as parser name and response to parse :param kwargs: dict, not used :return: dictionary or return value of called callable from parser.
[ "Parse", "response", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/CliResponseParser.py#L54-L70
27,305
ARMmbed/icetea
icetea_lib/ResultList.py
ResultList.append
def append(self, result): """ Append a new Result to the list. :param result: Result to append :return: Nothing :raises: TypeError if result is not Result or ResultList """ if isinstance(result, Result): self.data.append(result) elif isinstance(result, ResultList): self.data += result.data else: raise TypeError('unknown result type')
python
def append(self, result): if isinstance(result, Result): self.data.append(result) elif isinstance(result, ResultList): self.data += result.data else: raise TypeError('unknown result type')
[ "def", "append", "(", "self", ",", "result", ")", ":", "if", "isinstance", "(", "result", ",", "Result", ")", ":", "self", ".", "data", ".", "append", "(", "result", ")", "elif", "isinstance", "(", "result", ",", "ResultList", ")", ":", "self", ".", ...
Append a new Result to the list. :param result: Result to append :return: Nothing :raises: TypeError if result is not Result or ResultList
[ "Append", "a", "new", "Result", "to", "the", "list", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L46-L59
27,306
ARMmbed/icetea
icetea_lib/ResultList.py
ResultList.save
def save(self, heads, console=True): """ Create reports in different formats. :param heads: html table extra values in title rows :param console: Boolean, default is True. If set, also print out the console log. """ # Junit self._save_junit() # HTML self._save_html_report(heads) if console: # Console print self._print_console_summary()
python
def save(self, heads, console=True): # Junit self._save_junit() # HTML self._save_html_report(heads) if console: # Console print self._print_console_summary()
[ "def", "save", "(", "self", ",", "heads", ",", "console", "=", "True", ")", ":", "# Junit", "self", ".", "_save_junit", "(", ")", "# HTML", "self", ".", "_save_html_report", "(", "heads", ")", "if", "console", ":", "# Console print", "self", ".", "_print...
Create reports in different formats. :param heads: html table extra values in title rows :param console: Boolean, default is True. If set, also print out the console log.
[ "Create", "reports", "in", "different", "formats", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L64-L77
27,307
ARMmbed/icetea
icetea_lib/ResultList.py
ResultList._save_junit
def _save_junit(self): """ Save Junit report. :return: Nothing """ report = ReportJunit(self) file_name = report.get_latest_filename("result.junit.xml", "") report.generate(file_name) file_name = report.get_latest_filename("junit.xml", "../") report.generate(file_name)
python
def _save_junit(self): report = ReportJunit(self) file_name = report.get_latest_filename("result.junit.xml", "") report.generate(file_name) file_name = report.get_latest_filename("junit.xml", "../") report.generate(file_name)
[ "def", "_save_junit", "(", "self", ")", ":", "report", "=", "ReportJunit", "(", "self", ")", "file_name", "=", "report", ".", "get_latest_filename", "(", "\"result.junit.xml\"", ",", "\"\"", ")", "report", ".", "generate", "(", "file_name", ")", "file_name", ...
Save Junit report. :return: Nothing
[ "Save", "Junit", "report", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L79-L90
27,308
ARMmbed/icetea
icetea_lib/ResultList.py
ResultList._save_html_report
def _save_html_report(self, heads=None, refresh=None): """ Save html report. :param heads: headers as dict :param refresh: Boolean, if True will add a reload-tag to the report :return: Nothing """ report = ReportHtml(self) heads = heads if heads else {} test_report_filename = report.get_current_filename("html") report.generate(test_report_filename, title='Test Results', heads=heads, refresh=refresh) # Update latest.html in the log root directory latest_report_filename = report.get_latest_filename("html") report.generate(latest_report_filename, title='Test Results', heads=heads, refresh=refresh)
python
def _save_html_report(self, heads=None, refresh=None): report = ReportHtml(self) heads = heads if heads else {} test_report_filename = report.get_current_filename("html") report.generate(test_report_filename, title='Test Results', heads=heads, refresh=refresh) # Update latest.html in the log root directory latest_report_filename = report.get_latest_filename("html") report.generate(latest_report_filename, title='Test Results', heads=heads, refresh=refresh)
[ "def", "_save_html_report", "(", "self", ",", "heads", "=", "None", ",", "refresh", "=", "None", ")", ":", "report", "=", "ReportHtml", "(", "self", ")", "heads", "=", "heads", "if", "heads", "else", "{", "}", "test_report_filename", "=", "report", ".", ...
Save html report. :param heads: headers as dict :param refresh: Boolean, if True will add a reload-tag to the report :return: Nothing
[ "Save", "html", "report", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L92-L107
27,309
ARMmbed/icetea
icetea_lib/ResultList.py
ResultList.success_count
def success_count(self): """ Amount of passed test cases in this list. :return: integer """ return len([i for i, result in enumerate(self.data) if result.success])
python
def success_count(self): return len([i for i, result in enumerate(self.data) if result.success])
[ "def", "success_count", "(", "self", ")", ":", "return", "len", "(", "[", "i", "for", "i", ",", "result", "in", "enumerate", "(", "self", ".", "data", ")", "if", "result", ".", "success", "]", ")" ]
Amount of passed test cases in this list. :return: integer
[ "Amount", "of", "passed", "test", "cases", "in", "this", "list", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L117-L123
27,310
ARMmbed/icetea
icetea_lib/ResultList.py
ResultList.failure_count
def failure_count(self): """ Amount of failed test cases in this list. :return: integer """ return len([i for i, result in enumerate(self.data) if result.failure])
python
def failure_count(self): return len([i for i, result in enumerate(self.data) if result.failure])
[ "def", "failure_count", "(", "self", ")", ":", "return", "len", "(", "[", "i", "for", "i", ",", "result", "in", "enumerate", "(", "self", ".", "data", ")", "if", "result", ".", "failure", "]", ")" ]
Amount of failed test cases in this list. :return: integer
[ "Amount", "of", "failed", "test", "cases", "in", "this", "list", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L125-L131
27,311
ARMmbed/icetea
icetea_lib/ResultList.py
ResultList.inconclusive_count
def inconclusive_count(self): """ Amount of inconclusive test cases in this list. :return: integer """ inconc_count = len([i for i, result in enumerate(self.data) if result.inconclusive]) unknown_count = len([i for i, result in enumerate(self.data) if result.get_verdict() == "unknown"]) return inconc_count + unknown_count
python
def inconclusive_count(self): inconc_count = len([i for i, result in enumerate(self.data) if result.inconclusive]) unknown_count = len([i for i, result in enumerate(self.data) if result.get_verdict() == "unknown"]) return inconc_count + unknown_count
[ "def", "inconclusive_count", "(", "self", ")", ":", "inconc_count", "=", "len", "(", "[", "i", "for", "i", ",", "result", "in", "enumerate", "(", "self", ".", "data", ")", "if", "result", ".", "inconclusive", "]", ")", "unknown_count", "=", "len", "(",...
Amount of inconclusive test cases in this list. :return: integer
[ "Amount", "of", "inconclusive", "test", "cases", "in", "this", "list", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L133-L142
27,312
ARMmbed/icetea
icetea_lib/ResultList.py
ResultList.retry_count
def retry_count(self): """ Amount of retried test cases in this list. :return: integer """ retries = len([i for i, result in enumerate(self.data) if result.retries_left > 0]) return retries
python
def retry_count(self): retries = len([i for i, result in enumerate(self.data) if result.retries_left > 0]) return retries
[ "def", "retry_count", "(", "self", ")", ":", "retries", "=", "len", "(", "[", "i", "for", "i", ",", "result", "in", "enumerate", "(", "self", ".", "data", ")", "if", "result", ".", "retries_left", ">", "0", "]", ")", "return", "retries" ]
Amount of retried test cases in this list. :return: integer
[ "Amount", "of", "retried", "test", "cases", "in", "this", "list", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L144-L151
27,313
ARMmbed/icetea
icetea_lib/ResultList.py
ResultList.skip_count
def skip_count(self): """ Amount of skipped test cases in this list. :return: integer """ return len([i for i, result in enumerate(self.data) if result.skip])
python
def skip_count(self): return len([i for i, result in enumerate(self.data) if result.skip])
[ "def", "skip_count", "(", "self", ")", ":", "return", "len", "(", "[", "i", "for", "i", ",", "result", "in", "enumerate", "(", "self", ".", "data", ")", "if", "result", ".", "skip", "]", ")" ]
Amount of skipped test cases in this list. :return: integer
[ "Amount", "of", "skipped", "test", "cases", "in", "this", "list", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L153-L159
27,314
ARMmbed/icetea
icetea_lib/ResultList.py
ResultList.clean_fails
def clean_fails(self): """ Check if there are any fails that were not subsequently retried. :return: Boolean """ for item in self.data: if item.failure and not item.retries_left > 0: return True return False
python
def clean_fails(self): for item in self.data: if item.failure and not item.retries_left > 0: return True return False
[ "def", "clean_fails", "(", "self", ")", ":", "for", "item", "in", "self", ".", "data", ":", "if", "item", ".", "failure", "and", "not", "item", ".", "retries_left", ">", "0", ":", "return", "True", "return", "False" ]
Check if there are any fails that were not subsequently retried. :return: Boolean
[ "Check", "if", "there", "are", "any", "fails", "that", "were", "not", "subsequently", "retried", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L161-L170
27,315
ARMmbed/icetea
icetea_lib/ResultList.py
ResultList.clean_inconcs
def clean_inconcs(self): """ Check if there are any inconclusives or uknowns that were not subsequently retried. :return: Boolean """ for item in self.data: if (item.inconclusive or item.get_verdict() == "unknown") and not item.retries_left > 0: return True return False
python
def clean_inconcs(self): for item in self.data: if (item.inconclusive or item.get_verdict() == "unknown") and not item.retries_left > 0: return True return False
[ "def", "clean_inconcs", "(", "self", ")", ":", "for", "item", "in", "self", ".", "data", ":", "if", "(", "item", ".", "inconclusive", "or", "item", ".", "get_verdict", "(", ")", "==", "\"unknown\"", ")", "and", "not", "item", ".", "retries_left", ">", ...
Check if there are any inconclusives or uknowns that were not subsequently retried. :return: Boolean
[ "Check", "if", "there", "are", "any", "inconclusives", "or", "uknowns", "that", "were", "not", "subsequently", "retried", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L172-L181
27,316
ARMmbed/icetea
icetea_lib/ResultList.py
ResultList.total_duration
def total_duration(self): """ Sum of the durations of the tests in this list. :return: integer """ durations = [result.duration for result in self.data] return sum(durations)
python
def total_duration(self): durations = [result.duration for result in self.data] return sum(durations)
[ "def", "total_duration", "(", "self", ")", ":", "durations", "=", "[", "result", ".", "duration", "for", "result", "in", "self", ".", "data", "]", "return", "sum", "(", "durations", ")" ]
Sum of the durations of the tests in this list. :return: integer
[ "Sum", "of", "the", "durations", "of", "the", "tests", "in", "this", "list", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L236-L243
27,317
ARMmbed/icetea
icetea_lib/ResultList.py
ResultList.pass_rate
def pass_rate(self, include_skips=False, include_inconclusive=False, include_retries=True): """ Calculate pass rate for tests in this list. :param include_skips: Boolean, if True skipped tc:s will be included. Default is False :param include_inconclusive: Boolean, if True inconclusive tc:s will be included. Default is False. :param include_retries: Boolean, if True retried tc:s will be included in percentages. :return: Percentage in format .2f % """ total = self.count() success = self.success_count() retries = self.retry_count() try: if include_inconclusive and include_skips and include_retries: val = 100.0*success/total elif include_inconclusive and include_skips and not include_retries: val = 100.0 * success / (total - retries) elif include_skips and include_retries and not include_inconclusive: inconcs = self.inconclusive_count() val = 100.0 * success / (total - inconcs) elif include_skips and not include_retries and not include_inconclusive: inconcs = self.inconclusive_count() val = 100.0 * success / (total - inconcs - retries) elif include_inconclusive and include_retries and not include_skips: skipped = self.skip_count() val = 100.0 * success / (total - skipped) elif include_inconclusive and not include_retries and not include_skips: skipped = self.skip_count() val = 100.0 * success / (total - skipped - retries) elif not include_inconclusive and not include_skips and include_retries: failures = self.failure_count() val = 100.0 * success / (failures + success) else: failures = self.clean_fails() val = 100.0 * success / (failures + success) except ZeroDivisionError: val = 0 return format(val, '.2f') + " %"
python
def pass_rate(self, include_skips=False, include_inconclusive=False, include_retries=True): total = self.count() success = self.success_count() retries = self.retry_count() try: if include_inconclusive and include_skips and include_retries: val = 100.0*success/total elif include_inconclusive and include_skips and not include_retries: val = 100.0 * success / (total - retries) elif include_skips and include_retries and not include_inconclusive: inconcs = self.inconclusive_count() val = 100.0 * success / (total - inconcs) elif include_skips and not include_retries and not include_inconclusive: inconcs = self.inconclusive_count() val = 100.0 * success / (total - inconcs - retries) elif include_inconclusive and include_retries and not include_skips: skipped = self.skip_count() val = 100.0 * success / (total - skipped) elif include_inconclusive and not include_retries and not include_skips: skipped = self.skip_count() val = 100.0 * success / (total - skipped - retries) elif not include_inconclusive and not include_skips and include_retries: failures = self.failure_count() val = 100.0 * success / (failures + success) else: failures = self.clean_fails() val = 100.0 * success / (failures + success) except ZeroDivisionError: val = 0 return format(val, '.2f') + " %"
[ "def", "pass_rate", "(", "self", ",", "include_skips", "=", "False", ",", "include_inconclusive", "=", "False", ",", "include_retries", "=", "True", ")", ":", "total", "=", "self", ".", "count", "(", ")", "success", "=", "self", ".", "success_count", "(", ...
Calculate pass rate for tests in this list. :param include_skips: Boolean, if True skipped tc:s will be included. Default is False :param include_inconclusive: Boolean, if True inconclusive tc:s will be included. Default is False. :param include_retries: Boolean, if True retried tc:s will be included in percentages. :return: Percentage in format .2f %
[ "Calculate", "pass", "rate", "for", "tests", "in", "this", "list", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L245-L283
27,318
ARMmbed/icetea
icetea_lib/ResultList.py
ResultList.get_summary
def get_summary(self): """ Get a summary of this ResultLists contents as dictionary. :return: dictionary """ return { "count": self.count(), "pass": self.success_count(), "fail": self.failure_count(), "skip": self.skip_count(), "inconclusive": self.inconclusive_count(), "retries": self.retry_count(), "duration": self.total_duration() }
python
def get_summary(self): return { "count": self.count(), "pass": self.success_count(), "fail": self.failure_count(), "skip": self.skip_count(), "inconclusive": self.inconclusive_count(), "retries": self.retry_count(), "duration": self.total_duration() }
[ "def", "get_summary", "(", "self", ")", ":", "return", "{", "\"count\"", ":", "self", ".", "count", "(", ")", ",", "\"pass\"", ":", "self", ".", "success_count", "(", ")", ",", "\"fail\"", ":", "self", ".", "failure_count", "(", ")", ",", "\"skip\"", ...
Get a summary of this ResultLists contents as dictionary. :return: dictionary
[ "Get", "a", "summary", "of", "this", "ResultLists", "contents", "as", "dictionary", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L285-L299
27,319
ARMmbed/icetea
icetea_lib/ResultList.py
ResultList.next
def next(self): """ Implementation of next method from Iterator. :return: Result :raises: StopIteration if IndexError occurs. """ try: result = self.data[self.index] except IndexError: self.index = 0 raise StopIteration self.index += 1 return result
python
def next(self): try: result = self.data[self.index] except IndexError: self.index = 0 raise StopIteration self.index += 1 return result
[ "def", "next", "(", "self", ")", ":", "try", ":", "result", "=", "self", ".", "data", "[", "self", ".", "index", "]", "except", "IndexError", ":", "self", ".", "index", "=", "0", "raise", "StopIteration", "self", ".", "index", "+=", "1", "return", ...
Implementation of next method from Iterator. :return: Result :raises: StopIteration if IndexError occurs.
[ "Implementation", "of", "next", "method", "from", "Iterator", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResultList.py#L325-L338
27,320
ARMmbed/icetea
icetea_lib/tools/deprecated.py
deprecated
def deprecated(message=""): """ This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used first time and filter is set for show DeprecationWarning. """ def decorator_wrapper(func): """ Generate decorator wrapper function :param func: function to be decorated :return: wrapper """ @functools.wraps(func) def function_wrapper(*args, **kwargs): """ Wrapper which recognize deprecated line from source code :param args: args for actual function :param kwargs: kwargs for actual functions :return: something that actual function might returns """ current_call_source = '|'.join(traceback.format_stack(inspect.currentframe())) if current_call_source not in function_wrapper.last_call_source: warnings.warn("Function {} is now deprecated! {}".format(func.__name__, message), category=DeprecationWarning, stacklevel=2) function_wrapper.last_call_source.add(current_call_source) return func(*args, **kwargs) function_wrapper.last_call_source = set() return function_wrapper return decorator_wrapper
python
def deprecated(message=""): def decorator_wrapper(func): """ Generate decorator wrapper function :param func: function to be decorated :return: wrapper """ @functools.wraps(func) def function_wrapper(*args, **kwargs): """ Wrapper which recognize deprecated line from source code :param args: args for actual function :param kwargs: kwargs for actual functions :return: something that actual function might returns """ current_call_source = '|'.join(traceback.format_stack(inspect.currentframe())) if current_call_source not in function_wrapper.last_call_source: warnings.warn("Function {} is now deprecated! {}".format(func.__name__, message), category=DeprecationWarning, stacklevel=2) function_wrapper.last_call_source.add(current_call_source) return func(*args, **kwargs) function_wrapper.last_call_source = set() return function_wrapper return decorator_wrapper
[ "def", "deprecated", "(", "message", "=", "\"\"", ")", ":", "def", "decorator_wrapper", "(", "func", ")", ":", "\"\"\"\n Generate decorator wrapper function\n :param func: function to be decorated\n :return: wrapper\n \"\"\"", "@", "functools", ".", "w...
This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used first time and filter is set for show DeprecationWarning.
[ "This", "is", "a", "decorator", "which", "can", "be", "used", "to", "mark", "functions", "as", "deprecated", ".", "It", "will", "result", "in", "a", "warning", "being", "emitted", "when", "the", "function", "is", "used", "first", "time", "and", "filter", ...
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/deprecated.py#L24-L55
27,321
ARMmbed/icetea
icetea_lib/tools/file/FileUtils.py
remove_file
def remove_file(filename, path=None): """ Remove file filename from path. :param filename: Name of file to remove :param path: Path where file is located :return: True if successfull :raises OSError if chdir or remove fails. """ cwd = os.getcwd() try: if path: os.chdir(path) except OSError: raise try: os.remove(filename) os.chdir(cwd) return True except OSError: os.chdir(cwd) raise
python
def remove_file(filename, path=None): cwd = os.getcwd() try: if path: os.chdir(path) except OSError: raise try: os.remove(filename) os.chdir(cwd) return True except OSError: os.chdir(cwd) raise
[ "def", "remove_file", "(", "filename", ",", "path", "=", "None", ")", ":", "cwd", "=", "os", ".", "getcwd", "(", ")", "try", ":", "if", "path", ":", "os", ".", "chdir", "(", "path", ")", "except", "OSError", ":", "raise", "try", ":", "os", ".", ...
Remove file filename from path. :param filename: Name of file to remove :param path: Path where file is located :return: True if successfull :raises OSError if chdir or remove fails.
[ "Remove", "file", "filename", "from", "path", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/file/FileUtils.py#L55-L76
27,322
ARMmbed/icetea
icetea_lib/CliResponse.py
CliResponse.verify_message
def verify_message(self, expected_response, break_in_fail=True): """ Verifies that expected_response is found in self.lines. :param expected_response: response or responses to look for. Must be list or str. :param break_in_fail: If set to True, re-raises exceptions caught or if message was not found :return: True or False :raises: LookupError if message was not found and break_in_fail was True. Other exceptions might also be raised through searcher.verify_message. """ ok = True try: ok = verify_message(self.lines, expected_response) except (TypeError, LookupError) as inst: ok = False if break_in_fail: raise inst if ok is False and break_in_fail: raise LookupError("Unexpected message found") return ok
python
def verify_message(self, expected_response, break_in_fail=True): ok = True try: ok = verify_message(self.lines, expected_response) except (TypeError, LookupError) as inst: ok = False if break_in_fail: raise inst if ok is False and break_in_fail: raise LookupError("Unexpected message found") return ok
[ "def", "verify_message", "(", "self", ",", "expected_response", ",", "break_in_fail", "=", "True", ")", ":", "ok", "=", "True", "try", ":", "ok", "=", "verify_message", "(", "self", ".", "lines", ",", "expected_response", ")", "except", "(", "TypeError", "...
Verifies that expected_response is found in self.lines. :param expected_response: response or responses to look for. Must be list or str. :param break_in_fail: If set to True, re-raises exceptions caught or if message was not found :return: True or False :raises: LookupError if message was not found and break_in_fail was True. Other exceptions might also be raised through searcher.verify_message.
[ "Verifies", "that", "expected_response", "is", "found", "in", "self", ".", "lines", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/CliResponse.py#L68-L88
27,323
ARMmbed/icetea
icetea_lib/CliResponse.py
CliResponse.verify_trace
def verify_trace(self, expected_traces, break_in_fail=True): """ Verifies that expectedResponse is found in self.traces :param expected_traces: response or responses to look for. Must be list or str. :param break_in_fail: If set to True, re-raises exceptions caught or if message was not found :return: True or False :raises: LookupError if message was not found and breakInFail was True. Other Exceptions might also be raised through searcher.verify_message. """ ok = True try: ok = verify_message(self.traces, expected_traces) except (TypeError, LookupError) as inst: ok = False if break_in_fail: raise inst if ok is False and break_in_fail: raise LookupError("Unexpected message found") return ok
python
def verify_trace(self, expected_traces, break_in_fail=True): ok = True try: ok = verify_message(self.traces, expected_traces) except (TypeError, LookupError) as inst: ok = False if break_in_fail: raise inst if ok is False and break_in_fail: raise LookupError("Unexpected message found") return ok
[ "def", "verify_trace", "(", "self", ",", "expected_traces", ",", "break_in_fail", "=", "True", ")", ":", "ok", "=", "True", "try", ":", "ok", "=", "verify_message", "(", "self", ".", "traces", ",", "expected_traces", ")", "except", "(", "TypeError", ",", ...
Verifies that expectedResponse is found in self.traces :param expected_traces: response or responses to look for. Must be list or str. :param break_in_fail: If set to True, re-raises exceptions caught or if message was not found :return: True or False :raises: LookupError if message was not found and breakInFail was True. Other Exceptions might also be raised through searcher.verify_message.
[ "Verifies", "that", "expectedResponse", "is", "found", "in", "self", ".", "traces" ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/CliResponse.py#L90-L110
27,324
ARMmbed/icetea
icetea_lib/CliResponse.py
CliResponse.verify_response_duration
def verify_response_duration(self, expected=None, zero=0, threshold_percent=0, break_in_fail=True): """ Verify that response duration is in bounds. :param expected: seconds what is expected duration :param zero: seconds if one to normalize duration before calculating error rate :param threshold_percent: allowed error in percents :param break_in_fail: boolean, True if raise TestStepFail when out of bounds :return: (duration, expected duration, error) """ was = self.timedelta - zero error = abs(was/expected)*100.0 - 100.0 if expected > 0 else 0 msg = "should: %.3f, was: %.3f, error: %.3f %%" % (expected, was, error) self.logger.debug(msg) if abs(error) > threshold_percent: msg = "Thread::wait error(%.2f %%) was out of bounds (%.2f %%)" \ % (error, threshold_percent) self.logger.debug(msg) if break_in_fail: raise TestStepFail(msg) return was, expected, error
python
def verify_response_duration(self, expected=None, zero=0, threshold_percent=0, break_in_fail=True): was = self.timedelta - zero error = abs(was/expected)*100.0 - 100.0 if expected > 0 else 0 msg = "should: %.3f, was: %.3f, error: %.3f %%" % (expected, was, error) self.logger.debug(msg) if abs(error) > threshold_percent: msg = "Thread::wait error(%.2f %%) was out of bounds (%.2f %%)" \ % (error, threshold_percent) self.logger.debug(msg) if break_in_fail: raise TestStepFail(msg) return was, expected, error
[ "def", "verify_response_duration", "(", "self", ",", "expected", "=", "None", ",", "zero", "=", "0", ",", "threshold_percent", "=", "0", ",", "break_in_fail", "=", "True", ")", ":", "was", "=", "self", ".", "timedelta", "-", "zero", "error", "=", "abs", ...
Verify that response duration is in bounds. :param expected: seconds what is expected duration :param zero: seconds if one to normalize duration before calculating error rate :param threshold_percent: allowed error in percents :param break_in_fail: boolean, True if raise TestStepFail when out of bounds :return: (duration, expected duration, error)
[ "Verify", "that", "response", "duration", "is", "in", "bounds", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/CliResponse.py#L121-L142
27,325
ARMmbed/icetea
icetea_lib/ResourceProvider/ResourceConfig.py
ResourceConfig._hardware_count
def _hardware_count(self): """ Amount of hardware resources. :return: integer """ return self._counts.get("hardware") + self._counts.get("serial") + self._counts.get("mbed")
python
def _hardware_count(self): return self._counts.get("hardware") + self._counts.get("serial") + self._counts.get("mbed")
[ "def", "_hardware_count", "(", "self", ")", ":", "return", "self", ".", "_counts", ".", "get", "(", "\"hardware\"", ")", "+", "self", ".", "_counts", ".", "get", "(", "\"serial\"", ")", "+", "self", ".", "_counts", ".", "get", "(", "\"mbed\"", ")" ]
Amount of hardware resources. :return: integer
[ "Amount", "of", "hardware", "resources", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L41-L47
27,326
ARMmbed/icetea
icetea_lib/ResourceProvider/ResourceConfig.py
ResourceConfig._resolve_requirements
def _resolve_requirements(self, requirements): """ Internal method for resolving requirements into resource configurations. :param requirements: Resource requirements from test case configuration as dictionary. :return: Empty list if dut_count cannot be resolved, or nothing """ try: dut_count = requirements["duts"]["*"]["count"] except KeyError: return [] default_values = { "type": "hardware", "allowed_platforms": [], "nick": None, } default_values.update(requirements["duts"]["*"]) del default_values["count"] dut_keys = list(default_values.keys()) dut_keys.extend(["application", "location", "subtype"]) dut_requirements = self.__generate_indexed_requirements(dut_count, default_values, requirements) # Match groups of duts defined with 1..40 notation. for key in requirements["duts"].keys(): if not isinstance(key, string_types): continue match = re.search(r'([\d]{1,})\.\.([\d]{1,})', key) if match: first_dut_idx = int(match.group(1)) last_dut_idx = int(match.group(2)) for i in range(first_dut_idx, last_dut_idx+1): for k in dut_keys: if k in requirements["duts"][key]: dut_requirements[i-1].set(k, copy.copy(requirements["duts"][key][k])) for idx, req in enumerate(dut_requirements): if isinstance(req.get("nick"), string_types): nick = req.get("nick") req.set("nick", ResourceConfig.__replace_base_variables(nick, len(dut_requirements), idx)) self._solve_location(req, len(dut_requirements), idx) self._dut_requirements = dut_requirements return None
python
def _resolve_requirements(self, requirements): try: dut_count = requirements["duts"]["*"]["count"] except KeyError: return [] default_values = { "type": "hardware", "allowed_platforms": [], "nick": None, } default_values.update(requirements["duts"]["*"]) del default_values["count"] dut_keys = list(default_values.keys()) dut_keys.extend(["application", "location", "subtype"]) dut_requirements = self.__generate_indexed_requirements(dut_count, default_values, requirements) # Match groups of duts defined with 1..40 notation. for key in requirements["duts"].keys(): if not isinstance(key, string_types): continue match = re.search(r'([\d]{1,})\.\.([\d]{1,})', key) if match: first_dut_idx = int(match.group(1)) last_dut_idx = int(match.group(2)) for i in range(first_dut_idx, last_dut_idx+1): for k in dut_keys: if k in requirements["duts"][key]: dut_requirements[i-1].set(k, copy.copy(requirements["duts"][key][k])) for idx, req in enumerate(dut_requirements): if isinstance(req.get("nick"), string_types): nick = req.get("nick") req.set("nick", ResourceConfig.__replace_base_variables(nick, len(dut_requirements), idx)) self._solve_location(req, len(dut_requirements), idx) self._dut_requirements = dut_requirements return None
[ "def", "_resolve_requirements", "(", "self", ",", "requirements", ")", ":", "try", ":", "dut_count", "=", "requirements", "[", "\"duts\"", "]", "[", "\"*\"", "]", "[", "\"count\"", "]", "except", "KeyError", ":", "return", "[", "]", "default_values", "=", ...
Internal method for resolving requirements into resource configurations. :param requirements: Resource requirements from test case configuration as dictionary. :return: Empty list if dut_count cannot be resolved, or nothing
[ "Internal", "method", "for", "resolving", "requirements", "into", "resource", "configurations", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L109-L158
27,327
ARMmbed/icetea
icetea_lib/ResourceProvider/ResourceConfig.py
ResourceConfig._solve_location
def _solve_location(self, req, dut_req_len, idx): """ Helper function for resolving the location for a resource. :param req: Requirements dictionary :param dut_req_len: Amount of required resources :param idx: index, integer :return: Nothing, modifies req object """ if not req.get("location"): return if len(req.get("location")) == 2: for x_and_y, coord in enumerate(req.get("location")): if isinstance(coord, string_types): coord = ResourceConfig.__replace_coord_variables(coord, x_and_y, dut_req_len, idx) try: loc = req.get("location") loc[x_and_y] = eval(coord) # pylint: disable=eval-used req.set("location", loc) except SyntaxError as error: self.logger.error(error) loc = req.get("location") loc[x_and_y] = 0.0 req.set("location", loc) else: self.logger.error("invalid location field!") req.set("location", [0.0, 0.0])
python
def _solve_location(self, req, dut_req_len, idx): if not req.get("location"): return if len(req.get("location")) == 2: for x_and_y, coord in enumerate(req.get("location")): if isinstance(coord, string_types): coord = ResourceConfig.__replace_coord_variables(coord, x_and_y, dut_req_len, idx) try: loc = req.get("location") loc[x_and_y] = eval(coord) # pylint: disable=eval-used req.set("location", loc) except SyntaxError as error: self.logger.error(error) loc = req.get("location") loc[x_and_y] = 0.0 req.set("location", loc) else: self.logger.error("invalid location field!") req.set("location", [0.0, 0.0])
[ "def", "_solve_location", "(", "self", ",", "req", ",", "dut_req_len", ",", "idx", ")", ":", "if", "not", "req", ".", "get", "(", "\"location\"", ")", ":", "return", "if", "len", "(", "req", ".", "get", "(", "\"location\"", ")", ")", "==", "2", ":"...
Helper function for resolving the location for a resource. :param req: Requirements dictionary :param dut_req_len: Amount of required resources :param idx: index, integer :return: Nothing, modifies req object
[ "Helper", "function", "for", "resolving", "the", "location", "for", "a", "resource", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L160-L190
27,328
ARMmbed/icetea
icetea_lib/ResourceProvider/ResourceConfig.py
ResourceConfig.__replace_base_variables
def __replace_base_variables(text, req_len, idx): """ Replace i and n in text with index+1 and req_len. :param text: base text to modify :param req_len: amount of required resources :param idx: index of resource we are working on :return: modified string """ return text \ .replace("{i}", str(idx + 1)) \ .replace("{n}", str(req_len))
python
def __replace_base_variables(text, req_len, idx): return text \ .replace("{i}", str(idx + 1)) \ .replace("{n}", str(req_len))
[ "def", "__replace_base_variables", "(", "text", ",", "req_len", ",", "idx", ")", ":", "return", "text", ".", "replace", "(", "\"{i}\"", ",", "str", "(", "idx", "+", "1", ")", ")", ".", "replace", "(", "\"{n}\"", ",", "str", "(", "req_len", ")", ")" ]
Replace i and n in text with index+1 and req_len. :param text: base text to modify :param req_len: amount of required resources :param idx: index of resource we are working on :return: modified string
[ "Replace", "i", "and", "n", "in", "text", "with", "index", "+", "1", "and", "req_len", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L193-L204
27,329
ARMmbed/icetea
icetea_lib/ResourceProvider/ResourceConfig.py
ResourceConfig.__replace_coord_variables
def __replace_coord_variables(text, x_and_y, req_len, idx): """ Replace x and y with their coordinates and replace pi with value of pi. :param text: text: base text to modify :param x_and_y: location x and y :param req_len: amount of required resources :param idx: index of resource we are working on :return: str """ return ResourceConfig.__replace_base_variables(text, req_len, idx) \ .replace("{xy}", str(x_and_y)) \ .replace("{pi}", str(math.pi))
python
def __replace_coord_variables(text, x_and_y, req_len, idx): return ResourceConfig.__replace_base_variables(text, req_len, idx) \ .replace("{xy}", str(x_and_y)) \ .replace("{pi}", str(math.pi))
[ "def", "__replace_coord_variables", "(", "text", ",", "x_and_y", ",", "req_len", ",", "idx", ")", ":", "return", "ResourceConfig", ".", "__replace_base_variables", "(", "text", ",", "req_len", ",", "idx", ")", ".", "replace", "(", "\"{xy}\"", ",", "str", "("...
Replace x and y with their coordinates and replace pi with value of pi. :param text: text: base text to modify :param x_and_y: location x and y :param req_len: amount of required resources :param idx: index of resource we are working on :return: str
[ "Replace", "x", "and", "y", "with", "their", "coordinates", "and", "replace", "pi", "with", "value", "of", "pi", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L207-L219
27,330
ARMmbed/icetea
icetea_lib/ResourceProvider/ResourceConfig.py
ResourceConfig.__generate_indexed_requirements
def __generate_indexed_requirements(dut_count, basekeys, requirements): """ Generate indexed requirements from general requirements. :param dut_count: Amount of duts :param basekeys: base keys as dict :param requirements: requirements :return: Indexed requirements as dict. """ dut_requirements = [] for i in range(1, dut_count + 1): dut_requirement = ResourceRequirements(basekeys.copy()) if i in requirements["duts"]: for k in requirements["duts"][i]: dut_requirement.set(k, requirements["duts"][i][k]) elif str(i) in requirements["duts"]: i = str(i) for k in requirements["duts"][i]: dut_requirement.set(k, requirements["duts"][i][k]) dut_requirements.append(dut_requirement) return dut_requirements
python
def __generate_indexed_requirements(dut_count, basekeys, requirements): dut_requirements = [] for i in range(1, dut_count + 1): dut_requirement = ResourceRequirements(basekeys.copy()) if i in requirements["duts"]: for k in requirements["duts"][i]: dut_requirement.set(k, requirements["duts"][i][k]) elif str(i) in requirements["duts"]: i = str(i) for k in requirements["duts"][i]: dut_requirement.set(k, requirements["duts"][i][k]) dut_requirements.append(dut_requirement) return dut_requirements
[ "def", "__generate_indexed_requirements", "(", "dut_count", ",", "basekeys", ",", "requirements", ")", ":", "dut_requirements", "=", "[", "]", "for", "i", "in", "range", "(", "1", ",", "dut_count", "+", "1", ")", ":", "dut_requirement", "=", "ResourceRequireme...
Generate indexed requirements from general requirements. :param dut_count: Amount of duts :param basekeys: base keys as dict :param requirements: requirements :return: Indexed requirements as dict.
[ "Generate", "indexed", "requirements", "from", "general", "requirements", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L222-L242
27,331
ARMmbed/icetea
icetea_lib/ResourceProvider/ResourceConfig.py
ResourceConfig._resolve_hardware_count
def _resolve_hardware_count(self): """ Calculate amount of hardware resources. :return: Nothing, adds results to self._hardware_count """ length = len([d for d in self._dut_requirements if d.get("type") in ["hardware", "serial", "mbed"]]) self._hardware_count = length
python
def _resolve_hardware_count(self): length = len([d for d in self._dut_requirements if d.get("type") in ["hardware", "serial", "mbed"]]) self._hardware_count = length
[ "def", "_resolve_hardware_count", "(", "self", ")", ":", "length", "=", "len", "(", "[", "d", "for", "d", "in", "self", ".", "_dut_requirements", "if", "d", ".", "get", "(", "\"type\"", ")", "in", "[", "\"hardware\"", ",", "\"serial\"", ",", "\"mbed\"", ...
Calculate amount of hardware resources. :return: Nothing, adds results to self._hardware_count
[ "Calculate", "amount", "of", "hardware", "resources", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L258-L266
27,332
ARMmbed/icetea
icetea_lib/ResourceProvider/ResourceConfig.py
ResourceConfig._resolve_process_count
def _resolve_process_count(self): """ Calculate amount of process resources. :return: Nothing, adds results to self._process_count """ length = len([d for d in self._dut_requirements if d.get("type") == "process"]) self._process_count = length
python
def _resolve_process_count(self): length = len([d for d in self._dut_requirements if d.get("type") == "process"]) self._process_count = length
[ "def", "_resolve_process_count", "(", "self", ")", ":", "length", "=", "len", "(", "[", "d", "for", "d", "in", "self", ".", "_dut_requirements", "if", "d", ".", "get", "(", "\"type\"", ")", "==", "\"process\"", "]", ")", "self", ".", "_process_count", ...
Calculate amount of process resources. :return: Nothing, adds results to self._process_count
[ "Calculate", "amount", "of", "process", "resources", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L274-L281
27,333
ARMmbed/icetea
icetea_lib/ResourceProvider/ResourceConfig.py
ResourceConfig._resolve_dut_count
def _resolve_dut_count(self): """ Calculates total amount of resources required and their types. :return: Nothing, modifies _dut_count, _hardware_count and _process_count :raises: ValueError if total count does not match counts of types separately. """ self._dut_count = len(self._dut_requirements) self._resolve_process_count() self._resolve_hardware_count() if self._dut_count != self._hardware_count + self._process_count: raise ValueError("Missing or invalid type fields in dut configuration!")
python
def _resolve_dut_count(self): self._dut_count = len(self._dut_requirements) self._resolve_process_count() self._resolve_hardware_count() if self._dut_count != self._hardware_count + self._process_count: raise ValueError("Missing or invalid type fields in dut configuration!")
[ "def", "_resolve_dut_count", "(", "self", ")", ":", "self", ".", "_dut_count", "=", "len", "(", "self", ".", "_dut_requirements", ")", "self", ".", "_resolve_process_count", "(", ")", "self", ".", "_resolve_hardware_count", "(", ")", "if", "self", ".", "_dut...
Calculates total amount of resources required and their types. :return: Nothing, modifies _dut_count, _hardware_count and _process_count :raises: ValueError if total count does not match counts of types separately.
[ "Calculates", "total", "amount", "of", "resources", "required", "and", "their", "types", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L289-L301
27,334
ARMmbed/icetea
icetea_lib/ResourceProvider/ResourceConfig.py
ResourceConfig.set_dut_configuration
def set_dut_configuration(self, ident, config): """ Set requirements for dut ident. :param ident: Identity of dut. :param config: If ResourceRequirements object, add object as requirements for resource ident. If dictionary, create new ResourceRequirements object from dictionary. :return: Nothing """ if hasattr(config, "get_requirements"): self._dut_requirements[ident] = config elif isinstance(config, dict): self._dut_requirements[ident] = ResourceRequirements(config)
python
def set_dut_configuration(self, ident, config): if hasattr(config, "get_requirements"): self._dut_requirements[ident] = config elif isinstance(config, dict): self._dut_requirements[ident] = ResourceRequirements(config)
[ "def", "set_dut_configuration", "(", "self", ",", "ident", ",", "config", ")", ":", "if", "hasattr", "(", "config", ",", "\"get_requirements\"", ")", ":", "self", ".", "_dut_requirements", "[", "ident", "]", "=", "config", "elif", "isinstance", "(", "config"...
Set requirements for dut ident. :param ident: Identity of dut. :param config: If ResourceRequirements object, add object as requirements for resource ident. If dictionary, create new ResourceRequirements object from dictionary. :return: Nothing
[ "Set", "requirements", "for", "dut", "ident", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L313-L325
27,335
ARMmbed/icetea
icetea_lib/Plugin/plugins/LocalAllocator/DutMbed.py
DutMbed.flash
def flash(self, binary_location=None, forceflash=None): """ Flash a binary to the target device using mbed-flasher. :param binary_location: Binary to flash to device. :param forceflash: Not used. :return: False if an unknown error was encountered during flashing. True if flasher retcode == 0 :raises: ImportError if mbed-flasher not installed. :raises: DutConnectionError if flashing fails. """ if not Flash: self.logger.error("Mbed-flasher not installed!") raise ImportError("Mbed-flasher not installed!") try: # create build object self.build = Build.init(binary_location) except NotImplementedError as error: self.logger.error("Build initialization failed. " "Check your build location.") self.logger.debug(error) raise DutConnectionError(error) # check if need to flash - depend on forceflash -option if not self._flash_needed(forceflash=forceflash): self.logger.info("Skipping flash, not needed.") return True # initialize mbed-flasher with proper logger logger = get_external_logger("mbed-flasher", "FLS") flasher = Flash(logger=logger) if not self.device: self.logger.error("Trying to flash device but device is not there?") return False try: buildfile = self.build.get_file() if not buildfile: raise DutConnectionError("Binary {} not found".format(buildfile)) self.logger.info('Flashing dev: %s', self.device['target_id']) target_id = self.device.get("target_id") retcode = flasher.flash(build=buildfile, target_id=target_id, device_mapping_table=[self.device]) except FLASHER_ERRORS as error: if error.__class__ == NotImplementedError: self.logger.error("Flashing not supported for this platform!") elif error.__class__ == SyntaxError: self.logger.error("target_id required by mbed-flasher!") if FlashError is not None: if error.__class__ == FlashError: self.logger.error("Flasher raised the following error: %s Error code: %i", error.message, error.return_code) raise DutConnectionError(error) if retcode == 0: self.dutinformation.build_binary_sha1 = self.build.sha1 return True self.dutinformation.build_binary_sha1 = None return False
python
def flash(self, binary_location=None, forceflash=None): if not Flash: self.logger.error("Mbed-flasher not installed!") raise ImportError("Mbed-flasher not installed!") try: # create build object self.build = Build.init(binary_location) except NotImplementedError as error: self.logger.error("Build initialization failed. " "Check your build location.") self.logger.debug(error) raise DutConnectionError(error) # check if need to flash - depend on forceflash -option if not self._flash_needed(forceflash=forceflash): self.logger.info("Skipping flash, not needed.") return True # initialize mbed-flasher with proper logger logger = get_external_logger("mbed-flasher", "FLS") flasher = Flash(logger=logger) if not self.device: self.logger.error("Trying to flash device but device is not there?") return False try: buildfile = self.build.get_file() if not buildfile: raise DutConnectionError("Binary {} not found".format(buildfile)) self.logger.info('Flashing dev: %s', self.device['target_id']) target_id = self.device.get("target_id") retcode = flasher.flash(build=buildfile, target_id=target_id, device_mapping_table=[self.device]) except FLASHER_ERRORS as error: if error.__class__ == NotImplementedError: self.logger.error("Flashing not supported for this platform!") elif error.__class__ == SyntaxError: self.logger.error("target_id required by mbed-flasher!") if FlashError is not None: if error.__class__ == FlashError: self.logger.error("Flasher raised the following error: %s Error code: %i", error.message, error.return_code) raise DutConnectionError(error) if retcode == 0: self.dutinformation.build_binary_sha1 = self.build.sha1 return True self.dutinformation.build_binary_sha1 = None return False
[ "def", "flash", "(", "self", ",", "binary_location", "=", "None", ",", "forceflash", "=", "None", ")", ":", "if", "not", "Flash", ":", "self", ".", "logger", ".", "error", "(", "\"Mbed-flasher not installed!\"", ")", "raise", "ImportError", "(", "\"Mbed-flas...
Flash a binary to the target device using mbed-flasher. :param binary_location: Binary to flash to device. :param forceflash: Not used. :return: False if an unknown error was encountered during flashing. True if flasher retcode == 0 :raises: ImportError if mbed-flasher not installed. :raises: DutConnectionError if flashing fails.
[ "Flash", "a", "binary", "to", "the", "target", "device", "using", "mbed", "-", "flasher", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutMbed.py#L59-L117
27,336
ARMmbed/icetea
icetea_lib/Plugin/plugins/LocalAllocator/DutMbed.py
DutMbed._flash_needed
def _flash_needed(self, **kwargs): """ Check if flashing is needed. Flashing can be skipped if resource binary_sha1 attribute matches build sha1 and forceflash is not True. :param kwargs: Keyword arguments (forceflash: Boolean) :return: Boolean """ forceflash = kwargs.get("forceflash", False) cur_binary_sha1 = self.dutinformation.build_binary_sha1 if not forceflash and self.build.sha1 == cur_binary_sha1: return False return True
python
def _flash_needed(self, **kwargs): forceflash = kwargs.get("forceflash", False) cur_binary_sha1 = self.dutinformation.build_binary_sha1 if not forceflash and self.build.sha1 == cur_binary_sha1: return False return True
[ "def", "_flash_needed", "(", "self", ",", "*", "*", "kwargs", ")", ":", "forceflash", "=", "kwargs", ".", "get", "(", "\"forceflash\"", ",", "False", ")", "cur_binary_sha1", "=", "self", ".", "dutinformation", ".", "build_binary_sha1", "if", "not", "forcefla...
Check if flashing is needed. Flashing can be skipped if resource binary_sha1 attribute matches build sha1 and forceflash is not True. :param kwargs: Keyword arguments (forceflash: Boolean) :return: Boolean
[ "Check", "if", "flashing", "is", "needed", ".", "Flashing", "can", "be", "skipped", "if", "resource", "binary_sha1", "attribute", "matches", "build", "sha1", "and", "forceflash", "is", "not", "True", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutMbed.py#L119-L131
27,337
ARMmbed/icetea
icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py
SerialParams.get_params
def get_params(self): """ Get parameters as a tuple. :return: timeout, xonxoff, rtscts, baudrate """ return self.timeout, self.xonxoff, self.rtscts, self.baudrate
python
def get_params(self): return self.timeout, self.xonxoff, self.rtscts, self.baudrate
[ "def", "get_params", "(", "self", ")", ":", "return", "self", ".", "timeout", ",", "self", ".", "xonxoff", ",", "self", ".", "rtscts", ",", "self", ".", "baudrate" ]
Get parameters as a tuple. :return: timeout, xonxoff, rtscts, baudrate
[ "Get", "parameters", "as", "a", "tuple", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py#L46-L52
27,338
ARMmbed/icetea
icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py
DutSerial.open_connection
def open_connection(self): """ Open serial port connection. :return: Nothing :raises: DutConnectionError if serial port was already open or a SerialException occurs. ValueError if EnhancedSerial __init__ or value setters raise ValueError """ if self.readthread is not None: raise DutConnectionError("Trying to open serial port which was already open") self.logger.info("Open Connection " "for '%s' using '%s' baudrate: %d" % (self.dut_name, self.comport, self.serial_baudrate), extra={'type': '<->'}) if self.serial_xonxoff: self.logger.debug("Use software flow control for dut: %s" % self.dut_name) if self.serial_rtscts: self.logger.debug("Use hardware flow control for dut: %s" % self.dut_name) try: self.port = EnhancedSerial(self.comport) self.port.baudrate = self.serial_baudrate self.port.timeout = self.serial_timeout self.port.xonxoff = self.serial_xonxoff self.port.rtscts = self.serial_rtscts self.port.flushInput() self.port.flushOutput() except SerialException as err: self.logger.warning(err) raise DutConnectionError(str(err)) except ValueError as err: self.logger.warning(err) raise ValueError(str(err)) if self.ch_mode: self.logger.info("Use chunk-mode with size %d, delay: %.3f when write data" % (self.ch_mode_chunk_size, self.ch_mode_ch_delay), extra={'type': '<->'}) time.sleep(self.ch_mode_start_delay) else: self.logger.info("Use normal serial write mode", extra={'type': '<->'}) if self.params.reset: self.reset() # Start the serial reading thread self.readthread = Thread(name=self.name, target=self.run) self.readthread.start()
python
def open_connection(self): if self.readthread is not None: raise DutConnectionError("Trying to open serial port which was already open") self.logger.info("Open Connection " "for '%s' using '%s' baudrate: %d" % (self.dut_name, self.comport, self.serial_baudrate), extra={'type': '<->'}) if self.serial_xonxoff: self.logger.debug("Use software flow control for dut: %s" % self.dut_name) if self.serial_rtscts: self.logger.debug("Use hardware flow control for dut: %s" % self.dut_name) try: self.port = EnhancedSerial(self.comport) self.port.baudrate = self.serial_baudrate self.port.timeout = self.serial_timeout self.port.xonxoff = self.serial_xonxoff self.port.rtscts = self.serial_rtscts self.port.flushInput() self.port.flushOutput() except SerialException as err: self.logger.warning(err) raise DutConnectionError(str(err)) except ValueError as err: self.logger.warning(err) raise ValueError(str(err)) if self.ch_mode: self.logger.info("Use chunk-mode with size %d, delay: %.3f when write data" % (self.ch_mode_chunk_size, self.ch_mode_ch_delay), extra={'type': '<->'}) time.sleep(self.ch_mode_start_delay) else: self.logger.info("Use normal serial write mode", extra={'type': '<->'}) if self.params.reset: self.reset() # Start the serial reading thread self.readthread = Thread(name=self.name, target=self.run) self.readthread.start()
[ "def", "open_connection", "(", "self", ")", ":", "if", "self", ".", "readthread", "is", "not", "None", ":", "raise", "DutConnectionError", "(", "\"Trying to open serial port which was already open\"", ")", "self", ".", "logger", ".", "info", "(", "\"Open Connection ...
Open serial port connection. :return: Nothing :raises: DutConnectionError if serial port was already open or a SerialException occurs. ValueError if EnhancedSerial __init__ or value setters raise ValueError
[ "Open", "serial", "port", "connection", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py#L246-L292
27,339
ARMmbed/icetea
icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py
DutSerial.close_connection
def close_connection(self): # pylint: disable=C0103 """ Closes serial port connection. :return: Nothing """ if self.port: self.stop() self.logger.debug("Close port '%s'" % self.comport, extra={'type': '<->'}) self.port.close() self.port = False
python
def close_connection(self): # pylint: disable=C0103 if self.port: self.stop() self.logger.debug("Close port '%s'" % self.comport, extra={'type': '<->'}) self.port.close() self.port = False
[ "def", "close_connection", "(", "self", ")", ":", "# pylint: disable=C0103", "if", "self", ".", "port", ":", "self", ".", "stop", "(", ")", "self", ".", "logger", ".", "debug", "(", "\"Close port '%s'\"", "%", "self", ".", "comport", ",", "extra", "=", "...
Closes serial port connection. :return: Nothing
[ "Closes", "serial", "port", "connection", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py#L316-L327
27,340
ARMmbed/icetea
icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py
DutSerial.__send_break
def __send_break(self): """ Sends break to device. :return: result of EnhancedSerial safe_sendBreak() """ if self.port: self.logger.debug("sendBreak to device to reboot", extra={'type': '<->'}) result = self.port.safe_sendBreak() time.sleep(1) if result: self.logger.debug("reset completed", extra={'type': '<->'}) else: self.logger.warning("reset failed", extra={'type': '<->'}) return result return None
python
def __send_break(self): if self.port: self.logger.debug("sendBreak to device to reboot", extra={'type': '<->'}) result = self.port.safe_sendBreak() time.sleep(1) if result: self.logger.debug("reset completed", extra={'type': '<->'}) else: self.logger.warning("reset failed", extra={'type': '<->'}) return result return None
[ "def", "__send_break", "(", "self", ")", ":", "if", "self", ".", "port", ":", "self", ".", "logger", ".", "debug", "(", "\"sendBreak to device to reboot\"", ",", "extra", "=", "{", "'type'", ":", "'<->'", "}", ")", "result", "=", "self", ".", "port", "...
Sends break to device. :return: result of EnhancedSerial safe_sendBreak()
[ "Sends", "break", "to", "device", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py#L348-L363
27,341
ARMmbed/icetea
icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py
DutSerial.writeline
def writeline(self, data): """ Writes data to serial port. :param data: Data to write :return: Nothing :raises: IOError if SerialException occurs. """ try: if self.ch_mode: data += "\n" parts = split_by_n(data, self.ch_mode_chunk_size) for split_str in parts: self.port.write(split_str.encode()) time.sleep(self.ch_mode_ch_delay) else: self.port.write((data + "\n").encode()) except SerialException as err: self.logger.exception("SerialError occured while trying to write data {}.".format(data)) raise RuntimeError(str(err))
python
def writeline(self, data): try: if self.ch_mode: data += "\n" parts = split_by_n(data, self.ch_mode_chunk_size) for split_str in parts: self.port.write(split_str.encode()) time.sleep(self.ch_mode_ch_delay) else: self.port.write((data + "\n").encode()) except SerialException as err: self.logger.exception("SerialError occured while trying to write data {}.".format(data)) raise RuntimeError(str(err))
[ "def", "writeline", "(", "self", ",", "data", ")", ":", "try", ":", "if", "self", ".", "ch_mode", ":", "data", "+=", "\"\\n\"", "parts", "=", "split_by_n", "(", "data", ",", "self", ".", "ch_mode_chunk_size", ")", "for", "split_str", "in", "parts", ":"...
Writes data to serial port. :param data: Data to write :return: Nothing :raises: IOError if SerialException occurs.
[ "Writes", "data", "to", "serial", "port", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py#L366-L385
27,342
ARMmbed/icetea
icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py
DutSerial._readline
def _readline(self, timeout=1): """ Read line from serial port. :param timeout: timeout, default is 1 :return: stripped line or None """ line = self.port.readline(timeout=timeout) return strip_escape(line.strip()) if line is not None else line
python
def _readline(self, timeout=1): line = self.port.readline(timeout=timeout) return strip_escape(line.strip()) if line is not None else line
[ "def", "_readline", "(", "self", ",", "timeout", "=", "1", ")", ":", "line", "=", "self", ".", "port", ".", "readline", "(", "timeout", "=", "timeout", ")", "return", "strip_escape", "(", "line", ".", "strip", "(", ")", ")", "if", "line", "is", "no...
Read line from serial port. :param timeout: timeout, default is 1 :return: stripped line or None
[ "Read", "line", "from", "serial", "port", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py#L388-L396
27,343
ARMmbed/icetea
icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py
DutSerial.run
def run(self): """ Read lines while keep_reading is True. Calls process_dut for each received line. :return: Nothing """ self.keep_reading = True while self.keep_reading: line = self._readline() if line: self.input_queue.appendleft(line) Dut.process_dut(self)
python
def run(self): self.keep_reading = True while self.keep_reading: line = self._readline() if line: self.input_queue.appendleft(line) Dut.process_dut(self)
[ "def", "run", "(", "self", ")", ":", "self", ".", "keep_reading", "=", "True", "while", "self", ".", "keep_reading", ":", "line", "=", "self", ".", "_readline", "(", ")", "if", "line", ":", "self", ".", "input_queue", ".", "appendleft", "(", "line", ...
Read lines while keep_reading is True. Calls process_dut for each received line. :return: Nothing
[ "Read", "lines", "while", "keep_reading", "is", "True", ".", "Calls", "process_dut", "for", "each", "received", "line", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py#L408-L419
27,344
ARMmbed/icetea
icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py
DutSerial.stop
def stop(self): """ Stops and joins readthread. :return: Nothing """ self.keep_reading = False if self.readthread is not None: self.readthread.join() self.readthread = None
python
def stop(self): self.keep_reading = False if self.readthread is not None: self.readthread.join() self.readthread = None
[ "def", "stop", "(", "self", ")", ":", "self", ".", "keep_reading", "=", "False", "if", "self", ".", "readthread", "is", "not", "None", ":", "self", ".", "readthread", ".", "join", "(", ")", "self", ".", "readthread", "=", "None" ]
Stops and joins readthread. :return: Nothing
[ "Stops", "and", "joins", "readthread", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py#L421-L430
27,345
ARMmbed/icetea
icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py
DutSerial.print_info
def print_info(self): """ Prints Dut information nicely formatted into a table. """ table = PrettyTable() start_string = "DutSerial {} \n".format(self.name) row = [] info_string = "" if self.config: info_string = info_string + "Configuration for this DUT:\n\n {} \n".format(self.config) if self.comport: table.add_column("COM port", []) row.append(self.comport) if self.port: if hasattr(self.port, "baudrate"): table.add_column("Baudrate", []) row.append(self.port.baudrate) if hasattr(self.port, "xonxoff"): table.add_column("XON/XOFF", []) row.append(self.port.xonxoff) if hasattr(self.port, "timeout"): table.add_column("Timeout", []) row.append(self.port.timeout) if hasattr(self.port, "rtscts"): table.add_column("RTSCTS", []) row.append(self.port.rtscts) if self.location: table.add_column("Location", []) row.append("X = {}, Y = {}".format(self.location.x_coord, self.location.y_coord)) self.logger.info(start_string) self.logger.debug(info_string) table.add_row(row) print(table)
python
def print_info(self): table = PrettyTable() start_string = "DutSerial {} \n".format(self.name) row = [] info_string = "" if self.config: info_string = info_string + "Configuration for this DUT:\n\n {} \n".format(self.config) if self.comport: table.add_column("COM port", []) row.append(self.comport) if self.port: if hasattr(self.port, "baudrate"): table.add_column("Baudrate", []) row.append(self.port.baudrate) if hasattr(self.port, "xonxoff"): table.add_column("XON/XOFF", []) row.append(self.port.xonxoff) if hasattr(self.port, "timeout"): table.add_column("Timeout", []) row.append(self.port.timeout) if hasattr(self.port, "rtscts"): table.add_column("RTSCTS", []) row.append(self.port.rtscts) if self.location: table.add_column("Location", []) row.append("X = {}, Y = {}".format(self.location.x_coord, self.location.y_coord)) self.logger.info(start_string) self.logger.debug(info_string) table.add_row(row) print(table)
[ "def", "print_info", "(", "self", ")", ":", "table", "=", "PrettyTable", "(", ")", "start_string", "=", "\"DutSerial {} \\n\"", ".", "format", "(", "self", ".", "name", ")", "row", "=", "[", "]", "info_string", "=", "\"\"", "if", "self", ".", "config", ...
Prints Dut information nicely formatted into a table.
[ "Prints", "Dut", "information", "nicely", "formatted", "into", "a", "table", "." ]
b2b97ac607429830cf7d62dae2e3903692c7c778
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/plugins/LocalAllocator/DutSerial.py#L445-L477
27,346
bootphon/h5features
h5features/data.py
Data.append
def append(self, data): """Append a Data instance to self""" for k in self._entries.keys(): self._entries[k].append(data._entries[k])
python
def append(self, data): for k in self._entries.keys(): self._entries[k].append(data._entries[k])
[ "def", "append", "(", "self", ",", "data", ")", ":", "for", "k", "in", "self", ".", "_entries", ".", "keys", "(", ")", ":", "self", ".", "_entries", "[", "k", "]", ".", "append", "(", "data", ".", "_entries", "[", "k", "]", ")" ]
Append a Data instance to self
[ "Append", "a", "Data", "instance", "to", "self" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/data.py#L72-L75
27,347
bootphon/h5features
h5features/data.py
Data.init_group
def init_group(self, group, chunk_size, compression=None, compression_opts=None): """Initializes a HDF5 group compliant with the stored data. This method creates the datasets 'items', 'labels', 'features' and 'index' and leaves them empty. :param h5py.Group group: The group to initializes. :param float chunk_size: The size of a chunk in the file (in MB). :param str compression: Optional compression, see :class:`h5features.writer` for details :param str compression: Optional compression options, see :class:`h5features.writer` for details """ create_index(group, chunk_size) self._entries['items'].create_dataset( group, chunk_size, compression=compression, compression_opts=compression_opts) self._entries['features'].create_dataset( group, chunk_size, compression=compression, compression_opts=compression_opts) # chunking the labels depends on features chunks self._entries['labels'].create_dataset( group, self._entries['features'].nb_per_chunk, compression=compression, compression_opts=compression_opts) if self.has_properties(): self._entries['properties'].create_dataset( group, compression=compression, compression_opts=compression_opts)
python
def init_group(self, group, chunk_size, compression=None, compression_opts=None): create_index(group, chunk_size) self._entries['items'].create_dataset( group, chunk_size, compression=compression, compression_opts=compression_opts) self._entries['features'].create_dataset( group, chunk_size, compression=compression, compression_opts=compression_opts) # chunking the labels depends on features chunks self._entries['labels'].create_dataset( group, self._entries['features'].nb_per_chunk, compression=compression, compression_opts=compression_opts) if self.has_properties(): self._entries['properties'].create_dataset( group, compression=compression, compression_opts=compression_opts)
[ "def", "init_group", "(", "self", ",", "group", ",", "chunk_size", ",", "compression", "=", "None", ",", "compression_opts", "=", "None", ")", ":", "create_index", "(", "group", ",", "chunk_size", ")", "self", ".", "_entries", "[", "'items'", "]", ".", "...
Initializes a HDF5 group compliant with the stored data. This method creates the datasets 'items', 'labels', 'features' and 'index' and leaves them empty. :param h5py.Group group: The group to initializes. :param float chunk_size: The size of a chunk in the file (in MB). :param str compression: Optional compression, see :class:`h5features.writer` for details :param str compression: Optional compression options, see :class:`h5features.writer` for details
[ "Initializes", "a", "HDF5", "group", "compliant", "with", "the", "stored", "data", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/data.py#L111-L145
27,348
bootphon/h5features
h5features/data.py
Data.is_appendable_to
def is_appendable_to(self, group): """Returns True if the data can be appended in a given group.""" # First check only the names if not all([k in group for k in self._entries.keys()]): return False # If names are matching, check the contents for k in self._entries.keys(): if not self._entries[k].is_appendable_to(group): return False return True
python
def is_appendable_to(self, group): # First check only the names if not all([k in group for k in self._entries.keys()]): return False # If names are matching, check the contents for k in self._entries.keys(): if not self._entries[k].is_appendable_to(group): return False return True
[ "def", "is_appendable_to", "(", "self", ",", "group", ")", ":", "# First check only the names", "if", "not", "all", "(", "[", "k", "in", "group", "for", "k", "in", "self", ".", "_entries", ".", "keys", "(", ")", "]", ")", ":", "return", "False", "# If ...
Returns True if the data can be appended in a given group.
[ "Returns", "True", "if", "the", "data", "can", "be", "appended", "in", "a", "given", "group", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/data.py#L147-L158
27,349
bootphon/h5features
h5features/data.py
Data.write_to
def write_to(self, group, append=False): """Write the data to the given group. :param h5py.Group group: The group to write the data on. It is assumed that the group is already existing or initialized to store h5features data (i.e. the method ``Data.init_group`` have been called. :param bool append: If False, any existing data in the group is overwrited. If True, the data is appended to the end of the group and we assume ``Data.is_appendable_to`` is True for this group. """ write_index(self, group, append) self._entries['items'].write_to(group) self._entries['features'].write_to(group, append) self._entries['labels'].write_to(group) if self.has_properties(): self._entries['properties'].write_to(group, append=append)
python
def write_to(self, group, append=False): write_index(self, group, append) self._entries['items'].write_to(group) self._entries['features'].write_to(group, append) self._entries['labels'].write_to(group) if self.has_properties(): self._entries['properties'].write_to(group, append=append)
[ "def", "write_to", "(", "self", ",", "group", ",", "append", "=", "False", ")", ":", "write_index", "(", "self", ",", "group", ",", "append", ")", "self", ".", "_entries", "[", "'items'", "]", ".", "write_to", "(", "group", ")", "self", ".", "_entrie...
Write the data to the given group. :param h5py.Group group: The group to write the data on. It is assumed that the group is already existing or initialized to store h5features data (i.e. the method ``Data.init_group`` have been called. :param bool append: If False, any existing data in the group is overwrited. If True, the data is appended to the end of the group and we assume ``Data.is_appendable_to`` is True for this group.
[ "Write", "the", "data", "to", "the", "given", "group", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/data.py#L160-L179
27,350
bootphon/h5features
h5features/labels.py
Labels.check
def check(labels): """Raise IOError if labels are not correct `labels` must be a list of sorted numpy arrays of equal dimensions (must be 1D or 2D). In the case of 2D labels, the second axis must have the same shape for all labels. """ # type checking if not isinstance(labels, list): raise IOError('labels are not in a list') if not len(labels): raise IOError('the labels list is empty') if not all([isinstance(l, np.ndarray) for l in labels]): raise IOError('all labels must be numpy arrays') # dimension checking ndim = labels[0].ndim if ndim not in [1, 2]: raise IOError('labels dimension must be 1 or 2') if not all([l.ndim == ndim for l in labels]): raise IOError('all labels dimensions must be equal') if ndim == 2: shape1 = labels[0].shape[1] if not all([l.shape[1] == shape1 for l in labels]): raise IOError('all labels must have same shape on 2nd dim') # sort checking for label in labels: index = (np.argsort(label) if label.ndim == 1 else np.lexsort(label.T)) # print label, index # print len(index), label.shape[0] assert len(index) == label.shape[0] if not all(n == index[n] for n in range(label.shape[0]-1)): raise IOError('labels are not sorted in increasing order')
python
def check(labels): # type checking if not isinstance(labels, list): raise IOError('labels are not in a list') if not len(labels): raise IOError('the labels list is empty') if not all([isinstance(l, np.ndarray) for l in labels]): raise IOError('all labels must be numpy arrays') # dimension checking ndim = labels[0].ndim if ndim not in [1, 2]: raise IOError('labels dimension must be 1 or 2') if not all([l.ndim == ndim for l in labels]): raise IOError('all labels dimensions must be equal') if ndim == 2: shape1 = labels[0].shape[1] if not all([l.shape[1] == shape1 for l in labels]): raise IOError('all labels must have same shape on 2nd dim') # sort checking for label in labels: index = (np.argsort(label) if label.ndim == 1 else np.lexsort(label.T)) # print label, index # print len(index), label.shape[0] assert len(index) == label.shape[0] if not all(n == index[n] for n in range(label.shape[0]-1)): raise IOError('labels are not sorted in increasing order')
[ "def", "check", "(", "labels", ")", ":", "# type checking", "if", "not", "isinstance", "(", "labels", ",", "list", ")", ":", "raise", "IOError", "(", "'labels are not in a list'", ")", "if", "not", "len", "(", "labels", ")", ":", "raise", "IOError", "(", ...
Raise IOError if labels are not correct `labels` must be a list of sorted numpy arrays of equal dimensions (must be 1D or 2D). In the case of 2D labels, the second axis must have the same shape for all labels.
[ "Raise", "IOError", "if", "labels", "are", "not", "correct" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/labels.py#L56-L91
27,351
bootphon/h5features
h5features/converter.py
Converter._write
def _write(self, item, labels, features): """ Writes the given item to the owned file.""" data = Data([item], [labels], [features]) self._writer.write(data, self.groupname, append=True)
python
def _write(self, item, labels, features): data = Data([item], [labels], [features]) self._writer.write(data, self.groupname, append=True)
[ "def", "_write", "(", "self", ",", "item", ",", "labels", ",", "features", ")", ":", "data", "=", "Data", "(", "[", "item", "]", ",", "[", "labels", "]", ",", "[", "features", "]", ")", "self", ".", "_writer", ".", "write", "(", "data", ",", "s...
Writes the given item to the owned file.
[ "Writes", "the", "given", "item", "to", "the", "owned", "file", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/converter.py#L65-L68
27,352
bootphon/h5features
h5features/converter.py
Converter.convert
def convert(self, infile, item=None): """Convert an input file to h5features based on its extension. :raise IOError: if `infile` is not a valid file. :raise IOError: if `infile` extension is not supported. """ if not os.path.isfile(infile): raise IOError('{} is not a valid file'.format(infile)) if item is None: item = os.path.splitext(infile)[0] ext = os.path.splitext(infile)[1] if ext == '.npz': self.npz_convert(infile, item) elif ext == '.mat': self.mat_convert(infile, item) elif ext == '.h5': self.h5features_convert(infile) else: raise IOError('Unknown file format for {}'.format(infile))
python
def convert(self, infile, item=None): if not os.path.isfile(infile): raise IOError('{} is not a valid file'.format(infile)) if item is None: item = os.path.splitext(infile)[0] ext = os.path.splitext(infile)[1] if ext == '.npz': self.npz_convert(infile, item) elif ext == '.mat': self.mat_convert(infile, item) elif ext == '.h5': self.h5features_convert(infile) else: raise IOError('Unknown file format for {}'.format(infile))
[ "def", "convert", "(", "self", ",", "infile", ",", "item", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "infile", ")", ":", "raise", "IOError", "(", "'{} is not a valid file'", ".", "format", "(", "infile", ")", ")", "if...
Convert an input file to h5features based on its extension. :raise IOError: if `infile` is not a valid file. :raise IOError: if `infile` extension is not supported.
[ "Convert", "an", "input", "file", "to", "h5features", "based", "on", "its", "extension", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/converter.py#L80-L101
27,353
bootphon/h5features
h5features/converter.py
Converter.npz_convert
def npz_convert(self, infile, item): """Convert a numpy NPZ file to h5features.""" data = np.load(infile) labels = self._labels(data) features = data['features'] self._write(item, labels, features)
python
def npz_convert(self, infile, item): data = np.load(infile) labels = self._labels(data) features = data['features'] self._write(item, labels, features)
[ "def", "npz_convert", "(", "self", ",", "infile", ",", "item", ")", ":", "data", "=", "np", ".", "load", "(", "infile", ")", "labels", "=", "self", ".", "_labels", "(", "data", ")", "features", "=", "data", "[", "'features'", "]", "self", ".", "_wr...
Convert a numpy NPZ file to h5features.
[ "Convert", "a", "numpy", "NPZ", "file", "to", "h5features", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/converter.py#L103-L108
27,354
bootphon/h5features
h5features/converter.py
Converter.h5features_convert
def h5features_convert(self, infile): """Convert a h5features file to the latest h5features version.""" with h5py.File(infile, 'r') as f: groups = list(f.keys()) for group in groups: self._writer.write( Reader(infile, group).read(), self.groupname, append=True)
python
def h5features_convert(self, infile): with h5py.File(infile, 'r') as f: groups = list(f.keys()) for group in groups: self._writer.write( Reader(infile, group).read(), self.groupname, append=True)
[ "def", "h5features_convert", "(", "self", ",", "infile", ")", ":", "with", "h5py", ".", "File", "(", "infile", ",", "'r'", ")", "as", "f", ":", "groups", "=", "list", "(", "f", ".", "keys", "(", ")", ")", "for", "group", "in", "groups", ":", "sel...
Convert a h5features file to the latest h5features version.
[ "Convert", "a", "h5features", "file", "to", "the", "latest", "h5features", "version", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/converter.py#L117-L124
27,355
bootphon/h5features
h5features/h5features.py
read
def read(filename, groupname=None, from_item=None, to_item=None, from_time=None, to_time=None, index=None): """Reads in a h5features file. :param str filename: Path to a hdf5 file potentially serving as a container for many small files :param str groupname: HDF5 group to read the data from. If None, guess there is one and only one group in `filename`. :param str from_item: Optional. Read the data starting from this item. (defaults to the first stored item) :param str to_item: Optional. Read the data until reaching the item. (defaults to from_item if it was specified and to the last stored item otherwise) :param float from_time: Optional. (defaults to the beginning time in from_item) the specified times are included in the output :param float to_time: Optional. (defaults to the ending time in to_item) the specified times are included in the output :param int index: Not implemented, raise if used. :return: A tuple (times, features) or (times, features, properties) such as: * time is a dictionary of 1D arrays values (keys are items). * features: A dictionary of 2D arrays values (keys are items) with the 'features' dimension along the columns and the 'time' dimension along the lines. * properties: A dictionnary of dictionnaries (keys are items) with the corresponding properties. If there is no properties recorded, this value is not returned. .. note:: Note that all the files that are present on disk between to_item and from_item will be loaded and returned. It's the responsibility of the user to make sure that it will fit into RAM memory. """ # TODO legacy read from index not implemented if index is not None: raise NotImplementedError reader = Reader(filename, groupname) data = (reader.read(from_item, to_item, from_time, to_time) if index is None else reader.index_read(index)) if data.has_properties(): return data.dict_labels(), data.dict_features(), data.dict_properties() else: return data.dict_labels(), data.dict_features()
python
def read(filename, groupname=None, from_item=None, to_item=None, from_time=None, to_time=None, index=None): # TODO legacy read from index not implemented if index is not None: raise NotImplementedError reader = Reader(filename, groupname) data = (reader.read(from_item, to_item, from_time, to_time) if index is None else reader.index_read(index)) if data.has_properties(): return data.dict_labels(), data.dict_features(), data.dict_properties() else: return data.dict_labels(), data.dict_features()
[ "def", "read", "(", "filename", ",", "groupname", "=", "None", ",", "from_item", "=", "None", ",", "to_item", "=", "None", ",", "from_time", "=", "None", ",", "to_time", "=", "None", ",", "index", "=", "None", ")", ":", "# TODO legacy read from index not i...
Reads in a h5features file. :param str filename: Path to a hdf5 file potentially serving as a container for many small files :param str groupname: HDF5 group to read the data from. If None, guess there is one and only one group in `filename`. :param str from_item: Optional. Read the data starting from this item. (defaults to the first stored item) :param str to_item: Optional. Read the data until reaching the item. (defaults to from_item if it was specified and to the last stored item otherwise) :param float from_time: Optional. (defaults to the beginning time in from_item) the specified times are included in the output :param float to_time: Optional. (defaults to the ending time in to_item) the specified times are included in the output :param int index: Not implemented, raise if used. :return: A tuple (times, features) or (times, features, properties) such as: * time is a dictionary of 1D arrays values (keys are items). * features: A dictionary of 2D arrays values (keys are items) with the 'features' dimension along the columns and the 'time' dimension along the lines. * properties: A dictionnary of dictionnaries (keys are items) with the corresponding properties. If there is no properties recorded, this value is not returned. .. note:: Note that all the files that are present on disk between to_item and from_item will be loaded and returned. It's the responsibility of the user to make sure that it will fit into RAM memory.
[ "Reads", "in", "a", "h5features", "file", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/h5features.py#L34-L88
27,356
bootphon/h5features
h5features/h5features.py
write
def write(filename, groupname, items, times, features, properties=None, dformat='dense', chunk_size='auto', sparsity=0.1, mode='a'): """Write h5features data in a HDF5 file. This function is a wrapper to the Writer class. It has three purposes: * Check parameters for errors (see details below), * Create Items, Times and Features objects * Send them to the Writer. :param str filename: HDF5 file to be writted, potentially serving as a container for many small files. If the file does not exist, it is created. If the file is already a valid HDF5 file, try to append the data in it. :param str groupname: Name of the group to write the data in, or to append the data to if the group already exists in the file. :param items: List of files from which the features where extracted. Items must not contain duplicates. :type items: list of str :param times: Time value for the features array. Elements of a 1D array are considered as the center of the time window associated with the features. A 2D array must have 2 columns corresponding to the begin and end timestamps of the features time window. :type times: list of 1D or 2D numpy arrays :param features: Features should have time along the lines and features along the columns (accomodating row-major storage in hdf5 files). :type features: list of 2D numpy arrays :param properties: Optional. Properties associated with each item. Properties describe the features associated with each item in a dictionnary. It can store parameters or fields recorded by the user. :type properties: list of dictionnaries :param str dformat: Optional. Which format to store the features into (sparse or dense). Default is dense. :param float chunk_size: Optional. In Mo, tuning parameter corresponding to the size of a chunk in the h5file. By default the chunk size is guessed automatically. Tis parameter is ignored if the file already exists. :param float sparsity: Optional. Tuning parameter corresponding to the expected proportion (in [0, 1]) of non-zeros elements on average in a single frame. :param char mode: Optional. The mode for overwriting an existing file, 'a' to append data to the file, 'w' to overwrite it :raise IOError: if the filename is not valid or parameters are inconsistent. :raise NotImplementedError: if dformat == 'sparse' """ # Prepare the data, raise on error sparsity = sparsity if dformat == 'sparse' else None data = Data(items, times, features, properties=properties, sparsity=sparsity, check=True) # Write all that stuff in the HDF5 file's specified group Writer(filename, chunk_size=chunk_size).write(data, groupname, append=True)
python
def write(filename, groupname, items, times, features, properties=None, dformat='dense', chunk_size='auto', sparsity=0.1, mode='a'): # Prepare the data, raise on error sparsity = sparsity if dformat == 'sparse' else None data = Data(items, times, features, properties=properties, sparsity=sparsity, check=True) # Write all that stuff in the HDF5 file's specified group Writer(filename, chunk_size=chunk_size).write(data, groupname, append=True)
[ "def", "write", "(", "filename", ",", "groupname", ",", "items", ",", "times", ",", "features", ",", "properties", "=", "None", ",", "dformat", "=", "'dense'", ",", "chunk_size", "=", "'auto'", ",", "sparsity", "=", "0.1", ",", "mode", "=", "'a'", ")",...
Write h5features data in a HDF5 file. This function is a wrapper to the Writer class. It has three purposes: * Check parameters for errors (see details below), * Create Items, Times and Features objects * Send them to the Writer. :param str filename: HDF5 file to be writted, potentially serving as a container for many small files. If the file does not exist, it is created. If the file is already a valid HDF5 file, try to append the data in it. :param str groupname: Name of the group to write the data in, or to append the data to if the group already exists in the file. :param items: List of files from which the features where extracted. Items must not contain duplicates. :type items: list of str :param times: Time value for the features array. Elements of a 1D array are considered as the center of the time window associated with the features. A 2D array must have 2 columns corresponding to the begin and end timestamps of the features time window. :type times: list of 1D or 2D numpy arrays :param features: Features should have time along the lines and features along the columns (accomodating row-major storage in hdf5 files). :type features: list of 2D numpy arrays :param properties: Optional. Properties associated with each item. Properties describe the features associated with each item in a dictionnary. It can store parameters or fields recorded by the user. :type properties: list of dictionnaries :param str dformat: Optional. Which format to store the features into (sparse or dense). Default is dense. :param float chunk_size: Optional. In Mo, tuning parameter corresponding to the size of a chunk in the h5file. By default the chunk size is guessed automatically. Tis parameter is ignored if the file already exists. :param float sparsity: Optional. Tuning parameter corresponding to the expected proportion (in [0, 1]) of non-zeros elements on average in a single frame. :param char mode: Optional. The mode for overwriting an existing file, 'a' to append data to the file, 'w' to overwrite it :raise IOError: if the filename is not valid or parameters are inconsistent. :raise NotImplementedError: if dformat == 'sparse'
[ "Write", "h5features", "data", "in", "a", "HDF5", "file", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/h5features.py#L91-L158
27,357
bootphon/h5features
h5features/features.py
contains_empty
def contains_empty(features): """Check features data are not empty :param features: The features data to check. :type features: list of numpy arrays. :return: True if one of the array is empty, False else. """ if not features: return True for feature in features: if feature.shape[0] == 0: return True return False
python
def contains_empty(features): if not features: return True for feature in features: if feature.shape[0] == 0: return True return False
[ "def", "contains_empty", "(", "features", ")", ":", "if", "not", "features", ":", "return", "True", "for", "feature", "in", "features", ":", "if", "feature", ".", "shape", "[", "0", "]", "==", "0", ":", "return", "True", "return", "False" ]
Check features data are not empty :param features: The features data to check. :type features: list of numpy arrays. :return: True if one of the array is empty, False else.
[ "Check", "features", "data", "are", "not", "empty" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L27-L41
27,358
bootphon/h5features
h5features/features.py
parse_dformat
def parse_dformat(dformat, check=True): """Return `dformat` or raise if it is not 'dense' or 'sparse'""" if check and dformat not in ['dense', 'sparse']: raise IOError( "{} is a bad features format, please choose 'dense' or 'sparse'" .format(dformat)) return dformat
python
def parse_dformat(dformat, check=True): """Return `dformat` or raise if it is not 'dense' or 'sparse'""" if check and dformat not in ['dense', 'sparse']: raise IOError( "{} is a bad features format, please choose 'dense' or 'sparse'" .format(dformat)) return dformat
[ "def", "parse_dformat", "(", "dformat", ",", "check", "=", "True", ")", ":", "if", "check", "and", "dformat", "not", "in", "[", "'dense'", ",", "'sparse'", "]", ":", "raise", "IOError", "(", "\"{} is a bad features format, please choose 'dense' or 'sparse'\"", "."...
Return `dformat` or raise if it is not 'dense' or 'sparse
[ "Return", "dformat", "or", "raise", "if", "it", "is", "not", "dense", "or", "sparse" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L44-L50
27,359
bootphon/h5features
h5features/features.py
parse_dtype
def parse_dtype(features, check=True): """Return the features scalar type, raise if error Raise IOError if all features have not the same data type. Return dtype, the features scalar type. """ dtype = features[0].dtype if check: types = [x.dtype for x in features] if not all([t == dtype for t in types]): raise IOError('features must be homogeneous') return dtype
python
def parse_dtype(features, check=True): dtype = features[0].dtype if check: types = [x.dtype for x in features] if not all([t == dtype for t in types]): raise IOError('features must be homogeneous') return dtype
[ "def", "parse_dtype", "(", "features", ",", "check", "=", "True", ")", ":", "dtype", "=", "features", "[", "0", "]", ".", "dtype", "if", "check", ":", "types", "=", "[", "x", ".", "dtype", "for", "x", "in", "features", "]", "if", "not", "all", "(...
Return the features scalar type, raise if error Raise IOError if all features have not the same data type. Return dtype, the features scalar type.
[ "Return", "the", "features", "scalar", "type", "raise", "if", "error" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L53-L65
27,360
bootphon/h5features
h5features/features.py
parse_dim
def parse_dim(features, check=True): """Return the features dimension, raise if error Raise IOError if features have not all the same positive dimension. Return dim (int), the features dimension. """ # try: dim = features[0].shape[1] # except IndexError: # dim = 1 if check and not dim > 0: raise IOError('features dimension must be strictly positive') if check and not all([d == dim for d in [x.shape[1] for x in features]]): raise IOError('all files must have the same feature dimension') return dim
python
def parse_dim(features, check=True): # try: dim = features[0].shape[1] # except IndexError: # dim = 1 if check and not dim > 0: raise IOError('features dimension must be strictly positive') if check and not all([d == dim for d in [x.shape[1] for x in features]]): raise IOError('all files must have the same feature dimension') return dim
[ "def", "parse_dim", "(", "features", ",", "check", "=", "True", ")", ":", "# try:", "dim", "=", "features", "[", "0", "]", ".", "shape", "[", "1", "]", "# except IndexError:", "# dim = 1", "if", "check", "and", "not", "dim", ">", "0", ":", "raise",...
Return the features dimension, raise if error Raise IOError if features have not all the same positive dimension. Return dim (int), the features dimension.
[ "Return", "the", "features", "dimension", "raise", "if", "error" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L68-L84
27,361
bootphon/h5features
h5features/features.py
Features.is_appendable_to
def is_appendable_to(self, group): """Return True if features are appendable to a HDF5 group""" return (group.attrs['format'] == self.dformat and group[self.name].dtype == self.dtype and # We use a method because dim differs in dense and sparse. self._group_dim(group) == self.dim)
python
def is_appendable_to(self, group): return (group.attrs['format'] == self.dformat and group[self.name].dtype == self.dtype and # We use a method because dim differs in dense and sparse. self._group_dim(group) == self.dim)
[ "def", "is_appendable_to", "(", "self", ",", "group", ")", ":", "return", "(", "group", ".", "attrs", "[", "'format'", "]", "==", "self", ".", "dformat", "and", "group", "[", "self", ".", "name", "]", ".", "dtype", "==", "self", ".", "dtype", "and", ...
Return True if features are appendable to a HDF5 group
[ "Return", "True", "if", "features", "are", "appendable", "to", "a", "HDF5", "group" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L139-L144
27,362
bootphon/h5features
h5features/features.py
Features.create_dataset
def create_dataset( self, group, chunk_size, compression=None, compression_opts=None): """Initialize the features subgoup""" group.attrs['format'] = self.dformat super(Features, self)._create_dataset( group, chunk_size, compression, compression_opts) # TODO attribute declared outside __init__ is not safe. Used # because Labels.create_dataset need it. if chunk_size != 'auto': self.nb_per_chunk = nb_per_chunk( self.dtype.itemsize, self.dim, chunk_size) else: self.nb_per_chunk = 'auto'
python
def create_dataset( self, group, chunk_size, compression=None, compression_opts=None): group.attrs['format'] = self.dformat super(Features, self)._create_dataset( group, chunk_size, compression, compression_opts) # TODO attribute declared outside __init__ is not safe. Used # because Labels.create_dataset need it. if chunk_size != 'auto': self.nb_per_chunk = nb_per_chunk( self.dtype.itemsize, self.dim, chunk_size) else: self.nb_per_chunk = 'auto'
[ "def", "create_dataset", "(", "self", ",", "group", ",", "chunk_size", ",", "compression", "=", "None", ",", "compression_opts", "=", "None", ")", ":", "group", ".", "attrs", "[", "'format'", "]", "=", "self", ".", "dformat", "super", "(", "Features", ",...
Initialize the features subgoup
[ "Initialize", "the", "features", "subgoup" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L153-L166
27,363
bootphon/h5features
h5features/features.py
Features.write_to
def write_to(self, group, append=False): """Write stored features to a given group""" if self.sparsetodense: self.data = [x.todense() if sp.issparse(x) else x for x in self.data] nframes = sum([d.shape[0] for d in self.data]) dim = self._group_dim(group) feats = np.concatenate(self.data, axis=0) if append: nframes_group = group[self.name].shape[0] group[self.name].resize(nframes_group + nframes, axis=0) if dim == 1: group[self.name][nframes_group:] = feats else: group[self.name][nframes_group:, :] = feats else: group[self.name].resize(nframes, axis=0) group[self.name][...] = feats if dim == 1 else feats
python
def write_to(self, group, append=False): if self.sparsetodense: self.data = [x.todense() if sp.issparse(x) else x for x in self.data] nframes = sum([d.shape[0] for d in self.data]) dim = self._group_dim(group) feats = np.concatenate(self.data, axis=0) if append: nframes_group = group[self.name].shape[0] group[self.name].resize(nframes_group + nframes, axis=0) if dim == 1: group[self.name][nframes_group:] = feats else: group[self.name][nframes_group:, :] = feats else: group[self.name].resize(nframes, axis=0) group[self.name][...] = feats if dim == 1 else feats
[ "def", "write_to", "(", "self", ",", "group", ",", "append", "=", "False", ")", ":", "if", "self", ".", "sparsetodense", ":", "self", ".", "data", "=", "[", "x", ".", "todense", "(", ")", "if", "sp", ".", "issparse", "(", "x", ")", "else", "x", ...
Write stored features to a given group
[ "Write", "stored", "features", "to", "a", "given", "group" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L168-L187
27,364
bootphon/h5features
h5features/features.py
SparseFeatures.create_dataset
def create_dataset(self, group, chunk_size): """Initializes sparse specific datasets""" group.attrs['format'] = self.dformat group.attrs['dim'] = self.dim if chunk_size == 'auto': group.create_dataset( 'coordinates', (0, 2), dtype=np.float64, chunks=True, maxshape=(None, 2)) group.create_dataset( self.name, (0,), dtype=self.dtype, chunks=True, maxshape=(None,)) else: # for storing sparse data we don't use the self.nb_per_chunk, # which is only used by the Writer to determine times chunking. per_chunk = nb_per_chunk(self.dtype.itemsize, 1, chunk_size) group.create_dataset( 'coordinates', (0, 2), dtype=np.float64, chunks=(per_chunk, 2), maxshape=(None, 2)) group.create_dataset( self.name, (0,), dtype=self.dtype, chunks=(per_chunk,), maxshape=(None,)) dtype = np.int64 if chunk_size == 'auto': chunks = True self.nb_per_chunk = 'auto' else: chunks = (nb_per_chunk(np.dtype(dtype).itemsize, 1, chunk_size),) # Needed by Times.create_dataset self.nb_per_chunk = nb_per_chunk( self.dtype.itemsize, int(round(self.sparsity*self.dim)), chunk_size) group.create_dataset( 'frames', (0,), dtype=dtype, chunks=chunks, maxshape=(None,))
python
def create_dataset(self, group, chunk_size): group.attrs['format'] = self.dformat group.attrs['dim'] = self.dim if chunk_size == 'auto': group.create_dataset( 'coordinates', (0, 2), dtype=np.float64, chunks=True, maxshape=(None, 2)) group.create_dataset( self.name, (0,), dtype=self.dtype, chunks=True, maxshape=(None,)) else: # for storing sparse data we don't use the self.nb_per_chunk, # which is only used by the Writer to determine times chunking. per_chunk = nb_per_chunk(self.dtype.itemsize, 1, chunk_size) group.create_dataset( 'coordinates', (0, 2), dtype=np.float64, chunks=(per_chunk, 2), maxshape=(None, 2)) group.create_dataset( self.name, (0,), dtype=self.dtype, chunks=(per_chunk,), maxshape=(None,)) dtype = np.int64 if chunk_size == 'auto': chunks = True self.nb_per_chunk = 'auto' else: chunks = (nb_per_chunk(np.dtype(dtype).itemsize, 1, chunk_size),) # Needed by Times.create_dataset self.nb_per_chunk = nb_per_chunk( self.dtype.itemsize, int(round(self.sparsity*self.dim)), chunk_size) group.create_dataset( 'frames', (0,), dtype=dtype, chunks=chunks, maxshape=(None,))
[ "def", "create_dataset", "(", "self", ",", "group", ",", "chunk_size", ")", ":", "group", ".", "attrs", "[", "'format'", "]", "=", "self", ".", "dformat", "group", ".", "attrs", "[", "'dim'", "]", "=", "self", ".", "dim", "if", "chunk_size", "==", "'...
Initializes sparse specific datasets
[ "Initializes", "sparse", "specific", "datasets" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/features.py#L215-L256
27,365
bootphon/h5features
h5features/properties.py
read_properties
def read_properties(group): """Returns properties loaded from a group""" if 'properties' not in group: raise IOError('no properties in group') data = group['properties'][...][0].replace(b'__NULL__', b'\x00') return pickle.loads(data)
python
def read_properties(group): if 'properties' not in group: raise IOError('no properties in group') data = group['properties'][...][0].replace(b'__NULL__', b'\x00') return pickle.loads(data)
[ "def", "read_properties", "(", "group", ")", ":", "if", "'properties'", "not", "in", "group", ":", "raise", "IOError", "(", "'no properties in group'", ")", "data", "=", "group", "[", "'properties'", "]", "[", "...", "]", "[", "0", "]", ".", "replace", "...
Returns properties loaded from a group
[ "Returns", "properties", "loaded", "from", "a", "group" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/properties.py#L24-L30
27,366
bootphon/h5features
h5features/properties.py
Properties._eq_dicts
def _eq_dicts(d1, d2): """Returns True if d1 == d2, False otherwise""" if not d1.keys() == d2.keys(): return False for k, v1 in d1.items(): v2 = d2[k] if not type(v1) == type(v2): return False if isinstance(v1, np.ndarray): if not np.array_equal(v1, v2): return False else: if not v1 == v2: return False return True
python
def _eq_dicts(d1, d2): if not d1.keys() == d2.keys(): return False for k, v1 in d1.items(): v2 = d2[k] if not type(v1) == type(v2): return False if isinstance(v1, np.ndarray): if not np.array_equal(v1, v2): return False else: if not v1 == v2: return False return True
[ "def", "_eq_dicts", "(", "d1", ",", "d2", ")", ":", "if", "not", "d1", ".", "keys", "(", ")", "==", "d2", ".", "keys", "(", ")", ":", "return", "False", "for", "k", ",", "v1", "in", "d1", ".", "items", "(", ")", ":", "v2", "=", "d2", "[", ...
Returns True if d1 == d2, False otherwise
[ "Returns", "True", "if", "d1", "==", "d2", "False", "otherwise" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/properties.py#L57-L72
27,367
bootphon/h5features
h5features/properties.py
Properties.write_to
def write_to(self, group, append=False): """Writes the properties to a `group`, or append it""" data = self.data if append is True: try: # concatenate original and new properties in a single list original = read_properties(group) data = original + data except EOFError: pass # no former data to append on # h5py does not support embedded NULLs in strings ('\x00') data = pickle.dumps(data).replace(b'\x00', b'__NULL__') group['properties'][...] = np.void(data)
python
def write_to(self, group, append=False): data = self.data if append is True: try: # concatenate original and new properties in a single list original = read_properties(group) data = original + data except EOFError: pass # no former data to append on # h5py does not support embedded NULLs in strings ('\x00') data = pickle.dumps(data).replace(b'\x00', b'__NULL__') group['properties'][...] = np.void(data)
[ "def", "write_to", "(", "self", ",", "group", ",", "append", "=", "False", ")", ":", "data", "=", "self", ".", "data", "if", "append", "is", "True", ":", "try", ":", "# concatenate original and new properties in a single list", "original", "=", "read_properties"...
Writes the properties to a `group`, or append it
[ "Writes", "the", "properties", "to", "a", "group", "or", "append", "it" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/properties.py#L83-L96
27,368
bootphon/h5features
docs/exemple.py
generate_data
def generate_data(nitem, nfeat=2, dim=10, labeldim=1, base='item'): """Returns a randomly generated h5f.Data instance. - nitem is the number of items to generate. - nfeat is the number of features to generate for each item. - dim is the dimension of the features vectors. - base is the items basename - labeldim is the dimension of the labels vectors. """ import numpy as np # A list of item names items = [base + '_' + str(i) for i in range(nitem)] # A list of features arrays features = [np.random.randn(nfeat, dim) for _ in range(nitem)] # A list on 1D or 2D times arrays if labeldim == 1: labels = [np.linspace(0, 1, nfeat)] * nitem else: t = np.linspace(0, 1, nfeat) labels = [np.array([t+i for i in range(labeldim)])] * nitem # Format data as required by the writer return h5f.Data(items, labels, features, check=True)
python
def generate_data(nitem, nfeat=2, dim=10, labeldim=1, base='item'): import numpy as np # A list of item names items = [base + '_' + str(i) for i in range(nitem)] # A list of features arrays features = [np.random.randn(nfeat, dim) for _ in range(nitem)] # A list on 1D or 2D times arrays if labeldim == 1: labels = [np.linspace(0, 1, nfeat)] * nitem else: t = np.linspace(0, 1, nfeat) labels = [np.array([t+i for i in range(labeldim)])] * nitem # Format data as required by the writer return h5f.Data(items, labels, features, check=True)
[ "def", "generate_data", "(", "nitem", ",", "nfeat", "=", "2", ",", "dim", "=", "10", ",", "labeldim", "=", "1", ",", "base", "=", "'item'", ")", ":", "import", "numpy", "as", "np", "# A list of item names", "items", "=", "[", "base", "+", "'_'", "+",...
Returns a randomly generated h5f.Data instance. - nitem is the number of items to generate. - nfeat is the number of features to generate for each item. - dim is the dimension of the features vectors. - base is the items basename - labeldim is the dimension of the labels vectors.
[ "Returns", "a", "randomly", "generated", "h5f", ".", "Data", "instance", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/docs/exemple.py#L7-L32
27,369
bootphon/h5features
h5features/index.py
create_index
def create_index(group, chunk_size, compression=None, compression_opts=None): """Create an empty index dataset in the given group.""" dtype = np.int64 if chunk_size == 'auto': chunks = True else: chunks = (nb_per_chunk(np.dtype(dtype).itemsize, 1, chunk_size),) group.create_dataset( 'index', (0,), dtype=dtype, chunks=chunks, maxshape=(None,), compression=compression, compression_opts=compression_opts)
python
def create_index(group, chunk_size, compression=None, compression_opts=None): dtype = np.int64 if chunk_size == 'auto': chunks = True else: chunks = (nb_per_chunk(np.dtype(dtype).itemsize, 1, chunk_size),) group.create_dataset( 'index', (0,), dtype=dtype, chunks=chunks, maxshape=(None,), compression=compression, compression_opts=compression_opts)
[ "def", "create_index", "(", "group", ",", "chunk_size", ",", "compression", "=", "None", ",", "compression_opts", "=", "None", ")", ":", "dtype", "=", "np", ".", "int64", "if", "chunk_size", "==", "'auto'", ":", "chunks", "=", "True", "else", ":", "chunk...
Create an empty index dataset in the given group.
[ "Create", "an", "empty", "index", "dataset", "in", "the", "given", "group", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/index.py#L37-L48
27,370
bootphon/h5features
h5features/index.py
write_index
def write_index(data, group, append): """Write the data index to the given group. :param h5features.Data data: The that is being indexed. :param h5py.Group group: The group where to write the index. :param bool append: If True, append the created index to the existing one in the `group`. Delete any existing data in index if False. """ # build the index from data nitems = group['items'].shape[0] if 'items' in group else 0 last_index = group['index'][-1] if nitems > 0 else -1 index = last_index + cumindex(data._entries['features']) if append: nidx = group['index'].shape[0] # # in case we append to the end of an existing item # if data._entries['items']._continue_last_item(group): # nidx -= 1 group['index'].resize((nidx + index.shape[0],)) group['index'][nidx:] = index else: group['index'].resize((index.shape[0],)) group['index'][...] = index
python
def write_index(data, group, append): # build the index from data nitems = group['items'].shape[0] if 'items' in group else 0 last_index = group['index'][-1] if nitems > 0 else -1 index = last_index + cumindex(data._entries['features']) if append: nidx = group['index'].shape[0] # # in case we append to the end of an existing item # if data._entries['items']._continue_last_item(group): # nidx -= 1 group['index'].resize((nidx + index.shape[0],)) group['index'][nidx:] = index else: group['index'].resize((index.shape[0],)) group['index'][...] = index
[ "def", "write_index", "(", "data", ",", "group", ",", "append", ")", ":", "# build the index from data", "nitems", "=", "group", "[", "'items'", "]", ".", "shape", "[", "0", "]", "if", "'items'", "in", "group", "else", "0", "last_index", "=", "group", "[...
Write the data index to the given group. :param h5features.Data data: The that is being indexed. :param h5py.Group group: The group where to write the index. :param bool append: If True, append the created index to the existing one in the `group`. Delete any existing data in index if False.
[ "Write", "the", "data", "index", "to", "the", "given", "group", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/index.py#L51-L76
27,371
bootphon/h5features
h5features/index.py
read_index
def read_index(group, version='1.1'): """Return the index stored in a h5features group. :param h5py.Group group: The group to read the index from. :param str version: The h5features version of the `group`. :return: a 1D numpy array of features indices. """ if version == '0.1': return np.int64(group['index'][...]) elif version == '1.0': return group['file_index'][...] else: return group['index'][...]
python
def read_index(group, version='1.1'): if version == '0.1': return np.int64(group['index'][...]) elif version == '1.0': return group['file_index'][...] else: return group['index'][...]
[ "def", "read_index", "(", "group", ",", "version", "=", "'1.1'", ")", ":", "if", "version", "==", "'0.1'", ":", "return", "np", ".", "int64", "(", "group", "[", "'index'", "]", "[", "...", "]", ")", "elif", "version", "==", "'1.0'", ":", "return", ...
Return the index stored in a h5features group. :param h5py.Group group: The group to read the index from. :param str version: The h5features version of the `group`. :return: a 1D numpy array of features indices.
[ "Return", "the", "index", "stored", "in", "a", "h5features", "group", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/index.py#L79-L91
27,372
bootphon/h5features
h5features/entry.py
nb_per_chunk
def nb_per_chunk(item_size, item_dim, chunk_size): """Return the number of items that can be stored in one chunk. :param int item_size: Size of an item's scalar componant in Bytes (e.g. for np.float64 this is 8) :param int item_dim: Items dimension (length of the second axis) :param float chunk_size: The size of a chunk given in MBytes. """ # from Mbytes to bytes size = chunk_size * 10.**6 ratio = int(round(size / (item_size*item_dim))) return max(10, ratio)
python
def nb_per_chunk(item_size, item_dim, chunk_size): # from Mbytes to bytes size = chunk_size * 10.**6 ratio = int(round(size / (item_size*item_dim))) return max(10, ratio)
[ "def", "nb_per_chunk", "(", "item_size", ",", "item_dim", ",", "chunk_size", ")", ":", "# from Mbytes to bytes", "size", "=", "chunk_size", "*", "10.", "**", "6", "ratio", "=", "int", "(", "round", "(", "size", "/", "(", "item_size", "*", "item_dim", ")", ...
Return the number of items that can be stored in one chunk. :param int item_size: Size of an item's scalar componant in Bytes (e.g. for np.float64 this is 8) :param int item_dim: Items dimension (length of the second axis) :param float chunk_size: The size of a chunk given in MBytes.
[ "Return", "the", "number", "of", "items", "that", "can", "be", "stored", "in", "one", "chunk", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/entry.py#L22-L36
27,373
bootphon/h5features
h5features/entry.py
Entry.is_appendable
def is_appendable(self, entry): """Return True if entry can be appended to self""" try: if ( self.name == entry.name and self.dtype == entry.dtype and self.dim == entry.dim ): return True except AttributeError: return False return False
python
def is_appendable(self, entry): try: if ( self.name == entry.name and self.dtype == entry.dtype and self.dim == entry.dim ): return True except AttributeError: return False return False
[ "def", "is_appendable", "(", "self", ",", "entry", ")", ":", "try", ":", "if", "(", "self", ".", "name", "==", "entry", ".", "name", "and", "self", ".", "dtype", "==", "entry", ".", "dtype", "and", "self", ".", "dim", "==", "entry", ".", "dim", "...
Return True if entry can be appended to self
[ "Return", "True", "if", "entry", "can", "be", "appended", "to", "self" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/entry.py#L74-L85
27,374
bootphon/h5features
h5features/entry.py
Entry.append
def append(self, entry): """Append an entry to self""" if not self.is_appendable(entry): raise ValueError('entry not appendable') self.data += entry.data
python
def append(self, entry): if not self.is_appendable(entry): raise ValueError('entry not appendable') self.data += entry.data
[ "def", "append", "(", "self", ",", "entry", ")", ":", "if", "not", "self", ".", "is_appendable", "(", "entry", ")", ":", "raise", "ValueError", "(", "'entry not appendable'", ")", "self", ".", "data", "+=", "entry", ".", "data" ]
Append an entry to self
[ "Append", "an", "entry", "to", "self" ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/entry.py#L87-L91
27,375
bootphon/h5features
h5features/writer.py
Writer.write
def write(self, data, groupname='h5features', append=False): """Write h5features data in a specified group of the file. :param dict data: A `h5features.Data` instance to be writed on disk. :param str groupname: Optional. The name of the group in which to write the data. :param bool append: Optional. This parameter has no effect if the `groupname` is not an existing group in the file. If set to True, try to append new data in the group. If False (default) erase all data in the group before writing. :raise IOError: if append requested but not possible. """ if append and groupname in self.h5file: # append data to the group, raise if we cannot group = self.h5file[groupname] if not is_same_version(self.version, group): raise IOError( 'data is not appendable to the group {}: ' 'versions are different'.format(group.name)) if not data.is_appendable_to(group): raise IOError( 'data is not appendable to the group {}' .format(group.name)) else: # overwrite any existing data in group group = self._prepare(data, groupname) data.write_to(group, append)
python
def write(self, data, groupname='h5features', append=False): if append and groupname in self.h5file: # append data to the group, raise if we cannot group = self.h5file[groupname] if not is_same_version(self.version, group): raise IOError( 'data is not appendable to the group {}: ' 'versions are different'.format(group.name)) if not data.is_appendable_to(group): raise IOError( 'data is not appendable to the group {}' .format(group.name)) else: # overwrite any existing data in group group = self._prepare(data, groupname) data.write_to(group, append)
[ "def", "write", "(", "self", ",", "data", ",", "groupname", "=", "'h5features'", ",", "append", "=", "False", ")", ":", "if", "append", "and", "groupname", "in", "self", ".", "h5file", ":", "# append data to the group, raise if we cannot", "group", "=", "self"...
Write h5features data in a specified group of the file. :param dict data: A `h5features.Data` instance to be writed on disk. :param str groupname: Optional. The name of the group in which to write the data. :param bool append: Optional. This parameter has no effect if the `groupname` is not an existing group in the file. If set to True, try to append new data in the group. If False (default) erase all data in the group before writing. :raise IOError: if append requested but not possible.
[ "Write", "h5features", "data", "in", "a", "specified", "group", "of", "the", "file", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/writer.py#L123-L154
27,376
bootphon/h5features
h5features/writer.py
Writer._prepare
def _prepare(self, data, groupname): """Clear the group if existing and initialize empty datasets.""" if groupname in self.h5file: del self.h5file[groupname] group = self.h5file.create_group(groupname) group.attrs['version'] = self.version data.init_group( group, self.chunk_size, self.compression, self.compression_opts) return group
python
def _prepare(self, data, groupname): if groupname in self.h5file: del self.h5file[groupname] group = self.h5file.create_group(groupname) group.attrs['version'] = self.version data.init_group( group, self.chunk_size, self.compression, self.compression_opts) return group
[ "def", "_prepare", "(", "self", ",", "data", ",", "groupname", ")", ":", "if", "groupname", "in", "self", ".", "h5file", ":", "del", "self", ".", "h5file", "[", "groupname", "]", "group", "=", "self", ".", "h5file", ".", "create_group", "(", "groupname...
Clear the group if existing and initialize empty datasets.
[ "Clear", "the", "group", "if", "existing", "and", "initialize", "empty", "datasets", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/writer.py#L156-L164
27,377
bootphon/h5features
h5features/items.py
read_items
def read_items(group, version='1.1', check=False): """Return an Items instance initialized from a h5features group.""" if version == '0.1': # parse unicode to strings return ''.join( [unichr(int(c)) for c in group['files'][...]] ).replace('/-', '/').split('/\\') elif version == '1.0': return Items(list(group['files'][...]), check) else: return Items(list(group['items'][...]), check)
python
def read_items(group, version='1.1', check=False): if version == '0.1': # parse unicode to strings return ''.join( [unichr(int(c)) for c in group['files'][...]] ).replace('/-', '/').split('/\\') elif version == '1.0': return Items(list(group['files'][...]), check) else: return Items(list(group['items'][...]), check)
[ "def", "read_items", "(", "group", ",", "version", "=", "'1.1'", ",", "check", "=", "False", ")", ":", "if", "version", "==", "'0.1'", ":", "# parse unicode to strings", "return", "''", ".", "join", "(", "[", "unichr", "(", "int", "(", "c", ")", ")", ...
Return an Items instance initialized from a h5features group.
[ "Return", "an", "Items", "instance", "initialized", "from", "a", "h5features", "group", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/items.py#L26-L36
27,378
bootphon/h5features
h5features/items.py
Items.write_to
def write_to(self, group): """Write stored items to the given HDF5 group. We assume that self.create() has been called. """ # The HDF5 group where to write data items_group = group[self.name] nitems = items_group.shape[0] items_group.resize((nitems + len(self.data),)) items_group[nitems:] = self.data
python
def write_to(self, group): # The HDF5 group where to write data items_group = group[self.name] nitems = items_group.shape[0] items_group.resize((nitems + len(self.data),)) items_group[nitems:] = self.data
[ "def", "write_to", "(", "self", ",", "group", ")", ":", "# The HDF5 group where to write data", "items_group", "=", "group", "[", "self", ".", "name", "]", "nitems", "=", "items_group", ".", "shape", "[", "0", "]", "items_group", ".", "resize", "(", "(", "...
Write stored items to the given HDF5 group. We assume that self.create() has been called.
[ "Write", "stored", "items", "to", "the", "given", "HDF5", "group", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/items.py#L68-L79
27,379
bootphon/h5features
h5features/items.py
Items._create_dataset
def _create_dataset( self, group, chunk_size, compression, compression_opts): """Create an empty dataset in a group.""" if chunk_size == 'auto': chunks = True else: # if dtype is a variable str, guess representative size is 20 bytes per_chunk = ( nb_per_chunk(20, 1, chunk_size) if self.dtype == np.dtype('O') else nb_per_chunk( np.dtype(self.dtype).itemsize, 1, chunk_size)) chunks = (per_chunk,) shape = (0,) maxshape = (None,) # raise if per_chunk >= 4 Gb, this is requested by h5py group.create_dataset( self.name, shape, dtype=self.dtype, chunks=chunks, maxshape=maxshape, compression=compression, compression_opts=compression_opts)
python
def _create_dataset( self, group, chunk_size, compression, compression_opts): if chunk_size == 'auto': chunks = True else: # if dtype is a variable str, guess representative size is 20 bytes per_chunk = ( nb_per_chunk(20, 1, chunk_size) if self.dtype == np.dtype('O') else nb_per_chunk( np.dtype(self.dtype).itemsize, 1, chunk_size)) chunks = (per_chunk,) shape = (0,) maxshape = (None,) # raise if per_chunk >= 4 Gb, this is requested by h5py group.create_dataset( self.name, shape, dtype=self.dtype, chunks=chunks, maxshape=maxshape, compression=compression, compression_opts=compression_opts)
[ "def", "_create_dataset", "(", "self", ",", "group", ",", "chunk_size", ",", "compression", ",", "compression_opts", ")", ":", "if", "chunk_size", "==", "'auto'", ":", "chunks", "=", "True", "else", ":", "# if dtype is a variable str, guess representative size is 20 b...
Create an empty dataset in a group.
[ "Create", "an", "empty", "dataset", "in", "a", "group", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/items.py#L91-L111
27,380
bootphon/h5features
h5features/version.py
read_version
def read_version(group): """Return the h5features version of a given HDF5 `group`. Look for a 'version' attribute in the `group` and return its value. Return '0.1' if the version is not found. Raises an IOError if it is not supported. """ version = ('0.1' if 'version' not in group.attrs else group.attrs['version']) # decode from bytes to str if needed if isinstance(version, bytes): version = version.decode() if not is_supported_version(version): raise IOError('version {} is not supported'.format(version)) return version
python
def read_version(group): version = ('0.1' if 'version' not in group.attrs else group.attrs['version']) # decode from bytes to str if needed if isinstance(version, bytes): version = version.decode() if not is_supported_version(version): raise IOError('version {} is not supported'.format(version)) return version
[ "def", "read_version", "(", "group", ")", ":", "version", "=", "(", "'0.1'", "if", "'version'", "not", "in", "group", ".", "attrs", "else", "group", ".", "attrs", "[", "'version'", "]", ")", "# decode from bytes to str if needed", "if", "isinstance", "(", "v...
Return the h5features version of a given HDF5 `group`. Look for a 'version' attribute in the `group` and return its value. Return '0.1' if the version is not found. Raises an IOError if it is not supported.
[ "Return", "the", "h5features", "version", "of", "a", "given", "HDF5", "group", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/version.py#L46-L64
27,381
bootphon/h5features
h5features/reader.py
Reader.read
def read(self, from_item=None, to_item=None, from_time=None, to_time=None): """Retrieve requested data coordinates from the h5features index. :param str from_item: Optional. Read the data starting from this item. (defaults to the first stored item) :param str to_item: Optional. Read the data until reaching the item. (defaults to from_item if it was specified and to the last stored item otherwise). :param float from_time: Optional. (defaults to the beginning time in from_item) The specified times are included in the output. :param float to_time: Optional. (defaults to the ending time in to_item) the specified times are included in the output. :return: An instance of h5features.Data read from the file. """ # handling default arguments if to_item is None: to_item = self.items.data[-1] if from_item is None else from_item if from_item is None: from_item = self.items.data[0] # index coordinates of from/to_item. TODO optimize because we # have 4 accesses to list.index() where 2 are enougth. if not self.items.is_valid_interval(from_item, to_item): raise IOError('cannot read items: not a valid interval') from_idx = self.items.data.index(from_item) to_idx = self.items.data.index(to_item) from_pos = self._get_item_position(from_idx) to_pos = self._get_item_position(to_idx) lower = self._get_from_time(from_time, from_pos) # upper included with +1 upper = self._get_to_time(to_time, to_pos) + 1 # Step 2: access actual data if self.dformat == 'sparse': raise NotImplementedError( 'Reading sparse features not implemented') else: features = (self.group['features'][:, lower:upper].T if self.version == '0.1' else self.group['features'][lower:upper, ...]) labels = self._labels_group[lower:upper] # If we read a single item if to_idx == from_idx: features = [features] labels = [labels] # Several items case: split them from the index else: item_ends = self._index[from_idx:to_idx] - from_pos[0] + 1 features = np.split(features, item_ends, axis=0) labels = np.split(labels, item_ends, axis=0) items = self.items.data[from_idx:to_idx + 1] if self.properties is None: properties = None else: properties = self.properties[from_idx:to_idx + 1] return Data( items, labels, features, properties=properties, check=False)
python
def read(self, from_item=None, to_item=None, from_time=None, to_time=None): # handling default arguments if to_item is None: to_item = self.items.data[-1] if from_item is None else from_item if from_item is None: from_item = self.items.data[0] # index coordinates of from/to_item. TODO optimize because we # have 4 accesses to list.index() where 2 are enougth. if not self.items.is_valid_interval(from_item, to_item): raise IOError('cannot read items: not a valid interval') from_idx = self.items.data.index(from_item) to_idx = self.items.data.index(to_item) from_pos = self._get_item_position(from_idx) to_pos = self._get_item_position(to_idx) lower = self._get_from_time(from_time, from_pos) # upper included with +1 upper = self._get_to_time(to_time, to_pos) + 1 # Step 2: access actual data if self.dformat == 'sparse': raise NotImplementedError( 'Reading sparse features not implemented') else: features = (self.group['features'][:, lower:upper].T if self.version == '0.1' else self.group['features'][lower:upper, ...]) labels = self._labels_group[lower:upper] # If we read a single item if to_idx == from_idx: features = [features] labels = [labels] # Several items case: split them from the index else: item_ends = self._index[from_idx:to_idx] - from_pos[0] + 1 features = np.split(features, item_ends, axis=0) labels = np.split(labels, item_ends, axis=0) items = self.items.data[from_idx:to_idx + 1] if self.properties is None: properties = None else: properties = self.properties[from_idx:to_idx + 1] return Data( items, labels, features, properties=properties, check=False)
[ "def", "read", "(", "self", ",", "from_item", "=", "None", ",", "to_item", "=", "None", ",", "from_time", "=", "None", ",", "to_time", "=", "None", ")", ":", "# handling default arguments", "if", "to_item", "is", "None", ":", "to_item", "=", "self", ".",...
Retrieve requested data coordinates from the h5features index. :param str from_item: Optional. Read the data starting from this item. (defaults to the first stored item) :param str to_item: Optional. Read the data until reaching the item. (defaults to from_item if it was specified and to the last stored item otherwise). :param float from_time: Optional. (defaults to the beginning time in from_item) The specified times are included in the output. :param float to_time: Optional. (defaults to the ending time in to_item) the specified times are included in the output. :return: An instance of h5features.Data read from the file.
[ "Retrieve", "requested", "data", "coordinates", "from", "the", "h5features", "index", "." ]
d5f95db0f1cee58ac1ba4575d1212e796c39e1f9
https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/reader.py#L102-L171
27,382
openai/pachi-py
pachi_py/pachi/tools/twogtp.py
GTP_game.writesgf
def writesgf(self, sgffilename): "Write the game to an SGF file after a game" size = self.size outfile = open(sgffilename, "w") if not outfile: print "Couldn't create " + sgffilename return black_name = self.blackplayer.get_program_name() white_name = self.whiteplayer.get_program_name() black_seed = self.blackplayer.get_random_seed() white_seed = self.whiteplayer.get_random_seed() handicap = self.handicap komi = self.komi result = self.resultw outfile.write("(;GM[1]FF[4]RU[Japanese]SZ[%s]HA[%s]KM[%s]RE[%s]\n" % (size, handicap, komi, result)) outfile.write("PW[%s (random seed %s)]PB[%s (random seed %s)]\n" % (white_name, white_seed, black_name, black_seed)) outfile.write(self.sgffilestart) if handicap > 1: outfile.write("AB"); for stone in self.handicap_stones: outfile.write("[%s]" %(coords_to_sgf(size, stone))) outfile.write("PL[W]\n") to_play = self.first_to_play for move in self.moves: sgfmove = coords_to_sgf(size, move) outfile.write(";%s[%s]\n" % (to_play, sgfmove)) if to_play == "B": to_play = "W" else: to_play = "B" outfile.write(")\n") outfile.close
python
def writesgf(self, sgffilename): "Write the game to an SGF file after a game" size = self.size outfile = open(sgffilename, "w") if not outfile: print "Couldn't create " + sgffilename return black_name = self.blackplayer.get_program_name() white_name = self.whiteplayer.get_program_name() black_seed = self.blackplayer.get_random_seed() white_seed = self.whiteplayer.get_random_seed() handicap = self.handicap komi = self.komi result = self.resultw outfile.write("(;GM[1]FF[4]RU[Japanese]SZ[%s]HA[%s]KM[%s]RE[%s]\n" % (size, handicap, komi, result)) outfile.write("PW[%s (random seed %s)]PB[%s (random seed %s)]\n" % (white_name, white_seed, black_name, black_seed)) outfile.write(self.sgffilestart) if handicap > 1: outfile.write("AB"); for stone in self.handicap_stones: outfile.write("[%s]" %(coords_to_sgf(size, stone))) outfile.write("PL[W]\n") to_play = self.first_to_play for move in self.moves: sgfmove = coords_to_sgf(size, move) outfile.write(";%s[%s]\n" % (to_play, sgfmove)) if to_play == "B": to_play = "W" else: to_play = "B" outfile.write(")\n") outfile.close
[ "def", "writesgf", "(", "self", ",", "sgffilename", ")", ":", "size", "=", "self", ".", "size", "outfile", "=", "open", "(", "sgffilename", ",", "\"w\"", ")", "if", "not", "outfile", ":", "print", "\"Couldn't create \"", "+", "sgffilename", "return", "blac...
Write the game to an SGF file after a game
[ "Write", "the", "game", "to", "an", "SGF", "file", "after", "a", "game" ]
65f29fdd28747d34f2c3001f4016913e4aaeb8fc
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/twogtp.py#L272-L310
27,383
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
_escapeText
def _escapeText(text): """ Adds backslash-escapes to property value characters that need them.""" output = "" index = 0 match = reCharsToEscape.search(text, index) while match: output = output + text[index:match.start()] + '\\' + text[match.start()] index = match.end() match = reCharsToEscape.search(text, index) output = output + text[index:] return output
python
def _escapeText(text): output = "" index = 0 match = reCharsToEscape.search(text, index) while match: output = output + text[index:match.start()] + '\\' + text[match.start()] index = match.end() match = reCharsToEscape.search(text, index) output = output + text[index:] return output
[ "def", "_escapeText", "(", "text", ")", ":", "output", "=", "\"\"", "index", "=", "0", "match", "=", "reCharsToEscape", ".", "search", "(", "text", ",", "index", ")", "while", "match", ":", "output", "=", "output", "+", "text", "[", "index", ":", "ma...
Adds backslash-escapes to property value characters that need them.
[ "Adds", "backslash", "-", "escapes", "to", "property", "value", "characters", "that", "need", "them", "." ]
65f29fdd28747d34f2c3001f4016913e4aaeb8fc
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L579-L589
27,384
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
SGFParser.parse
def parse(self): """ Parses the SGF data stored in 'self.data', and returns a 'Collection'.""" c = Collection() while self.index < self.datalen: g = self.parseOneGame() if g: c.append(g) else: break return c
python
def parse(self): c = Collection() while self.index < self.datalen: g = self.parseOneGame() if g: c.append(g) else: break return c
[ "def", "parse", "(", "self", ")", ":", "c", "=", "Collection", "(", ")", "while", "self", ".", "index", "<", "self", ".", "datalen", ":", "g", "=", "self", ".", "parseOneGame", "(", ")", "if", "g", ":", "c", ".", "append", "(", "g", ")", "else"...
Parses the SGF data stored in 'self.data', and returns a 'Collection'.
[ "Parses", "the", "SGF", "data", "stored", "in", "self", ".", "data", "and", "returns", "a", "Collection", "." ]
65f29fdd28747d34f2c3001f4016913e4aaeb8fc
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L153-L162
27,385
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
SGFParser.parseOneGame
def parseOneGame(self): """ Parses one game from 'self.data'. Returns a 'GameTree' containing one game, or 'None' if the end of 'self.data' has been reached.""" if self.index < self.datalen: match = self.reGameTreeStart.match(self.data, self.index) if match: self.index = match.end() return self.parseGameTree() return None
python
def parseOneGame(self): if self.index < self.datalen: match = self.reGameTreeStart.match(self.data, self.index) if match: self.index = match.end() return self.parseGameTree() return None
[ "def", "parseOneGame", "(", "self", ")", ":", "if", "self", ".", "index", "<", "self", ".", "datalen", ":", "match", "=", "self", ".", "reGameTreeStart", ".", "match", "(", "self", ".", "data", ",", "self", ".", "index", ")", "if", "match", ":", "s...
Parses one game from 'self.data'. Returns a 'GameTree' containing one game, or 'None' if the end of 'self.data' has been reached.
[ "Parses", "one", "game", "from", "self", ".", "data", ".", "Returns", "a", "GameTree", "containing", "one", "game", "or", "None", "if", "the", "end", "of", "self", ".", "data", "has", "been", "reached", "." ]
65f29fdd28747d34f2c3001f4016913e4aaeb8fc
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L164-L172
27,386
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
Cursor.reset
def reset(self): """ Set 'Cursor' to point to the start of the root 'GameTree', 'self.game'.""" self.gametree = self.game self.nodenum = 0 self.index = 0 self.stack = [] self.node = self.gametree[self.index] self._setChildren() self._setFlags()
python
def reset(self): self.gametree = self.game self.nodenum = 0 self.index = 0 self.stack = [] self.node = self.gametree[self.index] self._setChildren() self._setFlags()
[ "def", "reset", "(", "self", ")", ":", "self", ".", "gametree", "=", "self", ".", "game", "self", ".", "nodenum", "=", "0", "self", ".", "index", "=", "0", "self", ".", "stack", "=", "[", "]", "self", ".", "node", "=", "self", ".", "gametree", ...
Set 'Cursor' to point to the start of the root 'GameTree', 'self.game'.
[ "Set", "Cursor", "to", "point", "to", "the", "start", "of", "the", "root", "GameTree", "self", ".", "game", "." ]
65f29fdd28747d34f2c3001f4016913e4aaeb8fc
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L511-L519
27,387
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
Cursor.previous
def previous(self): """ Moves the 'Cursor' to & returns the previous 'Node'. Raises 'GameTreeEndError' if the start of a branch is exceeded.""" if self.index - 1 >= 0: # more main line? self.index = self.index - 1 elif self.stack: # were we in a variation? self.gametree = self.stack.pop() self.index = len(self.gametree) - 1 else: raise GameTreeEndError self.node = self.gametree[self.index] self.nodenum = self.nodenum - 1 self._setChildren() self._setFlags() return self.node
python
def previous(self): if self.index - 1 >= 0: # more main line? self.index = self.index - 1 elif self.stack: # were we in a variation? self.gametree = self.stack.pop() self.index = len(self.gametree) - 1 else: raise GameTreeEndError self.node = self.gametree[self.index] self.nodenum = self.nodenum - 1 self._setChildren() self._setFlags() return self.node
[ "def", "previous", "(", "self", ")", ":", "if", "self", ".", "index", "-", "1", ">=", "0", ":", "# more main line?", "self", ".", "index", "=", "self", ".", "index", "-", "1", "elif", "self", ".", "stack", ":", "# were we in a variation?", "self", ".",...
Moves the 'Cursor' to & returns the previous 'Node'. Raises 'GameTreeEndError' if the start of a branch is exceeded.
[ "Moves", "the", "Cursor", "to", "&", "returns", "the", "previous", "Node", ".", "Raises", "GameTreeEndError", "if", "the", "start", "of", "a", "branch", "is", "exceeded", "." ]
65f29fdd28747d34f2c3001f4016913e4aaeb8fc
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L548-L562
27,388
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
Cursor._setChildren
def _setChildren(self): """ Sets up 'self.children'.""" if self.index + 1 < len(self.gametree): self.children = [self.gametree[self.index+1]] else: self.children = map(lambda list: list[0], self.gametree.variations)
python
def _setChildren(self): if self.index + 1 < len(self.gametree): self.children = [self.gametree[self.index+1]] else: self.children = map(lambda list: list[0], self.gametree.variations)
[ "def", "_setChildren", "(", "self", ")", ":", "if", "self", ".", "index", "+", "1", "<", "len", "(", "self", ".", "gametree", ")", ":", "self", ".", "children", "=", "[", "self", ".", "gametree", "[", "self", ".", "index", "+", "1", "]", "]", "...
Sets up 'self.children'.
[ "Sets", "up", "self", ".", "children", "." ]
65f29fdd28747d34f2c3001f4016913e4aaeb8fc
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L564-L569
27,389
openai/pachi-py
pachi_py/pachi/tools/sgflib/sgflib.py
Cursor._setFlags
def _setFlags(self): """ Sets up the flags 'self.atEnd' and 'self.atStart'.""" self.atEnd = not self.gametree.variations and (self.index + 1 == len(self.gametree)) self.atStart = not self.stack and (self.index == 0)
python
def _setFlags(self): self.atEnd = not self.gametree.variations and (self.index + 1 == len(self.gametree)) self.atStart = not self.stack and (self.index == 0)
[ "def", "_setFlags", "(", "self", ")", ":", "self", ".", "atEnd", "=", "not", "self", ".", "gametree", ".", "variations", "and", "(", "self", ".", "index", "+", "1", "==", "len", "(", "self", ".", "gametree", ")", ")", "self", ".", "atStart", "=", ...
Sets up the flags 'self.atEnd' and 'self.atStart'.
[ "Sets", "up", "the", "flags", "self", ".", "atEnd", "and", "self", ".", "atStart", "." ]
65f29fdd28747d34f2c3001f4016913e4aaeb8fc
https://github.com/openai/pachi-py/blob/65f29fdd28747d34f2c3001f4016913e4aaeb8fc/pachi_py/pachi/tools/sgflib/sgflib.py#L571-L574
27,390
cjdrake/pyeda
pyeda/logic/addition.py
ripple_carry_add
def ripple_carry_add(A, B, cin=0): """Return symbolic logic for an N-bit ripple carry adder.""" if len(A) != len(B): raise ValueError("expected A and B to be equal length") ss, cs = list(), list() for i, a in enumerate(A): c = (cin if i == 0 else cs[i-1]) ss.append(a ^ B[i] ^ c) cs.append(a & B[i] | a & c | B[i] & c) return farray(ss), farray(cs)
python
def ripple_carry_add(A, B, cin=0): if len(A) != len(B): raise ValueError("expected A and B to be equal length") ss, cs = list(), list() for i, a in enumerate(A): c = (cin if i == 0 else cs[i-1]) ss.append(a ^ B[i] ^ c) cs.append(a & B[i] | a & c | B[i] & c) return farray(ss), farray(cs)
[ "def", "ripple_carry_add", "(", "A", ",", "B", ",", "cin", "=", "0", ")", ":", "if", "len", "(", "A", ")", "!=", "len", "(", "B", ")", ":", "raise", "ValueError", "(", "\"expected A and B to be equal length\"", ")", "ss", ",", "cs", "=", "list", "(",...
Return symbolic logic for an N-bit ripple carry adder.
[ "Return", "symbolic", "logic", "for", "an", "N", "-", "bit", "ripple", "carry", "adder", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/addition.py#L21-L30
27,391
cjdrake/pyeda
pyeda/logic/addition.py
kogge_stone_add
def kogge_stone_add(A, B, cin=0): """Return symbolic logic for an N-bit Kogge-Stone adder.""" if len(A) != len(B): raise ValueError("expected A and B to be equal length") N = len(A) # generate/propagate logic gs = [A[i] & B[i] for i in range(N)] ps = [A[i] ^ B[i] for i in range(N)] for i in range(clog2(N)): start = 1 << i for j in range(start, N): gs[j] = gs[j] | ps[j] & gs[j-start] ps[j] = ps[j] & ps[j-start] # sum logic ss = [A[0] ^ B[0] ^ cin] ss += [A[i] ^ B[i] ^ gs[i-1] for i in range(1, N)] return farray(ss), farray(gs)
python
def kogge_stone_add(A, B, cin=0): if len(A) != len(B): raise ValueError("expected A and B to be equal length") N = len(A) # generate/propagate logic gs = [A[i] & B[i] for i in range(N)] ps = [A[i] ^ B[i] for i in range(N)] for i in range(clog2(N)): start = 1 << i for j in range(start, N): gs[j] = gs[j] | ps[j] & gs[j-start] ps[j] = ps[j] & ps[j-start] # sum logic ss = [A[0] ^ B[0] ^ cin] ss += [A[i] ^ B[i] ^ gs[i-1] for i in range(1, N)] return farray(ss), farray(gs)
[ "def", "kogge_stone_add", "(", "A", ",", "B", ",", "cin", "=", "0", ")", ":", "if", "len", "(", "A", ")", "!=", "len", "(", "B", ")", ":", "raise", "ValueError", "(", "\"expected A and B to be equal length\"", ")", "N", "=", "len", "(", "A", ")", "...
Return symbolic logic for an N-bit Kogge-Stone adder.
[ "Return", "symbolic", "logic", "for", "an", "N", "-", "bit", "Kogge", "-", "Stone", "adder", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/addition.py#L33-L49
27,392
cjdrake/pyeda
pyeda/logic/addition.py
brent_kung_add
def brent_kung_add(A, B, cin=0): """Return symbolic logic for an N-bit Brent-Kung adder.""" if len(A) != len(B): raise ValueError("expected A and B to be equal length") N = len(A) # generate/propagate logic gs = [A[i] & B[i] for i in range(N)] ps = [A[i] ^ B[i] for i in range(N)] # carry tree for i in range(floor(log(N, 2))): step = 2**i for start in range(2**(i+1)-1, N, 2**(i+1)): gs[start] = gs[start] | ps[start] & gs[start-step] ps[start] = ps[start] & ps[start-step] # inverse carry tree for i in range(floor(log(N, 2))-2, -1, -1): start = 2**(i+1)-1 step = 2**i while start + step < N: gs[start+step] = gs[start+step] | ps[start+step] & gs[start] ps[start+step] = ps[start+step] & ps[start] start += step # sum logic ss = [A[0] ^ B[0] ^ cin] ss += [A[i] ^ B[i] ^ gs[i-1] for i in range(1, N)] return farray(ss), farray(gs)
python
def brent_kung_add(A, B, cin=0): if len(A) != len(B): raise ValueError("expected A and B to be equal length") N = len(A) # generate/propagate logic gs = [A[i] & B[i] for i in range(N)] ps = [A[i] ^ B[i] for i in range(N)] # carry tree for i in range(floor(log(N, 2))): step = 2**i for start in range(2**(i+1)-1, N, 2**(i+1)): gs[start] = gs[start] | ps[start] & gs[start-step] ps[start] = ps[start] & ps[start-step] # inverse carry tree for i in range(floor(log(N, 2))-2, -1, -1): start = 2**(i+1)-1 step = 2**i while start + step < N: gs[start+step] = gs[start+step] | ps[start+step] & gs[start] ps[start+step] = ps[start+step] & ps[start] start += step # sum logic ss = [A[0] ^ B[0] ^ cin] ss += [A[i] ^ B[i] ^ gs[i-1] for i in range(1, N)] return farray(ss), farray(gs)
[ "def", "brent_kung_add", "(", "A", ",", "B", ",", "cin", "=", "0", ")", ":", "if", "len", "(", "A", ")", "!=", "len", "(", "B", ")", ":", "raise", "ValueError", "(", "\"expected A and B to be equal length\"", ")", "N", "=", "len", "(", "A", ")", "#...
Return symbolic logic for an N-bit Brent-Kung adder.
[ "Return", "symbolic", "logic", "for", "an", "N", "-", "bit", "Brent", "-", "Kung", "adder", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/logic/addition.py#L52-L77
27,393
cjdrake/pyeda
pyeda/parsing/dimacs.py
_expect_token
def _expect_token(lexer, types): """Return the next token, or raise an exception.""" tok = next(lexer) if any(isinstance(tok, t) for t in types): return tok else: raise Error("unexpected token: " + str(tok))
python
def _expect_token(lexer, types): tok = next(lexer) if any(isinstance(tok, t) for t in types): return tok else: raise Error("unexpected token: " + str(tok))
[ "def", "_expect_token", "(", "lexer", ",", "types", ")", ":", "tok", "=", "next", "(", "lexer", ")", "if", "any", "(", "isinstance", "(", "tok", ",", "t", ")", "for", "t", "in", "types", ")", ":", "return", "tok", "else", ":", "raise", "Error", "...
Return the next token, or raise an exception.
[ "Return", "the", "next", "token", "or", "raise", "an", "exception", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L134-L140
27,394
cjdrake/pyeda
pyeda/parsing/dimacs.py
parse_cnf
def parse_cnf(s, varname='x'): """ Parse an input string in DIMACS CNF format, and return an expression abstract syntax tree. Parameters ---------- s : str String containing a DIMACS CNF. varname : str, optional The variable name used for creating literals. Defaults to 'x'. Returns ------- An ast tuple, defined recursively: ast := ('var', names, indices) | ('not', ast) | ('or', ast, ...) | ('and', ast, ...) names := (name, ...) indices := (index, ...) """ lexer = iter(CNFLexer(s)) try: ast = _cnf(lexer, varname) except lex.RunError as exc: fstr = ("{0.args[0]}: " "(line: {0.lineno}, offset: {0.offset}, text: {0.text})") raise Error(fstr.format(exc)) # Check for end of buffer _expect_token(lexer, {EndToken}) return ast
python
def parse_cnf(s, varname='x'): lexer = iter(CNFLexer(s)) try: ast = _cnf(lexer, varname) except lex.RunError as exc: fstr = ("{0.args[0]}: " "(line: {0.lineno}, offset: {0.offset}, text: {0.text})") raise Error(fstr.format(exc)) # Check for end of buffer _expect_token(lexer, {EndToken}) return ast
[ "def", "parse_cnf", "(", "s", ",", "varname", "=", "'x'", ")", ":", "lexer", "=", "iter", "(", "CNFLexer", "(", "s", ")", ")", "try", ":", "ast", "=", "_cnf", "(", "lexer", ",", "varname", ")", "except", "lex", ".", "RunError", "as", "exc", ":", ...
Parse an input string in DIMACS CNF format, and return an expression abstract syntax tree. Parameters ---------- s : str String containing a DIMACS CNF. varname : str, optional The variable name used for creating literals. Defaults to 'x'. Returns ------- An ast tuple, defined recursively: ast := ('var', names, indices) | ('not', ast) | ('or', ast, ...) | ('and', ast, ...) names := (name, ...) indices := (index, ...)
[ "Parse", "an", "input", "string", "in", "DIMACS", "CNF", "format", "and", "return", "an", "expression", "abstract", "syntax", "tree", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L143-L181
27,395
cjdrake/pyeda
pyeda/parsing/dimacs.py
_cnf
def _cnf(lexer, varname): """Return a DIMACS CNF.""" _expect_token(lexer, {KW_p}) _expect_token(lexer, {KW_cnf}) nvars = _expect_token(lexer, {IntegerToken}).value nclauses = _expect_token(lexer, {IntegerToken}).value return _cnf_formula(lexer, varname, nvars, nclauses)
python
def _cnf(lexer, varname): _expect_token(lexer, {KW_p}) _expect_token(lexer, {KW_cnf}) nvars = _expect_token(lexer, {IntegerToken}).value nclauses = _expect_token(lexer, {IntegerToken}).value return _cnf_formula(lexer, varname, nvars, nclauses)
[ "def", "_cnf", "(", "lexer", ",", "varname", ")", ":", "_expect_token", "(", "lexer", ",", "{", "KW_p", "}", ")", "_expect_token", "(", "lexer", ",", "{", "KW_cnf", "}", ")", "nvars", "=", "_expect_token", "(", "lexer", ",", "{", "IntegerToken", "}", ...
Return a DIMACS CNF.
[ "Return", "a", "DIMACS", "CNF", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L184-L190
27,396
cjdrake/pyeda
pyeda/parsing/dimacs.py
_cnf_formula
def _cnf_formula(lexer, varname, nvars, nclauses): """Return a DIMACS CNF formula.""" clauses = _clauses(lexer, varname, nvars) if len(clauses) < nclauses: fstr = "formula has fewer than {} clauses" raise Error(fstr.format(nclauses)) if len(clauses) > nclauses: fstr = "formula has more than {} clauses" raise Error(fstr.format(nclauses)) return ('and', ) + clauses
python
def _cnf_formula(lexer, varname, nvars, nclauses): clauses = _clauses(lexer, varname, nvars) if len(clauses) < nclauses: fstr = "formula has fewer than {} clauses" raise Error(fstr.format(nclauses)) if len(clauses) > nclauses: fstr = "formula has more than {} clauses" raise Error(fstr.format(nclauses)) return ('and', ) + clauses
[ "def", "_cnf_formula", "(", "lexer", ",", "varname", ",", "nvars", ",", "nclauses", ")", ":", "clauses", "=", "_clauses", "(", "lexer", ",", "varname", ",", "nvars", ")", "if", "len", "(", "clauses", ")", "<", "nclauses", ":", "fstr", "=", "\"formula h...
Return a DIMACS CNF formula.
[ "Return", "a", "DIMACS", "CNF", "formula", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L193-L204
27,397
cjdrake/pyeda
pyeda/parsing/dimacs.py
_clauses
def _clauses(lexer, varname, nvars): """Return a tuple of DIMACS CNF clauses.""" tok = next(lexer) toktype = type(tok) if toktype is OP_not or toktype is IntegerToken: lexer.unpop_token(tok) first = _clause(lexer, varname, nvars) rest = _clauses(lexer, varname, nvars) return (first, ) + rest # null else: lexer.unpop_token(tok) return tuple()
python
def _clauses(lexer, varname, nvars): tok = next(lexer) toktype = type(tok) if toktype is OP_not or toktype is IntegerToken: lexer.unpop_token(tok) first = _clause(lexer, varname, nvars) rest = _clauses(lexer, varname, nvars) return (first, ) + rest # null else: lexer.unpop_token(tok) return tuple()
[ "def", "_clauses", "(", "lexer", ",", "varname", ",", "nvars", ")", ":", "tok", "=", "next", "(", "lexer", ")", "toktype", "=", "type", "(", "tok", ")", "if", "toktype", "is", "OP_not", "or", "toktype", "is", "IntegerToken", ":", "lexer", ".", "unpop...
Return a tuple of DIMACS CNF clauses.
[ "Return", "a", "tuple", "of", "DIMACS", "CNF", "clauses", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L207-L219
27,398
cjdrake/pyeda
pyeda/parsing/dimacs.py
_lits
def _lits(lexer, varname, nvars): """Return a tuple of DIMACS CNF clause literals.""" tok = _expect_token(lexer, {OP_not, IntegerToken}) if isinstance(tok, IntegerToken) and tok.value == 0: return tuple() else: if isinstance(tok, OP_not): neg = True tok = _expect_token(lexer, {IntegerToken}) else: neg = False index = tok.value if index > nvars: fstr = "formula literal {} is greater than {}" raise Error(fstr.format(index, nvars)) lit = ('var', (varname, ), (index, )) if neg: lit = ('not', lit) return (lit, ) + _lits(lexer, varname, nvars)
python
def _lits(lexer, varname, nvars): tok = _expect_token(lexer, {OP_not, IntegerToken}) if isinstance(tok, IntegerToken) and tok.value == 0: return tuple() else: if isinstance(tok, OP_not): neg = True tok = _expect_token(lexer, {IntegerToken}) else: neg = False index = tok.value if index > nvars: fstr = "formula literal {} is greater than {}" raise Error(fstr.format(index, nvars)) lit = ('var', (varname, ), (index, )) if neg: lit = ('not', lit) return (lit, ) + _lits(lexer, varname, nvars)
[ "def", "_lits", "(", "lexer", ",", "varname", ",", "nvars", ")", ":", "tok", "=", "_expect_token", "(", "lexer", ",", "{", "OP_not", ",", "IntegerToken", "}", ")", "if", "isinstance", "(", "tok", ",", "IntegerToken", ")", "and", "tok", ".", "value", ...
Return a tuple of DIMACS CNF clause literals.
[ "Return", "a", "tuple", "of", "DIMACS", "CNF", "clause", "literals", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L227-L248
27,399
cjdrake/pyeda
pyeda/parsing/dimacs.py
parse_sat
def parse_sat(s, varname='x'): """ Parse an input string in DIMACS SAT format, and return an expression. """ lexer = iter(SATLexer(s)) try: ast = _sat(lexer, varname) except lex.RunError as exc: fstr = ("{0.args[0]}: " "(line: {0.lineno}, offset: {0.offset}, text: {0.text})") raise Error(fstr.format(exc)) # Check for end of buffer _expect_token(lexer, {EndToken}) return ast
python
def parse_sat(s, varname='x'): lexer = iter(SATLexer(s)) try: ast = _sat(lexer, varname) except lex.RunError as exc: fstr = ("{0.args[0]}: " "(line: {0.lineno}, offset: {0.offset}, text: {0.text})") raise Error(fstr.format(exc)) # Check for end of buffer _expect_token(lexer, {EndToken}) return ast
[ "def", "parse_sat", "(", "s", ",", "varname", "=", "'x'", ")", ":", "lexer", "=", "iter", "(", "SATLexer", "(", "s", ")", ")", "try", ":", "ast", "=", "_sat", "(", "lexer", ",", "varname", ")", "except", "lex", ".", "RunError", "as", "exc", ":", ...
Parse an input string in DIMACS SAT format, and return an expression.
[ "Parse", "an", "input", "string", "in", "DIMACS", "SAT", "format", "and", "return", "an", "expression", "." ]
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/dimacs.py#L357-L374