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 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
google/openhtf | openhtf/plugs/usb/adb_protocol.py | AdbStreamTransport.enqueue_message | def enqueue_message(self, message, timeout):
"""Add the given message to this transport's queue.
This method also handles ACKing any WRTE messages.
Args:
message: The AdbMessage to enqueue.
timeout: The timeout to use for the operation. Specifically, WRTE
messages cause an OKAY to be ... | python | def enqueue_message(self, message, timeout):
"""Add the given message to this transport's queue.
This method also handles ACKing any WRTE messages.
Args:
message: The AdbMessage to enqueue.
timeout: The timeout to use for the operation. Specifically, WRTE
messages cause an OKAY to be ... | [
"def",
"enqueue_message",
"(",
"self",
",",
"message",
",",
"timeout",
")",
":",
"# Ack WRTE messages immediately, handle our OPEN ack if it gets enqueued.",
"if",
"message",
".",
"command",
"==",
"'WRTE'",
":",
"self",
".",
"_send_command",
"(",
"'OKAY'",
",",
"timeo... | Add the given message to this transport's queue.
This method also handles ACKing any WRTE messages.
Args:
message: The AdbMessage to enqueue.
timeout: The timeout to use for the operation. Specifically, WRTE
messages cause an OKAY to be sent; timeout is used for that send. | [
"Add",
"the",
"given",
"message",
"to",
"this",
"transport",
"s",
"queue",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L440-L455 | train |
google/openhtf | openhtf/plugs/usb/adb_protocol.py | AdbStreamTransport.write | def write(self, data, timeout):
"""Write data to this stream, using the given timeouts.PolledTimeout."""
if not self.remote_id:
raise usb_exceptions.AdbStreamClosedError(
'Cannot write() to half-opened %s', self)
if self.closed_state != self.ClosedState.OPEN:
raise usb_exceptions.AdbSt... | python | def write(self, data, timeout):
"""Write data to this stream, using the given timeouts.PolledTimeout."""
if not self.remote_id:
raise usb_exceptions.AdbStreamClosedError(
'Cannot write() to half-opened %s', self)
if self.closed_state != self.ClosedState.OPEN:
raise usb_exceptions.AdbSt... | [
"def",
"write",
"(",
"self",
",",
"data",
",",
"timeout",
")",
":",
"if",
"not",
"self",
".",
"remote_id",
":",
"raise",
"usb_exceptions",
".",
"AdbStreamClosedError",
"(",
"'Cannot write() to half-opened %s'",
",",
"self",
")",
"if",
"self",
".",
"closed_stat... | Write data to this stream, using the given timeouts.PolledTimeout. | [
"Write",
"data",
"to",
"this",
"stream",
"using",
"the",
"given",
"timeouts",
".",
"PolledTimeout",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L457-L474 | train |
google/openhtf | openhtf/plugs/usb/adb_protocol.py | AdbStreamTransport.read | def read(self, length, timeout):
"""Read 'length' bytes from this stream transport.
Args:
length: If not 0, read this many bytes from the stream, otherwise read all
available data (at least one byte).
timeout: timeouts.PolledTimeout to use for this read operation.
Returns:
The by... | python | def read(self, length, timeout):
"""Read 'length' bytes from this stream transport.
Args:
length: If not 0, read this many bytes from the stream, otherwise read all
available data (at least one byte).
timeout: timeouts.PolledTimeout to use for this read operation.
Returns:
The by... | [
"def",
"read",
"(",
"self",
",",
"length",
",",
"timeout",
")",
":",
"self",
".",
"_read_messages_until_true",
"(",
"lambda",
":",
"self",
".",
"_buffer_size",
"and",
"self",
".",
"_buffer_size",
">=",
"length",
",",
"timeout",
")",
"with",
"self",
".",
... | Read 'length' bytes from this stream transport.
Args:
length: If not 0, read this many bytes from the stream, otherwise read all
available data (at least one byte).
timeout: timeouts.PolledTimeout to use for this read operation.
Returns:
The bytes read from this stream. | [
"Read",
"length",
"bytes",
"from",
"this",
"stream",
"transport",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L476-L498 | train |
google/openhtf | openhtf/plugs/usb/adb_protocol.py | AdbConnection._make_stream_transport | def _make_stream_transport(self):
"""Create an AdbStreamTransport with a newly allocated local_id."""
msg_queue = queue.Queue()
with self._stream_transport_map_lock:
# Start one past the last id we used, and grab the first available one.
# This mimics the ADB behavior of 'increment an unsigned a... | python | def _make_stream_transport(self):
"""Create an AdbStreamTransport with a newly allocated local_id."""
msg_queue = queue.Queue()
with self._stream_transport_map_lock:
# Start one past the last id we used, and grab the first available one.
# This mimics the ADB behavior of 'increment an unsigned a... | [
"def",
"_make_stream_transport",
"(",
"self",
")",
":",
"msg_queue",
"=",
"queue",
".",
"Queue",
"(",
")",
"with",
"self",
".",
"_stream_transport_map_lock",
":",
"# Start one past the last id we used, and grab the first available one.",
"# This mimics the ADB behavior of 'incr... | Create an AdbStreamTransport with a newly allocated local_id. | [
"Create",
"an",
"AdbStreamTransport",
"with",
"a",
"newly",
"allocated",
"local_id",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L568-L594 | train |
google/openhtf | openhtf/plugs/usb/adb_protocol.py | AdbConnection._handle_message_for_stream | def _handle_message_for_stream(self, stream_transport, message, timeout):
"""Handle an incoming message, check if it's for the given stream.
If the message is not for the stream, then add it to the appropriate
message queue.
Args:
stream_transport: AdbStreamTransport currently waiting on a messa... | python | def _handle_message_for_stream(self, stream_transport, message, timeout):
"""Handle an incoming message, check if it's for the given stream.
If the message is not for the stream, then add it to the appropriate
message queue.
Args:
stream_transport: AdbStreamTransport currently waiting on a messa... | [
"def",
"_handle_message_for_stream",
"(",
"self",
",",
"stream_transport",
",",
"message",
",",
"timeout",
")",
":",
"if",
"message",
".",
"command",
"not",
"in",
"(",
"'OKAY'",
",",
"'CLSE'",
",",
"'WRTE'",
")",
":",
"raise",
"usb_exceptions",
".",
"AdbProt... | Handle an incoming message, check if it's for the given stream.
If the message is not for the stream, then add it to the appropriate
message queue.
Args:
stream_transport: AdbStreamTransport currently waiting on a message.
message: Message to check and handle.
timeout: Timeout to use for... | [
"Handle",
"an",
"incoming",
"message",
"check",
"if",
"it",
"s",
"for",
"the",
"given",
"stream",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L596-L642 | train |
google/openhtf | openhtf/plugs/usb/adb_protocol.py | AdbConnection.open_stream | def open_stream(self, destination, timeout_ms=None):
"""Opens a new stream to a destination service on the device.
Not the same as the posix 'open' or any other Open methods, this
corresponds to the OPEN message described in the ADB protocol
documentation mentioned above. It creates a stream (uniquely... | python | def open_stream(self, destination, timeout_ms=None):
"""Opens a new stream to a destination service on the device.
Not the same as the posix 'open' or any other Open methods, this
corresponds to the OPEN message described in the ADB protocol
documentation mentioned above. It creates a stream (uniquely... | [
"def",
"open_stream",
"(",
"self",
",",
"destination",
",",
"timeout_ms",
"=",
"None",
")",
":",
"timeout",
"=",
"timeouts",
".",
"PolledTimeout",
".",
"from_millis",
"(",
"timeout_ms",
")",
"stream_transport",
"=",
"self",
".",
"_make_stream_transport",
"(",
... | Opens a new stream to a destination service on the device.
Not the same as the posix 'open' or any other Open methods, this
corresponds to the OPEN message described in the ADB protocol
documentation mentioned above. It creates a stream (uniquely identified
by remote/local ids) that connects to a part... | [
"Opens",
"a",
"new",
"stream",
"to",
"a",
"destination",
"service",
"on",
"the",
"device",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L648-L680 | train |
google/openhtf | openhtf/plugs/usb/adb_protocol.py | AdbConnection.close_stream_transport | def close_stream_transport(self, stream_transport, timeout):
"""Remove the given stream transport's id from our map of id's.
If the stream id is actually removed, we send a CLSE message to let the
remote end know (this happens when we are ack'ing a CLSE message we
received). The ADB protocol doesn't s... | python | def close_stream_transport(self, stream_transport, timeout):
"""Remove the given stream transport's id from our map of id's.
If the stream id is actually removed, we send a CLSE message to let the
remote end know (this happens when we are ack'ing a CLSE message we
received). The ADB protocol doesn't s... | [
"def",
"close_stream_transport",
"(",
"self",
",",
"stream_transport",
",",
"timeout",
")",
":",
"with",
"self",
".",
"_stream_transport_map_lock",
":",
"if",
"stream_transport",
".",
"local_id",
"in",
"self",
".",
"_stream_transport_map",
":",
"del",
"self",
".",... | Remove the given stream transport's id from our map of id's.
If the stream id is actually removed, we send a CLSE message to let the
remote end know (this happens when we are ack'ing a CLSE message we
received). The ADB protocol doesn't say this is a requirement, but ADB
does it, so we do too.
Ar... | [
"Remove",
"the",
"given",
"stream",
"transport",
"s",
"id",
"from",
"our",
"map",
"of",
"id",
"s",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L682-L707 | train |
google/openhtf | openhtf/plugs/usb/adb_protocol.py | AdbConnection.streaming_command | def streaming_command(self, service, command='', timeout_ms=None):
"""One complete set of packets for a single command.
Helper function to call open_stream and yield the output. Sends
service:command in a new connection, reading the data for the response. All
the data is held in memory, large response... | python | def streaming_command(self, service, command='', timeout_ms=None):
"""One complete set of packets for a single command.
Helper function to call open_stream and yield the output. Sends
service:command in a new connection, reading the data for the response. All
the data is held in memory, large response... | [
"def",
"streaming_command",
"(",
"self",
",",
"service",
",",
"command",
"=",
"''",
",",
"timeout_ms",
"=",
"None",
")",
":",
"timeout",
"=",
"timeouts",
".",
"PolledTimeout",
".",
"from_millis",
"(",
"timeout_ms",
")",
"stream",
"=",
"self",
".",
"open_st... | One complete set of packets for a single command.
Helper function to call open_stream and yield the output. Sends
service:command in a new connection, reading the data for the response. All
the data is held in memory, large responses will be slow and can fill up
memory.
Args:
service: The s... | [
"One",
"complete",
"set",
"of",
"packets",
"for",
"a",
"single",
"command",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L709-L732 | train |
google/openhtf | openhtf/plugs/usb/adb_protocol.py | AdbConnection.read_for_stream | def read_for_stream(self, stream_transport, timeout_ms=None):
"""Attempt to read a packet for the given stream transport.
Will read packets from self.transport until one intended for the given
AdbStream is found. If another thread is already reading packets, this will
block until that thread reads a p... | python | def read_for_stream(self, stream_transport, timeout_ms=None):
"""Attempt to read a packet for the given stream transport.
Will read packets from self.transport until one intended for the given
AdbStream is found. If another thread is already reading packets, this will
block until that thread reads a p... | [
"def",
"read_for_stream",
"(",
"self",
",",
"stream_transport",
",",
"timeout_ms",
"=",
"None",
")",
":",
"timeout",
"=",
"timeouts",
".",
"PolledTimeout",
".",
"from_millis",
"(",
"timeout_ms",
")",
"# Bail when the timeout expires, or when we no longer have the given st... | Attempt to read a packet for the given stream transport.
Will read packets from self.transport until one intended for the given
AdbStream is found. If another thread is already reading packets, this will
block until that thread reads a packet for this stream, or timeout expires.
Note that this method ... | [
"Attempt",
"to",
"read",
"a",
"packet",
"for",
"the",
"given",
"stream",
"transport",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L734-L823 | train |
google/openhtf | openhtf/plugs/usb/adb_protocol.py | AdbConnection.connect | def connect(cls, transport, rsa_keys=None, timeout_ms=1000,
auth_timeout_ms=100):
"""Establish a new connection to a device, connected via transport.
Args:
transport: A transport to use for reads/writes from/to the device,
usually an instance of UsbHandle, but really it can be anyth... | python | def connect(cls, transport, rsa_keys=None, timeout_ms=1000,
auth_timeout_ms=100):
"""Establish a new connection to a device, connected via transport.
Args:
transport: A transport to use for reads/writes from/to the device,
usually an instance of UsbHandle, but really it can be anyth... | [
"def",
"connect",
"(",
"cls",
",",
"transport",
",",
"rsa_keys",
"=",
"None",
",",
"timeout_ms",
"=",
"1000",
",",
"auth_timeout_ms",
"=",
"100",
")",
":",
"timeout",
"=",
"timeouts",
".",
"PolledTimeout",
".",
"from_millis",
"(",
"timeout_ms",
")",
"if",
... | Establish a new connection to a device, connected via transport.
Args:
transport: A transport to use for reads/writes from/to the device,
usually an instance of UsbHandle, but really it can be anything with
read() and write() methods.
rsa_keys: List of AuthSigner subclass instances to b... | [
"Establish",
"a",
"new",
"connection",
"to",
"a",
"device",
"connected",
"via",
"transport",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L826-L912 | train |
google/openhtf | examples/example_plugs.py | ExamplePlug.increment | def increment(self):
"""Increment our value, return the previous value."""
self.value += self.increment_size
return self.value - self.increment_size | python | def increment(self):
"""Increment our value, return the previous value."""
self.value += self.increment_size
return self.value - self.increment_size | [
"def",
"increment",
"(",
"self",
")",
":",
"self",
".",
"value",
"+=",
"self",
".",
"increment_size",
"return",
"self",
".",
"value",
"-",
"self",
".",
"increment_size"
] | Increment our value, return the previous value. | [
"Increment",
"our",
"value",
"return",
"the",
"previous",
"value",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/examples/example_plugs.py#L76-L79 | train |
google/openhtf | openhtf/plugs/__init__.py | plug | def plug(update_kwargs=True, **plugs_map):
"""Creates a decorator that passes in plugs when invoked.
This function returns a decorator for a function that will replace positional
arguments to that function with the plugs specified. See the module
docstring for details and examples.
Note this decorator does... | python | def plug(update_kwargs=True, **plugs_map):
"""Creates a decorator that passes in plugs when invoked.
This function returns a decorator for a function that will replace positional
arguments to that function with the plugs specified. See the module
docstring for details and examples.
Note this decorator does... | [
"def",
"plug",
"(",
"update_kwargs",
"=",
"True",
",",
"*",
"*",
"plugs_map",
")",
":",
"for",
"a_plug",
"in",
"plugs_map",
".",
"values",
"(",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"a_plug",
",",
"PlugPlaceholder",
")",
"or",
"issubclass",
"(... | Creates a decorator that passes in plugs when invoked.
This function returns a decorator for a function that will replace positional
arguments to that function with the plugs specified. See the module
docstring for details and examples.
Note this decorator does not work with class or bound methods, but does ... | [
"Creates",
"a",
"decorator",
"that",
"passes",
"in",
"plugs",
"when",
"invoked",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/__init__.py#L217-L269 | train |
google/openhtf | openhtf/plugs/__init__.py | BasePlug.uses_base_tear_down | def uses_base_tear_down(cls):
"""Checks whether the tearDown method is the BasePlug implementation."""
this_tear_down = getattr(cls, 'tearDown')
base_tear_down = getattr(BasePlug, 'tearDown')
return this_tear_down.__code__ is base_tear_down.__code__ | python | def uses_base_tear_down(cls):
"""Checks whether the tearDown method is the BasePlug implementation."""
this_tear_down = getattr(cls, 'tearDown')
base_tear_down = getattr(BasePlug, 'tearDown')
return this_tear_down.__code__ is base_tear_down.__code__ | [
"def",
"uses_base_tear_down",
"(",
"cls",
")",
":",
"this_tear_down",
"=",
"getattr",
"(",
"cls",
",",
"'tearDown'",
")",
"base_tear_down",
"=",
"getattr",
"(",
"BasePlug",
",",
"'tearDown'",
")",
"return",
"this_tear_down",
".",
"__code__",
"is",
"base_tear_dow... | Checks whether the tearDown method is the BasePlug implementation. | [
"Checks",
"whether",
"the",
"tearDown",
"method",
"is",
"the",
"BasePlug",
"implementation",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/__init__.py#L196-L200 | train |
google/openhtf | openhtf/plugs/__init__.py | PlugManager.get_plug_mro | def get_plug_mro(self, plug_type):
"""Returns a list of names identifying the plug classes in the plug's MRO.
For example:
['openhtf.plugs.user_input.UserInput']
Or:
['openhtf.plugs.user_input.UserInput',
'my_module.advanced_user_input.AdvancedUserInput']
"""
ignored_classe... | python | def get_plug_mro(self, plug_type):
"""Returns a list of names identifying the plug classes in the plug's MRO.
For example:
['openhtf.plugs.user_input.UserInput']
Or:
['openhtf.plugs.user_input.UserInput',
'my_module.advanced_user_input.AdvancedUserInput']
"""
ignored_classe... | [
"def",
"get_plug_mro",
"(",
"self",
",",
"plug_type",
")",
":",
"ignored_classes",
"=",
"(",
"BasePlug",
",",
"FrontendAwareBasePlug",
")",
"return",
"[",
"self",
".",
"get_plug_name",
"(",
"base_class",
")",
"for",
"base_class",
"in",
"plug_type",
".",
"mro",... | Returns a list of names identifying the plug classes in the plug's MRO.
For example:
['openhtf.plugs.user_input.UserInput']
Or:
['openhtf.plugs.user_input.UserInput',
'my_module.advanced_user_input.AdvancedUserInput'] | [
"Returns",
"a",
"list",
"of",
"names",
"identifying",
"the",
"plug",
"classes",
"in",
"the",
"plug",
"s",
"MRO",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/__init__.py#L338-L352 | train |
google/openhtf | openhtf/plugs/__init__.py | PlugManager.initialize_plugs | def initialize_plugs(self, plug_types=None):
"""Instantiate required plugs.
Instantiates plug types and saves the instances in self._plugs_by_type for
use in provide_plugs().
Args:
plug_types: Plug types may be specified here rather than passed
into the constructor (this is use... | python | def initialize_plugs(self, plug_types=None):
"""Instantiate required plugs.
Instantiates plug types and saves the instances in self._plugs_by_type for
use in provide_plugs().
Args:
plug_types: Plug types may be specified here rather than passed
into the constructor (this is use... | [
"def",
"initialize_plugs",
"(",
"self",
",",
"plug_types",
"=",
"None",
")",
":",
"types",
"=",
"plug_types",
"if",
"plug_types",
"is",
"not",
"None",
"else",
"self",
".",
"_plug_types",
"for",
"plug_type",
"in",
"types",
":",
"# Create a logger for this plug. A... | Instantiate required plugs.
Instantiates plug types and saves the instances in self._plugs_by_type for
use in provide_plugs().
Args:
plug_types: Plug types may be specified here rather than passed
into the constructor (this is used primarily for unit testing
phase... | [
"Instantiate",
"required",
"plugs",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/__init__.py#L362-L409 | train |
google/openhtf | openhtf/plugs/__init__.py | PlugManager.update_plug | def update_plug(self, plug_type, plug_value):
"""Update internal data stores with the given plug value for plug type.
Safely tears down the old instance if one was already created, but that's
generally not the case outside unittests. Also, we explicitly pass the
plug_type rather than detecting it from... | python | def update_plug(self, plug_type, plug_value):
"""Update internal data stores with the given plug value for plug type.
Safely tears down the old instance if one was already created, but that's
generally not the case outside unittests. Also, we explicitly pass the
plug_type rather than detecting it from... | [
"def",
"update_plug",
"(",
"self",
",",
"plug_type",
",",
"plug_value",
")",
":",
"self",
".",
"_plug_types",
".",
"add",
"(",
"plug_type",
")",
"if",
"plug_type",
"in",
"self",
".",
"_plugs_by_type",
":",
"self",
".",
"_plugs_by_type",
"[",
"plug_type",
"... | Update internal data stores with the given plug value for plug type.
Safely tears down the old instance if one was already created, but that's
generally not the case outside unittests. Also, we explicitly pass the
plug_type rather than detecting it from plug_value to allow unittests to
override plugs ... | [
"Update",
"internal",
"data",
"stores",
"with",
"the",
"given",
"plug",
"value",
"for",
"plug",
"type",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/__init__.py#L425-L442 | train |
google/openhtf | openhtf/plugs/__init__.py | PlugManager.wait_for_plug_update | def wait_for_plug_update(self, plug_name, remote_state, timeout_s):
"""Wait for a change in the state of a frontend-aware plug.
Args:
plug_name: Plug name, e.g. 'openhtf.plugs.user_input.UserInput'.
remote_state: The last observed state.
timeout_s: Number of seconds to wait for an update.
... | python | def wait_for_plug_update(self, plug_name, remote_state, timeout_s):
"""Wait for a change in the state of a frontend-aware plug.
Args:
plug_name: Plug name, e.g. 'openhtf.plugs.user_input.UserInput'.
remote_state: The last observed state.
timeout_s: Number of seconds to wait for an update.
... | [
"def",
"wait_for_plug_update",
"(",
"self",
",",
"plug_name",
",",
"remote_state",
",",
"timeout_s",
")",
":",
"plug",
"=",
"self",
".",
"_plugs_by_name",
".",
"get",
"(",
"plug_name",
")",
"if",
"plug",
"is",
"None",
":",
"raise",
"InvalidPlugError",
"(",
... | Wait for a change in the state of a frontend-aware plug.
Args:
plug_name: Plug name, e.g. 'openhtf.plugs.user_input.UserInput'.
remote_state: The last observed state.
timeout_s: Number of seconds to wait for an update.
Returns:
An updated state, or None if the timeout runs out.
Ra... | [
"Wait",
"for",
"a",
"change",
"in",
"the",
"state",
"of",
"a",
"frontend",
"-",
"aware",
"plug",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/__init__.py#L477-L506 | train |
google/openhtf | openhtf/plugs/__init__.py | PlugManager.get_frontend_aware_plug_names | def get_frontend_aware_plug_names(self):
"""Returns the names of frontend-aware plugs."""
return [name for name, plug in six.iteritems(self._plugs_by_name)
if isinstance(plug, FrontendAwareBasePlug)] | python | def get_frontend_aware_plug_names(self):
"""Returns the names of frontend-aware plugs."""
return [name for name, plug in six.iteritems(self._plugs_by_name)
if isinstance(plug, FrontendAwareBasePlug)] | [
"def",
"get_frontend_aware_plug_names",
"(",
"self",
")",
":",
"return",
"[",
"name",
"for",
"name",
",",
"plug",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_plugs_by_name",
")",
"if",
"isinstance",
"(",
"plug",
",",
"FrontendAwareBasePlug",
")",
"]"
... | Returns the names of frontend-aware plugs. | [
"Returns",
"the",
"names",
"of",
"frontend",
"-",
"aware",
"plugs",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/__init__.py#L508-L511 | train |
google/openhtf | openhtf/output/servers/station_server.py | _wait_for_any_event | def _wait_for_any_event(events, timeout_s):
"""Wait for any in a list of threading.Event's to be set.
Args:
events: List of threading.Event's.
timeout_s: Max duration in seconds to wait before returning.
Returns:
True if at least one event was set before the timeout expired, else False.
"""
de... | python | def _wait_for_any_event(events, timeout_s):
"""Wait for any in a list of threading.Event's to be set.
Args:
events: List of threading.Event's.
timeout_s: Max duration in seconds to wait before returning.
Returns:
True if at least one event was set before the timeout expired, else False.
"""
de... | [
"def",
"_wait_for_any_event",
"(",
"events",
",",
"timeout_s",
")",
":",
"def",
"any_event_set",
"(",
")",
":",
"return",
"any",
"(",
"event",
".",
"is_set",
"(",
")",
"for",
"event",
"in",
"events",
")",
"result",
"=",
"timeouts",
".",
"loop_until_timeout... | Wait for any in a list of threading.Event's to be set.
Args:
events: List of threading.Event's.
timeout_s: Max duration in seconds to wait before returning.
Returns:
True if at least one event was set before the timeout expired, else False. | [
"Wait",
"for",
"any",
"in",
"a",
"list",
"of",
"threading",
".",
"Event",
"s",
"to",
"be",
"set",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/servers/station_server.py#L119-L135 | train |
google/openhtf | openhtf/output/servers/station_server.py | StationWatcher._poll_for_update | def _poll_for_update(self):
"""Call the callback with the current test state, then wait for a change."""
test, test_state = _get_executing_test()
if test is None:
time.sleep(_WAIT_FOR_EXECUTING_TEST_POLL_S)
return
state_dict, event = self._to_dict_with_event(test_state)
self._update_ca... | python | def _poll_for_update(self):
"""Call the callback with the current test state, then wait for a change."""
test, test_state = _get_executing_test()
if test is None:
time.sleep(_WAIT_FOR_EXECUTING_TEST_POLL_S)
return
state_dict, event = self._to_dict_with_event(test_state)
self._update_ca... | [
"def",
"_poll_for_update",
"(",
"self",
")",
":",
"test",
",",
"test_state",
"=",
"_get_executing_test",
"(",
")",
"if",
"test",
"is",
"None",
":",
"time",
".",
"sleep",
"(",
"_WAIT_FOR_EXECUTING_TEST_POLL_S",
")",
"return",
"state_dict",
",",
"event",
"=",
... | Call the callback with the current test state, then wait for a change. | [
"Call",
"the",
"callback",
"with",
"the",
"current",
"test",
"state",
"then",
"wait",
"for",
"a",
"change",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/servers/station_server.py#L176-L199 | train |
google/openhtf | openhtf/output/servers/station_server.py | StationWatcher._to_dict_with_event | def _to_dict_with_event(cls, test_state):
"""Process a test state into the format we want to send to the frontend."""
original_dict, event = test_state.asdict_with_event()
# This line may produce a 'dictionary changed size during iteration' error.
test_state_dict = data.convert_to_base_types(original_d... | python | def _to_dict_with_event(cls, test_state):
"""Process a test state into the format we want to send to the frontend."""
original_dict, event = test_state.asdict_with_event()
# This line may produce a 'dictionary changed size during iteration' error.
test_state_dict = data.convert_to_base_types(original_d... | [
"def",
"_to_dict_with_event",
"(",
"cls",
",",
"test_state",
")",
":",
"original_dict",
",",
"event",
"=",
"test_state",
".",
"asdict_with_event",
"(",
")",
"# This line may produce a 'dictionary changed size during iteration' error.",
"test_state_dict",
"=",
"data",
".",
... | Process a test state into the format we want to send to the frontend. | [
"Process",
"a",
"test",
"state",
"into",
"the",
"format",
"we",
"want",
"to",
"send",
"to",
"the",
"frontend",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/servers/station_server.py#L202-L210 | train |
google/openhtf | openhtf/util/threads.py | _safe_lock_release_py2 | def _safe_lock_release_py2(rlock):
"""Ensure that a threading.RLock is fully released for Python 2.
The RLock release code is:
https://github.com/python/cpython/blob/2.7/Lib/threading.py#L187
The RLock object's release method does not release all of its state if an
exception is raised in the middle of its... | python | def _safe_lock_release_py2(rlock):
"""Ensure that a threading.RLock is fully released for Python 2.
The RLock release code is:
https://github.com/python/cpython/blob/2.7/Lib/threading.py#L187
The RLock object's release method does not release all of its state if an
exception is raised in the middle of its... | [
"def",
"_safe_lock_release_py2",
"(",
"rlock",
")",
":",
"assert",
"isinstance",
"(",
"rlock",
",",
"threading",
".",
"_RLock",
")",
"ident",
"=",
"_thread",
".",
"get_ident",
"(",
")",
"expected_count",
"=",
"0",
"if",
"rlock",
".",
"_RLock__owner",
"==",
... | Ensure that a threading.RLock is fully released for Python 2.
The RLock release code is:
https://github.com/python/cpython/blob/2.7/Lib/threading.py#L187
The RLock object's release method does not release all of its state if an
exception is raised in the middle of its operation. There are three pieces of
... | [
"Ensure",
"that",
"a",
"threading",
".",
"RLock",
"is",
"fully",
"released",
"for",
"Python",
"2",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/threads.py#L54-L97 | train |
google/openhtf | openhtf/util/threads.py | loop | def loop(_=None, force=False): # pylint: disable=invalid-name
"""Causes a function to loop indefinitely."""
if not force:
raise AttributeError(
'threads.loop() is DEPRECATED. If you really like this and want to '
'keep it, file an issue at https://github.com/google/openhtf/issues '
'a... | python | def loop(_=None, force=False): # pylint: disable=invalid-name
"""Causes a function to loop indefinitely."""
if not force:
raise AttributeError(
'threads.loop() is DEPRECATED. If you really like this and want to '
'keep it, file an issue at https://github.com/google/openhtf/issues '
'a... | [
"def",
"loop",
"(",
"_",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"# pylint: disable=invalid-name",
"if",
"not",
"force",
":",
"raise",
"AttributeError",
"(",
"'threads.loop() is DEPRECATED. If you really like this and want to '",
"'keep it, file an issue at http... | Causes a function to loop indefinitely. | [
"Causes",
"a",
"function",
"to",
"loop",
"indefinitely",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/threads.py#L101-L118 | train |
google/openhtf | openhtf/util/threads.py | synchronized | def synchronized(func): # pylint: disable=invalid-name
"""Hold self._lock while executing func."""
@functools.wraps(func)
def synchronized_method(self, *args, **kwargs):
"""Wrapper to return."""
if not hasattr(self, '_lock'):
if func.__name__ in type(self).__dict__:
hint = ''
else:
... | python | def synchronized(func): # pylint: disable=invalid-name
"""Hold self._lock while executing func."""
@functools.wraps(func)
def synchronized_method(self, *args, **kwargs):
"""Wrapper to return."""
if not hasattr(self, '_lock'):
if func.__name__ in type(self).__dict__:
hint = ''
else:
... | [
"def",
"synchronized",
"(",
"func",
")",
":",
"# pylint: disable=invalid-name",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"synchronized_method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Wrapper to return.\"\"\"",
... | Hold self._lock while executing func. | [
"Hold",
"self",
".",
"_lock",
"while",
"executing",
"func",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/threads.py#L241-L257 | train |
google/openhtf | openhtf/util/threads.py | KillableThread.kill | def kill(self):
"""Terminates the current thread by raising an error."""
self._killed.set()
if not self.is_alive():
logging.debug('Cannot kill thread that is no longer running.')
return
if not self._is_thread_proc_running():
logging.debug("Thread's _thread_proc function is no longer ru... | python | def kill(self):
"""Terminates the current thread by raising an error."""
self._killed.set()
if not self.is_alive():
logging.debug('Cannot kill thread that is no longer running.')
return
if not self._is_thread_proc_running():
logging.debug("Thread's _thread_proc function is no longer ru... | [
"def",
"kill",
"(",
"self",
")",
":",
"self",
".",
"_killed",
".",
"set",
"(",
")",
"if",
"not",
"self",
".",
"is_alive",
"(",
")",
":",
"logging",
".",
"debug",
"(",
"'Cannot kill thread that is no longer running.'",
")",
"return",
"if",
"not",
"self",
... | Terminates the current thread by raising an error. | [
"Terminates",
"the",
"current",
"thread",
"by",
"raising",
"an",
"error",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/threads.py#L193-L203 | train |
google/openhtf | openhtf/util/threads.py | KillableThread.async_raise | def async_raise(self, exc_type):
"""Raise the exception."""
# Should only be called on a started thread, so raise otherwise.
assert self.ident is not None, 'Only started threads have thread identifier'
# If the thread has died we don't want to raise an exception so log.
if not self.is_alive():
... | python | def async_raise(self, exc_type):
"""Raise the exception."""
# Should only be called on a started thread, so raise otherwise.
assert self.ident is not None, 'Only started threads have thread identifier'
# If the thread has died we don't want to raise an exception so log.
if not self.is_alive():
... | [
"def",
"async_raise",
"(",
"self",
",",
"exc_type",
")",
":",
"# Should only be called on a started thread, so raise otherwise.",
"assert",
"self",
".",
"ident",
"is",
"not",
"None",
",",
"'Only started threads have thread identifier'",
"# If the thread has died we don't want to ... | Raise the exception. | [
"Raise",
"the",
"exception",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/threads.py#L205-L225 | train |
google/openhtf | openhtf/util/logs.py | get_record_logger_for | def get_record_logger_for(test_uid):
"""Return the child logger associated with the specified test UID."""
htf_logger = logging.getLogger(RECORD_LOGGER_PREFIX)
record_logger = HtfTestLogger('.'.join(((RECORD_LOGGER_PREFIX, test_uid))))
record_logger.parent = htf_logger
return record_logger | python | def get_record_logger_for(test_uid):
"""Return the child logger associated with the specified test UID."""
htf_logger = logging.getLogger(RECORD_LOGGER_PREFIX)
record_logger = HtfTestLogger('.'.join(((RECORD_LOGGER_PREFIX, test_uid))))
record_logger.parent = htf_logger
return record_logger | [
"def",
"get_record_logger_for",
"(",
"test_uid",
")",
":",
"htf_logger",
"=",
"logging",
".",
"getLogger",
"(",
"RECORD_LOGGER_PREFIX",
")",
"record_logger",
"=",
"HtfTestLogger",
"(",
"'.'",
".",
"join",
"(",
"(",
"(",
"RECORD_LOGGER_PREFIX",
",",
"test_uid",
"... | Return the child logger associated with the specified test UID. | [
"Return",
"the",
"child",
"logger",
"associated",
"with",
"the",
"specified",
"test",
"UID",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/logs.py#L161-L166 | train |
google/openhtf | openhtf/util/logs.py | initialize_record_handler | def initialize_record_handler(test_uid, test_record, notify_update):
"""Initialize the record handler for a test.
For each running test, we attach a record handler to the top-level OpenHTF
logger. The handler will append OpenHTF logs to the test record, while
filtering out logs that are specific to any other t... | python | def initialize_record_handler(test_uid, test_record, notify_update):
"""Initialize the record handler for a test.
For each running test, we attach a record handler to the top-level OpenHTF
logger. The handler will append OpenHTF logs to the test record, while
filtering out logs that are specific to any other t... | [
"def",
"initialize_record_handler",
"(",
"test_uid",
",",
"test_record",
",",
"notify_update",
")",
":",
"htf_logger",
"=",
"logging",
".",
"getLogger",
"(",
"LOGGER_PREFIX",
")",
"htf_logger",
".",
"addHandler",
"(",
"RecordHandler",
"(",
"test_uid",
",",
"test_r... | Initialize the record handler for a test.
For each running test, we attach a record handler to the top-level OpenHTF
logger. The handler will append OpenHTF logs to the test record, while
filtering out logs that are specific to any other test run. | [
"Initialize",
"the",
"record",
"handler",
"for",
"a",
"test",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/logs.py#L169-L177 | train |
google/openhtf | openhtf/util/logs.py | log_once | def log_once(log_func, msg, *args, **kwargs):
""""Logs a message only once."""
if msg not in _LOG_ONCE_SEEN:
log_func(msg, *args, **kwargs)
# Key on the message, ignoring args. This should fit most use cases.
_LOG_ONCE_SEEN.add(msg) | python | def log_once(log_func, msg, *args, **kwargs):
""""Logs a message only once."""
if msg not in _LOG_ONCE_SEEN:
log_func(msg, *args, **kwargs)
# Key on the message, ignoring args. This should fit most use cases.
_LOG_ONCE_SEEN.add(msg) | [
"def",
"log_once",
"(",
"log_func",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"msg",
"not",
"in",
"_LOG_ONCE_SEEN",
":",
"log_func",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Key on the message, ignorin... | Logs a message only once. | [
"Logs",
"a",
"message",
"only",
"once",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/logs.py#L188-L193 | train |
google/openhtf | openhtf/util/logs.py | configure_logging | def configure_logging():
"""One-time initialization of loggers. See module docstring for more info."""
# Define the top-level logger.
htf_logger = logging.getLogger(LOGGER_PREFIX)
htf_logger.propagate = False
htf_logger.setLevel(logging.DEBUG)
# By default, don't print any logs to the CLI.
if CLI_LOGGIN... | python | def configure_logging():
"""One-time initialization of loggers. See module docstring for more info."""
# Define the top-level logger.
htf_logger = logging.getLogger(LOGGER_PREFIX)
htf_logger.propagate = False
htf_logger.setLevel(logging.DEBUG)
# By default, don't print any logs to the CLI.
if CLI_LOGGIN... | [
"def",
"configure_logging",
"(",
")",
":",
"# Define the top-level logger.",
"htf_logger",
"=",
"logging",
".",
"getLogger",
"(",
"LOGGER_PREFIX",
")",
"htf_logger",
".",
"propagate",
"=",
"False",
"htf_logger",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
... | One-time initialization of loggers. See module docstring for more info. | [
"One",
"-",
"time",
"initialization",
"of",
"loggers",
".",
"See",
"module",
"docstring",
"for",
"more",
"info",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/logs.py#L319-L346 | train |
google/openhtf | openhtf/util/logs.py | RecordHandler.emit | def emit(self, record):
"""Save a logging.LogRecord to our test record.
Logs carry useful metadata such as the logger name and level information.
We capture this in a structured format in the test record to enable
filtering by client applications.
Args:
record: A logging.LogRecord to record.... | python | def emit(self, record):
"""Save a logging.LogRecord to our test record.
Logs carry useful metadata such as the logger name and level information.
We capture this in a structured format in the test record to enable
filtering by client applications.
Args:
record: A logging.LogRecord to record.... | [
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"try",
":",
"message",
"=",
"self",
".",
"format",
"(",
"record",
")",
"log_record",
"=",
"LogRecord",
"(",
"record",
".",
"levelno",
",",
"record",
".",
"name",
",",
"os",
".",
"path",
".",
"bas... | Save a logging.LogRecord to our test record.
Logs carry useful metadata such as the logger name and level information.
We capture this in a structured format in the test record to enable
filtering by client applications.
Args:
record: A logging.LogRecord to record. | [
"Save",
"a",
"logging",
".",
"LogRecord",
"to",
"our",
"test",
"record",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/logs.py#L269-L288 | train |
google/openhtf | openhtf/util/logs.py | CliFormatter.format | def format(self, record):
"""Format the record as tersely as possible but preserve info."""
super(CliFormatter, self).format(record)
localized_time = datetime.datetime.fromtimestamp(record.created)
terse_time = localized_time.strftime(u'%H:%M:%S')
terse_level = record.levelname[0]
terse_name = r... | python | def format(self, record):
"""Format the record as tersely as possible but preserve info."""
super(CliFormatter, self).format(record)
localized_time = datetime.datetime.fromtimestamp(record.created)
terse_time = localized_time.strftime(u'%H:%M:%S')
terse_level = record.levelname[0]
terse_name = r... | [
"def",
"format",
"(",
"self",
",",
"record",
")",
":",
"super",
"(",
"CliFormatter",
",",
"self",
")",
".",
"format",
"(",
"record",
")",
"localized_time",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"record",
".",
"created",
")",
"terse... | Format the record as tersely as possible but preserve info. | [
"Format",
"the",
"record",
"as",
"tersely",
"as",
"possible",
"but",
"preserve",
"info",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/logs.py#L294-L315 | train |
google/openhtf | openhtf/output/callbacks/mfg_inspector.py | _send_mfg_inspector_request | def _send_mfg_inspector_request(envelope_data, credentials, destination_url):
"""Send upload http request. Intended to be run in retry loop."""
logging.info('Uploading result...')
http = httplib2.Http()
if credentials.access_token_expired:
credentials.refresh(http)
credentials.authorize(http)
resp, c... | python | def _send_mfg_inspector_request(envelope_data, credentials, destination_url):
"""Send upload http request. Intended to be run in retry loop."""
logging.info('Uploading result...')
http = httplib2.Http()
if credentials.access_token_expired:
credentials.refresh(http)
credentials.authorize(http)
resp, c... | [
"def",
"_send_mfg_inspector_request",
"(",
"envelope_data",
",",
"credentials",
",",
"destination_url",
")",
":",
"logging",
".",
"info",
"(",
"'Uploading result...'",
")",
"http",
"=",
"httplib2",
".",
"Http",
"(",
")",
"if",
"credentials",
".",
"access_token_exp... | Send upload http request. Intended to be run in retry loop. | [
"Send",
"upload",
"http",
"request",
".",
"Intended",
"to",
"be",
"run",
"in",
"retry",
"loop",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/callbacks/mfg_inspector.py#L27-L48 | train |
google/openhtf | openhtf/output/callbacks/mfg_inspector.py | send_mfg_inspector_data | def send_mfg_inspector_data(inspector_proto, credentials, destination_url):
"""Upload MfgEvent to steam_engine."""
envelope = guzzle_pb2.TestRunEnvelope()
envelope.payload = zlib.compress(inspector_proto.SerializeToString())
envelope.payload_type = guzzle_pb2.COMPRESSED_MFG_EVENT
envelope_data = envelope.Seri... | python | def send_mfg_inspector_data(inspector_proto, credentials, destination_url):
"""Upload MfgEvent to steam_engine."""
envelope = guzzle_pb2.TestRunEnvelope()
envelope.payload = zlib.compress(inspector_proto.SerializeToString())
envelope.payload_type = guzzle_pb2.COMPRESSED_MFG_EVENT
envelope_data = envelope.Seri... | [
"def",
"send_mfg_inspector_data",
"(",
"inspector_proto",
",",
"credentials",
",",
"destination_url",
")",
":",
"envelope",
"=",
"guzzle_pb2",
".",
"TestRunEnvelope",
"(",
")",
"envelope",
".",
"payload",
"=",
"zlib",
".",
"compress",
"(",
"inspector_proto",
".",
... | Upload MfgEvent to steam_engine. | [
"Upload",
"MfgEvent",
"to",
"steam_engine",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/callbacks/mfg_inspector.py#L51-L69 | train |
google/openhtf | openhtf/output/callbacks/mfg_inspector.py | MfgInspector._convert | def _convert(self, test_record_obj):
"""Convert and cache a test record to a mfg-inspector proto."""
if self._cached_proto is None:
self._cached_proto = self._converter(test_record_obj)
return self._cached_proto | python | def _convert(self, test_record_obj):
"""Convert and cache a test record to a mfg-inspector proto."""
if self._cached_proto is None:
self._cached_proto = self._converter(test_record_obj)
return self._cached_proto | [
"def",
"_convert",
"(",
"self",
",",
"test_record_obj",
")",
":",
"if",
"self",
".",
"_cached_proto",
"is",
"None",
":",
"self",
".",
"_cached_proto",
"=",
"self",
".",
"_converter",
"(",
"test_record_obj",
")",
"return",
"self",
".",
"_cached_proto"
] | Convert and cache a test record to a mfg-inspector proto. | [
"Convert",
"and",
"cache",
"a",
"test",
"record",
"to",
"a",
"mfg",
"-",
"inspector",
"proto",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/callbacks/mfg_inspector.py#L174-L180 | train |
google/openhtf | openhtf/output/callbacks/mfg_inspector.py | MfgInspector.save_to_disk | def save_to_disk(self, filename_pattern=None):
"""Returns a callback to convert test record to proto and save to disk."""
if not self._converter:
raise RuntimeError(
'Must set _converter on subclass or via set_converter before calling '
'save_to_disk.')
pattern = filename_pattern ... | python | def save_to_disk(self, filename_pattern=None):
"""Returns a callback to convert test record to proto and save to disk."""
if not self._converter:
raise RuntimeError(
'Must set _converter on subclass or via set_converter before calling '
'save_to_disk.')
pattern = filename_pattern ... | [
"def",
"save_to_disk",
"(",
"self",
",",
"filename_pattern",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_converter",
":",
"raise",
"RuntimeError",
"(",
"'Must set _converter on subclass or via set_converter before calling '",
"'save_to_disk.'",
")",
"pattern",
"=... | Returns a callback to convert test record to proto and save to disk. | [
"Returns",
"a",
"callback",
"to",
"convert",
"test",
"record",
"to",
"proto",
"and",
"save",
"to",
"disk",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/callbacks/mfg_inspector.py#L182-L202 | train |
google/openhtf | openhtf/output/callbacks/mfg_inspector.py | MfgInspector.upload | def upload(self):
"""Returns a callback to convert a test record to a proto and upload."""
if not self._converter:
raise RuntimeError(
'Must set _converter on subclass or via set_converter before calling '
'upload.')
if not self.credentials:
raise RuntimeError('Must provide ... | python | def upload(self):
"""Returns a callback to convert a test record to a proto and upload."""
if not self._converter:
raise RuntimeError(
'Must set _converter on subclass or via set_converter before calling '
'upload.')
if not self.credentials:
raise RuntimeError('Must provide ... | [
"def",
"upload",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_converter",
":",
"raise",
"RuntimeError",
"(",
"'Must set _converter on subclass or via set_converter before calling '",
"'upload.'",
")",
"if",
"not",
"self",
".",
"credentials",
":",
"raise",
"Run... | Returns a callback to convert a test record to a proto and upload. | [
"Returns",
"a",
"callback",
"to",
"convert",
"a",
"test",
"record",
"to",
"a",
"proto",
"and",
"upload",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/callbacks/mfg_inspector.py#L204-L219 | train |
google/openhtf | openhtf/plugs/usb/shell_service.py | AsyncCommandHandle._writer_thread_proc | def _writer_thread_proc(self, is_raw):
"""Write as long as the stream is not closed."""
# If we're not in raw mode, do line-buffered reads to play nicer with
# potential interactive uses, max of MAX_ADB_DATA, since anything we write
# to the stream will get packetized to that size anyway.
#
# Lo... | python | def _writer_thread_proc(self, is_raw):
"""Write as long as the stream is not closed."""
# If we're not in raw mode, do line-buffered reads to play nicer with
# potential interactive uses, max of MAX_ADB_DATA, since anything we write
# to the stream will get packetized to that size anyway.
#
# Lo... | [
"def",
"_writer_thread_proc",
"(",
"self",
",",
"is_raw",
")",
":",
"# If we're not in raw mode, do line-buffered reads to play nicer with",
"# potential interactive uses, max of MAX_ADB_DATA, since anything we write",
"# to the stream will get packetized to that size anyway.",
"#",
"# Loop ... | Write as long as the stream is not closed. | [
"Write",
"as",
"long",
"as",
"the",
"stream",
"is",
"not",
"closed",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/shell_service.py#L132-L143 | train |
google/openhtf | openhtf/plugs/usb/shell_service.py | AsyncCommandHandle._reader_thread_proc | def _reader_thread_proc(self, timeout):
"""Read until the stream is closed."""
for data in self.stream.read_until_close(timeout_ms=timeout):
if self.stdout is not None:
self.stdout.write(data) | python | def _reader_thread_proc(self, timeout):
"""Read until the stream is closed."""
for data in self.stream.read_until_close(timeout_ms=timeout):
if self.stdout is not None:
self.stdout.write(data) | [
"def",
"_reader_thread_proc",
"(",
"self",
",",
"timeout",
")",
":",
"for",
"data",
"in",
"self",
".",
"stream",
".",
"read_until_close",
"(",
"timeout_ms",
"=",
"timeout",
")",
":",
"if",
"self",
".",
"stdout",
"is",
"not",
"None",
":",
"self",
".",
"... | Read until the stream is closed. | [
"Read",
"until",
"the",
"stream",
"is",
"closed",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/shell_service.py#L145-L149 | train |
google/openhtf | openhtf/plugs/usb/shell_service.py | AsyncCommandHandle.wait | def wait(self, timeout_ms=None):
"""Block until this command has completed.
Args:
timeout_ms: Timeout, in milliseconds, to wait.
Returns:
Output of the command if it complete and self.stdout is a StringIO
object or was passed in as None. Returns True if the command completed but
stdou... | python | def wait(self, timeout_ms=None):
"""Block until this command has completed.
Args:
timeout_ms: Timeout, in milliseconds, to wait.
Returns:
Output of the command if it complete and self.stdout is a StringIO
object or was passed in as None. Returns True if the command completed but
stdou... | [
"def",
"wait",
"(",
"self",
",",
"timeout_ms",
"=",
"None",
")",
":",
"closed",
"=",
"timeouts",
".",
"loop_until_timeout_or_true",
"(",
"timeouts",
".",
"PolledTimeout",
".",
"from_millis",
"(",
"timeout_ms",
")",
",",
"self",
".",
"stream",
".",
"is_closed... | Block until this command has completed.
Args:
timeout_ms: Timeout, in milliseconds, to wait.
Returns:
Output of the command if it complete and self.stdout is a StringIO
object or was passed in as None. Returns True if the command completed but
stdout was provided (and was not a StringIO o... | [
"Block",
"until",
"this",
"command",
"has",
"completed",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/shell_service.py#L169-L189 | train |
google/openhtf | openhtf/plugs/usb/shell_service.py | ShellService.command | def command(self, command, raw=False, timeout_ms=None):
"""Run the given command and return the output."""
return ''.join(self.streaming_command(command, raw, timeout_ms)) | python | def command(self, command, raw=False, timeout_ms=None):
"""Run the given command and return the output."""
return ''.join(self.streaming_command(command, raw, timeout_ms)) | [
"def",
"command",
"(",
"self",
",",
"command",
",",
"raw",
"=",
"False",
",",
"timeout_ms",
"=",
"None",
")",
":",
"return",
"''",
".",
"join",
"(",
"self",
".",
"streaming_command",
"(",
"command",
",",
"raw",
",",
"timeout_ms",
")",
")"
] | Run the given command and return the output. | [
"Run",
"the",
"given",
"command",
"and",
"return",
"the",
"output",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/shell_service.py#L223-L225 | train |
google/openhtf | openhtf/plugs/usb/shell_service.py | ShellService.streaming_command | def streaming_command(self, command, raw=False, timeout_ms=None):
"""Run the given command and yield the output as we receive it."""
if raw:
command = self._to_raw_command(command)
return self.adb_connection.streaming_command('shell', command, timeout_ms) | python | def streaming_command(self, command, raw=False, timeout_ms=None):
"""Run the given command and yield the output as we receive it."""
if raw:
command = self._to_raw_command(command)
return self.adb_connection.streaming_command('shell', command, timeout_ms) | [
"def",
"streaming_command",
"(",
"self",
",",
"command",
",",
"raw",
"=",
"False",
",",
"timeout_ms",
"=",
"None",
")",
":",
"if",
"raw",
":",
"command",
"=",
"self",
".",
"_to_raw_command",
"(",
"command",
")",
"return",
"self",
".",
"adb_connection",
"... | Run the given command and yield the output as we receive it. | [
"Run",
"the",
"given",
"command",
"and",
"yield",
"the",
"output",
"as",
"we",
"receive",
"it",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/shell_service.py#L227-L231 | train |
google/openhtf | openhtf/plugs/usb/shell_service.py | ShellService.async_command | def async_command(self, command, stdin=None, stdout=None, raw=False,
timeout_ms=None):
"""Run the given command on the device asynchronously.
Input will be read from stdin, output written to stdout. ADB doesn't
distinguish between stdout and stdin on the device, so they get interleaved... | python | def async_command(self, command, stdin=None, stdout=None, raw=False,
timeout_ms=None):
"""Run the given command on the device asynchronously.
Input will be read from stdin, output written to stdout. ADB doesn't
distinguish between stdout and stdin on the device, so they get interleaved... | [
"def",
"async_command",
"(",
"self",
",",
"command",
",",
"stdin",
"=",
"None",
",",
"stdout",
"=",
"None",
",",
"raw",
"=",
"False",
",",
"timeout_ms",
"=",
"None",
")",
":",
"timeout",
"=",
"timeouts",
".",
"PolledTimeout",
".",
"from_millis",
"(",
"... | Run the given command on the device asynchronously.
Input will be read from stdin, output written to stdout. ADB doesn't
distinguish between stdout and stdin on the device, so they get interleaved
into stdout here. stdin and stdout should be file-like objects, so you
could use sys.stdin and sys.stdou... | [
"Run",
"the",
"given",
"command",
"on",
"the",
"device",
"asynchronously",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/shell_service.py#L234-L273 | train |
google/openhtf | openhtf/util/conf.py | Configuration.load_flag_values | def load_flag_values(self, flags=None):
"""Load flag values given from command line flags.
Args:
flags: An argparse Namespace containing the command line flags.
"""
if flags is None:
flags = self._flags
for keyval in flags.config_value:
k, v = keyval.split('=', 1)
v = self._... | python | def load_flag_values(self, flags=None):
"""Load flag values given from command line flags.
Args:
flags: An argparse Namespace containing the command line flags.
"""
if flags is None:
flags = self._flags
for keyval in flags.config_value:
k, v = keyval.split('=', 1)
v = self._... | [
"def",
"load_flag_values",
"(",
"self",
",",
"flags",
"=",
"None",
")",
":",
"if",
"flags",
"is",
"None",
":",
"flags",
"=",
"self",
".",
"_flags",
"for",
"keyval",
"in",
"flags",
".",
"config_value",
":",
"k",
",",
"v",
"=",
"keyval",
".",
"split",
... | Load flag values given from command line flags.
Args:
flags: An argparse Namespace containing the command line flags. | [
"Load",
"flag",
"values",
"given",
"from",
"command",
"line",
"flags",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/conf.py#L255-L271 | train |
google/openhtf | openhtf/util/conf.py | Configuration.declare | def declare(self, name, description=None, **kwargs):
"""Declare a configuration key with the given name.
Args:
name: Configuration key to declare, must not have been already declared.
description: If provided, use this as the description for this key.
**kwargs: Other kwargs to pass to the Dec... | python | def declare(self, name, description=None, **kwargs):
"""Declare a configuration key with the given name.
Args:
name: Configuration key to declare, must not have been already declared.
description: If provided, use this as the description for this key.
**kwargs: Other kwargs to pass to the Dec... | [
"def",
"declare",
"(",
"self",
",",
"name",
",",
"description",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"_is_valid_key",
"(",
"name",
")",
":",
"raise",
"self",
".",
"InvalidKeyError",
"(",
"'Invalid key name, must begin w... | Declare a configuration key with the given name.
Args:
name: Configuration key to declare, must not have been already declared.
description: If provided, use this as the description for this key.
**kwargs: Other kwargs to pass to the Declaration, only default_value
is currently supporte... | [
"Declare",
"a",
"configuration",
"key",
"with",
"the",
"given",
"name",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/conf.py#L337-L353 | train |
google/openhtf | openhtf/util/conf.py | Configuration.reset | def reset(self):
"""Reset the loaded state of the configuration to what it was at import.
Note that this does *not* reset values set by commandline flags or loaded
from --config-file (in fact, any values loaded from --config-file that have
been overridden are reset to their value from --config-file).
... | python | def reset(self):
"""Reset the loaded state of the configuration to what it was at import.
Note that this does *not* reset values set by commandline flags or loaded
from --config-file (in fact, any values loaded from --config-file that have
been overridden are reset to their value from --config-file).
... | [
"def",
"reset",
"(",
"self",
")",
":",
"# Populate loaded_values with values from --config-file, if it was given.",
"self",
".",
"_loaded_values",
"=",
"{",
"}",
"if",
"self",
".",
"_flags",
".",
"config_file",
"is",
"not",
"None",
":",
"self",
".",
"load_from_file"... | Reset the loaded state of the configuration to what it was at import.
Note that this does *not* reset values set by commandline flags or loaded
from --config-file (in fact, any values loaded from --config-file that have
been overridden are reset to their value from --config-file). | [
"Reset",
"the",
"loaded",
"state",
"of",
"the",
"configuration",
"to",
"what",
"it",
"was",
"at",
"import",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/conf.py#L356-L366 | train |
google/openhtf | openhtf/util/conf.py | Configuration.load_from_file | def load_from_file(self, yamlfile, _override=True, _allow_undeclared=False):
"""Loads the configuration from a file.
Parsed contents must be a single dict mapping config key to value.
Args:
yamlfile: The opened file object to load configuration from.
See load_from_dict() for other args' descri... | python | def load_from_file(self, yamlfile, _override=True, _allow_undeclared=False):
"""Loads the configuration from a file.
Parsed contents must be a single dict mapping config key to value.
Args:
yamlfile: The opened file object to load configuration from.
See load_from_dict() for other args' descri... | [
"def",
"load_from_file",
"(",
"self",
",",
"yamlfile",
",",
"_override",
"=",
"True",
",",
"_allow_undeclared",
"=",
"False",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Loading configuration from file: %s'",
",",
"yamlfile",
")",
"try",
":",
"parsed... | Loads the configuration from a file.
Parsed contents must be a single dict mapping config key to value.
Args:
yamlfile: The opened file object to load configuration from.
See load_from_dict() for other args' descriptions.
Raises:
ConfigurationInvalidError: If configuration file can't be... | [
"Loads",
"the",
"configuration",
"from",
"a",
"file",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/conf.py#L368-L397 | train |
google/openhtf | openhtf/util/conf.py | Configuration.load_from_dict | def load_from_dict(self, dictionary, _override=True, _allow_undeclared=False):
"""Loads the config with values from a dictionary instead of a file.
This is meant for testing and bin purposes and shouldn't be used in most
applications.
Args:
dictionary: The dictionary containing config keys/value... | python | def load_from_dict(self, dictionary, _override=True, _allow_undeclared=False):
"""Loads the config with values from a dictionary instead of a file.
This is meant for testing and bin purposes and shouldn't be used in most
applications.
Args:
dictionary: The dictionary containing config keys/value... | [
"def",
"load_from_dict",
"(",
"self",
",",
"dictionary",
",",
"_override",
"=",
"True",
",",
"_allow_undeclared",
"=",
"False",
")",
":",
"undeclared_keys",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"self",
".",
"_modules",
"[",
"'six'",
"]",
".",... | Loads the config with values from a dictionary instead of a file.
This is meant for testing and bin purposes and shouldn't be used in most
applications.
Args:
dictionary: The dictionary containing config keys/values to update.
_override: If True, new values will override previous values.
... | [
"Loads",
"the",
"config",
"with",
"values",
"from",
"a",
"dictionary",
"instead",
"of",
"a",
"file",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/conf.py#L405-L445 | train |
google/openhtf | openhtf/util/conf.py | Configuration._asdict | def _asdict(self):
"""Create a dictionary snapshot of the current config values."""
# Start with any default values we have, and override with loaded values,
# and then override with flag values.
retval = {key: self._declarations[key].default_value for
key in self._declarations if self._de... | python | def _asdict(self):
"""Create a dictionary snapshot of the current config values."""
# Start with any default values we have, and override with loaded values,
# and then override with flag values.
retval = {key: self._declarations[key].default_value for
key in self._declarations if self._de... | [
"def",
"_asdict",
"(",
"self",
")",
":",
"# Start with any default values we have, and override with loaded values,",
"# and then override with flag values.",
"retval",
"=",
"{",
"key",
":",
"self",
".",
"_declarations",
"[",
"key",
"]",
".",
"default_value",
"for",
"key"... | Create a dictionary snapshot of the current config values. | [
"Create",
"a",
"dictionary",
"snapshot",
"of",
"the",
"current",
"config",
"values",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/conf.py#L448-L460 | train |
google/openhtf | openhtf/util/conf.py | Configuration.help_text | def help_text(self):
"""Return a string with all config keys and their descriptions."""
result = []
for name in sorted(self._declarations.keys()):
result.append(name)
result.append('-' * len(name))
decl = self._declarations[name]
if decl.description:
result.append(decl.descri... | python | def help_text(self):
"""Return a string with all config keys and their descriptions."""
result = []
for name in sorted(self._declarations.keys()):
result.append(name)
result.append('-' * len(name))
decl = self._declarations[name]
if decl.description:
result.append(decl.descri... | [
"def",
"help_text",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"for",
"name",
"in",
"sorted",
"(",
"self",
".",
"_declarations",
".",
"keys",
"(",
")",
")",
":",
"result",
".",
"append",
"(",
"name",
")",
"result",
".",
"append",
"(",
"'-'",
... | Return a string with all config keys and their descriptions. | [
"Return",
"a",
"string",
"with",
"all",
"config",
"keys",
"and",
"their",
"descriptions",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/conf.py#L463-L481 | train |
google/openhtf | openhtf/util/conf.py | Configuration.save_and_restore | def save_and_restore(self, _func=None, **config_values):
"""Decorator for saving conf state and restoring it after a function.
This decorator is primarily for use in tests, where conf keys may be updated
for individual test cases, but those values need to be reverted after the
test case is done.
E... | python | def save_and_restore(self, _func=None, **config_values):
"""Decorator for saving conf state and restoring it after a function.
This decorator is primarily for use in tests, where conf keys may be updated
for individual test cases, but those values need to be reverted after the
test case is done.
E... | [
"def",
"save_and_restore",
"(",
"self",
",",
"_func",
"=",
"None",
",",
"*",
"*",
"config_values",
")",
":",
"functools",
"=",
"self",
".",
"_modules",
"[",
"'functools'",
"]",
"# pylint: disable=redefined-outer-name",
"if",
"not",
"_func",
":",
"return",
"fun... | Decorator for saving conf state and restoring it after a function.
This decorator is primarily for use in tests, where conf keys may be updated
for individual test cases, but those values need to be reverted after the
test case is done.
Examples:
conf.declare('my_conf_key')
@conf.save_an... | [
"Decorator",
"for",
"saving",
"conf",
"state",
"and",
"restoring",
"it",
"after",
"a",
"function",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/conf.py#L483-L542 | train |
google/openhtf | openhtf/util/conf.py | Configuration.inject_positional_args | def inject_positional_args(self, method):
"""Decorator for injecting positional arguments from the configuration.
This decorator wraps the given method, so that any positional arguments are
passed with corresponding values from the configuration. The name of the
positional argument must match the conf... | python | def inject_positional_args(self, method):
"""Decorator for injecting positional arguments from the configuration.
This decorator wraps the given method, so that any positional arguments are
passed with corresponding values from the configuration. The name of the
positional argument must match the conf... | [
"def",
"inject_positional_args",
"(",
"self",
",",
"method",
")",
":",
"inspect",
"=",
"self",
".",
"_modules",
"[",
"'inspect'",
"]",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
"method",
")",
"# Index in argspec.args of the first keyword argument. This index... | Decorator for injecting positional arguments from the configuration.
This decorator wraps the given method, so that any positional arguments are
passed with corresponding values from the configuration. The name of the
positional argument must match the configuration key.
Keyword arguments are *NEVER*... | [
"Decorator",
"for",
"injecting",
"positional",
"arguments",
"from",
"the",
"configuration",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/conf.py#L544-L616 | train |
google/openhtf | openhtf/util/functions.py | call_once | def call_once(func):
"""Decorate a function to only allow it to be called once.
Note that it doesn't make sense to only call a function once if it takes
arguments (use @functools.lru_cache for that sort of thing), so this only
works on callables that take no args.
"""
argspec = inspect.getargspec(func)
i... | python | def call_once(func):
"""Decorate a function to only allow it to be called once.
Note that it doesn't make sense to only call a function once if it takes
arguments (use @functools.lru_cache for that sort of thing), so this only
works on callables that take no args.
"""
argspec = inspect.getargspec(func)
i... | [
"def",
"call_once",
"(",
"func",
")",
":",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"if",
"argspec",
".",
"args",
"or",
"argspec",
".",
"varargs",
"or",
"argspec",
".",
"keywords",
":",
"raise",
"ValueError",
"(",
"'Can only decorate... | Decorate a function to only allow it to be called once.
Note that it doesn't make sense to only call a function once if it takes
arguments (use @functools.lru_cache for that sort of thing), so this only
works on callables that take no args. | [
"Decorate",
"a",
"function",
"to",
"only",
"allow",
"it",
"to",
"be",
"called",
"once",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/functions.py#L23-L45 | train |
google/openhtf | openhtf/util/functions.py | call_at_most_every | def call_at_most_every(seconds, count=1):
"""Call the decorated function at most count times every seconds seconds.
The decorated function will sleep to ensure that at most count invocations
occur within any 'seconds' second window.
"""
def decorator(func):
try:
call_history = getattr(func, '_call_... | python | def call_at_most_every(seconds, count=1):
"""Call the decorated function at most count times every seconds seconds.
The decorated function will sleep to ensure that at most count invocations
occur within any 'seconds' second window.
"""
def decorator(func):
try:
call_history = getattr(func, '_call_... | [
"def",
"call_at_most_every",
"(",
"seconds",
",",
"count",
"=",
"1",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"try",
":",
"call_history",
"=",
"getattr",
"(",
"func",
",",
"'_call_history'",
")",
"except",
"AttributeError",
":",
"call_history",
... | Call the decorated function at most count times every seconds seconds.
The decorated function will sleep to ensure that at most count invocations
occur within any 'seconds' second window. | [
"Call",
"the",
"decorated",
"function",
"at",
"most",
"count",
"times",
"every",
"seconds",
"seconds",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/functions.py#L47-L73 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.