Retrieves a st of previous commits and Pulls and tries to reconnect them
436295
private void processOrphanCommits(GitHubRepo repo) {
        long refTime = Math.min(System.currentTimeMillis() - gitHubSettings.getCommitPullSyncTime(), gitHubClient.getRepoOffsetTime(repo));
        List<Commit> orphanCommits = commitRepository.findCommitsByCollectorItemIdAndTimestampAfterAndPullNumberIsNull(repo.getId(), refTime);
        List<GitRequest> pulls = gitRequestRepository.findByCollectorItemIdAndMergedAtIsBetween(repo.getId(), refTime, System.currentTimeMillis());
        orphanCommits = CommitPullMatcher.matchCommitToPulls(orphanCommits, pulls);
        List<Commit> orphanSaveList = orphanCommits.stream().filter(c -> !StringUtils.isEmpty(c.getPullNumber())).collect(Collectors.toList());
        orphanSaveList.forEach( c -> LOG.info( "Updating orphan " + c.getScmRevisionNumber() + " " +
                new DateTime(c.getScmCommitTimestamp()).toString("yyyy-MM-dd hh:mm:ss.SSa") + " with pull " + c.getPullNumber()));
        commitRepository.save(orphanSaveList);
    }
720378
function compileHistory(resultingArrayOfCommits) {
  var lastSha;
  if (historyCommits.length > 0) {
    lastSha = historyCommits[historyCommits.length - 1].commit.sha();
    if (
      resultingArrayOfCommits.length == 1 &&
      resultingArrayOfCommits[0].commit.sha() == lastSha
    ) {
      return;
    }
  }

  resultingArrayOfCommits.forEach(function(entry) {
    historyCommits.push(entry);
  });

  lastSha = historyCommits[historyCommits.length - 1].commit.sha();

  walker = repo.createRevWalk();
  walker.push(lastSha);
  walker.sorting(nodegit.Revwalk.SORT.TIME);

  return walker.fileHistoryWalk(historyFile, 500)
    .then(compileHistory);
}
287680
def run_all_commits
      commits = get_commits
      
      until commits.empty? do
        commits.each {|c| run_commit(c)}
        
        commits = get_commits
      end
    end
969749
def extract_log(rpath,extract=simple_attributes):
    
    # Get repo
    m_repo = git.Repo(rpath)

    # Count commits
    count = 0
    m_commits = m_repo.iter_commits()
    for commit in m_commits:
        count += 1

    # Initialize progress bar and index

    with tqdm.tqdm(total=count) as pbar:

        # Get commits again
        m_commits = m_repo.iter_commits()

        # Setup test_data extraction
        update_interval = max(min(count//100,100),5)
        index = 0
        buffer = []

        # Extract commit test_data
        while True:

            # Add the next commit to the buffer
            try:
                next_commit = next(m_commits)
                buffer.append(make_object_dict(next_commit,extract))
                index += 1
                if index%update_interval == 0:
                    pbar.update(update_interval)

            # If no more commits, clear the buffer
            except StopIteration:
                break

    # final_df = pd.concat(sub_df_list)
    return pd.DataFrame(buffer)
918764
function findRepos(callback) {
  var cwd = process.cwd(),
      tasks = [];

  fs.readdir(cwd, function(err, files) {
    if (err) return callback(err);

    var repos = [];
    files.forEach(function(file) {
      if (fs.existsSync(path.join(cwd, file, '.git'))) {
        repos.push(path.join(cwd, file));
      }
    });

    if (repos.length === 0) {
      return callback(new Error('No repositories found'));
    }

    repos.forEach(function(dir) {
      tasks.push(function(done) {
        done(err, git(dir));
      });
    });

    async.series(tasks, function(err, results) {
      callback(err, results);
    });
  });
}
27061
def commit(self, commit):
		
		try:
			changesets = self.repo.log(revrange=commit)
		except error.CommandError:
			raise KeyError("Commit %s not found" % commit)

		return self._commitData(changesets[0])
827094
def Commit(self):
		
		self.lock.acquire()
		try:
			for bucket in self.connections.values():
				try:
					for conn in bucket:
						conn.lock()
						try:
							conn.commit()
							conn.release()
						except Exception:
							conn.release()
				except Exception:
					pass
		finally:
			self.lock.release()
1151203
function (callback) {
        var conn = this.connection(),
            id = this._id; // use the raw ID object

        // prevent new transactions from using this connection.
        this.disconnect();

        // if commit was called with no active conn, it implies, no transact action
        // was called. as such it is an error.
        if (!conn) {
            // allow one pseudo commit even without connection, so that programmatic call of repeated commits or
            // rollbacks can be trapped.
            // note that the absence of `_id` indicates that a `.disconnect` was called.
            return callback && callback(id ? null : new AdapterError(AdapterError.TRANSACTION_UNINITIATED_COMM));
        }

        // we commit the connection and then release from hash
        conn.commit(function (error) {
            // try releasing the connection.
            // if that fails then treat it as a major error.
            try {
                conn.release();
            }
            // if there was an error during release, set that as the main error.
            catch (err) {
                !error && (error = err);
            }

            // if failure to issue commit or release, then rollback
            if (error && conn.transactionConfig.rollbackOnError) {
                return conn.rollback(function () {
                    // disassociate the connection from transaction and execute callback
                    Transaction.disassociateConnection(conn);
                    callback && callback(error);
                });
            }

            // disassociate the connection from transaction and execute callback
            Transaction.disassociateConnection(conn);
            callback && callback(error);
        });
    }
453288
def reconnect(self, old_node, new_node):
        

        self._check_node(old_node)
        self._check_node(new_node)
        if old_node.id == new_node.id:
            return
        old_rel = _rel_helper(lhs='us', rhs='old', ident='r', **self.definition)

        # get list of properties on the existing rel
        result, meta = self.source.cypher(
            "MATCH (us), (old) WHERE id(us)={self} and id(old)={old} "
            "MATCH " + old_rel + " RETURN r", {'old': old_node.id})
        if result:
            node_properties = _get_node_properties(result[0][0])
            existing_properties = node_properties.keys()
        else:
            raise NotConnected('reconnect', self.source, old_node)

        # remove old relationship and create new one
        new_rel = _rel_helper(lhs='us', rhs='new', ident='r2', **self.definition)
        q = "MATCH (us), (old), (new) " \
            "WHERE id(us)={self} and id(old)={old} and id(new)={new} " \
            "MATCH " + old_rel
        q += " CREATE UNIQUE" + new_rel

        # copy over properties if we have
        for p in existing_properties:
            q += " SET r2.{0} = r.{1}".format(p, p)
        q += " WITH r DELETE r"

        self.source.cypher(q, {'old': old_node.id, 'new': new_node.id})
545922
private TransactionRecoveryResult attemptRecovery(List<ReplayLog> oldReplayLog) throws SQLException{
		boolean tryAgain = false;
		Throwable failedThrowable = null;

		ConnectionHandle con = this.connectionHandle.get();
		if (con == null){ // safety! 
			throw PoolUtil.generateSQLException("ConnectionHandle is gone!", new IllegalStateException());
		}
		TransactionRecoveryResult recoveryResult = con.recoveryResult;
		ConnectionHook connectionHook = con.getPool().getConfig().getConnectionHook();

		int acquireRetryAttempts = con.getPool().getConfig().getAcquireRetryAttempts();
		long acquireRetryDelay = con.getPool().getConfig().getAcquireRetryDelayInMs();
		AcquireFailConfig acquireConfig = new AcquireFailConfig();
		acquireConfig.setAcquireRetryAttempts(new AtomicInteger(acquireRetryAttempts));
		acquireConfig.setAcquireRetryDelayInMs(acquireRetryDelay);
		acquireConfig.setLogMessage("Failed to replay transaction");

		Map<Object, Object> replaceTarget = new HashMap<Object, Object>();
		do{
			replaceTarget.clear(); 
			// make a copy
			for (Entry<Object, Object> entry: recoveryResult.getReplaceTarget().entrySet()){
				replaceTarget.put(entry.getKey(), entry.getValue());
			}

			List<PreparedStatement> prepStatementTarget = new ArrayList<PreparedStatement>();
			List<CallableStatement> callableStatementTarget = new ArrayList<CallableStatement>();
			List<Statement> statementTarget = new ArrayList<Statement>();
			Object result = null;
			tryAgain = false;
			// this connection is dead
			con.setInReplayMode(true); // don't go in a loop of saving our saved log!
			try{
				con.clearStatementCaches(true);
				con.getInternalConnection().close();
			} catch(Throwable t){
				// do nothing - also likely to fail here
			}
			try{
				con.setInternalConnection(memorize(con.getPool().obtainInternalConnection(con), con));
			} catch(SQLException e){
				throw con.markPossiblyBroken(e);
			}

			con.getOriginatingPartition().trackConnectionFinalizer(con); // track this too.

			for (ReplayLog replay: oldReplayLog){

				// we got new connections/statement handles so replace what we've got with the new ones
				if (replay.getTarget() instanceof Connection){
					replaceTarget.put(replay.getTarget(), con.getInternalConnection());
				}  else if (replay.getTarget() instanceof CallableStatement){
					if (replaceTarget.get(replay.getTarget()) == null){
						replaceTarget.put(replay.getTarget(), callableStatementTarget.remove(0));
					}
				} else if (replay.getTarget() instanceof PreparedStatement){
					if (replaceTarget.get(replay.getTarget()) == null){
						replaceTarget.put(replay.getTarget(), prepStatementTarget.remove(0));
					}
				}else if (replay.getTarget() instanceof Statement){
					if (replaceTarget.get(replay.getTarget()) == null){
						replaceTarget.put(replay.getTarget(), statementTarget.remove(0));
					}
				}


				try {
					// run again using the new connection/statement
					//					result = replay.getMethod().invoke(, replay.getArgs());
					result = runWithPossibleProxySwap(replay.getMethod(), replaceTarget.get(replay.getTarget()), replay.getArgs());

					// remember what we've got last 
					recoveryResult.setResult(result);

					// if we got a new statement (eg a prepareStatement call), save it, we'll use it for our search/replace
					if (result instanceof CallableStatement){
						callableStatementTarget.add((CallableStatement)result);
					} else if (result instanceof PreparedStatement){
						prepStatementTarget.add((PreparedStatement)result);
					} else if (result instanceof Statement){
						statementTarget.add((Statement)result);
					}  
				} catch (Throwable t) {
					// It blew up again, let's try a couple more times before giving up...
					// call the hook, if available.
					if (connectionHook != null){
						tryAgain = connectionHook.onAcquireFail(t, acquireConfig);
					} else {

						logger.error("Failed to replay transaction. Sleeping for "+acquireRetryDelay+"ms and trying again. Attempts left: "+acquireRetryAttempts+". Exception: "+t.getCause() + " Message:"+t.getMessage());

						try {
							Thread.sleep(acquireRetryDelay);
							if (acquireRetryAttempts > 0){
								tryAgain = (--acquireRetryAttempts) != 0;
							}
						} catch (InterruptedException e) {
							tryAgain=false;
						}
					}
					if (!tryAgain){
						failedThrowable = t;
					}
					break;
				}
			}
		} while (tryAgain);

		// fill last successful results
		for (Entry<Object, Object> entry: replaceTarget.entrySet()){
			recoveryResult.getReplaceTarget().put(entry.getKey(), entry.getValue());
		}

		for (ReplayLog replay: oldReplayLog){
			replay.setTarget(replaceTarget.get(replay.getTarget())); // fix our log
		}

		if (failedThrowable != null){
			throw PoolUtil.generateSQLException(failedThrowable.getMessage(), failedThrowable);
		}


		return recoveryResult;
	}
244393
function pull() {
  var tasks = [],
      cwd = process.cwd();

  findRepos(function(err, repos) {
    if (err) return console.log(err);
    repos.forEach(function(repo) {
      tasks.push(function(done) {
        repo.status(function(err, status) {
          var name = status.repo.path.replace(cwd + '/', '');
          if (!status.clean) {
            console.log('Skipped '.red + name.bold + ' (not clean)'.grey);
            done();
          }
          else {
            console.log('Pulling '.green + name.bold);
            process.chdir(status.repo.path);
            exec('git fetch', function(err, stdout, stderr) {
              if (err) return done(stderr);
              if (stdout && argv.v) console.log(indent(stdout));
              exec('git rebase', function(err, stdout, stderr) {
                if (err) return done(stderr);
                if (stdout && argv.v) console.log(indent(stdout));
                done(null);
              });
            });
          }
        });
      });
    });

    async.series(tasks, function(err, results) {
      if (err) {
        console.log('Error:'.red);
        console.log(err);
      }
      else {
        console.log('Done!');
      }
    });
  });
}
1035471
def traverse_commits(self) -> Generator[Commit, None, None]:
        

        if isinstance(self._path_to_repo, str):
            self._path_to_repo = [self._path_to_repo]

        for path_repo in self._path_to_repo:
            # if it is a remote repo, clone it first in a temporary folder!
            if self._isremote(path_repo):
                tmp_folder = tempfile.TemporaryDirectory()
                path_repo = self._clone_remote_repos(tmp_folder.name,
                                                     path_repo)

            git_repo = GitRepository(path_repo)

            self._sanity_check_filters(git_repo)
            self._check_timezones()

            logger.info('Analyzing git repository in %s', git_repo.path)

            if self._filepath is not None:
                self._filepath_commits = git_repo.get_commits_modified_file(
                    self._filepath)

            for commit in git_repo.get_list_commits(self._only_in_branch,
                                                    not self._reversed_order):
                logger.info('Commit #%s in %s from %s', commit.hash,
                            commit.committer_date,
                            commit.author.name)

                if self._is_commit_filtered(commit):
                    logger.info('Commit #%s filtered', commit.hash)
                    continue

                yield commit
1194717
def get_commits(self, since_sha=None):
        
        assert self.tempdir

        cmd = ['git', 'log', '--first-parent', '--reverse', COMMIT_FORMAT]
        if since_sha:
            commits = [self.get_commit(since_sha)]
            cmd.append('{}..HEAD'.format(since_sha))
        else:
            commits = []
            cmd.append('HEAD')

        output = cmd_output(*cmd, cwd=self.tempdir)

        for sha, date in chunk_iter(output.splitlines(), 2):
            commits.append(Commit(sha, int(date)))

        return commits
1096166
def reconnect
      tries = 0
      begin
        redis.synchronize do |client|
          client.reconnect
        end
      rescue Redis::BaseConnectionError
        if (tries += 1) <= 3
          log "Error reconnecting to Redis; retrying"
          sleep(tries)
          retry
        else
          log "Error reconnecting to Redis; quitting"
          raise
        end
      end
    end
350844
function tryRepairConnectionStart(moved, other, newDocking, points) {
  return _tryRepairConnectionSide(moved, other, newDocking, points);
}
554558
def get_commit(self, sha):
        
        assert isinstance(sha, (str, unicode)), sha
        headers, data = self._requester.requestJsonAndCheck(
            "GET",
            self.url + "/commits/" + sha
        )
        return github.Commit.Commit(self._requester, headers, data, completed=True)
576107
def amended_commits(commits):
    """"""
    # which SHA1 are declared as amended later?
    amended_sha1s = []
    for message in commits.values():
        amended_sha1s.extend(re.findall(r'AMENDS\s([0-f]+)', message))
    return amended_sha1s