Class::PromisePing

@param {string} addr - Hostname or ip addres
@param {PingConfig} config - Configuration for command ping
@return {Promise}
191192
function probe(addr, config) {
    // Do not reassign function argument
    var _config = config || {};

    // Convert callback base system command to promise base
    var deferred = Q.defer();

    // Spawn a ping process
    var ping = null;
    var platform = os.platform();
    try {
        var argumentBuilder = builderFactory.createBuilder(platform);
        ping = cp.spawn(
            builderFactory.getExecutablePath(platform, _config.v6),
            argumentBuilder.getResult(addr, _config)
        );
    } catch (err) {
        deferred.reject(err);
        return deferred.promise;
    }

    // Initial parser
    var parser = parserFactory.createParser(platform, _config);

    // Register events from system ping
    ping.once('error', function () {
        var err = new Error(
            util.format(
                'ping.probe: %s. %s',
                'there was an error while executing the ping program. ',
                'Check the path or permissions...'
            )
        );
        deferred.reject(err);
    });

    // Cache all lines from the system ping
    var outstring = [];
    ping.stdout.on('data', function (data) {
        outstring.push(String(data));
    });

    // Parse lines we have on closing system ping
    ping.once('close', function () {
        // Merge lines we have and split it by \n
        var lines = outstring.join('').split('\n');

        // Parse line one by one
        __.each(lines, parser.eat, parser);

        // Get result
        var ret = parser.getResult();

        deferred.resolve(ret);
    });

    return deferred.promise;
}
1068434
function lookupAsync(hostname) {
    return new Promise((resolve, reject) => {
        dns.lookup(hostname, { all: true }, (err, addresses) => {
            if (err)
                return reject(err);
            resolve(addresses[0].address);
        });
    });
}
914943
function getServerConfig(aCertDir) {
    const certFileRead = readFile(aCertDir + '/serverCert.pem');
    const keyFileRead = readFile(aCertDir + '/serverKey.pem');
    return Promise.all([certFileRead, keyFileRead]).
      then(files => [{ cert: files[0], key: files[1] }]);
  }
112661
function() {
        var self = this;

        return new Promise(function(resolve, reject) {
            var config = {};

            for (var i = 0; i < self._modules.length; i++) {
                var module = self._modules[i];

                var storedModule = config[module.name] = {
                    dependencies: module.dependencies
                };

                if (module.condition) {
                    storedModule.condition = module.condition;
                }

                if (!self._options.ignorePath) {
                    if (module.fullPath) {
                        storedModule.fullPath = upath.toUnix(module.fullPath);
                    } else {
                        var dirname = path.dirname(module.name);

                        var modulePath = module.path || (dirname !== '.' ? dirname + '/' + module.file : module.file);

                        storedModule.path = upath.toUnix(modulePath);
                    }
                }
            }

            resolve(config);
        });
    }
1122744
function initCheckApi(logger, config) {

    return new Promise((resolve, reject) => {
        var check = new Check(logger, config);

        var promises = [];

        var checkers = require('mazaid-checkers');

        for (var checker of checkers) {
            promises.push(check.add(checker));
        }

        Promise.all(promises)
            .then(() => {
                return check.init();
            })
            .then(() => {
                checkApi = check;
                resolve();
            })
            .catch((error) => {
                reject(error);
            });
    });

}
471622
function awaitPromise(promise) {
    var Promise = promise.constructor;
    var Fiber = Promise.Fiber;

    assert.strictEqual(
      typeof Fiber, "function",
      "Cannot await unless Promise.Fiber is defined"
    );

    var fiber = Fiber.current;

    assert.ok(
      fiber instanceof Fiber,
      "Cannot await without a Fiber"
    );

    var run = fiber.run;
    var throwInto = fiber.throwInto;

    if (process.domain) {
      run = process.domain.bind(run);
      throwInto = process.domain.bind(throwInto);
    }

    // The overridden es6PromiseThen function is adequate here because these
    // two callbacks do not need to run in a Fiber.
    es6PromiseThen.call(promise, function (result) {
      tryCatchNextTick(fiber, run, [result]);
    }, function (error) {
      tryCatchNextTick(fiber, throwInto, [error]);
    });

    return stackSafeYield(Fiber, awaitPromise);
  }
1092370
function HostEntry(addr, src) {
  if (!(this instanceof HostEntry))
    return new HostEntry(addr, src);

  this.addr = addr || new NetAddress();
  this.src = src || new NetAddress();
  this.prev = null;
  this.next = null;
  this.used = false;
  this.refCount = 0;
  this.attempts = 0;
  this.lastSuccess = 0;
  this.lastAttempt = 0;

  if (addr)
    this.fromOptions(addr, src);
}
385157
function(config) {
        var self = this;

        return new Promise(function(resolve, reject) {
            if (self._options.output) {
                fs.writeFileAsync(self._options.output, config)
                    .then(function() {
                        resolve(config);
                    });
            } else {
                resolve(config);
            }
        });
    }
110940
function chain(promise,
               onResolve = idResolveHandler,
               onReject = idRejectHandler) {
  var deferred = getDeferred(promise.constructor);
  switch (promise.status_) {
    case undefined:
      throw TypeError;
    case 0:
      promise.onResolve_.push(onResolve, deferred);
      promise.onReject_.push(onReject, deferred);
      break;
    case +1:
      promiseEnqueue(promise.value_, [onResolve, deferred]);
      break;
    case -1:
      promiseEnqueue(promise.value_, [onReject, deferred]);
      break;
  }
  return deferred.promise;
}
282355
@ObjectiveCName("pipeTo:")
    public Promise<T> pipeTo(PromiseResolver<T> resolver) {
        then(t -> resolver.result(t));
        failure(e -> resolver.error(e));
        return this;
    }
76744
function promiseCommand(command) {
    const opts = {
        env: process.env
    };
    console.log('>>>>', command)
    return spawnShell(command, opts).exitPromise
        .then((exitCode) => {
            if (exitCode === 0) {
                return;
            } else {
                throw Error("Exit " + exitCode)
            }
        })
}
580858
function _singlePromise () {
  let  done, cancel;
  const x = new Promise ( (resolve, reject ) => { 
                                                  done   = resolve
                                                  cancel = reject
                                 })

   return { 
               promise    : x
             , done       : done 
             , cancel     : cancel
             , onComplete : _after(x)
           }
   }
1368197
function generate(argv, config) {
  return new Promise((resolve, reject) => {
    _generate(argv, config, resolve, reject);
  });
}
469273
function resolve(promise) {
    var method = promise.state === FULFILLED ? 'onFulfilled' : 'onRejected';
    var arg = method === 'onFulfilled' ? promise.value : promise.reason;
    var handler, value;

    nextTick(function() {
      var isPromise;

      while (promise.handlers[0]) {
        handler = promise.handlers.shift();

        try {
          value = handler[method](arg);

          // Handle "thenables" as well as Promises
          isPromise = value instanceof Promise || value && isFunc(value.then);

          if (isPromise) {
            value.then(function(value) { fulfill(handler.promise, value); },
                       function(reason) { reject(handler.promise, reason); });
          } else {
            fulfill(handler.promise, value);
          }
        } catch(err) {
          reject(handler.promise, err);
        }
      }
    });

    return promise;
  }
806011
function attachHMRServer({httpServer, path, packagerServer}) {
  let client = null;

  function disconnect() {
    client = null;
    packagerServer.setHMRFileChangeListener(null);
  }

  // For the give platform and entry file, returns a promise with:
  //   - The full list of dependencies.
  //   - The shallow dependencies each file on the dependency list has
  //   - Inverse shallow dependencies map
  function getDependencies(platform, bundleEntry) {
    return packagerServer.getDependencies({
      platform: platform,
      dev: true,
      hot: true,
      entryFile: bundleEntry,
    }).then(response => {
      const {getModuleId} = response;

      // for each dependency builds the object:
      // `{path: '/a/b/c.js', deps: ['modA', 'modB', ...]}`
      return Promise.all(Object.values(response.dependencies).map(dep => {
        return dep.getName().then(depName => {
          if (dep.isAsset() || dep.isJSON()) {
            return Promise.resolve({path: dep.path, deps: []});
          }
          return packagerServer.getShallowDependencies({
            platform: platform,
            dev: true,
            hot: true,
            entryFile: dep.path
          })
            .then(deps => {
              return {
                path: dep.path,
                name: depName,
                deps,
              };
            });
        });
      }))
      .then(deps => {
        // list with all the dependencies' filenames the bundle entry has
        const dependenciesCache = response.dependencies.map(dep => dep.path);

        // map from module name to path
        const moduleToFilenameCache = Object.create(null);
        deps.forEach(dep => {
          moduleToFilenameCache[dep.name] = dep.path;
        });

        // map that indicates the shallow dependency each file included on the
        // bundle has
        const shallowDependencies = Object.create(null);
        deps.forEach(dep => {
          shallowDependencies[dep.path] = dep.deps;
        });

        // map from module name to the modules' dependencies the bundle entry
        // has
        const dependenciesModulesCache = Object.create(null);
        response.dependencies.forEach(dep => {
          dependenciesModulesCache[getModuleId(dep)] = dep;
        });


        const inverseDependenciesCache = Object.create(null);
        const inverseDependencies = getInverseDependencies(response);
        for (const [module, dependents] of inverseDependencies) {
          inverseDependenciesCache[getModuleId(module)] =
            Array.from(dependents).map(getModuleId);
        }

        return {
          dependenciesCache,
          dependenciesModulesCache,
          shallowDependencies,
          inverseDependenciesCache,
          resolutionResponse: response,
        };
      });
    });
  }

  const WebSocketServer = require('ws').Server;
  const wss = new WebSocketServer({
    server: httpServer,
    path: path,
  });

  wss.on('connection', ws => {
    const params = querystring.parse(url.parse(ws.upgradeReq.url).query);

    getDependencies(params.platform, params.bundleEntry)
      .then(({
        dependenciesCache,
        dependenciesModulesCache,
        shallowDependencies,
        inverseDependenciesCache,
      }) => {
        client = {
          ws,
          platform: params.platform,
          bundleEntry: params.bundleEntry,
          dependenciesCache,
          dependenciesModulesCache,
          shallowDependencies,
          inverseDependenciesCache,
        };

        packagerServer.setHMRFileChangeListener((type, filename) => {
          if (!client) {
            return;
          }

          const blacklisted = blacklist.find(blacklistedPath =>
            filename.indexOf(blacklistedPath) !== -1
          );

          if (blacklisted) {
            return;
          }

          client.ws.send(JSON.stringify({type: 'update-start'}));
          const promise = type === 'delete'
            ? Promise.resolve()
            : packagerServer.getShallowDependencies({
                entryFile: filename,
                platform: client.platform,
                dev: true,
                hot: true,
              }).then(deps => {
                if (!client) {
                  return [];
                }

                // if the file dependencies have change we need to invalidate the
                // dependencies caches because the list of files we need to send
                // to the client may have changed
                const oldDependencies = client.shallowDependencies[filename];
                if (arrayEquals(deps, oldDependencies)) {
                  // Need to create a resolution response to pass to the bundler
                  // to process requires after transform. By providing a
                  // specific response we can compute a non recursive one which
                  // is the least we need and improve performance.
                  return packagerServer.getDependencies({
                    platform: client.platform,
                    dev: true,
                    hot: true,
                    entryFile: filename,
                    recursive: true,
                  }).then(response => {
                    const module = packagerServer.getModuleForPath(filename);

                    return response.copy({dependencies: [module]});
                  });
                }

                // if there're new dependencies compare the full list of
                // dependencies we used to have with the one we now have
                return getDependencies(client.platform, client.bundleEntry)
                  .then(({
                    dependenciesCache: depsCache,
                    dependenciesModulesCache: depsModulesCache,
                    shallowDependencies: shallowDeps,
                    inverseDependenciesCache: inverseDepsCache,
                    resolutionResponse,
                  }) => {
                    if (!client) {
                      return {};
                    }

                    // build list of modules for which we'll send HMR updates
                    const modulesToUpdate = [packagerServer.getModuleForPath(filename)];
                    Object.keys(depsModulesCache).forEach(module => {
                      if (!client.dependenciesModulesCache[module]) {
                        modulesToUpdate.push(depsModulesCache[module]);
                      }
                    });

                    // Need to send modules to the client in an order it can
                    // process them: if a new dependency graph was uncovered
                    // because a new dependency was added, the file that was
                    // changed, which is the root of the dependency tree that
                    // will be sent, needs to be the last module that gets
                    // processed. Reversing the new modules makes sense
                    // because we get them through the resolver which returns
                    // a BFS ordered list.
                    modulesToUpdate.reverse();

                    // invalidate caches
                    client.dependenciesCache = depsCache;
                    client.dependenciesModulesCache = depsModulesCache;
                    client.shallowDependencies = shallowDeps;
                    client.inverseDependenciesCache = inverseDepsCache;

                    return resolutionResponse.copy({
                      dependencies: modulesToUpdate
                    });
                  });
              })
              .then((resolutionResponse) => {
                if (!client) {
                  return;
                }

                // make sure the file was modified is part of the bundle
                if (!client.shallowDependencies[filename]) {
                  return;
                }

                const httpServerAddress = httpServer.address();

                // Sanitize the value from the HTTP server
                let packagerHost = 'localhost';
                if (httpServer.address().address &&
                    httpServer.address().address !== '::' &&
                    httpServer.address().address !== '') {
                  packagerHost = httpServerAddress.address;
                }

                return packagerServer.buildBundleForHMR({
                  entryFile: client.bundleEntry,
                  platform: client.platform,
                  resolutionResponse,
                }, packagerHost, httpServerAddress.port);
              })
              .then(bundle => {
                if (!client || !bundle || bundle.isEmpty()) {
                  return;
                }

                return JSON.stringify({
                  type: 'update',
                  body: {
                    modules: bundle.getModulesIdsAndCode(),
                    inverseDependencies: client.inverseDependenciesCache,
                    sourceURLs: bundle.getSourceURLs(),
                    sourceMappingURLs: bundle.getSourceMappingURLs(),
                  },
                });
              })
              .catch(error => {
                // send errors to the client instead of killing packager server
                let body;
                if (error.type === 'TransformError' ||
                    error.type === 'NotFoundError' ||
                    error.type === 'UnableToResolveError') {
                  body = {
                    type: error.type,
                    description: error.description,
                    filename: error.filename,
                    lineNumber: error.lineNumber,
                  };
                } else {
                  console.error(error.stack || error);
                  body = {
                    type: 'InternalError',
                    description: 'react-packager has encountered an internal error, ' +
                      'please check your terminal error output for more details',
                  };
                }

                return JSON.stringify({type: 'error', body});
              })
              .then(update => {
                if (!client || !update) {
                  return;
                }

                client.ws.send(update);
              });

          promise.then(() => {
            client.ws.send(JSON.stringify({type: 'update-done'}));
          });
        });

        client.ws.on('error', e => {
          console.error('[Hot Module Replacement] Unexpected error', e);
          disconnect();
        });

        client.ws.on('close', () => disconnect());
      })
    .catch(err => {
      throw err;
    });
  });
}
744047
async function ip(options = {}) {
  const {
    host = 'https://api.ipify.org',
  } = options
  const res = await rqt(host)
  return res
}
1079040
function eventPromise (emitter, eventName) {
  return new Promise((resolve, reject) => {
    emitter.on(eventName, (...args) => {
      return resolve(args)
    })
  })
}