h/t https://github.com/elbaschid/virtual-node/blob/master/setup.py
545192
def run_cmd(self, cmd, cwd=None, extra_env=None):
        
        all_output = []
        cmd_parts = []

        for part in cmd:
            if len(part) > 45:
                part = part[:20] + "..." + part[-20:]
            if ' ' in part or '\n' in part or '"' in part or "'" in part:
                part = '"%s"' % part.replace('"', '\\"')
            cmd_parts.append(part)
        cmd_desc = ' '.join(cmd_parts)
        logger.debug(" ** Running command %s" % cmd_desc)

        # output
        stdout = subprocess.PIPE

        # env
        if extra_env:
            env = os.environ.copy()
            if extra_env:
                env.update(extra_env)
        else:
            env = None

        # execute
        try:
            proc = subprocess.Popen(
                [' '.join(cmd)], stderr=subprocess.STDOUT, stdin=None, stdout=stdout,
                cwd=cwd, env=env, shell=True)
        except Exception:
            e = sys.exc_info()[1]
            logger.error("Error %s while executing command %s" % (e, cmd_desc))
            raise

        stdout = proc.stdout
        while stdout:
            line = stdout.readline()
            if not line:
                break
            line = line.rstrip()
            all_output.append(line)
            logger.info(line)
        proc.wait()

        # error handler
        if proc.returncode:
            for s in all_output:
                logger.critical(s)
            raise OSError("Command %s failed with error code %s"
                % (cmd_desc, proc.returncode))

        return proc.returncode, all_output
390066
def setup():
    """"""
    install_requirements = ["attrdict"]
    if sys.version_info[:2] < (3, 4):
        install_requirements.append("pathlib")
    setup_requirements = ['six', 'setuptools>=17.1', 'setuptools_scm']
    needs_sphinx = {
        'build_sphinx',
        'docs',
        'upload_docs',
    }.intersection(sys.argv)
    if needs_sphinx:
        setup_requirements.append('sphinx')
    setuptools.setup(
        author="David Gidwani",
        author_email="david.gidwani@gmail.com",
        classifiers=[
            "Development Status :: 4 - Beta",
            "Intended Audience :: Developers",
            "License :: OSI Approved :: BSD License",
            "Operating System :: OS Independent",
            "Programming Language :: Python",
            "Programming Language :: Python :: 2",
            "Programming Language :: Python :: 2.7",
            "Programming Language :: Python :: 3",
            "Programming Language :: Python :: 3.3",
            "Programming Language :: Python :: 3.4",
            "Topic :: Software Development",
            "Topic :: Software Development :: Libraries :: Python Modules",
        ],
        description="Painless access to namespaced environment variables",
        download_url="https://github.com/darvid/biome/tarball/0.1",
        install_requires=install_requirements,
        keywords="conf config configuration environment",
        license="BSD",
        long_description=readme(),
        name="biome",
        package_dir={'': 'src'},
        packages=setuptools.find_packages('./src'),
        setup_requires=setup_requirements,
        tests_require=["pytest"],
        url="https://github.com/darvid/biome",
        use_scm_version=True,
    )
463831
def setup():
    

    init_tasks()

    run_hook("before_setup")

    # Create shared folder
    env.run("mkdir -p %s" % (paths.get_shared_path()))
    env.run("chmod 755 %s" % (paths.get_shared_path()))

    # Create backup folder
    env.run("mkdir -p %s" % (paths.get_backup_path()))
    env.run("chmod 750 %s" % (paths.get_backup_path()))

    # Create uploads folder
    env.run("mkdir -p %s" % (paths.get_upload_path()))
    env.run("chmod 775 %s" % (paths.get_upload_path()))

    run_hook("setup")
    run_hook("after_setup")
13060
def _setup_virtualenv():
    
    print("Downloading virtualenv...")
    import gzip, tarfile, io, tempfile, shutil
    tf = tarfile.open(fileobj=io.BytesIO(urlopen(VIRTUALENV_URL).read()))
    temp_folder = tempfile.mkdtemp()
    tf.extractall(temp_folder)
    print("Calling virtualenv...")
    subprocess.call([sys.executable, os.path.join(temp_folder, 'virtualenv-1.10', 'virtualenv.py'), 
                     '--no-setuptools', '--no-pip', '--no-site-packages', os.path.join(os.curdir, 'venv')])
    shutil.rmtree(temp_folder)
859861
function setupByCopy() {
    let task_dir;
    let required_tasks;

    try {
        const config = require(path.join(process.cwd(), 'project.config'));
        required_tasks = config.required_tasks;
        if (!required_tasks) {
            throw Error('no task required.');
        }
        task_dir = config.dir.task;
        if (!task_dir) {
            throw Error('task directory not defined.');
        }
    } catch (error) {
        console.warn(error);
        process.exit(0);
    }

    const dstTaskDir = path.join(process.cwd(), task_dir);
    if (!fs.existsSync(dstTaskDir)) {
        // create tasks dir
        fs.mkdirSync(dstTaskDir);
    }

    required_tasks.forEach((task) => {
        const src = path.join(__dirname, 'tasks', task);
        const dst = path.join(dstTaskDir, task);
        if (fs.existsSync(src)) {
            if (fs.existsSync(dst)) {
                fs.unlinkSync(dst);
            }
            fs.writeFileSync(dst, fs.readFileSync(src).toString());
        } else {
            console.error('task not found: ' + task);
            process.exit(1);
        }
    });
}
884770
function(techName, techPath, bundleNode, magicNode, force, forked) {

        var arch = this.ctx.arch,
            node = this.useFileOrBuild(new BemCreateNode.BemCreateNode({
                root: this.root,
                level: this.level,
                item: this.item,
                techPath: techPath,
                techName: techName,
                force: force,
                forked: forked === undefined? ~this.getForkedTechs().indexOf(techName): forked
            }));

        if (!node) return;

        // Set bem create node to arch and add dependencies to it
        arch.setNode(node)
            .addChildren(node, node.getDependencies());

        // Add file aliases to arch and link with node as parents
        node.getFiles && node.getFiles().forEach(function(f) {

            if (node.getId() === f) return;

            var alias = new fileNodes.FileNode({ path: f, root: this.root });
            arch.setNode(alias).addParents(node, alias);

        }, this);

        bundleNode && arch.addParents(node, bundleNode);
        magicNode && arch.addChildren(node, magicNode);

        return node;

    }
1115753
function ENV_node() {
      var Module = module.constructor;

      var parent = module.parent;
      var req = util.bind(parent, parent && parent.require || require);

      var fs = req('fs');
      var path = req('path');
      var vm = req('vm');

      this.requireCache = require.cache;
      this.main = require.main;
      this.name = 'node';
      this.global = global;
      this.isWindowsNode = (process.platform === 'win32');

      var _cwd = process.cwd();
      this.setCwd = function (cwd) { _cwd = path.resolve(_cwd, cwd); };
      this.getCwd = function () { return _cwd; };

      this.pathSep = path.sep;

      // var parentPath = util.splitPath(module.parent.filename);
      // module.parent.require = function(request, opts) {
      //   if (!opts) { opts = {}; }
      //   opts.dontExport = true;
      //   return _require({}, parentPath.directory, parentPath.filename, request, opts);
      // };

      this.log = function() {
        var msg;
        try {
          msg = Array.prototype.map.call(arguments, function(a) {
              if ((a instanceof Error) && a.message) {
                return 'Error:' + a.message + '\nStack:' + a.stack + '\nArguments:' + a.arguments;
              }
              return (typeof a == 'string' ? a : JSON.stringify(a));
            }).join(' ') + '\n';
        } catch(e) {
          msg = Array.prototype.join.call(arguments, ' ') + '\n';
        }

        process.stderr.write(msg);
        return msg;
      };

      this.getPath = function() {
        return __dirname;
      };

      this.eval = function (code, path) {
        return vm.runInThisContext(code, path, true);
      };

      this.fetch = function (p) {
        p = util.resolve(this.getCwd(), p);

        var filename, lowercaseFilename, files;
        try {
          var dirname = path.dirname(p);
          filename = path.basename(p);
          lowercaseFilename = filename.toLowerCase();
          files = fs.readdirSync(dirname);
        } catch (e) {
          return false;
        }

        for (var i = 0, testName; testName = files[i]; ++i) {
          if (testName.toLowerCase() == lowercaseFilename && testName != filename) {
            throw "Invalid case when importing [" + p + "].  You probably meant" + testName;
          }
        }

        try {
          return fs.readFileSync(p, 'utf8');
        } catch(e) {
          return false;
        }
      };

      var stackRe = /\((?!module.js)(?:file:\/\/)?(.*?)(:\d+)(:\d+)\)/g;
      this.loadModule = function (baseLoader, fromDir, fromFile, item, opts) {
        if (fromFile == INITIAL_FILE && !opts.initialImport) {
          var stack = new Error().stack;
          var match;
          stackRe.lastIndex = 0;
          do {
            match = stackRe.exec(stack);
          } while (match && /jsio\.js$/.test(match[1]));

          if (match) {
            fromDir = path.dirname(match[1]);
            fromFile = path.basename(match[1]);
          }
        }

        try {
          return baseLoader(null, fromDir, fromFile, item, opts);
        } catch(e) {
          if (e.code == MODULE_NOT_FOUND) {
            var require = req;
            // lookup node module for relative imports
            var module;
            var filename = path.join(fromDir, fromFile);
            module = this.requireCache[filename];
            if (!module) {
              module = new Module(filename);
              module.filename = filename;
              module.paths = Module._nodeModulePaths(path.dirname(filename));
            }
            var request = item.original || item.from;
            try {
              return {
                exports: module ? module.require(request) : require(request),
                path: item.from
              };
            } catch (e2) {
              if (e2.code == MODULE_NOT_FOUND) {
                throw e;
              }

              throw e2;
            }
          } else {
            throw e;
          }
        }
      };
    }
746867
def _create_github_remote_repo(basedir):
    '''
    '''
    github_user = _lazy('github_user')
    github_repo = _lazy('github_repo', default=os.path.basename(basedir))

    _insert_repo_infos_into_readme(basedir, github_user, github_repo)
    run(flo('cd {basedir} && git add README.md'))
    run(flo('cd {basedir} && git commit -am "Add github repo and user '
            'into README.md"'))

    print_msg('create github repo')
    run(flo("cd {basedir}  &&  "
            "curl -u '{github_user}' https://api.github.com/user/repos "
            "-d '") + '{"name":"' + flo('{github_repo}"') + "}'")
    run(flo('cd {basedir}  &&  '
            'git remote add origin '
            'git@github.com:{github_user}/{github_repo}.git'))
    run(flo('cd {basedir}  &&  git push origin master'))
271466
function(tech, bundleNode, magicNode) {

        var ctx = this.ctx,
            arch = ctx.arch,
            levelNode = arch.getNode(PATH.relative(this.root, this.level.dir)),
            depsTech = this.level.getTech('deps.js').getTechName(),
            bundles = arch.getChildren(levelNode)
                .filter(function(b) {
                    var n = arch.getNode(b);
                    return n instanceof exports.BundleNode && n !== this;
                }, this)
                .map(function(b) {
                    return U.getNodeTechPath(this.level, arch.getNode(b).item, depsTech);
                }, this);

        return this.setBemDeclNode(
            tech,
            this.level.resolveTech(tech),
            bundleNode,
            magicNode,
            'merge',
            bundles);

    }
1037012
def setup!
      env = ::Librarian::Chef::Environment.new(project_path: Dir.pwd)
      @originalpath, env.config_db.local['path'] = env.config_db.local['path'], @tmpdir
      ::Librarian::Action::Resolve.new(env).run
      ::Librarian::Action::Install.new(env).run

      ::RSpec.configure { |config| config.cookbook_path = @tmpdir }
    end
685651
function setupByLink() {
    console.warn("symlink doesn't resolve __dirname.");

    const srcTaskDir = path.join(__dirname, 'tasks');

    // detect target package
    const targets = [];
    const PACKAGES_DIR = path.join(__dirname, '..');
    fs.readdirSync(PACKAGES_DIR)
    .forEach((filePath) => {
        const absPath = path.join(PACKAGES_DIR, filePath);
        if (fs.statSync(absPath).isDirectory()) {
            if (/^cdp-/.test(filePath)) {
                // check project.config.js
                try {
                    const config = require(path.join(absPath, 'project.config'));
                    if (config.required_tasks) {
                        targets.push({
                            path: absPath,
                            required_tasks: config.required_tasks,
                            task_dir: config.dir.task,
                        });
                    }
                } catch (error) {
                    return; // next
                }
            }
        }
    });

    // link
    targets.forEach((target) => {
        const dstTaskDir = path.join(target.path, target.task_dir);
        if (!fs.existsSync(dstTaskDir)) {
            // create tasks dir
            fs.mkdirSync(dstTaskDir);
        }

        target.required_tasks.forEach((task) => {
            const src = path.join(srcTaskDir, task);
            const dst = path.join(dstTaskDir, task);
            if (!fs.existsSync(src)) {
                console.error('task not found: ' + task);
                process.exit(1);
            }
            if (fs.existsSync(dst)) {
                fs.unlinkSync(dst);
            }
            fs.symlinkSync(src, dst, 'file');
        });
    });
}
1245528
function setup(e) {

  e.explaination = []
  e.explain = function (template, parts, message) {
    e.explaination.push({
      template: template,
      parts: parts,
      message: message
    })
    return e
  }
  e.simple = function (name, actual, expected, operator, message) {
    return e.explain(
        name + ': {actual} {operator} {expected}'
      , { actual: actual
        , expected: expected
        , operator: operator }
      , message
    )
  }
  e.toString = function () {
    return e.explaination.map(function (e) {
      return (
        fomatto(e.template, e.parts)
      + ( e.message  ? '\n  ' + fomatto(e.message, e.parts) : '' )
      )
    }).join('\n')  
  }
 
  e.__defineGetter__('message', function () {
    return '' + e
  })
  return e
  
}
1106185
def build_src(ctx, dest=None):
    
    if dest:
        if not dest.startswith('/'):
            # Relative
            dest = os.path.join(os.getcwd(), dest)

        os.chdir(PROJECT_DIR)
        ctx.run('python setup.py sdist --dist-dir {0}'.format(dest))
    else:
        os.chdir(PROJECT_DIR)
        ctx.run('python setup.py sdist')
98777
function createDockerFile() {

    const extraPkgs = [
        'nodejs',
        'nodejs-legacy',
        'git',
        'wget',
        'build-essential',
        // In case we'd need to fallback-to-build for some of the binary dependencies
        // and use node-gyp, we'd need python, so let's install it just in case.
        'python'
   ];
    const nodeVersion = pkg.deploy.node;

    if (nodeVersion === 'system') {
        // In case we're setting a specific node version we use nvm to install npm so we don't
        // need to install npm through the apt-get
        extraPkgs.push('npm');
    }
    // An array where we store custom-sourced extra packages
    // Each element has 'repo_url', 'release', 'pool' and 'packages' properties
    // 'packages' is an array of package names
    // 'repo_url' and 'pool' combinations are unique
    const customSourcePkgs = [];
    // An array of URIs of custom .deb packages to be installed
    const debPkgs = [];

    // set some defaults
    if (!pkg.deploy) {
        pkg.deploy = {};
    }
    if (!pkg.deploy.target) {
        pkg.deploy.target = 'debian';
    }
    if (!pkg.deploy.dependencies) {
        pkg.deploy.dependencies = {};
    }
    if (!pkg.deploy.dependencies._all) {
        pkg.deploy.dependencies._all = [];
    }
    if (!pkg.deploy.node) {
        pkg.deploy.node = 'system';
    }

    const npmVersion = pkg.deploy.npm;
    // set the deploy target
    // allow the user to specify the exact target to use, like "debian:sid"
    const baseImg = /^.+:.+$/.test(pkg.deploy.target) ? pkg.deploy.target : targets[pkg.deploy.target];
    let contents = `FROM ${baseImg}\n`;

    if (!baseImg || baseImg === '') {
        console.error('ERROR: You must specify a valid target!');
        console.error('ERROR: Check the deploy stanza in package.json and targets.yaml');
        process.exit(2);
    }

    // get any additional packages that need to be installed
    Object.keys(pkg.deploy.dependencies).forEach((sys) => {
        if (sys === '_all' || (sys === baseImg || (new RegExp(sys)).test(baseImg))) {
            pkg.deploy.dependencies[sys].forEach((pkg) => {
                if (typeof pkg === 'string') {
                    extraPkgs.push(pkg);
                } else if (typeof pkg === 'object') {
                    if (pkg.uri) {
                        debPkgs.push(pkg.uri);
                    } else if (!pkg.repo_url || !pkg.pool || !pkg.packages || !pkg.release) {
                        console.error(`ERROR: Incorrect dependency spec: ${JSON.stringify(pkg)}`);
                        process.exit(1);
                    } else {
                        customSourcePkgs.push(pkg);
                    }
                } else {
                    console.error(`ERROR: Incorrect dependency spec: ${pkg}`);
                    process.exit(1);
                }
            });
        }
    });

    if (customSourcePkgs.some((customSourcePkgSpec) => /^https/.test(customSourcePkgSpec.repo_url))) {
        extraPkgs.push('apt-transport-https');
    }

    contents += `RUN apt-get update && apt-get install -y ${extraPkgs.join(' ')} && rm -rf /var/lib/apt/lists/*\n`; /**/

    if (customSourcePkgs.length) {
        contents += `RUN echo > /etc/apt/sources.list && ${customSourcePkgs.map((customSourcePkgSpec) =>
            `echo deb "${customSourcePkgSpec.repo_url} ${customSourcePkgSpec.release} ${customSourcePkgSpec.pool}" >> /etc/apt/sources.list`).join(' && ')}\n`;
        contents += `RUN apt-get update && ${customSourcePkgs.map((customSourcePkgSpec) => `apt-get install -y --force-yes -t ${customSourcePkgSpec.release} ${customSourcePkgSpec.packages.join(' ')}`).join(' && ')} && rm -rf /var/lib/apt/lists/*\n`; /**/
    }

    if (debPkgs.length) {
        contents += `RUN ${debPkgs.map((uri) => `wget ${uri} -O package.deb && dpkg -i package.deb && rm package.deb`).join(' && ')}\n`;
    }

    let npmCommand = 'npm';
    if (nodeVersion !== 'system') {
        const nvmDownloadURI = 'https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh';
        contents += 'ENV NVM_DIR /usr/local/nvm\n';
        contents += `RUN wget -qO- ${nvmDownloadURI} | bash && . $NVM_DIR/nvm.sh && nvm install ${nodeVersion}\n`;
        npmCommand = `. $NVM_DIR/nvm.sh && nvm use ${nodeVersion} && npm`;
    }

    if (!opts.deploy) {
        contents += `RUN mkdir /opt/service\nADD . /opt/service\nWORKDIR /opt/service\nRUN ${npmCommand} install && npm dedupe\n`;
    }

    if (opts.uid !== 0 &&
            // In 'Docker for Mac' the mapping between users/groups
            // is done internally by docker, so we can run as root
            os.type() !== 'Darwin') {
        contents += `RUN groupadd -o -g ${opts.gid} -r rungroup && useradd -o -m -r -g rungroup -u ${opts.uid} runuser\nUSER runuser\nENV HOME=/home/runuser LINK=g++\n`;
    } else {
        contents += 'ENV HOME=/root/ LINK=g++\n';
    }

    let envCommand = 'ENV IN_DOCKER=1';
    if (pkg.deploy.env && Object.keys(pkg.deploy.env)) {
        Object.keys(pkg.deploy.env).forEach((envVar) => {
            envCommand += ` ${envVar}="${pkg.deploy.env[envVar]}"`;
        });
    }
    contents += `${envCommand}\n`;

    if (opts.deploy) {
        let beforeInstall = '';
        let afterInstall = '';
        if (npmVersion) {
            beforeInstall += `${npmCommand} install npm@${npmVersion} &&`;
            npmCommand = './node_modules/.bin/npm';
            afterInstall = '&& rm -rf ./node_modules/npm ./node_modules/.bin/npm';
        }
        let installOpts = ' --production ';
        if (pkg.deploy.install_opts) {
            installOpts += `${pkg.deploy.install_opts.join(' ')} `;
        }
        contents += `CMD ${beforeInstall} ${npmCommand} install${installOpts} ${afterInstall}`;
    } else if (opts.tests) {
        contents += `CMD ${npmCommand} test`;
    } else if (opts.coverage) {
        contents += `CMD ${npmCommand} run-script coverage`;
    } else {
        contents += `CMD ${npmCommand} start`;
    }

    return fs.writeFileAsync('Dockerfile', contents);

}
1012427
def parse_setup(filepath):
    ''''''
    # TODO: Need to parse setup.cfg and merge with the data from below

    # Monkey patch setuptools.setup to capture keyword arguments
    setup_kwargs = {}

    def setup_interceptor(**kwargs):
        setup_kwargs.update(kwargs)

    import setuptools
    setuptools_setup = setuptools.setup
    setuptools.setup = setup_interceptor

    # Manually compile setup.py
    with open(filepath, 'r') as f:
        code = compile(f.read(), '', 'exec')
    setup = ModuleType('setup')
    exec(code, setup.__dict__)

    # Remove monkey patch
    setuptools.setup = setuptools_setup
    return setup_kwargs
617210
function buildNode(file, watch) {
  if (watch) {
    return gulp.watch(paths.src + file + '.js')
      .on('change', function(file) {
        $.util.log('Copying to lib...');
        gulp.src(file.path)
          .pipe($.plumber())
          .pipe($.babel())
          .pipe(gulp.dest(paths.dist));
      });
  } else {
    return gulp.src(paths.src + file + '.js')
      .pipe($.plumber())
      .pipe($.babel())
      .pipe(gulp.dest(paths.dist));
  }
}
673509
function setupContainerApi_(containNode_) {
  containNode_.popDesigner = popDesigner_;
  containNode_.saveDesigner = saveDesigner_;
  containNode_.dumpTree = dumpReactTree_;
  containNode_.loadTree = loadReactTree_;
  containNode_.streamTree = streamReactTree_;
  containNode_.listScenePage = listScenePage_;

  containNode_.keyOfNode = function (node) {
    return keyOfNode_(node);
  };
  containNode_.splitterMouseDn = function () {
    return splitterMouseDn_;
  };
}