Process a whole group of saves

@param  {Array} ops
@param  {Boolean} testCacheEnabled used for tests
@return {Promise}
760788
function batch(ops, testCacheEnabled) {
  const cacheEnabled = testCacheEnabled || CACHE_ENABLED;

  return postgres.batch(ops)
    .then((res) => {
      if (cacheEnabled) {
        return redis.batch(ops).then(() => res);
      }

      return res;
    });
}
426192
async function waitForOperationSucceeded(config, result) {
    let count = 0;
    while (true) {
        let opResult = await new Operations().getOperationDetails({
            subscriptionKey: config.subscriptionKey,
            operationId: result.operationId
        });

        if (opResult.error)
            throw new Error(JSON.stringify(opResult.error, null, 4));

        result = await opResult.json();
        process.stderr.write(`'\r${result.operationState}`);
        count++;
        for (let x = 0; x < count; x++)
            process.stderr.write(`.`);
        process.stderr.write('              ');

        if (result.operationState === 'Failed')
            throw new Error(JSON.stringify(result, null, 4));

        if (result.operationState === 'Succeeded')
            break;
        await Delay(1000);
    }
    process.stderr.write('done\n');
    return result;
}
819662
function save(options) {
    const self = this
    options = options || {}

    if (self.options.polymorph) return this.callParent(options)

    return Promise.all(
      this.map(function(record) {
        // validate all records at once.
        return record.validate()
      })
    )
      .then(function() {
        // if validation succeeded, start the transaction
        return self.store.startTransaction(options, function() {
          return self
            ._runLazyOperation(options)
            .then(function() {
              // inside the transaction create all new records and afterwards save all the others
              return self._create(options)
            })
            .then(function() {
              // will save all existing records with changes...
              return self.callParent(options, save)
            })
        })
      })
      .then(function() {
        return self
      })
  }
203478
function buildAsyncSaveFun(_this, _oldSave, _promise, _oldPromise) {
    return function() {

      // swap promises so save behaves like it has been called during the original call.
      var currentPromise = _this.$promise;
      _this.$promise = _oldPromise;

      // when save resolves, the timeout promise is resolved and the last resource promise returned
      // so it behaves
      _oldSave.call(_this).$promise.then(
        function(_data) {
          _promise.resolve(_data);
          _this.$promise = currentPromise;
        }, function(_reason) {
          _promise.reject(_reason);
          _this.$promise = currentPromise;
        }
      );

      _this.$dmStatus = null;
    };
  }
1204647
function defaultWorkflow(opts) {
  var tasks;
  var paths;
  var runnableTasks;
  var runnablePaths;

  return execP('git status')
    .then(function() {
      return getUnchanged(opts.globs);
    })
    .spread(function(a, b) {
      tasks = a;
      paths = b;
      console.log(
        'Executing: ' + '`git stash && git add . && git stash`.\n'.italic
      );
      return gitCmds.safeStashAll();
    })
    .then(function() {
      console.log(
        'Repo reverted to clean state. Looking at previous screenshots...\n'
      );
      console.log(
        'If anything goes wrong'.bold + ', simply run ' +
        '`git stash pop && git reset HEAD . && git stash pop --index` '.italic +
        'to restore your changes.'
      );
      // TODO: not good enough. Warn earlier about no task. Before stash
      var res = filterRunnables(tasks, paths, opts.taskName);
      runnableTasks = res[0];
      runnablePaths = res[1];

      return runTasks(writeScreenshots, opts, runnableTasks, runnablePaths);
    })
    .catch(function(e) {
      if (e.name === 'OperationalError' &&
          e.message.indexOf('Not a git repository') > -1) {
        return Promise.reject(new Error(notGitMsg));
      }

      return gitCmds
        .safeUnstashAll()
        .then(function() {
          return Promise.reject(e);
        });
    })
    .then(function() {
      console.log(
        'Executing: ' +
        '`git stash pop && git reset HEAD . && git stash pop --index`.\n'.italic
      );
      return gitCmds.safeUnstashAll();
    })
    .then(function() {
      console.log(
        'Repo back to modified state. Getting new screenshots and comparing ' +
        'them with previously recorded ones...\n'
      );
      return runTasks(compareScreenshots, opts, runnableTasks, runnablePaths);
    })
    .then(function() {
      return Promise.map(paths, function(dir, i) {
        return Promise.map(tasks[i], function(task) {
          var p = path.join(
            dir,
            consts.HUXLEY_FOLDER_NAME,
            task.name + consts.TASK_FOLDER_SUFFIX
          );
          return removeDirIfOk(p);
        });
      });
    });
}
463028
function done() {
  	var storage = config.storage;

  	ProcessingQueue.finished = true;

  	var runtime = now() - config.started;
  	var passed = config.stats.all - config.stats.bad;

  	emit("runEnd", globalSuite.end(true));
  	runLoggingCallbacks("done", {
  		passed: passed,
  		failed: config.stats.bad,
  		total: config.stats.all,
  		runtime: runtime
  	});

  	// Clear own storage items if all tests passed
  	if (storage && config.stats.bad === 0) {
  		for (var i = storage.length - 1; i >= 0; i--) {
  			var key = storage.key(i);

  			if (key.indexOf("qunit-test-") === 0) {
  				storage.removeItem(key);
  			}
  		}
  	}
  }
1201684
function (fn, repeatTest = 0, args = []) {
    /**
     * if a new hook gets executed we can assume that all commands should have finised
     * with exception of timeouts where `commandIsRunning` will never be reset but here
     */
    // commandIsRunning = false

    return new Promise((resolve, reject) => {
        try {
            const res = fn.apply(this, args)
            resolve(res)
        } catch (e) {
            if (repeatTest) {
                return resolve(executeSync(fn, --repeatTest, args))
            }

            /**
             * no need to modify stack if no stack available
             */
            if (!e.stack) {
                return reject(e)
            }

            e.stack = e.stack.split('\n').filter(STACKTRACE_FILTER_FN).join('\n')
            reject(e)
        }
    })
}
221447
function initCache (cachePath) {
    return new Promise(function (resolve, reject) {
      mkdirp(cachePath, function (err) {
        if (err) {
          reject(err)
        } else {
          resolve()
        }
      })
    })
  }
256167
@Override
	protected void doProcessQueuedOps(PersistentCollection collection, Serializable key, int nextIndex, SharedSessionContractImplementor session)
			throws HibernateException {
		// nothing to do
	}
70702
private void processNewOperation(StorageOperation operation) {
        if (operation instanceof MergeSegmentOperation) {
            this.operations.add(operation);
            this.mergeTransactionCount.incrementAndGet();
        } else if (operation instanceof StreamSegmentSealOperation) {
            this.operations.add(operation);
            this.hasSealPending.set(true);
        } else if (operation instanceof StreamSegmentTruncateOperation) {
            this.operations.add(operation);
            this.truncateCount.incrementAndGet();
        } else if (operation instanceof CachedStreamSegmentAppendOperation) {
            // Aggregate the Append Operation.
            AggregatedAppendOperation aggregatedAppend = getOrCreateAggregatedAppend(
                    operation.getStreamSegmentOffset(), operation.getSequenceNumber());
            aggregateAppendOperation((CachedStreamSegmentAppendOperation) operation, aggregatedAppend);
        }
    }
262126
function (collectionKey, queryKey) {
  return new Promise(function (ok) {
    redisClient.multi().get(collectionKey).get(queryKey).exec(function (err, results) {
      if (err) {
        err.message = util.format('mongoose cache error %s', queryKey);
        debug(err);
        ok([null, null]); // ignore error, instead reject
        //return error(err);
      }

      var collectionData = results[0] && JSON.parse(results[0]),
        queryData = results[1] && JSON.parse(results[1]);
      //debug('redis cache object size', queryKey, helpers.getObjectSize(queryData));

      // special cache miss where it is out of date
      if (queryData && collectionData && collectionData.lastWrite > queryData.metadata.lastWrite) {
        debug('mongoose cache out of date: ', queryKey);
        queryData = null;
      }
      ok([collectionData, queryData]);
    });
  });
}
627780
function batchLoop(){
                var promisesArray = createBatchJobs();

                Q[qFunction](promisesArray).then(function(batchResult){
                    if(qFunction === "allSettled"){
                      batchResult = batchResult.filter(function(res){return res.state === "fulfilled"}).map(function(item){return item.value;})
                    }

                    results = results.concat(batchResult);
                    //these are upserted, let's check the next ones
                    if(!disableLogs) {
                        console.log("This squad is done, " + dataCopy.length + " items remaining");
                    }
                    if(dataCopy.length == 0){
                        if(!disableLogs){
                            console.log("Finished the batch loop");
                        }
                        deferred.resolve(results);
                    }else{
                        batchLoop();
                    }
                }).catch(function(e){
                    if(!disableLogs) {
                        console.error(e);
                    }
                    deferred.reject(results);
                });
            }
618152
function(fromSuite, toSuite) {
      each(fromSuite.specs, function(spec){
        spec.assertions = []
        toSuite.specs.push(spec)
      })
    }
323412
function () {
            var result = new $.Deferred();
            this.storage.load()
                .then(function (data) {
                    var oldKeys = this.getKeys();
                    this.data = data;
                    result.resolve();
                    this.trigger(PREFERENCE_CHANGE, {
                        ids: _.union(this.getKeys(), oldKeys)
                    });
                }.bind(this))
                .fail(function (error) {
                    result.reject(error);
                });
            return result.promise();
        }
207320
async function (events) {
    const oThis = this
      , promiseArray = []
    ;

    // nothing to do
    if (!events || events.length === 0) {
      oThis.updateIntercomDataFile();
      return Promise.resolve();
    }

    //TODO: last processed transaction index.
    for (var i = 0; i < events.length; i++) {
      const eventObj = events[i]
        , j = i
      ;

      // await oThis.processEventObj(eventObj);

      if (oThis.parallelProcessingAllowed()) {
        promiseArray.push(new Promise(function (onResolve, onReject) {
          setTimeout(function () {
            oThis.processEventObj(eventObj)
              .then(onResolve)
              .catch(function (error) {
                logger.error('##### inside catch block #####: ', error);
                return onResolve();
              });
          }, (j * 1000 + 100));
        }));
      } else {
        await oThis.processEventObj(eventObj)
          .catch(function (error) {
            logger.error('inside catch block: ', error);
            return Promise.resolve();
          });
      }
    }

    if (oThis.parallelProcessingAllowed()) {
      await Promise.all(promiseArray);
    }

    oThis.updateIntercomDataFile();
    return Promise.resolve();
  }
52344
function onInstall(event) {
  const preCacheApplication = async () => {
    const cache = await caches.open(CACHE_NAME);
    // Fetching these with addAll fails for CORS-restricted content, so we use
    // fetchAndCache with no-cors mode to work around it.

    // Optional resources: failure on these will NOT fail the Promise chain.
    // We will also not wait for them to be installed.
    for (const url of OPTIONAL_RESOURCES) {
      const request = new Request(url, {mode: 'no-cors'});
      fetchAndCache(cache, request).catch(() => {});
    }

    // Critical resources: failure on these will fail the Promise chain.
    // The installation will not be complete until these are all cached.
    const criticalFetches = [];
    for (const url of CRITICAL_RESOURCES) {
      const request = new Request(url, {mode: 'no-cors'});
      criticalFetches.push(fetchAndCache(cache, request));
    }
    return Promise.all(criticalFetches);
  };

  event.waitUntil(preCacheApplication());
}
197820
function deps(entries, i, opts) {
    var e = entries[i];
    var fullPaths = R.map(R.applyLeft(path.resolve, opts.basedir || process.cwd()), [].concat(e.entry));
    var b = opts.browserify(fullPaths, cleanOpts(opts));
    return sort(fromStream(b.deps(opts)))
        .do(function (row) {
            if (!opts.cache[row.id]) {
                opts.cache[row.id] = row;
            }
        })
        .map(R.mixin({ level: e.level }))
        .toArray()
        .flatMap(function (rows) {
            var r = Rx.Observable.fromArray(rows);
            return i + 1 < entries.length
                ? r.concat(deps(entries, i + 1, opts))
                : r;
        });
}