text
stringlengths
81
112k
Yield the dynamic DNS records associated with this account. :param credentials: an AfraidCredentials instance :param url: the service URL def records(credentials, url="https://freedns.afraid.org/api/"): """ Yield the dynamic DNS records associated with this account. :param credentials: an AfraidC...
Update remote DNS record by requesting its special endpoint URL. This automatically picks the IP address using the HTTP connection: it is not possible to specify the IP address explicitly. :param url: URL to retrieve for triggering the update :return: IP address def update(url): """ Update re...
Return sha, lazily compute if not done yet. def sha(self): """Return sha, lazily compute if not done yet.""" if self._sha is None: self._sha = compute_auth_key(self.userid, self.password) return self._sha
Update the IP on the remote service. def update(self, *args, **kwargs): """Update the IP on the remote service.""" # first find the update_url for the provided account + hostname: update_url = next((r.update_url for r in records(self._credentials, self._url) ...
Register a listener function. :param observer: external listener function :param events: tuple or list of relevant events (default=None) def register_observer(self, observer, events=None): """Register a listener function. :param observer: external listener function :param even...
Notify observers. def notify_observers(self, event=None, msg=None): """Notify observers.""" for observer, events in list(self._observers.items()): # LOG.debug("trying to notify the observer") if events is None or event is None or event in events: try: ...
Detect the IP address. def detect(self): """Detect the IP address.""" if self.opts_family == AF_INET6: kind = IPV6_PUBLIC else: # 'INET': kind = IPV4 theip = None try: theip = detect_ip(kind) except GetIpException: LOG.exc...
Use the netifaces module to detect ifconfig information. def _detect(self): """Use the netifaces module to detect ifconfig information.""" theip = None try: if self.opts_family == AF_INET6: addrlist = netifaces.ifaddresses(self.opts_iface)[netifaces.AF_INET6] ...
Clean up temporary test dirs for passed tests. Leave failed test dirs for manual inspection. def clean_tempdir(context, scenario): """ Clean up temporary test dirs for passed tests. Leave failed test dirs for manual inspection. """ tempdir = getattr(context, 'tempdir', None) if tempdir a...
Check if the given ip address is in a reserved ipv4 address space. :param ip: ip address :return: boolean def is_reserved_ip(self, ip): """Check if the given ip address is in a reserved ipv4 address space. :param ip: ip address :return: boolean """ theip = ipad...
Return a randomly generated, public IPv4 address. :return: ip address def random_public_ip(self): """Return a randomly generated, public IPv4 address. :return: ip address """ randomip = random_ip() while self.is_reserved_ip(randomip): randomip = random_ip()...
Detect IP and return it. def detect(self): """Detect IP and return it.""" for theip in self.rips: LOG.debug("detected %s", str(theip)) self.set_current_value(str(theip)) return str(theip)
Update the IP on the remote service. def update(self, ip): """Update the IP on the remote service.""" timeout = 60 LOG.debug("Updating '%s' to '%s' at service '%s'", self.hostname, ip, self._updateurl) params = {"myip": ip, "hostname": self.hostname} req = requests.get(self._upd...
Return a git reference to patches branch base. Returns first part of .spec's patches_base is found, otherwise return Version(+%{milestone}). def patches_base_ref(default=exception.CantGuess): """Return a git reference to patches branch base. Returns first part of .spec's patches_base is found, ot...
Displays a list of items along with the index to enable a user to select an item. def display_listitems(items, url): '''Displays a list of items along with the index to enable a user to select an item. ''' if (len(items) == 2 and items[0].get_label() == '..' and items[1].get_played()): ...
Prints a message for a playing video and displays the parent listitem. def display_video(items): '''Prints a message for a playing video and displays the parent listitem. ''' parent_item, played_item = items title_line = 'Playing Media %s (%s)' % (played_item.get_label(), ...
Returns the selected item from provided items or None if 'q' was entered for quit. def get_user_choice(items): '''Returns the selected item from provided items or None if 'q' was entered for quit. ''' choice = raw_input('Choose an item or "q" to quit: ') while choice != 'q': try: ...
Decode data employing some charset detection and including unicode BOM stripping. def decode(data): """ Decode data employing some charset detection and including unicode BOM stripping. """ if isinstance(data, unicode): return data # Detect standard unicode BOMs. for bom, enco...
Returns a tuple containing the context for a line def get_context(self, line=1, column=0): 'Returns a tuple containing the context for a line' line -= 1 # The line is one-based # If there is no data in the file, there can be no context. datalen = len(self.data) if datalen <= ...
Formats a line from the data to be the appropriate length def _format_line(self, data, column=0, rel_line=1): 'Formats a line from the data to be the appropriate length' line_length = len(data) if line_length > 140: if rel_line == 0: # Trim from the beginning ...
Returns the line number that the given string position is found on def get_line(self, position): 'Returns the line number that the given string position is found on' datalen = len(self.data) count = len(self.data[0]) line = 1 while count < position: if line >= datal...
This is not an official XBMC method, it is here to faciliate mocking up the other methods when running outside of XBMC. def load_addon_strings(addon, filename): '''This is not an official XBMC method, it is here to faciliate mocking up the other methods when running outside of XBMC.''' def get_strings(...
Parses an addon id from the given addon.xml filename. def get_addon_id(addonxml): '''Parses an addon id from the given addon.xml filename.''' xml = parse(addonxml) addon_node = xml.getElementsByTagName('addon')[0] return addon_node.getAttribute('id')
Parses an addon name from the given addon.xml filename. def get_addon_name(addonxml): '''Parses an addon name from the given addon.xml filename.''' xml = parse(addonxml) addon_node = xml.getElementsByTagName('addon')[0] return addon_node.getAttribute('name')
Creates necessary directories for the given path or does nothing if the directories already exist. def _create_dir(path): '''Creates necessary directories for the given path or does nothing if the directories already exist. ''' try: os.makedirs(path) except OSError, exc: if exc....
Creates folders in the OS's temp directory. Doesn't touch any possible XBMC installation on the machine. Attempting to do as little work as possible to enable this function to work seamlessly. def translatePath(path): '''Creates folders in the OS's temp directory. Doesn't touch any possible XBMC instal...
Handles setup of the plugin state, including request arguments, handle, mode. This method never needs to be called directly. For testing, see plugin.test() def _parse_request(self, url=None, handle=None): '''Handles setup of the plugin state, including request arguments, handle...
Registers a module with a plugin. Requires a url_prefix that will then enable calls to url_for. :param module: Should be an instance `xbmcswift2.Module`. :param url_prefix: A url prefix to use for all module urls, e.g. '/mymodule' def register_module(self, module, ur...
A decorator to add a route to a view and also apply caching. The url_rule, name and options arguments are the same arguments for the route function. The TTL argument if given will passed along to the caching decorator. def cached_route(self, url_rule, name=None, options=None, TTL=None): ...
A decorator to add a route to a view. name is used to differentiate when there are multiple routes for a given view. def route(self, url_rule, name=None, options=None): '''A decorator to add a route to a view. name is used to differentiate when there are multiple routes for a given view.''' ...
This method adds a URL rule for routing purposes. The provided name can be different from the view function name if desired. The provided name is what is used in url_for to build a URL. The route decorator provides the same functionality. def add_url_rule(self, url_rule, view_func, nam...
Returns a valid XBMC plugin URL for the given endpoint name. endpoint can be the literal name of a function, or it can correspond to the name keyword arguments passed to the route decorator. Raises AmbiguousUrlException if there is more than one possible view for the given endpo...
Used when you need to redirect to another view, and you only have the final plugin:// url. def redirect(self, url): '''Used when you need to redirect to another view, and you only have the final plugin:// url.''' # TODO: Should we be overriding self.request with the new request? ...
The main entry point for a plugin. def run(self, test=False): '''The main entry point for a plugin.''' self._request = self._parse_request() log.debug('Handling incoming request for %s', self.request.path) items = self._dispatch(self.request.path) # Close any open storages whic...
The entry point for the console script xbmcswift2. The 'xbcmswift2' script is command bassed, so the second argument is always the command to execute. Each command has its own parser options and usages. If no command is provided or the -h flag is used without any other commands, the general help messag...
Adds escape sequences to colorize text and make it beautiful. To colorize text, prefix the text you want to color with the color (capitalized) wrapped in double angle brackets (i.e.: <<GREEN>>). End your string with <<NORMAL>>. If you don't, it will be done for you (assuming you used a c...
Uses curses to print in the fanciest way possible. def write(self, text): 'Uses curses to print in the fanciest way possible.' # Add color to the terminal. if not self.no_color: text = self.colorize_text(text) else: pattern = re.compile('\<\<[A-Z]*?\>\>') ...
Talk to Cleverbot. Arguments: input: The input argument is what you want to say to Cleverbot, such as "hello". tweak1-3: Changes Cleverbot's mood. **kwargs: Keyword arguments to update the request parameters with. Returns: Cleverbot's rep...
(pidfile:str) -> int | None Returns an int found in the named file, if there is one, and if there is a running process with that process id. Return None if no such process exists. def live_pidfile(pidfile): # pragma: no cover """(pidfile:str) -> int | None Returns an int found in the named file, if...
Attempts to turn a SIGTERM exception into a SystemExit exception. def _turn_sigterm_into_systemexit(): # pragma: no cover """ Attempts to turn a SIGTERM exception into a SystemExit exception. """ try: import signal except ImportError: return def handle_term(signo, frame): ...
Entry point for wsgiref's WSGI server Additional parameters: ``certfile``, ``keyfile`` Optional SSL certificate file and host key file names. You can generate self-signed test files as follows: $ openssl genrsa 1024 > keyfile $ chmod 400 keyfile $ openssl ...
Entry point for CherryPy's WSGI server Serves the specified WSGI app via CherryPyWSGIServer. ``app`` The WSGI 'application callable'; multiple WSGI applications may be passed as (script_name, callable) pairs. ``host`` This is the ipaddress to bind to (or a hostname if your ...
Given variables like ``['a=b', 'c=d']`` turns it into ``{'a': 'b', 'c': 'd'}`` def parse_vars(self, args): """ Given variables like ``['a=b', 'c=d']`` turns it into ``{'a': 'b', 'c': 'd'}`` """ result = {} for arg in args: if '=' not in arg: ...
Get proper arguments for re-running the command. This is primarily for fixing some issues under Windows. First, there was a bug in Windows when running an executable located at a path with a space in it. This has become a non-issue with current versions of Python and Windows, s...
Main function. Handles delegation to other functions. def main(): 'Main function. Handles delegation to other functions.' logging.basicConfig() type_choices = {'any': constants.PACKAGE_ANY, 'extension': constants.PACKAGE_EXTENSION, 'theme': constants.PACKAGE_THEME,...
Returns a dictionary of file information def package_contents(self): 'Returns a dictionary of file information' if self.contents_cache: return self.contents_cache # Get a list of ZipInfo objects. files = self.zf.infolist() out_files = {} # Iterate through ...
Write a blob of data to the XPI manager. def write(self, name, data): """Write a blob of data to the XPI manager.""" if isinstance(data, StringIO): self.zf.writestr(name, data.getvalue()) else: self.zf.writestr(name, to_utf8(data))
Write the contents of a file from the disk to the XPI. def write_file(self, name, path=None): """Write the contents of a file from the disk to the XPI.""" if path is None: path = name self.zf.write(path, name)
Appends key/val pairs to the end of a URL. Useful for passing arbitrary HTTP headers to XBMC to be used when fetching a media resource, e.g. cookies. def xbmc_url(url, **options): '''Appends key/val pairs to the end of a URL. Useful for passing arbitrary HTTP headers to XBMC to be used when fetching a ...
An enum class to mirror XBMC constatns. All args and kwargs.keys are added as atrrs on the returned object. >>> States = enum('NEW_JERSEY', NY='NEW_YORK') >>> States.NY 'NEW_YORK' >>> States.NEW_JERSEY 'NEW_JERSEY' >>> States._fields ['NY', 'NEW_JERSEY'] def enum(*args, **kwargs): ...
Returns a dict where items with a None value are removed def clean_dict(dct): '''Returns a dict where items with a None value are removed''' return dict((key, val) for key, val in dct.items() if val is not None)
Returns a new dictionary where values which aren't instances of basestring are pickled. Also, a new key '_pickled' contains a comma separated list of keys corresponding to the pickled values. def pickle_dict(items): '''Returns a new dictionary where values which aren't instances of basestring are pickl...
Takes a dict and unpickles values whose keys are found in '_pickled' key. >>> unpickle_args({'_pickled': ['foo']. 'foo': ['I3%0A.']}) {'foo': 3} def unpickle_args(items): '''Takes a dict and unpickles values whose keys are found in '_pickled' key. >>> unpickle_args({'_pickled': ['foo']. 'foo'...
Returns a dict pickled with pickle_dict def unpickle_dict(items): '''Returns a dict pickled with pickle_dict''' pickled_keys = items.pop('_pickled', '').split(',') ret = {} for key, val in items.items(): if key in pickled_keys: ret[key] = pickle.loads(val) else: ...
Returns the response for the given url. The optional data argument is passed directly to urlopen. def download_page(url, data=None): '''Returns the response for the given url. The optional data argument is passed directly to urlopen.''' conn = urllib2.urlopen(url, data) resp = conn.read() conn....
unquote(r'abc\x20def') -> 'abc def'. def unhex(inp): '''unquote(r'abc\x20def') -> 'abc def'.''' res = inp.split(r'\x') for i in xrange(1, len(res)): item = res[i] try: res[i] = _hextochr[item[:2]] + item[2:] except KeyError: res[i] = '%' + item except...
Load all the commands from an entrypoint def load_commands(self, namespace): """Load all the commands from an entrypoint""" for ep in pkg_resources.iter_entry_points(namespace): LOG.debug('found command %r', ep.name) cmd_name = (ep.name.replace('_', ' ') ...
Given an argument list, find a command and return the processor and any remaining arguments. def find_command(self, argv): """Given an argument list, find a command and return the processor and any remaining arguments. """ search_args = argv[:] name = '' while se...
Set up logging via the logging module's fileConfig function with the filename specified via ``config_uri`` (a string in the form ``filename#sectionname``). ConfigParser defaults are specified for the special ``__file__`` and ``here`` variables, similar to PasteDeploy config loading. def setup_logging(...
Prepares a file-based package for validation. timeout is the number of seconds before validation is aborted. If timeout is -1 then no timeout checking code will run. def prepare_package(err, path, expectation=0, for_appversions=None, timeout=-1): """Prepares a file-based package for va...
Loads the chrome.manifest if it's present def populate_chrome_manifest(err, xpi_package): "Loads the chrome.manifest if it's present" if 'chrome.manifest' in xpi_package: chrome_data = xpi_package.read('chrome.manifest') chrome = ChromeManifest(chrome_data, 'chrome.manifest') chrome_r...
Determines the type of add-on being validated based on install.rdf, file extension, and other properties. def detect_type(err, install_rdf=None, xpi_package=None): """Determines the type of add-on being validated based on install.rdf, file extension, and other properties.""" # The types in the install...
Detect, parse, and validate an OpenSearch provider def detect_opensearch(err, package, listed=False): 'Detect, parse, and validate an OpenSearch provider' # Parse the file. try: # Check if it is a file object. if hasattr(package, 'read'): srch_prov = parse(package) else...
Copies the ``source`` directory to the ``dest`` directory. ``vars``: A dictionary of variables to use in any substitutions. ``verbosity``: Higher numbers will show more about what is happening. ``simulate``: If true, then don't actually *do* anything. ``indent``: Indent any messages by this amount. ...
Checks if a file should be skipped based on its name. If it should be skipped, returns the reason, otherwise returns None. def should_skip_file(name): """ Checks if a file should be skipped based on its name. If it should be skipped, returns the reason, otherwise returns None. """ if ...
Takes any actions necessary based on command line options def setup_options(opts): '''Takes any actions necessary based on command line options''' if opts.quiet: logger.log.setLevel(logging.WARNING) logger.GLOBAL_LOG_LEVEL = logging.WARNING if opts.verbose: logger.log.setLevel(logg...
Attempts to extract a module name for the given addon's addon.xml file. Looks for the 'xbmc.python.pluginsource' extension node and returns the addon's filename without the .py suffix. def get_addon_module_name(addonxml_filename): '''Attempts to extract a module name for the given addon's addon.xml file. ...
Patches a few attributes of a plugin instance to enable a new call to plugin.run() def patch_plugin(plugin, path, handle=None): '''Patches a few attributes of a plugin instance to enable a new call to plugin.run() ''' if handle is None: handle = plugin.request.handle patch_sysargv(path,...
A run mode for the CLI that runs the plugin once and exits. def once(plugin, parent_stack=None): '''A run mode for the CLI that runs the plugin once and exits.''' plugin.clear_added_items() items = plugin.run() # if update_listing=True, we need to remove the last url from the parent # stack if...
A run mode for the CLI that runs the plugin in a loop based on user input. def interactive(plugin): '''A run mode for the CLI that runs the plugin in a loop based on user input. ''' items = [item for item in once(plugin) if not item.get_played()] parent_stack = [] # Keep track of parents so we...
Performs a breadth-first crawl of all possible routes from the starting path. Will only visit a URL once, even if it is referenced multiple times in a plugin. Requires user interaction in between each fetch. def crawl(plugin): '''Performs a breadth-first crawl of all possible routes from the starti...
The run method for the 'run' command. Executes a plugin from the command line. def run(opts, args): '''The run method for the 'run' command. Executes a plugin from the command line. ''' setup_options(opts) mode = Modes.ONCE if len(args) > 0 and hasattr(Modes, ar...
Attempts to import a plugin's source code and find an instance of :class:`~xbmcswif2.Plugin`. Returns an instance of PluginManager if succesful. def load_plugin_from_addonxml(cls, mode, url): '''Attempts to import a plugin's source code and find an instance of :class:`~xbmcswif2.Plugin`...
This method runs the the plugin in the appropriate mode parsed from the command line options. def run(self): '''This method runs the the plugin in the appropriate mode parsed from the command line options. ''' handle = 0 handlers = { Modes.ONCE: once, ...
Called to setup an application, given its configuration file/directory. The default implementation calls ``package.websetup.setup_config(command, filename, section, vars)`` or ``package.websetup.setup_app(command, config, vars)`` With ``setup_app`` the ``config`` object...
Import a module. def _import_module(self, s): """ Import a module. """ mod = __import__(s) parts = s.split('.') for part in parts[1:]: mod = getattr(mod, part) return mod
Talk to Cleverbot. Arguments: input: The input argument is what you want to say to Cleverbot, such as "hello". tweak1-3: Changes Cleverbot's mood. **kwargs: Keyword arguments to update the request parameters with. Returns: Cleverbot's rep...
Make a new conversation. Arguments: name: The key for the dictionary the conversation will be stored as in conversations. If None the conversation will be stored as a list instead. Mixing both types results in an error. **kwargs: Keyword arguments to pass...
Perform validation in one easy step! `path`: *Required* A file system path to the package to be validated. `format`: The format to return the results in. Defaults to "json". Currently, any other format will simply return the error bundle. `approved_applications`: Pat...
Add an error message for an unexpected exception in validator code, and move it to the front of the error message list. If `exc_info` is supplied, the error will be logged. If the error is a validation timeout, it is re-raised unless `msg_id` is "validation_timeout". def system_error(s...
Drop the given message object from the appropriate message list. Returns True if the message was found, otherwise False. def drop_message(self, message): """Drop the given message object from the appropriate message list. Returns True if the message was found, otherwise False.""" for...
Updates the tier and ending tier def set_tier(self, tier): 'Updates the tier and ending tier' self.tier = tier if tier > self.ending_tier: self.ending_tier = tier
Stores a message in the appropriate message stack. def _save_message(self, stack, type_, message, context=None, from_merge=False): 'Stores a message in the appropriate message stack.' uid = uuid.uuid4().hex message['uid'] = uid # Get the context for the message (...
Returns a boolean value describing whether the validation succeeded or not. def failed(self, fail_on_warnings=True): """Returns a boolean value describing whether the validation succeeded or not.""" return bool(self.errors) or (fail_on_warnings and bool(self.warnings))
Retrieves an object that has been stored by another test. def get_resource(self, name): 'Retrieves an object that has been stored by another test.' if name in self.resources: return self.resources[name] elif name in self.pushable_resources: return self.pushable_resource...
Saves an object such that it can be used by other tests. def save_resource(self, name, resource, pushable=False): 'Saves an object such that it can be used by other tests.' if pushable: self.pushable_resources[name] = resource else: self.resources[name] = resource
Saves the current error state to parse subpackages def push_state(self, new_file=''): 'Saves the current error state to parse subpackages' self.subpackages.append({'detected_type': self.detected_type, 'message_tree': self.message_tree, ...
Retrieves the last saved state and restores it. def pop_state(self): 'Retrieves the last saved state and restores it.' # Save a copy of the current state. state = self.subpackages.pop() metadata = self.metadata # We only rebuild message_tree anyway. No need to restore. ...
Returns a JSON summary of the validation operation. def render_json(self): 'Returns a JSON summary of the validation operation.' types = {0: 'unknown', 1: 'extension', 2: 'theme', 3: 'dictionary', 4: 'langpack', 5: 's...
Prints a summary of the validation process so far. def print_summary(self, verbose=False, no_color=False): 'Prints a summary of the validation process so far.' types = {0: 'Unknown', 1: 'Extension/Multi-Extension', 2: 'Full Theme', 3: 'Dictionary', ...
Flattens nested lists into strings. def _flatten_list(self, data): 'Flattens nested lists into strings.' if data is None: return '' if isinstance(data, types.StringTypes): return data elif isinstance(data, (list, tuple)): return '\n'.join(self._flatt...
Prints a message and takes care of all sorts of nasty code def _print_message(self, prefix, message, verbose=True): 'Prints a message and takes care of all sorts of nasty code' # Load up the standard output. output = ['\n', prefix, message['message']] # We have some extra stuff for ve...
Returns whether a GUID set in for_appversions format is compatbile with the current supported applications list. def supports_version(self, guid_set): """ Returns whether a GUID set in for_appversions format is compatbile with the current supported applications list. """ ...
Return whether there is an intersection between a support applications GUID set and a set of supported applications. def _compare_version(self, requirements, support): """ Return whether there is an intersection between a support applications GUID set and a set of supported applications...
Delete messages from errors, warnings, and notices whose tier is greater than the ending tier. def discard_unused_messages(self, ending_tier): """ Delete messages from errors, warnings, and notices whose tier is greater than the ending tier. """ stacks = [self.errors, s...
Tweaks will be lost for Cleverbot and its conversations. def migrator(state): """Tweaks will be lost for Cleverbot and its conversations.""" for tweak in ('tweak1', 'tweak2', 'tweak3'): del state[0][tweak] for convo in state[1]: if tweak in convo: del convo[tweak] ...
Nameless conversations will be lost. def migrator(state): """Nameless conversations will be lost.""" cleverbot_kwargs, convos_kwargs = state cb = Cleverbot(**cleverbot_kwargs) for convo_kwargs in convos_kwargs: cb.conversation(**convo_kwargs) return cb
Initialize with an UID def init_with_uid(self, uid): """Initialize with an UID """ self._uid = uid self._brain = None self._catalog = None self._instance = None
Initialize with a catalog brain def init_with_brain(self, brain): """Initialize with a catalog brain """ self._uid = api.get_uid(brain) self._brain = brain self._catalog = self.get_catalog_for(brain) self._instance = None
Initialize with an instance object def init_with_instance(self, instance): """Initialize with an instance object """ self._uid = api.get_uid(instance) self._brain = None self._catalog = self.get_catalog_for(instance) self._instance = instance