Builds a populated AppendEntries request.
482877
@SuppressWarnings("unchecked")
  protected AppendRequest buildAppendEntriesRequest(RaftMemberContext member, long lastIndex) {
    final RaftLogReader reader = member.getLogReader();

    final Indexed<RaftLogEntry> prevEntry = reader.getCurrentEntry();

    final DefaultRaftMember leader = raft.getLeader();
    AppendRequest.Builder builder = AppendRequest.builder()
        .withTerm(raft.getTerm())
        .withLeader(leader != null ? leader.memberId() : null)
        .withPrevLogIndex(prevEntry != null ? prevEntry.index() : reader.getFirstIndex() - 1)
        .withPrevLogTerm(prevEntry != null ? prevEntry.entry().term() : 0)
        .withCommitIndex(raft.getCommitIndex());

    // Build a list of entries to send to the member.
    final List<RaftLogEntry> entries = new ArrayList<>();

    // Build a list of entries up to the MAX_BATCH_SIZE. Note that entries in the log may
    // be null if they've been compacted and the member to which we're sending entries is just
    // joining the cluster or is otherwise far behind. Null entries are simply skipped and not
    // counted towards the size of the batch.
    // If there exists an entry in the log with size >= MAX_BATCH_SIZE the logic ensures that
    // entry will be sent in a batch of size one
    int size = 0;

    // Iterate through the log until the last index or the end of the log is reached.
    while (reader.hasNext()) {
      // Otherwise, read the next entry and add it to the batch.
      Indexed<RaftLogEntry> entry = reader.next();
      entries.add(entry.entry());
      size += entry.size();
      if (entry.index() == lastIndex || size >= MAX_BATCH_SIZE) {
        break;
      }
    }

    // Add the entries to the request builder and build the request.
    return builder.withEntries(entries).build();
  }
677887
def build_from_invalid_request(cls, invalid_request_object):
        """"""
        errors = [{err['parameter']: err['message']} for err in invalid_request_object.errors]
        return cls.build_response(Status.UNPROCESSABLE_ENTITY, errors)
284492
def build_request(self, input_data=None, api_data=None, aux_data=None, *args, **kwargs):
        
        if input_data is not None:
            self.client_data = input_data
        if api_data is not None:
            self.api_data = api_data
        if aux_data is not None:
            self.aux_data = aux_data

        self.request = RequestHolder()
        self.request.nonce = get_random_vector(EBConsts.FRESHNESS_NONCE_LEN)

        self.request.endpoint = self.get_endpoint()
        self.request.url = self.get_endpoint().get_url() + self.url_suffix

        self.request.configuration = self.config
        self.request.api_method = self.operation
        self.request.headers = {'X-Auth-Token': 'public'}

        # Result request body
        self.request.body = {
            'nonce': to_hex(self.request.nonce),
            'version': 1,
            'function': self.operation,
            'environment': self.env if self.env is not None else ENVIRONMENT_DEVELOPMENT,
        }

        if self.client_data is not None:
            self.request.body['client'] = self.client_data
        if self.api_data is not None:
            self.request.body['apidata'] = self.api_data
        if self.aux_data is not None:
            if isinstance(self.aux_data, dict):
                self.request.body = EBUtils.merge(self.request.body, self.aux_data)
            else:
                raise ValueError('Aux data has to be a dictionary')

        self.request = self.extend_request(self.request)
        return self.request
1235200
def build(self, **values: Any) -> str:
        """"""
        converted_values = {
            key: self._converters[key].to_url(value)
            for key, value in values.items()
            if key in self._converters
        }
        result = self._builder.format(**converted_values).split('|', 1)[1]
        query_string = urlencode(
            {
                key: value
                for key, value in values.items()
                if key not in self._converters and key not in self.defaults
            },
            doseq=True,
        )
        if query_string:
            result = "{}?{}".format(result, query_string)
        return result
362171
def add(self, items):
        """"""
        with _presub_lock:
            self.load_from_cloud()
            for entry in utils.ensure_listable(items):
                # add new entries, but only if they're unique
                if entry not in self.current:
                    self.current.append(entry)
            self.save_to_cloud()
663268
def new_build():
    """"""
    form = forms.BuildForm()
    if form.validate_on_submit():
        build = models.Build()
        form.populate_obj(build)
        build.owners.append(current_user)

        db.session.add(build)
        db.session.flush()

        auth.save_admin_log(build, created_build=True, message=build.name)

        db.session.commit()

        operations.UserOps(current_user.get_id()).evict()

        logging.info('Created build via UI: build_id=%r, name=%r',
                     build.id, build.name)
        return redirect(url_for('view_build', id=build.id))

    return render_template(
        'new_build.html',
        build_form=form)
828966
private void populateRequestHeaders(HttpRequestBase httpRequest, Map<String, String> requestHeaders) {

        Set<String> keySet = requestHeaders.keySet();
        Iterator<String> keySetIterator = keySet.iterator();
        while (keySetIterator.hasNext()) {
            String key = keySetIterator.next();
            String value = requestHeaders.get(key);
            httpRequest.addHeader(key, value);
        }

        PropertyHelper propertyHelper = PropertyHelper.getInstance();
        String requestSource = propertyHelper.getRequestSource() + propertyHelper.getVersion();
        if(propertyHelper.getRequestSourceHeader() != null){
            httpRequest.addHeader(propertyHelper.getRequestSourceHeader(), requestSource);
        }

    }
667725
protected function populate()
    {
        $this->collection = AnalyticsDb::ADB_STATS_DAILY;

        // $match
        $this->pipeline['$match']['entity'] = $this->entity;
        if (!empty($this->ref)) {
            $this->pipeline['$match']['ref'] = $this->ref;
        }
        $this->pipeline['$match']['ts'] = ['$gte' => $this->dateRange[0], '$lte' => $this->dateRange[1]];

        // $project
        $this->pipeline['$project'] = [
            'count'  => 1,
            'ref'    => 1,
            'ts'     => 1,
            'entity' => 1,
            'month'  => 1,
            'year'   => 1
        ];

        // $group
        $this->pipeline['$group'] = ['_id' => '$ts', 'totalCount' => ['$sum' => '$count']];

        // $sort -> by timestamp
        $this->pipeline['$sort'] = ['_id' => 1];
    }
103357
def build(config):
    """"""
    logger.info("\nRendering website now...\n")
    logger.info("entries:")
    tags = dict()
    entries = list()
    for post, post_id in find_new_posts_and_pages(DB):
        # this method will also parse the post's tags and
        # update the db collection containing the tags.
        if post.render():
            if post.header['kind'] in ['writing', 'link']:
                for tag in post.tags:
                    tag.posts = [post_id]
                    tags[tag.name] = tag
                entries.append(post)
            logger.info("%s" % post.path)

    for name, to in tags.items():
        logger.info("updating tag %s" % name)
        to.render()

    # This is expensive, we should insert only the recent entries
    # to the index using BeautifulSoup
    # update index
    logger.info("Updating index")
    last_entries, all_entries = _get_last_entries(DB, config['INDEX_SIZE'])
    last_entries = list(_filter_none_public(last_entries))
    update_index(last_entries)

    # update archive
    logger.info("Updating archive")

    # This is expensive, we should insert only the recent entries
    # to the archive using BeautifulSoup

    entries = [Entry.entry_from_db(
               os.path.join(CONFIG['content_root'],
                            e.get('filename')), e.doc_id) for e in
               DB.posts.all()]
    all_entries = list(_filter_none_public(all_entries))
    all_entries.sort(key=operator.attrgetter('date'), reverse=True)
    render_archive(all_entries[config['ARCHIVE_SIZE']:])
890018
def append(self, timestamp, key, value, headers=[]):
        
        if self._closed:
            return None

        offset = self._next_offset
        metadata = self._builder.append(offset, timestamp, key, value, headers)
        # Return of None means there's no space to add a new message
        if metadata is None:
            return None

        self._next_offset += 1
        return metadata
399176
def create(request):
    """"""

    errors = []
    success = False
    listOfResponses = ['', '', '']  # 3 Blank lines by default
    title = ''
    description = ''
    id = ''

    if request.method == 'POST':  # User saved the form
        # Retrieve parameters
        title = request.form.get('title')
        description = request.form.get('description')

        listOfResponses = []
        for rep in request.form.getlist('rep[]'):
            if rep != '':
                listOfResponses.append(rep)

        # Test if everything is ok
        if title == "":
            errors.append("Please set a title !")

        if len(listOfResponses) == 0:
            errors.append("Please set at least one response !")

        # Can we save the new question ?
        if len(errors) == 0:
            # Yes. Let save data
            curDB.execute("INSERT INTO Poll (title, description) VALUES (?, ?)", (title, description))

            # The id of the poll
            id = curDB.lastrowid

            # Insert responses
            for rep in listOfResponses:
                curDB.execute("INSERT INTO Response (pollId, title) VALUES (?, ?)", (id, rep))

            coxDB.commit()

            success = True

        # Minimum of 3 lines of questions
        while len(listOfResponses) < 3:
            listOfResponses.append('')

    return {'errors': errors, 'success': success, 'listOfResponses': listOfResponses, 'title': title, 'description': description, 'id': id}
114261
def build(self, builder):
        """"""

        params = dict(ItemOID=self.oid, Mandatory=bool_to_yes_no(self.mandatory))

        if self.order_number is not None:
            params["OrderNumber"] = str(self.order_number)

        if self.key_sequence is not None:
            params["KeySequence"] = str(self.key_sequence)

        if self.imputation_method_oid is not None:
            params["ImputationMethodOID"] = self.imputation_method_oid

        if self.role is not None:
            params["Role"] = self.role

        if self.role_codelist_oid is not None:
            params["RoleCodeListOID"] = self.role_codelist_oid

        builder.start("ItemRef", params)

        for attribute in self.attributes:
            attribute.build(builder)
        builder.end("ItemRef")
1342387
def build_parameters(request, meta, orgaMode, currentOrga):
    """"""

    postParameters = {}
    getParameters = {}
    files = {}

    def update_parameters(data):
        tmp_getParameters, tmp_postParameters, tmp_files = data

        getParameters.update(tmp_getParameters)
        postParameters.update(tmp_postParameters)
        files.update(tmp_files)

    update_parameters(build_base_parameters(request))
    update_parameters(build_user_requested_parameters(request, meta))
    update_parameters(build_orga_parameters(request, orgaMode, currentOrga))

    return (getParameters, postParameters, files)
86513
protected AppendRequest buildAppendEmptyRequest(RaftMemberContext member) {
    final RaftLogReader reader = member.getLogReader();

    // Read the previous entry from the reader.
    // The reader can be null for RESERVE members.
    Indexed<RaftLogEntry> prevEntry = reader != null ? reader.getCurrentEntry() : null;

    DefaultRaftMember leader = raft.getLeader();
    return AppendRequest.builder()
        .withTerm(raft.getTerm())
        .withLeader(leader != null ? leader.memberId() : null)
        .withPrevLogIndex(prevEntry != null ? prevEntry.index() : reader != null ? reader.getFirstIndex() - 1 : 0)
        .withPrevLogTerm(prevEntry != null ? prevEntry.entry().term() : 0)
        .withEntries(Collections.emptyList())
        .withCommitIndex(raft.getCommitIndex())
        .build();
  }
1152685
function fillMethods(apiObj, urls) {
  const urlKeys = Object.keys(urls);

  urlKeys.forEach((urlKey) => {
    const urlVal = urls[urlKey];

    if (typeof urlVal === 'string') {
      apiObj[urlKey] = assembleHttp(urlVal);
    } else if (urlVal.url) {
      apiObj[urlKey] = assembleHttp(urlVal);
    } else {
      apiObj[urlKey] = {};
      fillMethods(apiObj[urlKey], urlVal);
    }
  });
}
523904
protected AppendResponse appendEntries(AppendRequest request) {
    // Get the last entry index or default to the request log index.
    long lastEntryIndex = request.logIndex();
    if (!request.entries().isEmpty()) {
      lastEntryIndex = request.entries().get(request.entries().size() - 1).getIndex();
    }

    // Ensure the commitIndex is not increased beyond the index of the last entry in the request.
    long commitIndex = Math.max(context.getCommitIndex(), Math.min(request.commitIndex(), lastEntryIndex));

    // Append entries to the log starting at the last log index.
    for (Entry entry : request.entries()) {
      // If the entry index is greater than the last index and less than the commit index, append the entry.
      // We perform no additional consistency checks here since passive members may only receive committed entries.
      if (context.getLog().lastIndex() < entry.getIndex() && entry.getIndex() <= commitIndex) {
        context.getLog().skip(entry.getIndex() - context.getLog().lastIndex() - 1).append(entry);
        LOGGER.trace("{} - Appended {} to log at index {}", context.getCluster().member().address(), entry, entry.getIndex());
      }
    }

    // Update the context commit and global indices.
    long previousCommitIndex = context.getCommitIndex();
    context.setCommitIndex(commitIndex);
    context.setGlobalIndex(request.globalIndex());

    if (context.getCommitIndex() > previousCommitIndex) {
      LOGGER.trace("{} - Committed entries up to index {}", context.getCluster().member().address(), commitIndex);
    }

    // Apply commits to the state machine in batch.
    context.getStateMachine().applyAll(context.getCommitIndex());

    return AppendResponse.builder()
      .withStatus(Response.Status.OK)
      .withTerm(context.getTerm())
      .withSucceeded(true)
      .withLogIndex(context.getLog().lastIndex())
      .build();
  }
116614
@NonNull
    public ObservableDataBuilder<T> appends(@Nullable Observable<? extends Collection<? extends T>> appends) {
        mAppends = appends;
        return this;
    }