auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public WebElement getDisplayNameField(int instrNum) { return browser.driver.findElement(By.cssSelector("#instructorTable" + instrNum + " input[name='" + Const.ParamsNames.INSTRUCTOR_DISPLAY_NAME + "']")); }

Target:
public WebElement getDisplayNameField(int instrNum) { String displayNameFieldSelector = "#instructorTable" + instrNum + " input[name='" + Const.ParamsNames.INSTRUCTOR_DISPLAY_NAME + "']"; return browser.driver.findElement(By.cssSelector(displayNameFieldSelector)); }
Source:
void synchronizeGroups() { boolean isParkingPluginEnable = OsmandPlugin.getEnabledPlugin(ParkingPositionPlugin.class) != null; favoriteGroups.clear(); groups.clear(); List<FavoriteGroup> disablesGroups = new ArrayList<>(); List<FavoriteGroup> gs = helper.getFavoriteGroups(); Set<?> flt = filter; for (FavoriteGroup key : gs) { boolean empty = true; if (flt == null || flt.contains(key)) { if (key.personal) { ArrayList<FavouritePoint> list = new ArrayList<>(); for (FavouritePoint p : key.points) { if (p.getName().equals(FavouritePoint.PointType.PARKING.getName())) { if (isParkingPluginEnable) { list.add(p); empty = false; } } else { if (p.getName().equals(FavouritePoint.PointType.PARKING.getName())) { if (isParkingPluginEnable) { list.add(p); empty = false; } } else { list.add(p); empty = false; } } } favoriteGroups.put(key, list); } else { empty = false; favoriteGroups.put(key, new ArrayList<>(key.points)); } } else { ArrayList<FavouritePoint> list = new ArrayList<>(); for (FavouritePoint p : key.points) { if (flt.contains(p)) { list.add(p); empty = false; } } favoriteGroups.put(key, list); } if (!empty) { if (key.visible) { groups.add(key); } else { disablesGroups.add(key); } } } groups.addAll(disablesGroups); notifyDataSetChanged(); }

Target:
void synchronizeGroups() { favoriteGroups.clear(); groups.clear(); List<FavoriteGroup> disablesGroups = new ArrayList<>(); List<FavoriteGroup> gs = helper.getFavoriteGroups(); Set<?> flt = filter; for (FavoriteGroup key : gs) { boolean empty = true; if (flt == null || flt.contains(key)) { empty = false; favoriteGroups.put(key, new ArrayList<>(key.getPoints())); } else { ArrayList<FavouritePoint> list = new ArrayList<>(); for (FavouritePoint p : key.getPoints()) { if (flt.contains(p)) { list.add(p); empty = false; } } favoriteGroups.put(key, list); } if (!empty) { if (key.isVisible()) { groups.add(key); } else { disablesGroups.add(key); } } } groups.addAll(disablesGroups); notifyDataSetChanged(); }
Source:
public static void init(ProcessingEnvironment processingEnv) { OptionsHelper optionsHelper = new OptionsHelper(processingEnv); GENERATION_SUFFIX = optionsHelper.getGenerationSuffix(); }

Target:
public static void init(ProcessingEnvironment processingEnv) { OptionsHelper optionsHelper = new OptionsHelper(processingEnv); classSuffix = optionsHelper.getClassSuffix().trim(); if (classSuffix.isEmpty()) { throw new IllegalArgumentException("'" + classSuffix + "' may not be an emtpy string."); } if (!SourceVersion.isName(classSuffix) || classSuffix.contains(".")) { throw new IllegalArgumentException("'" + classSuffix + "' is not a valid Java identifier."); } }
Source:
@Override public long length() { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); writeTo(out); return out.size(); } catch (IOException ex) { throw new RuntimeException(ex); } }

Target:
@Override public long length() { return length; }
Source:
private SymbolReference<? extends ResolvedValueDeclaration> solveSymbolForFQN(String symbolName, TypeSolver typeSolver, String fqn) { if (fqn == null) { return SymbolReference.unsolved(ResolvedValueDeclaration.class); } ResolvedReferenceTypeDeclaration superClass = typeSolver.solveType(fqn); return new SymbolSolver(typeSolver).solveSymbolInType(superClass, symbolName); }

Target:
private SymbolReference<? extends ResolvedValueDeclaration> solveSymbolForFQN(String symbolName, TypeSolver typeSolver, String fqn) { if (fqn == null) { return SymbolReference.unsolved(ResolvedValueDeclaration.class); } ResolvedReferenceTypeDeclaration fqnTypeDeclaration = typeSolver.solveType(fqn); return new SymbolSolver(typeSolver).solveSymbolInType(fqnTypeDeclaration, symbolName); }
Source:
public String exportSampleList(@RequestBody final Map<String, String> data, @PathVariable final int exportType, final HttpServletRequest req, final HttpServletResponse response) { ExportSampleListController.LOG.info("Entering Export exportSampleList"); ExportSampleListController.LOG.info("Exiting Export exportSampleList"); return this.doExport(response, exportType, data); }

Target:
public String exportSampleList(@RequestBody final Map<String, String> data, @PathVariable final int exportType, final HttpServletRequest req, final HttpServletResponse response) { ExportSampleListController.LOG.debug("Entering Export exportSampleList"); final String export = this.doExport(response, exportType, data); ExportSampleListController.LOG.debug("Exiting Export exportSampleList"); return export; }
Source:
Mono<BlobBatchOperationInfo> prepareBlobBatchSubmission() { if (batchOperationQueue.isEmpty()) { return Mono.error(new UnsupportedOperationException("Empty batch requests aren't allowed.")); } BlobBatchOperationInfo operationInfo = new BlobBatchOperationInfo(); Deque<BlobBatchOperation<?>> operations = batchOperationQueue; batchOperationQueue = new ConcurrentLinkedDeque<>(); return Flux.generate(sink -> { if (operations.isEmpty()) { operationInfo.finalizeBatchOperations(); sink.complete(); } else { BlobBatchOperation<?> batchOperation = operations.pop(); sink.next(batchOperation.getResponse() .subscriberContext(Context.of(BATCH_REQUEST_URL_PATH, batchOperation.getRequestUrlPath(), BATCH_OPERATION_RESPONSE, batchOperation.getBatchOperationResponse(), BATCH_OPERATION_INFO, operationInfo)) .subscribe()); } }).then(Mono.just(operationInfo)); }

Target:
Mono<BlobBatchOperationInfo> prepareBlobBatchSubmission() { if (batchOperationQueue.isEmpty()) { return monoError(logger, new UnsupportedOperationException("Empty batch requests aren't allowed.")); } BlobBatchOperationInfo operationInfo = new BlobBatchOperationInfo(); Deque<BlobBatchOperation<?>> operations = batchOperationQueue; batchOperationQueue = new ConcurrentLinkedDeque<>(); return Flux.generate(sink -> { if (operations.isEmpty()) { operationInfo.finalizeBatchOperations(); sink.complete(); } else { BlobBatchOperation<?> batchOperation = operations.pop(); sink.next(batchOperation.getResponse() .subscriberContext(Context.of(BATCH_REQUEST_URL_PATH, batchOperation.getRequestUrlPath(), BATCH_OPERATION_RESPONSE, batchOperation.getBatchOperationResponse(), BATCH_OPERATION_INFO, operationInfo)) .subscribe()); } }).then(Mono.just(operationInfo)); }
Source:
public FeedbackResponseRow(int fbIndex, int personIndex, String personType, FeedbackResponseAttributes response, FeedbackSessionResultsBundle results) { String questionId = response.feedbackQuestionId; FeedbackQuestionAttributes question = results.questions.get(questionId); FeedbackQuestionDetails questionDetails = question.getQuestionDetails(); this.questionNumber = question.questionNumber; this.questionText = results.getQuestionText(questionId); this.questionMoreInfo = questionDetails.getQuestionAdditionalInfoHtml(this.questionNumber, personType + "-" + personIndex + "-session-" + fbIndex); if (personType.equals("recipient")) { this.responseText = response.getResponseDetails().getAnswerHtml(questionDetails); } else if (personType.equals("giver")) { this.responseText = results.getResponseAnswerHtml(response, question); } this.responseComments = new ArrayList<FeedbackResponseComment>(); List<FeedbackResponseCommentAttributes> frcs = results.responseComments.get(response.getId()); if (frcs != null && frcs.size() > 0) { for (FeedbackResponseCommentAttributes frc : frcs) { this.responseComments.add(new FeedbackResponseComment(frc, frc.giverEmail)); } } }

Target:
public FeedbackResponseRow(int fbIndex, int personIndex, String personType, FeedbackResponseAttributes response, FeedbackSessionResultsBundle results) { String questionId = response.feedbackQuestionId; FeedbackQuestionAttributes question = results.questions.get(questionId); FeedbackQuestionDetails questionDetails = question.getQuestionDetails(); this.questionNumber = question.questionNumber; this.questionText = results.getQuestionText(questionId); this.questionMoreInfo = questionDetails.getQuestionAdditionalInfoHtml(this.questionNumber, personType + "-" + personIndex + "-session-" + fbIndex); if (personType.equals("recipient")) { this.responseText = response.getResponseDetails().getAnswerHtml(questionDetails); } else if (personType.equals("giver")) { this.responseText = results.getResponseAnswerHtml(response, question); } this.responseComments = new ArrayList<FeedbackResponseComment>(); List<FeedbackResponseCommentAttributes> frcs = results.responseComments.get(response.getId()); if (frcs != null) { for (FeedbackResponseCommentAttributes frc : frcs) { this.responseComments.add(new FeedbackResponseComment(frc, frc.giverEmail)); } } }
Source:
public void doHeartBeat() throws IOException { LocalState state = ConfigUtils.workerState(workerState.conf, workerState.workerId); LSWorkerHeartbeat lsWorkerHeartbeat = new LSWorkerHeartbeat(Time.currentTimeSecs(), workerState.topologyId, workerState.localExecutors.stream() .map(executor -> new ExecutorInfo( executor.get(0).intValue(), executor.get(1).intValue())) .collect(Collectors.toList()), workerState.port); state.setWorkerHeartBeat(lsWorkerHeartbeat); state.cleanup(60); if (!workerState.stormClusterState.isPacemakerStateStore()) { LOG.debug("If pacemaker is not used, send supervisor"); heartbeatToMasterIfLocalbeatFail(lsWorkerHeartbeat); } }

Target:
public void doHeartBeat() throws IOException { LocalState state = ConfigUtils.workerState(workerState.conf, workerState.workerId); LSWorkerHeartbeat lsWorkerHeartbeat = new LSWorkerHeartbeat(Time.currentTimeSecs(), workerState.topologyId, workerState.localExecutors.stream() .map(executor -> new ExecutorInfo( executor.get(0).intValue(), executor.get(1).intValue())) .collect(Collectors.toList()), workerState.port); state.setWorkerHeartBeat(lsWorkerHeartbeat); state.cleanup(60); if (!workerState.stormClusterState.isPacemakerStateStore()) { LOG.debug("The pacemaker is not used, send heartbeat to master."); heartbeatToMasterIfLocalbeatFail(lsWorkerHeartbeat); } this.heatbeatMeter.mark(); }
Source:
private void deleteLocks(CommitData cd, final long commitTs) { ArrayList<Mutation> mutations = new ArrayList<>(updates.size() + 1); for (Entry<Bytes, Map<Column, Bytes>> rowUpdates : updates.entrySet()) { Flutation m = new Flutation(env, rowUpdates.getKey()); boolean isTriggerRow = isTriggerRow(rowUpdates.getKey()); for (Entry<Column, Bytes> colUpdates : rowUpdates.getValue().entrySet()) { ColumnUtil.commitColumn(env, isTriggerRow && colUpdates.getKey().equals(notification.getColumn()), false, colUpdates.getKey(), isWrite(colUpdates.getValue()), isDelete(colUpdates.getValue()), isReadLock(colUpdates.getValue()), startTs, commitTs, observedColumns, m); } mutations.add(m); } CompletableFuture<Void> cfuture = env.getSharedResources().getBatchWriter().writeMutationsAsyncFuture(mutations); addCallback(cfuture, cd, (cd2, result) -> finishCommit(cd, commitTs)); }

Target:
private void deleteLocks(CommitData cd, final long commitTs) { ArrayList<Mutation> mutations = new ArrayList<>(updates.size() + 1); for (Entry<Bytes, Map<Column, Bytes>> rowUpdates : updates.entrySet()) { Flutation m = new Flutation(env, rowUpdates.getKey()); boolean isTriggerRow = isTriggerRow(rowUpdates.getKey()); for (Entry<Column, Bytes> colUpdates : rowUpdates.getValue().entrySet()) { ColumnUtil.commitColumn(env, isTriggerRow && colUpdates.getKey().equals(notification.getColumn()), false, colUpdates.getKey(), isWrite(colUpdates.getValue()), isDelete(colUpdates.getValue()), isReadLock(colUpdates.getValue()), startTs, commitTs, observedColumns, m); } mutations.add(m); } CompletableFuture<Void> cfuture = env.getSharedResources().getBatchWriter().writeMutationsAsyncFuture(mutations); addCallback(cfuture, cd, result -> finishCommit(cd, commitTs)); }
Source:
public void validateCommitCursor(final NakadiCursor position) throws InvalidCursorException { validateCursorForNulls(position); KafkaCursor.fromNakadiCursor(position); }

Target:
public void validateCommitCursor(final NakadiCursor position) throws InvalidCursorException { KafkaCursor.fromNakadiCursor(position); }
Source:
public void testCreateDirectoryDialogAllowFolderNameModification() { final String directoryName = "mydir"; final DirectoryChooserFragment fragment = DirectoryChooserFragment.newInstance( directoryName, null, false, true); startFragment(fragment, DirectoryChooserActivityMock.class); fragment.onOptionsItemSelected(new TestMenuItem() { @Override public int getItemId() { return R.id.new_folder_item; } }); final AlertDialog dialog = (AlertDialog) ShadowDialog.getLatestDialog(); final ShadowAlertDialog shadowAlertDialog = Robolectric.shadowOf(dialog); assertEquals(shadowAlertDialog.getTitle(), "Create folder"); assertTrue(shadowAlertDialog.isShowing()) Button positiveBtn = shadowAlertDialog.getButton(DialogInterface.BUTTON_POSITIVE); assertNotNull(positiveBtn); TextView msgView = (TextView) dialog.findViewById(R.id.msgText); assertEquals(msgView.getText().toString(), "Create new folder with name \"mydir\"?"); EditText editText = (EditText) dialog.findViewById(R.id.editText); assertTrue(editText.getVisibility() == View.VISIBLE) assertEquals(editText.getText().toString(), "mydir"); }

Target:
public void testCreateDirectoryDialogAllowFolderNameModification() { final String directoryName = "mydir"; final DirectoryChooserFragment fragment = DirectoryChooserFragment.newInstance( directoryName, null, false, true); startFragment(fragment, DirectoryChooserActivityMock.class); fragment.onOptionsItemSelected(new TestMenuItem() { @Override public int getItemId() { return R.id.new_folder_item; } }); final AlertDialog dialog = (AlertDialog) ShadowDialog.getLatestDialog(); final ShadowAlertDialog shadowAlertDialog = Shadows.shadowOf(dialog); assertEquals(shadowAlertDialog.getTitle(), "Create folder"); assertTrue(shadowAlertDialog.isShowing()) final Button positiveBtn = shadowAlertDialog.getButton(DialogInterface.BUTTON_POSITIVE); assertNotNull(positiveBtn); final TextView msgView = (TextView) dialog.findViewById(R.id.msgText); assertEquals(msgView.getText().toString(), "Create new folder with name \"mydir\"?"); final EditText editText = (EditText) dialog.findViewById(R.id.editText); assertTrue(editText.getVisibility() == View.VISIBLE) assertEquals(editText.getText().toString(), "mydir"); }
Source:
public Void delete(@PathParam(RestParameter.ID) Long id) { ratingDao.delete(id); return null; }

Target:
public void delete(@PathParam(RestParameter.ID) Long id) { ratingDao.delete(id); }
Source:
private void initialize() { try { CVSUIPlugin.runWithProgress(null, true , monitor -> { try { ILogEntry[] entries = file.getLogEntries(monitor); String revision = file.getRevision(); for (ILogEntry entrie : entries) { if (entrie.getRevision().equals(revision)) { entry = entrie; return; } } } catch (TeamException e) { throw new InvocationTargetException(e); } }); } catch (InterruptedException e) { } catch (InvocationTargetException e) { CVSUIPlugin.openError(null, null, null, e); } }

Target:
private void initialize() { try { CVSUIPlugin.runWithProgress(null, true , monitor -> { try { ILogEntry[] entries = file.getLogEntries(monitor); String revision = file.getRevision(); for (ILogEntry e : entries) { if (e.getRevision().equals(revision)) { entry = e; return; } } } catch (TeamException e) { throw new InvocationTargetException(e); } }); } catch (InterruptedException e) { } catch (InvocationTargetException e) { CVSUIPlugin.openError(null, null, null, e); } }
Source:
private AccountInfoMap(Map<String, String> accountMap) { nameToAccountMap = new HashMap<>(); idToAccountMap = new HashMap<>(); for (Map.Entry<String, String> entry : accountMap.entrySet()) { String idKey = entry.getKey(); String valueString = entry.getValue(); Account account; try { JSONObject accountJson = new JSONObject(valueString); if (idKey == null) { logger.error( "Invalid account record when reading accountMap in ZNRecord because either idKey={} or accountJson={}" + "is null", idKey, accountJson); continue; } account = Account.fromJson(accountJson); if (account.getId() != Short.valueOf(idKey)) { logger.error( "Invalid account record when reading accountMap in ZNRecord because idKey and accountId do not match." + "idKey={}, accountId={}", idKey, account.getId()); continue; } } catch (Exception e) { logger.error("Invalid account record when reading accountMap in ZNRecord. key={}, valueString={}", idKey, valueString, e); continue; } Account conflictingAccount = nameToAccountMap.get(account.getName()); if (conflictingAccount != null) { logger.error("Duplicate account name exists. id={} name={} conflicts with a previously added id={} name={}." + "Removing account with id={} name={}", account.getId(), account.getName(), conflictingAccount.getId(), conflictingAccount.getName(), conflictingAccount.getId(), conflictingAccount.getName()); idToAccountMap.remove(conflictingAccount.getId()); nameToAccountMap.remove(conflictingAccount.getName()); } idToAccountMap.put(account.getId(), account); nameToAccountMap.put(account.getName(), account); } }

Target:
private AccountInfoMap(Map<String, String> accountMap) throws JSONException { nameToAccountMap = new HashMap<>(); idToAccountMap = new HashMap<>(); for (Map.Entry<String, String> entry : accountMap.entrySet()) { String idKey = entry.getKey(); String valueString = entry.getValue(); Account account; JSONObject accountJson = new JSONObject(valueString); if (idKey == null) { accountServiceMetrics.remoteDataCorruptionErrorCount.inc(); throw new IllegalStateException( "Invalid account record when reading accountMap in ZNRecord because idKey=null"); } account = Account.fromJson(accountJson); if (account.getId() != Short.valueOf(idKey)) { accountServiceMetrics.remoteDataCorruptionErrorCount.inc(); throw new IllegalStateException( "Invalid account record when reading accountMap in ZNRecord because idKey and accountId do not match. idKey=" + idKey + " accountId=" + account.getId()); } if (idToAccountMap.containsKey(account.getId()) || nameToAccountMap.containsKey(account.getName())) { throw new IllegalStateException( "Duplicate account id or name exists. id=" + account.getId() + " name=" + account.getName()); } idToAccountMap.put(account.getId(), account); nameToAccountMap.put(account.getName(), account); } }
Source:
private void initSwipeToRefreshHelper(View view) { if (view == null) { return; } mSwipeToRefreshHelper = new SwipeToRefreshHelper( this, (CustomSwipeRefreshLayout) view.findViewById(R.id.ptr_layout), new SwipeToRefreshHelper.RefreshListener() { @Override public void onRefreshStarted() { if (isFinishing()) { return; } if (!NetworkUtils.checkConnection(SitePickerActivity.this)) { mSwipeToRefreshHelper.setRefreshing(false); ToastUtils.showToast(SitePickerActivity.this, R.string.site_picker_no_network_refresh_error); return; } mDispatcher.dispatch(SiteActionBuilder.newRemoveWpcomAndJetpackSitesAction()); mSwipeToRefreshHelper.setRefreshing(true); mDispatcher.dispatch(SiteActionBuilder.newFetchSitesAction()); } }); }

Target:
private void initSwipeToRefreshHelper(View view) { if (view == null) { return; } mSwipeToRefreshHelper = new SwipeToRefreshHelper( this, (CustomSwipeRefreshLayout) view.findViewById(R.id.ptr_layout), new SwipeToRefreshHelper.RefreshListener() { @Override public void onRefreshStarted() { if (isFinishing()) { return; } if (!NetworkUtils.checkConnection(SitePickerActivity.this)) { mSwipeToRefreshHelper.setRefreshing(false); return; } mDispatcher.dispatch(SiteActionBuilder.newFetchSitesAction()); } }); }
Source:
public static FileMetadata lookup(Connection sql, int fid) throws ServiceException{ OMUtil.sqlCheck(sql); ResultSet result = FileMetadataTable.lookUpFile(sql, fid); try{ if (!result.next()) { throw new ServiceException(ServiceStatus.APP_FILE_NOT_EXIST); } FileMetadata fileData = new FileMetadata(result.getInt("fid"), result.getString("user"), result.getString("course"), result.getString("university"), result.getDate("creation_date"), result.getInt("rating")); result.close(); return fileData; } catch (SQLException ex) { throw new ServiceException(ServiceStatus.DATABASE_ERROR, ex); } }

Target:
public static FileMetadata lookup(Connection sql, int fid) throws ServiceException{ OMUtil.sqlCheck(sql); ResultSet result = FileMetadataTable.lookUpFile(sql, fid); try{ if (!result.next()) { throw new ServiceException(ServiceStatus.APP_FILE_NOT_EXIST); } FileMetadata fileData = new FileMetadata(result.getInt("fid"), result.getInt("uid"), result.getInt("cid"), result.getDate("creation_date")); result.close(); return fileData; } catch (SQLException ex) { throw new ServiceException(ServiceStatus.DATABASE_ERROR, ex); } }
Source:
private Ordering<Row> metricOrdering(final String column, final Comparator comparator) { return new Ordering<Row>() { @SuppressWarnings("unchecked") @Override public int compare(Row left, Row right) { if (left.getRaw(column) == null & right.getRaw(column) == null) { return 0; } else if (left.getRaw(column) == null) { return 1; } else if (right.getRaw(column) == null) { return -1; } return comparator.compare(left.getRaw(column), right.getRaw(column)); } }; }

Target:
private Ordering<Row> metricOrdering(final String column, final Comparator comparator) { return Ordering.from(Comparator.comparing((Row row) -> row.getRaw(column), Comparator.nullsLast(comparator))); }
Source:
protected void executeCommand() { VDSStatus statusBeforeUpgrade = getVds().getStatus(); if (statusBeforeUpgrade != VDSStatus.Maintenance) { boolean returnValue = resourceManager.runVdsCommand(VDSCommandType.GlusterServersList, new VdsIdVDSCommandParametersBase(getVdsId())).getSucceeded(); if (returnValue) { stopGlusterServices(getVdsId()); } Future<ActionReturnValue> maintenanceCmd = commandCoordinatorUtil.executeAsyncCommand(ActionType.MaintenanceNumberOfVdss, createMaintenanceParams(), cloneContext()); ActionReturnValue result; try { result = maintenanceCmd.get(); if (!result.getSucceeded()) { propagateFailure(result); return; } } catch (InterruptedException | ExecutionException e) { log.error("Exception", e); return; } } setSucceeded(true); }

Target:
protected void executeCommand() { VDSStatus statusBeforeUpgrade = getVds().getStatus(); if (statusBeforeUpgrade != VDSStatus.Maintenance) { if (getVds().getClusterSupportsGlusterService()) { boolean returnValue = resourceManager.runVdsCommand(VDSCommandType.GlusterServersList, new VdsIdVDSCommandParametersBase(getVdsId())).getSucceeded(); if (returnValue) { stopGlusterServices(getVdsId()); } } Future<ActionReturnValue> maintenanceCmd = commandCoordinatorUtil.executeAsyncCommand(ActionType.MaintenanceNumberOfVdss, createMaintenanceParams(), cloneContext()); ActionReturnValue result; try { result = maintenanceCmd.get(); if (!result.getSucceeded()) { propagateFailure(result); return; } } catch (InterruptedException | ExecutionException e) { log.error("Exception", e); return; } } setSucceeded(true); }
Source:
protected String resolvePrincipalInternal(final X509Certificate certificate) { LOGGER.debug("Resolving principal from Subject Alternative Name UPN for [{}]", certificate); try { val upnString = X509UPNExtractor.extractUPNString(certificate); return upnString != null ? upnString : getAlternatePrincipal(certificate); } catch (final CertificateParsingException e) { LOGGER.error("Error is encountered while trying to retrieve subject alternative names collection from certificate", e); return getAlternatePrincipal(certificate); } }

Target:
protected String resolvePrincipalInternal(final X509Certificate certificate) { LOGGER.debug("Resolving principal from Subject Alternative Name UPN for [{}]", certificate); try { val upnString = X509UPNExtractorUtils.extractUPNString(certificate); return StringUtils.isNotBlank(upnString) ? upnString : getAlternatePrincipal(certificate); } catch (final CertificateParsingException e) { LOGGER.error("Error is encountered while trying to retrieve subject alternative names collection from certificate", e); return getAlternatePrincipal(certificate); } }
Source:
private FunctionElement(JAXBElement element) { super(element); if (!element.getDeclaredType().equals(FunctionType.class)) { throw new FilterProcessingException( INVALID_INVOCATION + element.getDeclaredType().getName()); } FunctionType functionType = (FunctionType) element.getValue(); this.value = new HashMap<>(); this.value.put("type", "FILTER_FUNCTION"); this.value.put("filterFunctionName", functionType.getName()); this.value.put( "params", functionType .getExpression() .stream() .map(JAXBElement::getValue) .map(LiteralType.class::cast) .map( literalType -> literalType .getContent() .stream() .findFirst() .map( serializable -> { QName qName = literalType.getType(); return QNameMapper.convert(serializable, qName); }) .orElse("")) .collect(Collectors.toList())); }

Target:
private FunctionElement(JAXBElement element) { super(element); if (!element.getDeclaredType().equals(FunctionType.class)) { throw new FilterProcessingException( INVALID_INVOCATION + element.getDeclaredType().getName()); } FunctionType functionType = (FunctionType) element.getValue(); this.value = new HashMap<>(); this.value.put("type", "FILTER_FUNCTION"); this.value.put(XmlModelBuilder.FUNCTION_PROPERTY_NAME, functionType.getName()); this.value.put( XmlModelBuilder.FUNCTION_PROPERTY_PARAMS, createFunctionPropertyParameters(functionType)); }
Source:
public void notify(final IScriptEngine engine, final Script script, final int status) { switch (status) { case SCRIPT_START: case SCRIPT_INJECTION_START: if (fDispatcher != null) { fDispatcher.put(script); } fLastScript = script; break; case ENGINE_END: fFrameToSource.clear(); fLastScript = null; break; default: break; } super.notify(engine, script, status); }

Target:
public void notify(final IScriptEngine engine, final Script script, final int status) { final IScriptRegistry scriptRegistry = getDispatcher(); switch (status) { case SCRIPT_START: case SCRIPT_INJECTION_START: if (scriptRegistry != null) { scriptRegistry.put(script); } fLastScript = script; break; case SCRIPT_END: break; case ENGINE_END: fFrameToSource.clear(); fLastScript = null; break; default: break; } super.notify(engine, script, status); }
Source:
public int compareTo(Filter other) { if (!this.methodName.equals(other.methodName)) { return this.methodName.compareTo(other.methodName); } else if (!this.className.equals(other.className)) { return this.className.compareTo(other.className); } return 0; }

Target:
public int compareTo(Filter other) { int c = methodName.compareTo(other.methodName); if (c != 0) { return c; } return className.compareTo(other.className); }
Source:
public Set<Integer> getMembers() { return members; }

Target:
public Collection<CohortMembership> getMembers() { if (members == null) { members = new TreeSet<CohortMembership>(); } return members; }
Source:
public void shouldDoNumericProjectionWithStringBasedQuery() { Party partyHasKeyword = new Party(KEY_PARTY_KEYWORD, "party", "desc is a N1QL keyword", new Date(), 4000000, new Point(500, 500)); partyRepository.save(partyHasKeyword); Optional<Party> p = null; int count = 0; do { try { Thread.sleep(1000); } catch(Exception e){} try { p = partyRepository.findById(partyHasKeyword.getKey()); } catch (DataRetrievalFailureException e) } while ( !p.isPresent() && count++ < 60); long max = partyRepository.findMaxAttendees(); assertEquals(4000000, max); }

Target:
public void shouldDoNumericProjectionWithStringBasedQuery() { Party partyHasKeyword = new Party(KEY_PARTY_KEYWORD, "party", "desc is a N1QL keyword", new Date(), 4000000, new Point(500, 500)); partyRepository.save(partyHasKeyword); long max = partyRepository.findMaxAttendees(); assertEquals(4000000, max); }
Source:
public List<FeedbackResponseAttributes> getViewableFeedbackResponsesForQuestionInSection( FeedbackQuestionAttributes question, String userEmail, UserRole role, String section, SectionDisplayMode sectionDisplayMode) { List<FeedbackResponseAttributes> viewableResponses = new ArrayList<>(); switch (role) { case STUDENT: addNewResponses( viewableResponses, getFeedbackResponsesFromGiverForQuestionInSection( question.getId(), userEmail, section)); if (question.isResponseVisibleTo(FeedbackParticipantType.RECEIVER)) { addNewResponses( viewableResponses, getFeedbackResponsesForReceiverForQuestionInSection( question.getId(), userEmail, section)); } addNewResponses(viewableResponses, getViewableFeedbackResponsesForStudentForQuestion(question, userEmail)); break; case INSTRUCTOR: if (question.isResponseVisibleTo(FeedbackParticipantType.INSTRUCTORS)) { addNewResponses(viewableResponses, getFeedbackResponsesForQuestionInSection(question.getId(), section, sectionDisplayMode)); } break; default: Assumption.fail("The role of the requesting use has to be Student or Instructor"); break; } return viewableResponses; }

Target:
public List<FeedbackResponseAttributes> getViewableFeedbackResponsesForQuestionInSection( FeedbackQuestionAttributes question, String userEmail, UserRole role, String section, SectionDisplayMode sectionDisplayMode) { List<FeedbackResponseAttributes> viewableResponses = new ArrayList<>(); switch (role) { case STUDENT: addNewResponses( viewableResponses, getFeedbackResponsesFromGiverForQuestionInSection( question.getId(), userEmail, section)); if (question.isResponseVisibleTo(FeedbackParticipantType.RECEIVER)) { addNewResponses( viewableResponses, getFeedbackResponsesForReceiverForQuestionInSection( question.getId(), userEmail, section)); } addNewResponses(viewableResponses, getViewableFeedbackResponsesForStudentForQuestion(question, userEmail)); break; case INSTRUCTOR: if (question.isResponseVisibleTo(FeedbackParticipantType.INSTRUCTORS)) { addNewResponses(viewableResponses, getFeedbackResponsesForQuestionInSection(question.getId(), section, sectionDisplayMode)); } if (!question.isResponseVisibleTo(FeedbackParticipantType.RECEIVER)) { viewableResponses = excludeResponsesWithReceiverEmail(viewableResponses, userEmail); } break; default: Assumption.fail("The role of the requesting use has to be Student or Instructor"); break; } return viewableResponses; }
Source:
public LockRangeDialog(Shell parentShell, TmfXYChartViewer chartViewer) { super(parentShell); this.fChartViewer = chartViewer; }

Target:
public LockRangeDialog(Shell parentShell, TmfXYChartViewer chartViewer) { super(parentShell); fChartViewer = chartViewer; }
Source:
public void testNonMethodChainWordcount() throws Exception { TupleCollector<Map<Object, Integer>> collector = new TupleCollector<>(); collector.id = "testNonMethodChainWordcount"; MyStream<String> mystream = new MyStream<>(StreamFactory .fromFolder("./src/test/resources/data")) .flatMap(new Function.FlatMapFunction<String, String>() { @Override public Iterable<String> f(String input) { return Arrays.asList(input.split(" ")); } }); mystream.filterAndMap(new Function.MapFunction<String, String>() { @Override public String f(String input) { return input.replace("word", "newword"); } }, new Function.FilterFunction<String>() { @Override public Boolean f(String input) { return input.startsWith("word"); } }).countByKey().addOperator(collector, collector.inputPort, collector.outputPort).print().runEmbedded(5000); List<Map<Object, Integer>> data = (List<Map<Object, Integer>>)TupleCollector.results.get("testNonMethodChainWordcount"); Assert.assertTrue(data.size() > 1); Assert.assertEquals(expected, data.get(data.size() - 1)); }

Target:
public void testNonMethodChainWordcount() throws Exception { testId = "testNonMethodChainWordcount"; TupleCollector<Map<Object, Integer>> collector = new TupleCollector<>(); collector.id = testId; MyStream<String> mystream = new MyStream<>(StreamFactory .fromFolder("./src/test/resources/data")) .flatMap(new Function.FlatMapFunction<String, String>() { @Override public Iterable<String> f(String input) { return Arrays.asList(input.split(" ")); } }); mystream.myFilterAndMap(new Function.MapFunction<String, String>() { @Override public String f(String input) { return input.replace("word", "newword"); } }, new Function.FilterFunction<String>() { @Override public Boolean f(String input) { return input.startsWith("word"); } }).countByKey().addOperator(collector, collector.inputPort, collector.outputPort).print().runEmbedded(false, 30000, exitCondition); List<Map<Object, Integer>> data = (List<Map<Object, Integer>>)TupleCollector.results.get(testId); Assert.assertTrue(data.size() > 1); Assert.assertEquals(expected, data.get(data.size() - 1)); }
Source:
public void searchShouldReturnAResponseWithOneTransaction_whenFilteringByCardHolderNameFromLedger() { Account account = new Account("123456", TokenPaymentType.CARD); var searchParams = new PaymentSearchParams.Builder() .withCardHolderName("J Doe") .withPageNumber("1") .withDisplaySize("500") .build(); Response response = paymentSearchService.searchLedgerPayments(account, searchParams); JsonAssert.with(response.getEntity().toString()) .assertThat("count", is(1)) .assertThat("total", is(1)) .assertThat("page", is(1)) .assertThat("results", is(collectionWithSize(equalTo(1)))) .assertThat("results[0]", hasKey("amount")) .assertThat("results[0]", hasKey("state")) .assertThat("results[0]", hasKey("reference")) .assertThat("results[0]", hasKey("email")) .assertThat("results[0].card_details.cardholder_name", is("J Doe")) .assertThat("results[0].card_details", hasKey("first_digits_card_number")) .assertThat("results[0].card_details", hasKey("last_digits_card_number")) .assertThat("results[0].state", hasKey("status")) .assertThat("results[0].state", hasKey("finished")) .assertThat("results[0]", hasKey("_links")) .assertThat("_links", hasKey("self")) .assertThat("_links", hasKey("first_page")) .assertThat("_links", hasKey("last_page")) .assertThat("results[0]._links.capture", is(nullValue())) .assertNotDefined("_links.next_page") .assertNotDefined("_links.prev_page"); }

Target:
public void searchShouldReturnAResponseWithOneTransaction_whenFilteringByCardHolderNameFromLedger() { Account account = new Account("123456", TokenPaymentType.CARD); var searchParams = new PaymentSearchParams.Builder() .withCardHolderName("J Doe") .withPageNumber("1") .withDisplaySize("500") .build(); Response response = paymentSearchService.searchLedgerPayments(account, searchParams); JsonAssert.with(response.getEntity().toString()) .assertThat("count", is(1)) .assertThat("total", is(1)) .assertThat("page", is(1)) .assertThat("results", is(collectionWithSize(equalTo(1)))) .assertThat("results[0]", hasKey("amount")) .assertThat("results[0]", hasKey("state")) .assertThat("results[0]", hasKey("reference")) .assertThat("results[0]", hasKey("email")) .assertThat("results[0].card_details.cardholder_name", is("J Doe")) .assertThat("results[0].card_details", hasKey("first_digits_card_number")) .assertThat("results[0].card_details", hasKey("last_digits_card_number")) .assertThat("results[0].state", hasKey("status")) .assertThat("results[0].state", hasKey("finished")); }
Source:
public boolean execute(BindContext context) { for (BindOperation operation : operations) { log.debug("Starting execute of {}", operation.getClass().getSimpleName()); if (operation.execute(context)) { log.debug("Finished execute of {}", operation.getClass().getSimpleName()); } else { log.error("Skipped chain execute in operation {}", operation.getClass().getSimpleName()); return false; } } return true; }

Target:
private boolean execute(BindContext context) { for (BindOperation operation : operations) { log.debug("Starting execute of {}", operation.getClass().getSimpleName()); if (operation.execute(context)) { log.debug("Finished execute of {}", operation.getClass().getSimpleName()); } else { log.error("Skipped chain execute in operation {}", operation.getClass().getSimpleName()); return false; } } return true; }
Source:
public static List<Element> lockSyncFolder(Project project) { if (!ProjectUtilities.isFromEsiServer(project.getPrimaryProject())) { return Collections.emptyList(); } String folderId = Converters.getIProjectToIdConverter().apply(project.getPrimaryProject()) + "_sync"; Element folder = Converters.getIdToElementConverter().apply(folderId, project); if (folder == null) { return Collections.emptyList(); } ILockProjectService lockService = EsiUtils.getLockService(project); if (lockService == null) { return Collections.emptyList(); } Collection<Element> ownedElements = folder.getOwnedElement(); List<Element> lockedElements = new ArrayList<>(ownedElements.size()); for (Element element : folder.getOwnedElement()) { if (element instanceof com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Class && !lockService.isLocked(element) && lockService.canBeLocked(element)) { lockedElements.add(element); } } if (!lockService.lockElements(lockedElements, false, null)) { return Collections.emptyList(); } return lockedElements; }

Target:
public static List<Element> lockSyncFolder(Project project) { if (!ProjectUtilities.isFromEsiServer(project.getPrimaryProject())) { return Collections.emptyList(); } String folderId = Converters.getIProjectToIdConverter().apply(project.getPrimaryProject()) + MDKConstants.SYNC_SYSML_ID_SUFFIX; Element folder = Converters.getIdToElementConverter().apply(folderId, project); if (folder == null) { return Collections.emptyList(); } ILockProjectService lockService = EsiUtils.getLockService(project); if (lockService == null) { return Collections.emptyList(); } Collection<Element> ownedElements = folder.getOwnedElement(); List<Element> lockedElements = new ArrayList<>(ownedElements.size()); for (Element element : folder.getOwnedElement()) { if (element instanceof com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Class && !lockService.isLocked(element) && lockService.canBeLocked(element)) { lockedElements.add(element); } } if (!lockService.lockElements(lockedElements, false, null)) { return Collections.emptyList(); } return lockedElements; }
Source:
private void checkInitialization() { if (!addedEval || initialized) { return; } while (!initialized) { try { initLatch.await(); } catch (final InterruptedException e) { LOG.log(Level.WARNING, "Interrupted while waiting for routing table initialization from driver", e); } } }

Target:
private void checkInitialization() { if (!addedEval) { return; } while (true) { try { initLatch.await(); break; } catch (final InterruptedException e) { LOG.log(Level.WARNING, "Interrupted while waiting for routing table initialization from driver", e); } } }
Source:
public Integer offsetComparator(String offset1, String offset2) { int o1 = Optional.ofNullable(offset1) .filter(Strings::isNullOrEmpty) .map(Integer::parseInt) .orElse(-1); int o2 = Optional.ofNullable(offset2) .filter(Strings::isNullOrEmpty) .map(Integer::parseInt) .orElse(-1); if (o1 == -1 || o2 == -1) { return null; } return Integer.compare(o1, o2); }

Target:
public Integer offsetComparator(String offset1, String offset2) { if (offset1 == null || offset2 == null) { return null; } return Integer.compare(Integer.parseInt(offset1), Integer.parseInt(offset2)); }
Source:
public CosemDateTime getDaylightSavingsBegin() { return new CosemDateTime(this.daylightSavingsBegin); }

Target:
public CosemDateTime getDaylightSavingsBegin() { return this.daylightSavingsBegin; }
Source:
private boolean shouldExecuteInBatchMode(final RuntimeExecutionMode configuredMode) { final boolean existsUnboundedSource = existsContinuousSource(); if (configuredMode == RuntimeExecutionMode.BATCH && existsUnboundedSource) { throw new IllegalArgumentException( "Detected an UNBOUNDED source with the '" + RuntimeOptions.RUNTIME_MODE.key() + "' set to 'BATCH'. " + "This combination is not allowed, please set the '" + RuntimeOptions.RUNTIME_MODE.key() + "' to STREAMING or AUTOMATIC"); } if (checkNotNull(configuredMode) != RuntimeExecutionMode.AUTOMATIC) { return configuredMode == RuntimeExecutionMode.BATCH; } return !existsUnboundedSource; }

Target:
private boolean shouldExecuteInBatchMode(final RuntimeExecutionMode configuredMode) { final boolean existsUnboundedSource = existsUnboundedSource(); checkState(configuredMode != RuntimeExecutionMode.BATCH || !existsUnboundedSource, "Detected an UNBOUNDED source with the '" + ExecutionOptions.RUNTIME_MODE.key() + "' set to 'BATCH'. " + "This combination is not allowed, please set the '" + ExecutionOptions.RUNTIME_MODE.key() + "' to STREAMING or AUTOMATIC"); if (checkNotNull(configuredMode) != RuntimeExecutionMode.AUTOMATIC) { return configuredMode == RuntimeExecutionMode.BATCH; } return !existsUnboundedSource; }
Source:
private void nonTransactionalRemoveGroup(String groupName, long explicitFlags) { InvocationContext context = invocationContextFactory.createInvocationContext(false, UNBOUNDED); Map<K, V> keys = internalGetGroup(groupName, explicitFlags, context); long removeFlags = addIgnoreReturnValuesFlag(explicitFlags); for (K key : keys.keySet()) { assertKeyNotNull(key); InvocationContext ctx = singleKeyContextWithImplicitTransaction(); RemoveCommand command = createRemoveCommand(key, removeFlags); checkLockOwner(ctx, command); executeCommandAndCommitIfNeeded(ctx, command); } }

Target:
private void nonTransactionalRemoveGroup(String groupName, long explicitFlags) { InvocationContext context = invocationContextFactory.createInvocationContext(false, UNBOUNDED); Map<K, V> keys = internalGetGroup(groupName, explicitFlags, context); long removeFlags = addIgnoreReturnValuesFlag(explicitFlags); for (K key : keys.keySet()) { assertKeyNotNull(key); executeCommandAndCommitIfNeeded(contextBuilder, createRemoveCommand(key, removeFlags), 1); } }
Source:
private @NonNull Action[] getRevisionActions(@NonNull SCMRevision revision, String rawName) { Action[] revisionActions = new Action[0]; try { List<Action> actions = source.fetchActions(revision, event, listener); revisionActions = actions.toArray(new Action[0]); } catch (IOException | InterruptedException e) { printStackTrace(e, listener.error("Could not fetch metadata for revision %s of branch %s", revision, rawName)); } return revisionActions; }

Target:
private Action[] getRevisionActions(@NonNull SCMRevision revision, String rawName) { Action[] revisionActions = new Action[0]; try { List<Action> actions = source.fetchActions(revision, event, listener); revisionActions = actions.toArray(new Action[actions.size()]); } catch (IOException | InterruptedException e) { printStackTrace(e, listener.error("Could not fetch metadata for revision %s of branch %s", revision, rawName)); } return revisionActions; }
Source:
public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException { if (!TimeZoneRulesDataContract.DATA_URI.equals(uri)) { return null; } if (mAssetName == null) { throw new FileNotFoundException(); } if (!mode.equals("r")) { throw new SecurityException("Only read-only access supported."); } Context context = getContext(); try { AssetFileDescriptor fd = context.getAssets().openFd(mAssetName); return fd.getParcelFileDescriptor(); } catch (IOException e) { throw new RuntimeException("Unable to open asset file", e); } }

Target:
public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException { if (!TimeZoneRulesDataContract.DATA_URI.equals(uri)) { return null; } if (!"r".equals(mode)) { throw new SecurityException("Only read-only access supported."); } File distroFile = null; try { distroFile = File.createTempFile("distro", null, getContext().getFilesDir()); AssetManager assets = getContext().getAssets(); try (InputStream is = assets.open(TimeZoneDistro.FILE_NAME, ACCESS_STREAMING); FileOutputStream fos = new FileOutputStream(distroFile, false )) { copy(is, fos); } return ParcelFileDescriptor.open(distroFile, ParcelFileDescriptor.MODE_READ_ONLY); } catch (IOException e) { throw new RuntimeException("Unable to copy distro asset file", e); } finally { if (distroFile != null) { distroFile.delete(); } } }
Source:
private static void handleLaunchArguments(String[] args) { Path homePath = null; for (String arg : args) { boolean recognized = true; if (arg.startsWith(USE_SPECIFIED_DIR_AS_HOME)) { homePath = Paths.get(arg.substring(USE_SPECIFIED_DIR_AS_HOME.length())); } else if (arg.equals(USE_CURRENT_DIR_AS_HOME)) { homePath = Paths.get(""); } else if (arg.equals(START_HEADLESS)) { isHeadless = true; crashReportEnabled = false; } else if (arg.equals(NO_SAVE_GAMES)) { writeSaveGamesEnabled = false; } else if (arg.equals(NO_CRASH_REPORT)) { crashReportEnabled = false; } else if (arg.equals(NO_SOUND)) { soundEnabled = false; } else if (arg.equals(LOAD_LAST_GAME)) { loadLastGame = true; } else if(arg.startsWith(SERVER_PORT)) { try { serverPort = Integer.parseInt(arg.substring(SERVER_PORT.length())); } catch (NumberFormatException e) { new TransientConfig().setServerPort(TerasologyConstants.DEFAULT_PORT); System.out.println("Couldn't parse server port. Using default port."); } } else { recognized = false; } System.out.println((recognized ? "Recognized" : "Invalid") + " argument: " + arg); } try { if (homePath != null) { PathManager.getInstance().useOverrideHomePath(homePath); } else { PathManager.getInstance().useDefaultHomePath(); } } catch (IOException e) { if (!isHeadless) { reportException(e); } System.exit(0); } }

Target:
private static void handleLaunchArguments(String[] args) { Path homePath = null; for (String arg : args) { boolean recognized = true; if (arg.startsWith(USE_SPECIFIED_DIR_AS_HOME)) { homePath = Paths.get(arg.substring(USE_SPECIFIED_DIR_AS_HOME.length())); } else if (arg.equals(USE_CURRENT_DIR_AS_HOME)) { homePath = Paths.get(""); } else if (arg.equals(START_HEADLESS)) { isHeadless = true; crashReportEnabled = false; } else if (arg.equals(NO_SAVE_GAMES)) { writeSaveGamesEnabled = false; } else if (arg.equals(NO_CRASH_REPORT)) { crashReportEnabled = false; } else if (arg.equals(NO_SOUND)) { soundEnabled = false; } else if (arg.equals(LOAD_LAST_GAME)) { loadLastGame = true; } else if (arg.startsWith(SERVER_PORT)) { try { serverPort = Integer.parseInt(arg.substring(SERVER_PORT.length())); } catch (NumberFormatException e) { reportException(e); } } else { recognized = false; } System.out.println((recognized ? "Recognized" : "Invalid") + " argument: " + arg); } try { if (homePath != null) { PathManager.getInstance().useOverrideHomePath(homePath); } else { PathManager.getInstance().useDefaultHomePath(); } } catch (IOException e) { if (!isHeadless) { reportException(e); } System.exit(0); } }
Source:
public String bannerCreate(@ModelAttribute BannerDto bannerDto, HttpServletRequest request) { String loginName = LoginUserInfo.getLoginName(); bannerService.create(bannerDto, loginName); String ip = RequestIPParser.parse(request); String description = loginName + "在 " + sdf.format(new Date()) +"创建了" +"名称为:" + bannerDto.getName() + "的banner." ; auditLogService.createAuditLog(loginName, loginName, OperationType.BANNER, bannerDto.getName(), description, ip); return "redirect:/banner-manage/list"; }

Target:
public String bannerCreate(@ModelAttribute BannerDto bannerDto, HttpServletRequest request) { String loginName = LoginUserInfo.getLoginName(); String ip = RequestIPParser.parse(request); bannerService.create(bannerDto, loginName, ip); return "redirect:/banner-manage/list"; }