auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testAMeetingCannotBeCreatedWithoutAttendees() { ExcelReader excelReader = new ExcelReader(EXCEL_INPUT_DATA); List<Map<String, String>> meetingData = excelReader.getMapValues("MeetingData"); String organizer = meetingData.get(0).get("Organizer"); String subject = meetingData.get(0).get("Subject"); String startTime = meetingData.get(0).get("Start time"); String endTime = meetingData.get(0).get("End time"); String body = meetingData.get(0).get("Body"); HomeTabletPage homeTabletPage = new HomeTabletPage(); SchedulePage schedulePage = homeTabletPage.clickScheduleBtn(); schedulePage.setOrganizerTxtBox(organizer) .setSubjectTxtBox(subject) .setStartTimeDate(startTime) .setEndTimeDate(endTime) .setBodyTxtBox(body) .clickCreateBtn() .clickCancelButton(); Assert.assertTrue(schedulePage.isErrorAttendeeLblDisplayed()); }

Target:
public void testAMeetingCannotBeCreatedWithoutAttendees() { ExcelReader excelReader = new ExcelReader(EXCEL_INPUT_DATA); List<Map<String, String>> meetingData = excelReader.getMapValues("MeetingData"); String organizer = meetingData.get(0).get("Organizer"); String subject = meetingData.get(0).get("Subject"); String body = meetingData.get(0).get("Body"); HomeTabletPage homeTabletPage = new HomeTabletPage(); SchedulePage schedulePage = homeTabletPage.clickScheduleBtn(); schedulePage .setOrganizerTxtBox(organizer) .setSubjectTxtBox(subject) .setBodyTxtBox(body) .clickCreateBtn() .clickCancelButton(); Assert.assertTrue(schedulePage.isErrorAttendeeLblDisplayed()); }
Source:
public TeamServiceImpl(TeamRepository teamRepository, UserService userService, MailService mailService, TeamInviteTokenRepository teamInviteTokenRepository) { this.teamRepository = teamRepository; this.teamInviteTokenRepository = teamInviteTokenRepository; this.userService = userService; this.mailService = mailService; }

Target:
public TeamServiceImpl(TeamRepository teamRepository, UserService userService, MailService mailService, TeamInviteTokenRepository teamInviteTokenRepository) { this.teamRepository = teamRepository; this.userService = userService; this.mailService = mailService; this.teamInviteTokenRepository = teamInviteTokenRepository; }
Source:
public Serializer getSerializer(String id) { SerializerContribution contrib = getDescriptor(EXTENSION_POINT_NAME, id); if (contrib == null) { contrib = getDescriptor(EXTENSION_POINT_NAME, DEFAULT_SERIALIZER_NAME); if (contrib == null) { throw new UnknownSerializer(id); } } return contrib.getImplementation(); }

Target:
public Serializer getSerializer(String id) { SerializerContribution contrib = getDescriptor(EXTENSION_POINT_NAME, id); if (contrib == null) { contrib = getDescriptor(EXTENSION_POINT_NAME, DEFAULT_SERIALIZER_NAME); if (contrib == null) { throw new NuxeoException("UnknownSerializer named " + id); } } return contrib.getImplementation(); }
Source:
protected List<StorageDomainStatic> filterAttachedStorageDomains() { List<StorageDomain> connectedStorageDomainsToVds = new ArrayList<>(); for (StorageDomain storageDomain : getParameters().getStorageDomainList()) { if (!connectStorageDomain(storageDomain)) { logErrorMessage(storageDomain); } else { connectedStorageDomainsToVds.add(storageDomain); } } List<StorageDomainStatic> storageDomainsWithAttachedStoragePoolId = getAttachedStorageDomains(connectedStorageDomainsToVds); for (StorageDomain storageDomain : connectedStorageDomainsToVds) { if (containsRunningVMs(storageDomain)) { log.warn( "Skipping disconnect Storage Domain from VDS '{}' because it has running VMs on it. ", storageDomain.getName(), getVdsId() ); continue; } if (!disconnectStorageDomain(storageDomain)) { log.warn("Could not disconnect Storage Domain from VDS '{}'. ", storageDomain.getName(), getVdsId()); } } return storageDomainsWithAttachedStoragePoolId; }

Target:
protected List<StorageDomainStatic> filterAttachedStorageDomains() { List<StorageDomain> connectedStorageDomainsToVds = new ArrayList<>(); for (StorageDomain storageDomain : getParameters().getStorageDomainList()) { if (!connectStorageDomain(storageDomain)) { logErrorMessage(storageDomain); } else { connectedStorageDomainsToVds.add(storageDomain); } } List<StorageDomainStatic> storageDomainsWithAttachedStoragePoolId = getAttachedStorageDomains(connectedStorageDomainsToVds); for (StorageDomain storageDomain : connectedStorageDomainsToVds) { if (containsRunningHostedEngine(storageDomain)) { log.info( "Skipping disconnect Storage Domain from VDS '{}' because Hosted Engine VM is running on it.", storageDomain.getName(), getVdsId() ); continue; } if (!disconnectStorageDomain(storageDomain)) { log.warn("Could not disconnect Storage Domain from VDS '{}'. ", storageDomain.getName(), getVdsId()); } } return storageDomainsWithAttachedStoragePoolId; }
Source:
public double getSchedulingJitterPercent() { if (containsKey(CONFIG_SCHEDULING_JITTER_PERCENT)) { return getDouble(CONFIG_SCHEDULING_JITTER_PERCENT) / 100.0; } return 0; }

Target:
public double getSchedulingJitterPercent() { return getDouble(CONFIG_SCHEDULING_JITTER_PERCENT, DEFAULT_SCHEDULING_JITTER_PERCENT); }
Source:
static boolean isIdempotent(Object value) { if (value == null) { return true; } else if (value instanceof Assignment) { Assignment assignment = (Assignment) value; return assignment.isIdempotent(); } else if (value instanceof FCall) { return false; } else if (value instanceof RawString) { return false; } else if (value instanceof Collection) { for (Object elt : ((Collection) value)) { if (!isIdempotent(elt)) return false; } return true; } else if (value instanceof Map) { for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) { if (!isIdempotent(entry.getKey()) || !isIdempotent(entry.getValue())) return false; } } else if (value instanceof Clause){ Object clauseValue = ((Clause) value).firstValue(); return !(clauseValue instanceof FCall); } return true; }

Target:
static boolean isIdempotent(Object value) { if (value == null) { return true; } else if (value instanceof Assignment) { Assignment assignment = (Assignment) value; return assignment.isIdempotent(); } else if (value instanceof FCall) { return false; } else if (value instanceof RawString) { return false; } else if (value instanceof Collection) { for (Object elt : ((Collection) value)) { if (!isIdempotent(elt)) return false; } return true; } else if (value instanceof Map) { for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) { if (!isIdempotent(entry.getKey()) || !isIdempotent(entry.getValue())) return false; } } else if (value instanceof Clause) { Object clauseValue = ((Clause) value).firstValue(); return isIdempotent(clauseValue); } return true; }
Source:
boolean update(WatermarkMessage watermarkMessage, SystemStreamPartition ssp) { WatermarkState state = watermarkStates.get(ssp); boolean updated = state.update(watermarkMessage.getTimestamp(), watermarkMessage.getTaskName()); if (updated) { long minTimestamp = watermarkStates.entrySet().stream() .filter(entry -> entry.getKey().getSystemStream().equals(ssp.getSystemStream())) .map(entry -> entry.getValue().getWatermarkTime()) .min(Long::compare) .get(); Long curWatermark = watermarks.get(ssp.getSystemStream()); if (curWatermark == null || curWatermark < minTimestamp) { watermarks.put(ssp.getSystemStream(), minTimestamp); return true; } } return false; }

Target:
void update(WatermarkMessage watermarkMessage, SystemStreamPartition ssp) { WatermarkState state = watermarkStates.get(ssp); if (state != null) { state.update(watermarkMessage.getTimestamp(), watermarkMessage.getTaskName()); } else { LOG.error("SSP doesn't have watermark states", ssp); } }
Source:
Integer getFreeIndex() { Integer index; if (freeIndexList.isEmpty()) { index = arrayList.size(); } else { int freeIndexToRemove = freeIndexList.size() - 1; index = freeIndexList.get(freeIndexToRemove); freeIndexList.remove(freeIndexToRemove); } return index; }

Target:
Integer getFreeIndex() { Integer index; int freeIndexListSize = freeIndexList.size(); if (freeIndexListSize == 0) { index = pool.size(); } else { index = freeIndexList.remove(freeIndexListSize - 1); } return index; }
Source:
private String getCharactersCount(String content) { int numChars = content.length(); String charCountString = mFragment.getResources().getQuantityString(R.plurals.char_count,numChars); return String.format("%s %s", numChars , charCountString); }

Target:
private String getCharactersCount(String content) { int numChars = content.length(); String charCount = NumberFormat.getInstance().format(numChars); String charCountString = mFragment.getResources().getQuantityString(R.plurals.char_count, numChars); return String.format("%s %s", charCount, charCountString); }
Source:
public HttpResponse doCancelItem(@QueryParameter long id) { Item item = getItem(id); if (item != null) { if(item.hasCancelPermission()){ if(cancel(item)) { return HttpResponses.status(HttpServletResponse.SC_NO_CONTENT); } return HttpResponses.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not cancel run for id " + id); } return HttpResponses.error(422, "Item for id (" + id + ") is not cancellable"); } return HttpResponses.error(422, "Provided id (" + id + ") does not exist"); }

Target:
public HttpResponse doCancelItem(@QueryParameter long id) throws IOException, ServletException { Item item = getItem(id); if (item != null) { if(item.hasCancelPermission()){ if(cancel(item)) { return HttpResponses.status(HttpServletResponse.SC_NO_CONTENT); } return HttpResponses.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not cancel run for id " + id); } return HttpResponses.error(422, "Item for id (" + id + ") is not cancellable"); } return HttpResponses.error(HttpServletResponse.SC_NOT_FOUND, "Provided id (" + id + ") not found"); }
Source:
private static void populate(int size, int[] fuzz, ISegmentStore<@NonNull ISegment> store, long low, long high) { for (int i = (int) low; i < high; i++) { long start = (long) i + fuzz[i % size]; store.add(new BasicSegment(start, start + 10)); } }

Target:
private static void populate(int size, int[] fuzz, ISegmentStore<@NonNull ISegment> store, long low, long high) { for (long i = low; i < high; i++) { long start = i + fuzz[(int) (i % size)]; store.add(new BasicSegment(start, start + 10)); } }
Source:
private static Class<?> getClass(String className) { try { return Class.forName(className); } catch (ClassNotFoundException e) { throw new IllegalStateException("Java 8 or later but class " + className + " is missing"); } }

Target:
private static Class<?> getClass(String className) { try { return Class.forName(className); } catch (ClassNotFoundException e) { throw new IllegalStateException("Java 8 or later but class " + className + " is missing", e); } }
Source:
public void fireChangeEventsOnFields() { NativeEvent event = Document.get().createChangeEvent(); DomEvent.fireNativeEvent(event, userNameEditor.asValueBox()); event = Document.get().createChangeEvent(); DomEvent.fireNativeEvent(event, passwordEditor.asValueBox()); }

Target:
public void fireChangeEventsOnFields() { userNameEditor.fireChangeEvent(); passwordEditor.fireChangeEvent(); profileEditor.fireChangeEvent(); }
Source:
public void stop(ComponentContext context) throws InterruptedException { super.stop(context); executor.shutdownNow(); executor.awaitTermination(10, TimeUnit.SECONDS); executor = null; }

Target:
public void stop(ComponentContext context) throws InterruptedException { executor.shutdownNow(); executor.awaitTermination(10, TimeUnit.SECONDS); executor = null; super.stop(context); }
Source:
public static void restartJobServiceTriggerAt(Context context, long triggerAtMillis) { JobInfo.Builder builder = getFeedUpdateJobBuilder(context); builder.setMinimumLatency(triggerAtMillis); JobScheduler jobScheduler = context.getSystemService(JobScheduler.class); if (jobScheduler != null) { jobScheduler.cancel(JOB_ID_FEED_UPDATE); jobScheduler.schedule(builder.build()); Log.d(TAG, "JobScheduler was set for " + triggerAtMillis); } }

Target:
private static void restartJobServiceTriggerAt(Context context, long triggerAtMillis) { JobScheduler jobScheduler = context.getSystemService(JobScheduler.class); if (jobScheduler == null) { Log.d(TAG, "JobScheduler was null."); return; } JobInfo.Builder builder = getFeedUpdateJobBuilder(context); builder.setMinimumLatency(triggerAtMillis); jobScheduler.cancel(JOB_ID_FEED_UPDATE); jobScheduler.schedule(builder.build()); Log.d(TAG, "JobScheduler was set for " + triggerAtMillis); }
Source:
protected Expression getExpressionFromOperationList(List<Operation> operations, long expressionDefinitionId) { for (Operation operation : operations) { final Expression expression = getExpressionFromContainer(operation, expressionDefinitionId); if (expression == null) { return expression; } } return null; }

Target:
protected Expression getExpressionFromOperationList(List<Operation> operations, long expressionDefinitionId) { for (Operation operation : operations) { final Expression expression = getExpressionFromContainer(operation, expressionDefinitionId); if (expression != null) { return expression; } } return null; }
Source:
private void assertResult(String moveCode, boolean doable, OrderByMoveIndexBlockingQueue.MoveResult<TestdataSolution> result) { assertCode(moveCode, result.getMove()); boolean y = result.isMoveDoable(); if (doable) { assertThat(y).isTrue(); } else { assertThat(y).isFalse(); } }

Target:
private void assertResult(String moveCode, boolean doable, OrderByMoveIndexBlockingQueue.MoveResult<TestdataSolution> result) { assertCode(moveCode, result.getMove()); assertThat(result.isMoveDoable()).isEqualTo(doable); }
Source:
State setState(final State newState) { final State oldState; synchronized (stateLock) { oldState = state; if (state == State.PENDING_SHUTDOWN && newState != State.DEAD) { log.debug("Invalid transition from PENDING_SHUTDOWN to {}: " + "only DEAD state is a valid next state", newState); ENDING_SHUTDOWN, all other transitions will be return null; } else if (state == State.DEAD) { log.debug("Invalid transition from DEAD to {}: " + "no valid next state after DEAD", newState); return null; } else if (state == State.PARTITIONS_REVOKED && newState == State.PARTITIONS_REVOKED) { log.debug("Invalid transition from PARTITIONS_REVOKED to PARTITIONS_REVOKED: " + "self transition is not allowed"); return null; } else if (!state.isValidTransition(newState)) { log.error("Unexpected state transition from to {}", oldState, newState); throw new StreamsException(logPrefix + "Unexpected state transition from " + oldState + " to " + newState); } else { log.info("State transition from to {}", oldState, newState); } state = newState; if (newState == State.RUNNING) { updateThreadMetadata(taskManager.activeTasks(), taskManager.standbyTasks()); } else { updateThreadMetadata(Collections.emptyMap(), Collections.emptyMap()); } } if (stateListener != null) { stateListener.onChange(this, state, oldState); } return oldState; }

Target:
State setState(final State newState) { final State oldState; synchronized (stateLock) { oldState = state; if (state == State.PENDING_SHUTDOWN && newState != State.DEAD) { log.debug("Ignoring request to transit from PENDING_SHUTDOWN to {}: " + "only DEAD state is a valid next state", newState); ENDING_SHUTDOWN, all other transitions will be return null; } else if (state == State.DEAD) { log.debug("Ignoring request to transit from DEAD to {}: " + "no valid next state after DEAD", newState); return null; } else if (state == State.PARTITIONS_REVOKED && newState == State.PARTITIONS_REVOKED) { log.debug("Ignoring request to transit from PARTITIONS_REVOKED to PARTITIONS_REVOKED: " + "self transition is not allowed"); return null; } else if (!state.isValidTransition(newState)) { log.error("Unexpected state transition from to {}", oldState, newState); throw new StreamsException(logPrefix + "Unexpected state transition from " + oldState + " to " + newState); } else { log.info("State transition from to {}", oldState, newState); } state = newState; if (newState == State.RUNNING) { updateThreadMetadata(taskManager.activeTasks(), taskManager.standbyTasks()); } else { updateThreadMetadata(Collections.emptyMap(), Collections.emptyMap()); } } if (stateListener != null) { stateListener.onChange(this, state, oldState); } return oldState; }
Source:
private void handshakeReq(ProtocolVersion proposedVer, String user, String pwd, Map<String, String> userAttrs) throws ClientConnectionException { BinaryContext ctx = new BinaryContext(BinaryCachingMetadataHandler.create(), new IgniteConfiguration(), null); try (BinaryWriterExImpl writer = new BinaryWriterExImpl(ctx, new BinaryHeapOutputStream(32), null, null)) { ProtocolContext protocolContext = protocolContextFromVersion(proposedVer); writer.writeInt(0); writer.writeByte((byte) ClientListenerRequest.HANDSHAKE); writer.writeShort(proposedVer.major()); writer.writeShort(proposedVer.minor()); writer.writeShort(proposedVer.patch()); writer.writeByte(ClientListenerNioListener.THIN_CLIENT); if (protocolContext.isFeaturesSupported()) { byte[] features = ThinProtocolFeature.featuresAsBytes(protocolContext.features()); writer.writeByteArray(features); } if (protocolContext.isUserAttributesSupported()) writer.writeMap(userAttrs); if (protocolContext.isAuthorizationSupported() && user != null && !user.isEmpty()) { writer.writeString(user); writer.writeString(pwd); } writer.out().writeInt(0, writer.out().position() - 4); write(writer.array(), writer.out().position()); } }

Target:
private void handshakeReq(ProtocolVersion proposedVer, String user, String pwd, Map<String, String> userAttrs) throws ClientConnectionException { BinaryContext ctx = new BinaryContext(BinaryCachingMetadataHandler.create(), new IgniteConfiguration(), null); try (BinaryWriterExImpl writer = new BinaryWriterExImpl(ctx, new BinaryHeapOutputStream(32), null, null)) { ProtocolContext protocolCtx = protocolContextFromVersion(proposedVer); writer.writeInt(0); writer.writeByte((byte) ClientListenerRequest.HANDSHAKE); writer.writeShort(proposedVer.major()); writer.writeShort(proposedVer.minor()); writer.writeShort(proposedVer.patch()); writer.writeByte(ClientListenerNioListener.THIN_CLIENT); if (protocolCtx.isFeatureSupported(BITMAP_FEATURES)) { byte[] features = ProtocolBitmaskFeature.featuresAsBytes(protocolCtx.features()); writer.writeByteArray(features); } if (protocolCtx.isFeatureSupported(USER_ATTRIBUTES)) writer.writeMap(userAttrs); boolean authSupported = protocolCtx.isFeatureSupported(AUTHORIZATION); if (authSupported && user != null && !user.isEmpty()) { writer.writeString(user); writer.writeString(pwd); } writer.out().writeInt(0, writer.out().position() - 4); write(writer.array(), writer.out().position()); } }
Source:
protected List<Bundle> installCoreBundles() { List<Bundle> bundles = new ArrayList<>(); try { List<String> locationPatterns = new ArrayList<>(); locationPatterns.add(blueprintBundlesLocation); if (StringUtils.hasText(standardBundlesLocation)) { locationPatterns.add(standardBundlesLocation); } if (StringUtils.hasText(customBundlesLocation)) { locationPatterns.add(customBundlesLocation); } for (String locationPattern : locationPatterns) { try { for (Resource bundleResource : resourcePatternResolver.getResources(locationPattern)) { String location = bundleResource.getURI().toString(); logger.debug("Installing Bundle: {}", location); try { Bundle bundle = installBundle(bundleResource, location); bundles.add(bundle); } catch (BundleException e) { logger.error("Error installing Bundle: $location", e); } } } catch (FileNotFoundException e) { logger.debug("Could not find Bundles at location '{}'.", locationPattern); } } } catch (IOException ioe) { throw new RuntimeException("Error installing core Bundles: " + ioe.getMessage(), ioe); } return bundles; }

Target:
protected List<Bundle> installCoreBundles() { List<Bundle> bundles = new ArrayList<>(); try { List<String> locationPatterns = new ArrayList<>(); locationPatterns.add(blueprintBundlesLocation); if (StringUtils.hasText(standardBundlesLocation)) { locationPatterns.add(standardBundlesLocation); } if (StringUtils.hasText(customBundlesLocation)) { locationPatterns.add(customBundlesLocation); } for (String locationPattern : locationPatterns) { try { for (Resource bundleResource : resourcePatternResolver.getResources(locationPattern)) { String location = bundleResource.getURI().toString(); logger.debug("Installing Bundle: {}", location); try { Bundle bundle = installBundle(bundleResource, location); bundles.add(bundle); } catch (BundleException e) { logger.error("Error installing Bundle in {}: {}", location, e); } } } catch (FileNotFoundException e) { logger.debug("Could not find Bundles at location '{}'.", locationPattern); } } } catch (IOException ioe) { throw new RuntimeException("Error installing core Bundles: " + ioe.getMessage(), ioe); } return bundles; }
Source:
public Iterable<Issue> search( @NotNull(message = "Sort field can't be NULL") final Sort sort, @NotNull(message = "Sort direction can't be NULL") final Search.Order direction, @NotNull(message = "Search qualifiers can't be NULL") final EnumMap<Qualifier, String> qualifiers) throws IOException { final Map<String, String> params = new HashMap<String, String>(); for (final EnumMap.Entry<Qualifier, String> entry : qualifiers .entrySet()) { params.put(entry.getKey().getQualifier(), entry.getValue()); } params.put("sort", sort.getSort()); params.put("direction", direction.getOrder()); return this.iterate(params); }

Target:
public Iterable<Issue> search( @NotNull(message = "Sort field can't be NULL") final Sort sort, @NotNull(message = "Sort direction can't be NULL") final Search.Order direction, @NotNull(message = "Search qualifiers can't be NULL") final EnumMap<Qualifier, String> qualifiers) throws IOException { final Map<String, String> params = new HashMap<String, String>(); for (final EnumMap.Entry<Qualifier, String> entry : qualifiers .entrySet()) { params.put(entry.getKey().identifier(), entry.getValue()); } params.put("sort", sort.identifier()); params.put("direction", direction.identifier()); return this.iterate(params); }
Source:
public boolean isValid(ComplaintValidationContext context) { this.context = context; try { this.complainantTypes = context.getComplaintDAO().getComplainantTypes(); if (context.getComplaintDTO().getComplainantType() == null || context.getComplaintDTO().getComplainantType().getId() == null) { getMessages().add(getErrorMessage("complaints.complainantType.required")); return false; } if (!doesComplainantTypeExist(context.getComplaintDTO().getComplainantType().getId())) { getMessages().add(getErrorMessage("complaints.complainantType.notExists")); return false; } if (isComplainantTypeSetToOther(context.getComplaintDTO().getComplainantType()) && (context.getComplaintDTO().getComplainantTypeOther() == null || context.getComplaintDTO().getComplainantTypeOther().trim() == "")) { getMessages().add(getErrorMessage("complaints.complainantType.otherMissing")); return false; } return true; } catch (Exception e) { String error = getErrorMessage("complaints.error"); LOGGER.error(error, e); getMessages().add(error); return false; } }

Target:
public boolean isValid(ComplaintValidationContext context) { this.context = context; try { this.complainantTypes = context.getComplaintDAO().getComplainantTypes(); if (context.getComplaintDTO().getComplainantType() == null || context.getComplaintDTO().getComplainantType().getId() == null) { getMessages().add(getErrorMessage("complaints.complainantType.required")); return false; } if (!doesComplainantTypeExist(context.getComplaintDTO().getComplainantType().getId())) { getMessages().add(getErrorMessage("complaints.complainantType.notExists")); return false; } if (isComplainantTypeSetToOther(context.getComplaintDTO().getComplainantType()) && StringUtils.isEmpty(context.getComplaintDTO().getComplainantTypeOther())) { getMessages().add(getErrorMessage("complaints.complainantType.otherMissing")); return false; } return true; } catch (Exception e) { String error = getErrorMessage("complaints.error"); LOGGER.error(error, e); getMessages().add(error); return false; } }
Source:
public Set<String> getDisabledAdministrativeMonitors(){ return disabledAdministrativeMonitors; }

Target:
public Set<String> getDisabledAdministrativeMonitors(){ synchronized (this.disabledAdministrativeMonitors) { return new HashSet<>(disabledAdministrativeMonitors); } }
Source:
public void verify(byte[] contentBytes, byte[] signatureBytes) throws SignatureVerificationException { try { if (publicKey == null) { throw new IllegalArgumentException("The given Public Key is null."); } if (!isDERSignature(signatureBytes)) { signatureBytes = JOSEToDER(signatureBytes); } boolean valid = crypto.verifySignatureFor(getDescription(), publicKey, contentBytes, signatureBytes); if (!valid) { throw new SignatureVerificationException(this); } } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException | IllegalArgumentException e) { throw new SignatureVerificationException(this, e); } }

Target:
public void verify(byte[] contentBytes, byte[] signatureBytes) throws SignatureVerificationException { try { if (publicKey == null) { throw new IllegalStateException("The given Public Key is null."); } if (!isDERSignature(signatureBytes)) { signatureBytes = JOSEToDER(signatureBytes); } boolean valid = crypto.verifySignatureFor(getDescription(), publicKey, contentBytes, signatureBytes); if (!valid) { throw new SignatureVerificationException(this); } } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException | IllegalStateException e) { throw new SignatureVerificationException(this, e); } }
Source:
private IStatus unzip(byte[] byteArray, IPath location) { ZipInputStream stream = new ZipInputStream(new ByteArrayInputStream(byteArray)); ZipEntry entry; IStatus status = Status.OK_STATUS; try { while ((entry = stream.getNextEntry()) != null) { try { String name = skipOneLevel(entry.getName()); if (!name.isEmpty()) { Path path = Paths.get(location.toOSString(), name); if (entry.isDirectory()) { Files.createDirectories(path); } else { try (OutputStream output = new FileOutputStream(path.toFile())) { IOUtils.copy(stream, output); } } } } catch (InvalidPathException e) } } catch (IOException e) { status = new Status(IStatus.ERROR, LauncherUIPlugin.PLUGIN_ID, e.getLocalizedMessage(), e); } return status; }

Target:
private IStatus unzip(byte[] byteArray, IPath location) { ZipInputStream stream = new ZipInputStream(new ByteArrayInputStream(byteArray)); ZipEntry entry; IStatus status = Status.OK_STATUS; try { while ((entry = stream.getNextEntry()) != null) { unzipEntry(location, stream, entry); } } catch (IOException e) { status = new Status(IStatus.ERROR, LauncherUIPlugin.PLUGIN_ID, e.getLocalizedMessage(), e); } return status; }
Source:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { Map<String, Object> state = new TreeMap<String, Object>(jsm.getState()); String path = request.getParameter("path"); if (path != null) { Iterator<String> it = state.keySet().iterator(); while (it.hasNext()) { if(!it.next().startsWith(path)) { it.remove(); } } } if (state.containsKey("ScoreBoard.Twitter.AccessTokenSecret")) { state.put("ScoreBoard.Twitter.AccessTokenSecret", "<removed>"); } if (state.isEmpty()) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "No objects found."); } else { response.setContentType("application/json"); String json = JSON.std .with(JSON.Feature.PRETTY_PRINT_OUTPUT) .composeString() .startObject() .putObject("state", state) .end() .finish(); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Expires", "-1"); response.setCharacterEncoding("utf-8"); response.getOutputStream().print(json); response.getOutputStream().flush(); response.setStatus(HttpServletResponse.SC_OK); } }

Target:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { Map<String, Object> state = new TreeMap<>(jsm.getState()); String path = request.getParameter("path"); if (path != null) { Iterator<String> it = state.keySet().iterator(); while (it.hasNext()) { if(!it.next().startsWith(path)) { it.remove(); } } } if (state.containsKey("ScoreBoard.Twitter.AccessTokenSecret")) { state.put("ScoreBoard.Twitter.AccessTokenSecret", "<removed>"); } if (state.isEmpty()) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "No objects found."); } else { response.setContentType("application/json"); String json = JSON.std .with(JSON.Feature.PRETTY_PRINT_OUTPUT) .composeString() .startObject() .putObject("state", state) .end() .finish(); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Expires", "-1"); response.setCharacterEncoding("utf-8"); response.getOutputStream().print(json); response.getOutputStream().flush(); response.setStatus(HttpServletResponse.SC_OK); } }
Source:
public FilterPanel addPanelAt(int index) { FilterPanel panel = new ListPanel(ui, model, this, index); getChildren().add(index, panel); guiController.panelFilterExpressionChanged(panel); updatePanelIndices(); setCurrentlySelectedPanel(Optional.of(index)); mainStage.show(); return panel; }

Target:
public FilterPanel addPanelAt(int index) { FilterPanel panel = new ListPanel(ui, model, this, index); getChildren().add(index, panel); guiController.panelFilterExpressionChanged(panel); updatePanelIndices(); setCurrentlySelectedPanel(Optional.of(index)); ui.showMainStage(); return panel; }
Source:
private boolean compareSortKeys(IndexSortKey sortKey, String fieldName, Object dir) { String field = sortKey.getField().toString(); if (sortKey.isCaseInsensitive()) { field = Translator.getHiddenForField(sortKey.getField()).toString(); } if (field.equals(fieldName)) { int direction = ((Number) dir).intValue(); return sortKey.isDesc() == (direction < 0); } return false; }

Target:
private boolean compareSortKeys(IndexSortKey sortKey, String fieldName, Object dir) { String field = sortKey.getField().toString(); if (sortKey.isCaseInsensitive()) { field = Translator.translatePath(Translator.getHiddenForField(sortKey.getField())); } if (field.equals(fieldName)) { int direction = ((Number) dir).intValue(); return sortKey.isDesc() == (direction < 0); } return false; }
Source:
private void storeCert() throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { final Map<String, String> trustStoreProperties = getTrustStoreSystemProperties(); String storeType = trustStoreProperties.get(TRUST_STORE_TYPE_KEY); final String password = trustStoreProperties.get(TRUST_STORE_PASSWORD_KEY); final String storeLoc = trustStoreProperties.get(TRUST_STORE_KEY); if (storeType == null) { LOG.warn(STORE_TYPE_ERROR, TRUST_STORE_TYPE_KEY); storeType = JKS_TYPE; } if (password != null && !PKCS11_TYPE.equalsIgnoreCase(storeType)) { FileOutputStream os = null; try { os = new FileOutputStream(storeLoc); trustStore.store(os, password.toCharArray()); } finally { IOUtils.closeQuietly(os); } } }

Target:
private void storeCert() throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { final Map<String, String> trustStoreProperties = getTrustStoreSystemProperties(); String storeType = trustStoreProperties.get(TRUST_STORE_TYPE_KEY); final String password = trustStoreProperties.get(TRUST_STORE_PASSWORD_KEY); final String storeLoc = trustStoreProperties.get(TRUST_STORE_KEY); if (storeType == null) { LOG.warn(STORE_TYPE_ERROR, TRUST_STORE_TYPE_KEY); storeType = JKS_TYPE; } if (password != null && !PKCS11_TYPE.equalsIgnoreCase(storeType)) { try (FileOutputStream os = new FileOutputStream(storeLoc)) { trustStore.store(os, password.toCharArray()); } } }
Source:
public void execute() throws ExecutionException, InterruptedException { final String discountCodeId = UUID.randomUUID().toString(); final DefaultRemoveDiscountCodeFormData removeDiscountCodeFormData = new DefaultRemoveDiscountCodeFormData(); removeDiscountCodeFormData.setDiscountCodeId(discountCodeId); when: { when(hookRunner.runUnaryOperatorHook(any(), any(), cartUpdateCommandCaptor.capture())) .thenAnswer(invocation -> invocation.getArgument(2)); when(hookRunner.runActionHook(any(), any(), any())) .thenAnswer(invocation -> CompletableFuture.completedFuture(invocation.getArgument(2))); when(sphereClient.execute(any())) .thenReturn(CompletableFuture.completedFuture(cart)); } final Cart updatedCart = defaultRemoveDiscountCodeControllerAction.apply(cart, removeDiscountCodeFormData) .toCompletableFuture().get(); then: { assertThat(updatedCart).isNotNull(); final CartUpdateCommand cartUpdateCommand = cartUpdateCommandCaptor.getValue(); assertThat(cartUpdateCommand.getUpdateActions()).hasSize(1); final UpdateAction<Cart> cartUpdateAction = cartUpdateCommand.getUpdateActions().get(0); assertThat(cartUpdateAction).isInstanceOf(RemoveDiscountCode.class); final RemoveDiscountCode removeDiscountCode = (RemoveDiscountCode) cartUpdateAction; assertThat(removeDiscountCode.getDiscountCode().getId()).isEqualTo(discountCodeId); } }

Target:
public void execute() throws ExecutionException, InterruptedException { final String discountCodeId = UUID.randomUUID().toString(); final DefaultRemoveDiscountCodeFormData removeDiscountCodeFormData = new DefaultRemoveDiscountCodeFormData(); removeDiscountCodeFormData.setDiscountCodeId(discountCodeId); mockHookRunnerThatReturnsCart(); mockSphereClientThatReturnsCart(); final Cart updatedCart = defaultRemoveDiscountCodeControllerAction.apply(cart, removeDiscountCodeFormData) .toCompletableFuture().get(); assertThat(updatedCart).isNotNull(); final CartUpdateCommand cartUpdateCommand = cartUpdateCommandCaptor.getValue(); assertThat(cartUpdateCommand.getUpdateActions()) .hasSize(1) .hasOnlyElementsOfType(RemoveDiscountCode.class); final RemoveDiscountCode removeDiscountCode = (RemoveDiscountCode) cartUpdateCommand.getUpdateActions().get(0); assertThat(removeDiscountCode.getDiscountCode().getId()).isEqualTo(discountCodeId); }
Source:
public Resource display(@PathVariable("type") ModuleType type, @PathVariable("name") String name) { final ModuleDefinition definition = this.repository.findByNameAndType(name, type); if (definition == null) { throw new DefinitionNotFoundException(String.format( "There is no definition named '%s' for module type '%s'.", name, type.name())); } final Resource resource = definition.getResource(); if (!definition.getResource().exists()) { throw new ConfigurationFileNotFoundException(String.format("The Resourse ('%s" + "') associated with the module named '%s' (%s) does not exist.", definition.getResource().getFilename(), name, type.name())); } try { if (resource.getFile().length() == 0 && logger.isWarnEnabled()) { logger.warn(String.format("The length of the file '%s' for module '%s' (%s) is zero.", resource.getFilename(), definition.getName(), definition.getType().name())); } } catch (IOException e) { throw new IllegalStateException("Unable to return the file for the provided resource: " + resource.getFilename(), e); } return resource; }

Target:
public Resource display(@PathVariable("type") ModuleType type, @PathVariable("name") String name) { final ModuleDefinition definition = this.repository.findByNameAndType(name, type); if (definition == null) { throw new NoSuchDefinitionException(name, String.format( "There is no definition named '%s' for module type '%s'.", name, type.name())); } final Resource resource = definition.getResource(); try { if (resource.getFile().length() == 0 && logger.isWarnEnabled()) { logger.warn(String.format("The length of the file '%s' for module '%s' (%s) is zero.", resource.getFilename(), definition.getName(), definition.getType().name())); } } catch (IOException e) { throw new IllegalStateException("Unable to return the file for the provided resource: " + resource.getFilename(), e); } return resource; }
Source:
public void run() { while (currentPutCount.get() < totalPutCount) { try { int burstCount = threadLocalRandom.nextInt(maxParallelRequest) + 1; logger.trace("PutThread producing " + burstCount + " times "); final CountDownLatch countDownLatch = new CountDownLatch(burstCount); final AtomicInteger failureCount = new AtomicInteger(0); for (int j = 0; j < burstCount; j++) { Callback<Pair<String, byte[]>> callback = new Callback<Pair<String, byte[]>>() { @Override public void onCompletion(Pair<String, byte[]> result, Exception exception) { if (exception == null) { if (currentPutCount.get() < totalPutCount) { blobAccessInfos.add(new BlobAccessInfo(result.getFirst(), result.getSecond())); currentPutCount.incrementAndGet(); } } else { logger.error("PutBlob failed with " + exception.getStackTrace()); failureCount.incrementAndGet(); } countDownLatch.countDown(); } }; FutureResult futureResult = new FutureResult(); putHelper.putBlob(futureResult, callback); } countDownLatch.await(); if (failureCount.get() > maxFailuresPerPutBatchToStopPuts) { logger.error(failureCount.get() + " failures during this batch, hence exiting the Put Thread"); break; } Thread.sleep(threadLocalRandom.nextLong(sleepTimeBetweenBatchPutsInMs)); } catch (InterruptedException ex) { logger.error("InterruptedException in putThread " + ex.getStackTrace()); } } putComplete.set(true); logger.info( "Exiting Producer. Current Put Count " + currentPutCount.get() + ", total Put Count " + totalPutCount); }

Target:
public void run() { try { while (currentPutCount.get() < totalPutCount) { int burstCount = threadLocalRandom.nextInt(maxParallelRequest) + 1; logger.info("PutThread producing " + burstCount + " times "); final CountDownLatch countDownLatch = new CountDownLatch(burstCount); final AtomicInteger failureCount = new AtomicInteger(0); for (int j = 0; j < burstCount; j++) { Callback<Pair<String, byte[]>> callback = new Callback<Pair<String, byte[]>>() { @Override public void onCompletion(Pair<String, byte[]> result, Exception exception) { if (exception == null) { if (currentPutCount.get() < totalPutCount) { generatedBlobAccessInfos.add(new BlobAccessInfo(result.getFirst(), result.getSecond())); currentPutCount.incrementAndGet(); } } else { logger.error("PutBlob failed with ", exception); failureCount.incrementAndGet(); } countDownLatch.countDown(); } }; putHelper.putBlob(callback); } countDownLatch.await(5, TimeUnit.MINUTES); if (failureCount.get() > maxFailuresPerPutBatchToStopPuts) { logger.error(failureCount.get() + " failures during this batch, hence exiting the Put Thread"); break; } Thread.sleep(threadLocalRandom.nextLong(sleepTimeBetweenBatchPutsInMs)); } } catch (InterruptedException ex) { logger.error("InterruptedException in putThread ", ex); } finally { putComplete.set(true); } logger.info( "Exiting Producer. Current Put Count " + currentPutCount.get() + ", total Put Count " + totalPutCount); }
Source:
protected void processFiltered(File file, FileText fileText) throws CheckstyleException { if (CommonUtils.matchesFileExtension(file, getFileExtensions())) { final String msg = "%s occurred during the analysis of file %s."; final String fileName = file.getPath(); try { if (!ordinaryChecks.isEmpty() || !commentChecks.isEmpty()) { final FileText text = new FileText(fileText); final FileContents contents = new FileContents(text); final DetailAST rootAST = parse(contents); if (!ordinaryChecks.isEmpty()) { walk(rootAST, contents, AstState.ORDINARY); } if (!commentChecks.isEmpty()) { final DetailAST astWithComments = appendHiddenCommentNodes(rootAST); walk(astWithComments, contents, AstState.WITH_COMMENTS); } } } catch (final TokenStreamRecognitionException tre) { final String exceptionMsg = String.format(Locale.ROOT, msg, "TokenStreamRecognitionException", fileName); throw new CheckstyleException(exceptionMsg, tre); } catch (RecognitionException | TokenStreamException ex) { final String exceptionMsg = String.format(Locale.ROOT, msg, ex.getClass().getSimpleName(), fileName); throw new CheckstyleException(exceptionMsg, ex); } } }

Target:
protected void processFiltered(File file, FileText fileText) throws CheckstyleException { if (CommonUtils.matchesFileExtension(file, getFileExtensions())) { final String msg = "%s occurred during the analysis of file %s."; final String fileName = file.getPath(); try { if (!ordinaryChecks.isEmpty() || !commentChecks.isEmpty()) { final FileContents contents = new FileContents(fileText); final DetailAST rootAST = parse(contents); if (!ordinaryChecks.isEmpty()) { walk(rootAST, contents, AstState.ORDINARY); } if (!commentChecks.isEmpty()) { final DetailAST astWithComments = appendHiddenCommentNodes(rootAST); walk(astWithComments, contents, AstState.WITH_COMMENTS); } } } catch (final TokenStreamRecognitionException tre) { final String exceptionMsg = String.format(Locale.ROOT, msg, "TokenStreamRecognitionException", fileName); throw new CheckstyleException(exceptionMsg, tre); } catch (RecognitionException | TokenStreamException ex) { final String exceptionMsg = String.format(Locale.ROOT, msg, ex.getClass().getSimpleName(), fileName); throw new CheckstyleException(exceptionMsg, ex); } } }
Source:
public boolean isHangoutJoinerAutomationServiceEnabled() { List<AccessibilityServiceInfo> visualFeedbackServices = getVisualFeedbackServices(); for (AccessibilityServiceInfo service : visualFeedbackServices) { if (service.getId().equalsIgnoreCase(SERVICE_ID)) { return true; } } return false; }

Target:
public boolean isHangoutJoinerAutomationServiceEnabled() { List<AccessibilityServiceInfo> visualFeedbackServices = getVisualFeedbackServices(); for (AccessibilityServiceInfo service : visualFeedbackServices) { if (SERVICE_ID.equals(service.getId())) { return true; } } return false; }
Source:
private void viewPages() { requestNextStepOfActiveQuickStartTask(); SiteModel selectedSite = getSelectedSite(); if (selectedSite != null) { ToastUtils.showToast(getActivity(), R.string.site_cannot_be_loaded); ActivityLauncher.viewCurrentBlogPages(requireActivity(), selectedSite); } }

Target:
private void viewPages() { requestNextStepOfActiveQuickStartTask(); SiteModel selectedSite = getSelectedSite(); if (selectedSite != null) { ActivityLauncher.viewCurrentBlogPages(requireActivity(), selectedSite); } else { ToastUtils.showToast(getActivity(), R.string.site_cannot_be_loaded); } }
Source:
private EnvVars buildEnv(final Job<?, ?> job) { EnvVars env = new EnvVars(); for (EnvironmentContributor contributor : EnvironmentContributor.all()) { try { contributor.buildEnvironmentFor(job, env, TaskListener.NULL); } catch (Exception e) { LOGGER.warning("failed to build env, skipping"); } } return env; }

Target:
private EnvVars buildEnv(final Job<?, ?> job) { final EnvVars env = new EnvVars(); for (final EnvironmentContributor contributor : EnvironmentContributor.all()) { try { contributor.buildEnvironmentFor(job, env, TaskListener.NULL); } catch (Exception e) { LOGGER.warning("failed to build env, skipping"); } } return env; }
Source:
public void saveFactors(final DmsProject measurementDataset, final List<MeasurementVariable> variables) { if (variables != null && !variables.isEmpty()) { for (final MeasurementVariable variable : variables) { switch (variable.getOperation().toString()) { case "ADD": final int rank = this.getNextRank(measurementDataset); this.insertVariable(measurementDataset, variable, rank); break; case "DELETE": this.deleteVariableForFactors(measurementDataset, variable); break; default: break; } } } }

Target:
public void saveFactors(final DmsProject measurementDataset, final List<MeasurementVariable> variables) { if (variables != null && !variables.isEmpty()) { for (final MeasurementVariable variable : variables) { switch (variable.getOperation()) { case ADD: final int rank = this.getNextRank(measurementDataset); this.insertVariable(measurementDataset, variable, rank); break; case DELETE: this.deleteVariableForFactors(measurementDataset, variable); break; default: break; } } } }
Source:
private void addSSLPortToJson(JSONObject jsonObject) throws JSONException { for (PortType portType : ports.keySet()) { if (portType != PortType.PLAINTEXT) { jsonObject.put("sslport", ports.get(portType)); } } }

Target:
private void addSSLPortToJson(JSONObject jsonObject) throws JSONException { for (PortType portType : ports.keySet()) { if (portType == PortType.SSL) { jsonObject.put("sslport", ports.get(portType)); } } }
Source:
private static double averageColumn(double[][] arrayOfArrays, int columnIndex) { double sum = 0; int count = 0; StringBuilder values = new StringBuilder(); for (double[] array : arrayOfArrays) { double value = array[columnIndex]; values.append(value).append(' '); if (value == NA || value == NSU) { continue; } sum += value; count++; } double average = count == 0 ? NA : (double) (sum / count); String logMessage = "Average(" + values.toString().trim() + ") = " + average; log.fine(replaceMagicNumbers(logMessage)); return average; }

Target:
private static double averageColumn(double[][] arrayOfArrays, int columnIndex) { double sum = 0; int count = 0; StringBuilder values = new StringBuilder(); for (double[] array : arrayOfArrays) { double value = array[columnIndex]; values.append(value).append(' '); if (isValidSpecialValue(value)) { continue; } sum += value; count++; } double average = count == 0 ? NA : (double) (sum / count); String logMessage = "Average(" + values.toString().trim() + ") = " + average; log.fine(replaceMagicNumbers(logMessage)); return average; }
Source:
public void updateOnMediaChanged(String blogId, String mediaId) { if (mediaId == null) { return; } Cursor cursor = WordPress.wpDB.getMediaFile(blogId, mediaId); if (cursor == null || !cursor.moveToFirst()) { mMediaGridFragment.removeFromMultiSelect(mediaId); mMediaGridFragment.refreshMediaFromDB(); if (mMediaEditFragment != null && mMediaEditFragment.isVisible() && mediaId.equals(mMediaEditFragment.getMediaId())) { if (mMediaEditFragment.isInLayout()) { mMediaEditFragment.loadMedia(null); } else { getFragmentManager().popBackStack(); } } } else { mMediaGridFragment.refreshMediaFromDB(); } if (cursor != null) { cursor.close(); } }

Target:
public void updateOnMediaChanged(String blogId, String mediaId) { if (mediaId == null) { return; } if (!WordPress.wpDB.mediaFileExists(blogId, mediaId)) { mMediaGridFragment.removeFromMultiSelect(mediaId); if (mMediaEditFragment != null && mMediaEditFragment.isVisible() && mediaId.equals(mMediaEditFragment.getMediaId())) { if (mMediaEditFragment.isInLayout()) { mMediaEditFragment.loadMedia(null); } else { getFragmentManager().popBackStack(); } } } mMediaGridFragment.refreshMediaFromDB(); mMediaGridFragment.updateFilterText(); mMediaGridFragment.updateSpinnerAdapter(); }
Source:
void put(SystemStreamPartition ssp, Object key, Object message) { List<IncomingMessageEnvelope> messages = bufferedMessages.get(ssp); String offset = String.valueOf(messages.size()); if (message instanceof EndOfStreamMessage) { offset = IncomingMessageEnvelope.END_OF_STREAM_OFFSET; } IncomingMessageEnvelope messageEnvelope = new IncomingMessageEnvelope(ssp, offset, key, message, 0, 0L, System.nanoTime()); bufferedMessages.get(ssp) .add(messageEnvelope); }

Target:
void put(SystemStreamPartition ssp, Object key, Object message) { List<IncomingMessageEnvelope> messages = bufferedMessages.get(ssp); String offset = String.valueOf(messages.size()); if (message instanceof EndOfStreamMessage) { offset = IncomingMessageEnvelope.END_OF_STREAM_OFFSET; } IncomingMessageEnvelope messageEnvelope = new IncomingMessageEnvelope(ssp, offset, key, message, 0, 0L, Instant.now().toEpochMilli()); bufferedMessages.get(ssp) .add(messageEnvelope); }