/* package-private
763549
final PullResponse pull(
      ProjectSubscriptionName subscription, boolean returnImmediately, int maxMessages) {

    PullRequest request =
        PullRequest.newBuilder()
            .setSubscription(subscription == null ? null : subscription.toString())
            .setReturnImmediately(returnImmediately)
            .setMaxMessages(maxMessages)
            .build();
    return pull(request);
  }
1249560
public String build(final InternalKnowledgePackage pkg,
                        final FunctionDescr functionDescr,
                        final TypeResolver typeResolver,
                        final Map<String, LineMappings> lineMappings,
                        final List<KnowledgeBuilderResult> errors) {

        final Map<String, Object> vars = new HashMap<String, Object>();

        vars.put("package",
                 pkg.getName());

        vars.put("imports",
                 pkg.getImports().keySet());

        final List<String> staticImports = new LinkedList<String>();
        for (String staticImport : pkg.getStaticImports()) {
            if (!staticImport.endsWith(functionDescr.getName())) {
                staticImports.add(staticImport);
            }
        }

        vars.put("staticImports",
                 staticImports);

        vars.put("className",
                 StringUtils.ucFirst(functionDescr.getName()));

        vars.put("methodName",
                 functionDescr.getName());

        vars.put("returnType",
                 functionDescr.getReturnType());

        vars.put("parameterTypes",
                 functionDescr.getParameterTypes());

        vars.put("parameterNames",
                 functionDescr.getParameterNames());

        vars.put("hashCode",
                 functionDescr.getText().hashCode());

        // Check that all the parameters are resolvable
        final List<String> names = functionDescr.getParameterNames();
        final List<String> types = functionDescr.getParameterTypes();
        for (int i = 0, size = names.size(); i < size; i++) {
            try {
                typeResolver.resolveType(types.get(i));
            } catch (final ClassNotFoundException e) {
                errors.add(new FunctionError(functionDescr,
                                             e,
                                             "Unable to resolve type " + types.get(i) + " while building function."));
                break;
            }
        }

        vars.put("text",
                 functionDescr.getText());

        final String text = String.valueOf(TemplateRuntime.eval(template, null, new MapVariableResolverFactory(vars)));

        final BufferedReader reader = new BufferedReader(new StringReader(text));
        final String lineStartsWith = "    public static " + functionDescr.getReturnType() + " " + functionDescr.getName();
        try {
            String line;
            int offset = 0;
            while ((line = reader.readLine()) != null) {
                offset++;
                if (line.startsWith(lineStartsWith)) {
                    break;
                }
            }
            functionDescr.setOffset(offset);
        } catch (final IOException e) {
            // won't ever happen, it's just reading over a string.
            throw new RuntimeException("Error determining start offset with function");
        }

        final String name = pkg.getName() + "." + StringUtils.ucFirst(functionDescr.getName());
        final LineMappings mapping = new LineMappings(name);
        mapping.setStartLine(functionDescr.getLine());
        mapping.setOffset(functionDescr.getOffset());
        lineMappings.put(name,
                         mapping);

        return text;
    }
463208
function(callback) {
    async.waterfall([
      // Make root directory.
      maybeMkdir.bind(null, this.root),

      // Make tmp directory.
      function(done) {
        this.tempdir = path.join(this.root, '.tmp');
        maybeMkdir(this.tempdir, { purge: true }, done);
      }.bind(this),

      // Make directories for each package, package version.
      function(done) {
        var dirs = [];
        for (var package in this.packageToVersions) {
          dirs.push(path.resolve(this.tempdir, package));
          var versions = this.packageToVersions[package];
          for (var version in versions) {
            dirs.push(path.resolve(this.tempdir, package, version));
          }
        }

        async.parallel(dirs.map(function(dir) {
          return maybeMkdir.bind(null, dir);
        }), function(err) {
          return done && done(err);
        });
      }.bind(this)
    ], callback);
  }
1323633
function Bundle(packages, name)
    {
        this.packages = _.map(packages, function (package) {

            if (_.isString(package)) {
                return new Package(package);
            }

            return package;
        });
        this.name = name || 'bundle';
    }
669188
@Override
  public void exitStandardFileOptionJavaPackage(final StandardFileOptionJavaPackageContext ctx) {
    verifyOptionNameUnique("javaPackage", ctx.getStart());
    scopes.getFileOptions().setJavaPackage(removeQuotes(ctx.StringLiteral().getText()));
  }
940609
function getPackageName(content, pluginLookup, identifierPath) {
  let memberPath = identifierPath.parentPath;
  while (memberPath.isMemberExpression()) {
    const code = content.slice(identifierPath.node.end, memberPath.node.end);
    const pluginName = pluginLookup[code];
    if (pluginName) {
      return pluginName;
    }

    memberPath = memberPath.parentPath;
  }

  return '';
}
934646
function ()
		{
			var nmPath = this.modulePath + 'node_modules/';
			var pkgJson;
			var pkgName;
			var pkgInfo;
			var packageList = {};
			var validScript = /[\w|\W]+\.[js|coffee]+$/;
			if (fs.existsSync(nmPath))
			{
				this.e.log&&this.e.log('Importing packages...','system');
				var packages = fs.readdirSync(nmPath);
				for (p in packages)
				{
					try {
						if (packages[p].indexOf('wns')!==-1 &&
							(packages[p].indexOf('pkg') !== -1 || packages[p].indexOf('package') !== -1))
						{
							pkgName = packages[p];
							pkgDir = nmPath + pkgName;
							pkgJson = pkgDir + '/package.json';
							if (fs.existsSync(pkgJson))
							{
								pkgInfo = JSON.parse(fs.readFileSync(pkgJson));
								pkgInfo.require = pkgInfo.require||{};
								Object.defineProperty(pkgInfo,'classes',{ value: {}, enumerable: false })
								var files = fs.readdirSync(pkgDir);
								for (f in files)
								{
									var fileName = files[f].split('/').pop();
									if (validScript.test(fileName))
									{
										var className = fileName.split('.');
										className.splice(-1);
										pkgInfo.classes[className] = pkgDir+'/'+fileName;
									}
								}
								packageList[pkgInfo.name]=pkgInfo;
							}
						}
					} catch (e)
					{
						console.error('Error on loading package `'+pkgName+"`.")
						throw e;
					}
				}
			}

			this.removeInvalidPackages(packageList);
			this.loadPackages(packageList);
		}
1190462
private static void getWildcardTypePackageNames(WildcardType type,
      Map<String, Class<?>> packageNames) {
    for (Type boundType : type.getUpperBounds()) {
      getTypePackageNames(boundType, packageNames);
    }

    for (Type boundType : type.getLowerBounds()) {
      getTypePackageNames(boundType, packageNames);
    }
  }
1050256
@Override
    public T deletePackage(Package pack) throws IllegalArgumentException {
        Validate.notNull(pack, "Package name must be specified");

        return deletePackages(false, pack);
    }
360725
async function embellish({ content, filename, packageData, basePath } /*: EmbelishOptions */) /*: Promise<string> */ {
  if (filename) {
    const packageFile = path.resolve(path.dirname(filename), 'package.json');

    return embellish({
      content: await readFileContent(filename),
      basePath: path.dirname(packageFile),
      packageData: await Package.readFromFile(packageFile)
    });
  }

  if (!content || !basePath) {
    throw new Error('Unable to embelish content unless content is provided');
  }

  const ast = parse(content);
  await insertLicense(ast, packageData, basePath);
  await insertBadges(ast, packageData, basePath);
  return Promise.resolve(toMarkdown(ast));
}
512253
@Override
    @Path("/{package}/{asset}")
    @ApiOperation(value="Retrieve an asset, an asset package, or all the asset packages",
        response=PackageList.class)
    @ApiImplicitParams({
        @ApiImplicitParam(name="discoveryUrls", paramType="query", dataType="array"),
        @ApiImplicitParam(name="branch", paramType="query", dataType="string"),
        @ApiImplicitParam(name="discoveryType", paramType="query", dataType="string"),
        @ApiImplicitParam(name="groupId", paramType="query", dataType="string"),
        @ApiImplicitParam(name="archiveDirs", paramType="query", dataType="string")})
    public JSONObject get(String path, Map<String,String> headers) throws ServiceException, JSONException {

        try {
            AssetServices assetServices = ServiceLocator.getAssetServices();
            Query query = getQuery(path, headers);
            String discoveryType = query.getFilter("discoveryType");
            if (discoveryType != null) {
                if (!discoveryType.isEmpty() && discoveryType.equals("central")) {
                    String groupId = query.getFilter("groupId");
                    try {
                        Discover discover = new Discover(groupId, true);
                        return discover.run().getPackages();
                    }
                    catch (JSONException e) {
                        throw new ServiceException(ServiceException.INTERNAL_ERROR,
                                "Invalid response from maven central search query", e);
                    }
                }
                else if ("git".equals(discoveryType)){
                    String[] repoUrls = query.getArrayFilter("discoveryUrls");
                    String branch = query.getFilter("branch");
                    if (branch != null)
                        return assetServices.discoverGitAssets(repoUrls[0], branch);
                    else
                        return assetServices.getGitBranches(repoUrls);
                }
            }

            if (query.getBooleanFilter("archiveDirs")) {
                List<ArchiveDir> archiveDirs = assetServices.getArchiveDirs();
                JSONObject json = new JsonObject();
                json.put("root", assetServices.getArchiveDir().getAbsolutePath());
                for (ArchiveDir archiveDir : archiveDirs)
                    json.put(archiveDir.getJsonName(), archiveDir.getJson());
                return json;
            }

            String pkg = getSegment(path, 1);
            String asset = pkg == null ? null : getSegment(path, 2);

            if (pkg == null) {
                if (query.hasFilters()) {
                    return assetServices.getAssetPackageList(query).getJson();
                }
                else {
                    JSONObject json = getPackages(query).getJson();
                    if (assetServices.getArchiveDir().isDirectory())
                        json.put("hasArchive", true);
                    return json;
                }
            }
            else {
                if (asset == null) {
                    return getPackage(pkg).getJson();
                }
                else {
                    return getAssetInfo(pkg + "/" + asset).getJson();
                }
            }
        }
        catch (ServiceException ex) {
            throw ex;
        }
        catch (Exception ex) {
            throw new ServiceException(ex.getMessage(), ex);
        }
    }
807413
function bundleApp(codeList, ns, domload, compile, before, npmTree, o) {
  var l = []
    , usedBuiltIns = npmTree._builtIns
    , len = 0;
  delete npmTree._builtIns;

  // 1. construct the global namespace object
  l.push("window." + ns + " = {data:{}, path:{}};");

  // 2. attach path code to the namespace object so that require.js can efficiently resolve paths
  l.push('\n// include npm::path');
  var pathCode = read(join(builtInDir, 'path.posix.js'));
  l.push('(function (exports) {\n ' + pathCode + '\n}(window.' + ns + '.path));');

  // 3. pull in serialized data
  Object.keys(o.data).forEach(function (name) {
    return l.push(ns + ".data." + name + " = " + o.data[name] + ";");
  });

  // 4. attach require code
  var config = {
    namespace : ns
  , domains   : Object.keys(o.domains) // TODO: remove npm from here
  , arbiters  : o.arbiters
  , logging   : o.logLevel
  , npmTree   : npmTree
  , builtIns  : builtIns
  , slash     : '/' //TODO: figure out if different types can coexist, if so, determine in resolver, and on client
  };

  l.push(anonWrap(read(join(dir, 'require.js'))
    .replace(/VERSION/, JSON.parse(read(join(dir, '..', 'package.json'))).version)
    .replace(/REQUIRECONFIG/, JSON.stringify(config))
  ));

  // 5. include CommonJS compatible code in the order they have to be defined
  var defineWrap = function (exportName, domain, code) {
    return ns + ".define('" + exportName + "','" + domain + "',function (require, module, exports) {\n" + code + "\n});";
  };

  // 6. harvest function splits code into app and non-app code and defineWraps
  var harvest = function (onlyMain) {
    codeList.forEach(function (pair) {
      var dom = pair[0]
        , file = pair[1]
        , basename = file.split('.')[0];
      if ((dom === 'app') !== onlyMain) {
        return;
      }
      var code = before(compile(join(o.domains[dom], file)));
      l.push(defineWrap(basename, dom, code));
    });
  };

  // 7.a) include required builtIns
  l.push("\n// node builtins\n");
  len = l.length;
  usedBuiltIns.forEach(function (b) {
    if (b === 'path') { // already included
      return;
    }
    l.push(defineWrap(b, 'npm', read(join(builtInDir, b + '.js'))));
  });
  if (l.length === len) {
    l.pop();
  }

  // 7.b) include modules not on the app domain
  l.push("\n// shared code\n");
  len = l.length;
  harvest(false);
  if (l.length === len) {
    l.pop();
  }

  // 7.c) include modules on the app domain, and wait for domloader if set
  l.push("\n// app code - safety wrapped\n\n");
  domload(harvest(true));

  // 8. use a closure to encapsulate the private internal data and APIs
  return anonWrap(l.join('\n'));
}
1190150
function(next) {
            core.allowPackages.forEach(function(pkg) {
                try {
                    var mod = path.dirname(require.resolve(pkg)).replace(/\/lib$/, "");
                    core.packages[pkg] = { path: mod };
                    if (lib.statSync(mod + "/etc").isDirectory()) {
                        core.packages[pkg].etc = 1;
                        var cfg = lib.readFileSync(mod + "/etc/config");
                        if (cfg) {
                            config = cfg + "\n" + config;
                            core.packages[pkg].config = 1;
                            core.parseConfig(cfg, 1);
                        }
                    }
                    ["modules","locales","views","web"].forEach(function(x) {
                        if (lib.statSync(mod + "/" + x).isDirectory()) {
                            core.path[x].unshift(mod + "/" + x);
                            core.packages[pkg][x] = 1;
                        }
                    });
                    logger.debug("init:", "npm package:", pkg, core.packages[pkg]);
                } catch(e) {
                    logger.error("init:", "npm package:", pkg, e);
                }
            });
            next();
        }
643360
function startPackage(package, cb) {
   if (isUndefined(packageRuntimes[package.packageName])) {
      packageRuntimes[package.packageName] = {};
   }

   var packageRuntime = packageRuntimes[package.packageName];

   if (!isUndefined(packageRuntime.process)) {
      cb(new Error('package already running'));
      return;
   }

   packageRuntime.startupTimer = setTimeout(function() { 
      packageRuntime.startupTimer = null;
      cb();
   }, startupTimout * 1000);

   packageRuntime.process = exec(package.launchCommand, { cwd: (!isUndefined(package.workingDirectory) ? path.resolve(package.workingDirectory) : undefined) }, function(err) {
      packageRuntime.process = null;
      if (!isUndefined(packageRuntime.startupTimer)) {
         clearTimeout(packageRuntime.startupTimer);
         packageRuntime.startupTimer = null;
         cb(err);
      } else if (!isUndefined(packageRuntime.killTimer)) {
         clearTimeout(packageRuntime.killTimer);
         packageRuntime.killTimer = null;
         packageRuntime.killedCallback();
         packageRuntime.killedCallback = null;
      }
   });
}
564483
private void enterPackageName(BufferedReader br) throws IOException {
        String suggestedRootPackage = getDefaultRootPackage() + "." + appName;
        while (true) {
            printInstruction("Enter the Java root package of your application: [" + suggestedRootPackage + "]");

            String packageNameCandidate = br.readLine();
            if (isBlank(packageNameCandidate)) {
                rootPackage = suggestedRootPackage;
                break;
            } else {
                if (isPackageNameValid(packageNameCandidate)) {
                    rootPackage = packageNameCandidate;
                    break;
                } else {
                    System.out.println("Oops! invalid Java package name.");
                    System.out.println("");
                    continue;
                }
            }
        }
    }
937995
function stopPackage(packageName, cb) {
   var packageRuntime = packageRuntimes[packageName];

   if (isUndefined(packageRuntime) || isUndefined(packageRuntime.process)) {
      cb();
      return;
   }

   if (!isUndefined(packageRuntime.killTimer)) {
      cb(new Error('already attempting to stop package ' + packageName));
      return;
   }

   if (!isUndefined(packageRuntime.startupTimer)) {
      clearTimeout(packageRuntime.startupTimer);
      packageRuntime.startupTimer = null;
   }

   packageRuntime.killedCallback = cb;
   packageRuntime.killTimer = setTimeout(function() {
      packageRuntime.killedCallback = null; 
      packageRuntime.killTimer = null;
      cb(new Error('unable to stop package ' + packageName));
   }, killTimout * 1000);

   packageRuntime.process.kill();
}
181493
private boolean inSamePackage(Class<?> c1, Class<?> c2) {
        String nameC1 = c1.getName();
        String nameC2 = c2.getName();
        int indexDotC1 = nameC1.lastIndexOf('.');
        int indexDotC2 = nameC2.lastIndexOf('.');
        if (indexDotC1 != indexDotC2) {
            return false; // cannot be in the same package if indices are not the same
        }
        if (indexDotC1 == -1) {
            return true; // both of them are in default package
        }
        return nameC1.regionMatches(0, nameC2, 0, indexDotC1);
    }