For a given election, this function updates or creates the
        CandidateElection object using the model method on the election.
435938
def get_or_create_candidate_election(
        self, row, election, candidate, party
    ):
        
        return election.update_or_create_candidate(
            candidate, party.aggregate_candidates, row["uncontested"]
        )
42712
def get_election_delegates(self, election):
        """"""
        candidate_election = CandidateElection.objects.get(
            candidate=self, election=election
        )

        return candidate_election.delegates.all()
585882
def update_models(self, model, name, info):
        

        if info.method_name in ["add_input_data_port", "remove_input_data_port", "input_data_ports"]:
            (model_list, data_list, model_name, model_class, model_key) = self.get_model_info("input_data_port")
        elif info.method_name in ["add_output_data_port", "remove_output_data_port", "output_data_ports"]:
            (model_list, data_list, model_name, model_class, model_key) = self.get_model_info("output_data_port")
        elif info.method_name in ["add_income", "remove_income", "income"]:
            (model_list, data_list, model_name, model_class, model_key) = self.get_model_info("income")
        elif info.method_name in ["add_outcome", "remove_outcome", "outcomes"]:
            (model_list, data_list, model_name, model_class, model_key) = self.get_model_info("outcome")
        else:
            return

        if "add" in info.method_name:
            self.add_missing_model(model_list, data_list, model_name, model_class, model_key)
        elif "remove" in info.method_name:
            destroy = info.kwargs.get('destroy', True)
            self.remove_specific_model(model_list, info.result, model_key, destroy)
        elif info.method_name in ["input_data_ports", "output_data_ports", "income", "outcomes"]:
            self.re_initiate_model_list(model_list, data_list, model_name, model_class, model_key)
655837
public void setLastVotedFor(MemberId candidate) {
    // If we've already voted for another candidate in this term then the last voted for candidate cannot be overridden.
    checkState(!(lastVotedFor != null && candidate != null), "Already voted for another candidate");
    DefaultRaftMember member = cluster.getMember(candidate);
    checkState(member != null, "Unknown candidate: %d", candidate);
    this.lastVotedFor = candidate;
    meta.storeVote(this.lastVotedFor);

    if (candidate != null) {
      log.debug("Voted for {}", member.memberId());
    } else {
      log.trace("Reset last voted for");
    }
  }
1139425
protected void updateSelection()
   {
      byte[] data = m_model.getData();
      int offset = m_model.getOffset();
      Point selectedCell = m_model.getSelectedCell();

      DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
      DateFormat timeFormat = new SimpleDateFormat("HH:mm");
      DateFormat timestampFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");

      int selectionIndex = (selectedCell.y * m_model.getColumns()) + selectedCell.x;
      String selectionLabel = selectedCell.y + "," + selectedCell.x;
      String differenceLabel = Integer.toString(Math.abs(m_model.getCurrentSelectionIndex() - selectionIndex));

      String shortValueLabel = "";
      String longSixValueLabel = "";
      String longValueLabel = "";
      String doubleValueLabel = "";
      String durationValueLabel = "";
      String timeUnitsValueLabel = "";
      String guidValueLabel = "";
      String percentageValueLabel = "";
      String dateValueLabel = "";
      String timeValueLabel = "";
      String timestampValueLabel = "";
      String workUnitsValueLabel = "";

      if (selectionIndex + offset + 2 <= data.length)
      {
         shortValueLabel = Integer.toString(MPPUtility.getShort(data, selectionIndex + offset));
         timeUnitsValueLabel = MPPUtility.getDurationTimeUnits(MPPUtility.getShort(data, selectionIndex + offset)).toString();

         Double value = MPPUtility.getPercentage(data, selectionIndex + offset);
         if (value != null)
         {
            percentageValueLabel = value.toString();
         }

         Date date = MPPUtility.getDate(data, selectionIndex + offset);
         if (date != null)
         {
            dateValueLabel = dateFormat.format(date);
         }

         timeValueLabel = timeFormat.format(MPPUtility.getTime(data, selectionIndex + offset));
      }

      //
      // 1 byte
      //
      workUnitsValueLabel = MPPUtility.getWorkTimeUnits(MPPUtility.getByte(data, selectionIndex + offset)).toString();

      //
      // 4 bytes
      //
      if (selectionIndex + offset + 4 <= data.length)
      {
         Date timestamp = MPPUtility.getTimestamp(data, selectionIndex + offset);
         if (timestamp != null)
         {
            timestampValueLabel = timestampFormat.format(timestamp);
         }
      }

      //
      // 6 bytes
      //
      if (selectionIndex + offset + 6 <= data.length)
      {
         longSixValueLabel = Long.toString(MPPUtility.getLong6(data, selectionIndex + offset));
      }

      //
      // 8 bytes
      //
      if (selectionIndex + offset + 8 <= data.length)
      {
         longValueLabel = Long.toString(MPPUtility.getLong(data, selectionIndex + offset));
         doubleValueLabel = Double.toString(MPPUtility.getDouble(data, selectionIndex + offset));
         durationValueLabel = Duration.getInstance(MPPUtility.getDouble(data, selectionIndex + offset) / 60000, TimeUnit.HOURS).toString();
      }

      //
      // 16 bytes
      //
      if (selectionIndex + offset + 16 <= data.length)
      {
         guidValueLabel = MPPUtility.getGUID(data, selectionIndex + offset).toString().toUpperCase();
      }

      m_model.setPreviousSelectionIndex(m_model.getCurrentSelectionIndex());
      m_model.setCurrentSelectionIndex(selectionIndex);
      m_model.setPreviousSelectionValueLabel(m_model.getCurrentSelectionValueLabel());
      m_model.setCurrentSelectionValueLabel(selectionLabel);
      m_model.setSelectionDifferenceValueLabel(differenceLabel);
      m_model.setShortValueLabel(shortValueLabel);
      m_model.setLongSixValueLabel(longSixValueLabel);
      m_model.setLongValueLabel(longValueLabel);
      m_model.setDoubleValueLabel(doubleValueLabel);
      m_model.setDurationValueLabel(durationValueLabel);
      m_model.setTimeUnitsValueLabel(timeUnitsValueLabel);
      m_model.setGuidValueLabel(guidValueLabel);
      m_model.setPercentageValueLabel(percentageValueLabel);
      m_model.setDateValueLabel(dateValueLabel);
      m_model.setTimeValueLabel(timeValueLabel);
      m_model.setTimestampValueLabel(timestampValueLabel);
      m_model.setWorkUnitsValueLabel(workUnitsValueLabel);
   }
266884
def save(self, *args, **kwargs):
        
        if self.party:
            self.uid = "{}_election:{}-{}".format(
                self.race.uid,
                self.election_day.date,
                slugify(self.party.ap_code),
            )
        else:
            self.uid = "{}_election:{}".format(
                self.race.uid, self.election_day.date
            )
        super(Election, self).save(*args, **kwargs)
93786
def addRemoteCandidate(self, candidate):
        
        # FIXME: don't use private member!
        if not self._connection._remote_candidates_end:
            if candidate is None:
                self._connection.add_remote_candidate(None)
            else:
                self._connection.add_remote_candidate(candidate_to_aioice(candidate))
408905
public void updateMethodKey() {
        Arrays.stream(ParamType.values()).forEach(paramType -> this.syncMethodKey(paramType));

        this.validationDataRepository.flush();
        this.validationStore.refresh();
        log.info("[METHOD_KEY_SYNC] Complete");
    }
1117168
def update(self, campaign_id, schedule, nick=None):
        ''''''
        request = TOPRequest('xxxxx.xxxxx.campaign.schedule.update')
        request['campaign_id'] = campaign_id
        request['schedule'] = schedule
        if nick!=None: request['nick'] = nick
        self.create(self.execute(request), fields=['success','result','success','result_code','result_message'], models={'result':CampaignSchedule})
        return self.result
1330352
def update(self, campaign_id, area, nick=None):
        ''''''
        request = TOPRequest('xxxxx.xxxxx.campaign.area.update')
        request['campaign_id'] = campaign_id
        request['area'] = area
        if nick!=None: request['nick'] = nick
        self.create(self.execute(request), fields=['success','result','success','result_code','result_message'], models={'result':CampaignArea})
        return self.result
207710
function refreshModel(o) {
  if (!(o instanceof Model)) {throw new TypeError('Model expected')}
  _.forEach(o.elements(), refreshElement)
}
586974
protected function updateSelector()
    {
        $buffer = implode('', $this->getBuffer());
        $qtiClassMap = ($this->isWebComponentFriendly()) ? array_merge(self::$qtiClassMapping, self::$wcFriendlyQtiClassMapping) : self::$qtiClassMapping;

        if (strpos($buffer, ',') === false) {

            // Do not rescope if already scoped!
            if (strpos($buffer, '#' . $this->getId()) === false) {
                $buffer = ($this->doesMapQtiClasses() === true) ? CssUtils::mapSelector($buffer, $qtiClassMap) : $buffer;
                $buffer = ($this->doesMapQtiPseudoClasses() === true) ? CssUtils::mapPseudoClasses($buffer, self::getQtiPseudoClassMapping()) : $buffer;
                $this->output('#' . $this->getId() . ' ' . $buffer . '{');
            } else {
                $buffer = ($this->doesMapQtiPseudoClasses() === true) ? CssUtils::mapPseudoClasses($buffer, self::getQtiPseudoClassMapping()) : $buffer;
                $this->output($buffer . '{');
            }
        } else {
            $classes = explode(',', $buffer);
            $newClasses = array();

            foreach ($classes as $c) {

                // Same as above, do not rescope if already scoped...
                if (strpos($c, '#' . $this->getId()) === false) {
                    $c = ($this->doesMapQtiClasses() === true) ? CssUtils::mapSelector($c, $qtiClassMap) : $c;
                    $newC =  '#' . $this->getId() . ' ' . trim($c);
                    $newC = str_replace(trim($c), $newC, $c);
                } else {
                    $newC = $c;
                }

                $newClasses[] = $newC;
            }

            $buffer = implode(',', $newClasses);
            $buffer = ($this->doesMapQtiPseudoClasses() === true) ? CssUtils::mapPseudoClasses($buffer, self::getQtiPseudoClassMapping()) : $buffer;
            $this->output($buffer . '{');
        }
    }
897176
@Override
    protected void updateSelector() {
        final boolean bTrace = TraceComponent.isAnyTracingEnabled();
        VirtualConnection vci = null;
        NioSocketIOChannel ioSocket = null;
        TCPBaseRequestContext work = null;

        final Queue<Object> queue = getWorkQueue();
        if (bTrace && tc.isDebugEnabled()) {
            Tr.debug(this, tc, "updateSelector - processing " + queue.size() + " items");
        }
        while (!queue.isEmpty()) {
            work = (TCPBaseRequestContext) queue.remove();
            ioSocket = (NioSocketIOChannel) work.getTCPConnLink().getSocketIOChannel();
            vci = work.getTCPConnLink().getVirtualConnection();
            // if connection is closed from another thread (like during tcpchannel
            // stop)
            // the vc can become null. if so, ignore this request
            if (vci == null) {
                if (bTrace && tc.isEventEnabled()) {
                    SocketChannel channel = ioSocket != null ? ioSocket.getChannel() : null;
                    Tr.event(this, tc, "Ignoring due to null vc on " + ((channel != null) ? channel.toString() : "<UNKNOWN>"));
                }
                continue;
            }

            final int selectorOp;
            if (work.isRequestTypeRead()) {
                selectorOp = SelectionKey.OP_READ;
            } else {
                selectorOp = SelectionKey.OP_WRITE;
            }
            // if key is already set, then this channel is already registered
            // so, we can just change the interest ops
            SelectionKey key = getKey(ioSocket.getChannel());
            if (key != null) {
                if (bTrace && tc.isEventEnabled()) {
                    Tr.event(this, tc, "changing interest ops for channel " + ioSocket.getChannel() + " to " + selectorOp + " for key " + key);
                }

                if (vci.isInputStateTrackingOperational()) {
                    synchronized (vci.getLockObject()) {
                        // Change it interestOp from none, to the correct operation
                        // Change the request's selection key's interested
                        key.interestOps(selectorOp);

                        if (work.isRequestTypeRead()) {
                            if (((TCPReadRequestContextImpl) work).getReadCompletedCallback() != null) {
                                // only allow closes for outstanding async requests
                                vci.setReadStatetoCloseAllowedNoSync();
                            }
                        } else {
                            if (((TCPWriteRequestContextImpl) work).getWriteCompletedCallback() != null) {
                                // only allow closes for outstanding async requests
                                vci.setWriteStatetoCloseAllowedNoSync();
                            }
                        }
                        if (vci.getCloseWaiting()) {
                            vci.getLockObject().notify();
                        }
                    } // end-vc-sync
                } else {
                    // Change the request's selection key's interested
                    key.interestOps(selectorOp);
                }
            } else {
                if (work.isRequestTypeRead()) {
                    ioSocket.setChannelSelectorRead(this);
                } else {
                    ioSocket.setChannelSelectorWrite(this);
                }

                try {
                    if (vci.isInputStateTrackingOperational()) {
                        synchronized (vci.getLockObject()) {
                            SelectionKey selKey = ioSocket.register(selector, selectorOp, work);
                            if (bTrace && tc.isEventEnabled()) {
                                Tr.event(this, tc, "registered " + ioSocket.getChannel() + ", key is " + selKey);
                            }
                            updateCount();
                            if (work.isRequestTypeRead()) {
                                if (((TCPReadRequestContextImpl) work).getReadCompletedCallback() != null) {
                                    // only allow closed for outstanding async requests
                                    vci.setReadStatetoCloseAllowedNoSync();
                                }
                            } else {
                                if (((TCPWriteRequestContextImpl) work).getWriteCompletedCallback() != null) {
                                    // only allow closed for outstanding async requests
                                    vci.setWriteStatetoCloseAllowedNoSync();
                                }
                            }
                            if (vci.getCloseWaiting()) {
                                vci.getLockObject().notify();
                            }
                        } // end-vc-sync
                    } else {
                        SelectionKey selKey = ioSocket.register(selector, selectorOp, work);
                        if (bTrace && tc.isEventEnabled()) {
                            Tr.event(this, tc, "registered " + ioSocket.getChannel() + ", key is " + selKey);
                        }
                        updateCount();
                    }
                } catch (ClosedChannelException cce) {

                    boolean completeOperation = true;
                    if (bTrace && tc.isEventEnabled())
                        Tr.event(this, tc, "SocketChannel register for " + ioSocket + " failed, exception is: " + cce);

                    // only check permission for async read/write
                    if (vci.isInputStateTrackingOperational() && !work.blockedThread) {
                        completeOperation = false;
                        if (work.isRequestTypeRead()) {
                            if (vci.requestPermissionToFinishRead()) {
                                completeOperation = true;
                            }
                        } else {
                            if (vci.requestPermissionToFinishWrite()) {
                                completeOperation = true;
                            }
                        }
                    }

                    if (completeOperation) {
                        if (!wqm.dispatch(work, cce)) {
                            // error could not be dispatched, so put request back on work
                            // queue
                            // and let it fail again later
                            addWork(work);
                        }
                    }
                    continue;
                }
            }
            if (work.hasTimeout()) {
                if (work.getTimeoutTime() < nextTimeoutTime) {
                    nextTimeoutTime = work.getTimeoutTime();
                }
            }
        } // end-while

        // if we found any work, reset quit flags
        if (null != work) {
            waitingToQuit = false;
            quit = false;
        }
    }
767041
def create_new_model(model, from_method)
      if model.is_a?(Model)
        if model.buffer?
          fail "The #{from_method} does not take a buffer.  Call .save! on buffer's to persist them."
        end

        # Set the new path and the persistor.
        model.options = @options.merge(parent: self, path: @options[:path] + [:[]])
      else
        model = wrap_values([model]).first
      end


      if model.is_a?(Model)
        promise = model.can_create?.then do |can_create|
          unless can_create
            fail "permissions did not allow create for #{model.inspect}"
          end
        end.then do

          # Add it to the array and trigger any watches or on events.
          reactive_array_append(model)

          @persistor.added(model, @array.size - 1)
        end.then do
          nil.then do
            # Validate and save
            model.run_changed
          end.then do
            # Mark the model as not new
            model.instance_variable_set('@new', false)

            # Mark the model as loaded
            model.change_state_to(:loaded_state, :loaded)

          end.fail do |err|
            # remove from the collection because it failed to save on the server
            # we don't need to call delete on the server.
            index = @array.index(model)
            delete_at(index, true)

            # remove from the id list
            @persistor.try(:remove_tracking_id, model)

            # re-raise, err might not be an Error object, so we use a rejected promise to re-raise
            Promise.new.reject(err)
          end
        end
      else
        promise = nil.then do
          # Add it to the array and trigger any watches or on events.
          reactive_array_append(model)

          @persistor.added(model, @array.size - 1)
        end
      end

      promise = promise.then do
        # resolve the model
        model
      end

      # unwrap the promise if the persistor is synchronus.
      # This will return the value or raise the exception.
      promise = promise.unwrap unless @persistor.async?

      # return
      promise
    end
1121787
function() {
      this.candidates = []; // flush, if any
      for(var i=0;i<this.num_candidates;i++) {
        var cand = this.sampleCandidate();
        this.candidates.push(cand);
      }
    }
725782
function (event) {
      event.preventDefault();
      var collection = this.getCollection();
      var id = this.state.id;
      var model;
      if (id) {
        // Update existing model
        model = collection.get(id);
        model.save(this.state, {wait: true});
      } else {
        // Create a new one
        collection.create(this.state, {wait: true});
      }
      // Set initial state
      this.replaceState(this.getInitialState());
    }
244699
def migrate_constituencies(apps, schema_editor):
    
    Constituency = apps.get_model("representatives", "Constituency")
    for c in Constituency.objects.all():
        c.save()