<commit_before>import mbuild as mb
import numpy as np

from copy import deepcopy

__all__ = ['Monolayer']

class Monolayer(mb.Compound):
    """A general monolayer recipe.

    Parameters
    ----------
    surface : mb.Compound
        Surface on which the monolayer will be built.
    chains : list of mb.Compounds
        The chains to be replicated and attached to the surface.
    fractions : list
        The fractions of the pattern to be allocated to each chain.
    backfill : list of mb.Compound, optional, default=None
        If there are fewer chains than there are ports on the surface,
        copies of `backfill` will be used to fill the remaining ports.
    pattern : mb.Pattern, optional, default=mb.Random2DPattern
        An array of planar binding locations. If not provided, the entire
        surface will be filled with `chain`.
    tile_x : int, optional, default=1
        Number of times to replicate substrate in x-direction.
    tile_y : int, optional, default=1
        Number of times to replicate substrate in y-direction.

    """

    def __init__(self, surface, chains, fractions=None, backfill=None, pattern=None,
                 tile_x=1, tile_y=1, **kwargs):
        super(Monolayer, self).__init__()

        # Replicate the surface.
        tiled_compound = mb.TiledCompound(surface, n_tiles=(tile_x, tile_y, 1))
        self.add(tiled_compound, label='tiled_surface')

        if pattern is None:  # Fill the surface.
            pattern = mb.Random2DPattern(len(tiled_compound.referenced_ports()))

        if isinstance(chains, mb.Compound):
            chains = [chains]

        n_chains = len(pattern.points)

        # Attach chains of each type to binding sites based on specified fractions
        for i,chain in enumerate(chains[:-1]):

            # Create sub-pattern for this chain type
            subpattern = deepcopy(pattern)
            n_points = round(fractions[i] * n_chains)
            points = subpattern.points[np.random.choice(subpattern.points.shape[0], n_points, replace=False)]
            subpattern.points = points

            # Remove now-occupied points from overall pattern
            pattern.points = np.array([point for point in pattern.points.tolist() if point not in subpattern.points.tolist()])

            # Attach chains to the surface
            attached_chains = subpattern.apply_to_compound(guest=chain,
                              host=self['tiled_surface'], backfill=None, **kwargs)
            self.add(attached_chains)

        # Attach final chain type. Remaining sites get a backfill.
        attached_chains, backfills = pattern.apply_to_compound(guest=chains[-1],
                         host=self['tiled_surface'], backfill=backfill, **kwargs)
        self.add(attached_chains)
        self.add(backfills)
<commit_msg>All chains added in main loop.  Warnings provided after rounding.<commit_after>import mbuild as mb
import numpy as np
import warnings

from copy import deepcopy

__all__ = ['Monolayer']

class Monolayer(mb.Compound):
    """A general monolayer recipe.

    Parameters
    ----------
    surface : mb.Compound
        Surface on which the monolayer will be built.
    chains : list of mb.Compounds
        The chains to be replicated and attached to the surface.
    fractions : list
        The fractions of the pattern to be allocated to each chain.
    backfill : list of mb.Compound, optional, default=None
        If there are fewer chains than there are ports on the surface,
        copies of `backfill` will be used to fill the remaining ports.
    pattern : mb.Pattern, optional, default=mb.Random2DPattern
        An array of planar binding locations. If not provided, the entire
        surface will be filled with `chain`.
    tile_x : int, optional, default=1
        Number of times to replicate substrate in x-direction.
    tile_y : int, optional, default=1
        Number of times to replicate substrate in y-direction.

    """

    def __init__(self, surface, chains, fractions=None, backfill=None, pattern=None,
                 tile_x=1, tile_y=1, **kwargs):
        super(Monolayer, self).__init__()

        # Replicate the surface.
        tiled_compound = mb.TiledCompound(surface, n_tiles=(tile_x, tile_y, 1))
        self.add(tiled_compound, label='tiled_surface')

        if pattern is None:  # Fill the surface.
            pattern = mb.Random2DPattern(len(tiled_compound.referenced_ports()))

        if isinstance(chains, mb.Compound):
            chains = [chains]

        n_chains = len(pattern.points)

        # Attach chains of each type to binding sites based on specified fractions
        for i,chain in enumerate(chains):

            if i < len(chains)-1:
                # Create sub-pattern for this chain type
                subpattern = deepcopy(pattern)
                n_points = round(fractions[i] * n_chains)
                warnings.warn("\n Adding {} of chain {}".format(int(n_points), chain))
                points = subpattern.points[np.random.choice(subpattern.points.shape[0], n_points, replace=False)]
                subpattern.points = points

                # Remove now-occupied points from overall pattern
                pattern.points = np.array([point for point in pattern.points.tolist()
                                           if point not in subpattern.points.tolist()])

                # Attach chains to the surface
                attached_chains, _ = subpattern.apply_to_compound(guest=chain,
                                     host=self['tiled_surface'], backfill=None, **kwargs)

            else:
                # Attach final chain type. Remaining sites get a backfill.
                warnings.warn("\n Adding {} of chain {}".format(len(pattern), chains[-1]))
                attached_chains, backfills = pattern.apply_to_compound(guest=chains[-1],
                             host=self['tiled_surface'], backfill=backfill, **kwargs)
                self.add(backfills)

            self.add(attached_chains)
<|endoftext|>


<commit_before>import datetime
import threading
import time

import cherrypy
from cherrypy.lib import cptools, http

class VaryHeaderAwareStore():
    def __init__(self):
        # keep a nested dictionary of cached responses indexed first by
        #  URI and then by "Vary" header values
        self.uri_store = {}

    def get_key_from_request(self, request, response=None):
        """The key into the index needs to be some combination of
        the URI and the request headers indicated by the response
        as Varying in a normalized (e.g. sorted) format."""
        # First, get a cached response for the URI
        uri = VaryHeaderUnawareStore.get_key_from_request(request)
        try:
            cached_resp = self._get_any_response(uri)
            response_headers = cached_resp[1]
        except KeyError:
            response_headers = response.headers
        vary_header_values = self._get_vary_header_values(request, response_headers)
        return uri, '|'.join(vary_header_values)

    def _get_vary_header_values(request, response_headers):
        h = response_headers
        vary_header_names = [e.value for e in h.elements('Vary')]
        vary_header_names.sort()
        vary_header_values = [
            request.headers.get(h_name, '')
            for h_name in vary_header_names]
        return vary_header_values
    _get_vary_header_values = staticmethod(_get_vary_header_values)

    def _get_any_response(self, uri):
        """
        When a request for a URI comes in, we need to check
        if it is already in the cache, but the response hasn't
        yet been generated to determine the vary headers.
        We can assume the Vary headers do not change for a
        given URI, so use the Vary headers from a previous
        response (any will do).
        """
        vary_store = self.uri_store.get(uri)
        if not vary_store:
            # No values exist for this URI
            raise KeyError(uri)
        return vary_store.values()[0]

    def __getitem__(self, key):
        return self.get(key)

    def get(self, key, *args, **kwargs):
        uri, h_vals = key
        vary_store = self.uri_store.get(uri, {})
        return vary_store.get(h_vals, *args, **kwargs)

    def __setitem__(self, key, value):
        uri, h_vals = key
        vary_store = self.uri_store.setdefault(uri, {})
        vary_store[h_vals] = value

    def __delitem__(self, key):
        uri, h_vals = key
        vary_store = self.uri_store[uri]
        del vary_store[h_vals]
        if not vary_store:
            # if the vary store is empty, delete the URI entry also
            del self.uri_store[uri]

    def pop(self, key, *args, **kwargs):
        item = self.get(key, *args, **kwargs)
        del self[key]

    def __len__(self):
        lengths = [len(store) for store in self.uri_store.values()]
        return sum(lengths)

class VaryHeaderUnawareStore(dict):
    def get_key_from_request(request, response=None):
        return cherrypy.url(qs=request.query_string)
    get_key_from_request = staticmethod(get_key_from_request)

class MemoryCache:

    maxobjects = 1000
    maxobj_size = 100000
    maxsize = 10000000
    delay = 600

    def __init__(self):
        self.clear()
        t = threading.Thread(target=self.expire_cache, name='expire_cache')
        self.expiration_thread = t
        if hasattr(threading.Thread, "daemon"):
            # Python 2.6+
            t.daemon = True
        else:
            t.setDaemon(True)
        t.start()

    def clear(self):
        """Reset the cache to its initial, empty state."""
        self.store = VaryHeaderAwareStore()
        self.expirations = {}
        self.tot_puts = 0
        self.tot_gets = 0
        self.tot_hist = 0
        self.tot_expires = 0
        self.tot_non_modified = 0
        self.cursize = 0

    def key(self):
        request = cherrypy.request
        try:
            response = cherrypy.response
        except AttributeError:
            response = None
        return self.store.get_key_from_request(request, response)

    def expire_cache(self):
        # expire_cache runs in a separate thread which the servers are
        # not aware of. It's possible that "time" will be set to None
        # arbitrarily, so we check "while time" to avoid exceptions.
        # See tickets #99 and #180 for more information.
        while time:
            now = time.time()
            for expiration_time, objects in self.expirations.items():
                if expiration_time <= now:
                    for obj_size, obj_key in objects:
                        try:
                            del self.store[obj_key]
                            self.tot_expires += 1
                            self.cursize -= obj_size
                        except KeyError:
                            # the key may have been deleted elsewhere
                            pass
                    del self.expirations[expiration_time]
            time.sleep(0.1)

    def get(self):
        """Return the object if in the cache, else None."""
        self.tot_gets += 1
        cache_item = self.store.get(self.key(), None)
        if cache_item:
            self.tot_hist += 1
            return cache_item
        else:
            return None

    def put(self, obj):
        if len(self.store) < self.maxobjects:
            # Size check no longer includes header length
            obj_size = len(obj[2])
            total_size = self.cursize + obj_size

            # checks if there's space for the object
            if (obj_size < self.maxobj_size and total_size < self.maxsize):
                # add to the expirations list and cache
                expiration_time = cherrypy.response.time + self.delay
                obj_key = self.key()
                bucket = self.expirations.setdefault(expiration_time, [])
                bucket.append((obj_size, obj_key))
                self.store[obj_key] = obj
                self.tot_puts += 1
                self.cursize = total_size

    def delete(self):
        self.store.pop(self.key(), None)

def get(invalid_methods=("POST", "PUT", "DELETE"), **kwargs):
    """Try to obtain cached output. If fresh enough, raise HTTPError(304).

    If POST, PUT, or DELETE:
        * invalidates (deletes) any cached response for this resource
        * sets request.cached = False
        * sets request.cacheable = False

    else if a cached copy exists:
        * sets request.cached = True
        * sets request.cacheable = False
        * sets response.headers to the cached values
        * checks the cached Last-Modified response header against the
            current If-(Un)Modified-Since request headers; raises 304
            if necessary.
        * sets response.status and response.body to the cached values
        * returns True

    otherwise:
        * sets request.cached = False
        * sets request.cacheable = True
        * returns False
    """
    request = cherrypy.request

    # POST, PUT, DELETE should invalidate (delete) the cached copy.
    # See http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.10.
    if request.method in invalid_methods:
        cherrypy._cache.delete()
        request.cached = False
        request.cacheable = False
        return False

    cache_data = cherrypy._cache.get()
    request.cached = c = bool(cache_data)
    request.cacheable = not c
    if c:
        response = cherrypy.response
        s, h, b, create_time, original_req_headers = cache_data

        # Check 'Vary' selecting headers. If any headers mentioned in "Vary"
        # differ between the cached and current request, bail out and
        # let the rest of CP handle the request. This should properly
        # mimic the behavior of isolated caches as RFC 2616 assumes:
        # "If the selecting request header fields for the cached entry
        # do not match the selecting request header fields of the new
        # request, then the cache MUST NOT use a cached entry to satisfy
        # the request unless it first relays the new request to the origin
        # server in a conditional request and the server responds with
        # 304 (Not Modified), including an entity tag or Content-Location
        # that indicates the entity to be used.
        # TODO: can we store multiple variants based on Vary'd headers?
        for header_element in h.elements('Vary'):
            key = header_element.value
            if original_req_headers.get(key, 'missing') != request.headers.get(key, 'missing'):
                request.cached = False
                request.cacheable = True
                return False

        # Copy the response headers. See http://www.cherrypy.org/ticket/721.
        response.headers = rh = http.HeaderMap()
        for k in h:
            dict.__setitem__(rh, k, dict.__getitem__(h, k))

        # Add the required Age header
        response.headers["Age"] = str(int(response.time - create_time))

        try:
            # Note that validate_since depends on a Last-Modified header;
            # this was put into the cached copy, and should have been
            # resurrected just above (response.headers = cache_data[1]).
            cptools.validate_since()
        except cherrypy.HTTPRedirect, x:
            if x.status == 304:
                cherrypy._cache.tot_non_modified += 1
            raise

        # serve it & get out from the request
        response.status = s
        response.body = b
    return c

def tee_output():
    def tee(body):
        """Tee response.body into a list."""
        output = []
        for chunk in body:
            output.append(chunk)
            yield chunk

        # Might as well do this here; why cache if the body isn't consumed?
        if response.headers.get('Pragma', None) != 'no-cache':
            # save the cache data
            body = ''.join(output)
            vary = [he.value for he in
                    cherrypy.response.headers.elements('Vary')]
            sel_headers = dict([(k, v) for k, v
                                in cherrypy.request.headers.iteritems()
                                if k in vary])
            cherrypy._cache.put((response.status, response.headers or {},
                                 body, response.time, sel_headers))

    response = cherrypy.response
    response.body = tee(response.body)

def expires(secs=0, force=False):
    """Tool for influencing cache mechanisms using the 'Expires' header.

    'secs' must be either an int or a datetime.timedelta, and indicates the
    number of seconds between response.time and when the response should
    expire. The 'Expires' header will be set to (response.time + secs).

    If 'secs' is zero, the 'Expires' header is set one year in the past, and
    the following "cache prevention" headers are also set:
       'Pragma': 'no-cache'
       'Cache-Control': 'no-cache, must-revalidate'

    If 'force' is False (the default), the following headers are checked:
    'Etag', 'Last-Modified', 'Age', 'Expires'. If any are already present,
    none of the above response headers are set.
    """

    response = cherrypy.response
    headers = response.headers

    cacheable = False
    if not force:
        # some header names that indicate that the response can be cached
        for indicator in ('Etag', 'Last-Modified', 'Age', 'Expires'):
            if indicator in headers:
                cacheable = True
                break

    if not cacheable:
        if isinstance(secs, datetime.timedelta):
            secs = (86400 * secs.days) + secs.seconds

        if secs == 0:
            if force or "Pragma" not in headers:
                headers["Pragma"] = "no-cache"
            if cherrypy.request.protocol >= (1, 1):
                if force or "Cache-Control" not in headers:
                    headers["Cache-Control"] = "no-cache, must-revalidate"
            # Set an explicit Expires date in the past.
            expiry = http.HTTPDate(1169942400.0)
        else:
            expiry = http.HTTPDate(response.time + secs)
        if force or "Expires" not in headers:
            headers["Expires"] = expiry
<commit_msg>Added a few comments Removed deprecated code that was superceded by r2213<commit_after>import datetime
import threading
import time

import cherrypy
from cherrypy.lib import cptools, http

class VaryHeaderAwareStore():
    """
    A cache store that honors the Vary headers and keeps
    a separate cached copy for each.
    """
    def __init__(self):
        # keep a nested dictionary of cached responses indexed first by
        #  URI and then by "Vary" header values
        self.uri_store = {}

    def get_key_from_request(self, request, response=None):
        """The key into the index needs to be some combination of
        the URI and the request headers indicated by the response
        as Varying in a normalized (e.g. sorted) format."""
        # First, get a cached response for the URI
        uri = VaryHeaderUnawareStore.get_key_from_request(request)
        try:
            # Try to get the cached response from the uri
            cached_resp = self._get_any_response(uri)
            response_headers = cached_resp[1]
        except KeyError:
            # if the cached response isn't available, use the immediate
            #  response
            response_headers = response.headers
        vary_header_values = self._get_vary_header_values(request, response_headers)
        return uri, '|'.join(vary_header_values)

    def _get_vary_header_values(request, response_headers):
        h = response_headers
        vary_header_names = [e.value for e in h.elements('Vary')]
        vary_header_names.sort()
        vary_header_values = [
            request.headers.get(h_name, '')
            for h_name in vary_header_names]
        return vary_header_values
    _get_vary_header_values = staticmethod(_get_vary_header_values)

    def _get_any_response(self, uri):
        """
        When a request for a URI comes in, we need to check
        if it is already in the cache, but the response hasn't
        yet been generated to determine the vary headers.
        We can assume the Vary headers do not change for a
        given URI, so use the Vary headers from a previous
        response (any will do).
        """
        vary_store = self.uri_store.get(uri)
        if not vary_store:
            # No values exist for this URI
            raise KeyError(uri)
        return vary_store.values()[0]

    def __getitem__(self, key):
        return self.get(key)

    def get(self, key, *args, **kwargs):
        uri, h_vals = key
        vary_store = self.uri_store.get(uri, {})
        return vary_store.get(h_vals, *args, **kwargs)

    def __setitem__(self, key, value):
        uri, h_vals = key
        vary_store = self.uri_store.setdefault(uri, {})
        vary_store[h_vals] = value

    def __delitem__(self, key):
        uri, h_vals = key
        vary_store = self.uri_store[uri]
        del vary_store[h_vals]
        if not vary_store:
            # if the vary store is empty, delete the URI entry also
            del self.uri_store[uri]

    def pop(self, key, *args, **kwargs):
        item = self.get(key, *args, **kwargs)
        del self[key]

    def __len__(self):
        lengths = [len(store) for store in self.uri_store.values()]
        return sum(lengths)

class VaryHeaderUnawareStore(dict):
    def get_key_from_request(request, response=None):
        return cherrypy.url(qs=request.query_string)
    get_key_from_request = staticmethod(get_key_from_request)

class MemoryCache:

    maxobjects = 1000
    maxobj_size = 100000
    maxsize = 10000000
    delay = 600

    def __init__(self):
        self.clear()
        t = threading.Thread(target=self.expire_cache, name='expire_cache')
        self.expiration_thread = t
        if hasattr(threading.Thread, "daemon"):
            # Python 2.6+
            t.daemon = True
        else:
            t.setDaemon(True)
        t.start()

    def clear(self):
        """Reset the cache to its initial, empty state."""
        self.store = VaryHeaderAwareStore()
        self.expirations = {}
        self.tot_puts = 0
        self.tot_gets = 0
        self.tot_hist = 0
        self.tot_expires = 0
        self.tot_non_modified = 0
        self.cursize = 0

    def key(self):
        request = cherrypy.request
        try:
            response = cherrypy.response
        except AttributeError:
            response = None
        return self.store.get_key_from_request(request, response)

    def expire_cache(self):
        # expire_cache runs in a separate thread which the servers are
        # not aware of. It's possible that "time" will be set to None
        # arbitrarily, so we check "while time" to avoid exceptions.
        # See tickets #99 and #180 for more information.
        while time:
            now = time.time()
            for expiration_time, objects in self.expirations.items():
                if expiration_time <= now:
                    for obj_size, obj_key in objects:
                        try:
                            del self.store[obj_key]
                            self.tot_expires += 1
                            self.cursize -= obj_size
                        except KeyError:
                            # the key may have been deleted elsewhere
                            pass
                    del self.expirations[expiration_time]
            time.sleep(0.1)

    def get(self):
        """Return the object if in the cache, else None."""
        self.tot_gets += 1
        cache_item = self.store.get(self.key(), None)
        if cache_item:
            self.tot_hist += 1
            return cache_item
        else:
            return None

    def put(self, obj):
        if len(self.store) < self.maxobjects:
            # Size check no longer includes header length
            obj_size = len(obj[2])
            total_size = self.cursize + obj_size

            # checks if there's space for the object
            if (obj_size < self.maxobj_size and total_size < self.maxsize):
                # add to the expirations list and cache
                expiration_time = cherrypy.response.time + self.delay
                obj_key = self.key()
                bucket = self.expirations.setdefault(expiration_time, [])
                bucket.append((obj_size, obj_key))
                self.store[obj_key] = obj
                self.tot_puts += 1
                self.cursize = total_size

    def delete(self):
        self.store.pop(self.key(), None)

def get(invalid_methods=("POST", "PUT", "DELETE"), **kwargs):
    """Try to obtain cached output. If fresh enough, raise HTTPError(304).

    If POST, PUT, or DELETE:
        * invalidates (deletes) any cached response for this resource
        * sets request.cached = False
        * sets request.cacheable = False

    else if a cached copy exists:
        * sets request.cached = True
        * sets request.cacheable = False
        * sets response.headers to the cached values
        * checks the cached Last-Modified response header against the
            current If-(Un)Modified-Since request headers; raises 304
            if necessary.
        * sets response.status and response.body to the cached values
        * returns True

    otherwise:
        * sets request.cached = False
        * sets request.cacheable = True
        * returns False
    """
    request = cherrypy.request

    # POST, PUT, DELETE should invalidate (delete) the cached copy.
    # See http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.10.
    if request.method in invalid_methods:
        cherrypy._cache.delete()
        request.cached = False
        request.cacheable = False
        return False

    cache_data = cherrypy._cache.get()
    request.cached = c = bool(cache_data)
    request.cacheable = not c
    if c:
        response = cherrypy.response
        s, h, b, create_time, original_req_headers = cache_data

        # Copy the response headers. See http://www.cherrypy.org/ticket/721.
        response.headers = rh = http.HeaderMap()
        for k in h:
            dict.__setitem__(rh, k, dict.__getitem__(h, k))

        # Add the required Age header
        response.headers["Age"] = str(int(response.time - create_time))

        try:
            # Note that validate_since depends on a Last-Modified header;
            # this was put into the cached copy, and should have been
            # resurrected just above (response.headers = cache_data[1]).
            cptools.validate_since()
        except cherrypy.HTTPRedirect, x:
            if x.status == 304:
                cherrypy._cache.tot_non_modified += 1
            raise

        # serve it & get out from the request
        response.status = s
        response.body = b
    return c

def tee_output():
    def tee(body):
        """Tee response.body into a list."""
        output = []
        for chunk in body:
            output.append(chunk)
            yield chunk

        # Might as well do this here; why cache if the body isn't consumed?
        if response.headers.get('Pragma', None) != 'no-cache':
            # save the cache data
            body = ''.join(output)
            vary = [he.value for he in
                    cherrypy.response.headers.elements('Vary')]
            sel_headers = dict([(k, v) for k, v
                                in cherrypy.request.headers.iteritems()
                                if k in vary])
            cherrypy._cache.put((response.status, response.headers or {},
                                 body, response.time, sel_headers))

    response = cherrypy.response
    response.body = tee(response.body)

def expires(secs=0, force=False):
    """Tool for influencing cache mechanisms using the 'Expires' header.

    'secs' must be either an int or a datetime.timedelta, and indicates the
    number of seconds between response.time and when the response should
    expire. The 'Expires' header will be set to (response.time + secs).

    If 'secs' is zero, the 'Expires' header is set one year in the past, and
    the following "cache prevention" headers are also set:
       'Pragma': 'no-cache'
       'Cache-Control': 'no-cache, must-revalidate'

    If 'force' is False (the default), the following headers are checked:
    'Etag', 'Last-Modified', 'Age', 'Expires'. If any are already present,
    none of the above response headers are set.
    """

    response = cherrypy.response
    headers = response.headers

    cacheable = False
    if not force:
        # some header names that indicate that the response can be cached
        for indicator in ('Etag', 'Last-Modified', 'Age', 'Expires'):
            if indicator in headers:
                cacheable = True
                break

    if not cacheable:
        if isinstance(secs, datetime.timedelta):
            secs = (86400 * secs.days) + secs.seconds

        if secs == 0:
            if force or "Pragma" not in headers:
                headers["Pragma"] = "no-cache"
            if cherrypy.request.protocol >= (1, 1):
                if force or "Cache-Control" not in headers:
                    headers["Cache-Control"] = "no-cache, must-revalidate"
            # Set an explicit Expires date in the past.
            expiry = http.HTTPDate(1169942400.0)
        else:
            expiry = http.HTTPDate(response.time + secs)
        if force or "Expires" not in headers:
            headers["Expires"] = expiry
<|endoftext|>


<commit_before>import json

from django.test import TestCase
from mock import patch

from regcore_write.views import layer

class ViewsLayerTest(TestCase):
    def put(self, data, name='layname', label='lablab', version='verver'):
        """Shorthand function for PUTing data to a view layer"""
        url = '/layer/{}/{}/{}'.format(name, label, version)
        if isinstance(data, dict):
            data = json.dumps(data)
        return self.client.put(url, content_type='application/json',
                               data=data)

    def test_add_not_json(self):
        """Non-JSON is invalid"""
        response = self.put('{Invalid}')
        self.assertEqual(400, response.status_code)

    def test_add_label_mismatch(self):
        """Root label must match that found in the url"""
        response = self.put({'nonlab': []}, label='lablab')
        self.assertEqual(400, response.status_code)

    def put_with_mock_data(self, message, *labels, **kwargs):
        """Helper function to mock out the value returned from fetching the
        regulation from the database, then put the provided message, and
        return the response."""
        root = []
        children = root
        for label in labels:
            node = {'label': label.split('-'), 'children': []}
            children.append(node)
            children = node['children']

        with patch('regcore_write.views.layer.db') as db:
            db.Regulations.return_value.get.return_value = root[0]
            self.put(message, **kwargs)
            self.assertTrue(db.Layers.return_value.bulk_put.called)
            layers_saved = db.Layers.return_value.bulk_put.call_args[0][0]
            return list(reversed(layers_saved))     # switch to outside in

    def test_add_success(self):
        """Can correctly add layer data when node is present in the db"""
        message = {
            'lablab': [1, 2],
            'lablab-b': [2, 3],
            'lablab-b-4': [3, 4],
        }
        l1, l2, l3 = self.put_with_mock_data(
            message, 'lablab', 'lablab-b', 'lablab-b-4')

        message['label'] = 'lablab'
        self.assertEqual(message, l1)

        #   Sub layers have fewer elements
        del message['lablab']
        message['label'] = 'lablab-b'
        self.assertEqual(message, l2)
        del message['lablab-b']
        message['label'] = 'lablab-b-4'
        self.assertEqual(message, l3)

    def test_add_skip_level(self):
        """Can correctly add layer data, even when skipping a node"""
        message = {
            'lablab': [1, 2],
            'lablab-b-4': [3, 4],
        }
        l1, l2, l3 = self.put_with_mock_data(
            message, 'lablab', 'lablab-b', 'lablab-b-4')

        message['label'] = 'lablab'
        self.assertEqual(message, l1)
        #   Sub layers have fewer elements
        del message['lablab']
        message['label'] = 'lablab-b'
        self.assertEqual(message, l2)
        message['label'] = 'lablab-b-4'
        self.assertEqual(message, l3)

    def test_add_interp_children(self):
        """Can correctly add layer data to interpretations"""
        message = {'99-5-Interp': [1, 2], '99-5-a-Interp': [3, 4]}
        layers_saved = self.put_with_mock_data(
            message, '99', '99-Interp', '99-5-Interp', '99-5-a-Interp',
            label='99')
        self.assertEqual(4, len(layers_saved))
        for saved in layers_saved:
            self.assertTrue('99-5-Interp' in saved)
            self.assertTrue('99-5-a-Interp' in saved)

    def test_add_subpart_children(self):
        """Can correctly add layer data to subparts"""
        message = {'99-1': [1, 2], '99-1-a': [3, 4]}
        l1, l2, l3, l4 = self.put_with_mock_data(
            message, '99', '99-Subpart-A', '99-1', '99-1-a', label='99')
        for saved in (l1, l2, l3):
            self.assertTrue('99-1' in saved)

        for saved in (l1, l2, l3, l4):
            self.assertTrue('99-1-a' in saved)

    def test_add_referenced(self):
        """The 'referenced' key is special; it should get added"""
        message = {'99-1': [1, 2], '99-1-a': [3, 4], 'referenced': [5, 6]}
        layers_saved = self.put_with_mock_data(
            message, '99', '99-Subpart-A', '99-1', '99-1-a', label='99')
        self.assertEqual(4, len(layers_saved))
        self.assertTrue(all('referenced' in saved for saved in layers_saved))

    @patch('regcore_write.views.layer.db')
    def test_child_layers_no_results(self, db):
        """If the db returns no regulation data, nothing should get saved"""
        db.Regulations.return_value.get.return_value = None
        self.assertEqual([], layer.child_layers('layname', 'lll', 'vvv', {}))
        self.assertTrue(db.Regulations.return_value.get.called)
        lab, ver = db.Regulations.return_value.get.call_args[0]
        self.assertEqual('lll', lab)
        self.assertEqual('vvv', ver)

    def test_child_label_of(self):
        """Correctly determine relationships between labels"""
        self.assertTrue(layer.child_label_of('1005-5-a-1-Interp-1',
                        '1005-5-Interp'))
<commit_msg>Didn't copy this test correctly<commit_after>import json

from django.test import TestCase
from mock import patch

from regcore_write.views import layer

class ViewsLayerTest(TestCase):
    def put(self, data, name='layname', label='lablab', version='verver'):
        """Shorthand function for PUTing data to a view layer"""
        url = '/layer/{}/{}/{}'.format(name, label, version)
        if isinstance(data, dict):
            data = json.dumps(data)
        return self.client.put(url, content_type='application/json',
                               data=data)

    def test_add_not_json(self):
        """Non-JSON is invalid"""
        response = self.put('{Invalid}')
        self.assertEqual(400, response.status_code)

    def test_add_label_mismatch(self):
        """Root label must match that found in the url"""
        response = self.put({'nonlab': []}, label='lablab')
        self.assertEqual(400, response.status_code)

    def put_with_mock_data(self, message, *labels, **kwargs):
        """Helper function to mock out the value returned from fetching the
        regulation from the database, then put the provided message, and
        return the response."""
        root = []
        children = root
        for label in labels:
            node = {'label': label.split('-'), 'children': []}
            children.append(node)
            children = node['children']

        with patch('regcore_write.views.layer.db') as db:
            db.Regulations.return_value.get.return_value = root[0]
            self.put(message, **kwargs)
            self.assertTrue(db.Layers.return_value.bulk_put.called)
            layers_saved = db.Layers.return_value.bulk_put.call_args[0][0]
            return list(reversed(layers_saved))     # switch to outside in

    def test_add_success(self):
        """Can correctly add layer data when node is present in the db"""
        message = {
            'lablab': [1, 2],
            'lablab-b': [2, 3],
            'lablab-b-4': [3, 4],
        }
        l1, l2, l3 = self.put_with_mock_data(
            message, 'lablab', 'lablab-b', 'lablab-b-4')

        message['label'] = 'lablab'
        self.assertEqual(message, l1)

        #   Sub layers have fewer elements
        del message['lablab']
        message['label'] = 'lablab-b'
        self.assertEqual(message, l2)
        del message['lablab-b']
        message['label'] = 'lablab-b-4'
        self.assertEqual(message, l3)

    def test_add_skip_level(self):
        """Can correctly add layer data, even when skipping a node"""
        message = {
            'lablab': [1, 2],
            'lablab-b-4': [3, 4],
        }
        l1, l2, l3 = self.put_with_mock_data(
            message, 'lablab', 'lablab-b', 'lablab-b-4')

        message['label'] = 'lablab'
        self.assertEqual(message, l1)
        #   Sub layers have fewer elements
        del message['lablab']
        message['label'] = 'lablab-b'
        self.assertEqual(message, l2)
        message['label'] = 'lablab-b-4'
        self.assertEqual(message, l3)

    def test_add_interp_children(self):
        """Can correctly add layer data to interpretations"""
        message = {'99-5-Interp': [1, 2], '99-5-a-Interp': [3, 4]}
        l1, l2, l3, l4 = self.put_with_mock_data(
            message, '99', '99-Interp', '99-5-Interp', '99-5-a-Interp',
            label='99')
        for saved in (l1, l2, l3):
            self.assertTrue('99-5-Interp' in saved)
            self.assertTrue('99-5-a-Interp' in saved)
        self.assertFalse('99-5-Interp' in l4)
        self.assertTrue('99-5-a-Interp' in l4)

    def test_add_subpart_children(self):
        """Can correctly add layer data to subparts"""
        message = {'99-1': [1, 2], '99-1-a': [3, 4]}
        l1, l2, l3, l4 = self.put_with_mock_data(
            message, '99', '99-Subpart-A', '99-1', '99-1-a', label='99')
        for saved in (l1, l2, l3):
            self.assertTrue('99-1' in saved)
            self.assertTrue('99-1-a' in saved)
        self.assertFalse('99-1' in l4)
        self.assertTrue('99-1-a' in l4)

    def test_add_referenced(self):
        """The 'referenced' key is special; it should get added"""
        message = {'99-1': [1, 2], '99-1-a': [3, 4], 'referenced': [5, 6]}
        layers_saved = self.put_with_mock_data(
            message, '99', '99-Subpart-A', '99-1', '99-1-a', label='99')
        self.assertEqual(4, len(layers_saved))
        self.assertTrue(all('referenced' in saved for saved in layers_saved))

    @patch('regcore_write.views.layer.db')
    def test_child_layers_no_results(self, db):
        """If the db returns no regulation data, nothing should get saved"""
        db.Regulations.return_value.get.return_value = None
        self.assertEqual([], layer.child_layers('layname', 'lll', 'vvv', {}))
        self.assertTrue(db.Regulations.return_value.get.called)
        lab, ver = db.Regulations.return_value.get.call_args[0]
        self.assertEqual('lll', lab)
        self.assertEqual('vvv', ver)

    def test_child_label_of(self):
        """Correctly determine relationships between labels"""
        self.assertTrue(layer.child_label_of('1005-5-a-1-Interp-1',
                        '1005-5-Interp'))
<|endoftext|>


<commit_before>import bpy
from ..icons.icons import load_icons
from bpy.props import StringProperty, BoolProperty, EnumProperty
from .. import rman_cycles_convert
from ..rman_utils import shadergraph_utils
from .. import rman_bl_nodes

class SHADING_OT_convert_all_renderman_nodetree(bpy.types.Operator):

    ''''''
    bl_idname = "shading.convert_cycles_stuff"
    bl_label = "Convert All Cycles to RenderMan"
    bl_description = "Convert all nodetrees to RenderMan"

    def execute(self, context):
        for mat in bpy.data.materials:
            mat.use_nodes = True
            nt = mat.node_tree
            if shadergraph_utils.is_renderman_nodetree(mat):
                continue
            output = nt.nodes.new('RendermanOutputNode')
            try:
                if not rman_cycles_convert.convert_cycles_nodetree(mat, output):
                    default = nt.nodes.new('PxrSurfaceBxdfNode')
                    default.location = output.location
                    default.location[0] -= 300
                    nt.links.new(default.outputs[0], output.inputs[0])
            except Exception as e:
                self.report({'ERROR'}, "Error converting " + mat.name)
                #self.report({'ERROR'}, str(e))
                # uncomment to debug conversion
                import traceback
                traceback.print_exc()

        for light in bpy.data.lights:
            if light.renderman.use_renderman_node:
                continue
            light.use_nodes = True
            light_type = light.type
            light.renderman.light_primary_visibility = False
            nt = light.node_tree

            light_shader = ''
            if light_type == 'SUN':
                light_shader = 'PxrDistantLight'
            elif light_type == 'HEMI':
                light_shader = 'PxrDomeLight'
            elif light_type == 'AREA':
                if light.shape == 'DISK':
                    light_shader = 'PxrDiskLight'
                elif light.shape == 'ELLIPSE':
                    light_shader = 'PxrSphereLight'
                else:
                    light_shader = 'PxrRectLight'
            elif light_type == 'SPOT':
                light_shader = 'PxrDiskLight'
            elif light_type == 'POINT':
                light_shader = 'PxrSphereLight'
            else:
                light_shader = 'PxrRectLight'

            light.type = 'AREA'
            light.renderman.use_renderman_node = True

            output = nt.nodes.new('RendermanOutputNode')
            default = nt.nodes.new('%sLightNode' % light_shader)

            default.location = output.location
            default.location[0] -= 300
            nt.links.new(default.outputs[0], output.inputs[1])

            output.inputs[0].hide = True
            output.inputs[2].hide = True
            output.inputs[3].hide = True
            light.renderman.renderman_light_role = 'RMAN_LIGHT'

            if light_type == 'SPOT':
                node = context.light.renderman.get_light_node()
                node.coneAngle = math.degrees(light.spot_size)
                node.coneSoftness = light.spot_blend

        # convert cycles vis settings
        for ob in context.scene.objects:
            if not ob.cycles_visibility.camera:
                ob.renderman.visibility_camera = False
            if not ob.cycles_visibility.diffuse or not ob.cycles_visibility.glossy:
                ob.renderman.visibility_trace_indirect = False
            if not ob.cycles_visibility.transmission:
                ob.renderman.visibility_trace_transmission = False
        return {'FINISHED'}

class SHADING_OT_convert_cycles_to_renderman_nodetree(bpy.types.Operator):

    ''''''
    bl_idname = "shading.convert_cycles_shader"
    bl_label = "Convert Cycles Shader"
    bl_description = "Try to convert the current Cycles Shader to RenderMan"

    idtype: StringProperty(name="ID Type", default="material")
    bxdf_name: StringProperty(name="Bxdf Name", default="PxrDisneyBsdf")

    def execute(self, context):
        idtype = self.properties.idtype
        if idtype == 'node_editor':
            idblock = context.space_data.id
            idtype = 'material'
        else:
            context_data = {'material': context.material,
                            'light': context.light, 'world': context.scene.world}
            idblock = context_data[idtype]

        idblock.use_nodes = True
        nt = idblock.node_tree

        if idtype == 'material':
            output = nt.nodes.new('RendermanOutputNode')
            if context.material.grease_pencil:
                shadergraph_utils.convert_grease_pencil_mat(context.material, nt, output)

            elif not rman_cycles_convert.convert_cycles_nodetree(idblock, output):
                default = nt.nodes.new('%sBxdfNode' %
                                       self.properties.bxdf_name)
                default.location = output.location
                default.location[0] -= 300
                nt.links.new(default.outputs[0], output.inputs[0])

                if idblock.renderman.copy_color_params:
                    default.diffuseColor = idblock.diffuse_color
                    default.diffuseGain = idblock.diffuse_intensity
                    default.enablePrimarySpecular = True
                    default.specularFaceColor = idblock.specular_color

            output.inputs[3].hide = True

        return {'FINISHED'}

class SHADING_OT_add_renderman_nodetree(bpy.types.Operator):

    ''''''
    bl_idname = "shading.add_renderman_nodetree"
    bl_label = "Add RenderMan Nodetree"
    bl_description = "Add a RenderMan shader node tree"

    idtype: StringProperty(name="ID Type", default="material")

    def get_type_items(self, context):
        icons = load_icons()
        rman_unknown_icon = icons.get("out_unknown.png")
        items = []
        i = 0
        for i,n in enumerate(rman_bl_nodes.__RMAN_BXDF_NODES__):
            rman_bxdf_icon = icons.get("out_%s.png" % n.name, None)
            if not rman_bxdf_icon:
                items.append( (n.name, n.name, '', rman_unknown_icon.icon_id, i))
            else:
                items.append( (n.name, n.name, '', rman_bxdf_icon.icon_id, i))
        return items
    bxdf_name: EnumProperty(items=get_type_items, name="Material")

    def execute(self, context):
        idtype = self.properties.idtype
        if idtype == 'node_editor':
            idblock = context.space_data.id
            idtype = 'material'
        else:
            context_data = {'material': context.material,
                            'light': context.light, 'world': context.scene.world}
            idblock = context_data[idtype]

        # nt = bpy.data.node_groups.new(idblock.name,
        #                              type='RendermanPatternGraph')
        #nt.use_fake_user = True
        idblock.use_nodes = True
        nt = idblock.node_tree

        if idtype == 'material':
            output = nt.nodes.new('RendermanOutputNode')
            if context.material.grease_pencil:
                shadergraph_utils.convert_grease_pencil_mat(context.material, nt, output)

            else:
                default = nt.nodes.new('%sBxdfNode' %
                                       self.properties.bxdf_name)
                default.location = output.location
                default.location[0] -= 300
                nt.links.new(default.outputs[0], output.inputs[0])

                '''
                if idblock.renderman.copy_color_params:
                    default.diffuseColor = idblock.diffuse_color
                    default.diffuseGain = idblock.diffuse_intensity
                    default.enablePrimarySpecular = True
                    default.specularFaceColor = idblock.specular_color
                '''

            output.inputs[3].hide = True

        elif idtype == 'light':
            light_type = idblock.type
            light = idblock

            light_shader = ''
            if light_type == 'SUN':
                light_shader = 'PxrDistantLight'
            elif light_type == 'HEMI':
                light_shader = 'PxrDomeLight'
            elif light_type == 'AREA':
                if light.shape == 'DISK':
                    light_shader = 'PxrDiskLight'
                elif light.shape == 'ELLIPSE':
                    light_shader = 'PxrSphereLight'
                else:
                    light_shader = 'PxrRectLight'
            elif light_type == 'SPOT':
                light_shader = 'PxrDiskLight'
            elif light_type == 'POINT':
                light_shader = 'PxrSphereLight'
            else:
                light_shader = 'PxrRectLight'

            light.type = 'AREA'
            light.renderman.use_renderman_node = True

            output = nt.nodes.new('RendermanOutputNode')
            default = nt.nodes.new('%sLightNode' %
                                    light_shader)
            default.location = output.location
            default.location[0] -= 300
            nt.links.new(default.outputs[0], output.inputs[1])

            output.inputs[0].hide = True
            output.inputs[2].hide = True
            output.inputs[3].hide = True

            light.renderman.renderman_light_role = 'RMAN_LIGHT'
            if light_type == 'SPOT':
                node = context.light.renderman.get_light_node()
                node.coneAngle = math.degrees(light.spot_size)
                node.coneSoftness = light.spot_blend

        elif idtype == 'world':
            # world
            idblock.renderman.use_renderman_node = True
            if shadergraph_utils.find_node(idblock, 'RendermanIntegratorsOutputNode'):
                return {'FINISHED'}
            output = nt.nodes.new('RendermanIntegratorsOutputNode')
            default = nt.nodes.new('PxrPathTracerIntegratorNode')
            default.location = output.location
            default.location[0] -= 200
            nt.links.new(default.outputs[0], output.inputs[0])

            sf_output = nt.nodes.new('RendermanSamplefiltersOutputNode')
            sf_output.location = default.location
            sf_output.location[0] -= 300

            df_output = nt.nodes.new('RendermanDisplayfiltersOutputNode')
            df_output.location = sf_output.location
            df_output.location[0] -= 300

            # create a default background display filter set to world color
            bg = nt.nodes.new('PxrBackgroundDisplayFilterDisplayfilterNode')
            bg.backgroundColor = idblock.color
            bg.location = df_output.location
            bg.location[0] -= 300
            nt.links.new(bg.outputs[0], df_output.inputs[0])

        return {'FINISHED'}

    def draw(self, context):
        layout = self.layout
        col = layout.column()
        col.label(text="Select a Material")
        col.prop(self, 'bxdf_name')

    def invoke(self, context, event):

        idtype = self.properties.idtype
        if idtype == 'node_editor':
            idblock = context.space_data.id
            idtype = 'material'
        else:
            context_data = {'material': context.material,
                            'light': context.light, 'world': context.scene.world}
            idblock = context_data[idtype]

        # nt = bpy.data.node_groups.new(idblock.name,
        #                              type='RendermanPatternGraph')
        #nt.use_fake_user = True
        idblock.use_nodes = True
        nt = idblock.node_tree

        if idtype == 'material':
            wm = context.window_manager
            return wm.invoke_props_dialog(self)
        return self.execute(context)

classes = [
    SHADING_OT_convert_all_renderman_nodetree,
    SHADING_OT_convert_cycles_to_renderman_nodetree,
    SHADING_OT_add_renderman_nodetree,
]

def register():
    for cls in classes:
        bpy.utils.register_class(cls)

def unregister():

    for cls in classes:
        bpy.utils.unregister_class(cls)        <commit_msg>Update description on the cycles convert operators to mention that this may not work.<commit_after>import bpy
from ..icons.icons import load_icons
from bpy.props import StringProperty, BoolProperty, EnumProperty
from .. import rman_cycles_convert
from ..rman_utils import shadergraph_utils
from .. import rman_bl_nodes

class SHADING_OT_convert_all_renderman_nodetree(bpy.types.Operator):

    ''''''
    bl_idname = "shading.convert_cycles_stuff"
    bl_label = "Convert All Cycles to RenderMan"
    bl_description = "Convert all Cycles nodetrees to RenderMan. This is not guaranteed to work. It is still recommended to use RenderMan only nodes."

    def execute(self, context):
        for mat in bpy.data.materials:
            mat.use_nodes = True
            nt = mat.node_tree
            if shadergraph_utils.is_renderman_nodetree(mat):
                continue
            output = nt.nodes.new('RendermanOutputNode')
            try:
                if not rman_cycles_convert.convert_cycles_nodetree(mat, output):
                    default = nt.nodes.new('PxrSurfaceBxdfNode')
                    default.location = output.location
                    default.location[0] -= 300
                    nt.links.new(default.outputs[0], output.inputs[0])
            except Exception as e:
                self.report({'ERROR'}, "Error converting " + mat.name)
                #self.report({'ERROR'}, str(e))
                # uncomment to debug conversion
                import traceback
                traceback.print_exc()

        for light in bpy.data.lights:
            if light.renderman.use_renderman_node:
                continue
            light.use_nodes = True
            light_type = light.type
            light.renderman.light_primary_visibility = False
            nt = light.node_tree

            light_shader = ''
            if light_type == 'SUN':
                light_shader = 'PxrDistantLight'
            elif light_type == 'HEMI':
                light_shader = 'PxrDomeLight'
            elif light_type == 'AREA':
                if light.shape == 'DISK':
                    light_shader = 'PxrDiskLight'
                elif light.shape == 'ELLIPSE':
                    light_shader = 'PxrSphereLight'
                else:
                    light_shader = 'PxrRectLight'
            elif light_type == 'SPOT':
                light_shader = 'PxrDiskLight'
            elif light_type == 'POINT':
                light_shader = 'PxrSphereLight'
            else:
                light_shader = 'PxrRectLight'

            light.type = 'AREA'
            light.renderman.use_renderman_node = True

            output = nt.nodes.new('RendermanOutputNode')
            default = nt.nodes.new('%sLightNode' % light_shader)

            default.location = output.location
            default.location[0] -= 300
            nt.links.new(default.outputs[0], output.inputs[1])

            output.inputs[0].hide = True
            output.inputs[2].hide = True
            output.inputs[3].hide = True
            light.renderman.renderman_light_role = 'RMAN_LIGHT'

            if light_type == 'SPOT':
                node = context.light.renderman.get_light_node()
                node.coneAngle = math.degrees(light.spot_size)
                node.coneSoftness = light.spot_blend

        # convert cycles vis settings
        for ob in context.scene.objects:
            if not ob.cycles_visibility.camera:
                ob.renderman.visibility_camera = False
            if not ob.cycles_visibility.diffuse or not ob.cycles_visibility.glossy:
                ob.renderman.visibility_trace_indirect = False
            if not ob.cycles_visibility.transmission:
                ob.renderman.visibility_trace_transmission = False
        return {'FINISHED'}

class SHADING_OT_convert_cycles_to_renderman_nodetree(bpy.types.Operator):

    ''''''
    bl_idname = "shading.convert_cycles_shader"
    bl_label = "Convert Cycles Shader"
    bl_description = "Try to convert the current Cycles Shader to RenderMan. This is not guaranteed to work. It is still recommended to use RenderMan only nodes."

    idtype: StringProperty(name="ID Type", default="material")
    bxdf_name: StringProperty(name="Bxdf Name", default="PxrDisneyBsdf")

    def execute(self, context):
        idtype = self.properties.idtype
        if idtype == 'node_editor':
            idblock = context.space_data.id
            idtype = 'material'
        else:
            context_data = {'material': context.material,
                            'light': context.light, 'world': context.scene.world}
            idblock = context_data[idtype]

        idblock.use_nodes = True
        nt = idblock.node_tree

        if idtype == 'material':
            output = nt.nodes.new('RendermanOutputNode')
            if context.material.grease_pencil:
                shadergraph_utils.convert_grease_pencil_mat(context.material, nt, output)

            elif not rman_cycles_convert.convert_cycles_nodetree(idblock, output):
                default = nt.nodes.new('%sBxdfNode' %
                                       self.properties.bxdf_name)
                default.location = output.location
                default.location[0] -= 300
                nt.links.new(default.outputs[0], output.inputs[0])

                if idblock.renderman.copy_color_params:
                    default.diffuseColor = idblock.diffuse_color
                    default.diffuseGain = idblock.diffuse_intensity
                    default.enablePrimarySpecular = True
                    default.specularFaceColor = idblock.specular_color

            output.inputs[3].hide = True

        return {'FINISHED'}

class SHADING_OT_add_renderman_nodetree(bpy.types.Operator):

    ''''''
    bl_idname = "shading.add_renderman_nodetree"
    bl_label = "Add RenderMan Nodetree"
    bl_description = "Add a RenderMan shader node tree"

    idtype: StringProperty(name="ID Type", default="material")

    def get_type_items(self, context):
        icons = load_icons()
        rman_unknown_icon = icons.get("out_unknown.png")
        items = []
        i = 0
        for i,n in enumerate(rman_bl_nodes.__RMAN_BXDF_NODES__):
            rman_bxdf_icon = icons.get("out_%s.png" % n.name, None)
            if not rman_bxdf_icon:
                items.append( (n.name, n.name, '', rman_unknown_icon.icon_id, i))
            else:
                items.append( (n.name, n.name, '', rman_bxdf_icon.icon_id, i))
        return items
    bxdf_name: EnumProperty(items=get_type_items, name="Material")

    def execute(self, context):
        idtype = self.properties.idtype
        if idtype == 'node_editor':
            idblock = context.space_data.id
            idtype = 'material'
        else:
            context_data = {'material': context.material,
                            'light': context.light, 'world': context.scene.world}
            idblock = context_data[idtype]

        # nt = bpy.data.node_groups.new(idblock.name,
        #                              type='RendermanPatternGraph')
        #nt.use_fake_user = True
        idblock.use_nodes = True
        nt = idblock.node_tree

        if idtype == 'material':
            output = nt.nodes.new('RendermanOutputNode')
            if context.material.grease_pencil:
                shadergraph_utils.convert_grease_pencil_mat(context.material, nt, output)

            else:
                default = nt.nodes.new('%sBxdfNode' %
                                       self.properties.bxdf_name)
                default.location = output.location
                default.location[0] -= 300
                nt.links.new(default.outputs[0], output.inputs[0])

                '''
                if idblock.renderman.copy_color_params:
                    default.diffuseColor = idblock.diffuse_color
                    default.diffuseGain = idblock.diffuse_intensity
                    default.enablePrimarySpecular = True
                    default.specularFaceColor = idblock.specular_color
                '''

            output.inputs[3].hide = True

        elif idtype == 'light':
            light_type = idblock.type
            light = idblock

            light_shader = ''
            if light_type == 'SUN':
                light_shader = 'PxrDistantLight'
            elif light_type == 'HEMI':
                light_shader = 'PxrDomeLight'
            elif light_type == 'AREA':
                if light.shape == 'DISK':
                    light_shader = 'PxrDiskLight'
                elif light.shape == 'ELLIPSE':
                    light_shader = 'PxrSphereLight'
                else:
                    light_shader = 'PxrRectLight'
            elif light_type == 'SPOT':
                light_shader = 'PxrDiskLight'
            elif light_type == 'POINT':
                light_shader = 'PxrSphereLight'
            else:
                light_shader = 'PxrRectLight'

            light.type = 'AREA'
            light.renderman.use_renderman_node = True

            output = nt.nodes.new('RendermanOutputNode')
            default = nt.nodes.new('%sLightNode' %
                                    light_shader)
            default.location = output.location
            default.location[0] -= 300
            nt.links.new(default.outputs[0], output.inputs[1])

            output.inputs[0].hide = True
            output.inputs[2].hide = True
            output.inputs[3].hide = True

            light.renderman.renderman_light_role = 'RMAN_LIGHT'
            if light_type == 'SPOT':
                node = context.light.renderman.get_light_node()
                node.coneAngle = math.degrees(light.spot_size)
                node.coneSoftness = light.spot_blend

        elif idtype == 'world':
            # world
            idblock.renderman.use_renderman_node = True
            if shadergraph_utils.find_node(idblock, 'RendermanIntegratorsOutputNode'):
                return {'FINISHED'}
            output = nt.nodes.new('RendermanIntegratorsOutputNode')
            default = nt.nodes.new('PxrPathTracerIntegratorNode')
            default.location = output.location
            default.location[0] -= 200
            nt.links.new(default.outputs[0], output.inputs[0])

            sf_output = nt.nodes.new('RendermanSamplefiltersOutputNode')
            sf_output.location = default.location
            sf_output.location[0] -= 300

            df_output = nt.nodes.new('RendermanDisplayfiltersOutputNode')
            df_output.location = sf_output.location
            df_output.location[0] -= 300

            # create a default background display filter set to world color
            bg = nt.nodes.new('PxrBackgroundDisplayFilterDisplayfilterNode')
            bg.backgroundColor = idblock.color
            bg.location = df_output.location
            bg.location[0] -= 300
            nt.links.new(bg.outputs[0], df_output.inputs[0])

        return {'FINISHED'}

    def draw(self, context):
        layout = self.layout
        col = layout.column()
        col.label(text="Select a Material")
        col.prop(self, 'bxdf_name')

    def invoke(self, context, event):

        idtype = self.properties.idtype
        if idtype == 'node_editor':
            idblock = context.space_data.id
            idtype = 'material'
        else:
            context_data = {'material': context.material,
                            'light': context.light, 'world': context.scene.world}
            idblock = context_data[idtype]

        # nt = bpy.data.node_groups.new(idblock.name,
        #                              type='RendermanPatternGraph')
        #nt.use_fake_user = True
        idblock.use_nodes = True
        nt = idblock.node_tree

        if idtype == 'material':
            wm = context.window_manager
            return wm.invoke_props_dialog(self)
        return self.execute(context)

classes = [
    SHADING_OT_convert_all_renderman_nodetree,
    SHADING_OT_convert_cycles_to_renderman_nodetree,
    SHADING_OT_add_renderman_nodetree,
]

def register():
    for cls in classes:
        bpy.utils.register_class(cls)

def unregister():

    for cls in classes:
        bpy.utils.unregister_class(cls)        <|endoftext|>


<commit_before>"""Builder for websites."""
import os
import shutil
import datetime as dt

from regolith.builders.basebuilder import BuilderBase
from regolith.fsclient import _id_key
from regolith.sorters import doc_date_key, position_key, ene_date_key
from regolith.tools import (
    all_docs_from_collection,
    filter_publications,
    filter_projects,
    make_bibtex_file,
    document_by_value,
    dereference_institution,
    fuzzy_retrieval
)

PROJ_URL_BASE = 'https://gitlab.thebillingegroup.com/talks/'

class InternalHtmlBuilder(BuilderBase):
    """Build HTML files for website"""

    btype = "internalhtml"
    needed_dbs = ["people", "meetings"]

    def __init__(self, rc):
        super().__init__(rc)
        # TODO: get this from the RC
        self.cmds = [
            "root_index",
            "meetings",
            "nojekyll",
            "cname",
        ]

    def construct_global_ctx(self):
        """Constructs the global context"""
        super().construct_global_ctx()
        gtx = self.gtx
        rc = self.rc
        gtx["jobs"] = list(all_docs_from_collection(rc.client, "jobs"))
        gtx["people"] = sorted(
            all_docs_from_collection(rc.client, "people"),
            key=position_key,
            reverse=True,
        )
        gtx["meetings"] = list(
            all_docs_from_collection(rc.client, "meetings")
        )
        gtx["group"] = document_by_value(
            all_docs_from_collection(rc.client, "groups"), "name", rc.groupname
        )
        gtx["all_docs_from_collection"] = all_docs_from_collection
        gtx["institutions"] = sorted(
            all_docs_from_collection(rc.client, "institutions"), key=_id_key
        )

    def finish(self):
        """Move files over to their destination and remove them from the
        source"""
        # static
        stsrc = os.path.join(
            getattr(self.rc, "static_source", "templates"), "static"
        )
        stdst = os.path.join(self.bldir, "static")
        if os.path.isdir(stdst):
            shutil.rmtree(stdst)
        shutil.copytree(stsrc, stdst)

    def root_index(self):
        """Render root index"""
        self.render("introot_index.html", "intindex.html", title="Home")

    def meetings(self):
        """Render projects"""
        rc = self.rc
        mtgsi = all_docs_from_collection(rc.client, "meetings")
        peeps = all_docs_from_collection(rc.client, "people")
        pp_mtgs, f_mtgs = [], []

        for mtg in mtgsi:
            if not mtg.get('lead'):
                print("{} missing a meeting lead".format(mtg["_id"]))
            if not mtg.get('scribe'):
                print("{} missing a meeting scribe".format(mtg["_id"]))
            lead = fuzzy_retrieval(
                all_docs_from_collection(rc.client, "people"),
                ["_id", "name", "aka"],
                mtg.get("lead"))
            if not lead:
                print("{} lead {} not found in people".format(mtg["_id"],mtg.get("lead")))
            mtg["lead"] = lead["name"]
            scribe = fuzzy_retrieval(
                all_docs_from_collection(rc.client, "people"),
                ["_id", "name", "aka"],
                mtg.get("scribe"))
            if not scribe:
                print("{} scribe {} not found in people".format(mtg["_id"],mtg.get("scribe")))
            mtg["scribe"] = scribe["name"]
            if mtg.get("journal_club"):
                prsn = fuzzy_retrieval(
                    all_docs_from_collection(rc.client, "people"),
                    ["_id", "name", "aka"],
                    mtg["journal_club"].get("presenter"))
                if not prsn:
                    print(
                    "{} presenter {} not found in people".format(mtg["_id"],mtg["presentation"].get("presenter")))
                mtg["journal_club"]["presenter"] = prsn["name"]
            if mtg.get("presentation"):
                prsn = fuzzy_retrieval(
                    all_docs_from_collection(rc.client, "people"),
                    ["_id", "name", "aka"],
                    mtg["presentation"].get("presenter"))
                if mtg["presentation"].get("presenter") == "hold":
                    prsn = {}
                    prsn["name"] = "Hold"
                if not prsn:
                    print(
                    "{} presenter {} not found in people".format(mtg["_id"],mtg["presentation"].get("presenter")))
                mtg["presentation"]["presenter"] = prsn["name"]
                mtg["presentation"]["link"] = PROJ_URL_BASE + \
                                              mtg["presentation"].get("link","tbd")
            mtg['date'] = dt.date(mtg.get("year"), mtg.get("month"),
                                  mtg.get("day"))
            mtg['datestr'] = mtg['date'].strftime('%m/%d/%Y')
            today = dt.date.today()
            if mtg['date'] >= today:
                f_mtgs.append(mtg)
            else:
                pp_mtgs.append(mtg)

        pp_mtgs = sorted(pp_mtgs, key=lambda x: x.get('date'), reverse=True)
        f_mtgs = sorted(f_mtgs, key=lambda x: x.get('date'))
        self.render(
            "grpmeetings.html", "grpmeetings.html", title="Group Meetings",
            ppmeetings=pp_mtgs, fmeetings=f_mtgs
        )

    def nojekyll(self):
        """Touches a nojekyll file in the build dir"""
        with open(os.path.join(self.bldir, ".nojekyll"), "a+"):
            pass

    def cname(self):
        """Add CNAME"""
        rc = self.rc
        if not hasattr(rc, "cname"):
            return
        with open(
                os.path.join(self.bldir, "CNAME"), "w", encoding="utf-8"
        ) as f:
            f.write(rc.cname)

    def people(self):
        """Render people, former members, and each person"""
        rc = self.rc
        peeps_dir = os.path.join(self.bldir, "people")
        former_peeps_dir = os.path.join(self.bldir, "former")
        os.makedirs(peeps_dir, exist_ok=True)
        os.makedirs(former_peeps_dir, exist_ok=True)
        peeps = self.gtx["people"]
        for p in peeps:
            names = frozenset(p.get("aka", []) + [p["name"]])
            pubs = filter_publications(
                all_docs_from_collection(rc.client, "citations"),
                names,
                reverse=True,
                bold=False,
            )

            bibfile = make_bibtex_file(
                pubs, pid=p["_id"], person_dir=peeps_dir
            )
            ene = p.get("employment", []) + p.get("education", [])
            ene.sort(key=ene_date_key, reverse=True)
            for e in ene:
                dereference_institution(e, self.gtx["institutions"])
            projs = filter_projects(
                all_docs_from_collection(rc.client, "projects"), names
            )
            self.render(
                "person.html",
                os.path.join("people", p["_id"] + ".html"),
                p=p,
                title=p.get("name", ""),
                pubs=pubs,
                names=names,
                bibfile=bibfile,
                education_and_employment=ene,
                projects=projs,
            )
        self.render(
            "people.html", os.path.join("people", "index.html"), title="People"
        )

        self.render(
            "former.html",
            os.path.join("former", "index.html"),
            title="Former Members",
        )

    def projects(self):
        """Render projects"""
        rc = self.rc
        projs = all_docs_from_collection(rc.client, "projects")
        self.render(
            "projects.html", "projects.html", title="Projects", projects=projs
        )

    def blog(self):
        """Render the blog and rss"""
        rc = self.rc
        blog_dir = os.path.join(self.bldir, "blog")
        os.makedirs(blog_dir, exist_ok=True)
        posts = list(all_docs_from_collection(rc.client, "blog"))
        posts.sort(key=ene_date_key, reverse=True)
        for post in posts:
            self.render(
                "blog_post.html",
                os.path.join("blog", post["_id"] + ".html"),
                post=post,
                title=post["title"],
            )
        self.render(
            "blog_index.html",
            os.path.join("blog", "index.html"),
            title="Blog",
            posts=posts,
        )
        self.render("rss.xml", os.path.join("blog", "rss.xml"), items=posts)

    def jobs(self):
        """Render the jobs and each job"""
        jobs_dir = os.path.join(self.bldir, "jobs")
        os.makedirs(jobs_dir, exist_ok=True)
        for job in self.gtx["jobs"]:
            self.render(
                "job.html",
                os.path.join("jobs", job["_id"] + ".html"),
                job=job,
                title="{0} ({1})".format(job["title"], job["_id"]),
            )
        self.render(
            "jobs.html", os.path.join("jobs", "index.html"), title="Jobs"
        )

    def abstracts(self):
        """Render each abstract"""
        abs_dir = os.path.join(self.bldir, "abstracts")
        os.makedirs(abs_dir, exist_ok=True)
        for ab in self.gtx["abstracts"]:
            self.render(
                "abstract.html",
                os.path.join("abstracts", ab["_id"] + ".html"),
                abstract=ab,
                title="{0} {1} - {2}".format(
                    ab["firstname"], ab["lastname"], ab["title"]
                ),
            )
<commit_msg>fix bug in error message for missing Jclub presenter<commit_after>"""Builder for websites."""
import os
import shutil
import datetime as dt

from regolith.builders.basebuilder import BuilderBase
from regolith.fsclient import _id_key
from regolith.sorters import doc_date_key, position_key, ene_date_key
from regolith.tools import (
    all_docs_from_collection,
    filter_publications,
    filter_projects,
    make_bibtex_file,
    document_by_value,
    dereference_institution,
    fuzzy_retrieval
)

PROJ_URL_BASE = 'https://gitlab.thebillingegroup.com/talks/'

class InternalHtmlBuilder(BuilderBase):
    """Build HTML files for website"""

    btype = "internalhtml"
    needed_dbs = ["people", "meetings"]

    def __init__(self, rc):
        super().__init__(rc)
        # TODO: get this from the RC
        self.cmds = [
            "root_index",
            "meetings",
            "nojekyll",
            "cname",
        ]

    def construct_global_ctx(self):
        """Constructs the global context"""
        super().construct_global_ctx()
        gtx = self.gtx
        rc = self.rc
        gtx["jobs"] = list(all_docs_from_collection(rc.client, "jobs"))
        gtx["people"] = sorted(
            all_docs_from_collection(rc.client, "people"),
            key=position_key,
            reverse=True,
        )
        gtx["meetings"] = list(
            all_docs_from_collection(rc.client, "meetings")
        )
        gtx["group"] = document_by_value(
            all_docs_from_collection(rc.client, "groups"), "name", rc.groupname
        )
        gtx["all_docs_from_collection"] = all_docs_from_collection
        gtx["institutions"] = sorted(
            all_docs_from_collection(rc.client, "institutions"), key=_id_key
        )

    def finish(self):
        """Move files over to their destination and remove them from the
        source"""
        # static
        stsrc = os.path.join(
            getattr(self.rc, "static_source", "templates"), "static"
        )
        stdst = os.path.join(self.bldir, "static")
        if os.path.isdir(stdst):
            shutil.rmtree(stdst)
        shutil.copytree(stsrc, stdst)

    def root_index(self):
        """Render root index"""
        self.render("introot_index.html", "intindex.html", title="Home")

    def meetings(self):
        """Render projects"""
        rc = self.rc
        mtgsi = all_docs_from_collection(rc.client, "meetings")
        peeps = all_docs_from_collection(rc.client, "people")
        pp_mtgs, f_mtgs = [], []

        for mtg in mtgsi:
            if not mtg.get('lead'):
                print("{} missing a meeting lead".format(mtg["_id"]))
            if not mtg.get('scribe'):
                print("{} missing a meeting scribe".format(mtg["_id"]))
            lead = fuzzy_retrieval(
                all_docs_from_collection(rc.client, "people"),
                ["_id", "name", "aka"],
                mtg.get("lead"))
            if not lead:
                print("{} lead {} not found in people".format(mtg["_id"],mtg.get("lead")))
            mtg["lead"] = lead["name"]
            scribe = fuzzy_retrieval(
                all_docs_from_collection(rc.client, "people"),
                ["_id", "name", "aka"],
                mtg.get("scribe"))
            if not scribe:
                print("{} scribe {} not found in people".format(mtg["_id"],mtg.get("scribe")))
            mtg["scribe"] = scribe["name"]
            if mtg.get("journal_club"):
                prsn = fuzzy_retrieval(
                    all_docs_from_collection(rc.client, "people"),
                    ["_id", "name", "aka"],
                    mtg["journal_club"].get("presenter"))
                if not prsn:
                    print(
                    "{} Jclub presenter {} not found in people".format(mtg["_id"],mtg["journal_club"].get("presenter")))
                mtg["journal_club"]["presenter"] = prsn["name"]
            if mtg.get("presentation"):
                prsn = fuzzy_retrieval(
                    all_docs_from_collection(rc.client, "people"),
                    ["_id", "name", "aka"],
                    mtg["presentation"].get("presenter"))
                if mtg["presentation"].get("presenter") == "hold":
                    prsn = {}
                    prsn["name"] = "Hold"
                if not prsn:
                    print(
                    "{} presenter {} not found in people".format(mtg["_id"],mtg["presentation"].get("presenter")))
                mtg["presentation"]["presenter"] = prsn["name"]
                mtg["presentation"]["link"] = PROJ_URL_BASE + \
                                              mtg["presentation"].get("link","tbd")
            mtg['date'] = dt.date(mtg.get("year"), mtg.get("month"),
                                  mtg.get("day"))
            mtg['datestr'] = mtg['date'].strftime('%m/%d/%Y')
            today = dt.date.today()
            if mtg['date'] >= today:
                f_mtgs.append(mtg)
            else:
                pp_mtgs.append(mtg)

        pp_mtgs = sorted(pp_mtgs, key=lambda x: x.get('date'), reverse=True)
        f_mtgs = sorted(f_mtgs, key=lambda x: x.get('date'))
        self.render(
            "grpmeetings.html", "grpmeetings.html", title="Group Meetings",
            ppmeetings=pp_mtgs, fmeetings=f_mtgs
        )

    def nojekyll(self):
        """Touches a nojekyll file in the build dir"""
        with open(os.path.join(self.bldir, ".nojekyll"), "a+"):
            pass

    def cname(self):
        """Add CNAME"""
        rc = self.rc
        if not hasattr(rc, "cname"):
            return
        with open(
                os.path.join(self.bldir, "CNAME"), "w", encoding="utf-8"
        ) as f:
            f.write(rc.cname)

    def people(self):
        """Render people, former members, and each person"""
        rc = self.rc
        peeps_dir = os.path.join(self.bldir, "people")
        former_peeps_dir = os.path.join(self.bldir, "former")
        os.makedirs(peeps_dir, exist_ok=True)
        os.makedirs(former_peeps_dir, exist_ok=True)
        peeps = self.gtx["people"]
        for p in peeps:
            names = frozenset(p.get("aka", []) + [p["name"]])
            pubs = filter_publications(
                all_docs_from_collection(rc.client, "citations"),
                names,
                reverse=True,
                bold=False,
            )

            bibfile = make_bibtex_file(
                pubs, pid=p["_id"], person_dir=peeps_dir
            )
            ene = p.get("employment", []) + p.get("education", [])
            ene.sort(key=ene_date_key, reverse=True)
            for e in ene:
                dereference_institution(e, self.gtx["institutions"])
            projs = filter_projects(
                all_docs_from_collection(rc.client, "projects"), names
            )
            self.render(
                "person.html",
                os.path.join("people", p["_id"] + ".html"),
                p=p,
                title=p.get("name", ""),
                pubs=pubs,
                names=names,
                bibfile=bibfile,
                education_and_employment=ene,
                projects=projs,
            )
        self.render(
            "people.html", os.path.join("people", "index.html"), title="People"
        )

        self.render(
            "former.html",
            os.path.join("former", "index.html"),
            title="Former Members",
        )

    def projects(self):
        """Render projects"""
        rc = self.rc
        projs = all_docs_from_collection(rc.client, "projects")
        self.render(
            "projects.html", "projects.html", title="Projects", projects=projs
        )

    def blog(self):
        """Render the blog and rss"""
        rc = self.rc
        blog_dir = os.path.join(self.bldir, "blog")
        os.makedirs(blog_dir, exist_ok=True)
        posts = list(all_docs_from_collection(rc.client, "blog"))
        posts.sort(key=ene_date_key, reverse=True)
        for post in posts:
            self.render(
                "blog_post.html",
                os.path.join("blog", post["_id"] + ".html"),
                post=post,
                title=post["title"],
            )
        self.render(
            "blog_index.html",
            os.path.join("blog", "index.html"),
            title="Blog",
            posts=posts,
        )
        self.render("rss.xml", os.path.join("blog", "rss.xml"), items=posts)

    def jobs(self):
        """Render the jobs and each job"""
        jobs_dir = os.path.join(self.bldir, "jobs")
        os.makedirs(jobs_dir, exist_ok=True)
        for job in self.gtx["jobs"]:
            self.render(
                "job.html",
                os.path.join("jobs", job["_id"] + ".html"),
                job=job,
                title="{0} ({1})".format(job["title"], job["_id"]),
            )
        self.render(
            "jobs.html", os.path.join("jobs", "index.html"), title="Jobs"
        )

    def abstracts(self):
        """Render each abstract"""
        abs_dir = os.path.join(self.bldir, "abstracts")
        os.makedirs(abs_dir, exist_ok=True)
        for ab in self.gtx["abstracts"]:
            self.render(
                "abstract.html",
                os.path.join("abstracts", ab["_id"] + ".html"),
                abstract=ab,
                title="{0} {1} - {2}".format(
                    ab["firstname"], ab["lastname"], ab["title"]
                ),
            )
<|endoftext|>


<commit_before>"""
:copyright: (c) 2010 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""

from django.conf.urls.defaults import *

def foo(request):
    from django.http import HttpResponse
    return HttpResponse()

urlpatterns = patterns('',
    url('', foo, name='gargoyle_test_foo'),
)
<commit_msg>django url import deprecation error<commit_after>"""
:copyright: (c) 2010 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""

from django.conf.urls import *

def foo(request):
    from django.http import HttpResponse
    return HttpResponse()

urlpatterns = patterns('',
    url('', foo, name='gargoyle_test_foo'),
)
<|endoftext|>


<commit_before># coding: utf-8

"""
URLpatterns for the debug toolbar.

These should not be loaded explicitly; the debug toolbar middleware will patch
this into the urlconf for the request.
"""

from __future__ import unicode_literals

from django.conf.urls import patterns, url
from django.contrib import admin

from .models import NonAsciiRepr

admin.autodiscover()

urlpatterns = patterns('tests.views',
    url(r'^set_session/$', 'set_session'),
    url(r'^resolving1/(.+)/(.+)/$', 'resolving_view', name='positional-resolving'),
    url(r'^resolving2/(?P<arg1>.+)/(?P<arg2>.+)/$', 'resolving_view'),
    url(r'^resolving3/(.+)/$', 'resolving_view', { 'arg2' : 'default' }),
    url(r'^regular/(?P<title>.*)/$', 'regular_view'),
    url(r'^non_ascii_context/$', 'non_ascii_context'),
    url(r'^non_ascii_bytes_in_db_params/$', 'new_user', {'username': 'djàngó'.encode('utf-8')}),
    url(r'^non_ascii_request/$', 'regular_view', {'title': NonAsciiRepr()}),
    url(r'^new_user/$', 'new_user'),
    url(r'^execute_sql/$', 'execute_sql'),
)
<commit_msg>Remove inappropriate docstring.<commit_after># coding: utf-8

from __future__ import unicode_literals

from django.conf.urls import patterns, url
from django.contrib import admin

from .models import NonAsciiRepr

admin.autodiscover()

urlpatterns = patterns('tests.views',
    url(r'^set_session/$', 'set_session'),
    url(r'^resolving1/(.+)/(.+)/$', 'resolving_view', name='positional-resolving'),
    url(r'^resolving2/(?P<arg1>.+)/(?P<arg2>.+)/$', 'resolving_view'),
    url(r'^resolving3/(.+)/$', 'resolving_view', { 'arg2' : 'default' }),
    url(r'^regular/(?P<title>.*)/$', 'regular_view'),
    url(r'^non_ascii_context/$', 'non_ascii_context'),
    url(r'^non_ascii_bytes_in_db_params/$', 'new_user', {'username': 'djàngó'.encode('utf-8')}),
    url(r'^non_ascii_request/$', 'regular_view', {'title': NonAsciiRepr()}),
    url(r'^new_user/$', 'new_user'),
    url(r'^execute_sql/$', 'execute_sql'),
)
<|endoftext|>