text
stringlengths
81
112k
Process publication value 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(va...
Content instance of the wrapped object 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
Catalog brain of the wrapped object 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
Primary registered catalog for the wrapped portal type 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 the primary catalog for the given brain or object 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 = ...
Lookup brain from the right 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"...
Wraps an object into a Super Model 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 '{}'" ...
Convert value to string This method is used to generate a simple JSON representation of the object (without dereferencing objects etc.) def stringify(self, value): """Convert value to string This method is used to generate a simple JSON representation of the object (without de...
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`. def to_dict(self, converter=None): """Returns a copy dict of the current object If a converter function is given, pass each valu...
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.''' ...
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 unique across all plugins and modules. There are not names...
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...
Override to add command options. 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
Returns True if the provided value is a valid pluglin id 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)
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 provide a value. If the validator callable has an error_mess...
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. 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 the...
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. def update_file(filename, items): '''Edits the given file in place, replacing any instances of {key} wit...
Creates a new XBMC Addon directory based on user input 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 ...
Return the list of supported applications. 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_ve...
Returns the first triple value matching the given subject, predicate, and/or object 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: # Filt...
Returns a generator of objects that correspond to the specified subjects and predicates. 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...
Returns triples that correspond to the specified subject, predicates, and objects. 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: # Filt...
Given an error bundle, a list of overlays that are present in the current package or subpackage are returned. 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. """ ...
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. def reverse_lookup(self, state, path): """ Returns a chrome URL for a given path, given the current package depth in an er...
Join the arguments together to form a predictable URL chunk. 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. ...
Application entry point 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.ins...
Returns a URIRef object for use with the RDF document. 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))
Returns the BNode which describes the topmost subject of the graph. 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: ...
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. def get_object(self, subject=None, predicate=None): """Eliminates some of the glue code for sear...
Same as get_object, except returns a list of objects which satisfy the query rather than a single result. 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 resul...
Return the list of supported applications. 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, sel...
Adds context menu items. If replace_items is True all previous context menu items will be removed. 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, a...
Sets the listitem's icon image def set_icon(self, icon): '''Sets the listitem's icon image''' self._icon = icon return self._listitem.setIconImage(icon)
Sets the listitem's thumbnail image def set_thumbnail(self, thumbnail): '''Sets the listitem's thumbnail image''' self._thumbnail = thumbnail return self._listitem.setThumbnailImage(thumbnail)
Sets the listitem's path def set_path(self, path): '''Sets the listitem's path''' self._path = path return self._listitem.setPath(path)
Sets the listitem's playable flag 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
A ListItem constructor for setting a lot of properties not available in the regular __init__ method. Useful to collect all the properties in a dict and then use the **dct to call this method. def from_dict(cls, label=None, label2=None, icon=None, thumbnail=None, path=None, sel...
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 should use :meth:`xbmcswi...
Returns a list of existing stores. The returned names can then be used to call get_storage(). 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 does...
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. If the storage does not already exist, it will be created. .....
Returns the localized string from strings.xml for the given stringid. 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 = {} ...
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 the settings value be returned. .. note:: It is sugges...
Adds the provided list of items to the specified playlist. Available playlists include *video* and *music*. def add_to_playlist(self, items, playlist='video'): '''Adds the provided list of items to the specified playlist. Available playlists include *video* and *music*. ''' play...
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. def get_view_mode_id(self, view_mode): '''Attempts to return a view_mode_id for a giv...
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 heading: The heading for the window. Defaults to the current ...
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. def notify(self, msg='', title=None, delay=5000, image=''): '''Displays a temporar...
Creates an xbmcswift2.ListItem if the provided value for item is a dict. If item is already a valid xbmcswift2.ListItem, the item is returned unmodified. def _listitemify(self, item): '''Creates an xbmcswift2.ListItem if the provided value for item is a dict. If item is already a valid ...
Adds subtitles to playing video. :param subtitles: A URL to a remote subtitles file or a local filename for a subtitles file. .. warning:: You must start playing a video before calling this method or it will loop for an indefinite length. def _add_subtit...
Takes a url or a listitem to be played. Used in conjunction with a playable list item with a path that calls back into your addon. :param item: A playable list item or url. Pass None to alert XBMC of a failure to resolve the item. .. warning:: When using set_r...
Adds ListItems to the XBMC interface. Each item in the provided list should either be instances of xbmcswift2.ListItem, or regular dictionaries that will be passed to xbmcswift2.ListItem.from_dict. Returns the list of ListItems. :param items: An iterable of items where each item is eith...
Wrapper for xbmcplugin.endOfDirectory. Records state in self._end_of_directory. Typically it is not necessary to call this method directly, as calling :meth:`~xbmcswift2.Plugin.finish` will call this method. def end_of_directory(self, succeeded=True, update_listing=False, ...
A wrapper for `xbmcplugin.addSortMethod() <http://mirrors.xbmc.org/docs/python-docs/xbmcplugin.html#-addSortMethod>`_. You can use ``dir(xbmcswift2.SortMethod)`` to list all available sort methods. :param sort_method: A valid sort method. You can provided the constant ...
Adds the provided items to the XBMC interface. :param items: an iterable of items where each item is either a dictionary with keys/values suitable for passing to :meth:`xbmcswift2.ListItem.from_dict` or an instance of :class:`xbmcswift2.ListItem`. :param sort_methods...
Register a cleanup function to be called at the end of every validation task. Takes either a callable (including a class with a __call_ method), or a class with a `cleanup` class method. def register_cleanup(cleanup): """Register a cleanup function to be called at the end of every validation task. Take...
Returns all values after (and including) `version` for the app `guid` def version_range(guid, version, before=None, app_versions=None): """Returns all values after (and including) `version` for the app `guid`""" if app_versions is None: app_versions = validator.constants.APPROVED_APPLICATIONS app_...
Attempts to match a url to the given path. If successful, a tuple is returned. The first item is the matchd function and the second item is a dictionary containing items to be passed to the function parsed from the provided path. If the provided path does not match this url rule then a ...
Returns a relative path for the given dictionary of items. Uses this url rule's url pattern and replaces instances of <var_name> with the appropriate value from the items dict. def _make_path(self, items): '''Returns a relative path for the given dictionary of items. Uses this url rul...
Returns a relative path complete with query string for the given dictionary of items. Any items with keys matching this rule's url pattern will be inserted into the path. Any remaining items will be appended as query string parameters. All items will be urlencoded. Any items wh...
Write the dict to disk def sync(self): '''Write the dict to disk''' if self.flag == 'r': return filename = self.filename tempname = filename + '.tmp' fileobj = open(tempname, 'wb' if self.file_format == 'pickle' else 'w') try: self.dump(fileobj) ...
Handles the writing of the dict to the file object def dump(self, fileobj): '''Handles the writing of the dict to the file object''' if self.file_format == 'csv': csv.writer(fileobj).writerows(self.raw_dict().items()) elif self.file_format == 'json': json.dump(self.raw_d...
Load the dict from the file object def load(self, fileobj): '''Load the dict from the file object''' # try formats from most restrictive to least restrictive for loader in (pickle.load, json.load, csv.reader): fileobj.seek(0) try: return self.initial_upda...
Initially fills the underlying dictionary with keys, values and timestamps. def initial_update(self, mapping): '''Initially fills the underlying dictionary with keys, values and timestamps. ''' for key, val in mapping.items(): _, timestamp = val if not se...
Returns a logging instance for the provided name. The returned object is an instance of logging.Logger. Logged messages will be printed to stderr when running in the CLI, or forwarded to XBMC's log when running in XBMC mode. def setup_log(name): '''Returns a logging instance for the provided name. The ...
Returns True for all records if running in the CLI, else returns True. When running inside XBMC it calls the xbmc.log() method and prevents the message from being double printed to STDOUT. def filter(self, record): '''Returns True for all records if running in the CLI, else returns ...
Tests a manifest name value for trademarks. def validate_name(err, value, source): 'Tests a manifest name value for trademarks.' ff_pattern = re.compile('(mozilla|firefox)', re.I) err.metadata['name'] = value if ff_pattern.search(value): err.warning( ('metadata_helpers', '_test_n...
Tests a manifest UUID value def validate_id(err, value, source): 'Tests a manifest UUID value' field_name = '<em:id>' if source == 'install.rdf' else 'id' id_pattern = re.compile( '(' # UUID format. '\{[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}\}' '|' # "email" form...
Tests a manifest version number def validate_version(err, value, source): 'Tests a manifest version number' field_name = '<em:version>' if source == 'install.rdf' else 'version' err.metadata['version'] = value # May not be longer than 32 characters if len(value) > 32: err.error( ...
Query the status of a specific pin (or all configured pins if pin is ommitted) def get_device(self, pin=None): """ Query the status of a specific pin (or all configured pins if pin is ommitted) """ url = self.base_url + '/device' try: r = requests.get(url, params={'pin': pin}, timeo...
Query the device status. Returns JSON of the device internal state def get_status(self): """ Query the device status. Returns JSON of the device internal state """ url = self.base_url + '/status' try: r = requests.get(url, timeout=10) return r.json() except Reque...
Actuate a device pin def put_device(self, pin, state, momentary=None, times=None, pause=None): """ Actuate a device pin """ url = self.base_url + '/device' payload = { "pin": pin, "state": state } if momentary is not None: payload["momentary...
Sync settings to the Konnected device def put_settings(self, sensors=[], actuators=[], auth_token=None, endpoint=None, blink=None, discovery=None, dht_sensors=[], ds18b20_sensors=[]): """ Sync settings to the Konnected device """ url = self.base_url + '/setting...
Parses a mime-type into its component parts. Carves up a mime-type and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/xhtml;q=0.5' would get parsed into: ('application', 'xhtml', ...
Parse a media-range into its component parts. Carves up a media range and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/*;q=0.5' would get parsed into: ('application', '*', {'q'...
Find the best match for a mime-type amongst parsed media-ranges. Find the best match for a given mime-type against a list of media_ranges that have already been parsed by parse_media_range(). Returns a tuple of the fitness value and the value of the 'q' quality parameter of the best match, or (-1, 0) i...
Return the quality ('q') of a mime-type against a list of media-ranges. Returns the quality 'q' of a mime-type when compared against the media-ranges in ranges. For example: >>> quality('text/html','text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5') ...
Return mime-type with the highest quality ('q') from list of candidates. Takes a list of supported mime-types and finds the best match for all the media-ranges listed in header. The value of header must be a string that conforms to the format of the HTTP Accept: header. The value of 'supported' is a li...
Helper that creates a XSLT stylesheet def makeXsl(filename): """ Helper that creates a XSLT stylesheet """ pkg = 'cnxml2html' package = ''.join(['.' + x for x in __name__.split('.')[:-1]])[1:] if package != '': pkg = package + '.' + pkg path = pkg_resources.resource_filename(pkg, filename) xml = etre...
Given a collxml file (collection.xml) this returns an HTML version of it (including "include" anchor links to the modules) def transform_collxml(collxml_file): """ Given a collxml file (collection.xml) this returns an HTML version of it (including "include" anchor links to the modules) """ xml...
Given a module cnxml file (index.cnxml) this returns an HTML version of it def transform_cnxml(cnxml_file): """ Given a module cnxml file (index.cnxml) this returns an HTML version of it """ xml = etree.parse(cnxml_file) xslt = makeXsl('cnxml2xhtml.xsl') xml = xslt(xml) return xml
Given an unzipped collection generate a giant HTML file representing the entire collection (including loading and converting individual modules) def transform_collection(collection_dir): """ Given an unzipped collection generate a giant HTML file representing the entire collection (including loadin...
From dict to instance :param d: Dict :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True :param force_cast: Cast forcibly if True :param restrict: Prohibit extra parameters if True :return: Instance Usage: >>> from...
From dict to optional instance. :param d: Dict :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True :param force_cast: Cast forcibly if True :param restrict: Prohibit extra parameters if True :return: Instance Usage: ...
From list of dict to list of instance :param ds: List of dict :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True :param force_cast: Cast forcibly if True :param restrict: Prohibit extra parameters if True :return: List of instance ...
From list of dict to optional list of instance. :param ds: List of dict :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True :param force_cast: Cast forcibly if True :param restrict: Prohibit extra parameters if True :return: List of ins...
From dict of dict to dict of instance :param ds: Dict of dict :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True :param force_cast: Cast forcibly if True :param restrict: Prohibit extra parameters if True :return: Dict of instance ...
From dict of dict to optional dict of instance. :param ds: Dict of dict :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True :param force_cast: Cast forcibly if True :param restrict: Prohibit extra parameters if True :return: Dict of ins...
From json string to instance :param data: Json string :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True :param force_cast: Cast forcibly if True :param restrict: Prohibit extra parameters if True :return: Instance Usage: ...
From json file path to instance :param fpath: Json file path :param encoding: Json file encoding :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True :param force_cast: Cast forcibly if True :param restrict: Prohibit extra parameters if ...
From json string to list of instance :param data: Json string :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True :param force_cast: Cast forcibly if True :param restrict: Prohibit extra parameters if True :return: List of instance ...
From json file path to list of instance :param fpath: Json file path :param encoding: Json file encoding :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True :param force_cast: Cast forcibly if True :param restrict: Prohibit extra parame...
From yaml string to instance :param data: Yaml string :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True :param force_cast: Cast forcibly if True :param restrict: Prohibit extra parameters if True :return: Instance Usage: ...
From yaml file path to instance :param fpath: Yaml file path :param encoding: Yaml file encoding :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True :param force_cast: Cast forcibly if True :param restrict: Prohibit extra parameters if ...
From yaml string to list of instance :param data: Yaml string :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True :param force_cast: Cast forcibly if True :param restrict: Prohibit extra parameters if True :return: List of instance ...
From yaml file path to list of instance :param fpath: Yaml file path :param encoding: Yaml file encoding :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True :param force_cast: Cast forcibly if True :param restrict: Prohibit extra parame...
From csv file path to list of instance :param fpath: Csv file path :param fieldnames: Specify csv header names if not included in the file :param encoding: Csv file encoding :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True :param res...
From url which returns json to instance :param url: Url which returns json :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True :param force_cast: Cast forcibly if True :param restrict: Prohibit extra parameters if True :return: Instance...
:param index: Usage: >>> TList([1, 2, 3, 4, 5]).get(3) Option --> 4 >>> TList([1, 2, 3, 4, 5]).get(5) Option --> None def get(self, index: int) -> TOption[T]: """ :param index: Usage: >>> TList([1, 2, 3, 4, 5]).get(3) ...
:param func: :type func: T, int -> U :rtype: TList[U] Usage: >>> TList([10, 20, 30, 40, 50]).emap(lambda x, i: (x+1, i)) [(11, 0), (21, 1), (31, 2), (41, 3), (51, 4)] def emap(self, func): """ :param func: :type func: T, int -> U :rtype:...
:param func: :type func: T -> bool Usage: >>> TList([1, 2, 30, 4, 50]).head_while(lambda x: x < 10) [1, 2] def head_while(self, func: Callable[[T], bool]) -> 'TList[T]': """ :param func: :type func: T -> bool Usage: >>> TList([1, 2...
Usage: >>> TList([1, 2, 3, 2, 1]).uniq() [1, 2, 3] def uniq(self) -> 'TList[T]': """ Usage: >>> TList([1, 2, 3, 2, 1]).uniq() [1, 2, 3] """ rs = TList() for e in self: if e not in rs: rs.append(e) ...