Convert a Choice to a cached instance representation.
968991
def choice_default_serializer(self, obj):
        """"""
        if not obj:
            return None
        self.choice_default_add_related_pks(obj)
        return dict((
            ('id', obj.id),
            ('choice_text', obj.choice_text),
            self.field_to_json(
                'PK', 'question', model=Question, pk=obj.question_id),
            self.field_to_json(
                'PKList', 'voters', model=User, pks=obj._voter_pks)
        ))
1118075
def _name_value_to_bson(name, value, check_keys, opts):
    """"""

    # First see if the type is already cached. KeyError will only ever
    # happen once per subtype.
    try:
        return _ENCODERS[type(value)](name, value, check_keys, opts)
    except KeyError:
        pass

    # Second, fall back to trying _type_marker. This has to be done
    # before the loop below since users could subclass one of our
    # custom types that subclasses a python built-in (e.g. Binary)
    marker = getattr(value, "_type_marker", None)
    if isinstance(marker, int) and marker in _MARKERS:
        func = _MARKERS[marker]
        # Cache this type for faster subsequent lookup.
        _ENCODERS[type(value)] = func
        return func(name, value, check_keys, opts)

    # If all else fails test each base type. This will only happen once for
    # a subtype of a supported base type.
    for base in _ENCODERS:
        if isinstance(value, base):
            func = _ENCODERS[base]
            # Cache this type for faster subsequent lookup.
            _ENCODERS[type(value)] = func
            return func(name, value, check_keys, opts)

    raise InvalidDocument("cannot convert value of type %s to bson" %
                          type(value))
789879
def memoize(f):
    """"""
    def _c(*args, **kwargs):
        if not hasattr(f, 'cache'):
            f.cache = dict()
        key = (args, tuple(kwargs))
        if key not in f.cache:
            f.cache[key] = f(*args, **kwargs)
        return f.cache[key]
    return wraps(f)(_c)
413545
def choices(cls):
        
        # "natural" order, aka as given when instantiating
        if not hasattr(cls, '__choices_'):
            cls.__choices_ = tuple([c.choice for c in list(cls)])
        return cls.__choices_
1215862
def cached(f):
    """"""
    def memoized(*args, **kwargs):
        if hasattr(memoized, '__cache__'):
            return memoized.__cache__
        result = f(*args, **kwargs)
        memoized.__cache__ = result
        return result
    return memoized
1200841
def take(self, obj):
        """"""
        cached = self._thread_local.cache[self._get_cache_key(obj)]
        build_kwargs = {}

        if 'model' in cached and 'pks' in cached:
            build_kwargs['queryset'] = cached['model'].objects.filter(pk__in=cached['pks'])

        elif 'obj' in cached:
            if cached['obj'].__class__.objects.filter(pk=cached['obj'].pk).exists():
                build_kwargs['obj'] = cached['obj']
            else:
                # Object was deleted in the meantime.
                build_kwargs['queryset'] = cached['obj'].__class__.objects.none()

        self._clean_cache(obj)

        return build_kwargs
611523
def get_instance(page_to_consume):
    """"""
    global _instances
    if isinstance(page_to_consume, basestring):
        uri = page_to_consume
        page_to_consume = page.get_instance(uri)
    elif isinstance(page_to_consume, page.Page):
        uri = page_to_consume.uri
    else:
        raise TypeError(
            "get_instance() expects a parker.Page or basestring derivative."
        )

    page_to_consume.fetch()
    parsed_page = parser.parse(page_to_consume)

    try:
        instance = _instances[uri]
    except KeyError:
        instance = ConsumePage(
            parsed_page
        )
        _instances[uri] = instance

    return instance
261002
private static NumberFormat getInstance(Locale desiredLocale,
                                           int choice) {
        // Check whether a provider can provide an implementation that's closer
        // to the requested locale than what the Java runtime itself can provide.
        /* J2ObjC: java.text.spi is not provided.
        LocaleServiceProviderPool pool =
            LocaleServiceProviderPool.getPool(NumberFormatProvider.class);
        if (pool.hasProviders()) {
            NumberFormat providersInstance = pool.getLocalizedObject(
                                    NumberFormatGetter.INSTANCE,
                                    desiredLocale,
                                    choice);
            if (providersInstance != null) {
                return providersInstance;
            }
        }*/

        /* try the cache first */
        String[] numberPatterns = (String[])cachedLocaleData.get(desiredLocale);
        if (numberPatterns == null) { /* cache miss */
            LocaleData data = LocaleData.get(desiredLocale);
            numberPatterns = new String[4];
            numberPatterns[NUMBERSTYLE] = data.numberPattern;
            numberPatterns[CURRENCYSTYLE] = data.currencyPattern;
            numberPatterns[PERCENTSTYLE] = data.percentPattern;
            numberPatterns[INTEGERSTYLE] = data.integerPattern;
            /* update cache */
            cachedLocaleData.put(desiredLocale, numberPatterns);
        }

        DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(desiredLocale);
        int entry = (choice == INTEGERSTYLE) ? NUMBERSTYLE : choice;
        DecimalFormat format = new DecimalFormat(numberPatterns[entry], symbols);

        if (choice == INTEGERSTYLE) {
            format.setMaximumFractionDigits(0);
            format.setDecimalSeparatorAlwaysShown(false);
            format.setParseIntegerOnly(true);
        } else if (choice == CURRENCYSTYLE) {
            adjustForCurrencyDefaultFractionDigits(format, symbols);
        }

        return format;
    }
281836
def choice(choices):
    """"""
    def decorator(function):
        """Decorate a function with args."""
        @functools.wraps(function)
        def wrapper(*args, **kwargs):
            """Wrap the function."""
            series = function(*args, **kwargs)
            return series.isin(set(choices))

        return wrapper

    return decorator
723233
def _to_instances(self, pks):
        
        # we want instances, so create an object for each pk, without
        # checking for pk existence if asked
        meth = self.cls.lazy_connect if self._instances_skip_exist_test else self.cls
        return [meth(pk) for pk in pks]
803079
def rr_cache(maxsize=128, choice=random.choice, typed=False):
    
    if maxsize is None:
        return _cache(_UnboundCache(), typed)
    else:
        return _cache(RRCache(maxsize, choice), typed)
746297
def compute_default_choice(self):
        """"""

        choices = self.choices

        if len(choices) == 0:
            return None

        high_choice = max(choices, key=lambda choice: choice.performance)
        self.redis.hset(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "default-choice", high_choice.name)
        self.refresh()
        return high_choice
919025
def get(cls, id=None, condition=None, fields=None, cache=False, engine_name=None, **kwargs):
        
        
        if id is None and condition is None:
            return None
        
        can_cacheable = (cache or getattr(cls, '__cacheable__', None)) and \
            isinstance(id, (int, long, str, unicode))
        if can_cacheable:
            #send 'get_object' topic to get cached object
            obj = dispatch.get(cls, 'get_object', id)
            if obj:
                return obj

        if condition is not None:
            _cond = condition
        else:
            if is_condition(id):
                _cond = id
            else:
                _cond = cls.c[cls._primary_field] == id
            #todo
            # if isinstance(id, (int, long)):
            #     _cond = cls.c.id==id
            # elif isinstance(id, (str, unicode)) and id.isdigit():
            #     _cond = cls.c.id==int(id)
            # else:
            #     _cond = id

        #if there is no cached object, then just fetch from database
        obj = cls.filter(_cond, **kwargs).fields(*(fields or [])).one()
        
        if obj and cache or getattr(cls, '__cacheable__', None):
            dispatch.call(cls, 'set_object', instance=obj)

        return obj
712308
def get(self, *args, **kwargs):
        """"""
        assert not args
        assert list(kwargs.keys()) == ['pk']
        pk = kwargs['pk']
        model_name = self.model.__name__
        object_spec = (model_name, pk, None)
        instances = self.cache.get_instances((object_spec,))
        try:
            model_data = instances[(model_name, pk)][0]
        except KeyError:
            raise self.model.DoesNotExist(
                "No match for %r with args %r, kwargs %r" %
                (self.model, args, kwargs))
        else:
            return CachedModel(self.model, model_data)
962561
@Override
   protected Object convert(Object instance) {
      try {
         return ProtobufUtil.toWrappedByteArray(serializationContext, instance);
      } catch (IOException e) {
         throw new CacheException(e);
      }
   }
1329210
def _get_populate_from_value(self, instance):
        """"""
        if hasattr(self.populate_from, '__call__'):
            # ResolweSlugField(populate_from=lambda instance: ...)
            return self.populate_from(instance)
        else:
            # ResolweSlugField(populate_from='foo')
            attr = getattr(instance, self.populate_from)
            return attr() if callable(attr) else attr
763680
def _setChoiceDict(self):
        """"""
        # value is name of choice parameter (same as key)
        self.choiceDict = {}
        for c in self.choice: self.choiceDict[c] = c