auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public double getTotalCurrent(){ double totalCurrent = 0; for(int i = 0; i <= 15; i++){ totalCurrent += Math.abs(getCurrent(i)); } return totalCurrent; }

Target:
public double getTotalCurrent(){ return pdp.getTotalCurrent(); }
Source:
public State makeState(Map<String, Object> conf, IMetricsContext metrics, int partitionIndex, int numPartitions) { LOG.info("makeState(partitonIndex={}, numpartitions={}", partitionIndex, numPartitions); TridentKafkaState<K, V> state = new TridentKafkaState<K, V>() .withKafkaTopicSelector(this.topicSelector) .withTridentTupleToKafkaMapper(this.mapper); state.prepare(producerProperties); return state; }

Target:
public State makeState(Map<String, Object> conf, IMetricsContext metrics, int partitionIndex, int numPartitions) { LOG.info("makeState(partitonIndex={}, numpartitions={}", partitionIndex, numPartitions); TridentKafkaState<K, V> state = new TridentKafkaState<>(); state.withKafkaTopicSelector(this.topicSelector) .withTridentTupleToKafkaMapper(this.mapper); state.prepare(producerProperties); return state; }
Source:
private SendRequest createSendRequest(PaymentIntent paymentIntent, boolean signInputs, boolean forceEnsureMinRequiredFee) { final Wallet wallet = viewModel.wallet; boolean llmqInstantSendActive = wallet.getContext().sporkManager.isSporkActive(SporkManager.SPORK_20_INSTANTSEND_LLMQ_BASED); paymentIntent.setInstantX(false); final SendRequest sendRequest = paymentIntent.toSendRequest(); sendRequest.coinSelector = llmqInstantSendActive ? ZeroConfCoinSelector.get() : InstantXCoinSelector.get(); sendRequest.useInstantSend = false; sendRequest.feePerKb = ECONOMIC_FEE; sendRequest.ensureMinRequiredFee = forceEnsureMinRequiredFee; sendRequest.signInputs = signInputs; Coin walletBalance = wallet.getBalance(BalanceType.ESTIMATED); sendRequest.emptyWallet = viewModel.paymentIntent.mayEditAmount() && walletBalance.equals(paymentIntent.getAmount()); return sendRequest; }

Target:
private SendRequest createSendRequest(PaymentIntent paymentIntent, boolean signInputs, boolean forceEnsureMinRequiredFee) { paymentIntent.setInstantX(false); final SendRequest sendRequest = paymentIntent.toSendRequest(); sendRequest.coinSelector = ZeroConfCoinSelector.get(); sendRequest.useInstantSend = false; sendRequest.feePerKb = ECONOMIC_FEE; sendRequest.ensureMinRequiredFee = forceEnsureMinRequiredFee; sendRequest.signInputs = signInputs; Coin walletBalance = viewModel.wallet.getBalance(BalanceType.ESTIMATED); sendRequest.emptyWallet = viewModel.paymentIntent.mayEditAmount() && walletBalance.equals(paymentIntent.getAmount()); return sendRequest; }
Source:
private void updateRowsOnHosts(MemoryTableHandle table, Collection<Slice> fragments) { Map<HostAddress, Long> rowsOnHosts = hostsPerTable.computeIfAbsent( table.getTableId(), key -> new ConcurrentHashMap<>()); for (Slice fragment : fragments) { WriteInfo writeInfo = WriteInfo.fromSlice(fragment); rowsOnHosts.compute( writeInfo.getHostAndPort(), (hostAddress, rows) -> (rows == null ? 0 : rows) + writeInfo.getRows()); } }

Target:
private void updateRowsOnHosts(MemoryTableHandle table, Collection<Slice> fragments) { checkState( tableDataFragments.containsKey(table.getTableId()), "Uninitialized table [%s.%s]", table.getSchemaName(), table.getTableName()); Map<HostAddress, MemoryDataFragment> dataFragments = tableDataFragments.get(table.getTableId()); for (Slice fragment : fragments) { MemoryDataFragment memoryDataFragment = MemoryDataFragment.fromSlice(fragment); dataFragments.merge(memoryDataFragment.getHostAddress(), memoryDataFragment, MemoryDataFragment::merge); } }
Source:
protected static void setSliderFunction(final Slider slider, final SType type) { slider.setOnMouseReleased(event -> { if (type == SType.VOLUME_SOUNDTRACK) { State.setSoundtrackVolume(soundtrackVolumeSlider. getValue() / VOLUME_CONVERTER); MainMenuScene.getAudioPlayer(). setVolume(State.getSoundtrackVolume()); } else { State.setSoundEffectVolume(soundEffectVolumeSlider. getValue() / VOLUME_CONVERTER); AbstractMenuScene.getButtonSoundEffectPlayer(). setVolume(State.getSoundEffectVolume()); AbstractInfoPopup.getButtonSoundEffectPlayer(). setVolume(State.getSoundEffectVolume()); } }); }

Target:
protected static void setSliderFunction(final Slider slider, final SType type) { slider.setOnMouseReleased(event -> { if (type == SType.VOLUME_SOUNDTRACK) { State.setSoundtrackVolume(soundtrackVolumeSlider. getValue() / VOLUME_CONVERTER); MainMenuScene.getAudioPlayer(). setVolume(State.getSoundtrackVolume()); } else { State.setSoundEffectVolume(soundEffectVolumeSlider. getValue() / VOLUME_CONVERTER); } playButtonSound(); }); }
Source:
public void copyAllRightToLeft(Iterable<? extends Diff> differences, Monitor monitor) { long start = 0; if (LOGGER.isDebugEnabled()) { start = System.currentTimeMillis(); LOGGER.debug("copyAllRightToLeft(differences, monitor) - Start"); } ComputeDiffsToMerge computer = new ComputeDiffsToMerge(true, registry, null); for (Diff diff : Iterables.filter(differences, filter)) { if (!AbstractMerger.isInTerminalState(diff)) { Set<Diff> diffsToMerge = computer.getAllDiffsToMergeFor(diff); for (Diff toMerge : diffsToMerge) { if (!AbstractMerger.isInTerminalState(toMerge)) { final IMerger merger = registry.getHighestRankingMerger(toMerge); if (LOGGER.isDebugEnabled()) { LOGGER.debug("copyAllLeftToRight - Selected merger: " + merger.getClass().getSimpleName()); } merger.copyRightToLeft(toMerge, monitor); } } } } if (LOGGER.isDebugEnabled()) { long duration = System.currentTimeMillis() - start; LOGGER.debug("copyAllRightToLeft(differences, monitor) - Stop - Time spent: " + duration + "ms"); } }

Target:
public void copyAllRightToLeft(Iterable<? extends Diff> differences, Monitor monitor) { long start = 0; if (LOGGER.isDebugEnabled()) { start = System.currentTimeMillis(); LOGGER.debug("copyAllRightToLeft(differences, monitor) - Start"); } ComputeDiffsToMerge computer = new ComputeDiffsToMerge(true, registry); for (Diff diff : Iterables.filter(differences, filter)) { if (!AbstractMerger.isInTerminalState(diff)) { Set<Diff> diffsToMerge = computer.getAllDiffsToMerge(diff); for (Diff toMerge : diffsToMerge) { if (!AbstractMerger.isInTerminalState(toMerge)) { final IMerger merger = registry.getHighestRankingMerger(toMerge); if (LOGGER.isDebugEnabled()) { LOGGER.debug("copyAllLeftToRight - Selected merger: " + merger.getClass().getSimpleName()); } merger.copyRightToLeft(toMerge, monitor); } } } } if (LOGGER.isDebugEnabled()) { long duration = System.currentTimeMillis() - start; LOGGER.debug("copyAllRightToLeft(differences, monitor) - Stop - Time spent: " + duration + "ms"); } }
Source:
public void testFinishButtonDisabledInLauncherApplicationProjectWizard() { log.step("Import project start"); NewLauncherProjectWizard wizard = new NewLauncherProjectWizard(); NewLauncherProjectWizardPage wizardPage = new NewLauncherProjectWizardPage(wizard); wizard.openWizardFromShellMenu(); assertFalse(wizardPage.isFinishButtonEnabled()); wizardPage.setProjectName("project_2_customized_settings"); String defaultLocationBackup = ""; wizardPage.toggleUseDefaultLocationCheckBox(false); defaultLocationBackup = wizardPage.getProjectLocation(); wizardPage.setCustomProjectLocation(""); assertFalse(wizardPage.isFinishButtonEnabled()); wizardPage.setCustomProjectLocation(defaultLocationBackup); wizardPage.toggleUseDefaultLocationCheckBox(true); String defaultArtifactIdBackup = ""; defaultArtifactIdBackup = wizardPage.getArtifactId(); wizardPage.setArtifactId(""); assertFalse(wizardPage.isFinishButtonEnabled()); wizardPage.setArtifactId(defaultArtifactIdBackup); String defaultGroupIdBackup = ""; defaultGroupIdBackup = wizardPage.getGroupId(); wizardPage.setGroupId(""); assertFalse(wizardPage.isFinishButtonEnabled()); wizardPage.setGroupId(defaultGroupIdBackup); String defaultVersionBackup = ""; defaultVersionBackup = wizardPage.getVersion(); wizardPage.setVersion(""); assertFalse(wizardPage.isFinishButtonEnabled()); wizardPage.setVersion(defaultVersionBackup); new DefaultShell("New Launcher project").close(); log.step("Window closed"); new WaitWhile(new JobIsRunning(), TimePeriod.VERY_LONG); checkForErrors(); }

Target:
public void testFinishButtonDisabledInLauncherApplicationProjectWizard() { log.step("Import project start"); NewLauncherProjectWizard wizard = new NewLauncherProjectWizard(); NewLauncherProjectWizardPage wizardPage = new NewLauncherProjectWizardPage(wizard); wizard.openWizardFromShellMenu(); assertFalse(wizard.isFinishEnabled()); wizardPage.setProjectName("project_2_customized_settings"); String defaultLocationBackup = ""; wizardPage.toggleUseDefaultLocationCheckBox(false); defaultLocationBackup = wizardPage.getProjectLocation(); wizardPage.setCustomProjectLocation(""); assertFalse(wizard.isFinishEnabled()); wizardPage.setCustomProjectLocation(defaultLocationBackup); wizardPage.toggleUseDefaultLocationCheckBox(true); String defaultArtifactIdBackup = ""; defaultArtifactIdBackup = wizardPage.getArtifactId(); wizardPage.setArtifactId(""); assertFalse(wizard.isFinishEnabled()); wizardPage.setArtifactId(defaultArtifactIdBackup); String defaultGroupIdBackup = ""; defaultGroupIdBackup = wizardPage.getGroupId(); wizardPage.setGroupId(""); assertFalse(wizard.isFinishEnabled()); wizardPage.setGroupId(defaultGroupIdBackup); String defaultVersionBackup = ""; defaultVersionBackup = wizardPage.getVersion(); wizardPage.setVersion(""); assertFalse(wizard.isFinishEnabled()); wizardPage.setVersion(defaultVersionBackup); new DefaultShell("New Launcher project").close(); log.step("Window closed"); new WaitWhile(new JobIsRunning(), TimePeriod.VERY_LONG); checkForErrors(); }
Source:
public final void testExecuteLogOutput() throws Exception { final CheckstyleAntTaskLogStub antTask = new CheckstyleAntTaskLogStub(); final URL url = new File(getPath(CONFIG_FILE)).toURI().toURL(); antTask.setProject(new Project()); antTask.setConfigURL(url); antTask.setFile(new File(getPath(FLAWLESS_INPUT))); mockStatic(System.class); when(System.currentTimeMillis()).thenReturn(1L); antTask.execute(); final List<MessageLevelPair> expectedList = Arrays.asList( new MessageLevelPair("checkstyle version ", 3), new MessageLevelPair("compiled on ", 3), new MessageLevelPair("Adding standalone file for audit", 3), new MessageLevelPair("To locate the files took 0 ms.", 3), new MessageLevelPair("Running Checkstyle ", 2), new MessageLevelPair("Using configuration ", 3), new MessageLevelPair("Starting audit", 4), new MessageLevelPair("Audit done.", 4), new MessageLevelPair("To process the files took 0 ms.", 3), new MessageLevelPair("Total execution took 0 ms.", 3) ); final List<MessageLevelPair> loggedMessages = antTask.getLoggedMessages(); assertEquals(expectedList.size(), loggedMessages.size()); for (int i = 0; i < expectedList.size(); i++) { final MessageLevelPair expected = expectedList.get(i); final MessageLevelPair actual = loggedMessages.get(i); assertTrue(actual.getMsg().startsWith(expected.getMsg())); assertEquals(expected.getLevel(), actual.getLevel()); } }

Target:
public final void testExecuteLogOutput() throws Exception { final CheckstyleAntTaskLogStub antTask = new CheckstyleAntTaskLogStub(); final URL url = new File(getPath(CONFIG_FILE)).toURI().toURL(); antTask.setProject(new Project()); antTask.setConfigURL(url); antTask.setFile(new File(getPath(FLAWLESS_INPUT))); mockStatic(System.class); when(System.currentTimeMillis()).thenReturn(1L); antTask.execute(); final List<MessageLevelPair> expectedList = Arrays.asList( new MessageLevelPair("checkstyle version ", Project.MSG_VERBOSE), new MessageLevelPair("compiled on ", Project.MSG_VERBOSE), new MessageLevelPair("Adding standalone file for audit", Project.MSG_VERBOSE), new MessageLevelPair("To locate the files took 0 ms.", Project.MSG_VERBOSE), new MessageLevelPair("Running Checkstyle ", Project.MSG_INFO), new MessageLevelPair("Using configuration ", Project.MSG_VERBOSE), new MessageLevelPair("Starting audit", Project.MSG_DEBUG), new MessageLevelPair("Audit done.", Project.MSG_DEBUG), new MessageLevelPair("To process the files took 0 ms.", Project.MSG_VERBOSE), new MessageLevelPair("Total execution took 0 ms.", Project.MSG_VERBOSE) ); final List<MessageLevelPair> loggedMessages = antTask.getLoggedMessages(); assertEquals(expectedList.size(), loggedMessages.size()); for (int i = 0; i < expectedList.size(); i++) { final MessageLevelPair expected = expectedList.get(i); final MessageLevelPair actual = loggedMessages.get(i); assertTrue(actual.getMsg().startsWith(expected.getMsg())); assertEquals(expected.getLevel(), actual.getLevel()); } }
Source:
public WikipediaBenchmark(WorkloadConfiguration workConf) { super("wikipedia", workConf, true); this.commentLength = new FlatHistogram<Integer>(this.rng(), RevisionHistograms.COMMENT_LENGTH); this.minorEdit = new FlatHistogram<Integer>(this.rng(), RevisionHistograms.MINOR_EDIT); this.revisionDeltas = (FlatHistogram<Integer>[])new FlatHistogram[RevisionHistograms.REVISION_DELTA_SIZES.length]; for (int i = 0; i < this.revisionDeltas.length; i++) { this.revisionDeltas[i] = new FlatHistogram<Integer>(this.rng(), RevisionHistograms.REVISION_DELTAS[i]); } }

Target:
public WikipediaBenchmark(WorkloadConfiguration workConf) { super("wikipedia", workConf, true); this.commentLength = new FlatHistogram<Integer>(this.rng(), RevisionHistograms.COMMENT_LENGTH); this.minorEdit = new FlatHistogram<Integer>(this.rng(), RevisionHistograms.MINOR_EDIT); this.revisionDeltas = new FlatHistogram[RevisionHistograms.REVISION_DELTA_SIZES.length]; for (int i = 0; i < this.revisionDeltas.length; i++) { this.revisionDeltas[i] = new FlatHistogram<Integer>(this.rng(), RevisionHistograms.REVISION_DELTAS[i]); } }
Source:
private Map<String, Collection<UpstreamInfo>> fetchServiceToUpstreamInfoMap(Collection<String> services) throws Exception { Map<String, Collection<String>> serviceToUpstreams = zkFetcher.fetchChildrenInParallel(services); Map<String, UpstreamInfo> upstreamToInfo = zkFetcher.fetchDataInParallel(upstreamPaths(serviceToUpstreams), new UpstreamInfoDeserializer()); Map<String, Collection<UpstreamInfo>> serviceToUpstreamInfo = new HashMap<>(services.size()); for (Entry<String, Collection<String>> entry : serviceToUpstreams.entrySet()) { for (String upstream : entry.getValue()) { if (serviceToUpstreamInfo.containsKey(entry.getKey())) { serviceToUpstreamInfo.get(entry.getKey()).add(upstreamToInfo.get(upstream)); } else { serviceToUpstreamInfo.put(entry.getKey(), Lists.newArrayList(upstreamToInfo.get(upstream))); } } } return serviceToUpstreamInfo; }

Target:
private Map<String, Collection<UpstreamInfo>> fetchServiceToUpstreamInfoMap(Collection<String> services) throws Exception { Map<String, Collection<String>> serviceToUpstreams = zkFetcher.fetchChildrenInParallel(services); Map<String, UpstreamInfo> upstreamToInfo = zkFetcher.fetchDataInParallel(upstreamPaths(serviceToUpstreams), new UpstreamInfoDeserializer()); Map<String, Collection<UpstreamInfo>> serviceToUpstreamInfo = new HashMap<>(services.size()); for (Entry<String, Collection<String>> entry : serviceToUpstreams.entrySet()) { for (String upstream : entry.getValue()) { if (!serviceToUpstreamInfo.containsKey(entry.getKey())) { serviceToUpstreamInfo.put(entry.getKey(), Lists.<UpstreamInfo>newArrayList(upstreamToInfo.get(upstream))); } else { serviceToUpstreamInfo.get(entry.getKey()).add(upstreamToInfo.get(upstream)); } } } return serviceToUpstreamInfo; }
Source:
public void testMetaDataChangedEventListener(DBMSType dbmsType, DBMSConnection dbmsConnection, DBMSProcessor dbmsProcessor) throws Exception { bibDatabase = new BibDatabase(); BibDatabaseContext context = new BibDatabaseContext(bibDatabase); dbmsSynchronizer = new DBMSSynchronizer(context, ',', pattern, new DummyFileUpdateMonitor()); dbmsSynchronizer.openSharedDatabase(dbmsConnection); MetaData testMetaData = new MetaData(); testMetaData.registerListener(dbmsSynchronizer); dbmsSynchronizer.setMetaData(testMetaData); testMetaData.setMode(BibDatabaseMode.BIBTEX); Map<String, String> expectedMap = MetaDataSerializer.getSerializedStringMap(testMetaData, pattern); Map<String, String> actualMap = dbmsProcessor.getSharedMetaData(); assertEquals(expectedMap, actualMap); }

Target:
public void testMetaDataChangedEventListener(DBMSType dbmsType, DBMSConnection dbmsConnection, DBMSProcessor dbmsProcessor) throws Exception { setUp(dbmsConnection); MetaData testMetaData = new MetaData(); testMetaData.registerListener(dbmsSynchronizer); dbmsSynchronizer.setMetaData(testMetaData); testMetaData.setMode(BibDatabaseMode.BIBTEX); Map<String, String> expectedMap = MetaDataSerializer.getSerializedStringMap(testMetaData, pattern); Map<String, String> actualMap = dbmsProcessor.getSharedMetaData(); assertEquals(expectedMap, actualMap); clear(dbmsConnection); }
Source:
public static byte[] getByteBufferHash(final ByteBuffer byteBuffer) { try { final MessageDigest md = MessageDigest.getInstance("SHA-256"); final ByteBuffer bufferCopy = byteBuffer.slice(); final byte[] byteBufferArray = new byte[bufferCopy.remaining()]; bufferCopy.get(byteBufferArray); return md.digest(byteBufferArray); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); throw new RuntimeException("SHA-256 algorithm is not available in the current environment."); } }

Target:
public static byte[] getByteBufferHash(final ByteBuffer byteBuffer) { final ByteBuffer bufferCopy = byteBuffer.slice(); final byte[] byteBufferArray = new byte[bufferCopy.remaining()]; bufferCopy.get(byteBufferArray); return md.digest(byteBufferArray); }
Source:
public void checkCidrFormatAnnotation() { CidrContainer container = new CidrContainer(cidr); Set<ConstraintViolation<CidrContainer>> result = validator.validate(container); if ((!validNetworkAddressExpectedResult) && (validCidrFormatExpectedResult)) { assertEquals("Failed to validate CIDR's error format: " + container.getCidr(), "CIDR_NOT_NETWORK_ADDRESS", result.iterator().next().getMessage()); } else if (!validCidrFormatExpectedResult) { assertEquals("Failed to validate CIDR's error format: " + container.getCidr(), "BAD_CIDR_FORMAT", result.iterator().next().getMessage()); } else { assertEquals("Failed to validate CIDR's format: " + container.getCidr(), validCidrFormatExpectedResult, result.isEmpty()); } }

Target:
public void checkCidrFormatAnnotation() { CidrContainer container = new CidrContainer(cidr); Set<ConstraintViolation<CidrContainer>> result = validator.validate(container); if (!validNetworkAddressExpectedResult && validCidrFormatExpectedResult) { assertEquals("Failed to validate CIDR's error format: " + container.getCidr(), VdcBllMessages.CIDR_NOT_NETWORK_ADDRESS.name(), result.iterator().next().getMessage()); } else if (!validCidrFormatExpectedResult) { assertEquals("Failed to validate CIDR's error format: " + container.getCidr(), VdcBllMessages.BAD_CIDR_FORMAT.name(), result.iterator().next().getMessage()); } else { assertEquals("Failed to validate CIDR's format: " + container.getCidr(), validCidrFormatExpectedResult, result.isEmpty()); } }
Source:
private String convertAndAppendMetadata(StreamsDatum streamsDatum) throws IOException { Object object = streamsDatum.getDocument(); String docAsJson = (object instanceof String) ? object.toString() : OBJECT_MAPPER.writeValueAsString(object); if(streamsDatum.getMetadata() == null || streamsDatum.getMetadata().size() == 0) return docAsJson; else { ObjectNode node = (ObjectNode)OBJECT_MAPPER.readTree(docAsJson); try { node.put("_metadata", OBJECT_MAPPER.readTree(OBJECT_MAPPER.writeValueAsBytes(streamsDatum.getMetadata()))); } catch(Throwable e) { LOGGER.warn("Unable to write metadata"); } return OBJECT_MAPPER.writeValueAsString(node); } }

Target:
private String convertAndAppendMetadata(StreamsDatum streamsDatum) throws IOException { Object object = streamsDatum.getDocument(); String docAsJson = (object instanceof String) ? object.toString() : OBJECT_MAPPER.writeValueAsString(object); if(streamsDatum.getMetadata() == null || streamsDatum.getMetadata().size() == 0) return docAsJson; else { ObjectNode node = (ObjectNode)OBJECT_MAPPER.readTree(docAsJson); node.put("_metadata", OBJECT_MAPPER.readTree(OBJECT_MAPPER.writeValueAsBytes(streamsDatum.getMetadata()))); return OBJECT_MAPPER.writeValueAsString(node); } }
Source:
protected Set<ApplicationResource> findResources(String path) throws IOException { Set<ApplicationResource> resources = new HashSet<>(); LOG.trace("Using ResourceFinder to find matches for {}", path); Pattern pattern = WildcardUtil.compileWildcardPattern(path); Map<String, URL> matches = finder.getResourcesMap(""); for (Map.Entry<String, URL> entry : matches.entrySet()) { if (pattern.matcher(entry.getKey()).matches()) { try { resources.add(new StrutsApplicationResource(entry.getValue())); } catch (MalformedURLException e) { LOG.warn("Cannot access [{}]", entry.getValue(), e); } } } LOG.trace("Found resources for path {}", resources, path); return resources; }

Target:
protected Set<ApplicationResource> findResources(String path) throws IOException { Set<ApplicationResource> resources = new HashSet<>(); LOG.trace("Using ResourceFinder to find matches for {}", path); Pattern pattern = WildcardUtil.compileWildcardPattern(path); Map<String, URL> matches = finder.getResourcesMap(""); for (Map.Entry<String, URL> entry : matches.entrySet()) { if (pattern.matcher(entry.getKey()).matches()) { resources.add(new StrutsApplicationResource(entry.getValue())); } } LOG.trace("Found resources for path {}", resources, path); return resources; }
Source:
public void testCustomLifeCycle() throws Exception { restAPIPublisher.changeAPILifeCycleStatus(apiId, Constants.PUBLISHED); Assert.assertEquals(APILifeCycleState.PUBLISHED.getState(), restAPIPublisher.getLifecycleStatus(apiId). getData(), "lifecycle not changed to published"); restAPIPublisher.changeAPILifeCycleStatus(apiId, PROMOTE); Assert.assertEquals(PROMOTE + "d", restAPIPublisher.getLifecycleStatus(apiId).getData(), "lifecycle not changed to custom"); restAPIPublisher.changeAPILifeCycleStatus(apiId, RE_PUBLISH); Assert.assertEquals(APILifeCycleState.PUBLISHED.getState(), restAPIPublisher.getLifecycleStatus(apiId). getData(), "lifecycle not changed to published"); }

Target:
public void testCustomLifeCycle() throws Exception { restAPIPublisher.changeAPILifeCycleStatus(apiId, APILifeCycleAction.PUBLISH.getAction()); Assert.assertEquals(APILifeCycleState.PUBLISHED.getState(), restAPIPublisher.getLifecycleStatus(apiId). getData(), "lifecycle not changed to published"); restAPIPublisher.changeAPILifeCycleStatus(apiId, APILifeCycleAction.PROMOTE.getAction()); Assert.assertEquals(APILifeCycleState.PROMOTED.getState(), restAPIPublisher.getLifecycleStatus(apiId).getData(), "lifecycle not changed to custom"); restAPIPublisher.changeAPILifeCycleStatus(apiId, APILifeCycleAction.RE_PUBLISH.getAction()); Assert.assertEquals(APILifeCycleState.PUBLISHED.getState(), restAPIPublisher.getLifecycleStatus(apiId). getData(), "lifecycle not changed to published"); }
Source:
public static void onAdvancementEvent(AdvancementEvent event) { if (ENABLED && event.getAdvancement().getDisplay() != null && event.getAdvancement().getDisplay().shouldAnnounceToChat()) { logger.info("{} got the advancement", event.getEntityPlayer().getDisplayNameString(), event.getAdvancement().getDisplayText().getUnformattedText()); } }

Target:
public static void onAdvancementEvent(AdvancementEvent event) { if (event.getAdvancement().getDisplay() != null && event.getAdvancement().getDisplay().shouldAnnounceToChat()) { logger.info("{} got the advancement", event.getEntityPlayer().getDisplayNameString(), event.getAdvancement().getDisplayText().getUnformattedText()); } }
Source:
public void testIV3AnalyticsProviderInDE(String wikiName, String path) { networkTrafficInterceptor.startIntercepting(); String testedPage = urlBuilder.getUrlForPath(wikiName, path); AdsBaseObject adsBaseObject = new AdsBaseObject(driver, testedPage); JavascriptActions jsActions = new JavascriptActions(driver); jsActions.waitForJavaScriptTruthy("typeof(iom) == 'object'"); assertTrackingPixels(adsBaseObject, URL_TRACKING_SCRIPT); }

Target:
public void testIV3AnalyticsProviderInDE(String wikiName, String path) { networkTrafficInterceptor.startIntercepting(); String testedPage = urlBuilder.getUrlForPath(wikiName, path); AdsBaseObject adsBaseObject = new AdsBaseObject(driver, testedPage); JavascriptActions jsActions = new JavascriptActions(driver); jsActions.waitForJavaScriptTruthy("typeof iom === 'object'"); assertTrackingPixels(adsBaseObject, URL_TRACKING_SCRIPT); }
Source:
public CounterChartViewer(Composite parent, String title, String xLabel, String yLabel) { super(parent, title, xLabel, yLabel); Chart chart = getSwtChart(); chart.getTitle().setVisible(true); getSwtChart().getAxisSet().getXAxes()[0].getTitle().setVisible(true); chart.getLegend().setPosition(SWT.RIGHT); chart.getLegend().setVisible(true); Color backgroundColor = new Color(Display.getDefault(), 250, 250, 250); chart.setBackground(backgroundColor); backgroundColor.dispose(); }

Target:
public CounterChartViewer(Composite parent, String title, String xLabel, String yLabel) { super(parent, title, xLabel, yLabel); Chart chart = getSwtChart(); chart.getTitle().setVisible(true); getSwtChart().getAxisSet().getXAxes()[0].getTitle().setVisible(true); chart.getLegend().setPosition(SWT.RIGHT); chart.getLegend().setVisible(true); chart.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW)); }
Source:
public static long copy(final DataHandle<Location> in, final DataHandle<Location> out, final long length, final Task task, final int bufferSize) throws IOException { long inputlength; try { inputlength = in.length(); } catch (final IOException exc) { inputlength = 0; } if (task != null) { if (length > 0) task.setProgressMaximum(length); else if (inputlength > 0) task.setProgressMaximum(inputlength); } final byte[] buffer = new byte[bufferSize]; long totalRead = 0; while (true) { if (task != null && task.isCanceled()) break; final int r; if (length > 0 && totalRead + bufferSize > length) { int remaining = (int) (length - totalRead); r = in.read(buffer, 0, remaining); } else { r = in.read(buffer); } if (r <= 0) break; if (task != null && task.isCanceled()) break; out.write(buffer, 0, r); totalRead += r; if (task != null) task.setProgressValue(task .getProgressValue() + r); } return totalRead; }

Target:
public static long copy(final DataHandle<Location> in, final DataHandle<Location> out, final long length, final Task task, final int bufferSize) throws IOException { final long inputlength; { long i = 0; try { i = in.length(); } catch (final IOException exc) { i = 0; } inputlength = i; } if (task != null) { if (length > 0) task.setProgressMaximum(length); else if (inputlength > 0) task.setProgressMaximum(inputlength); } final byte[] buffer = new byte[bufferSize]; long totalRead = 0; while (true) { if (task != null && task.isCanceled()) break; final int r; if (length > 0 && totalRead + bufferSize > length) { int remaining = (int) (length - totalRead); r = in.read(buffer, 0, remaining); } else { r = in.read(buffer); } if (r <= 0) break; if (task != null && task.isCanceled()) break; out.write(buffer, 0, r); totalRead += r; if (task != null) { task.setProgressValue(task.getProgressValue() + r); } } return totalRead; }
Source:
static ReplicaView replicaInfo(Node node, long logOffset, long timeSinceLastCaughtUpMs) { return new ReplicaView() { @Override public Node endpoint() { return node; } @Override public long logEndOffset() { return logOffset; } @Override public long timeSinceLastCaughtUpMs() { return timeSinceLastCaughtUpMs; } }; }

Target:
static ReplicaView replicaInfo(Node node, long logOffset, long timeSinceLastCaughtUpMs) { return new ReplicaView.DefaultReplicaView(node, logOffset, timeSinceLastCaughtUpMs); }
Source:
public static List<Variable> getRunTimeVariables( Collection<Variable> variables) { List<Variable> runtimeVariables = ReportalUtil.getVariablesByRegex(variables, "(?!(^" + Reportal.REPORTAL_CONFIG_PREFIX + ")).+"); return runtimeVariables; }

Target:
public static List<Variable> getRunTimeVariables( Collection<Variable> variables) { List<Variable> runtimeVariables = ReportalUtil.getVariablesByRegex(variables, Reportal.REPORTAL_CONFIG_PREFIX_NEGATION_REGEX); return runtimeVariables; }
Source:
public void doTestRawQueryNXDomain(Executor executor) throws InterruptedException { final String msg = "RawQuery " + TEST_NX_DOMAIN; for (Network network : getTestableNetworks()) { final NetworkCapabilities nc = (network != null) ? mCM.getNetworkCapabilities(network) : mCM.getNetworkCapabilities(mCM.getActiveNetwork()); assertNotNull("Couldn't determine NetworkCapabilities for " + network, nc); if (!nc.hasTransport(TRANSPORT_WIFI)) continue; final VerifyCancelCallback callback = new VerifyCancelCallback(msg); mDns.rawQuery(network, TEST_NX_DOMAIN, CLASS_IN, TYPE_AAAA, FLAG_NO_CACHE_LOOKUP, executor, null, callback); assertTrue(msg + " but no answer after " + TIMEOUT_MS + "ms.", callback.waitForAnswer()); callback.assertNXDomain(); } }

Target:
public void doTestRawQueryNXDomain(Executor executor) throws InterruptedException { final String msg = "RawQuery " + TEST_NX_DOMAIN; for (Network network : getTestableNetworks()) { final NetworkCapabilities nc = (network != null) ? mCM.getNetworkCapabilities(network) : mCM.getNetworkCapabilities(mCM.getActiveNetwork()); assertNotNull("Couldn't determine NetworkCapabilities for " + network, nc); if (nc.hasTransport(TRANSPORT_CELLULAR)) continue; final VerifyCancelCallback callback = new VerifyCancelCallback(msg); mDns.rawQuery(network, TEST_NX_DOMAIN, CLASS_IN, TYPE_AAAA, FLAG_NO_CACHE_LOOKUP, executor, null, callback); assertTrue(msg + " but no answer after " + TIMEOUT_MS + "ms.", callback.waitForAnswer()); callback.assertNXDomain(); } }
Source:
public Set<SearchFilterItem> setActiveFilterParams(Model model, HttpServletRequest request) { Map<String, String[]> parameterMap = request.getParameterMap(); model.addAttribute("parameterMap", parameterMap); Map<String, String[]> filtersOnlyMap = parameterMap.entrySet().stream() .filter(entry -> Stream.of(SingletonSearchFilterType.values()).map (SingletonSearchFilterType::getParameterName).collect(Collectors.toList()).contains(entry .getKey()) || ("filterJournals").equals(entry.getKey())) .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue())); Set<SearchFilterItem> activeFilterItems = new LinkedHashSet<>(); filtersOnlyMap.forEach((filterName, filterValues) -> buildActiveFilterItems(activeFilterItems, parameterMap, filterName, filterValues)); return activeFilterItems; }

Target:
public Set<SearchFilterItem> setActiveFilterParams(Model model, HttpServletRequest request) { Map<String, String[]> parameterMap = request.getParameterMap(); model.addAttribute("parameterMap", parameterMap); Map<String, String[]> filtersOnlyMap = parameterMap.entrySet().stream() .filter(entry -> FILTER_PARAMETER_NAMES.contains(entry.getKey()) || ("filterJournals").equals(entry.getKey())) .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue())); Set<SearchFilterItem> activeFilterItems = new LinkedHashSet<>(); filtersOnlyMap.forEach((filterName, filterValues) -> buildActiveFilterItems(activeFilterItems, parameterMap, filterName, filterValues)); return activeFilterItems; }
Source:
public void testSaveAndRetrieveCustomToken() { List<String> allowedClasses = new ArrayList<String>(); allowedClasses.add("java.util."); allowedClasses.add("org.springframework.security."); allowedClasses.add("org.company.oauth2.CustomOAuth2AccessToken"); allowedClasses.add("org.company.oauth2.CustomOAuth2Authentication"); WhitelistedSerializationStrategy newStrategy = new WhitelistedSerializationStrategy(allowedClasses); SerializationStrategy oldStrategy = SerializationUtils.getSerializationStrategy(); try { SerializationUtils.setSerializationStrategy(newStrategy); OAuth2AccessToken accessToken = new DefaultOAuth2AccessToken("FOO"); Authentication authentication = new UsernamePasswordAuthenticationToken("marissa", "koala"); AuthorizationCodeResourceDetails resource = new AuthorizationCodeResourceDetails(); resource.setClientId("client"); resource.setScope(Arrays.asList("foo", "bar")); tokenStore.saveAccessToken(resource, authentication, accessToken); OAuth2AccessToken result = tokenStore.getAccessToken(resource, authentication); } finally { SerializationUtils.setSerializationStrategy(oldStrategy); } }

Target:
public void testSaveAndRetrieveCustomToken() { OAuth2AccessToken accessToken = new CustomOAuth2AccessToken("FOO"); Authentication authentication = new UsernamePasswordAuthenticationToken("marissa", "koala"); AuthorizationCodeResourceDetails resource = new AuthorizationCodeResourceDetails(); resource.setClientId("client"); resource.setScope(Arrays.asList("foo", "bar")); tokenStore.saveAccessToken(resource, authentication, accessToken); OAuth2AccessToken result = tokenStore.getAccessToken(resource, authentication); assertNotNull(result); assertEquals(accessToken, result); }
Source:
public void applyXSettingsToQuery(SolrQuery query, XSettings xSettings) { XField xField = xSettings.getField(); String fieldName = xFieldNameMapper.mapXField(xField); XRange xRange = xSettings.getRange(); XRangeConverter xRangeConverter = xRangeConverterManager.getXRangeConverter(xRange.getClass()); String startParam = xRangeConverter.convertStart(xRange); String endParam = xRangeConverter.convertEnd(xRange); String gapParam = xRangeConverter.convertGap(xRange); rangeFacetToQueryApplier.applyRangeFacet(query, fieldName, startParam, endParam, gapParam); }

Target:
public void applyXSettingsToQuery(SolrQuery query, XSettings xSettings) { Preconditions.checkNotNull(query); Preconditions.checkNotNull(xSettings); XField xField = xSettings.getField(); String fieldName = xFieldNameMapper.mapXField(xField); XRange xRange = xSettings.getRange(); XRangeConverter xRangeConverter = xRangeConverterManager.getXRangeConverter(xRange.getClass()); String startParam = xRangeConverter.convertStart(xRange); String endParam = xRangeConverter.convertEnd(xRange); String gapParam = xRangeConverter.convertGap(xRange); rangeFacetToQueryApplier.applyRangeFacet(query, fieldName, startParam, endParam, gapParam); }
Source:
public synchronized LinkedHashMap<ComponentName, RegistrationInfoImpl> getResolvedMap() { return new LinkedHashMap<ComponentName,RegistrationInfoImpl>(resolved); }

Target:
public synchronized Map<ComponentName, RegistrationInfoImpl> getResolvedMap() { return Collections.unmodifiableMap(resolved); }
Source:
private static void handleHundredKmWithPreviousType( String mgrsPart, MgrsPartType previousType, StringBuilder mgrsBuilder) { LOGGER.trace("Found a 100KM which occurs after a {}", mgrsPart, previousType); switch (previousType) { case ZONE: LOGGER.trace("Saving this part"); mgrsBuilder.append(mgrsPart); break; case HUNDRED_KM: case NUMERIC: case NONE: LOGGER.trace("Ignoring this part, since 100KM is only valid after a ZONE"); break; } }

Target:
private static void handleHundredKmWithPreviousType( String mgrsPart, MgrsPartType previousType, StringBuilder mgrsBuilder) { LOGGER.trace("Found a 100KM which occurs after a {}", mgrsPart, previousType); switch (previousType) { case ZONE: LOGGER.trace("Saving this part [{}]", mgrsPart); mgrsBuilder.append(mgrsPart); break; case HUNDRED_KM: case NUMERIC: case NONE: LOGGER.trace("Ignoring this part [{}], since 100KM is only valid after a ZONE", mgrsPart); } }
Source:
public static String encodeWebSocketKey(String key) throws NoSuchAlgorithmException, NullPointerException, IOException { String toEncode = key + WEB_SOCKET_GUID; return Base64.getEncoder().encodeToString(encoder.getHashSHA1(toEncode.getBytes())); }

Target:
public static String encodeWebSocketKey(String key) { String toEncode = key + WEB_SOCKET_GUID; try { return Base64.getEncoder().encodeToString(encoder.getHashSHA1(toEncode.getBytes())); } catch (NoSuchAlgorithmException e) { return null; } }
Source:
public void checkConstructorWithThrowable() { Throwable testThrowable = new RuntimeException("yo"); StorIOException storIOException = new StorIOException(testThrowable); assertThat(storIOException.getCause()).isEqualTo(testThrowable); }

Target:
public void checkConstructorWithThrowable() { Throwable testThrowable = new RuntimeException("yo"); StorIOException storIOException = new StorIOException(testThrowable); assertThat(storIOException.getCause()).isSameAs(testThrowable); }
Source:
public void validate(FailureCollector collector) { if (!containsMacro("sheetValue") && sheet.equalsIgnoreCase(SHEET_NO) && !StringUtils.isNumeric(sheetValue)) { collector.addFailure( String.format("Invalid sheet number: '%s'.", sheetValue), "The value should be greater than or equal to zero.") .withConfigProperty(SHEET_VALUE); } if (!(Strings.isNullOrEmpty(tableExpiryPeriod)) && (Strings.isNullOrEmpty(memoryTableName))) { collector.addFailure( "Value for Table Expiry Period is valid only when file tracking table is specified.", null) .withConfigProperty(TABLE_EXPIRY_PERIOD); } if (!Strings.isNullOrEmpty(rowsLimit) && !StringUtils.isNumeric(rowsLimit)) { collector.addFailure(String.format("Invalid row limit: '%s'.", rowsLimit), "Numeric value expected.") .withConfigProperty(ROWS_LIMIT); } collector.getOrThrowException(); }

Target:
public void validate(FailureCollector collector) { if (!containsMacro("sheetValue") && sheet.equalsIgnoreCase(SHEET_NO) && !StringUtils.isNumeric(sheetValue)) { collector.addFailure( String.format("Invalid sheet number: '%s'.", sheetValue), "The value should be greater than or equal to zero.") .withConfigProperty(SHEET_VALUE); } if (!(Strings.isNullOrEmpty(tableExpiryPeriod)) && (Strings.isNullOrEmpty(memoryTableName))) { collector.addFailure( "Value for Table Expiry Period is valid only when file tracking table is specified.", null) .withConfigProperty(TABLE_EXPIRY_PERIOD); } if (!Strings.isNullOrEmpty(rowsLimit) && !StringUtils.isNumeric(rowsLimit)) { collector.addFailure(String.format("Invalid row limit: '%s'.", rowsLimit), "Numeric value expected.") .withConfigProperty(ROWS_LIMIT); } if (Strings.isNullOrEmpty(columnList) && Strings.isNullOrEmpty(outputSchema)) { collector.addFailure( "'Field Name Schema Type Mapping' and 'Columns To Be Extracted' cannot both be empty.", null) .withConfigProperty(OUTPUT_SCHEMA).withConfigProperty(COLUMN_LIST); } }
Source:
public static StreamingPlanSection extractStreamingSections(SubPlan subPlan) { List<SubPlan> childrenRoots = new ArrayList<>(); StreamingSubPlan streamingSection = extractStreamingSection(subPlan, childrenRoots); return new StreamingPlanSection( streamingSection, childrenRoots.stream() .map(SqlQueryScheduler::extractStreamingSections) .collect(toImmutableList())); }

Target:
public static StreamingPlanSection extractStreamingSections(SubPlan subPlan) { ImmutableList.Builder<SubPlan> materializedExchangeChildren = ImmutableList.builder(); StreamingSubPlan streamingSection = extractStreamingSection(subPlan, materializedExchangeChildren); return new StreamingPlanSection( streamingSection, materializedExchangeChildren.build().stream() .map(SqlQueryScheduler::extractStreamingSections) .collect(toImmutableList())); }
Source:
public void testDisableHtmlEscaping() { String testStr = "==="; String json = DHE_GSON.toJson(testStr); assertEquals(testStr.length() + 2, json.length()); assertEquals(testStr, json.substring(1, 1 + testStr.length())); }

Target:
public void testDisableHtmlEscaping() { assertEquals("\"\\u003d\\u003d\\u003d\"", GSON.toJson("===")); assertEquals("\"===\"", DHE_GSON.toJson("===")); }
Source:
protected void executeVdsBrokerCommand() { UpdateGlusterGeoRepKeysVDSParameters parameters = getParameters(); status = getBroker().glusterGeoRepKeysUpdate(parameters.getRemoteUserName(), new ArrayList<>(parameters.getGeoRepPubKeys())); proceedProxyReturnValue(); }

Target:
protected void executeVdsBrokerCommand() { UpdateGlusterGeoRepKeysVDSParameters parameters = getParameters(); status = getBroker().glusterGeoRepKeysUpdate(parameters.getGeoRepPubKeys(), parameters.getRemoteUserName()); proceedProxyReturnValue(); }
Source:
public void actionDialogOK() { fCollectAction.setCollectString(fCollectString.getText()); fCollectAction.setCharPtrAsStrings(fTreatCharPtrAsStrings.getSelection()); Integer limit = getCharPtrAsStringLimit(fTreatCharPtrAsStringsLimit.getText()); fCollectAction.setCharPtrAsStringsLimit(limit); }

Target:
public void actionDialogOK() { fCollectAction.setCollectString(fCollectString.getText()); fCollectAction.setCharPtrAsStrings(fTreatCharPtrAsStrings.getSelection()); try { Integer limit = getCharPtrAsStringLimit(fTreatCharPtrAsStringsLimit.getText()); fCollectAction.setCharPtrAsStringsLimit(limit); } catch (IllegalCollectStringLimitException e) { } }
Source:
public OutputWriter createOutputWriter() { if (file.exists() && overwriteFile==false){ throw new IllegalStateException("The file already exists. Please configure the job to overwrite the existing file."); } List<String> headers = new ArrayList<String>(); for (int i = 0; i < columns.length; i++) { String columnName = columns[i].getName(); headers.add(columnName); if (columnToBeSortedOn != null) { if (columnName.equals(columnToBeSortedOn.getName())) { indexOfColumnToBeSortedOn = i; } } } if (columnToBeSortedOn != null) { if (indexOfColumnToBeSortedOn == -1) { this.isColumnToBeSortedOnPresentInInput = false; indexOfColumnToBeSortedOn = columns.length; headers.add(columnToBeSortedOn.getName()); InputColumn<?>[] newColumns = new InputColumn<?>[columns.length + 1]; for (int i = 0; i < columns.length; i++) { newColumns[i] = columns[i]; } newColumns[columns.length] = columnToBeSortedOn; columns = newColumns; } } if (_targetFile == null) { try { initTempFile(); } catch (Exception e) { throw new RuntimeException(e); } } return CsvOutputWriterFactory.getWriter(_targetFile.getPath(), headers.toArray(new String[0]), separatorChar, quoteChar, escapeChar, includeHeader, columns); }

Target:
public OutputWriter createOutputWriter() { List<String> headers = new ArrayList<String>(); for (int i = 0; i < columns.length; i++) { String columnName = columns[i].getName(); headers.add(columnName); if (columnToBeSortedOn != null) { if (columnName.equals(columnToBeSortedOn.getName())) { indexOfColumnToBeSortedOn = i; } } } if (columnToBeSortedOn != null) { if (indexOfColumnToBeSortedOn == -1) { this.isColumnToBeSortedOnPresentInInput = false; indexOfColumnToBeSortedOn = columns.length; headers.add(columnToBeSortedOn.getName()); InputColumn<?>[] newColumns = new InputColumn<?>[columns.length + 1]; for (int i = 0; i < columns.length; i++) { newColumns[i] = columns[i]; } newColumns[columns.length] = columnToBeSortedOn; columns = newColumns; } } if (_targetFile == null) { try { initTempFile(); } catch (Exception e) { throw new RuntimeException(e); } } return CsvOutputWriterFactory.getWriter(_targetFile.getPath(), headers.toArray(new String[0]), separatorChar, quoteChar, escapeChar, includeHeader, columns); }
Source:
public void filePage003_diffPage() { HistoryPagePageObject historyPage = new HistoryPagePageObject(driver); historyPage.openHistoryPage(Global.DOMAIN + URLsContent.wikiDir + URLsContent.fileNS + URLsContent.fileName); historyPage.goToDiffPageFromHistoryPage(); DiffPagePageObject diffPage = new DiffPagePageObject(driver); diffPage.verifyDiffTablePresent(); }

Target:
public void filePage003_diffPage() { HistoryPagePageObject historyPage = new HistoryPagePageObject(driver); historyPage.openFileHistoryPage(URLsContent.filePage + URLsContent.fileName001); historyPage.goToDiffPageFromHistoryPage(); DiffPagePageObject diffPage = new DiffPagePageObject(driver); diffPage.verifyDiffTablePresent(); }
Source:
public String[] getDnsServers() { WinDef.ULONGByReference bufferSize = new WinDef.ULONGByReference(); int ret = IPHlpAPI.INSTANCE.GetNetworkParams(null, bufferSize); if (ret != IPHlpAPI.ERROR_BUFFER_OVERFLOW) { LOG.error("Failed to get network parameters buffer size. Error code: {}", ret); return new String[0]; } FIXED_INFO buffer = new FIXED_INFO(new Memory(bufferSize.getValue().longValue())); ret = IPHlpAPI.INSTANCE.GetNetworkParams(buffer, bufferSize); if (ret != 0) { LOG.error("Failed to get network parameters. Error code: {}", ret); return new String[0]; } List<String> list = new ArrayList<>(); IPHlpAPI.IP_ADDR_STRING dns = buffer.DnsServerList; while(dns != null) { String addr = new String(dns.IpAddress.String); int nullPos = addr.indexOf(0); if(nullPos != -1) { addr = addr.substring(0, nullPos); } list.add(addr); dns = dns.Next; } return list.toArray(new String[0]); }

Target:
public String[] getDnsServers() { WinDef.ULONGByReference bufferSize = new WinDef.ULONGByReference(); int ret = IPHlpAPI.INSTANCE.GetNetworkParams(null, bufferSize); if (ret != IPHlpAPI.ERROR_BUFFER_OVERFLOW) { LOG.error("Failed to get network parameters buffer size. Error code: {}", ret); return new String[0]; } FIXED_INFO buffer = new FIXED_INFO(new Memory(bufferSize.getValue().longValue())); ret = IPHlpAPI.INSTANCE.GetNetworkParams(buffer, bufferSize); if (ret != 0) { LOG.error("Failed to get network parameters. Error code: {}", ret); return new String[0]; } List<String> list = new ArrayList<>(); IPHlpAPI.IP_ADDR_STRING dns = buffer.DnsServerList; while (dns != null) { String addr = new String(dns.IpAddress.String); int nullPos = addr.indexOf(0); if (nullPos != -1) { addr = addr.substring(0, nullPos); } list.add(addr); dns = dns.Next; } return list.toArray(new String[list.size()]); }
Source:
protected StorageDomain addParents(StorageDomain model) { Guid storageDomainId = Guid.createGuidFromString(model.getId()); List<Guid> dataCenterIds = StorageDomainHelper.getAttachedDataCenters(this, storageDomainId); if (!CollectionUtils.isEmpty(dataCenterIds)) { DataCenters dataCenters = new DataCenters(); for (Guid dataCenterId : dataCenterIds) { DataCenter dataCenter = new DataCenter(); dataCenter.setId(dataCenterId.toString()); dataCenters.getDataCenters().add(dataCenter); } model.setDataCenters(dataCenters); } return model; }

Target:
protected StorageDomain addParents(StorageDomain model) { StorageDomainHelper.addAttachedDataCenterReferences(this, model); return model; }
Source:
public void selectAllFiles() { logger.info("selectAllFiles called"); List<FileMetadata> allFiles = new ArrayList<>(); for (FileMetadata fm : workingVersion.getFileMetadatas()) { allFiles.add(fm); } selectedFiles = allFiles; }

Target:
public void selectAllFiles() { logger.fine("selectAllFiles called"); selectedFiles = workingVersion.getFileMetadatas(); }
Source:
public void tearDown() throws IOException, InterruptedException { try (AutoMlClient client = AutoMlClient.create()) { while (!client.getOperationsClient().getOperation(operationFullName).getDone()) { Thread.sleep(1000); } client.getOperationsClient().deleteOperation(operationFullName); } System.setOut(null); }

Target:
public void tearDown() throws IOException, InterruptedException { try (AutoMlClient client = AutoMlClient.create()) { client.getOperationsClient().cancelOperation(operationFullName); client.getOperationsClient().awaitTermination(5, TimeUnit.SECONDS); } System.setOut(null); }
Source:
default Subscription onChange(Consumer<T> consumer) { PropertyListener<T> listener = new PropertyListener<T>() { @Override public void onChange(T value) { consumer.accept(value); } }; addListener(listener); return () -> removeListener(listener); }

Target:
default Subscription onChange(Consumer<T> consumer) { return subscribe(consumer); }
Source:
public static long getCFInstanceIndex() { long cfInstanceIndex = -1L; try { cfInstanceIndex = Long.parseLong(System.getenv("CF_INSTANCE_INDEX")); } catch(Exception e) { return cfInstanceIndex; } return cfInstanceIndex; }

Target:
public static long getCFInstanceIndex() { long cfInstanceIndex = -1L; try { cfInstanceIndex = Long.parseLong(System.getenv("CF_INSTANCE_INDEX")); } catch(SecurityException securityException) { LOG.info("GetCFInstanceIndex: Could not access environment variable CF_INSTANCE_INDEX, permission denied. Value of -1 is returned."); } catch(NumberFormatException numberFormatException) { LOG.info("GetCFInstanceIndex: Could not parse value of environment variable CF_INSTANCE_INDEX as Long. Value of -1 is returned."); } catch(NullPointerException nullPointerException) { LOG.info("GetCFInstanceIndex: Could not find value for environment variable CF_INSTANCE_INDEX. This could indicate a local deployment is running. Value of -1 is returned."); } return cfInstanceIndex; }