text stringlengths 18 773k |
|---|
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)) |
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) |
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 media resource, e.g.
cookies.
'''
optionstring = urllib.urlencode(options)
if optionstring:
return url + '|' + optionstring
return ... |
def enum(*args, **kwargs):
'''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 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) |
def pickle_dict(items):
'''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.
'''
ret = {}
pickled_keys = []
for key, val in items.items():
if ... |
def unpickle_args(items):
'''Takes a dict and unpickles values whose keys are found in
'_pickled' key.
>>> unpickle_args({'_pickled': ['foo']. 'foo': ['I3%0A.']})
{'foo': 3}
'''
# Technically there can be more than one _pickled value. At this point
# we'll just use the first one
pickled... |
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:
ret[key] = val
return ret |
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.close()
return resp |
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 UnicodeDecodeError:
res[i... |
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('_', ' ')
if self.convert_underscores
... |
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 search_args:
if search_args[0].startswith('-'):
name = '%s %s' % (name, sear... |
def setup_logging(config_uri, fileConfig=fileConfig,
configparser=configparser):
"""
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 ... |
def prepare_package(err, path, expectation=0, for_appversions=None,
timeout=-1):
"""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.
"""
package = None
try:
... |
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_recursion_buster = set()
# Handle t... |
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.rdf don't pair up 1:1 with the type
# system that we're using for expectations and the like. This is
#... |
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:
# It's not a file object; open it (the... |
def copy_dir(source, dest, vars, verbosity=1, simulate=False, indent=0,
sub_vars=True, interactive=False, overwrite=True,
template_renderer=None, out_=sys.stdout):
"""
Copies the ``source`` directory to the ``dest`` directory.
``vars``: A dictionary of variables to use in any subs... |
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 name.startswith('.'):
return 'Skipping hidden file %(filename)s'
if name.endswith('~') or name.endswith('.bak'):
... |
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(logging.DEBUG)
logger.GLOBAL_LOG_LEVEL = logging.DEBUG |
def get_addon_module_name(addonxml_filename):
'''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.
'''
try:
xml = ET.parse(addonxml_filename).getroot()
e... |
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, handle)
plugin._end_of_directory = False |
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 parent_stack and plugin._update_listing:
del parent_... |
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 can have a '..' option
selected_item = get_user_choice(items)
while se... |
def crawl(plugin):
'''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.
'''
# TODO: use OrderedSet?
paths_visited = set()
paths_to... |
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, args[0].upper()):
_mode = args.pop(0).upper()
mode = getattr(Modes... |
def load_plugin_from_addonxml(cls, mode, url):
'''Attempts to import a plugin's source code and find an instance of
:class:`~xbmcswif2.Plugin`. Returns an instance of PluginManager if
succesful.
'''
cwd = os.getcwd()
sys.path.insert(0, cwd)
module_name = get_addon... |
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,
Modes.CRAWL: crawl,
Modes.INTERACTIVE: interactive,
}
handler = handlers[... |
def _setup_config(self, dist, filename, section, vars, verbosity):
"""
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... |
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 |
def say(self, input=None, **kwargs):
"""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 wit... |
def conversation(self, name=None, **kwargs):
"""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 a... |
def validate(path, format='json',
approved_applications=None,
determined=True,
listed=True,
expectation=PACKAGE_ANY,
for_appversions=None,
overrides=None,
timeout=-1,
compat_test=False,
**kw):
"""
... |
def system_error(self, msg_id=None, message=None, description=None,
validation_timeout=False, exc_info=None, **kw):
"""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... |
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 type_ in 'errors', 'warnings', 'notices':
list_ = getattr(self, type_)
if message in list_:
... |
def set_tier(self, tier):
'Updates the tier and ending tier'
self.tier = tier
if tier > self.ending_tier:
self.ending_tier = tier |
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 (if there's a context available)
if context i... |
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)) |
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_resources[name]
else:
return False |
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 |
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,
'resources': self.pushable_resources,
... |
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.
# Copy the existing state back into place
... |
def render_json(self):
'Returns a JSON summary of the validation operation.'
types = {0: 'unknown',
1: 'extension',
2: 'theme',
3: 'dictionary',
4: 'langpack',
5: 'search',
8: 'webapp'}
output ... |
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',
4: 'Language Pack',
... |
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._flatten_list(x) for x in data) |
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 verbose mode.
if verbose:
verbose_output =... |
def supports_version(self, guid_set):
"""
Returns whether a GUID set in for_appversions format is compatbile with
the current supported applications list.
"""
# Don't let the test run if we haven't parsed install.rdf yet.
if self.supported_versions is None:
r... |
def _compare_version(self, requirements, support):
"""
Return whether there is an intersection between a support applications
GUID set and a set of supported applications.
"""
for guid in requirements:
# If we support any of the GUIDs in the guid_set, test if any of
... |
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, self.warnings, self.notices]
for stack in stacks:
for message in stack:
... |
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]
return state |
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 |
def init_with_uid(self, uid):
"""Initialize with an UID
"""
self._uid = uid
self._brain = None
self._catalog = None
self._instance = None |
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 |
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 |
def process_value(self, value):
"""Process publication value
"""
# UID -> SuperModel
if api.is_uid(value):
return self.to_super_model(value)
# Content -> SuperModel
elif api.is_object(value):
return self.to_super_model(value)
# String -> Un... |
def instance(self):
"""Content instance of the wrapped object
"""
if self._instance is None:
logger.debug("SuperModel::instance: *Wakup object*")
self._instance = api.get_object(self.brain)
return self._instance |
def brain(self):
"""Catalog brain of the wrapped object
"""
if self._brain is None:
logger.debug("SuperModel::brain: *Fetch catalog brain*")
self._brain = self.get_brain_by_uid(self.uid)
return self._brain |
def catalog(self):
"""Primary registered catalog for the wrapped portal type
"""
if self._catalog is None:
logger.debug("SuperModel::catalog: *Fetch catalog*")
self._catalog = self.get_catalog_for(self.brain)
return self._catalog |
def get_catalog_for(self, brain_or_object):
"""Return the primary catalog for the given brain or object
"""
if not api.is_object(brain_or_object):
raise TypeError("Invalid object type %r" % brain_or_object)
catalogs = api.get_catalogs_for(brain_or_object, default="uid_catalog... |
def get_brain_by_uid(self, uid):
"""Lookup brain from the right catalog
"""
if uid == "0":
return api.get_portal()
# ensure we have the primary catalog
if self._catalog is None:
uid_catalog = api.get_tool("uid_catalog")
results = uid_catalog({... |
def to_super_model(self, thing):
"""Wraps an object into a Super Model
"""
if api.is_uid(thing):
return SuperModel(thing)
if not api.is_object(thing):
raise TypeError("Expected a portal object, got '{}'"
.format(type(thing)))
re... |
def stringify(self, value):
"""Convert value to string
This method is used to generate a simple JSON representation of the
object (without dereferencing objects etc.)
"""
# SuperModel -> UID
if ISuperModel.providedBy(value):
return str(value)
# DateTi... |
def to_dict(self, converter=None):
"""Returns a copy dict of the current object
If a converter function is given, pass each value to it.
Per default the values are converted by `self.stringify`.
"""
if converter is None:
converter = self.stringify
out = dict(... |
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.'''
def decorator(func):
'''Adds a url rule for the provided function'''
view_name = name or func.__n... |
def url_for(self, endpoint, explicit=False, **items):
'''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.
Currently, view names must be u... |
def add_url_rule(self, url_rule, view_func, name, options=None):
'''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 provi... |
def get_parser(self, prog_name):
"""Override to add command options."""
parser = argparse.ArgumentParser(description=self.get_description(),
prog=prog_name, add_help=False)
return parser |
def validate_pluginid(value):
'''Returns True if the provided value is a valid pluglin id'''
valid = string.ascii_letters + string.digits + '.'
return all(c in valid for c in value) |
def get_valid_value(prompt, validator, default=None):
'''Displays the provided prompt and gets input from the user. This behavior
loops indefinitely until the provided validator returns True for the user
input. If a default value is provided, it will be used only if the user
hits Enter and does not prov... |
def get_value(prompt, default=None, hidden=False):
'''Displays the provided prompt and returns the input from the user. If the
user hits Enter and there is a default value provided, the default is
returned.
'''
_prompt = '%s : ' % prompt
if default:
_prompt = '%s [%s]: ' % (prompt, defau... |
def update_file(filename, items):
'''Edits the given file in place, replacing any instances of {key} with the
appropriate value from the provided items dict. If the given filename ends
with ".xml" values will be quoted and escaped for XML.
'''
# TODO: Implement something in the templates to denote w... |
def create_new_project():
'''Creates a new XBMC Addon directory based on user input'''
readline.parse_and_bind('tab: complete')
print \
'''
xbmcswift2 - A micro-framework for creating XBMC plugins.
xbmc@jonathanbeluch.com
--
'''
print 'I\'m going to ask you a few questions to get this proje... |
def get_applications(self):
"""Return the list of supported applications."""
if ('applications' not in self.data or
'gecko' not in self.data['applications']):
return []
app = self.data['applications']['gecko']
min_version = app.get('strict_min_version', u'42.0... |
def get_value(self, subject=None, predicate=None, object_=None):
"""Returns the first triple value matching the given subject,
predicate, and/or object"""
for triple in self.triples:
# Filter out non-matches
if (subject and triple['subject'] != subject) or \
... |
def get_objects(self, subject=None, predicate=None):
"""Returns a generator of objects that correspond to the
specified subjects and predicates."""
for triple in self.triples:
# Filter out non-matches
if ((subject and triple['subject'] != subject) or
(pr... |
def get_triples(self, subject=None, predicate=None, object_=None):
"""Returns triples that correspond to the specified subject,
predicates, and objects."""
for triple in self.triples:
# Filter out non-matches
if subject is not None and triple['subject'] != subject:
... |
def get_applicable_overlays(self, error_bundle):
"""
Given an error bundle, a list of overlays that are present in the
current package or subpackage are returned.
"""
content_paths = self.get_triples(subject='content')
if not content_paths:
return set()
... |
def reverse_lookup(self, state, path):
"""
Returns a chrome URL for a given path, given the current package depth
in an error bundle.
State may either be an error bundle or the actual package stack.
"""
# Make sure the path starts with a forward slash.
if not pa... |
def _url_chunk_join(self, *args):
"""Join the arguments together to form a predictable URL chunk."""
# Strip slashes from either side of each path piece.
pathlets = map(lambda s: s.strip('/'), args)
# Remove empty pieces.
pathlets = filter(None, pathlets)
url = '/'.join(p... |
def run(self, argv):
"""Application entry point"""
try:
self.options, remainder = self.parser.parse_known_args(argv)
self._configure_logging()
if self.options.relative_plugins:
curdir = os.getcwd()
sys.path.insert(0, curdir)
... |
def uri(self, element, namespace=None):
'Returns a URIRef object for use with the RDF document.'
if namespace is None:
namespace = self.namespace
return URIRef('%s#%s' % (namespace, element)) |
def get_root_subject(self):
'Returns the BNode which describes the topmost subject of the graph.'
manifest = URIRef(self.manifest)
if list(self.rdf.triples((manifest, None, None))):
return manifest
else:
return self.rdf.subjects(None, self.manifest).next() |
def get_object(self, subject=None, predicate=None):
"""Eliminates some of the glue code for searching RDF. Pass
in a URIRef object (generated by the `uri` function above or
a BNode object (returned by this function) for either of the
parameters."""
# Get the result of the search... |
def get_objects(self, subject=None, predicate=None):
"""Same as get_object, except returns a list of objects which
satisfy the query rather than a single result."""
# Get the result of the search
results = self.rdf.objects(subject, predicate)
return list(results) |
def get_applications(self):
"""Return the list of supported applications."""
applications = []
# Isolate all of the bnodes referring to target applications
for target_app in self.get_objects(None,
self.uri('targetApplication')):
app... |
def add_context_menu_items(self, items, replace_items=False):
'''Adds context menu items. If replace_items is True all
previous context menu items will be removed.
'''
for label, action in items:
assert isinstance(label, basestring)
assert isinstance(action, bases... |
def set_icon(self, icon):
'''Sets the listitem's icon image'''
self._icon = icon
return self._listitem.setIconImage(icon) |
def set_thumbnail(self, thumbnail):
'''Sets the listitem's thumbnail image'''
self._thumbnail = thumbnail
return self._listitem.setThumbnailImage(thumbnail) |
def set_path(self, path):
'''Sets the listitem's path'''
self._path = path
return self._listitem.setPath(path) |
def set_is_playable(self, is_playable):
'''Sets the listitem's playable flag'''
value = 'false'
if is_playable:
value = 'true'
self.set_property('isPlayable', value)
self.is_folder = not is_playable |
def from_dict(cls, label=None, label2=None, icon=None, thumbnail=None,
path=None, selected=None, info=None, properties=None,
context_menu=None, replace_context_menu=False,
is_playable=None, info_type='video', stream_info=None):
'''A ListItem constructor for ... |
def cached(self, TTL=60 * 24):
'''A decorator that will cache the output of the wrapped function. The
key used for the cache is the function name as well as the `*args` and
`**kwargs` passed to the function.
:param TTL: time to live in minutes
.. note:: For route caching, you s... |
def list_storages(self):
'''Returns a list of existing stores. The returned names can then be
used to call get_storage().
'''
# Filter out any storages used by xbmcswift2 so caller doesn't corrupt
# them.
return [name for name in os.listdir(self.storage_path)
... |
def get_storage(self, name='main', file_format='pickle', TTL=None):
'''Returns a storage for the given name. The returned storage is a
fully functioning python dictionary and is designed to be used that
way. It is usually not necessary for the caller to load or save the
storage manually.... |
def get_string(self, stringid):
'''Returns the localized string from strings.xml for the given
stringid.
'''
stringid = int(stringid)
if not hasattr(self, '_strings'):
self._strings = {}
if not stringid in self._strings:
self._strings[stringid] = s... |
def get_setting(self, key, converter=None, choices=None):
'''Returns the settings value for the provided key.
If converter is str, unicode, bool or int the settings value will be
returned converted to the provided type.
If choices is an instance of list or tuple its item at position of t... |
def add_to_playlist(self, items, playlist='video'):
'''Adds the provided list of items to the specified playlist.
Available playlists include *video* and *music*.
'''
playlists = {'music': 0, 'video': 1}
assert playlist in playlists.keys(), ('Playlist "%s" is invalid.' %
... |
def get_view_mode_id(self, view_mode):
'''Attempts to return a view_mode_id for a given view_mode
taking into account the current skin. If not view_mode_id can
be found, None is returned. 'thumbnail' is currently the only
suppported view_mode.
'''
view_mode_ids = VIEW_MOD... |
def keyboard(self, default=None, heading=None, hidden=False):
'''Displays the keyboard input window to the user. If the user does not
cancel the modal, the value entered by the user will be returned.
:param default: The placeholder text used to prepopulate the input field.
:param headin... |
def notify(self, msg='', title=None, delay=5000, image=''):
'''Displays a temporary notification message to the user. If
title is not provided, the plugin name will be used. To have a
blank title, pass '' for the title argument. The delay argument
is in milliseconds.
'''
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.