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
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
227,000
google/openhtf
openhtf/plugs/usb/__init__.py
_open_usb_handle
def _open_usb_handle(serial_number=None, **kwargs): """Open a UsbHandle subclass, based on configuration. If configuration 'remote_usb' is set, use it to connect to remote usb, otherwise attempt to connect locally.'remote_usb' is set to usb type, EtherSync or other. Example of Cambrionix unit in config: r...
python
def _open_usb_handle(serial_number=None, **kwargs): """Open a UsbHandle subclass, based on configuration. If configuration 'remote_usb' is set, use it to connect to remote usb, otherwise attempt to connect locally.'remote_usb' is set to usb type, EtherSync or other. Example of Cambrionix unit in config: r...
[ "def", "_open_usb_handle", "(", "serial_number", "=", "None", ",", "*", "*", "kwargs", ")", ":", "init_dependent_flags", "(", ")", "remote_usb", "=", "conf", ".", "remote_usb", "if", "remote_usb", ":", "if", "remote_usb", ".", "strip", "(", ")", "==", "'et...
Open a UsbHandle subclass, based on configuration. If configuration 'remote_usb' is set, use it to connect to remote usb, otherwise attempt to connect locally.'remote_usb' is set to usb type, EtherSync or other. Example of Cambrionix unit in config: remote_usb: ethersync ethersync: mac_addr: 78:a5:...
[ "Open", "a", "UsbHandle", "subclass", "based", "on", "configuration", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/__init__.py#L62-L96
227,001
google/openhtf
openhtf/plugs/usb/__init__.py
AndroidTriggers._try_open
def _try_open(cls): """Try to open a USB handle.""" handle = None for usb_cls, subcls, protocol in [(adb_device.CLASS, adb_device.SUBCLASS, adb_device.PROTOCOL), (fastboot_device.CLASS, ...
python
def _try_open(cls): """Try to open a USB handle.""" handle = None for usb_cls, subcls, protocol in [(adb_device.CLASS, adb_device.SUBCLASS, adb_device.PROTOCOL), (fastboot_device.CLASS, ...
[ "def", "_try_open", "(", "cls", ")", ":", "handle", "=", "None", "for", "usb_cls", ",", "subcls", ",", "protocol", "in", "[", "(", "adb_device", ".", "CLASS", ",", "adb_device", ".", "SUBCLASS", ",", "adb_device", ".", "PROTOCOL", ")", ",", "(", "fastb...
Try to open a USB handle.
[ "Try", "to", "open", "a", "USB", "handle", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/__init__.py#L164-L188
227,002
google/openhtf
openhtf/plugs/usb/fastboot_device.py
_retry_usb_function
def _retry_usb_function(count, func, *args, **kwargs): """Helper function to retry USB.""" helper = timeouts.RetryHelper(count) while True: try: return func(*args, **kwargs) except usb_exceptions.CommonUsbError: if not helper.retry_if_possible(): raise time.sleep(0.1) else: ...
python
def _retry_usb_function(count, func, *args, **kwargs): """Helper function to retry USB.""" helper = timeouts.RetryHelper(count) while True: try: return func(*args, **kwargs) except usb_exceptions.CommonUsbError: if not helper.retry_if_possible(): raise time.sleep(0.1) else: ...
[ "def", "_retry_usb_function", "(", "count", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "helper", "=", "timeouts", ".", "RetryHelper", "(", "count", ")", "while", "True", ":", "try", ":", "return", "func", "(", "*", "args", ",",...
Helper function to retry USB.
[ "Helper", "function", "to", "retry", "USB", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/fastboot_device.py#L112-L123
227,003
google/openhtf
openhtf/plugs/usb/fastboot_device.py
FastbootDevice.get_boot_config
def get_boot_config(self, name, info_cb=None): """Get bootconfig, either as full dict or specific value for key.""" result = {} def default_info_cb(msg): """Default Info CB.""" if not msg.message: return key, value = msg.message.split(':', 1) result[key.strip()] = value.strip...
python
def get_boot_config(self, name, info_cb=None): """Get bootconfig, either as full dict or specific value for key.""" result = {} def default_info_cb(msg): """Default Info CB.""" if not msg.message: return key, value = msg.message.split(':', 1) result[key.strip()] = value.strip...
[ "def", "get_boot_config", "(", "self", ",", "name", ",", "info_cb", "=", "None", ")", ":", "result", "=", "{", "}", "def", "default_info_cb", "(", "msg", ")", ":", "\"\"\"Default Info CB.\"\"\"", "if", "not", "msg", ".", "message", ":", "return", "key", ...
Get bootconfig, either as full dict or specific value for key.
[ "Get", "bootconfig", "either", "as", "full", "dict", "or", "specific", "value", "for", "key", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/fastboot_device.py#L49-L63
227,004
google/openhtf
openhtf/plugs/usb/local_usb.py
LibUsbHandle._device_to_sysfs_path
def _device_to_sysfs_path(device): """Convert device to corresponding sysfs path.""" return '%s-%s' % ( device.getBusNumber(), '.'.join([str(item) for item in device.GetPortNumberList()]))
python
def _device_to_sysfs_path(device): """Convert device to corresponding sysfs path.""" return '%s-%s' % ( device.getBusNumber(), '.'.join([str(item) for item in device.GetPortNumberList()]))
[ "def", "_device_to_sysfs_path", "(", "device", ")", ":", "return", "'%s-%s'", "%", "(", "device", ".", "getBusNumber", "(", ")", ",", "'.'", ".", "join", "(", "[", "str", "(", "item", ")", "for", "item", "in", "device", ".", "GetPortNumberList", "(", "...
Convert device to corresponding sysfs path.
[ "Convert", "device", "to", "corresponding", "sysfs", "path", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/local_usb.py#L112-L116
227,005
google/openhtf
openhtf/plugs/usb/local_usb.py
LibUsbHandle.open
def open(cls, **kwargs): """See iter_open, but raises if multiple or no matches found.""" handle_iter = cls.iter_open(**kwargs) try: handle = six.next(handle_iter) except StopIteration: # No matching interface, raise. raise usb_exceptions.DeviceNotFoundError( 'Open failed wi...
python
def open(cls, **kwargs): """See iter_open, but raises if multiple or no matches found.""" handle_iter = cls.iter_open(**kwargs) try: handle = six.next(handle_iter) except StopIteration: # No matching interface, raise. raise usb_exceptions.DeviceNotFoundError( 'Open failed wi...
[ "def", "open", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "handle_iter", "=", "cls", ".", "iter_open", "(", "*", "*", "kwargs", ")", "try", ":", "handle", "=", "six", ".", "next", "(", "handle_iter", ")", "except", "StopIteration", ":", "# No mat...
See iter_open, but raises if multiple or no matches found.
[ "See", "iter_open", "but", "raises", "if", "multiple", "or", "no", "matches", "found", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/local_usb.py#L158-L178
227,006
google/openhtf
openhtf/plugs/usb/local_usb.py
LibUsbHandle.iter_open
def iter_open(cls, name=None, interface_class=None, interface_subclass=None, interface_protocol=None, serial_number=None, port_path=None, default_timeout_ms=None): """Find and yield locally connected devices that match. Note that devices are opened (and interfaces claimd) as the...
python
def iter_open(cls, name=None, interface_class=None, interface_subclass=None, interface_protocol=None, serial_number=None, port_path=None, default_timeout_ms=None): """Find and yield locally connected devices that match. Note that devices are opened (and interfaces claimd) as the...
[ "def", "iter_open", "(", "cls", ",", "name", "=", "None", ",", "interface_class", "=", "None", ",", "interface_subclass", "=", "None", ",", "interface_protocol", "=", "None", ",", "serial_number", "=", "None", ",", "port_path", "=", "None", ",", "default_tim...
Find and yield locally connected devices that match. Note that devices are opened (and interfaces claimd) as they are yielded. Any devices yielded must be Close()'d. Args: name: Name to give *all* returned handles, used for logging only. interface_class: USB interface_class to match. int...
[ "Find", "and", "yield", "locally", "connected", "devices", "that", "match", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/local_usb.py#L182-L241
227,007
google/openhtf
examples/all_the_things.py
hello_world
def hello_world(test, example, prompts): """A hello world test phase.""" test.logger.info('Hello World!') test.measurements.widget_type = prompts.prompt( 'What\'s the widget type? (Hint: try `MyWidget` to PASS)', text_input=True) if test.measurements.widget_type == 'raise': raise Exception() t...
python
def hello_world(test, example, prompts): """A hello world test phase.""" test.logger.info('Hello World!') test.measurements.widget_type = prompts.prompt( 'What\'s the widget type? (Hint: try `MyWidget` to PASS)', text_input=True) if test.measurements.widget_type == 'raise': raise Exception() t...
[ "def", "hello_world", "(", "test", ",", "example", ",", "prompts", ")", ":", "test", ".", "logger", ".", "info", "(", "'Hello World!'", ")", "test", ".", "measurements", ".", "widget_type", "=", "prompts", ".", "prompt", "(", "'What\\'s the widget type? (Hint:...
A hello world test phase.
[ "A", "hello", "world", "test", "phase", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/examples/all_the_things.py#L55-L66
227,008
google/openhtf
examples/all_the_things.py
set_measurements
def set_measurements(test): """Test phase that sets a measurement.""" test.measurements.level_none = 0 time.sleep(1) test.measurements.level_some = 8 time.sleep(1) test.measurements.level_all = 9 time.sleep(1) level_all = test.get_measurement('level_all') assert level_all.value == 9
python
def set_measurements(test): """Test phase that sets a measurement.""" test.measurements.level_none = 0 time.sleep(1) test.measurements.level_some = 8 time.sleep(1) test.measurements.level_all = 9 time.sleep(1) level_all = test.get_measurement('level_all') assert level_all.value == 9
[ "def", "set_measurements", "(", "test", ")", ":", "test", ".", "measurements", ".", "level_none", "=", "0", "time", ".", "sleep", "(", "1", ")", "test", ".", "measurements", ".", "level_some", "=", "8", "time", ".", "sleep", "(", "1", ")", "test", "....
Test phase that sets a measurement.
[ "Test", "phase", "that", "sets", "a", "measurement", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/examples/all_the_things.py#L75-L84
227,009
google/openhtf
openhtf/util/data.py
pprint_diff
def pprint_diff(first, second, first_name='first', second_name='second'): """Compare the pprint representation of two objects and yield diff lines.""" return difflib.unified_diff( pprint.pformat(first).splitlines(), pprint.pformat(second).splitlines(), fromfile=first_name, tofile=second_name, line...
python
def pprint_diff(first, second, first_name='first', second_name='second'): """Compare the pprint representation of two objects and yield diff lines.""" return difflib.unified_diff( pprint.pformat(first).splitlines(), pprint.pformat(second).splitlines(), fromfile=first_name, tofile=second_name, line...
[ "def", "pprint_diff", "(", "first", ",", "second", ",", "first_name", "=", "'first'", ",", "second_name", "=", "'second'", ")", ":", "return", "difflib", ".", "unified_diff", "(", "pprint", ".", "pformat", "(", "first", ")", ".", "splitlines", "(", ")", ...
Compare the pprint representation of two objects and yield diff lines.
[ "Compare", "the", "pprint", "representation", "of", "two", "objects", "and", "yield", "diff", "lines", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/data.py#L42-L47
227,010
google/openhtf
openhtf/util/data.py
equals_log_diff
def equals_log_diff(expected, actual, level=logging.ERROR): """Compare two string blobs, error log diff if they don't match.""" if expected == actual: return True # Output the diff first. logging.log(level, '***** Data mismatch: *****') for line in difflib.unified_diff( expected.splitlines(), actua...
python
def equals_log_diff(expected, actual, level=logging.ERROR): """Compare two string blobs, error log diff if they don't match.""" if expected == actual: return True # Output the diff first. logging.log(level, '***** Data mismatch: *****') for line in difflib.unified_diff( expected.splitlines(), actua...
[ "def", "equals_log_diff", "(", "expected", ",", "actual", ",", "level", "=", "logging", ".", "ERROR", ")", ":", "if", "expected", "==", "actual", ":", "return", "True", "# Output the diff first.", "logging", ".", "log", "(", "level", ",", "'***** Data mismatch...
Compare two string blobs, error log diff if they don't match.
[ "Compare", "two", "string", "blobs", "error", "log", "diff", "if", "they", "don", "t", "match", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/data.py#L50-L61
227,011
google/openhtf
openhtf/util/data.py
assert_records_equal_nonvolatile
def assert_records_equal_nonvolatile(first, second, volatile_fields, indent=0): """Compare two test_record tuples, ignoring any volatile fields. 'Volatile' fields include any fields that are expected to differ between successive runs of the same test, mainly timestamps. All other fields are recursively compar...
python
def assert_records_equal_nonvolatile(first, second, volatile_fields, indent=0): """Compare two test_record tuples, ignoring any volatile fields. 'Volatile' fields include any fields that are expected to differ between successive runs of the same test, mainly timestamps. All other fields are recursively compar...
[ "def", "assert_records_equal_nonvolatile", "(", "first", ",", "second", ",", "volatile_fields", ",", "indent", "=", "0", ")", ":", "if", "isinstance", "(", "first", ",", "dict", ")", "and", "isinstance", "(", "second", ",", "dict", ")", ":", "if", "set", ...
Compare two test_record tuples, ignoring any volatile fields. 'Volatile' fields include any fields that are expected to differ between successive runs of the same test, mainly timestamps. All other fields are recursively compared.
[ "Compare", "two", "test_record", "tuples", "ignoring", "any", "volatile", "fields", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/data.py#L64-L105
227,012
google/openhtf
openhtf/util/data.py
convert_to_base_types
def convert_to_base_types(obj, ignore_keys=tuple(), tuple_type=tuple, json_safe=True): """Recursively convert objects into base types. This is used to convert some special types of objects used internally into base types for more friendly output via mechanisms such as JSON. It is used ...
python
def convert_to_base_types(obj, ignore_keys=tuple(), tuple_type=tuple, json_safe=True): """Recursively convert objects into base types. This is used to convert some special types of objects used internally into base types for more friendly output via mechanisms such as JSON. It is used ...
[ "def", "convert_to_base_types", "(", "obj", ",", "ignore_keys", "=", "tuple", "(", ")", ",", "tuple_type", "=", "tuple", ",", "json_safe", "=", "True", ")", ":", "# Because it's *really* annoying to pass a single string accidentally.", "assert", "not", "isinstance", "...
Recursively convert objects into base types. This is used to convert some special types of objects used internally into base types for more friendly output via mechanisms such as JSON. It is used for sending internal objects via the network and outputting test records. Specifically, the conversions that are p...
[ "Recursively", "convert", "objects", "into", "base", "types", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/data.py#L108-L186
227,013
google/openhtf
openhtf/util/data.py
total_size
def total_size(obj): """Returns the approximate total memory footprint an object.""" seen = set() def sizeof(current_obj): try: return _sizeof(current_obj) except Exception: # pylint: disable=broad-except # Not sure what just happened, but let's assume it's a reference. return struct.ca...
python
def total_size(obj): """Returns the approximate total memory footprint an object.""" seen = set() def sizeof(current_obj): try: return _sizeof(current_obj) except Exception: # pylint: disable=broad-except # Not sure what just happened, but let's assume it's a reference. return struct.ca...
[ "def", "total_size", "(", "obj", ")", ":", "seen", "=", "set", "(", ")", "def", "sizeof", "(", "current_obj", ")", ":", "try", ":", "return", "_sizeof", "(", "current_obj", ")", "except", "Exception", ":", "# pylint: disable=broad-except", "# Not sure what jus...
Returns the approximate total memory footprint an object.
[ "Returns", "the", "approximate", "total", "memory", "footprint", "an", "object", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/data.py#L189-L218
227,014
google/openhtf
openhtf/output/callbacks/__init__.py
OutputToFile.open_output_file
def open_output_file(self, test_record): """Open file based on pattern.""" # Ignore keys for the log filename to not convert larger data structures. record_dict = data.convert_to_base_types( test_record, ignore_keys=('code_info', 'phases', 'log_records')) pattern = self.filename_pattern if i...
python
def open_output_file(self, test_record): """Open file based on pattern.""" # Ignore keys for the log filename to not convert larger data structures. record_dict = data.convert_to_base_types( test_record, ignore_keys=('code_info', 'phases', 'log_records')) pattern = self.filename_pattern if i...
[ "def", "open_output_file", "(", "self", ",", "test_record", ")", ":", "# Ignore keys for the log filename to not convert larger data structures.", "record_dict", "=", "data", ".", "convert_to_base_types", "(", "test_record", ",", "ignore_keys", "=", "(", "'code_info'", ",",...
Open file based on pattern.
[ "Open", "file", "based", "on", "pattern", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/callbacks/__init__.py#L82-L98
227,015
google/openhtf
pylint_plugins/mutablerecords_plugin.py
mutable_record_transform
def mutable_record_transform(cls): """Transform mutable records usage by updating locals.""" if not (len(cls.bases) > 0 and isinstance(cls.bases[0], astroid.Call) and cls.bases[0].func.as_string() == 'mutablerecords.Record'): return try: # Add required attributes. if len(cls.bases...
python
def mutable_record_transform(cls): """Transform mutable records usage by updating locals.""" if not (len(cls.bases) > 0 and isinstance(cls.bases[0], astroid.Call) and cls.bases[0].func.as_string() == 'mutablerecords.Record'): return try: # Add required attributes. if len(cls.bases...
[ "def", "mutable_record_transform", "(", "cls", ")", ":", "if", "not", "(", "len", "(", "cls", ".", "bases", ")", ">", "0", "and", "isinstance", "(", "cls", ".", "bases", "[", "0", "]", ",", "astroid", ".", "Call", ")", "and", "cls", ".", "bases", ...
Transform mutable records usage by updating locals.
[ "Transform", "mutable", "records", "usage", "by", "updating", "locals", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/pylint_plugins/mutablerecords_plugin.py#L25-L44
227,016
google/openhtf
openhtf/util/__init__.py
_log_every_n_to_logger
def _log_every_n_to_logger(n, logger, level, message, *args): # pylint: disable=invalid-name """Logs the given message every n calls to a logger. Args: n: Number of calls before logging. logger: The logger to which to log. level: The logging level (e.g. logging.INFO). message: A message to log ...
python
def _log_every_n_to_logger(n, logger, level, message, *args): # pylint: disable=invalid-name """Logs the given message every n calls to a logger. Args: n: Number of calls before logging. logger: The logger to which to log. level: The logging level (e.g. logging.INFO). message: A message to log ...
[ "def", "_log_every_n_to_logger", "(", "n", ",", "logger", ",", "level", ",", "message", ",", "*", "args", ")", ":", "# pylint: disable=invalid-name", "logger", "=", "logger", "or", "logging", ".", "getLogger", "(", ")", "def", "_gen", "(", ")", ":", "# pyl...
Logs the given message every n calls to a logger. Args: n: Number of calls before logging. logger: The logger to which to log. level: The logging level (e.g. logging.INFO). message: A message to log *args: Any format args for the message. Returns: A method that logs and returns True every n...
[ "Logs", "the", "given", "message", "every", "n", "calls", "to", "a", "logger", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/__init__.py#L29-L49
227,017
google/openhtf
openhtf/util/__init__.py
log_every_n
def log_every_n(n, level, message, *args): # pylint: disable=invalid-name """Logs a message every n calls. See _log_every_n_to_logger.""" return _log_every_n_to_logger(n, None, level, message, *args)
python
def log_every_n(n, level, message, *args): # pylint: disable=invalid-name """Logs a message every n calls. See _log_every_n_to_logger.""" return _log_every_n_to_logger(n, None, level, message, *args)
[ "def", "log_every_n", "(", "n", ",", "level", ",", "message", ",", "*", "args", ")", ":", "# pylint: disable=invalid-name", "return", "_log_every_n_to_logger", "(", "n", ",", "None", ",", "level", ",", "message", ",", "*", "args", ")" ]
Logs a message every n calls. See _log_every_n_to_logger.
[ "Logs", "a", "message", "every", "n", "calls", ".", "See", "_log_every_n_to_logger", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/__init__.py#L52-L54
227,018
google/openhtf
openhtf/util/__init__.py
partial_format
def partial_format(target, **kwargs): """Formats a string without requiring all values to be present. This function allows substitutions to be gradually made in several steps rather than all at once. Similar to string.Template.safe_substitute. """ output = target[:] for tag, var in re.findall(r'(\{(.*?)\...
python
def partial_format(target, **kwargs): """Formats a string without requiring all values to be present. This function allows substitutions to be gradually made in several steps rather than all at once. Similar to string.Template.safe_substitute. """ output = target[:] for tag, var in re.findall(r'(\{(.*?)\...
[ "def", "partial_format", "(", "target", ",", "*", "*", "kwargs", ")", ":", "output", "=", "target", "[", ":", "]", "for", "tag", ",", "var", "in", "re", ".", "findall", "(", "r'(\\{(.*?)\\})'", ",", "output", ")", ":", "root", "=", "var", ".", "spl...
Formats a string without requiring all values to be present. This function allows substitutions to be gradually made in several steps rather than all at once. Similar to string.Template.safe_substitute.
[ "Formats", "a", "string", "without", "requiring", "all", "values", "to", "be", "present", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/__init__.py#L96-L110
227,019
google/openhtf
openhtf/util/__init__.py
SubscribableStateMixin.asdict_with_event
def asdict_with_event(self): """Get a dict representation of this object and an update event. Returns: state: Dict representation of this object. update_event: An event that is guaranteed to be set if an update has been triggered since the returned dict was generated. """ event = ...
python
def asdict_with_event(self): """Get a dict representation of this object and an update event. Returns: state: Dict representation of this object. update_event: An event that is guaranteed to be set if an update has been triggered since the returned dict was generated. """ event = ...
[ "def", "asdict_with_event", "(", "self", ")", ":", "event", "=", "threading", ".", "Event", "(", ")", "with", "self", ".", "_lock", ":", "self", ".", "_update_events", ".", "add", "(", "event", ")", "return", "self", ".", "_asdict", "(", ")", ",", "e...
Get a dict representation of this object and an update event. Returns: state: Dict representation of this object. update_event: An event that is guaranteed to be set if an update has been triggered since the returned dict was generated.
[ "Get", "a", "dict", "representation", "of", "this", "object", "and", "an", "update", "event", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/__init__.py#L158-L169
227,020
google/openhtf
openhtf/util/__init__.py
SubscribableStateMixin.notify_update
def notify_update(self): """Notify any update events that there was an update.""" with self._lock: for event in self._update_events: event.set() self._update_events.clear()
python
def notify_update(self): """Notify any update events that there was an update.""" with self._lock: for event in self._update_events: event.set() self._update_events.clear()
[ "def", "notify_update", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "for", "event", "in", "self", ".", "_update_events", ":", "event", ".", "set", "(", ")", "self", ".", "_update_events", ".", "clear", "(", ")" ]
Notify any update events that there was an update.
[ "Notify", "any", "update", "events", "that", "there", "was", "an", "update", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/__init__.py#L171-L176
227,021
google/openhtf
openhtf/output/servers/web_gui_server.py
bind_port
def bind_port(requested_port): """Bind sockets to an available port, returning sockets and the bound port.""" sockets = tornado.netutil.bind_sockets(requested_port) if requested_port != 0: return sockets, requested_port # Get the actual port number. for s in sockets: host, port = s.getsockname()[:2]...
python
def bind_port(requested_port): """Bind sockets to an available port, returning sockets and the bound port.""" sockets = tornado.netutil.bind_sockets(requested_port) if requested_port != 0: return sockets, requested_port # Get the actual port number. for s in sockets: host, port = s.getsockname()[:2]...
[ "def", "bind_port", "(", "requested_port", ")", ":", "sockets", "=", "tornado", ".", "netutil", ".", "bind_sockets", "(", "requested_port", ")", "if", "requested_port", "!=", "0", ":", "return", "sockets", ",", "requested_port", "# Get the actual port number.", "f...
Bind sockets to an available port, returning sockets and the bound port.
[ "Bind", "sockets", "to", "an", "available", "port", "returning", "sockets", "and", "the", "bound", "port", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/servers/web_gui_server.py#L47-L60
227,022
google/openhtf
openhtf/util/timeouts.py
loop_until_timeout_or_valid
def loop_until_timeout_or_valid(timeout_s, function, validation_fn, sleep_s=1): # pylint: disable=invalid-name """Loops until the specified function returns valid or a timeout is reached. Note: The function may return anything which, when passed to validation_fn, evaluates to implicit True. This function will ...
python
def loop_until_timeout_or_valid(timeout_s, function, validation_fn, sleep_s=1): # pylint: disable=invalid-name """Loops until the specified function returns valid or a timeout is reached. Note: The function may return anything which, when passed to validation_fn, evaluates to implicit True. This function will ...
[ "def", "loop_until_timeout_or_valid", "(", "timeout_s", ",", "function", ",", "validation_fn", ",", "sleep_s", "=", "1", ")", ":", "# pylint: disable=invalid-name", "if", "timeout_s", "is", "None", "or", "not", "hasattr", "(", "timeout_s", ",", "'has_expired'", ")...
Loops until the specified function returns valid or a timeout is reached. Note: The function may return anything which, when passed to validation_fn, evaluates to implicit True. This function will loop calling the function as long as the result of validation_fn(function_result) returns something which evaluat...
[ "Loops", "until", "the", "specified", "function", "returns", "valid", "or", "a", "timeout", "is", "reached", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L122-L151
227,023
google/openhtf
openhtf/util/timeouts.py
loop_until_timeout_or_true
def loop_until_timeout_or_true(timeout_s, function, sleep_s=1): # pylint: disable=invalid-name """Loops until the specified function returns True or a timeout is reached. Note: The function may return anything which evaluates to implicit True. This function will loop calling it as long as it continues to retur...
python
def loop_until_timeout_or_true(timeout_s, function, sleep_s=1): # pylint: disable=invalid-name """Loops until the specified function returns True or a timeout is reached. Note: The function may return anything which evaluates to implicit True. This function will loop calling it as long as it continues to retur...
[ "def", "loop_until_timeout_or_true", "(", "timeout_s", ",", "function", ",", "sleep_s", "=", "1", ")", ":", "# pylint: disable=invalid-name", "return", "loop_until_timeout_or_valid", "(", "timeout_s", ",", "function", ",", "lambda", "x", ":", "x", ",", "sleep_s", ...
Loops until the specified function returns True or a timeout is reached. Note: The function may return anything which evaluates to implicit True. This function will loop calling it as long as it continues to return something which evaluates to False. We ensure this method is called at least once regardless o...
[ "Loops", "until", "the", "specified", "function", "returns", "True", "or", "a", "timeout", "is", "reached", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L154-L172
227,024
google/openhtf
openhtf/util/timeouts.py
loop_until_timeout_or_not_none
def loop_until_timeout_or_not_none(timeout_s, function, sleep_s=1): # pylint: disable=invalid-name """Loops until the specified function returns non-None or until a timeout. Args: timeout_s: The number of seconds to wait until a timeout condition is reached. As a convenience, this accepts None to mean...
python
def loop_until_timeout_or_not_none(timeout_s, function, sleep_s=1): # pylint: disable=invalid-name """Loops until the specified function returns non-None or until a timeout. Args: timeout_s: The number of seconds to wait until a timeout condition is reached. As a convenience, this accepts None to mean...
[ "def", "loop_until_timeout_or_not_none", "(", "timeout_s", ",", "function", ",", "sleep_s", "=", "1", ")", ":", "# pylint: disable=invalid-name", "return", "loop_until_timeout_or_valid", "(", "timeout_s", ",", "function", ",", "lambda", "x", ":", "x", "is", "not", ...
Loops until the specified function returns non-None or until a timeout. Args: timeout_s: The number of seconds to wait until a timeout condition is reached. As a convenience, this accepts None to mean never timeout. Can also be passed a PolledTimeout object instead of an integer. function: T...
[ "Loops", "until", "the", "specified", "function", "returns", "non", "-", "None", "or", "until", "a", "timeout", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L175-L189
227,025
google/openhtf
openhtf/util/timeouts.py
loop_until_true_else_raise
def loop_until_true_else_raise(timeout_s, function, invert=False, message=None, sleep_s=1): """Repeatedly call the given function until truthy, or raise on a timeout. Args: timeout_s: The...
python
def loop_until_true_else_raise(timeout_s, function, invert=False, message=None, sleep_s=1): """Repeatedly call the given function until truthy, or raise on a timeout. Args: timeout_s: The...
[ "def", "loop_until_true_else_raise", "(", "timeout_s", ",", "function", ",", "invert", "=", "False", ",", "message", "=", "None", ",", "sleep_s", "=", "1", ")", ":", "def", "validate", "(", "x", ")", ":", "return", "bool", "(", "x", ")", "!=", "invert"...
Repeatedly call the given function until truthy, or raise on a timeout. Args: timeout_s: The number of seconds to wait until a timeout condition is reached. As a convenience, this accepts None to mean never timeout. Can also be passed a PolledTimeout object instead of an integer. function: Th...
[ "Repeatedly", "call", "the", "given", "function", "until", "truthy", "or", "raise", "on", "a", "timeout", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L192-L232
227,026
google/openhtf
openhtf/util/timeouts.py
execute_forever
def execute_forever(method, interval_s): # pylint: disable=invalid-name """Executes a method forever at the specified interval. Args: method: The callable to execute. interval_s: The number of seconds to start the execution after each method finishes. Returns: An Interval object. """ int...
python
def execute_forever(method, interval_s): # pylint: disable=invalid-name """Executes a method forever at the specified interval. Args: method: The callable to execute. interval_s: The number of seconds to start the execution after each method finishes. Returns: An Interval object. """ int...
[ "def", "execute_forever", "(", "method", ",", "interval_s", ")", ":", "# pylint: disable=invalid-name", "interval", "=", "Interval", "(", "method", ")", "interval", ".", "start", "(", "interval_s", ")", "return", "interval" ]
Executes a method forever at the specified interval. Args: method: The callable to execute. interval_s: The number of seconds to start the execution after each method finishes. Returns: An Interval object.
[ "Executes", "a", "method", "forever", "at", "the", "specified", "interval", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L316-L328
227,027
google/openhtf
openhtf/util/timeouts.py
execute_until_false
def execute_until_false(method, interval_s): # pylint: disable=invalid-name """Executes a method forever until the method returns a false value. Args: method: The callable to execute. interval_s: The number of seconds to start the execution after each method finishes. Returns: An Interval ob...
python
def execute_until_false(method, interval_s): # pylint: disable=invalid-name """Executes a method forever until the method returns a false value. Args: method: The callable to execute. interval_s: The number of seconds to start the execution after each method finishes. Returns: An Interval ob...
[ "def", "execute_until_false", "(", "method", ",", "interval_s", ")", ":", "# pylint: disable=invalid-name", "interval", "=", "Interval", "(", "method", ",", "stop_if_false", "=", "True", ")", "interval", ".", "start", "(", "interval_s", ")", "return", "interval" ]
Executes a method forever until the method returns a false value. Args: method: The callable to execute. interval_s: The number of seconds to start the execution after each method finishes. Returns: An Interval object.
[ "Executes", "a", "method", "forever", "until", "the", "method", "returns", "a", "false", "value", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L331-L343
227,028
google/openhtf
openhtf/util/timeouts.py
retry_until_true_or_limit_reached
def retry_until_true_or_limit_reached(method, limit, sleep_s=1, catch_exceptions=()): """Executes a method until the retry limit is hit or True is returned.""" return retry_until_valid_or_limit_reached( method, limit, lambda x: x, sleep_s, catch_exceptions)
python
def retry_until_true_or_limit_reached(method, limit, sleep_s=1, catch_exceptions=()): """Executes a method until the retry limit is hit or True is returned.""" return retry_until_valid_or_limit_reached( method, limit, lambda x: x, sleep_s, catch_exceptions)
[ "def", "retry_until_true_or_limit_reached", "(", "method", ",", "limit", ",", "sleep_s", "=", "1", ",", "catch_exceptions", "=", "(", ")", ")", ":", "return", "retry_until_valid_or_limit_reached", "(", "method", ",", "limit", ",", "lambda", "x", ":", "x", ",",...
Executes a method until the retry limit is hit or True is returned.
[ "Executes", "a", "method", "until", "the", "retry", "limit", "is", "hit", "or", "True", "is", "returned", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L347-L351
227,029
google/openhtf
openhtf/util/timeouts.py
retry_until_not_none_or_limit_reached
def retry_until_not_none_or_limit_reached(method, limit, sleep_s=1, catch_exceptions=()): """Executes a method until the retry limit is hit or not None is returned.""" return retry_until_valid_or_limit_reached( method, limit, lambda x: x is not None, sleep_s, catch_ex...
python
def retry_until_not_none_or_limit_reached(method, limit, sleep_s=1, catch_exceptions=()): """Executes a method until the retry limit is hit or not None is returned.""" return retry_until_valid_or_limit_reached( method, limit, lambda x: x is not None, sleep_s, catch_ex...
[ "def", "retry_until_not_none_or_limit_reached", "(", "method", ",", "limit", ",", "sleep_s", "=", "1", ",", "catch_exceptions", "=", "(", ")", ")", ":", "return", "retry_until_valid_or_limit_reached", "(", "method", ",", "limit", ",", "lambda", "x", ":", "x", ...
Executes a method until the retry limit is hit or not None is returned.
[ "Executes", "a", "method", "until", "the", "retry", "limit", "is", "hit", "or", "not", "None", "is", "returned", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L354-L358
227,030
google/openhtf
openhtf/util/timeouts.py
retry_until_valid_or_limit_reached
def retry_until_valid_or_limit_reached(method, limit, validation_fn, sleep_s=1, catch_exceptions=()): """Executes a method until the retry limit or validation_fn returns True. The method is always called once so the effective lower limit for 'limit' is 1. Passing in a numb...
python
def retry_until_valid_or_limit_reached(method, limit, validation_fn, sleep_s=1, catch_exceptions=()): """Executes a method until the retry limit or validation_fn returns True. The method is always called once so the effective lower limit for 'limit' is 1. Passing in a numb...
[ "def", "retry_until_valid_or_limit_reached", "(", "method", ",", "limit", ",", "validation_fn", ",", "sleep_s", "=", "1", ",", "catch_exceptions", "=", "(", ")", ")", ":", "assert", "limit", ">", "0", ",", "'Limit must be greater than 0'", "def", "_execute_method"...
Executes a method until the retry limit or validation_fn returns True. The method is always called once so the effective lower limit for 'limit' is 1. Passing in a number less than 1 will still result it the method being called once. Args: method: The method to execute should take no arguments. limit...
[ "Executes", "a", "method", "until", "the", "retry", "limit", "or", "validation_fn", "returns", "True", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L361-L395
227,031
google/openhtf
openhtf/util/timeouts.py
take_at_least_n_seconds
def take_at_least_n_seconds(time_s): """A context manager which ensures it takes at least time_s to execute. Example: with take_at_least_n_seconds(5): do.Something() do.SomethingElse() # if Something and SomethingElse took 3 seconds, the with block with sleep # for 2 seconds before exiting....
python
def take_at_least_n_seconds(time_s): """A context manager which ensures it takes at least time_s to execute. Example: with take_at_least_n_seconds(5): do.Something() do.SomethingElse() # if Something and SomethingElse took 3 seconds, the with block with sleep # for 2 seconds before exiting....
[ "def", "take_at_least_n_seconds", "(", "time_s", ")", ":", "timeout", "=", "PolledTimeout", "(", "time_s", ")", "yield", "while", "not", "timeout", ".", "has_expired", "(", ")", ":", "time", ".", "sleep", "(", "timeout", ".", "remaining", ")" ]
A context manager which ensures it takes at least time_s to execute. Example: with take_at_least_n_seconds(5): do.Something() do.SomethingElse() # if Something and SomethingElse took 3 seconds, the with block with sleep # for 2 seconds before exiting. Args: time_s: The number of seconds...
[ "A", "context", "manager", "which", "ensures", "it", "takes", "at", "least", "time_s", "to", "execute", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L401-L419
227,032
google/openhtf
openhtf/util/timeouts.py
take_at_most_n_seconds
def take_at_most_n_seconds(time_s, func, *args, **kwargs): """A function that returns whether a function call took less than time_s. NOTE: The function call is not killed and will run indefinitely if hung. Args: time_s: Maximum amount of time to take. func: Function to call. *args: Arguments to call...
python
def take_at_most_n_seconds(time_s, func, *args, **kwargs): """A function that returns whether a function call took less than time_s. NOTE: The function call is not killed and will run indefinitely if hung. Args: time_s: Maximum amount of time to take. func: Function to call. *args: Arguments to call...
[ "def", "take_at_most_n_seconds", "(", "time_s", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "thread", "=", "threading", ".", "Thread", "(", "target", "=", "func", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ")", "thr...
A function that returns whether a function call took less than time_s. NOTE: The function call is not killed and will run indefinitely if hung. Args: time_s: Maximum amount of time to take. func: Function to call. *args: Arguments to call the function with. **kwargs: Keyword arguments to call the ...
[ "A", "function", "that", "returns", "whether", "a", "function", "call", "took", "less", "than", "time_s", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L422-L440
227,033
google/openhtf
openhtf/util/timeouts.py
execute_after_delay
def execute_after_delay(time_s, func, *args, **kwargs): """A function that executes the given function after a delay. Executes func in a separate thread after a delay, so that this function returns immediately. Note that any exceptions raised by func will be ignored (but logged). Also, if time_s is a PolledT...
python
def execute_after_delay(time_s, func, *args, **kwargs): """A function that executes the given function after a delay. Executes func in a separate thread after a delay, so that this function returns immediately. Note that any exceptions raised by func will be ignored (but logged). Also, if time_s is a PolledT...
[ "def", "execute_after_delay", "(", "time_s", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "timeout", "=", "PolledTimeout", ".", "from_seconds", "(", "time_s", ")", "def", "target", "(", ")", ":", "time", ".", "sleep", "(", "timeout...
A function that executes the given function after a delay. Executes func in a separate thread after a delay, so that this function returns immediately. Note that any exceptions raised by func will be ignored (but logged). Also, if time_s is a PolledTimeout with no expiration, then this method simply returns ...
[ "A", "function", "that", "executes", "the", "given", "function", "after", "a", "delay", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L443-L468
227,034
google/openhtf
openhtf/util/timeouts.py
PolledTimeout.from_millis
def from_millis(cls, timeout_ms): """Create a new PolledTimeout if needed. If timeout_ms is already a PolledTimeout, just return it, otherwise create a new PolledTimeout with the given timeout in milliseconds. Args: timeout_ms: PolledTimeout object, or number of milliseconds to use for c...
python
def from_millis(cls, timeout_ms): """Create a new PolledTimeout if needed. If timeout_ms is already a PolledTimeout, just return it, otherwise create a new PolledTimeout with the given timeout in milliseconds. Args: timeout_ms: PolledTimeout object, or number of milliseconds to use for c...
[ "def", "from_millis", "(", "cls", ",", "timeout_ms", ")", ":", "if", "hasattr", "(", "timeout_ms", ",", "'has_expired'", ")", ":", "return", "timeout_ms", "if", "timeout_ms", "is", "None", ":", "return", "cls", "(", "None", ")", "return", "cls", "(", "ti...
Create a new PolledTimeout if needed. If timeout_ms is already a PolledTimeout, just return it, otherwise create a new PolledTimeout with the given timeout in milliseconds. Args: timeout_ms: PolledTimeout object, or number of milliseconds to use for creating a new one. Returns: A ...
[ "Create", "a", "new", "PolledTimeout", "if", "needed", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L41-L59
227,035
google/openhtf
openhtf/util/timeouts.py
Interval.start
def start(self, interval_s): """Starts executing the method at the specified interval. Args: interval_s: The amount of time between executions of the method. Returns: False if the interval was already running. """ if self.running: return False self.stopped.clear() def _e...
python
def start(self, interval_s): """Starts executing the method at the specified interval. Args: interval_s: The amount of time between executions of the method. Returns: False if the interval was already running. """ if self.running: return False self.stopped.clear() def _e...
[ "def", "start", "(", "self", ",", "interval_s", ")", ":", "if", "self", ".", "running", ":", "return", "False", "self", ".", "stopped", ".", "clear", "(", ")", "def", "_execute", "(", ")", ":", "# Always execute immediately once", "if", "not", "self", "....
Starts executing the method at the specified interval. Args: interval_s: The amount of time between executions of the method. Returns: False if the interval was already running.
[ "Starts", "executing", "the", "method", "at", "the", "specified", "interval", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L257-L281
227,036
google/openhtf
openhtf/util/timeouts.py
Interval.stop
def stop(self, timeout_s=None): """Stops the interval. If a timeout is provided and stop returns False then the thread is effectively abandoned in whatever state it was in (presumably dead-locked). Args: timeout_s: The time in seconds to wait on the thread to finish. By default it's f...
python
def stop(self, timeout_s=None): """Stops the interval. If a timeout is provided and stop returns False then the thread is effectively abandoned in whatever state it was in (presumably dead-locked). Args: timeout_s: The time in seconds to wait on the thread to finish. By default it's f...
[ "def", "stop", "(", "self", ",", "timeout_s", "=", "None", ")", ":", "self", ".", "stopped", ".", "set", "(", ")", "if", "self", ".", "thread", ":", "self", ".", "thread", ".", "join", "(", "timeout_s", ")", "return", "not", "self", ".", "thread", ...
Stops the interval. If a timeout is provided and stop returns False then the thread is effectively abandoned in whatever state it was in (presumably dead-locked). Args: timeout_s: The time in seconds to wait on the thread to finish. By default it's forever. Returns: False if a t...
[ "Stops", "the", "interval", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L283-L300
227,037
google/openhtf
openhtf/util/timeouts.py
Interval.join
def join(self, timeout_s=None): """Joins blocking until the interval ends or until timeout is reached. Args: timeout_s: The time in seconds to wait, defaults to forever. Returns: True if the interval is still running and we reached the timeout. """ if not self.thread: return False...
python
def join(self, timeout_s=None): """Joins blocking until the interval ends or until timeout is reached. Args: timeout_s: The time in seconds to wait, defaults to forever. Returns: True if the interval is still running and we reached the timeout. """ if not self.thread: return False...
[ "def", "join", "(", "self", ",", "timeout_s", "=", "None", ")", ":", "if", "not", "self", ".", "thread", ":", "return", "False", "self", ".", "thread", ".", "join", "(", "timeout_s", ")", "return", "self", ".", "running" ]
Joins blocking until the interval ends or until timeout is reached. Args: timeout_s: The time in seconds to wait, defaults to forever. Returns: True if the interval is still running and we reached the timeout.
[ "Joins", "blocking", "until", "the", "interval", "ends", "or", "until", "timeout", "is", "reached", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L302-L313
227,038
google/openhtf
pylint_plugins/conf_plugin.py
transform_declare
def transform_declare(node): """Transform conf.declare calls by stashing the declared names.""" global CURRENT_ROOT if not (isinstance(node.func, astroid.Attribute) and isinstance(node.func.expr, astroid.Name) and node.func.expr.name == 'conf' and node.func.attrname == 'declare'): ...
python
def transform_declare(node): """Transform conf.declare calls by stashing the declared names.""" global CURRENT_ROOT if not (isinstance(node.func, astroid.Attribute) and isinstance(node.func.expr, astroid.Name) and node.func.expr.name == 'conf' and node.func.attrname == 'declare'): ...
[ "def", "transform_declare", "(", "node", ")", ":", "global", "CURRENT_ROOT", "if", "not", "(", "isinstance", "(", "node", ".", "func", ",", "astroid", ".", "Attribute", ")", "and", "isinstance", "(", "node", ".", "func", ".", "expr", ",", "astroid", ".",...
Transform conf.declare calls by stashing the declared names.
[ "Transform", "conf", ".", "declare", "calls", "by", "stashing", "the", "declared", "names", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/pylint_plugins/conf_plugin.py#L30-L59
227,039
google/openhtf
pylint_plugins/conf_plugin.py
transform_conf_module
def transform_conf_module(cls): """Transform usages of the conf module by updating locals.""" global CONF_NODE if cls.name == 'openhtf.conf': # Put all the attributes in Configuration into the openhtf.conf node. cls._locals.update(cls.locals['Configuration'][0].locals) # Store reference to this node...
python
def transform_conf_module(cls): """Transform usages of the conf module by updating locals.""" global CONF_NODE if cls.name == 'openhtf.conf': # Put all the attributes in Configuration into the openhtf.conf node. cls._locals.update(cls.locals['Configuration'][0].locals) # Store reference to this node...
[ "def", "transform_conf_module", "(", "cls", ")", ":", "global", "CONF_NODE", "if", "cls", ".", "name", "==", "'openhtf.conf'", ":", "# Put all the attributes in Configuration into the openhtf.conf node.", "cls", ".", "_locals", ".", "update", "(", "cls", ".", "locals"...
Transform usages of the conf module by updating locals.
[ "Transform", "usages", "of", "the", "conf", "module", "by", "updating", "locals", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/pylint_plugins/conf_plugin.py#L62-L72
227,040
google/openhtf
pylint_plugins/conf_plugin.py
register
def register(linter): """Register all transforms with the linter.""" MANAGER.register_transform(astroid.Call, transform_declare) MANAGER.register_transform(astroid.Module, transform_conf_module)
python
def register(linter): """Register all transforms with the linter.""" MANAGER.register_transform(astroid.Call, transform_declare) MANAGER.register_transform(astroid.Module, transform_conf_module)
[ "def", "register", "(", "linter", ")", ":", "MANAGER", ".", "register_transform", "(", "astroid", ".", "Call", ",", "transform_declare", ")", "MANAGER", ".", "register_transform", "(", "astroid", ".", "Module", ",", "transform_conf_module", ")" ]
Register all transforms with the linter.
[ "Register", "all", "transforms", "with", "the", "linter", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/pylint_plugins/conf_plugin.py#L75-L78
227,041
google/openhtf
openhtf/plugs/user_input.py
ConsolePrompt.run
def run(self): """Main logic for this thread to execute.""" if platform.system() == 'Windows': # Windows doesn't support file-like objects for select(), so fall back # to raw_input(). response = input(''.join((self._message, os.linesep, ...
python
def run(self): """Main logic for this thread to execute.""" if platform.system() == 'Windows': # Windows doesn't support file-like objects for select(), so fall back # to raw_input(). response = input(''.join((self._message, os.linesep, ...
[ "def", "run", "(", "self", ")", ":", "if", "platform", ".", "system", "(", ")", "==", "'Windows'", ":", "# Windows doesn't support file-like objects for select(), so fall back", "# to raw_input().", "response", "=", "input", "(", "''", ".", "join", "(", "(", "self...
Main logic for this thread to execute.
[ "Main", "logic", "for", "this", "thread", "to", "execute", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L90-L127
227,042
google/openhtf
openhtf/plugs/user_input.py
UserInput._asdict
def _asdict(self): """Return a dictionary representation of the current prompt.""" with self._cond: if self._prompt is None: return return {'id': self._prompt.id, 'message': self._prompt.message, 'text-input': self._prompt.text_input}
python
def _asdict(self): """Return a dictionary representation of the current prompt.""" with self._cond: if self._prompt is None: return return {'id': self._prompt.id, 'message': self._prompt.message, 'text-input': self._prompt.text_input}
[ "def", "_asdict", "(", "self", ")", ":", "with", "self", ".", "_cond", ":", "if", "self", ".", "_prompt", "is", "None", ":", "return", "return", "{", "'id'", ":", "self", ".", "_prompt", ".", "id", ",", "'message'", ":", "self", ".", "_prompt", "."...
Return a dictionary representation of the current prompt.
[ "Return", "a", "dictionary", "representation", "of", "the", "current", "prompt", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L146-L153
227,043
google/openhtf
openhtf/plugs/user_input.py
UserInput.remove_prompt
def remove_prompt(self): """Remove the prompt.""" with self._cond: self._prompt = None if self._console_prompt: self._console_prompt.Stop() self._console_prompt = None self.notify_update()
python
def remove_prompt(self): """Remove the prompt.""" with self._cond: self._prompt = None if self._console_prompt: self._console_prompt.Stop() self._console_prompt = None self.notify_update()
[ "def", "remove_prompt", "(", "self", ")", ":", "with", "self", ".", "_cond", ":", "self", ".", "_prompt", "=", "None", "if", "self", ".", "_console_prompt", ":", "self", ".", "_console_prompt", ".", "Stop", "(", ")", "self", ".", "_console_prompt", "=", ...
Remove the prompt.
[ "Remove", "the", "prompt", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L158-L165
227,044
google/openhtf
openhtf/plugs/user_input.py
UserInput.prompt
def prompt(self, message, text_input=False, timeout_s=None, cli_color=''): """Display a prompt and wait for a response. Args: message: A string to be presented to the user. text_input: A boolean indicating whether the user must respond with text. timeout_s: Seconds to wait before raising a Pr...
python
def prompt(self, message, text_input=False, timeout_s=None, cli_color=''): """Display a prompt and wait for a response. Args: message: A string to be presented to the user. text_input: A boolean indicating whether the user must respond with text. timeout_s: Seconds to wait before raising a Pr...
[ "def", "prompt", "(", "self", ",", "message", ",", "text_input", "=", "False", ",", "timeout_s", "=", "None", ",", "cli_color", "=", "''", ")", ":", "self", ".", "start_prompt", "(", "message", ",", "text_input", ",", "cli_color", ")", "return", "self", ...
Display a prompt and wait for a response. Args: message: A string to be presented to the user. text_input: A boolean indicating whether the user must respond with text. timeout_s: Seconds to wait before raising a PromptUnansweredError. cli_color: An ANSI color code, or the empty string. ...
[ "Display", "a", "prompt", "and", "wait", "for", "a", "response", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L167-L184
227,045
google/openhtf
openhtf/plugs/user_input.py
UserInput.start_prompt
def start_prompt(self, message, text_input=False, cli_color=''): """Display a prompt. Args: message: A string to be presented to the user. text_input: A boolean indicating whether the user must respond with text. cli_color: An ANSI color code, or the empty string. Raises: MultipleP...
python
def start_prompt(self, message, text_input=False, cli_color=''): """Display a prompt. Args: message: A string to be presented to the user. text_input: A boolean indicating whether the user must respond with text. cli_color: An ANSI color code, or the empty string. Raises: MultipleP...
[ "def", "start_prompt", "(", "self", ",", "message", ",", "text_input", "=", "False", ",", "cli_color", "=", "''", ")", ":", "with", "self", ".", "_cond", ":", "if", "self", ".", "_prompt", ":", "raise", "MultiplePromptsError", "prompt_id", "=", "uuid", "...
Display a prompt. Args: message: A string to be presented to the user. text_input: A boolean indicating whether the user must respond with text. cli_color: An ANSI color code, or the empty string. Raises: MultiplePromptsError: There was already an existing prompt. Returns: A...
[ "Display", "a", "prompt", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L186-L216
227,046
google/openhtf
openhtf/plugs/user_input.py
UserInput.wait_for_prompt
def wait_for_prompt(self, timeout_s=None): """Wait for the user to respond to the current prompt. Args: timeout_s: Seconds to wait before raising a PromptUnansweredError. Returns: A string response, or the empty string if text_input was False. Raises: PromptUnansweredError: Timed ou...
python
def wait_for_prompt(self, timeout_s=None): """Wait for the user to respond to the current prompt. Args: timeout_s: Seconds to wait before raising a PromptUnansweredError. Returns: A string response, or the empty string if text_input was False. Raises: PromptUnansweredError: Timed ou...
[ "def", "wait_for_prompt", "(", "self", ",", "timeout_s", "=", "None", ")", ":", "with", "self", ".", "_cond", ":", "if", "self", ".", "_prompt", ":", "if", "timeout_s", "is", "None", ":", "self", ".", "_cond", ".", "wait", "(", "3600", "*", "24", "...
Wait for the user to respond to the current prompt. Args: timeout_s: Seconds to wait before raising a PromptUnansweredError. Returns: A string response, or the empty string if text_input was False. Raises: PromptUnansweredError: Timed out waiting for the user to respond.
[ "Wait", "for", "the", "user", "to", "respond", "to", "the", "current", "prompt", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L218-L238
227,047
google/openhtf
openhtf/plugs/user_input.py
UserInput.respond
def respond(self, prompt_id, response): """Respond to the prompt with the given ID. If there is no active prompt or the given ID doesn't match the active prompt, do nothing. Args: prompt_id: A string uniquely identifying the prompt. response: A string response to the given prompt. Ret...
python
def respond(self, prompt_id, response): """Respond to the prompt with the given ID. If there is no active prompt or the given ID doesn't match the active prompt, do nothing. Args: prompt_id: A string uniquely identifying the prompt. response: A string response to the given prompt. Ret...
[ "def", "respond", "(", "self", ",", "prompt_id", ",", "response", ")", ":", "_LOG", ".", "debug", "(", "'Responding to prompt (%s): \"%s\"'", ",", "prompt_id", ",", "response", ")", "with", "self", ".", "_cond", ":", "if", "not", "(", "self", ".", "_prompt...
Respond to the prompt with the given ID. If there is no active prompt or the given ID doesn't match the active prompt, do nothing. Args: prompt_id: A string uniquely identifying the prompt. response: A string response to the given prompt. Returns: True if the prompt with the given I...
[ "Respond", "to", "the", "prompt", "with", "the", "given", "ID", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L240-L261
227,048
google/openhtf
openhtf/core/phase_executor.py
PhaseExecutionOutcome.is_terminal
def is_terminal(self): """True if this result will stop the test.""" return (self.raised_exception or self.is_timeout or self.phase_result == openhtf.PhaseResult.STOP)
python
def is_terminal(self): """True if this result will stop the test.""" return (self.raised_exception or self.is_timeout or self.phase_result == openhtf.PhaseResult.STOP)
[ "def", "is_terminal", "(", "self", ")", ":", "return", "(", "self", ".", "raised_exception", "or", "self", ".", "is_timeout", "or", "self", ".", "phase_result", "==", "openhtf", ".", "PhaseResult", ".", "STOP", ")" ]
True if this result will stop the test.
[ "True", "if", "this", "result", "will", "stop", "the", "test", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L119-L122
227,049
google/openhtf
openhtf/core/phase_executor.py
PhaseExecutorThread._thread_proc
def _thread_proc(self): """Execute the encompassed phase and save the result.""" # Call the phase, save the return value, or default it to CONTINUE. phase_return = self._phase_desc(self._test_state) if phase_return is None: phase_return = openhtf.PhaseResult.CONTINUE # If phase_return is inva...
python
def _thread_proc(self): """Execute the encompassed phase and save the result.""" # Call the phase, save the return value, or default it to CONTINUE. phase_return = self._phase_desc(self._test_state) if phase_return is None: phase_return = openhtf.PhaseResult.CONTINUE # If phase_return is inva...
[ "def", "_thread_proc", "(", "self", ")", ":", "# Call the phase, save the return value, or default it to CONTINUE.", "phase_return", "=", "self", ".", "_phase_desc", "(", "self", ".", "_test_state", ")", "if", "phase_return", "is", "None", ":", "phase_return", "=", "o...
Execute the encompassed phase and save the result.
[ "Execute", "the", "encompassed", "phase", "and", "save", "the", "result", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L152-L161
227,050
google/openhtf
openhtf/core/phase_executor.py
PhaseExecutorThread.join_or_die
def join_or_die(self): """Wait for thread to finish, returning a PhaseExecutionOutcome instance.""" if self._phase_desc.options.timeout_s is not None: self.join(self._phase_desc.options.timeout_s) else: self.join(DEFAULT_PHASE_TIMEOUT_S) # We got a return value or an exception and handled i...
python
def join_or_die(self): """Wait for thread to finish, returning a PhaseExecutionOutcome instance.""" if self._phase_desc.options.timeout_s is not None: self.join(self._phase_desc.options.timeout_s) else: self.join(DEFAULT_PHASE_TIMEOUT_S) # We got a return value or an exception and handled i...
[ "def", "join_or_die", "(", "self", ")", ":", "if", "self", ".", "_phase_desc", ".", "options", ".", "timeout_s", "is", "not", "None", ":", "self", ".", "join", "(", "self", ".", "_phase_desc", ".", "options", ".", "timeout_s", ")", "else", ":", "self",...
Wait for thread to finish, returning a PhaseExecutionOutcome instance.
[ "Wait", "for", "thread", "to", "finish", "returning", "a", "PhaseExecutionOutcome", "instance", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L172-L190
227,051
google/openhtf
openhtf/core/phase_executor.py
PhaseExecutor.execute_phase
def execute_phase(self, phase): """Executes a phase or skips it, yielding PhaseExecutionOutcome instances. Args: phase: Phase to execute. Returns: The final PhaseExecutionOutcome that wraps the phase return value (or exception) of the final phase run. All intermediary results, if any, ...
python
def execute_phase(self, phase): """Executes a phase or skips it, yielding PhaseExecutionOutcome instances. Args: phase: Phase to execute. Returns: The final PhaseExecutionOutcome that wraps the phase return value (or exception) of the final phase run. All intermediary results, if any, ...
[ "def", "execute_phase", "(", "self", ",", "phase", ")", ":", "repeat_count", "=", "1", "repeat_limit", "=", "phase", ".", "options", ".", "repeat_limit", "or", "sys", ".", "maxsize", "while", "not", "self", ".", "_stopping", ".", "is_set", "(", ")", ":",...
Executes a phase or skips it, yielding PhaseExecutionOutcome instances. Args: phase: Phase to execute. Returns: The final PhaseExecutionOutcome that wraps the phase return value (or exception) of the final phase run. All intermediary results, if any, are REPEAT and handled internally. ...
[ "Executes", "a", "phase", "or", "skips", "it", "yielding", "PhaseExecutionOutcome", "instances", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L211-L235
227,052
google/openhtf
openhtf/core/phase_executor.py
PhaseExecutor._execute_phase_once
def _execute_phase_once(self, phase_desc, is_last_repeat): """Executes the given phase, returning a PhaseExecutionOutcome.""" # Check this before we create a PhaseState and PhaseRecord. if phase_desc.options.run_if and not phase_desc.options.run_if(): _LOG.debug('Phase %s skipped due to run_if returni...
python
def _execute_phase_once(self, phase_desc, is_last_repeat): """Executes the given phase, returning a PhaseExecutionOutcome.""" # Check this before we create a PhaseState and PhaseRecord. if phase_desc.options.run_if and not phase_desc.options.run_if(): _LOG.debug('Phase %s skipped due to run_if returni...
[ "def", "_execute_phase_once", "(", "self", ",", "phase_desc", ",", "is_last_repeat", ")", ":", "# Check this before we create a PhaseState and PhaseRecord.", "if", "phase_desc", ".", "options", ".", "run_if", "and", "not", "phase_desc", ".", "options", ".", "run_if", ...
Executes the given phase, returning a PhaseExecutionOutcome.
[ "Executes", "the", "given", "phase", "returning", "a", "PhaseExecutionOutcome", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L237-L276
227,053
google/openhtf
openhtf/core/phase_executor.py
PhaseExecutor.stop
def stop(self, timeout_s=None): """Stops execution of the current phase, if any. It will raise a ThreadTerminationError, which will cause the test to stop executing and terminate with an ERROR state. Args: timeout_s: int or None, timeout in seconds to wait for the phase to stop. """ self...
python
def stop(self, timeout_s=None): """Stops execution of the current phase, if any. It will raise a ThreadTerminationError, which will cause the test to stop executing and terminate with an ERROR state. Args: timeout_s: int or None, timeout in seconds to wait for the phase to stop. """ self...
[ "def", "stop", "(", "self", ",", "timeout_s", "=", "None", ")", ":", "self", ".", "_stopping", ".", "set", "(", ")", "with", "self", ".", "_current_phase_thread_lock", ":", "phase_thread", "=", "self", ".", "_current_phase_thread", "if", "not", "phase_thread...
Stops execution of the current phase, if any. It will raise a ThreadTerminationError, which will cause the test to stop executing and terminate with an ERROR state. Args: timeout_s: int or None, timeout in seconds to wait for the phase to stop.
[ "Stops", "execution", "of", "the", "current", "phase", "if", "any", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L281-L306
227,054
google/openhtf
openhtf/core/phase_group.py
load_code_info
def load_code_info(phases_or_groups): """Recursively load code info for a PhaseGroup or list of phases or groups.""" if isinstance(phases_or_groups, PhaseGroup): return phases_or_groups.load_code_info() ret = [] for phase in phases_or_groups: if isinstance(phase, PhaseGroup): ret.append(phase.load...
python
def load_code_info(phases_or_groups): """Recursively load code info for a PhaseGroup or list of phases or groups.""" if isinstance(phases_or_groups, PhaseGroup): return phases_or_groups.load_code_info() ret = [] for phase in phases_or_groups: if isinstance(phase, PhaseGroup): ret.append(phase.load...
[ "def", "load_code_info", "(", "phases_or_groups", ")", ":", "if", "isinstance", "(", "phases_or_groups", ",", "PhaseGroup", ")", ":", "return", "phases_or_groups", ".", "load_code_info", "(", ")", "ret", "=", "[", "]", "for", "phase", "in", "phases_or_groups", ...
Recursively load code info for a PhaseGroup or list of phases or groups.
[ "Recursively", "load", "code", "info", "for", "a", "PhaseGroup", "or", "list", "of", "phases", "or", "groups", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L192-L204
227,055
google/openhtf
openhtf/core/phase_group.py
flatten_phases_and_groups
def flatten_phases_and_groups(phases_or_groups): """Recursively flatten nested lists for the list of phases or groups.""" if isinstance(phases_or_groups, PhaseGroup): phases_or_groups = [phases_or_groups] ret = [] for phase in phases_or_groups: if isinstance(phase, PhaseGroup): ret.append(phase.fl...
python
def flatten_phases_and_groups(phases_or_groups): """Recursively flatten nested lists for the list of phases or groups.""" if isinstance(phases_or_groups, PhaseGroup): phases_or_groups = [phases_or_groups] ret = [] for phase in phases_or_groups: if isinstance(phase, PhaseGroup): ret.append(phase.fl...
[ "def", "flatten_phases_and_groups", "(", "phases_or_groups", ")", ":", "if", "isinstance", "(", "phases_or_groups", ",", "PhaseGroup", ")", ":", "phases_or_groups", "=", "[", "phases_or_groups", "]", "ret", "=", "[", "]", "for", "phase", "in", "phases_or_groups", ...
Recursively flatten nested lists for the list of phases or groups.
[ "Recursively", "flatten", "nested", "lists", "for", "the", "list", "of", "phases", "or", "groups", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L207-L219
227,056
google/openhtf
openhtf/core/phase_group.py
optionally_with_args
def optionally_with_args(phase, **kwargs): """Apply only the args that the phase knows. If the phase has a **kwargs-style argument, it counts as knowing all args. Args: phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or iterable of those, the phase or phase group (or iterable) to ...
python
def optionally_with_args(phase, **kwargs): """Apply only the args that the phase knows. If the phase has a **kwargs-style argument, it counts as knowing all args. Args: phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or iterable of those, the phase or phase group (or iterable) to ...
[ "def", "optionally_with_args", "(", "phase", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "phase", ",", "PhaseGroup", ")", ":", "return", "phase", ".", "with_args", "(", "*", "*", "kwargs", ")", "if", "isinstance", "(", "phase", ",", "co...
Apply only the args that the phase knows. If the phase has a **kwargs-style argument, it counts as knowing all args. Args: phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or iterable of those, the phase or phase group (or iterable) to apply with_args to. **kwargs: argume...
[ "Apply", "only", "the", "args", "that", "the", "phase", "knows", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L222-L244
227,057
google/openhtf
openhtf/core/phase_group.py
optionally_with_plugs
def optionally_with_plugs(phase, **subplugs): """Apply only the with_plugs that the phase knows. This will determine the subset of plug overrides for only plugs the phase actually has. Args: phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or iterable of those, the phase or phase...
python
def optionally_with_plugs(phase, **subplugs): """Apply only the with_plugs that the phase knows. This will determine the subset of plug overrides for only plugs the phase actually has. Args: phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or iterable of those, the phase or phase...
[ "def", "optionally_with_plugs", "(", "phase", ",", "*", "*", "subplugs", ")", ":", "if", "isinstance", "(", "phase", ",", "PhaseGroup", ")", ":", "return", "phase", ".", "with_plugs", "(", "*", "*", "subplugs", ")", "if", "isinstance", "(", "phase", ",",...
Apply only the with_plugs that the phase knows. This will determine the subset of plug overrides for only plugs the phase actually has. Args: phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or iterable of those, the phase or phase group (or iterable) to apply the plug chan...
[ "Apply", "only", "the", "with_plugs", "that", "the", "phase", "knows", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L247-L275
227,058
google/openhtf
openhtf/core/phase_group.py
PhaseGroup.convert_if_not
def convert_if_not(cls, phases_or_groups): """Convert list of phases or groups into a new PhaseGroup if not already.""" if isinstance(phases_or_groups, PhaseGroup): return mutablerecords.CopyRecord(phases_or_groups) flattened = flatten_phases_and_groups(phases_or_groups) return cls(main=flattened...
python
def convert_if_not(cls, phases_or_groups): """Convert list of phases or groups into a new PhaseGroup if not already.""" if isinstance(phases_or_groups, PhaseGroup): return mutablerecords.CopyRecord(phases_or_groups) flattened = flatten_phases_and_groups(phases_or_groups) return cls(main=flattened...
[ "def", "convert_if_not", "(", "cls", ",", "phases_or_groups", ")", ":", "if", "isinstance", "(", "phases_or_groups", ",", "PhaseGroup", ")", ":", "return", "mutablerecords", ".", "CopyRecord", "(", "phases_or_groups", ")", "flattened", "=", "flatten_phases_and_group...
Convert list of phases or groups into a new PhaseGroup if not already.
[ "Convert", "list", "of", "phases", "or", "groups", "into", "a", "new", "PhaseGroup", "if", "not", "already", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L79-L85
227,059
google/openhtf
openhtf/core/phase_group.py
PhaseGroup.with_context
def with_context(cls, setup_phases, teardown_phases): """Create PhaseGroup creator function with setup and teardown phases. Args: setup_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/ callables/iterables, phases to run during the setup for the PhaseGroup returned from t...
python
def with_context(cls, setup_phases, teardown_phases): """Create PhaseGroup creator function with setup and teardown phases. Args: setup_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/ callables/iterables, phases to run during the setup for the PhaseGroup returned from t...
[ "def", "with_context", "(", "cls", ",", "setup_phases", ",", "teardown_phases", ")", ":", "setup", "=", "flatten_phases_and_groups", "(", "setup_phases", ")", "teardown", "=", "flatten_phases_and_groups", "(", "teardown_phases", ")", "def", "_context_wrapper", "(", ...
Create PhaseGroup creator function with setup and teardown phases. Args: setup_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/ callables/iterables, phases to run during the setup for the PhaseGroup returned from the created function. teardown_phases: list of phase_des...
[ "Create", "PhaseGroup", "creator", "function", "with", "setup", "and", "teardown", "phases", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L88-L110
227,060
google/openhtf
openhtf/core/phase_group.py
PhaseGroup.combine
def combine(self, other, name=None): """Combine with another PhaseGroup and return the result.""" return PhaseGroup( setup=self.setup + other.setup, main=self.main + other.main, teardown=self.teardown + other.teardown, name=name)
python
def combine(self, other, name=None): """Combine with another PhaseGroup and return the result.""" return PhaseGroup( setup=self.setup + other.setup, main=self.main + other.main, teardown=self.teardown + other.teardown, name=name)
[ "def", "combine", "(", "self", ",", "other", ",", "name", "=", "None", ")", ":", "return", "PhaseGroup", "(", "setup", "=", "self", ".", "setup", "+", "other", ".", "setup", ",", "main", "=", "self", ".", "main", "+", "other", ".", "main", ",", "...
Combine with another PhaseGroup and return the result.
[ "Combine", "with", "another", "PhaseGroup", "and", "return", "the", "result", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L122-L128
227,061
google/openhtf
openhtf/core/phase_group.py
PhaseGroup.wrap
def wrap(self, main_phases, name=None): """Returns PhaseGroup with additional main phases.""" new_main = list(self.main) if isinstance(main_phases, collections.Iterable): new_main.extend(main_phases) else: new_main.append(main_phases) return PhaseGroup( setup=self.setup, ...
python
def wrap(self, main_phases, name=None): """Returns PhaseGroup with additional main phases.""" new_main = list(self.main) if isinstance(main_phases, collections.Iterable): new_main.extend(main_phases) else: new_main.append(main_phases) return PhaseGroup( setup=self.setup, ...
[ "def", "wrap", "(", "self", ",", "main_phases", ",", "name", "=", "None", ")", ":", "new_main", "=", "list", "(", "self", ".", "main", ")", "if", "isinstance", "(", "main_phases", ",", "collections", ".", "Iterable", ")", ":", "new_main", ".", "extend"...
Returns PhaseGroup with additional main phases.
[ "Returns", "PhaseGroup", "with", "additional", "main", "phases", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L130-L141
227,062
google/openhtf
openhtf/core/phase_group.py
PhaseGroup.flatten
def flatten(self): """Internally flatten out nested iterables.""" return PhaseGroup( setup=flatten_phases_and_groups(self.setup), main=flatten_phases_and_groups(self.main), teardown=flatten_phases_and_groups(self.teardown), name=self.name)
python
def flatten(self): """Internally flatten out nested iterables.""" return PhaseGroup( setup=flatten_phases_and_groups(self.setup), main=flatten_phases_and_groups(self.main), teardown=flatten_phases_and_groups(self.teardown), name=self.name)
[ "def", "flatten", "(", "self", ")", ":", "return", "PhaseGroup", "(", "setup", "=", "flatten_phases_and_groups", "(", "self", ".", "setup", ")", ",", "main", "=", "flatten_phases_and_groups", "(", "self", ".", "main", ")", ",", "teardown", "=", "flatten_phas...
Internally flatten out nested iterables.
[ "Internally", "flatten", "out", "nested", "iterables", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L175-L181
227,063
google/openhtf
openhtf/core/phase_group.py
PhaseGroup.load_code_info
def load_code_info(self): """Load coded info for all contained phases.""" return PhaseGroup( setup=load_code_info(self.setup), main=load_code_info(self.main), teardown=load_code_info(self.teardown), name=self.name)
python
def load_code_info(self): """Load coded info for all contained phases.""" return PhaseGroup( setup=load_code_info(self.setup), main=load_code_info(self.main), teardown=load_code_info(self.teardown), name=self.name)
[ "def", "load_code_info", "(", "self", ")", ":", "return", "PhaseGroup", "(", "setup", "=", "load_code_info", "(", "self", ".", "setup", ")", ",", "main", "=", "load_code_info", "(", "self", ".", "main", ")", ",", "teardown", "=", "load_code_info", "(", "...
Load coded info for all contained phases.
[ "Load", "coded", "info", "for", "all", "contained", "phases", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L183-L189
227,064
google/openhtf
openhtf/output/servers/pub_sub.py
PubSub.publish
def publish(cls, message, client_filter=None): """Publish messages to subscribers. Args: message: The message to publish. client_filter: A filter function to call passing in each client. Only clients for whom the function returns True will have the message ...
python
def publish(cls, message, client_filter=None): """Publish messages to subscribers. Args: message: The message to publish. client_filter: A filter function to call passing in each client. Only clients for whom the function returns True will have the message ...
[ "def", "publish", "(", "cls", ",", "message", ",", "client_filter", "=", "None", ")", ":", "with", "cls", ".", "_lock", ":", "for", "client", "in", "cls", ".", "subscribers", ":", "if", "(", "not", "client_filter", ")", "or", "client_filter", "(", "cli...
Publish messages to subscribers. Args: message: The message to publish. client_filter: A filter function to call passing in each client. Only clients for whom the function returns True will have the message sent to them.
[ "Publish", "messages", "to", "subscribers", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/servers/pub_sub.py#L43-L55
227,065
google/openhtf
examples/repeat.py
FailTwicePlug.run
def run(self): """Increments counter and raises an exception for first two runs.""" self.count += 1 print('FailTwicePlug: Run number %s' % (self.count)) if self.count < 3: raise RuntimeError('Fails a couple times') return True
python
def run(self): """Increments counter and raises an exception for first two runs.""" self.count += 1 print('FailTwicePlug: Run number %s' % (self.count)) if self.count < 3: raise RuntimeError('Fails a couple times') return True
[ "def", "run", "(", "self", ")", ":", "self", ".", "count", "+=", "1", "print", "(", "'FailTwicePlug: Run number %s'", "%", "(", "self", ".", "count", ")", ")", "if", "self", ".", "count", "<", "3", ":", "raise", "RuntimeError", "(", "'Fails a couple time...
Increments counter and raises an exception for first two runs.
[ "Increments", "counter", "and", "raises", "an", "exception", "for", "first", "two", "runs", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/examples/repeat.py#L41-L48
227,066
google/openhtf
openhtf/core/phase_descriptor.py
PhaseOptions.format_strings
def format_strings(self, **kwargs): """String substitution of name.""" return mutablerecords.CopyRecord( self, name=util.format_string(self.name, kwargs))
python
def format_strings(self, **kwargs): """String substitution of name.""" return mutablerecords.CopyRecord( self, name=util.format_string(self.name, kwargs))
[ "def", "format_strings", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "mutablerecords", ".", "CopyRecord", "(", "self", ",", "name", "=", "util", ".", "format_string", "(", "self", ".", "name", ",", "kwargs", ")", ")" ]
String substitution of name.
[ "String", "substitution", "of", "name", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_descriptor.py#L96-L99
227,067
google/openhtf
openhtf/core/phase_descriptor.py
PhaseDescriptor.wrap_or_copy
def wrap_or_copy(cls, func, **options): """Return a new PhaseDescriptor from the given function or instance. We want to return a new copy so that you can reuse a phase with different options, plugs, measurements, etc. Args: func: A phase function or PhaseDescriptor instance. **options: Opt...
python
def wrap_or_copy(cls, func, **options): """Return a new PhaseDescriptor from the given function or instance. We want to return a new copy so that you can reuse a phase with different options, plugs, measurements, etc. Args: func: A phase function or PhaseDescriptor instance. **options: Opt...
[ "def", "wrap_or_copy", "(", "cls", ",", "func", ",", "*", "*", "options", ")", ":", "if", "isinstance", "(", "func", ",", "openhtf", ".", "PhaseGroup", ")", ":", "raise", "PhaseWrapError", "(", "'Cannot wrap PhaseGroup <%s> as a phase.'", "%", "(", "func", "...
Return a new PhaseDescriptor from the given function or instance. We want to return a new copy so that you can reuse a phase with different options, plugs, measurements, etc. Args: func: A phase function or PhaseDescriptor instance. **options: Options to update on the result. Raises: ...
[ "Return", "a", "new", "PhaseDescriptor", "from", "the", "given", "function", "or", "instance", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_descriptor.py#L135-L161
227,068
google/openhtf
openhtf/core/phase_descriptor.py
PhaseDescriptor.with_known_args
def with_known_args(self, **kwargs): """Send only known keyword-arguments to the phase when called.""" argspec = inspect.getargspec(self.func) stored = {} for key, arg in six.iteritems(kwargs): if key in argspec.args or argspec.keywords: stored[key] = arg if stored: return self.w...
python
def with_known_args(self, **kwargs): """Send only known keyword-arguments to the phase when called.""" argspec = inspect.getargspec(self.func) stored = {} for key, arg in six.iteritems(kwargs): if key in argspec.args or argspec.keywords: stored[key] = arg if stored: return self.w...
[ "def", "with_known_args", "(", "self", ",", "*", "*", "kwargs", ")", ":", "argspec", "=", "inspect", ".", "getargspec", "(", "self", ".", "func", ")", "stored", "=", "{", "}", "for", "key", ",", "arg", "in", "six", ".", "iteritems", "(", "kwargs", ...
Send only known keyword-arguments to the phase when called.
[ "Send", "only", "known", "keyword", "-", "arguments", "to", "the", "phase", "when", "called", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_descriptor.py#L179-L188
227,069
google/openhtf
openhtf/core/phase_descriptor.py
PhaseDescriptor.with_args
def with_args(self, **kwargs): """Send these keyword-arguments to the phase when called.""" # Make a copy so we can have multiple of the same phase with different args # in the same test. new_info = mutablerecords.CopyRecord(self) new_info.options = new_info.options.format_strings(**kwargs) new_...
python
def with_args(self, **kwargs): """Send these keyword-arguments to the phase when called.""" # Make a copy so we can have multiple of the same phase with different args # in the same test. new_info = mutablerecords.CopyRecord(self) new_info.options = new_info.options.format_strings(**kwargs) new_...
[ "def", "with_args", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Make a copy so we can have multiple of the same phase with different args", "# in the same test.", "new_info", "=", "mutablerecords", ".", "CopyRecord", "(", "self", ")", "new_info", ".", "options", ...
Send these keyword-arguments to the phase when called.
[ "Send", "these", "keyword", "-", "arguments", "to", "the", "phase", "when", "called", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_descriptor.py#L190-L198
227,070
google/openhtf
openhtf/core/phase_descriptor.py
PhaseDescriptor._apply_with_plugs
def _apply_with_plugs(self, subplugs, error_on_unknown): """Substitute plugs for placeholders for this phase. Args: subplugs: dict of plug name to plug class, plug classes to replace. error_on_unknown: bool, if True, then error when an unknown plug name is provided. Raises: ope...
python
def _apply_with_plugs(self, subplugs, error_on_unknown): """Substitute plugs for placeholders for this phase. Args: subplugs: dict of plug name to plug class, plug classes to replace. error_on_unknown: bool, if True, then error when an unknown plug name is provided. Raises: ope...
[ "def", "_apply_with_plugs", "(", "self", ",", "subplugs", ",", "error_on_unknown", ")", ":", "plugs_by_name", "=", "{", "plug", ".", "name", ":", "plug", "for", "plug", "in", "self", ".", "plugs", "}", "new_plugs", "=", "dict", "(", "plugs_by_name", ")", ...
Substitute plugs for placeholders for this phase. Args: subplugs: dict of plug name to plug class, plug classes to replace. error_on_unknown: bool, if True, then error when an unknown plug name is provided. Raises: openhtf.plugs.InvalidPlugError if for one of the plug names one of ...
[ "Substitute", "plugs", "for", "placeholders", "for", "this", "phase", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_descriptor.py#L208-L255
227,071
google/openhtf
openhtf/plugs/usb/usb_handle.py
requires_open_handle
def requires_open_handle(method): # pylint: disable=invalid-name """Decorator to ensure a handle is open for certain methods. Subclasses should decorate their Read() and Write() with this rather than checking their own internal state, keeping all "is this handle open" logic in is_closed(). Args: method...
python
def requires_open_handle(method): # pylint: disable=invalid-name """Decorator to ensure a handle is open for certain methods. Subclasses should decorate their Read() and Write() with this rather than checking their own internal state, keeping all "is this handle open" logic in is_closed(). Args: method...
[ "def", "requires_open_handle", "(", "method", ")", ":", "# pylint: disable=invalid-name", "@", "functools", ".", "wraps", "(", "method", ")", "def", "wrapper_requiring_open_handle", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"The wra...
Decorator to ensure a handle is open for certain methods. Subclasses should decorate their Read() and Write() with this rather than checking their own internal state, keeping all "is this handle open" logic in is_closed(). Args: method: A class method on a subclass of UsbHandle Raises: HandleClosed...
[ "Decorator", "to", "ensure", "a", "handle", "is", "open", "for", "certain", "methods", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/usb_handle.py#L36-L59
227,072
google/openhtf
openhtf/plugs/usb/usb_handle_stub.py
StubUsbHandle._dotify
def _dotify(cls, data): """Add dots.""" return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data)
python
def _dotify(cls, data): """Add dots.""" return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data)
[ "def", "_dotify", "(", "cls", ",", "data", ")", ":", "return", "''", ".", "join", "(", "char", "if", "char", "in", "cls", ".", "PRINTABLE_DATA", "else", "'.'", "for", "char", "in", "data", ")" ]
Add dots.
[ "Add", "dots", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/usb_handle_stub.py#L36-L38
227,073
google/openhtf
openhtf/plugs/usb/usb_handle_stub.py
StubUsbHandle.write
def write(self, data, dummy=None): """Stub Write method.""" assert not self.closed if self.expected_write_data is None: return expected_data = self.expected_write_data.pop(0) if expected_data != data: raise ValueError('Expected %s, got %s (%s)' % ( self._dotify(expected_data),...
python
def write(self, data, dummy=None): """Stub Write method.""" assert not self.closed if self.expected_write_data is None: return expected_data = self.expected_write_data.pop(0) if expected_data != data: raise ValueError('Expected %s, got %s (%s)' % ( self._dotify(expected_data),...
[ "def", "write", "(", "self", ",", "data", ",", "dummy", "=", "None", ")", ":", "assert", "not", "self", ".", "closed", "if", "self", ".", "expected_write_data", "is", "None", ":", "return", "expected_data", "=", "self", ".", "expected_write_data", ".", "...
Stub Write method.
[ "Stub", "Write", "method", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/usb_handle_stub.py#L40-L50
227,074
google/openhtf
openhtf/plugs/usb/usb_handle_stub.py
StubUsbHandle.read
def read(self, length, dummy=None): """Stub Read method.""" assert not self.closed data = self.expected_read_data.pop(0) if length < len(data): raise ValueError( 'Overflow packet length. Read %d bytes, got %d bytes: %s', length, len(data), self._dotify(data)) return data
python
def read(self, length, dummy=None): """Stub Read method.""" assert not self.closed data = self.expected_read_data.pop(0) if length < len(data): raise ValueError( 'Overflow packet length. Read %d bytes, got %d bytes: %s', length, len(data), self._dotify(data)) return data
[ "def", "read", "(", "self", ",", "length", ",", "dummy", "=", "None", ")", ":", "assert", "not", "self", ".", "closed", "data", "=", "self", ".", "expected_read_data", ".", "pop", "(", "0", ")", "if", "length", "<", "len", "(", "data", ")", ":", ...
Stub Read method.
[ "Stub", "Read", "method", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/usb_handle_stub.py#L52-L60
227,075
google/openhtf
openhtf/plugs/cambrionix/__init__.py
EtherSync.get_usb_serial
def get_usb_serial(self, port_num): """Get the device serial number Args: port_num: port number on the Cambrionix unit Return: usb device serial number """ port = self.port_map[str(port_num)] arg = ''.join(['DEVICE INFO,', self._addr, '.', port]) cmd = (['esuit64', '-t', arg])...
python
def get_usb_serial(self, port_num): """Get the device serial number Args: port_num: port number on the Cambrionix unit Return: usb device serial number """ port = self.port_map[str(port_num)] arg = ''.join(['DEVICE INFO,', self._addr, '.', port]) cmd = (['esuit64', '-t', arg])...
[ "def", "get_usb_serial", "(", "self", ",", "port_num", ")", ":", "port", "=", "self", ".", "port_map", "[", "str", "(", "port_num", ")", "]", "arg", "=", "''", ".", "join", "(", "[", "'DEVICE INFO,'", ",", "self", ".", "_addr", ",", "'.'", ",", "po...
Get the device serial number Args: port_num: port number on the Cambrionix unit Return: usb device serial number
[ "Get", "the", "device", "serial", "number" ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/cambrionix/__init__.py#L47-L72
227,076
google/openhtf
openhtf/plugs/cambrionix/__init__.py
EtherSync.open_usb_handle
def open_usb_handle(self, port_num): """open usb port Args: port_num: port number on the Cambrionix unit Return: usb handle """ serial = self.get_usb_serial(port_num) return local_usb.LibUsbHandle.open(serial_number=serial)
python
def open_usb_handle(self, port_num): """open usb port Args: port_num: port number on the Cambrionix unit Return: usb handle """ serial = self.get_usb_serial(port_num) return local_usb.LibUsbHandle.open(serial_number=serial)
[ "def", "open_usb_handle", "(", "self", ",", "port_num", ")", ":", "serial", "=", "self", ".", "get_usb_serial", "(", "port_num", ")", "return", "local_usb", ".", "LibUsbHandle", ".", "open", "(", "serial_number", "=", "serial", ")" ]
open usb port Args: port_num: port number on the Cambrionix unit Return: usb handle
[ "open", "usb", "port" ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/cambrionix/__init__.py#L74-L84
227,077
google/openhtf
openhtf/util/console_output.py
_printed_len
def _printed_len(some_string): """Compute the visible length of the string when printed.""" return len([x for x in ANSI_ESC_RE.sub('', some_string) if x in string.printable])
python
def _printed_len(some_string): """Compute the visible length of the string when printed.""" return len([x for x in ANSI_ESC_RE.sub('', some_string) if x in string.printable])
[ "def", "_printed_len", "(", "some_string", ")", ":", "return", "len", "(", "[", "x", "for", "x", "in", "ANSI_ESC_RE", ".", "sub", "(", "''", ",", "some_string", ")", "if", "x", "in", "string", ".", "printable", "]", ")" ]
Compute the visible length of the string when printed.
[ "Compute", "the", "visible", "length", "of", "the", "string", "when", "printed", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L65-L68
227,078
google/openhtf
openhtf/util/console_output.py
banner_print
def banner_print(msg, color='', width=60, file=sys.stdout, logger=_LOG): """Print the message as a banner with a fixed width. Also logs the message (un-bannered) to the given logger at the debug level. Args: msg: The message to print. color: Optional colorama color string to be applied to the message. Y...
python
def banner_print(msg, color='', width=60, file=sys.stdout, logger=_LOG): """Print the message as a banner with a fixed width. Also logs the message (un-bannered) to the given logger at the debug level. Args: msg: The message to print. color: Optional colorama color string to be applied to the message. Y...
[ "def", "banner_print", "(", "msg", ",", "color", "=", "''", ",", "width", "=", "60", ",", "file", "=", "sys", ".", "stdout", ",", "logger", "=", "_LOG", ")", ":", "if", "logger", ":", "logger", ".", "debug", "(", "ANSI_ESC_RE", ".", "sub", "(", "...
Print the message as a banner with a fixed width. Also logs the message (un-bannered) to the given logger at the debug level. Args: msg: The message to print. color: Optional colorama color string to be applied to the message. You can concatenate colorama color strings together in order to get any...
[ "Print", "the", "message", "as", "a", "banner", "with", "a", "fixed", "width", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L78-L109
227,079
google/openhtf
openhtf/util/console_output.py
bracket_print
def bracket_print(msg, color='', width=8, file=sys.stdout): """Prints the message in brackets in the specified color and end the line. Args: msg: The message to put inside the brackets (a brief status message). color: Optional colorama color string to be applied to the message. You can concatenate ...
python
def bracket_print(msg, color='', width=8, file=sys.stdout): """Prints the message in brackets in the specified color and end the line. Args: msg: The message to put inside the brackets (a brief status message). color: Optional colorama color string to be applied to the message. You can concatenate ...
[ "def", "bracket_print", "(", "msg", ",", "color", "=", "''", ",", "width", "=", "8", ",", "file", "=", "sys", ".", "stdout", ")", ":", "if", "CLI_QUIET", ":", "return", "lpad", "=", "int", "(", "math", ".", "ceil", "(", "(", "width", "-", "2", ...
Prints the message in brackets in the specified color and end the line. Args: msg: The message to put inside the brackets (a brief status message). color: Optional colorama color string to be applied to the message. You can concatenate colorama color strings together in order to get any set of ...
[ "Prints", "the", "message", "in", "brackets", "in", "the", "specified", "color", "and", "end", "the", "line", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L112-L133
227,080
google/openhtf
openhtf/util/console_output.py
cli_print
def cli_print(msg, color='', end=None, file=sys.stdout, logger=_LOG): """Print the message to file and also log it. This function is intended as a 'tee' mechanism to enable the CLI interface as a first-class citizen, while ensuring that everything the operator sees also has an analogous logging entry in the te...
python
def cli_print(msg, color='', end=None, file=sys.stdout, logger=_LOG): """Print the message to file and also log it. This function is intended as a 'tee' mechanism to enable the CLI interface as a first-class citizen, while ensuring that everything the operator sees also has an analogous logging entry in the te...
[ "def", "cli_print", "(", "msg", ",", "color", "=", "''", ",", "end", "=", "None", ",", "file", "=", "sys", ".", "stdout", ",", "logger", "=", "_LOG", ")", ":", "if", "logger", ":", "logger", ".", "debug", "(", "'-> {}'", ".", "format", "(", "msg"...
Print the message to file and also log it. This function is intended as a 'tee' mechanism to enable the CLI interface as a first-class citizen, while ensuring that everything the operator sees also has an analogous logging entry in the test record for later inspection. Args: msg: The message to print/log....
[ "Print", "the", "message", "to", "file", "and", "also", "log", "it", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L136-L160
227,081
google/openhtf
openhtf/util/console_output.py
error_print
def error_print(msg, color=colorama.Fore.RED, file=sys.stderr): """Print the error message to the file in the specified color. Args: msg: The error message to be printed. color: Optional colorama color string to be applied to the message. You can concatenate colorama color strings together here, bu...
python
def error_print(msg, color=colorama.Fore.RED, file=sys.stderr): """Print the error message to the file in the specified color. Args: msg: The error message to be printed. color: Optional colorama color string to be applied to the message. You can concatenate colorama color strings together here, bu...
[ "def", "error_print", "(", "msg", ",", "color", "=", "colorama", ".", "Fore", ".", "RED", ",", "file", "=", "sys", ".", "stderr", ")", ":", "if", "CLI_QUIET", ":", "return", "file", ".", "write", "(", "'{sep}{bright}{color}Error: {normal}{msg}{sep}{reset}'", ...
Print the error message to the file in the specified color. Args: msg: The error message to be printed. color: Optional colorama color string to be applied to the message. You can concatenate colorama color strings together here, but note that style strings will not be applied. file: A fi...
[ "Print", "the", "error", "message", "to", "the", "file", "in", "the", "specified", "color", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L163-L179
227,082
google/openhtf
openhtf/util/console_output.py
action_result_context
def action_result_context(action_text, width=60, status_width=8, succeed_text='OK', fail_text='FAIL', unknown_text='????', file=sys.stdout, ...
python
def action_result_context(action_text, width=60, status_width=8, succeed_text='OK', fail_text='FAIL', unknown_text='????', file=sys.stdout, ...
[ "def", "action_result_context", "(", "action_text", ",", "width", "=", "60", ",", "status_width", "=", "8", ",", "succeed_text", "=", "'OK'", ",", "fail_text", "=", "'FAIL'", ",", "unknown_text", "=", "'????'", ",", "file", "=", "sys", ".", "stdout", ",", ...
A contextmanager that prints actions and results to the CLI. When entering the context, the action will be printed, and when the context is exited, the result will be printed. The object yielded by the context is used to mark the action as a success or failure, and a raise from inside the context will also res...
[ "A", "contextmanager", "that", "prints", "actions", "and", "results", "to", "the", "CLI", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L204-L290
227,083
google/openhtf
openhtf/util/exceptions.py
reraise
def reraise(exc_type, message=None, *args, **kwargs): # pylint: disable=invalid-name """reraises an exception for exception translation. This is primarily used for when you immediately reraise an exception that is thrown in a library, so that your client will not have to depend on various exceptions defined i...
python
def reraise(exc_type, message=None, *args, **kwargs): # pylint: disable=invalid-name """reraises an exception for exception translation. This is primarily used for when you immediately reraise an exception that is thrown in a library, so that your client will not have to depend on various exceptions defined i...
[ "def", "reraise", "(", "exc_type", ",", "message", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=invalid-name", "last_lineno", "=", "inspect", ".", "currentframe", "(", ")", ".", "f_back", ".", "f_lineno", "line_msg", ...
reraises an exception for exception translation. This is primarily used for when you immediately reraise an exception that is thrown in a library, so that your client will not have to depend on various exceptions defined in the library implementation that is being abstracted. The advantage of this helper funct...
[ "reraises", "an", "exception", "for", "exception", "translation", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/exceptions.py#L22-L74
227,084
rflamary/POT
ot/plot.py
plot1D_mat
def plot1D_mat(a, b, M, title=''): """ Plot matrix M with the source and target 1D distribution Creates a subplot with the source distribution a on the left and target distribution b on the tot. The matrix M is shown in between. Parameters ---------- a : np.array, shape (na,) Source ...
python
def plot1D_mat(a, b, M, title=''): """ Plot matrix M with the source and target 1D distribution Creates a subplot with the source distribution a on the left and target distribution b on the tot. The matrix M is shown in between. Parameters ---------- a : np.array, shape (na,) Source ...
[ "def", "plot1D_mat", "(", "a", ",", "b", ",", "M", ",", "title", "=", "''", ")", ":", "na", ",", "nb", "=", "M", ".", "shape", "gs", "=", "gridspec", ".", "GridSpec", "(", "3", ",", "3", ")", "xa", "=", "np", ".", "arange", "(", "na", ")", ...
Plot matrix M with the source and target 1D distribution Creates a subplot with the source distribution a on the left and target distribution b on the tot. The matrix M is shown in between. Parameters ---------- a : np.array, shape (na,) Source distribution b : np.array, shape (nb,) ...
[ "Plot", "matrix", "M", "with", "the", "source", "and", "target", "1D", "distribution" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/plot.py#L14-L54
227,085
rflamary/POT
ot/plot.py
plot2D_samples_mat
def plot2D_samples_mat(xs, xt, G, thr=1e-8, **kwargs): """ Plot matrix M in 2D with lines using alpha values Plot lines between source and target 2D samples with a color proportional to the value of the matrix G between samples. Parameters ---------- xs : ndarray, shape (ns,2) Sourc...
python
def plot2D_samples_mat(xs, xt, G, thr=1e-8, **kwargs): """ Plot matrix M in 2D with lines using alpha values Plot lines between source and target 2D samples with a color proportional to the value of the matrix G between samples. Parameters ---------- xs : ndarray, shape (ns,2) Sourc...
[ "def", "plot2D_samples_mat", "(", "xs", ",", "xt", ",", "G", ",", "thr", "=", "1e-8", ",", "*", "*", "kwargs", ")", ":", "if", "(", "'color'", "not", "in", "kwargs", ")", "and", "(", "'c'", "not", "in", "kwargs", ")", ":", "kwargs", "[", "'color'...
Plot matrix M in 2D with lines using alpha values Plot lines between source and target 2D samples with a color proportional to the value of the matrix G between samples. Parameters ---------- xs : ndarray, shape (ns,2) Source samples positions b : ndarray, shape (nt,2) Targe...
[ "Plot", "matrix", "M", "in", "2D", "with", "lines", "using", "alpha", "values" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/plot.py#L57-L85
227,086
rflamary/POT
ot/gpu/da.py
sinkhorn_lpl1_mm
def sinkhorn_lpl1_mm(a, labels_a, b, M, reg, eta=0.1, numItermax=10, numInnerItermax=200, stopInnerThr=1e-9, verbose=False, log=False, to_numpy=True): """ Solve the entropic regularization optimal transport problem with nonconvex group lasso regularization on GPU ...
python
def sinkhorn_lpl1_mm(a, labels_a, b, M, reg, eta=0.1, numItermax=10, numInnerItermax=200, stopInnerThr=1e-9, verbose=False, log=False, to_numpy=True): """ Solve the entropic regularization optimal transport problem with nonconvex group lasso regularization on GPU ...
[ "def", "sinkhorn_lpl1_mm", "(", "a", ",", "labels_a", ",", "b", ",", "M", ",", "reg", ",", "eta", "=", "0.1", ",", "numItermax", "=", "10", ",", "numInnerItermax", "=", "200", ",", "stopInnerThr", "=", "1e-9", ",", "verbose", "=", "False", ",", "log"...
Solve the entropic regularization optimal transport problem with nonconvex group lasso regularization on GPU If the input matrix are in numpy format, they will be uploaded to the GPU first which can incur significant time overhead. The function solves the following optimization problem: .. math:...
[ "Solve", "the", "entropic", "regularization", "optimal", "transport", "problem", "with", "nonconvex", "group", "lasso", "regularization", "on", "GPU" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/gpu/da.py#L22-L144
227,087
rflamary/POT
ot/datasets.py
get_2D_samples_gauss
def get_2D_samples_gauss(n, m, sigma, random_state=None): """ Deprecated see make_2D_samples_gauss """ return make_2D_samples_gauss(n, m, sigma, random_state=None)
python
def get_2D_samples_gauss(n, m, sigma, random_state=None): """ Deprecated see make_2D_samples_gauss """ return make_2D_samples_gauss(n, m, sigma, random_state=None)
[ "def", "get_2D_samples_gauss", "(", "n", ",", "m", ",", "sigma", ",", "random_state", "=", "None", ")", ":", "return", "make_2D_samples_gauss", "(", "n", ",", "m", ",", "sigma", ",", "random_state", "=", "None", ")" ]
Deprecated see make_2D_samples_gauss
[ "Deprecated", "see", "make_2D_samples_gauss" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/datasets.py#L83-L85
227,088
rflamary/POT
ot/datasets.py
get_data_classif
def get_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs): """ Deprecated see make_data_classif """ return make_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs)
python
def get_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs): """ Deprecated see make_data_classif """ return make_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs)
[ "def", "get_data_classif", "(", "dataset", ",", "n", ",", "nz", "=", ".5", ",", "theta", "=", "0", ",", "random_state", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "make_data_classif", "(", "dataset", ",", "n", ",", "nz", "=", ".5", "...
Deprecated see make_data_classif
[ "Deprecated", "see", "make_data_classif" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/datasets.py#L170-L172
227,089
rflamary/POT
ot/bregman.py
sinkhorn
def sinkhorn(a, b, M, reg, method='sinkhorn', numItermax=1000, stopThr=1e-9, verbose=False, log=False, **kwargs): u""" Solve the entropic regularization optimal transport problem and return the OT matrix The function solves the following optimization problem: .. math:: \gamma = ar...
python
def sinkhorn(a, b, M, reg, method='sinkhorn', numItermax=1000, stopThr=1e-9, verbose=False, log=False, **kwargs): u""" Solve the entropic regularization optimal transport problem and return the OT matrix The function solves the following optimization problem: .. math:: \gamma = ar...
[ "def", "sinkhorn", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "method", "=", "'sinkhorn'", ",", "numItermax", "=", "1000", ",", "stopThr", "=", "1e-9", ",", "verbose", "=", "False", ",", "log", "=", "False", ",", "*", "*", "kwargs", ")", ":",...
u""" Solve the entropic regularization optimal transport problem and return the OT matrix The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq ...
[ "u", "Solve", "the", "entropic", "regularization", "optimal", "transport", "problem", "and", "return", "the", "OT", "matrix" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L16-L128
227,090
rflamary/POT
ot/bregman.py
sinkhorn2
def sinkhorn2(a, b, M, reg, method='sinkhorn', numItermax=1000, stopThr=1e-9, verbose=False, log=False, **kwargs): u""" Solve the entropic regularization optimal transport problem and return the loss The function solves the following optimization problem: .. math:: W = \min_\gamm...
python
def sinkhorn2(a, b, M, reg, method='sinkhorn', numItermax=1000, stopThr=1e-9, verbose=False, log=False, **kwargs): u""" Solve the entropic regularization optimal transport problem and return the loss The function solves the following optimization problem: .. math:: W = \min_\gamm...
[ "def", "sinkhorn2", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "method", "=", "'sinkhorn'", ",", "numItermax", "=", "1000", ",", "stopThr", "=", "1e-9", ",", "verbose", "=", "False", ",", "log", "=", "False", ",", "*", "*", "kwargs", ")", ":"...
u""" Solve the entropic regularization optimal transport problem and return the loss The function solves the following optimization problem: .. math:: W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where :...
[ "u", "Solve", "the", "entropic", "regularization", "optimal", "transport", "problem", "and", "return", "the", "loss" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L131-L245
227,091
rflamary/POT
ot/bregman.py
geometricBar
def geometricBar(weights, alldistribT): """return the weighted geometric mean of distributions""" assert(len(weights) == alldistribT.shape[1]) return np.exp(np.dot(np.log(alldistribT), weights.T))
python
def geometricBar(weights, alldistribT): """return the weighted geometric mean of distributions""" assert(len(weights) == alldistribT.shape[1]) return np.exp(np.dot(np.log(alldistribT), weights.T))
[ "def", "geometricBar", "(", "weights", ",", "alldistribT", ")", ":", "assert", "(", "len", "(", "weights", ")", "==", "alldistribT", ".", "shape", "[", "1", "]", ")", "return", "np", ".", "exp", "(", "np", ".", "dot", "(", "np", ".", "log", "(", ...
return the weighted geometric mean of distributions
[ "return", "the", "weighted", "geometric", "mean", "of", "distributions" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L968-L971
227,092
rflamary/POT
ot/bregman.py
geometricMean
def geometricMean(alldistribT): """return the geometric mean of distributions""" return np.exp(np.mean(np.log(alldistribT), axis=1))
python
def geometricMean(alldistribT): """return the geometric mean of distributions""" return np.exp(np.mean(np.log(alldistribT), axis=1))
[ "def", "geometricMean", "(", "alldistribT", ")", ":", "return", "np", ".", "exp", "(", "np", ".", "mean", "(", "np", ".", "log", "(", "alldistribT", ")", ",", "axis", "=", "1", ")", ")" ]
return the geometric mean of distributions
[ "return", "the", "geometric", "mean", "of", "distributions" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L974-L976
227,093
rflamary/POT
ot/bregman.py
projR
def projR(gamma, p): """return the KL projection on the row constrints """ return np.multiply(gamma.T, p / np.maximum(np.sum(gamma, axis=1), 1e-10)).T
python
def projR(gamma, p): """return the KL projection on the row constrints """ return np.multiply(gamma.T, p / np.maximum(np.sum(gamma, axis=1), 1e-10)).T
[ "def", "projR", "(", "gamma", ",", "p", ")", ":", "return", "np", ".", "multiply", "(", "gamma", ".", "T", ",", "p", "/", "np", ".", "maximum", "(", "np", ".", "sum", "(", "gamma", ",", "axis", "=", "1", ")", ",", "1e-10", ")", ")", ".", "T...
return the KL projection on the row constrints
[ "return", "the", "KL", "projection", "on", "the", "row", "constrints" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L979-L981
227,094
rflamary/POT
ot/bregman.py
projC
def projC(gamma, q): """return the KL projection on the column constrints """ return np.multiply(gamma, q / np.maximum(np.sum(gamma, axis=0), 1e-10))
python
def projC(gamma, q): """return the KL projection on the column constrints """ return np.multiply(gamma, q / np.maximum(np.sum(gamma, axis=0), 1e-10))
[ "def", "projC", "(", "gamma", ",", "q", ")", ":", "return", "np", ".", "multiply", "(", "gamma", ",", "q", "/", "np", ".", "maximum", "(", "np", ".", "sum", "(", "gamma", ",", "axis", "=", "0", ")", ",", "1e-10", ")", ")" ]
return the KL projection on the column constrints
[ "return", "the", "KL", "projection", "on", "the", "column", "constrints" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L984-L986
227,095
rflamary/POT
ot/bregman.py
barycenter
def barycenter(A, M, reg, weights=None, numItermax=1000, stopThr=1e-4, verbose=False, log=False): """Compute the entropic regularized wasserstein barycenter of distributions A The function solves the following optimization problem: .. math:: \mathbf{a} = arg\min_\mathbf{a} \sum_i W_...
python
def barycenter(A, M, reg, weights=None, numItermax=1000, stopThr=1e-4, verbose=False, log=False): """Compute the entropic regularized wasserstein barycenter of distributions A The function solves the following optimization problem: .. math:: \mathbf{a} = arg\min_\mathbf{a} \sum_i W_...
[ "def", "barycenter", "(", "A", ",", "M", ",", "reg", ",", "weights", "=", "None", ",", "numItermax", "=", "1000", ",", "stopThr", "=", "1e-4", ",", "verbose", "=", "False", ",", "log", "=", "False", ")", ":", "if", "weights", "is", "None", ":", "...
Compute the entropic regularized wasserstein barycenter of distributions A The function solves the following optimization problem: .. math:: \mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i) where : - :math:`W_{reg}(\cdot,\cdot)` is the entropic regularized Wasserstein ...
[ "Compute", "the", "entropic", "regularized", "wasserstein", "barycenter", "of", "distributions", "A" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L989-L1082
227,096
rflamary/POT
ot/bregman.py
convolutional_barycenter2d
def convolutional_barycenter2d(A, reg, weights=None, numItermax=10000, stopThr=1e-9, stabThr=1e-30, verbose=False, log=False): """Compute the entropic regularized wasserstein barycenter of distributions A where A is a collection of 2D images. The function solves the following optimization problem: .....
python
def convolutional_barycenter2d(A, reg, weights=None, numItermax=10000, stopThr=1e-9, stabThr=1e-30, verbose=False, log=False): """Compute the entropic regularized wasserstein barycenter of distributions A where A is a collection of 2D images. The function solves the following optimization problem: .....
[ "def", "convolutional_barycenter2d", "(", "A", ",", "reg", ",", "weights", "=", "None", ",", "numItermax", "=", "10000", ",", "stopThr", "=", "1e-9", ",", "stabThr", "=", "1e-30", ",", "verbose", "=", "False", ",", "log", "=", "False", ")", ":", "if", ...
Compute the entropic regularized wasserstein barycenter of distributions A where A is a collection of 2D images. The function solves the following optimization problem: .. math:: \mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i) where : - :math:`W_{reg}(\cdot,\cdot)...
[ "Compute", "the", "entropic", "regularized", "wasserstein", "barycenter", "of", "distributions", "A", "where", "A", "is", "a", "collection", "of", "2D", "images", "." ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L1085-L1192
227,097
rflamary/POT
ot/bregman.py
unmix
def unmix(a, D, M, M0, h0, reg, reg0, alpha, numItermax=1000, stopThr=1e-3, verbose=False, log=False): """ Compute the unmixing of an observation with a given dictionary using Wasserstein distance The function solve the following optimization problem: .. math:: \mathbf{h} = arg\min_\m...
python
def unmix(a, D, M, M0, h0, reg, reg0, alpha, numItermax=1000, stopThr=1e-3, verbose=False, log=False): """ Compute the unmixing of an observation with a given dictionary using Wasserstein distance The function solve the following optimization problem: .. math:: \mathbf{h} = arg\min_\m...
[ "def", "unmix", "(", "a", ",", "D", ",", "M", ",", "M0", ",", "h0", ",", "reg", ",", "reg0", ",", "alpha", ",", "numItermax", "=", "1000", ",", "stopThr", "=", "1e-3", ",", "verbose", "=", "False", ",", "log", "=", "False", ")", ":", "# M = M/n...
Compute the unmixing of an observation with a given dictionary using Wasserstein distance The function solve the following optimization problem: .. math:: \mathbf{h} = arg\min_\mathbf{h} (1- \\alpha) W_{M,reg}(\mathbf{a},\mathbf{Dh})+\\alpha W_{M0,reg0}(\mathbf{h}_0,\mathbf{h}) where : - :m...
[ "Compute", "the", "unmixing", "of", "an", "observation", "with", "a", "given", "dictionary", "using", "Wasserstein", "distance" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L1195-L1300
227,098
rflamary/POT
ot/bregman.py
empirical_sinkhorn
def empirical_sinkhorn(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs): ''' Solve the entropic regularization optimal transport problem and return the OT matrix from empirical data The function solves the following optimization pr...
python
def empirical_sinkhorn(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs): ''' Solve the entropic regularization optimal transport problem and return the OT matrix from empirical data The function solves the following optimization pr...
[ "def", "empirical_sinkhorn", "(", "X_s", ",", "X_t", ",", "reg", ",", "a", "=", "None", ",", "b", "=", "None", ",", "metric", "=", "'sqeuclidean'", ",", "numIterMax", "=", "10000", ",", "stopThr", "=", "1e-9", ",", "verbose", "=", "False", ",", "log"...
Solve the entropic regularization optimal transport problem and return the OT matrix from empirical data The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b ...
[ "Solve", "the", "entropic", "regularization", "optimal", "transport", "problem", "and", "return", "the", "OT", "matrix", "from", "empirical", "data" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L1303-L1390
227,099
rflamary/POT
ot/bregman.py
empirical_sinkhorn2
def empirical_sinkhorn2(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs): ''' Solve the entropic regularization optimal transport problem from empirical data and return the OT loss The function solves the following optimization pr...
python
def empirical_sinkhorn2(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs): ''' Solve the entropic regularization optimal transport problem from empirical data and return the OT loss The function solves the following optimization pr...
[ "def", "empirical_sinkhorn2", "(", "X_s", ",", "X_t", ",", "reg", ",", "a", "=", "None", ",", "b", "=", "None", ",", "metric", "=", "'sqeuclidean'", ",", "numIterMax", "=", "10000", ",", "stopThr", "=", "1e-9", ",", "verbose", "=", "False", ",", "log...
Solve the entropic regularization optimal transport problem from empirical data and return the OT loss The function solves the following optimization problem: .. math:: W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamm...
[ "Solve", "the", "entropic", "regularization", "optimal", "transport", "problem", "from", "empirical", "data", "and", "return", "the", "OT", "loss" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L1393-L1480