auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static String toString(final String[] enumerators) { StringBuilder result = new StringBuilder("("); for (int i = 0; i < enumerators.length; i++) { result.append("'").append(enumerators[i]).append("'"); if (i < enumerators.length - 1) { result.append(", "); } } result.append(")"); return result.toString(); }

Target:
private static String toString(final String[] enumerators) { String result = "("; for (int i = 0; i < enumerators.length; i++) { result += "'" + enumerators[i] + "'"; if (i < enumerators.length - 1) { result += ", "; } } result += ")"; return result; }
Source:
private String extractVmIps(List<VmGuestAgentInterface> nics) { if (nics == null || nics.isEmpty()) { return null; } Stream<String> ipsV4 = nics.stream().map(VmGuestAgentInterface::getIpv4Addresses).flatMap(List::stream); Stream<String> ipsV6 = nics.stream().map(VmGuestAgentInterface::getIpv6Addresses).flatMap(List::stream); String ips = Stream.of(ipsV4, ipsV6).flatMap(stream -> stream).collect(Collectors.joining(" ")); return ips.isEmpty() ? null : ips; }

Target:
private String extractVmIps(List<VmGuestAgentInterface> nics) { Stream<String> ipsV4 = nics.stream().map(VmGuestAgentInterface::getIpv4Addresses).flatMap(List::stream); Stream<String> ipsV6 = nics.stream().map(VmGuestAgentInterface::getIpv6Addresses).flatMap(List::stream); String ips = Stream.of(ipsV4, ipsV6).flatMap(stream -> stream).collect(Collectors.joining(" ")); return ips.isEmpty() ? null : ips; }
Source:
private static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); System.out.println("Encrypted the file"); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }

Target:
private static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Source:
private void addPVToEditor(String pvAddress, final String displayName, DataBrowserEditor editor) { if (editor == null) { return; } Model model = editor.getModel(); final double period = Preferences.getScanPeriod(); try { final PVItem item = new PVItemWithUnits(displayName, pvAddress, period); item.useDefaultArchiveDataSources(); AxisConfig axis = model.addAxis(item.getDisplayName()); axis.setAutoScale(false); item.setAxis(axis); model.addItem(item); } catch (Exception ex) { MessageDialog.openError(editor.getSite().getShell(), Messages.Error, NLS.bind(Messages.ErrorFmt, ex.getMessage())); } }

Target:
private void addPVToEditor(String pvAddress, final String displayName, DataBrowserEditor editor) { if (editor == null) { return; } Model model = editor.getModel(); final double period = Preferences.getScanPeriod(); try { AxisConfig axis = model.addAxis(displayName); axis.setAutoScale(false); final PVItem item = new PVItemWithUnits(displayName, pvAddress, period, axis); item.useDefaultArchiveDataSources(); item.setAxis(axis); model.addItem(item); } catch (Exception ex) { MessageDialog.openError(editor.getSite().getShell(), Messages.Error, NLS.bind(Messages.ErrorFmt, ex.getMessage())); } }
Source:
public static boolean isDimAllowed(int dimId) { if(blacklistedDims.isEmpty() || !blacklistedDims.contains(dimId)) { return whitelistedDims.isEmpty() || whitelistedDims.contains(dimId); } return true; }

Target:
public static boolean isDimAllowed(int dimId) { if(blacklistedDims.isEmpty() || !blacklistedDims.contains(dimId)) { return whitelistedDims.isEmpty() || whitelistedDims.contains(dimId); } return false; }
Source:
private void logNonDownVms(List<VM> notDownVms) { if (!notDownVms.isEmpty()) { AuditLogableBase logable = new AuditLogableBase(); logable.addCustomValue("URL", getParameters().getUrl()); logable.addCustomValue("Vms", StringUtils.join(notDownVms, ",")); auditLogDirector.log(logable, AuditLogType.IMPORTEXPORT_GET_EXTERNAL_VMS_NOT_IN_DOWN_STATUS); } }

Target:
private void logNonDownVms(List<VM> notDownVms) { if (!notDownVms.isEmpty()) { if (shouldLogToAuditLog()) { AuditLogableBase logable = new AuditLogableBase(); logable.addCustomValue("URL", getParameters().getUrl()); logable.addCustomValue("Vms", StringUtils.join(notDownVms, ",")); auditLogDirector.log(logable, AuditLogType.IMPORTEXPORT_GET_EXTERNAL_VMS_NOT_IN_DOWN_STATUS); } else { log.warn( "The following VMs retrieved from external server '{}' are not in down status and therefore can't be imported: '{}'.", getParameters().getUrl(), StringUtils.join(notDownVms, ",")); } } }
Source:
private void readSubscribeCommands() throws IOException, TransportException { String line; ArrayList<SubscribeCommand> cmdList = null; Map<String, ObjectId> stateList = null; String repo = null; while (!(line = in.readString()).startsWith("done")) { if (line == PacketLineIn.END) { commands.put(repo, cmdList); refState.put(repo, stateList); repo = null; cmdList = null; stateList = null; } else if (line.startsWith("repository ")) { repo = line.substring("repository ".length()); cmdList = new ArrayList<SubscribeCommand>(); stateList = new HashMap<String, ObjectId>(); } else { if (repo == null || cmdList == null || stateList == null) throw new IOException(MessageFormat.format(JGitText .get().invalidSubscribeRequest, line)); if (line.startsWith("want ")) cmdList.add(new SubscribeCommand(SUBSCRIBE, line.substring( "want ".length()))); else if (line.startsWith("stop ")) throw new TransportException("stop command not supported"); else if (line.startsWith("have ")) { String[] parts = line.split(" ", 3); stateList.put(parts[2], ObjectId.fromString(parts[1])); } } } }

Target:
private Request readSubscribeCommands() throws IOException, TransportException { Request r = new Request(); r.commands = new HashMap<String, List<SubscribeCommand>>(); r.clientRefState = new HashMap<String, Map<String, ObjectId>>(); String line; ArrayList<SubscribeCommand> cmdList = null; Map<String, ObjectId> stateList = null; String repo = null; while (!(line = in.readString()).startsWith("done")) { if (line == PacketLineIn.END && repo != null) { r.commands.put(repo, cmdList); r.clientRefState.put(repo, stateList); repo = null; cmdList = null; stateList = null; } else if (line.startsWith("repository ")) { repo = line.substring("repository ".length()); cmdList = new ArrayList<SubscribeCommand>(); stateList = new HashMap<String, ObjectId>(); } else { if (repo == null || cmdList == null || stateList == null) throw new TransportException(MessageFormat.format(JGitText .get().invalidSubscribeRequest, line)); if (line.startsWith("want ")) cmdList.add(new SubscribeCommand(SUBSCRIBE, line.substring( "want ".length()))); else if (line.startsWith("stop ")) throw new TransportException("stop command not supported"); else if (line.startsWith("have ")) { String[] parts = line.split(" ", 3); if (parts.length < 3) throw new TransportException(MessageFormat.format( JGitText.get().invalidSubscribeRequest, line)); stateList.put(parts[2], ObjectId.fromString(parts[1])); } } } return r; }
Source:
public void refresh() { fCategoryViewer.setInput(fModel); super.refresh(); }

Target:
public void refresh() { fCategoryViewer.refresh(); super.refresh(); }
Source:
public Money plus(List<Money> amounts) { return new Money(this.wrapped.plus(amounts.stream().map(x -> x.wrapped).collect(Collectors.toList()))); }

Target:
public Money plus(List<Money> amounts) { return new Money(this.wrapped.plus((Iterable<BigMoney>)(amounts.stream().map(x -> x.wrapped)::iterator))); }
Source:
public void testRegularAndRuntimeParametersAreEqualWithRequest() { ReadRowsRequest request = ReadRowsRequest.newBuilder().setRowsLimit(10).build(); CloudBigtableScanConfiguration withRegularParameters = config .toBuilder() .withRequest(request) .withKeys(START_ROW, STOP_ROW) .withConfiguration("somekey", "somevalue") .build(); CloudBigtableScanConfiguration withRuntimeParameters = new CloudBigtableScanConfiguration.Builder() .withTableId(StaticValueProvider.of(TABLE)) .withProjectId(StaticValueProvider.of(PROJECT)) .withInstanceId(StaticValueProvider.of(INSTANCE)) .withRequest(StaticValueProvider.of(request)) .withKeys(START_ROW, STOP_ROW) .withConfiguration("somekey", StaticValueProvider.of("somevalue")) .build(); Assert.assertNotSame(withRegularParameters, withRuntimeParameters); Assert.assertEquals(withRegularParameters, withRuntimeParameters); ReadRowsRequest updatedRequest = withRegularParameters.getRequest(); withRegularParameters = withRegularParameters.toBuilder().withRequest(updatedRequest).build(); withRuntimeParameters = withRuntimeParameters .toBuilder() .withRequest(StaticValueProvider.of(updatedRequest)) .build(); Assert.assertNotSame(withRegularParameters, withRuntimeParameters); Assert.assertEquals(withRegularParameters, withRuntimeParameters); }

Target:
public void testRegularAndRuntimeParametersAreEqualWithRequest() { ReadRowsRequest request = ReadRowsRequest.newBuilder().setRowsLimit(10).build(); CloudBigtableScanConfiguration withRegularParameters = config .toBuilder() .withRequest(request) .withKeys(START_ROW, STOP_ROW) .withConfiguration("somekey", "somevalue") .build(); CloudBigtableScanConfiguration withRuntimeParameters = new CloudBigtableScanConfiguration.Builder() .withTableId(StaticValueProvider.of(TABLE)) .withProjectId(StaticValueProvider.of(PROJECT)) .withInstanceId(StaticValueProvider.of(INSTANCE)) .withRequest(StaticValueProvider.of(request)) .withKeys(START_ROW, STOP_ROW) .withConfiguration("somekey", StaticValueProvider.of("somevalue")) .build(); Assert.assertEquals(withRegularParameters, withRuntimeParameters); ReadRowsRequest updatedRequest = withRegularParameters.getRequest(); withRegularParameters = withRegularParameters.toBuilder().withRequest(updatedRequest).build(); withRuntimeParameters = withRuntimeParameters .toBuilder() .withRequest(StaticValueProvider.of(updatedRequest)) .build(); Assert.assertEquals(withRegularParameters, withRuntimeParameters); }
Source:
public static CompositeRequirement allOf(List<Requirement> requirements) { return new MultiCompositeRequirement(copyOf(wrapAsCompositeRequirements(requirements).stream().map(ImmutableSet::of).collect(Collectors.toList()))); }

Target:
public static CompositeRequirement allOf(List<Requirement> requirements) { return new MultiCompositeRequirement(wrapAsCompositeRequirements(requirements).stream() .map(ImmutableSet::of) .collect(toImmutableSet())); }
Source:
void should_fail_if_null() { List<SoftAssertions> softAssertions = new ArrayList<SoftAssertions>() {{ add(softlyNotAnnotated1); add(softlyNotAnnotated2); }}; ThrowingCallable code = () -> assertThat(softAssertions).doesNotContainNull(); assertThatAssertionErrorIsThrownBy(code).withMessage(ShouldNotContainNull.shouldNotContainNull(softAssertions).create()); }

Target:
void should_fail_if_null() { ThrowingCallable code = () -> assertThat(softlyNotAnnotated).isNotNull(); assertThatAssertionErrorIsThrownBy(code).withMessage(ShouldNotBeNull.shouldNotBeNull().create()); }
Source:
private String kaomojiify(String message) throws Exception { String[] words = splitWords(message); String kaomoji = ""; if (words.length <= 0 ){ return "ⓃⒶⓃⒾ(☉൧ ಠ ꐦ)"; } if (words.length >= 1 ){ if (words[0].equals("wat")){ words[0] = "confused"; } else if (words[0].equals("nsfw") | words[0].equals("wtf")){ kaomoji = "ⓃⒶⓃⒾ(☉൧ ಠ ꐦ)"; } else if (words[0].equals("vilebot")){ kaomoji = "( ͡° ͜ʖ ͡° )"; } else { kaomoji = getKaomoji(words[0]); } if (kaomoji.isEmpty()){ kaomoji = "щ(ಥдಥщ)"; } } return kaomoji; }

Target:
private String kaomojiify(String message) throws Exception { String[] words = splitWords(message); String kaomoji = ""; if (words.length <= 0 ){ return "ⓃⒶⓃⒾ(☉൧ ಠ ꐦ)"; } if (words.length >= 1 ){ if (words[0].equals("wat")){ words[0] = "confused"; } else if (words[0].equals("nsfw") || words[0].equals("wtf")){ kaomoji = "ⓃⒶⓃⒾ(☉൧ ಠ ꐦ)"; } else if (words[0].equals("vilebot")){ kaomoji = "( ͡° ͜ʖ ͡° )"; } else { kaomoji = getKaomoji(words[0]); } if (kaomoji.isEmpty()){ kaomoji = "щ(ಥдಥщ)"; } } return kaomoji; }
Source:
public void addAJPListenerInGUI() throws Exception { ConfigFragment config = page.getConfigFragment(); WizardWindow wizard = config.getResourceManager().addResource(); Editor editor = wizard.getEditor(); editor.text("name", AJP_LISTENER_TBA); editor.text(SOCKET_BINDING, SOCKET_BINDING_AJP_TBA); boolean result = wizard.finishAndDismissReloadRequiredWindow(); Assert.assertTrue("Window should be closed", result); Assert.assertTrue("AJP listener should be present in table", config.resourceIsPresent(AJP_LISTENER_TBA)); new ResourceVerifier(AJP_LISTENER_ADDRESS_TBA, client).verifyExists(); new ResourceVerifier(AJP_LISTENER_ADDRESS_TBA, client).verifyAttribute(SOCKET_BINDING, SOCKET_BINDING_AJP_TBA); }

Target:
public void addAJPListenerInGUI() throws Exception { ConfigFragment config = page.getConfigFragment(); String socketBinding = undertowOps.createSocketBinding(); WizardWindow wizard = config.getResourceManager().addResource(); Editor editor = wizard.getEditor(); editor.text("name", AJP_LISTENER_TBA); editor.text(SOCKET_BINDING, socketBinding); boolean result = wizard.finishAndDismissReloadRequiredWindow(); Assert.assertTrue("Window should be closed", result); Assert.assertTrue("AJP listener should be present in table", config.resourceIsPresent(AJP_LISTENER_TBA)); new ResourceVerifier(AJP_LISTENER_ADDRESS_TBA, client) .verifyExists() .verifyAttribute(SOCKET_BINDING, socketBinding); }
Source:
public static RetryIntervalType find(String value) { for (RetryIntervalType r : RetryIntervalType.values()) { if (r.type.equalsIgnoreCase(value)) { return r; } } throw new ConfigException("Invalid retry_interval_type"); }

Target:
public static RetryIntervalType find(String value) { for (RetryIntervalType r : RetryIntervalType.values()) { if (r.type.equalsIgnoreCase(value)) { return r; } } throw new ConfigException("Invalid retry_interval_type: " + value); }
Source:
TreeDefinition(TreeBranchDefinition branch, String speciesName, String binomial, boolean dominant, EnumLeafType leafType, Color primary, Color secondary, IWoodType woodType) { String uid = Constants.MOD_ID + ".tree" + this; String unlocalizedDescription = "for.description.tree" + this; String unlocalizedName = "for.trees.species." + speciesName; this.branch = branch; ILeafSpriteProvider leafIconProvider = TreeManager.treeFactory.getLeafIconProvider(leafType, primary, secondary); IGermlingModelProvider germlingIconProvider = ModelProviderFactory.create(woodType, uid, leafIconProvider); IWoodProvider woodProvider = WoodProviderFactory.create(woodType); ILeafProvider leafProvider = new LeafProvider(); IAlleleTreeSpeciesBuilder speciesBuilder = TreeManager.treeFactory.createSpecies(uid, unlocalizedName, "Sengir", unlocalizedDescription, dominant, branch.getBranch(), binomial, Constants.MOD_ID, leafIconProvider, germlingIconProvider, woodProvider, this, leafProvider); setSpeciesProperties(speciesBuilder); this.species = speciesBuilder.build(); leafProvider.init(this.species); this.woodType = woodType; }

Target:
TreeDefinition(TreeBranchDefinition branch, String speciesName, String binomial, boolean dominant, EnumLeafType leafType, Color primary, Color secondary, IWoodType woodType) { String uid = Constants.MOD_ID + ".tree" + this; String unlocalizedDescription = "for.description.tree" + this; String unlocalizedName = "for.trees.species." + speciesName; this.branch = branch; ILeafSpriteProvider leafIconProvider = TreeManager.treeFactory.getLeafIconProvider(leafType, primary, secondary); IGermlingModelProvider germlingIconProvider = ModelProviderFactory.create(woodType, uid, leafIconProvider); IWoodProvider woodProvider = WoodProviderFactory.create(woodType); ILeafProvider leafProvider = new LeafProvider(); IAlleleTreeSpeciesBuilder speciesBuilder = TreeManager.treeFactory.createSpecies(uid, unlocalizedName, "Sengir", unlocalizedDescription, dominant, branch.getBranch(), binomial, Constants.MOD_ID, leafIconProvider, germlingIconProvider, woodProvider, this, leafProvider); setSpeciesProperties(speciesBuilder); this.species = speciesBuilder.build(); this.woodType = woodType; }
Source:
private CucumberTestContext() { throw new AssertionError(); }

Target:
private CucumberTestContext() { }
Source:
public int compare(int i, int j) { float vi = a[i]; float vj = a[j]; return (floatEquals(vi, vj)) ? 0 : (vi > vj) ? 1 : -1; }

Target:
public int compare(int i, int j) { float vi = a[i]; float vj = a[j]; return Float.compare(vi, vj); }
Source:
public void testEquals() { ______TS("Different classes, should be different"); FeedbackQuestionDetails ftqd1 = new FeedbackTextQuestionDetails("text question"); FeedbackQuestionDetails ftqd2 = new FeedbackMcqQuestionDetails(); assertFalse(ftqd1.equals(ftqd2)); ______TS("Some attributes are different, should be different"); ftqd1 = new FeedbackTextQuestionDetails("first question"); ftqd2 = new FeedbackTextQuestionDetails("second question"); assertFalse(ftqd1.equals(ftqd2)); ftqd2 = new FeedbackTextQuestionDetails("first question"); ((FeedbackTextQuestionDetails) ftqd1).setRecommendedLength(50); assertFalse(ftqd1.equals(ftqd2)); ______TS("All attributes are same, should be same"); ((FeedbackTextQuestionDetails) ftqd2).setRecommendedLength(50); assertTrue(ftqd1.equals(ftqd2)); }

Target:
public void testEquals() { ______TS("Same object with different references, should be same"); FeedbackQuestionDetails ftqd1 = new FeedbackTextQuestionDetails("text question"); FeedbackQuestionDetails ftqd2 = ftqd1; assertEquals(ftqd1, ftqd2); ______TS("One input is null, should be different"); ftqd1 = new FeedbackTextQuestionDetails("text question"); ftqd2 = null; assertNotEquals(ftqd1, ftqd2); ______TS("Different classes, should be different"); ftqd1 = new FeedbackTextQuestionDetails("text question"); ftqd2 = new FeedbackMcqQuestionDetails(); assertNotEquals(ftqd1, ftqd2); ______TS("Some attributes are different, should be different"); ftqd1 = new FeedbackTextQuestionDetails("first question"); ftqd2 = new FeedbackTextQuestionDetails("second question"); assertNotEquals(ftqd1, ftqd2); ftqd2 = new FeedbackTextQuestionDetails("first question"); ((FeedbackTextQuestionDetails) ftqd1).setRecommendedLength(50); assertNotEquals(ftqd1, ftqd2); ______TS("All attributes are same, should be same"); ((FeedbackTextQuestionDetails) ftqd2).setRecommendedLength(50); assertEquals(ftqd1, ftqd2); }
Source:
protected boolean validate() { boolean returnValue = true; Permission p = getPermissionDao().get(getParameters().getPermission().getId()); if (MultiLevelAdministrationHandler.isLastSuperUserPermission(p.getRoleId())) { getReturnValue().getValidationMessages() .add(EngineMessage.ERROR_CANNOT_REMOVE_LAST_SUPER_USER_ROLE.toString()); returnValue = false; } else if (p.getRoleType().equals(RoleType.ADMIN) && !isSystemSuperUser()) { addValidationMessage(EngineMessage.PERMISSION_REMOVE_FAILED_ONLY_SYSTEM_SUPER_USER_CAN_REMOVE_ADMIN_ROLES); returnValue = false; } if(getParameters().getTargetId() != null && !Objects.equals(p.getAdElementId(), getParameters().getTargetId())) { addValidationMessage(EngineMessage.INHERITED_PERMISSION_CANT_BE_REMOVED); returnValue = false; } return returnValue; }

Target:
protected boolean validate() { boolean returnValue = true; Permission p = getPermissionDao().get(getParameters().getPermission().getId()); if (MultiLevelAdministrationHandler.isLastSuperUserPermission(p.getRoleId())) { getReturnValue().getValidationMessages() .add(EngineMessage.ERROR_CANNOT_REMOVE_LAST_SUPER_USER_ROLE.toString()); returnValue = false; } else if (p.getRoleType().equals(RoleType.ADMIN) && !isSystemSuperUser()) { addValidationMessage(EngineMessage.PERMISSION_REMOVE_FAILED_ONLY_SYSTEM_SUPER_USER_CAN_REMOVE_ADMIN_ROLES); returnValue = false; } if(!Objects.equals(p.getAdElementId(), getParameters().getTargetId())) { addValidationMessage(EngineMessage.INHERITED_PERMISSION_CANT_BE_REMOVED); returnValue = false; } return returnValue; }
Source:
public void should_create_mock_from_final_class_in_the_JDK() throws Exception { assumeTrue(ClassFileVersion.ofThisVm().isLessThan(ClassFileVersion.JAVA_V9)); MockCreationSettings<Pattern> settings = settingsFor(Pattern.class); Pattern proxy = mockMaker.createMock(settings, new MockHandlerImpl<Pattern>(settings)); assertThat(proxy.pattern()).isEqualTo("bar"); }

Target:
public void should_create_mock_from_final_class_in_the_JDK() throws Exception { assumeTrue(ClassFileVersion.ofThisVm().isLessThan(JAVA_V9)); MockCreationSettings<Pattern> settings = settingsFor(Pattern.class); Pattern proxy = mockMaker.createMock(settings, new MockHandlerImpl<Pattern>(settings)); assertThat(proxy.pattern()).isEqualTo("bar"); }
Source:
private void fitPartial( MultiDataSet dataSet, List<S.Builder> featureStatsBuilders, List<S.Builder> labelStatsBuilders ) { int numInputs = dataSet.getFeatures().length; int numOutputs = dataSet.getLabels().length; ensureStatsBuilders(featureStatsBuilders, numInputs); ensureStatsBuilders(labelStatsBuilders, numOutputs); for (int i = 0; i < numInputs; i++) { featureStatsBuilders.get(i).add(dataSet.getFeatures(i), dataSet.getFeaturesMaskArray(i)); } if (isFitLabel()) { for (int i = 0; i < numOutputs; i++) { labelStatsBuilders.get(i).add(dataSet.getLabels(i), dataSet.getLabelsMaskArray(i)); } } }

Target:
private void fitPartial(MultiDataSet dataSet, List<S.Builder> featureStatsBuilders, List<S.Builder> labelStatsBuilders) { int numInputs = dataSet.numFeatureArrays(); int numOutputs = dataSet.numLabelsArrays(); ensureStatsBuilders(featureStatsBuilders, numInputs); ensureStatsBuilders(labelStatsBuilders, numOutputs); for (int i = 0; i < numInputs; i++) { featureStatsBuilders.get(i).add(dataSet.getFeatures(i), dataSet.getFeaturesMaskArray(i)); } if (isFitLabel()) { for (int i = 0; i < numOutputs; i++) { labelStatsBuilders.get(i).add(dataSet.getLabels(i), dataSet.getLabelsMaskArray(i)); } } }
Source:
public Sequence<T> run(final Query<T> query, final Map<String, Object> responseContext) { final QueryMetrics<? super Query<T>> queryMetrics = queryToolChest.makeMetrics(query); applyCustomDimensions.accept(queryMetrics); final Query<T> queryWithMetrics = query.withQueryMetrics(queryMetrics); return Sequences.wrap( new LazySequence<>(() -> queryRunner.run(queryWithMetrics, responseContext)), new SequenceWrapper() { private long startTimeNs; @Override public void before() { startTimeNs = System.nanoTime(); } @Override public void after(boolean isDone, Throwable thrown) { if (thrown != null) { queryMetrics.status("failed"); } else if (!isDone) { queryMetrics.status("short"); } long timeTakenNs = System.nanoTime() - startTimeNs; reportMetric.accept(queryMetrics, timeTakenNs); if (creationTimeNs > 0) { queryMetrics.reportWaitTime(startTimeNs - creationTimeNs); } queryMetrics.emit(emitter); } } ); }

Target:
public Sequence<T> run(final Query<T> query, final Map<String, Object> responseContext) { final QueryMetrics<? super Query<T>> queryMetrics = queryToolChest.makeMetrics(query); applyCustomDimensions.accept(queryMetrics); return Sequences.wrap( new LazySequence<>(() -> queryRunner.run(query, responseContext)), new SequenceWrapper() { private long startTimeNs; @Override public void before() { startTimeNs = System.nanoTime(); } @Override public void after(boolean isDone, Throwable thrown) { if (thrown != null) { queryMetrics.status("failed"); } else if (!isDone) { queryMetrics.status("short"); } long timeTakenNs = System.nanoTime() - startTimeNs; reportMetric.accept(queryMetrics, timeTakenNs); if (creationTimeNs > 0) { queryMetrics.reportWaitTime(startTimeNs - creationTimeNs); } queryMetrics.emit(emitter); } } ); }
Source:
private boolean isJobOnMinionType(Job job, String minionType) { Set<String> hostsWithTargetMinionType = new HashSet<String>(); List<HostState> hostStates = spawn.hostManager.listHostStatus(minionType); for (HostState hostState : hostStates) { hostsWithTargetMinionType.add(hostState.getHostUuid()); } for (JobTask jobTask : job.getCopyOfTasks()) { if (!hostsWithTargetMinionType.contains(jobTask.getHostUUID())) { return false; } List<JobTaskReplica> replicas = jobTask.getReplicas(); for (JobTaskReplica replica : replicas) { if (!hostsWithTargetMinionType.contains(replica.getHostUUID())) { return false; } } } return true; }

Target:
private boolean isJobOnMinionType(Job job, String minionType) { Set<String> hostsWithTargetMinionType = getHostsWithTargetMninionType(minionType); for (JobTask jobTask : job.getCopyOfTasks()) { if (!hostsWithTargetMinionType.contains(jobTask.getHostUUID())) { return false; } List<JobTaskReplica> replicas = jobTask.getReplicas(); for (JobTaskReplica replica : replicas) { if (!hostsWithTargetMinionType.contains(replica.getHostUUID())) { return false; } } } return true; }
Source:
private static String getRoutingDataCacheKey(RoutingDataReaderType routingDataReaderType, String endpoint) { return routingDataReaderType.name() + "_" + endpoint; }

Target:
private static String getRoutingDataCacheKey(RoutingDataReaderType routingDataReaderType, String endpoint) { if (routingDataReaderType == null) { throw new MultiZkException("RoutingDataManager: RoutingDataReaderType cannot be null!"); } return routingDataReaderType.name() + "_" + endpoint; }
Source:
private void rejoinModifies(ProgressMonitor pm) { HashMap<String, DiffEntry> nameMap = new HashMap<>(); ArrayList<DiffEntry> newAdded = new ArrayList<>(added.size()); pm.beginTask(JGitText.get().renamesRejoiningModifies, added.size() + deleted.size()); for (DiffEntry src : deleted) { if (pm.isCancelled()) { break; } nameMap.put(src.oldPath, src); pm.update(1); } for (DiffEntry dst : added) { if (pm.isCancelled()) { break; } DiffEntry src = nameMap.remove(dst.newPath); if (src != null) { if (sameType(src.oldMode, dst.newMode)) { entries.add(DiffEntry.pair(ChangeType.MODIFY, src, dst, src.score)); } else { nameMap.put(src.oldPath, src); newAdded.add(dst); } } else { newAdded.add(dst); } pm.update(1); } added = newAdded; deleted = new ArrayList<>(nameMap.values()); }

Target:
private void rejoinModifies(ProgressMonitor pm) throws CanceledException { HashMap<String, DiffEntry> nameMap = new HashMap<>(); ArrayList<DiffEntry> newAdded = new ArrayList<>(added.size()); pm.beginTask(JGitText.get().renamesRejoiningModifies, added.size() + deleted.size()); for (DiffEntry src : deleted) { nameMap.put(src.oldPath, src); advanceOrCancel(pm); } for (DiffEntry dst : added) { DiffEntry src = nameMap.remove(dst.newPath); if (src != null) { if (sameType(src.oldMode, dst.newMode)) { entries.add(DiffEntry.pair(ChangeType.MODIFY, src, dst, src.score)); } else { nameMap.put(src.oldPath, src); newAdded.add(dst); } } else { newAdded.add(dst); } advanceOrCancel(pm); } added = newAdded; deleted = new ArrayList<>(nameMap.values()); }
Source:
public static boolean is(String name, Class<?> type) { while (type != null) { if (name.equals(type.getName())) { return true; } Class<?>[] interfaces = type.getInterfaces(); if (interfaces != null) { for (Class<?> i : interfaces) { if (is(name, i)) { return true; } } } type = type.getSuperclass(); } return false; }

Target:
static boolean is(String name, Class<?> type) { while (type != null) { if (name.equals(type.getName())) { return true; } Class<?>[] interfaces = type.getInterfaces(); if (interfaces != null) { for (Class<?> i : interfaces) { if (is(name, i)) { return true; } } } type = type.getSuperclass(); } return false; }
Source:
public Object[] factory() { List<Object> tests = new ArrayList<>(3 * 3 * 2); for (TransactionMode txMode : TransactionMode.values()) { if (txMode == NONE) { continue; } for (LockingMode lockingMode : LockingMode.values()) { tests.add(new TxFunctionalTest<byte[], byte[]>().keyValueGenerator(BYTE_ARRAY_GENERATOR).transactionMode(txMode).lockingMode(lockingMode)); tests.add(new TxFunctionalTest<String, String>().keyValueGenerator(STRING_GENERATOR).transactionMode(txMode).lockingMode(lockingMode)); tests.add(new TxFunctionalTest<Object[], Object[]>().keyValueGenerator(GENERIC_ARRAY_GENERATOR).transactionMode(txMode).javaSerialization().lockingMode(lockingMode)); } } return tests.toArray(); }

Target:
public Object[] factory() { return Arrays.stream(TransactionMode.values()) .filter(tMode -> tMode != NONE) .flatMap(txMode -> Arrays.stream(LockingMode.values()) .flatMap(lockingMode -> Stream.builder() .add(new TxFunctionalTest<byte[], byte[]>() .keyValueGenerator(BYTE_ARRAY_GENERATOR) .transactionMode(txMode) .lockingMode(lockingMode)) .add(new TxFunctionalTest<String, String>() .keyValueGenerator(STRING_GENERATOR) .transactionMode(txMode) .lockingMode(lockingMode)) .add(new TxFunctionalTest<Object[], Object[]>() .keyValueGenerator(GENERIC_ARRAY_GENERATOR).javaSerialization() .transactionMode(txMode) .lockingMode(lockingMode)) .build())).toArray(); }
Source:
private void handleRequest(HttpRequest httpRequest) throws RestServiceException { if (request == null) { nettyMetrics.requestArrivalRate.mark(); request = new NettyRequest(httpRequest); responseChannel = new NettyResponseChannel(ctx, nettyMetrics); logger.trace("Channel now handling request {}", ctx.channel(), request.getUri()); if (RestMethod.POST.equals(request.getRestMethod())) { requestHandler.handleRequest(request, responseChannel); } } else { logger.warn("Discarding duplicate request on channel {}. Current request - {}. Duplicate request - {}", ctx.channel(), request.getUri(), httpRequest.getUri()); nettyMetrics.duplicateRequestError.inc(); } }

Target:
private void handleRequest(HttpRequest httpRequest) throws RestServiceException { if (request == null) { nettyMetrics.requestArrivalRate.mark(); request = new NettyRequest(httpRequest); responseChannel = new NettyResponseChannel(ctx, nettyMetrics); logger.trace("Channel now handling request {}", ctx.channel(), request.getUri()); if (request.getRestMethod().equals(RestMethod.POST)) { requestHandler.handleRequest(request, responseChannel); } } else { logger.warn("Discarding duplicate request on channel {}. Current request - {}. Duplicate request - {}", ctx.channel(), request.getUri(), httpRequest.getUri()); nettyMetrics.duplicateRequestError.inc(); } }
Source:
public static String getJavaLevel(IJavaProject project) throws Exception { IClasspathEntry[] classpathEntries = project.getRawClasspath(); for (IClasspathEntry classpathEntry : classpathEntries) { if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) { IPath path = classpathEntry.getPath(); if (path == null || path.segmentCount() < 3) continue; if (PATH_JRE_CONTAINER.equals(path.segment(0)) && PATH_JRE_STANDARD_VM.equals(path.segment(1))) { String jreName = path.segment(2); return EE.parse(jreName) .getVersionLabel(); } } } throw new IllegalArgumentException("No standard JRE container found on project classpath"); }

Target:
public static String getJavaLevel(IJavaProject project) throws Exception { IClasspathEntry[] classpathEntries = project.getRawClasspath(); for (IClasspathEntry classpathEntry : classpathEntries) { if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) { IPath path = classpathEntry.getPath(); if (path == null || path.segmentCount() < 3) continue; if (PATH_JRE_CONTAINER.equals(path.segment(0)) && PATH_JRE_STANDARD_VM.equals(path.segment(1))) { String jreName = path.segment(2); EE ee = EE.parse(jreName); if (ee == null) { throw new IllegalArgumentException("Unrecognized Java compliance level: " + jreName); } return ee.getVersionLabel(); } } } throw new IllegalArgumentException("No standard JRE container found on project classpath"); }
Source:
public void onStreamProcessorLaunchSuccess(SamzaResource resource) { String containerId = resource.getContainerId(); String containerHost = resource.getHost(); String processorId = getPendingProcessorId(containerId); LOG.info("Successfully started Processor ID: on Container ID: on host: {}", processorId, containerId, containerHost); if (processorId != null) { LOG.info("Moving Processor ID: on Container ID: on host: from pending to running state.", processorId, containerId, containerHost); state.pendingProcessors.remove(processorId); state.runningProcessors.put(processorId, resource); if (jobConfig.getApplicationMasterHighAvailabilityEnabled()) { state.processorToExecutionId.put(processorId, containerId); } if (state.neededProcessors.decrementAndGet() == 0) { state.jobHealthy.set(true); } containerManager.handleContainerLaunchSuccess(processorId, containerHost); } else { LOG.warn("Did not find a pending Processor ID for Container ID: on host: {}. " + "Ignoring invalid/redundant notification.", containerId, containerHost); } }

Target:
public void onStreamProcessorLaunchSuccess(SamzaResource resource) { String containerId = resource.getContainerId(); String containerHost = resource.getHost(); String processorId = getPendingProcessorId(containerId); LOG.info("Successfully started Processor ID: on Container ID: on host: {}", processorId, containerId, containerHost); if (processorId != null) { LOG.info("Moving Processor ID: on Container ID: on host: from pending to running state.", processorId, containerId, containerHost); state.pendingProcessors.remove(processorId); state.runningProcessors.put(processorId, resource); if (state.neededProcessors.decrementAndGet() == 0) { state.jobHealthy.set(true); } containerManager.handleContainerLaunchSuccess(processorId, containerHost); } else { LOG.warn("Did not find a pending Processor ID for Container ID: on host: {}. " + "Ignoring invalid/redundant notification.", containerId, containerHost); } }
Source:
public void correctHeaders() throws Exception { refreshIndex(); Entity testEntity=new Entity().chainPut("name", "Solitaire1"); WebResource.Builder builder = app().collection("games") .getResource(true, getAdminToken()) .type(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON); ClientResponse apiResponse=builder.post(ClientResponse.class, testEntity); assertEquals(200, apiResponse.getStatus()); MultivaluedMap<String, String> headers = apiResponse.getHeaders(); List<String> contentType = headers.get("Content-Type"); assertEquals(1, contentType.size()); assertEquals(MediaType.APPLICATION_JSON, contentType.get(0)); }

Target:
public void correctHeaders() throws Exception { Entity testEntity=new Entity().chainPut("name", "Solitaire1"); WebResource.Builder builder = app().collection("games") .getResource(true, getAdminToken()) .type(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON); ClientResponse apiResponse=builder.post(ClientResponse.class, testEntity); assertEquals(200, apiResponse.getStatus()); MultivaluedMap<String, String> headers = apiResponse.getHeaders(); List<String> contentType = headers.get("Content-Type"); assertEquals(1, contentType.size()); assertEquals(MediaType.APPLICATION_JSON, contentType.get(0)); }
Source:
public static VView loadView(IFile file, Collection<String> registeredEcores) throws IOException { final String path = file.getLocation().toString(); VView view = loadView(path); if (!viewIsResolved(view)) { view = tryResolve(view, path, registeredEcores); if (viewIsResolved(view)) { return null; } } return view; }

Target:
public static VView loadView(IFile file, Collection<String> registeredEcores) throws IOException { final String path = file.getLocation().toString(); final VView view = loadView(path); if (view != null && !viewIsResolved(view)) { return tryResolve(view, path, registeredEcores); } return view; }
Source:
private static boolean submitDeviceReportRecord(DeviceReportRecord slr, String submissionUrl, DataSubmissionListener listener, int index, boolean forceLogs) { File f = new File(slr.getFilePath()); if (f.length() == 0) { return true; } listener.startSubmission(index, f.length()); CommcareRequestGenerator generator; User user; try { user = CommCareApplication.instance().getSession().getLoggedInUser(); } catch (SessionUnavailableException e) { return false; } generator = new CommcareRequestGenerator(user); List<MultipartBody.Part> parts = new ArrayList<>(); parts.add(FormUploadUtil.createEncryptedFilePart( "xml_submission_file", f, "text/xml", new SecretKeySpec(slr.getKey(), "AES"))); HashMap<String, String> queryParams = new HashMap<>(); queryParams.put(QUERY_PARAM_FORCE_LOGS, String.valueOf(forceLogs)); Response<ResponseBody> response = null; try { response = generator.postMultipart(submissionUrl, parts, queryParams); } catch (IOException e) { e.printStackTrace(); return false; } catch (IllegalStateException e) { e.printStackTrace(); return false; } finally { if (response != null && response.body() != null) { response.body().close(); } } int responseCode = response.code(); return (responseCode >= 200 && responseCode < 300); }

Target:
private static boolean submitDeviceReportRecord(DeviceReportRecord slr, String submissionUrl, DataSubmissionListener listener, int index, boolean forceLogs) { File f = new File(slr.getFilePath()); if (f.length() == 0) { return true; } listener.startSubmission(index, f.length()); CommcareRequestGenerator generator; User user; try { user = CommCareApplication.instance().getSession().getLoggedInUser(); } catch (SessionUnavailableException e) { return false; } generator = new CommcareRequestGenerator(user); List<MultipartBody.Part> parts = new ArrayList<>(); parts.add(FormUploadUtil.createEncryptedFilePart( "xml_submission_file", f, "text/xml", new SecretKeySpec(slr.getKey(), "AES"))); Response<ResponseBody> response = null; try { response = generator.postLogs(submissionUrl, parts, forceLogs); } catch (IOException e) { e.printStackTrace(); return false; } catch (IllegalStateException e) { e.printStackTrace(); return false; } finally { if (response != null && response.body() != null) { response.body().close(); } } int responseCode = response.code(); return (responseCode >= 200 && responseCode < 300); }
Source:
protected CommandBase(T parameters, CommandContext cmdContext) { if (cmdContext == null) { cmdContext = new CommandContext(new EngineContext().withSessionId(parameters.getSessionId())) .withExecutionContext(new ExecutionContext()); } else if (cmdContext.getEngineContext().getSessionId() == null) { cmdContext.getEngineContext().withSessionId(parameters.getSessionId()); } this.context = cmdContext; _parameters = parameters; DbUser user = SessionDataContainer.getInstance().getUser(cmdContext.getEngineContext().getSessionId(), true); if (user != null) { setCurrentUser(user); } if (SessionDataContainer.getInstance().getPrincipalName(cmdContext.getEngineContext().getSessionId()) == null) { setUserName("engine@internal"); } else { setUserName(SessionDataContainer.getInstance().getUserName(cmdContext.getEngineContext().getSessionId())); } ExecutionContext executionContext = cmdContext.getExecutionContext(); if (executionContext.getJob() != null) { setJobId(executionContext.getJob().getId()); } else if (executionContext.getStep() != null) { setJobId(executionContext.getStep().getJobId()); } Guid commandIdFromParameters = parameters.getCommandId(); if (commandIdFromParameters == null) { commandIdFromParameters = Guid.newGuid(); getParameters().setCommandId(commandIdFromParameters); } commandId = commandIdFromParameters; taskHandlers = initTaskHandlers(); setCorrelationId(parameters.getCorrelationId()); }

Target:
protected CommandBase(T parameters, CommandContext cmdContext) { if (cmdContext == null) { cmdContext = new CommandContext(new EngineContext().withSessionId(parameters.getSessionId())) .withExecutionContext(new ExecutionContext()); } else if (cmdContext.getEngineContext().getSessionId() == null) { cmdContext.getEngineContext().withSessionId(parameters.getSessionId()); } this.context = cmdContext; _parameters = parameters; DbUser user = SessionDataContainer.getInstance().getUser(cmdContext.getEngineContext().getSessionId(), true); if (user != null) { setCurrentUser(user); } if (SessionDataContainer.getInstance().getPrincipalName(cmdContext.getEngineContext().getSessionId()) == null) { setUserName("SYSTEM"); } else { setUserName(SessionDataContainer.getInstance().getUserName(cmdContext.getEngineContext().getSessionId())); } ExecutionContext executionContext = cmdContext.getExecutionContext(); if (executionContext.getJob() != null) { setJobId(executionContext.getJob().getId()); } else if (executionContext.getStep() != null) { setJobId(executionContext.getStep().getJobId()); } Guid commandIdFromParameters = parameters.getCommandId(); if (commandIdFromParameters == null) { commandIdFromParameters = Guid.newGuid(); getParameters().setCommandId(commandIdFromParameters); } commandId = commandIdFromParameters; taskHandlers = initTaskHandlers(); setCorrelationId(parameters.getCorrelationId()); }
Source:
public static String getTokenFromProperty(DavProperty property) { if (property == null) return null; return property.getValue().toString(); }

Target:
public static String getTokenFromProperty(DavProperty property) { return (property == null) ? null : property.getValue().toString(); }
Source:
private void validateParameters() throws ProjectCreationFailedException { if (createProjectArgs.getProjectName() == null || createProjectArgs.getProjectName().isEmpty()) { throw new ProjectCreationFailedException( "fatal: project name is required"); } if (createProjectArgs.getProjectName().endsWith(Constants.DOT_GIT_EXT)) { createProjectArgs.setProjectName(createProjectArgs.getProjectName() .substring( 0, createProjectArgs.getProjectName().length() - Constants.DOT_GIT_EXT.length())); } if (!currentUser.getCapabilities().canCreateProject()) { throw new ProjectCreationFailedException(String.format( "%s does not have \"Create Project\" capability.", currentUser.getUserName())); } if (createProjectArgs.ownerIds == null && createProjectArgs.ownerIds.isEmpty()) { createProjectArgs.ownerIds = new ArrayList<AccountGroup.UUID>(projectOwnerGroups); } while (createProjectArgs.branch.startsWith("/")) { createProjectArgs.branch = createProjectArgs.branch.substring(1); } if (!createProjectArgs.branch.startsWith(Constants.R_HEADS)) { createProjectArgs.branch = Constants.R_HEADS + createProjectArgs.branch; } if (!Repository.isValidRefName(createProjectArgs.branch)) { throw new ProjectCreationFailedException(String.format( "Branch \"%s\" is not a valid name.", createProjectArgs.branch)); } }

Target:
private void validateParameters() throws ProjectCreationFailedException { if (createProjectArgs.getProjectName() == null || createProjectArgs.getProjectName().isEmpty()) { throw new ProjectCreationFailedException("Project name is required"); } if (createProjectArgs.getProjectName().endsWith(Constants.DOT_GIT_EXT)) { createProjectArgs.setProjectName(createProjectArgs.getProjectName() .substring( 0, createProjectArgs.getProjectName().length() - Constants.DOT_GIT_EXT.length())); } if (!currentUser.getCapabilities().canCreateProject()) { throw new ProjectCreationFailedException(String.format( "%s does not have \"Create Project\" capability.", currentUser.getUserName())); } if (createProjectArgs.ownerIds == null || createProjectArgs.ownerIds.isEmpty()) { createProjectArgs.ownerIds = new ArrayList<AccountGroup.UUID>(projectOwnerGroups); } while (createProjectArgs.branch.startsWith("/")) { createProjectArgs.branch = createProjectArgs.branch.substring(1); } if (!createProjectArgs.branch.startsWith(Constants.R_HEADS)) { createProjectArgs.branch = Constants.R_HEADS + createProjectArgs.branch; } if (!Repository.isValidRefName(createProjectArgs.branch)) { throw new ProjectCreationFailedException(String.format( "Branch \"%s\" is not a valid name.", createProjectArgs.branch)); } }
Source:
private SiteInit createSiteInit() { final ConsoleUI ui = ConsoleUI.getInstance(batchMode); final File sitePath = getSitePath(); final List<Module> m = new ArrayList<Module>(); m.add(new InitModule()); m.add(new AbstractModule() { @Override protected void configure() { bind(ConsoleUI.class).toInstance(ui); bind(File.class).annotatedWith(SitePath.class).toInstance(sitePath); bind(ReloadSiteLibrary.class).toInstance(new ReloadSiteLibrary() { @Override public void reload() { Init.super.loadSiteLib(); } }); } }); try { return Guice.createInjector(PRODUCTION, m).getInstance(SiteInit.class); } catch (CreationException ce) { final Message first = ce.getErrorMessages().iterator().next(); Throwable why = first.getCause(); if (why instanceof Die) { throw (Die) why; } final StringBuilder buf = new StringBuilder(ce.getLocalizedMessage()); while (why != null) { buf.append(why.getMessage()); why = why.getCause(); if (why != null) { buf.append("\n caused by "); } } throw die(buf.toString(), new RuntimeException("InitInjector failed", ce)); } }

Target:
private SiteInit createSiteInit() { final ConsoleUI ui = ConsoleUI.getInstance(batchMode); final File sitePath = getSitePath(); final List<Module> m = new ArrayList<Module>(); m.add(new InitModule()); m.add(new AbstractModule() { @Override protected void configure() { bind(ConsoleUI.class).toInstance(ui); bind(File.class).annotatedWith(SitePath.class).toInstance(sitePath); bind(ReloadSiteLibrary.class).toInstance(new ReloadSiteLibrary() { @Override public void reload() { Init.super.loadSiteLib(); } }); } }); try { return Guice.createInjector(PRODUCTION, m).getInstance(SiteInit.class); } catch (CreationException ce) { final Message first = ce.getErrorMessages().iterator().next(); Throwable why = first.getCause(); if (why instanceof Die) { throw (Die) why; } final StringBuilder buf = new StringBuilder(ce.getMessage()); while (why != null) { buf.append("\n"); buf.append(why.getMessage()); why = why.getCause(); if (why != null) { buf.append("\n caused by "); } } throw die(buf.toString(), new RuntimeException("InitInjector failed", ce)); } }