Handles a vote request.
171488
protected VoteResponse handleVote(VoteRequest request) {
    // If the request term is not as great as the current context term then don't
    // vote for the candidate. We want to vote for candidates that are at least
    // as up to date as us.
    if (request.term() < context.getTerm()) {
      LOGGER.trace("{} - Rejected {}: candidate's term is less than the current term", context.getCluster().member().address(), request);
      return VoteResponse.builder()
        .withStatus(Response.Status.OK)
        .withTerm(context.getTerm())
        .withVoted(false)
        .build();
    }
    // If a leader was already determined for this term then reject the request.
    else if (context.getLeader() != null) {
      LOGGER.trace("{} - Rejected {}: leader already exists", context.getCluster().member().address(), request);
      return VoteResponse.builder()
        .withStatus(Response.Status.OK)
        .withTerm(context.getTerm())
        .withVoted(false)
        .build();
    }
    // If the requesting candidate is not a known member of the cluster (to this
    // node) then don't vote for it. Only vote for candidates that we know about.
    else if (!context.getClusterState().getRemoteMemberStates().stream().<Integer>map(m -> m.getMember().id()).collect(Collectors.toSet()).contains(request.candidate())) {
      LOGGER.trace("{} - Rejected {}: candidate is not known to the local member", context.getCluster().member().address(), request);
      return VoteResponse.builder()
        .withStatus(Response.Status.OK)
        .withTerm(context.getTerm())
        .withVoted(false)
        .build();
    }
    // If no vote has been cast, check the log and cast a vote if necessary.
    else if (context.getLastVotedFor() == 0) {
      if (isLogUpToDate(request.logIndex(), request.logTerm(), request)) {
        context.setLastVotedFor(request.candidate());
        return VoteResponse.builder()
          .withStatus(Response.Status.OK)
          .withTerm(context.getTerm())
          .withVoted(true)
          .build();
      } else {
        return VoteResponse.builder()
          .withStatus(Response.Status.OK)
          .withTerm(context.getTerm())
          .withVoted(false)
          .build();
      }
    }
    // If we already voted for the requesting server, respond successfully.
    else if (context.getLastVotedFor() == request.candidate()) {
      LOGGER.debug("{} - Accepted {}: already voted for {}", context.getCluster().member().address(), request, context.getCluster().member(context.getLastVotedFor()).address());
      return VoteResponse.builder()
        .withStatus(Response.Status.OK)
        .withTerm(context.getTerm())
        .withVoted(true)
        .build();
    }
    // In this case, we've already voted for someone else.
    else {
      LOGGER.debug("{} - Rejected {}: already voted for {}", context.getCluster().member().address(), request, context.getCluster().member(context.getLastVotedFor()).address());
      return VoteResponse.builder()
        .withStatus(Response.Status.OK)
        .withTerm(context.getTerm())
        .withVoted(false)
        .build();
    }
  }
996334
protected VoteResponse handleVote(VoteRequest request) {
    // If the request term is not as great as the current context term then don't
    // vote for the candidate. We want to vote for candidates that are at least
    // as up to date as us.
    if (request.term() < raft.getTerm()) {
      log.debug("Rejected {}: candidate's term is less than the current term", request);
      return VoteResponse.builder()
          .withStatus(RaftResponse.Status.OK)
          .withTerm(raft.getTerm())
          .withVoted(false)
          .build();
    }
    // If a leader was already determined for this term then reject the request.
    else if (raft.getLeader() != null) {
      log.debug("Rejected {}: leader already exists", request);
      return VoteResponse.builder()
          .withStatus(RaftResponse.Status.OK)
          .withTerm(raft.getTerm())
          .withVoted(false)
          .build();
    }
    // If the requesting candidate is not a known member of the cluster (to this
    // node) then don't vote for it. Only vote for candidates that we know about.
    else if (!raft.getCluster().getRemoteMemberStates().stream().map(m -> m.getMember().memberId()).collect(Collectors.toSet()).contains(request.candidate())) {
      log.debug("Rejected {}: candidate is not known to the local member", request);
      return VoteResponse.builder()
          .withStatus(RaftResponse.Status.OK)
          .withTerm(raft.getTerm())
          .withVoted(false)
          .build();
    }
    // If no vote has been cast, check the log and cast a vote if necessary.
    else if (raft.getLastVotedFor() == null) {
      if (isLogUpToDate(request.lastLogIndex(), request.lastLogTerm(), request)) {
        raft.setLastVotedFor(request.candidate());
        return VoteResponse.builder()
            .withStatus(RaftResponse.Status.OK)
            .withTerm(raft.getTerm())
            .withVoted(true)
            .build();
      } else {
        return VoteResponse.builder()
            .withStatus(RaftResponse.Status.OK)
            .withTerm(raft.getTerm())
            .withVoted(false)
            .build();
      }
    }
    // If we already voted for the requesting server, respond successfully.
    else if (raft.getLastVotedFor() == request.candidate()) {
      log.debug("Accepted {}: already voted for {}", request, raft.getCluster().getMember(raft.getLastVotedFor()).memberId());
      return VoteResponse.builder()
          .withStatus(RaftResponse.Status.OK)
          .withTerm(raft.getTerm())
          .withVoted(true)
          .build();
    }
    // In this case, we've already voted for someone else.
    else {
      log.debug("Rejected {}: already voted for {}", request, raft.getCluster().getMember(raft.getLastVotedFor()).memberId());
      return VoteResponse.builder()
          .withStatus(RaftResponse.Status.OK)
          .withTerm(raft.getTerm())
          .withVoted(false)
          .build();
    }
  }
1085261
def vote(request, abbr, vote_id):
    '''
    
    '''
    vote = db.votes.find_one(vote_id)
    if vote is None:
        raise Http404('no such vote: {0}'.format(vote_id))
    bill = vote.bill()

    return render(request, templatename('vote'),
                  dict(abbr=abbr, metadata=Metadata.get_object(abbr),
                       bill=bill,
                       vote=vote,
                       nav_active='bills'))
1151875
def handle_save(self, request, response):
        
        form_valid = isinstance(response, HttpResponseRedirect)
        if request.POST.get("_save") and form_valid:
            return redirect("admin:index")
        return response
1265830
def request_view(request, request_pk):
    '''
    
    '''
    if request.is_ajax():
        if not request.user.is_authenticated():
            return HttpResponse(json.dumps(dict()),
                                content_type="application/json")

        try:
            relevant_request = Request.objects.get(pk=request_pk)
        except Request.DoesNotExist:
            return HttpResponse(json.dumps(dict()),
                                content_type="application/json")

        try:
            user_profile = UserProfile.objects.get(user=request.user)
        except UserProfile.DoesNotExist:
            return HttpResponse(json.dumps(dict()),
                                content_type="application/json")

        upvote = user_profile in relevant_request.upvotes.all()
        vote_form = VoteForm(
            request.POST if "upvote" in request.POST else None,
            profile=user_profile,
            request=relevant_request,
            )
        if vote_form.is_valid():
            vote_form.save()
            response = dict()
            response['vote_count_{pk}'.format(pk=request_pk)] = \
                relevant_request.upvotes.all().count()

            list_string = 'vote_list_{pk}'.format(pk=request_pk)
            vote_string = 'in_votes_{pk}'.format(pk=request_pk)
            count_string = 'vote_count_{pk}'.format(pk=request_pk)
            response[list_string], response[vote_string], \
                response[count_string] = build_ajax_votes(
                    relevant_request,
                    user_profile
                )
            return HttpResponse(json.dumps(response),
                                content_type="application/json")
        return HttpResponse(json.dumps(dict()),
                            content_type="application/json")

    relevant_request = get_object_or_404(Request, pk=request_pk)

    if relevant_request.private:
        if relevant_request.owner.user != request.user or \
          relevant_request.request_type.managers.filter(incumbent__user=request.user):
          return HttpResponseRedirect(
              reverse("managers:requests",
                      kwargs={"requestType": relevant_request.request_type.url_name}))

    userProfile = UserProfile.objects.get(user=request.user)
    request_responses = Response.objects.filter(request=relevant_request)
    relevant_managers = relevant_request.request_type.managers.filter(active=True)
    manager = any(i.incumbent == userProfile for i in relevant_managers)
    if manager:
        response_form = ManagerResponseForm(
            request.POST if "add_response" in request.POST else None,
            initial={'action': Response.NONE},
            profile=userProfile,
            request=relevant_request,
            )
    else:
        response_form = ResponseForm(
            request.POST if "add_response" in request.POST else None,
            profile=userProfile,
            request=relevant_request,
            prefix="response",
            )
    upvote = userProfile in relevant_request.upvotes.all()
    vote_form = VoteForm(
        request.POST if "upvote" in request.POST else None,
        profile=userProfile,
        request=relevant_request,
        )
    if response_form.is_valid():
        response_form.save()
        return HttpResponseRedirect(reverse('managers:view_request', kwargs={
            'request_pk': relevant_request.pk,
            }))
    if vote_form.is_valid():
        vote_form.save()
        return HttpResponseRedirect(reverse('managers:view_request', kwargs={
            'request_pk': relevant_request.pk,
            }))
    upvote = userProfile in relevant_request.upvotes.all()
    return render_to_response('view_request.html', {
        'page_name': "View Request",
        'relevant_request': relevant_request,
        'request_responses': request_responses,
        'upvote': upvote,
        'vote_form': vote_form,
        'response_form': response_form,
        'relevant_managers': relevant_managers,
        }, context_instance=RequestContext(request))
11481
def handle(self):
        """"""
        self.close_connection = 1

        self.handle_one_request()
        while not self.close_connection:
            self.handle_one_request()
734651
def vote(self, upvote, id, remote_addr):
        """"""

        rv = self.db.execute(
            'SELECT likes, dislikes, voters FROM comments WHERE id=?', (id, )) \
            .fetchone()

        if rv is None:
            return None

        likes, dislikes, voters = rv
        if likes + dislikes >= 142:
            return {'likes': likes, 'dislikes': dislikes}

        bf = Bloomfilter(bytearray(voters), likes + dislikes)
        if remote_addr in bf:
            return {'likes': likes, 'dislikes': dislikes}

        bf.add(remote_addr)
        self.db.execute([
            'UPDATE comments SET',
            '    likes = likes + 1,' if upvote else 'dislikes = dislikes + 1,',
            '    voters = ?'
            'WHERE id=?;'], (buffer(bf.array), id))

        if upvote:
            return {'likes': likes + 1, 'dislikes': dislikes}
        return {'likes': likes, 'dislikes': dislikes + 1}
533507
def vote(self, identifier, weight=100.0):
        ''' 
        '''
        for num_of_retries in range(default.max_retry):
            try:
                self.steem_instance().vote(identifier, 
                    weight, self.mainaccount)
                self.msg.message("voted for " + identifier)
                time.sleep(5)
            except Exception as e:
                if re.search(r'You have already voted in a similar way', str(e)):
                    self.msg.error_message('''Already voted on 
                                        {}'''.format(identifier))
                    return "already voted"
                else:
                    self.util.retry('''COULD NOT VOTE ON 
                                    {}'''.format(identifier), 
                                    e, num_of_retries, default.wait_time)
                    self.s = None
            else:
                return True
1220691
def build_ajax_votes(request, user_profile):
    """"""
    vote_list = ''
    for profile in request.upvotes.all():
        vote_list += \
            '<li><a title="View Profile" href="{url}">{name}</a></li>'.format(
                url=reverse(
                    'member_profile',
                    kwargs={'targetUsername': profile.user.username}
                ),
                name='You' if profile.user == user_profile.user \
                    else profile.user.get_full_name(),
            )

    in_votes = user_profile in request.upvotes.all()
    count = request.upvotes.all().count()

    return (vote_list, in_votes, count)
1309088
def poll(self):
        """"""
        self._returncode = self.process.poll()

        if self._returncode is not None:
            self.set_status(self.S_DONE, "status set to Done")

        return self._returncode
797217
def submit(self):
        """"""
        if self._dirty:
            self.save()

        self._connection.run(['submit', '-c', str(self._change)], marshal_output=False)
862395
def _handle_post(self, method, remainder, request=None):
        '''
        
        '''
        if request is None:
            self._raise_method_deprecation_warning(self._handle_post)

        # check for custom POST/PUT requests
        if remainder:
            match = self._handle_custom_action(method, remainder, request)
            if match:
                return match

            controller = self._lookup_child(remainder[0])
            if controller and not ismethod(controller):
                return lookup_controller(controller, remainder[1:], request)

        # check for regular POST/PUT requests
        controller = self._find_controller(method)
        if controller:
            return controller, remainder

        abort(405)
723778
def votes(self, req) -> int:
        
        try:
            votes = len(self[req.key].propagates)
        except KeyError:
            votes = 0
        return votes
132364
def _handle_results(options):
    """"""
    results_processor = options.get('_process_results')
    if not results_processor:
        results_processor = _process_results

    processor_result = results_processor()
    if isinstance(processor_result, (Async, Context)):
        processor_result.start()
166980
def up_vote!(votable)
      begin
        up_vote(votable)
        success = true
      rescue Exceptions::AlreadyVotedError
        success = false
      end
      success
    end
141973
def _handle_request(self, request):
        """"""
        if 'types' in self.method_data[request['method']]:
            self._validate_params_types(request['method'], request['params'])

        if self.serve_exception:
            raise self.serve_exception()
        d = self._call_method(request)
        self.pending.add(d)
        if self.timeout:
            timeout_deferred = self.reactor.callLater(self.timeout, d.cancel)

            def completed(result):
                if timeout_deferred.active():
                    # cancel the timeout_deferred if it has not been fired yet
                    # this is to prevent d's deferred chain from firing twice
                    # (and raising an exception).
                    timeout_deferred.cancel()
                return result
            d.addBoth(completed)
        try:
            result = yield d
        except defer.CancelledError:
            # The request was cancelled due to a timeout or by cancelPending
            # having been called. We return a TimeoutError to the client.
            self._remove_pending(d)
            raise TimeoutError()
        except Exception as e:
            self._remove_pending(d)
            raise e
        self._remove_pending(d)
        # Do not respond to notifications.
        if request['id'] is None:
            defer.returnValue(None)

        respond = {}
        self._fill_ver(request['jsonrpc'], respond)
        respond['result'] = result
        respond['id'] = request['id']

        defer.returnValue(respond)
227054
public function upVoteAction(Request $request)
    {
        $reference = $request->get('reference');
        $value = $request->get('value');
        $this->get('event_dispatcher')->dispatch(Events::VOTE_UP, new UpVoteEvent($request, $reference, $value));

        return;
    }