auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected SimpleResult compareMetricValues(final Object value1, final Object value2, final String metricName) { boolean equal = true; String description = ""; if (value1 == null || value2 == null) { if (value1 != null || value2 != null) { equal = false; description = "One of the values is null"; } } else { if (value1 instanceof Number) { double numValue1 = ((Number) value1).doubleValue(); double numValue2 = ((Number) value2).doubleValue(); double relativeChange = (numValue1 == 0 && numValue2 == 0) ? 0 : (numValue1 == 0) ? Double.MAX_VALUE : (numValue1 - numValue2) / numValue2; if (relativeChange != 0) { if (MetricToAllowableRelativeChange.containsKey(metricName)) { double allowableRelativeChange = MetricToAllowableRelativeChange.get(metricName); if (abs(relativeChange) >= allowableRelativeChange) { equal = false; description = "Changed by " + RELATIVE_CHANGE_DECIMAL_FORMAT.format(relativeChange) + " which is outside of the allowable tolerance of " + RELATIVE_CHANGE_DECIMAL_FORMAT.format(allowableRelativeChange); } else { equal = true; description = "Changed by " + RELATIVE_CHANGE_DECIMAL_FORMAT.format(relativeChange) + " which is within the allowable tolerance of " + RELATIVE_CHANGE_DECIMAL_FORMAT.format(allowableRelativeChange); } } else { equal = false; description = "Changed by " + RELATIVE_CHANGE_DECIMAL_FORMAT.format(relativeChange); } } } else { if (!value1.equals(value2)) { equal = false; description = "Different Values"; } } } return new SimpleResult(equal, description); <START> } <END></code><technical_language>This static suggestion private static void validateMetricNames(final MetricsFile<?, ?> metrics, final File metricsFile, final Collection<String> metricNames) {</technical_language>

Target:
protected SimpleResult compareMetricValues(final Object value1, final Object value2, final String metricName) { boolean equal = true; String description = ""; if (value1 == null || value2 == null) { if (value1 != null || value2 != null) { equal = false; description = "One of the values is null"; } } else { if (value1 instanceof Number) { double numValue1 = ((Number) value1).doubleValue(); double numValue2 = ((Number) value2).doubleValue(); double relativeChange = (numValue1 == 0 && numValue2 == 0) ? 0 : (numValue1 == 0) ? Double.MAX_VALUE : (numValue1 - numValue2) / numValue2; if (relativeChange != 0) { if (MetricToAllowableRelativeChange.containsKey(metricName)) { double allowableRelativeChange = MetricToAllowableRelativeChange.get(metricName); if (Math.abs(relativeChange) >= allowableRelativeChange) { equal = false; description = "Changed by " + relativeChange + " which is outside of the allowable tolerance of " + allowableRelativeChange; } else { equal = true; description = "Changed by " + relativeChange + " which is within the allowable tolerance of " + allowableRelativeChange; } } else { equal = false; description = "Changed by " + relativeChange; } } } else { if (!value1.equals(value2)) { equal = false; description = ""; } } } return new SimpleResult(equal, description); }
Source:
<code>public void run() { taskExecutor.execute(new Runnable() { public void run() { int count = 0; while (initialized && (maxMessagesPerPoll <= 0 || count < maxMessagesPerPoll)) { try { if (!pollingTask.call()) { break; } count++; } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { <START> throw new MessageHandlingException(new ErrorMessage(e), null); <END> } } } } }); }</code><technical_language>I agree a odd create a new ErrorMessage act failedMessage, I change this point. In case, I this invoked doPoll() throw checked exceptions. change throw new MessageHandlingException(new ErrorMessage(e), this.getComponentName() + " failed invoke pollingTask", e);</technical_language>

Target:
public void run() { taskExecutor.execute(new Runnable() { public void run() { int count = 0; while (initialized && (maxMessagesPerPoll <= 0 || count < maxMessagesPerPoll)) { try { if (!pollingTask.call()) { break; } count++; } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { throw new MessageHandlingException(new ErrorMessage(e), AbstractPollingEndpoint.this.getComponentName() + " failed to invoke pollingTask.", e); } } } } }); }
Source:
<code>private void insertValues(final String key, final String val, final String updateTs) throws InterruptedException { final CountDownLatch committed = new CountDownLatch(1); Assert.assertNull( dbi.withHandle( new HandleCallback<Void>() { @Override public Void withHandle(Handle handle) throws Exception { try { final String query; if (tsColumn == null) { handle.createStatement( String.format("DELETE FROM %s WHERE %s='%s'", tableName, keyName, key) ).execute(); handle.commit(); query = String.format( "INSERT INTO %s (%s, %s) VALUES ('%s', '%s')", tableName, keyName, valName, key, val ); } else { query = String.format( "INSERT INTO %s (%s, %s, %s) VALUES ('%s', '%s', '%s')", tableName, tsColumn, keyName, valName, updateTs, key, val ); } if (1 != handle.createStatement(query).execute()) { throw new ISE("Did not return the correct number of rows"); } handle.commit(); return null; } finally { committed.countDown(); } } } ) ); committed.await(10, TimeUnit.SECONDS); <START> Thread.sleep(2); <END> }</code><technical_language>reason for sleep here, wait before</technical_language>

Target:
private void insertValues(final String key, final String val, final String updateTs) throws InterruptedException { final String query; if (tsColumn == null) { handle.createStatement( String.format("DELETE FROM %s WHERE %s='%s'", tableName, keyName, key) ).setQueryTimeout(1).execute(); query = String.format( "INSERT INTO %s (%s, %s) VALUES ('%s', '%s')", tableName, keyName, valName, key, val ); } else { query = String.format( "INSERT INTO %s (%s, %s, %s) VALUES ('%s', '%s', '%s')", tableName, tsColumn, keyName, valName, updateTs, key, val ); } Assert.assertEquals(1, handle.createStatement(query).setQueryTimeout(1).execute()); handle.commit(); Thread.sleep(2); }
Source:
<code>public void getExistedObjectExecuteAsBlocking() { TestSubscriber<Changes> changesTestSubscriber = new TestSubscriber<Changes>(); storIOContentResolver .observeChangesOfUri(TestItem.CONTENT_URI) .take(1) .subscribe(changesTestSubscriber); <START> TestItem testItemToInsert = TestItem.create(null, "value"); <END> contentResolver.insert(TestItem.CONTENT_URI, testItemToInsert.toContentValues()); TestItem testItem = storIOContentResolver .get() .object(TestItem.class) .withQuery(Query.builder() .uri(TestItem.CONTENT_URI) .where(TestItem.COLUMN_VALUE + "=?") .whereArgs("value") .build()) .prepare() .executeAsBlocking(); assertThat(testItem).isNotNull(); assertThat(testItemToInsert.equalsWithoutId(testItem)).isTrue(); changesTestSubscriber.awaitTerminalEvent(60, SECONDS); changesTestSubscriber.assertNoErrors(); changesTestSubscriber.assertValue(Changes.newInstance(TestItem.CONTENT_URI)); }</code><technical_language>please insert more items select particular</technical_language>

Target:
public void getExistedObjectExecuteAsBlocking() { TestSubscriber<Changes> changesTestSubscriber = new TestSubscriber<Changes>(); storIOContentResolver .observeChangesOfUri(TestItem.CONTENT_URI) .take(1) .subscribe(changesTestSubscriber); TestItem testItemToInsert = TestItem.create(null, "value"); contentResolver.insert(TestItem.CONTENT_URI, testItemToInsert.toContentValues()); contentResolver.insert(TestItem.CONTENT_URI, TestItem.create(null, "value1").toContentValues()); contentResolver.insert(TestItem.CONTENT_URI, TestItem.create(null, "value2").toContentValues()); TestItem testItem = storIOContentResolver .get() .object(TestItem.class) .withQuery(Query.builder() .uri(TestItem.CONTENT_URI) .where(TestItem.COLUMN_VALUE + "=?") .whereArgs("value") .build()) .prepare() .executeAsBlocking(); assertThat(testItem).isNotNull(); assertThat(testItemToInsert.equalsWithoutId(testItem)).isTrue(); changesTestSubscriber.awaitTerminalEvent(60, SECONDS); changesTestSubscriber.assertNoErrors(); changesTestSubscriber.assertValue(Changes.newInstance(TestItem.CONTENT_URI)); }
Source:
<code>static int lineNumber(CommentNode node, int offset) { int lineNumber = node.getStartLinePosition(); <START> String contentBeforeTodo = node.getCode().substring(0, offset); <END> for (int i = 0; i < contentBeforeTodo.length(); i++) { if (contentBeforeTodo.charAt(i) == '\n') { lineNumber++; } } return lineNumber; }</code><technical_language>Name of variable is incorrect in this case now</technical_language>

Target:
static int lineNumber(CommentNode node, int offset) { String content = node.getCode(); if (offset < 0 || offset > content.length()) { throw new IllegalArgumentException("Out of range offset: " + offset + " for comment content (size: " + content.length() + ")"); } int lineFeedCountBeforeOffset = (int) content.substring(0, offset).chars().filter(c -> c == '\n').count(); return node.getStartLinePosition() + lineFeedCountBeforeOffset; }
Source:
<code>private void checkImageTarget() { if (getVm().getOrigin() == OriginType.KVM && getActionState() == CommandActionState.EXECUTE) { for (DiskImage image : getVm().getImages()) { <START> StorageDomain domain = storageDomainDao.get(getStorageDomainId()); <END> if (domain.getStorageType().isBlockDomain()) { image.setActualSizeInBytes(image.getSize()); } } } }</code><technical_language>worth caching storage domain for case VMs multiple disks, no</technical_language>

Target:
private void checkImageTarget() { if (getVm().getOrigin() == OriginType.KVM && getActionState() == CommandActionState.EXECUTE) { StorageDomain domain = storageDomainDao.get(getStorageDomainId()); for (DiskImage image : getVm().getImages()) { if (domain.getStorageType().isBlockDomain()) { image.setActualSizeInBytes(image.getSize()); } } } }
Source:
<code>public void openFileWithApplication(String filePath, String application) throws IOException { String[] openWith; if ((application != null) && !application.isEmpty()) { openWith = application.split(" "); } else { openWith = new String[] {"xdg-open"}; } String[] cmdArray = new String[openWith.length + 1]; System.arraycopy(openWith, 0, cmdArray, 0, openWith.length); cmdArray[cmdArray.length - 1] = filePath; <START> Process process = Runtime.getRuntime().exec(cmdArray); <END> StreamGobbler streamGobblerInput = new StreamGobbler(process.getInputStream(), LOGGER::debug); StreamGobbler streamGobblerError = new StreamGobbler(process.getErrorStream(), LOGGER::debug); JabRefExecutorService.INSTANCE.execute(streamGobblerInput); JabRefExecutorService.INSTANCE.execute(streamGobblerError); }</code><technical_language>I guess process starting done in a thread..</technical_language>

Target:
public void openFileWithApplication(String filePath, String application) throws IOException { String[] openWith; if ((application != null) && !application.isEmpty()) { openWith = application.split(" "); } else { openWith = new String[] {"xdg-open"}; } String[] cmdArray = new String[openWith.length + 1]; System.arraycopy(openWith, 0, cmdArray, 0, openWith.length); cmdArray[cmdArray.length - 1] = filePath; ProcessBuilder processBuilder = new ProcessBuilder(cmdArray); Process process = processBuilder.start(); StreamGobbler streamGobblerInput = new StreamGobbler(process.getInputStream(), LOGGER::debug); StreamGobbler streamGobblerError = new StreamGobbler(process.getErrorStream(), LOGGER::debug); JabRefExecutorService.INSTANCE.execute(streamGobblerInput); JabRefExecutorService.INSTANCE.execute(streamGobblerError); }
Source:
<code>private void checkIsPrimaryKey(String fieldName) { RealmObjectSchema objectSchema = proxyState.getRealm$realm().getSchema().getSchemaForClass(getType()); if (objectSchema.hasPrimaryKey() && objectSchema.getPrimaryKey().equals(fieldName)) { <START> throw new RealmException(String.format("Primary key field '%s' cannot be changed after object created." <END> , fieldName)); } }</code><technical_language>Throw IllegalArgumentException instead</technical_language>

Target:
private void checkIsPrimaryKey(String fieldName) { RealmObjectSchema objectSchema = proxyState.getRealm$realm().getSchema().getSchemaForClass(getType()); if (objectSchema.hasPrimaryKey() && objectSchema.getPrimaryKey().equals(fieldName)) { throw new IllegalArgumentException(String.format( "Primary key field '%s' cannot be changed after object was created.", fieldName)); } }
Source:
<code>public final <E> void assertSatisfy(AssertionInfo info, Iterable<? extends E> actual, Consumer<? super E>... consumers) { assertNotNull(info, actual); requireNonNull(consumers, "The Consumer<? super E>... expressing the assertions consumers must not be null"); requireNonNull(consumers[0], "The Consumer<? super E>... expressing the assertions consumers must not be null"); <START> List<E>[] stasfiedElementsLists = new ArrayList[consumers.length]; for (int i = 0; i < consumers.length; i++) { Consumer<? super E> consumer = consumers[i]; stasfiedElementsLists[i] = stream(actual).filter(element -> { try { consumer.accept(element); } catch (AssertionError ex) { return false; } return true; }).collect(toList()); } if (!isSatisfied(stasfiedElementsLists, 0)) throw failures.failure(info, shouldSatisfy(actual)); } <END></code><technical_language>Typo in variable name "stasfiedElementsList". suggestion List<E>[] satisfiedElementsLists = new ArrayList[consumers.length]; for (int i = 0; i < consumers.length; i++) { Consumer<? super E> consumer = consumers[i]; satisfiedElementsLists[i] = stream(actual).filter(element -> { try { consumer.accept(element); } catch (AssertionError ex) { return false; } return true; }).collect(toList()); } if (!isSatisfied(satisfiedElementsLists, 0)) throw failures.failure(info, shouldSatisfy(actual)); }</technical_language>

Target:
public final <E> void assertSatisfy(AssertionInfo info, Iterable<? extends E> actual, Consumer<? super E>... consumers) { assertNotNull(info, actual); requireNonNull(consumers, "The Consumer<? super E>... expressing the assertions consumers must not be null"); for (Consumer<? super E> consumer : consumers) requireNonNull(consumer, "The element in consumers must not be null"); List<E>[] satisfiedElementsLists = stream(consumers) .map(listFilteredBySatisfiedElements(actual)) .<List<E>> toArray(List[]::new); if (!isSatisfied(satisfiedElementsLists, 0)) throw failures.failure(info, shouldSatisfy(actual)); }
Source:
<code>public boolean isEnabled() { <START> return Boolean.parseBoolean( userProperties.getProperty( NEXUS_STAGING_MAVEN_PLUGIN_REMOVAL_PROPERTY, <END> Boolean.TRUE.toString() ) ); }</code><technical_language>This is causing a nullptr in InitialGroovyManipulatorTest. I store a enabled Boolean initialise correctly set store userProperties object</technical_language>

Target:
public boolean isEnabled() { return enabled; }
Source:
<code>public void createPackage(Path originFolderPath, Path destinationPath) throws ArchiverException, IOException { checkArgument(originFolderPath != null, "The origin path must not be null"); <START> checkArgument(originFolderPath.toFile().exists(), "The origin path must exists"); <END> Path metaInfPath = originFolderPath.resolve(META_INF.value()); this.withDomain(originFolderPath.resolve(DOMAIN.value()).toFile()) .withApplications(originFolderPath.resolve(APPLICATIONS.value()).toFile()) .withMaven(metaInfPath.resolve(MAVEN.value()).toFile()); this.createArchive(destinationPath); }</code><technical_language>exists -> exist</technical_language>

Target:
public void createPackage(Path originFolderPath, Path destinationPath) throws ArchiverException, IOException { checkArgument(originFolderPath != null, "The origin path must not be null"); checkArgument(originFolderPath.toFile().exists(), "The origin path must exist"); Path metaInfPath = originFolderPath.resolve(META_INF.value()); this.withDomain(originFolderPath.resolve(DOMAIN.value()).toFile()) .withApplications(originFolderPath.resolve(APPLICATIONS.value()).toFile()) .withMaven(metaInfPath.resolve(MAVEN.value()).toFile()); this.createArchive(destinationPath); }
Source:
<code>public void subscribeStateChanges(final org.I0Itec.zkclient.IZkStateListener listener) { <START> subscribeStateChanges(new IZkStateListener() { <END> @Override public void handleStateChanged(KeeperState state) throws Exception { listener.handleStateChanged(state); } @Override public void handleNewSession() throws Exception { listener.handleNewSession(); } @Override public void handleSessionEstablishmentError(Throwable error) throws Exception { listener.handleSessionEstablishmentError(error); } }); }</code><technical_language>duplicated code. a single wrapper implement class for IOItech interface</technical_language>

Target:
public void subscribeStateChanges(final org.I0Itec.zkclient.IZkStateListener listener) { subscribeStateChanges(new IZkStateListenerI0ItecImpl(listener)); }
Source:
<code>public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { String[] beanNames = beanFactory.getBeanNamesForType(Provider.class); for (String beanName : beanNames) { BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); <START> beanDefinition.setScope(BeanDefinition.SCOPE_PROTOTYPE); <END> } }</code><technical_language>Is necessary set prototype scope for Provider ? I do kill some logic if some bean of Provider.class singleton scope (in custom code for example)</technical_language>

Target:
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { String[] beanNames = beanFactory.getBeanNamesForType(Provider.class); for (String beanName : beanNames) { BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); if ("".equals(beanDefinition.getScope())){ beanDefinition.setScope(BeanDefinition.SCOPE_PROTOTYPE); } } }
Source:
<code>public boolean isInfoboxDisplayed() { <START> wait.forElementVisible(infobox); <END> return infobox.isDisplayed(); }</code><technical_language>this throw timeout if infobox is visible. wait.forElementPresent() instead, create variable selector</technical_language>

Target:
public boolean isInfoboxDisplayed() { wait.forElementPresent(By.cssSelector(".portable-infobox")); return infobox.isDisplayed(); }
Source:
<code>public double getHetPercent() { <START> return (double) abCalls / (double) numCalls * 100d; <END> }</code><technical_language>do want actual percents? rates else is in Picard</technical_language>

Target:
public double getHetPercent() { return (double) abCalls / (double) numCalls; }
Source:
<code>public void start() { if ( cluster == null ) { try { log.connectingToCassandra( config.getHost(), config.getPort() ); cluster = new Cluster.Builder() .addContactPoint( config.getHost() ) <START> .withPort( config.getPort() ) <END> .build(); Session bootstrapSession = cluster.connect(); bootstrapSession.execute( "CREATE KEYSPACE IF NOT EXISTS " + config.getDatabaseName() + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1 }" ); bootstrapSession.close(); session = cluster.connect( config.getDatabaseName() ); sequenceHandler = new CassandraSequenceHandler(this); } catch (RuntimeException e) { throw log.unableToInitializeCassandra( e ); } } }</code><technical_language>Support for credentials great, too</technical_language>

Target:
public void start() { if ( cluster == null ) { try { log.connectingToCassandra( config.getHost(), config.getPort() ); cluster = new Cluster.Builder() .addContactPoint( config.getHost() ) .withPort( config.getPort() ) .withCredentials( config.getUsername(), config.getPassword() ) .build(); Session bootstrapSession = cluster.connect(); bootstrapSession.execute( "CREATE KEYSPACE IF NOT EXISTS " + config.getDatabaseName() + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1 }" ); bootstrapSession.close(); session = cluster.connect( config.getDatabaseName() ); sequenceHandler = new CassandraSequenceHandler(this); } catch (RuntimeException e) { throw log.unableToInitializeCassandra( e ); } } }
Source:
<code>public void testGetChangeInfo() throws Exception { if (!isVersion26OrLater()) { return; } int reviewId = Integer.parseInt(reviewHarness.shortId); ChangeInfo changeInfo = reviewHarness.client.getChangeInfo(reviewId, new NullProgressMonitor()); if (reviewHarness.client.isVersion29OrLater(new NullProgressMonitor())) { ChangeInfoTest.assertHasCodeReviewLabels29(changeInfo, true); } else { ChangeInfoTest.assertHasCodeReviewLabels29(changeInfo, false); <START> } <END> }</code><technical_language>Ok, I get this. test assert is for 29 for 29? test method name is longer appropriate</technical_language>

Target:
public void testGetChangeInfo() throws Exception { if (!isVersion26OrLater()) { return; } int reviewId = Integer.parseInt(reviewHarness.shortId); ChangeInfo changeInfo = reviewHarness.client.getChangeInfo(reviewId, new NullProgressMonitor()); if (reviewHarness.client.isVersion29OrLater(new NullProgressMonitor())) { ChangeInfoTest.assertHasCodeReviewLabels(changeInfo, true); } else { ChangeInfoTest.assertHasCodeReviewLabels(changeInfo, false); } }
Source:
<code>public Object getAdditionalProposalInfo(IProgressMonitor monitor) { ServerCapabilities capabilities = info.getCapabilites(); if (capabilities != null) { CompletionOptions options = capabilities.getCompletionProvider(); if (options != null && Boolean.TRUE.equals(options.getResolveProvider())) { try { <START> updateCompletionItem(info.getInitializedLanguageClient().get(50, TimeUnit.MILLISECONDS) <END> .getTextDocumentService() .resolveCompletionItem(item) .get(500, TimeUnit.MILLISECONDS)); } catch (InterruptedException | ExecutionException | TimeoutException e) { LanguageServerPlugin.logError(e); } } } StringBuilder res = new StringBuilder(); if (this.item.getDetail() != null) { res.append("<p>" + this.item.getDetail() + "</p>"); } if (res.length() > 0) { res.append("<br/>"); } if (this.item.getDocumentation() != null) { res.append("<p>" + this.item.getDocumentation() + "</p>"); } return res.toString(); }</code><technical_language>a timeout instead of a thenApply() get line 164</technical_language>

Target:
public Object getAdditionalProposalInfo(IProgressMonitor monitor) { ServerCapabilities capabilities = info.getCapabilites(); if (capabilities != null) { CompletionOptions options = capabilities.getCompletionProvider(); if (options != null && Boolean.TRUE.equals(options.getResolveProvider())) { try { updateCompletionItem(info.getInitializedLanguageClient() .thenCompose(ls -> ls.getTextDocumentService().resolveCompletionItem(item)) .get(500, TimeUnit.MILLISECONDS)); } catch (InterruptedException | ExecutionException | TimeoutException e) { LanguageServerPlugin.logError(e); } } } StringBuilder res = new StringBuilder(); if (this.item.getDetail() != null) { res.append("<p>" + this.item.getDetail() + "</p>"); } if (res.length() > 0) { res.append("<br/>"); } if (this.item.getDocumentation() != null) { res.append("<p>" + this.item.getDocumentation() + "</p>"); } return res.toString(); }
Source:
<code>public List<FiringGroup> apply(final BattleState battleState) { <START> final Collection<Unit> canFire = battleState.getBombardingUnits(); <END> final Collection<Unit> enemyUnits = CollectionUtils.getMatches( battleState.filterUnits(ALIVE, OFFENSE.getOpposite()), Matches.unitIsNotInfrastructureAndNotCapturedOnEntering( battleState.getPlayer(OFFENSE), battleState.getBattleSite(), battleState.getGameData())); return FiringGroup.groupBySuicideOnHit(NAVAL_BOMBARD, canFire, enemyUnits); }</code><technical_language>nit, 'bombarindUnits' a more descriptive name here? consider inlining avoid intermediate variable</technical_language>

Target:
public List<FiringGroup> apply(final BattleState battleState) { final Collection<Unit> enemyUnits = CollectionUtils.getMatches( battleState.filterUnits(ALIVE, OFFENSE.getOpposite()), Matches.unitIsNotInfrastructureAndNotCapturedOnEntering( battleState.getPlayer(OFFENSE), battleState.getBattleSite(), battleState.getGameData())); return FiringGroup.groupBySuicideOnHit( NAVAL_BOMBARD, battleState.getBombardingUnits(), enemyUnits); }
Source:
<code>private EntityDescriptor entityDescriptor(InputStream inputStream) { try { Document document = this.parserPool.parse(inputStream); Element element = document.getDocumentElement(); return (EntityDescriptor) this.unmarshaller.unmarshall(element); } catch (Exception ex) { throw new Saml2Exception(ex); } <START> } <END></code><technical_language>Is this a change intended? unintentionally removed support for EntitiesDescriptor</technical_language>

Target:
private EntityDescriptor entityDescriptor(InputStream inputStream) { Document document = document(inputStream); Element element = document.getDocumentElement(); Unmarshaller unmarshaller = this.registry.getUnmarshallerFactory().getUnmarshaller(element); if (unmarshaller == null) { throw new Saml2Exception("Unsupported element of type " + element.getTagName()); } try { XMLObject object = unmarshaller.unmarshall(element); if (object instanceof EntitiesDescriptor) { return ((EntitiesDescriptor) object).getEntityDescriptors().get(0); } if (object instanceof EntityDescriptor) { return (EntityDescriptor) object; } } catch (Exception ex) { throw new Saml2Exception(ex); } throw new Saml2Exception("Unsupported element of type " + element.getTagName()); }
Source:
<code>void setChangeInfo(ChangeInfo info) { GitwebLink gw = Gerrit.getGitwebLink(); if (gw != null) { <START> JsArray<RevisionInfo> revisions = info.revisions().values(); for (int i = 0; i < revisions.length(); i++) { <END> if (revisions.get(i)._number() == patchSetId.get()) { String c = revisions.get(i).name(); SafeHtml.setInnerHTML(filePath, formatPath(path, info.project(), c)); SafeHtml.setInnerHTML(project, new SafeHtmlBuilder() .openAnchor() .setAttribute("href", gw.toFile(info.project(), c, "")) .setAttribute("title", gw.getLinkName()) .append(info.project()) .closeAnchor()); return; } } } project.setInnerText(info.project()); }</code><technical_language>This shorter: for (RevisionInfo info : Natives.asList(info.revisions().values())</technical_language>

Target:
void setChangeInfo(ChangeInfo info) { GitwebLink gw = Gerrit.getGitwebLink(); if (gw != null) { for (RevisionInfo rev : Natives.asList(info.revisions().values())) { if (rev._number() == patchSetId.get()) { String c = rev.name(); SafeHtml.setInnerHTML(filePath, formatPath(path, info.project(), c)); SafeHtml.setInnerHTML(project, new SafeHtmlBuilder() .openAnchor() .setAttribute("href", gw.toFile(info.project(), c, "")) .setAttribute("title", gw.getLinkName()) .append(info.project()) .closeAnchor()); return; } } } project.setInnerText(info.project()); }
Source:
<code>public void reset() throws Exception { HTTP2Client http2Client = new HTTP2Client(); http2Client.start(); SocketAddress serverAddress = new InetSocketAddress("localhost", 8080); CompletableFuture<Session> sessionCF = http2Client.connect(serverAddress, new Session.Listener.Adapter()); Session session = sessionCF.get(); HttpFields requestHeaders = HttpFields.build() <START> .add(HttpHeader.USER_AGENT, "Jetty HTTP2Client {version}"); <END> MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); HeadersFrame headersFrame = new HeadersFrame(request, null, true); CompletableFuture<Stream> streamCF = session.newStream(headersFrame, new Stream.Listener.Adapter() { @Override public void onReset(Stream stream, ResetFrame frame) { } }); Stream stream = streamCF.get(); stream.reset(new ResetFrame(stream.getId(), ErrorCode.CANCEL_STREAM_ERROR.code), Callback.NOOP); }</code><technical_language>Please put() a multiple occurrences header</technical_language>

Target:
public void reset() throws Exception { HTTP2Client http2Client = new HTTP2Client(); http2Client.start(); SocketAddress serverAddress = new InetSocketAddress("localhost", 8080); CompletableFuture<Session> sessionCF = http2Client.connect(serverAddress, new Session.Listener.Adapter()); Session session = sessionCF.get(); HttpFields requestHeaders = HttpFields.build() .put(HttpHeader.USER_AGENT, "Jetty HTTP2Client {version}"); MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); HeadersFrame headersFrame = new HeadersFrame(request, null, true); CompletableFuture<Stream> streamCF = session.newStream(headersFrame, new Stream.Listener.Adapter() { @Override public void onReset(Stream stream, ResetFrame frame) { } }); Stream stream = streamCF.get(); stream.reset(new ResetFrame(stream.getId(), ErrorCode.CANCEL_STREAM_ERROR.code), Callback.NOOP); }
Source:
<code>public SamzaSqlRelMessage convertToRelMessage(KV<Object, Object> samzaMessage) { List<Object> values = new ArrayList<>(); List<String> fieldNames = new ArrayList<>(); Object value = samzaMessage.getValue(); if (value instanceof IndexedRecord) { IndexedRecord record = (IndexedRecord) value; fieldNames.addAll(relationalSchema.getFieldNames()); <START> Schema recordSchema = record.getSchema(); <END> values.addAll(relationalSchema.getFieldList() .stream() .map(x -> getRelField(x.getType(), record.get(recordSchema.getField(x.getName()).pos()))) .collect(Collectors.toList())); } else if (value == null) { fieldNames.addAll(relationalSchema.getFieldNames()); IntStream.range(0, fieldNames.size() - 1).forEach(x -> values.add(null)); } else { String msg = "Avro message converter doesn't support messages of type " + value.getClass(); LOG.error(msg); throw new SamzaException(msg); } return new SamzaSqlRelMessage(samzaMessage.getKey(), fieldNames, values); }</code><technical_language>I noticed converter relationalSchema avroSchema member variables constructor. schema record, instead of validating avroSchema is in constructor? relationalSchema avroSchema final destination schema source schema arbitrary? part is obvious me. want add description relationalSchema avroSchema clarify usage</technical_language>

Target:
public SamzaSqlRelMessage convertToRelMessage(KV<Object, Object> samzaMessage) { List<Object> values = new ArrayList<>(); List<String> fieldNames = new ArrayList<>(); Object value = samzaMessage.getValue(); if (value instanceof IndexedRecord) { IndexedRecord record = (IndexedRecord) value; fieldNames.addAll(relationalSchema.getFieldNames()); values.addAll(relationalSchema.getFieldList() .stream() .map(x -> getRelField(x.getType(), record.get(this.avroSchema.getField(x.getName()).pos()))) .collect(Collectors.toList())); } else if (value == null) { fieldNames.addAll(relationalSchema.getFieldNames()); IntStream.range(0, fieldNames.size() - 1).forEach(x -> values.add(null)); } else { String msg = "Avro message converter doesn't support messages of type " + value.getClass(); LOG.error(msg); throw new SamzaException(msg); } return new SamzaSqlRelMessage(samzaMessage.getKey(), fieldNames, values); }
Source:
<code>JanusGraphServer embeddedDbServer(CassandraEmbeddedConfiguration cassandraConfiguration, JanusGraphConfiguration janusGraphConfiguration) { if (!Files.exists(Paths.get(cassandraConfiguration.getStorageFolder()))) { logger.info(String.format("Extract storage from [%s].", PATH_STRONGBOX_DB)); initStorage(cassandraConfiguration); <START> logger.info(String.format("Sotorage extracted to [%s].", cassandraConfiguration.getStorageFolder())); <END> } return new JanusGraphWithEmbeddedCassandra(cassandraConfiguration, janusGraphConfiguration); }</code><technical_language>Typo: Sotorage --> Storage</technical_language>

Target:
JanusGraphServer embeddedDbServer(CassandraEmbeddedConfiguration cassandraConfiguration, JanusGraphConfiguration janusGraphConfiguration) { if (!Files.exists(Paths.get(cassandraConfiguration.getStorageRoot()))) { logger.info(String.format("Extract storage from [%s].", PATH_STRONGBOX_DB)); initStorage(cassandraConfiguration); logger.info(String.format("Storage extracted to [%s].", cassandraConfiguration.getStorageRoot())); } return new JanusGraphWithEmbeddedCassandra(cassandraConfiguration, janusGraphConfiguration); }
Source:
<code>private static void handleIdManager(final String[] args) { <START> if ("label".equals(args[1])) { <END> CreateLabel.main(Arrays.copyOfRange(args, 2, args.length)); } }</code><technical_language>create, label</technical_language>

Target:
private static void handleIdManager(final String[] args) { if ("create".equals(args[1])) { CreateLabel.main(Arrays.copyOfRange(args, 2, args.length)); } }
Source:
<code>void deactivateTopology(SchedulerStateManagerAdaptor stateManager, final TopologyAPI.Topology topology) throws InterruptedException { List<TopologyAPI.Config.KeyValue> topologyConfig = topology.getTopologyConfig().getKvsList(); long deactivateSleepSeconds = TopologyUtils.getConfigWithDefault( topologyConfig, TOPOLOGY_UPDATE_DEACTIVATE_WAIT_SECS, 0L); logInfo("Deactivating topology %s before handling update request", topology.getName()); assertTrue(TMasterUtils.transitionTopologyState( topology.getName(), TMasterUtils.TMasterCommand.DEACTIVATE, stateManager, TopologyAPI.TopologyState.RUNNING, TopologyAPI.TopologyState.PAUSED), "Failed to deactivate topology %s. Aborting update request", topology.getName()); <START> if (deactivateSleepSeconds > 0) { <END> logInfo("Deactivated topology %s. Sleeping for %d seconds before handling update request", topology.getName(), deactivateSleepSeconds); Thread.sleep(deactivateSleepSeconds * 1000); } else { logInfo("Deactivated topology %s.", topology.getName()); } }</code><technical_language>users expected this configuration? Is based size of topology</technical_language>

Target:
void deactivateTopology(SchedulerStateManagerAdaptor stateManager, final TopologyAPI.Topology topology) throws InterruptedException { List<TopologyAPI.Config.KeyValue> topologyConfig = topology.getTopologyConfig().getKvsList(); long deactivateSleepSeconds = TopologyUtils.getConfigWithDefault( topologyConfig, TOPOLOGY_UPDATE_DEACTIVATE_WAIT_SECS, 0L); logInfo("Deactivating topology %s before handling update request: %d", topology.getName(), deactivateSleepSeconds); NetworkUtils.TunnelConfig tunnelConfig = NetworkUtils.TunnelConfig.build(config, NetworkUtils.HeronSystem.SCHEDULER); assertTrue(TMasterUtils.transitionTopologyState( topology.getName(), TMasterUtils.TMasterCommand.DEACTIVATE, stateManager, TopologyAPI.TopologyState.RUNNING, TopologyAPI.TopologyState.PAUSED, tunnelConfig), "Failed to deactivate topology %s. Aborting update request", topology.getName()); if (deactivateSleepSeconds > 0) { logInfo("Deactivated topology %s. Sleeping for %d seconds before handling update request", topology.getName(), deactivateSleepSeconds); Thread.sleep(deactivateSleepSeconds * 1000); } else { logInfo("Deactivated topology %s.", topology.getName()); } }
Source:
<code>public Token appendCheckpoint(Token snapshotTimestamp) { <START> return appendCheckpointOnSnapshot(snapshotTimestamp); <END> }</code><technical_language>I combine this method appendCheckpointOnSnapshot(), right? same</technical_language>

Target:
public Token appendCheckpoint(Token snapshotTimestamp) { long start = System.currentTimeMillis(); if (!Address.isAddress(snapshotTimestamp.getSequence())) { snapshotTimestamp = forceHole(); } try { rt.getAddressSpaceView().read(snapshotTimestamp.getSequence()); } catch (TrimmedException te) { log.info("appendCheckpointOnSnapshot: stream tail at has been trimmed. Checkpoint on same state" + "as previous checkpoint.", snapshotTimestamp); } rt.getObjectsView().TXBuild() .type(TransactionType.SNAPSHOT) .snapshot(snapshotTimestamp) .build() .begin(); try (Timer.Context context = MetricsUtils.getConditionalContext(appendCheckpointTimer)) { log.info("appendCheckpoint: Started checkpoint for at snapshot {}", streamId, snapshotTimestamp); ICorfuSMR<T> corfuObject = (ICorfuSMR<T>) this.map; Set<Map.Entry> entries = this.map.entrySet(); long vloVersion = snapshotTimestamp.getSequence(); startCheckpoint(snapshotTimestamp, vloVersion); appendObjectState(entries); finishCheckpoint(); long cpDuration = System.currentTimeMillis() - start; log.info("appendCheckpoint: completed checkpoint for {}, entries({}), tableSize({}) bytes, " + "cpSize({}) bytes at snapshot in ms", streamId, entries.size(), MetricsUtils.sizeOf.deepSizeOf(entries), numBytes, snapshotTimestamp, cpDuration); } finally { rt.getObjectsView().TXEnd(); } return snapshotTimestamp; }
Source:
<code>protected void doUpdateStatus( RuntimeIdentity id, Predicate<WorkspaceStatus> predicate, WorkspaceStatus newStatus) throws InfrastructureException { EntityManager entityManager = managerProvider.get(); KubernetesRuntimeState existingState = entityManager.find(KubernetesRuntimeState.class, new RuntimeId(id)); <START> Optional<KubernetesRuntimeState> runtimeStateOpt = get(id); <END> if (!runtimeStateOpt.isPresent()) { throw new InfrastructureException( "Runtime state for workspace with id '" + id.getWorkspaceId() + "' was not found"); } if (!predicate.test(existingState.getStatus())) { throw new IllegalStateException("Runtime status doesn't match to the specified predicate"); } existingState.setStatus(newStatus); entityManager.flush(); }</code><technical_language>of runtimes is odd</technical_language>

Target:
protected void doUpdateStatus( RuntimeIdentity id, Predicate<WorkspaceStatus> predicate, WorkspaceStatus newStatus) throws InfrastructureException { EntityManager entityManager = managerProvider.get(); Optional<KubernetesRuntimeState> existingStateOpt = get(id); if (!existingStateOpt.isPresent()) { throw new InfrastructureException( "Runtime state for workspace with id '" + id.getWorkspaceId() + "' was not found"); } KubernetesRuntimeState existingState = existingStateOpt.get(); if (!predicate.test(existingState.getStatus())) { throw new IllegalStateException("Runtime status doesn't match to the specified predicate"); } existingState.setStatus(newStatus); entityManager.flush(); }
Source:
<code>private void loadWiki() { final Callback<LastFmAlbum> wikiCallback = new Callback<LastFmAlbum>(){ @Override public void onResponse(Call<LastFmAlbum> call, Response<LastFmAlbum> response) { LastFmAlbum lastFmAlbum = response.body(); if (lastFmAlbum.getAlbum().getWiki() != null) { String wik = lastFmAlbum.getAlbum().getWiki().getContent(); if (wik != null && !wik.trim().equals("")) { wiki = Html.fromHtml(wik); wikiReady(); return; } } <START> if(call.request().url().queryParameter("lang") != null) { <END> lastFMRestClient.getApiService().getAlbumInfo(getAlbum().getTitle(), getAlbum().getArtistName(), null).enqueue(this); return; } wiki = null; wikiReady(); } @Override public void onFailure(Call<LastFmAlbum> call, Throwable t) { t.printStackTrace(); wiki = null; } }; lastFMRestClient.getApiService().getAlbumInfo(getAlbum().getTitle(), getAlbum().getArtistName(), Locale.getDefault().getLanguage()).enqueue(wikiCallback); }</code><technical_language>right before? This retry lang is set</technical_language>

Target:
private void loadWiki() { loadWiki(Locale.getDefault().getLanguage()); }
Source:
<code>@Test public void compileJavaFile() throws Exception { <START> final String value = "Hello World!"; <END> TypeSpec type = TypeSpec.classBuilder("Test") .addModifiers(Modifier.PUBLIC) .addSuperinterface(ParameterizedTypeName.get(Callable.class, String.class)) .addMethod(MethodSpec.methodBuilder("call") .returns(String.class) .addModifiers(Modifier.PUBLIC) .addStatement("return $S", value) .build()) .build(); JavaFile javaFile = JavaFile.builder("foo", type).build(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticCollector, Locale.getDefault(), StandardCharsets.UTF_8); File classOutput = tmp.newFolder(); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(classOutput)); CompilationTask task = compiler.getTask(null, fileManager, diagnosticCollector, Collections.<String>emptySet(), Collections.<String>emptySet(), Collections.singleton(javaFile.toJavaFileObject())); assertThat(task.call()).isTrue(); assertThat(diagnosticCollector.getDiagnostics()).isEmpty(); ClassLoader loader = new URLClassLoader(new URL[] { classOutput.toURI().toURL() }); Callable<?> test = Class.forName("foo.Test", true, loader).asSubclass(Callable.class).newInstance(); assertThat(Callable.class.getMethod("call").invoke(test)).isEqualTo(value); }</code><technical_language>sweet</technical_language>

Target:
@Test public void compileJavaFile() throws Exception { final String value = "Hello World!"; TypeSpec type = TypeSpec.classBuilder("Test") .addModifiers(Modifier.PUBLIC) .addSuperinterface(ParameterizedTypeName.get(Callable.class, String.class)) .addMethod(MethodSpec.methodBuilder("call") .returns(String.class) .addModifiers(Modifier.PUBLIC) .addStatement("return $S", value) .build()) .build(); JavaFile javaFile = JavaFile.builder("foo", type).build(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticCollector, Locale.getDefault(), StandardCharsets.UTF_8); File classOutput = temporaryFolder.newFolder(); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(classOutput)); CompilationTask task = compiler.getTask(null, fileManager, diagnosticCollector, Collections.<String>emptySet(), Collections.<String>emptySet(), Collections.singleton(javaFile.toJavaFileObject())); assertThat(task.call()).isTrue(); assertThat(diagnosticCollector.getDiagnostics()).isEmpty(); ClassLoader loader = new URLClassLoader(new URL[] { classOutput.toURI().toURL() }); Callable<?> test = Class.forName("foo.Test", true, loader).asSubclass(Callable.class).newInstance(); assertThat(Callable.class.getMethod("call").invoke(test)).isEqualTo(value); }
Source:
<code>public Model getGETModel(Representation rep) { ModelImpl modelImpl = (ModelImpl) super.getGETModel(rep); if (rep instanceof DefaultRepresentation) { modelImpl .property("display", new StringProperty()) .property("uuid", new StringProperty()) .property("drug", new RefProperty("#/definitions/DrugGetRef")) .property("conceptReferenceTerm", new RefProperty("#/definitions/ConceptreferencetermGetRef")) .property("conceptMapType", new RefProperty("#/definitions/ConceptmaptypeGetRef")); } else if (rep instanceof FullRepresentation) { modelImpl .property("display", new StringProperty()) .property("uuid", new StringProperty()) .property("auditInfo", new StringProperty()) .property("drug", new RefProperty("#/definitions/DrugGet")) .property("conceptReferenceTerm", new RefProperty("#/definitions/ConceptreferencetermGet")) .property("conceptMapType", new RefProperty("#/definitions/ConceptmaptypeGet")); ; } <START> return modelImpl; <END> }</code><technical_language>is of this empty line</technical_language>

Target:
public Model getGETModel(Representation rep) { ModelImpl modelImpl = (ModelImpl) super.getGETModel(rep); if (rep instanceof DefaultRepresentation) { modelImpl.property("display", new StringProperty()).property("uuid", new StringProperty()) .property("drug", new RefProperty("#/definitions/DrugGetRef")) .property("conceptReferenceTerm", new RefProperty("#/definitions/ConceptreferencetermGetRef")) .property("conceptMapType", new RefProperty("#/definitions/ConceptmaptypeGetRef")); } else if (rep instanceof FullRepresentation) { modelImpl.property("display", new StringProperty()).property("uuid", new StringProperty()) .property("auditInfo", new StringProperty()).property("drug", new RefProperty("#/definitions/DrugGet")) .property("conceptReferenceTerm", new RefProperty("#/definitions/ConceptreferencetermGet")) .property("conceptMapType", new RefProperty("#/definitions/ConceptmaptypeGet")); } return modelImpl; }
Source:
<code>private IdleStrategy parseIdleStrategy(final String arg) throws ParseException { if (arg == null || arg.equalsIgnoreCase("NULL")) { return null; } IdleStrategy strategy; if (arg.startsWith(BackoffIdleStrategy.class.getName())) { strategy = parseBackoffIdleStrategy(arg); } else { try { final Class clazz = Class.forName(arg); strategy = (IdleStrategy)clazz.newInstance(); } <START> catch (final ClassNotFoundException ex) <END> { throw new ParseException("Class not found: " + ex.getMessage()); } catch (final IllegalAccessException ex) { throw new ParseException("Illegal access of class '" + arg + "': " + ex.getMessage()); } catch (final InstantiationException ex) { throw new ParseException("Could not instantiate class '" + arg + "': " + ex.getMessage()); } catch (final ClassCastException ex) { throw new ParseException("Class was not an IdleStrategy. " + ex.getMessage()); } } return strategy; }</code><technical_language>improved Java 7 multiple exception catch blocks</technical_language>

Target:
private IdleStrategy parseIdleStrategy(final String arg) throws ParseException { if (arg == null || arg.equalsIgnoreCase(NULL_VALUE)) { return null; } IdleStrategy strategy; if (arg.startsWith(BackoffIdleStrategy.class.getName())) { strategy = parseBackoffIdleStrategy(arg); } else { try { final Class clazz = Class.forName(arg); strategy = (IdleStrategy)clazz.newInstance(); } catch (final ClassNotFoundException | IllegalAccessException | InstantiationException | ClassCastException ex) { throw new ParseException("Error creating new instance of '" + arg + "': " + ex.getMessage()); } } return strategy; }
Source:
<code>public void review(final PendingCertifiedProductDTO listing) { for (PendingCertificationResultDTO cert : listing.getCertificationCriterion()) { <START> if (cert.getMeetsCriteria() != null && cert.getMeetsCriteria()) { <END> if (cert.getTestTools() != null && cert.getTestTools().size() > 0) { Iterator<PendingCertificationResultTestToolDTO> testToolIter = cert.getTestTools().iterator(); while (testToolIter.hasNext()) { PendingCertificationResultTestToolDTO testTool = testToolIter.next(); if (!StringUtils.isEmpty(testTool.getName()) && StringUtils.isEmpty(testTool.getVersion())) { listing.getErrorMessages() .add(msgUtil.getMessage("listing.criteria.missingTestToolVersion", testTool.getName(), cert.getNumber())); } } } } } }</code><technical_language>I want a "nest" emoji; find one..</technical_language>

Target:
public void review(final PendingCertifiedProductDTO listing) { for (PendingCertificationResultDTO cert : listing.getCertificationCriterion()) { if (cert.getMeetsCriteria() != null && cert.getMeetsCriteria() && cert.getTestTools() != null && cert.getTestTools().size() > 0) { for (PendingCertificationResultTestToolDTO testTool : cert.getTestTools()) if (!StringUtils.isEmpty(testTool.getName()) && StringUtils.isEmpty(testTool.getVersion())) { listing.getErrorMessages() .add(msgUtil.getMessage("listing.criteria.missingTestToolVersion", testTool.getName(), cert.getNumber())); } } } }
Source:
<code>private Set<String> getOccupiedProperties() { Set<String> propertiesMitWerten = new HashSet<>(); <START> for (ProcessProperty pp : processPropertyList) <END> if (isEmptyString(pp.getValue())) propertiesMitWerten.add(pp.getName()); return propertiesMitWerten; }</code><technical_language>Please bracket in in next lines</technical_language>

Target:
private Set<String> getOccupiedProperties() { Set<String> occupiedProperties = new HashSet<>(); for (ProcessProperty processProperty : processPropertyList) { if (StringUtils.isNotBlank(processProperty.getValue())) { occupiedProperties.add(processProperty.getName()); } } return occupiedProperties; }