Add pyramid_webpack methods and config to the app
338321
def includeme(config):
    
    settings = config.registry.settings
    root_package_name = config.root_package.__name__
    config.registry.webpack = {
        'DEFAULT': WebpackState(settings, root_package_name)
    }
    for extra_config in aslist(settings.get('webpack.configs', [])):
        state = WebpackState(settings, root_package_name, name=extra_config)
        config.registry.webpack[extra_config] = state

    # Set up any static views
    for state in six.itervalues(config.registry.webpack):
        if state.static_view:
            config.add_static_view(name=state.static_view_name,
                                   path=state.static_view_path,
                                   cache_max_age=state.cache_max_age)

    config.add_request_method(get_webpack, 'webpack')
1153083
def setup(app):
    

    app.add_directive('readthedocs-embed', EmbedDirective)
    app.add_config_value('readthedocs_embed_project', '', 'html')
    app.add_config_value('readthedocs_embed_version', '', 'html')
    app.add_config_value('readthedocs_embed_doc', '', 'html')

    return app
562976
function bundleEmbedJS(options) {
    const srcmap = require('./srcmap');
    const BUILT_PATH = path.join(__dirname, '..', config.dir.built);

    // commpact entry file
    const wrap = fs.readFileSync(
        path.join(BUILT_PATH, config.main.basename + '-entry.js')
    ).toString()
        .replace(/^\ufeff/gm, '')
        .replace(/\r\n/gm, '\n')
        .replace(/\/\/<<[\s\S]*?\/\/>>/, '__LIRBRARY_CODE__')
        .replace(/\/\*[\s\S]*?\*\//gm, '')
        .replace(/\/\/[\s\S]*?\n/gm, '')
        .replace(/ {4}/gm, '')
        .replace(/\n/gm, ' ')
        .replace('__LIRBRARY_CODE__', '\n' + '__LIRBRARY_CODE__' + '\n')
        .replace(/^ /gm, '')
        .replace(/ $/gm, '')
        .split('\n');

    const imple = fs.readFileSync(
        path.join(BUILT_PATH, config.main.basename + '-all.js')
    ).toString()
        .replace(/^\ufeff/gm, '')
        .replace(/\r\n/gm, '\n')
    ;

    const node = srcmap.getNodeFromCode(imple);

    node.prepend(wrap[0] + '\n');
    if (options.banner) {
        node.prepend(banner('.js', config.main.basename));
    }
    node.add('\n' + wrap[2] + '\n');

    const bundleSrc = '\ufeff' + srcmap.getCodeFromNode(node, (srcPath) => {
        const regex_src = new RegExp(`${config.dir.src}\\/${config.dir.script}\\/`);
        return srcPath
            .replace(/\.\.\//g, '')
            .replace(regex_src, SOURCE_MAP_NAMESPACE)
        ;
    });
    fs.writeFileSync(path.join(BUILT_PATH, config.main.basename + '.js'), bundleSrc);
    fs.writeFileSync(path.join(DST_PATH, config.main.basename + '.js'), bundleSrc);
}
602578
def setup(self, app):
        
        super().setup(app)

        if isinstance(self.cfg.template_folders, str):
            self.cfg.template_folders = [self.cfg.template_folders]

        self.cfg.template_folders = list(self.cfg.template_folders)
        if not self.cfg.loader:
            self.cfg.loader = FileSystemLoader(
                self.cfg.template_folders, encoding=self.cfg.encoding)

        self.env = jinja2.Environment(
            auto_reload=self.cfg.auto_reload,
            cache_size=self.cfg.cache_size,
            extensions=self.cfg.extensions,
            loader=self.cfg.loader,
        )
        self.env.globals['app'] = app

        @self.register
        @jinja2.contextfunction
        def debug(ctx, value=None):
            """ Debug current context to template. """
            return jinja2.filters.do_pprint(value is None and ctx or value)

        @self.filter
        def jsonify(obj):
            return dumps(obj, ensure_ascii=False, encode_html_chars=True)
1131723
def setup(app):
    
    # Used internally. For rebuilding all pages when one or versions fail.
    app.add_config_value('sphinxcontrib_versioning_versions', SC_VERSIONING_VERSIONS, 'html')

    # Needed for banner.
    app.config.html_static_path.append(STATIC_DIR)
    app.add_stylesheet('banner.css')

    # Tell Sphinx which config values can be set by the user.
    for name, default in Config():
        app.add_config_value('scv_{}'.format(name), default, 'html')

    # Event handlers.
    app.connect('builder-inited', EventHandlers.builder_inited)
    app.connect('env-updated', EventHandlers.env_updated)
    app.connect('html-page-context', EventHandlers.html_page_context)
    return dict(version=__version__)
853773
function buildJS(src, filename, dest, applyHeader, forceIncludePaths) {
  dest = dest || config.dist.jsPath;
  applyHeader = applyHeader || false;
  forceIncludePaths = forceIncludePaths || false;

  return gulp.src(src)
    .pipe(gulpif(
      forceIncludePaths,
      include({
        includePaths: [
          path.dirname(src),
          __dirname,
          config.packagesPath
        ]
      }),
      include()
    ))
    .on('error', console.log) // eslint-disable-line no-console
    .pipe(babel())
    .pipe(uglify({
      output: {
        // try to preserve non-standard headers (e.g. from objectFitPolyfill)
        comments: /^(!|---)/
      }
    }))
    .pipe(gulpif(applyHeader, header(config.prj.header, {
      config: config
    })))
    .pipe(rename(filename))
    .pipe(gulp.dest(dest));
}
660360
function addReactSupport(env, webpackConfig) {
    var babelLoaderOptions = webpackConfig.module.rules.filter(function(rule) {
        return rule.loader == 'babel-loader'
    })[0].options;

    // 添加 babel-preset-react 启用 JSX
    babelLoaderOptions.presets.push('react');
}
392028
def setup(app):
    '''  '''
    app.add_node(
        bokehjs_content,
        html=(
            html_visit_bokehjs_content,
            html_depart_bokehjs_content
        )
    )
    app.add_directive('bokehjs-content', BokehJSContent)
708954
def includeme(config):
    
    settings = config.registry.settings
    swagger_versions = get_swagger_versions(settings)

    # for rendering /swagger.yaml
    config.add_renderer(
        'yaml', 'pyramid_swagger.api.YamlRendererFactory',
    )

    # Add the SwaggerSchema to settings to make it available to the validation
    # tween and `register_api_doc_endpoints`
    settings['pyramid_swagger.schema12'] = None
    settings['pyramid_swagger.schema20'] = None

    # Store under two keys so that 1.2 and 2.0 can co-exist.
    if SWAGGER_12 in swagger_versions:
        settings['pyramid_swagger.schema12'] = get_swagger_schema(settings)

    if SWAGGER_20 in swagger_versions:
        settings['pyramid_swagger.schema20'] = get_swagger_spec(settings)

    config.add_tween(
        "pyramid_swagger.tween.validation_tween_factory",
        under=pyramid.tweens.EXCVIEW
    )

    config.add_renderer('pyramid_swagger', PyramidSwaggerRendererFactory())

    if settings.get('pyramid_swagger.enable_api_doc_views', True):
        if SWAGGER_12 in swagger_versions:
            register_api_doc_endpoints(
                config,
                settings['pyramid_swagger.schema12'].get_api_doc_endpoints())

        if SWAGGER_20 in swagger_versions:
            register_api_doc_endpoints(
                config,
                build_swagger_20_swagger_schema_views(config),
                base_path=settings.get('pyramid_swagger.base_path_api_docs', ''))
714516
def init_app(self, app):
    

    app.config.setdefault(FEATURE_FLAGS_CONFIG, {})
    app.config.setdefault(RAISE_ERROR_ON_MISSING_FEATURES, False)

    if hasattr(app, "add_template_test"):
      # flask 0.10 and higher has a proper hook
      app.add_template_test(self.check, name=self.JINJA_TEST_NAME)
    else:
      app.jinja_env.tests[self.JINJA_TEST_NAME] = self.check

    if not hasattr(app, 'extensions'):
      app.extensions = {}
    app.extensions[EXTENSION_NAME] = self
576597
def init():
    

    mochapyfile = os.path.join(os.path.join(CWD, "brew.py"))

    header("Initializing Mocha ...")
    if os.path.isfile(mochapyfile):
        print("WARNING: It seems like Mocha is already setup!")
        print("*" * 80)
    else:
        print("")
        print("Copying files to the current directory...")
        copy_resource_dir(SKELETON_DIR + "/create/", CWD)
        print("")

        _npm_install_static()
        print("")
        print("----- Your Mocha is ready! ----")
        print("")
        print("> What's next?")
        print("- Edit the config [ application/config.py ] ")
        print("- If necessary setup your model database [ mocha :initdb ]")
        print("- Launch app on development mode, run [ mocha :serve ]")
        print("")
        print("*" * 80)
1191387
function (options, callback) {
        options = extend({}, MODULE_LOADER_DEFAULTS, options)
        var modulesFolder = options.uri

        iterateFiles(modulesFolder, loadModule, callback, isJsFile)

        function loadModule(fileName) {
            if (options.skip && options.skip.test(fileName)) {
                return
            }
            var module = require(fileName)
            var name = path.relative(options.uri, fileName)
            options.core.add(name, module)
        }
    }
1226716
function(userConf, template, callback) {

        var content = userConf,
        //if nothing to merge.
            newContent = JSON.parse( JSON.stringify(content) );

        var isStandalone = true,
            env = self.Env.get(),
            appsPath = "",
            modelsPath = "";


        //Pushing default app first.
        self.bundles.push(self.startingApp);//This is a JSON.push.
        var root = new _(self.executionPath).toUnixStyle();
        try {
            var pkg = require(_(root + '/project.json')).bundles;
        } catch (err) {
            callback(err);
        } //bundlesPath will be default.


        //For each app.
        for (var app in content) {
            //Checking if genuine app.
            console.debug('Checking if application [ '+ app +' ]is registered ');

            if ( typeof(content[app][env]) != "undefined" ) {

                if (
                    pkg[app] != 'undefined' && pkg[app]['src'] != 'undefined' && env == 'dev'
                    || pkg[app] != 'undefined' && pkg[app]['src'] != 'undefined' && env == 'debug'
                ) {
                    var p = _(pkg[app].src);
                    content[app][env]['bundlesPath'] = "{executionPath}/"+ p.replace('/' + app, '');
                } else {
                    var p = ( typeof(pkg[app].release.link) != 'undefined' ) ? _(pkg[app].release.link) : _(pkg[app].release.target);
                    content[app][env]['bundlesPath'] = "{executionPath}/"+ p.replace('/' + app, '');
                }

                appsPath = (typeof(content[app][env]['bundlesPath']) != "undefined")
                    ? content[app][env].bundlesPath
                    : template["{bundle}"]["{env}"].bundlesPath;



                modelsPath = (typeof(content[app][env]['modelsPath']) != "undefined")
                    ?  content[app][env].modelsPath
                    :  template["{bundle}"]["{env}"].modelsPath;

                //I had to for this one...
                appsPath = appsPath.replace(/\{executionPath\}/g, root);
                //modelsPath = modelsPath.replace(/\{executionPath\}/g, mPath);

                //console.log("My env ", env, self.executionPath, JSON.stringify(template, null, '\t') );
                //Existing app and port sharing => != standalone.
                if ( !fs.existsSync(appsPath) ) {
                    new _(appsPath).mkdirSync()
                }
                var masterPort = content[self.startingApp][env].port.http;
                //Check if standalone or shared instance
                if (content[app][env].port.http != masterPort) {
                    isStandalone = false;
                    self.Host.standaloneMode = isStandalone
                } else if (app != self.startingApp) {
                    self.bundles.push(app)
                }
                self.allBundles.push(app);

                //Mergin user's & template.
                newContent[app][env] = merge(
                    newContent[app][env],
                    JSON.parse( JSON.stringify(template["{bundle}"]["{env}"]))//only copy of it.
                );


                //Variables replace. Compare with gina/core/template/conf/env.json.
                var version = undefined, middleware = undefined;
                try {
                    self.version    = version = require(_(getPath('gina').root +'/package.json' )).version;
                    self.middleware = middleware = fs.readFileSync(_(getPath('gina').root + '/MIDDLEWARE')).toString() || 'none';

                    setContext('gina.version', version);
                    setContext('gina.middleware', middleware);

                } catch (err) {
                    console.debug(err.stack)
                }

                var reps = {
                    "executionPath" : root,
                    "bundlesPath" : appsPath,
                    "modelsPath" : modelsPath,
                    "env" : env,
                    "bundle" : app,
                    "version": version
                };


                //console.error("reps ", reps);
                newContent = whisper(reps, newContent);


            }
            //Else not in the scenario.

        }//EO for.


        console.debug('Env configuration loaded \n');

        // TRUE means that all apps sharing the same process will merge into one.
        if (!isStandalone) self.Host.standaloneMode = isStandalone;

        console.debug('Is server running as a standalone instance ? ' + isStandalone);

        callback(false, newContent)
    }
504013
function addDeployPlugin(webpackConfig, wpkConfig, env) {
    env = proccessFtpPath(env);

    webpackConfig.plugins.push(new DeployPlugin({
        server: `${env.__ftp_user__}:${env.__ftp_password__}@${env.__ftp_host__}:${env.__ftp_port__}`,
        workspace: wpkConfig.output.path,
        deployTo: env.__ftp_path__
    }));
}
414019
def configure_module_files
      source = "#{@target_dir}/app/apis/#{@project_name}/modules/#{@module_name}_apis.rb"
      application_module = @project_name.split('_').map(&:capitalize)*''
      file = File.read(source)
      replace = file.gsub(/module Rammer/, "module #{application_module}")
      File.open(source, "w"){|f|
        f.puts replace
      }
    end
71837
def add_package(pkg_type, pkg_name, working=None):
    
    kvp = {pkg_type: pkg_name}
    working = os.getcwd() if not working else os.path.abspath(working)
    if '-dist/scripts' in working:
        config = working + "/config.JSON"
    elif '-dist' in working:
        config = working + "/scripts/config.JSON"
    else:
        config = working + "/*-dist/scripts/config.JSON"
        entropy = glob.glob(config)
        if entropy:
            config = entropy[0]  # we'll just assume it's the first one...
    print("config", config, 'working', working)
    config = load_config(config)
    config.update(kvp)
    export_to_json(config)
1072474
function bundler(loader, options, modules) {
  var stack    = modules.slice(0);
  var mods     = [];
  var finished = {};

  function processModule(mod) {
    if (finished.hasOwnProperty(mod.id)) {
      return;
    }

    mod = loader.getModule(mod.id);

    // browser pack chunk
    var browserpack = {
      id     : mod.id,
      source : mod.source,
      deps   : {}
    };

    // Gather up all dependencies
    var i, length, dep;
    for (i = 0, length = mod.deps.length; i < length; i++) {
      dep = mod.deps[i];
      stack.push(dep);
      browserpack.deps[dep.id] = dep.id;
    }

    finished[mod.id] = browserpack;
    mods.unshift(browserpack);
  }

  // Process all modules
  while (stack.length) {
    processModule(stack.pop());
  }

  var stream = browserPack(options).setEncoding("utf8");
  var promise = pstream(stream);

  stream.end(JSON.stringify(mods));
  return promise;
}