Generate server translation file, forching a cache overwrite
764864
public function generateServerBundles()
    {
        $usage = $this->getResource(self::INSTANCE_LANGUAGE_USAGE_GUI);
        foreach ($this->getAvailableLanguagesByUsage($usage) as $language) {
            $langCode = $this->getCode($language);
            $this->buildServerBundle($langCode);
        }
    }
402607
function generateSite(config, useServer) {
  var fileMap = new FileMap(config)
    , siteBuilder = new SiteBuilder(config)
    , server = require(__dirname + '/server')(siteBuilder);

  fileMap.walk();
  fileMap.on('ready', function() {
    siteBuilder.fileMap = fileMap;
    siteBuilder.build();
  });

  siteBuilder.once('ready', function() {
    if (useServer) {
      server.run();
      server.watch();
    }
  });

  return siteBuilder;
}
201680
private function _generateJSFile()
    {
        $this->_loadLanguageItems();

        $data = [];
        foreach ($this->_languageItems as $language_item) {
            $data[md5($language_item->message)] = $language_item->languageTranslate->translation;
        }

        $filename = $this->_basePath . '/' . $this->_languageId . '.js';

        file_put_contents($filename, str_replace('{language_items}', Json::encode($data), $this->_template));
    }
164258
function generateUtilityFiles(next) {
    fs.copy(path.join(getConfig('template.folder'), 'index.js'), path.join(getConfig('output.folder'), 'index.js'), function (err) {
        if (err) { next(err); return; }
        if (getConfig('output.log')) { logger.info('(Created) Index file: ' + path.resolve(path.join(getConfig('output.folder'), 'index.js'))); }
        fs.copy(path.join(getConfig('template.folder'), '..', 'utils.js'), path.join(getConfig('output.folder'), 'utils.js'), function (err) {
            if (err) { next(err); return; }
            next(null);
        });
    });
    try {
        overriddenAliases = require(path.join(process.cwd(), getConfig('output.folder'), 'alias.json'));
    } catch (ignore) {}
}
400146
function cacheStream(strategy) {
    if (!(strategy instanceof CacheStrategy)) {
        strategy = DefaultCacheStrategy.INSTANCE;
    }

    return through.obj(function(chunk, enc, cb) {
        strategy.executeStart(this, chunk).then(function(isChanged) {
            var filename = path.resolve(chunk.path);

            if (isChanged === true) {
                gutil.log(OBSOLETE_MESSAGE, gutil.colors.magenta(tildify(filename)));

                cb(null, chunk);
            } else {
                gutil.log(UP_TO_DATE_MESSAGE, gutil.colors.magenta(tildify(filename)));

                cb();
            }
        });
    }, function(cb) {
        strategy.executeEnd().then(function() {
            cb();
        });
    });
}
1051401
def _cache_translation_needs_fallback(instance, language_code, related_name, timeout=cache.default_timeout):
    
    if not appsettings.PARLER_ENABLE_CACHING or not instance.pk or instance._state.adding:
        return

    tr_model = instance._parler_meta.get_model_by_related_name(related_name)
    key = get_translation_cache_key(tr_model, instance.pk, language_code)
    cache.set(key, {'__FALLBACK__': True}, timeout=timeout)
691575
protected function generateGroupFiles(): void
    {
        foreach($this->languages as $language){
            foreach($this->translation_groups as $group){
                $file = $this->language_folder . $language . "\\" . $group->name . ".php";
                if(!file_exists($file)){
                    $new_file = fopen($file, "a");
                    fclose($new_file);
                    $this->info("Created translation group - $group->name - for language $language.");
                }
            }
        }
    }
42463
function generateBundle(locale, messages, reactElements, options) {
  var builtContent;
  var onBuildWrite = options.onBuildWrite || defaultOnBuildWrite;
  options = options || {};

  init();

  assertLocale(locale);
  assertMessages(messages);
  assertReactElements(reactElements);

  // Load i18n content.
  loadCldr(locale);
  loadMessages(messages);

  // Set locale.
  Globalize.locale(locale);

  // Have react to render all passed components, therefore the formatters in
  // use will be created in Globalize.cache.
  _reactElements(reactElements).forEach(function(reactElement) {
    React.renderToString(reactElement);
   });

  // Compile all generated formatters.
  builtContent = GlobalizeCompiler(Globalize.cache);

  // Cleanup.
  Globalize.cache = {};

  return onBuildWrite(locale, builtContent);
}
892012
function generateModule (f) {

      // f.dest must be a string or write will fail
      var moduleNames = [];
      var filePaths = f.src.filter(existsFilter);

      if (options.watch) {
        watcher.add(filePaths);
      }

      var modules = filePaths.map(function (filepath) {

        var moduleName = normalizePath(path.relative(options.base, filepath));
        if (grunt.util.kindOf(options.rename) === 'function') {
          moduleName = options.rename(moduleName);
        }
        moduleNames.push(options.quoteChar + moduleName + options.quoteChar);

        var compiled;

        if (options.watch && (compiled = fileCache[filepath])) {
          // return compiled file contents from cache
          return compiled;
        }

        if (options.target === 'js') {
          compiled = compileTemplate(moduleName, filepath, options);
        } else if (options.target === 'coffee') {
          compiled = compileCoffeeTemplate(moduleName, filepath, options);
        } else {
          grunt.fail.fatal('Unknown target "' + options.target + '" specified');
        }

        if (options.watch) {
          // store compiled file contents in cache
          fileCache[filepath] = compiled;
        }

        return compiled;
      });

      // don't generate empty modules
      if (!modules.length) {
        return;
      }

      counter += modules.length;
      modules = modules.join('\n');

      var fileHeader = options.fileHeaderString !== '' ? options.fileHeaderString + '\n' : '';
      var fileFooter = options.fileFooterString !== '' ? options.fileFooterString + '\n' : '';
      var bundle = '';
      var targetModule = f.module || options.module;
      var indentString = options.indentString;
      var quoteChar = options.quoteChar;
      var strict = (options.useStrict) ? indentString + quoteChar + 'use strict' + quoteChar + ';\n' : '';
      var amdPrefix = '';
      var amdSuffix = '';
      // If options.module is a function, use that to get the targetModule
      if (grunt.util.kindOf(targetModule) === 'function') {
        targetModule = targetModule(f, target);
      }

      if (options.amd) {
        amdPrefix = options.amdPrefixString;
        amdSuffix = options.amdSuffixString;
      }

      if (!targetModule && options.singleModule) {
        throw new Error('When using singleModule: true be sure to specify a (target) module');
      }

      if (options.existingModule && !options.singleModule) {
        throw new Error('When using existingModule: true be sure to set singleModule: true');
      }

      if (options.singleModule) {
        var moduleSuffix = options.existingModule ? '' : ', []';
        if (options.target === 'js') {
          bundle = 'angular.module(' + quoteChar + targetModule + quoteChar + moduleSuffix + ').run([' + quoteChar + '$templateCache' + quoteChar + ', function($templateCache) {\n' + strict;
          modules += '\n}]);\n';
        } else if (options.target === 'coffee') {
          bundle = 'angular.module(' + quoteChar + targetModule + quoteChar + moduleSuffix + ').run([' + quoteChar + '$templateCache' + quoteChar + ', ($templateCache) ->\n';
          modules += '\n])\n';
        }
      } else if (targetModule) {
        //Allow a 'no targetModule if module is null' option
        bundle = 'angular.module(' + quoteChar + targetModule + quoteChar + ', [' + moduleNames.join(', ') + '])';
        if (options.target === 'js') {
          bundle += ';';
        }

        bundle += '\n\n';
      }
      grunt.file.write(f.dest, grunt.util.normalizelf(fileHeader + amdPrefix + bundle + modules + amdSuffix + fileFooter));
    }
915679
def cache_file(self, template):
        '''
        
        '''
        saltpath = salt.utils.url.create(template)
        self.file_client().get_file(saltpath, '', True, self.saltenv)
1080638
def load_config(check_dir):
    

    # Defaults for top-level keys
    options = {
        "checks": "__init__.py",
        "dependencies": None,
        "translations": None
    }

    # Defaults for translation keys
    translation_options = {
        "localedir": "locale",
        "domain": "messages",
    }

    config_file = Path(check_dir) / ".cs50.yaml"

    with open(config_file) as f:
        config = lib50.config.load(f.read(), "check50")

    if isinstance(config, dict):
        options.update(config)

    if options["translations"]:
        if isinstance(options["translations"], dict):
            translation_options.update(options["translations"])
        options["translations"] = translation_options

    if isinstance(options["checks"], dict):
        # Compile simple checks
        with open(check_dir / "__init__.py", "w") as f:
            f.write(simple.compile(options["checks"]))
        options["checks"] = "__init__.py"

    return options
483734
function(options) {
    return _.merge(options.data, {

      // Render helper method. Allows to render
      // partials within template files.
      render: function(filename) {
        var filepath = options.cwd + filename;
        var template = readTemplateFile({ src: [ filepath ] });
        return grunt.template.process(template, options);
      },

      // Translation helper method.
      // Allows resolving keys within a translation file.
      translate: function(key) {
        var translation = options.translations[key];

        if (!translation) {
          grunt.fail.warn('No translation found for key:', key);
        }
        return translation;
      }
    });
  }
698641
function cache(item, options) {
    var dir_path = pathutils.join([
        item.conf.cache.base_path,
        pathutils.getHashPath(item.source),
    ]);

    var meta_path = pathutils.join([dir_path, "meta"]);
    var source_path = pathutils.join([dir_path, "source"]);

    if (item.source_type === "file" && !item.conf.cache.copy_source_file) {
        source_path = item.source;
    }

    var target_path = pathutils.join([dir_path, 'targets', pathutils.getOptionsPath(options)]);

    /*
     * lock the files in sequence, not in parallel
     * otherwise a deadlock with other request may occur
     */
    var promise = lock(source_path).then(function(l) {
        logging.debug(item.id, "Locked: source file");
        item.locks.source = l;
        return lock(meta_path);
    }).then(function(l) {
        logging.debug(item.id, "Locked: metadata");
        item.locks.meta = l;
        return lock(target_path);
    }).then(function(l) {
        logging.debug(item.id, "Locked: target file");
        item.locks.target = l;
        return item;
    }).
    then(function(item) {
        return meta_data_still_fresh(item);
    }).
    then(function(item) {
        //meta data is still fresh
        logging.debug(item.id, "Metadata is still fresh");

        return item;
    }, function(item) {
        //meta_data is stale or doesn't exist
        logging.debug(item.id, "Metadata is stale");
        //clear the item directory and download a new version of the source
        var source_promise = fsutils.cleardir(dir_path).
        then(function() {
            logging.debug(item.id, "Item directory cleared");
            logging.debug(item.id, "Requesting source", item.source);
            return source(item);
        }, function(err) {
            // clearing the directory failed.
            // maybe it didn't exists, which would be ok
            if (err.code === "ENOENT") {
                logging.debug(item.id, "Requesting source", item.source);
                return source(item);
            } else {
                //no, it failed for some other reason
                item.error = err;
                throw item;
            }
        }).
        then(function(success) {
            //download succeeded
            logging.debug(item.id, "Source file ready");
            stats.download_success();
            //now only read metadata, don't evaluate headers or else
            //things with max-age=0 will always fail
            return read_meta_data(item);
        }, function(error) {
            logging.debug(item.id, "Acquiring source failed", error);
            stats.download_failure();
            throw item;
        });

        return source_promise;
    }).
    then(function(item) {
        //at this point the item is definitely fresh
        return get_target_file(item);
    }).
    then(function(item) {
        //the target has also been found. all done! \o/
        item.locks.meta();
        logging.debug(item.id, "Released lock: metadata");
        if (typeof item.locks.source === "function") {
            item.locks.source();
            logging.debug(item.id, "Released lock: source file");
        } else {
            //
        }

        register_for_gc(item);
        return item;
    },function(item) {
        item.locks.meta();
        logging.debug(item.id, "Released lock: metadata");
        item.locks.source();
        logging.debug(item.id, "Released lock: source file");
        item.locks.target();
        logging.debug(item.id, "Released lock: target file");

        register_for_gc(item);
        throw item;
    });

    return promise;
}
122172
def cache_node(node, provider, opts):
    '''
    
    '''
    if isinstance(opts, dict):
        __opts__.update(opts)

    if 'update_cachedir' not in __opts__ or not __opts__['update_cachedir']:
        return

    if not os.path.exists(os.path.join(__opts__['cachedir'], 'active')):
        init_cachedir()

    base = os.path.join(__opts__['cachedir'], 'active')
    provider, driver = provider.split(':')
    prov_dir = os.path.join(base, driver, provider)
    if not os.path.exists(prov_dir):
        os.makedirs(prov_dir)
    path = os.path.join(prov_dir, '{0}.p'.format(node['name']))
    mode = 'wb' if six.PY3 else 'w'
    with salt.utils.files.fopen(path, mode) as fh_:
        salt.utils.msgpack.dump(node, fh_, encoding=MSGPACK_ENCODING)
787863
function serveRoutes(server) {
    var app = server.app;
    var generator = server.generator;

    // route browserscripts, including builtins
    u.each(self.scripts, function(script) {
      var handler = browserify(script.path, script.opts);
      if (script.delay) {
        var delayed = function(req, res) {
          debug(req.path, 'waiting', script.delay);
          setTimeout(function() {
            debug(req.path, 'done waiting', script.delay);
            handler(req, res);
          }, u.ms(script.delay));
        };
      }
      app.get(script.route, delayed || handler);
    });

    // editor api
    if (opts.editor) {
      app.post('/pub/_files', function(req, res) {
        generator.serverSave(req.body, req.user, function(err, results) {
          if (err) return res.status(500).send(err);
          res.status(200).send(results);
        });
      });
      app.get('/pub/_opts.json', function(req, res) {
        res.set('Cache-Control', 'no-cache');
        res.send(serializeOpts(server.generator));
      });
    }

    // admin api
    app.get('/admin/flushCaches', function(req, res) {
      generator.flushCaches(function(err, results) {
        if (err) return res.status(500).send(err);
        res.status(200).send(results);
      });
    });

    app.get('/admin/reloadSources', function(req, res) {
      res.send(generator.reloadSources(req.query.src));
    });

    app.get('/admin/outputPages', function(req, res) {
      generator.outputPages(req.query.output, function(err, results) {
        if (err) return res.status(500).send(err);
        res.status(200).send(u.flatten(results));
      });
    });

    app.get('/admin/logPages', function(req, res) {
      res.send(generator.logPages());
    });

    app.get('/admin/reload', function(req, res) {
      generator.reload();
      res.status(200).send('OK');
    });
  }
138269
def update():
    '''
    
    '''
    try:
        salt.fileserver.reap_fileserver_cache_dir(
            os.path.join(__opts__['cachedir'], 'roots', 'hash'),
            find_file
        )
    except (IOError, OSError):
        # Hash file won't exist if no files have yet been served up
        pass

    mtime_map_path = os.path.join(__opts__['cachedir'], 'roots', 'mtime_map')
    # data to send on event
    data = {'changed': False,
            'files': {'changed': []},
            'backend': 'roots'}

    # generate the new map
    new_mtime_map = salt.fileserver.generate_mtime_map(__opts__, __opts__['file_roots'])

    old_mtime_map = {}
    # if you have an old map, load that
    if os.path.exists(mtime_map_path):
        with salt.utils.files.fopen(mtime_map_path, 'rb') as fp_:
            for line in fp_:
                line = salt.utils.stringutils.to_unicode(line)
                try:
                    file_path, mtime = line.replace('\n', '').split(':', 1)
                    old_mtime_map[file_path] = mtime
                    if mtime != new_mtime_map.get(file_path, mtime):
                        data['files']['changed'].append(file_path)
                except ValueError:
                    # Document the invalid entry in the log
                    log.warning(
                        'Skipped invalid cache mtime entry in %s: %s',
                        mtime_map_path, line
                    )

    # compare the maps, set changed to the return value
    data['changed'] = salt.fileserver.diff_mtime_map(old_mtime_map, new_mtime_map)

    # compute files that were removed and added
    old_files = set(old_mtime_map.keys())
    new_files = set(new_mtime_map.keys())
    data['files']['removed'] = list(old_files - new_files)
    data['files']['added'] = list(new_files - old_files)

    # write out the new map
    mtime_map_path_dir = os.path.dirname(mtime_map_path)
    if not os.path.exists(mtime_map_path_dir):
        os.makedirs(mtime_map_path_dir)
    with salt.utils.files.fopen(mtime_map_path, 'wb') as fp_:
        for file_path, mtime in six.iteritems(new_mtime_map):
            fp_.write(
                salt.utils.stringutils.to_bytes(
                    '{0}:{1}\n'.format(file_path, mtime)
                )
            )

    if __opts__.get('fileserver_events', False):
        # if there is a change, fire an event
        event = salt.utils.event.get_event(
                'master',
                __opts__['sock_dir'],
                __opts__['transport'],
                opts=__opts__,
                listen=False)
        event.fire_event(data,
                         salt.utils.event.tagify(['roots', 'update'], prefix='fileserver'))
304710
async def convert_endpoint(url_string, ts, is_just_checking):
    '''
    
    '''
    response = singletons.server.response

    # Prep ForeignResource and ensure does not validate security settings
    singletons.settings
    foreign_res = ForeignResource(url_string)

    target_ts = TypeString(ts)
    target_resource = TypedResource(url_string, target_ts)

    # Send back cache if it exists
    if target_resource.cache_exists():
        if is_just_checking:
            return _just_checking_response(True, target_resource)
        return await response.file(target_resource.cache_path, headers={
            'Content-Type': target_ts.mimetype,
        })

    # Check if already downloaded. If not, queue up download.
    if not foreign_res.cache_exists():
        singletons.workers.enqueue_download(foreign_res)

    # Queue up a single function that will in turn queue up conversion
    # process
    singletons.workers.enqueue_sync(
        enqueue_conversion_path,
        url_string,
        str(target_ts),
        singletons.workers.enqueue_convert
    )

    if is_just_checking:
        return _just_checking_response(False, target_resource)

    # Respond with placeholder
    return singletons.placeholders.stream_response(target_ts, response)