Example #1
0
GCEImages.prototype._parseArguments = function (options, callback) {
  var defaultOptions = {
    deprecated: false,
    osNames: Object.keys(GCEImages.OS_URLS)
  };

  var parsedArguments = {
    options: options,
    callback: callback
  };

  if (typeof options === 'string') {
    parsedArguments.options = {
      osNames: [options]
    };
  }

  if (typeof options === 'function') {
    parsedArguments.callback = options;
  }

  parsedArguments.options = assign(defaultOptions, parsedArguments.options);
  parsedArguments.options.osNames = arrify(parsedArguments.options.osNames);

  return parsedArguments;
};
Example #2
0
const fkill = async (inputs, options = {}) => {
	inputs = arrify(inputs);

	const exists = await processExists.all(inputs);

	const errors = [];

	const handleKill = async input => {
		try {
			input = await parseInput(input);

			if (input === process.pid) {
				return;
			}

			await kill(input, options);
		} catch (error) {
			if (!exists.get(input)) {
				errors.push(`Killing process ${input} failed: Process doesn't exist`);
				return;
			}

			errors.push(`Killing process ${input} failed: ${error.message.replace(/.*\n/, '').replace(/kill: \d+: /, '').trim()}`);
		}
	};

	await Promise.all(
		inputs.map(input => handleKill(input))
	);

	if (errors.length > 0 && !options.silent) {
		throw new AggregateError(errors);
	}
};
Example #3
0
        /**
         * For "delete" hooks we want to set the scope to
         * the entity instance we are going to delete
         * We won't have any entity data inside the entity but, if needed,
         * we can then call the "datastoreEntity()" helper on the scope (this)
         * from inside the hook.
         * For "multiple" ids to delete, we obviously can't set any scope.
         */
        function getScopeForDeleteHooks() {
            let id = is.object(args[0]) && {}.hasOwnProperty.call(args[0], '__override')
                ? arrify(args[0].__override)[0]
                : args[0];

            if (is.array(id)) {
                return null;
            }

            id = parseId(id);
            let ancestors;
            let namespace;
            let key;

            if (hookType === 'post') {
                ({ key } = args);
                if (is.array(key)) {
                    return null;
                }
            } else {
                ({
                    1: ancestors,
                    2: namespace,
                    4: key,
                } = args);
            }

            if (!id && !ancestors && !namespace && !key) {
                return undefined;
            }

            return _this.__model(null, id, ancestors, namespace, key);
        }
Example #4
0
  }, function(err, resp) {
    if (err) {
      callback(err, null, null, resp);
      return;
    }

    var files = arrify(resp.items).map(function(file) {
      var options = {};

      if (query.versions) {
        options.generation = file.generation;
      }

      var fileInstance = self.file(file.name, options);
      fileInstance.metadata = file;

      return fileInstance;
    });

    var nextQuery = null;
    if (resp.nextPageToken) {
      nextQuery = extend({}, query, {
        pageToken: resp.nextPageToken
      });
    }

    callback(null, files, nextQuery, resp);
  });
Example #5
0
Model.prototype.query = function(input, callback) {
  this.request({
    method: 'POST',
    uri: '/predict',
    json: {
      input: {
        csvInstance: arrify(input)
      }
    }
  }, function(err, resp) {
    if (err) {
      callback(err, null, resp);
      return;
    }

    var results = {
      winner: resp.outputLabel || resp.outputValue,
    };

    if (resp.outputMulti) {
      results.scores = resp.outputMulti
        .sort(function(a, b) {
          return a.score < b.score ? 1 : a.score > b.score ? -1 : 0;
        })
        .map(function(scoreObject) {
          scoreObject.score = parseFloat(scoreObject.score);
          return scoreObject;
        });
    }

    callback(null, results, resp);
  });
};
Example #6
0
 Request.prototype.progress = function (fns) {
     for (var _i = 0, _a = arrify(fns); _i < _a.length; _i++) {
         var fn = _a[_i];
         this._progress.push(fn);
     }
     return this;
 };
Example #7
0
    recordTypes.forEach(function(recordType) {
      var recordTypeSet = arrify(parsedZonefile[recordType]);

      recordTypeSet.forEach(function(record) {
        recordsToCreate.push(Record.fromZoneRecord_(self, recordType, record));
      });
    });
Example #8
0
function generateGlobTasks(patterns, opts) {
	var globTasks = [];

	patterns = arrify(patterns);
	opts = objectAssign({
		cache: Object.create(null),
		statCache: Object.create(null),
		realpathCache: Object.create(null),
		symlinks: Object.create(null),
		ignore: []
	}, opts);

	patterns.forEach(function (pattern, i) {
		if (isNegative(pattern)) {
			return;
		}

		var ignore = patterns.slice(i).filter(isNegative).map(function (pattern) {
			return pattern.slice(1);
		});

		globTasks.push({
			pattern: pattern,
			opts: objectAssign({}, opts, {
				ignore: opts.ignore.concat(ignore)
			})
		});
	});

	return globTasks;
}
Example #9
0
        Object.keys(data.versions).forEach(function (version) {
          arrify(data.versions[version]).forEach(function (info) {
            // Handle plain string locations.
            if (typeof info === 'string') {
              info = { location: info }
            }

            // check if commit sha is specified
            var dependency = typings.parseDependency(info.location)
            if (dependency.type === 'github' || dependency.type === 'bitbucket') {
              if (dependency.meta.sha === 'master') {
                return done(new Error(info.location + ' is mutable and may change, consider specifying a commit hash'))
              }
            }

            typingsBatch.push(function (done) {
              typings.installDependency({
                name: name,
                location: info.location
              }, {
                cwd: __dirname,
                name: name,
                global: globalSources.indexOf(source) > -1
              })
                .then(function () {
                  return done()
                }, done)
            })
          })
        })
Example #10
0
  dataset.getMetadata(function(err, metadata, apiResp) {
    if (err) {
      callback(err, null, apiResp);
      return;
    }

    var access = [].slice.call(arrify(metadata.access));

    access.push({
      role: 'WRITER',
      groupByEmail: '*****@*****.**'
    });

    dataset.setMetadata({
      access: access
    }, function(err, apiResp) {
      if (err) {
        callback(err, null, apiResp);
        return;
      }

      config.destination = format('{baseUrl}/projects/{pId}/datasets/{dId}', {
        baseUrl: 'bigquery.googleapis.com',
        pId: dataset.parent.projectId,
        dId: dataset.id
      });

      self.createSink(name, config, callback);
    });
  });
Example #11
0
  topic.iam.getPolicy(function(err, policy, apiResp) {
    if (err) {
      callback(err, null, apiResp);
      return;
    }

    policy.bindings = arrify(policy.bindings);

    policy.bindings.push({
      role: 'roles/pubsub.publisher',
      members: [
        'serviceAccount:cloud-logs@system.gserviceaccount.com'
      ]
    });

    topic.iam.setPolicy(policy, function(err, policy, apiResp) {
      if (err) {
        callback(err, null, apiResp);
        return;
      }

      config.destination = format('{baseUrl}/{topicName}', {
        baseUrl: 'pubsub.googleapis.com',
        topicName: topic.name
      });

      self.createSink(name, config, callback);
    });
  });
Example #12
0
Logging.prototype.getEntries = function(options, callback) {
  if (is.fn(options)) {
    callback = options;
    options = {};
  }

  var body = extend({
    orderBy: 'timestamp desc'
  }, options);
  body.projectIds = arrify(body.projectIds);
  body.projectIds.push(this.projectId);

  this.request({
    method: 'POST',
    uri: '/entries:list',
    json: body
  }, function(err, resp) {
    if (err) {
      callback(err, null, null, resp);
      return;
    }

    var nextQuery = null;

    if (resp.nextPageToken) {
      nextQuery = extend({}, body, {
        pageToken: resp.nextPageToken
      });
    }

    var entries = arrify(resp.entries).map(Entry.fromApiResponse_);

    callback(null, entries, nextQuery, resp);
  });
};
Example #13
0
IAM.prototype.testPermissions = function(permissions, callback) {
  if (!is.array(permissions) && !is.string(permissions)) {
    throw new Error('Permissions are required.');
  }

  permissions = arrify(permissions);

  var protoOpts = {
    service: 'IAMPolicy',
    method: 'testIamPermissions'
  };

  var reqOpts = {
    resource: this.id,
    permissions: permissions
  };

  this.request(protoOpts, reqOpts, function(err, resp) {
    if (err) {
      callback(err, null, resp);
      return;
    }

    var availablePermissions = arrify(resp.permissions);

    var permissionsHash = permissions.reduce(function(acc, permission) {
      acc[permission] = availablePermissions.indexOf(permission) > -1;
      return acc;
    }, {});

    callback(null, permissionsHash, resp);
  });
};
Example #14
0
/**
 * Service is a base class, meant to be inherited from by a "service," like
 * BigQuery or Storage.
 *
 * This handles making authenticated requests by exposing a `makeReq_` function.
 *
 * @constructor
 * @alias module:common/service
 *
 * @param {object} config - Configuration object.
 * @param {string} config.baseUrl - The base URL to make API requests to.
 * @param {string[]} config.scopes - The scopes required for the request.
 * @param {object} options - [Configuration object](#/docs).
 */
function Service(config, options) {
  var reqCfg = extend({}, config, {
    credentials: options.credentials,
    keyFile: options.keyFilename,
    email: options.email
  });

  this.makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory(reqCfg);
  this.authClient = this.makeAuthenticatedRequest.authClient;
  this.baseUrl = config.baseUrl;
  this.getCredentials = this.makeAuthenticatedRequest.getCredentials;
  this.globalInterceptors = arrify(options.interceptors_);
  this.interceptors = [];
  this.packageJson = config.packageJson;
  this.projectId = options.projectId || PROJECT_ID_TOKEN;
  this.projectIdRequired = config.projectIdRequired !== false;
  this.Promise = options.promise || Promise;

  var isCloudFunctionEnv = !!process.env.FUNCTION_NAME;

  if (isCloudFunctionEnv) {
    this.interceptors.push({
      request: function(reqOpts) {
        reqOpts.forever = false;
        return reqOpts;
      }
    });
  }
}
  this.activeRequest_ = this.request(protoOpts, reqOpts, function(err, resp) {
    self.activeRequest_ = null;

    if (err) {
      if (err.code === 504) {
        // Simulate a server timeout where no messages were received.
        resp = {
          receivedMessages: []
        };
      } else {
        callback(err, null, resp);
        return;
      }
    }

    var messages = arrify(resp.receivedMessages)
      .map(function(msg) {
        return Subscription.formatMessage_(msg, self.encoding);
      })
      .map(self.decorateMessage_.bind(self));

    self.refreshPausedStatus_();

    if (self.autoAck && messages.length !== 0) {
      var ackIds = messages.map(prop('ackId'));

      self.ack(ackIds, function(err) {
        callback(err, messages, resp);
      });
    } else {
      callback(null, messages, resp);
    }
  });
Example #16
0
FSWatcher.prototype.unwatch = function(paths) {
  if (this.closed) return this;
  paths = arrify(paths);

  paths.forEach(function(path) {
    if (this._closers[path]) {
      this._closers[path]();
      delete this._closers[path];
      this._getWatchedDir(sysPath.dirname(path)).remove(sysPath.basename(path));
    } else {
      //convert to absolute path
      path = sysPath.resolve(path);
      
      this._ignoredPaths[path] = true;
      if (path in this._watched) {
        this._ignoredPaths[path + '/**/*'] = true;
      }

      // reset the cached userIgnored anymatch fn
      // to make ignoredPaths changes effective
      this._userIgnored = null;
    }
  }, this);

  return this;
};
Example #17
0
 Request.prototype.use = function (fns) {
     for (var _i = 0, _a = arrify(fns); _i < _a.length; _i++) {
         var fn = _a[_i];
         this.middleware.push(fn);
     }
     return this;
 };
  transformations.forEach((transformation) => {
    const elem = (nsUri === undefined)
      ? doc.get(transformation.path)
      : doc.get(transformation.path, nsUri);
    const { isMandatory = true } = transformation;

    if (!(elem instanceof libxmljs.Element)) {
      if (isMandatory) {
        throw new PluginError(PLUGIN_NAME, `Can't find element at "${transformation.path}"`);
      }

      return;
    }

    if ({}.hasOwnProperty.call(transformation, 'text')) {
      elem.text(transformation.text);
    }

    const attrs = arrify(transformation.attrs || transformation.attr);
    attrs.forEach((attr) => {
      Object.keys(attr).forEach((key) => {
        const oldAttr = elem.attr(key);
        const oldVal = oldAttr && oldAttr.value();
        const val = stringOrNumber(attr[key], oldVal);
        elem.attr({ [key]: val });
      });
    });
  });
Example #19
0
Iam.prototype.testPermissions = function(permissions, callback) {
  if (!is.array(permissions) && !is.string(permissions)) {
    throw new Error('Permissions are required.');
  }

  permissions = arrify(permissions);

  this.request_({
    uri: '/iam/testPermissions',
    qs: {
      permissions: permissions
    },
    useQuerystring: true
  }, function(err, resp) {
    if (err) {
      callback(err, null, resp);
      return;
    }

    var availablePermissions = arrify(resp.permissions);

    var permissionsHash = permissions.reduce(function(acc, permission) {
      acc[permission] = availablePermissions.indexOf(permission) > -1;
      return acc;
    }, {});

    callback(null, permissionsHash, resp);
  });
};
Example #20
0
Translate.prototype.detect = function(input, callback) {
  input = arrify(input);

  this.request({
    uri: '/detect',
    useQuerystring: true,
    qs: {
      q: input
    }
  }, function(err, resp) {
    if (err) {
      callback(err, null, resp);
      return;
    }

    var results = resp.data.detections.map(function(detection, index) {
      var result = extend({}, detection[0], {
        input: input[index]
      });

      // Deprecated.
      delete result.isReliable;

      return result;
    });

    if (input.length === 1) {
      results = results[0];
    }

    callback(null, results, resp);
  });
};
Example #21
0
Fly.prototype.start = function (tasks, options) {
	tasks = arrify(tasks.length ? tasks : 'default')
	options = assign({
		parallel: false,
		value: null
	}, options || {})

	_('start %o in ' + (options.parallel ? 'parallel' : 'sequence'), tasks)

	var self = this
	var value = options.value

	return co.call(self, function * (tasks) {
		if (options.parallel) {
			yield tasks.map(function (task) {
				self.exec(task, value, Object.create(self))
			})
		} else {
			for (var task of tasks) {
				value = yield self.exec(task, value)
			}
		}
		return value
	}, [].concat(tasks).filter(function (task) {
		return Object.keys(self.host).indexOf(task) !== -1 || !self.emit('task_not_found', {task: task})
	}))
}
Example #22
0
      function decorateAnnotations(annotations) {
        for (var annotationType in annotations) {
          if (annotations.hasOwnProperty(annotationType)) {
            var annotationGroup = arrify(annotations[annotationType]);

            var formattedAnnotationGroup = annotationGroup
              .map(formatAnnotationBuilder(annotationType));

            // An annotation can be singular, e.g. SafeSearch. It is either
            // violent or not. Unlike face detection, where there can be
            // multiple results.
            //
            // Be sure the original type (object or array) is preserved and
            // not wrapped in an array if it wasn't originally.
            if (!is.array(annotations[annotationType])) {
              formattedAnnotationGroup = formattedAnnotationGroup[0];
            }

            delete annotations[annotationType];
            var typeShortName = typeRespNameToShortName[annotationType];
            annotations[typeShortName] = formattedAnnotationGroup;
          }
        }

        if (types.length === 1) {
          // Only a single detection type was asked for, so no need to box in
          // the results. Make them accessible without using a key.
          var key = Object.keys(annotations)[0];
          var errors = annotations.errors;
          annotations = annotations[key];
          annotations.errors = errors;
        }

        return annotations;
      }
Example #23
0
  this.request(protoOpts, reqOpts, function(err, resp) {
    if (err) {
      callback(err, null, null, resp);
      return;
    }

    var subscriptions = arrify(resp.subscriptions).map(function(sub) {
      // Depending on if we're using a subscriptions.list or
      // topics.subscriptions.list API endpoint, we will get back a
      // Subscription resource or just the name of the subscription.
      var subscriptionInstance = self.subscription(sub.name || sub);

      if (sub.name) {
        subscriptionInstance.metadata = sub;
      }

      return subscriptionInstance;
    });

    var nextQuery = null;

    if (resp.nextPageToken) {
      nextQuery = options;
      nextQuery.pageToken = resp.nextPageToken;
    }

    callback(null, subscriptions, nextQuery, resp);
  });
Example #24
0
  function createFlatMutationsList(entries) {
    entries = arrify(entries).map(function(entry) {
      return Mutation.parse(entry).mutations;
    });

    return flatten(entries);
  }
Example #25
0
function getMessage(first, ...rest) {
  if (isPlainObject(first) && first.message && first.ref) {
    return [...arrify(first.message), getLink(first.ref), ...rest]
  } else {
    return [first, ...rest]
  }
}
Example #26
0
Topic.prototype.publish = function(messages, callback) {
  messages = arrify(messages);

  if (messages.length === 0) {
    throw new Error('Cannot publish without a message.');
  }

  if (!messages.every(prop('data'))) {
    throw new Error('Cannot publish message without a `data` property.');
  }

  callback = callback || util.noop;

  var protoOpts = {
    service: 'Publisher',
    method: 'publish',
  };

  var reqOpts = {
    topic: this.name,
    messages: messages.map(Topic.formatMessage_)
  };

  this.request(protoOpts, reqOpts, function(err, result) {
    if (err) {
      callback(err, null, result);
      return;
    }

    callback(null, arrify(result.messageIds), result);
  });
};
Example #27
0
        function onEntity(entityDataFetched) {
            const entityData = arrify(entityDataFetched);

            if (ids.length === 1
                && (entityData.length === 0 || typeof entityData[0] === 'undefined' || entityData[0] === null)) {
                if (_this.gstore.config.errorOnEntityNotFound) {
                    return Promise.reject(new GstoreError(
                        errorCodes.ERR_ENTITY_NOT_FOUND,
                        `${_this.entityKind} { ${ids[0].toString()} } not found`
                    ));
                }

                return null;
            }

            const entity = entityData
                .map((data) => {
                    if (typeof data === 'undefined' || data === null) {
                        return null;
                    }
                    return _this.__model(data, null, null, null, data[_this.gstore.ds.KEY]);
                });

            if (Array.isArray(id)
              && options.preserveOrder
              && entity.every(e => typeof e !== 'undefined' && e !== null)) {
                entity.sort((a, b) => id.indexOf(a.entityKey.id) - id.indexOf(b.entityKey.id));
            }

            return Array.isArray(id) ? entity : entity[0];
        }
Subscription.prototype.ack = function(ackIds, callback) {
  var self = this;

  ackIds = arrify(ackIds);

  if (ackIds.length === 0) {
    throw new Error([
      'At least one ID must be specified before it can be acknowledged.'
    ].join(''));
  }

  callback = callback || util.noop;

  var protoOpts = {
    service: 'Subscriber',
    method: 'acknowledge'
  };

  var reqOpts = {
    subscription: this.name,
    ackIds: ackIds
  };

  this.request(protoOpts, reqOpts, function(err, resp) {
    if (!err) {
      ackIds.forEach(function(ackId) {
        delete self.inProgressAckIds[ackId];
      });

      self.refreshPausedStatus_();
    }

    callback(err, resp);
  });
};
Example #29
0
Vision.findImages_ = function(images, callback) {
  var MAX_PARALLEL_LIMIT = 5;
  images = arrify(images);

  function findImage(image, callback) {
    if (image instanceof File) {
      callback(null, {
        source: {
          gcsImageUri: format('gs://{bucketName}/{fileName}', {
            bucketName: image.bucket.name,
            fileName: image.name
          })
        }
      });

      return;
    }

    // File exists on disk.
    fs.readFile(image, { encoding: 'base64' }, function(err, contents) {
      if (err) {
        callback(err);
        return;
      }

      callback(null, { content: contents });
    });
  }

  async.mapLimit(images, MAX_PARALLEL_LIMIT, findImage, callback);
};
Example #30
0
Model.prototype.unset = function (keys = []) {
	if (!Array.isArray(keys) && typeof keys !== 'string') {
		throw new TypeError(`Expected \`keys\` to be string or array, not ${typeof keys}`);
	}

	this.store.dispatch(unset(arrify(keys)));
};