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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
google/mobly | mobly/controllers/android_device_lib/services/logcat.py | Logcat.start | def start(self):
"""Starts a standing adb logcat collection.
The collection runs in a separate subprocess and saves logs in a file.
"""
self._assert_not_running()
if self._configs.clear_log:
self.clear_adb_log()
self._start() | python | def start(self):
"""Starts a standing adb logcat collection.
The collection runs in a separate subprocess and saves logs in a file.
"""
self._assert_not_running()
if self._configs.clear_log:
self.clear_adb_log()
self._start() | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_assert_not_running",
"(",
")",
"if",
"self",
".",
"_configs",
".",
"clear_log",
":",
"self",
".",
"clear_adb_log",
"(",
")",
"self",
".",
"_start",
"(",
")"
] | Starts a standing adb logcat collection.
The collection runs in a separate subprocess and saves logs in a file. | [
"Starts",
"a",
"standing",
"adb",
"logcat",
"collection",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/services/logcat.py#L195-L203 | train | 205,400 |
google/mobly | mobly/controllers/android_device_lib/services/logcat.py | Logcat._start | def _start(self):
"""The actual logic of starting logcat."""
self._enable_logpersist()
logcat_file_path = self._configs.output_file_path
if not logcat_file_path:
f_name = 'adblog,%s,%s.txt' % (self._ad.model,
self._ad._normalized_serial)
logcat_file_path = os.path.join(self._ad.log_path, f_name)
utils.create_dir(os.path.dirname(logcat_file_path))
cmd = '"%s" -s %s logcat -v threadtime %s >> "%s"' % (
adb.ADB, self._ad.serial, self._configs.logcat_params,
logcat_file_path)
process = utils.start_standing_subprocess(cmd, shell=True)
self._adb_logcat_process = process
self.adb_logcat_file_path = logcat_file_path | python | def _start(self):
"""The actual logic of starting logcat."""
self._enable_logpersist()
logcat_file_path = self._configs.output_file_path
if not logcat_file_path:
f_name = 'adblog,%s,%s.txt' % (self._ad.model,
self._ad._normalized_serial)
logcat_file_path = os.path.join(self._ad.log_path, f_name)
utils.create_dir(os.path.dirname(logcat_file_path))
cmd = '"%s" -s %s logcat -v threadtime %s >> "%s"' % (
adb.ADB, self._ad.serial, self._configs.logcat_params,
logcat_file_path)
process = utils.start_standing_subprocess(cmd, shell=True)
self._adb_logcat_process = process
self.adb_logcat_file_path = logcat_file_path | [
"def",
"_start",
"(",
"self",
")",
":",
"self",
".",
"_enable_logpersist",
"(",
")",
"logcat_file_path",
"=",
"self",
".",
"_configs",
".",
"output_file_path",
"if",
"not",
"logcat_file_path",
":",
"f_name",
"=",
"'adblog,%s,%s.txt'",
"%",
"(",
"self",
".",
... | The actual logic of starting logcat. | [
"The",
"actual",
"logic",
"of",
"starting",
"logcat",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/services/logcat.py#L205-L219 | train | 205,401 |
google/mobly | mobly/controllers/android_device_lib/services/logcat.py | Logcat.stop | def stop(self):
"""Stops the adb logcat service."""
if not self._adb_logcat_process:
return
try:
utils.stop_standing_subprocess(self._adb_logcat_process)
except:
self._ad.log.exception('Failed to stop adb logcat.')
self._adb_logcat_process = None | python | def stop(self):
"""Stops the adb logcat service."""
if not self._adb_logcat_process:
return
try:
utils.stop_standing_subprocess(self._adb_logcat_process)
except:
self._ad.log.exception('Failed to stop adb logcat.')
self._adb_logcat_process = None | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_adb_logcat_process",
":",
"return",
"try",
":",
"utils",
".",
"stop_standing_subprocess",
"(",
"self",
".",
"_adb_logcat_process",
")",
"except",
":",
"self",
".",
"_ad",
".",
"log",
".",
... | Stops the adb logcat service. | [
"Stops",
"the",
"adb",
"logcat",
"service",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/services/logcat.py#L221-L229 | train | 205,402 |
google/mobly | mobly/controllers/android_device_lib/jsonrpc_client_base.py | JsonRpcClientBase.connect | def connect(self, uid=UNKNOWN_UID, cmd=JsonRpcCommand.INIT):
"""Opens a connection to a JSON RPC server.
Opens a connection to a remote client. The connection attempt will time
out if it takes longer than _SOCKET_CONNECTION_TIMEOUT seconds. Each
subsequent operation over this socket will time out after
_SOCKET_READ_TIMEOUT seconds as well.
Args:
uid: int, The uid of the session to join, or UNKNOWN_UID to start a
new session.
cmd: JsonRpcCommand, The command to use for creating the connection.
Raises:
IOError: Raised when the socket times out from io error
socket.timeout: Raised when the socket waits to long for connection.
ProtocolError: Raised when there is an error in the protocol.
"""
self._counter = self._id_counter()
self._conn = socket.create_connection(('localhost', self.host_port),
_SOCKET_CONNECTION_TIMEOUT)
self._conn.settimeout(_SOCKET_READ_TIMEOUT)
self._client = self._conn.makefile(mode='brw')
resp = self._cmd(cmd, uid)
if not resp:
raise ProtocolError(self._ad,
ProtocolError.NO_RESPONSE_FROM_HANDSHAKE)
result = json.loads(str(resp, encoding='utf8'))
if result['status']:
self.uid = result['uid']
else:
self.uid = UNKNOWN_UID | python | def connect(self, uid=UNKNOWN_UID, cmd=JsonRpcCommand.INIT):
"""Opens a connection to a JSON RPC server.
Opens a connection to a remote client. The connection attempt will time
out if it takes longer than _SOCKET_CONNECTION_TIMEOUT seconds. Each
subsequent operation over this socket will time out after
_SOCKET_READ_TIMEOUT seconds as well.
Args:
uid: int, The uid of the session to join, or UNKNOWN_UID to start a
new session.
cmd: JsonRpcCommand, The command to use for creating the connection.
Raises:
IOError: Raised when the socket times out from io error
socket.timeout: Raised when the socket waits to long for connection.
ProtocolError: Raised when there is an error in the protocol.
"""
self._counter = self._id_counter()
self._conn = socket.create_connection(('localhost', self.host_port),
_SOCKET_CONNECTION_TIMEOUT)
self._conn.settimeout(_SOCKET_READ_TIMEOUT)
self._client = self._conn.makefile(mode='brw')
resp = self._cmd(cmd, uid)
if not resp:
raise ProtocolError(self._ad,
ProtocolError.NO_RESPONSE_FROM_HANDSHAKE)
result = json.loads(str(resp, encoding='utf8'))
if result['status']:
self.uid = result['uid']
else:
self.uid = UNKNOWN_UID | [
"def",
"connect",
"(",
"self",
",",
"uid",
"=",
"UNKNOWN_UID",
",",
"cmd",
"=",
"JsonRpcCommand",
".",
"INIT",
")",
":",
"self",
".",
"_counter",
"=",
"self",
".",
"_id_counter",
"(",
")",
"self",
".",
"_conn",
"=",
"socket",
".",
"create_connection",
... | Opens a connection to a JSON RPC server.
Opens a connection to a remote client. The connection attempt will time
out if it takes longer than _SOCKET_CONNECTION_TIMEOUT seconds. Each
subsequent operation over this socket will time out after
_SOCKET_READ_TIMEOUT seconds as well.
Args:
uid: int, The uid of the session to join, or UNKNOWN_UID to start a
new session.
cmd: JsonRpcCommand, The command to use for creating the connection.
Raises:
IOError: Raised when the socket times out from io error
socket.timeout: Raised when the socket waits to long for connection.
ProtocolError: Raised when there is an error in the protocol. | [
"Opens",
"a",
"connection",
"to",
"a",
"JSON",
"RPC",
"server",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/jsonrpc_client_base.py#L190-L222 | train | 205,403 |
google/mobly | mobly/controllers/android_device_lib/jsonrpc_client_base.py | JsonRpcClientBase.clear_host_port | def clear_host_port(self):
"""Stops the adb port forwarding of the host port used by this client.
"""
if self.host_port:
self._adb.forward(['--remove', 'tcp:%d' % self.host_port])
self.host_port = None | python | def clear_host_port(self):
"""Stops the adb port forwarding of the host port used by this client.
"""
if self.host_port:
self._adb.forward(['--remove', 'tcp:%d' % self.host_port])
self.host_port = None | [
"def",
"clear_host_port",
"(",
"self",
")",
":",
"if",
"self",
".",
"host_port",
":",
"self",
".",
"_adb",
".",
"forward",
"(",
"[",
"'--remove'",
",",
"'tcp:%d'",
"%",
"self",
".",
"host_port",
"]",
")",
"self",
".",
"host_port",
"=",
"None"
] | Stops the adb port forwarding of the host port used by this client. | [
"Stops",
"the",
"adb",
"port",
"forwarding",
"of",
"the",
"host",
"port",
"used",
"by",
"this",
"client",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/jsonrpc_client_base.py#L230-L235 | train | 205,404 |
google/mobly | mobly/controllers/android_device_lib/jsonrpc_client_base.py | JsonRpcClientBase._client_send | def _client_send(self, msg):
"""Sends an Rpc message through the connection.
Args:
msg: string, the message to send.
Raises:
Error: a socket error occurred during the send.
"""
try:
self._client.write(msg.encode("utf8") + b'\n')
self._client.flush()
self.log.debug('Snippet sent %s.', msg)
except socket.error as e:
raise Error(
self._ad,
'Encountered socket error "%s" sending RPC message "%s"' %
(e, msg)) | python | def _client_send(self, msg):
"""Sends an Rpc message through the connection.
Args:
msg: string, the message to send.
Raises:
Error: a socket error occurred during the send.
"""
try:
self._client.write(msg.encode("utf8") + b'\n')
self._client.flush()
self.log.debug('Snippet sent %s.', msg)
except socket.error as e:
raise Error(
self._ad,
'Encountered socket error "%s" sending RPC message "%s"' %
(e, msg)) | [
"def",
"_client_send",
"(",
"self",
",",
"msg",
")",
":",
"try",
":",
"self",
".",
"_client",
".",
"write",
"(",
"msg",
".",
"encode",
"(",
"\"utf8\"",
")",
"+",
"b'\\n'",
")",
"self",
".",
"_client",
".",
"flush",
"(",
")",
"self",
".",
"log",
"... | Sends an Rpc message through the connection.
Args:
msg: string, the message to send.
Raises:
Error: a socket error occurred during the send. | [
"Sends",
"an",
"Rpc",
"message",
"through",
"the",
"connection",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/jsonrpc_client_base.py#L237-L254 | train | 205,405 |
google/mobly | mobly/controllers/android_device_lib/jsonrpc_client_base.py | JsonRpcClientBase._client_receive | def _client_receive(self):
"""Receives the server's response of an Rpc message.
Returns:
Raw byte string of the response.
Raises:
Error: a socket error occurred during the read.
"""
try:
response = self._client.readline()
self.log.debug('Snippet received: %s', response)
return response
except socket.error as e:
raise Error(
self._ad,
'Encountered socket error reading RPC response "%s"' % e) | python | def _client_receive(self):
"""Receives the server's response of an Rpc message.
Returns:
Raw byte string of the response.
Raises:
Error: a socket error occurred during the read.
"""
try:
response = self._client.readline()
self.log.debug('Snippet received: %s', response)
return response
except socket.error as e:
raise Error(
self._ad,
'Encountered socket error reading RPC response "%s"' % e) | [
"def",
"_client_receive",
"(",
"self",
")",
":",
"try",
":",
"response",
"=",
"self",
".",
"_client",
".",
"readline",
"(",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'Snippet received: %s'",
",",
"response",
")",
"return",
"response",
"except",
"socket"... | Receives the server's response of an Rpc message.
Returns:
Raw byte string of the response.
Raises:
Error: a socket error occurred during the read. | [
"Receives",
"the",
"server",
"s",
"response",
"of",
"an",
"Rpc",
"message",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/jsonrpc_client_base.py#L256-L272 | train | 205,406 |
google/mobly | mobly/controllers/android_device_lib/jsonrpc_client_base.py | JsonRpcClientBase._rpc | def _rpc(self, method, *args):
"""Sends an rpc to the app.
Args:
method: str, The name of the method to execute.
args: any, The args of the method.
Returns:
The result of the rpc.
Raises:
ProtocolError: Something went wrong with the protocol.
ApiError: The rpc went through, however executed with errors.
"""
with self._lock:
apiid = next(self._counter)
data = {'id': apiid, 'method': method, 'params': args}
request = json.dumps(data)
self._client_send(request)
response = self._client_receive()
if not response:
raise ProtocolError(self._ad,
ProtocolError.NO_RESPONSE_FROM_SERVER)
result = json.loads(str(response, encoding='utf8'))
if result['error']:
raise ApiError(self._ad, result['error'])
if result['id'] != apiid:
raise ProtocolError(self._ad, ProtocolError.MISMATCHED_API_ID)
if result.get('callback') is not None:
if self._event_client is None:
self._event_client = self._start_event_client()
return callback_handler.CallbackHandler(
callback_id=result['callback'],
event_client=self._event_client,
ret_value=result['result'],
method_name=method,
ad=self._ad)
return result['result'] | python | def _rpc(self, method, *args):
"""Sends an rpc to the app.
Args:
method: str, The name of the method to execute.
args: any, The args of the method.
Returns:
The result of the rpc.
Raises:
ProtocolError: Something went wrong with the protocol.
ApiError: The rpc went through, however executed with errors.
"""
with self._lock:
apiid = next(self._counter)
data = {'id': apiid, 'method': method, 'params': args}
request = json.dumps(data)
self._client_send(request)
response = self._client_receive()
if not response:
raise ProtocolError(self._ad,
ProtocolError.NO_RESPONSE_FROM_SERVER)
result = json.loads(str(response, encoding='utf8'))
if result['error']:
raise ApiError(self._ad, result['error'])
if result['id'] != apiid:
raise ProtocolError(self._ad, ProtocolError.MISMATCHED_API_ID)
if result.get('callback') is not None:
if self._event_client is None:
self._event_client = self._start_event_client()
return callback_handler.CallbackHandler(
callback_id=result['callback'],
event_client=self._event_client,
ret_value=result['result'],
method_name=method,
ad=self._ad)
return result['result'] | [
"def",
"_rpc",
"(",
"self",
",",
"method",
",",
"*",
"args",
")",
":",
"with",
"self",
".",
"_lock",
":",
"apiid",
"=",
"next",
"(",
"self",
".",
"_counter",
")",
"data",
"=",
"{",
"'id'",
":",
"apiid",
",",
"'method'",
":",
"method",
",",
"'para... | Sends an rpc to the app.
Args:
method: str, The name of the method to execute.
args: any, The args of the method.
Returns:
The result of the rpc.
Raises:
ProtocolError: Something went wrong with the protocol.
ApiError: The rpc went through, however executed with errors. | [
"Sends",
"an",
"rpc",
"to",
"the",
"app",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/jsonrpc_client_base.py#L289-L326 | train | 205,407 |
google/mobly | mobly/controllers/android_device_lib/jsonrpc_client_base.py | JsonRpcClientBase.disable_hidden_api_blacklist | def disable_hidden_api_blacklist(self):
"""If necessary and possible, disables hidden api blacklist."""
version_codename = self._ad.adb.getprop('ro.build.version.codename')
sdk_version = int(self._ad.adb.getprop('ro.build.version.sdk'))
# we check version_codename in addition to sdk_version because P builds
# in development report sdk_version 27, but still enforce the blacklist.
if self._ad.is_rootable and (sdk_version >= 28
or version_codename == 'P'):
self._ad.adb.shell(
'settings put global hidden_api_blacklist_exemptions "*"') | python | def disable_hidden_api_blacklist(self):
"""If necessary and possible, disables hidden api blacklist."""
version_codename = self._ad.adb.getprop('ro.build.version.codename')
sdk_version = int(self._ad.adb.getprop('ro.build.version.sdk'))
# we check version_codename in addition to sdk_version because P builds
# in development report sdk_version 27, but still enforce the blacklist.
if self._ad.is_rootable and (sdk_version >= 28
or version_codename == 'P'):
self._ad.adb.shell(
'settings put global hidden_api_blacklist_exemptions "*"') | [
"def",
"disable_hidden_api_blacklist",
"(",
"self",
")",
":",
"version_codename",
"=",
"self",
".",
"_ad",
".",
"adb",
".",
"getprop",
"(",
"'ro.build.version.codename'",
")",
"sdk_version",
"=",
"int",
"(",
"self",
".",
"_ad",
".",
"adb",
".",
"getprop",
"(... | If necessary and possible, disables hidden api blacklist. | [
"If",
"necessary",
"and",
"possible",
"disables",
"hidden",
"api",
"blacklist",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/jsonrpc_client_base.py#L328-L337 | train | 205,408 |
google/mobly | mobly/controllers/iperf_server.py | IPerfServer.start | def start(self, extra_args="", tag=""):
"""Starts iperf server on specified port.
Args:
extra_args: A string representing extra arguments to start iperf
server with.
tag: Appended to log file name to identify logs from different
iperf runs.
"""
if self.started:
return
utils.create_dir(self.log_path)
if tag:
tag = tag + ','
out_file_name = "IPerfServer,{},{}{}.log".format(
self.port, tag, len(self.log_files))
full_out_path = os.path.join(self.log_path, out_file_name)
cmd = '%s %s > %s' % (self.iperf_str, extra_args, full_out_path)
self.iperf_process = utils.start_standing_subprocess(cmd, shell=True)
self.log_files.append(full_out_path)
self.started = True | python | def start(self, extra_args="", tag=""):
"""Starts iperf server on specified port.
Args:
extra_args: A string representing extra arguments to start iperf
server with.
tag: Appended to log file name to identify logs from different
iperf runs.
"""
if self.started:
return
utils.create_dir(self.log_path)
if tag:
tag = tag + ','
out_file_name = "IPerfServer,{},{}{}.log".format(
self.port, tag, len(self.log_files))
full_out_path = os.path.join(self.log_path, out_file_name)
cmd = '%s %s > %s' % (self.iperf_str, extra_args, full_out_path)
self.iperf_process = utils.start_standing_subprocess(cmd, shell=True)
self.log_files.append(full_out_path)
self.started = True | [
"def",
"start",
"(",
"self",
",",
"extra_args",
"=",
"\"\"",
",",
"tag",
"=",
"\"\"",
")",
":",
"if",
"self",
".",
"started",
":",
"return",
"utils",
".",
"create_dir",
"(",
"self",
".",
"log_path",
")",
"if",
"tag",
":",
"tag",
"=",
"tag",
"+",
... | Starts iperf server on specified port.
Args:
extra_args: A string representing extra arguments to start iperf
server with.
tag: Appended to log file name to identify logs from different
iperf runs. | [
"Starts",
"iperf",
"server",
"on",
"specified",
"port",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/iperf_server.py#L125-L145 | train | 205,409 |
google/mobly | mobly/controllers/sniffer_lib/local/local_base.py | SnifferLocalBase._post_process | def _post_process(self):
"""Utility function which is executed after a capture is done. It
moves the capture file to the requested location.
"""
self._process = None
shutil.move(self._temp_capture_file_path, self._capture_file_path) | python | def _post_process(self):
"""Utility function which is executed after a capture is done. It
moves the capture file to the requested location.
"""
self._process = None
shutil.move(self._temp_capture_file_path, self._capture_file_path) | [
"def",
"_post_process",
"(",
"self",
")",
":",
"self",
".",
"_process",
"=",
"None",
"shutil",
".",
"move",
"(",
"self",
".",
"_temp_capture_file_path",
",",
"self",
".",
"_capture_file_path",
")"
] | Utility function which is executed after a capture is done. It
moves the capture file to the requested location. | [
"Utility",
"function",
"which",
"is",
"executed",
"after",
"a",
"capture",
"is",
"done",
".",
"It",
"moves",
"the",
"capture",
"file",
"to",
"the",
"requested",
"location",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/sniffer_lib/local/local_base.py#L106-L111 | train | 205,410 |
google/mobly | mobly/controllers/android_device_lib/adb.py | list_occupied_adb_ports | def list_occupied_adb_ports():
"""Lists all the host ports occupied by adb forward.
This is useful because adb will silently override the binding if an attempt
to bind to a port already used by adb was made, instead of throwing binding
error. So one should always check what ports adb is using before trying to
bind to a port with adb.
Returns:
A list of integers representing occupied host ports.
"""
out = AdbProxy().forward('--list')
clean_lines = str(out, 'utf-8').strip().split('\n')
used_ports = []
for line in clean_lines:
tokens = line.split(' tcp:')
if len(tokens) != 3:
continue
used_ports.append(int(tokens[1]))
return used_ports | python | def list_occupied_adb_ports():
"""Lists all the host ports occupied by adb forward.
This is useful because adb will silently override the binding if an attempt
to bind to a port already used by adb was made, instead of throwing binding
error. So one should always check what ports adb is using before trying to
bind to a port with adb.
Returns:
A list of integers representing occupied host ports.
"""
out = AdbProxy().forward('--list')
clean_lines = str(out, 'utf-8').strip().split('\n')
used_ports = []
for line in clean_lines:
tokens = line.split(' tcp:')
if len(tokens) != 3:
continue
used_ports.append(int(tokens[1]))
return used_ports | [
"def",
"list_occupied_adb_ports",
"(",
")",
":",
"out",
"=",
"AdbProxy",
"(",
")",
".",
"forward",
"(",
"'--list'",
")",
"clean_lines",
"=",
"str",
"(",
"out",
",",
"'utf-8'",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"used_ports",
... | Lists all the host ports occupied by adb forward.
This is useful because adb will silently override the binding if an attempt
to bind to a port already used by adb was made, instead of throwing binding
error. So one should always check what ports adb is using before trying to
bind to a port with adb.
Returns:
A list of integers representing occupied host ports. | [
"Lists",
"all",
"the",
"host",
"ports",
"occupied",
"by",
"adb",
"forward",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/adb.py#L90-L109 | train | 205,411 |
google/mobly | mobly/controllers/android_device_lib/adb.py | AdbProxy._exec_cmd | def _exec_cmd(self, args, shell, timeout, stderr):
"""Executes adb commands.
Args:
args: string or list of strings, program arguments.
See subprocess.Popen() documentation.
shell: bool, True to run this command through the system shell,
False to invoke it directly. See subprocess.Popen() docs.
timeout: float, the number of seconds to wait before timing out.
If not specified, no timeout takes effect.
stderr: a Byte stream, like io.BytesIO, stderr of the command will
be written to this object if provided.
Returns:
The output of the adb command run if exit code is 0.
Raises:
ValueError: timeout value is invalid.
AdbError: The adb command exit code is not 0.
AdbTimeoutError: The adb command timed out.
"""
if timeout and timeout <= 0:
raise ValueError('Timeout is not a positive value: %s' % timeout)
try:
(ret, out, err) = utils.run_command(
args, shell=shell, timeout=timeout)
except psutil.TimeoutExpired:
raise AdbTimeoutError(
cmd=args, timeout=timeout, serial=self.serial)
if stderr:
stderr.write(err)
logging.debug('cmd: %s, stdout: %s, stderr: %s, ret: %s',
utils.cli_cmd_to_string(args), out, err, ret)
if ret == 0:
return out
else:
raise AdbError(
cmd=args,
stdout=out,
stderr=err,
ret_code=ret,
serial=self.serial) | python | def _exec_cmd(self, args, shell, timeout, stderr):
"""Executes adb commands.
Args:
args: string or list of strings, program arguments.
See subprocess.Popen() documentation.
shell: bool, True to run this command through the system shell,
False to invoke it directly. See subprocess.Popen() docs.
timeout: float, the number of seconds to wait before timing out.
If not specified, no timeout takes effect.
stderr: a Byte stream, like io.BytesIO, stderr of the command will
be written to this object if provided.
Returns:
The output of the adb command run if exit code is 0.
Raises:
ValueError: timeout value is invalid.
AdbError: The adb command exit code is not 0.
AdbTimeoutError: The adb command timed out.
"""
if timeout and timeout <= 0:
raise ValueError('Timeout is not a positive value: %s' % timeout)
try:
(ret, out, err) = utils.run_command(
args, shell=shell, timeout=timeout)
except psutil.TimeoutExpired:
raise AdbTimeoutError(
cmd=args, timeout=timeout, serial=self.serial)
if stderr:
stderr.write(err)
logging.debug('cmd: %s, stdout: %s, stderr: %s, ret: %s',
utils.cli_cmd_to_string(args), out, err, ret)
if ret == 0:
return out
else:
raise AdbError(
cmd=args,
stdout=out,
stderr=err,
ret_code=ret,
serial=self.serial) | [
"def",
"_exec_cmd",
"(",
"self",
",",
"args",
",",
"shell",
",",
"timeout",
",",
"stderr",
")",
":",
"if",
"timeout",
"and",
"timeout",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"'Timeout is not a positive value: %s'",
"%",
"timeout",
")",
"try",
":",
"(... | Executes adb commands.
Args:
args: string or list of strings, program arguments.
See subprocess.Popen() documentation.
shell: bool, True to run this command through the system shell,
False to invoke it directly. See subprocess.Popen() docs.
timeout: float, the number of seconds to wait before timing out.
If not specified, no timeout takes effect.
stderr: a Byte stream, like io.BytesIO, stderr of the command will
be written to this object if provided.
Returns:
The output of the adb command run if exit code is 0.
Raises:
ValueError: timeout value is invalid.
AdbError: The adb command exit code is not 0.
AdbTimeoutError: The adb command timed out. | [
"Executes",
"adb",
"commands",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/adb.py#L138-L180 | train | 205,412 |
google/mobly | mobly/controllers/android_device_lib/adb.py | AdbProxy._execute_and_process_stdout | def _execute_and_process_stdout(self, args, shell, handler):
"""Executes adb commands and processes the stdout with a handler.
Args:
args: string or list of strings, program arguments.
See subprocess.Popen() documentation.
shell: bool, True to run this command through the system shell,
False to invoke it directly. See subprocess.Popen() docs.
handler: func, a function to handle adb stdout line by line.
Returns:
The stderr of the adb command run if exit code is 0.
Raises:
AdbError: The adb command exit code is not 0.
"""
proc = subprocess.Popen(
args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=shell,
bufsize=1)
out = '[elided, processed via handler]'
try:
# Even if the process dies, stdout.readline still works
# and will continue until it runs out of stdout to process.
while True:
line = proc.stdout.readline()
if line:
handler(line)
else:
break
finally:
# Note, communicate will not contain any buffered output.
(unexpected_out, err) = proc.communicate()
if unexpected_out:
out = '[unexpected stdout] %s' % unexpected_out
for line in unexpected_out.splitlines():
handler(line)
ret = proc.returncode
logging.debug('cmd: %s, stdout: %s, stderr: %s, ret: %s',
utils.cli_cmd_to_string(args), out, err, ret)
if ret == 0:
return err
else:
raise AdbError(cmd=args, stdout=out, stderr=err, ret_code=ret) | python | def _execute_and_process_stdout(self, args, shell, handler):
"""Executes adb commands and processes the stdout with a handler.
Args:
args: string or list of strings, program arguments.
See subprocess.Popen() documentation.
shell: bool, True to run this command through the system shell,
False to invoke it directly. See subprocess.Popen() docs.
handler: func, a function to handle adb stdout line by line.
Returns:
The stderr of the adb command run if exit code is 0.
Raises:
AdbError: The adb command exit code is not 0.
"""
proc = subprocess.Popen(
args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=shell,
bufsize=1)
out = '[elided, processed via handler]'
try:
# Even if the process dies, stdout.readline still works
# and will continue until it runs out of stdout to process.
while True:
line = proc.stdout.readline()
if line:
handler(line)
else:
break
finally:
# Note, communicate will not contain any buffered output.
(unexpected_out, err) = proc.communicate()
if unexpected_out:
out = '[unexpected stdout] %s' % unexpected_out
for line in unexpected_out.splitlines():
handler(line)
ret = proc.returncode
logging.debug('cmd: %s, stdout: %s, stderr: %s, ret: %s',
utils.cli_cmd_to_string(args), out, err, ret)
if ret == 0:
return err
else:
raise AdbError(cmd=args, stdout=out, stderr=err, ret_code=ret) | [
"def",
"_execute_and_process_stdout",
"(",
"self",
",",
"args",
",",
"shell",
",",
"handler",
")",
":",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",... | Executes adb commands and processes the stdout with a handler.
Args:
args: string or list of strings, program arguments.
See subprocess.Popen() documentation.
shell: bool, True to run this command through the system shell,
False to invoke it directly. See subprocess.Popen() docs.
handler: func, a function to handle adb stdout line by line.
Returns:
The stderr of the adb command run if exit code is 0.
Raises:
AdbError: The adb command exit code is not 0. | [
"Executes",
"adb",
"commands",
"and",
"processes",
"the",
"stdout",
"with",
"a",
"handler",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/adb.py#L182-L228 | train | 205,413 |
google/mobly | mobly/controllers/android_device_lib/adb.py | AdbProxy._construct_adb_cmd | def _construct_adb_cmd(self, raw_name, args, shell):
"""Constructs an adb command with arguments for a subprocess call.
Args:
raw_name: string, the raw unsanitized name of the adb command to
format.
args: string or list of strings, arguments to the adb command.
See subprocess.Proc() documentation.
shell: bool, True to run this command through the system shell,
False to invoke it directly. See subprocess.Proc() docs.
Returns:
The adb command in a format appropriate for subprocess. If shell is
True, then this is a string; otherwise, this is a list of
strings.
"""
args = args or ''
name = raw_name.replace('_', '-')
if shell:
args = utils.cli_cmd_to_string(args)
# Add quotes around "adb" in case the ADB path contains spaces. This
# is pretty common on Windows (e.g. Program Files).
if self.serial:
adb_cmd = '"%s" -s "%s" %s %s' % (ADB, self.serial, name, args)
else:
adb_cmd = '"%s" %s %s' % (ADB, name, args)
else:
adb_cmd = [ADB]
if self.serial:
adb_cmd.extend(['-s', self.serial])
adb_cmd.append(name)
if args:
if isinstance(args, basestring):
adb_cmd.append(args)
else:
adb_cmd.extend(args)
return adb_cmd | python | def _construct_adb_cmd(self, raw_name, args, shell):
"""Constructs an adb command with arguments for a subprocess call.
Args:
raw_name: string, the raw unsanitized name of the adb command to
format.
args: string or list of strings, arguments to the adb command.
See subprocess.Proc() documentation.
shell: bool, True to run this command through the system shell,
False to invoke it directly. See subprocess.Proc() docs.
Returns:
The adb command in a format appropriate for subprocess. If shell is
True, then this is a string; otherwise, this is a list of
strings.
"""
args = args or ''
name = raw_name.replace('_', '-')
if shell:
args = utils.cli_cmd_to_string(args)
# Add quotes around "adb" in case the ADB path contains spaces. This
# is pretty common on Windows (e.g. Program Files).
if self.serial:
adb_cmd = '"%s" -s "%s" %s %s' % (ADB, self.serial, name, args)
else:
adb_cmd = '"%s" %s %s' % (ADB, name, args)
else:
adb_cmd = [ADB]
if self.serial:
adb_cmd.extend(['-s', self.serial])
adb_cmd.append(name)
if args:
if isinstance(args, basestring):
adb_cmd.append(args)
else:
adb_cmd.extend(args)
return adb_cmd | [
"def",
"_construct_adb_cmd",
"(",
"self",
",",
"raw_name",
",",
"args",
",",
"shell",
")",
":",
"args",
"=",
"args",
"or",
"''",
"name",
"=",
"raw_name",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
"if",
"shell",
":",
"args",
"=",
"utils",
".",
"c... | Constructs an adb command with arguments for a subprocess call.
Args:
raw_name: string, the raw unsanitized name of the adb command to
format.
args: string or list of strings, arguments to the adb command.
See subprocess.Proc() documentation.
shell: bool, True to run this command through the system shell,
False to invoke it directly. See subprocess.Proc() docs.
Returns:
The adb command in a format appropriate for subprocess. If shell is
True, then this is a string; otherwise, this is a list of
strings. | [
"Constructs",
"an",
"adb",
"command",
"with",
"arguments",
"for",
"a",
"subprocess",
"call",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/adb.py#L230-L266 | train | 205,414 |
google/mobly | mobly/controllers/android_device_lib/adb.py | AdbProxy.getprop | def getprop(self, prop_name):
"""Get a property of the device.
This is a convenience wrapper for "adb shell getprop xxx".
Args:
prop_name: A string that is the name of the property to get.
Returns:
A string that is the value of the property, or None if the property
doesn't exist.
"""
return self.shell(
['getprop', prop_name],
timeout=DEFAULT_GETPROP_TIMEOUT_SEC).decode('utf-8').strip() | python | def getprop(self, prop_name):
"""Get a property of the device.
This is a convenience wrapper for "adb shell getprop xxx".
Args:
prop_name: A string that is the name of the property to get.
Returns:
A string that is the value of the property, or None if the property
doesn't exist.
"""
return self.shell(
['getprop', prop_name],
timeout=DEFAULT_GETPROP_TIMEOUT_SEC).decode('utf-8').strip() | [
"def",
"getprop",
"(",
"self",
",",
"prop_name",
")",
":",
"return",
"self",
".",
"shell",
"(",
"[",
"'getprop'",
",",
"prop_name",
"]",
",",
"timeout",
"=",
"DEFAULT_GETPROP_TIMEOUT_SEC",
")",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"strip",
"(",
")"
] | Get a property of the device.
This is a convenience wrapper for "adb shell getprop xxx".
Args:
prop_name: A string that is the name of the property to get.
Returns:
A string that is the value of the property, or None if the property
doesn't exist. | [
"Get",
"a",
"property",
"of",
"the",
"device",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/adb.py#L280-L294 | train | 205,415 |
google/mobly | mobly/controllers/android_device_lib/adb.py | AdbProxy.has_shell_command | def has_shell_command(self, command):
"""Checks to see if a given check command exists on the device.
Args:
command: A string that is the name of the command to check.
Returns:
A boolean that is True if the command exists and False otherwise.
"""
try:
output = self.shell(['command', '-v',
command]).decode('utf-8').strip()
return command in output
except AdbError:
# If the command doesn't exist, then 'command -v' can return
# an exit code > 1.
return False | python | def has_shell_command(self, command):
"""Checks to see if a given check command exists on the device.
Args:
command: A string that is the name of the command to check.
Returns:
A boolean that is True if the command exists and False otherwise.
"""
try:
output = self.shell(['command', '-v',
command]).decode('utf-8').strip()
return command in output
except AdbError:
# If the command doesn't exist, then 'command -v' can return
# an exit code > 1.
return False | [
"def",
"has_shell_command",
"(",
"self",
",",
"command",
")",
":",
"try",
":",
"output",
"=",
"self",
".",
"shell",
"(",
"[",
"'command'",
",",
"'-v'",
",",
"command",
"]",
")",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"strip",
"(",
")",
"return",
... | Checks to see if a given check command exists on the device.
Args:
command: A string that is the name of the command to check.
Returns:
A boolean that is True if the command exists and False otherwise. | [
"Checks",
"to",
"see",
"if",
"a",
"given",
"check",
"command",
"exists",
"on",
"the",
"device",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/adb.py#L296-L312 | train | 205,416 |
google/mobly | mobly/controllers/android_device_lib/adb.py | AdbProxy.instrument | def instrument(self, package, options=None, runner=None, handler=None):
"""Runs an instrumentation command on the device.
This is a convenience wrapper to avoid parameter formatting.
Example:
.. code-block:: python
device.instrument(
'com.my.package.test',
options = {
'class': 'com.my.package.test.TestSuite',
},
)
Args:
package: string, the package of the instrumentation tests.
options: dict, the instrumentation options including the test
class.
runner: string, the test runner name, which defaults to
DEFAULT_INSTRUMENTATION_RUNNER.
handler: optional func, when specified the function is used to parse
the instrumentation stdout line by line as the output is
generated; otherwise, the stdout is simply returned once the
instrumentation is finished.
Returns:
The stdout of instrumentation command or the stderr if the handler
is set.
"""
if runner is None:
runner = DEFAULT_INSTRUMENTATION_RUNNER
if options is None:
options = {}
options_list = []
for option_key, option_value in options.items():
options_list.append('-e %s %s' % (option_key, option_value))
options_string = ' '.join(options_list)
instrumentation_command = 'am instrument -r -w %s %s/%s' % (
options_string, package, runner)
logging.info('AndroidDevice|%s: Executing adb shell %s', self.serial,
instrumentation_command)
if handler is None:
# Flow kept for backwards-compatibility reasons
self._exec_adb_cmd(
'shell',
instrumentation_command,
shell=False,
timeout=None,
stderr=None)
else:
return self._execute_adb_and_process_stdout(
'shell', instrumentation_command, shell=False, handler=handler) | python | def instrument(self, package, options=None, runner=None, handler=None):
"""Runs an instrumentation command on the device.
This is a convenience wrapper to avoid parameter formatting.
Example:
.. code-block:: python
device.instrument(
'com.my.package.test',
options = {
'class': 'com.my.package.test.TestSuite',
},
)
Args:
package: string, the package of the instrumentation tests.
options: dict, the instrumentation options including the test
class.
runner: string, the test runner name, which defaults to
DEFAULT_INSTRUMENTATION_RUNNER.
handler: optional func, when specified the function is used to parse
the instrumentation stdout line by line as the output is
generated; otherwise, the stdout is simply returned once the
instrumentation is finished.
Returns:
The stdout of instrumentation command or the stderr if the handler
is set.
"""
if runner is None:
runner = DEFAULT_INSTRUMENTATION_RUNNER
if options is None:
options = {}
options_list = []
for option_key, option_value in options.items():
options_list.append('-e %s %s' % (option_key, option_value))
options_string = ' '.join(options_list)
instrumentation_command = 'am instrument -r -w %s %s/%s' % (
options_string, package, runner)
logging.info('AndroidDevice|%s: Executing adb shell %s', self.serial,
instrumentation_command)
if handler is None:
# Flow kept for backwards-compatibility reasons
self._exec_adb_cmd(
'shell',
instrumentation_command,
shell=False,
timeout=None,
stderr=None)
else:
return self._execute_adb_and_process_stdout(
'shell', instrumentation_command, shell=False, handler=handler) | [
"def",
"instrument",
"(",
"self",
",",
"package",
",",
"options",
"=",
"None",
",",
"runner",
"=",
"None",
",",
"handler",
"=",
"None",
")",
":",
"if",
"runner",
"is",
"None",
":",
"runner",
"=",
"DEFAULT_INSTRUMENTATION_RUNNER",
"if",
"options",
"is",
"... | Runs an instrumentation command on the device.
This is a convenience wrapper to avoid parameter formatting.
Example:
.. code-block:: python
device.instrument(
'com.my.package.test',
options = {
'class': 'com.my.package.test.TestSuite',
},
)
Args:
package: string, the package of the instrumentation tests.
options: dict, the instrumentation options including the test
class.
runner: string, the test runner name, which defaults to
DEFAULT_INSTRUMENTATION_RUNNER.
handler: optional func, when specified the function is used to parse
the instrumentation stdout line by line as the output is
generated; otherwise, the stdout is simply returned once the
instrumentation is finished.
Returns:
The stdout of instrumentation command or the stderr if the handler
is set. | [
"Runs",
"an",
"instrumentation",
"command",
"on",
"the",
"device",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/adb.py#L319-L374 | train | 205,417 |
google/mobly | mobly/asserts.py | assert_equal | def assert_equal(first, second, msg=None, extras=None):
"""Assert the equality of objects, otherwise fail the test.
Error message is "first != second" by default. Additional explanation can
be supplied in the message.
Args:
first: The first object to compare.
second: The second object to compare.
msg: A string that adds additional info about the failure.
extras: An optional field for extra information to be included in
test result.
"""
my_msg = None
try:
_pyunit_proxy.assertEqual(first, second)
except AssertionError as e:
my_msg = str(e)
if msg:
my_msg = "%s %s" % (my_msg, msg)
# This raise statement is outside of the above except statement to prevent
# Python3's exception message from having two tracebacks.
if my_msg is not None:
raise signals.TestFailure(my_msg, extras=extras) | python | def assert_equal(first, second, msg=None, extras=None):
"""Assert the equality of objects, otherwise fail the test.
Error message is "first != second" by default. Additional explanation can
be supplied in the message.
Args:
first: The first object to compare.
second: The second object to compare.
msg: A string that adds additional info about the failure.
extras: An optional field for extra information to be included in
test result.
"""
my_msg = None
try:
_pyunit_proxy.assertEqual(first, second)
except AssertionError as e:
my_msg = str(e)
if msg:
my_msg = "%s %s" % (my_msg, msg)
# This raise statement is outside of the above except statement to prevent
# Python3's exception message from having two tracebacks.
if my_msg is not None:
raise signals.TestFailure(my_msg, extras=extras) | [
"def",
"assert_equal",
"(",
"first",
",",
"second",
",",
"msg",
"=",
"None",
",",
"extras",
"=",
"None",
")",
":",
"my_msg",
"=",
"None",
"try",
":",
"_pyunit_proxy",
".",
"assertEqual",
"(",
"first",
",",
"second",
")",
"except",
"AssertionError",
"as",... | Assert the equality of objects, otherwise fail the test.
Error message is "first != second" by default. Additional explanation can
be supplied in the message.
Args:
first: The first object to compare.
second: The second object to compare.
msg: A string that adds additional info about the failure.
extras: An optional field for extra information to be included in
test result. | [
"Assert",
"the",
"equality",
"of",
"objects",
"otherwise",
"fail",
"the",
"test",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/asserts.py#L33-L57 | train | 205,418 |
google/mobly | mobly/controllers/android_device_lib/callback_handler.py | CallbackHandler.waitAndGet | def waitAndGet(self, event_name, timeout=DEFAULT_TIMEOUT):
"""Blocks until an event of the specified name has been received and
return the event, or timeout.
Args:
event_name: string, name of the event to get.
timeout: float, the number of seconds to wait before giving up.
Returns:
SnippetEvent, the oldest entry of the specified event.
Raises:
Error: If the specified timeout is longer than the max timeout
supported.
TimeoutError: The expected event does not occur within time limit.
"""
if timeout:
if timeout > MAX_TIMEOUT:
raise Error(
self._ad,
'Specified timeout %s is longer than max timeout %s.' %
(timeout, MAX_TIMEOUT))
# Convert to milliseconds for java side.
timeout_ms = int(timeout * 1000)
try:
raw_event = self._event_client.eventWaitAndGet(
self._id, event_name, timeout_ms)
except Exception as e:
if 'EventSnippetException: timeout.' in str(e):
raise TimeoutError(
self._ad,
'Timed out after waiting %ss for event "%s" triggered by'
' %s (%s).' % (timeout, event_name, self._method_name,
self._id))
raise
return snippet_event.from_dict(raw_event) | python | def waitAndGet(self, event_name, timeout=DEFAULT_TIMEOUT):
"""Blocks until an event of the specified name has been received and
return the event, or timeout.
Args:
event_name: string, name of the event to get.
timeout: float, the number of seconds to wait before giving up.
Returns:
SnippetEvent, the oldest entry of the specified event.
Raises:
Error: If the specified timeout is longer than the max timeout
supported.
TimeoutError: The expected event does not occur within time limit.
"""
if timeout:
if timeout > MAX_TIMEOUT:
raise Error(
self._ad,
'Specified timeout %s is longer than max timeout %s.' %
(timeout, MAX_TIMEOUT))
# Convert to milliseconds for java side.
timeout_ms = int(timeout * 1000)
try:
raw_event = self._event_client.eventWaitAndGet(
self._id, event_name, timeout_ms)
except Exception as e:
if 'EventSnippetException: timeout.' in str(e):
raise TimeoutError(
self._ad,
'Timed out after waiting %ss for event "%s" triggered by'
' %s (%s).' % (timeout, event_name, self._method_name,
self._id))
raise
return snippet_event.from_dict(raw_event) | [
"def",
"waitAndGet",
"(",
"self",
",",
"event_name",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
")",
":",
"if",
"timeout",
":",
"if",
"timeout",
">",
"MAX_TIMEOUT",
":",
"raise",
"Error",
"(",
"self",
".",
"_ad",
",",
"'Specified timeout %s is longer than max timeo... | Blocks until an event of the specified name has been received and
return the event, or timeout.
Args:
event_name: string, name of the event to get.
timeout: float, the number of seconds to wait before giving up.
Returns:
SnippetEvent, the oldest entry of the specified event.
Raises:
Error: If the specified timeout is longer than the max timeout
supported.
TimeoutError: The expected event does not occur within time limit. | [
"Blocks",
"until",
"an",
"event",
"of",
"the",
"specified",
"name",
"has",
"been",
"received",
"and",
"return",
"the",
"event",
"or",
"timeout",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/callback_handler.py#L72-L107 | train | 205,419 |
google/mobly | mobly/controllers/android_device_lib/callback_handler.py | CallbackHandler.waitForEvent | def waitForEvent(self, event_name, predicate, timeout=DEFAULT_TIMEOUT):
"""Wait for an event of a specific name that satisfies the predicate.
This call will block until the expected event has been received or time
out.
The predicate function defines the condition the event is expected to
satisfy. It takes an event and returns True if the condition is
satisfied, False otherwise.
Note all events of the same name that are received but don't satisfy
the predicate will be discarded and not be available for further
consumption.
Args:
event_name: string, the name of the event to wait for.
predicate: function, a function that takes an event (dictionary) and
returns a bool.
timeout: float, default is 120s.
Returns:
dictionary, the event that satisfies the predicate if received.
Raises:
TimeoutError: raised if no event that satisfies the predicate is
received after timeout seconds.
"""
deadline = time.time() + timeout
while time.time() <= deadline:
# Calculate the max timeout for the next event rpc call.
rpc_timeout = deadline - time.time()
if rpc_timeout < 0:
break
# A single RPC call cannot exceed MAX_TIMEOUT.
rpc_timeout = min(rpc_timeout, MAX_TIMEOUT)
try:
event = self.waitAndGet(event_name, rpc_timeout)
except TimeoutError:
# Ignoring TimeoutError since we need to throw one with a more
# specific message.
break
if predicate(event):
return event
raise TimeoutError(
self._ad,
'Timed out after %ss waiting for an "%s" event that satisfies the '
'predicate "%s".' % (timeout, event_name, predicate.__name__)) | python | def waitForEvent(self, event_name, predicate, timeout=DEFAULT_TIMEOUT):
"""Wait for an event of a specific name that satisfies the predicate.
This call will block until the expected event has been received or time
out.
The predicate function defines the condition the event is expected to
satisfy. It takes an event and returns True if the condition is
satisfied, False otherwise.
Note all events of the same name that are received but don't satisfy
the predicate will be discarded and not be available for further
consumption.
Args:
event_name: string, the name of the event to wait for.
predicate: function, a function that takes an event (dictionary) and
returns a bool.
timeout: float, default is 120s.
Returns:
dictionary, the event that satisfies the predicate if received.
Raises:
TimeoutError: raised if no event that satisfies the predicate is
received after timeout seconds.
"""
deadline = time.time() + timeout
while time.time() <= deadline:
# Calculate the max timeout for the next event rpc call.
rpc_timeout = deadline - time.time()
if rpc_timeout < 0:
break
# A single RPC call cannot exceed MAX_TIMEOUT.
rpc_timeout = min(rpc_timeout, MAX_TIMEOUT)
try:
event = self.waitAndGet(event_name, rpc_timeout)
except TimeoutError:
# Ignoring TimeoutError since we need to throw one with a more
# specific message.
break
if predicate(event):
return event
raise TimeoutError(
self._ad,
'Timed out after %ss waiting for an "%s" event that satisfies the '
'predicate "%s".' % (timeout, event_name, predicate.__name__)) | [
"def",
"waitForEvent",
"(",
"self",
",",
"event_name",
",",
"predicate",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
")",
":",
"deadline",
"=",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"while",
"time",
".",
"time",
"(",
")",
"<=",
"deadline",
":",
"#... | Wait for an event of a specific name that satisfies the predicate.
This call will block until the expected event has been received or time
out.
The predicate function defines the condition the event is expected to
satisfy. It takes an event and returns True if the condition is
satisfied, False otherwise.
Note all events of the same name that are received but don't satisfy
the predicate will be discarded and not be available for further
consumption.
Args:
event_name: string, the name of the event to wait for.
predicate: function, a function that takes an event (dictionary) and
returns a bool.
timeout: float, default is 120s.
Returns:
dictionary, the event that satisfies the predicate if received.
Raises:
TimeoutError: raised if no event that satisfies the predicate is
received after timeout seconds. | [
"Wait",
"for",
"an",
"event",
"of",
"a",
"specific",
"name",
"that",
"satisfies",
"the",
"predicate",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/callback_handler.py#L109-L155 | train | 205,420 |
google/mobly | mobly/controllers/android_device_lib/callback_handler.py | CallbackHandler.getAll | def getAll(self, event_name):
"""Gets all the events of a certain name that have been received so
far. This is a non-blocking call.
Args:
callback_id: The id of the callback.
event_name: string, the name of the event to get.
Returns:
A list of SnippetEvent, each representing an event from the Java
side.
"""
raw_events = self._event_client.eventGetAll(self._id, event_name)
return [snippet_event.from_dict(msg) for msg in raw_events] | python | def getAll(self, event_name):
"""Gets all the events of a certain name that have been received so
far. This is a non-blocking call.
Args:
callback_id: The id of the callback.
event_name: string, the name of the event to get.
Returns:
A list of SnippetEvent, each representing an event from the Java
side.
"""
raw_events = self._event_client.eventGetAll(self._id, event_name)
return [snippet_event.from_dict(msg) for msg in raw_events] | [
"def",
"getAll",
"(",
"self",
",",
"event_name",
")",
":",
"raw_events",
"=",
"self",
".",
"_event_client",
".",
"eventGetAll",
"(",
"self",
".",
"_id",
",",
"event_name",
")",
"return",
"[",
"snippet_event",
".",
"from_dict",
"(",
"msg",
")",
"for",
"ms... | Gets all the events of a certain name that have been received so
far. This is a non-blocking call.
Args:
callback_id: The id of the callback.
event_name: string, the name of the event to get.
Returns:
A list of SnippetEvent, each representing an event from the Java
side. | [
"Gets",
"all",
"the",
"events",
"of",
"a",
"certain",
"name",
"that",
"have",
"been",
"received",
"so",
"far",
".",
"This",
"is",
"a",
"non",
"-",
"blocking",
"call",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/callback_handler.py#L157-L170 | train | 205,421 |
google/mobly | mobly/controllers/attenuator.py | _validate_config | def _validate_config(config):
"""Verifies that a config dict for an attenuator device is valid.
Args:
config: A dict that is the configuration for an attenuator device.
Raises:
attenuator.Error: A config is not valid.
"""
required_keys = [KEY_ADDRESS, KEY_MODEL, KEY_PORT, KEY_PATHS]
for key in required_keys:
if key not in config:
raise Error("Required key %s missing from config %s",
(key, config)) | python | def _validate_config(config):
"""Verifies that a config dict for an attenuator device is valid.
Args:
config: A dict that is the configuration for an attenuator device.
Raises:
attenuator.Error: A config is not valid.
"""
required_keys = [KEY_ADDRESS, KEY_MODEL, KEY_PORT, KEY_PATHS]
for key in required_keys:
if key not in config:
raise Error("Required key %s missing from config %s",
(key, config)) | [
"def",
"_validate_config",
"(",
"config",
")",
":",
"required_keys",
"=",
"[",
"KEY_ADDRESS",
",",
"KEY_MODEL",
",",
"KEY_PORT",
",",
"KEY_PATHS",
"]",
"for",
"key",
"in",
"required_keys",
":",
"if",
"key",
"not",
"in",
"config",
":",
"raise",
"Error",
"("... | Verifies that a config dict for an attenuator device is valid.
Args:
config: A dict that is the configuration for an attenuator device.
Raises:
attenuator.Error: A config is not valid. | [
"Verifies",
"that",
"a",
"config",
"dict",
"for",
"an",
"attenuator",
"device",
"is",
"valid",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/attenuator.py#L86-L99 | train | 205,422 |
google/mobly | mobly/controllers/monsoon.py | get_instances | def get_instances(serials):
"""Create Monsoon instances from a list of serials.
Args:
serials: A list of Monsoon (integer) serials.
Returns:
A list of Monsoon objects.
"""
objs = []
for s in serials:
objs.append(Monsoon(serial=s))
return objs | python | def get_instances(serials):
"""Create Monsoon instances from a list of serials.
Args:
serials: A list of Monsoon (integer) serials.
Returns:
A list of Monsoon objects.
"""
objs = []
for s in serials:
objs.append(Monsoon(serial=s))
return objs | [
"def",
"get_instances",
"(",
"serials",
")",
":",
"objs",
"=",
"[",
"]",
"for",
"s",
"in",
"serials",
":",
"objs",
".",
"append",
"(",
"Monsoon",
"(",
"serial",
"=",
"s",
")",
")",
"return",
"objs"
] | Create Monsoon instances from a list of serials.
Args:
serials: A list of Monsoon (integer) serials.
Returns:
A list of Monsoon objects. | [
"Create",
"Monsoon",
"instances",
"from",
"a",
"list",
"of",
"serials",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/monsoon.py#L78-L90 | train | 205,423 |
google/mobly | mobly/controllers/monsoon.py | MonsoonProxy.GetStatus | def GetStatus(self):
"""Requests and waits for status.
Returns:
status dictionary.
"""
# status packet format
STATUS_FORMAT = ">BBBhhhHhhhHBBBxBbHBHHHHBbbHHBBBbbbbbbbbbBH"
STATUS_FIELDS = [
"packetType",
"firmwareVersion",
"protocolVersion",
"mainFineCurrent",
"usbFineCurrent",
"auxFineCurrent",
"voltage1",
"mainCoarseCurrent",
"usbCoarseCurrent",
"auxCoarseCurrent",
"voltage2",
"outputVoltageSetting",
"temperature",
"status",
"leds",
"mainFineResistor",
"serialNumber",
"sampleRate",
"dacCalLow",
"dacCalHigh",
"powerUpCurrentLimit",
"runTimeCurrentLimit",
"powerUpTime",
"usbFineResistor",
"auxFineResistor",
"initialUsbVoltage",
"initialAuxVoltage",
"hardwareRevision",
"temperatureLimit",
"usbPassthroughMode",
"mainCoarseResistor",
"usbCoarseResistor",
"auxCoarseResistor",
"defMainFineResistor",
"defUsbFineResistor",
"defAuxFineResistor",
"defMainCoarseResistor",
"defUsbCoarseResistor",
"defAuxCoarseResistor",
"eventCode",
"eventData",
]
self._SendStruct("BBB", 0x01, 0x00, 0x00)
while 1: # Keep reading, discarding non-status packets
read_bytes = self._ReadPacket()
if not read_bytes:
return None
calsize = struct.calcsize(STATUS_FORMAT)
if len(read_bytes) != calsize or read_bytes[0] != 0x10:
logging.warning("Wanted status, dropped type=0x%02x, len=%d",
read_bytes[0], len(read_bytes))
continue
status = dict(
zip(STATUS_FIELDS, struct.unpack(STATUS_FORMAT, read_bytes)))
p_type = status["packetType"]
if p_type != 0x10:
raise MonsoonError("Package type %s is not 0x10." % p_type)
for k in status.keys():
if k.endswith("VoltageSetting"):
status[k] = 2.0 + status[k] * 0.01
elif k.endswith("FineCurrent"):
pass # needs calibration data
elif k.endswith("CoarseCurrent"):
pass # needs calibration data
elif k.startswith("voltage") or k.endswith("Voltage"):
status[k] = status[k] * 0.000125
elif k.endswith("Resistor"):
status[k] = 0.05 + status[k] * 0.0001
if k.startswith("aux") or k.startswith("defAux"):
status[k] += 0.05
elif k.endswith("CurrentLimit"):
status[k] = 8 * (1023 - status[k]) / 1023.0
return status | python | def GetStatus(self):
"""Requests and waits for status.
Returns:
status dictionary.
"""
# status packet format
STATUS_FORMAT = ">BBBhhhHhhhHBBBxBbHBHHHHBbbHHBBBbbbbbbbbbBH"
STATUS_FIELDS = [
"packetType",
"firmwareVersion",
"protocolVersion",
"mainFineCurrent",
"usbFineCurrent",
"auxFineCurrent",
"voltage1",
"mainCoarseCurrent",
"usbCoarseCurrent",
"auxCoarseCurrent",
"voltage2",
"outputVoltageSetting",
"temperature",
"status",
"leds",
"mainFineResistor",
"serialNumber",
"sampleRate",
"dacCalLow",
"dacCalHigh",
"powerUpCurrentLimit",
"runTimeCurrentLimit",
"powerUpTime",
"usbFineResistor",
"auxFineResistor",
"initialUsbVoltage",
"initialAuxVoltage",
"hardwareRevision",
"temperatureLimit",
"usbPassthroughMode",
"mainCoarseResistor",
"usbCoarseResistor",
"auxCoarseResistor",
"defMainFineResistor",
"defUsbFineResistor",
"defAuxFineResistor",
"defMainCoarseResistor",
"defUsbCoarseResistor",
"defAuxCoarseResistor",
"eventCode",
"eventData",
]
self._SendStruct("BBB", 0x01, 0x00, 0x00)
while 1: # Keep reading, discarding non-status packets
read_bytes = self._ReadPacket()
if not read_bytes:
return None
calsize = struct.calcsize(STATUS_FORMAT)
if len(read_bytes) != calsize or read_bytes[0] != 0x10:
logging.warning("Wanted status, dropped type=0x%02x, len=%d",
read_bytes[0], len(read_bytes))
continue
status = dict(
zip(STATUS_FIELDS, struct.unpack(STATUS_FORMAT, read_bytes)))
p_type = status["packetType"]
if p_type != 0x10:
raise MonsoonError("Package type %s is not 0x10." % p_type)
for k in status.keys():
if k.endswith("VoltageSetting"):
status[k] = 2.0 + status[k] * 0.01
elif k.endswith("FineCurrent"):
pass # needs calibration data
elif k.endswith("CoarseCurrent"):
pass # needs calibration data
elif k.startswith("voltage") or k.endswith("Voltage"):
status[k] = status[k] * 0.000125
elif k.endswith("Resistor"):
status[k] = 0.05 + status[k] * 0.0001
if k.startswith("aux") or k.startswith("defAux"):
status[k] += 0.05
elif k.endswith("CurrentLimit"):
status[k] = 8 * (1023 - status[k]) / 1023.0
return status | [
"def",
"GetStatus",
"(",
"self",
")",
":",
"# status packet format",
"STATUS_FORMAT",
"=",
"\">BBBhhhHhhhHBBBxBbHBHHHHBbbHHBBBbbbbbbbbbBH\"",
"STATUS_FIELDS",
"=",
"[",
"\"packetType\"",
",",
"\"firmwareVersion\"",
",",
"\"protocolVersion\"",
",",
"\"mainFineCurrent\"",
",",
... | Requests and waits for status.
Returns:
status dictionary. | [
"Requests",
"and",
"waits",
"for",
"status",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/monsoon.py#L181-L263 | train | 205,424 |
google/mobly | mobly/controllers/monsoon.py | MonsoonProxy.SetVoltage | def SetVoltage(self, v):
"""Set the output voltage, 0 to disable.
"""
if v == 0:
self._SendStruct("BBB", 0x01, 0x01, 0x00)
else:
self._SendStruct("BBB", 0x01, 0x01, int((v - 2.0) * 100)) | python | def SetVoltage(self, v):
"""Set the output voltage, 0 to disable.
"""
if v == 0:
self._SendStruct("BBB", 0x01, 0x01, 0x00)
else:
self._SendStruct("BBB", 0x01, 0x01, int((v - 2.0) * 100)) | [
"def",
"SetVoltage",
"(",
"self",
",",
"v",
")",
":",
"if",
"v",
"==",
"0",
":",
"self",
".",
"_SendStruct",
"(",
"\"BBB\"",
",",
"0x01",
",",
"0x01",
",",
"0x00",
")",
"else",
":",
"self",
".",
"_SendStruct",
"(",
"\"BBB\"",
",",
"0x01",
",",
"0... | Set the output voltage, 0 to disable. | [
"Set",
"the",
"output",
"voltage",
"0",
"to",
"disable",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/monsoon.py#L274-L280 | train | 205,425 |
google/mobly | mobly/controllers/monsoon.py | MonsoonProxy.SetMaxCurrent | def SetMaxCurrent(self, i):
"""Set the max output current.
"""
if i < 0 or i > 8:
raise MonsoonError(("Target max current %sA, is out of acceptable "
"range [0, 8].") % i)
val = 1023 - int((i / 8) * 1023)
self._SendStruct("BBB", 0x01, 0x0a, val & 0xff)
self._SendStruct("BBB", 0x01, 0x0b, val >> 8) | python | def SetMaxCurrent(self, i):
"""Set the max output current.
"""
if i < 0 or i > 8:
raise MonsoonError(("Target max current %sA, is out of acceptable "
"range [0, 8].") % i)
val = 1023 - int((i / 8) * 1023)
self._SendStruct("BBB", 0x01, 0x0a, val & 0xff)
self._SendStruct("BBB", 0x01, 0x0b, val >> 8) | [
"def",
"SetMaxCurrent",
"(",
"self",
",",
"i",
")",
":",
"if",
"i",
"<",
"0",
"or",
"i",
">",
"8",
":",
"raise",
"MonsoonError",
"(",
"(",
"\"Target max current %sA, is out of acceptable \"",
"\"range [0, 8].\"",
")",
"%",
"i",
")",
"val",
"=",
"1023",
"-"... | Set the max output current. | [
"Set",
"the",
"max",
"output",
"current",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/monsoon.py#L290-L298 | train | 205,426 |
google/mobly | mobly/controllers/monsoon.py | MonsoonProxy.SetMaxPowerUpCurrent | def SetMaxPowerUpCurrent(self, i):
"""Set the max power up current.
"""
if i < 0 or i > 8:
raise MonsoonError(("Target max current %sA, is out of acceptable "
"range [0, 8].") % i)
val = 1023 - int((i / 8) * 1023)
self._SendStruct("BBB", 0x01, 0x08, val & 0xff)
self._SendStruct("BBB", 0x01, 0x09, val >> 8) | python | def SetMaxPowerUpCurrent(self, i):
"""Set the max power up current.
"""
if i < 0 or i > 8:
raise MonsoonError(("Target max current %sA, is out of acceptable "
"range [0, 8].") % i)
val = 1023 - int((i / 8) * 1023)
self._SendStruct("BBB", 0x01, 0x08, val & 0xff)
self._SendStruct("BBB", 0x01, 0x09, val >> 8) | [
"def",
"SetMaxPowerUpCurrent",
"(",
"self",
",",
"i",
")",
":",
"if",
"i",
"<",
"0",
"or",
"i",
">",
"8",
":",
"raise",
"MonsoonError",
"(",
"(",
"\"Target max current %sA, is out of acceptable \"",
"\"range [0, 8].\"",
")",
"%",
"i",
")",
"val",
"=",
"1023"... | Set the max power up current. | [
"Set",
"the",
"max",
"power",
"up",
"current",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/monsoon.py#L300-L308 | train | 205,427 |
google/mobly | mobly/controllers/monsoon.py | MonsoonProxy._FlushInput | def _FlushInput(self):
""" Flush all read data until no more available. """
self.ser.flush()
flushed = 0
while True:
ready_r, ready_w, ready_x = select.select([self.ser], [],
[self.ser], 0)
if len(ready_x) > 0:
logging.error("Exception from serial port.")
return None
elif len(ready_r) > 0:
flushed += 1
self.ser.read(1) # This may cause underlying buffering.
self.ser.flush() # Flush the underlying buffer too.
else:
break | python | def _FlushInput(self):
""" Flush all read data until no more available. """
self.ser.flush()
flushed = 0
while True:
ready_r, ready_w, ready_x = select.select([self.ser], [],
[self.ser], 0)
if len(ready_x) > 0:
logging.error("Exception from serial port.")
return None
elif len(ready_r) > 0:
flushed += 1
self.ser.read(1) # This may cause underlying buffering.
self.ser.flush() # Flush the underlying buffer too.
else:
break | [
"def",
"_FlushInput",
"(",
"self",
")",
":",
"self",
".",
"ser",
".",
"flush",
"(",
")",
"flushed",
"=",
"0",
"while",
"True",
":",
"ready_r",
",",
"ready_w",
",",
"ready_x",
"=",
"select",
".",
"select",
"(",
"[",
"self",
".",
"ser",
"]",
",",
"... | Flush all read data until no more available. | [
"Flush",
"all",
"read",
"data",
"until",
"no",
"more",
"available",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/monsoon.py#L422-L437 | train | 205,428 |
google/mobly | mobly/controllers/monsoon.py | MonsoonData.average_current | def average_current(self):
"""Average current in the unit of mA.
"""
len_data_pt = len(self.data_points)
if len_data_pt == 0:
return 0
cur = sum(self.data_points) * 1000 / len_data_pt
return round(cur, self.sr) | python | def average_current(self):
"""Average current in the unit of mA.
"""
len_data_pt = len(self.data_points)
if len_data_pt == 0:
return 0
cur = sum(self.data_points) * 1000 / len_data_pt
return round(cur, self.sr) | [
"def",
"average_current",
"(",
"self",
")",
":",
"len_data_pt",
"=",
"len",
"(",
"self",
".",
"data_points",
")",
"if",
"len_data_pt",
"==",
"0",
":",
"return",
"0",
"cur",
"=",
"sum",
"(",
"self",
".",
"data_points",
")",
"*",
"1000",
"/",
"len_data_p... | Average current in the unit of mA. | [
"Average",
"current",
"in",
"the",
"unit",
"of",
"mA",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/monsoon.py#L481-L488 | train | 205,429 |
google/mobly | mobly/controllers/monsoon.py | MonsoonData.total_charge | def total_charge(self):
"""Total charged used in the unit of mAh.
"""
charge = (sum(self.data_points) / self.hz) * 1000 / 3600
return round(charge, self.sr) | python | def total_charge(self):
"""Total charged used in the unit of mAh.
"""
charge = (sum(self.data_points) / self.hz) * 1000 / 3600
return round(charge, self.sr) | [
"def",
"total_charge",
"(",
"self",
")",
":",
"charge",
"=",
"(",
"sum",
"(",
"self",
".",
"data_points",
")",
"/",
"self",
".",
"hz",
")",
"*",
"1000",
"/",
"3600",
"return",
"round",
"(",
"charge",
",",
"self",
".",
"sr",
")"
] | Total charged used in the unit of mAh. | [
"Total",
"charged",
"used",
"in",
"the",
"unit",
"of",
"mAh",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/monsoon.py#L491-L495 | train | 205,430 |
google/mobly | mobly/controllers/monsoon.py | MonsoonData.total_power | def total_power(self):
"""Total power used.
"""
power = self.average_current * self.voltage
return round(power, self.sr) | python | def total_power(self):
"""Total power used.
"""
power = self.average_current * self.voltage
return round(power, self.sr) | [
"def",
"total_power",
"(",
"self",
")",
":",
"power",
"=",
"self",
".",
"average_current",
"*",
"self",
".",
"voltage",
"return",
"round",
"(",
"power",
",",
"self",
".",
"sr",
")"
] | Total power used. | [
"Total",
"power",
"used",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/monsoon.py#L498-L502 | train | 205,431 |
google/mobly | mobly/controllers/monsoon.py | MonsoonData.save_to_text_file | def save_to_text_file(monsoon_data, file_path):
"""Save multiple MonsoonData objects to a text file.
Args:
monsoon_data: A list of MonsoonData objects to write to a text
file.
file_path: The full path of the file to save to, including the file
name.
"""
if not monsoon_data:
raise MonsoonError("Attempting to write empty Monsoon data to "
"file, abort")
utils.create_dir(os.path.dirname(file_path))
with io.open(file_path, 'w', encoding='utf-8') as f:
for md in monsoon_data:
f.write(str(md))
f.write(MonsoonData.delimiter) | python | def save_to_text_file(monsoon_data, file_path):
"""Save multiple MonsoonData objects to a text file.
Args:
monsoon_data: A list of MonsoonData objects to write to a text
file.
file_path: The full path of the file to save to, including the file
name.
"""
if not monsoon_data:
raise MonsoonError("Attempting to write empty Monsoon data to "
"file, abort")
utils.create_dir(os.path.dirname(file_path))
with io.open(file_path, 'w', encoding='utf-8') as f:
for md in monsoon_data:
f.write(str(md))
f.write(MonsoonData.delimiter) | [
"def",
"save_to_text_file",
"(",
"monsoon_data",
",",
"file_path",
")",
":",
"if",
"not",
"monsoon_data",
":",
"raise",
"MonsoonError",
"(",
"\"Attempting to write empty Monsoon data to \"",
"\"file, abort\"",
")",
"utils",
".",
"create_dir",
"(",
"os",
".",
"path",
... | Save multiple MonsoonData objects to a text file.
Args:
monsoon_data: A list of MonsoonData objects to write to a text
file.
file_path: The full path of the file to save to, including the file
name. | [
"Save",
"multiple",
"MonsoonData",
"objects",
"to",
"a",
"text",
"file",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/monsoon.py#L543-L559 | train | 205,432 |
google/mobly | mobly/controllers/monsoon.py | MonsoonData.from_text_file | def from_text_file(file_path):
"""Load MonsoonData objects from a text file generated by
MonsoonData.save_to_text_file.
Args:
file_path: The full path of the file load from, including the file
name.
Returns:
A list of MonsoonData objects.
"""
results = []
with io.open(file_path, 'r', encoding='utf-8') as f:
data_strs = f.read().split(MonsoonData.delimiter)
for data_str in data_strs:
results.append(MonsoonData.from_string(data_str))
return results | python | def from_text_file(file_path):
"""Load MonsoonData objects from a text file generated by
MonsoonData.save_to_text_file.
Args:
file_path: The full path of the file load from, including the file
name.
Returns:
A list of MonsoonData objects.
"""
results = []
with io.open(file_path, 'r', encoding='utf-8') as f:
data_strs = f.read().split(MonsoonData.delimiter)
for data_str in data_strs:
results.append(MonsoonData.from_string(data_str))
return results | [
"def",
"from_text_file",
"(",
"file_path",
")",
":",
"results",
"=",
"[",
"]",
"with",
"io",
".",
"open",
"(",
"file_path",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"data_strs",
"=",
"f",
".",
"read",
"(",
")",
".",
"split"... | Load MonsoonData objects from a text file generated by
MonsoonData.save_to_text_file.
Args:
file_path: The full path of the file load from, including the file
name.
Returns:
A list of MonsoonData objects. | [
"Load",
"MonsoonData",
"objects",
"from",
"a",
"text",
"file",
"generated",
"by",
"MonsoonData",
".",
"save_to_text_file",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/monsoon.py#L562-L578 | train | 205,433 |
google/mobly | mobly/controllers/monsoon.py | MonsoonData._validate_data | def _validate_data(self):
"""Verifies that the data points contained in the class are valid.
"""
msg = "Error! Expected {} timestamps, found {}.".format(
len(self._data_points), len(self._timestamps))
if len(self._data_points) != len(self._timestamps):
raise MonsoonError(msg) | python | def _validate_data(self):
"""Verifies that the data points contained in the class are valid.
"""
msg = "Error! Expected {} timestamps, found {}.".format(
len(self._data_points), len(self._timestamps))
if len(self._data_points) != len(self._timestamps):
raise MonsoonError(msg) | [
"def",
"_validate_data",
"(",
"self",
")",
":",
"msg",
"=",
"\"Error! Expected {} timestamps, found {}.\"",
".",
"format",
"(",
"len",
"(",
"self",
".",
"_data_points",
")",
",",
"len",
"(",
"self",
".",
"_timestamps",
")",
")",
"if",
"len",
"(",
"self",
"... | Verifies that the data points contained in the class are valid. | [
"Verifies",
"that",
"the",
"data",
"points",
"contained",
"in",
"the",
"class",
"are",
"valid",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/monsoon.py#L580-L586 | train | 205,434 |
google/mobly | mobly/controllers/monsoon.py | MonsoonData.update_offset | def update_offset(self, new_offset):
"""Updates how many data points to skip in caculations.
Always use this function to update offset instead of directly setting
self.offset.
Args:
new_offset: The new offset.
"""
self.offset = new_offset
self.data_points = self._data_points[self.offset:]
self.timestamps = self._timestamps[self.offset:] | python | def update_offset(self, new_offset):
"""Updates how many data points to skip in caculations.
Always use this function to update offset instead of directly setting
self.offset.
Args:
new_offset: The new offset.
"""
self.offset = new_offset
self.data_points = self._data_points[self.offset:]
self.timestamps = self._timestamps[self.offset:] | [
"def",
"update_offset",
"(",
"self",
",",
"new_offset",
")",
":",
"self",
".",
"offset",
"=",
"new_offset",
"self",
".",
"data_points",
"=",
"self",
".",
"_data_points",
"[",
"self",
".",
"offset",
":",
"]",
"self",
".",
"timestamps",
"=",
"self",
".",
... | Updates how many data points to skip in caculations.
Always use this function to update offset instead of directly setting
self.offset.
Args:
new_offset: The new offset. | [
"Updates",
"how",
"many",
"data",
"points",
"to",
"skip",
"in",
"caculations",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/monsoon.py#L588-L599 | train | 205,435 |
google/mobly | mobly/controllers/monsoon.py | MonsoonData.get_data_with_timestamps | def get_data_with_timestamps(self):
"""Returns the data points with timestamps.
Returns:
A list of tuples in the format of (timestamp, data)
"""
result = []
for t, d in zip(self.timestamps, self.data_points):
result.append(t, round(d, self.lr))
return result | python | def get_data_with_timestamps(self):
"""Returns the data points with timestamps.
Returns:
A list of tuples in the format of (timestamp, data)
"""
result = []
for t, d in zip(self.timestamps, self.data_points):
result.append(t, round(d, self.lr))
return result | [
"def",
"get_data_with_timestamps",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"for",
"t",
",",
"d",
"in",
"zip",
"(",
"self",
".",
"timestamps",
",",
"self",
".",
"data_points",
")",
":",
"result",
".",
"append",
"(",
"t",
",",
"round",
"(",
"... | Returns the data points with timestamps.
Returns:
A list of tuples in the format of (timestamp, data) | [
"Returns",
"the",
"data",
"points",
"with",
"timestamps",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/monsoon.py#L601-L610 | train | 205,436 |
google/mobly | mobly/controllers/monsoon.py | MonsoonData.get_average_record | def get_average_record(self, n):
"""Returns a list of average current numbers, each representing the
average over the last n data points.
Args:
n: Number of data points to average over.
Returns:
A list of average current values.
"""
history_deque = collections.deque()
averages = []
for d in self.data_points:
history_deque.appendleft(d)
if len(history_deque) > n:
history_deque.pop()
avg = sum(history_deque) / len(history_deque)
averages.append(round(avg, self.lr))
return averages | python | def get_average_record(self, n):
"""Returns a list of average current numbers, each representing the
average over the last n data points.
Args:
n: Number of data points to average over.
Returns:
A list of average current values.
"""
history_deque = collections.deque()
averages = []
for d in self.data_points:
history_deque.appendleft(d)
if len(history_deque) > n:
history_deque.pop()
avg = sum(history_deque) / len(history_deque)
averages.append(round(avg, self.lr))
return averages | [
"def",
"get_average_record",
"(",
"self",
",",
"n",
")",
":",
"history_deque",
"=",
"collections",
".",
"deque",
"(",
")",
"averages",
"=",
"[",
"]",
"for",
"d",
"in",
"self",
".",
"data_points",
":",
"history_deque",
".",
"appendleft",
"(",
"d",
")",
... | Returns a list of average current numbers, each representing the
average over the last n data points.
Args:
n: Number of data points to average over.
Returns:
A list of average current values. | [
"Returns",
"a",
"list",
"of",
"average",
"current",
"numbers",
"each",
"representing",
"the",
"average",
"over",
"the",
"last",
"n",
"data",
"points",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/monsoon.py#L612-L630 | train | 205,437 |
google/mobly | mobly/controllers/monsoon.py | Monsoon.set_voltage | def set_voltage(self, volt, ramp=False):
"""Sets the output voltage of monsoon.
Args:
volt: Voltage to set the output to.
ramp: If true, the output voltage will be increased gradually to
prevent tripping Monsoon overvoltage.
"""
if ramp:
self.mon.RampVoltage(self.mon.start_voltage, volt)
else:
self.mon.SetVoltage(volt) | python | def set_voltage(self, volt, ramp=False):
"""Sets the output voltage of monsoon.
Args:
volt: Voltage to set the output to.
ramp: If true, the output voltage will be increased gradually to
prevent tripping Monsoon overvoltage.
"""
if ramp:
self.mon.RampVoltage(self.mon.start_voltage, volt)
else:
self.mon.SetVoltage(volt) | [
"def",
"set_voltage",
"(",
"self",
",",
"volt",
",",
"ramp",
"=",
"False",
")",
":",
"if",
"ramp",
":",
"self",
".",
"mon",
".",
"RampVoltage",
"(",
"self",
".",
"mon",
".",
"start_voltage",
",",
"volt",
")",
"else",
":",
"self",
".",
"mon",
".",
... | Sets the output voltage of monsoon.
Args:
volt: Voltage to set the output to.
ramp: If true, the output voltage will be increased gradually to
prevent tripping Monsoon overvoltage. | [
"Sets",
"the",
"output",
"voltage",
"of",
"monsoon",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/monsoon.py#L684-L695 | train | 205,438 |
google/mobly | mobly/controllers/monsoon.py | Monsoon.take_samples | def take_samples(self, sample_hz, sample_num, sample_offset=0, live=False):
"""Take samples of the current value supplied by monsoon.
This is the actual measurement for power consumption. This function
blocks until the number of samples requested has been fulfilled.
Args:
hz: Number of points to take for every second.
sample_num: Number of samples to take.
offset: The number of initial data points to discard in MonsoonData
calculations. sample_num is extended by offset to compensate.
live: Print each sample in console as measurement goes on.
Returns:
A MonsoonData object representing the data obtained in this
sampling. None if sampling is unsuccessful.
"""
sys.stdout.flush()
voltage = self.mon.GetVoltage()
self.log.info("Taking samples at %dhz for %ds, voltage %.2fv.",
sample_hz, (sample_num / sample_hz), voltage)
sample_num += sample_offset
# Make sure state is normal
self.mon.StopDataCollection()
status = self.mon.GetStatus()
native_hz = status["sampleRate"] * 1000
# Collect and average samples as specified
self.mon.StartDataCollection()
# In case sample_hz doesn't divide native_hz exactly, use this
# invariant: 'offset' = (consumed samples) * sample_hz -
# (emitted samples) * native_hz
# This is the error accumulator in a variation of Bresenham's
# algorithm.
emitted = offset = 0
collected = []
# past n samples for rolling average
history_deque = collections.deque()
current_values = []
timestamps = []
try:
last_flush = time.time()
while emitted < sample_num or sample_num == -1:
# The number of raw samples to consume before emitting the next
# output
need = int((native_hz - offset + sample_hz - 1) / sample_hz)
if need > len(collected): # still need more input samples
samples = self.mon.CollectData()
if not samples:
break
collected.extend(samples)
else:
# Have enough data, generate output samples.
# Adjust for consuming 'need' input samples.
offset += need * sample_hz
# maybe multiple, if sample_hz > native_hz
while offset >= native_hz:
# TODO(angli): Optimize "collected" operations.
this_sample = sum(collected[:need]) / need
this_time = int(time.time())
timestamps.append(this_time)
if live:
self.log.info("%s %s", this_time, this_sample)
current_values.append(this_sample)
sys.stdout.flush()
offset -= native_hz
emitted += 1 # adjust for emitting 1 output sample
collected = collected[need:]
now = time.time()
if now - last_flush >= 0.99: # flush every second
sys.stdout.flush()
last_flush = now
except Exception as e:
pass
self.mon.StopDataCollection()
try:
return MonsoonData(
current_values,
timestamps,
sample_hz,
voltage,
offset=sample_offset)
except:
return None | python | def take_samples(self, sample_hz, sample_num, sample_offset=0, live=False):
"""Take samples of the current value supplied by monsoon.
This is the actual measurement for power consumption. This function
blocks until the number of samples requested has been fulfilled.
Args:
hz: Number of points to take for every second.
sample_num: Number of samples to take.
offset: The number of initial data points to discard in MonsoonData
calculations. sample_num is extended by offset to compensate.
live: Print each sample in console as measurement goes on.
Returns:
A MonsoonData object representing the data obtained in this
sampling. None if sampling is unsuccessful.
"""
sys.stdout.flush()
voltage = self.mon.GetVoltage()
self.log.info("Taking samples at %dhz for %ds, voltage %.2fv.",
sample_hz, (sample_num / sample_hz), voltage)
sample_num += sample_offset
# Make sure state is normal
self.mon.StopDataCollection()
status = self.mon.GetStatus()
native_hz = status["sampleRate"] * 1000
# Collect and average samples as specified
self.mon.StartDataCollection()
# In case sample_hz doesn't divide native_hz exactly, use this
# invariant: 'offset' = (consumed samples) * sample_hz -
# (emitted samples) * native_hz
# This is the error accumulator in a variation of Bresenham's
# algorithm.
emitted = offset = 0
collected = []
# past n samples for rolling average
history_deque = collections.deque()
current_values = []
timestamps = []
try:
last_flush = time.time()
while emitted < sample_num or sample_num == -1:
# The number of raw samples to consume before emitting the next
# output
need = int((native_hz - offset + sample_hz - 1) / sample_hz)
if need > len(collected): # still need more input samples
samples = self.mon.CollectData()
if not samples:
break
collected.extend(samples)
else:
# Have enough data, generate output samples.
# Adjust for consuming 'need' input samples.
offset += need * sample_hz
# maybe multiple, if sample_hz > native_hz
while offset >= native_hz:
# TODO(angli): Optimize "collected" operations.
this_sample = sum(collected[:need]) / need
this_time = int(time.time())
timestamps.append(this_time)
if live:
self.log.info("%s %s", this_time, this_sample)
current_values.append(this_sample)
sys.stdout.flush()
offset -= native_hz
emitted += 1 # adjust for emitting 1 output sample
collected = collected[need:]
now = time.time()
if now - last_flush >= 0.99: # flush every second
sys.stdout.flush()
last_flush = now
except Exception as e:
pass
self.mon.StopDataCollection()
try:
return MonsoonData(
current_values,
timestamps,
sample_hz,
voltage,
offset=sample_offset)
except:
return None | [
"def",
"take_samples",
"(",
"self",
",",
"sample_hz",
",",
"sample_num",
",",
"sample_offset",
"=",
"0",
",",
"live",
"=",
"False",
")",
":",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"voltage",
"=",
"self",
".",
"mon",
".",
"GetVoltage",
"(",
")... | Take samples of the current value supplied by monsoon.
This is the actual measurement for power consumption. This function
blocks until the number of samples requested has been fulfilled.
Args:
hz: Number of points to take for every second.
sample_num: Number of samples to take.
offset: The number of initial data points to discard in MonsoonData
calculations. sample_num is extended by offset to compensate.
live: Print each sample in console as measurement goes on.
Returns:
A MonsoonData object representing the data obtained in this
sampling. None if sampling is unsuccessful. | [
"Take",
"samples",
"of",
"the",
"current",
"value",
"supplied",
"by",
"monsoon",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/monsoon.py#L723-L808 | train | 205,439 |
google/mobly | mobly/controllers/monsoon.py | Monsoon.usb | def usb(self, state):
"""Sets the monsoon's USB passthrough mode. This is specific to the
USB port in front of the monsoon box which connects to the powered
device, NOT the USB that is used to talk to the monsoon itself.
"Off" means USB always off.
"On" means USB always on.
"Auto" means USB is automatically turned off when sampling is going on,
and turned back on when sampling finishes.
Args:
stats: The state to set the USB passthrough to.
Returns:
True if the state is legal and set. False otherwise.
"""
state_lookup = {"off": 0, "on": 1, "auto": 2}
state = state.lower()
if state in state_lookup:
current_state = self.mon.GetUsbPassthrough()
while (current_state != state_lookup[state]):
self.mon.SetUsbPassthrough(state_lookup[state])
time.sleep(1)
current_state = self.mon.GetUsbPassthrough()
return True
return False | python | def usb(self, state):
"""Sets the monsoon's USB passthrough mode. This is specific to the
USB port in front of the monsoon box which connects to the powered
device, NOT the USB that is used to talk to the monsoon itself.
"Off" means USB always off.
"On" means USB always on.
"Auto" means USB is automatically turned off when sampling is going on,
and turned back on when sampling finishes.
Args:
stats: The state to set the USB passthrough to.
Returns:
True if the state is legal and set. False otherwise.
"""
state_lookup = {"off": 0, "on": 1, "auto": 2}
state = state.lower()
if state in state_lookup:
current_state = self.mon.GetUsbPassthrough()
while (current_state != state_lookup[state]):
self.mon.SetUsbPassthrough(state_lookup[state])
time.sleep(1)
current_state = self.mon.GetUsbPassthrough()
return True
return False | [
"def",
"usb",
"(",
"self",
",",
"state",
")",
":",
"state_lookup",
"=",
"{",
"\"off\"",
":",
"0",
",",
"\"on\"",
":",
"1",
",",
"\"auto\"",
":",
"2",
"}",
"state",
"=",
"state",
".",
"lower",
"(",
")",
"if",
"state",
"in",
"state_lookup",
":",
"c... | Sets the monsoon's USB passthrough mode. This is specific to the
USB port in front of the monsoon box which connects to the powered
device, NOT the USB that is used to talk to the monsoon itself.
"Off" means USB always off.
"On" means USB always on.
"Auto" means USB is automatically turned off when sampling is going on,
and turned back on when sampling finishes.
Args:
stats: The state to set the USB passthrough to.
Returns:
True if the state is legal and set. False otherwise. | [
"Sets",
"the",
"monsoon",
"s",
"USB",
"passthrough",
"mode",
".",
"This",
"is",
"specific",
"to",
"the",
"USB",
"port",
"in",
"front",
"of",
"the",
"monsoon",
"box",
"which",
"connects",
"to",
"the",
"powered",
"device",
"NOT",
"the",
"USB",
"that",
"is"... | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/monsoon.py#L811-L836 | train | 205,440 |
google/mobly | mobly/controllers/monsoon.py | Monsoon.measure_power | def measure_power(self, hz, duration, tag, offset=30):
"""Measure power consumption of the attached device.
Because it takes some time for the device to calm down after the usb
connection is cut, an offset is set for each measurement. The default
is 30s. The total time taken to measure will be (duration + offset).
Args:
hz: Number of samples to take per second.
duration: Number of seconds to take samples for in each step.
offset: The number of seconds of initial data to discard.
tag: A string that's the name of the collected data group.
Returns:
A MonsoonData object with the measured power data.
"""
num = duration * hz
oset = offset * hz
data = None
self.usb("auto")
time.sleep(1)
with self.dut.handle_usb_disconnect():
time.sleep(1)
try:
data = self.take_samples(hz, num, sample_offset=oset)
if not data:
raise MonsoonError(
"No data was collected in measurement %s." % tag)
data.tag = tag
self.dut.log.info("Measurement summary: %s", repr(data))
return data
finally:
self.mon.StopDataCollection()
self.log.info("Finished taking samples, reconnecting to dut.")
self.usb("on")
self.dut.adb.wait_for_device(timeout=DEFAULT_TIMEOUT_USB_ON)
# Wait for device to come back online.
time.sleep(10)
self.dut.log.info("Dut reconnected.") | python | def measure_power(self, hz, duration, tag, offset=30):
"""Measure power consumption of the attached device.
Because it takes some time for the device to calm down after the usb
connection is cut, an offset is set for each measurement. The default
is 30s. The total time taken to measure will be (duration + offset).
Args:
hz: Number of samples to take per second.
duration: Number of seconds to take samples for in each step.
offset: The number of seconds of initial data to discard.
tag: A string that's the name of the collected data group.
Returns:
A MonsoonData object with the measured power data.
"""
num = duration * hz
oset = offset * hz
data = None
self.usb("auto")
time.sleep(1)
with self.dut.handle_usb_disconnect():
time.sleep(1)
try:
data = self.take_samples(hz, num, sample_offset=oset)
if not data:
raise MonsoonError(
"No data was collected in measurement %s." % tag)
data.tag = tag
self.dut.log.info("Measurement summary: %s", repr(data))
return data
finally:
self.mon.StopDataCollection()
self.log.info("Finished taking samples, reconnecting to dut.")
self.usb("on")
self.dut.adb.wait_for_device(timeout=DEFAULT_TIMEOUT_USB_ON)
# Wait for device to come back online.
time.sleep(10)
self.dut.log.info("Dut reconnected.") | [
"def",
"measure_power",
"(",
"self",
",",
"hz",
",",
"duration",
",",
"tag",
",",
"offset",
"=",
"30",
")",
":",
"num",
"=",
"duration",
"*",
"hz",
"oset",
"=",
"offset",
"*",
"hz",
"data",
"=",
"None",
"self",
".",
"usb",
"(",
"\"auto\"",
")",
"... | Measure power consumption of the attached device.
Because it takes some time for the device to calm down after the usb
connection is cut, an offset is set for each measurement. The default
is 30s. The total time taken to measure will be (duration + offset).
Args:
hz: Number of samples to take per second.
duration: Number of seconds to take samples for in each step.
offset: The number of seconds of initial data to discard.
tag: A string that's the name of the collected data group.
Returns:
A MonsoonData object with the measured power data. | [
"Measure",
"power",
"consumption",
"of",
"the",
"attached",
"device",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/monsoon.py#L846-L884 | train | 205,441 |
google/mobly | mobly/records.py | ExceptionRecord._set_details | def _set_details(self, content):
"""Sets the `details` field.
Args:
content: the content to extract details from.
"""
try:
self.details = str(content)
except UnicodeEncodeError:
if sys.version_info < (3, 0):
# If Py2 threw encode error, convert to unicode.
self.details = unicode(content)
else:
# We should never hit this in Py3, if this happens, record
# an encoded version of the content for users to handle.
logging.error(
'Unable to decode "%s" in Py3, encoding in utf-8.',
content)
self.details = content.encode('utf-8') | python | def _set_details(self, content):
"""Sets the `details` field.
Args:
content: the content to extract details from.
"""
try:
self.details = str(content)
except UnicodeEncodeError:
if sys.version_info < (3, 0):
# If Py2 threw encode error, convert to unicode.
self.details = unicode(content)
else:
# We should never hit this in Py3, if this happens, record
# an encoded version of the content for users to handle.
logging.error(
'Unable to decode "%s" in Py3, encoding in utf-8.',
content)
self.details = content.encode('utf-8') | [
"def",
"_set_details",
"(",
"self",
",",
"content",
")",
":",
"try",
":",
"self",
".",
"details",
"=",
"str",
"(",
"content",
")",
"except",
"UnicodeEncodeError",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
":",
"# If Py2 threw... | Sets the `details` field.
Args:
content: the content to extract details from. | [
"Sets",
"the",
"details",
"field",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/records.py#L255-L273 | train | 205,442 |
google/mobly | mobly/config_parser.py | _load_config_file | def _load_config_file(path):
"""Loads a test config file.
The test config file has to be in YAML format.
Args:
path: A string that is the full path to the config file, including the
file name.
Returns:
A dict that represents info in the config file.
"""
with io.open(utils.abs_path(path), 'r', encoding='utf-8') as f:
conf = yaml.load(f)
return conf | python | def _load_config_file(path):
"""Loads a test config file.
The test config file has to be in YAML format.
Args:
path: A string that is the full path to the config file, including the
file name.
Returns:
A dict that represents info in the config file.
"""
with io.open(utils.abs_path(path), 'r', encoding='utf-8') as f:
conf = yaml.load(f)
return conf | [
"def",
"_load_config_file",
"(",
"path",
")",
":",
"with",
"io",
".",
"open",
"(",
"utils",
".",
"abs_path",
"(",
"path",
")",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"conf",
"=",
"yaml",
".",
"load",
"(",
"f",
")",
"ret... | Loads a test config file.
The test config file has to be in YAML format.
Args:
path: A string that is the full path to the config file, including the
file name.
Returns:
A dict that represents info in the config file. | [
"Loads",
"a",
"test",
"config",
"file",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/config_parser.py#L142-L156 | train | 205,443 |
google/mobly | mobly/controllers/android_device_lib/services/snippet_management_service.py | SnippetManagementService.add_snippet_client | def add_snippet_client(self, name, package):
"""Adds a snippet client to the management.
Args:
name: string, the attribute name to which to attach the snippet
client. E.g. `name='maps'` attaches the snippet client to
`ad.maps`.
package: string, the package name of the snippet apk to connect to.
Raises:
Error, if a duplicated name or package is passed in.
"""
# Should not load snippet with the same name more than once.
if name in self._snippet_clients:
raise Error(
self,
'Name "%s" is already registered with package "%s", it cannot '
'be used again.' %
(name, self._snippet_clients[name].client.package))
# Should not load the same snippet package more than once.
for snippet_name, client in self._snippet_clients.items():
if package == client.package:
raise Error(
self,
'Snippet package "%s" has already been loaded under name'
' "%s".' % (package, snippet_name))
client = snippet_client.SnippetClient(package=package, ad=self._device)
client.start_app_and_connect()
self._snippet_clients[name] = client | python | def add_snippet_client(self, name, package):
"""Adds a snippet client to the management.
Args:
name: string, the attribute name to which to attach the snippet
client. E.g. `name='maps'` attaches the snippet client to
`ad.maps`.
package: string, the package name of the snippet apk to connect to.
Raises:
Error, if a duplicated name or package is passed in.
"""
# Should not load snippet with the same name more than once.
if name in self._snippet_clients:
raise Error(
self,
'Name "%s" is already registered with package "%s", it cannot '
'be used again.' %
(name, self._snippet_clients[name].client.package))
# Should not load the same snippet package more than once.
for snippet_name, client in self._snippet_clients.items():
if package == client.package:
raise Error(
self,
'Snippet package "%s" has already been loaded under name'
' "%s".' % (package, snippet_name))
client = snippet_client.SnippetClient(package=package, ad=self._device)
client.start_app_and_connect()
self._snippet_clients[name] = client | [
"def",
"add_snippet_client",
"(",
"self",
",",
"name",
",",
"package",
")",
":",
"# Should not load snippet with the same name more than once.",
"if",
"name",
"in",
"self",
".",
"_snippet_clients",
":",
"raise",
"Error",
"(",
"self",
",",
"'Name \"%s\" is already regist... | Adds a snippet client to the management.
Args:
name: string, the attribute name to which to attach the snippet
client. E.g. `name='maps'` attaches the snippet client to
`ad.maps`.
package: string, the package name of the snippet apk to connect to.
Raises:
Error, if a duplicated name or package is passed in. | [
"Adds",
"a",
"snippet",
"client",
"to",
"the",
"management",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/services/snippet_management_service.py#L59-L87 | train | 205,444 |
google/mobly | mobly/controllers/android_device_lib/services/snippet_management_service.py | SnippetManagementService.remove_snippet_client | def remove_snippet_client(self, name):
"""Removes a snippet client from management.
Args:
name: string, the name of the snippet client to remove.
Raises:
Error: if no snippet client is managed under the specified name.
"""
if name not in self._snippet_clients:
raise Error(self._device, MISSING_SNIPPET_CLIENT_MSG % name)
client = self._snippet_clients.pop(name)
client.stop_app() | python | def remove_snippet_client(self, name):
"""Removes a snippet client from management.
Args:
name: string, the name of the snippet client to remove.
Raises:
Error: if no snippet client is managed under the specified name.
"""
if name not in self._snippet_clients:
raise Error(self._device, MISSING_SNIPPET_CLIENT_MSG % name)
client = self._snippet_clients.pop(name)
client.stop_app() | [
"def",
"remove_snippet_client",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"_snippet_clients",
":",
"raise",
"Error",
"(",
"self",
".",
"_device",
",",
"MISSING_SNIPPET_CLIENT_MSG",
"%",
"name",
")",
"client",
"=",
"self",
... | Removes a snippet client from management.
Args:
name: string, the name of the snippet client to remove.
Raises:
Error: if no snippet client is managed under the specified name. | [
"Removes",
"a",
"snippet",
"client",
"from",
"management",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/services/snippet_management_service.py#L89-L101 | train | 205,445 |
google/mobly | mobly/controllers/android_device_lib/services/snippet_management_service.py | SnippetManagementService.start | def start(self):
"""Starts all the snippet clients under management."""
for client in self._snippet_clients.values():
if not client.is_alive:
self._device.log.debug('Starting SnippetClient<%s>.',
client.package)
client.start_app_and_connect()
else:
self._device.log.debug(
'Not startng SnippetClient<%s> because it is already alive.',
client.package) | python | def start(self):
"""Starts all the snippet clients under management."""
for client in self._snippet_clients.values():
if not client.is_alive:
self._device.log.debug('Starting SnippetClient<%s>.',
client.package)
client.start_app_and_connect()
else:
self._device.log.debug(
'Not startng SnippetClient<%s> because it is already alive.',
client.package) | [
"def",
"start",
"(",
"self",
")",
":",
"for",
"client",
"in",
"self",
".",
"_snippet_clients",
".",
"values",
"(",
")",
":",
"if",
"not",
"client",
".",
"is_alive",
":",
"self",
".",
"_device",
".",
"log",
".",
"debug",
"(",
"'Starting SnippetClient<%s>.... | Starts all the snippet clients under management. | [
"Starts",
"all",
"the",
"snippet",
"clients",
"under",
"management",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/services/snippet_management_service.py#L103-L113 | train | 205,446 |
google/mobly | mobly/controllers/android_device_lib/services/snippet_management_service.py | SnippetManagementService.stop | def stop(self):
"""Stops all the snippet clients under management."""
for client in self._snippet_clients.values():
if client.is_alive:
self._device.log.debug('Stopping SnippetClient<%s>.',
client.package)
client.stop_app()
else:
self._device.log.debug(
'Not stopping SnippetClient<%s> because it is not alive.',
client.package) | python | def stop(self):
"""Stops all the snippet clients under management."""
for client in self._snippet_clients.values():
if client.is_alive:
self._device.log.debug('Stopping SnippetClient<%s>.',
client.package)
client.stop_app()
else:
self._device.log.debug(
'Not stopping SnippetClient<%s> because it is not alive.',
client.package) | [
"def",
"stop",
"(",
"self",
")",
":",
"for",
"client",
"in",
"self",
".",
"_snippet_clients",
".",
"values",
"(",
")",
":",
"if",
"client",
".",
"is_alive",
":",
"self",
".",
"_device",
".",
"log",
".",
"debug",
"(",
"'Stopping SnippetClient<%s>.'",
",",... | Stops all the snippet clients under management. | [
"Stops",
"all",
"the",
"snippet",
"clients",
"under",
"management",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/services/snippet_management_service.py#L115-L125 | train | 205,447 |
google/mobly | mobly/controllers/android_device_lib/services/snippet_management_service.py | SnippetManagementService.pause | def pause(self):
"""Pauses all the snippet clients under management.
This clears the host port of a client because a new port will be
allocated in `resume`.
"""
for client in self._snippet_clients.values():
self._device.log.debug(
'Clearing host port %d of SnippetClient<%s>.',
client.host_port, client.package)
client.clear_host_port() | python | def pause(self):
"""Pauses all the snippet clients under management.
This clears the host port of a client because a new port will be
allocated in `resume`.
"""
for client in self._snippet_clients.values():
self._device.log.debug(
'Clearing host port %d of SnippetClient<%s>.',
client.host_port, client.package)
client.clear_host_port() | [
"def",
"pause",
"(",
"self",
")",
":",
"for",
"client",
"in",
"self",
".",
"_snippet_clients",
".",
"values",
"(",
")",
":",
"self",
".",
"_device",
".",
"log",
".",
"debug",
"(",
"'Clearing host port %d of SnippetClient<%s>.'",
",",
"client",
".",
"host_por... | Pauses all the snippet clients under management.
This clears the host port of a client because a new port will be
allocated in `resume`. | [
"Pauses",
"all",
"the",
"snippet",
"clients",
"under",
"management",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/services/snippet_management_service.py#L127-L137 | train | 205,448 |
google/mobly | mobly/controllers/android_device_lib/services/snippet_management_service.py | SnippetManagementService.resume | def resume(self):
"""Resumes all paused snippet clients."""
for client in self._snippet_clients.values():
# Resume is only applicable if a client is alive and does not have
# a host port.
if client.is_alive and client.host_port is None:
self._device.log.debug('Resuming SnippetClient<%s>.',
client.package)
client.restore_app_connection()
else:
self._device.log.debug('Not resuming SnippetClient<%s>.',
client.package) | python | def resume(self):
"""Resumes all paused snippet clients."""
for client in self._snippet_clients.values():
# Resume is only applicable if a client is alive and does not have
# a host port.
if client.is_alive and client.host_port is None:
self._device.log.debug('Resuming SnippetClient<%s>.',
client.package)
client.restore_app_connection()
else:
self._device.log.debug('Not resuming SnippetClient<%s>.',
client.package) | [
"def",
"resume",
"(",
"self",
")",
":",
"for",
"client",
"in",
"self",
".",
"_snippet_clients",
".",
"values",
"(",
")",
":",
"# Resume is only applicable if a client is alive and does not have",
"# a host port.",
"if",
"client",
".",
"is_alive",
"and",
"client",
".... | Resumes all paused snippet clients. | [
"Resumes",
"all",
"paused",
"snippet",
"clients",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/services/snippet_management_service.py#L139-L150 | train | 205,449 |
google/mobly | mobly/controllers/android_device_lib/event_dispatcher.py | EventDispatcher.poll_events | def poll_events(self):
"""Continuously polls all types of events from sl4a.
Events are sorted by name and store in separate queues.
If there are registered handlers, the handlers will be called with
corresponding event immediately upon event discovery, and the event
won't be stored. If exceptions occur, stop the dispatcher and return
"""
while self.started:
event_obj = None
event_name = None
try:
event_obj = self._sl4a.eventWait(50000)
except:
if self.started:
print("Exception happened during polling.")
print(traceback.format_exc())
raise
if not event_obj:
continue
elif 'name' not in event_obj:
print("Received Malformed event {}".format(event_obj))
continue
else:
event_name = event_obj['name']
# if handler registered, process event
if event_name in self.handlers:
self.handle_subscribed_event(event_obj, event_name)
if event_name == "EventDispatcherShutdown":
self._sl4a.closeSl4aSession()
break
else:
self.lock.acquire()
if event_name in self.event_dict: # otherwise, cache event
self.event_dict[event_name].put(event_obj)
else:
q = queue.Queue()
q.put(event_obj)
self.event_dict[event_name] = q
self.lock.release() | python | def poll_events(self):
"""Continuously polls all types of events from sl4a.
Events are sorted by name and store in separate queues.
If there are registered handlers, the handlers will be called with
corresponding event immediately upon event discovery, and the event
won't be stored. If exceptions occur, stop the dispatcher and return
"""
while self.started:
event_obj = None
event_name = None
try:
event_obj = self._sl4a.eventWait(50000)
except:
if self.started:
print("Exception happened during polling.")
print(traceback.format_exc())
raise
if not event_obj:
continue
elif 'name' not in event_obj:
print("Received Malformed event {}".format(event_obj))
continue
else:
event_name = event_obj['name']
# if handler registered, process event
if event_name in self.handlers:
self.handle_subscribed_event(event_obj, event_name)
if event_name == "EventDispatcherShutdown":
self._sl4a.closeSl4aSession()
break
else:
self.lock.acquire()
if event_name in self.event_dict: # otherwise, cache event
self.event_dict[event_name].put(event_obj)
else:
q = queue.Queue()
q.put(event_obj)
self.event_dict[event_name] = q
self.lock.release() | [
"def",
"poll_events",
"(",
"self",
")",
":",
"while",
"self",
".",
"started",
":",
"event_obj",
"=",
"None",
"event_name",
"=",
"None",
"try",
":",
"event_obj",
"=",
"self",
".",
"_sl4a",
".",
"eventWait",
"(",
"50000",
")",
"except",
":",
"if",
"self"... | Continuously polls all types of events from sl4a.
Events are sorted by name and store in separate queues.
If there are registered handlers, the handlers will be called with
corresponding event immediately upon event discovery, and the event
won't be stored. If exceptions occur, stop the dispatcher and return | [
"Continuously",
"polls",
"all",
"types",
"of",
"events",
"from",
"sl4a",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/event_dispatcher.py#L52-L91 | train | 205,450 |
google/mobly | mobly/controllers/android_device_lib/event_dispatcher.py | EventDispatcher.register_handler | def register_handler(self, handler, event_name, args):
"""Registers an event handler.
One type of event can only have one event handler associated with it.
Args:
handler: The event handler function to be registered.
event_name: Name of the event the handler is for.
args: User arguments to be passed to the handler when it's called.
Raises:
IllegalStateError: Raised if attempts to register a handler after
the dispatcher starts running.
DuplicateError: Raised if attempts to register more than one
handler for one type of event.
"""
if self.started:
raise IllegalStateError(("Can't register service after polling is"
" started"))
self.lock.acquire()
try:
if event_name in self.handlers:
raise DuplicateError('A handler for {} already exists'.format(
event_name))
self.handlers[event_name] = (handler, args)
finally:
self.lock.release() | python | def register_handler(self, handler, event_name, args):
"""Registers an event handler.
One type of event can only have one event handler associated with it.
Args:
handler: The event handler function to be registered.
event_name: Name of the event the handler is for.
args: User arguments to be passed to the handler when it's called.
Raises:
IllegalStateError: Raised if attempts to register a handler after
the dispatcher starts running.
DuplicateError: Raised if attempts to register more than one
handler for one type of event.
"""
if self.started:
raise IllegalStateError(("Can't register service after polling is"
" started"))
self.lock.acquire()
try:
if event_name in self.handlers:
raise DuplicateError('A handler for {} already exists'.format(
event_name))
self.handlers[event_name] = (handler, args)
finally:
self.lock.release() | [
"def",
"register_handler",
"(",
"self",
",",
"handler",
",",
"event_name",
",",
"args",
")",
":",
"if",
"self",
".",
"started",
":",
"raise",
"IllegalStateError",
"(",
"(",
"\"Can't register service after polling is\"",
"\" started\"",
")",
")",
"self",
".",
"lo... | Registers an event handler.
One type of event can only have one event handler associated with it.
Args:
handler: The event handler function to be registered.
event_name: Name of the event the handler is for.
args: User arguments to be passed to the handler when it's called.
Raises:
IllegalStateError: Raised if attempts to register a handler after
the dispatcher starts running.
DuplicateError: Raised if attempts to register more than one
handler for one type of event. | [
"Registers",
"an",
"event",
"handler",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/event_dispatcher.py#L93-L119 | train | 205,451 |
google/mobly | mobly/controllers/android_device_lib/event_dispatcher.py | EventDispatcher.start | def start(self):
"""Starts the event dispatcher.
Initiates executor and start polling events.
Raises:
IllegalStateError: Can't start a dispatcher again when it's already
running.
"""
if not self.started:
self.started = True
self.executor = ThreadPoolExecutor(max_workers=32)
self.poller = self.executor.submit(self.poll_events)
else:
raise IllegalStateError("Dispatcher is already started.") | python | def start(self):
"""Starts the event dispatcher.
Initiates executor and start polling events.
Raises:
IllegalStateError: Can't start a dispatcher again when it's already
running.
"""
if not self.started:
self.started = True
self.executor = ThreadPoolExecutor(max_workers=32)
self.poller = self.executor.submit(self.poll_events)
else:
raise IllegalStateError("Dispatcher is already started.") | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"started",
":",
"self",
".",
"started",
"=",
"True",
"self",
".",
"executor",
"=",
"ThreadPoolExecutor",
"(",
"max_workers",
"=",
"32",
")",
"self",
".",
"poller",
"=",
"self",
".",
"ex... | Starts the event dispatcher.
Initiates executor and start polling events.
Raises:
IllegalStateError: Can't start a dispatcher again when it's already
running. | [
"Starts",
"the",
"event",
"dispatcher",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/event_dispatcher.py#L121-L135 | train | 205,452 |
google/mobly | mobly/controllers/android_device_lib/event_dispatcher.py | EventDispatcher.clean_up | def clean_up(self):
"""Clean up and release resources after the event dispatcher polling
loop has been broken.
The following things happen:
1. Clear all events and flags.
2. Close the sl4a client the event_dispatcher object holds.
3. Shut down executor without waiting.
"""
if not self.started:
return
self.started = False
self.clear_all_events()
# At this point, the sl4a apk is destroyed and nothing is listening on
# the socket. Avoid sending any sl4a commands; just clean up the socket
# and return.
self._sl4a.disconnect()
self.poller.set_result("Done")
# The polling thread is guaranteed to finish after a max of 60 seconds,
# so we don't wait here.
self.executor.shutdown(wait=False) | python | def clean_up(self):
"""Clean up and release resources after the event dispatcher polling
loop has been broken.
The following things happen:
1. Clear all events and flags.
2. Close the sl4a client the event_dispatcher object holds.
3. Shut down executor without waiting.
"""
if not self.started:
return
self.started = False
self.clear_all_events()
# At this point, the sl4a apk is destroyed and nothing is listening on
# the socket. Avoid sending any sl4a commands; just clean up the socket
# and return.
self._sl4a.disconnect()
self.poller.set_result("Done")
# The polling thread is guaranteed to finish after a max of 60 seconds,
# so we don't wait here.
self.executor.shutdown(wait=False) | [
"def",
"clean_up",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"started",
":",
"return",
"self",
".",
"started",
"=",
"False",
"self",
".",
"clear_all_events",
"(",
")",
"# At this point, the sl4a apk is destroyed and nothing is listening on",
"# the socket. Avoi... | Clean up and release resources after the event dispatcher polling
loop has been broken.
The following things happen:
1. Clear all events and flags.
2. Close the sl4a client the event_dispatcher object holds.
3. Shut down executor without waiting. | [
"Clean",
"up",
"and",
"release",
"resources",
"after",
"the",
"event",
"dispatcher",
"polling",
"loop",
"has",
"been",
"broken",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/event_dispatcher.py#L137-L157 | train | 205,453 |
google/mobly | mobly/controllers/android_device_lib/event_dispatcher.py | EventDispatcher.pop_event | def pop_event(self, event_name, timeout=DEFAULT_TIMEOUT):
"""Pop an event from its queue.
Return and remove the oldest entry of an event.
Block until an event of specified name is available or
times out if timeout is set.
Args:
event_name: Name of the event to be popped.
timeout: Number of seconds to wait when event is not present.
Never times out if None.
Returns:
The oldest entry of the specified event. None if timed out.
Raises:
IllegalStateError: Raised if pop is called before the dispatcher
starts polling.
"""
if not self.started:
raise IllegalStateError(
"Dispatcher needs to be started before popping.")
e_queue = self.get_event_q(event_name)
if not e_queue:
raise TypeError("Failed to get an event queue for {}".format(
event_name))
try:
# Block for timeout
if timeout:
return e_queue.get(True, timeout)
# Non-blocking poll for event
elif timeout == 0:
return e_queue.get(False)
else:
# Block forever on event wait
return e_queue.get(True)
except queue.Empty:
raise queue.Empty('Timeout after {}s waiting for event: {}'.format(
timeout, event_name)) | python | def pop_event(self, event_name, timeout=DEFAULT_TIMEOUT):
"""Pop an event from its queue.
Return and remove the oldest entry of an event.
Block until an event of specified name is available or
times out if timeout is set.
Args:
event_name: Name of the event to be popped.
timeout: Number of seconds to wait when event is not present.
Never times out if None.
Returns:
The oldest entry of the specified event. None if timed out.
Raises:
IllegalStateError: Raised if pop is called before the dispatcher
starts polling.
"""
if not self.started:
raise IllegalStateError(
"Dispatcher needs to be started before popping.")
e_queue = self.get_event_q(event_name)
if not e_queue:
raise TypeError("Failed to get an event queue for {}".format(
event_name))
try:
# Block for timeout
if timeout:
return e_queue.get(True, timeout)
# Non-blocking poll for event
elif timeout == 0:
return e_queue.get(False)
else:
# Block forever on event wait
return e_queue.get(True)
except queue.Empty:
raise queue.Empty('Timeout after {}s waiting for event: {}'.format(
timeout, event_name)) | [
"def",
"pop_event",
"(",
"self",
",",
"event_name",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
")",
":",
"if",
"not",
"self",
".",
"started",
":",
"raise",
"IllegalStateError",
"(",
"\"Dispatcher needs to be started before popping.\"",
")",
"e_queue",
"=",
"self",
".... | Pop an event from its queue.
Return and remove the oldest entry of an event.
Block until an event of specified name is available or
times out if timeout is set.
Args:
event_name: Name of the event to be popped.
timeout: Number of seconds to wait when event is not present.
Never times out if None.
Returns:
The oldest entry of the specified event. None if timed out.
Raises:
IllegalStateError: Raised if pop is called before the dispatcher
starts polling. | [
"Pop",
"an",
"event",
"from",
"its",
"queue",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/event_dispatcher.py#L159-L200 | train | 205,454 |
google/mobly | mobly/controllers/android_device_lib/event_dispatcher.py | EventDispatcher.wait_for_event | def wait_for_event(self,
event_name,
predicate,
timeout=DEFAULT_TIMEOUT,
*args,
**kwargs):
"""Wait for an event that satisfies a predicate to appear.
Continuously pop events of a particular name and check against the
predicate until an event that satisfies the predicate is popped or
timed out. Note this will remove all the events of the same name that
do not satisfy the predicate in the process.
Args:
event_name: Name of the event to be popped.
predicate: A function that takes an event and returns True if the
predicate is satisfied, False otherwise.
timeout: Number of seconds to wait.
*args: Optional positional args passed to predicate().
**kwargs: Optional keyword args passed to predicate().
Returns:
The event that satisfies the predicate.
Raises:
queue.Empty: Raised if no event that satisfies the predicate was
found before time out.
"""
deadline = time.time() + timeout
while True:
event = None
try:
event = self.pop_event(event_name, 1)
except queue.Empty:
pass
if event and predicate(event, *args, **kwargs):
return event
if time.time() > deadline:
raise queue.Empty(
'Timeout after {}s waiting for event: {}'.format(
timeout, event_name)) | python | def wait_for_event(self,
event_name,
predicate,
timeout=DEFAULT_TIMEOUT,
*args,
**kwargs):
"""Wait for an event that satisfies a predicate to appear.
Continuously pop events of a particular name and check against the
predicate until an event that satisfies the predicate is popped or
timed out. Note this will remove all the events of the same name that
do not satisfy the predicate in the process.
Args:
event_name: Name of the event to be popped.
predicate: A function that takes an event and returns True if the
predicate is satisfied, False otherwise.
timeout: Number of seconds to wait.
*args: Optional positional args passed to predicate().
**kwargs: Optional keyword args passed to predicate().
Returns:
The event that satisfies the predicate.
Raises:
queue.Empty: Raised if no event that satisfies the predicate was
found before time out.
"""
deadline = time.time() + timeout
while True:
event = None
try:
event = self.pop_event(event_name, 1)
except queue.Empty:
pass
if event and predicate(event, *args, **kwargs):
return event
if time.time() > deadline:
raise queue.Empty(
'Timeout after {}s waiting for event: {}'.format(
timeout, event_name)) | [
"def",
"wait_for_event",
"(",
"self",
",",
"event_name",
",",
"predicate",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"deadline",
"=",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"while",
"True",
":"... | Wait for an event that satisfies a predicate to appear.
Continuously pop events of a particular name and check against the
predicate until an event that satisfies the predicate is popped or
timed out. Note this will remove all the events of the same name that
do not satisfy the predicate in the process.
Args:
event_name: Name of the event to be popped.
predicate: A function that takes an event and returns True if the
predicate is satisfied, False otherwise.
timeout: Number of seconds to wait.
*args: Optional positional args passed to predicate().
**kwargs: Optional keyword args passed to predicate().
Returns:
The event that satisfies the predicate.
Raises:
queue.Empty: Raised if no event that satisfies the predicate was
found before time out. | [
"Wait",
"for",
"an",
"event",
"that",
"satisfies",
"a",
"predicate",
"to",
"appear",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/event_dispatcher.py#L202-L245 | train | 205,455 |
google/mobly | mobly/controllers/android_device_lib/event_dispatcher.py | EventDispatcher.pop_events | def pop_events(self, regex_pattern, timeout):
"""Pop events whose names match a regex pattern.
If such event(s) exist, pop one event from each event queue that
satisfies the condition. Otherwise, wait for an event that satisfies
the condition to occur, with timeout.
Results are sorted by timestamp in ascending order.
Args:
regex_pattern: The regular expression pattern that an event name
should match in order to be popped.
timeout: Number of seconds to wait for events in case no event
matching the condition exits when the function is called.
Returns:
Events whose names match a regex pattern.
Empty if none exist and the wait timed out.
Raises:
IllegalStateError: Raised if pop is called before the dispatcher
starts polling.
queue.Empty: Raised if no event was found before time out.
"""
if not self.started:
raise IllegalStateError(
"Dispatcher needs to be started before popping.")
deadline = time.time() + timeout
while True:
#TODO: fix the sleep loop
results = self._match_and_pop(regex_pattern)
if len(results) != 0 or time.time() > deadline:
break
time.sleep(1)
if len(results) == 0:
raise queue.Empty('Timeout after {}s waiting for event: {}'.format(
timeout, regex_pattern))
return sorted(results, key=lambda event: event['time']) | python | def pop_events(self, regex_pattern, timeout):
"""Pop events whose names match a regex pattern.
If such event(s) exist, pop one event from each event queue that
satisfies the condition. Otherwise, wait for an event that satisfies
the condition to occur, with timeout.
Results are sorted by timestamp in ascending order.
Args:
regex_pattern: The regular expression pattern that an event name
should match in order to be popped.
timeout: Number of seconds to wait for events in case no event
matching the condition exits when the function is called.
Returns:
Events whose names match a regex pattern.
Empty if none exist and the wait timed out.
Raises:
IllegalStateError: Raised if pop is called before the dispatcher
starts polling.
queue.Empty: Raised if no event was found before time out.
"""
if not self.started:
raise IllegalStateError(
"Dispatcher needs to be started before popping.")
deadline = time.time() + timeout
while True:
#TODO: fix the sleep loop
results = self._match_and_pop(regex_pattern)
if len(results) != 0 or time.time() > deadline:
break
time.sleep(1)
if len(results) == 0:
raise queue.Empty('Timeout after {}s waiting for event: {}'.format(
timeout, regex_pattern))
return sorted(results, key=lambda event: event['time']) | [
"def",
"pop_events",
"(",
"self",
",",
"regex_pattern",
",",
"timeout",
")",
":",
"if",
"not",
"self",
".",
"started",
":",
"raise",
"IllegalStateError",
"(",
"\"Dispatcher needs to be started before popping.\"",
")",
"deadline",
"=",
"time",
".",
"time",
"(",
"... | Pop events whose names match a regex pattern.
If such event(s) exist, pop one event from each event queue that
satisfies the condition. Otherwise, wait for an event that satisfies
the condition to occur, with timeout.
Results are sorted by timestamp in ascending order.
Args:
regex_pattern: The regular expression pattern that an event name
should match in order to be popped.
timeout: Number of seconds to wait for events in case no event
matching the condition exits when the function is called.
Returns:
Events whose names match a regex pattern.
Empty if none exist and the wait timed out.
Raises:
IllegalStateError: Raised if pop is called before the dispatcher
starts polling.
queue.Empty: Raised if no event was found before time out. | [
"Pop",
"events",
"whose",
"names",
"match",
"a",
"regex",
"pattern",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/event_dispatcher.py#L247-L285 | train | 205,456 |
google/mobly | mobly/controllers/android_device_lib/event_dispatcher.py | EventDispatcher.get_event_q | def get_event_q(self, event_name):
"""Obtain the queue storing events of the specified name.
If no event of this name has been polled, wait for one to.
Returns:
A queue storing all the events of the specified name.
None if timed out.
Raises:
queue.Empty: Raised if the queue does not exist and timeout has
passed.
"""
self.lock.acquire()
if not event_name in self.event_dict or self.event_dict[
event_name] is None:
self.event_dict[event_name] = queue.Queue()
self.lock.release()
event_queue = self.event_dict[event_name]
return event_queue | python | def get_event_q(self, event_name):
"""Obtain the queue storing events of the specified name.
If no event of this name has been polled, wait for one to.
Returns:
A queue storing all the events of the specified name.
None if timed out.
Raises:
queue.Empty: Raised if the queue does not exist and timeout has
passed.
"""
self.lock.acquire()
if not event_name in self.event_dict or self.event_dict[
event_name] is None:
self.event_dict[event_name] = queue.Queue()
self.lock.release()
event_queue = self.event_dict[event_name]
return event_queue | [
"def",
"get_event_q",
"(",
"self",
",",
"event_name",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"if",
"not",
"event_name",
"in",
"self",
".",
"event_dict",
"or",
"self",
".",
"event_dict",
"[",
"event_name",
"]",
"is",
"None",
":",
"self... | Obtain the queue storing events of the specified name.
If no event of this name has been polled, wait for one to.
Returns:
A queue storing all the events of the specified name.
None if timed out.
Raises:
queue.Empty: Raised if the queue does not exist and timeout has
passed. | [
"Obtain",
"the",
"queue",
"storing",
"events",
"of",
"the",
"specified",
"name",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/event_dispatcher.py#L304-L324 | train | 205,457 |
google/mobly | mobly/controllers/android_device_lib/event_dispatcher.py | EventDispatcher.handle_subscribed_event | def handle_subscribed_event(self, event_obj, event_name):
"""Execute the registered handler of an event.
Retrieve the handler and its arguments, and execute the handler in a
new thread.
Args:
event_obj: Json object of the event.
event_name: Name of the event to call handler for.
"""
handler, args = self.handlers[event_name]
self.executor.submit(handler, event_obj, *args) | python | def handle_subscribed_event(self, event_obj, event_name):
"""Execute the registered handler of an event.
Retrieve the handler and its arguments, and execute the handler in a
new thread.
Args:
event_obj: Json object of the event.
event_name: Name of the event to call handler for.
"""
handler, args = self.handlers[event_name]
self.executor.submit(handler, event_obj, *args) | [
"def",
"handle_subscribed_event",
"(",
"self",
",",
"event_obj",
",",
"event_name",
")",
":",
"handler",
",",
"args",
"=",
"self",
".",
"handlers",
"[",
"event_name",
"]",
"self",
".",
"executor",
".",
"submit",
"(",
"handler",
",",
"event_obj",
",",
"*",
... | Execute the registered handler of an event.
Retrieve the handler and its arguments, and execute the handler in a
new thread.
Args:
event_obj: Json object of the event.
event_name: Name of the event to call handler for. | [
"Execute",
"the",
"registered",
"handler",
"of",
"an",
"event",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/event_dispatcher.py#L326-L337 | train | 205,458 |
google/mobly | mobly/controllers/android_device_lib/event_dispatcher.py | EventDispatcher._handle | def _handle(self, event_handler, event_name, user_args, event_timeout,
cond, cond_timeout):
"""Pop an event of specified type and calls its handler on it. If
condition is not None, block until condition is met or timeout.
"""
if cond:
cond.wait(cond_timeout)
event = self.pop_event(event_name, event_timeout)
return event_handler(event, *user_args) | python | def _handle(self, event_handler, event_name, user_args, event_timeout,
cond, cond_timeout):
"""Pop an event of specified type and calls its handler on it. If
condition is not None, block until condition is met or timeout.
"""
if cond:
cond.wait(cond_timeout)
event = self.pop_event(event_name, event_timeout)
return event_handler(event, *user_args) | [
"def",
"_handle",
"(",
"self",
",",
"event_handler",
",",
"event_name",
",",
"user_args",
",",
"event_timeout",
",",
"cond",
",",
"cond_timeout",
")",
":",
"if",
"cond",
":",
"cond",
".",
"wait",
"(",
"cond_timeout",
")",
"event",
"=",
"self",
".",
"pop_... | Pop an event of specified type and calls its handler on it. If
condition is not None, block until condition is met or timeout. | [
"Pop",
"an",
"event",
"of",
"specified",
"type",
"and",
"calls",
"its",
"handler",
"on",
"it",
".",
"If",
"condition",
"is",
"not",
"None",
"block",
"until",
"condition",
"is",
"met",
"or",
"timeout",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/event_dispatcher.py#L339-L347 | train | 205,459 |
google/mobly | mobly/controllers/android_device_lib/event_dispatcher.py | EventDispatcher.handle_event | def handle_event(self,
event_handler,
event_name,
user_args,
event_timeout=None,
cond=None,
cond_timeout=None):
"""Handle events that don't have registered handlers
In a new thread, poll one event of specified type from its queue and
execute its handler. If no such event exists, the thread waits until
one appears.
Args:
event_handler: Handler for the event, which should take at least
one argument - the event json object.
event_name: Name of the event to be handled.
user_args: User arguments for the handler; to be passed in after
the event json.
event_timeout: Number of seconds to wait for the event to come.
cond: A condition to wait on before executing the handler. Should
be a threading.Event object.
cond_timeout: Number of seconds to wait before the condition times
out. Never times out if None.
Returns:
A concurrent.Future object associated with the handler.
If blocking call worker.result() is triggered, the handler
needs to return something to unblock.
"""
worker = self.executor.submit(self._handle, event_handler, event_name,
user_args, event_timeout, cond,
cond_timeout)
return worker | python | def handle_event(self,
event_handler,
event_name,
user_args,
event_timeout=None,
cond=None,
cond_timeout=None):
"""Handle events that don't have registered handlers
In a new thread, poll one event of specified type from its queue and
execute its handler. If no such event exists, the thread waits until
one appears.
Args:
event_handler: Handler for the event, which should take at least
one argument - the event json object.
event_name: Name of the event to be handled.
user_args: User arguments for the handler; to be passed in after
the event json.
event_timeout: Number of seconds to wait for the event to come.
cond: A condition to wait on before executing the handler. Should
be a threading.Event object.
cond_timeout: Number of seconds to wait before the condition times
out. Never times out if None.
Returns:
A concurrent.Future object associated with the handler.
If blocking call worker.result() is triggered, the handler
needs to return something to unblock.
"""
worker = self.executor.submit(self._handle, event_handler, event_name,
user_args, event_timeout, cond,
cond_timeout)
return worker | [
"def",
"handle_event",
"(",
"self",
",",
"event_handler",
",",
"event_name",
",",
"user_args",
",",
"event_timeout",
"=",
"None",
",",
"cond",
"=",
"None",
",",
"cond_timeout",
"=",
"None",
")",
":",
"worker",
"=",
"self",
".",
"executor",
".",
"submit",
... | Handle events that don't have registered handlers
In a new thread, poll one event of specified type from its queue and
execute its handler. If no such event exists, the thread waits until
one appears.
Args:
event_handler: Handler for the event, which should take at least
one argument - the event json object.
event_name: Name of the event to be handled.
user_args: User arguments for the handler; to be passed in after
the event json.
event_timeout: Number of seconds to wait for the event to come.
cond: A condition to wait on before executing the handler. Should
be a threading.Event object.
cond_timeout: Number of seconds to wait before the condition times
out. Never times out if None.
Returns:
A concurrent.Future object associated with the handler.
If blocking call worker.result() is triggered, the handler
needs to return something to unblock. | [
"Handle",
"events",
"that",
"don",
"t",
"have",
"registered",
"handlers"
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/event_dispatcher.py#L349-L382 | train | 205,460 |
google/mobly | mobly/controllers/android_device_lib/event_dispatcher.py | EventDispatcher.pop_all | def pop_all(self, event_name):
"""Return and remove all stored events of a specified name.
Pops all events from their queue. May miss the latest ones.
If no event is available, return immediately.
Args:
event_name: Name of the events to be popped.
Returns:
List of the desired events.
Raises:
IllegalStateError: Raised if pop is called before the dispatcher
starts polling.
"""
if not self.started:
raise IllegalStateError(("Dispatcher needs to be started before "
"popping."))
results = []
try:
self.lock.acquire()
while True:
e = self.event_dict[event_name].get(block=False)
results.append(e)
except (queue.Empty, KeyError):
return results
finally:
self.lock.release() | python | def pop_all(self, event_name):
"""Return and remove all stored events of a specified name.
Pops all events from their queue. May miss the latest ones.
If no event is available, return immediately.
Args:
event_name: Name of the events to be popped.
Returns:
List of the desired events.
Raises:
IllegalStateError: Raised if pop is called before the dispatcher
starts polling.
"""
if not self.started:
raise IllegalStateError(("Dispatcher needs to be started before "
"popping."))
results = []
try:
self.lock.acquire()
while True:
e = self.event_dict[event_name].get(block=False)
results.append(e)
except (queue.Empty, KeyError):
return results
finally:
self.lock.release() | [
"def",
"pop_all",
"(",
"self",
",",
"event_name",
")",
":",
"if",
"not",
"self",
".",
"started",
":",
"raise",
"IllegalStateError",
"(",
"(",
"\"Dispatcher needs to be started before \"",
"\"popping.\"",
")",
")",
"results",
"=",
"[",
"]",
"try",
":",
"self",
... | Return and remove all stored events of a specified name.
Pops all events from their queue. May miss the latest ones.
If no event is available, return immediately.
Args:
event_name: Name of the events to be popped.
Returns:
List of the desired events.
Raises:
IllegalStateError: Raised if pop is called before the dispatcher
starts polling. | [
"Return",
"and",
"remove",
"all",
"stored",
"events",
"of",
"a",
"specified",
"name",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/event_dispatcher.py#L384-L412 | train | 205,461 |
google/mobly | mobly/controllers/android_device_lib/event_dispatcher.py | EventDispatcher.clear_events | def clear_events(self, event_name):
"""Clear all events of a particular name.
Args:
event_name: Name of the events to be popped.
"""
self.lock.acquire()
try:
q = self.get_event_q(event_name)
q.queue.clear()
except queue.Empty:
return
finally:
self.lock.release() | python | def clear_events(self, event_name):
"""Clear all events of a particular name.
Args:
event_name: Name of the events to be popped.
"""
self.lock.acquire()
try:
q = self.get_event_q(event_name)
q.queue.clear()
except queue.Empty:
return
finally:
self.lock.release() | [
"def",
"clear_events",
"(",
"self",
",",
"event_name",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"q",
"=",
"self",
".",
"get_event_q",
"(",
"event_name",
")",
"q",
".",
"queue",
".",
"clear",
"(",
")",
"except",
"queue",
... | Clear all events of a particular name.
Args:
event_name: Name of the events to be popped. | [
"Clear",
"all",
"events",
"of",
"a",
"particular",
"name",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/event_dispatcher.py#L414-L427 | train | 205,462 |
google/mobly | mobly/controllers/android_device_lib/event_dispatcher.py | EventDispatcher.clear_all_events | def clear_all_events(self):
"""Clear all event queues and their cached events."""
self.lock.acquire()
self.event_dict.clear()
self.lock.release() | python | def clear_all_events(self):
"""Clear all event queues and their cached events."""
self.lock.acquire()
self.event_dict.clear()
self.lock.release() | [
"def",
"clear_all_events",
"(",
"self",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"self",
".",
"event_dict",
".",
"clear",
"(",
")",
"self",
".",
"lock",
".",
"release",
"(",
")"
] | Clear all event queues and their cached events. | [
"Clear",
"all",
"event",
"queues",
"and",
"their",
"cached",
"events",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/event_dispatcher.py#L429-L433 | train | 205,463 |
google/mobly | mobly/controllers/android_device_lib/snippet_event.py | from_dict | def from_dict(event_dict):
"""Create a SnippetEvent object from a dictionary.
Args:
event_dict: a dictionary representing an event.
Returns:
A SnippetEvent object.
"""
return SnippetEvent(
callback_id=event_dict['callbackId'],
name=event_dict['name'],
creation_time=event_dict['time'],
data=event_dict['data']) | python | def from_dict(event_dict):
"""Create a SnippetEvent object from a dictionary.
Args:
event_dict: a dictionary representing an event.
Returns:
A SnippetEvent object.
"""
return SnippetEvent(
callback_id=event_dict['callbackId'],
name=event_dict['name'],
creation_time=event_dict['time'],
data=event_dict['data']) | [
"def",
"from_dict",
"(",
"event_dict",
")",
":",
"return",
"SnippetEvent",
"(",
"callback_id",
"=",
"event_dict",
"[",
"'callbackId'",
"]",
",",
"name",
"=",
"event_dict",
"[",
"'name'",
"]",
",",
"creation_time",
"=",
"event_dict",
"[",
"'time'",
"]",
",",
... | Create a SnippetEvent object from a dictionary.
Args:
event_dict: a dictionary representing an event.
Returns:
A SnippetEvent object. | [
"Create",
"a",
"SnippetEvent",
"object",
"from",
"a",
"dictionary",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/snippet_event.py#L16-L29 | train | 205,464 |
google/mobly | mobly/utils.py | create_dir | def create_dir(path):
"""Creates a directory if it does not exist already.
Args:
path: The path of the directory to create.
"""
full_path = abs_path(path)
if not os.path.exists(full_path):
try:
os.makedirs(full_path)
except OSError as e:
# ignore the error for dir already exist.
if e.errno != os.errno.EEXIST:
raise | python | def create_dir(path):
"""Creates a directory if it does not exist already.
Args:
path: The path of the directory to create.
"""
full_path = abs_path(path)
if not os.path.exists(full_path):
try:
os.makedirs(full_path)
except OSError as e:
# ignore the error for dir already exist.
if e.errno != os.errno.EEXIST:
raise | [
"def",
"create_dir",
"(",
"path",
")",
":",
"full_path",
"=",
"abs_path",
"(",
"path",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"full_path",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"full_path",
")",
"except",
"OSError",
"as"... | Creates a directory if it does not exist already.
Args:
path: The path of the directory to create. | [
"Creates",
"a",
"directory",
"if",
"it",
"does",
"not",
"exist",
"already",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/utils.py#L89-L102 | train | 205,465 |
google/mobly | mobly/utils.py | create_alias | def create_alias(target_path, alias_path):
"""Creates an alias at 'alias_path' pointing to the file 'target_path'.
On Unix, this is implemented via symlink. On Windows, this is done by
creating a Windows shortcut file.
Args:
target_path: Destination path that the alias should point to.
alias_path: Path at which to create the new alias.
"""
if platform.system() == 'Windows' and not alias_path.endswith('.lnk'):
alias_path += '.lnk'
if os.path.lexists(alias_path):
os.remove(alias_path)
if platform.system() == 'Windows':
from win32com import client
shell = client.Dispatch('WScript.Shell')
shortcut = shell.CreateShortCut(alias_path)
shortcut.Targetpath = target_path
shortcut.save()
else:
os.symlink(target_path, alias_path) | python | def create_alias(target_path, alias_path):
"""Creates an alias at 'alias_path' pointing to the file 'target_path'.
On Unix, this is implemented via symlink. On Windows, this is done by
creating a Windows shortcut file.
Args:
target_path: Destination path that the alias should point to.
alias_path: Path at which to create the new alias.
"""
if platform.system() == 'Windows' and not alias_path.endswith('.lnk'):
alias_path += '.lnk'
if os.path.lexists(alias_path):
os.remove(alias_path)
if platform.system() == 'Windows':
from win32com import client
shell = client.Dispatch('WScript.Shell')
shortcut = shell.CreateShortCut(alias_path)
shortcut.Targetpath = target_path
shortcut.save()
else:
os.symlink(target_path, alias_path) | [
"def",
"create_alias",
"(",
"target_path",
",",
"alias_path",
")",
":",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'Windows'",
"and",
"not",
"alias_path",
".",
"endswith",
"(",
"'.lnk'",
")",
":",
"alias_path",
"+=",
"'.lnk'",
"if",
"os",
".",
"pa... | Creates an alias at 'alias_path' pointing to the file 'target_path'.
On Unix, this is implemented via symlink. On Windows, this is done by
creating a Windows shortcut file.
Args:
target_path: Destination path that the alias should point to.
alias_path: Path at which to create the new alias. | [
"Creates",
"an",
"alias",
"at",
"alias_path",
"pointing",
"to",
"the",
"file",
"target_path",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/utils.py#L105-L126 | train | 205,466 |
google/mobly | mobly/utils.py | epoch_to_human_time | def epoch_to_human_time(epoch_time):
"""Converts an epoch timestamp to human readable time.
This essentially converts an output of get_current_epoch_time to an output
of get_current_human_time
Args:
epoch_time: An integer representing an epoch timestamp in milliseconds.
Returns:
A time string representing the input time.
None if input param is invalid.
"""
if isinstance(epoch_time, int):
try:
d = datetime.datetime.fromtimestamp(epoch_time / 1000)
return d.strftime("%m-%d-%Y %H:%M:%S ")
except ValueError:
return None | python | def epoch_to_human_time(epoch_time):
"""Converts an epoch timestamp to human readable time.
This essentially converts an output of get_current_epoch_time to an output
of get_current_human_time
Args:
epoch_time: An integer representing an epoch timestamp in milliseconds.
Returns:
A time string representing the input time.
None if input param is invalid.
"""
if isinstance(epoch_time, int):
try:
d = datetime.datetime.fromtimestamp(epoch_time / 1000)
return d.strftime("%m-%d-%Y %H:%M:%S ")
except ValueError:
return None | [
"def",
"epoch_to_human_time",
"(",
"epoch_time",
")",
":",
"if",
"isinstance",
"(",
"epoch_time",
",",
"int",
")",
":",
"try",
":",
"d",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"epoch_time",
"/",
"1000",
")",
"return",
"d",
".",
"str... | Converts an epoch timestamp to human readable time.
This essentially converts an output of get_current_epoch_time to an output
of get_current_human_time
Args:
epoch_time: An integer representing an epoch timestamp in milliseconds.
Returns:
A time string representing the input time.
None if input param is invalid. | [
"Converts",
"an",
"epoch",
"timestamp",
"to",
"human",
"readable",
"time",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/utils.py#L147-L165 | train | 205,467 |
google/mobly | mobly/utils.py | find_files | def find_files(paths, file_predicate):
"""Locate files whose names and extensions match the given predicate in
the specified directories.
Args:
paths: A list of directory paths where to find the files.
file_predicate: A function that returns True if the file name and
extension are desired.
Returns:
A list of files that match the predicate.
"""
file_list = []
for path in paths:
p = abs_path(path)
for dirPath, _, fileList in os.walk(p):
for fname in fileList:
name, ext = os.path.splitext(fname)
if file_predicate(name, ext):
file_list.append((dirPath, name, ext))
return file_list | python | def find_files(paths, file_predicate):
"""Locate files whose names and extensions match the given predicate in
the specified directories.
Args:
paths: A list of directory paths where to find the files.
file_predicate: A function that returns True if the file name and
extension are desired.
Returns:
A list of files that match the predicate.
"""
file_list = []
for path in paths:
p = abs_path(path)
for dirPath, _, fileList in os.walk(p):
for fname in fileList:
name, ext = os.path.splitext(fname)
if file_predicate(name, ext):
file_list.append((dirPath, name, ext))
return file_list | [
"def",
"find_files",
"(",
"paths",
",",
"file_predicate",
")",
":",
"file_list",
"=",
"[",
"]",
"for",
"path",
"in",
"paths",
":",
"p",
"=",
"abs_path",
"(",
"path",
")",
"for",
"dirPath",
",",
"_",
",",
"fileList",
"in",
"os",
".",
"walk",
"(",
"p... | Locate files whose names and extensions match the given predicate in
the specified directories.
Args:
paths: A list of directory paths where to find the files.
file_predicate: A function that returns True if the file name and
extension are desired.
Returns:
A list of files that match the predicate. | [
"Locate",
"files",
"whose",
"names",
"and",
"extensions",
"match",
"the",
"given",
"predicate",
"in",
"the",
"specified",
"directories",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/utils.py#L184-L204 | train | 205,468 |
google/mobly | mobly/utils.py | load_file_to_base64_str | def load_file_to_base64_str(f_path):
"""Loads the content of a file into a base64 string.
Args:
f_path: full path to the file including the file name.
Returns:
A base64 string representing the content of the file in utf-8 encoding.
"""
path = abs_path(f_path)
with io.open(path, 'rb') as f:
f_bytes = f.read()
base64_str = base64.b64encode(f_bytes).decode("utf-8")
return base64_str | python | def load_file_to_base64_str(f_path):
"""Loads the content of a file into a base64 string.
Args:
f_path: full path to the file including the file name.
Returns:
A base64 string representing the content of the file in utf-8 encoding.
"""
path = abs_path(f_path)
with io.open(path, 'rb') as f:
f_bytes = f.read()
base64_str = base64.b64encode(f_bytes).decode("utf-8")
return base64_str | [
"def",
"load_file_to_base64_str",
"(",
"f_path",
")",
":",
"path",
"=",
"abs_path",
"(",
"f_path",
")",
"with",
"io",
".",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"f",
":",
"f_bytes",
"=",
"f",
".",
"read",
"(",
")",
"base64_str",
"=",
"base64",... | Loads the content of a file into a base64 string.
Args:
f_path: full path to the file including the file name.
Returns:
A base64 string representing the content of the file in utf-8 encoding. | [
"Loads",
"the",
"content",
"of",
"a",
"file",
"into",
"a",
"base64",
"string",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/utils.py#L207-L220 | train | 205,469 |
google/mobly | mobly/utils.py | find_field | def find_field(item_list, cond, comparator, target_field):
"""Finds the value of a field in a dict object that satisfies certain
conditions.
Args:
item_list: A list of dict objects.
cond: A param that defines the condition.
comparator: A function that checks if an dict satisfies the condition.
target_field: Name of the field whose value to be returned if an item
satisfies the condition.
Returns:
Target value or None if no item satisfies the condition.
"""
for item in item_list:
if comparator(item, cond) and target_field in item:
return item[target_field]
return None | python | def find_field(item_list, cond, comparator, target_field):
"""Finds the value of a field in a dict object that satisfies certain
conditions.
Args:
item_list: A list of dict objects.
cond: A param that defines the condition.
comparator: A function that checks if an dict satisfies the condition.
target_field: Name of the field whose value to be returned if an item
satisfies the condition.
Returns:
Target value or None if no item satisfies the condition.
"""
for item in item_list:
if comparator(item, cond) and target_field in item:
return item[target_field]
return None | [
"def",
"find_field",
"(",
"item_list",
",",
"cond",
",",
"comparator",
",",
"target_field",
")",
":",
"for",
"item",
"in",
"item_list",
":",
"if",
"comparator",
"(",
"item",
",",
"cond",
")",
"and",
"target_field",
"in",
"item",
":",
"return",
"item",
"[... | Finds the value of a field in a dict object that satisfies certain
conditions.
Args:
item_list: A list of dict objects.
cond: A param that defines the condition.
comparator: A function that checks if an dict satisfies the condition.
target_field: Name of the field whose value to be returned if an item
satisfies the condition.
Returns:
Target value or None if no item satisfies the condition. | [
"Finds",
"the",
"value",
"of",
"a",
"field",
"in",
"a",
"dict",
"object",
"that",
"satisfies",
"certain",
"conditions",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/utils.py#L223-L240 | train | 205,470 |
google/mobly | mobly/utils.py | rand_ascii_str | def rand_ascii_str(length):
"""Generates a random string of specified length, composed of ascii letters
and digits.
Args:
length: The number of characters in the string.
Returns:
The random string generated.
"""
letters = [random.choice(ascii_letters_and_digits) for _ in range(length)]
return ''.join(letters) | python | def rand_ascii_str(length):
"""Generates a random string of specified length, composed of ascii letters
and digits.
Args:
length: The number of characters in the string.
Returns:
The random string generated.
"""
letters = [random.choice(ascii_letters_and_digits) for _ in range(length)]
return ''.join(letters) | [
"def",
"rand_ascii_str",
"(",
"length",
")",
":",
"letters",
"=",
"[",
"random",
".",
"choice",
"(",
"ascii_letters_and_digits",
")",
"for",
"_",
"in",
"range",
"(",
"length",
")",
"]",
"return",
"''",
".",
"join",
"(",
"letters",
")"
] | Generates a random string of specified length, composed of ascii letters
and digits.
Args:
length: The number of characters in the string.
Returns:
The random string generated. | [
"Generates",
"a",
"random",
"string",
"of",
"specified",
"length",
"composed",
"of",
"ascii",
"letters",
"and",
"digits",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/utils.py#L243-L254 | train | 205,471 |
google/mobly | mobly/utils.py | concurrent_exec | def concurrent_exec(func, param_list):
"""Executes a function with different parameters pseudo-concurrently.
This is basically a map function. Each element (should be an iterable) in
the param_list is unpacked and passed into the function. Due to Python's
GIL, there's no true concurrency. This is suited for IO-bound tasks.
Args:
func: The function that parforms a task.
param_list: A list of iterables, each being a set of params to be
passed into the function.
Returns:
A list of return values from each function execution. If an execution
caused an exception, the exception object will be the corresponding
result.
"""
with concurrent.futures.ThreadPoolExecutor(max_workers=30) as executor:
# Start the load operations and mark each future with its params
future_to_params = {executor.submit(func, *p): p for p in param_list}
return_vals = []
for future in concurrent.futures.as_completed(future_to_params):
params = future_to_params[future]
try:
return_vals.append(future.result())
except Exception as exc:
logging.exception("{} generated an exception: {}".format(
params, traceback.format_exc()))
return_vals.append(exc)
return return_vals | python | def concurrent_exec(func, param_list):
"""Executes a function with different parameters pseudo-concurrently.
This is basically a map function. Each element (should be an iterable) in
the param_list is unpacked and passed into the function. Due to Python's
GIL, there's no true concurrency. This is suited for IO-bound tasks.
Args:
func: The function that parforms a task.
param_list: A list of iterables, each being a set of params to be
passed into the function.
Returns:
A list of return values from each function execution. If an execution
caused an exception, the exception object will be the corresponding
result.
"""
with concurrent.futures.ThreadPoolExecutor(max_workers=30) as executor:
# Start the load operations and mark each future with its params
future_to_params = {executor.submit(func, *p): p for p in param_list}
return_vals = []
for future in concurrent.futures.as_completed(future_to_params):
params = future_to_params[future]
try:
return_vals.append(future.result())
except Exception as exc:
logging.exception("{} generated an exception: {}".format(
params, traceback.format_exc()))
return_vals.append(exc)
return return_vals | [
"def",
"concurrent_exec",
"(",
"func",
",",
"param_list",
")",
":",
"with",
"concurrent",
".",
"futures",
".",
"ThreadPoolExecutor",
"(",
"max_workers",
"=",
"30",
")",
"as",
"executor",
":",
"# Start the load operations and mark each future with its params",
"future_to... | Executes a function with different parameters pseudo-concurrently.
This is basically a map function. Each element (should be an iterable) in
the param_list is unpacked and passed into the function. Due to Python's
GIL, there's no true concurrency. This is suited for IO-bound tasks.
Args:
func: The function that parforms a task.
param_list: A list of iterables, each being a set of params to be
passed into the function.
Returns:
A list of return values from each function execution. If an execution
caused an exception, the exception object will be the corresponding
result. | [
"Executes",
"a",
"function",
"with",
"different",
"parameters",
"pseudo",
"-",
"concurrently",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/utils.py#L258-L287 | train | 205,472 |
google/mobly | mobly/utils.py | run_command | def run_command(cmd,
stdout=None,
stderr=None,
shell=False,
timeout=None,
cwd=None,
env=None):
"""Runs a command in a subprocess.
This function is very similar to subprocess.check_output. The main
difference is that it returns the return code and std error output as well
as supporting a timeout parameter.
Args:
cmd: string or list of strings, the command to run.
See subprocess.Popen() documentation.
stdout: file handle, the file handle to write std out to. If None is
given, then subprocess.PIPE is used. See subprocess.Popen()
documentation.
stdee: file handle, the file handle to write std err to. If None is
given, then subprocess.PIPE is used. See subprocess.Popen()
documentation.
shell: bool, True to run this command through the system shell,
False to invoke it directly. See subprocess.Popen() docs.
timeout: float, the number of seconds to wait before timing out.
If not specified, no timeout takes effect.
cwd: string, the path to change the child's current directory to before
it is executed. Note that this directory is not considered when
searching the executable, so you can't specify the program's path
relative to cwd.
env: dict, a mapping that defines the environment variables for the
new process. Default behavior is inheriting the current process'
environment.
Returns:
A 3-tuple of the consisting of the return code, the std output, and the
std error.
Raises:
psutil.TimeoutExpired: The command timed out.
"""
# Only import psutil when actually needed.
# psutil may cause import error in certain env. This way the utils module
# doesn't crash upon import.
import psutil
if stdout is None:
stdout = subprocess.PIPE
if stderr is None:
stderr = subprocess.PIPE
process = psutil.Popen(
cmd, stdout=stdout, stderr=stderr, shell=shell, cwd=cwd, env=env)
timer = None
timer_triggered = threading.Event()
if timeout and timeout > 0:
# The wait method on process will hang when used with PIPEs with large
# outputs, so use a timer thread instead.
def timeout_expired():
timer_triggered.set()
process.terminate()
timer = threading.Timer(timeout, timeout_expired)
timer.start()
# If the command takes longer than the timeout, then the timer thread
# will kill the subprocess, which will make it terminate.
(out, err) = process.communicate()
if timer is not None:
timer.cancel()
if timer_triggered.is_set():
raise psutil.TimeoutExpired(timeout, pid=process.pid)
return (process.returncode, out, err) | python | def run_command(cmd,
stdout=None,
stderr=None,
shell=False,
timeout=None,
cwd=None,
env=None):
"""Runs a command in a subprocess.
This function is very similar to subprocess.check_output. The main
difference is that it returns the return code and std error output as well
as supporting a timeout parameter.
Args:
cmd: string or list of strings, the command to run.
See subprocess.Popen() documentation.
stdout: file handle, the file handle to write std out to. If None is
given, then subprocess.PIPE is used. See subprocess.Popen()
documentation.
stdee: file handle, the file handle to write std err to. If None is
given, then subprocess.PIPE is used. See subprocess.Popen()
documentation.
shell: bool, True to run this command through the system shell,
False to invoke it directly. See subprocess.Popen() docs.
timeout: float, the number of seconds to wait before timing out.
If not specified, no timeout takes effect.
cwd: string, the path to change the child's current directory to before
it is executed. Note that this directory is not considered when
searching the executable, so you can't specify the program's path
relative to cwd.
env: dict, a mapping that defines the environment variables for the
new process. Default behavior is inheriting the current process'
environment.
Returns:
A 3-tuple of the consisting of the return code, the std output, and the
std error.
Raises:
psutil.TimeoutExpired: The command timed out.
"""
# Only import psutil when actually needed.
# psutil may cause import error in certain env. This way the utils module
# doesn't crash upon import.
import psutil
if stdout is None:
stdout = subprocess.PIPE
if stderr is None:
stderr = subprocess.PIPE
process = psutil.Popen(
cmd, stdout=stdout, stderr=stderr, shell=shell, cwd=cwd, env=env)
timer = None
timer_triggered = threading.Event()
if timeout and timeout > 0:
# The wait method on process will hang when used with PIPEs with large
# outputs, so use a timer thread instead.
def timeout_expired():
timer_triggered.set()
process.terminate()
timer = threading.Timer(timeout, timeout_expired)
timer.start()
# If the command takes longer than the timeout, then the timer thread
# will kill the subprocess, which will make it terminate.
(out, err) = process.communicate()
if timer is not None:
timer.cancel()
if timer_triggered.is_set():
raise psutil.TimeoutExpired(timeout, pid=process.pid)
return (process.returncode, out, err) | [
"def",
"run_command",
"(",
"cmd",
",",
"stdout",
"=",
"None",
",",
"stderr",
"=",
"None",
",",
"shell",
"=",
"False",
",",
"timeout",
"=",
"None",
",",
"cwd",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"# Only import psutil when actually needed.",
"... | Runs a command in a subprocess.
This function is very similar to subprocess.check_output. The main
difference is that it returns the return code and std error output as well
as supporting a timeout parameter.
Args:
cmd: string or list of strings, the command to run.
See subprocess.Popen() documentation.
stdout: file handle, the file handle to write std out to. If None is
given, then subprocess.PIPE is used. See subprocess.Popen()
documentation.
stdee: file handle, the file handle to write std err to. If None is
given, then subprocess.PIPE is used. See subprocess.Popen()
documentation.
shell: bool, True to run this command through the system shell,
False to invoke it directly. See subprocess.Popen() docs.
timeout: float, the number of seconds to wait before timing out.
If not specified, no timeout takes effect.
cwd: string, the path to change the child's current directory to before
it is executed. Note that this directory is not considered when
searching the executable, so you can't specify the program's path
relative to cwd.
env: dict, a mapping that defines the environment variables for the
new process. Default behavior is inheriting the current process'
environment.
Returns:
A 3-tuple of the consisting of the return code, the std output, and the
std error.
Raises:
psutil.TimeoutExpired: The command timed out. | [
"Runs",
"a",
"command",
"in",
"a",
"subprocess",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/utils.py#L290-L360 | train | 205,473 |
google/mobly | mobly/utils.py | start_standing_subprocess | def start_standing_subprocess(cmd, shell=False, env=None):
"""Starts a long-running subprocess.
This is not a blocking call and the subprocess started by it should be
explicitly terminated with stop_standing_subprocess.
For short-running commands, you should use subprocess.check_call, which
blocks.
Args:
cmd: string, the command to start the subprocess with.
shell: bool, True to run this command through the system shell,
False to invoke it directly. See subprocess.Proc() docs.
env: dict, a custom environment to run the standing subprocess. If not
specified, inherits the current environment. See subprocess.Popen()
docs.
Returns:
The subprocess that was started.
"""
logging.debug('Starting standing subprocess with: %s', cmd)
proc = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=shell,
env=env)
# Leaving stdin open causes problems for input, e.g. breaking the
# code.inspect() shell (http://stackoverflow.com/a/25512460/1612937), so
# explicitly close it assuming it is not needed for standing subprocesses.
proc.stdin.close()
proc.stdin = None
logging.debug('Started standing subprocess %d', proc.pid)
return proc | python | def start_standing_subprocess(cmd, shell=False, env=None):
"""Starts a long-running subprocess.
This is not a blocking call and the subprocess started by it should be
explicitly terminated with stop_standing_subprocess.
For short-running commands, you should use subprocess.check_call, which
blocks.
Args:
cmd: string, the command to start the subprocess with.
shell: bool, True to run this command through the system shell,
False to invoke it directly. See subprocess.Proc() docs.
env: dict, a custom environment to run the standing subprocess. If not
specified, inherits the current environment. See subprocess.Popen()
docs.
Returns:
The subprocess that was started.
"""
logging.debug('Starting standing subprocess with: %s', cmd)
proc = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=shell,
env=env)
# Leaving stdin open causes problems for input, e.g. breaking the
# code.inspect() shell (http://stackoverflow.com/a/25512460/1612937), so
# explicitly close it assuming it is not needed for standing subprocesses.
proc.stdin.close()
proc.stdin = None
logging.debug('Started standing subprocess %d', proc.pid)
return proc | [
"def",
"start_standing_subprocess",
"(",
"cmd",
",",
"shell",
"=",
"False",
",",
"env",
"=",
"None",
")",
":",
"logging",
".",
"debug",
"(",
"'Starting standing subprocess with: %s'",
",",
"cmd",
")",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",... | Starts a long-running subprocess.
This is not a blocking call and the subprocess started by it should be
explicitly terminated with stop_standing_subprocess.
For short-running commands, you should use subprocess.check_call, which
blocks.
Args:
cmd: string, the command to start the subprocess with.
shell: bool, True to run this command through the system shell,
False to invoke it directly. See subprocess.Proc() docs.
env: dict, a custom environment to run the standing subprocess. If not
specified, inherits the current environment. See subprocess.Popen()
docs.
Returns:
The subprocess that was started. | [
"Starts",
"a",
"long",
"-",
"running",
"subprocess",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/utils.py#L363-L397 | train | 205,474 |
google/mobly | mobly/utils.py | stop_standing_subprocess | def stop_standing_subprocess(proc):
"""Stops a subprocess started by start_standing_subprocess.
Before killing the process, we check if the process is running, if it has
terminated, Error is raised.
Catches and ignores the PermissionError which only happens on Macs.
Args:
proc: Subprocess to terminate.
Raises:
Error: if the subprocess could not be stopped.
"""
# Only import psutil when actually needed.
# psutil may cause import error in certain env. This way the utils module
# doesn't crash upon import.
import psutil
pid = proc.pid
logging.debug('Stopping standing subprocess %d', pid)
process = psutil.Process(pid)
failed = []
try:
children = process.children(recursive=True)
except AttributeError:
# Handle versions <3.0.0 of psutil.
children = process.get_children(recursive=True)
for child in children:
try:
child.kill()
child.wait(timeout=10)
except psutil.NoSuchProcess:
# Ignore if the child process has already terminated.
pass
except:
failed.append(child.pid)
logging.exception('Failed to kill standing subprocess %d',
child.pid)
try:
process.kill()
process.wait(timeout=10)
except psutil.NoSuchProcess:
# Ignore if the process has already terminated.
pass
except:
failed.append(pid)
logging.exception('Failed to kill standing subprocess %d', pid)
if failed:
raise Error('Failed to kill standing subprocesses: %s' % failed)
# Call wait and close pipes on the original Python object so we don't get
# runtime warnings.
if proc.stdout:
proc.stdout.close()
if proc.stderr:
proc.stderr.close()
proc.wait()
logging.debug('Stopped standing subprocess %d', pid) | python | def stop_standing_subprocess(proc):
"""Stops a subprocess started by start_standing_subprocess.
Before killing the process, we check if the process is running, if it has
terminated, Error is raised.
Catches and ignores the PermissionError which only happens on Macs.
Args:
proc: Subprocess to terminate.
Raises:
Error: if the subprocess could not be stopped.
"""
# Only import psutil when actually needed.
# psutil may cause import error in certain env. This way the utils module
# doesn't crash upon import.
import psutil
pid = proc.pid
logging.debug('Stopping standing subprocess %d', pid)
process = psutil.Process(pid)
failed = []
try:
children = process.children(recursive=True)
except AttributeError:
# Handle versions <3.0.0 of psutil.
children = process.get_children(recursive=True)
for child in children:
try:
child.kill()
child.wait(timeout=10)
except psutil.NoSuchProcess:
# Ignore if the child process has already terminated.
pass
except:
failed.append(child.pid)
logging.exception('Failed to kill standing subprocess %d',
child.pid)
try:
process.kill()
process.wait(timeout=10)
except psutil.NoSuchProcess:
# Ignore if the process has already terminated.
pass
except:
failed.append(pid)
logging.exception('Failed to kill standing subprocess %d', pid)
if failed:
raise Error('Failed to kill standing subprocesses: %s' % failed)
# Call wait and close pipes on the original Python object so we don't get
# runtime warnings.
if proc.stdout:
proc.stdout.close()
if proc.stderr:
proc.stderr.close()
proc.wait()
logging.debug('Stopped standing subprocess %d', pid) | [
"def",
"stop_standing_subprocess",
"(",
"proc",
")",
":",
"# Only import psutil when actually needed.",
"# psutil may cause import error in certain env. This way the utils module",
"# doesn't crash upon import.",
"import",
"psutil",
"pid",
"=",
"proc",
".",
"pid",
"logging",
".",
... | Stops a subprocess started by start_standing_subprocess.
Before killing the process, we check if the process is running, if it has
terminated, Error is raised.
Catches and ignores the PermissionError which only happens on Macs.
Args:
proc: Subprocess to terminate.
Raises:
Error: if the subprocess could not be stopped. | [
"Stops",
"a",
"subprocess",
"started",
"by",
"start_standing_subprocess",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/utils.py#L400-L456 | train | 205,475 |
google/mobly | mobly/utils.py | get_available_host_port | def get_available_host_port():
"""Gets a host port number available for adb forward.
Returns:
An integer representing a port number on the host available for adb
forward.
Raises:
Error: when no port is found after MAX_PORT_ALLOCATION_RETRY times.
"""
# Only import adb module if needed.
from mobly.controllers.android_device_lib import adb
for _ in range(MAX_PORT_ALLOCATION_RETRY):
port = portpicker.PickUnusedPort()
# Make sure adb is not using this port so we don't accidentally
# interrupt ongoing runs by trying to bind to the port.
if port not in adb.list_occupied_adb_ports():
return port
raise Error('Failed to find available port after {} retries'.format(
MAX_PORT_ALLOCATION_RETRY)) | python | def get_available_host_port():
"""Gets a host port number available for adb forward.
Returns:
An integer representing a port number on the host available for adb
forward.
Raises:
Error: when no port is found after MAX_PORT_ALLOCATION_RETRY times.
"""
# Only import adb module if needed.
from mobly.controllers.android_device_lib import adb
for _ in range(MAX_PORT_ALLOCATION_RETRY):
port = portpicker.PickUnusedPort()
# Make sure adb is not using this port so we don't accidentally
# interrupt ongoing runs by trying to bind to the port.
if port not in adb.list_occupied_adb_ports():
return port
raise Error('Failed to find available port after {} retries'.format(
MAX_PORT_ALLOCATION_RETRY)) | [
"def",
"get_available_host_port",
"(",
")",
":",
"# Only import adb module if needed.",
"from",
"mobly",
".",
"controllers",
".",
"android_device_lib",
"import",
"adb",
"for",
"_",
"in",
"range",
"(",
"MAX_PORT_ALLOCATION_RETRY",
")",
":",
"port",
"=",
"portpicker",
... | Gets a host port number available for adb forward.
Returns:
An integer representing a port number on the host available for adb
forward.
Raises:
Error: when no port is found after MAX_PORT_ALLOCATION_RETRY times. | [
"Gets",
"a",
"host",
"port",
"number",
"available",
"for",
"adb",
"forward",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/utils.py#L488-L507 | train | 205,476 |
google/mobly | mobly/utils.py | grep | def grep(regex, output):
"""Similar to linux's `grep`, this returns the line in an output stream
that matches a given regex pattern.
It does not rely on the `grep` binary and is not sensitive to line endings,
so it can be used cross-platform.
Args:
regex: string, a regex that matches the expected pattern.
output: byte string, the raw output of the adb cmd.
Returns:
A list of strings, all of which are output lines that matches the
regex pattern.
"""
lines = output.decode('utf-8').strip().splitlines()
results = []
for line in lines:
if re.search(regex, line):
results.append(line.strip())
return results | python | def grep(regex, output):
"""Similar to linux's `grep`, this returns the line in an output stream
that matches a given regex pattern.
It does not rely on the `grep` binary and is not sensitive to line endings,
so it can be used cross-platform.
Args:
regex: string, a regex that matches the expected pattern.
output: byte string, the raw output of the adb cmd.
Returns:
A list of strings, all of which are output lines that matches the
regex pattern.
"""
lines = output.decode('utf-8').strip().splitlines()
results = []
for line in lines:
if re.search(regex, line):
results.append(line.strip())
return results | [
"def",
"grep",
"(",
"regex",
",",
"output",
")",
":",
"lines",
"=",
"output",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"strip",
"(",
")",
".",
"splitlines",
"(",
")",
"results",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"if",
"re",
".",
... | Similar to linux's `grep`, this returns the line in an output stream
that matches a given regex pattern.
It does not rely on the `grep` binary and is not sensitive to line endings,
so it can be used cross-platform.
Args:
regex: string, a regex that matches the expected pattern.
output: byte string, the raw output of the adb cmd.
Returns:
A list of strings, all of which are output lines that matches the
regex pattern. | [
"Similar",
"to",
"linux",
"s",
"grep",
"this",
"returns",
"the",
"line",
"in",
"an",
"output",
"stream",
"that",
"matches",
"a",
"given",
"regex",
"pattern",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/utils.py#L510-L530 | train | 205,477 |
google/mobly | mobly/utils.py | cli_cmd_to_string | def cli_cmd_to_string(args):
"""Converts a cmd arg list to string.
Args:
args: list of strings, the arguments of a command.
Returns:
String representation of the command.
"""
if isinstance(args, basestring):
# Return directly if it's already a string.
return args
return ' '.join([pipes.quote(arg) for arg in args]) | python | def cli_cmd_to_string(args):
"""Converts a cmd arg list to string.
Args:
args: list of strings, the arguments of a command.
Returns:
String representation of the command.
"""
if isinstance(args, basestring):
# Return directly if it's already a string.
return args
return ' '.join([pipes.quote(arg) for arg in args]) | [
"def",
"cli_cmd_to_string",
"(",
"args",
")",
":",
"if",
"isinstance",
"(",
"args",
",",
"basestring",
")",
":",
"# Return directly if it's already a string.",
"return",
"args",
"return",
"' '",
".",
"join",
"(",
"[",
"pipes",
".",
"quote",
"(",
"arg",
")",
... | Converts a cmd arg list to string.
Args:
args: list of strings, the arguments of a command.
Returns:
String representation of the command. | [
"Converts",
"a",
"cmd",
"arg",
"list",
"to",
"string",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/utils.py#L533-L545 | train | 205,478 |
google/mobly | mobly/controllers/android_device_lib/fastboot.py | exe_cmd | def exe_cmd(*cmds):
"""Executes commands in a new shell. Directing stderr to PIPE.
This is fastboot's own exe_cmd because of its peculiar way of writing
non-error info to stderr.
Args:
cmds: A sequence of commands and arguments.
Returns:
The output of the command run.
Raises:
Exception: An error occurred during the command execution.
"""
cmd = ' '.join(cmds)
proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
(out, err) = proc.communicate()
if not err:
return out
return err | python | def exe_cmd(*cmds):
"""Executes commands in a new shell. Directing stderr to PIPE.
This is fastboot's own exe_cmd because of its peculiar way of writing
non-error info to stderr.
Args:
cmds: A sequence of commands and arguments.
Returns:
The output of the command run.
Raises:
Exception: An error occurred during the command execution.
"""
cmd = ' '.join(cmds)
proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
(out, err) = proc.communicate()
if not err:
return out
return err | [
"def",
"exe_cmd",
"(",
"*",
"cmds",
")",
":",
"cmd",
"=",
"' '",
".",
"join",
"(",
"cmds",
")",
"proc",
"=",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
",",
"shell",
"=",
"True",
")",
"(",
"out",
",",
"err",
... | Executes commands in a new shell. Directing stderr to PIPE.
This is fastboot's own exe_cmd because of its peculiar way of writing
non-error info to stderr.
Args:
cmds: A sequence of commands and arguments.
Returns:
The output of the command run.
Raises:
Exception: An error occurred during the command execution. | [
"Executes",
"commands",
"in",
"a",
"new",
"shell",
".",
"Directing",
"stderr",
"to",
"PIPE",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/fastboot.py#L18-L38 | train | 205,479 |
google/mobly | mobly/controller_manager.py | verify_controller_module | def verify_controller_module(module):
"""Verifies a module object follows the required interface for
controllers.
The interface is explained in the docstring of
`base_test.BaseTestClass.register_controller`.
Args:
module: An object that is a controller module. This is usually
imported with import statements or loaded by importlib.
Raises:
ControllerError: if the module does not match the Mobly controller
interface, or one of the required members is null.
"""
required_attributes = ('create', 'destroy', 'MOBLY_CONTROLLER_CONFIG_NAME')
for attr in required_attributes:
if not hasattr(module, attr):
raise signals.ControllerError(
'Module %s missing required controller module attribute'
' %s.' % (module.__name__, attr))
if not getattr(module, attr):
raise signals.ControllerError(
'Controller interface %s in %s cannot be null.' %
(attr, module.__name__)) | python | def verify_controller_module(module):
"""Verifies a module object follows the required interface for
controllers.
The interface is explained in the docstring of
`base_test.BaseTestClass.register_controller`.
Args:
module: An object that is a controller module. This is usually
imported with import statements or loaded by importlib.
Raises:
ControllerError: if the module does not match the Mobly controller
interface, or one of the required members is null.
"""
required_attributes = ('create', 'destroy', 'MOBLY_CONTROLLER_CONFIG_NAME')
for attr in required_attributes:
if not hasattr(module, attr):
raise signals.ControllerError(
'Module %s missing required controller module attribute'
' %s.' % (module.__name__, attr))
if not getattr(module, attr):
raise signals.ControllerError(
'Controller interface %s in %s cannot be null.' %
(attr, module.__name__)) | [
"def",
"verify_controller_module",
"(",
"module",
")",
":",
"required_attributes",
"=",
"(",
"'create'",
",",
"'destroy'",
",",
"'MOBLY_CONTROLLER_CONFIG_NAME'",
")",
"for",
"attr",
"in",
"required_attributes",
":",
"if",
"not",
"hasattr",
"(",
"module",
",",
"att... | Verifies a module object follows the required interface for
controllers.
The interface is explained in the docstring of
`base_test.BaseTestClass.register_controller`.
Args:
module: An object that is a controller module. This is usually
imported with import statements or loaded by importlib.
Raises:
ControllerError: if the module does not match the Mobly controller
interface, or one of the required members is null. | [
"Verifies",
"a",
"module",
"object",
"follows",
"the",
"required",
"interface",
"for",
"controllers",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controller_manager.py#L25-L49 | train | 205,480 |
google/mobly | mobly/controller_manager.py | ControllerManager.register_controller | def register_controller(self, module, required=True, min_number=1):
"""Loads a controller module and returns its loaded devices.
This is to be used in a mobly test class.
Args:
module: A module that follows the controller module interface.
required: A bool. If True, failing to register the specified
controller module raises exceptions. If False, the objects
failed to instantiate will be skipped.
min_number: An integer that is the minimum number of controller
objects to be created. Default is one, since you should not
register a controller module without expecting at least one
object.
Returns:
A list of controller objects instantiated from controller_module, or
None if no config existed for this controller and it was not a
required controller.
Raises:
ControllerError:
* The controller module has already been registered.
* The actual number of objects instantiated is less than the
* `min_number`.
* `required` is True and no corresponding config can be found.
* Any other error occurred in the registration process.
"""
verify_controller_module(module)
# Use the module's name as the ref name
module_ref_name = module.__name__.split('.')[-1]
if module_ref_name in self._controller_objects:
raise signals.ControllerError(
'Controller module %s has already been registered. It cannot '
'be registered again.' % module_ref_name)
# Create controller objects.
module_config_name = module.MOBLY_CONTROLLER_CONFIG_NAME
if module_config_name not in self.controller_configs:
if required:
raise signals.ControllerError(
'No corresponding config found for %s' %
module_config_name)
logging.warning(
'No corresponding config found for optional controller %s',
module_config_name)
return None
try:
# Make a deep copy of the config to pass to the controller module,
# in case the controller module modifies the config internally.
original_config = self.controller_configs[module_config_name]
controller_config = copy.deepcopy(original_config)
objects = module.create(controller_config)
except:
logging.exception(
'Failed to initialize objects for controller %s, abort!',
module_config_name)
raise
if not isinstance(objects, list):
raise signals.ControllerError(
'Controller module %s did not return a list of objects, abort.'
% module_ref_name)
# Check we got enough controller objects to continue.
actual_number = len(objects)
if actual_number < min_number:
module.destroy(objects)
raise signals.ControllerError(
'Expected to get at least %d controller objects, got %d.' %
(min_number, actual_number))
# Save a shallow copy of the list for internal usage, so tests can't
# affect internal registry by manipulating the object list.
self._controller_objects[module_ref_name] = copy.copy(objects)
logging.debug('Found %d objects for controller %s', len(objects),
module_config_name)
self._controller_modules[module_ref_name] = module
return objects | python | def register_controller(self, module, required=True, min_number=1):
"""Loads a controller module and returns its loaded devices.
This is to be used in a mobly test class.
Args:
module: A module that follows the controller module interface.
required: A bool. If True, failing to register the specified
controller module raises exceptions. If False, the objects
failed to instantiate will be skipped.
min_number: An integer that is the minimum number of controller
objects to be created. Default is one, since you should not
register a controller module without expecting at least one
object.
Returns:
A list of controller objects instantiated from controller_module, or
None if no config existed for this controller and it was not a
required controller.
Raises:
ControllerError:
* The controller module has already been registered.
* The actual number of objects instantiated is less than the
* `min_number`.
* `required` is True and no corresponding config can be found.
* Any other error occurred in the registration process.
"""
verify_controller_module(module)
# Use the module's name as the ref name
module_ref_name = module.__name__.split('.')[-1]
if module_ref_name in self._controller_objects:
raise signals.ControllerError(
'Controller module %s has already been registered. It cannot '
'be registered again.' % module_ref_name)
# Create controller objects.
module_config_name = module.MOBLY_CONTROLLER_CONFIG_NAME
if module_config_name not in self.controller_configs:
if required:
raise signals.ControllerError(
'No corresponding config found for %s' %
module_config_name)
logging.warning(
'No corresponding config found for optional controller %s',
module_config_name)
return None
try:
# Make a deep copy of the config to pass to the controller module,
# in case the controller module modifies the config internally.
original_config = self.controller_configs[module_config_name]
controller_config = copy.deepcopy(original_config)
objects = module.create(controller_config)
except:
logging.exception(
'Failed to initialize objects for controller %s, abort!',
module_config_name)
raise
if not isinstance(objects, list):
raise signals.ControllerError(
'Controller module %s did not return a list of objects, abort.'
% module_ref_name)
# Check we got enough controller objects to continue.
actual_number = len(objects)
if actual_number < min_number:
module.destroy(objects)
raise signals.ControllerError(
'Expected to get at least %d controller objects, got %d.' %
(min_number, actual_number))
# Save a shallow copy of the list for internal usage, so tests can't
# affect internal registry by manipulating the object list.
self._controller_objects[module_ref_name] = copy.copy(objects)
logging.debug('Found %d objects for controller %s', len(objects),
module_config_name)
self._controller_modules[module_ref_name] = module
return objects | [
"def",
"register_controller",
"(",
"self",
",",
"module",
",",
"required",
"=",
"True",
",",
"min_number",
"=",
"1",
")",
":",
"verify_controller_module",
"(",
"module",
")",
"# Use the module's name as the ref name",
"module_ref_name",
"=",
"module",
".",
"__name__... | Loads a controller module and returns its loaded devices.
This is to be used in a mobly test class.
Args:
module: A module that follows the controller module interface.
required: A bool. If True, failing to register the specified
controller module raises exceptions. If False, the objects
failed to instantiate will be skipped.
min_number: An integer that is the minimum number of controller
objects to be created. Default is one, since you should not
register a controller module without expecting at least one
object.
Returns:
A list of controller objects instantiated from controller_module, or
None if no config existed for this controller and it was not a
required controller.
Raises:
ControllerError:
* The controller module has already been registered.
* The actual number of objects instantiated is less than the
* `min_number`.
* `required` is True and no corresponding config can be found.
* Any other error occurred in the registration process. | [
"Loads",
"a",
"controller",
"module",
"and",
"returns",
"its",
"loaded",
"devices",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controller_manager.py#L71-L145 | train | 205,481 |
google/mobly | mobly/controller_manager.py | ControllerManager.unregister_controllers | def unregister_controllers(self):
"""Destroy controller objects and clear internal registry.
This will be called after each test class.
"""
# TODO(xpconanfan): actually record these errors instead of just
# logging them.
for name, module in self._controller_modules.items():
logging.debug('Destroying %s.', name)
with expects.expect_no_raises(
'Exception occurred destroying %s.' % name):
module.destroy(self._controller_objects[name])
self._controller_objects = collections.OrderedDict()
self._controller_modules = {} | python | def unregister_controllers(self):
"""Destroy controller objects and clear internal registry.
This will be called after each test class.
"""
# TODO(xpconanfan): actually record these errors instead of just
# logging them.
for name, module in self._controller_modules.items():
logging.debug('Destroying %s.', name)
with expects.expect_no_raises(
'Exception occurred destroying %s.' % name):
module.destroy(self._controller_objects[name])
self._controller_objects = collections.OrderedDict()
self._controller_modules = {} | [
"def",
"unregister_controllers",
"(",
"self",
")",
":",
"# TODO(xpconanfan): actually record these errors instead of just",
"# logging them.",
"for",
"name",
",",
"module",
"in",
"self",
".",
"_controller_modules",
".",
"items",
"(",
")",
":",
"logging",
".",
"debug",
... | Destroy controller objects and clear internal registry.
This will be called after each test class. | [
"Destroy",
"controller",
"objects",
"and",
"clear",
"internal",
"registry",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controller_manager.py#L147-L160 | train | 205,482 |
google/mobly | mobly/controller_manager.py | ControllerManager._create_controller_info_record | def _create_controller_info_record(self, controller_module_name):
"""Creates controller info record for a particular controller type.
Info is retrieved from all the controller objects spawned from the
specified module, using the controller module's `get_info` function.
Args:
controller_module_name: string, the name of the controller module
to retrieve info from.
Returns:
A records.ControllerInfoRecord object.
"""
module = self._controller_modules[controller_module_name]
controller_info = None
try:
controller_info = module.get_info(
copy.copy(self._controller_objects[controller_module_name]))
except AttributeError:
logging.warning('No optional debug info found for controller '
'%s. To provide it, implement `get_info`.',
controller_module_name)
try:
yaml.dump(controller_info)
except TypeError:
logging.warning('The info of controller %s in class "%s" is not '
'YAML serializable! Coercing it to string.',
controller_module_name, self._class_name)
controller_info = str(controller_info)
return records.ControllerInfoRecord(
self._class_name, module.MOBLY_CONTROLLER_CONFIG_NAME,
controller_info) | python | def _create_controller_info_record(self, controller_module_name):
"""Creates controller info record for a particular controller type.
Info is retrieved from all the controller objects spawned from the
specified module, using the controller module's `get_info` function.
Args:
controller_module_name: string, the name of the controller module
to retrieve info from.
Returns:
A records.ControllerInfoRecord object.
"""
module = self._controller_modules[controller_module_name]
controller_info = None
try:
controller_info = module.get_info(
copy.copy(self._controller_objects[controller_module_name]))
except AttributeError:
logging.warning('No optional debug info found for controller '
'%s. To provide it, implement `get_info`.',
controller_module_name)
try:
yaml.dump(controller_info)
except TypeError:
logging.warning('The info of controller %s in class "%s" is not '
'YAML serializable! Coercing it to string.',
controller_module_name, self._class_name)
controller_info = str(controller_info)
return records.ControllerInfoRecord(
self._class_name, module.MOBLY_CONTROLLER_CONFIG_NAME,
controller_info) | [
"def",
"_create_controller_info_record",
"(",
"self",
",",
"controller_module_name",
")",
":",
"module",
"=",
"self",
".",
"_controller_modules",
"[",
"controller_module_name",
"]",
"controller_info",
"=",
"None",
"try",
":",
"controller_info",
"=",
"module",
".",
"... | Creates controller info record for a particular controller type.
Info is retrieved from all the controller objects spawned from the
specified module, using the controller module's `get_info` function.
Args:
controller_module_name: string, the name of the controller module
to retrieve info from.
Returns:
A records.ControllerInfoRecord object. | [
"Creates",
"controller",
"info",
"record",
"for",
"a",
"particular",
"controller",
"type",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controller_manager.py#L162-L193 | train | 205,483 |
google/mobly | mobly/controller_manager.py | ControllerManager.get_controller_info_records | def get_controller_info_records(self):
"""Get the info records for all the controller objects in the manager.
New info records for each controller object are created for every call
so the latest info is included.
Returns:
List of records.ControllerInfoRecord objects. Each opject conatins
the info of a type of controller
"""
info_records = []
for controller_module_name in self._controller_objects.keys():
with expects.expect_no_raises(
'Failed to collect controller info from %s' %
controller_module_name):
record = self._create_controller_info_record(
controller_module_name)
if record:
info_records.append(record)
return info_records | python | def get_controller_info_records(self):
"""Get the info records for all the controller objects in the manager.
New info records for each controller object are created for every call
so the latest info is included.
Returns:
List of records.ControllerInfoRecord objects. Each opject conatins
the info of a type of controller
"""
info_records = []
for controller_module_name in self._controller_objects.keys():
with expects.expect_no_raises(
'Failed to collect controller info from %s' %
controller_module_name):
record = self._create_controller_info_record(
controller_module_name)
if record:
info_records.append(record)
return info_records | [
"def",
"get_controller_info_records",
"(",
"self",
")",
":",
"info_records",
"=",
"[",
"]",
"for",
"controller_module_name",
"in",
"self",
".",
"_controller_objects",
".",
"keys",
"(",
")",
":",
"with",
"expects",
".",
"expect_no_raises",
"(",
"'Failed to collect ... | Get the info records for all the controller objects in the manager.
New info records for each controller object are created for every call
so the latest info is included.
Returns:
List of records.ControllerInfoRecord objects. Each opject conatins
the info of a type of controller | [
"Get",
"the",
"info",
"records",
"for",
"all",
"the",
"controller",
"objects",
"in",
"the",
"manager",
"."
] | 38ba2cf7d29a20e6a2fca1718eecb337df38db26 | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controller_manager.py#L195-L214 | train | 205,484 |
mozilla/treeherder | treeherder/services/elasticsearch/utils.py | dict_to_op | def dict_to_op(d, index_name, doc_type, op_type='index'):
"""
Create a bulk-indexing operation from the given dictionary.
"""
if d is None:
return d
op_types = ('create', 'delete', 'index', 'update')
if op_type not in op_types:
msg = 'Unknown operation type "{}", must be one of: {}'
raise Exception(msg.format(op_type, ', '.join(op_types)))
if 'id' not in d:
raise Exception('"id" key not found')
operation = {
'_op_type': op_type,
'_index': index_name,
'_type': doc_type,
'_id': d.pop('id'),
}
operation.update(d)
return operation | python | def dict_to_op(d, index_name, doc_type, op_type='index'):
"""
Create a bulk-indexing operation from the given dictionary.
"""
if d is None:
return d
op_types = ('create', 'delete', 'index', 'update')
if op_type not in op_types:
msg = 'Unknown operation type "{}", must be one of: {}'
raise Exception(msg.format(op_type, ', '.join(op_types)))
if 'id' not in d:
raise Exception('"id" key not found')
operation = {
'_op_type': op_type,
'_index': index_name,
'_type': doc_type,
'_id': d.pop('id'),
}
operation.update(d)
return operation | [
"def",
"dict_to_op",
"(",
"d",
",",
"index_name",
",",
"doc_type",
",",
"op_type",
"=",
"'index'",
")",
":",
"if",
"d",
"is",
"None",
":",
"return",
"d",
"op_types",
"=",
"(",
"'create'",
",",
"'delete'",
",",
"'index'",
",",
"'update'",
")",
"if",
"... | Create a bulk-indexing operation from the given dictionary. | [
"Create",
"a",
"bulk",
"-",
"indexing",
"operation",
"from",
"the",
"given",
"dictionary",
"."
] | cc47bdec872e5c668d0f01df89517390a164cda3 | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/services/elasticsearch/utils.py#L2-L25 | train | 205,485 |
mozilla/treeherder | treeherder/services/elasticsearch/utils.py | to_dict | def to_dict(obj):
"""
Create a filtered dict from the given object.
Note: This function is currently specific to the FailureLine model.
"""
if not isinstance(obj.test, str):
# TODO: can we handle this in the DB?
# Reftests used to use tuple indicies, which we can't support.
# This is fixed upstream, but we also need to handle it here to allow
# for older branches.
return
keys = [
'id',
'job_guid',
'test',
'subtest',
'status',
'expected',
'message',
'best_classification',
'best_is_verified',
]
all_fields = obj.to_dict()
return {k: v for k, v in all_fields.items() if k in keys} | python | def to_dict(obj):
"""
Create a filtered dict from the given object.
Note: This function is currently specific to the FailureLine model.
"""
if not isinstance(obj.test, str):
# TODO: can we handle this in the DB?
# Reftests used to use tuple indicies, which we can't support.
# This is fixed upstream, but we also need to handle it here to allow
# for older branches.
return
keys = [
'id',
'job_guid',
'test',
'subtest',
'status',
'expected',
'message',
'best_classification',
'best_is_verified',
]
all_fields = obj.to_dict()
return {k: v for k, v in all_fields.items() if k in keys} | [
"def",
"to_dict",
"(",
"obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
".",
"test",
",",
"str",
")",
":",
"# TODO: can we handle this in the DB?",
"# Reftests used to use tuple indicies, which we can't support.",
"# This is fixed upstream, but we also need to handle it ... | Create a filtered dict from the given object.
Note: This function is currently specific to the FailureLine model. | [
"Create",
"a",
"filtered",
"dict",
"from",
"the",
"given",
"object",
"."
] | cc47bdec872e5c668d0f01df89517390a164cda3 | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/services/elasticsearch/utils.py#L28-L54 | train | 205,486 |
mozilla/treeherder | treeherder/log_parser/parsers.py | StepParser.start_step | def start_step(self, lineno, name="Unnamed step", timestamp=None):
"""Create a new step and update the state to reflect we're now in the middle of a step."""
self.state = self.STATES['step_in_progress']
self.stepnum += 1
self.steps.append({
"name": name,
"started": timestamp,
"started_linenumber": lineno,
"errors": [],
}) | python | def start_step(self, lineno, name="Unnamed step", timestamp=None):
"""Create a new step and update the state to reflect we're now in the middle of a step."""
self.state = self.STATES['step_in_progress']
self.stepnum += 1
self.steps.append({
"name": name,
"started": timestamp,
"started_linenumber": lineno,
"errors": [],
}) | [
"def",
"start_step",
"(",
"self",
",",
"lineno",
",",
"name",
"=",
"\"Unnamed step\"",
",",
"timestamp",
"=",
"None",
")",
":",
"self",
".",
"state",
"=",
"self",
".",
"STATES",
"[",
"'step_in_progress'",
"]",
"self",
".",
"stepnum",
"+=",
"1",
"self",
... | Create a new step and update the state to reflect we're now in the middle of a step. | [
"Create",
"a",
"new",
"step",
"and",
"update",
"the",
"state",
"to",
"reflect",
"we",
"re",
"now",
"in",
"the",
"middle",
"of",
"a",
"step",
"."
] | cc47bdec872e5c668d0f01df89517390a164cda3 | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/log_parser/parsers.py#L202-L211 | train | 205,487 |
mozilla/treeherder | treeherder/log_parser/parsers.py | StepParser.end_step | def end_step(self, lineno, timestamp=None, result_code=None):
"""Fill in the current step's summary and update the state to show the current step has ended."""
self.state = self.STATES['step_finished']
step_errors = self.sub_parser.get_artifact()
step_error_count = len(step_errors)
if step_error_count > settings.PARSER_MAX_STEP_ERROR_LINES:
step_errors = step_errors[:settings.PARSER_MAX_STEP_ERROR_LINES]
self.artifact["errors_truncated"] = True
self.current_step.update({
"finished": timestamp,
"finished_linenumber": lineno,
# Whilst the result code is present on both the start and end buildbot-style step
# markers, for Taskcluster logs the start marker line lies about the result, since
# the log output is unbuffered, so Taskcluster does not know the real result at
# that point. As such, we only set the result when ending a step.
"result": self.RESULT_DICT.get(result_code, "unknown"),
"errors": step_errors
})
# reset the sub_parser for the next step
self.sub_parser.clear() | python | def end_step(self, lineno, timestamp=None, result_code=None):
"""Fill in the current step's summary and update the state to show the current step has ended."""
self.state = self.STATES['step_finished']
step_errors = self.sub_parser.get_artifact()
step_error_count = len(step_errors)
if step_error_count > settings.PARSER_MAX_STEP_ERROR_LINES:
step_errors = step_errors[:settings.PARSER_MAX_STEP_ERROR_LINES]
self.artifact["errors_truncated"] = True
self.current_step.update({
"finished": timestamp,
"finished_linenumber": lineno,
# Whilst the result code is present on both the start and end buildbot-style step
# markers, for Taskcluster logs the start marker line lies about the result, since
# the log output is unbuffered, so Taskcluster does not know the real result at
# that point. As such, we only set the result when ending a step.
"result": self.RESULT_DICT.get(result_code, "unknown"),
"errors": step_errors
})
# reset the sub_parser for the next step
self.sub_parser.clear() | [
"def",
"end_step",
"(",
"self",
",",
"lineno",
",",
"timestamp",
"=",
"None",
",",
"result_code",
"=",
"None",
")",
":",
"self",
".",
"state",
"=",
"self",
".",
"STATES",
"[",
"'step_finished'",
"]",
"step_errors",
"=",
"self",
".",
"sub_parser",
".",
... | Fill in the current step's summary and update the state to show the current step has ended. | [
"Fill",
"in",
"the",
"current",
"step",
"s",
"summary",
"and",
"update",
"the",
"state",
"to",
"show",
"the",
"current",
"step",
"has",
"ended",
"."
] | cc47bdec872e5c668d0f01df89517390a164cda3 | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/log_parser/parsers.py#L213-L232 | train | 205,488 |
mozilla/treeherder | treeherder/log_parser/parsers.py | TinderboxPrintParser.parse_line | def parse_line(self, line, lineno):
"""Parse a single line of the log"""
match = self.RE_TINDERBOXPRINT.match(line) if line else None
if match:
line = match.group('line')
for regexp_item in self.TINDERBOX_REGEXP_TUPLE:
match = regexp_item['re'].match(line)
if match:
artifact = match.groupdict()
# handle duplicate fields
for to_field, from_field in regexp_item['duplicates_fields'].items():
# if to_field not present or None copy form from_field
if to_field not in artifact or artifact[to_field] is None:
artifact[to_field] = artifact[from_field]
artifact.update(regexp_item['base_dict'])
self.artifact.append(artifact)
return
# default case: consider it html content
# try to detect title/value splitting on <br/>
artifact = {"content_type": "raw_html", }
if "<br/>" in line:
title, value = line.split("<br/>", 1)
artifact["title"] = title
artifact["value"] = value
# or similar long lines if they contain a url
elif "href" in line and "title" in line:
def parse_url_line(line_data):
class TpLineParser(HTMLParser):
def handle_starttag(self, tag, attrs):
d = dict(attrs)
artifact["url"] = d['href']
artifact["title"] = d['title']
def handle_data(self, data):
artifact["value"] = data
p = TpLineParser()
p.feed(line_data)
p.close()
# strip ^M returns on windows lines otherwise
# handle_data will yield no data 'value'
parse_url_line(line.replace('\r', ''))
else:
artifact["value"] = line
self.artifact.append(artifact) | python | def parse_line(self, line, lineno):
"""Parse a single line of the log"""
match = self.RE_TINDERBOXPRINT.match(line) if line else None
if match:
line = match.group('line')
for regexp_item in self.TINDERBOX_REGEXP_TUPLE:
match = regexp_item['re'].match(line)
if match:
artifact = match.groupdict()
# handle duplicate fields
for to_field, from_field in regexp_item['duplicates_fields'].items():
# if to_field not present or None copy form from_field
if to_field not in artifact or artifact[to_field] is None:
artifact[to_field] = artifact[from_field]
artifact.update(regexp_item['base_dict'])
self.artifact.append(artifact)
return
# default case: consider it html content
# try to detect title/value splitting on <br/>
artifact = {"content_type": "raw_html", }
if "<br/>" in line:
title, value = line.split("<br/>", 1)
artifact["title"] = title
artifact["value"] = value
# or similar long lines if they contain a url
elif "href" in line and "title" in line:
def parse_url_line(line_data):
class TpLineParser(HTMLParser):
def handle_starttag(self, tag, attrs):
d = dict(attrs)
artifact["url"] = d['href']
artifact["title"] = d['title']
def handle_data(self, data):
artifact["value"] = data
p = TpLineParser()
p.feed(line_data)
p.close()
# strip ^M returns on windows lines otherwise
# handle_data will yield no data 'value'
parse_url_line(line.replace('\r', ''))
else:
artifact["value"] = line
self.artifact.append(artifact) | [
"def",
"parse_line",
"(",
"self",
",",
"line",
",",
"lineno",
")",
":",
"match",
"=",
"self",
".",
"RE_TINDERBOXPRINT",
".",
"match",
"(",
"line",
")",
"if",
"line",
"else",
"None",
"if",
"match",
":",
"line",
"=",
"match",
".",
"group",
"(",
"'line'... | Parse a single line of the log | [
"Parse",
"a",
"single",
"line",
"of",
"the",
"log"
] | cc47bdec872e5c668d0f01df89517390a164cda3 | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/log_parser/parsers.py#L300-L348 | train | 205,489 |
mozilla/treeherder | treeherder/log_parser/parsers.py | ErrorParser.parse_line | def parse_line(self, line, lineno):
"""Check a single line for an error. Keeps track of the linenumber"""
# TaskCluster logs are a bit wonky.
#
# TaskCluster logs begin with output coming from TaskCluster itself,
# before it has transitioned control of the task to the configured
# process. These "internal" logs look like the following:
#
# [taskcluster 2016-09-09 17:41:43.544Z] Worker Group: us-west-2b
#
# If an error occurs during this "setup" phase, TaskCluster may emit
# lines beginning with ``[taskcluster:error]``.
#
# Once control has transitioned from TaskCluster to the configured
# task process, lines can be whatever the configured process emits.
# The popular ``run-task`` wrapper prefixes output to emulate
# TaskCluster's "internal" logs. e.g.
#
# [vcs 2016-09-09T17:45:02.842230Z] adding changesets
#
# This prefixing can confuse error parsing. So, we strip it.
#
# Because regular expression matching and string manipulation can be
# expensive when performed on every line, we only strip the TaskCluster
# log prefix if we know we're in a TaskCluster log.
# First line of TaskCluster logs almost certainly has this.
if line.startswith('[taskcluster '):
self.is_taskcluster = True
# For performance reasons, only do this if we have identified as
# a TC task.
if self.is_taskcluster:
line = re.sub(self.RE_TASKCLUSTER_NORMAL_PREFIX, "", line)
if self.is_error_line(line):
self.add(line, lineno) | python | def parse_line(self, line, lineno):
"""Check a single line for an error. Keeps track of the linenumber"""
# TaskCluster logs are a bit wonky.
#
# TaskCluster logs begin with output coming from TaskCluster itself,
# before it has transitioned control of the task to the configured
# process. These "internal" logs look like the following:
#
# [taskcluster 2016-09-09 17:41:43.544Z] Worker Group: us-west-2b
#
# If an error occurs during this "setup" phase, TaskCluster may emit
# lines beginning with ``[taskcluster:error]``.
#
# Once control has transitioned from TaskCluster to the configured
# task process, lines can be whatever the configured process emits.
# The popular ``run-task`` wrapper prefixes output to emulate
# TaskCluster's "internal" logs. e.g.
#
# [vcs 2016-09-09T17:45:02.842230Z] adding changesets
#
# This prefixing can confuse error parsing. So, we strip it.
#
# Because regular expression matching and string manipulation can be
# expensive when performed on every line, we only strip the TaskCluster
# log prefix if we know we're in a TaskCluster log.
# First line of TaskCluster logs almost certainly has this.
if line.startswith('[taskcluster '):
self.is_taskcluster = True
# For performance reasons, only do this if we have identified as
# a TC task.
if self.is_taskcluster:
line = re.sub(self.RE_TASKCLUSTER_NORMAL_PREFIX, "", line)
if self.is_error_line(line):
self.add(line, lineno) | [
"def",
"parse_line",
"(",
"self",
",",
"line",
",",
"lineno",
")",
":",
"# TaskCluster logs are a bit wonky.",
"#",
"# TaskCluster logs begin with output coming from TaskCluster itself,",
"# before it has transitioned control of the task to the configured",
"# process. These \"internal\"... | Check a single line for an error. Keeps track of the linenumber | [
"Check",
"a",
"single",
"line",
"for",
"an",
"error",
".",
"Keeps",
"track",
"of",
"the",
"linenumber"
] | cc47bdec872e5c668d0f01df89517390a164cda3 | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/log_parser/parsers.py#L436-L472 | train | 205,490 |
mozilla/treeherder | treeherder/webapp/api/job_log_url.py | JobLogUrlViewSet.retrieve | def retrieve(self, request, project, pk=None):
"""
Returns a job_log_url object given its ID
"""
log = JobLog.objects.get(id=pk)
return Response(self._log_as_dict(log)) | python | def retrieve(self, request, project, pk=None):
"""
Returns a job_log_url object given its ID
"""
log = JobLog.objects.get(id=pk)
return Response(self._log_as_dict(log)) | [
"def",
"retrieve",
"(",
"self",
",",
"request",
",",
"project",
",",
"pk",
"=",
"None",
")",
":",
"log",
"=",
"JobLog",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"pk",
")",
"return",
"Response",
"(",
"self",
".",
"_log_as_dict",
"(",
"log",
")",
... | Returns a job_log_url object given its ID | [
"Returns",
"a",
"job_log_url",
"object",
"given",
"its",
"ID"
] | cc47bdec872e5c668d0f01df89517390a164cda3 | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/webapp/api/job_log_url.py#L23-L28 | train | 205,491 |
mozilla/treeherder | treeherder/perfalert/perfalert/__init__.py | linear_weights | def linear_weights(i, n):
"""A window function that falls off arithmetically.
This is used to calculate a weighted moving average (WMA) that gives higher
weight to changes near the point being analyzed, and smooth out changes at
the opposite edge of the moving window. See bug 879903 for details.
"""
if i >= n:
return 0.0
return float(n - i) / float(n) | python | def linear_weights(i, n):
"""A window function that falls off arithmetically.
This is used to calculate a weighted moving average (WMA) that gives higher
weight to changes near the point being analyzed, and smooth out changes at
the opposite edge of the moving window. See bug 879903 for details.
"""
if i >= n:
return 0.0
return float(n - i) / float(n) | [
"def",
"linear_weights",
"(",
"i",
",",
"n",
")",
":",
"if",
"i",
">=",
"n",
":",
"return",
"0.0",
"return",
"float",
"(",
"n",
"-",
"i",
")",
"/",
"float",
"(",
"n",
")"
] | A window function that falls off arithmetically.
This is used to calculate a weighted moving average (WMA) that gives higher
weight to changes near the point being analyzed, and smooth out changes at
the opposite edge of the moving window. See bug 879903 for details. | [
"A",
"window",
"function",
"that",
"falls",
"off",
"arithmetically",
"."
] | cc47bdec872e5c668d0f01df89517390a164cda3 | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/perfalert/perfalert/__init__.py#L44-L53 | train | 205,492 |
mozilla/treeherder | treeherder/perfalert/perfalert/__init__.py | calc_t | def calc_t(w1, w2, weight_fn=None):
"""Perform a Students t-test on the two sets of revision data.
See the analyze() function for a description of the `weight_fn` argument.
"""
if not w1 or not w2:
return 0
s1 = analyze(w1, weight_fn)
s2 = analyze(w2, weight_fn)
delta_s = s2['avg'] - s1['avg']
if delta_s == 0:
return 0
if s1['variance'] == 0 and s2['variance'] == 0:
return float('inf')
return delta_s / (((s1['variance'] / s1['n']) + (s2['variance'] / s2['n'])) ** 0.5) | python | def calc_t(w1, w2, weight_fn=None):
"""Perform a Students t-test on the two sets of revision data.
See the analyze() function for a description of the `weight_fn` argument.
"""
if not w1 or not w2:
return 0
s1 = analyze(w1, weight_fn)
s2 = analyze(w2, weight_fn)
delta_s = s2['avg'] - s1['avg']
if delta_s == 0:
return 0
if s1['variance'] == 0 and s2['variance'] == 0:
return float('inf')
return delta_s / (((s1['variance'] / s1['n']) + (s2['variance'] / s2['n'])) ** 0.5) | [
"def",
"calc_t",
"(",
"w1",
",",
"w2",
",",
"weight_fn",
"=",
"None",
")",
":",
"if",
"not",
"w1",
"or",
"not",
"w2",
":",
"return",
"0",
"s1",
"=",
"analyze",
"(",
"w1",
",",
"weight_fn",
")",
"s2",
"=",
"analyze",
"(",
"w2",
",",
"weight_fn",
... | Perform a Students t-test on the two sets of revision data.
See the analyze() function for a description of the `weight_fn` argument. | [
"Perform",
"a",
"Students",
"t",
"-",
"test",
"on",
"the",
"two",
"sets",
"of",
"revision",
"data",
"."
] | cc47bdec872e5c668d0f01df89517390a164cda3 | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/perfalert/perfalert/__init__.py#L56-L73 | train | 205,493 |
mozilla/treeherder | treeherder/etl/jobs.py | _remove_existing_jobs | def _remove_existing_jobs(data):
"""
Remove jobs from data where we already have them in the same state.
1. split the incoming jobs into pending, running and complete.
2. fetch the ``job_guids`` from the db that are in the same state as they
are in ``data``.
3. build a new list of jobs in ``new_data`` that are not already in
the db and pass that back. It could end up empty at that point.
"""
new_data = []
guids = [datum['job']['job_guid'] for datum in data]
state_map = {
guid: state for (guid, state) in Job.objects.filter(
guid__in=guids).values_list('guid', 'state')
}
for datum in data:
job = datum['job']
if not state_map.get(job['job_guid']):
new_data.append(datum)
else:
# should not transition from running to pending,
# or completed to any other state
current_state = state_map[job['job_guid']]
if current_state == 'completed' or (
job['state'] == 'pending' and
current_state == 'running'):
continue
new_data.append(datum)
return new_data | python | def _remove_existing_jobs(data):
"""
Remove jobs from data where we already have them in the same state.
1. split the incoming jobs into pending, running and complete.
2. fetch the ``job_guids`` from the db that are in the same state as they
are in ``data``.
3. build a new list of jobs in ``new_data`` that are not already in
the db and pass that back. It could end up empty at that point.
"""
new_data = []
guids = [datum['job']['job_guid'] for datum in data]
state_map = {
guid: state for (guid, state) in Job.objects.filter(
guid__in=guids).values_list('guid', 'state')
}
for datum in data:
job = datum['job']
if not state_map.get(job['job_guid']):
new_data.append(datum)
else:
# should not transition from running to pending,
# or completed to any other state
current_state = state_map[job['job_guid']]
if current_state == 'completed' or (
job['state'] == 'pending' and
current_state == 'running'):
continue
new_data.append(datum)
return new_data | [
"def",
"_remove_existing_jobs",
"(",
"data",
")",
":",
"new_data",
"=",
"[",
"]",
"guids",
"=",
"[",
"datum",
"[",
"'job'",
"]",
"[",
"'job_guid'",
"]",
"for",
"datum",
"in",
"data",
"]",
"state_map",
"=",
"{",
"guid",
":",
"state",
"for",
"(",
"guid... | Remove jobs from data where we already have them in the same state.
1. split the incoming jobs into pending, running and complete.
2. fetch the ``job_guids`` from the db that are in the same state as they
are in ``data``.
3. build a new list of jobs in ``new_data`` that are not already in
the db and pass that back. It could end up empty at that point. | [
"Remove",
"jobs",
"from",
"data",
"where",
"we",
"already",
"have",
"them",
"in",
"the",
"same",
"state",
"."
] | cc47bdec872e5c668d0f01df89517390a164cda3 | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/etl/jobs.py#L40-L72 | train | 205,494 |
mozilla/treeherder | treeherder/etl/jobs.py | _schedule_log_parsing | def _schedule_log_parsing(job, job_logs, result):
"""Kick off the initial task that parses the log data.
log_data is a list of job log objects and the result for that job
"""
# importing here to avoid an import loop
from treeherder.log_parser.tasks import parse_logs
task_types = {
"errorsummary_json",
"buildbot_text",
"builds-4h"
}
job_log_ids = []
for job_log in job_logs:
# a log can be submitted already parsed. So only schedule
# a parsing task if it's ``pending``
# the submitter is then responsible for submitting the
# text_log_summary artifact
if job_log.status != JobLog.PENDING:
continue
# if this is not a known type of log, abort parse
if job_log.name not in task_types:
continue
job_log_ids.append(job_log.id)
# TODO: Replace the use of different queues for failures vs not with the
# RabbitMQ priority feature (since the idea behind separate queues was
# only to ensure failures are dealt with first if there is a backlog).
if result != 'success':
queue = 'log_parser_fail'
priority = 'failures'
else:
queue = 'log_parser'
priority = "normal"
parse_logs.apply_async(queue=queue,
args=[job.id, job_log_ids, priority]) | python | def _schedule_log_parsing(job, job_logs, result):
"""Kick off the initial task that parses the log data.
log_data is a list of job log objects and the result for that job
"""
# importing here to avoid an import loop
from treeherder.log_parser.tasks import parse_logs
task_types = {
"errorsummary_json",
"buildbot_text",
"builds-4h"
}
job_log_ids = []
for job_log in job_logs:
# a log can be submitted already parsed. So only schedule
# a parsing task if it's ``pending``
# the submitter is then responsible for submitting the
# text_log_summary artifact
if job_log.status != JobLog.PENDING:
continue
# if this is not a known type of log, abort parse
if job_log.name not in task_types:
continue
job_log_ids.append(job_log.id)
# TODO: Replace the use of different queues for failures vs not with the
# RabbitMQ priority feature (since the idea behind separate queues was
# only to ensure failures are dealt with first if there is a backlog).
if result != 'success':
queue = 'log_parser_fail'
priority = 'failures'
else:
queue = 'log_parser'
priority = "normal"
parse_logs.apply_async(queue=queue,
args=[job.id, job_log_ids, priority]) | [
"def",
"_schedule_log_parsing",
"(",
"job",
",",
"job_logs",
",",
"result",
")",
":",
"# importing here to avoid an import loop",
"from",
"treeherder",
".",
"log_parser",
".",
"tasks",
"import",
"parse_logs",
"task_types",
"=",
"{",
"\"errorsummary_json\"",
",",
"\"bu... | Kick off the initial task that parses the log data.
log_data is a list of job log objects and the result for that job | [
"Kick",
"off",
"the",
"initial",
"task",
"that",
"parses",
"the",
"log",
"data",
"."
] | cc47bdec872e5c668d0f01df89517390a164cda3 | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/etl/jobs.py#L331-L372 | train | 205,495 |
mozilla/treeherder | treeherder/etl/jobs.py | store_job_data | def store_job_data(repository, data):
"""
Store job data instances into jobs db
Example:
[
{
"revision": "24fd64b8251fac5cf60b54a915bffa7e51f636b5",
"job": {
"job_guid": "d19375ce775f0dc166de01daa5d2e8a73a8e8ebf",
"name": "xpcshell",
"desc": "foo",
"job_symbol": "XP",
"group_name": "Shelliness",
"group_symbol": "XPC",
"product_name": "firefox",
"state": "TODO",
"result": 0,
"reason": "scheduler",
"who": "sendchange-unittest",
"submit_timestamp": 1365732271,
"start_timestamp": "20130411165317",
"end_timestamp": "1365733932"
"machine": "tst-linux64-ec2-314",
"build_platform": {
"platform": "Ubuntu VM 12.04",
"os_name": "linux",
"architecture": "x86_64"
},
"machine_platform": {
"platform": "Ubuntu VM 12.04",
"os_name": "linux",
"architecture": "x86_64"
},
"option_collection": {
"opt": true
},
"log_references": [
{
"url": "http://ftp.mozilla.org/pub/...",
"name": "unittest"
}
],
artifacts:[{
type:" json | img | ...",
name:"",
log_urls:[
]
blob:""
}],
},
"superseded": []
},
...
]
"""
# Ensure that we have job data to process
if not data:
return
# remove any existing jobs that already have the same state
data = _remove_existing_jobs(data)
if not data:
return
superseded_job_guid_placeholders = []
# TODO: Refactor this now that store_job_data() is only over called with one job at a time.
for datum in data:
try:
# TODO: this might be a good place to check the datum against
# a JSON schema to ensure all the fields are valid. Then
# the exception we caught would be much more informative. That
# being said, if/when we transition to only using the pulse
# job consumer, then the data will always be vetted with a
# JSON schema before we get to this point.
job = datum['job']
revision = datum['revision']
superseded = datum.get('superseded', [])
revision_field = 'revision__startswith' if len(revision) < 40 else 'revision'
filter_kwargs = {'repository': repository, revision_field: revision}
push_id = Push.objects.values_list('id', flat=True).get(**filter_kwargs)
# load job
job_guid = _load_job(repository, job, push_id)
for superseded_guid in superseded:
superseded_job_guid_placeholders.append(
# superseded by guid, superseded guid
[job_guid, superseded_guid]
)
except Exception as e:
# Surface the error immediately unless running in production, where we'd
# rather report it on New Relic and not block storing the remaining jobs.
# TODO: Once buildbot support is removed, remove this as part of
# refactoring this method to process just one job at a time.
if 'DYNO' not in os.environ:
raise
logger.exception(e)
# make more fields visible in new relic for the job
# where we encountered the error
datum.update(datum.get("job", {}))
newrelic.agent.record_exception(params=datum)
# skip any jobs that hit errors in these stages.
continue
# Update the result/state of any jobs that were superseded by those ingested above.
if superseded_job_guid_placeholders:
for (job_guid, superseded_by_guid) in superseded_job_guid_placeholders:
Job.objects.filter(guid=superseded_by_guid).update(
result='superseded',
state='completed') | python | def store_job_data(repository, data):
"""
Store job data instances into jobs db
Example:
[
{
"revision": "24fd64b8251fac5cf60b54a915bffa7e51f636b5",
"job": {
"job_guid": "d19375ce775f0dc166de01daa5d2e8a73a8e8ebf",
"name": "xpcshell",
"desc": "foo",
"job_symbol": "XP",
"group_name": "Shelliness",
"group_symbol": "XPC",
"product_name": "firefox",
"state": "TODO",
"result": 0,
"reason": "scheduler",
"who": "sendchange-unittest",
"submit_timestamp": 1365732271,
"start_timestamp": "20130411165317",
"end_timestamp": "1365733932"
"machine": "tst-linux64-ec2-314",
"build_platform": {
"platform": "Ubuntu VM 12.04",
"os_name": "linux",
"architecture": "x86_64"
},
"machine_platform": {
"platform": "Ubuntu VM 12.04",
"os_name": "linux",
"architecture": "x86_64"
},
"option_collection": {
"opt": true
},
"log_references": [
{
"url": "http://ftp.mozilla.org/pub/...",
"name": "unittest"
}
],
artifacts:[{
type:" json | img | ...",
name:"",
log_urls:[
]
blob:""
}],
},
"superseded": []
},
...
]
"""
# Ensure that we have job data to process
if not data:
return
# remove any existing jobs that already have the same state
data = _remove_existing_jobs(data)
if not data:
return
superseded_job_guid_placeholders = []
# TODO: Refactor this now that store_job_data() is only over called with one job at a time.
for datum in data:
try:
# TODO: this might be a good place to check the datum against
# a JSON schema to ensure all the fields are valid. Then
# the exception we caught would be much more informative. That
# being said, if/when we transition to only using the pulse
# job consumer, then the data will always be vetted with a
# JSON schema before we get to this point.
job = datum['job']
revision = datum['revision']
superseded = datum.get('superseded', [])
revision_field = 'revision__startswith' if len(revision) < 40 else 'revision'
filter_kwargs = {'repository': repository, revision_field: revision}
push_id = Push.objects.values_list('id', flat=True).get(**filter_kwargs)
# load job
job_guid = _load_job(repository, job, push_id)
for superseded_guid in superseded:
superseded_job_guid_placeholders.append(
# superseded by guid, superseded guid
[job_guid, superseded_guid]
)
except Exception as e:
# Surface the error immediately unless running in production, where we'd
# rather report it on New Relic and not block storing the remaining jobs.
# TODO: Once buildbot support is removed, remove this as part of
# refactoring this method to process just one job at a time.
if 'DYNO' not in os.environ:
raise
logger.exception(e)
# make more fields visible in new relic for the job
# where we encountered the error
datum.update(datum.get("job", {}))
newrelic.agent.record_exception(params=datum)
# skip any jobs that hit errors in these stages.
continue
# Update the result/state of any jobs that were superseded by those ingested above.
if superseded_job_guid_placeholders:
for (job_guid, superseded_by_guid) in superseded_job_guid_placeholders:
Job.objects.filter(guid=superseded_by_guid).update(
result='superseded',
state='completed') | [
"def",
"store_job_data",
"(",
"repository",
",",
"data",
")",
":",
"# Ensure that we have job data to process",
"if",
"not",
"data",
":",
"return",
"# remove any existing jobs that already have the same state",
"data",
"=",
"_remove_existing_jobs",
"(",
"data",
")",
"if",
... | Store job data instances into jobs db
Example:
[
{
"revision": "24fd64b8251fac5cf60b54a915bffa7e51f636b5",
"job": {
"job_guid": "d19375ce775f0dc166de01daa5d2e8a73a8e8ebf",
"name": "xpcshell",
"desc": "foo",
"job_symbol": "XP",
"group_name": "Shelliness",
"group_symbol": "XPC",
"product_name": "firefox",
"state": "TODO",
"result": 0,
"reason": "scheduler",
"who": "sendchange-unittest",
"submit_timestamp": 1365732271,
"start_timestamp": "20130411165317",
"end_timestamp": "1365733932"
"machine": "tst-linux64-ec2-314",
"build_platform": {
"platform": "Ubuntu VM 12.04",
"os_name": "linux",
"architecture": "x86_64"
},
"machine_platform": {
"platform": "Ubuntu VM 12.04",
"os_name": "linux",
"architecture": "x86_64"
},
"option_collection": {
"opt": true
},
"log_references": [
{
"url": "http://ftp.mozilla.org/pub/...",
"name": "unittest"
}
],
artifacts:[{
type:" json | img | ...",
name:"",
log_urls:[
]
blob:""
}],
},
"superseded": []
},
...
] | [
"Store",
"job",
"data",
"instances",
"into",
"jobs",
"db"
] | cc47bdec872e5c668d0f01df89517390a164cda3 | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/etl/jobs.py#L375-L490 | train | 205,496 |
mozilla/treeherder | treeherder/services/pulse/exchange.py | get_exchange | def get_exchange(connection, name, create=False):
"""
Get a Kombu Exchange object using the passed in name.
Can create an Exchange but this is typically not wanted in production-like
environments and only useful for testing.
"""
exchange = Exchange(name, type="topic", passive=not create)
# bind the exchange to our connection so operations can be performed on it
bound_exchange = exchange(connection)
# ensure the exchange exists. Throw an error if it was created with
# passive=True and it doesn't exist.
bound_exchange.declare()
return bound_exchange | python | def get_exchange(connection, name, create=False):
"""
Get a Kombu Exchange object using the passed in name.
Can create an Exchange but this is typically not wanted in production-like
environments and only useful for testing.
"""
exchange = Exchange(name, type="topic", passive=not create)
# bind the exchange to our connection so operations can be performed on it
bound_exchange = exchange(connection)
# ensure the exchange exists. Throw an error if it was created with
# passive=True and it doesn't exist.
bound_exchange.declare()
return bound_exchange | [
"def",
"get_exchange",
"(",
"connection",
",",
"name",
",",
"create",
"=",
"False",
")",
":",
"exchange",
"=",
"Exchange",
"(",
"name",
",",
"type",
"=",
"\"topic\"",
",",
"passive",
"=",
"not",
"create",
")",
"# bind the exchange to our connection so operations... | Get a Kombu Exchange object using the passed in name.
Can create an Exchange but this is typically not wanted in production-like
environments and only useful for testing. | [
"Get",
"a",
"Kombu",
"Exchange",
"object",
"using",
"the",
"passed",
"in",
"name",
"."
] | cc47bdec872e5c668d0f01df89517390a164cda3 | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/services/pulse/exchange.py#L4-L20 | train | 205,497 |
mozilla/treeherder | treeherder/seta/job_priorities.py | SETAJobPriorities._process | def _process(self, project, build_system, job_priorities):
'''Return list of ref_data_name for job_priorities'''
jobs = []
# we cache the reference data names in order to reduce API calls
cache_key = '{}-{}-ref_data_names_cache'.format(project, build_system)
ref_data_names_map = cache.get(cache_key)
if not ref_data_names_map:
# cache expired so re-build the reference data names map; the map
# contains the ref_data_name of every treeherder *test* job for this project
ref_data_names_map = self._build_ref_data_names(project, build_system)
# update the cache
cache.set(cache_key, ref_data_names_map, SETA_REF_DATA_NAMES_CACHE_TIMEOUT)
# now check the JobPriority table against the list of valid runnable
for jp in job_priorities:
# if this JobPriority entry is no longer supported in SETA then ignore it
if not valid_platform(jp.platform):
continue
if is_job_blacklisted(jp.testtype):
continue
key = jp.unique_identifier()
if key in ref_data_names_map:
# e.g. desktop-test-linux64-pgo/opt-reftest-13 or builder name
jobs.append(ref_data_names_map[key])
else:
logger.warning('Job priority (%s) not found in accepted jobs list', jp)
return jobs | python | def _process(self, project, build_system, job_priorities):
'''Return list of ref_data_name for job_priorities'''
jobs = []
# we cache the reference data names in order to reduce API calls
cache_key = '{}-{}-ref_data_names_cache'.format(project, build_system)
ref_data_names_map = cache.get(cache_key)
if not ref_data_names_map:
# cache expired so re-build the reference data names map; the map
# contains the ref_data_name of every treeherder *test* job for this project
ref_data_names_map = self._build_ref_data_names(project, build_system)
# update the cache
cache.set(cache_key, ref_data_names_map, SETA_REF_DATA_NAMES_CACHE_TIMEOUT)
# now check the JobPriority table against the list of valid runnable
for jp in job_priorities:
# if this JobPriority entry is no longer supported in SETA then ignore it
if not valid_platform(jp.platform):
continue
if is_job_blacklisted(jp.testtype):
continue
key = jp.unique_identifier()
if key in ref_data_names_map:
# e.g. desktop-test-linux64-pgo/opt-reftest-13 or builder name
jobs.append(ref_data_names_map[key])
else:
logger.warning('Job priority (%s) not found in accepted jobs list', jp)
return jobs | [
"def",
"_process",
"(",
"self",
",",
"project",
",",
"build_system",
",",
"job_priorities",
")",
":",
"jobs",
"=",
"[",
"]",
"# we cache the reference data names in order to reduce API calls",
"cache_key",
"=",
"'{}-{}-ref_data_names_cache'",
".",
"format",
"(",
"projec... | Return list of ref_data_name for job_priorities | [
"Return",
"list",
"of",
"ref_data_name",
"for",
"job_priorities"
] | cc47bdec872e5c668d0f01df89517390a164cda3 | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/seta/job_priorities.py#L27-L56 | train | 205,498 |
mozilla/treeherder | treeherder/seta/job_priorities.py | SETAJobPriorities._build_ref_data_names | def _build_ref_data_names(self, project, build_system):
'''
We want all reference data names for every task that runs on a specific project.
For example:
* Buildbot - "Windows 8 64-bit mozilla-inbound debug test web-platform-tests-1"
* TaskCluster = "test-linux64/opt-mochitest-webgl-e10s-1"
'''
ignored_jobs = []
ref_data_names = {}
runnable_jobs = list_runnable_jobs(project)
for job in runnable_jobs:
# get testtype e.g. web-platform-tests-4
testtype = parse_testtype(
build_system_type=job['build_system_type'],
job_type_name=job['job_type_name'],
platform_option=job['platform_option'],
ref_data_name=job['ref_data_name']
)
if not valid_platform(job['platform']):
continue
if is_job_blacklisted(testtype):
ignored_jobs.append(job['ref_data_name'])
continue
key = unique_key(testtype=testtype,
buildtype=job['platform_option'],
platform=job['platform'])
if build_system == '*':
ref_data_names[key] = job['ref_data_name']
elif job['build_system_type'] == build_system:
ref_data_names[key] = job['ref_data_name']
for ref_data_name in sorted(ignored_jobs):
logger.info('Ignoring %s', ref_data_name)
return ref_data_names | python | def _build_ref_data_names(self, project, build_system):
'''
We want all reference data names for every task that runs on a specific project.
For example:
* Buildbot - "Windows 8 64-bit mozilla-inbound debug test web-platform-tests-1"
* TaskCluster = "test-linux64/opt-mochitest-webgl-e10s-1"
'''
ignored_jobs = []
ref_data_names = {}
runnable_jobs = list_runnable_jobs(project)
for job in runnable_jobs:
# get testtype e.g. web-platform-tests-4
testtype = parse_testtype(
build_system_type=job['build_system_type'],
job_type_name=job['job_type_name'],
platform_option=job['platform_option'],
ref_data_name=job['ref_data_name']
)
if not valid_platform(job['platform']):
continue
if is_job_blacklisted(testtype):
ignored_jobs.append(job['ref_data_name'])
continue
key = unique_key(testtype=testtype,
buildtype=job['platform_option'],
platform=job['platform'])
if build_system == '*':
ref_data_names[key] = job['ref_data_name']
elif job['build_system_type'] == build_system:
ref_data_names[key] = job['ref_data_name']
for ref_data_name in sorted(ignored_jobs):
logger.info('Ignoring %s', ref_data_name)
return ref_data_names | [
"def",
"_build_ref_data_names",
"(",
"self",
",",
"project",
",",
"build_system",
")",
":",
"ignored_jobs",
"=",
"[",
"]",
"ref_data_names",
"=",
"{",
"}",
"runnable_jobs",
"=",
"list_runnable_jobs",
"(",
"project",
")",
"for",
"job",
"in",
"runnable_jobs",
":... | We want all reference data names for every task that runs on a specific project.
For example:
* Buildbot - "Windows 8 64-bit mozilla-inbound debug test web-platform-tests-1"
* TaskCluster = "test-linux64/opt-mochitest-webgl-e10s-1" | [
"We",
"want",
"all",
"reference",
"data",
"names",
"for",
"every",
"task",
"that",
"runs",
"on",
"a",
"specific",
"project",
"."
] | cc47bdec872e5c668d0f01df89517390a164cda3 | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/seta/job_priorities.py#L72-L113 | train | 205,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.