_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q34900
ConfigParser.next
train
def next(self): """ Return the next token. Keep track of our current position in the config for nice errors. """ if self.current_token == len(self.tokens): return None token = self.tokens[self.current_token] if token["type"] == "newline": self.line += 1 self.line_start = token["start"] self.current_token += 1 if token["type"] == "unknown": self.error("Unknown token") return token
python
{ "resource": "" }
q34901
ConfigParser.remove_quotes
train
def remove_quotes(self, value): """ Remove any surrounding quotes from a value and unescape any contained quotes of that type. """ # beware the empty string if not value: return value if value[0] == value[-1] == '"': return value[1:-1].replace('\\"', '"') if value[0] == value[-1] == "'": return value[1:-1].replace("\\'", "'") return value
python
{ "resource": "" }
q34902
ConfigParser.make_value
train
def make_value(self, value): """ Converts to actual value, or remains as string. """ # ensure any escape sequences are converted to unicode value = self.unicode_escape_sequence_fix(value) if value and value[0] in ['"', "'"]: return self.remove_quotes(value) try: return int(value) except ValueError: pass try: return float(value) except ValueError: pass if value.lower() == "true": return True if value.lower() == "false": return False if value.lower() == "none": return None return value
python
{ "resource": "" }
q34903
ConfigParser.config_function
train
def config_function(self, token): """ Process a config function from a token """ match = token["match"] function = match.group(2).lower() param = match.group(3) or "" value_type = match.group(6) or "auto" # fix any escaped closing parenthesis param = param.replace(r"\)", ")") CONFIG_FUNCTIONS = { "base64": self.make_function_value_private, "env": self.make_value_from_env, "hide": self.make_function_value_private, "shell": self.make_value_from_shell, } return CONFIG_FUNCTIONS[function](param, value_type, function)
python
{ "resource": "" }
q34904
ConfigParser.value_convert
train
def value_convert(self, value, value_type): """ convert string into type used by `config functions` """ CONVERSION_OPTIONS = { "str": str, "int": int, "float": float, # Treat booleans specially "bool": (lambda val: val.lower() in ("true", "1")), # Auto-guess the type "auto": self.make_value, } try: return CONVERSION_OPTIONS[value_type](value) except (TypeError, ValueError): self.notify_user("Bad type conversion") return None
python
{ "resource": "" }
q34905
ConfigParser.make_value_from_env
train
def make_value_from_env(self, param, value_type, function): """ get environment variable """ value = os.getenv(param) if value is None: self.notify_user("Environment variable `%s` undefined" % param) return self.value_convert(value, value_type)
python
{ "resource": "" }
q34906
ConfigParser.make_value_from_shell
train
def make_value_from_shell(self, param, value_type, function): """ run command in the shell """ try: value = check_output(param, shell=True).rstrip() except CalledProcessError: # for value_type of 'bool' we return False on error code if value_type == "bool": value = False else: if self.py3_wrapper: self.py3_wrapper.report_exception( msg="shell: called with command `%s`" % param ) self.notify_user("shell script exited with an error") value = None else: # if the value_type is 'bool' then we return True for success if value_type == "bool": value = True else: # convert bytes to unicode value = value.decode("utf-8") value = self.value_convert(value, value_type) return value
python
{ "resource": "" }
q34907
ConfigParser.make_function_value_private
train
def make_function_value_private(self, value, value_type, function): """ Wraps converted value so that it is hidden in logs etc. Note this is not secure just reduces leaking info Allows base 64 encode stuff using base64() or plain hide() in the config """ # remove quotes value = self.remove_quotes(value) if function == "base64": try: import base64 value = base64.b64decode(value).decode("utf-8") except TypeError as e: self.notify_user("base64(..) error %s" % str(e)) # check we are in a module definition etc if not self.current_module: self.notify_user("%s(..) used outside of module or section" % function) return None module = self.current_module[-1].split()[0] if module in CONFIG_FILE_SPECIAL_SECTIONS + I3S_MODULE_NAMES: self.notify_user( "%s(..) cannot be used outside of py3status module " "configuration" % function ) return None value = self.value_convert(value, value_type) module_name = self.current_module[-1] return PrivateHide(value, module_name)
python
{ "resource": "" }
q34908
ConfigParser.separator
train
def separator(self, separator=",", end_token=None): """ Read through tokens till the required separator is found. We ignore newlines. If an end token is supplied raise a ParseEnd exception if it is found. """ while True: token = self.next() t_value = token["value"] if end_token and t_value == end_token: raise self.ParseEnd() if t_value == separator: return if t_value == "\n": continue self.error("Unexpected character")
python
{ "resource": "" }
q34909
ConfigParser.make_list
train
def make_list(self, end_token="]"): """ We are in a list so get values until the end token. This can also used to get tuples. """ out = [] while True: try: value = self.value_assign(end_token=end_token) out.append(value) self.separator(end_token=end_token) except self.ParseEnd: return out
python
{ "resource": "" }
q34910
ConfigParser.dict_key
train
def dict_key(self): """ Find the next key in a dict. We skip any newlines and check for if the dict has ended. """ while True: token = self.next() t_value = token["value"] if t_value == "\n": continue if t_value == "}": raise self.ParseEnd() if token["type"] == "literal": return self.make_value(t_value) self.error("Invalid Key")
python
{ "resource": "" }
q34911
ConfigParser.make_dict
train
def make_dict(self): """ We are in a dict so get key value pairs until the end token. """ out = {} while True: try: key = self.dict_key() self.separator(separator=":") value = self.value_assign(end_token="]") out[key] = value self.separator(end_token="}") except self.ParseEnd: return out
python
{ "resource": "" }
q34912
ConfigParser.module_def
train
def module_def(self): """ This is a module definition so parse content till end. """ if self.module_level == MAX_NESTING_LEVELS: self.error("Module nested too deep") self.module_level += 1 module = ModuleDefinition() self.parse(module, end_token="}") self.module_level -= 1 self.current_module.pop() return module
python
{ "resource": "" }
q34913
ConfigParser.process_value
train
def process_value(self, name, value, module_name): """ This method allow any encodings to be dealt with. Currently only base64 is supported. Note: If other encodings are added then this should be split so that there is a method for each encoding. """ # if we have a colon in the name of a setting then it # indicates that it has been encoded. if ":" in name: if module_name.split(" ")[0] in I3S_MODULE_NAMES + ["general"]: self.error("Only py3status modules can use obfuscated") if type(value).__name__ not in ["str", "unicode"]: self.error("Only strings can be obfuscated") (name, scheme) = name.split(":") if scheme == "base64": value = PrivateBase64(value, module_name) elif scheme == "hide": value = PrivateHide(value, module_name) else: self.error("Unknown scheme {} for data".format(scheme)) return name, value
python
{ "resource": "" }
q34914
ConfigParser.parse
train
def parse(self, dictionary=None, end_token=None): """ Parse through the tokens. Finding names and values. This is called at the start of parsing the config but is also called to parse module definitions. """ self.level += 1 name = [] if dictionary is None: dictionary = self.config while True: token = self.next() if token is None: # we have got to the end of the config break t_type = token["type"] t_value = token["value"] if t_type == "newline": continue elif t_value == end_token: self.level -= 1 return elif t_type == "literal": value = self.remove_quotes(t_value) if not name and not re.match("[a-zA-Z_]", value): self.error("Invalid name") name.append(value) elif t_type == "function": self.error("Name expected") elif t_type == "operator": name = " ".join(name) if not name: self.error("Name expected") elif t_value == "+=" and name not in dictionary: # deal with encoded names if name.split(":")[0] not in dictionary: # order is treated specially if not (self.level == 1 and name == "order"): self.error("{} does not exist".format(name)) if t_value in ["{"]: if self.current_module: self.check_child_friendly(self.current_module[-1]) self.check_module_name(name) self.current_module.append(name) value = self.assignment(token) # order is treated specially to create a list if self.level == 1 and name == "order": if not value: self.error("Invalid module") self.check_module_name(value, offset=1) dictionary.setdefault(name, []).append(value) # assignment of module definition elif t_value == "{": # If this is an py3status module and in a container and has # no instance name then give it an anon one. This allows # us to have multiple non-instance named modules defined # without them clashing. if ( self.level > 1 and " " not in name and name not in I3S_MODULE_NAMES ): name = "{} _anon_module_{}".format(name, self.anon_count) self.anon_count += 1 dictionary[name] = value # assignment of value elif t_value == "=": try: name, value = self.process_value( name, value, self.current_module[-1] ) except IndexError: self.error("Missing {", previous=True) dictionary[name] = value # appending to existing values elif t_value == "+=": dictionary[name] += value else: self.error("Unexpected character") name = []
python
{ "resource": "" }
q34915
Py3status.on_click
train
def on_click(self, event): """ Control moc with mouse clicks. """ button = event["button"] if button == self.button_pause: if self.state == "STOP": self.py3.command_run("mocp --play") else: self.py3.command_run("mocp --toggle-pause") elif button == self.button_stop: self.py3.command_run("mocp --stop") elif button == self.button_next: self.py3.command_run("mocp --next") elif button == self.button_previous: self.py3.command_run("mocp --prev") else: self.py3.prevent_refresh()
python
{ "resource": "" }
q34916
Py3._thresholds_init
train
def _thresholds_init(self): """ Initiate and check any thresholds set """ thresholds = getattr(self._py3status_module, "thresholds", []) self._thresholds = {} if isinstance(thresholds, list): try: thresholds.sort() except TypeError: pass self._thresholds[None] = [(x[0], self._get_color(x[1])) for x in thresholds] return elif isinstance(thresholds, dict): for key, value in thresholds.items(): if isinstance(value, list): try: value.sort() except TypeError: pass self._thresholds[key] = [ (x[0], self._get_color(x[1])) for x in value ]
python
{ "resource": "" }
q34917
Py3._report_exception
train
def _report_exception(self, msg, frame_skip=2): """ THIS IS PRIVATE AND UNSUPPORTED. logs an exception that occurs inside of a Py3 method. We only log the exception once to prevent spamming the logs and we do not notify the user. frame_skip is used to change the place in the code that the error is reported as coming from. We want to show it as coming from the py3status module where the Py3 method was called. """ # We use a hash to see if the message is being repeated. msg_hash = hash(msg) if msg_hash in self._report_exception_cache: return self._report_exception_cache.add(msg_hash) # If we just report the error the traceback will end in the try # except block that we are calling from. # We want to show the traceback originating from the module that # called the Py3 method so get the correct error frame and pass this # along. error_frame = sys._getframe(0) while frame_skip: error_frame = error_frame.f_back frame_skip -= 1 self._py3_wrapper.report_exception( msg, notify_user=False, error_frame=error_frame )
python
{ "resource": "" }
q34918
Py3.flatten_dict
train
def flatten_dict(self, d, delimiter="-", intermediates=False, parent_key=None): """ Flatten a dictionary. Values that are dictionaries are flattened using delimiter in between (eg. parent-child) Values that are lists are flattened using delimiter followed by the index (eg. parent-0) example: .. code-block:: python { 'fish_facts': { 'sharks': 'Most will drown if they stop moving', 'skates': 'More than 200 species', }, 'fruits': ['apple', 'peach', 'watermelon'], 'number': 52 } # becomes { 'fish_facts-sharks': 'Most will drown if they stop moving', 'fish_facts-skates': 'More than 200 species', 'fruits-0': 'apple', 'fruits-1': 'peach', 'fruits-2': 'watermelon', 'number': 52 } # if intermediates is True then we also get unflattened elements # as well as the flattened ones. { 'fish_facts': { 'sharks': 'Most will drown if they stop moving', 'skates': 'More than 200 species', }, 'fish_facts-sharks': 'Most will drown if they stop moving', 'fish_facts-skates': 'More than 200 species', 'fruits': ['apple', 'peach', 'watermelon'], 'fruits-0': 'apple', 'fruits-1': 'peach', 'fruits-2': 'watermelon', 'number': 52 } """ items = [] if isinstance(d, list): d = dict(enumerate(d)) for k, v in d.items(): if parent_key: k = u"{}{}{}".format(parent_key, delimiter, k) if intermediates: items.append((k, v)) if isinstance(v, list): v = dict(enumerate(v)) if isinstance(v, collections.Mapping): items.extend( self.flatten_dict(v, delimiter, intermediates, str(k)).items() ) else: items.append((str(k), v)) return dict(items)
python
{ "resource": "" }
q34919
Py3.is_my_event
train
def is_my_event(self, event): """ Checks if an event triggered belongs to the module receiving it. This is mainly for containers who will also receive events from any children they have. Returns True if the event name and instance match that of the module checking. """ return ( event.get("name") == self._module.module_name and event.get("instance") == self._module.module_inst )
python
{ "resource": "" }
q34920
Py3.log
train
def log(self, message, level=LOG_INFO): """ Log the message. The level must be one of LOG_ERROR, LOG_INFO or LOG_WARNING """ assert level in [ self.LOG_ERROR, self.LOG_INFO, self.LOG_WARNING, ], "level must be LOG_ERROR, LOG_INFO or LOG_WARNING" # nicely format logs if we can using pretty print if isinstance(message, (dict, list, set, tuple)): message = pformat(message) # start on new line if multi-line output try: if "\n" in message: message = "\n" + message except: # noqa e722 pass message = "Module `{}`: {}".format(self._module.module_full_name, message) self._py3_wrapper.log(message, level)
python
{ "resource": "" }
q34921
Py3.update
train
def update(self, module_name=None): """ Update a module. If module_name is supplied the module of that name is updated. Otherwise the module calling is updated. """ if not module_name: return self._module.force_update() else: module_info = self._get_module_info(module_name) if module_info: module_info["module"].force_update()
python
{ "resource": "" }
q34922
Py3.get_output
train
def get_output(self, module_name): """ Return the output of the named module. This will be a list. """ output = [] module_info = self._get_module_info(module_name) if module_info: output = module_info["module"].get_latest() # we do a deep copy so that any user does not change the actual output # of the module. return deepcopy(output)
python
{ "resource": "" }
q34923
Py3.trigger_event
train
def trigger_event(self, module_name, event): """ Trigger an event on a named module. """ if module_name: self._py3_wrapper.events_thread.process_event(module_name, event)
python
{ "resource": "" }
q34924
Py3.notify_user
train
def notify_user(self, msg, level="info", rate_limit=5, title=None, icon=None): """ Send a notification to the user. level must be 'info', 'error' or 'warning'. rate_limit is the time period in seconds during which this message should not be repeated. icon must be an icon path or icon name. """ module_name = self._module.module_full_name if isinstance(msg, Composite): msg = msg.text() if title is None: title = "py3status: {}".format(module_name) elif isinstance(title, Composite): title = title.text() # force unicode for python2 str if self._is_python_2: if isinstance(msg, str): msg = msg.decode("utf-8") if isinstance(title, str): title = title.decode("utf-8") if msg: self._py3_wrapper.notify_user( msg=msg, level=level, rate_limit=rate_limit, module_name=module_name, title=title, icon=icon, )
python
{ "resource": "" }
q34925
Py3.register_function
train
def register_function(self, function_name, function): """ Register a function for the module. The following functions can be registered .. py:function:: content_function() Called to discover what modules a container is displaying. This is used to determine when updates need passing on to the container and also when modules can be put to sleep. the function must return a set of module names that are being displayed. .. note:: This function should only be used by containers. .. py:function:: urgent_function(module_names) This function will be called when one of the contents of a container has changed from a non-urgent to an urgent state. It is used by the group module to switch to displaying the urgent module. ``module_names`` is a list of modules that have become urgent .. note:: This function should only be used by containers. """ my_info = self._get_module_info(self._module.module_full_name) my_info[function_name] = function
python
{ "resource": "" }
q34926
Py3.time_in
train
def time_in(self, seconds=None, sync_to=None, offset=0): """ Returns the time a given number of seconds into the future. Helpful for creating the ``cached_until`` value for the module output. .. note:: from version 3.1 modules no longer need to explicitly set a ``cached_until`` in their response unless they wish to directly control it. :param seconds: specifies the number of seconds that should occur before the update is required. Passing a value of ``CACHE_FOREVER`` returns ``CACHE_FOREVER`` which can be useful for some modules. :param sync_to: causes the update to be synchronized to a time period. 1 would cause the update on the second, 60 to the nearest minute. By default we synchronize to the nearest second. 0 will disable this feature. :param offset: is used to alter the base time used. A timer that started at a certain time could set that as the offset and any synchronization would then be relative to that time. """ # if called with CACHE_FOREVER we just return this if seconds is self.CACHE_FOREVER: return self.CACHE_FOREVER if seconds is None: # If we have a sync_to then seconds can be 0 if sync_to and sync_to > 0: seconds = 0 else: try: # use py3status modules cache_timeout seconds = self._py3status_module.cache_timeout except AttributeError: # use default cache_timeout seconds = self._module.config["cache_timeout"] # Unless explicitly set we sync to the nearest second # Unless the requested update is in less than a second if sync_to is None: if seconds and seconds < 1: if 1 % seconds == 0: sync_to = seconds else: sync_to = 0 else: sync_to = 1 if seconds: seconds -= 0.1 requested = time() + seconds - offset # if sync_to then we find the sync time for the requested time if sync_to: requested = (requested + sync_to) - (requested % sync_to) return requested + offset
python
{ "resource": "" }
q34927
Py3.format_contains
train
def format_contains(self, format_string, names): """ Determines if ``format_string`` contains a placeholder string ``names`` or a list of placeholders ``names``. ``names`` is tested against placeholders using fnmatch so the following patterns can be used: .. code-block:: none * matches everything ? matches any single character [seq] matches any character in seq [!seq] matches any character not in seq This is useful because a simple test like ``'{placeholder}' in format_string`` will fail if the format string contains placeholder formatting eg ``'{placeholder:.2f}'`` """ # We cache things to prevent parsing the format_string more than needed if isinstance(names, list): key = str(names) else: key = names names = [names] try: return self._format_placeholders_cache[format_string][key] except KeyError: pass if format_string not in self._format_placeholders: placeholders = self._formatter.get_placeholders(format_string) self._format_placeholders[format_string] = placeholders else: placeholders = self._format_placeholders[format_string] if format_string not in self._format_placeholders_cache: self._format_placeholders_cache[format_string] = {} for name in names: for placeholder in placeholders: if fnmatch(placeholder, name): self._format_placeholders_cache[format_string][key] = True return True self._format_placeholders_cache[format_string][key] = False return False
python
{ "resource": "" }
q34928
Py3.get_color_names_list
train
def get_color_names_list(self, format_strings): """ Returns a list of color names in ``format_string``. :param format_strings: Accepts a format string or a list of format strings. """ if not format_strings: return [] if not getattr(self._py3status_module, "thresholds", None): return [] if isinstance(format_strings, basestring): format_strings = [format_strings] names = set() for string in format_strings: names.update(self._formatter.get_color_names(string)) return list(names)
python
{ "resource": "" }
q34929
Py3.get_placeholders_list
train
def get_placeholders_list(self, format_string, matches=None): """ Returns a list of placeholders in ``format_string``. If ``matches`` is provided then it is used to filter the result using fnmatch so the following patterns can be used: .. code-block:: none * matches everything ? matches any single character [seq] matches any character in seq [!seq] matches any character not in seq This is useful because we just get simple placeholder without any formatting that may be applied to them eg ``'{placeholder:.2f}'`` will give ``['{placeholder}']`` """ if format_string not in self._format_placeholders: placeholders = self._formatter.get_placeholders(format_string) self._format_placeholders[format_string] = placeholders else: placeholders = self._format_placeholders[format_string] if not matches: return list(placeholders) elif isinstance(matches, basestring): matches = [matches] # filter matches found = set() for match in matches: for placeholder in placeholders: if fnmatch(placeholder, match): found.add(placeholder) return list(found)
python
{ "resource": "" }
q34930
Py3.safe_format
train
def safe_format( self, format_string, param_dict=None, force_composite=False, attr_getter=None ): r""" Parser for advanced formatting. Unknown placeholders will be shown in the output eg ``{foo}``. Square brackets ``[]`` can be used. The content of them will be removed from the output if there is no valid placeholder contained within. They can also be nested. A pipe (vertical bar) ``|`` can be used to divide sections the first valid section only will be shown in the output. A backslash ``\`` can be used to escape a character eg ``\[`` will show ``[`` in the output. ``\?`` is special and is used to provide extra commands to the format string, example ``\?color=#FF00FF``. Multiple commands can be given using an ampersand ``&`` as a separator, example ``\?color=#FF00FF&show``. ``\?if=<placeholder>`` can be used to check if a placeholder exists. An exclamation mark ``!`` after the equals sign ``=`` can be used to negate the condition. ``\?if=<placeholder>=<value>`` can be used to determine if {<placeholder>} would be replaced with <value>. ``[]`` in <value> don't need to be escaped. ``{<placeholder>}`` will be converted, or removed if it is None or empty. Formatting can also be applied to the placeholder Eg ``{number:03.2f}``. example format_string: ``"[[{artist} - ]{title}]|{file}"`` This will show ``artist - title`` if artist is present, ``title`` if title but no artist, and ``file`` if file is present but not artist or title. param_dict is a dictionary of placeholders that will be substituted. If a placeholder is not in the dictionary then if the py3status module has an attribute with the same name then it will be used. .. note:: Added in version 3.3 Composites can be included in the param_dict. The result returned from this function can either be a string in the case of simple parsing or a Composite if more complex. If force_composite parameter is True a composite will always be returned. attr_getter is a function that will when called with an attribute name as a parameter will return a value. """ try: return self._formatter.format( format_string, self._py3status_module, param_dict, force_composite=force_composite, attr_getter=attr_getter, ) except Exception: self._report_exception(u"Invalid format `{}`".format(format_string)) return "invalid format"
python
{ "resource": "" }
q34931
Py3.check_commands
train
def check_commands(self, cmd_list): """ Checks to see if commands in list are available using ``which``. returns the first available command. If a string is passed then that command will be checked for. """ # if a string is passed then convert it to a list. This prevents an # easy mistake that could be made if isinstance(cmd_list, basestring): cmd_list = [cmd_list] for cmd in cmd_list: if self.command_run("which {}".format(cmd)) == 0: return cmd
python
{ "resource": "" }
q34932
Py3.command_run
train
def command_run(self, command): """ Runs a command and returns the exit code. The command can either be supplied as a sequence or string. An Exception is raised if an error occurs """ # convert the command to sequence if a string if isinstance(command, basestring): command = shlex.split(command) try: return Popen(command, stdout=PIPE, stderr=PIPE, close_fds=True).wait() except Exception as e: # make a pretty command for error loggings and... if isinstance(command, basestring): pretty_cmd = command else: pretty_cmd = " ".join(command) msg = "Command `{cmd}` {error}".format(cmd=pretty_cmd, error=e.errno) raise exceptions.CommandError(msg, error_code=e.errno)
python
{ "resource": "" }
q34933
Py3.command_output
train
def command_output( self, command, shell=False, capture_stderr=False, localized=False ): """ Run a command and return its output as unicode. The command can either be supplied as a sequence or string. :param command: command to run can be a str or list :param shell: if `True` then command is run through the shell :param capture_stderr: if `True` then STDERR is piped to STDOUT :param localized: if `False` then command is forced to use its default (English) locale A CommandError is raised if an error occurs """ # make a pretty command for error loggings and... if isinstance(command, basestring): pretty_cmd = command else: pretty_cmd = " ".join(command) # convert the non-shell command to sequence if it is a string if not shell and isinstance(command, basestring): command = shlex.split(command) stderr = STDOUT if capture_stderr else PIPE env = self._english_env if not localized else None try: process = Popen( command, stdout=PIPE, stderr=stderr, close_fds=True, universal_newlines=True, shell=shell, env=env, ) except Exception as e: msg = "Command `{cmd}` {error}".format(cmd=pretty_cmd, error=e) raise exceptions.CommandError(msg, error_code=e.errno) output, error = process.communicate() if self._is_python_2 and isinstance(output, str): output = output.decode("utf-8") error = error.decode("utf-8") retcode = process.poll() if retcode: # under certain conditions a successfully run command may get a # return code of -15 even though correct output was returned see # #664. This issue seems to be related to arch linux but the # reason is not entirely clear. if retcode == -15: msg = "Command `{cmd}` returned SIGTERM (ignoring)" self.log(msg.format(cmd=pretty_cmd)) else: msg = "Command `{cmd}` returned non-zero exit status {error}" output_oneline = output.replace("\n", " ") if output_oneline: msg += " ({output})" msg = msg.format(cmd=pretty_cmd, error=retcode, output=output_oneline) raise exceptions.CommandError( msg, error_code=retcode, error=error, output=output ) return output
python
{ "resource": "" }
q34934
Py3._storage_init
train
def _storage_init(self): """ Ensure that storage is initialized. """ if not self._storage.initialized: self._storage.init(self._module._py3_wrapper, self._is_python_2)
python
{ "resource": "" }
q34935
Py3.storage_set
train
def storage_set(self, key, value): """ Store a value for the module. """ if not self._module: return self._storage_init() module_name = self._module.module_full_name return self._storage.storage_set(module_name, key, value)
python
{ "resource": "" }
q34936
Py3.storage_get
train
def storage_get(self, key): """ Retrieve a value for the module. """ if not self._module: return self._storage_init() module_name = self._module.module_full_name return self._storage.storage_get(module_name, key)
python
{ "resource": "" }
q34937
Py3.storage_del
train
def storage_del(self, key=None): """ Remove the value stored with the key from storage. If key is not supplied then all values for the module are removed. """ if not self._module: return self._storage_init() module_name = self._module.module_full_name return self._storage.storage_del(module_name, key=key)
python
{ "resource": "" }
q34938
Py3.storage_keys
train
def storage_keys(self): """ Return a list of the keys for values stored for the module. Keys will contain the following metadata entries: - '_ctime': storage creation timestamp - '_mtime': storage last modification timestamp """ if not self._module: return [] self._storage_init() module_name = self._module.module_full_name return self._storage.storage_keys(module_name)
python
{ "resource": "" }
q34939
Py3.storage_items
train
def storage_items(self): """ Return key, value pairs of the stored data for the module. Keys will contain the following metadata entries: - '_ctime': storage creation timestamp - '_mtime': storage last modification timestamp """ if not self._module: return {}.items() self._storage_init() items = [] module_name = self._module.module_full_name for key in self._storage.storage_keys(module_name): value = self._storage.storage_get(module_name, key) items.add((key, value)) return items
python
{ "resource": "" }
q34940
Py3.play_sound
train
def play_sound(self, sound_file): """ Plays sound_file if possible. """ self.stop_sound() if sound_file: cmd = self.check_commands(["ffplay", "paplay", "play"]) if cmd: if cmd == "ffplay": cmd = "ffplay -autoexit -nodisp -loglevel 0" sound_file = os.path.expanduser(sound_file) c = shlex.split("{} {}".format(cmd, sound_file)) self._audio = Popen(c)
python
{ "resource": "" }
q34941
Py3.threshold_get_color
train
def threshold_get_color(self, value, name=None): """ Obtain color for a value using thresholds. The value will be checked against any defined thresholds. These should have been set in the i3status configuration. If more than one threshold is needed for a module then the name can also be supplied. If the user has not supplied a named threshold but has defined a general one that will be used. If the gradients config parameter is True then rather than sharp thresholds we will use a gradient between the color values. :param value: numerical value to be graded :param name: accepts a string, otherwise 'threshold' accepts 3-tuples to allow name with different values eg ('name', 'key', 'thresholds') """ # If first run then process the threshold data. if self._thresholds is None: self._thresholds_init() # allow name with different values if isinstance(name, tuple): name_used = "{}/{}".format(name[0], name[1]) if name[2]: self._thresholds[name_used] = [ (x[0], self._get_color(x[1])) for x in name[2] ] name = name[0] else: # if name not in thresholds info then use defaults name_used = name if name_used not in self._thresholds: name_used = None # convert value to int/float thresholds = self._thresholds.get(name_used) color = None try: value = float(value) except (TypeError, ValueError): pass # skip on empty thresholds/values if not thresholds or value in [None, ""]: pass elif isinstance(value, basestring): # string for threshold in thresholds: if value == threshold[0]: color = threshold[1] break else: # int/float try: if self._get_config_setting("gradients"): try: colors, minimum, maximum = self._threshold_gradients[name_used] except KeyError: colors = self._gradients.make_threshold_gradient( self, thresholds ) minimum = min(thresholds)[0] maximum = max(thresholds)[0] self._threshold_gradients[name_used] = ( colors, minimum, maximum, ) if value < minimum: color = colors[0] elif value > maximum: color = colors[-1] else: value -= minimum col_index = int( ((len(colors) - 1) / (maximum - minimum)) * value ) color = colors[col_index] else: color = thresholds[0][1] for threshold in thresholds: if value >= threshold[0]: color = threshold[1] else: break except TypeError: color = None # save color so it can be accessed via safe_format() if name: color_name = "color_threshold_%s" % name else: color_name = "color_threshold" setattr(self._py3status_module, color_name, color) return color
python
{ "resource": "" }
q34942
Py3.request
train
def request( self, url, params=None, data=None, headers=None, timeout=None, auth=None, cookiejar=None, ): """ Make a request to a url and retrieve the results. If the headers parameter does not provide an 'User-Agent' key, one will be added automatically following the convention: py3status/<version> <per session random uuid> :param url: url to request eg `http://example.com` :param params: extra query string parameters as a dict :param data: POST data as a dict. If this is not supplied the GET method will be used :param headers: http headers to be added to the request as a dict :param timeout: timeout for the request in seconds :param auth: authentication info as tuple `(username, password)` :param cookiejar: an object of a CookieJar subclass :returns: HttpResponse """ # The aim of this function is to be a limited lightweight replacement # for the requests library but using only pythons standard libs. # IMPORTANT NOTICE # This function is excluded from private variable hiding as it is # likely to need api keys etc which people may have obfuscated. # Therefore it is important that no logging is done in this function # that might reveal this information. if headers is None: headers = {} if timeout is None: timeout = getattr(self._py3status_module, "request_timeout", 10) if "User-Agent" not in headers: headers["User-Agent"] = "py3status/{} {}".format(version, self._uid) return HttpResponse( url, params=params, data=data, headers=headers, timeout=timeout, auth=auth, cookiejar=cookiejar, )
python
{ "resource": "" }
q34943
Py3status._get_ip
train
def _get_ip(self, interface): """ Returns the interface's IPv4 address if device exists and has a valid ip address. Otherwise, returns an empty string """ if interface in ni.interfaces(): addresses = ni.ifaddresses(interface) if ni.AF_INET in addresses: return addresses[ni.AF_INET][0]["addr"] return ""
python
{ "resource": "" }
q34944
Py3status.on_click
train
def on_click(self, event): """ Display a notification following the specified format """ if not self.notification: return if self.charging: format = self.format_notify_charging else: format = self.format_notify_discharging message = self.py3.safe_format( format, dict( ascii_bar=self.ascii_bar, icon=self.icon, percent=self.percent_charged, time_remaining=self.time_remaining, ), ) if message: self.py3.notify_user(message, "info")
python
{ "resource": "" }
q34945
Py3status._extract_battery_info_from_acpi
train
def _extract_battery_info_from_acpi(self): """ Get the battery info from acpi # Example acpi -bi raw output (Discharging): Battery 0: Discharging, 94%, 09:23:28 remaining Battery 0: design capacity 5703 mAh, last full capacity 5283 mAh = 92% Battery 1: Unknown, 98% Battery 1: design capacity 1880 mAh, last full capacity 1370 mAh = 72% # Example Charging Battery 0: Charging, 96%, 00:20:40 until charged Battery 0: design capacity 5566 mAh, last full capacity 5156 mAh = 92% Battery 1: Unknown, 98% Battery 1: design capacity 1879 mAh, last full capacity 1370 mAh = 72% """ def _parse_battery_info(acpi_battery_lines): battery = {} battery["percent_charged"] = int( findall("(?<= )(\d+)(?=%)", acpi_battery_lines[0])[0] ) battery["charging"] = "Charging" in acpi_battery_lines[0] battery["capacity"] = int( findall("(?<= )(\d+)(?= mAh)", acpi_battery_lines[1])[1] ) # ACPI only shows time remaining if battery is discharging or # charging try: battery["time_remaining"] = "".join( findall( "(?<=, )(\d+:\d+:\d+)(?= remaining)|" "(?<=, )(\d+:\d+:\d+)(?= until)", acpi_battery_lines[0], )[0] ) except IndexError: battery["time_remaining"] = FULLY_CHARGED return battery acpi_list = self.py3.command_output(["acpi", "-b", "-i"]).splitlines() # Separate the output because each pair of lines corresponds to a # single battery. Now the list index will correspond to the index of # the battery we want to look at acpi_list = [acpi_list[i : i + 2] for i in range(0, len(acpi_list) - 1, 2)] return [_parse_battery_info(battery) for battery in acpi_list]
python
{ "resource": "" }
q34946
Py3status.example_method
train
def example_method(self, i3s_output_list, i3s_config): """ This method will return an empty text message so it will NOT be displayed on your i3bar. If you want something displayed you should write something in the 'full_text' key of your response. See the i3bar protocol spec for more information: http://i3wm.org/docs/i3bar-protocol.html """ # create out output text replacing the placeholder full_text = self.format.format(output='example') response = { 'cached_until': time() + self.cache_timeout, 'full_text': full_text } return response
python
{ "resource": "" }
q34947
Py3status.on_click
train
def on_click(self, event): """ Toggle between display modes 'ip' and 'status' """ button = event["button"] if button == self.button_toggle: self.toggled = True if self.mode == "ip": self.mode = "status" else: self.mode = "ip" elif button == self.button_refresh: self.idle_time = 0 else: self.py3.prevent_refresh()
python
{ "resource": "" }
q34948
Py3status._get_layout
train
def _get_layout(self): """ Get the outputs layout from xrandr and try to detect the currently active layout as best as we can on start. """ connected = list() active_layout = list() disconnected = list() layout = OrderedDict( {"connected": OrderedDict(), "disconnected": OrderedDict()} ) current = self.py3.command_output("xrandr") for line in current.splitlines(): try: s = line.split(" ") infos = line[line.find("(") :] if s[1] == "connected": output, state, mode = s[0], s[1], None for index, x in enumerate(s[2:], 2): if "x" in x and "+" in x: mode = x active_layout.append(output) infos = line[line.find(s[index + 1]) :] break elif "(" in x: break connected.append(output) elif s[1] == "disconnected": output, state, mode = s[0], s[1], None disconnected.append(output) else: continue except Exception as err: self.py3.log('xrandr error="{}"'.format(err)) else: layout[state][output] = {"infos": infos, "mode": mode, "state": state} # initialize the active layout if self.active_layout is None: self.active_comb = tuple(active_layout) self.active_layout = self._get_string_and_set_width( tuple(active_layout), self.active_mode ) return layout
python
{ "resource": "" }
q34949
Py3status._set_available_combinations
train
def _set_available_combinations(self): """ Generate all connected outputs combinations and set the max display width while iterating. """ available = set() combinations_map = {} whitelist = None if self.output_combinations: whitelist = self.output_combinations.split("|") self.max_width = 0 for output in range(len(self.layout["connected"])): for comb in combinations(self.layout["connected"], output + 1): for mode in ["clone", "extend"]: string = self._get_string_and_set_width(comb, mode) if whitelist and string not in whitelist: continue if len(comb) == 1: combinations_map[string] = (comb, None) else: combinations_map[string] = (comb, mode) available.add(string) # Preserve the order in which user defined the output combinations if whitelist: available = reversed([comb for comb in whitelist if comb in available]) self.available_combinations = deque(available) self.combinations_map = combinations_map
python
{ "resource": "" }
q34950
Py3status._get_string_and_set_width
train
def _get_string_and_set_width(self, combination, mode): """ Construct the string to be displayed and record the max width. """ show = "{}".format(self._separator(mode)).join(combination) show = show.rstrip("{}".format(self._separator(mode))) self.max_width = max([self.max_width, len(show)]) return show
python
{ "resource": "" }
q34951
Py3status._choose_what_to_display
train
def _choose_what_to_display(self, force_refresh=False): """ Choose what combination to display on the bar. By default we try to display the active layout on the first run, else we display the last selected combination. """ for _ in range(len(self.available_combinations)): if ( self.displayed is None and self.available_combinations[0] == self.active_layout ): self.displayed = self.available_combinations[0] break else: if self.displayed == self.available_combinations[0]: break else: self.available_combinations.rotate(1) else: if force_refresh: self.displayed = self.available_combinations[0] else: self.py3.log('xrandr error="displayed combination is not available"')
python
{ "resource": "" }
q34952
Py3status._apply_workspaces
train
def _apply_workspaces(self, combination, mode): """ Allows user to force move a comma separated list of workspaces to the given output when it's activated. Example: - DP1_workspaces = "1,2,3" """ if len(combination) > 1 and mode == "extend": sleep(3) for output in combination: workspaces = getattr(self, "{}_workspaces".format(output), "").split( "," ) for workspace in workspaces: if not workspace: continue # switch to workspace cmd = '{} workspace "{}"'.format(self.py3.get_wm_msg(), workspace) self.py3.command_run(cmd) # move it to output cmd = '{} move workspace to output "{}"'.format( self.py3.get_wm_msg(), output ) self.py3.command_run(cmd) # log this self.py3.log( "moved workspace {} to output {}".format(workspace, output) )
python
{ "resource": "" }
q34953
Py3status._fallback_to_available_output
train
def _fallback_to_available_output(self): """ Fallback to the first available output when the active layout was composed of only one output. This allows us to avoid cases where you get stuck with a black sreen on your laptop by switching back to the integrated screen automatically ! """ if len(self.active_comb) == 1: self._choose_what_to_display(force_refresh=True) self._apply() self.py3.update()
python
{ "resource": "" }
q34954
Py3status._force_force_on_start
train
def _force_force_on_start(self): """ Force the user configured mode on start. """ if self.force_on_start in self.available_combinations: self.displayed = self.force_on_start self._choose_what_to_display(force_refresh=True) self._apply(force=True) self.py3.update() self.force_on_start = None
python
{ "resource": "" }
q34955
Py3status._force_on_change
train
def _force_on_change(self): """ Handle force_on_change feature. """ for layout in self.force_on_change: if layout in self.available_combinations: if self.active_layout != layout: self.displayed = layout self._apply(force=True) self.py3.update() break else: break
python
{ "resource": "" }
q34956
Py3status.xrandr
train
def xrandr(self): """ This is the main py3status method, it will orchestrate what's being displayed on the bar. """ self.layout = self._get_layout() self._set_available_combinations() self._choose_what_to_display() if len(self.available_combinations) < 2 and self.hide_if_single_combination: full_text = self.py3.safe_format(self.format, {"output": ""}) else: if self.fixed_width is True: output = self._center(self.displayed) else: output = self.displayed full_text = self.py3.safe_format(self.format, {"output": output}) response = { "cached_until": self.py3.time_in(self.cache_timeout), "full_text": full_text, } # coloration if self.displayed == self.active_layout: response["color"] = self.py3.COLOR_GOOD elif self.displayed not in self.available_combinations: response["color"] = self.py3.COLOR_BAD # force default layout setup at module startup if self.force_on_start is not None: sleep(1) self._force_force_on_start() # follow on change if not self._no_force_on_change and self.force_on_change: self._force_on_change() # this was a click event triggered update if self._no_force_on_change: self._no_force_on_change = False # fallback detection if self.active_layout not in self.available_combinations: response["color"] = self.py3.COLOR_DEGRADED if self.fallback is True: self._fallback_to_available_output() return response
python
{ "resource": "" }
q34957
Py3status._set_optimal_area
train
def _set_optimal_area(self, data): """ Reduce the zone to reduce the size of fetched data on refresh """ lats = [station["latitude"] for station in data.values()] longs = [station["longitude"] for station in data.values()] self.gps.update( { "gpsTopLatitude": max(lats), "gpsTopLongitude": max(longs), "gpsBotLatitude": min(lats), "gpsBotLongitude": min(longs), } )
python
{ "resource": "" }
q34958
Py3status._get_text
train
def _get_text(self): """ Get the current metadata """ if self._data.get("state") == PLAYING: color = self.py3.COLOR_PLAYING or self.py3.COLOR_GOOD state_symbol = self.state_play elif self._data.get("state") == PAUSED: color = self.py3.COLOR_PAUSED or self.py3.COLOR_DEGRADED state_symbol = self.state_pause else: color = self.py3.COLOR_STOPPED or self.py3.COLOR_BAD state_symbol = self.state_stop if self._data.get("error_occurred"): color = self.py3.COLOR_BAD try: ptime_ms = self._player.Position ptime = _get_time_str(ptime_ms) except Exception: ptime = None if ( self.py3.format_contains(self.format, "time") and self._data.get("state") == PLAYING ): # Don't get trapped in aliasing errors! update = time() + 0.5 else: update = self.py3.CACHE_FOREVER placeholders = { "player": self._data.get("player"), "state": state_symbol, "album": self._data.get("album"), "artist": self._data.get("artist"), "length": self._data.get("length"), "time": ptime, "title": self._data.get("title") or "No Track", "full_name": self._player_details.get("full_name"), # for debugging ;p } return (placeholders, color, update)
python
{ "resource": "" }
q34959
Py3status._set_player
train
def _set_player(self): """ Sort the current players into priority order and set self._player Players are ordered by working state then prefernce supplied by user and finally by instance if a player has more than one running. """ players = [] for name, p in self._mpris_players.items(): # we set the priority here as we need to establish the player name # which might not be immediately available. if "_priority" not in p: if self.player_priority: try: priority = self.player_priority.index(p["name"]) except ValueError: try: priority = self.player_priority.index("*") except ValueError: priority = None else: priority = 0 if priority is not None: p["_priority"] = priority if p.get("_priority") is not None: players.append((p["_state_priority"], p["_priority"], p["index"], name)) if players: top_player = self._mpris_players.get(sorted(players)[0][3]) else: top_player = {} self._player = top_player.get("_dbus_player") self._player_details = top_player self.py3.update()
python
{ "resource": "" }
q34960
Py3status._add_player
train
def _add_player(self, player_id): """ Add player to mpris_players """ if not player_id.startswith(SERVICE_BUS): return False player = self._dbus.get(player_id, SERVICE_BUS_URL) if player.Identity not in self._mpris_names: self._mpris_names[player.Identity] = player_id.split(".")[-1] for p in self._mpris_players.values(): if not p["name"] and p["identity"] in self._mpris_names: p["name"] = self._mpris_names[p["identity"]] p["full_name"] = u"{} {}".format(p["name"], p["index"]) identity = player.Identity name = self._mpris_names.get(identity) if ( self.player_priority != [] and name not in self.player_priority and "*" not in self.player_priority ): return False if identity not in self._mpris_name_index: self._mpris_name_index[identity] = 0 status = player.PlaybackStatus state_priority = WORKING_STATES.index(status) index = self._mpris_name_index[identity] self._mpris_name_index[identity] += 1 try: subscription = player.PropertiesChanged.connect( self._player_monitor(player_id) ) except AttributeError: subscription = {} self._mpris_players[player_id] = { "_dbus_player": player, "_id": player_id, "_state_priority": state_priority, "index": index, "identity": identity, "name": name, "full_name": u"{} {}".format(name, index), "status": status, "subscription": subscription, } return True
python
{ "resource": "" }
q34961
Py3status._remove_player
train
def _remove_player(self, player_id): """ Remove player from mpris_players """ player = self._mpris_players.get(player_id) if player: if player.get("subscription"): player["subscription"].disconnect() del self._mpris_players[player_id]
python
{ "resource": "" }
q34962
Py3status.mpris
train
def mpris(self): """ Get the current output format and return it. """ if self._kill: raise KeyboardInterrupt current_player_id = self._player_details.get("id") cached_until = self.py3.CACHE_FOREVER if self._player is None: text = self.format_none color = self.py3.COLOR_BAD composite = [{"full_text": text, "color": color}] self._data = {} else: self._init_data() (text, color, cached_until) = self._get_text() self._control_states = self._get_control_states() buttons = self._get_response_buttons() composite = self.py3.safe_format(self.format, dict(text, **buttons)) if self._data.get( "error_occurred" ) or current_player_id != self._player_details.get("id"): # Something went wrong or the player changed during our processing # This is usually due to something like a player being killed # whilst we are checking its details # Retry but limit the number of attempts self._tries += 1 if self._tries < 3: return self.mpris() # Max retries hit we need to output something composite = [ {"full_text": "Something went wrong", "color": self.py3.COLOR_BAD} ] cached_until = self.py3.time_in(1) response = { "cached_until": cached_until, "color": color, "composite": composite, } # we are outputing so reset tries self._tries = 0 return response
python
{ "resource": "" }
q34963
Py3status.on_click
train
def on_click(self, event): """ Handles click events """ index = event["index"] button = event["button"] if index not in self._control_states.keys(): if button == self.button_toggle: index = "toggle" elif button == self.button_stop: index = "stop" elif button == self.button_next: index = "next" elif button == self.button_previous: index = "previous" else: return elif button != 1: return try: control_state = self._control_states.get(index) if self._player and self._get_button_state(control_state): getattr(self._player, self._control_states[index]["action"])() except GError as err: self.py3.log(str(err).split(":", 1)[-1])
python
{ "resource": "" }
q34964
Py3status._get_timezone
train
def _get_timezone(self, tz): """ Find and return the time zone if possible """ # special Local timezone if tz == "Local": try: return tzlocal.get_localzone() except pytz.UnknownTimeZoneError: return "?" # we can use a country code to get tz # FIXME this is broken for multi-timezone countries eg US # for now we just grab the first one if len(tz) == 2: try: zones = pytz.country_timezones(tz) except KeyError: return "?" tz = zones[0] # get the timezone try: zone = pytz.timezone(tz) except pytz.UnknownTimeZoneError: return "?" return zone
python
{ "resource": "" }
q34965
setup
train
def setup(sphinx): """ This will be called by sphinx. """ create_auto_documentation() # add the py3status lexer (for code blocks) from sphinx.highlighting import lexers lexers['py3status'] = Py3statusLexer() # enable screenshot directive for dynamic screenshots sphinx.add_directive('screenshot', ScreenshotDirective)
python
{ "resource": "" }
q34966
Py3status._compile_re
train
def _compile_re(self, expression): """ Compile given regular expression for current sanitize words """ meta_words = "|".join(self.sanitize_words) expression = expression.replace("META_WORDS_HERE", meta_words) return re.compile(expression, re.IGNORECASE)
python
{ "resource": "" }
q34967
Py3status._sanitize_title
train
def _sanitize_title(self, title): """ Remove redunant meta data from title and return it """ title = re.sub(self.inside_brackets, "", title) title = re.sub(self.after_delimiter, "", title) return title.strip()
python
{ "resource": "" }
q34968
Py3status.spotify
train
def spotify(self): """ Get the current "artist - title" and return it. """ (text, color) = self._get_text() response = { "cached_until": self.py3.time_in(self.cache_timeout), "color": color, "full_text": text, } return response
python
{ "resource": "" }
q34969
Storage.get_legacy_storage_path
train
def get_legacy_storage_path(self): """ Detect and return existing legacy storage path. """ config_dir = os.path.dirname( self.py3_wrapper.config.get("i3status_config_path", "/tmp") ) storage_path = os.path.join(config_dir, "py3status.data") if os.path.exists(storage_path): return storage_path else: return None
python
{ "resource": "" }
q34970
Storage.save
train
def save(self): """ Save our data to disk. We want to always have a valid file. """ with NamedTemporaryFile( dir=os.path.dirname(self.storage_path), delete=False ) as f: # we use protocol=2 for python 2/3 compatibility dump(self.data, f, protocol=2) f.flush() os.fsync(f.fileno()) tmppath = f.name os.rename(tmppath, self.storage_path)
python
{ "resource": "" }
q34971
Py3status.secs_to_dhms
train
def secs_to_dhms(time_in_secs): """Convert seconds to days, hours, minutes, seconds. Using days as the largest unit of time. Blindly using the days in `time.gmtime()` will fail if it's more than one month (days > 31). """ days = int(time_in_secs / SECS_IN_DAY) remaining_secs = time_in_secs % SECS_IN_DAY hours = int(remaining_secs / SECS_IN_HOUR) remaining_secs = remaining_secs % SECS_IN_HOUR mins = int(remaining_secs / SECS_IN_MIN) secs = int(remaining_secs % SECS_IN_MIN) return days, hours, mins, secs
python
{ "resource": "" }
q34972
Py3status._setup_bar
train
def _setup_bar(self): """ Setup the process bar. """ bar = u"" items_cnt = len(PROGRESS_BAR_ITEMS) bar_val = float(self._time_left) / self._section_time * self.num_progress_bars while bar_val > 0: selector = int(bar_val * items_cnt) selector = min(selector, items_cnt - 1) bar += PROGRESS_BAR_ITEMS[selector] bar_val -= 1 bar = bar.ljust(self.num_progress_bars) return bar
python
{ "resource": "" }
q34973
Py3status.pomodoro
train
def pomodoro(self): """ Pomodoro response handling and countdown """ if not self._initialized: self._init() cached_until = self.py3.time_in(0) if self._running: self._time_left = ceil(self._end_time - time()) time_left = ceil(self._time_left) else: time_left = ceil(self._time_left) vals = {"ss": int(time_left), "mm": int(ceil(time_left / 60))} if self.py3.format_contains(self.format, "mmss"): hours, rest = divmod(time_left, 3600) mins, seconds = divmod(rest, 60) if hours: vals["mmss"] = u"%d%s%02d%s%02d" % ( hours, self.format_separator, mins, self.format_separator, seconds, ) else: vals["mmss"] = u"%d%s%02d" % (mins, self.format_separator, seconds) if self.py3.format_contains(self.format, "bar"): vals["bar"] = self._setup_bar() formatted = self.format.format(**vals) if self._running: if self._active: format = self.format_active else: format = self.format_break else: if self._active: format = self.format_stopped else: format = self.format_break_stopped cached_until = self.py3.CACHE_FOREVER response = { "full_text": format.format( breakno=self._break_number, format=formatted, **vals ), "cached_until": cached_until, } if self._alert: response["urgent"] = True self._alert = False if not self._running: response["color"] = self.py3.COLOR_BAD else: if self._active: response["color"] = self.py3.COLOR_GOOD else: response["color"] = self.py3.COLOR_DEGRADED return response
python
{ "resource": "" }
q34974
UdevMonitor._setup_pyudev_monitoring
train
def _setup_pyudev_monitoring(self): """ Setup the udev monitor. """ context = pyudev.Context() monitor = pyudev.Monitor.from_netlink(context) self.udev_observer = pyudev.MonitorObserver(monitor, self._udev_event) self.udev_observer.start() self.py3_wrapper.log("udev monitoring enabled")
python
{ "resource": "" }
q34975
UdevMonitor.subscribe
train
def subscribe(self, py3_module, trigger_action, subsystem): """ Subscribe the given module to the given udev subsystem. Here we will lazy load the monitor if necessary and return success or failure based on the availability of pyudev. """ if self.pyudev_available: # lazy load the udev monitor if self.udev_observer is None: self._setup_pyudev_monitoring() if trigger_action not in ON_TRIGGER_ACTIONS: self.py3_wrapper.log( "module %s: invalid action %s on udev events subscription" % (py3_module.module_full_name, trigger_action) ) return False self.udev_consumers[subsystem].append((py3_module, trigger_action)) self.py3_wrapper.log( "module %s subscribed to udev events on %s" % (py3_module.module_full_name, subsystem) ) return True else: self.py3_wrapper.log( "pyudev module not installed: module %s not subscribed to events on %s" % (py3_module.module_full_name, subsystem) ) return False
python
{ "resource": "" }
q34976
UdevMonitor.trigger_actions
train
def trigger_actions(self, subsystem): """ Refresh all modules which subscribed to the given subsystem. """ for py3_module, trigger_action in self.udev_consumers[subsystem]: if trigger_action in ON_TRIGGER_ACTIONS: self.py3_wrapper.log( "%s udev event, refresh consumer %s" % (subsystem, py3_module.module_full_name) ) py3_module.force_update()
python
{ "resource": "" }
q34977
I3statusModule.run
train
def run(self): """ updates the modules output. Currently only time and tztime need to do this """ if self.update_time_value(): self.i3status.py3_wrapper.notify_update(self.module_name) due_time = self.py3.time_in(sync_to=self.time_delta) self.i3status.py3_wrapper.timeout_queue_add(self, due_time)
python
{ "resource": "" }
q34978
I3statusModule.update_from_item
train
def update_from_item(self, item): """ Update from i3status output. returns if item has changed. """ if not self.is_time_module: # correct the output # Restore the name/instance. item["name"] = self.name item["instance"] = self.instance # change color good/bad is set specifically for module if "color" in item and item["color"] in self.color_map: item["color"] = self.color_map[item["color"]] # have we updated? is_updated = self.item != item self.item = item else: # If no timezone or a minute has passed update timezone t = time() if self.time_zone_check_due < t: # If we are late for our timezone update then schedule the next # update to happen when we next get new data from i3status interval = self.i3status.update_interval if not self.set_time_zone(item): # we had an issue with an invalid time zone probably due to # suspending. re check the time zone when we next can. self.time_zone_check_due = 0 elif self.time_zone_check_due and ( t - self.time_zone_check_due > 5 + interval ): self.time_zone_check_due = 0 else: # Check again in 30 mins. We do this in case the timezone # used has switched to/from summer time self.time_zone_check_due = ((int(t) // 1800) * 1800) + 1800 if not self.time_started: self.time_started = True self.i3status.py3_wrapper.timeout_queue_add(self) is_updated = False # update time to be shown return is_updated
python
{ "resource": "" }
q34979
I3statusModule.set_time_zone
train
def set_time_zone(self, item): """ Work out the time zone and create a shim tzinfo. We return True if all is good or False if there was an issue and we need to re check the time zone. see issue #1375 """ # parse i3status date i3s_time = item["full_text"].encode("UTF-8", "replace") try: # python3 compatibility code i3s_time = i3s_time.decode() except: # noqa e722 pass # get datetime and time zone info parts = i3s_time.split() i3s_datetime = " ".join(parts[:2]) # occassionally we do not get the timezone name if len(parts) < 3: return True else: i3s_time_tz = parts[2] date = datetime.strptime(i3s_datetime, TIME_FORMAT) # calculate the time delta utcnow = datetime.utcnow() delta = datetime( date.year, date.month, date.day, date.hour, date.minute ) - datetime(utcnow.year, utcnow.month, utcnow.day, utcnow.hour, utcnow.minute) # create our custom timezone try: self.tz = Tz(i3s_time_tz, delta) except ValueError: return False return True
python
{ "resource": "" }
q34980
I3status.setup
train
def setup(self): """ Do any setup work needed to run i3status modules """ for conf_name in self.py3_config["i3s_modules"]: module = I3statusModule(conf_name, self) self.i3modules[conf_name] = module if module.is_time_module: self.time_modules.append(module)
python
{ "resource": "" }
q34981
I3status.valid_config_param
train
def valid_config_param(self, param_name, cleanup=False): """ Check if a given section name is a valid parameter for i3status. """ if cleanup: valid_config_params = [ _ for _ in self.i3status_module_names if _ not in ["cpu_usage", "ddate", "ipv6", "load", "time"] ] else: valid_config_params = self.i3status_module_names + ["general", "order"] return param_name.split(" ")[0] in valid_config_params
python
{ "resource": "" }
q34982
I3status.set_responses
train
def set_responses(self, json_list): """ Set the given i3status responses on their respective configuration. """ self.update_json_list() updates = [] for index, item in enumerate(self.json_list): conf_name = self.py3_config["i3s_modules"][index] module = self.i3modules[conf_name] if module.update_from_item(item): updates.append(conf_name) if updates: self.py3_wrapper.notify_update(updates)
python
{ "resource": "" }
q34983
I3status.write_in_tmpfile
train
def write_in_tmpfile(text, tmpfile): """ Write the given text in the given tmpfile in python2 and python3. """ try: tmpfile.write(text) except TypeError: tmpfile.write(str.encode(text)) except UnicodeEncodeError: tmpfile.write(text.encode("utf-8"))
python
{ "resource": "" }
q34984
I3status.write_tmp_i3status_config
train
def write_tmp_i3status_config(self, tmpfile): """ Given a temporary file descriptor, write a valid i3status config file based on the parsed one from 'i3status_config_path'. """ # order += ... for module in self.py3_config["i3s_modules"]: self.write_in_tmpfile('order += "%s"\n' % module, tmpfile) self.write_in_tmpfile("\n", tmpfile) # config params for general section and each module for section_name in ["general"] + self.py3_config["i3s_modules"]: section = self.py3_config[section_name] self.write_in_tmpfile("%s {\n" % section_name, tmpfile) for key, value in section.items(): # don't include color values except in the general section if key.startswith("color"): if ( section_name.split(" ")[0] not in I3S_COLOR_MODULES or key not in I3S_ALLOWED_COLORS ): continue # Set known fixed format for time and tztime so we can work # out the timezone if section_name.split()[0] in TIME_MODULES: if key == "format": value = TZTIME_FORMAT if key == "format_time": continue if isinstance(value, bool): value = "{}".format(value).lower() self.write_in_tmpfile(' %s = "%s"\n' % (key, value), tmpfile) self.write_in_tmpfile("}\n\n", tmpfile) tmpfile.flush()
python
{ "resource": "" }
q34985
I3status.spawn_i3status
train
def spawn_i3status(self): """ Spawn i3status using a self generated config file and poll its output. """ try: with NamedTemporaryFile(prefix="py3status_") as tmpfile: self.write_tmp_i3status_config(tmpfile) i3status_pipe = Popen( [self.i3status_path, "-c", tmpfile.name], stdout=PIPE, stderr=PIPE, # Ignore the SIGTSTP signal for this subprocess preexec_fn=lambda: signal(SIGTSTP, SIG_IGN), ) self.py3_wrapper.log( "i3status spawned using config file {}".format(tmpfile.name) ) self.poller_inp = IOPoller(i3status_pipe.stdout) self.poller_err = IOPoller(i3status_pipe.stderr) self.tmpfile_path = tmpfile.name # Store the pipe so we can signal it self.i3status_pipe = i3status_pipe try: # loop on i3status output while self.py3_wrapper.running: line = self.poller_inp.readline() if line: # remove leading comma if present if line[0] == ",": line = line[1:] if line.startswith("[{"): json_list = loads(line) self.last_output = json_list self.set_responses(json_list) self.ready = True else: err = self.poller_err.readline() code = i3status_pipe.poll() if code is not None: msg = "i3status died" if err: msg += " and said: {}".format(err) else: msg += " with code {}".format(code) raise IOError(msg) except IOError: err = sys.exc_info()[1] self.error = err self.py3_wrapper.log(err, "error") except OSError: self.error = "Problem starting i3status maybe it is not installed" except Exception: self.py3_wrapper.report_exception("", notify_user=True) self.i3status_pipe = None
python
{ "resource": "" }
q34986
catch_factory
train
def catch_factory(attr): """ Factory returning a catch function """ def _catch(s, *args, **kw): """ This is used to catch and process all calls. """ def process(value): """ return the actual value after processing """ if attr.startswith("__"): # __repr__, __str__ etc return getattr(value, attr)(*args, **kw) else: # upper, lower etc return getattr(u"".__class__, attr)(value, *args, **kw) stack = inspect.stack() mod = inspect.getmodule(stack[1][0]) # We are called from the owning module so allow if mod.__name__.split(".")[-1] == s._module_name: return process(s._value) # very shallow calling no stack if len(stack) < 3: return process(s._private) # Check if this is an internal or external module. We need to allow # calls to modules like requests etc remote = not inspect.getmodule(stack[2][0]).__name__.startswith("py3status") valid = False # go through the stack to see how we came through the code for frame in stack[2:]: mod = inspect.getmodule(frame[0]) if remote and mod.__name__.split(".")[-1] == s._module_name: # the call to an external module started in the correct module # so allow this usage valid = True break if mod.__name__ == "py3status.py3" and frame[3] == "request": # Py3.request has special needs due so it is allowed to access # private variables. valid = True break if mod.__name__.startswith("py3status"): # We were somewhere else in py3status than the module, maybe we # are doing some logging. Prevent usage return process(s._private) if valid: return process(s._value) return process(s._private) return _catch
python
{ "resource": "" }
q34987
Py3status._github_count
train
def _github_count(self, url): """ Get counts for requests that return 'total_count' in the json response. """ url = self.url_api + url + "&per_page=1" # if we have authentication details use them as we get better # rate-limiting. if self.username and self.auth_token: auth = (self.username, self.auth_token) else: auth = None try: info = self.py3.request(url, auth=auth) except (self.py3.RequestException): return if info and info.status_code == 200: return int(info.json()["total_count"]) if info.status_code == 422: if not self.repo_warning: self.py3.notify_user("Github repo cannot be found.") self.repo_warning = True return "?"
python
{ "resource": "" }
q34988
Py3status._notifications
train
def _notifications(self): """ Get the number of unread notifications. """ if not self.username or not self.auth_token: if not self.notification_warning: self.py3.notify_user( "Github module needs username and " "auth_token to check notifications." ) self.notification_warning = True return "?" if self.notifications == "all" or not self.repo: url = self.url_api + "/notifications" else: url = self.url_api + "/repos/" + self.repo + "/notifications" url += "?per_page=100" try: info = self.py3.request(url, auth=(self.username, self.auth_token)) except (self.py3.RequestException): return if info.status_code == 200: links = info.headers.get("Link") if not links: return len(info.json()) last_page = 1 for link in links.split(","): if 'rel="last"' in link: last_url = link[link.find("<") + 1 : link.find(">")] parsed = urlparse.urlparse(last_url) last_page = int(urlparse.parse_qs(parsed.query)["page"][0]) if last_page == 1: return len(info.json()) try: last_page_info = self.py3.request( last_url, auth=(self.username, self.auth_token) ) except self.py3.RequestException: return return len(info.json()) * (last_page - 1) + len(last_page_info.json()) if info.status_code == 404: if not self.repo_warning: self.py3.notify_user("Github repo cannot be found.") self.repo_warning = True
python
{ "resource": "" }
q34989
Common.get_config_attribute
train
def get_config_attribute(self, name, attribute): """ Look for the attribute in the config. Start with the named module and then walk up through any containing group and then try the general section of the config. """ # A user can set a param to None in the config to prevent a param # being used. This is important when modules do something like # # color = self.py3.COLOR_MUTED or self.py3.COLOR_BAD config = self.config["py3_config"] param = config[name].get(attribute, self.none_setting) if hasattr(param, "none_setting") and name in config[".module_groups"]: for module in config[".module_groups"][name]: if attribute in config.get(module, {}): param = config[module].get(attribute) break if hasattr(param, "none_setting"): # check py3status config section param = config["py3status"].get(attribute, self.none_setting) if hasattr(param, "none_setting"): # check py3status general section param = config["general"].get(attribute, self.none_setting) if param and (attribute == "color" or attribute.startswith("color_")): if param[0] != "#": # named color param = COLOR_NAMES.get(param.lower(), self.none_setting) elif len(param) == 4: # This is a color like #123 convert it to #112233 param = ( "#" + param[1] + param[1] + param[2] + param[2] + param[3] + param[3] ) return param
python
{ "resource": "" }
q34990
Py3statusWrapper.timeout_queue_add
train
def timeout_queue_add(self, item, cache_time=0): """ Add a item to be run at a future time. This must be a Module, I3statusModule or a Task """ # add the info to the add queue. We do this so that actually adding # the module is done in the core thread. self.timeout_add_queue.append((item, cache_time)) # if the timeout_add_queue is not due to be processed until after this # update request is due then trigger an update now. if self.timeout_due is None or cache_time < self.timeout_due: self.update_request.set()
python
{ "resource": "" }
q34991
Py3statusWrapper.timeout_process_add_queue
train
def timeout_process_add_queue(self, module, cache_time): """ Add a module to the timeout_queue if it is scheduled in the future or if it is due for an update immediately just trigger that. the timeout_queue is a dict with the scheduled time as the key and the value is a list of module instance names due to be updated at that point. An ordered list of keys is kept to allow easy checking of when updates are due. A list is also kept of which modules are in the update_queue to save having to search for modules in it unless needed. """ # If already set to update do nothing if module in self.timeout_update_due: return # remove if already in the queue key = self.timeout_queue_lookup.get(module) if key: queue_item = self.timeout_queue[key] queue_item.remove(module) if not queue_item: del self.timeout_queue[key] self.timeout_keys.remove(key) if cache_time == 0: # if cache_time is 0 we can just trigger the module update self.timeout_update_due.append(module) self.timeout_queue_lookup[module] = None else: # add the module to the timeout queue if cache_time not in self.timeout_keys: self.timeout_queue[cache_time] = set([module]) self.timeout_keys.append(cache_time) # sort keys so earliest is first self.timeout_keys.sort() # when is next timeout due? try: self.timeout_due = self.timeout_keys[0] except IndexError: self.timeout_due = None else: self.timeout_queue[cache_time].add(module) # note that the module is in the timeout_queue self.timeout_queue_lookup[module] = cache_time
python
{ "resource": "" }
q34992
Py3statusWrapper.timeout_queue_process
train
def timeout_queue_process(self): """ Check the timeout_queue and set any due modules to update. """ # process any items that need adding to the queue while self.timeout_add_queue: self.timeout_process_add_queue(*self.timeout_add_queue.popleft()) now = time.time() due_timeouts = [] # find any due timeouts for timeout in self.timeout_keys: if timeout > now: break due_timeouts.append(timeout) if due_timeouts: # process them for timeout in due_timeouts: modules = self.timeout_queue[timeout] # remove from the queue del self.timeout_queue[timeout] self.timeout_keys.remove(timeout) for module in modules: # module no longer in queue del self.timeout_queue_lookup[module] # tell module to update self.timeout_update_due.append(module) # when is next timeout due? try: self.timeout_due = self.timeout_keys[0] except IndexError: self.timeout_due = None # process any finished modules. # Now that the module has finished running it may have been marked to # be triggered again. This is most likely to happen when events are # being processed and the events are arriving much faster than the # module can handle them. It is important as a module may handle # events but not trigger the module update. If during the event the # module is due to update the update is not actioned but it needs to be # once the events have finished or else the module will no longer # continue to update. while self.timeout_finished: module_name = self.timeout_finished.popleft() self.timeout_running.discard(module_name) if module_name in self.timeout_missed: module = self.timeout_missed.pop(module_name) self.timeout_update_due.append(module) # run any modules that are due while self.timeout_update_due: module = self.timeout_update_due.popleft() module_name = getattr(module, "module_full_name", None) # if the module is running then we do not want to trigger it but # instead wait till it has finished running and then trigger if module_name and module_name in self.timeout_running: self.timeout_missed[module_name] = module else: self.timeout_running.add(module_name) Runner(module, self, module_name) # we return how long till we next need to process the timeout_queue if self.timeout_due is not None: return self.timeout_due - time.time()
python
{ "resource": "" }
q34993
Py3statusWrapper.gevent_monkey_patch_report
train
def gevent_monkey_patch_report(self): """ Report effective gevent monkey patching on the logs. """ try: import gevent.socket import socket if gevent.socket.socket is socket.socket: self.log("gevent monkey patching is active") return True else: self.notify_user("gevent monkey patching failed.") except ImportError: self.notify_user("gevent is not installed, monkey patching failed.") return False
python
{ "resource": "" }
q34994
Py3statusWrapper.get_user_modules
train
def get_user_modules(self): """ Search configured include directories for user provided modules. user_modules: { 'weather_yahoo': ('~/i3/py3status/', 'weather_yahoo.py') } """ user_modules = {} for include_path in self.config["include_paths"]: for f_name in sorted(os.listdir(include_path)): if not f_name.endswith(".py"): continue module_name = f_name[:-3] # do not overwrite modules if already found if module_name in user_modules: pass user_modules[module_name] = (include_path, f_name) return user_modules
python
{ "resource": "" }
q34995
Py3statusWrapper.get_user_configured_modules
train
def get_user_configured_modules(self): """ Get a dict of all available and configured py3status modules in the user's i3status.conf. """ user_modules = {} if not self.py3_modules: return user_modules for module_name, module_info in self.get_user_modules().items(): for module in self.py3_modules: if module_name == module.split(" ")[0]: include_path, f_name = module_info user_modules[module_name] = (include_path, f_name) return user_modules
python
{ "resource": "" }
q34996
Py3statusWrapper.notify_user
train
def notify_user( self, msg, level="error", rate_limit=None, module_name="", icon=None, title="py3status", ): """ Display notification to user via i3-nagbar or send-notify We also make sure to log anything to keep trace of it. NOTE: Message should end with a '.' for consistency. """ dbus = self.config.get("dbus_notify") if dbus: # force msg, icon, title to be a string title = u"{}".format(title) msg = u"{}".format(msg) if icon: icon = u"{}".format(icon) else: msg = u"py3status: {}".format(msg) if level != "info" and module_name == "": fix_msg = u"{} Please try to fix this and reload i3wm (Mod+Shift+R)" msg = fix_msg.format(msg) # Rate limiting. If rate limiting then we need to calculate the time # period for which the message should not be repeated. We just use # A simple chunked time model where a message cannot be repeated in a # given time period. Messages can be repeated more frequently but must # be in different time periods. limit_key = "" if rate_limit: try: limit_key = time.time() // rate_limit except TypeError: pass # We use a hash to see if the message is being repeated. This is crude # and imperfect but should work for our needs. msg_hash = hash(u"{}#{}#{}#{}".format(module_name, limit_key, msg, title)) if msg_hash in self.notified_messages: return elif module_name: log_msg = 'Module `%s` sent a notification. "%s: %s"' % ( module_name, title, msg, ) self.log(log_msg, level) else: self.log(msg, level) self.notified_messages.add(msg_hash) try: if dbus: # fix any html entities msg = msg.replace("&", "&amp;") msg = msg.replace("<", "&lt;") msg = msg.replace(">", "&gt;") cmd = ["notify-send"] if icon: cmd += ["-i", icon] cmd += ["-u", DBUS_LEVELS.get(level, "normal"), "-t", "10000"] cmd += [title, msg] else: py3_config = self.config.get("py3_config", {}) nagbar_font = py3_config.get("py3status", {}).get("nagbar_font") wm_nag = self.config["wm"]["nag"] cmd = [wm_nag, "-m", msg, "-t", level] if nagbar_font: cmd += ["-f", nagbar_font] Popen(cmd, stdout=open("/dev/null", "w"), stderr=open("/dev/null", "w")) except Exception as err: self.log("notify_user error: %s" % err)
python
{ "resource": "" }
q34997
Py3statusWrapper.stop
train
def stop(self): """ Set the Event lock, this will break all threads' loops. """ self.running = False # stop the command server try: self.commands_thread.kill() except: # noqa e722 pass try: self.lock.set() if self.config["debug"]: self.log("lock set, exiting") # run kill() method on all py3status modules for module in self.modules.values(): module.kill() except: # noqa e722 pass
python
{ "resource": "" }
q34998
Py3statusWrapper.refresh_modules
train
def refresh_modules(self, module_string=None, exact=True): """ Update modules. if module_string is None all modules are refreshed if module_string then modules with the exact name or those starting with the given string depending on exact parameter will be refreshed. If a module is an i3status one then we refresh i3status. To prevent abuse, we rate limit this function to 100ms for full refreshes. """ if not module_string: if time.time() > (self.last_refresh_ts + 0.1): self.last_refresh_ts = time.time() else: # rate limiting return update_i3status = False for name, module in self.output_modules.items(): if ( module_string is None or (exact and name == module_string) or (not exact and name.startswith(module_string)) ): if module["type"] == "py3status": if self.config["debug"]: self.log("refresh py3status module {}".format(name)) module["module"].force_update() else: if self.config["debug"]: self.log("refresh i3status module {}".format(name)) update_i3status = True if update_i3status: self.i3status_thread.refresh_i3status()
python
{ "resource": "" }
q34999
Py3statusWrapper.notify_update
train
def notify_update(self, update, urgent=False): """ Name or list of names of modules that have updated. """ if not isinstance(update, list): update = [update] self.update_queue.extend(update) # find containers that use the modules that updated containers = self.config["py3_config"][".module_groups"] containers_to_update = set() for item in update: if item in containers: containers_to_update.update(set(containers[item])) # force containers to update for container in containers_to_update: container_module = self.output_modules.get(container) if container_module: # If the container registered a urgent_function then call it # if this update is urgent. if urgent and container_module.get("urgent_function"): container_module["urgent_function"](update) # If a container has registered a content_function we use that # to see if the container needs to be updated. # We only need to update containers if their active content has # changed. if container_module.get("content_function"): if set(update) & container_module["content_function"](): container_module["module"].force_update() else: # we don't know so just update. container_module["module"].force_update() # we need to update the output if self.update_queue: self.update_request.set()
python
{ "resource": "" }