syncs one or multiple objects between local and remote database

@param  {StringOrObject} docsOrIds   object or ID of object or array of objects/ids (all optional)
@return {Promise}
771911
function sync (state, docsOrIds) {
  var syncedObjects = []
  var errors = state.db.constructor.Errors

  return Promise.resolve(state.remote)

  .then(function (remote) {
    return new Promise(function (resolve, reject) {
      if (Array.isArray(docsOrIds)) {
        docsOrIds = docsOrIds.map(toId)
      } else {
        docsOrIds = docsOrIds && [toId(docsOrIds)]
      }

      if (docsOrIds && docsOrIds.filter(Boolean).length !== docsOrIds.length) {
        return Promise.reject(errors.NOT_AN_OBJECT)
      }

      var replication = state.db.sync(remote, {
        doc_ids: docsOrIds,
        include_docs: true
      })

      /* istanbul ignore next */
      replication.catch(function () {
        // handled trough 'error' event
      })

      replication.on('complete', function () {
        resolve(syncedObjects)
      })
      replication.on('error', reject)

      replication.on('change', function (change) {
        syncedObjects = syncedObjects.concat(change.change.docs)

        for (var i = 0; i < change.change.docs.length; i++) {
          state.emitter.emit(change.direction, change.change.docs[i])
        }
      })
    })
  })
}
905280
function (translationIds) {
          var results = {}; // storing the actual results
          var promises = []; // promises to wait for
          // Wraps the promise a) being always resolved and b) storing the link id->value
          var translate = function (translationId) {
            var deferred = $q.defer();
            var regardless = function (value) {
              results[translationId] = value;
              deferred.resolve([translationId, value]);
            };
            // we don't care whether the promise was resolved or rejected; just store the values
            $translate(translationId, interpolateParams, interpolationId, defaultTranslationText, forceLanguage, sanitizeStrategy).then(regardless, regardless);
            return deferred.promise;
          };
          for (var i = 0, c = translationIds.length; i < c; i++) {
            promises.push(translate(translationIds[i]));
          }
          // wait for all (including storing to results)
          return $q.all(promises).then(function () {
            // return the results
            return results;
          });
        }
1005078
function(cursor, callback) {
    groupedDelta = {};

    async.series([
      (cb) => {
        logger.info('Fetching delta', {category: 'sync-remote-delta'});

        fetchDelta({cursor}, (err, newCursor) => {
          if(err) return cb(err);

          cb(null, newCursor);
        });
      },
      (cb) => {
        logger.info('Applying collections which need to be redownloaded', {category: 'sync-remote-delta'});

        syncDb.find({$and: [{directory: true}, {downloadOriginal: true}]}, (err, syncedNodes) => {
          if(err) return cb(err);
          if(!syncedNodes) return cb(null);

          async.map(syncedNodes, (syncedNode, mapCb) => {
            if(!syncedNode.remoteId) mapCb(null);

            fetchDelta({id: syncedNode.remoteId}, mapCb);
          }, cb);
        });
      }
    ], (err, results) => {
      logger.info('getDelta ended', {category: 'sync-remote-delta'});

      callback(err, results[0]);
    });
  }
859652
function connect (state) {
  return Promise.resolve(state.remote)

  .then(function (remote) {
    if (state.replication) {
      return
    }

    state.replication = state.db.sync(remote, {
      create_target: true,
      live: true,
      retry: true
    })

    state.replication.on('error', function (error) {
      state.emitter.emit('error', error)
    })

    state.replication.on('change', function (change) {
      for (var i = 0; i < change.change.docs.length; i++) {
        state.emitter.emit(change.direction, change.change.docs[i])
      }
    })

    state.emitter.emit('connect')
  })
}
54721
function(req, res, fromMessage) {
            var name = req.params.name;
            var doc  = req.body;
            var id   = this.toId(req.params.id || doc._id);
            if (typeof id === 'undefined' || id === '') {
                return res.send(400, "invalid id.");
            }
            doc._id   = id;
            doc._time = new Date().getTime();
            var collection = new mongodb.Collection(this.db, name);
            collection.update(
                { "_id" : id },
                doc,
                { safe:true, upsert:true },
                function(err, n) {
                    if(err) {
                        res.send("Oops!: " + err);
                    } else {
                        if (n==0) {
                            res.send(404, 'Document not found!');
                        } else {
                            var msg = {
                                method: 'update',
                                id: doc._id,
                                time: doc._time,
                                data: doc
                            };
                            rest.onSuccess(name, msg, fromMessage);
                            res.send(doc);
                        }
                    }
                }
            );
        }
32294
function updateNode(node, callback) {
  syncDb.update(node._id, node, (err, result) => {
    if(err) return callback(err);

    callback(null, node);
  });
}
467215
function getDocs(src, target, diffs, state) {
  diffs = pouchdbUtils.clone(diffs); // we do not need to modify this

  var resultDocs = [],
      ok = true;

  function getAllDocs() {

    var bulkGetOpts = createBulkGetOpts(diffs);

    if (!bulkGetOpts.docs.length) { // optimization: skip empty requests
      return;
    }

    return src.bulkGet(bulkGetOpts).then(function (bulkGetResponse) {
      /* istanbul ignore if */
      if (state.cancelled) {
        throw new Error('cancelled');
      }
      return Promise.all(bulkGetResponse.results.map(function (bulkGetInfo) {
        return Promise.all(bulkGetInfo.docs.map(function (doc) {
          var remoteDoc = doc.ok;

          if (doc.error) {
            // when AUTO_COMPACTION is set, docs can be returned which look
            // like this: {"missing":"1-7c3ac256b693c462af8442f992b83696"}
            ok = false;
          }

          if (!remoteDoc || !remoteDoc._attachments) {
            return remoteDoc;
          }

          return getDocAttachmentsFromTargetOrSource(target, src, remoteDoc)
                   .then(function (attachments) {
                           var filenames = Object.keys(remoteDoc._attachments);
                           attachments
                             .forEach(function (attachment, i) {
                                        var att = remoteDoc._attachments[filenames[i]];
                                        delete att.stub;
                                        delete att.length;
                                        att.data = attachment;
                                      });

                                      return remoteDoc;
                                    });
        }));
      }))

      .then(function (results) {
        resultDocs = resultDocs.concat(pouchdbUtils.flatten(results).filter(Boolean));
      });
    });
  }

  function hasAttachments(doc) {
    return doc._attachments && Object.keys(doc._attachments).length > 0;
  }

  function hasConflicts(doc) {
    return doc._conflicts && doc._conflicts.length > 0;
  }

  function fetchRevisionOneDocs(ids) {
    // Optimization: fetch gen-1 docs and attachments in
    // a single request using _all_docs
    return src.allDocs({
      keys: ids,
      include_docs: true,
      conflicts: true
    }).then(function (res) {
      if (state.cancelled) {
        throw new Error('cancelled');
      }
      res.rows.forEach(function (row) {
        if (row.deleted || !row.doc || !isGenOne(row.value.rev) ||
            hasAttachments(row.doc) || hasConflicts(row.doc)) {
          // if any of these conditions apply, we need to fetch using get()
          return;
        }

        // strip _conflicts array to appease CSG (#5793)
        /* istanbul ignore if */
        if (row.doc._conflicts) {
          delete row.doc._conflicts;
        }

        // the doc we got back from allDocs() is sufficient
        resultDocs.push(row.doc);
        delete diffs[row.id];
      });
    });
  }

  function getRevisionOneDocs() {
    // filter out the generation 1 docs and get them
    // leaving the non-generation one docs to be got otherwise
    var ids = Object.keys(diffs).filter(function (id) {
      var missing = diffs[id].missing;
      return missing.length === 1 && isGenOne(missing[0]);
    });
    if (ids.length > 0) {
      return fetchRevisionOneDocs(ids);
    }
  }

  function returnResult() {
    return { ok:ok, docs:resultDocs };
  }

  return Promise.resolve()
    .then(getRevisionOneDocs)
    .then(getAllDocs)
    .then(returnResult);
}
1073099
function getHeroes(req, res) {
  const docquery = Hero.find({}).read(ReadPreference.NEAREST);
  docquery
    .exec()
    .then(heroes => res.status(200).json(heroes))
    .catch(error => res.status(500).send(error));
}
50931
def sync(self, localpath, href, exclude=None, block=True):
        
        logger.info(u("sync: %s %s") % (localpath, href))
        try:
            localpath = _(localpath)
            href = remote(href)
            localRoot, localFolders, localFiles = next(os.walk(localpath))
            remoteFolders, remoteFiles = self.list(href)
            if remoteFiles is None or remoteFolders is None:
                remoteFiles = {}
                remoteFolders = {}
                self.mkdir(href)

            def norm(folder):
                path = os.path.join(href, _(folder))
                if path[len(path) - 1] != os.path.sep:
                    path += u("/")
                return path

            foldersToCreate = filter(
                lambda folderPath: folderPath not in remoteFolders,
                map(norm, localFolders)
            )
            apply_async("mkdir", lambda path: self.mkdir(path), foldersToCreate, self.limit)

            filesToSync = filter(
                lambda lFile: os.path.join(href, _(lFile)) not in remoteFiles,
                localFiles
            )
            fileArgs = [(os.path.join(localpath, f), os.path.join(href, f))
                        for f in filesToSync]
            apply_async("upload", lambda s, t: self.upload(s, t), fileArgs, self.limit)

            for folder in localFolders:
                localFolderPath = os.path.join(localpath, folder)
                remoteFolderPath = os.path.join(href, folder)
                if exclude:
                    bSync = exclude(localFolderPath, remoteFolderPath)
                else:
                    bSync = True
                if bSync:
                    apply_async(
                        "sync",
                        lambda localpath, href: self.sync(localpath, href, exclude, False),
                        [(localFolderPath, remoteFolderPath), ]
                    )
        except ConnectionException:
            raise
        except Exception:
            e = sys.exc_info()[1]
            logger.exception(e)
        if block:
            qWork.join()
939132
function getDocument(document, docdbClient, nodeContext) {
    var documentUrl = `${collectionUrl}/docs/${document.id}`;
    nodeContext.log(`Getting document:\n${document.id}\n`);

    return new Promise((resolve, reject) => {
        nodeContext.log("trying read");
        docdbClient.readDocument(documentUrl, (err, result) => {
            nodeContext.log("reading");
            if (err) {
                nodeContext.log("error");
                if (err.code == HttpStatusCodes.NOTFOUND) {
                    nodeContext.log("creating");
                    docdbClient.createDocument(collectionUrl, document, (err, created) => {
                        nodeContext.log("try to create");
                        if (err) reject(err)
                        else resolve(created);
                    });
                } else {
                    reject(err);
                }
            } else {
                resolve(result);
            }
        });
    });
}
446305
function sync(collection, newCollection, index) {
        if (index === void 0) { index = 'id'; }
        var answer = removeElements(collection, newCollection, index);
        if (newCollection) {
            newCollection.forEach(function (item) {
                var oldItem = _.find(collection, function (c) { return c[index] === item[index]; });
                if (!oldItem) {
                    answer = true;
                    collection.push(item);
                }
                else {
                    if (item !== oldItem) {
                        angular.copy(item, oldItem);
                        answer = true;
                    }
                }
            });
        }
        return answer;
    }
365853
function sync(method, collection, options, query) {
      //
      // Method and or collection was not provided, set default arguments.
      // Additionally default to CREATE if the method is not a string.
      //
      if (!(collection instanceof backbone.Collection)) {
        if ('string' !== typeof method) {
          options = method;
          method = 'create';
        } else {
          options = collection;
        }

        collection = this;
      }

      options = options || {};

      if ('create' === method) {
        if (collection.any(function anyStored(model) { return model.stored; })) method = 'update';
        if (collection.any(function anyNew(model) { return !model.stored; })) options.upsert = true;
      }

      return backbone.sync(method, collection, options, query);
    }
1017229
function(options) {
      options = options ? _.extend({}, options) : {};
      if (options.parse === void 0) options.parse = true;
      var success = options.success;
      var collection = this;
      options.success = function(resp) {
        var method = options.reset ? 'reset' : 'set';
        collection[method](resp, options);
        if (success) success(collection, resp, options);
        collection.trigger('sync', collection, resp, options);
      };
      wrapError(this, options);
      return this.sync('read', this, options);
    }
296702
function updateCollection(id, collID, collObj) {
  return updateItem(id, item => {
    const pos = item.dataset.findIndex(e => e.collectionID === collID);
    if (_.isFunction(collObj)) {
      collObj(item.dataset[pos]);
    } else {
      item.dataset[pos] = collObj;
    }
  });
}
348823
function updateItem(id, updater) {
  return new Promise((resolve, reject) => {
    return instance.pkgs.then(db => {
      const obj = db.transaction(db.name, 'readwrite')
        .objectStore(db.name);
      const req = obj.get(id);
      req.onerror = event => reject(event);
      req.onsuccess = event => {
        const res = event.target.result;
        updater(res);
        const upd = obj.put(res);
        upd.onsuccess = () => resolve();
        upd.onerror = event => reject(event);
      };
    });
  });
}
769555
function refreshSyncers(keys) {
	if (typeof keys === 'string') {
		keys = [keys]
	}
	if (!keys) {
		keys = Object.keys(this._syncers)
	}
	return Promise.all(keys.map(key => {
		return this._syncers[key].refresh()
	}))
}
1187158
function _syncWithFileSystem() {
        _mrofList = _mrofList.filter(function (e) {return e; });
        return Async.doSequentially(_mrofList, _checkExt, false);
    }