INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Retrieves the file at `path` and return it's content.
Android only.
- _path_ - the path to the file on the device
- _decode_ - True/False decode the data (base64) before returning it (default=False) | def pull_file(self, path, decode=False):
"""Retrieves the file at `path` and return it's content.
Android only.
- _path_ - the path to the file on the device
- _decode_ - True/False decode the data (base64) before returning it (default=False)
"""
driver = self._curre... |
Retrieves a folder at `path`. Returns the folder's contents zipped.
Android only.
- _path_ - the path to the folder on the device
- _decode_ - True/False decode the data (base64) before returning it (default=False) | def pull_folder(self, path, decode=False):
"""Retrieves a folder at `path`. Returns the folder's contents zipped.
Android only.
- _path_ - the path to the folder on the device
- _decode_ - True/False decode the data (base64) before returning it (default=False)
"""
dri... |
Puts the data in the file specified as `path`.
Android only.
- _path_ - the path on the device
- _data_ - data to be written to the file
- _encode_ - True/False encode the data as base64 before writing it to the file (default=False) | def push_file(self, path, data, encode=False):
"""Puts the data in the file specified as `path`.
Android only.
- _path_ - the path on the device
- _data_ - data to be written to the file
- _encode_ - True/False encode the data as base64 before writing it to the file (default... |
Opens an arbitrary activity during a test. If the activity belongs to
another application, that application is started and the activity is opened.
Android only.
- _appPackage_ - The package containing the activity to start.
- _appActivity_ - The activity to start.
- _appWaitPac... | def start_activity(self, appPackage, appActivity, **opts):
"""Opens an arbitrary activity during a test. If the activity belongs to
another application, that application is started and the activity is opened.
Android only.
- _appPackage_ - The package containing the activity to start.
... |
Wait for an activity: block until target activity presents
or time out.
Android only.
- _activity_ - target activity
- _timeout_ - max wait time, in seconds
- _interval_ - sleep interval between retries, in seconds | def wait_activity(self, activity, timeout, interval=1):
"""Wait for an activity: block until target activity presents
or time out.
Android only.
- _activity_ - target activity
- _timeout_ - max wait time, in seconds
- _interval_ - sleep interval between retries, in s... |
Install App via Appium
Android only.
- app_path - path to app
- app_package - package of install app to verify | def install_app(self, app_path, app_package):
""" Install App via Appium
Android only.
- app_path - path to app
- app_package - package of install app to verify
"""
driver = self._current_application()
driver.install_app(app_path)
return driver.i... |
Set location
- _latitute_
- _longitude_
- _altitude_ = 10 [optional]
Android only.
New in AppiumLibrary 1.5 | def set_location(self, latitude, longitude, altitude=10):
""" Set location
- _latitute_
- _longitude_
- _altitude_ = 10 [optional]
Android only.
New in AppiumLibrary 1.5
"""
driver = self._current_application()
driver.set_location(latitud... |
Click element identified by `locator`.
Key attributes for arbitrary elements are `index` and `name`. See
`introduction` for details about locating elements. | def click_element(self, locator):
"""Click element identified by `locator`.
Key attributes for arbitrary elements are `index` and `name`. See
`introduction` for details about locating elements.
"""
self._info("Clicking element '%s'." % locator)
self._element_find(... |
Click button | def click_button(self, index_or_name):
""" Click button """
_platform_class_dict = {'ios': 'UIAButton',
'android': 'android.widget.Button'}
if self._is_support_platform(_platform_class_dict):
class_name = self._get_class(_platform_class_dict)
... |
Click text identified by ``text``.
By default tries to click first text involves given ``text``, if you would
like to click exactly matching text, then set ``exact_match`` to `True`.
If there are multiple use of ``text`` and you do not want first one,
use `locator` with `Get Web... | def click_text(self, text, exact_match=False):
"""Click text identified by ``text``.
By default tries to click first text involves given ``text``, if you would
like to click exactly matching text, then set ``exact_match`` to `True`.
If there are multiple use of ``text`` and you ... |
Types the given `text` into text field identified by `locator`.
See `introduction` for details about locating elements. | def input_text(self, locator, text):
"""Types the given `text` into text field identified by `locator`.
See `introduction` for details about locating elements.
"""
self._info("Typing text '%s' into text field '%s'" % (text, locator))
self._element_input_text_by_locator(loc... |
Types the given password into text field identified by `locator`.
Difference between this keyword and `Input Text` is that this keyword
does not log the given password. See `introduction` for details about
locating elements. | def input_password(self, locator, text):
"""Types the given password into text field identified by `locator`.
Difference between this keyword and `Input Text` is that this keyword
does not log the given password. See `introduction` for details about
locating elements.
"""
... |
Sets the given value into text field identified by `locator`. This is an IOS only keyword, input value makes use of set_value
See `introduction` for details about locating elements. | def input_value(self, locator, text):
"""Sets the given value into text field identified by `locator`. This is an IOS only keyword, input value makes use of set_value
See `introduction` for details about locating elements.
"""
self._info("Setting text '%s' into text field '%s'" % (... |
Verifies that current page contains `text`.
If this keyword fails, it automatically logs the page source
using the log level specified with the optional `loglevel` argument.
Giving `NONE` as level disables logging. | def page_should_contain_text(self, text, loglevel='INFO'):
"""Verifies that current page contains `text`.
If this keyword fails, it automatically logs the page source
using the log level specified with the optional `loglevel` argument.
Giving `NONE` as level disables logging.
... |
Verifies that current page not contains `text`.
If this keyword fails, it automatically logs the page source
using the log level specified with the optional `loglevel` argument.
Giving `NONE` as level disables logging. | def page_should_not_contain_text(self, text, loglevel='INFO'):
"""Verifies that current page not contains `text`.
If this keyword fails, it automatically logs the page source
using the log level specified with the optional `loglevel` argument.
Giving `NONE` as level disables loggin... |
Verifies that current page contains `locator` element.
If this keyword fails, it automatically logs the page source
using the log level specified with the optional `loglevel` argument.
Giving `NONE` as level disables logging. | def page_should_contain_element(self, locator, loglevel='INFO'):
"""Verifies that current page contains `locator` element.
If this keyword fails, it automatically logs the page source
using the log level specified with the optional `loglevel` argument.
Giving `NONE` as level disabl... |
Verifies that current page not contains `locator` element.
If this keyword fails, it automatically logs the page source
using the log level specified with the optional `loglevel` argument.
Giving `NONE` as level disables logging. | def page_should_not_contain_element(self, locator, loglevel='INFO'):
"""Verifies that current page not contains `locator` element.
If this keyword fails, it automatically logs the page source
using the log level specified with the optional `loglevel` argument.
Giving `NONE` as leve... |
Verifies that element identified with locator is disabled.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements. | def element_should_be_disabled(self, locator, loglevel='INFO'):
"""Verifies that element identified with locator is disabled.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
if self._element_find(locato... |
Verifies that element identified with locator is visible.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
New in AppiumLibrary 1.4.5 | def element_should_be_visible(self, locator, loglevel='INFO'):
"""Verifies that element identified with locator is visible.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
New in AppiumLibrary 1.4.... |
Verify that an attribute of an element matches the expected criteria.
The element is identified by _locator_. See `introduction` for details
about locating elements. If more than one element matches, the first element is selected.
The _attr_name_ is the name of the attribute within the se... | def element_attribute_should_match(self, locator, attr_name, match_pattern, regexp=False):
"""Verify that an attribute of an element matches the expected criteria.
The element is identified by _locator_. See `introduction` for details
about locating elements. If more than one element matche... |
Verifies element identified by ``locator`` contains text ``expected``.
If you wish to assert an exact (not a substring) match on the text
of the element, use `Element Text Should Be`.
Key attributes for arbitrary elements are ``id`` and ``xpath``. ``message`` can be used to override the d... | def element_should_contain_text(self, locator, expected, message=''):
"""Verifies element identified by ``locator`` contains text ``expected``.
If you wish to assert an exact (not a substring) match on the text
of the element, use `Element Text Should Be`.
Key attributes for arbi... |
Verifies element identified by ``locator`` exactly contains text ``expected``.
In contrast to `Element Should Contain Text`, this keyword does not try
a substring match but an exact match on the element identified by ``locator``.
``message`` can be used to override the default error messa... | def element_text_should_be(self, locator, expected, message=''):
"""Verifies element identified by ``locator`` exactly contains text ``expected``.
In contrast to `Element Should Contain Text`, this keyword does not try
a substring match but an exact match on the element identified by ``loca... |
Get element attribute using given attribute: name, value,...
Examples:
| Get Element Attribute | locator | name |
| Get Element Attribute | locator | value | | def get_element_attribute(self, locator, attribute):
"""Get element attribute using given attribute: name, value,...
Examples:
| Get Element Attribute | locator | name |
| Get Element Attribute | locator | value |
"""
elements = self._element_find(locator, False... |
Get element location
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements. | def get_element_location(self, locator):
"""Get element location
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
element = self._element_find(locator, True, True)
element_location = element.loc... |
Get element size
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements. | def get_element_size(self, locator):
"""Get element size
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
element = self._element_find(locator, True, True)
element_size = element.size
s... |
Get element text (for hybrid and mobile browser use `xpath` locator, others might cause problem)
Example:
| ${text} | Get Text | //*[contains(@text,'foo')] |
New in AppiumLibrary 1.4. | def get_text(self, locator):
"""Get element text (for hybrid and mobile browser use `xpath` locator, others might cause problem)
Example:
| ${text} | Get Text | //*[contains(@text,'foo')] |
New in AppiumLibrary 1.4.
"""
text = self._get_text(locator)
... |
Returns number of elements matching ``xpath``
One should not use the `xpath=` prefix for 'xpath'. XPath is assumed.
| *Correct:* |
| ${count} | Get Matching Xpath Count | //android.view.View[@text='Test'] |
| Incorrect: |
| ${count} | Get Matching Xpath Count | xpath=... | def get_matching_xpath_count(self, xpath):
"""Returns number of elements matching ``xpath``
One should not use the `xpath=` prefix for 'xpath'. XPath is assumed.
| *Correct:* |
| ${count} | Get Matching Xpath Count | //android.view.View[@text='Test'] |
| Incorrect: |
... |
Verifies that element identified with text is visible.
New in AppiumLibrary 1.4.5 | def text_should_be_visible(self, text, exact_match=False, loglevel='INFO'):
"""Verifies that element identified with text is visible.
New in AppiumLibrary 1.4.5
"""
if not self._element_find_by_text(text, exact_match).is_displayed():
self.log_source(loglevel)
... |
Verifies that the page contains the given number of elements located by the given ``xpath``.
One should not use the `xpath=` prefix for 'xpath'. XPath is assumed.
| *Correct:* |
| Xpath Should Match X Times | //android.view.View[@text='Test'] | 1 |
| Incorrect: |
| Xpath... | def xpath_should_match_x_times(self, xpath, count, error=None, loglevel='INFO'):
"""Verifies that the page contains the given number of elements located by the given ``xpath``.
One should not use the `xpath=` prefix for 'xpath'. XPath is assumed.
| *Correct:* |
| Xpath Should Mat... |
Closes the current application and also close webdriver session. | def close_application(self):
"""Closes the current application and also close webdriver session."""
self._debug('Closing application with session id %s' % self._current_application().session_id)
self._cache.close() |
Opens a new application to given Appium server.
Capabilities of appium server, Android and iOS,
Please check https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/server-args.md
| *Option* | *Man.* | *Description* |
| remote_url | Yes ... | def open_application(self, remote_url, alias=None, **kwargs):
"""Opens a new application to given Appium server.
Capabilities of appium server, Android and iOS,
Please check https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/server-args.md
| *Option* ... |
Switches the active application by index or alias.
`index_or_alias` is either application index (an integer) or alias
(a string). Index is got as the return value of `Open Application`.
This keyword returns the index of the previous active application,
which can be used to switch... | def switch_application(self, index_or_alias):
"""Switches the active application by index or alias.
`index_or_alias` is either application index (an integer) or alias
(a string). Index is got as the return value of `Open Application`.
This keyword returns the index of the previou... |
Sets the timeout in seconds used by various keywords.
There are several `Wait ...` keywords that take timeout as an
argument. All of these timeout arguments are optional. The timeout
used by all of them can be set globally using this keyword.
The previous timeout value is returne... | def set_appium_timeout(self, seconds):
"""Sets the timeout in seconds used by various keywords.
There are several `Wait ...` keywords that take timeout as an
argument. All of these timeout arguments are optional. The timeout
used by all of them can be set globally using this keywor... |
Returns the current session ID as a reference | def get_appium_sessionId(self):
"""Returns the current session ID as a reference"""
self._info("Appium Session ID: " + self._current_application().session_id)
return self._current_application().session_id |
Logs and returns the entire html source of the current page or frame.
The `loglevel` argument defines the used log level. Valid log levels are
`WARN`, `INFO` (default), `DEBUG`, `TRACE` and `NONE` (no logging). | def log_source(self, loglevel='INFO'):
"""Logs and returns the entire html source of the current page or frame.
The `loglevel` argument defines the used log level. Valid log levels are
`WARN`, `INFO` (default), `DEBUG`, `TRACE` and `NONE` (no logging).
"""
ll = loglevel.up... |
Lock the device for a certain period of time. iOS only. | def lock(self, seconds=5):
"""
Lock the device for a certain period of time. iOS only.
"""
self._current_application().lock(robot.utils.timestr_to_secs(seconds)) |
Return the desired capability value by desired capability name | def get_capability(self, capability_name):
"""
Return the desired capability value by desired capability name
"""
try:
capability = self._current_application().capabilities[capability_name]
except Exception as e:
raise e
return capability |
Find element matches by UI Automator. | def _find_by_android(self, browser, criteria, tag, constraints):
"""Find element matches by UI Automator."""
return self._filter_elements(
browser.find_elements_by_android_uiautomator(criteria),
tag, constraints) |
Find element matches by UI Automation. | def _find_by_ios(self, browser, criteria, tag, constraints):
"""Find element matches by UI Automation."""
return self._filter_elements(
browser.find_elements_by_ios_uiautomation(criteria),
tag, constraints) |
Find element matches by iOSNsPredicateString. | def _find_by_nsp(self, browser, criteria, tag, constraints):
"""Find element matches by iOSNsPredicateString."""
return self._filter_elements(
browser.find_elements_by_ios_predicate(criteria),
tag, constraints) |
Find element matches by iOSChainString. | def _find_by_chain(self, browser, criteria, tag, constraints):
"""Find element matches by iOSChainString."""
return self._filter_elements(
browser.find_elements_by_ios_class_chain(criteria),
tag, constraints) |
Sends a press of keycode to the device.
Android only.
Possible keycodes & meta states can be found in
http://developer.android.com/reference/android/view/KeyEvent.html
Meta state describe the pressed state of key modifiers such as
Shift, Ctrl & Alt keys. The Meta State is an i... | def press_keycode(self, keycode, metastate=None):
"""Sends a press of keycode to the device.
Android only.
Possible keycodes & meta states can be found in
http://developer.android.com/reference/android/view/KeyEvent.html
Meta state describe the pressed state of key modifiers s... |
Sends a long press of keycode to the device.
Android only.
See `press keycode` for more details. | def long_press_keycode(self, keycode, metastate=None):
"""Sends a long press of keycode to the device.
Android only.
See `press keycode` for more details.
"""
driver = self._current_application()
driver.long_press_keycode(int(keycode), metastate) |
Takes a screenshot of the current page and embeds it into the log.
`filename` argument specifies the name of the file to write the
screenshot into. If no `filename` is given, the screenshot is saved into file
`appium-screenshot-<counter>.png` under the directory where
the Robot Fra... | def capture_page_screenshot(self, filename=None):
"""Takes a screenshot of the current page and embeds it into the log.
`filename` argument specifies the name of the file to write the
screenshot into. If no `filename` is given, the screenshot is saved into file
`appium-screenshot-<... |
Read power stats and return dictionary | def rapl_read():
""" Read power stats and return dictionary"""
basenames = glob.glob('/sys/class/powercap/intel-rapl:*/')
basenames = sorted(set({x for x in basenames}))
pjoin = os.path.join
ret = list()
for path in basenames:
name = None
try:
name = cat(pjoin(path, ... |
Dynamically change the scale of the graph (y lable) | def get_label_scale(self, min_val, max_val, size):
"""Dynamically change the scale of the graph (y lable)"""
if size < self.SCALE_DENSITY:
label_cnt = 1
else:
label_cnt = int(size / self.SCALE_DENSITY)
try:
if max_val >= 100:
label = [i... |
Return a list of bar widths, one for each bar in data.
If self.bar_width is None this implementation will stretch
the bars across the available space specified by maxcol. | def calculate_bar_widths(self, size, bardata):
"""
Return a list of bar widths, one for each bar in data.
If self.bar_width is None this implementation will stretch
the bars across the available space specified by maxcol.
"""
(maxcol, _) = size
if self.bar_width... |
Show a column of the graph selected for display | def set_visible_graphs(self, visible_graph_list=None):
"""Show a column of the graph selected for display"""
if visible_graph_list is None:
visible_graph_list = self.visible_graph_list
vline = urwid.AttrWrap(urwid.SolidFill(u'|'), 'line')
graph_vector_column_list = []
... |
Returns the processor name in the system | def get_processor_name():
""" Returns the processor name in the system """
if platform.system() == "Linux":
with open("/proc/cpuinfo", "rb") as cpuinfo:
all_info = cpuinfo.readlines()
for line in all_info:
if b'model name' in line:
return re.su... |
Kills a process and all its children | def kill_child_processes(parent_proc):
""" Kills a process and all its children """
logging.debug("Killing stress process")
try:
for proc in parent_proc.children(recursive=True):
logging.debug('Killing %s', proc)
proc.kill()
parent_proc.kill()
except AttributeErro... |
Print statistics to csv file | def output_to_csv(sources, csv_writeable_file):
"""Print statistics to csv file"""
file_exists = os.path.isfile(csv_writeable_file)
with open(csv_writeable_file, 'a') as csvfile:
csv_dict = OrderedDict()
csv_dict.update({'Time': time.strftime("%Y-%m-%d_%H:%M:%S")})
summaries = [val ... |
Print statistics to the terminal | def output_to_terminal(sources):
"""Print statistics to the terminal"""
results = OrderedDict()
for source in sources:
if source.get_is_available():
source.update()
results.update(source.get_summary())
for key, value in results.items():
sys.stdout.write(str(key) +... |
Print statistics to the terminal in Json format | def output_to_json(sources):
"""Print statistics to the terminal in Json format"""
results = OrderedDict()
for source in sources:
if source.get_is_available():
source.update()
source_name = source.get_source_name()
results[source_name] = source.get_sensors_summary... |
Return the path to the user s-tui config directory | def get_user_config_dir():
"""
Return the path to the user s-tui config directory
"""
user_home = os.getenv('XDG_CONFIG_HOME')
if user_home is None or not user_home:
config_path = os.path.expanduser(os.path.join('~', '.config', 's-tui'))
else:
config_path = os.path.join(user_home... |
Return the path to the user s-tui config directory | def get_user_config_file():
"""
Return the path to the user s-tui config directory
"""
user_home = os.getenv('XDG_CONFIG_HOME')
if user_home is None or not user_home:
config_path = os.path.expanduser(os.path.join('~', '.config',
's-tui', ... |
Create the user s-tui config directory if it doesn't exist | def make_user_config_dir():
"""
Create the user s-tui config directory if it doesn't exist
"""
config_path = get_user_config_dir()
if not user_config_dir_exists():
try:
os.mkdir(config_path)
os.mkdir(os.path.join(config_path, 'hooks.d'))
except OSError:
... |
Converts seconds to a string of hours:minutes:seconds | def seconds_to_text(secs):
""" Converts seconds to a string of hours:minutes:seconds """
hours = (secs)//3600
minutes = (secs - hours*3600)//60
seconds = secs - hours*3600 - minutes*60
return "%02d:%02d:%02d" % (hours, minutes, seconds) |
On Python 3 opens a file in text mode by using fs encoding and
a proper en/decoding errors handler.
On Python 2 this is just an alias for open(name, 'rt'). | def _open_text(fname, **kwargs):
"""On Python 3 opens a file in text mode by using fs encoding and
a proper en/decoding errors handler.
On Python 2 this is just an alias for open(name, 'rt').
"""
if PY3:
kwargs.setdefault('encoding', ENCODING)
kwargs.setdefault('errors', ENCODING_ERR... |
Return file content.
fallback: the value returned in case the file does not exist or
cannot be read
binary: whether to open the file in binary or text mode. | def cat(fname, fallback=_DEFAULT, binary=True):
"""Return file content.
fallback: the value returned in case the file does not exist or
cannot be read
binary: whether to open the file in binary or text mode.
"""
try:
with _open_binary(fname) if binary else _open_text(fname) as ... |
check if the format of number is (num)(G|m|B) i.e 500GB, 200mb. 400
etc.. | def get_valid_byte(num, default):
"""check if the format of number is (num)(G|m|B) i.e 500GB, 200mb. 400
etc.. """
num_valid = re.match(r"\A([0-9]+)(M|G|m|g|)(B|b|\b)\Z", num, re.I)
if num_valid:
return num
return default |
Return ScriptHook for source_name Source and with a ready timeout
of timeoutMilliseconds | def load_script(self, source_name, timeoutMilliseconds=0):
"""
Return ScriptHook for source_name Source and with a ready timeout
of timeoutMilliseconds
"""
script_path = os.path.join(self.scripts_dir_path,
self._source_to_script_name(source_nam... |
This returns a dict of sensor of the source and their values | def get_sensors_summary(self):
""" This returns a dict of sensor of the source and their values """
sub_title_list = self.get_sensor_list()
graph_vector_summary = OrderedDict()
for graph_idx, graph_data in enumerate(self.last_measurement):
val_str = str(round(graph_data, 1))... |
Returns a dict of source name and sensors with their values | def get_summary(self):
""" Returns a dict of source name and sensors with their values """
graph_vector_summary = OrderedDict()
graph_vector_summary[self.get_source_name()] = (
'[' + self.measurement_unit + ']')
graph_vector_summary.update(self.get_sensors_summary())
... |
Evaluate the current state of this Source and
invoke any attached hooks if they've been triggered | def eval_hooks(self):
"""
Evaluate the current state of this Source and
invoke any attached hooks if they've been triggered
"""
logging.debug("Evaluating hooks")
if self.get_edge_triggered():
logging.debug("Hook triggered")
for hook in [h for h in ... |
Run callback, optionally passing a variable number
of arguments `callback_args` | def invoke(self):
"""
Run callback, optionally passing a variable number
of arguments `callback_args`
"""
# Don't sleep a hook if it has never run
if self.timeout_milliseconds > 0:
self.ready_time = (
datetime.now() +
timedelta... |
Inheriting radio button of urwid | def radio_button(g, l, fn):
""" Inheriting radio button of urwid """
w = urwid.RadioButton(g, l, False, on_state_change=fn)
w = urwid.AttrWrap(w, 'button normal', 'button select')
return w |
Starts a new stress process with a given cmd | def start_stress(self, stress_cmd):
""" Starts a new stress process with a given cmd """
with open(os.devnull, 'w') as dev_null:
try:
stress_proc = subprocess.Popen(stress_cmd, stdout=dev_null,
stderr=dev_null)
se... |
Update all the graphs that are being displayed | def update_displayed_information(self):
""" Update all the graphs that are being displayed """
for source in self.controller.sources:
source_name = source.get_source_name()
if (any(self.graphs_menu.active_sensors[source_name]) or
any(self.summary_menu.active_... |
Reset graph data and display empty graph | def on_reset_button(self, _):
"""Reset graph data and display empty graph"""
for graph in self.visible_graphs.values():
graph.reset()
for graph in self.graphs.values():
try:
graph.source.reset()
except NotImplementedError:
pass
... |
Return to main screen and update sensor that
are active in the view | def on_graphs_menu_close(self, update):
"""Return to main screen and update sensor that
are active in the view"""
logging.info("closing sensor menu, update=%s", update)
if update:
for sensor, visible_sensors in \
self.graphs_menu.active_sensors.items():
... |
Return to main screen and update sensor that
are active in the view | def on_summary_menu_close(self, update):
"""Return to main screen and update sensor that
are active in the view"""
logging.info("closing summary_menu menu, update=%s", update)
if update:
for sensor, visible_sensors in \
self.summary_menu.active_sensors.ite... |
Open stress options | def on_stress_menu_open(self, widget):
"""Open stress options"""
self.original_widget = urwid.Overlay(self.stress_menu.main_window,
self.original_widget,
('relative', self.left_margin),
... |
Open Help menu | def on_help_menu_open(self, widget):
"""Open Help menu"""
self.original_widget = urwid.Overlay(self.help_menu.main_window,
self.original_widget,
('relative', self.left_margin),
... |
Open About menu | def on_about_menu_open(self, widget):
"""Open About menu"""
self.original_widget = urwid.Overlay(self.about_menu.main_window,
self.original_widget,
('relative', self.left_margin),
... |
Open Sensor menu on top of existing frame | def on_graphs_menu_open(self, widget):
"""Open Sensor menu on top of existing frame"""
self.original_widget = urwid.Overlay(
self.graphs_menu.main_window,
self.original_widget,
('relative', self.left_margin),
self.graphs_menu.get_size()[1],
('r... |
Open Sensor menu on top of existing frame | def on_summary_menu_open(self, widget):
"""Open Sensor menu on top of existing frame"""
self.original_widget = urwid.Overlay(
self.summary_menu.main_window,
self.original_widget,
('relative', self.left_margin),
self.summary_menu.get_size()[1],
... |
Notify the controller of a new mode setting. | def on_mode_button(self, my_button, state):
"""Notify the controller of a new mode setting."""
if state:
# The new mode is the label of the button
self.controller.set_mode(my_button.get_label()) |
Enable smooth edges if utf-8 is supported | def on_unicode_checkbox(self, w=None, state=False):
"""Enable smooth edges if utf-8 is supported"""
logging.debug("unicode State is %s", state)
# Update the controller to the state of the checkbox
self.controller.smooth_graph_mode = state
if state:
self.hline = urwid... |
Display sidebar controls. i.e. buttons, and controls | def _generate_graph_controls(self):
""" Display sidebar controls. i.e. buttons, and controls"""
# setup mode radio buttons
stress_modes = self.controller.stress_conroller.get_modes()
group = []
for mode in stress_modes:
self.mode_buttons.append(radio_button(group, mod... |
Read and display processor name | def _generate_cpu_stats():
"""Read and display processor name """
cpu_name = urwid.Text("CPU Name N/A", align="center")
try:
cpu_name = urwid.Text(get_processor_name().strip(), align="center")
except OSError:
logging.info("CPU name not available")
return [... |
Show a pile of the graph selected for dislpay | def show_graphs(self):
"""Show a pile of the graph selected for dislpay"""
elements = itertools.chain.from_iterable(
([graph]
for graph in self.visible_graphs.values()))
self.graph_place_holder.original_widget = urwid.Pile(elements) |
Uses configurations defined by user to configure sources for display.
This should be the only place where sources are initiated
This returns a list of sources after configurations are applied | def _load_config(self, t_thresh):
"""
Uses configurations defined by user to configure sources for display.
This should be the only place where sources are initiated
This returns a list of sources after configurations are applied
"""
# Load and configure user config dir ... |
Configures the possible stress processes and modes | def _config_stress(self):
""" Configures the possible stress processes and modes """
# Configure stress_process
self.stress_exe = None
stress_installed = False
self.stress_exe = which('stress')
if self.stress_exe:
stress_installed = True
else:
... |
Starts the main loop and graph animation | def main(self):
""" Starts the main loop and graph animation """
loop = MainLoop(self.view, DEFAULT_PALETTE,
handle_mouse=self.handle_mouse)
self.view.show_graphs()
self.animate_graph(loop)
try:
loop.run()
except (ZeroDivisionError) as ... |
Updates stress mode according to radio buttons state | def update_stress_mode(self):
""" Updates stress mode according to radio buttons state """
self.stress_conroller.kill_stress_process()
# Start a new clock upon starting a new stress test
self.view.clock_view.set_text(ZERO_TIME)
self.stress_start_time = timeit.default_timer()
... |
Save the current configuration to a user config file | def save_settings(self):
""" Save the current configuration to a user config file """
def _save_displayed_setting(conf, submenu):
for source, visible_sensors in \
self.view.graphs_menu.active_sensors.items():
section = source + "," + submenu
... |
Update the graph and schedule the next update
This is where the magic happens | def animate_graph(self, loop, user_data=None):
"""
Update the graph and schedule the next update
This is where the magic happens
"""
self.view.update_displayed_information()
# Save to CSV if configured
if self.save_csv or self.csv_file is not None:
ou... |
A generator that returns short sequential combinations of lower and
upper-case letters that will never repeat.
If *use_unicode* is ``True``, use nonlatin cryllic, arabic, and syriac
letters instead of the usual ABCs.
The *identifier_length* represents the length of the string to return using
the a... | def obfuscation_machine(use_unicode=False, identifier_length=1):
"""
A generator that returns short sequential combinations of lower and
upper-case letters that will never repeat.
If *use_unicode* is ``True``, use nonlatin cryllic, arabic, and syriac
letters instead of the usual ABCs.
The *ide... |
Returns 'source' all obfuscated. | def apply_obfuscation(source):
"""
Returns 'source' all obfuscated.
"""
global keyword_args
global imported_modules
tokens = token_utils.listified_tokenizer(source)
keyword_args = analyze.enumerate_keyword_args(tokens)
imported_modules = analyze.enumerate_imports(tokens)
variables = ... |
Iterates over *tokens*, which must be an equivalent output to what
tokenize.generate_tokens() produces, calling *obfunc* on each with the
following parameters:
- **tokens:** The current list of tokens.
- **index:** The current position in the list.
*obfunc* is expected to return t... | def find_obfuscatables(tokens, obfunc, ignore_length=False):
"""
Iterates over *tokens*, which must be an equivalent output to what
tokenize.generate_tokens() produces, calling *obfunc* on each with the
following parameters:
- **tokens:** The current list of tokens.
- **index:** ... |
Given a list of *tokens* and an *index* (representing the current position),
returns the token string if it is a variable name that can be safely
obfuscated.
Returns '__skipline__' if the rest of the tokens on this line should be skipped.
Returns '__skipnext__' if the next token should be skipped.
... | def obfuscatable_variable(tokens, index, ignore_length=False):
"""
Given a list of *tokens* and an *index* (representing the current position),
returns the token string if it is a variable name that can be safely
obfuscated.
Returns '__skipline__' if the rest of the tokens on this line should be sk... |
Given a list of *tokens* and an *index* (representing the current position),
returns the token string if it is a class name that can be safely
obfuscated. | def obfuscatable_class(tokens, index, **kwargs):
"""
Given a list of *tokens* and an *index* (representing the current position),
returns the token string if it is a class name that can be safely
obfuscated.
"""
tok = tokens[index]
token_type = tok[0]
token_string = tok[1]
if index >... |
Iterates over *tokens*, which must be an equivalent output to what
tokenize.generate_tokens() produces, replacing the given identifier name
(*replace*) by calling *obfunc* on each token with the following parameters:
- **module:** The name of the script we're currently obfuscating.
- **to... | def replace_obfuscatables(module, tokens, obfunc, replace, name_generator, table=None):
"""
Iterates over *tokens*, which must be an equivalent output to what
tokenize.generate_tokens() produces, replacing the given identifier name
(*replace*) by calling *obfunc* on each token with the following paramet... |
If the token string inside *tokens[index]* matches *replace*, return
*replacement*. *right_of_equal*, and *inside_parens* are used to determine
whether or not this token is safe to obfuscate. | def obfuscate_variable(
tokens,
index,
replace,
replacement,
right_of_equal,
inside_parens,
inside_function):
"""
If the token string inside *tokens[index]* matches *replace*, return
*replacement*. *right_of_equal*, and *inside_parens* are used to dete... |
If the token string (a function) inside *tokens[index]* matches *replace*,
return *replacement*. | def obfuscate_function(tokens, index, replace, replacement, *args):
"""
If the token string (a function) inside *tokens[index]* matches *replace*,
return *replacement*.
"""
def return_replacement(replacement):
FUNC_REPLACEMENTS[replacement] = replace
return replacement
tok = toke... |
If the token string (a class) inside *tokens[index]* matches *replace*,
return *replacement*. | def obfuscate_class(tokens, index, replace, replacement, *args):
"""
If the token string (a class) inside *tokens[index]* matches *replace*,
return *replacement*.
"""
def return_replacement(replacement):
CLASS_REPLACEMENTS[replacement] = replace
return replacement
tok = tokens[in... |
If the token string (a unique value anywhere) inside *tokens[index]*
matches *replace*, return *replacement*.
.. note::
This function is only for replacing absolutely unique ocurrences of
*replace* (where we don't have to worry about their position). | def obfuscate_unique(tokens, index, replace, replacement, *args):
"""
If the token string (a unique value anywhere) inside *tokens[index]*
matches *replace*, return *replacement*.
.. note::
This function is only for replacing absolutely unique ocurrences of
*replace* (where we don't ha... |
Produces a series of variable assignments in the form of::
<obfuscated name> = <some identifier>
for each item in *names* using *name_generator* to come up with the
replacement names.
If *table* is provided, replacements will be looked up there before
generating a new unique name. | def remap_name(name_generator, names, table=None):
"""
Produces a series of variable assignments in the form of::
<obfuscated name> = <some identifier>
for each item in *names* using *name_generator* to come up with the
replacement names.
If *table* is provided, replacements will be looke... |
Inserts the given string after the next newline inside tokens starting at
*tokens[index]*. Indents must be a list of indentation tokens that will
preceeed the insert (can be an empty list). | def insert_in_next_line(tokens, index, string):
"""
Inserts the given string after the next newline inside tokens starting at
*tokens[index]*. Indents must be a list of indentation tokens that will
preceeed the insert (can be an empty list).
"""
tokenized_string = token_utils.listified_tokenize... |
Inserts an assignment, '<obfuscated identifier> = <builtin function>' at
the beginning of *tokens* (after the shebang and encoding if present) for
every Python built-in function that is used inside *tokens*. Also, replaces
all of said builti-in functions in *tokens* with each respective obfuscated
ide... | def obfuscate_builtins(module, tokens, name_generator, table=None):
"""
Inserts an assignment, '<obfuscated identifier> = <builtin function>' at
the beginning of *tokens* (after the shebang and encoding if present) for
every Python built-in function that is used inside *tokens*. Also, replaces
all... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.