Memorizes an imported item
488057
def _onWhat(self, name, line, pos, absPosition):
        """"""
        self.__lastImport.what.append(ImportWhat(name, line, pos, absPosition))
388720
def _do_magic_import(self, rule, p_selectors, p_parents, p_children, scope, media, c_lineno, c_property, c_codestr, code, name):
        
        if callable(STATIC_ROOT):
            files = sorted(STATIC_ROOT(name))
        else:
            glob_path = os.path.join(STATIC_ROOT, name)
            files = glob.glob(glob_path)
            files = sorted((file[len(STATIC_ROOT):], None) for file in files)

        if files:
            # Build magic context
            map_name = os.path.normpath(
                os.path.dirname(name)).replace('\\', '_').replace('/', '_')
            kwargs = {}

            def setdefault(var, val):
                _var = '$' + map_name + '-' + var
                if _var in rule[CONTEXT]:
                    kwargs[var] = interpolate(rule[CONTEXT][_var], rule)
                else:
                    rule[CONTEXT][_var] = val
                    kwargs[var] = interpolate(val, rule)
                return rule[CONTEXT][_var]

            setdefault(
                'sprite-base-class', StringValue('.' + map_name + '-sprite'))
            setdefault('sprite-dimensions', BooleanValue(False))
            position = setdefault('position', NumberValue(0, '%'))
            spacing = setdefault('spacing', NumberValue(0))
            repeat = setdefault('repeat', StringValue('no-repeat'))
            names = tuple(os.path.splitext(
                os.path.basename(file))[0] for file, storage in files)
            for n in names:
                setdefault(n + '-position', position)
                setdefault(n + '-spacing', spacing)
                setdefault(n + '-repeat', repeat)
            sprite_map = _sprite_map(name, **kwargs)
            rule[CONTEXT]['$' + map_name + '-' + 'sprites'] = sprite_map
            ret = '''
                @import "compass/utilities/sprites/base";

                // All sprites should extend this class
                // The %(map_name)s-sprite mixin will do so for you.
                #{$%(map_name)s-sprite-base-class} {
                    background: $%(map_name)s-sprites;
                }

                // Use this to set the dimensions of an element
                // based on the size of the original image.
                @mixin %(map_name)s-sprite-dimensions($name) {
                    @include sprite-dimensions($%(map_name)s-sprites, $name);
                }

                // Move the background position to display the sprite.
                @mixin %(map_name)s-sprite-position($name, $offset-x: 0, $offset-y: 0) {
                    @include sprite-position($%(map_name)s-sprites, $name, $offset-x, $offset-y);
                }

                // Extends the sprite base class and set the background position for the desired sprite.
                // It will also apply the image dimensions if $dimensions is true.
                @mixin %(map_name)s-sprite($name, $dimensions: $%(map_name)s-sprite-dimensions, $offset-x: 0, $offset-y: 0) {
                    @extend #{$%(map_name)s-sprite-base-class};
                    @include sprite($%(map_name)s-sprites, $name, $dimensions, $offset-x, $offset-y);
                }

                @mixin %(map_name)s-sprites($sprite-names, $dimensions: $%(map_name)s-sprite-dimensions) {
                    @include sprites($%(map_name)s-sprites, $sprite-names, $%(map_name)s-sprite-base-class, $dimensions);
                }

                // Generates a class for each sprited image.
                @mixin all-%(map_name)s-sprites($dimensions: $%(map_name)s-sprite-dimensions) {
                    @include %(map_name)s-sprites(%(sprites)s, $dimensions);
                }
            ''' % {'map_name': map_name, 'sprites': ' '.join(names)}
            return ret
581416
function memoize(fn, keyFn) {
  if (!keyFn) {
    keyFn = function keyFn() {
      if (arguments.length === 1) {
        return arguments[0];
      } else if (arguments.length === 0) {
        return 'undefined';
      }

      var args = [];

      for (var i = 0; i < arguments.length; i++) {
        args.push(arguments[i]);
      }

      return args.join('$');
    };
  }

  var memoizedFn = function memoizedFn() {
    var self = this;
    var args = arguments;
    var ret;
    var k = keyFn.apply(self, args);
    var cache = memoizedFn.cache;

    if (!(ret = cache[k])) {
      ret = cache[k] = fn.apply(self, args);
    }

    return ret;
  };

  memoizedFn.cache = {};
  return memoizedFn;
}
442679
def import_handle(self, original, loc, tokens):
        """"""
        if len(tokens) == 1:
            imp_from, imports = None, tokens[0]
        elif len(tokens) == 2:
            imp_from, imports = tokens
            if imp_from == "__future__":
                self.strict_err_or_warn("unnecessary from __future__ import (Coconut does these automatically)", original, loc)
                return ""
        else:
            raise CoconutInternalException("invalid import tokens", tokens)
        if self.strict:
            self.unused_imports.update(imported_names(imports))
        return universal_import(imports, imp_from=imp_from, target=self.target)
674819
def set_item_data(self, item, filename, line_number):
        """"""
        set_item_user_text(item, '%s%s%d' % (filename, self.SEP, line_number))
1335973
def import_wiki_items(item_seq, model=WikiItem,  batch_len=100, db_alias='default', verbosity=2):
    """"""
    return djdb.import_items(item_seq, dest_model=model, batch_len=batch_len, db_alias=db_alias, verbosity=verbosity)
486479
def import_entry(self, title, content, item_node):
        
        try:
            creation_date = datetime.strptime(
                item_node.find('{%s}post_date_gmt' % WP_NS).text,
                '%Y-%m-%d %H:%M:%S')
        except ValueError as error:
            print 'Import entry error: {}'.format(error)

            creation_date = datetime.now()

        if settings.USE_TZ:
            creation_date = timezone.make_aware(
                creation_date, pytz.timezone('GMT'))

        excerpt = strip_tags(item_node.find(
            '{%sexcerpt/}encoded' % WP_NS).text or '')
        if not excerpt:
            if self.auto_excerpt:
                excerpt = Truncator(strip_tags(content)).words(50)
            else:
                excerpt = ''

        # Prefer use this function than
        # item_node.find('{%s}post_name' % WP_NS).text
        # Because slug can be not well formated
        slug = slugify(title)[:255] or 'post-%s' % item_node.find(
            '{%s}post_id' % WP_NS).text

        entry_dict = {
            'title': title,
            'content': content,
            'excerpt': excerpt,
            'tags': ', '.join(self.get_entry_tags(item_node.findall(
                'category'))),
            'status': self.REVERSE_STATUS[item_node.find(
                '{%s}status' % WP_NS).text],
            'comment_enabled': item_node.find(
                '{%s}comment_status' % WP_NS).text == 'open',
            'pingback_enabled': item_node.find(
                '{%s}ping_status' % WP_NS).text == 'open',
            'featured': item_node.find('{%s}is_sticky' % WP_NS).text == '1',
            'password': item_node.find('{%s}post_password' % WP_NS).text or '',
            'login_required': item_node.find(
                '{%s}status' % WP_NS).text == 'private',
            'last_update': timezone.now()}
        entry_dict['trackback_enabled'] = entry_dict['pingback_enabled']

        entry, created = Entry.objects.get_or_create(
            slug=slug, creation_date=creation_date,
            defaults=entry_dict)
        if created:
            try:
                entry.categories.add(*self.get_entry_categories(
                    item_node.findall('category')))
                entry.authors.add(self.authors[item_node.find(
                    '{http://purl.org/dc/elements/1.1/}creator').text])
                entry.sites.add(self.SITE)
            except KeyError as error:
                print 'Import entry error: {}'.format(error)

        return entry, created
1080645
def append(self, item: TransItem):
        

        if not (1 <= item.index <= settings.I18N_MAX_SENTENCES_PER_GROUP):
            return

        if len(self.sentences) < item.index:
            for _ in range(len(self.sentences), item.index):
                self.sentences.append(Sentence())

        self.sentences[item.index - 1].append(item)
980429
def rewrite_file_imports(item, vendored_libs, vendor_dir):
    """"""
    text = item.read_text(encoding='utf-8')
    renames = LIBRARY_RENAMES
    for k in LIBRARY_RENAMES.keys():
        if k not in vendored_libs:
            vendored_libs.append(k)
    for lib in vendored_libs:
        to_lib = lib
        if lib in renames:
            to_lib = renames[lib]
        text = re.sub(
            r'([\n\s]*)import %s([\n\s\.]+)' % lib,
            r'\1import %s\2' % to_lib,
            text,
        )
        text = re.sub(
            r'([\n\s]*)from %s([\s\.])+' % lib,
            r'\1from %s\2' % to_lib,
            text,
        )
        text = re.sub(
            r"(\n\s*)__import__\('%s([\s'\.])+" % lib,
            r"\1__import__('%s\2" % to_lib,
            text,
        )
    item.write_text(text, encoding='utf-8')
1287713
def _memorize(func):
  

  def _wrapper(self, *args, **kwargs):
    """Wrapper to cache the function's output.
    """
    if self.use_cache:
      cache = load_cache(self.cache_filename)
      original_key = ':'.join([
          self.__class__.__name__,
          func.__name__,
          '_'.join([str(a) for a in args]),
          '_'.join([str(w) for w in kwargs.values()])])
      cache_key = hashlib.md5(original_key.encode('utf-8')).hexdigest()
      cached_val = cache.get(cache_key)
      if cached_val:
        return cached_val
    val = func(self, *args, **kwargs)
    if self.use_cache:
      cache.set(cache_key, val)
    return val
  return _wrapper
180218
def memoize(obj):
    
    cache = obj.cache = {}

    @functools.wraps(obj)
    def memoizer(*args, **kwargs):
        key = str(args) + str(kwargs)
        if key not in cache:
            cache[key] = obj(*args, **kwargs)
        # only keep the most recent 100 entries
        if len(cache) > 100:
            cache.popitem(last=False)
        return cache[key]
    return memoizer
840614
def copy(self):
        '''

        '''
        return type(self)(self.anneal, self.tm, overhang=self.overhang,
                          name=self.name, note=self.note)
1337768
def store_item(self, item):
        '''  '''
        #print('storing item', item)
        item_id = self._id_of(item)
        #print('item_id', item_id)
        if item_id is None:
            #print('storing item', item)
            blob = self.serialize(item)
            with self._write_lock:
                self._execute(
                    'INSERT into objects (code) values (?);',
                    (blob,)
                )
                self.autocommit()
1368103
def memorize(func):
    
    @wraps(func)
    def wrapped_func(*args, **kwargs):
        if (len(args) > 0 and len(kwargs) > 0): 
            cacheKey = list(args)
            cacheKey.append(kwargs)
        elif (len(args) > 0): 
            cacheKey = args
        else:
            cacheKey = func.__name__
            
        global __cache__
        result = __cache__.get(cacheKey)
        if result is None:
            result = func(*args, **kwargs)
            __cache__[cacheKey] = result
        return result

    return wrapped_func
1226416
function importItem(data) {
  // Legacy format converter
  data = legacy.convertPackage(data);

  const now = new Date();
  data.id = misc.uuidv4().slice(0, 8);
  data.sessionStarted = now.toString();
  return putItem(data);
}
784367
def expiring_memoize(obj):
    """"""

    cache = obj.cache = {}
    last_access = obj.last_access = defaultdict(int)

    @wraps(obj)
    def memoizer(*args, **kwargs):
        key = str(args) + str(kwargs)

        if last_access[key] and last_access[key] + 10 < time():
            if key in cache:
                del cache[key]

        last_access[key] = time()

        if key not in cache:
            cache[key] = obj(*args, **kwargs)
        return cache[key]

    return memoizer
999842
def visit_Import(self, node, frame):
        """"""
        if node.with_context:
            self.unoptimize_scope(frame)
        self.writeline('l_%s = ' % node.target, node)
        if frame.toplevel:
            self.write('context.vars[%r] = ' % node.target)
        self.write('environment.get_template(')
        self.visit(node.template, frame)
        self.write(', %r).' % self.name)
        if node.with_context:
            self.write('make_module(context.parent, True, locals())')
        else:
            self.write('module')
        if frame.toplevel and not node.target.startswith('_'):
            self.writeline('context.exported_vars.discard(%r)' % node.target)
        frame.assigned_names.add(node.target)