Instruction:
How would you implement a function in Python 3 that
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.

Response:
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_visit = set(item.get_path() for item in once(plugin))

    while paths_to_visit and continue_or_quit():
        path = paths_to_visit.pop()
        paths_visited.add(path)

        # Run the new listitem
        patch_plugin(plugin, path)
        new_paths = set(item.get_path() for item in once(plugin))

        # Filter new items by checking against urls_visited and
        # urls_tovisit
        paths_to_visit.update(path for path in new_paths
                              if path not in paths_visited)


Instruction:
Make a summary of the following Python 3 code
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, _mode)

        url = None
        if len(args) > 0:
            # A url was specified
            url = args.pop(0)

        plugin_mgr = PluginManager.load_plugin_from_addonxml(mode, url)
        plugin_mgr.run()

Response:
The run method for the run command. Executes a plugin from the
        command line.


Instruction:
Given the following Python 3 function, write the documentation
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_module_name(os.path.join(cwd, 'addon.xml'))
        addon = __import__(module_name)

        # Find the first instance of xbmcswift2.Plugin
        try:
            plugin = (attr_value for attr_value in vars(addon).values()
                      if isinstance(attr_value, Plugin)).next()
        except StopIteration:
            sys.exit('Could\'t find a Plugin instance in %s.py' % module_name)

        return cls(plugin, mode, url)

Response:
Attempts to import a plugin s source code and find an instance of
        :class ~xbmcswif2. Plugin.


Instruction:
Can you generate the documentation for the following Python 3 function
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[self.mode]
        patch_sysargv(self.url or 'plugin://%s/' % self.plugin.id, handle)
        return handler(self.plugin)

Response:
This method runs the plugin in the appropriate mode parsed from
 the command line options.


Instruction:
Can you tell what is the following Python 3 function doing
def _setup_config(self, dist, filename, section, vars, verbosity):
        modules = [line.strip() for line in dist.get_metadata_lines('top_level.txt')
                    if line.strip() and not line.strip().startswith('#')]

        if not modules:
            print('No modules are listed in top_level.txt')
            print('Try running python setup.py egg_info to regenerate that file')

        for mod_name in modules:
            mod_name = mod_name + '.websetup'
            try:
                mod = self._import_module(mod_name)
            except ImportError as e:
                print(e)
                desc = getattr(e, 'args', ['No module named websetup'])[0]
                if not desc.startswith('No module named websetup'):
                    raise
                mod = None

            if mod is None:
                continue

            if hasattr(mod, 'setup_app'):
                if verbosity:
                    print('Running setup_app() from %s' % mod_name)
                self._call_setup_app(mod.setup_app, filename, section, vars)
            elif hasattr(mod, 'setup_config'):
                if verbosity:
                    print('Running setup_config() from %s' % mod_name)
                mod.setup_config(None, filename, section, vars)
            else:
                print('No setup_app() or setup_config() function in %s (%s)' % (mod.__name__, mod.__file__))

Response: This function is called by the application setup. py to generate a new configuration file.


Instruction:
Make a summary of the following Python 3 code
def say(self, input=None, **kwargs):
        params = self._get_params(input, kwargs)
        try:
            reply = yield from self.session.get(
                self.url, params=params, timeout=self.timeout)
        except asyncio.TimeoutError:
            raise Timeout(self.timeout)
        else:
            try:
                data = yield from reply.json()
            except ValueError as error:
                raise DecodeError(error)
            else:
                if reply.status == 200:
                    self.data = data
                    return data.get('output')
                else:
                    raise APIError(data.get('error'), data.get('status'))

Response:
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 reply.

        Raises:
            APIError: A Cleverbot API error occurred.
            DecodeError: An error occurred while reading the reply.
            Timeout: The request timed out.


Instruction:
Make a summary of the following Python 3 code
def conversation(self, name=None, **kwargs):
        convo = Conversation(self, **kwargs)
        super().conversation(name, convo)
        return convo

Response: Make a new conversation.


Instruction:
Can you generate a brief explanation for the following Python 3 code
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):
    """
    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`:
        Path to the list of approved application versions
    `determined`:
        If set to `False`, validation will halt at the end of the first tier
        that raises errors.
    `listed`:
        Whether the app is headed for the app marketplace or AMO. Defaults to
        `True`.
    `expectation`:
        The type of package that should be expected. Must be a symbolic
        constant from validator.constants (i.e.:
        validator.constants.PACKAGE_*). Defaults to PACKAGE_ANY.
    `for_appversions`:
        A dict of app GUIDs referencing lists of versions. Determines which
        version-dependant tests should be run.
    `timeout`:
        Number of seconds before aborting addon validation, or -1 to
        run with no timeout.
    `compat_tests`:
        A flag to signal the validator to skip tests which should not be run
        during compatibility bumps. Defaults to `False`.
    """

    bundle = ErrorBundle(listed=listed, determined=determined,
                         overrides=overrides, for_appversions=for_appversions)
    bundle.save_resource('is_compat_test', compat_test)

    if approved_applications is None:
        approved_applications = os.path.join(os.path.dirname(__file__),
                                             'app_versions.json')

    if isinstance(approved_applications, types.StringTypes):
        # Load up the target applications if the approved applications is a
        # path (string).
        with open(approved_applications) as approved_apps:
            apps = json.load(approved_apps)
    elif isinstance(approved_applications, dict):
        # If the lists of approved applications are already in a dict, just use
        # that instead of trying to pull from a file.
        apps = approved_applications
    else:
        raise ValueError('Unknown format for `approved_applications`.')

    constants.APPROVED_APPLICATIONS.clear()
    constants.APPROVED_APPLICATIONS.update(apps)

    submain.prepare_package(bundle, path, expectation,
                            for_appversions=for_appversions,
                            timeout=timeout)

    return format_result(bundle, format)

Response: Validate a file system path.


Instruction:
Make a summary of the following Python 3 code
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 will be logged.

        If the error is a validation timeout, it is re-raised unless
        `msg_id` is "validation_timeout"."""

        if exc_info:
            if (isinstance(exc_info[1], validator.ValidationTimeout) and
                    msg_id != 'validation_timeout'):
                # These should always propagate to the top-level exception
                # handler, and be reported only once.
                raise exc_info[1]

            log.error('Unexpected error during validation: %s: %s'
                      % (exc_info[0].__name__, exc_info[1]),
                      exc_info=exc_info)

        full_id = ('validator', 'unexpected_exception')
        if msg_id:
            full_id += (msg_id,)

        self.error(full_id,
                   message or 'An unexpected error has occurred.',
                   description or
                   ('Validation was unable to complete successfully due '
                    'to an unexpected error.',
                    'The error has been logged, but please consider '
                    'filing an issue report here: '
                    'https://bit.ly/1POrYYU'),
                   tier=1, **kw)

        # Move the error message to the beginning of the list.
        self.errors.insert(0, self.errors.pop())

Response:
Add an error message for an unexpected exception in validator
        code and move it to the front of the error message list.


Instruction:
Can you tell what is the following Python 3 function doing
def drop_message(self, message):

        for type_ in 'errors', 'warnings', 'notices':
            list_ = getattr(self, type_)
            if message in list_:
                list_.remove(message)
                if 'signing_severity' in message:
                    self.signing_summary[message['signing_severity']] -= 1
                return True

        return False

Response: Drop the given message object from the appropriate message list. Returns True if the message was found otherwise False.


Instruction:
Can you generate the documentation for the following Python 3 function
def set_tier(self, tier):
        'Updates the tier and ending tier'
        self.tier = tier
        if tier > self.ending_tier:
            self.ending_tier = tier

Response: Updates the tier and ending tier


Instruction:
How would you code a function in Python 3 to
store a message in the appropriate message stack.

Response:
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 is not None:
            if isinstance(context, tuple):
                message['context'] = context
            else:
                message['context'] = (
                    context.get_context(line=message['line'],
                                        column=message['column']))
        else:
            message['context'] = None

        if self.package_stack:
            if not isinstance(message['file'], list):
                message['file'] = [message['file']]

            message['file'] = self.package_stack + message['file']

        # Test that if for_appversions is set that we're only applying to
        # supported add-ons. THIS IS THE LAST FILTER BEFORE THE MESSAGE IS
        # ADDED TO THE STACK!
        if message['for_appversions']:
            if not self.supports_version(message['for_appversions']):
                if self.instant:
                    print '(Instant error discarded)'
                    self._print_message(type_, message, verbose=True)
                return
        elif self.version_requirements:
            # If there was no for_appversions but there were version
            # requirements detailed in the decorator, use the ones from the
            # decorator.
            message['for_appversions'] = self.version_requirements

        # Save the message to the stack.
        stack.append(message)

        # Mark the tier that the error occurred at.
        if message['tier'] is None:
            message['tier'] = self.tier

        # Build out the compatibility summary if possible.
        if message['compatibility_type'] and not from_merge:
            self.compat_summary['%ss' % message['compatibility_type']] += 1

        # Build out the message tree entry.
        if message['id']:
            tree = self.message_tree
            last_id = None
            for eid in message['id']:
                if last_id is not None:
                    tree = tree[last_id]
                if eid not in tree:
                    tree[eid] = {'__errors': 0,
                                 '__warnings': 0,
                                 '__notices': 0,
                                 '__messages': []}
                tree[eid]['__%s' % type_] += 1
                last_id = eid

            tree[last_id]['__messages'].append(uid)

        # If instant mode is turned on, output the message immediately.
        if self.instant:
            self._print_message(type_, message, verbose=True)


Instruction:
Here you have a function in Python 3, explain what it does
def failed(self, fail_on_warnings=True):

        return bool(self.errors) or (fail_on_warnings and bool(self.warnings))

Response:
Returns a boolean value describing whether the validation
        succeeded or not.


Instruction:
Write a Python 3 function for
retrieving an object that has been stored by another test.

Response:
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


Instruction:
Can you create a Python 3 function that
saves an object such that it can be used by other tests.

Response:
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


Instruction:
Can you tell what is the following Python 3 function doing
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,
                                 'metadata': self.metadata})

        self.message_tree = {}
        self.pushable_resources = {}
        self.metadata = {'requires_chrome': False,
                         'listed': self.metadata.get('listed'),
                         'validator_version': validator.__version__}

        self.package_stack.append(new_file)

Response: Saves the current error state to parse subpackages


Instruction:
Implement a Python 3 function for
retrieving the last saved state and restores it.

Response:
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
        self.detected_type = state['detected_type']
        self.message_tree = state['message_tree']
        self.pushable_resources = state['resources']
        self.metadata = state['metadata']

        name = self.package_stack.pop()

        self.metadata.setdefault('sub_packages', {})[name] = metadata


Instruction:
Can you write a function in Python 3 where it
returns a JSON summary of the validation operation.

Response:
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 = {'detected_type': types[self.detected_type],
                  'ending_tier': self.ending_tier,
                  'success': not self.failed(),
                  'messages': [],
                  'errors': len(self.errors),
                  'warnings': len(self.warnings),
                  'notices': len(self.notices),
                  'message_tree': self.message_tree,
                  'compatibility_summary': self.compat_summary,
                  'signing_summary': self.signing_summary,
                  'metadata': self.metadata}

        messages = output['messages']

        # Copy messages to the JSON output
        for error in self.errors:
            error['type'] = 'error'
            messages.append(error)

        for warning in self.warnings:
            warning['type'] = 'warning'
            messages.append(warning)

        for notice in self.notices:
            notice['type'] = 'notice'
            messages.append(notice)

        # Output the JSON.
        return json.dumps(output)


Instruction:
Write a Python 3 script for
printing a summary of the validation process so far.

Response:
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',
                 5: 'Search Provider',
                 7: 'Subpackage',
                 8: 'App'}
        detected_type = types[self.detected_type]

        buffer = StringIO()
        self.handler = OutputHandler(buffer, no_color)

        # Make a neat little printout.
        self.handler.write('\n<<GREEN>>Summary:') \
            .write('-' * 30) \
            .write('Detected type: <<BLUE>>%s' % detected_type) \
            .write('-' * 30)

        if self.failed():
            self.handler.write('<<BLUE>>Test failed! Errors:')

            # Print out all the errors/warnings:
            for error in self.errors:
                self._print_message('<<RED>>Error:<<NORMAL>>\t',
                                    error, verbose)
            for warning in self.warnings:
                self._print_message('<<YELLOW>>Warning:<<NORMAL>> ',
                                    warning, verbose)
        else:
            self.handler.write('<<GREEN>>All tests succeeded!')

        if self.notices:
            for notice in self.notices:
                self._print_message(prefix='<<WHITE>>Notice:<<NORMAL>>\t',
                                    message=notice,
                                    verbose=verbose)

        if 'is_jetpack' in self.metadata and verbose:
            self.handler.write('\n')
            self.handler.write('<<GREEN>>Jetpack add-on detected.<<NORMAL>>\n'
                               'Identified files:')
            if 'jetpack_identified_files' in self.metadata:
                for filename, data in \
                        self.metadata['jetpack_identified_files'].items():
                    self.handler.write((' %s\n' % filename) +
                                       ('  %s : %s' % data))

            if 'jetpack_unknown_files' in self.metadata:
                self.handler.write('Unknown files:')
                for filename in self.metadata['jetpack_unknown_files']:
                    self.handler.write(' %s' % filename)

        self.handler.write('\n')
        if self.unfinished:
            self.handler.write('<<RED>>Validation terminated early')
            self.handler.write('Errors during validation are preventing '
                               'the validation process from completing.')
            self.handler.write('Use the <<YELLOW>>--determined<<NORMAL>> '
                               'flag to ignore these errors.')
            self.handler.write('\n')

        return buffer.getvalue()


Instruction:
How would you explain what the following Python 3 function does
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)

Response: Flattens nested lists into strings.


Instruction:
Write a Python 3 script for
printing a message and takes care of all sorts of nasty code

Response:
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 = []

            # Detailed problem description.
            if message['description']:
                verbose_output.append(
                    self._flatten_list(message['description']))

            if message.get('signing_severity'):
                verbose_output.append(
                    ('\tAutomated signing severity: %s' %
                     message['signing_severity']))

            if message.get('signing_help'):
                verbose_output.append(
                    '\tSuggestions for passing automated signing:')
                verbose_output.append(
                    self._flatten_list(message['signing_help']))

            # Show the user what tier we're on
            verbose_output.append('\tTier:\t%d' % message['tier'])

            # If file information is available, output that as well.
            files = message['file']
            if files is not None and files != '':
                fmsg = '\tFile:\t%s'

                # Nested files (subpackes) are stored in a list.
                if type(files) is list:
                    if files[-1] == '':
                        files[-1] = '(none)'
                    verbose_output.append(fmsg % ' > '.join(files))
                else:
                    verbose_output.append(fmsg % files)

            # If there is a line number, that gets put on the end.
            if message['line']:
                verbose_output.append('\tLine:\t%s' % message['line'])
            if message['column'] and message['column'] != 0:
                verbose_output.append('\tColumn:\t%d' % message['column'])

            if message.get('context'):
                verbose_output.append('\tContext:')
                verbose_output.extend([('\t> %s' % x
                                        if x is not None
                                        else '\t>' + ('-' * 20))
                                       for x
                                       in message['context']])

            # Stick it in with the standard items.
            output.append('\n')
            output.append('\n'.join(verbose_output))

        # Send the final output to the handler to be rendered.
        self.handler.write(u''.join(map(unicodehelper.decode, output)))


Instruction:
Can you implement a function in Python 3 that
returns whether a GUID set in for_appversions format is compatbile with the current supported applications list.

Response:
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:
            raise Exception('Early compatibility test run before install.rdf '
                            'was parsed.')

        return self._compare_version(requirements=guid_set,
                                     support=self.supported_versions)


Instruction:
Here you have a function in Python 3, explain what it does
def _compare_version(self, requirements, support):

        for guid in requirements:
            # If we support any of the GUIDs in the guid_set, test if any of
            # the provided versions for the GUID are supported.
            if (guid in support and
                any((detected_version in requirements[guid]) for
                    detected_version in support[guid])):
                return True

Response: Compare the version of the application and the set of supported applications.


Instruction:
Write a Python 3 function for
deleting unused messages from errors warnings and notices.

Response:
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:
                if message['tier'] > ending_tier:
                    stack.remove(message)


Instruction:
Can you implement a function in Python 3 that
tweaks will be lost for Cleverbot and its conversations.

Response:
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


Instruction:
Implement a function in Python 3 to
migrate the state of the state machine into a Cleverbot object.

Response:
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


Instruction:
Implement a function in Python 3 to
initialize with an UID

Response:
def init_with_uid(self, uid):
        """Initialize with an UID
        """
        self._uid = uid
        self._brain = None
        self._catalog = None
        self._instance = None


Instruction:
Can you tell what is the following Python 3 function doing
def init_with_brain(self, brain):
        self._uid = api.get_uid(brain)
        self._brain = brain
        self._catalog = self.get_catalog_for(brain)
        self._instance = None

Response: Initialize with a catalog brain


Instruction:
Given the following Python 3 function, write the documentation
def init_with_instance(self, instance):
        self._uid = api.get_uid(instance)
        self._brain = None
        self._catalog = self.get_catalog_for(instance)
        self._instance = instance

Response: Initialize with an instance object


Instruction:
Can you generate the documentation for the following Python 3 function
def process_value(self, 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 -> Unicode
        elif isinstance(value, basestring):
            return safe_unicode(value).encode("utf-8")
        # DateTime -> DateTime
        elif isinstance(value, DateTime):
            return value
        # Process list values
        elif isinstance(value, (LazyMap, list, tuple)):
            return map(self.process_value, value)
        # Process dict values
        elif isinstance(value, (dict)):
            return {k: self.process_value(v) for k, v in value.iteritems()}
        # Process function
        elif safe_callable(value):
            return self.process_value(value())
        # Always return the unprocessed value last
        return value

Response: Process the value of the key - value pair.


Instruction:
Make a summary of the following Python 3 code
def instance(self):
        if self._instance is None:
            logger.debug("SuperModel::instance: *Wakup object*")
            self._instance = api.get_object(self.brain)
        return self._instance

Response: Return the content instance of the wrapped object


Instruction:
Write a Python 3 function that can
return the catalog brain of the wrapped object

Response:
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


Instruction:
Here you have a function in Python 3, explain what it does
def catalog(self):
        if self._catalog is None:
            logger.debug("SuperModel::catalog: *Fetch catalog*")
            self._catalog = self.get_catalog_for(self.brain)
        return self._catalog

Response: Primary registered catalog for the wrapped portal type


Instruction:
Implement a Python 3 function for
returning the primary catalog for the given brain or object

Response:
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")
        return catalogs[0]


Instruction:
Write a Python 3 script to
wrap an object into a Super Model

Response:
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)))
        return thing


Instruction:
How would you explain what the following Python 3 function does
def stringify(self, value):
        # SuperModel -> UID
        if ISuperModel.providedBy(value):
            return str(value)
        # DateTime -> ISO8601 format
        elif isinstance(value, (DateTime)):
            return value.ISO8601()
        # Image/Files -> filename
        elif safe_hasattr(value, "filename"):
            return value.filename
        # Dict -> convert_value_to_string
        elif isinstance(value, dict):
            return {k: self.stringify(v) for k, v in value.iteritems()}
        # List -> convert_value_to_string
        if isinstance(value, (list, tuple, LazyMap)):
            return map(self.stringify, value)
        # Callables
        elif safe_callable(value):
            return self.stringify(value())
        elif isinstance(value, unicode):
            value = value.encode("utf8")
        try:
            return str(value)
        except (AttributeError, TypeError, ValueError):
            logger.warn("Could not convert {} to string".format(repr(value)))
            return None

Response: Convert value to string


Instruction:
Here you have a function in Python 3, explain what it does
def to_dict(self, converter=None):
        if converter is None:
            converter = self.stringify
        out = dict()
        for k, v in self.iteritems():
            out[k] = converter(v)
        return out

Response: Returns a copy dict of the current object.


Instruction:
Can you generate a brief explanation for the following Python 3 code
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.__name__
            self.add_url_rule(url_rule, func, name=view_name, options=options)
            return func
        return decorator

Response:
A decorator to add a route to a view. name is used to
        differentiate when there are multiple routes for a given view. options is used to
        differentiate when there are multiple routes for a given view.


Instruction:
Given the following Python 3 function, write the documentation
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 unique across all plugins and
        modules. There are not namespace prefixes for modules.
        '''
        # TODO: Enable items to be passed with keywords of other var names
        #       such as endpoing and explicit
        # TODO: Figure out how to handle the case where a module wants to
        # call a parent plugin view.
        if not explicit and not endpoint.startswith(self._namespace):
            endpoint = '%s.%s' % (self._namespace, endpoint)
        return self._plugin.url_for(endpoint, **items)

Response: Returns a valid XBMC plugin URL for the given endpoint name.


Instruction:
Here you have a function in Python 3, explain what it does
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 provides the same functionality.
        '''
        name = '%s.%s' % (self._namespace, name)

        def register_rule(plugin, url_prefix):
            '''Registers a url rule for the provided plugin and
            url_prefix.
            '''
            full_url_rule = url_prefix + url_rule
            plugin.add_url_rule(full_url_rule, view_func, name, options)

        # Delay actual registration of the url rule until this module is
        # registered with a plugin
        self._register_funcs.append(register_rule)

Response: This method adds a url rule for routing purposes.


Instruction:
Implement a Python 3 function for
overriding to add command options.

Response:
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


Instruction:
Implement a Python 3 function for
returning True if the provided value is a valid pluglin id

Response:
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)


Instruction:
Implement a function in Python 3 to
display the provided prompt and gets input from the user.

Response:
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 provide a value.

    If the validator callable has an error_message attribute, it will be
    displayed for an invalid value, otherwise a generic message is used.
    '''
    ans = get_value(prompt, default)
    while not validator(ans):
        try:
            print validator.error_message
        except AttributeError:
            print 'Invalid value.'
        ans = get_value(prompt, default)

    return ans


Instruction:
Can you generate a brief explanation for the following Python 3 code
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, default)

    if hidden:
        ans = getpass(_prompt)
    else:
        ans = raw_input(_prompt)

    # If user hit Enter and there is a default value
    if not ans and default:
        ans = default
    return ans

Response: Displays the provided prompt and returns the input from the user.


Instruction:
Can you tell what is the following Python 3 function doing
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 whether the value
    # being replaced is an XML attribute or a value. Perhaps move to dyanmic
    # XML tree building rather than string replacement.
    should_escape = filename.endswith('addon.xml')

    with open(filename, 'r') as inp:
        text = inp.read()

    for key, val in items.items():
        if should_escape:
            val = saxutils.quoteattr(val)
        text = text.replace('{%s}' % key, val)
    output = text

    with open(filename, 'w') as out:
        out.write(output)

Response:
Edits the given file in place replacing any instances of key with the the
CTYPE appropriate value from the provided items dict.


Instruction:
Can you generate the documentation for the following Python 3 function
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 project' \
        ' started.'

    opts = {}

    # Plugin Name
    opts['plugin_name'] = get_valid_value(
        'What is your plugin name?',
        validate_nonblank
    )

    # Plugin ID
    opts['plugin_id'] = get_valid_value(
        'Enter your plugin id.',
        validate_pluginid,
        'plugin.video.%s' % (opts['plugin_name'].lower().replace(' ', ''))
    )

    # Parent Directory
    opts['parent_dir'] = get_valid_value(
        'Enter parent folder (where to create project)',
        validate_isfolder,
        getcwd()
    )
    opts['plugin_dir'] = os.path.join(opts['parent_dir'], opts['plugin_id'])
    assert not os.path.isdir(opts['plugin_dir']), \
        'A folder named %s already exists in %s.' % (opts['plugin_id'],
                                                     opts['parent_dir'])

    # Provider
    opts['provider_name'] = get_valid_value(
        'Enter provider name',
        validate_nonblank,
    )

    # Create the project folder by copying over skel
    copytree(SKEL, opts['plugin_dir'], ignore=ignore_patterns('*.pyc'))

    # Walk through all the new files and fill in with out options
    for root, dirs, files in os.walk(opts['plugin_dir']):
        for filename in files:
            update_file(os.path.join(root, filename), opts)

    print 'Projects successfully created in %s.' % opts['plugin_dir']
    print 'Done.'

Response: Create a new project in the current directory.


Instruction:
Can you implement a function in Python 3 that
returns the list of supported applications.

Response:
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')
        max_version = app.get('strict_max_version', u'*')
        return [{u'guid': FIREFOX_GUID,
                 u'min_version': min_version,
                 u'max_version': max_version}]


Instruction:
Implement a Python 3 function for
returning the first triple value matching the given subject predicate and object.

Response:
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 \
               (predicate and triple['predicate'] != predicate) or \
               (object_ and triple['object'] != object_):  # pragma: no cover
                continue

            # Return the first found.
            return triple

        return None


Instruction:
How would you explain what the following Python 3 function does
def get_objects(self, subject=None, predicate=None):

        for triple in self.triples:

            # Filter out non-matches
            if ((subject and triple['subject'] != subject) or
                (predicate and triple['predicate'] != predicate)):
                continue

            yield triple['object']

Response:
Returns a generator of objects that correspond to the
            specified subjects and predicates.


Instruction:
Explain what the following Python 3 code does
def get_triples(self, subject=None, predicate=None, object_=None):

        for triple in self.triples:

            # Filter out non-matches
            if subject is not None and triple['subject'] != subject:
                continue
            if predicate is not None and triple['predicate'] != predicate:
                continue
            if object_ is not None and triple['object'] != object_:
                continue

            yield triple

Response: Returns a generator of triples that correspond to the specified subject predicate and object.


Instruction:
How would you implement a function in Python 3 that
returns a set of overlays that are applicable to the current package or subpackage.

Response:
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()

        # Create some variables that will store where the applicable content
        # instruction path references and where it links to.
        chrome_path = ''
        content_root_path = '/'

        # Look through each of the listed packages and paths.
        for path in content_paths:
            chrome_name = path['predicate']
            if not path['object']:
                continue
            path_location = path['object'].strip().split()[0]

            # Handle jarred paths differently.
            if path_location.startswith('jar:'):
                if not error_bundle.is_nested_package:
                    continue

                # Parse out the JAR and it's location within the chrome.
                split_jar_url = path_location[4:].split('!', 2)
                # Ignore invalid/unsupported JAR URLs.
                if len(split_jar_url) != 2:
                    continue

                # Unpack the JAR URL.
                jar_path, package_path = split_jar_url

                # Ignore the instruction if the JAR it points to doesn't match
                # up with the current subpackage tree.
                if jar_path != error_bundle.package_stack[0]:
                    continue
                chrome_path = self._url_chunk_join(chrome_name, package_path)
                # content_root_path stays at the default: /

                break
            else:
                # If we're in a subpackage, a content instruction referring to
                # the root of the package obviously doesn't apply.
                if error_bundle.is_nested_package:
                    continue

                chrome_path = self._url_chunk_join(chrome_name, 'content')
                content_root_path = '/%s/' % path_location.strip('/')
                break

        if not chrome_path:
            return set()

        applicable_overlays = set()
        chrome_path = 'chrome://%s' % self._url_chunk_join(chrome_path + '/')

        for overlay in self.get_triples(subject='overlay'):
            if not overlay['object']:
                error_bundle.error(
                    err_id=('chromemanifest', 'get_applicable_overalys',
                            'object'),
                    error='Overlay instruction missing a property.',
                    description='When overlays are registered in a chrome '
                                'manifest file, they require a namespace and '
                                'a chrome URL at minimum.',
                    filename=overlay['filename'],
                    line=overlay['line'],
                    context=self.context)  #TODO(basta): Update this!
                continue
            overlay_url = overlay['object'].split()[0]
            if overlay_url.startswith(chrome_path):
                overlay_relative_path = overlay_url[len(chrome_path):]
                applicable_overlays.add('/%s' %
                        self._url_chunk_join(content_root_path,
                                             overlay_relative_path))

        return applicable_overlays


Instruction:
Make a summary of the following Python 3 code
def reverse_lookup(self, state, path):

        # Make sure the path starts with a forward slash.
        if not path.startswith('/'):
            path = '/%s' % path

        # If the state is an error bundle, extract the package stack.
        if not isinstance(state, list):
            state = state.package_stack

        content_paths = self.get_triples(subject='content')
        for content_path in content_paths:
            chrome_name = content_path['predicate']
            if not content_path['object']:
                continue
            path_location = content_path['object'].split()[0]

            if path_location.startswith('jar:'):
                if not state:
                    continue

                # Parse out the JAR and it's location within the chrome.
                split_jar_url = path_location[4:].split('!', 2)
                # Ignore invalid/unsupported JAR URLs.
                if len(split_jar_url) != 2:
                    continue

                # Unpack the JAR URL.
                jar_path, package_path = split_jar_url

                if jar_path != state[0]:
                    continue

                return 'chrome://%s' % self._url_chunk_join(chrome_name,
                                                            package_path,
                                                            path)
            else:
                if state:
                    continue

                path_location = '/%s/' % path_location.strip('/')
                rel_path = os.path.relpath(path, path_location)

                if rel_path.startswith('../') or rel_path == '..':
                    continue

                return 'chrome://%s' % self._url_chunk_join(chrome_name,
                                                            rel_path)

        return None

Response:
Returns a chrome URL for a given path given the current package depth
        in an error bundle.


Instruction:
Make a summary of the following Python 3 code
def _url_chunk_join(self, *args):
        # 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(pathlets)
        # If this is a directory, add a trailing slash.
        if args[-1].endswith('/'):
            url = '%s/' % url
        return url

Response: Join the arguments together to form a predictable URL chunk.


Instruction:
Can you tell what is the following Python 3 function doing
def run(self, argv):
        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)
                pkg_resources.working_set.add_entry(curdir)

            try:
                self._load_commands_for_current_dir()
            except pkg_resources.DistributionNotFound as e:
                try:
                    error_msg = repr(e)
                except:
                    error_msg = 'Unknown Error'

                log.error('Failed to load project commands with error '
                          '``%s``, have you installed your project?' % error_msg)

        except Exception as err:
            if hasattr(self, 'options'):
                debug = self.options.debug
            else:
                debug = True

            if debug:
                log.exception(err)
            else:
                log.error(err)

            return 1

        return self._run_subcommand(remainder)

Response: Main entry point for the application.


Instruction:
Can you implement a function in Python 3 that
returns a URIRef object for use with the RDF document.

Response:
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))


Instruction:
Can you tell what is the following Python 3 function doing
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()

Response: Returns the BNode which describes the topmost subject of the graph.


Instruction:
Explain what the following Python 3 code does
def get_object(self, subject=None, predicate=None):

        # Get the result of the search
        results = self.rdf.objects(subject, predicate)
        as_list = list(results)

        # Don't raise exceptions, value test!
        if not as_list:
            return None

        return as_list[0]

Response:
Eliminates some of the glue code for searching RDF. Pass
        in a URIRef object for either of the the
        parameters.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_applications(self):
        applications = []

        # Isolate all of the bnodes referring to target applications
        for target_app in self.get_objects(None,
                                           self.uri('targetApplication')):
            applications.append({
                'guid': self.get_object(target_app, self.uri('id')),
                'min_version': self.get_object(target_app,
                                               self.uri('minVersion')),
                'max_version': self.get_object(target_app,
                                               self.uri('maxVersion'))})
        return applications

Response: Return the list of supported applications.


Instruction:
How would you explain what the following Python 3 function does
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, basestring)
        if replace_items:
            self._context_menu_items = []
        self._context_menu_items.extend(items)
        self._listitem.addContextMenuItems(items, replace_items)

Response: Adds context menu items.


Instruction:
Can you generate the documentation for the following Python 3 function
def set_icon(self, icon):
        '''Sets the listitem's icon image'''
        self._icon = icon
        return self._listitem.setIconImage(icon)

Response: Sets the listitem s icon image


Instruction:
How would you code a function in Python 3 to
set the listitem s thumbnail image

Response:
def set_thumbnail(self, thumbnail):
        '''Sets the listitem's thumbnail image'''
        self._thumbnail = thumbnail
        return self._listitem.setThumbnailImage(thumbnail)


Instruction:
Explain what the following Python 3 code does
def set_path(self, path):
        '''Sets the listitem's path'''
        self._path = path
        return self._listitem.setPath(path)

Response: Sets the listitem s path


Instruction:
Write a Python 3 script for
setting the listitem s playable flag

Response:
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


Instruction:
Here you have a function in Python 3, explain what it does
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 should use
                  :meth:`xbmcswift2.Plugin.cached_route`.
        '''
        def decorating_function(function):
            # TODO test this method
            storage = self.get_storage(self._function_cache_name, file_format='pickle',
                                       TTL=TTL)
            kwd_mark = 'f35c2d973e1bbbc61ca60fc6d7ae4eb3'

            @wraps(function)
            def wrapper(*args, **kwargs):
                key = (function.__name__, kwd_mark,) + args
                if kwargs:
                    key += (kwd_mark,) + tuple(sorted(kwargs.items()))

                try:
                    result = storage[key]
                    log.debug('Storage hit for function "%s" with args "%s" '
                              'and kwargs "%s"', function.__name__, args,
                              kwargs)
                except KeyError:
                    log.debug('Storage miss for function "%s" with args "%s" '
                              'and kwargs "%s"', function.__name__, args,
                              kwargs)
                    result = function(*args, **kwargs)
                    storage[key] = result
                    storage.sync()
                return result
            return wrapper
        return decorating_function

Response: A decorator that caches the output of a function.


Instruction:
Write a Python 3 function that can
return a list of existing stores. The returned names can then be used to call get_storage.

Response:
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)
                if not name.startswith('.')]


Instruction:
How would you implement a function in Python 3 that
returns a storage for the given name.

Response:
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. If the storage does not already exist, it will be
        created.

        .. seealso:: :class:`xbmcswift2.TimedStorage` for more details.

        :param name: The name  of the storage to retrieve.
        :param file_format: Choices are 'pickle', 'csv', and 'json'. Pickle is
                            recommended as it supports python objects.

                            .. note:: If a storage already exists for the given
                                      name, the file_format parameter is
                                      ignored. The format will be determined by
                                      the existing storage file.
        :param TTL: The time to live for storage items specified in minutes or None
                    for no expiration. Since storage items aren't expired until a
                    storage is loaded form disk, it is possible to call
                    get_storage() with a different TTL than when the storage was
                    created. The currently specified TTL is always honored.
        '''

        if not hasattr(self, '_unsynced_storages'):
            self._unsynced_storages = {}
        filename = os.path.join(self.storage_path, name)
        try:
            storage = self._unsynced_storages[filename]
            log.debug('Loaded storage "%s" from memory', name)
        except KeyError:
            if TTL:
                TTL = timedelta(minutes=TTL)

            try:
                storage = TimedStorage(filename, file_format, TTL)
            except ValueError:
                # Thrown when the storage file is corrupted and can't be read.
                # Prompt user to delete storage.
                choices = ['Clear storage', 'Cancel']
                ret = xbmcgui.Dialog().select('A storage file is corrupted. It'
                                              ' is recommended to clear it.',
                                              choices)
                if ret == 0:
                    os.remove(filename)
                    storage = TimedStorage(filename, file_format, TTL)
                else:
                    raise Exception('Corrupted storage file at %s' % filename)

            self._unsynced_storages[filename] = storage
            log.debug('Loaded storage "%s" from disk', name)
        return storage


Instruction:
Write a Python 3 function that can
return the localized string from strings. xml for the given stringid.

Response:
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] = self.addon.getLocalizedString(stringid)
        return self._strings[stringid]


Instruction:
Implement a function in Python 3 to
return the value of the setting with the provided id.

Response:
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 the
        settings value be returned.
        .. note:: It is suggested to always use unicode for text-settings
                  because else xbmc returns utf-8 encoded strings.

        :param key: The id of the setting defined in settings.xml.
        :param converter: (Optional) Choices are str, unicode, bool and int.
        :param converter: (Optional) Choices are instances of list or tuple.

        Examples:
            * ``plugin.get_setting('per_page', int)``
            * ``plugin.get_setting('password', unicode)``
            * ``plugin.get_setting('force_viewmode', bool)``
            * ``plugin.get_setting('content', choices=('videos', 'movies'))``
        '''
        #TODO: allow pickling of settings items?
        # TODO: STUB THIS OUT ON CLI
        value = self.addon.getSetting(id=key)
        if converter is str:
            return value
        elif converter is unicode:
            return value.decode('utf-8')
        elif converter is bool:
            return value == 'true'
        elif converter is int:
            return int(value)
        elif isinstance(choices, (list, tuple)):
            return choices[int(value)]
        elif converter is None:
            log.warning('No converter provided, unicode should be used, '
                        'but returning str value')
            return value
        else:
            raise TypeError('Acceptable converters are str, unicode, bool and '
                            'int. Acceptable choices are instances of list '
                            ' or tuple.')


Instruction:
Can you write a function in Python 3 where it
adds the provided list of items to the specified playlist.

Response:
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.' %
                                              playlist)
        selected_playlist = xbmc.PlayList(playlists[playlist])

        _items = []
        for item in items:
            if not hasattr(item, 'as_xbmc_listitem'):
                if 'info_type' in item.keys():
                    log.warning('info_type key has no affect for playlist '
                                'items as the info_type is inferred from the '
                                'playlist type.')
                # info_type has to be same as the playlist type
                item['info_type'] = playlist
                item = xbmcswift2.ListItem.from_dict(**item)
            _items.append(item)
            selected_playlist.add(item.get_path(), item.as_xbmc_listitem())
        return _items


Instruction:
Can you generate the documentation for the following Python 3 function
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_MODES.get(view_mode.lower())
        if view_mode_ids:
            return view_mode_ids.get(xbmc.getSkinDir())
        return None

Response: Attempts to return a view_mode_id for a given view_mode.


Instruction:
Can you generate a brief explanation for the following Python 3 code
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 heading: The heading for the window. Defaults to the current
                        addon's name. If you require a blank heading, pass an
                        empty string.
        :param hidden: Whether or not the input field should be masked with
                       stars, e.g. a password field.
        '''
        if heading is None:
            heading = self.addon.getAddonInfo('name')
        if default is None:
            default = ''
        keyboard = xbmc.Keyboard(default, heading, hidden)
        keyboard.doModal()
        if keyboard.isConfirmed():
            return keyboard.getText()

Response: Displays the keyboard input window to the user.


Instruction:
Given the following Python 3 function, write the documentation
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.
        '''
        if not msg:
            log.warning('Empty message for notification dialog')
        if title is None:
            title = self.addon.getAddonInfo('name')
        xbmc.executebuiltin('XBMC.Notification("%s", "%s", "%s", "%s")' %
                            (msg, title, delay, image))

Response: Displays a temporary notification message to the user.


Instruction:
Can you generate the documentation for the following Python 3 function
def _listitemify(self, item):
        '''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.
        '''
        info_type = self.info_type if hasattr(self, 'info_type') else 'video'

        # Create ListItems for anything that is not already an instance of
        # ListItem
        if not hasattr(item, 'as_tuple'):
            if 'info_type' not in item.keys():
                item['info_type'] = info_type
            item = xbmcswift2.ListItem.from_dict(**item)
        return item

Response:
Creates an xbmcswift2. ListItem if the provided value for item is a
        dict.


Instruction:
Create a Python 3 function for
adding subtitles to playing video.

Response:
def _add_subtitles(self, subtitles):
        '''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.
        '''
        # This method is named with an underscore to suggest that callers pass
        # the subtitles argument to set_resolved_url instead of calling this
        # method directly. This is to ensure a video is played before calling
        # this method.
        player = xbmc.Player()
        for _ in xrange(30):
            if player.isPlaying():
                break
            time.sleep(1)
        else:
            raise Exception('No video playing. Aborted after 30 seconds.')

        player.setSubtitles(subtitles)


Instruction:
How would you code a function in Python 3 to
set the resolved url of a playable list item.

Response:
def set_resolved_url(self, item=None, subtitles=None):
        '''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_resolved_url you should ensure
                                  the initial playable item (which calls back
                                  into your addon) doesn't have a trailing
                                  slash in the URL. Otherwise it won't work
                                  reliably with XBMC's PlayMedia().
        :param subtitles: A URL to a remote subtitles file or a local filename
                          for a subtitles file to be played along with the
                          item.
        '''
        if self._end_of_directory:
            raise Exception('Current XBMC handle has been removed. Either '
                            'set_resolved_url(), end_of_directory(), or '
                            'finish() has already been called.')
        self._end_of_directory = True

        succeeded = True
        if item is None:
            # None item indicates the resolve url failed.
            item = {}
            succeeded = False

        if isinstance(item, basestring):
            # caller is passing a url instead of an item dict
            item = {'path': item}

        item = self._listitemify(item)
        item.set_played(True)
        xbmcplugin.setResolvedUrl(self.handle, succeeded,
                                  item.as_xbmc_listitem())

        # call to _add_subtitles must be after setResolvedUrl
        if subtitles:
            self._add_subtitles(subtitles)
        return [item]


Instruction:
Write a Python 3 function for
adding ListItems to the XBMC interface.

Response:
def add_items(self, items):
        '''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 either a
                      dictionary with keys/values suitable for passing to
                      :meth:`xbmcswift2.ListItem.from_dict` or an instance of
                      :class:`xbmcswift2.ListItem`.
        '''
        _items = [self._listitemify(item) for item in items]
        tuples = [item.as_tuple() for item in _items]
        xbmcplugin.addDirectoryItems(self.handle, tuples, len(tuples))

        # We need to keep track internally of added items so we can return them
        # all at the end for testing purposes
        self.added_items.extend(_items)

        # Possibly need an if statement if only for debug mode
        return _items


Instruction:
Write a Python 3 function that can
wrap for xbmcplugin. endOfDirectory. Records state in self. _end_of_directory.

Response:
def end_of_directory(self, succeeded=True, update_listing=False,
                         cache_to_disc=True):
        '''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.
        '''
        self._update_listing = update_listing
        if not self._end_of_directory:
            self._end_of_directory = True
            # Finalize the directory items
            return xbmcplugin.endOfDirectory(self.handle, succeeded,
                                             update_listing, cache_to_disc)
        assert False, 'Already called endOfDirectory.'


Instruction:
Given the following Python 3 function, write the documentation
def add_sort_method(self, sort_method, label2_mask=None):
        '''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
                            from xbmcplugin, an attribute of SortMethod, or a
                            string name. For instance, the following method
                            calls are all equivalent:

                            * ``plugin.add_sort_method(xbmcplugin.SORT_METHOD_TITLE)``
                            * ``plugin.add_sort_metohd(SortMethod.TITLE)``
                            * ``plugin.add_sort_method('title')``
        :param label2_mask: A mask pattern for label2. See the `XBMC
                            documentation
                            <http://mirrors.xbmc.org/docs/python-docs/xbmcplugin.html#-addSortMethod>`_
                            for more information.
        '''
        try:
            # Assume it's a string and we need to get the actual int value
            sort_method = SortMethod.from_string(sort_method)
        except AttributeError:
            # sort_method was already an int (or a bad value)
            pass

        if label2_mask:
            xbmcplugin.addSortMethod(self.handle, sort_method, label2_mask)
        else:
            xbmcplugin.addSortMethod(self.handle, sort_method)

Response: A wrapper for xbmcplugin. addSortMethod that adds a sort method to the current sort hierarchy.


Instruction:
Write a Python 3 function that can
finish the list items in the XBMC interface.

Response:
def finish(self, items=None, sort_methods=None, succeeded=True,
               update_listing=False, cache_to_disc=True, view_mode=None):
        '''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: a list of valid XBMC sort_methods. Each item in
                             the list can either be a sort method or a tuple of
                             ``sort_method, label2_mask``. See
                             :meth:`add_sort_method` for
                             more detail concerning valid sort_methods.

                             Example call with sort_methods::

                                sort_methods = ['label', 'title', ('date', '%D')]
                                plugin.finish(items, sort_methods=sort_methods)

        :param view_mode: can either be an integer (or parseable integer
            string) corresponding to a view_mode or the name of a type of view.
            Currrently the only view type supported is 'thumbnail'.
        :returns: a list of all ListItems added to the XBMC interface.
        '''
        # If we have any items, add them. Items are optional here.
        if items:
            self.add_items(items)
        if sort_methods:
            for sort_method in sort_methods:
                if not isinstance(sort_method, basestring) and hasattr(sort_method, '__len__'):
                    self.add_sort_method(*sort_method)
                else:
                    self.add_sort_method(sort_method)

        # Attempt to set a view_mode if given
        if view_mode is not None:
            # First check if we were given an integer or parseable integer
            try:
                view_mode_id = int(view_mode)
            except ValueError:
                # Attempt to lookup a view mode
                view_mode_id = self.get_view_mode_id(view_mode)

            if view_mode_id is not None:
                self.set_view_mode(view_mode_id)

        # Finalize the directory items
        self.end_of_directory(succeeded, update_listing, cache_to_disc)

        # Return the cached list of all the list items that were added
        return self.added_items


Instruction:
Can you tell what is the following Python 3 function doing
def register_cleanup(cleanup):

    if not callable(cleanup):
        # Allow decorating a class with a `cleanup` classm ethod.
        cleanup = cleanup.cleanup

    CLEANUP_FUNCTIONS.append(cleanup.cleanup)
    return cleanup

Response:
Register a cleanup function to be called at the end of every validation
    task. Takes either a callable that is called at the end of every validation
    task. Takes either a class with a __call_ method or a class with a cleanup class method.


Instruction:
How would you explain what the following Python 3 function does
def version_range(guid, version, before=None, app_versions=None):

    if app_versions is None:
        app_versions = validator.constants.APPROVED_APPLICATIONS
    app_key = None

    # Support for shorthand instead of full GUIDs.
    for app_guid, app_name in APPLICATIONS.items():
        if app_name == guid:
            guid = app_guid
            break

    for key in app_versions.keys():
        if app_versions[key]['guid'] == guid:
            app_key = key
            break

    if not app_key or version not in app_versions[app_key]['versions']:
        raise Exception('Bad GUID or version provided for version range: %s'
                        % version)

    all_versions = app_versions[app_key]['versions']
    version_pos = all_versions.index(version)
    before_pos = None
    if before is not None and before in all_versions:
        before_pos = all_versions.index(before)

    return all_versions[version_pos:before_pos]

Response: Returns all values after and including the version for the app guid


Instruction:
Can you tell what is the following Python 3 function doing
def match(self, path):
        '''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
        NotFoundException is raised.
        '''
        m = self._regex.search(path)
        if not m:
            raise NotFoundException

        # urlunencode the values
        items = dict((key, unquote_plus(val))
                     for key, val in m.groupdict().items())

        # unpickle any items if present
        items = unpickle_dict(items)

        # We need to update our dictionary with default values provided in
        # options if the keys don't already exist.
        [items.setdefault(key, val) for key, val in self._options.items()]
        return self._view_func, items

Response: Attempts to match a url to the given path.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _make_path(self, items):
        '''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.
        '''
        for key, val in items.items():
            if not isinstance(val, basestring):
                raise TypeError, ('Value "%s" for key "%s" must be an instance'
                                  ' of basestring' % (val, key))
            items[key] = quote_plus(val)

        try:
            path = self._url_format.format(**items)
        except AttributeError:
            # Old version of python
            path = self._url_format
            for key, val in items.items():
                path = path.replace('{%s}' % key, val)
        return path

Response: Returns a relative path for the given dictionary of items.


Instruction:
Make a summary of the following Python 3 code
def make_path_qs(self, items):
        '''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 which are not instances of
        basestring, or int/long will be pickled before being urlencoded.

        .. warning:: The pickling of items only works for key/value pairs which
                     will be in the query string. This behavior should only be
                     used for the simplest of python objects. It causes the
                     URL to get very lengthy (and unreadable) and XBMC has a
                     hard limit on URL length. See the caching section if you
                     need to persist a large amount of data between requests.
        '''
        # Convert any ints and longs to strings
        for key, val in items.items():
            if isinstance(val, (int, long)):
                items[key] = str(val)

        # First use our defaults passed when registering the rule
        url_items = dict((key, val) for key, val in self._options.items()
                         if key in self._keywords)

        # Now update with any items explicitly passed to url_for
        url_items.update((key, val) for key, val in items.items()
                         if key in self._keywords)

        # Create the path
        path = self._make_path(url_items)

        # Extra arguments get tacked on to the query string
        qs_items = dict((key, val) for key, val in items.items()
                        if key not in self._keywords)
        qs = self._make_qs(qs_items)

        if qs:
            return '?'.join([path, qs])
        return path

Response: Returns a relative path complete with query string for the given items.


Instruction:
Can you create a Python 3 function that
writes the dict to disk

Response:
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)
        except Exception:
            os.remove(tempname)
            raise
        finally:
            fileobj.close()
        shutil.move(tempname, self.filename)    # atomic commit
        if self.mode is not None:
            os.chmod(self.filename, self.mode)


Instruction:
Create a Python 3 function to
handle the writing of the dict to the file object

Response:
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_dict(), fileobj, separators=(',', ':'))
        elif self.file_format == 'pickle':
            pickle.dump(dict(self.raw_dict()), fileobj, 2)
        else:
            raise NotImplementedError('Unknown format: ' +
                                      repr(self.file_format))


Instruction:
Here you have a function in Python 3, explain what it does
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_update(loader(fileobj))
            except Exception as e:
                pass
        raise ValueError('File not in a supported format')

Response: Load the dict from the file object fileobj


Instruction:
Create a Python 3 function to
initial update of the underlying dictionary with keys values and timestamps.

Response:
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 self.TTL or (datetime.utcnow() -
                datetime.utcfromtimestamp(timestamp) < self.TTL):
                self.__setitem__(key, val, raw=True)


Instruction:
Write a Python 3 script to
return a logging instance for the provided name.

Response:
def setup_log(name):
    '''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.
    '''
    _log = logging.getLogger(name)
    _log.setLevel(GLOBAL_LOG_LEVEL)
    handler = logging.StreamHandler()
    formatter = logging.Formatter(
        '%(asctime)s - %(levelname)s - [%(name)s] %(message)s')
    handler.setFormatter(formatter)
    _log.addHandler(handler)
    _log.addFilter(XBMCFilter('[%s] ' % name))
    return _log


Instruction:
How would you explain what the following Python 3 function does
def filter(self, record):
        '''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.
        '''

        # When running in XBMC, any logged statements will be double printed
        # since we are calling xbmc.log() explicitly. Therefore we return False
        # so every log message is filtered out and not printed again.
        if CLI_MODE:
            return True
        else:
            # Must not be imported until here because of import order issues
            # when running in CLI
            from xbmcswift2 import xbmc
            xbmc_level = XBMCFilter.xbmc_levels.get(
                XBMCFilter.python_to_xbmc.get(record.levelname))
            xbmc.log('%s%s' % (self.prefix, record.getMessage()), xbmc_level)
            return False

Response: Returns True if all records if running in CLI else returns False.


Instruction:
Write a Python 3 script for
testing a manifest name value for trademarks.

Response:
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_name', 'trademark'),
            'Add-on has potentially illegal name.',
            'Add-on names cannot contain the Mozilla or Firefox '
            'trademarks. These names should not be contained in add-on '
            'names if at all possible.',
            source)


Instruction:
Here you have a function in Python 3, explain what it does
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" format.
        '[a-z0-9-\.\+_]*\@[a-z0-9-\._]+'
        ')',
        re.I)

    err.metadata['id'] = value

    # Must be a valid UUID string.
    if not id_pattern.match(value):
        err.error(
            ('metadata_helpers', '_test_id', 'invalid'),
            'The value of {name} is invalid'.format(name=field_name),
            ['The values supplied for {name} in the {source} file is not a '
             'valid UUID string or email address.'.format(
                 name=field_name, source=source),
             'For help, please consult: '
             'https://developer.mozilla.org/en/install_manifests#id'],
            source)

Response: Tests a manifest UUID value


Instruction:
Can you generate a brief explanation for the following Python 3 code
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(
            ('metadata_helpers', '_test_version', 'too_long'),
            'The value of {name} is too long'.format(name=field_name),
            'Values supplied for {name} in the {source} file must be 32 '
            'characters or less.'.format(name=field_name, source=source),
            source)

    # Must be a valid version number.
    if not VERSION_PATTERN.match(value):
        err.error(
            ('metadata_helpers', '_test_version', 'invalid_format'),
            'The value of {name} is invalid'.format(name=field_name),
            'The values supplied for version in the {source} file is not a '
            'valid version string. It can only contain letters, numbers, and '
            'the symbols +*.-_.'.format(name=field_name, source=source),
            source)

Response: Tests a manifest version number


Instruction:
Implement a function in Python 3 to
query the status of a specific pin or all configured pins

Response:
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}, timeout=10)
            return r.json()
        except RequestException as err:
            raise Client.ClientError(err)


Instruction:
Explain what the following Python 3 code does
def get_status(self):
        url = self.base_url + '/status'
        try:
            r = requests.get(url, timeout=10)
            return r.json()
        except RequestException as err:
            raise Client.ClientError(err)

Response: Query the device status. Returns the device internal state.


Instruction:
How would you implement a function in Python 3 that
actuates a device pin

Response:
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"] = momentary

        if times is not None:
            payload["times"] = times

        if pause is not None:
            payload["pause"] = pause

        try:
            r = requests.put(url, json=payload, timeout=10)
            return r.json()
        except RequestException as err:
            raise Client.ClientError(err)


Instruction:
Given the following Python 3 function, write the documentation
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 + '/settings'

        payload = {
            "sensors": sensors,
            "actuators": actuators,
            "dht_sensors": dht_sensors,
            "ds18b20_sensors": ds18b20_sensors,
            "token": auth_token,
            "apiUrl": endpoint
        }

        if blink is not None:
            payload['blink'] = blink

        if discovery is not None:
            payload['discovery'] = discovery

        try:
            r = requests.put(url, json=payload, timeout=10)
            return r.ok
        except RequestException as err:
            raise Client.ClientError(err)

Response: Syncs the settings to the Konnected device


Instruction:
Here you have a function in Python 3, explain what it does
def parse_mime_type(mime_type):
    full_type, params = cgi.parse_header(mime_type)
    # Java URLConnection class sends an Accept header that includes a
    # single '*'. Turn it into a legal wildcard.
    if full_type == '*':
        full_type = '*/*'

    type_parts = full_type.split('/') if '/' in full_type else None
    if not type_parts or len(type_parts) > 2:
        raise MimeTypeParseException(
            "Can't parse type \"{}\"".format(full_type))

    (type, subtype) = type_parts

    return (type.strip(), subtype.strip(), params)

Response: Parses a mime - type into its component parts.


Instruction:
Write a Python 3 function that can
parse a media - range into its component parts.

Response:
def parse_media_range(range):
    """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', '0.5'})

    In addition this function also guarantees that there is a value for 'q'
    in the params dictionary, filling it in with a proper default if
    necessary.

    :rtype: (str,str,dict)
    """
    (type, subtype, params) = parse_mime_type(range)
    params.setdefault('q', params.pop('Q', None))  # q is case insensitive
    try:
        if not params['q'] or not 0 <= float(params['q']) <= 1:
            params['q'] = '1'
    except ValueError:  # from float()
        params['q'] = '1'

    return (type, subtype, params)


Instruction:
Can you tell what is the following Python 3 function doing
def quality_and_fitness_parsed(mime_type, parsed_ranges):
    best_fitness = -1
    best_fit_q = 0
    (target_type, target_subtype, target_params) = \
        parse_media_range(mime_type)

    for (type, subtype, params) in parsed_ranges:

        # check if the type and the subtype match
        type_match = (
            type in (target_type, '*') or
            target_type == '*'
        )
        subtype_match = (
            subtype in (target_subtype, '*') or
            target_subtype == '*'
        )

        # if they do, assess the "fitness" of this mime_type
        if type_match and subtype_match:

            # 100 points if the type matches w/o a wildcard
            fitness = type == target_type and 100 or 0

            # 10 points if the subtype matches w/o a wildcard
            fitness += subtype == target_subtype and 10 or 0

            # 1 bonus point for each matching param besides "q"
            param_matches = sum([
                1 for (key, value) in target_params.items()
                if key != 'q' and key in params and value == params[key]
            ])
            fitness += param_matches

            # finally, add the target's "q" param (between 0 and 1)
            fitness += float(target_params.get('q', 1))

            if fitness > best_fitness:
                best_fitness = fitness
                best_fit_q = params['q']

    return float(best_fit_q), best_fitness

Response: Find the best match for a given mime - type amongst parsed media - ranges. Returns a tuple of the fitness value and the value of the q quality parameter of the best match.


Instruction:
Can you generate the documentation for the following Python 3 function
def quality(mime_type, ranges):
    parsed_ranges = [parse_media_range(r) for r in ranges.split(',')]

    return quality_parsed(mime_type, parsed_ranges)

Response: Return the quality of a mime - type against a list of media - ranges.


Instruction:
Explain what the following Python 3 code does
def best_match(supported, header):
    split_header = _filter_blank(header.split(','))
    parsed_header = [parse_media_range(r) for r in split_header]
    weighted_matches = []
    pos = 0
    for mime_type in supported:
        weighted_matches.append((
            quality_and_fitness_parsed(mime_type, parsed_header),
            pos,
            mime_type
        ))
        pos += 1
    weighted_matches.sort()

    return weighted_matches[-1][0][0] and weighted_matches[-1][2] or ''

Response: Return mime - type with the highest quality ('q') from list of candidates.


Instruction:
Here you have a function in Python 3, explain what it does
def makeXsl(filename):
  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 = etree.parse(path)
  return etree.XSLT(xml)

Response: Helper that creates a XSLT stylesheet from a file.


Instruction:
Can you write a function in Python 3 where it
gives a collxml file this returns an HTML version of it

Response:
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 = etree.parse(collxml_file)
    xslt = makeXsl('collxml2xhtml.xsl')
    xml = xslt(xml)
    return xml


Instruction:
Create a Python 3 function for
giving a module cnxml file this returns an HTML version of it

Response:
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


Instruction:
Write a Python 3 script to
give an unzipped collection generate a giant HTML file representing the entire collection

Response:
def transform_collection(collection_dir):
    """ Given an unzipped collection generate a giant HTML file representing
        the entire collection (including loading and converting individual modules) """

    collxml_file = open(os.path.join(collection_dir, 'collection.xml'))
    collxml_html = transform_collxml(collxml_file)

    # For each included module, parse and convert it
    for node in INCLUDE_XPATH(collxml_html):
        href = node.attrib['href']
        module = href.split('@')[0]
        # version = None # We don't care about version
        module_dir = os.path.join(collection_dir, module)

        # By default, use the index_auto_generated.cnxml file for the module
        module_path = os.path.join(module_dir, 'index_auto_generated.cnxml')
        if not os.path.exists(module_path):
          module_path = os.path.join(module_dir, 'index.cnxml')

        module_html = transform_cnxml(module_path)

        # Replace the include link with the body of the module
        module_body = MODULE_BODY_XPATH(module_html)

        node.getparent().replace(node, module_body[0])
    return collxml_html