If we discover a Leader with the same term — step down
483315
def on_receive_append_entries(self, data):
        """"""
        if self.storage.term == data['term']:
            self.state.to_follower()
246002
private void changeRole(PrimaryTerm term) {
    threadContext.execute(() -> {
      if (term.term() >= currentTerm) {
        log.debug("{} - Term changed: {}", memberId, term);
        currentTerm = term.term();
        leader = term.primary() != null ? term.primary().memberId() : null;
        followers = term.backups(replicationFactor - 1)
            .stream()
            .map(GroupMember::memberId)
            .collect(Collectors.toList());

        if (Objects.equals(leader, clusterMembershipService.getLocalMember().id())) {
          if (this.role == null) {
            this.role = new LeaderRole(this);
            log.debug("{} transitioning to {}", clusterMembershipService.getLocalMember().id(), Role.LEADER);
          } else if (this.role.role() != Role.LEADER) {
            this.role.close();
            this.role = new LeaderRole(this);
            log.debug("{} transitioning to {}", clusterMembershipService.getLocalMember().id(), Role.LEADER);
          }
        } else if (followers.contains(clusterMembershipService.getLocalMember().id())) {
          if (this.role == null) {
            this.role = new FollowerRole(this);
            log.debug("{} transitioning to {}", clusterMembershipService.getLocalMember().id(), Role.FOLLOWER);
          } else if (this.role.role() != Role.FOLLOWER) {
            this.role.close();
            this.role = new FollowerRole(this);
            log.debug("{} transitioning to {}", clusterMembershipService.getLocalMember().id(), Role.FOLLOWER);
          }
        } else {
          if (this.role == null) {
            this.role = new NoneRole(this);
            log.debug("{} transitioning to {}", clusterMembershipService.getLocalMember().id(), Role.NONE);
          } else if (this.role.role() != Role.NONE) {
            this.role.close();
            this.role = new NoneRole(this);
            log.debug("{} transitioning to {}", clusterMembershipService.getLocalMember().id(), Role.NONE);
          }
        }
      }
    });
  }
1074726
def down_by_name(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1):
    """"""
    files = command.list_files(*filters, remote_dir=remote_dir)
    greatest = sorted(files, key=lambda f: f.filename)
    to_sync = greatest[-count:]
    _notify_sync(Direction.down, to_sync)
    down_by_files(to_sync[::-1], local_dir=local_dir)
572436
function LeaderElection(client, path, id) {
  EventEmitter.call(this);

  /**
   * Ref. to client.
   *
   * @type {Rorschach}
   */
  this.client = client;


  /**
   * ZooKeeper path where participants' nodes exist.
   *
   * @type {String}
   */
  this.path = path;


  /**
   * Id of participant. It's kept in node.
   *
   * @type {String}
   */
  this.id = id;


  /**
   * Leadership state
   *
   * @type {Boolean}
   */
  this.isLeader = false;


  /**
   * Initial state.
   *
   * @type {State}
   */
  this.state = State.LATENT;
}
570457
protected boolean updateTermAndLeader(long term, int leader) {
    // If the request indicates a term that is greater than the current term or no leader has been
    // set for the current term, update leader and term.
    if (term > context.getTerm() || (term == context.getTerm() && context.getLeader() == null && leader != 0)) {
      context.setTerm(term);
      context.setLeader(leader);

      // Reset the current cluster configuration to the last committed configuration when a leader change occurs.
      context.getClusterState().reset();
      return true;
    }
    return false;
  }
1224776
private void makeIncoming() {
        if (stays == null && move == null) {
            for (BitSet in : ins) {
                in.clear();
            }
            stays = new BitSet();
            move = new BitSet();
            for (int i = 0; i < hosts.length; i++) {
                if (hosts[i] != null && hosts[i].isInstantiated()) {
                    int newPos = hosts[i].getValue();
                    if (oldPos[i] != -1 && newPos != oldPos[i]) {
                        //The VM has move
                        ins[newPos].set(i);
                        move.set(i);
                    } else if (newPos == oldPos[i]) {
                        stays.set(i);
                    }
                }
            }
        }
    }
908145
public void setLeader(MemberId leader) {
    if (!Objects.equals(this.leader, leader)) {
      if (leader == null) {
        this.leader = null;
      } else {
        // If a valid leader ID was specified, it must be a member that's currently a member of the
        // ACTIVE members configuration. Note that we don't throw exceptions for unknown members. It's
        // possible that a failure following a configuration change could result in an unknown leader
        // sending AppendRequest to this server. Simply configure the leader if it's known.
        DefaultRaftMember member = cluster.getMember(leader);
        if (member != null) {
          this.leader = leader;
          log.info("Found leader {}", member.memberId());
          electionListeners.forEach(l -> l.accept(member));
        }
      }

      this.lastVotedFor = null;
      meta.storeVote(null);
    }
  }
359505
def stepBy(self, steps):
        
        self.setValue(self.value() + steps*self.singleStep())
1266391
CompletableFuture<Void> identify() {
    Member leader = context.getLeader();
    if (joinFuture != null && leader != null) {
      if (context.getLeader().equals(member())) {
        if (context.getState() == CopycatServer.State.LEADER && !((LeaderState) context.getServerState()).configuring()) {
          if (joinFuture != null)
            joinFuture.complete(null);
        } else {
          cancelJoinTimer();
          joinTimeout = context.getThreadContext().schedule(context.getElectionTimeout().multipliedBy(2), this::identify);
        }
      } else {
        cancelJoinTimer();
        joinTimeout = context.getThreadContext().schedule(context.getElectionTimeout().multipliedBy(2), this::identify);

        LOGGER.debug("{} - Sending server identification to {}", member().address(), leader.address());
        context.getConnections().getConnection(leader.serverAddress()).thenCompose(connection -> {
          ReconfigureRequest request = ReconfigureRequest.builder()
            .withIndex(configuration.index())
            .withTerm(configuration.term())
            .withMember(member())
            .build();
          LOGGER.trace("{} - Sending {} to {}", member.address(), request, leader.address());
          return connection.<ConfigurationRequest, ConfigurationResponse>sendAndReceive(request);
        }).whenComplete((response, error) -> {
          cancelJoinTimer();
          if (error == null) {
            LOGGER.trace("{} - Received {}", member.address(), response);
            if (response.status() == Response.Status.OK) {
              if (joinFuture != null) {
                joinFuture.complete(null);
              }
            } else if (response.error() == null || response.error() == CopycatError.Type.CONFIGURATION_ERROR) {
              LOGGER.debug("{} - Failed to update configuration: configuration change already in progress", member.address());
              joinTimeout = context.getThreadContext().schedule(context.getElectionTimeout().multipliedBy(2), this::identify);
            }
          } else {
            LOGGER.warn("{} - Failed to update configuration: {}", member.address(), error.getMessage());
            joinTimeout = context.getThreadContext().schedule(context.getElectionTimeout().multipliedBy(2), this::identify);
          }
        });
      }
    }
    return joinFuture;
  }
271642
public boolean abandonLeadership(String entityIdentifier, boolean healthyConnection) {
    Hold hold = maintenanceHolds.remove(entityIdentifier);
    return (hold != null) && healthyConnection && silentlyUnlock(hold, entityIdentifier);
  }
51915
def _on_leave(self, event):
        """"""
        if self._toplevel:
            self._toplevel.destroy()
            self._toplevel = None
        if self._id:
            self.master.after_cancel(self._id)
            self._id = None
572519
def decrease_step(self) -> str:
        
        if self._steps_index > 0:
            self._steps_index = self._steps_index - 1
        return 'step: {}'.format(self.current_step())
1199997
def on_discovery_remove(self, name):
        
        self.configurables[Discovery][name].stop()

        self.sync_balancer_files()
217971
function down(){
        var key = (grunt.option('name') || ""),
            label = ( key || "EMPTY"),
            cmd = (migrateBinPath + " down " + key).trim();

        grunt.log.write('Running migration "DOWN" [' + label + ']...').ok();
        run(cmd);
    }
498628
private void pessimisticSearchNext(
                                      DeleteStack    stack)
    {
        synchronized(_index)
        {
            internalSearchNext(stack, _index.vno(), _index.xno());
            _pessimisticSearchNexts++;
        }
    }
164555
@Override
	public void notifyLeaderAddress(String leaderAddress, UUID leaderSessionID) {
		future.complete(new LeaderAddressAndId(leaderAddress, leaderSessionID));
	}
1110098
private MetricGroup up_down_host_(String host, boolean up) {
        final GroupName group = GroupName.valueOf(
                getBasePath(),
                Tags.valueOf(singletonMap("host", MetricValue.fromStrValue(host))));
        return new SimpleMetricGroup(group, singleton(up ? UP_METRIC : DOWN_METRIC));
    }