def send_agi_command(self, channel, command, as_list=False):

action = actions.Command({'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': channel,<EOL>'<STR_LIT>': command},<EOL>as_list=as_list)<EOL>return self.send_action(action)<EOL>

Send a :class:`~panoramisk.actions.Command` to the server:

        :param channel: Channel name where to launch command.
               Ex: 'SIP/000000-00000a53'
        :type channel: String
        :param command: command to launch. Ex: 'GET VARIABLE async_agi_server'
        :type command: String
        :param as_list: If True, the action Future will retrieve all responses
        :type as_list: boolean
        :return: a Future that will receive the response
        :rtype: asyncio.Future

        :Example:

        ::

            manager = Manager()
            resp = manager.send_agi_command('SIP/000000-00000a53',
                                            'GET VARIABLE async_agi_server')

        Return a response :class:`~panoramisk.message.Message`.
        See https://wiki.asterisk.org/wiki/display/AST/Asterisk+11+ManagerAction_AGI


if self.loop is None:  <EOL><INDENT>self.loop = asyncio.get_event_loop()<EOL><DEDENT>t = asyncio.Task(<EOL>self.loop.create_connection(<EOL>self.config['<STR_LIT>'],<EOL>self.config['<STR_LIT:host>'], self.config['<STR_LIT:port>'],<EOL>ssl=self.config['<STR_LIT>']),<EOL>loop=self.loop)<EOL>t.add_done_callback(self.connection_made)<EOL>return t<EOL>


def register_event(self, pattern, callback=None):

def _register_event(callback):<EOL><INDENT>if not self.callbacks[pattern]:<EOL><INDENT>self.patterns.append((pattern,<EOL>re.compile(fnmatch.translate(pattern))))<EOL><DEDENT>self.callbacks[pattern].append(callback)<EOL>return callback<EOL><DEDENT>if callback is not None:<EOL><INDENT>return _register_event(callback)<EOL><DEDENT>else:<EOL><INDENT>return _register_event<EOL><DEDENT>

register an event. See :class:`~panoramisk.message.Message`:

        .. code-block:: python

            >>> def callback(manager, event):
            ...     print(manager, event)
            >>> manager = Manager()
            >>> manager.register_event('Meetme*', callback)
            <function callback at 0x...>

        You can also use the manager as a decorator:

        .. code-block:: python

            >>> manager = Manager()
            >>> @manager.register_event('Meetme*')
            ... def callback(manager, event):
            ...     print(manager, event)


if self.pinger:<EOL><INDENT>self.pinger.cancel()<EOL>self.pinger = None<EOL><DEDENT>if getattr(self, '<STR_LIT>', None):<EOL><INDENT>self.protocol.close()<EOL><DEDENT>


if '<STR_LIT>' in self:<EOL><INDENT>return True<EOL><DEDENT>if self.response in self.success_responses:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

return True if a response status is Success or Follows:

        .. code-block:: python

            >>> resp = Message({'Response': 'Success'})
            >>> print(resp.success)
            True
            >>> resp['Response'] = 'Failed'
            >>> resp.success
            False


for line in self.content.split('<STR_LIT:\n>'):<EOL><INDENT>yield line<EOL><DEDENT>


if '<STR_LIT>' in self:<EOL><INDENT>return utils.parse_agi_result(self['<STR_LIT>'])<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % self)<EOL><DEDENT>


values = self.get(key, None)<EOL>if not isinstance(values, list):<EOL><INDENT>raise TypeError("<STR_LIT>".format(key, values))<EOL><DEDENT>result = utils.CaseInsensitiveDict()<EOL>for item in values:<EOL><INDENT>k, v = item.split('<STR_LIT:=>', <NUM_LIT:1>)<EOL>result[k] = v<EOL><DEDENT>return result<EOL>

Convert a multi values header to a case-insensitive dict:

        .. code-block:: python

            >>> resp = Message({
            ...     'Response': 'Success',
            ...     'ChanVariable': [
            ...         'FROM_DID=', 'SIPURI=sip:42@10.10.10.1:4242'],
            ... })
            >>> print(resp.chanvariable)
            ['FROM_DID=', 'SIPURI=sip:42@10.10.10.1:4242']
            >>> value = resp.getdict('chanvariable')
            >>> print(value['sipuri'])
            sip:42@10.10.10.1:4242


command += '<STR_LIT:\n>'<EOL>self.writer.write(command.encode(self.encoding))<EOL>yield from self.writer.drain()<EOL>agi_result = yield from self._read_result()<EOL>while agi_result.get('<STR_LIT>') == <NUM_LIT:100>:<EOL><INDENT>agi_result = yield from self._read_result()<EOL><DEDENT>if '<STR_LIT:error>' in agi_result and agi_result['<STR_LIT:error>'] == '<STR_LIT>':<EOL><INDENT>buff_usage_error = yield from self.reader.readline()<EOL>agi_result['<STR_LIT>'] += buff_usage_error.decode(self.encoding)<EOL><DEDENT>return agi_result<EOL>

Send a command for FastAGI request:

        :param command: Command to launch on FastAGI request. Ex: 'EXEC StartMusicOnHolds'
        :type command: String

        :Example:

        ::

            @asyncio.coroutine
            def call_waiting(request):
                print(['AGI variables:', request.headers])
                yield from request.send_command('ANSWER')
                yield from request.send_command('EXEC StartMusicOnHold')
                yield from request.send_command('EXEC Wait 10')


response = yield from self.reader.readline()<EOL>return parse_agi_result(response.decode(self.encoding)[:-<NUM_LIT:1>])<EOL>

Parse read a response from the AGI and parse it.

        :return dict: The AGI response parsed into a dict.


assert callable(endpoint), endpoint<EOL>if path in self._route:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if not asyncio.iscoroutinefunction(endpoint):<EOL><INDENT>endpoint = asyncio.coroutine(endpoint)<EOL><DEDENT>self._route[path] = endpoint<EOL>

Add a route for FastAGI requests:

        :param path: URI to answer. Ex: 'calls/start'
        :type path: String
        :param endpoint: command to launch. Ex: start
        :type endpoint: callable

        :Example:

        ::

            @asyncio.coroutine
            def start(request):
                print('Receive a FastAGI request')
                print(['AGI variables:', request.headers])

            fa_app = Application()
            fa_app.add_route('calls/start', start)


if path not in self._route:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>del(self._route[path])<EOL>

Delete a route for FastAGI requests:

        :param path: URI to answer. Ex: 'calls/start'
        :type path: String

        :Example:

        ::

            @asyncio.coroutine
            def start(request):
                print('Receive a FastAGI request')
                print(['AGI variables:', request.headers])

            fa_app = Application()
            fa_app.add_route('calls/start', start)
            fa_app.del_route('calls/start')


@asyncio.coroutine<EOL><INDENT>def handler(self, reader, writer):<DEDENT>

buffer = b'<STR_LIT>'<EOL>while b'<STR_LIT>' not in buffer:<EOL><INDENT>buffer += yield from reader.read(self.buf_size)<EOL><DEDENT>lines = buffer[:-<NUM_LIT:2>].decode(self.default_encoding).split('<STR_LIT:\n>')<EOL>headers = OrderedDict([<EOL>line.split('<STR_LIT>', <NUM_LIT:1>) for line in lines if '<STR_LIT>' in line<EOL>])<EOL>agi_network_script = headers.get('<STR_LIT>')<EOL>log.info('<STR_LIT>',<EOL>writer.get_extra_info('<STR_LIT>'), agi_network_script)<EOL>log.debug("<STR_LIT>", headers)<EOL>if agi_network_script is not None:<EOL><INDENT>route = self._route.get(agi_network_script)<EOL>if route is not None:<EOL><INDENT>request = Request(app=self,<EOL>headers=headers,<EOL>reader=reader, writer=writer,<EOL>encoding=self.default_encoding)<EOL>try:<EOL><INDENT>yield from route(request)<EOL><DEDENT>except BaseException:<EOL><INDENT>log.exception(<EOL>'<STR_LIT>',<EOL>agi_network_script<EOL>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>log.error('<STR_LIT>', agi_network_script)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>log.error('<STR_LIT>')<EOL><DEDENT>log.debug("<STR_LIT>")<EOL>writer.close()<EOL>

AsyncIO coroutine handler to launch socket listening.

        :Example:

        ::

            @asyncio.coroutine
            def start(request):
                print('Receive a FastAGI request')
                print(['AGI variables:', request.headers])

            fa_app = Application()
            fa_app.add_route('calls/start', start)
            coro = asyncio.start_server(fa_app.handler, '0.0.0.0', 4574)
            server = loop.run_until_complete(coro)

        See https://docs.python.org/3/library/asyncio-stream.html


<EOL>if line == '<STR_LIT>':<EOL><INDENT>return {'<STR_LIT:error>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'}<EOL><DEDENT>kwargs = dict(code=<NUM_LIT:0>, response="<STR_LIT>", line=line)<EOL>m = re_code.search(line)<EOL>try:<EOL><INDENT>kwargs.update(m.groupdict())<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>return agi_code_check(**kwargs)<EOL>

Parse AGI results using Regular expression.

    AGI Result examples::

        100 result=0 Trying...

        200 result=0

        200 result=-1

        200 result=132456

        200 result= (timeout)

        510 Invalid or unknown command

        520-Invalid command syntax. Proper usage follows:
        int() argument must be a string, a bytes-like object or a number, not
        'NoneType'

        HANGUP


def agi_code_check(code=None, response=None, line=None):

code = int(code)<EOL>response = response or "<STR_LIT>"<EOL>result = {'<STR_LIT>': code, '<STR_LIT:result>': ('<STR_LIT>', '<STR_LIT>'), '<STR_LIT>': '<STR_LIT>'}<EOL>if code == <NUM_LIT:100>:<EOL><INDENT>result['<STR_LIT>'] = line<EOL><DEDENT>elif code == <NUM_LIT:200>:<EOL><INDENT>for key, value, data in re_kv.findall(response):<EOL><INDENT>result[key] = (value, data)<EOL>if data == '<STR_LIT>':<EOL><INDENT>return {<EOL>'<STR_LIT:error>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'}<EOL><DEDENT>elif key == '<STR_LIT:result>' and value == '<STR_LIT>':<EOL><INDENT>return {<EOL>'<STR_LIT:error>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'}<EOL><DEDENT><DEDENT><DEDENT>elif code == <NUM_LIT>:<EOL><INDENT>result['<STR_LIT:error>'] = '<STR_LIT>'<EOL><DEDENT>elif code == <NUM_LIT>:<EOL><INDENT>result['<STR_LIT:error>'] = '<STR_LIT>'<EOL>result['<STR_LIT>'] = line<EOL><DEDENT>else:<EOL><INDENT>result['<STR_LIT:error>'] = '<STR_LIT>'<EOL>result['<STR_LIT>'] = line<EOL><DEDENT>return result<EOL>

Check the AGI code and return a dict to help on error handling.


for instance in cls.instances:<EOL><INDENT>if uid:<EOL><INDENT>instance.uid = uid<EOL><DEDENT>instance.generator = instance.get_generator()<EOL><DEDENT>

Mostly used for unit testing. Allow to use a static uuid and reset
        all counter


return ["<STR_LIT>" % (self.__class__.__name__,<EOL>i.prefix, self.uid)<EOL>for i in self.instances]<EOL>


flist = []<EOL>for dirpath, _dirnames, filenames in os.walk(dirname):<EOL><INDENT>for fname in filenames:<EOL><INDENT>flist.append(osp.join(dirpath, fname))<EOL><DEDENT><DEDENT>return flist<EOL>

Return data files in directory *dirname*


<EOL>version = "<STR_LIT>".format(version=__version__)<EOL>parser = OptionParser(version=version)<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>", action="<STR_LIT:store>", dest="<STR_LIT:username>",<EOL>type="<STR_LIT:string>", default="<STR_LIT>", metavar="<STR_LIT>", help="<STR_LIT:user>"<EOL>)<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>", metavar="<STR_LIT>", action="<STR_LIT:store>",<EOL>type="<STR_LIT:string>", dest="<STR_LIT>", default="<STR_LIT>", help="<STR_LIT>"<EOL>)<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>", metavar="<STR_LIT>", action="<STR_LIT:store>",<EOL>type="<STR_LIT:string>", dest="<STR_LIT>", default="<STR_LIT>", help="<STR_LIT>"<EOL>)<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>", metavar="<STR_LIT>", action="<STR_LIT:store>",<EOL>type="<STR_LIT:string>", dest="<STR_LIT:message>", default="<STR_LIT>", help="<STR_LIT>"<EOL>)<EOL>parser.add_option(<EOL>"<STR_LIT:-c>", "<STR_LIT>", metavar="<STR_LIT>", action="<STR_LIT:store>",<EOL>type="<STR_LIT:string>", dest="<STR_LIT>", help="<STR_LIT>",<EOL>default="<STR_LIT>")<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>", metavar="<STR_LIT>", action="<STR_LIT:store_true>",<EOL>default=False, dest="<STR_LIT>", help="<STR_LIT>"<EOL>)<EOL>parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>", metavar="<STR_LIT>",<EOL>action="<STR_LIT:store_true>", default=False, dest="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>)<EOL>options = parser.parse_args(sys.argv)[<NUM_LIT:0>]<EOL>mandatories = ["<STR_LIT:username>", ]<EOL>if not options.get_google_credentials:<EOL><INDENT>mandatories.append("<STR_LIT>")  <EOL>mandatories.append("<STR_LIT:message>")  <EOL>mandatories.append("<STR_LIT>")  <EOL><DEDENT>if not all(options.__dict__[mandatory] for mandatory in mandatories):<EOL><INDENT>parser.error("<STR_LIT>")<EOL><DEDENT>return options<EOL>


if os.path.exists(options.config):<EOL><INDENT>config = configparser.ConfigParser()<EOL>try:<EOL><INDENT>config.read(options.config)<EOL><DEDENT>except Exception as err:<EOL><INDENT>if not options.quiet:<EOL><INDENT>sys.stderr.write("<STR_LIT>".format(config=options.config, err=err))<EOL><DEDENT>sys.exit(-<NUM_LIT:1>)<EOL><DEDENT>try:<EOL><INDENT>configdata = {<EOL>"<STR_LIT>": config.get("<STR_LIT>", "<STR_LIT>"),<EOL>"<STR_LIT>": config.get("<STR_LIT>", "<STR_LIT>"),<EOL>"<STR_LIT:start>": config.get("<STR_LIT>", "<STR_LIT:start>"),<EOL>"<STR_LIT:end>": config.get("<STR_LIT>", "<STR_LIT:end>"),<EOL>"<STR_LIT:message>": config.get("<STR_LIT>", "<STR_LIT:message>"),<EOL>}<EOL><DEDENT>except configparser.NoOptionError as err:<EOL><INDENT>if not options.quiet:<EOL><INDENT>sys.stderr.write("<STR_LIT>".format(err=err))<EOL><DEDENT>sys.exit(-<NUM_LIT:1>)<EOL><DEDENT>mandatories = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT:start>", "<STR_LIT:end>", "<STR_LIT:message>", ]<EOL>if not all(configdata[mandatory] for mandatory in mandatories):<EOL><INDENT>if not options.quiet:<EOL><INDENT>sys.stdout.write("<STR_LIT>")<EOL><DEDENT>sys.exit(<NUM_LIT:0>)<EOL><DEDENT>return configdata<EOL><DEDENT>else:<EOL><INDENT>if not options.quiet:<EOL><INDENT>sys.stderr.write("<STR_LIT>".format(config=options.config))<EOL><DEDENT>sys.exit(<NUM_LIT:0>)<EOL><DEDENT>


try:<EOL><INDENT>if options.get_google_credentials:<EOL><INDENT>flow = flow_from_clientsecrets(config["<STR_LIT>"], scope=SCOPE, redirect_uri="<STR_LIT>")<EOL>sys.stdout.write("<STR_LIT>".format(url=flow.step1_get_authorize_url()))<EOL>token = input("<STR_LIT>")<EOL>credentials = flow.step2_exchange(token)<EOL>storage = Storage(os.path.join(config["<STR_LIT>"], "<STR_LIT>".format(username=options.username)))<EOL>storage.put(credentials)<EOL>credentials.set_store(storage)<EOL><DEDENT>else:<EOL><INDENT>storage = Storage(os.path.join(config["<STR_LIT>"], "<STR_LIT>".format(username=options.username)))<EOL>credentials = storage.get()<EOL><DEDENT><DEDENT>except Exception as err:<EOL><INDENT>if not options.quiet:<EOL><INDENT>sys.stderr.write("<STR_LIT>".format(err=err))<EOL><DEDENT>sys.exit(-<NUM_LIT:1>)<EOL><DEDENT>return credentials<EOL>


now = datetime.datetime.now()<EOL>return {<EOL>"<STR_LIT:start>": {<EOL>"<STR_LIT>": (now + datetime.timedelta(minutes=int(config["<STR_LIT:start>"]))).strftime(DT_FORMAT),<EOL>"<STR_LIT>": options.timezone,<EOL>},<EOL>"<STR_LIT:end>": {<EOL>"<STR_LIT>": (now + datetime.timedelta(minutes=int(config["<STR_LIT:end>"]))).strftime(DT_FORMAT),<EOL>"<STR_LIT>": options.timezone,<EOL>},<EOL>}<EOL>


def create_event(options, config, credentials):

try:<EOL><INDENT>http = credentials.authorize(httplib2.Http())<EOL>service = build("<STR_LIT>", "<STR_LIT>", http=http)<EOL>event = {<EOL>"<STR_LIT>": options.message,<EOL>"<STR_LIT:location>": "<STR_LIT>",<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT>": [<EOL>{<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": config["<STR_LIT:message>"],<EOL>},<EOL>],<EOL>}<EOL>}<EOL>event.update(create_event_datetimes(options, config))<EOL>service.events().insert(calendarId=options.calendar, sendNotifications=True, body=event).execute()<EOL><DEDENT>except Exception as err:<EOL><INDENT>if not options.quiet:<EOL><INDENT>sys.stderr.write("<STR_LIT>".format(err=err))<EOL><DEDENT>sys.exit(-<NUM_LIT:1>)<EOL><DEDENT>

Create event in calendar with sms reminder.


<EOL>options = parse_options()<EOL>config = parse_config(options)<EOL>credentials = get_google_credentials(options, config)<EOL>if not options.get_google_credentials:<EOL><INDENT>create_event(options, config, credentials)<EOL><DEDENT>

Processing notification call main function.


def get_model_url_name(model_nfo, page, with_namespace=False):

prefix = '<STR_LIT>'<EOL>if with_namespace:<EOL><INDENT>prefix = '<STR_LIT>'<EOL><DEDENT>return ('<STR_LIT>' % (prefix, '<STR_LIT>' % model_nfo, page)).lower()<EOL>

Returns a URL for a given Tree admin page type.


return get_model_url_name(get_app_n_model('<STR_LIT>'), page, with_namespace)<EOL>


Returns a URL for a given Tree Item admin page type.


try:<EOL><INDENT>admin.site.unregister(MODEL_TREE_CLASS)<EOL><DEDENT>except NotRegistered:<EOL><INDENT>pass<EOL><DEDENT>admin.site.register(MODEL_TREE_CLASS, _TREE_ADMIN())<EOL>

Forces unregistration of tree admin class with following re-registration.


global _TREE_ADMIN<EOL>_TREE_ADMIN = lambda: admin_class<EOL>_reregister_tree_admin()<EOL>

Sets a class that should be used instead of TreeAdmin
    to represent trees in the Admin interface.
    Note that the class must inherit from TreeAdmin.


global _ITEM_ADMIN<EOL>_ITEM_ADMIN = lambda: admin_class<EOL>_reregister_tree_admin()<EOL>

Sets a class that should be used instead of TreeItemAdmin
    to represent tree items in the Admin interface.
    Note that the class must inherit from TreeItemAdmin.


path = args[<NUM_LIT:0>].path<EOL>shift = '<STR_LIT>'<EOL>if '<STR_LIT>' in path:<EOL><INDENT>shift += '<STR_LIT>'<EOL><DEDENT>elif '<STR_LIT>' in path:<EOL><INDENT>if '<STR_LIT>' not in kwargs:<EOL><INDENT>shift += '<STR_LIT>'<EOL><DEDENT><DEDENT>return HttpResponseRedirect(path + shift)<EOL>

Fixes Admin contrib redirects compatibility problems
    introduced in Django 1.4 by url handling changes.


if '<STR_LIT>' in request.POST:<EOL><INDENT>return HttpResponseRedirect('<STR_LIT>')<EOL><DEDENT>elif '<STR_LIT>' in request.POST:<EOL><INDENT>return HttpResponseRedirect('<STR_LIT>')<EOL><DEDENT>elif '<STR_LIT>' in request.POST:<EOL><INDENT>return response<EOL><DEDENT>return HttpResponseRedirect('<STR_LIT>')<EOL>


def response_add(self, request, obj, post_url_continue=None, **kwargs):

if post_url_continue is None:<EOL><INDENT>post_url_continue = '<STR_LIT>' % obj.pk<EOL><DEDENT>return self._redirect(request, super(TreeItemAdmin, self).response_add(request, obj, post_url_continue))<EOL>

Redirects to the appropriate items' 'continue' page on item add.

        As we administer tree items within tree itself, we
        should make some changes to redirection process.


def response_change(self, request, obj, **kwargs):

return self._redirect(request, super(TreeItemAdmin, self).response_change(request, obj))<EOL>

Redirects to the appropriate items' 'add' page on item change.

        As we administer tree items within tree itself, we
        should make some changes to redirection process.


def get_form(self, request, obj=None, **kwargs):

if obj is not None and obj.parent is not None:<EOL><INDENT>self.previous_parent = obj.parent<EOL>previous_parent_id = self.previous_parent.id<EOL><DEDENT>else:<EOL><INDENT>previous_parent_id = None<EOL><DEDENT>my_choice_field = TreeItemChoiceField(self.tree, initial=previous_parent_id)<EOL>form = super(TreeItemAdmin, self).get_form(request, obj, **kwargs)<EOL>my_choice_field.label = form.base_fields['<STR_LIT>'].label<EOL>my_choice_field.help_text = form.base_fields['<STR_LIT>'].help_text<EOL>my_choice_field.widget = form.base_fields['<STR_LIT>'].widget<EOL>form.base_fields['<STR_LIT>'] = my_choice_field<EOL>if not getattr(self, '<STR_LIT>', False):<EOL><INDENT>self.known_url_names = []<EOL>self.known_url_rules = []<EOL>resolver = get_resolver(get_urlconf())<EOL>for ns, (url_prefix, ns_resolver) in resolver.namespace_dict.items():<EOL><INDENT>if ns != '<STR_LIT>':<EOL><INDENT>self._stack_known_urls(ns_resolver.reverse_dict, ns)<EOL><DEDENT><DEDENT>self._stack_known_urls(resolver.reverse_dict)<EOL>self.known_url_rules = sorted(self.known_url_rules)<EOL><DEDENT>form.known_url_names_hint = _(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>form.known_url_names = self.known_url_names<EOL>form.known_url_rules = self.known_url_rules<EOL>return form<EOL>

Returns modified form for TreeItem model.
        'Parent' field choices are built by sitetree itself.


def get_tree(self, request, tree_id, item_id=None):

if tree_id is None:<EOL><INDENT>tree_id = self.get_object(request, item_id).tree_id<EOL><DEDENT>self.tree = MODEL_TREE_CLASS._default_manager.get(pk=tree_id)<EOL>self.tree.verbose_name_plural = self.tree._meta.verbose_name_plural<EOL>self.tree.urls = _TREE_URLS<EOL>return self.tree<EOL>

Fetches Tree for current or given TreeItem.


def item_move(self, request, tree_id, item_id, direction):

current_item = MODEL_TREE_ITEM_CLASS._default_manager.get(pk=item_id)<EOL>if direction == '<STR_LIT>':<EOL><INDENT>sort_order = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>sort_order = '<STR_LIT>'<EOL><DEDENT>siblings = MODEL_TREE_ITEM_CLASS._default_manager.filter(<EOL>parent=current_item.parent,<EOL>tree=current_item.tree<EOL>).order_by(sort_order)<EOL>previous_item = None<EOL>for item in siblings:<EOL><INDENT>if item != current_item:<EOL><INDENT>previous_item = item<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if previous_item is not None:<EOL><INDENT>current_item_sort_order = current_item.sort_order<EOL>previous_item_sort_order = previous_item.sort_order<EOL>current_item.sort_order = previous_item_sort_order<EOL>previous_item.sort_order = current_item_sort_order<EOL>current_item.save()<EOL>previous_item.save()<EOL><DEDENT>return HttpResponseRedirect('<STR_LIT>')<EOL>

Moves item up or down by swapping 'sort_order' field values of neighboring items.


def save_model(self, request, obj, form, change):

if change:<EOL><INDENT>if obj.parent is not None and obj.parent.id == obj.id:<EOL><INDENT>obj.parent = self.previous_parent<EOL>messages.warning(<EOL>request, _("<STR_LIT>"), '<STR_LIT>', True)<EOL><DEDENT><DEDENT>obj.tree = self.tree<EOL>obj.save()<EOL>

Saves TreeItem model under certain Tree.
        Handles item's parent assignment exception.


urls = super(TreeAdmin, self).get_urls()<EOL>prefix_change = '<STR_LIT>' if DJANGO_POST_19 else '<STR_LIT>'<EOL>sitetree_urls = [<EOL>url(r'<STR_LIT>', redirects_handler, name=get_tree_item_url_name('<STR_LIT>')),<EOL>url(r'<STR_LIT>' % prefix_change,<EOL>self.admin_site.admin_view(self.tree_admin.item_add), name=get_tree_item_url_name('<STR_LIT>')),<EOL>url(r'<STR_LIT>' % prefix_change,<EOL>self.admin_site.admin_view(self.tree_admin.item_edit), name=get_tree_item_url_name('<STR_LIT>')),<EOL>url(r'<STR_LIT>' % prefix_change,<EOL>self.admin_site.admin_view(self.tree_admin.item_edit), name=get_tree_item_url_name('<STR_LIT>')),<EOL>url(r'<STR_LIT>' % prefix_change,<EOL>self.admin_site.admin_view(self.tree_admin.item_delete), name=get_tree_item_url_name('<STR_LIT>')),<EOL>url(r'<STR_LIT>' % prefix_change,<EOL>self.admin_site.admin_view(self.tree_admin.item_history), name=get_tree_item_url_name('<STR_LIT>')),<EOL>url(r'<STR_LIT>' % prefix_change,<EOL>self.admin_site.admin_view(self.tree_admin.item_move), name=get_tree_item_url_name('<STR_LIT>')),<EOL>]<EOL>if not DJANGO_POST_19:<EOL><INDENT>sitetree_urls = patterns_func('<STR_LIT>', *sitetree_urls)<EOL><DEDENT>if SMUGGLER_INSTALLED:<EOL><INDENT>sitetree_urls += (url(r'<STR_LIT>', self.admin_site.admin_view(self.dump_view), name='<STR_LIT>'),)<EOL><DEDENT>return sitetree_urls + urls<EOL>

Manages not only TreeAdmin URLs but also TreeItemAdmin URLs.


from smuggler.views import dump_to_response<EOL>return dump_to_response(request, [MODEL_TREE, MODEL_TREE_ITEM], filename_prefix='<STR_LIT>')<EOL>

Dumps sitetrees with items using django-smuggler.

        :param request:
        :return:


tokens = token.split_contents()<EOL>use_template = detect_clause(parser, '<STR_LIT>', tokens)<EOL>tokens_num = len(tokens)<EOL>if tokens_num in (<NUM_LIT:3>, <NUM_LIT:5>):<EOL><INDENT>tree_alias = parser.compile_filter(tokens[<NUM_LIT:2>])<EOL>return sitetree_treeNode(tree_alias, use_template)<EOL><DEDENT>else:<EOL><INDENT>raise template.TemplateSyntaxError(<EOL>'<STR_LIT>' % tokens[<NUM_LIT:0>])<EOL><DEDENT>

Parses sitetree tag parameters.

    Two notation types are possible:
        1. Two arguments:
           {% sitetree_tree from "mytree" %}
           Used to render tree for "mytree" site tree.

        2. Four arguments:
           {% sitetree_tree from "mytree" template "sitetree/mytree.html" %}
           Used to render tree for "mytree" site tree using specific
           template "sitetree/mytree.html"


tokens = token.split_contents()<EOL>use_template = detect_clause(parser, '<STR_LIT>', tokens)<EOL>tokens_num = len(tokens)<EOL>clauses_in_places = (<EOL>tokens_num == <NUM_LIT:5> and tokens[<NUM_LIT:1>] == '<STR_LIT>' and tokens[<NUM_LIT:3>] == '<STR_LIT>' and tokens[<NUM_LIT:4>] in ('<STR_LIT>', '<STR_LIT>')<EOL>)<EOL>if clauses_in_places and use_template is not None:<EOL><INDENT>tree_item = tokens[<NUM_LIT:2>]<EOL>navigation_type = tokens[<NUM_LIT:4>]<EOL>return sitetree_childrenNode(tree_item, navigation_type, use_template)<EOL><DEDENT>else:<EOL><INDENT>raise template.TemplateSyntaxError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % tokens[<NUM_LIT:0>])<EOL><DEDENT>

Parses sitetree_children tag parameters.

       Six arguments:
           {% sitetree_children of someitem for menu template "sitetree/mychildren.html" %}
           Used to render child items of specific site tree 'someitem'
           using template "sitetree/mychildren.html" for menu navigation.

           Basically template argument should contain path to current template itself.

           Allowed navigation types: 1) menu; 2) sitetree.


tokens = token.split_contents()<EOL>use_template = detect_clause(parser, '<STR_LIT>', tokens)<EOL>tokens_num = len(tokens)<EOL>if tokens_num == <NUM_LIT:3>:<EOL><INDENT>tree_alias = parser.compile_filter(tokens[<NUM_LIT:2>])<EOL>return sitetree_breadcrumbsNode(tree_alias, use_template)<EOL><DEDENT>else:<EOL><INDENT>raise template.TemplateSyntaxError(<EOL>'<STR_LIT>' % tokens[<NUM_LIT:0>])<EOL><DEDENT>

Parses sitetree_breadcrumbs tag parameters.

    Two notation types are possible:
        1. Two arguments:
           {% sitetree_breadcrumbs from "mytree" %}
           Used to render breadcrumb path for "mytree" site tree.

        2. Four arguments:
           {% sitetree_breadcrumbs from "mytree" template "sitetree/mycrumb.html" %}
           Used to render breadcrumb path for "mytree" site tree using specific
           template "sitetree/mycrumb.html"


tokens = token.split_contents()<EOL>use_template = detect_clause(parser, '<STR_LIT>', tokens)<EOL>tokens_num = len(tokens)<EOL>if tokens_num == <NUM_LIT:5> and tokens[<NUM_LIT:3>] == '<STR_LIT>':<EOL><INDENT>tree_alias = parser.compile_filter(tokens[<NUM_LIT:2>])<EOL>tree_branches = parser.compile_filter(tokens[<NUM_LIT:4>])<EOL>return sitetree_menuNode(tree_alias, tree_branches, use_template)<EOL><DEDENT>else:<EOL><INDENT>raise template.TemplateSyntaxError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % tokens[<NUM_LIT:0>])<EOL><DEDENT>

Parses sitetree_menu tag parameters.

        {% sitetree_menu from "mytree" include "trunk,1,level3" %}
        Used to render trunk, branch with id 1 and branch aliased 'level3'
        elements from "mytree" site tree as a menu.

        These are reserved aliases:
            * 'trunk' - items without parents
            * 'this-children' - items under item resolved as current for the current page
            * 'this-siblings' - items under parent of item resolved as current for
              the current page (current item included)
            * 'this-ancestor-children' - items under grandparent item (closest to root)
              for the item resolved as current for the current page

        {% sitetree_menu from "mytree" include "trunk,1,level3" template "sitetree/mymenu.html" %}


return sitetree_urlNode.for_tag(parser, token, '<STR_LIT>', '<STR_LIT>')<EOL>

This tag is much the same as Django built-in 'url' tag.
    The difference is that after 'for' it should get TreeItem object.


return sitetree_page_titleNode.for_tag(parser, token, '<STR_LIT>', '<STR_LIT>')<EOL>

Renders a title for current page, resolved against sitetree item representing current URL.


return sitetree_page_descriptionNode.for_tag(parser, token, '<STR_LIT>', '<STR_LIT>')<EOL>

Renders a description for the current page, resolved against sitetree item representing current URL.


return sitetree_page_hintNode.for_tag(parser, token, '<STR_LIT>', '<STR_LIT>')<EOL>

Renders a hint for the current page, resolved against sitetree item representing current URL.


def detect_clause(parser, clause_name, tokens):

if clause_name in tokens:<EOL><INDENT>t_index = tokens.index(clause_name)<EOL>clause_value = parser.compile_filter(tokens[t_index + <NUM_LIT:1>])<EOL>del tokens[t_index:t_index + <NUM_LIT:2>]<EOL><DEDENT>else:<EOL><INDENT>clause_value = None<EOL><DEDENT>return clause_value<EOL>

Helper function detects a certain clause in tag tokens list.
    Returns its value.


def render(context, tree_items, use_template):

context.push()<EOL>context['<STR_LIT>'] = tree_items<EOL>if isinstance(use_template, FilterExpression):<EOL><INDENT>use_template = use_template.resolve(context)<EOL><DEDENT>content = get_template(use_template).render(context.flatten() if _CONTEXT_FLATTEN else context)<EOL>context.pop()<EOL>return content<EOL>

Render helper is used by template node functions
    to render given template with given tree items in context.


@classmethod<EOL><INDENT>def for_tag(cls, parser, token, preposition, error_hint):<DEDENT>

tokens = token.split_contents()<EOL>if len(tokens) >= <NUM_LIT:3> and tokens[<NUM_LIT:1>] == preposition:<EOL><INDENT>as_var = cls.get_as_var(tokens)<EOL>tree_alias = parser.compile_filter(tokens[<NUM_LIT:2>])<EOL>return cls(tree_alias, as_var)<EOL><DEDENT>raise template.TemplateSyntaxError(<EOL>'<STR_LIT>' % (tokens[<NUM_LIT:0>], error_hint))<EOL>


as_var = None<EOL>if tokens[-<NUM_LIT:2>] == '<STR_LIT>':<EOL><INDENT>as_var = tokens[-<NUM_LIT:1>]<EOL>tokens[-<NUM_LIT:2>:] = []<EOL><DEDENT>return as_var<EOL>

Returns context variable from `as` template tag clause if any.

         Modifies tokens inplace.

        :param tokens:
        :rtype: None|str


Should return a computed value to be used in render().


def get_options(option_func=None):<EOL><INDENT>from optparse import make_option<EOL>from django.core.management.base import BaseCommand<EOL>func = option_func or make_option<EOL>options = tuple([func(*option.args, **option.kwargs) for option in command_options])<EOL>if option_func is None:<EOL><INDENT>if VERSION < (<NUM_LIT:1>, <NUM_LIT:8>):<EOL><INDENT>result = BaseCommand.option_list + options<EOL><DEDENT>else:<EOL><INDENT>result = []<EOL><DEDENT><DEDENT>else:<EOL><INDENT>result = options<EOL><DEDENT>return result<EOL><DEDENT>return get_options<EOL>

Compatibility function to get rid of optparse in management commands after Django 1.10.

    :param tuple command_options: tuple with `CommandOption` objects.


tree_token = u'<STR_LIT>' % (self.tree, self.template)<EOL>context_kwargs = {'<STR_LIT>': '<STR_LIT>'}<EOL>context = template.Context(context_kwargs) if VERSION >= (<NUM_LIT:1>, <NUM_LIT:8>) else template.Context(**context_kwargs)<EOL>context.update({'<STR_LIT>': object()})<EOL>choices_str = sitetree_tree(<EOL>Parser(None), Token(token_type=TOKEN_BLOCK, contents=tree_token)<EOL>).render(context)<EOL>tree_choices = [(ITEMS_FIELD_ROOT_ID, self.root_title)]<EOL>for line in choices_str.splitlines():<EOL><INDENT>if line.strip():<EOL><INDENT>splitted = line.split('<STR_LIT>')<EOL>tree_choices.append((splitted[<NUM_LIT:0>], mark_safe(splitted[<NUM_LIT:1>])))<EOL><DEDENT><DEDENT>return tree_choices<EOL>

Build choices list runtime using 'sitetree_tree' tag


sitetree = getattr(_THREAD_LOCAL, _THREAD_SITETREE, None)<EOL>if sitetree is None:<EOL><INDENT>sitetree = SiteTree()<EOL>setattr(_THREAD_LOCAL, _THREAD_SITETREE, sitetree)<EOL><DEDENT>return sitetree<EOL>

Returns SiteTree (thread-singleton) object, implementing utility methods.

    :rtype: SiteTree


global _ITEMS_PROCESSOR<EOL>global _ITEMS_PROCESSOR_ARGS_LEN<EOL>_ITEMS_PROCESSOR = func<EOL>if func:<EOL><INDENT>args_len = len(getargspec(func).args)<EOL>if args_len not in {<NUM_LIT:2>, <NUM_LIT:3>}:<EOL><INDENT>raise SiteTreeError('<STR_LIT>')<EOL><DEDENT>_ITEMS_PROCESSOR_ARGS_LEN = args_len<EOL><DEDENT>

Registers a hook callable to process tree items right before they are passed to templates.

    Callable should be able to:

        a) handle ``tree_items`` and ``tree_sender`` key params.
            ``tree_items`` will contain a list of extended TreeItem objects ready to pass to template.
            ``tree_sender`` will contain navigation type identifier
                (e.g.: `menu`, `sitetree`, `breadcrumbs`, `menu.children`, `sitetree.children`)

        b) return a list of extended TreeItems objects to pass to template.

    Example::

        # Put the following code somewhere where it'd be triggered as expected. E.g. in app view.py.

        # First import the register function.
        from sitetree.sitetreeapp import register_items_hook

        # The following function will be used as items processor.
        def my_items_processor(tree_items, tree_sender):
            # Suppose we want to process only menu child items.
            if tree_sender == 'menu.children':
                # Lets add 'Hooked: ' to resolved titles of every item.
                for item in tree_items:
                    item.title_resolved = 'Hooked: %s' % item.title_resolved
            # Return items list mutated or not.
            return tree_items

        # And we register items processor.
        register_items_hook(my_items_processor)

    :param func:


global _I18N_TREES<EOL>_I18N_TREES = aliases<EOL>

Registers aliases of internationalized sitetrees.
    Internationalized sitetrees are those, which are dubbed by other trees having
    locale identifying suffixes in their aliases.

    Lets suppose ``my_tree`` is the alias of a generic tree. This tree is the one
    that we call by its alias in templates, and it is the one which is used
    if no i18n version of that tree is found.

    Given that ``my_tree_en``, ``my_tree_ru`` and other ``my_tree_{locale-id}``-like
    trees are considered internationalization sitetrees. These are used (if available)
    in accordance with current locale used by project.

    Example::

        # Put the following code somewhere where it'd be triggered as expected. E.g. in main urls.py.

        # First import the register function.
        from sitetree.sitetreeapp import register_i18n_trees

        # At last we register i18n trees.
        register_i18n_trees(['my_tree', 'my_another_tree'])

    :param aliases:


def register_dynamic_trees(trees, *args, **kwargs):

global _DYNAMIC_TREES<EOL>if _IDX_ORPHAN_TREES not in _DYNAMIC_TREES:<EOL><INDENT>_DYNAMIC_TREES[_IDX_ORPHAN_TREES] = {}<EOL><DEDENT>if isinstance(trees, dict):  <EOL><INDENT>trees = [trees]<EOL>trees.extend(args)<EOL><DEDENT>for tree in trees or []:<EOL><INDENT>if tree is not None and tree['<STR_LIT>'] is not None:<EOL><INDENT>if tree['<STR_LIT>'] is None:<EOL><INDENT>for st in tree['<STR_LIT>']:<EOL><INDENT>if st.alias not in _DYNAMIC_TREES[_IDX_ORPHAN_TREES]:<EOL><INDENT>_DYNAMIC_TREES[_IDX_ORPHAN_TREES][st.alias] = []<EOL><DEDENT>_DYNAMIC_TREES[_IDX_ORPHAN_TREES][st.alias].append(st)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>index = _IDX_TPL % (tree['<STR_LIT>'], tree['<STR_LIT>'])<EOL>if index not in _DYNAMIC_TREES:<EOL><INDENT>_DYNAMIC_TREES[index] = []<EOL><DEDENT>_DYNAMIC_TREES[index].extend(tree['<STR_LIT>'])<EOL><DEDENT><DEDENT><DEDENT>reset_cache = kwargs.get('<STR_LIT>', False)<EOL>if reset_cache:<EOL><INDENT>cache_ = get_sitetree().cache<EOL>cache_.empty()<EOL>cache_.reset()<EOL><DEDENT>

Registers dynamic trees to be available for `sitetree` runtime.
    Expects `trees` to be an iterable with structures created with `compose_dynamic_tree()`.

    Example::

        register_dynamic_trees(

            # Get all the trees from `my_app`.
            compose_dynamic_tree('my_app'),

            # Get all the trees from `my_app` and attach them to `main` tree root.
            compose_dynamic_tree('my_app', target_tree_alias='main'),

            # Get all the trees from `my_app` and attach them to `has_dynamic` aliased item in `main` tree.
            compose_dynamic_tree('articles', target_tree_alias='main', parent_tree_item_alias='has_dynamic'),

            # Define a tree right on the registration.
            compose_dynamic_tree((
                tree('dynamic', items=(
                    item('dynamic_1', 'dynamic_1_url', children=(
                        item('dynamic_1_sub_1', 'dynamic_1_sub_1_url'),
                    )),
                    item('dynamic_2', 'dynamic_2_url'),
                )),
            )),
        )

    Accepted kwargs:
        bool reset_cache: Resets tree cache, to introduce all changes made to a tree immediately.


return _DYNAMIC_TREES<EOL>

Returns a dictionary with currently registered dynamic trees.


def compose_dynamic_tree(src, target_tree_alias=None, parent_tree_item_alias=None, include_trees=None):

def result(sitetrees=src):<EOL><INDENT>if include_trees is not None:<EOL><INDENT>sitetrees = [tree for tree in sitetrees if tree.alias in include_trees]<EOL><DEDENT>return {<EOL>'<STR_LIT>': src,<EOL>'<STR_LIT>': sitetrees,<EOL>'<STR_LIT>': target_tree_alias,<EOL>'<STR_LIT>': parent_tree_item_alias}<EOL><DEDENT>if isinstance(src, six.string_types):<EOL><INDENT>try:<EOL><INDENT>module = import_app_sitetree_module(src)<EOL>return None if module is None else result(getattr(module, '<STR_LIT>', None))<EOL><DEDENT>except ImportError as e:<EOL><INDENT>if settings.DEBUG:<EOL><INDENT>warnings.warn('<STR_LIT>' % (src, e))<EOL><DEDENT>return None<EOL><DEDENT><DEDENT>return result()<EOL>

Returns a structure describing a dynamic sitetree.utils
    The structure can be built from various sources,

    :param str|iterable src: If a string is passed to `src`, it'll be treated as the name of an app,
        from where one want to import sitetrees definitions. `src` can be an iterable
        of tree definitions (see `sitetree.toolbox.tree()` and `item()` functions).

    :param str|unicode target_tree_alias: Static tree alias to attach items from dynamic trees to.

    :param str|unicode parent_tree_item_alias: Tree item alias from a static tree to attach items from dynamic trees to.

    :param list include_trees: Sitetree aliases to filter `src`.

    :rtype: dict


self.title = title<EOL>


cache.set('<STR_LIT>', True)<EOL>

Instructs sitetree to drop and recreate cache.

        Could be used to show up tree changes made in a different process.


<EOL>cache.get('<STR_LIT>') and self.empty(init=False)<EOL>self.cache = cache.get(<EOL>'<STR_LIT>', {'<STR_LIT>': {}, '<STR_LIT>': {}, '<STR_LIT>': {}, '<STR_LIT>': {}})<EOL>

Initializes local cache from Django cache.


cache.set('<STR_LIT>', self.cache, CACHE_TIMEOUT)<EOL>


cache.delete('<STR_LIT>')<EOL>cache.delete('<STR_LIT>')<EOL>kwargs.get('<STR_LIT>', True) and self.init()<EOL>


return self.cache[entry_name].get(key, False)<EOL>

Returns cache entry parameter value by its name.

        :param str|unicode entry_name:
        :param key:
        :return:


def update_entry_value(self, entry_name, key, value):

if key not in self.cache[entry_name]:<EOL><INDENT>self.cache[entry_name][key] = {}<EOL><DEDENT>self.cache[entry_name][key].update(value)<EOL>

Updates cache entry parameter with new data.

        :param str|unicode entry_name:
        :param key:
        :param value:


def set_entry(self, entry_name, key, value):

self.cache[entry_name][key] = value<EOL>

Replaces entire cache entry parameter data by its name with new data.

        :param str|unicode entry_name:
        :param key:
        :param value:


self.cache = Cache()<EOL>self.current_page_context = context<EOL>self.current_request = context.get('<STR_LIT>', None) if context else None<EOL>self.current_lang = get_language()<EOL>self._current_app_is_admin = None<EOL>self._current_user_permissions = _UNSET<EOL>self._items_urls = {}  <EOL>self._current_items = {}<EOL>

Initializes sitetree to handle new request.

        :param Context|None context:


if alias not in _I18N_TREES:<EOL><INDENT>return alias<EOL><DEDENT>current_language_code = self.current_lang<EOL>i18n_tree_alias = '<STR_LIT>' % (alias, current_language_code)<EOL>trees_count = self.cache.get_entry('<STR_LIT>', i18n_tree_alias)<EOL>if trees_count is False:<EOL><INDENT>trees_count = MODEL_TREE_CLASS.objects.filter(alias=i18n_tree_alias).count()<EOL>self.cache.set_entry('<STR_LIT>', i18n_tree_alias, trees_count)<EOL><DEDENT>if trees_count:<EOL><INDENT>alias = i18n_tree_alias<EOL><DEDENT>return alias<EOL>

Resolves internationalized tree alias.
        Verifies whether a separate sitetree is available for currently active language.
        If so, returns i18n alias. If not, returns the initial alias.

        :param str|unicode alias:
        :rtype: str|unicode


if not _DYNAMIC_TREES:<EOL><INDENT>return src_tree_items<EOL><DEDENT>trees = deepcopy(_DYNAMIC_TREES)<EOL>items = []<EOL>if not src_tree_items:<EOL><INDENT>if _IDX_ORPHAN_TREES in trees and tree_alias in trees[_IDX_ORPHAN_TREES]:<EOL><INDENT>for tree in trees[_IDX_ORPHAN_TREES][tree_alias]:<EOL><INDENT>items.extend(tree.dynamic_items)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for static_item in list(src_tree_items):<EOL><INDENT>items.append(static_item)<EOL>if not static_item.alias:<EOL><INDENT>continue<EOL><DEDENT>idx = _IDX_TPL % (tree_alias, static_item.alias)<EOL>if idx not in trees:<EOL><INDENT>continue<EOL><DEDENT>for tree in trees[idx]:<EOL><INDENT>tree.alias = tree_alias<EOL>for dyn_item in tree.dynamic_items:<EOL><INDENT>if dyn_item.parent is None:<EOL><INDENT>dyn_item.parent = static_item<EOL><DEDENT>dyn_item.id = generate_id_for(dyn_item)<EOL>items.append(dyn_item)<EOL><DEDENT><DEDENT><DEDENT>idx = _IDX_TPL % (tree_alias, None)<EOL>if idx in _DYNAMIC_TREES:<EOL><INDENT>trees = deepcopy(_DYNAMIC_TREES)<EOL>for tree in trees[idx]:<EOL><INDENT>tree.alias = tree_alias<EOL>items.extend(tree.dynamic_items)<EOL><DEDENT><DEDENT><DEDENT>return items<EOL>

Attaches dynamic sitetrees items registered with `register_dynamic_trees()`
        to an initial (source) items list.

        :param str|unicode tree_alias:
        :param list src_tree_items:
        :rtype: list


is_admin = self._current_app_is_admin<EOL>if is_admin is None:<EOL><INDENT>context = self.current_page_context<EOL>current_app = getattr(<EOL>getattr(context.get('<STR_LIT>', None), '<STR_LIT>', None), '<STR_LIT>',<EOL>getattr(context, '<STR_LIT>', None))<EOL>if current_app is None:  <EOL><INDENT>current_app = context.get('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>is_admin = current_app == ADMIN_APP_NAME<EOL>self._current_app_is_admin = is_admin<EOL><DEDENT>return is_admin<EOL>

Returns boolean whether current application is Admin contrib.

        :rtype: bool


cache_ = self.cache<EOL>get_cache_entry = cache_.get_entry<EOL>set_cache_entry = cache_.set_entry<EOL>caching_required = False<EOL>if not self.current_app_is_admin():<EOL><INDENT>alias = self.resolve_tree_i18n_alias(alias)<EOL><DEDENT>sitetree = get_cache_entry('<STR_LIT>', alias)<EOL>if not sitetree:<EOL><INDENT>if DYNAMIC_ONLY:<EOL><INDENT>sitetree = []<EOL><DEDENT>else:<EOL><INDENT>sitetree = (<EOL>MODEL_TREE_ITEM_CLASS.objects.<EOL>select_related('<STR_LIT>', '<STR_LIT>').<EOL>prefetch_related('<STR_LIT>').<EOL>filter(tree__alias__exact=alias).<EOL>order_by('<STR_LIT>', '<STR_LIT>'))<EOL><DEDENT>sitetree = self.attach_dynamic_tree_items(alias, sitetree)<EOL>set_cache_entry('<STR_LIT>', alias, sitetree)<EOL>caching_required = True<EOL><DEDENT>parents = get_cache_entry('<STR_LIT>', alias)<EOL>if not parents:<EOL><INDENT>parents = defaultdict(list)<EOL>for item in sitetree:<EOL><INDENT>parent = getattr(item, '<STR_LIT>')<EOL>parents[parent].append(item)<EOL><DEDENT>set_cache_entry('<STR_LIT>', alias, parents)<EOL><DEDENT>if caching_required:<EOL><INDENT>cache_update = cache_.update_entry_value<EOL>for item in sitetree:<EOL><INDENT>cache_update('<STR_LIT>', alias, {item.id: item})<EOL><DEDENT><DEDENT>url = self.url<EOL>calculate_item_depth = self.calculate_item_depth<EOL>for item in sitetree:<EOL><INDENT>if caching_required:<EOL><INDENT>item.has_children = False<EOL>if not hasattr(item, '<STR_LIT>'):<EOL><INDENT>item.depth = calculate_item_depth(alias, item.id)<EOL><DEDENT>item.depth_range = range(item.depth)<EOL>if item.access_restricted:<EOL><INDENT>permissions_src = (<EOL>item.permissions if getattr(item, '<STR_LIT>', False)<EOL>else item.access_permissions.all())<EOL>item.perms = set(<EOL>['<STR_LIT>' % (perm.content_type.app_label, perm.codename) for perm in permissions_src])<EOL><DEDENT><DEDENT>item.url_resolved = url(item)<EOL>item.title_resolved = LazyTitle(item.title) if VARIABLE_TAG_START in item.title else item.title<EOL>item.is_current = False<EOL>item.in_current_branch = False<EOL><DEDENT>self.get_tree_current_item(alias)<EOL>if caching_required:<EOL><INDENT>cache_.save()<EOL><DEDENT>return alias, sitetree<EOL>

Gets site tree items from the given site tree.
        Caches result to dictionary.
        Returns (tree alias, tree items) tuple.

        :param str|unicode alias:
        :rtype: tuple


def calculate_item_depth(self, tree_alias, item_id, depth=<NUM_LIT:0>):

item = self.get_item_by_id(tree_alias, item_id)<EOL>if hasattr(item, '<STR_LIT>'):<EOL><INDENT>depth = item.depth + depth<EOL><DEDENT>else:<EOL><INDENT>if item.parent is not None:<EOL><INDENT>depth = self.calculate_item_depth(tree_alias, item.parent.id, depth + <NUM_LIT:1>)<EOL><DEDENT><DEDENT>return depth<EOL>

Calculates depth of the item in the tree.

        :param str|unicode tree_alias:
        :param int item_id:
        :param int depth:
        :rtype: int


def get_item_by_id(self, tree_alias, item_id):

return self.cache.get_entry('<STR_LIT>', tree_alias)[item_id]<EOL>

Get the item from the tree by its ID.

        :param str|unicode tree_alias:
        :param int item_id:
        :rtype: TreeItemBase


current_item = self._current_items.get(tree_alias, _UNSET)<EOL>if current_item is not _UNSET:<EOL><INDENT>if current_item is not None:<EOL><INDENT>current_item.is_current = True  <EOL><DEDENT>return current_item<EOL><DEDENT>current_item = None<EOL>if self.current_app_is_admin():<EOL><INDENT>self._current_items[tree_alias] = current_item<EOL>return None<EOL><DEDENT>current_url = self.current_request.path<EOL>if isinstance(current_url, str):<EOL><INDENT>current_url = current_url.encode('<STR_LIT>')<EOL><DEDENT>if current_url:<EOL><INDENT>current_url = urlquote(current_url)<EOL><DEDENT>for url_item, url in self._items_urls.items():<EOL><INDENT>if url != current_url:<EOL><INDENT>continue<EOL><DEDENT>url_item.is_current = True<EOL>if url_item.tree.alias == tree_alias:<EOL><INDENT>current_item = url_item<EOL><DEDENT><DEDENT>if current_item is not None:<EOL><INDENT>self._current_items[tree_alias] = current_item<EOL><DEDENT>return current_item<EOL>

Resolves current tree item of 'tree_alias' tree matching current
        request path against URL of given tree item.

        :param str|unicode tree_alias:
        :rtype: TreeItemBase


def url(self, sitetree_item, context=None):

context = context or self.current_page_context<EOL>resolve_var = self.resolve_var<EOL>if not isinstance(sitetree_item, MODEL_TREE_ITEM_CLASS):<EOL><INDENT>sitetree_item = resolve_var(sitetree_item, context)<EOL><DEDENT>resolved_url = self._items_urls.get(sitetree_item)<EOL>if resolved_url is not None:<EOL><INDENT>return resolved_url<EOL><DEDENT>if sitetree_item.urlaspattern:<EOL><INDENT>url = sitetree_item.url<EOL>view_path = url<EOL>all_arguments = []<EOL>if '<STR_LIT:U+0020>' in url:<EOL><INDENT>view_path = url.split('<STR_LIT:U+0020>')<EOL>for view_argument in view_path[<NUM_LIT:1>:]:<EOL><INDENT>resolved = resolve_var(view_argument)<EOL>all_arguments.append('<STR_LIT>' % resolved)<EOL><DEDENT>view_path = view_path[<NUM_LIT:0>].strip('<STR_LIT>')<EOL><DEDENT>url_pattern = "<STR_LIT>" % (view_path, '<STR_LIT:U+0020>'.join(all_arguments))<EOL><DEDENT>else:<EOL><INDENT>url_pattern = '<STR_LIT:%s>' % sitetree_item.url<EOL><DEDENT>if sitetree_item.urlaspattern:<EOL><INDENT>url_token = '<STR_LIT>' % url_pattern<EOL>url_tag(<EOL>Parser(None),<EOL>Token(token_type=TOKEN_BLOCK, contents=url_token)<EOL>).render(context)<EOL>resolved_url = context['<STR_LIT>'] or UNRESOLVED_ITEM_MARKER<EOL><DEDENT>else:<EOL><INDENT>resolved_url = url_pattern<EOL><DEDENT>self._items_urls[sitetree_item] = resolved_url<EOL>return resolved_url<EOL>

Resolves item's URL.

        :param TreeItemBase sitetree_item: TreeItemBase heir object, 'url' property of which
            is processed as URL pattern or simple URL.

        :param Context context:

        :rtype: str|unicode


def init_tree(self, tree_alias, context):

request = context.get('<STR_LIT>', None)<EOL>if request is None:<EOL><INDENT>raise SiteTreeError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if id(request) != id(self.current_request):<EOL><INDENT>self.init(context)<EOL><DEDENT>tree_alias = self.resolve_var(tree_alias)<EOL>tree_alias, sitetree_items = self.get_sitetree(tree_alias)<EOL>if not sitetree_items:<EOL><INDENT>return None, None<EOL><DEDENT>return tree_alias, sitetree_items<EOL>

Initializes sitetree in memory.

        Returns tuple with resolved tree alias and items on success.

        On fail returns (None, None).

        :param str|unicode tree_alias:
        :param Context context:
        :rtype: tuple


def get_current_page_title(self, tree_alias, context):

return self.get_current_page_attr('<STR_LIT>', tree_alias, context)<EOL>

Returns resolved from sitetree title for current page.

        :param str|unicode tree_alias:
        :param Context context:
        :rtype: str|unicode


def get_current_page_attr(self, attr_name, tree_alias, context):

tree_alias, sitetree_items = self.init_tree(tree_alias, context)<EOL>current_item = self.get_tree_current_item(tree_alias)<EOL>if current_item is None:<EOL><INDENT>if settings.DEBUG and RAISE_ITEMS_ERRORS_ON_DEBUG:<EOL><INDENT>raise SiteTreeError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % attr_name)<EOL><DEDENT>return '<STR_LIT>'<EOL><DEDENT>return getattr(current_item, attr_name, '<STR_LIT>')<EOL>

Returns an arbitrary attribute of a sitetree item resolved as current for current page.

        :param str|unicode attr_name:
        :param str|unicode tree_alias:
        :param Context context:
        :rtype: str|unicode


def get_ancestor_level(self, current_item, depth=<NUM_LIT:1>):

if current_item.parent is None:<EOL><INDENT>return current_item<EOL><DEDENT>if depth <= <NUM_LIT:1>:<EOL><INDENT>return current_item.parent<EOL><DEDENT>return self.get_ancestor_level(current_item.parent, depth=depth-<NUM_LIT:1>)<EOL>

Returns ancestor of level `deep` recursively

        :param TreeItemBase current_item:
        :param int depth:
        :rtype: TreeItemBase


def menu(self, tree_alias, tree_branches, context):

tree_alias, sitetree_items = self.init_tree(tree_alias, context)<EOL>if not sitetree_items:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>tree_branches = self.resolve_var(tree_branches)<EOL>parent_isnull = False<EOL>parent_ids = []<EOL>parent_aliases = []<EOL>current_item = self.get_tree_current_item(tree_alias)<EOL>self.tree_climber(tree_alias, current_item)<EOL>for branch_id in tree_branches.split('<STR_LIT:U+002C>'):<EOL><INDENT>branch_id = branch_id.strip()<EOL>if branch_id == ALIAS_TRUNK:<EOL><INDENT>parent_isnull = True<EOL><DEDENT>elif branch_id == ALIAS_THIS_CHILDREN and current_item is not None:<EOL><INDENT>branch_id = current_item.id<EOL>parent_ids.append(branch_id)<EOL><DEDENT>elif branch_id == ALIAS_THIS_ANCESTOR_CHILDREN and current_item is not None:<EOL><INDENT>branch_id = self.get_ancestor_item(tree_alias, current_item).id<EOL>parent_ids.append(branch_id)<EOL><DEDENT>elif branch_id == ALIAS_THIS_SIBLINGS and current_item is not None and current_item.parent is not None:<EOL><INDENT>branch_id = current_item.parent.id<EOL>parent_ids.append(branch_id)<EOL><DEDENT>elif branch_id == ALIAS_THIS_PARENT_SIBLINGS and current_item is not None:<EOL><INDENT>branch_id = self.get_ancestor_level(current_item, depth=<NUM_LIT:2>).id<EOL>parent_ids.append(branch_id)<EOL><DEDENT>elif branch_id.isdigit():<EOL><INDENT>parent_ids.append(int(branch_id))<EOL><DEDENT>else:<EOL><INDENT>parent_aliases.append(branch_id)<EOL><DEDENT><DEDENT>check_access = self.check_access<EOL>menu_items = []<EOL>for item in sitetree_items:<EOL><INDENT>if not item.hidden and item.inmenu and check_access(item, context):<EOL><INDENT>if item.parent is None:<EOL><INDENT>if parent_isnull:<EOL><INDENT>menu_items.append(item)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if item.parent.id in parent_ids or item.parent.alias in parent_aliases:<EOL><INDENT>menu_items.append(item)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>menu_items = self.apply_hook(menu_items, '<STR_LIT>')<EOL>self.update_has_children(tree_alias, menu_items, '<STR_LIT>')<EOL>return menu_items<EOL>

Builds and returns menu structure for 'sitetree_menu' tag.

        :param str|unicode tree_alias:
        :param str|unicode tree_branches:
        :param Context context:
        :rtype: list|str


processor = _ITEMS_PROCESSOR<EOL>if processor is None:<EOL><INDENT>return items<EOL><DEDENT>if _ITEMS_PROCESSOR_ARGS_LEN == <NUM_LIT:2>:<EOL><INDENT>return processor(tree_items=items, tree_sender=sender)<EOL><DEDENT>return processor(tree_items=items, tree_sender=sender, context=self.current_page_context)<EOL>

Applies item processing hook, registered with ``register_item_hook()``
        to items supplied, and returns processed list.

        Returns initial items list if no hook is registered.

        :param list items:
        :param str|unicode sender: menu, breadcrumbs, sitetree, {type}.children, {type}.has_children
        :rtype: list


if hasattr(self.current_request.user.is_authenticated, '<STR_LIT>'):<EOL><INDENT>authenticated = self.current_request.user.is_authenticated()<EOL><DEDENT>else:<EOL><INDENT>authenticated = self.current_request.user.is_authenticated<EOL><DEDENT>if item.access_loggedin and not authenticated:<EOL><INDENT>return False<EOL><DEDENT>if item.access_guest and authenticated:<EOL><INDENT>return False<EOL><DEDENT>if item.access_restricted:<EOL><INDENT>user_perms = self._current_user_permissions<EOL>if user_perms is _UNSET:<EOL><INDENT>user_perms = set(context['<STR_LIT:user>'].get_all_permissions())<EOL>self._current_user_permissions = user_perms<EOL><DEDENT>if item.access_perm_type == MODEL_TREE_ITEM_CLASS.PERM_TYPE_ALL:<EOL><INDENT>if len(item.perms) != len(item.perms.intersection(user_perms)):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not len(item.perms.intersection(user_perms)):<EOL><INDENT>return False<EOL><DEDENT><DEDENT><DEDENT>return True<EOL>

Checks whether a current user has an access to a certain item.

        :param TreeItemBase item:
        :param Context context:
        :rtype: bool


def breadcrumbs(self, tree_alias, context):

tree_alias, sitetree_items = self.init_tree(tree_alias, context)<EOL>if not sitetree_items:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>current_item = self.get_tree_current_item(tree_alias)<EOL>breadcrumbs = []<EOL>if current_item is not None:<EOL><INDENT>context_ = self.current_page_context<EOL>check_access = self.check_access<EOL>get_item_by_id = self.get_item_by_id<EOL>def climb(base_item):<EOL><INDENT>"""<STR_LIT>"""<EOL>if base_item.inbreadcrumbs and not base_item.hidden and check_access(base_item, context_):<EOL><INDENT>breadcrumbs.append(base_item)<EOL><DEDENT>if hasattr(base_item, '<STR_LIT>') and base_item.parent is not None:<EOL><INDENT>climb(get_item_by_id(tree_alias, base_item.parent.id))<EOL><DEDENT><DEDENT>climb(current_item)<EOL>breadcrumbs.reverse()<EOL><DEDENT>items = self.apply_hook(breadcrumbs, '<STR_LIT>')<EOL>self.update_has_children(tree_alias, items, '<STR_LIT>')<EOL>return items<EOL>

Builds and returns breadcrumb trail structure for 'sitetree_breadcrumbs' tag.

        :param str|unicode tree_alias:
        :param Context context:
        :rtype: list|str


tree_alias, sitetree_items = self.init_tree(tree_alias, context)<EOL>if not sitetree_items:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>tree_items = self.filter_items(self.get_children(tree_alias, None), '<STR_LIT>')<EOL>tree_items = self.apply_hook(tree_items, '<STR_LIT>')<EOL>self.update_has_children(tree_alias, tree_items, '<STR_LIT>')<EOL>return tree_items<EOL>

Builds and returns tree structure for 'sitetree_tree' tag.

        :param str|unicode tree_alias:
        :param Context context:
        :rtype: list|str


def children(self, parent_item, navigation_type, use_template, context):

<EOL>parent_item = self.resolve_var(parent_item, context)<EOL>tree_alias, tree_items = self.get_sitetree(parent_item.tree.alias)<EOL>self.tree_climber(tree_alias, self.get_tree_current_item(tree_alias))<EOL>tree_items = self.get_children(tree_alias, parent_item)<EOL>tree_items = self.filter_items(tree_items, navigation_type)<EOL>tree_items = self.apply_hook(tree_items, '<STR_LIT>' % navigation_type)<EOL>self.update_has_children(tree_alias, tree_items, navigation_type)<EOL>my_template = get_template(use_template)<EOL>context.push()<EOL>context['<STR_LIT>'] = tree_items<EOL>rendered = my_template.render(context.flatten() if _CONTEXT_FLATTEN else context)<EOL>context.pop()<EOL>return rendered<EOL>

Builds and returns site tree item children structure for 'sitetree_children' tag.

        :param TreeItemBase parent_item:
        :param str|unicode navigation_type: menu, sitetree
        :param str|unicode use_template:
        :param Context context:
        :rtype: list


def get_children(self, tree_alias, item):

if not self.current_app_is_admin():<EOL><INDENT>tree_alias = self.resolve_tree_i18n_alias(tree_alias)<EOL><DEDENT>return self.cache.get_entry('<STR_LIT>', tree_alias)[item]<EOL>

Returns item's children.

        :param str|unicode tree_alias:
        :param TreeItemBase|None item:
        :rtype: list


def update_has_children(self, tree_alias, tree_items, navigation_type):

get_children = self.get_children<EOL>filter_items = self.filter_items<EOL>apply_hook = self.apply_hook<EOL>for tree_item in tree_items:<EOL><INDENT>children = get_children(tree_alias, tree_item)<EOL>children = filter_items(children, navigation_type)<EOL>children = apply_hook(children, '<STR_LIT>' % navigation_type)<EOL>tree_item.has_children = len(children) > <NUM_LIT:0><EOL><DEDENT>

Updates 'has_children' attribute for tree items inplace.

        :param str|unicode tree_alias:
        :param list tree_items:
        :param str|unicode navigation_type: sitetree, breadcrumbs, menu


def filter_items(self, items, navigation_type=None):

if self.current_app_is_admin():<EOL><INDENT>return items<EOL><DEDENT>items_filtered = []<EOL>context = self.current_page_context<EOL>check_access = self.check_access<EOL>for item in items:<EOL><INDENT>if item.hidden:<EOL><INDENT>continue<EOL><DEDENT>if not check_access(item, context):<EOL><INDENT>continue<EOL><DEDENT>if not getattr(item, '<STR_LIT>' % navigation_type, True):  <EOL><INDENT>continue<EOL><DEDENT>items_filtered.append(item)<EOL><DEDENT>return items_filtered<EOL>

Filters sitetree item's children if hidden and by navigation type.

        NB: We do not apply any filters to sitetree in admin app.

        :param list items:
        :param str|unicode navigation_type: sitetree, breadcrumbs, menu
        :rtype: list


def get_ancestor_item(self, tree_alias, base_item):

parent = None<EOL>if hasattr(base_item, '<STR_LIT>') and base_item.parent is not None:<EOL><INDENT>parent = self.get_ancestor_item(tree_alias, self.get_item_by_id(tree_alias, base_item.parent.id))<EOL><DEDENT>if parent is None:<EOL><INDENT>return base_item<EOL><DEDENT>return parent<EOL>

Climbs up the site tree to resolve root item for chosen one.

        :param str|unicode tree_alias:
        :param TreeItemBase base_item:
        :rtype: TreeItemBase


def tree_climber(self, tree_alias, base_item):

if base_item is not None:<EOL><INDENT>base_item.in_current_branch = True<EOL>if hasattr(base_item, '<STR_LIT>') and base_item.parent is not None:<EOL><INDENT>self.tree_climber(tree_alias, self.get_item_by_id(tree_alias, base_item.parent.id))<EOL><DEDENT><DEDENT>

Climbs up the site tree to mark items of current branch.

        :param str|unicode tree_alias:
        :param TreeItemBase base_item:


def resolve_var(self, varname, context=None):

context = context or self.current_page_context<EOL>if isinstance(varname, FilterExpression):<EOL><INDENT>varname = varname.resolve(context)<EOL><DEDENT>else:<EOL><INDENT>varname = varname.strip()<EOL>try:<EOL><INDENT>varname = Variable(varname).resolve(context)<EOL><DEDENT>except VariableDoesNotExist:<EOL><INDENT>varname = varname<EOL><DEDENT><DEDENT>return varname<EOL>

Resolves name as a variable in a given context.

        If no context specified page context' is considered as context.

        :param str|unicode varname:
        :param Context context:
        :return:


return id(obj)<EOL>

Generates and returns a unique identifier for the given object.


def tree(alias, title='<STR_LIT>', items=None, **kwargs):

tree_obj = get_tree_model()(alias=alias, title=title, **kwargs)<EOL>tree_obj.id = generate_id_for(tree_obj)<EOL>tree_obj.is_dynamic = True<EOL>if items is not None:<EOL><INDENT>tree_obj.dynamic_items = []<EOL>def traverse(items):<EOL><INDENT>for item in items:<EOL><INDENT>item.tree = tree_obj<EOL>tree_obj.dynamic_items.append(item)<EOL>if hasattr(item, '<STR_LIT>'):<EOL><INDENT>traverse(item.dynamic_children)<EOL><DEDENT><DEDENT><DEDENT>traverse(items)<EOL><DEDENT>return tree_obj<EOL>

Dynamically creates and returns a sitetree.

    :param str|unicode alias:
    :param str|unicode title:
    :param iterable items: dynamic sitetree items objects created by `item` function.
    :param kwargs: Additional arguments to pass to tree item initializer.

    :rtype: TreeBase


def item(<EOL>title, url, children=None, url_as_pattern=True, hint='<STR_LIT>', alias='<STR_LIT>', description='<STR_LIT>',<EOL>in_menu=True, in_breadcrumbs=True, in_sitetree=True,<EOL>access_loggedin=False, access_guest=False,<EOL>access_by_perms=None, perms_mode_all=True, **kwargs):

item_obj = get_tree_item_model()(<EOL>title=title, url=url, urlaspattern=url_as_pattern,<EOL>hint=hint, alias=alias, description=description, inmenu=in_menu,<EOL>insitetree=in_sitetree, inbreadcrumbs=in_breadcrumbs,<EOL>access_loggedin=access_loggedin, access_guest=access_guest,<EOL>**kwargs)<EOL>item_obj.id = generate_id_for(item_obj)<EOL>item_obj.is_dynamic = True<EOL>item_obj.dynamic_children = []<EOL>cleaned_permissions = []<EOL>if access_by_perms:<EOL><INDENT>if not isinstance(access_by_perms, list):<EOL><INDENT>access_by_perms = [access_by_perms]<EOL><DEDENT>for perm in access_by_perms:<EOL><INDENT>if isinstance(perm, six.string_types):<EOL><INDENT>try:<EOL><INDENT>app, codename = perm.split('<STR_LIT:.>')<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % perm)<EOL><DEDENT>try:<EOL><INDENT>perm = Permission.objects.get(codename=codename, content_type__app_label=app)<EOL><DEDENT>except Permission.DoesNotExist:<EOL><INDENT>raise ValueError('<STR_LIT>' % (app, codename))<EOL><DEDENT><DEDENT>elif not isinstance(perm, (int, Permission)):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>cleaned_permissions.append(perm)<EOL><DEDENT><DEDENT>item_obj.permissions = cleaned_permissions or []<EOL>item_obj.access_perm_type = item_obj.PERM_TYPE_ALL if perms_mode_all else item_obj.PERM_TYPE_ANY<EOL>if item_obj.permissions:<EOL><INDENT>item_obj.access_restricted = True<EOL><DEDENT>if children is not None:<EOL><INDENT>for child in children:<EOL><INDENT>child.parent = item_obj<EOL>item_obj.dynamic_children.append(child)<EOL><DEDENT><DEDENT>return item_obj<EOL>

Dynamically creates and returns a sitetree item object.

    :param str|unicode title:

    :param str|unicode url:

    :param list, set children: a list of children for tree item. Children should also be created by `item` function.

    :param bool url_as_pattern: consider URL as a name of a named URL

    :param str|unicode hint: hints are usually shown to users

    :param str|unicode alias: item name to address it from templates

    :param str|unicode description: additional information on item (usually is not shown to users)

    :param bool in_menu: show this item in menus

    :param bool in_breadcrumbs: show this item in breadcrumbs

    :param bool in_sitetree: show this item in sitetrees

    :param bool access_loggedin: show item to logged in users only

    :param bool access_guest: show item to guest users only

    :param list|str||unicode|int, Permission access_by_perms: restrict access to users with these permissions.

        This can be set to one or a list of permission names, IDs or Permission instances.

        Permission names are more portable and should be in a form `<app_label>.<perm_codename>`, e.g.:
            my_app.allow_save

    :param bool perms_mode_all: permissions set interpretation rule:
                True - user should have all the permissions;
                False - user should have any of chosen permissions.

    :rtype: TreeItemBase


module_name = settings.APP_MODULE_NAME<EOL>module = import_module(app)<EOL>try:<EOL><INDENT>sub_module = import_module('<STR_LIT>' % (app, module_name))<EOL>return sub_module<EOL><DEDENT>except ImportError:<EOL><INDENT>if module_has_submodule(module, module_name):<EOL><INDENT>raise<EOL><DEDENT>return None<EOL><DEDENT>

Imports sitetree module from a given app.

    :param str|unicode app: Application name
    :return: module|None


from django.conf import settings as django_settings<EOL>submodules = []<EOL>for app in django_settings.INSTALLED_APPS:<EOL><INDENT>module = import_app_sitetree_module(app)<EOL>if module is not None:<EOL><INDENT>submodules.append(module)<EOL><DEDENT><DEDENT>return submodules<EOL>

Imports sitetrees modules from packages (apps).
    Returns a list of submodules.

    :rtype: list


try:<EOL><INDENT>app_name, model_name = getattr(settings, settings_entry_name).split('<STR_LIT:.>')<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ImproperlyConfigured(<EOL>'<STR_LIT>' % settings_entry_name)<EOL><DEDENT>return app_name, model_name<EOL>

Returns tuple with application and tree[item] model class names.

    :param str|unicode settings_entry_name:
    :rtype: tuple


app_name, model_name = get_app_n_model(settings_entry_name)<EOL>try:<EOL><INDENT>model = apps_get_model(app_name, model_name)<EOL><DEDENT>except (LookupError, ValueError):<EOL><INDENT>model = None<EOL><DEDENT>if model is None:<EOL><INDENT>raise ImproperlyConfigured(<EOL>'<STR_LIT>' % (settings_entry_name, model_name))<EOL><DEDENT>return model<EOL>

Returns a certain sitetree model as defined in the project settings.

    :param str|unicode settings_entry_name:
    :rtype: TreeItemBase|TreeBase


return get_model_class('<STR_LIT>')<EOL>

Returns the Tree model, set for the project.

    :rtype: TreeBase


Returns the TreeItem model, set for the project.

    :rtype: TreeItemBase


def save(self, force_insert=False, force_update=False, **kwargs):

<EOL>if self.parent == self:<EOL><INDENT>self.parent = None<EOL><DEDENT>id_ = self.id<EOL>if id_ and self.sort_order == <NUM_LIT:0>:<EOL><INDENT>self.sort_order = id_<EOL><DEDENT>super(TreeItemBase, self).save(force_insert, force_update, **kwargs)<EOL>if self.sort_order == <NUM_LIT:0>:<EOL><INDENT>self.sort_order = self.id<EOL>self.save()<EOL><DEDENT>

Ensure that item is not its own parent and set proper sort order.


from web.apps.aiohttp_app import AiohttpApplication<EOL>class Home(Handler):<EOL><INDENT>async def get(self, request, response):<EOL><INDENT>response.body = HELLO_WORLD<EOL>return response<EOL><DEDENT><DEDENT>class Landing(Handler):<EOL><INDENT>async def get(self, request, response):<EOL><INDENT>response.body = LANDING_PAGE<EOL>return response<EOL><DEDENT><DEDENT>app = AiohttpApplication()<EOL>app.add_route('<STR_LIT:/>', Home())<EOL>app.add_route('<STR_LIT>', Landing())<EOL>app.add_static_route('<STR_LIT>', STATIC_PATH)<EOL>app.timed_call(<NUM_LIT>, app.stop)<EOL>app.start(port=port)<EOL>

Without logging...

    Running 30s test @ http://127.0.0.1:8888/
      12 threads and 400 connections
      Thread Stats   Avg      Stdev     Max   +/- Stdev
        Latency    89.37ms    6.68ms 290.76ms   89.18%
        Req/Sec   369.61     80.32   666.00     83.37%
      132444 requests in 30.04s, 20.59MB read
    Requests/sec:   4408.86
    Transfer/sec:    701.81KB


from web.apps.sanic_app import SanicApplication<EOL>from sanic import Sanic, response<EOL>app = SanicApplication()<EOL>class Home(Handler):<EOL><INDENT>async def get(self, request, response):<EOL><INDENT>response.body = HELLO_WORLD.encode()<EOL>return response<EOL><DEDENT><DEDENT>class Landing(Handler):<EOL><INDENT>async def get(self, request, response):<EOL><INDENT>response.body = LANDING_PAGE.encode()<EOL>return response<EOL><DEDENT><DEDENT>app.add_route('<STR_LIT:/>', Home())<EOL>app.add_route('<STR_LIT>', Landing())<EOL>app.add_static_route('<STR_LIT>', STATIC_PATH)<EOL>app.timed_call(<NUM_LIT>, app.stop)<EOL>app.start(port=port)<EOL>

With logging

    Running 30s test @ http://127.0.0.1:8888/
      12 threads and 400 connections
      Thread Stats   Avg      Stdev     Max   +/- Stdev
        Latency    62.65ms   10.04ms 189.96ms   87.87%
        Req/Sec   526.93    159.98     1.00k    64.25%
      188860 requests in 30.06s, 23.41MB read
    Requests/sec:   6283.35
    Transfer/sec:    797.69KB


from web.apps.falcon_app import FalconApplication<EOL>app = FalconApplication()<EOL>class Home(Handler):<EOL><INDENT>def get(self, req, resp):<EOL><INDENT>resp.body = HELLO_WORLD<EOL><DEDENT><DEDENT>class Landing(Handler):<EOL><INDENT>def get(self, req, resp):<EOL><INDENT>resp.body = LANDING_PAGE<EOL><DEDENT><DEDENT>app.add_route('<STR_LIT:/>', Home())<EOL>app.add_route('<STR_LIT>', Landing())<EOL>app.add_static_route('<STR_LIT>', STATIC_PATH)<EOL>app.start(port=port)<EOL>


from web.apps.flask_app import FlaskApplication<EOL>from flask import Flask<EOL>app = FlaskApplication()<EOL>def home():<EOL><INDENT>return HELLO_WORLD<EOL><DEDENT>def landing():<EOL><INDENT>return LANDING_PAGE<EOL><DEDENT>app.add_route('<STR_LIT:/>', home)<EOL>app.add_route('<STR_LIT>', landing)<EOL>app.add_static_route('<STR_LIT>', STATIC_PATH)<EOL>app.timed_call(<NUM_LIT>, app.stop)<EOL>app.start(port=port)<EOL>


import tornado.web<EOL>from web.apps.tornado_app import TornadoApplication<EOL>from tornado.log import enable_pretty_logging<EOL>enable_pretty_logging()<EOL>app = TornadoApplication()<EOL>class Home(Handler):<EOL><INDENT>def get(self, req, resp):<EOL><INDENT>resp.write(HELLO_WORLD)<EOL>resp.finish()<EOL><DEDENT><DEDENT>class Landing(Handler):<EOL><INDENT>def get(self, req, resp):<EOL><INDENT>resp.write(LANDING_PAGE)<EOL>resp.finish()<EOL><DEDENT><DEDENT>app.add_route('<STR_LIT:/>', Home())<EOL>app.add_route('<STR_LIT>', Landing())<EOL>app.add_static_route('<STR_LIT>', STATIC_PATH)<EOL>app.timed_call(<NUM_LIT>, app.stop)<EOL>app.start(port=port)<EOL>

Even without logging it's slower!

    Running 30s test @ http://127.0.0.1:8888/
      12 threads and 400 connections
      Thread Stats   Avg      Stdev     Max   +/- Stdev
        Latency   179.14ms   26.19ms 464.63ms   92.60%
        Req/Sec   184.55    107.47   560.00     57.59%
      64871 requests in 30.10s, 12.87MB read
    Requests/sec:   2155.42
    Transfer/sec:    437.82KB

    with logging

    Running 30s test @ http://127.0.0.1:8888/
      12 threads and 400 connections
      Thread Stats   Avg      Stdev     Max   +/- Stdev
        Latency   209.77ms   28.48ms 320.47ms   91.43%
        Req/Sec   156.14     79.60   500.00     63.72%
      55415 requests in 30.10s, 10.99MB read
    Requests/sec:   1841.04
    Transfer/sec:    373.96KB


from twisted.web import server<EOL>from twisted.web.resource import Resource<EOL>from twisted.web.static import File<EOL>from web.apps.twisted_app import TwistedApplication<EOL>class Main(Resource):<EOL><INDENT>def getChild(self, name, request):<EOL><INDENT>name = name.decode()<EOL>if name == '<STR_LIT>':<EOL><INDENT>return self<EOL><DEDENT>return self.children[name]<EOL><DEDENT>def render_GET(self, request):<EOL><INDENT>return HELLO_WORLD.encode()<EOL><DEDENT><DEDENT>class Landing(Resource):<EOL><INDENT>isLeaf = True<EOL>def render_GET(self, request):<EOL><INDENT>return LANDING_PAGE.encode()<EOL><DEDENT><DEDENT>root = Main()<EOL>root.putChild('<STR_LIT>', Landing())<EOL>root.putChild('<STR_LIT>', File(STATIC_PATH))<EOL>site = server.Site(root)<EOL>app = TwistedApplication(port=port, site=site)<EOL>app.timed_call(<NUM_LIT>, app.stop)<EOL>app.start()<EOL>

With logging

    Running 30s test @ http://127.0.0.1:8888/
      12 threads and 400 connections
      Thread Stats   Avg      Stdev     Max   +/- Stdev
        Latency   124.17ms   24.74ms 492.40ms   85.64%
        Req/Sec   245.94     80.01     0.86k    66.42%
      87585 requests in 30.05s, 11.78MB read
    Requests/sec:   2914.22
    Transfer/sec:    401.27KB


from web.apps.vibora_app import ViboraApplication<EOL>from vibora import Request, Response<EOL>app = ViboraApplication()<EOL>class AsyncHandler(Handler):<EOL><INDENT>async def __call__(self, request: Request) -> Response:<EOL><INDENT>return super().__call__(request)<EOL><DEDENT><DEDENT>class Home(AsyncHandler):<EOL><INDENT>async def get(self, request, response):<EOL><INDENT>return Response(HELLO_WORLD.encode())<EOL><DEDENT><DEDENT>class Landing(AsyncHandler):<EOL><INDENT>async def get(self, request, response):<EOL><INDENT>return Response(LANDING_PAGE.encode())<EOL><DEDENT><DEDENT>app.add_static_route('<STR_LIT>', STATIC_PATH)<EOL>app.add_route('<STR_LIT:/>', Home())<EOL>app.add_route('<STR_LIT>', Landing())<EOL>app.timed_call(<NUM_LIT>, app.stop)<EOL>app.start(port=port)<EOL>


change = json.loads(message)<EOL>log.debug(f'<STR_LIT>')<EOL>ref = change.get('<STR_LIT>')<EOL>if not ref:<EOL><INDENT>return<EOL><DEDENT>nodes = self.viewer.xpath('<STR_LIT>', ref=ref)<EOL>if not nodes:<EOL><INDENT>return  <EOL><DEDENT>node = nodes[<NUM_LIT:0>]<EOL>if change.get('<STR_LIT:type>') and change.get('<STR_LIT:name>'):<EOL><INDENT>if change['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>trigger = getattr(node, change['<STR_LIT:name>'])<EOL>trigger()<EOL><DEDENT>elif change['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>setattr(node, change['<STR_LIT:name>'], change['<STR_LIT:value>'])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>log.warning(f"<STR_LIT>")<EOL><DEDENT>

When we get an event from js, lookup the node and invoke the
        action on the enaml node.


log.debug(f'<STR_LIT>')<EOL>self.write_message(json.dumps(change['<STR_LIT:value>']))<EOL>

When an event from enaml occurs, send it out the websocket
        so the client's browser can update accordingly.


if self.__class__.view:<EOL><INDENT>self.view.handler = self<EOL>self.view.request = self.request<EOL>return<EOL><DEDENT>with enaml.imports():<EOL><INDENT>from views.index import View<EOL><DEDENT>self.__class__.view = View(<EOL>company=current_company,<EOL>request=self.request,<EOL>handler=self,<EOL>)<EOL>

Load the view on first load could also load based on session, group, etc..


if self.is_websocket():<EOL><INDENT>return super(DemoHandler, self).get(*args, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>self.write(self.view.render())<EOL><DEDENT>

Execute the correct handler depending on what is connecting.


<EOL>change = tornado.escape.json_decode(message)<EOL>ref = change.get('<STR_LIT>')<EOL>if not ref:<EOL><INDENT>return<EOL><DEDENT>node = self.view.xpath('<STR_LIT>'.format(ref), first=True)<EOL>if node is None:<EOL><INDENT>return<EOL><DEDENT>if change.get('<STR_LIT:type>') and change.get('<STR_LIT:name>'):<EOL><INDENT>if change['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>trigger = getattr(node, change['<STR_LIT:name>'])<EOL>trigger()<EOL><DEDENT>if change['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>setattr(node, change['<STR_LIT:name>'], change['<STR_LIT:value>'])<EOL><DEDENT><DEDENT>


menus = {}<EOL>links = [p.link for p in self.pages if p.link] + self.links <EOL>for link in links:<EOL><INDENT>for menu in link.menus:<EOL><INDENT>if menu not in menus:<EOL><INDENT>menus[menu] = []<EOL><DEDENT>menus[menu].append(link)<EOL><DEDENT><DEDENT>for name,menu in menus.items():<EOL><INDENT>k = '<STR_LIT>'.format(name)<EOL>if hasattr(self,k):<EOL><INDENT>setattr(self,k,menu)<EOL><DEDENT><DEDENT>


static_path = os.path.abspath(os.path.join(os.path.dirname(__file__),"<STR_LIT>"))<EOL>urls = [<EOL>(r"<STR_LIT>", cyclone.web.StaticFileHandler, {"<STR_LIT:path>": static_path}),<EOL>]<EOL>for p in self.pages:<EOL><INDENT>handler = p.handler<EOL>handler.site = self<EOL>handler.page = p<EOL>urls.append((p.link.url,handler))<EOL><DEDENT>return urls<EOL>


return Site(app=app)<EOL>


if self.__class__.view:<EOL><INDENT>return<EOL><DEDENT>with enaml.imports():<EOL><INDENT>View = pydoc.locate(self.page.view)<EOL><DEDENT>assert View, "<STR_LIT>".format(self.page.view)<EOL>self.__class__.view = View(<EOL>site=self.site,<EOL>page=self.page,<EOL>request=self.request,<EOL>)<EOL>


super(Block, self).initialize()<EOL>self.refresh_items()<EOL>

A reimplemented initializer.

        This method will add the include objects to the parent of the
        include and ensure that they are initialized.


block = self.block<EOL>if block and self.is_initialized and change['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>if change['<STR_LIT>'] == '<STR_LIT:replace>':<EOL><INDENT>raise NotImplementedError<EOL><DEDENT>for c in self.children:<EOL><INDENT>block.children.remove(c)<EOL>c.set_parent(None)<EOL><DEDENT>self.refresh_items()<EOL><DEDENT>


if self.is_initialized and change['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>old_block = change['<STR_LIT>']<EOL>for c in self.children:<EOL><INDENT>old_block.children.remove(c)<EOL>c.set_parent(None)<EOL><DEDENT>self.refresh_items()<EOL><DEDENT>

A change handler for the 'objects' list of the Include.

        If the object is initialized objects which are removed will be
        unparented and objects which are added will be reparented. Old
        objects will be destroyed if the 'destroy_old' flag is True.


if not self.is_initialized or change['<STR_LIT:type>'] != '<STR_LIT>':<EOL><INDENT>return<EOL><DEDENT>block = self.block<EOL>new_children = change['<STR_LIT:value>']<EOL>old_children = change['<STR_LIT>']<EOL>for c in old_children:<EOL><INDENT>if c not in new_children and not c.is_destroyed:<EOL><INDENT>c.destroy()<EOL><DEDENT>else:<EOL><INDENT>c.set_parent(None)<EOL><DEDENT><DEDENT>if block:<EOL><INDENT>before = None<EOL>if self.mode == '<STR_LIT:replace>':<EOL><INDENT>block.children = []<EOL><DEDENT>if self.mode == '<STR_LIT>' and block.children:<EOL><INDENT>before = block.children[<NUM_LIT:0>]<EOL><DEDENT>block.insert_children(before, new_children)<EOL><DEDENT>else:<EOL><INDENT>self.parent.insert_children(self, new_children)<EOL><DEDENT>

When the children of the block change. Update the referenced
        block.


super(WebApplication, self).__init__(*args, **kwargs)<EOL>self.resolver = ProxyResolver(factories=lxml_components.FACTORIES)<EOL>


super(Raw, self)._update_proxy(change)<EOL>

The superclass implementation is sufficient.


@observe('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>')<EOL><INDENT>def _update_proxy(self, change):<DEDENT>

super(Markdown, self)._update_proxy(change)<EOL>


raise NotImplementedError<EOL>


@observe('<STR_LIT:id>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:text>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>')<EOL><INDENT>def _update_proxy(self, change):<DEDENT>

<EOL>if change['<STR_LIT:type>'] == '<STR_LIT>' and self.proxy_is_active:<EOL><INDENT>handler = getattr(self.proxy, '<STR_LIT>' + change['<STR_LIT:name>'], None)<EOL>if handler is not None:<EOL><INDENT>handler(change['<STR_LIT:value>'])<EOL><DEDENT>else:<EOL><INDENT>self.proxy.set_attribute(change['<STR_LIT:name>'], change['<STR_LIT:value>'])<EOL><DEDENT>self._notify_modified(change)<EOL><DEDENT>

Update the proxy widget when the Widget data
        changes.


root = self.root_object()<EOL>if isinstance(root, Html):<EOL><INDENT>name = change['<STR_LIT:name>']<EOL>change = {<EOL>'<STR_LIT>': self.ref,<EOL>'<STR_LIT:type>': change['<STR_LIT:type>'],<EOL>'<STR_LIT:name>': change['<STR_LIT:name>'],<EOL>'<STR_LIT:value>': change['<STR_LIT:value>']<EOL>}<EOL>root.modified(change)<EOL><DEDENT>

If a change occurs when we have a websocket connection active
        notify the websocket client of the change.


nodes = self.proxy.find(query, **kwargs)<EOL>return [n.declaration for n in nodes]<EOL>

Find nodes matching the given xpath query


for k, v in kwargs.items():<EOL><INDENT>setattr(self, k, v)<EOL><DEDENT>if not self.is_initialized:<EOL><INDENT>self.initialize()<EOL><DEDENT>if not self.proxy_is_active:<EOL><INDENT>self.activate_proxy()<EOL><DEDENT>


self.prepare(**kwargs)<EOL>return self.proxy.render()<EOL>


super(Notebook, self)._update_proxy(change)<EOL>


@observe('<STR_LIT>', '<STR_LIT>')<EOL><INDENT>def _update_proxy(self, change):<DEDENT>

super(Code, self)._update_proxy(change)<EOL>


self.widget = SubElement(self.parent_widget(), self.declaration.tag)<EOL>

Create the toolkit widget for the proxy object.

        This method is called during the top-down pass, just before the
        'init_widget()' method is called. This method should create the
        toolkit widget and assign it to the 'widget' attribute.


widget = self.widget<EOL>d = self.declaration<EOL>ref = d.ref<EOL>CACHE[ref] = atomref(self)<EOL>widget.set('<STR_LIT>', ref)<EOL>if d.text:<EOL><INDENT>self.set_text(d.text)<EOL><DEDENT>if d.tail:<EOL><INDENT>self.set_tail(d.tail)<EOL><DEDENT>if d.style:<EOL><INDENT>self.set_style(d.style)<EOL><DEDENT>if d.cls:<EOL><INDENT>self.set_cls(d.cls)<EOL><DEDENT>if d.attrs:<EOL><INDENT>self.set_attrs(d.attrs)<EOL><DEDENT>if d.id:<EOL><INDENT>widget.set('<STR_LIT:id>', d.id)<EOL><DEDENT>if d.draggable:<EOL><INDENT>self.set_draggable(d.draggable)<EOL><DEDENT>for name, member in d.members().items():<EOL><INDENT>if not member.metadata:<EOL><INDENT>continue<EOL><DEDENT>meta = member.metadata<EOL>if not (meta.get('<STR_LIT>') and meta.get('<STR_LIT>')):<EOL><INDENT>continue<EOL><DEDENT>elif not meta.get('<STR_LIT>', True):<EOL><INDENT>continue<EOL><DEDENT>elif isinstance(member, Event):<EOL><INDENT>continue<EOL><DEDENT>value = getattr(d, name)<EOL>if value:<EOL><INDENT>self.set_attribute(name, value)<EOL><DEDENT><DEDENT>

Initialize the state of the toolkit widget.

        This method is called during the top-down pass, just after the
        'create_widget()' method is called. This method should init the
        state of the widget. The child widgets will not yet be created.


pass<EOL>

Initialize the layout of the toolkit widget.

        This method is called during the bottom-up pass. This method
        should initialize the layout of the widget. The child widgets
        will be fully initialized and layed out when this is called.


pass<EOL>

Initialize the event handlers of the toolkit widget.

        This method is called during the bottom-up pass. This method
        should initialize the event handlers for the widget. The child widgets
        will be fully initialized and layed out when this is called.


self.create_widget()<EOL>self.init_widget()<EOL>

Activate the proxy for the top-down pass.


self.init_layout()<EOL>self.init_events()<EOL>

Activate the proxy tree for the bottom-up pass.


widget = self.widget<EOL>if widget is not None:<EOL><INDENT>parent = widget.getparent()<EOL>if parent is not None:<EOL><INDENT>parent.remove(widget)<EOL><DEDENT>del self.widget<EOL>d = self.declaration<EOL>try:<EOL><INDENT>del CACHE[d.ref]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>super(WebComponent, self).destroy()<EOL>

A reimplemented destructor.

        This destructor will clear the reference to the toolkit widget
        and set its parent to None.


super(WebComponent, self).child_added(child)<EOL>if child.widget is not None:<EOL><INDENT>for i, c in enumerate(self.children()):<EOL><INDENT>if c == child:<EOL><INDENT>self.widget.insert(i, child.widget)<EOL>break<EOL><DEDENT><DEDENT><DEDENT>

Handle the child added event from the declaration.

        This handler will insert the child toolkit widget in the correct.
        position. Subclasses which need more control should reimplement this
        method.


super(WebComponent, self).child_removed(child)<EOL>if child.widget is not None:<EOL><INDENT>for i, c in enumerate(self.children()):<EOL><INDENT>if c == child:<EOL><INDENT>del self.widget[i]<EOL>break<EOL><DEDENT><DEDENT><DEDENT>

Handle the child removed event from the declaration.

        This handler will unparent the child toolkit widget. Subclasses
        which need more control should reimplement this method.


return tostring(self.widget, pretty_print=True,<EOL>encoding='<STR_LIT:utf-8>', method='<STR_LIT:html>')<EOL>


nodes = self.widget.xpath(query, **kwargs)<EOL>if not nodes:<EOL><INDENT>return []<EOL><DEDENT>matches = []<EOL>for node in nodes:<EOL><INDENT>aref = CACHE.get(node.attrib.get('<STR_LIT>'))<EOL>obj = aref() if aref else None<EOL>if obj is None:<EOL><INDENT>continue<EOL><DEDENT>matches.append(obj)<EOL><DEDENT>return matches<EOL>


parent = self.parent()<EOL>if parent is not None:<EOL><INDENT>return parent.widget<EOL><DEDENT>

Get the parent toolkit widget for this object.

        Returns
        -------
        result : QObject or None
            The toolkit widget declared on the declaration parent, or
            None if there is no such parent.


for child in self.children():<EOL><INDENT>w = child.widget<EOL>if w is not None:<EOL><INDENT>yield w<EOL><DEDENT><DEDENT>

Get the child toolkit widgets for this object.

        Returns
        -------
        result : iterable of QObject
            The child widgets defined for this object.


self.widget.attrib.update(attrs)<EOL>

Set any attributes not explicitly defined


if value is True:<EOL><INDENT>self.widget.set(name, name)<EOL><DEDENT>elif value is False:<EOL><INDENT>del self.widget.attrib[name]<EOL><DEDENT>else:<EOL><INDENT>self.widget.set(name, str(value))<EOL><DEDENT>

Default handler for those not explicitly defined


self.widget.set('<STR_LIT>', '<STR_LIT:true>' if draggable else '<STR_LIT:false>')<EOL>

The draggable attr must be explicitly set to true or false


d = self.declaration<EOL>if d.source:<EOL><INDENT>self.set_source(d.source)<EOL><DEDENT>else:<EOL><INDENT>super(RawComponent, self).init_widget()<EOL><DEDENT>


self.widget.clear()<EOL>html = etree.HTML(source)<EOL>self.widget.extend(html[<NUM_LIT:0>])<EOL>super(RawComponent, self).init_widget()<EOL>

Set the source by parsing the source and inserting it into the
        component.


filtered_path = os.path.join(<EOL>settings.MEDIA_ROOT,<EOL>VERSATILEIMAGEFIELD_FILTERED_DIRNAME<EOL>)<EOL>sized_path = os.path.join(<EOL>settings.MEDIA_ROOT,<EOL>VERSATILEIMAGEFIELD_SIZED_DIRNAME<EOL>)<EOL>placeholder_path = os.path.join(<EOL>settings.MEDIA_ROOT,<EOL>VERSATILEIMAGEFIELD_PLACEHOLDER_DIRNAME<EOL>)<EOL>rmtree(filtered_path, ignore_errors=True)<EOL>rmtree(sized_path, ignore_errors=True)<EOL>rmtree(placeholder_path, ignore_errors=True)<EOL>

Delete files made by VersatileImageFields during tests.


Assert `field_instance` (VersatileImageField instance) deletes.


self.client.login(username='<STR_LIT:test>', password='<STR_LIT>')<EOL>

Build test instances, create test client.


def assertImageEqual(self, image1, image2):

h1 = image1.histogram()<EOL>h2 = image2.histogram()<EOL>rms = math.sqrt(<EOL>reduce(<EOL>operator.add,<EOL>map(lambda a, b: (a - b) ** <NUM_LIT:2>, h1, h2)<EOL>) // len(h1)<EOL>)<EOL>self.assertEqual(rms, <NUM_LIT:0.0>)<EOL>

Assert that `image1` & `image2` are identical images.


self._create_on_demand = VERSATILEIMAGEFIELD_CREATE_ON_DEMAND<EOL>super(VersatileImageMixIn, self).__init__(*args, **kwargs)<EOL>if self.field.ppoi_field:<EOL><INDENT>instance_ppoi_value = getattr(<EOL>self.instance,<EOL>self.field.ppoi_field,<EOL>(<NUM_LIT:0.5>, <NUM_LIT:0.5>)<EOL>)<EOL>self.ppoi = instance_ppoi_value<EOL><DEDENT>else:<EOL><INDENT>self.ppoi = (<NUM_LIT:0.5>, <NUM_LIT:0.5>)<EOL><DEDENT>


if not self.name and self.field.placeholder_image_name:<EOL><INDENT>return self.storage.url(self.field.placeholder_image_name)<EOL><DEDENT>return super(VersatileImageMixIn, self).url<EOL>

Return the appropriate URL.

URL is constructed based on these field conditions:
    * If empty (not `self.name`) and a placeholder is defined, the
      URL to the placeholder is returned.
    * Otherwise, defaults to vanilla ImageFieldFile behavior.


return self._create_on_demand<EOL>


return self._ppoi_value<EOL>

Primary Point of Interest (ppoi) getter.


ppoi = validate_ppoi(<EOL>value,<EOL>return_converted_tuple=True<EOL>)<EOL>if ppoi is not False:<EOL><INDENT>self._ppoi_value = ppoi<EOL>self.build_filters_and_sizers(ppoi, self.create_on_demand)<EOL><DEDENT>

Primary Point of Interest (ppoi) setter.


def build_filters_and_sizers(self, ppoi_value, create_on_demand):

name = self.name<EOL>if not name and self.field.placeholder_image_name:<EOL><INDENT>name = self.field.placeholder_image_name<EOL><DEDENT>self.filters = FilterLibrary(<EOL>name,<EOL>self.storage,<EOL>versatileimagefield_registry,<EOL>ppoi_value,<EOL>create_on_demand<EOL>)<EOL>for (<EOL>attr_name,<EOL>sizedimage_cls<EOL>) in iteritems(versatileimagefield_registry._sizedimage_registry):<EOL><INDENT>setattr(<EOL>self,<EOL>attr_name,<EOL>sizedimage_cls(<EOL>path_to_image=name,<EOL>storage=self.storage,<EOL>create_on_demand=create_on_demand,<EOL>ppoi=ppoi_value<EOL>)<EOL>)<EOL><DEDENT>

Build the filters and sizers for a field.


folder, filename = os.path.split(self.name)<EOL>return os.path.join(folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME, '<STR_LIT>')<EOL>

Return the location where filtered images are stored.


folder, filename = os.path.split(self.name)<EOL>return os.path.join(VERSATILEIMAGEFIELD_SIZED_DIRNAME, folder, '<STR_LIT>')<EOL>

Return the location where sized images are stored.


sized_root_folder = self.get_sized_root_folder()<EOL>return os.path.join(<EOL>sized_root_folder,<EOL>VERSATILEIMAGEFIELD_FILTERED_DIRNAME<EOL>)<EOL>

Return the location where filtered + sized images are stored.


def delete_matching_files_from_storage(self, root_folder, regex):

if not self.name:   <EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>directory_list, file_list = self.storage.listdir(root_folder)<EOL><DEDENT>except OSError:   <EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>folder, filename = os.path.split(self.name)<EOL>basename, ext = os.path.splitext(filename)<EOL>for f in file_list:<EOL><INDENT>if not f.startswith(basename) or not f.endswith(ext):   <EOL><INDENT>continue<EOL><DEDENT>tag = f[len(basename):-len(ext)]<EOL>assert f == basename + tag + ext<EOL>if regex.match(tag) is not None:<EOL><INDENT>file_location = os.path.join(root_folder, f)<EOL>self.storage.delete(file_location)<EOL>cache.delete(<EOL>self.storage.url(file_location)<EOL>)<EOL>print(<EOL>"<STR_LIT>".format(<EOL>file=os.path.join(root_folder, f),<EOL>original=self.name<EOL>)<EOL>)<EOL><DEDENT><DEDENT><DEDENT>

Delete files in `root_folder` which match `regex` before file ext.

Example values:
    * root_folder = 'foo/'
    * self.name = 'bar.jpg'
    * regex = re.compile('-baz')

    Result:
        * foo/bar-baz.jpg <- Deleted
        * foo/bar-biz.jpg <- Not deleted


self.delete_matching_files_from_storage(<EOL>self.get_filtered_root_folder(),<EOL>filter_regex<EOL>)<EOL>

Delete all filtered images created from `self.name`.


self.delete_matching_files_from_storage(<EOL>self.get_sized_root_folder(),<EOL>sizer_regex<EOL>)<EOL>

Delete all sized images created from `self.name`.


self.delete_matching_files_from_storage(<EOL>self.get_filtered_sized_root_folder(),<EOL>filter_and_sizer_regex<EOL>)<EOL>

Delete all filtered sized images created from `self.name`.


self.delete_filtered_images()<EOL>self.delete_sized_images()<EOL>self.delete_filtered_sized_images()<EOL>

Delete all images created from `self.name`.


context_request = None<EOL>if self.context:<EOL><INDENT>context_request = self.context.get('<STR_LIT>', None)<EOL><DEDENT>return build_versatileimagefield_url_set(<EOL>value,<EOL>self.sizes,<EOL>request=context_request<EOL>)<EOL>


return self.to_native(value)<EOL>


valid = True<EOL>while valid is True:<EOL><INDENT>if len(value) == <NUM_LIT:2> and isinstance(value, tuple):<EOL><INDENT>for x in value:<EOL><INDENT>if x >= <NUM_LIT:0> and x <= <NUM_LIT:1>:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>valid = False<EOL><DEDENT><DEDENT>break<EOL><DEDENT>else:<EOL><INDENT>valid = False<EOL><DEDENT><DEDENT>return valid<EOL>

Validates that a tuple (`value`)...
...has a len of exactly 2
...both values are floats/ints that are greater-than-or-equal-to 0
   AND less-than-or-equal-to 1


valid_ppoi = True<EOL>to_return = None<EOL>if isinstance(value, tuple):<EOL><INDENT>valid_ppoi = validate_ppoi_tuple(value)<EOL>if valid_ppoi:<EOL><INDENT>to_return = value<EOL><DEDENT><DEDENT>else:<EOL><INDENT>tup = tuple()<EOL>try:<EOL><INDENT>string_split = [<EOL>float(segment.strip())<EOL>for segment in value.split('<STR_LIT:x>')<EOL>if float(segment.strip()) >= <NUM_LIT:0> and float(segment.strip()) <= <NUM_LIT:1><EOL>]<EOL><DEDENT>except Exception:<EOL><INDENT>valid_ppoi = False<EOL><DEDENT>else:<EOL><INDENT>tup = tuple(string_split)<EOL><DEDENT>valid_ppoi = validate_ppoi_tuple(tup)<EOL>if valid_ppoi:<EOL><INDENT>to_return = tup<EOL><DEDENT><DEDENT>if not valid_ppoi:<EOL><INDENT>raise ValidationError(<EOL>message=INVALID_CENTERPOINT_ERROR_MESSAGE % str(value),<EOL>code='<STR_LIT>'<EOL>)<EOL><DEDENT>else:<EOL><INDENT>if to_return and return_converted_tuple is True:<EOL><INDENT>return to_return<EOL><DEDENT><DEDENT>

Converts, validates and optionally returns a string with formatting:
'%(x_axis)dx%(y_axis)d' into a two position tuple.

If a tuple is passed to `value` it is also validated.

Both x_axis and y_axis must be floats or ints greater
than 0 and less than 1.


def cli_progress_bar(start, end, bar_length=<NUM_LIT:50>):

percent = float(start) / end<EOL>hashes = '<STR_LIT:#>' * int(round(percent * bar_length))<EOL>spaces = '<STR_LIT:->' * (bar_length - len(hashes))<EOL>stdout.write(<EOL>"<STR_LIT>".format(<EOL>hashes + spaces,<EOL>start,<EOL>end,<EOL>int(round(percent * <NUM_LIT:100>))<EOL>)<EOL>)<EOL>stdout.flush()<EOL>

Prints out a Yum-style progress bar (via sys.stdout.write).
`start`: The 'current' value of the progress bar.
`end`: The '100%' value of the progress bar.
`bar_length`: The size of the overall progress bar.

Example output with start=20, end=100, bar_length=50:
[###########----------------------------------------] 20/100 (100%)

Intended to be used in a loop. Example:
end = 100
for i in range(end):
    cli_progress_bar(i, end)

Based on an implementation found here:
    http://stackoverflow.com/a/13685020/1149774


def __init__(self, instance_or_queryset,<EOL>rendition_key_set, image_attr, verbose=False):

if isinstance(instance_or_queryset, Model):<EOL><INDENT>queryset = instance_or_queryset.__class__._default_manager.filter(<EOL>pk=instance_or_queryset.pk<EOL>)<EOL><DEDENT>elif isinstance(instance_or_queryset, QuerySet):<EOL><INDENT>queryset = instance_or_queryset<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT:{}>".format(self.__class__.__name__)<EOL>)<EOL><DEDENT>self.queryset = queryset<EOL>if isinstance(rendition_key_set, six.string_types):<EOL><INDENT>rendition_key_set = get_rendition_key_set(rendition_key_set)<EOL><DEDENT>self.size_key_list = [<EOL>size_key<EOL>for key, size_key in validate_versatileimagefield_sizekey_list(<EOL>rendition_key_set<EOL>)<EOL>]<EOL>self.image_attr = image_attr<EOL>self.verbose = verbose<EOL>

Arguments:
`instance_or_queryset`: A django model instance or QuerySet
`rendition_key_set`: Either a string that corresponds to a key on
                settings.VERSATILEIMAGEFIELD_RENDITION_KEY_SETS
                or an iterable
                of 2-tuples, both strings:
    [0]: The 'name' of the image size.
    [1]: A VersatileImageField 'size_key'.
    Example: [
        ('large', 'url'),
        ('medium', 'crop__400x400'),
        ('small', 'thumbnail__100x100')
    ]
`image_attr`: A dot-notated path to a VersatileImageField on
              `instance_or_queryset`
`verbose`: bool signifying whether a progress bar should be printed
           to sys.stdout


versatileimagefieldfile.create_on_demand = True<EOL>try:<EOL><INDENT>url = get_url_from_image_key(versatileimagefieldfile, size_key)<EOL><DEDENT>except Exception:<EOL><INDENT>success = False<EOL>url_or_filepath = versatileimagefieldfile.name<EOL>logger.exception('<STR_LIT>',<EOL>extra={'<STR_LIT:path>': url_or_filepath})<EOL><DEDENT>else:<EOL><INDENT>success = True<EOL>url_or_filepath = url<EOL><DEDENT>return (success, url_or_filepath)<EOL>

Returns a 2-tuple:
0: bool signifying whether the image was successfully pre-warmed
1: The url of the successfully created image OR the path on storage of
   the image that was not able to be successfully created.

Arguments:
`size_key_list`: A list of VersatileImageField size keys. Examples:
    * 'crop__800x450'
    * 'thumbnail__800x800'
`versatileimagefieldfile`: A VersatileImageFieldFile instance


num_images_pre_warmed = <NUM_LIT:0><EOL>failed_to_create_image_path_list = []<EOL>total = self.queryset.count() * len(self.size_key_list)<EOL>for a, instance in enumerate(self.queryset, start=<NUM_LIT:1>):<EOL><INDENT>for b, size_key in enumerate(self.size_key_list, start=<NUM_LIT:1>):<EOL><INDENT>success, url_or_filepath = self._prewarm_versatileimagefield(<EOL>size_key,<EOL>reduce(getattr, self.image_attr.split("<STR_LIT:.>"), instance)<EOL>)<EOL>if success is True:<EOL><INDENT>num_images_pre_warmed += <NUM_LIT:1><EOL>if self.verbose:<EOL><INDENT>cli_progress_bar(num_images_pre_warmed, total)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>failed_to_create_image_path_list.append(url_or_filepath)<EOL><DEDENT>if a * b == total:<EOL><INDENT>stdout.write('<STR_LIT:\n>')<EOL><DEDENT><DEDENT><DEDENT>stdout.flush()<EOL>return (num_images_pre_warmed, failed_to_create_image_path_list)<EOL>

Returns a 2-tuple:
[0]: Number of images successfully pre-warmed
[1]: A list of paths on the storage class associated with the
     VersatileImageField field being processed by `self` of
     files that could not be successfully seeded.


if data is not None:<EOL><INDENT>if hasattr(data, '<STR_LIT>'):<EOL><INDENT>data.open()<EOL><DEDENT>return super(VersatileImageFormField, self).to_python(data)<EOL><DEDENT>

Ensure data is prepped properly before handing off to ImageField.


return hashlib.md5(image_key.encode('<STR_LIT:utf-8>')).hexdigest()<EOL>