http://docs.couchdb.org/en/latest/api/server/common.html#post--_replicate
328767
function replicateDb (source, target, opts0, callback0) {
    const { opts, callback } = getCallback(opts0, callback0)

    // _replicate
    opts.source = _serializeAsUrl(source)
    opts.target = _serializeAsUrl(target)

    return relax({ db: '_replicate', body: opts, method: 'POST' }, callback)
  }
312215
def post_document(self, data):
    
    data.update({ 'client' : CLIENT })
    return self._call('POST', self._generate_url_path('documents'), data)
358350
def create(self, doc_details):

        '''
            
        '''
        
        # https://developer.couchbase.com/documentation/mobile/1.5/references/sync-gateway/admin-rest-api/index.html#/document/post__db___doc_

        title = '%s.create' % self.__class__.__name__

    # validate input
        if self.model:
            doc_details = self.model.validate(doc_details, path_to_root='', object_title='%s(doc_details={...}' % title)

    # define request fields
        from copy import deepcopy
        new_record = deepcopy(doc_details)
        url = self.bucket_url + '/'

    # send request and construct output
        response = requests.post(url, json=new_record)
        if response.status_code not in (200, 201):
            response = response.json()
            raise Exception('%s() error: %s' % (title, response))
        response = response.json()
        new_record['_id'] = response['id']
        new_record['_rev'] = response['rev']
    
        return new_record
1210750
function process_post(request, response, uri, body) {
	if (!authorised(request))
		return fail(401, "unauthorized", response);

	// be safe
	if (body === undefined)
		body = null;
		
	let path = URL.parse(request.url).pathname;

	// does path start with /things/thingID for some thingID?

	if (/^\/things\/.+/.test(path)) {
		path = path.substr(8);
		
		let i = path.indexOf('/');
		var thingID;
		
		if (i < 0) {
			thingID = path;
			path = "";
		} else {
			thingID = path.substr(0, i);
			path = path.substr(i);
		}
		
		if (thingID) {
			let thing = things[thingID];
			
			if (!thing)
				return fail(404, "unknown thing: " + thingID, response);
				
			// /things/thingID/properties to update all properties
			// /things/thingID/properties/propName to update given property
			
			if (path === "/properties") {
				// update properties from request body
				
				try {
					let values = JSON.parse(body);
					if (typeof values != 'object')
						return fail(555, "invalid data", response);
					
					// fail if any of the values are invalid or readonly
					for (var name in values) {
						if (values.hasOwnProperty(name)) {
							let value = values[name];
							let property = thing.properties[name];
							
							if (property === undefined)
								return fail(404, "unknown property name: " + name, response);

							if (property.meta) {
								if (property.meta.writable !== undefined  && !property.meta.writable)
									return fail(405, "read-only", response);
							
								if (invalid(value, property.meta, thing))
									return fail(400, "invalid data", response);
							}							
						}
					}
					
					// all values are good so update and notify
					for (var name in values) {
						if (values.hasOwnProperty(name)) {
							let value = values[name];
							let property = thing.properties[name];
							
							if (property != undefined) {
								property.value = value;
								
								// notify exposing app of external change
								if (property.handler)
									property.handler(value);
							}
						}
					}
					
					thing.emitState(values); // notify all clients
					// *** need to validate against model's data type ***
					// *** need to notify clients ***
					return succeed(204, "no data", response);
				} catch (err) {
					return fail(404, "invalid: " + body, response);
				}
			} else if (/^\/properties\/.+/.test(path)) {
				path = path.substr(12);
				console.log("property name: " + path);
				let property = thing.properties[path];
				
				if (property === undefined)
					return fail(404, "unknown property: " + path, response);
					
				console.log('parsing request body');
					
				// update named property from request body
				try {
					let value = JSON.parse(body);
					
					if (property.meta) {
						if (property.meta.writable !== undefined  && !property.meta.writable)
							return fail(405, "read-only", response);

						if (invalid(value, property.meta, thing)) {
							console.log('failed to set ' + path + ' to ' + value);
							return fail(400, "invalid data", response);
						}
					}

					property.value = value;
					
					// notify exposing app of external change
					if (property.handler)
						property.handler(value);
									
					console.log('setting ' + property.name + ' to ' + value);
					console.log('calling emitValue with path = ' + path + ' and value = ' + value);
					thing.emitValue(path, value);
					// *** need to validate against model's data type ***
					// *** need to notify clients ***
					console.log('succeeded in setting ' + property.name + ' to ' + property.value);
					return succeed(204, "no data", response);
				} catch (err) {
					console.log('failed to parse request body');
					return fail(404, "invalid: " + body, response);
				}
			}
			
			// /things/thingID/actions/actName to invoke given action (POST only)
			
			if (/^\/actions\/.+/.test(path)) {
				path = path.substr(9);
				//console.log("action name: " + path);
				
				let action = thing.actions[path];
				
				if (action === undefined)
					return fail(404, "unknown action: " + path, response);
					
				// *** need to validate input data against model's data type
				let input = null;
				
				//console.log(" input body is: " + JSON.stringify(body));
				
				if (body !== undefined) {
					try {
						input = JSON.parse(body);
					} catch (err) {
						return fail(404, "invalid: " + body, response);
					}
				}
				
				if (action.meta && action.meta.input && invalid(input, action.meta.input, thing))
					return fail(400, "invalid input", response);
					
				if (action.handler === undefined) {
					// succeed immediately as nothing to be done
					console.log('action ' + action.name + ' has no handler');
					return succeed(204, "no data", response);
				} else {
					//console.log('ready to invoke handler for action ' + action.name);
					// invoke handler and use promise to deliver response
					// after testing response against model's data type
					action.handler(input).then(output => {
						if (action.meta && action.meta.output && invalid(output, action.meta.output, thing)) {
							console.log(output + ' is invalid');
							return fail(400, "invalid output", response);
						}
						let body = JSON.stringify(output, null, 4);
						
						console.log('output body is ' + body);
						
						if (body === undefined) {
							console.log('body is undefined');
							response.writeHead(204, {
								'Content-Type': mime_types.json,
								'Pragma': 'no-cache',
								'Cache-Control': 'no-cache',
								'Access-Control-Allow-Origin': '*'
							});
						} else {
							response.writeHead(200, {
								'Content-Type': mime_types.json,
								'Pragma': 'no-cache',
								'Cache-Control': 'no-cache',
								'Access-Control-Allow-Origin': '*',
								'Content-Length': body.length
							});
							response.write(body);
						}
						
						response.end();
						return;
					}).catch(err => {
						console.log('handler failed: ' + err);
						return fail(500, "action failed: " + err, response);
					});
					
					return;  // deferred response
				}
			}
		}
		
		return fail(404, "missing thingID: " + uri.path, response);
	}
}
76399
protected void pullBulkWithAllDocs(final List<RevisionInternal> bulkRevs) {
        // http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API

        ++httpConnectionCount;
        final RevisionList remainingRevs = new RevisionList(bulkRevs);

        Collection<String> keys = CollectionUtils.transform(bulkRevs,
                new CollectionUtils.Functor<RevisionInternal, String>() {
                    public String invoke(RevisionInternal rev) {
                        return rev.getDocID();
                    }
                }
        );

        Map<String, Object> body = new HashMap<String, Object>();
        body.put("keys", keys);

        Future future = sendAsyncRequest("POST",
                "_all_docs?include_docs=true",
                body,
                new RemoteRequestCompletion() {

                    public void onCompletion(RemoteRequest remoteRequest, Response httpResponse, Object result, Throwable e) {

                        Map<String, Object> res = (Map<String, Object>) result;

                        if (e != null) {
                            setError(e);

                            // TODO: There is a known bug caused by the line below, which is
                            // TODO: causing testMockSinglePullCouchDb to fail when running on a Nexus5 device.
                            // TODO: (the batching behavior is different in that case)
                            // TODO: See https://github.com/couchbase/couchbase-lite-java-core/issues/271
                            // completedChangesCount.addAndGet(bulkRevs.size());

                        } else {
                            // Process the resulting rows' documents.
                            // We only add a document if it doesn't have attachments, and if its
                            // revID matches the one we asked for.
                            List<Map<String, Object>> rows = (List<Map<String, Object>>) res.get("rows");
                            Log.v(TAG, "%s checking %d bulk-fetched remote revisions", this, rows.size());
                            for (Map<String, Object> row : rows) {
                                Map<String, Object> doc = (Map<String, Object>) row.get("doc");
                                if (doc != null && doc.get("_attachments") == null) {
                                    RevisionInternal rev = new RevisionInternal(doc);
                                    RevisionInternal removedRev = remainingRevs.removeAndReturnRev(rev);
                                    if (removedRev != null) {
                                        rev.setSequence(removedRev.getSequence());
                                        queueDownloadedRevision(rev);
                                    }
                                } else {
                                    Status status = statusFromBulkDocsResponseItem(row);
                                    if (status.isError() && row.containsKey("key") && row.get("key") != null) {
                                        RevisionInternal rev = remainingRevs.revWithDocId((String) row.get("key"));
                                        if (rev != null) {
                                            remainingRevs.remove(rev);
                                            revisionFailed(rev, new CouchbaseLiteException(status));
                                        }
                                    }

                                }
                            }
                        }

                        // Any leftover revisions that didn't get matched will be fetched individually:
                        if (remainingRevs.size() > 0) {
                            Log.v(TAG,
                                    "%s bulk-fetch didn't work for %d of %d revs; getting individually",
                                    this, remainingRevs.size(), bulkRevs.size());
                            for (RevisionInternal rev : remainingRevs) {
                                queueRemoteRevision(rev);
                            }
                            pullRemoteRevisions();
                        }

                        --httpConnectionCount;
                        // Start another task if there are still revisions waiting to be pulled:
                        pullRemoteRevisions();
                    }
                });
        pendingFutures.add(future);
    }
316756
def replicate_from(other_db, continuous = false, create_target = false, doc_ids = nil)
      replicate(other_db, continuous, :target => name, :create_target => create_target, :doc_ids => doc_ids)
    end
884044
function pull (state, docsOrIds) {
  var pulledObjects = []
  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.replicate.from(remote, {
        doc_ids: docsOrIds
      })

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

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

      replication.on('change', function (change) {
        pulledObjects = pulledObjects.concat(change.docs)
        for (var i = 0; i < change.docs.length; i++) {
          state.emitter.emit('pull', change.docs[i])
        }
      })
    })
  })
}
153879
function processReconcile(field, toSet, setSep, reconcileSet) {
    // 
    if (reconcileSet) {
      reconcileSet.forEach(function(t) {
        var s = { uri: t.uri };
        s[toSet] = t.setVal;
        context.pubsub.item.save(s);
      });
      return;
    }
  }
292562
private void submitRevisions(final List<DocumentChange> changes) {
        synchronized (changesLock) {
            try {
                java.net.URI remoteUri = remote.toURI();
                for (DocumentChange change : changes) {
                    // Skip revisions that originally came from the database I'm syncing to:
                    URL source = change.getSource();
                    if (source != null && source.toURI().equals(remoteUri))
                        continue;
                    RevisionInternal rev = change.getAddedRevision();
                    if (rev == null)
                        continue;
                    if (getLocalDatabase().runFilter(filter, filterParams, rev)) {
                        if (doneBeginReplicating) {
                            pauseOrResume();
                            waitIfPaused();
                            // if not running state anymore, exit from loop.
                            if (!isRunning())
                                break;
                            RevisionInternal nuRev = rev.copyWithoutBody();
                            addToInbox(nuRev);
                        } else {
                            RevisionInternal nuRev = rev.copyWithoutBody();
                            queueChanges.add(nuRev);
                        }
                    }
                }
            } catch (java.net.URISyntaxException uriException) {
                // Not possible since it would not be an active replicator.
                // However, until we refactor everything to use java.net,
                // I'm not sure we have a choice but to swallow this.
                Log.e(TAG, "Active replicator found with invalid URI", uriException);
            }
        }
    }
321685
def replicate(self):
        """"""
        return np.sum(
            self.proxies[self.window :] * self._xs[:-1], axis=1
        ).reindex(self.r.index)
1347703
function(operation, res) {
      var that = this;
      var method = res.req.method;

      return operation.then(function(doc) {
        if (method === 'POST') {
          if (that._path && (that._key || that._index)) {
            res.header('Location', '/' + that._path + '/' + doc[that._key || that._index]);
          }

          return res.status(201).json(doc);
        }

        return res.status(200).json(doc);
      }, function(err) {
        console.error(err.message);

        if (method === 'POST' || method === 'PUT') {
          return res.status(409).end();
        }

        if (method === 'GET') {
          res.status(404).end();
        }

        return res.status(500).end();
      });
    }
1344601
function putRouteFromDB(req, res) {
  expectJSON(function () {
    return db.put(req.uri, JSON.stringify(req.body)).then(() => req.body);
  }, res);
}
239149
function push (state, docsOrIds) {
  var pushedObjects = []
  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.replicate.to(remote, {
        create_target: true,
        doc_ids: docsOrIds,
        include_docs: true
      })

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

      replication.on('complete', function () {
        resolve(pushedObjects)
      })
      replication.on('error', reject)
      replication.on('change', function (change) {
        pushedObjects = pushedObjects.concat(change.docs)

        for (var i = 0; i < change.docs.length; i++) {
          state.emitter.emit('push', change.docs[i])
        }
      })
    })
  })
}
778660
function updateDocument(existingDoc, newDoc, id, db, f_ShouldUpdate, shouldCreate, f_Merge, callback) {
    if (!f_ShouldUpdate) {
        f_ShouldUpdate = always;
    }

    if (!f_Merge) {
        f_Merge = useNewVersion;
    }

    // If we never grabbed the existing document from the DB, fetch it and try again.
    if (!existingDoc) {
        return db.get(id, function (err, r) {
            // If the fetch came back with nothing, attempt to do a fresh insert unless the user
            // doesn't want documents to be created.
            if (err && (err.error === "not_found")) {
                if (!shouldCreate)
                    // Don't create a document where one didn't exist, if the user so desires.
                    return callback(null, null);

                return db.insert(newDoc, id, function (err, r) {
                    // If someone beat us here, we should retry this whole operation.
                    if (err && err.error === "conflict")
                        return updateDocument(null, newDoc, id, db, f_ShouldUpdate, shouldCreate, f_Merge, callback);

                    // If anything else happened, we should bail.
                    if (err)
                        return callback("Could not fetch existing document: " + err.toString());

                    // The insert worked.  We're done.
                    return callback(null, extend({}, newDoc, {_rev: r.rev}));
                });
            }

            // If the fetch came back with any other error, bail.
            if (err)
                return callback("Could not fetch existing document: " + err.toString());

            // We got the document.  Let's try the update again.
            return updateDocument(r, newDoc, id, db, f_ShouldUpdate, shouldCreate, f_Merge, callback);
        });
    }

    if (!f_ShouldUpdate(existingDoc, newDoc)) {
        return callback(null, existingDoc);
    }

    // Before merging, record that we want to undelete a document that has been deleted.
    var mergedDoc = f_Merge(omit(existingDoc, "_deleted"), newDoc);
    if (!mergedDoc || typeof mergedDoc !== "object" || mergedDoc instanceof Error) {
        // Allow a user defined merge algorithm to say ``sorry...can't merge'' by returning a non-object or Error.
        // Bubble this error, so that the user can then test for it in their callback.
        return callback(mergedDoc);
    }

    // It's essential that we specify a revision or this will never terminate.
    // It's probably not a good idea to trust a user-specified merge function to do this.
    mergedDoc = extend({}, mergedDoc, { _rev: existingDoc._rev });

    // The document exists, and is out of date.  We need to overwrite it.
    db.insert(
        mergedDoc,
        id,
        function (err, result) {
            // If someone beat us here, we need to try the whole thing again.
            if (err && err.error === "conflict")
                return updateDocument(null, newDoc, id, db, f_ShouldUpdate, shouldCreate, f_Merge, callback);

            // If anything else happened, bail.
            if (err)
                return callback("Could not update the document to the proposed version: " + err.toString());

            // Update the new document's _rev
            mergedDoc._rev = result.rev;

            // The replacement worked.  We're done.  Finally!
            return callback(null, mergedDoc);
        }
    );
}
876136
def save(self, data):
        """"""
        if not self.is_connected:
            raise Exception("No database selected")
        if not data:
            return False
        if isinstance(data, dict):
            doc = couchdb.Document()
            doc.update(data)
            self.db.create(doc)
        elif isinstance(data, couchdb.Document):
            self.db.update(data)
        elif isinstance(data, list):
            self.db.update(data)
        return True
1370638
function (item) {
        /* istanbul ignore if */
        // The persistence service should always be set before calling this method.
        // This check is an additional precaution.
        if (!__private.provider) {
            log.error('Unable to perform remote operation. The persistence service has not been set');
            return;
        }

        if (item.value instanceof Array) {
            item.value.forEach(function (e) {
                updateRemoteItem(e);
            });
        } else if (item !== undefined && item.type !== undefined) {
            const url = __private.provider + '/' + appName + '/' + _convertKey(item.key);
            if (item.value === undefined) {
                request.delete(url, _handleRequestError);
            } else {
                request.post(url, {
                    headers: { 'Content-Type': Constants.HTTP_CONTENT_TYPE_JSON },
                    json: { value: item.value, type: item.type, timestamp: item.timestamp }
                }, _handleRequestError);
            }
        }
    }
512937
function queryReplication (id, opts0, callback0) {
    const { opts, callback } = getCallback(opts0, callback0)
    return relax({ db: '_replicator', method: 'GET', path: id, qs: opts }, callback)
  }