auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static Class<?>[] getClassesInPackage(Class<?> klass) { String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "/" + klass.getPackage().getName().replaceAll("\\.", "/") + "/*.class"; ArrayList<Class<?>> results = new ArrayList<Class<?>>(); ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); try { Resource[] resources = resourcePatternResolver.getResources(packageSearchPath); if (resources != null) { for (Resource resource: resources) { String unqualifiedClassName = resource.getFilename().replace(".class", ""); String className = klass.getPackage().getName() +"." + unqualifiedClassName; Class<?> candidate = ClassUtils.resolveClassName(className, klass.getClassLoader()); <START> if (!Modifier.isAbstract(candidate.getModifiers()) && className.endsWith(TEST_CLASSNAME_SUFFIX)) { <END> results.add(candidate); } } } } catch (IOException e) { throw new RuntimeException(e); } return results.toArray(new Class<?>[results.size()]); }</code><technical_language>move suffix search Resource scan</technical_language>

Target:
private static Class<?>[] getClassesInPackage(Class<?> klass) { String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "/" + klass.getPackage().getName().replaceAll("\\.", "/") + "/*" + TEST_CLASSNAME_SUFFIX + ".class"; ArrayList<Class<?>> results = new ArrayList<Class<?>>(); ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); try { Resource[] resources = resourcePatternResolver.getResources(packageSearchPath); if (resources != null) { for (Resource resource: resources) { String unqualifiedClassName = resource.getFilename().replace(".class", ""); String className = klass.getPackage().getName() +"." + unqualifiedClassName; Class<?> candidate = ClassUtils.resolveClassName(className, klass.getClassLoader()); if (!Modifier.isAbstract(candidate.getModifiers())) { results.add(candidate); } } } } catch (IOException e) { throw new RuntimeException(e); } return results.toArray(new Class<?>[results.size()]); }
Source:
<code>public void testWaitForCompletionSuccess() { TestAnalysis module = setUpAnalysis(); IStatus status = module.schedule(); assertEquals(IStatus.ERROR, status.getSeverity()); TmfTraceStub trace = new TmfTraceStub(); trace.init("t1"); try { module.setTrace(trace); } catch (TmfAnalysisException e) { fail(e.getMessage()); } status = module.schedule(); <START> assertEquals(Status.OK_STATUS, status); <END> boolean completed = module.waitForCompletion(); assertTrue(completed); assertEquals(1, module.getAnalysisOutput()); }</code><technical_language>this work? I similar in a test I do: assertTrue(status.isOK()); else false. YMMV</technical_language>

Target:
public void testWaitForCompletionSuccess() { TestAnalysis module = setUpAnalysis(); IStatus status = module.schedule(); assertEquals(IStatus.ERROR, status.getSeverity()); try { module.setTrace(TmfTestTrace.A_TEST_10K.getTrace()); } catch (TmfAnalysisException e) { fail(e.getMessage()); } module.setParameter(TestAnalysis.PARAM_TEST, 1); status = module.schedule(); assertEquals(Status.OK_STATUS, status); boolean completed = module.waitForCompletion(new NullProgressMonitor()); assertTrue(completed); assertEquals(1, module.getAnalysisOutput()); }
Source:
<code>private boolean shouldRemoveMostRecentTombstone() { switch (purgeConfig.getPurgeLatestTombstone()) { case ALWAYS: return true; case IF_DELETE_FOLLOWS_FIRST_WRITE: return firstWriteToken && deleteRightAfterFirstWriteTimestamp == maxTombstoneTimestamp; case IF_FIRST_WRITE_PRESENT: return firstWriteToken; } <START> assert false: "Developer error"; <END> return false; }</code><technical_language>Remove this line</technical_language>

Target:
private boolean shouldRemoveMostRecentTombstone() { switch (purgeConfig.getPurgeLatestTombstone()) { case ALWAYS: return true; case IF_DELETE_FOLLOWS_FIRST_WRITE: return firstWriteToken && deleteRightAfterFirstWriteTimestamp == maxTombstoneTimestamp; case IF_FIRST_WRITE_PRESENT: return firstWriteToken; } assert false; return false; }
Source:
<code>protected Iterable<List<Object>> computeNext() { <START> if (updateType == null) { <END> warningsManager.clearWarnings(); } while (client.isRunning()) { checkInterruption(null); QueryStatusInfo results = client.currentStatusInfo(); progressCallback.accept(QueryStats.create(results.getId(), results.getStats())); warningsManager.addWarnings(results.getWarnings()); Iterable<List<Object>> data = client.currentData().getData(); try { client.advance(); } catch (RuntimeException e) { checkInterruption(e); throw e; } if (data != null) { return data; } } verify(client.isFinished()); QueryStatusInfo results = client.finalStatusInfo(); progressCallback.accept(QueryStats.create(results.getId(), results.getStats())); warningsManager.addWarnings(results.getWarnings()); if (results.getError() != null) { throw new RuntimeException(resultsException(results)); } return endOfData(); }</code><technical_language>track of this is a query more explicitly. Instead of checking for updateType == null, record a "isQuery" flag in constructor test for that</technical_language>

Target:
protected Iterable<List<Object>> computeNext() { if (isQuery) { warningsManager.clearWarnings(); } while (client.isRunning()) { checkInterruption(null); QueryStatusInfo results = client.currentStatusInfo(); progressCallback.accept(QueryStats.create(results.getId(), results.getStats())); warningsManager.addWarnings(results.getWarnings()); Iterable<List<Object>> data = client.currentData().getData(); try { client.advance(); } catch (RuntimeException e) { checkInterruption(e); throw e; } if (data != null) { return data; } } verify(client.isFinished()); QueryStatusInfo results = client.finalStatusInfo(); progressCallback.accept(QueryStats.create(results.getId(), results.getStats())); warningsManager.addWarnings(results.getWarnings()); if (results.getError() != null) { throw new RuntimeException(resultsException(results)); } return endOfData(); }
Source:
<code>private boolean returnsNullOnGivenInputTypes(ApplicableFunction applicableFunction, List<Type> parameterTypes) { Signature boundSignature = applicableFunction.getBoundSignature(); FunctionKind functionKind = boundSignature.getKind(); if (functionKind != SCALAR) { return true; } for (int i = 0; i < parameterTypes.size(); i++) { Type parameterType = parameterTypes.get(i); if (parameterType.equals(UNKNOWN)) { <START> ScalarFunctionImplementation implementation = getScalarFunctionImplementation(new FunctionHandle(boundSignature)); <END> if (implementation.getArgumentProperty(i).getNullConvention() != RETURN_NULL_ON_NULL) { return false; } } } return true; }</code><technical_language>bother changing this</technical_language>

Target:
private boolean returnsNullOnGivenInputTypes(ApplicableFunction applicableFunction, List<Type> parameterTypes) { Signature boundSignature = applicableFunction.getBoundSignature(); FunctionKind functionKind = boundSignature.getKind(); if (functionKind != SCALAR) { return true; } for (int i = 0; i < parameterTypes.size(); i++) { Type parameterType = parameterTypes.get(i); if (parameterType.equals(UNKNOWN)) { ScalarFunctionImplementation implementation = getScalarFunctionImplementation(boundSignature); if (implementation.getArgumentProperty(i).getNullConvention() != RETURN_NULL_ON_NULL) { return false; } } } return true; }
Source:
<code>private boolean applyAddTablePartitions(@Nullable JournalContext context, Journal.JournalEntry entry) { alluxio.proto.journal.Table.AddTablePartitionsEntry addTablePartitions = entry.getAddTablePartitions(); if (!addTablePartitions.getDbName().equals(mName)) { return false; } mTables.compute(addTablePartitions.getTableName(), (key, existingTable) -> { if (existingTable != null) { if (addTablePartitions.getVersion() == existingTable.getVersion()) { <START> LOG.info("Adding partitions to table {}.{}", mName, addTablePartitions.getTableName()); <END> if (context != null) { context.append(entry); } existingTable.addPartitions(addTablePartitions); return existingTable; } LOG.info("Will not add partitions to table {}.{}, because of mismatched versions. " + "version-to-delete: existing-version: {}", mName, addTablePartitions.getTableName(), addTablePartitions.getVersion(), existingTable.getVersion()); } LOG.debug("Cannot add partitions to table {}.{}, because it does not exist.", mName, addTablePartitions.getTableName()); return existingTable; }); return true; }</code><technical_language>add # partitions adding in message</technical_language>

Target:
private boolean applyAddTablePartitions(@Nullable JournalContext context, Journal.JournalEntry entry) { alluxio.proto.journal.Table.AddTablePartitionsEntry addTablePartitions = entry.getAddTablePartitions(); if (!addTablePartitions.getDbName().equals(mName)) { return false; } mTables.compute(addTablePartitions.getTableName(), (key, existingTable) -> { if (existingTable != null) { if (addTablePartitions.getVersion() == existingTable.getVersion()) { LOG.info("Adding partitions to table {}.{}", addTablePartitions.getPartitionsCount(), mName, addTablePartitions.getTableName()); if (context != null) { context.append(entry); } existingTable.addPartitions(addTablePartitions); return existingTable; } LOG.info("Will not add partitions to table {}.{}, because of mismatched versions. " + "version-to-add-partitions: existing-version: {}", mName, addTablePartitions.getTableName(), addTablePartitions.getVersion(), existingTable.getVersion()); } LOG.debug("Cannot add partitions to table {}.{}, because it does not exist.", mName, addTablePartitions.getTableName()); return existingTable; }); return true; }
Source:
<code>public void testMetaDataProtocolVersion() { <START> long serversTimstamp = System.currentTimeMillis(); <END> String version = MetaDataProtocol.getVersion(serversTimstamp); assertEquals("4.16.x", version); assertEquals(String.format("%d.%d.%s", PHOENIX_MAJOR_VERSION, PHOENIX_MINOR_VERSION, "x"), version); }</code><technical_language>I this assert fit for branches assertEquals("4.16.x", version); needed. Thought</technical_language>

Target:
public void testMetaDataProtocolVersion() { assertEquals(String.format("%d.%d.%s", PHOENIX_MAJOR_VERSION, PHOENIX_MINOR_VERSION, "x"), MetaDataProtocol.getVersion(System.currentTimeMillis())); }
Source:
<code>private void scheduleRefresh(Duration delay) { if (executor.isShutdown()) { return; } <START> executor.schedule((Runnable) this::refresh, delay.toMillis(), TimeUnit.MILLISECONDS); <END> }</code><technical_language>Is (Runnable) needed</technical_language>

Target:
private void scheduleRefresh(Duration delay) { if (executor.isShutdown()) { return; } executor.schedule(this::refresh, delay.toMillis(), TimeUnit.MILLISECONDS); }
Source:
<code>private void registerPoolStatistics(String poolName, ResourcePageSource pageSource) { <START> registerStatistic(pageSource, poolName, "allocatedMemory", STATISTICS_POOL_TAG, PROPERTY_POOL_KEY, new Callable<Number>() { <END> @Override public Number call() throws Exception { return pageSource.delegatePageSource.getAllocatedSizeUnSync(); } }); }</code><technical_language>allocatedMemory is renamed allocatedSize if store stats, size means allocated... check code call allocatedMemory</technical_language>

Target:
private void registerPoolStatistics(String poolName, ResourcePageSource pageSource) { STAT_POOL_METHOD_REFERENCES.entrySet().stream().forEach((entry)-> registerStatistic(pageSource, poolName, entry.getKey(), STATISTICS_POOL_TAG, PROPERTY_POOL_KEY, () -> entry.getValue().apply(pageSource)) ); }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IndexSpec indexSpec = (IndexSpec) o; if (bitmapSerdeFactory != null ? !bitmapSerdeFactory.equals(indexSpec.bitmapSerdeFactory) : indexSpec.bitmapSerdeFactory != null) { return false; } if (dimensionCompression != null ? !dimensionCompression.equals(indexSpec.dimensionCompression) : indexSpec.dimensionCompression != null) { return false; } <START> if (!Objects.equals(spatialDimensionDelimiter, indexSpec.spatialDimensionDelimiter)) { <END> return false; } return !(metricCompression != null ? !metricCompression.equals(indexSpec.metricCompression) : indexSpec.metricCompression != null); }</code><technical_language>spatialDimensionDelimiter is non-null, this line simplified</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IndexSpec indexSpec = (IndexSpec) o; if (!bitmapSerdeFactory.equals(indexSpec.bitmapSerdeFactory)) { return false; } if (!dimensionCompression.equals(indexSpec.dimensionCompression)) { return false; } if (!longEncoding.equals(indexSpec.longEncoding)) { return false; } if (!spatialDimensionDelimiter.equals(indexSpec.spatialDimensionDelimiter)) { return false; } return metricCompression.equals(indexSpec.metricCompression); }
Source:
<code>private DatumReader<Object> buildDatumReader(Schema schema, Schema writtenSchema) { if (specific) { <START> return new SpecificDatumReader<Object>(unwrapNull(writtenSchema), unwrapNull(schema)); <END> } else { return new GenericDatumReader<Object>(unwrapNull(writtenSchema), unwrapNull(schema)); } }</code><technical_language>I this is call this reader if is a value. changing assumptions for other parts of code. If fields assumed non-null in past, code checks reader handle nulls sets correct default value</technical_language>

Target:
private DatumReader<Object> buildDatumReader(Schema schema, Schema writtenSchema) { if (specific) { return new SpecificDatumReader<Object>(unwrapNullable(writtenSchema), unwrapNullable(schema)); } else { return new GenericDatumReader<Object>(unwrapNullable(writtenSchema), unwrapNullable(schema)); } }
Source:
<code>public void setUp() throws Exception { super.setUp(); iProject = project.project; testRepo = new TestRepository(gitDir); testRepo.connect(iProject); repo = RepositoryMapping.getMapping(iProject).getRepository(); <START> new Git(repo).commit().setAuthor("JUnit", "junit@jgit.org") <END> .setMessage("Initial commit").call(); }</code><technical_language>added a try resources here</technical_language>

Target:
public void setUp() throws Exception { super.setUp(); iProject = project.project; testRepo = new TestRepository(gitDir); testRepo.connect(iProject); repo = RepositoryMapping.getMapping(iProject).getRepository(); try (Git git = new Git(repo)) { git.commit().setAuthor("JUnit", "junit@jgit.org") .setMessage("Initial commit").call(); } }
Source:
<code><START> private List<?> getRelatedArticles() { <END> Map<String, Map<String, ?>> relationshipsByDoi = new HashMap<>(); for (Map<String, ?> relatedArticle : readRelatedArticles()) { relationshipsByDoi.put((String) relatedArticle.get("doi"), relatedArticle); } return relationshipsByDoi.values().stream() .sorted(BY_DESCENDING_PUB_DATE) .collect(Collectors.toList()); }</code><technical_language>return type be: List<Map<String, ?>></technical_language>

Target:
private List<Map<String, ?>> getRelatedArticles() { Map<String, Map<String, ?>> relationshipsByDoi = new HashMap<>(); for (String direction : RELATIONSHIP_DIRECTIONS) { for (Map<String, ?> relatedArticle : relationships.get(direction)) { String relatedArticleDoi = (String) relatedArticle.get("doi"); Map<String, ?> previous = relationshipsByDoi.put(relatedArticleDoi, relatedArticle); if (previous != null) { Preconditions.checkState(Objects.equals(relatedArticle.get("revisionNumber"), previous.get("revisionNumber")) && Objects.equals(relatedArticle.get("title"), previous.get("title")) && Objects.equals(relatedArticle.get("publicationDate"), previous.get("publicationDate"))); } } } return relationshipsByDoi.values().stream() .filter(ArticleMetadata::isPublished) .sorted(BY_DESCENDING_PUB_DATE) .collect(Collectors.toList()); }
Source:
<code>public Weighting getWeightingForCH( WeightingMap weightingMap, FlagEncoder encoder ) { String weightingStr = weightingMap.getWeighting().toLowerCase(); if (weightingStr.isEmpty()) <START> weightingStr = getCHWeighting().get(0); <END> for (Weighting w : algoFactories.keySet()) { if (w.matches(weightingStr, encoder)) return w; } throw new IllegalStateException("No weighting found for request " + weightingMap + ", encoder:" + encoder + ", " + algoFactories); }</code><technical_language>This is valid assume 'fastest' in weighting list. throw exception if is empty a more clear exception ArrayOutOfBounds</technical_language>

Target:
public Weighting getWeightingForCH( WeightingMap weightingMap, FlagEncoder encoder ) { String weightingStr = weightingMap.getWeighting().toLowerCase(); if (weightingStr.isEmpty()) weightingStr = getCHWeightings().get(0); for (Weighting w : algoFactories.keySet()) { if (w.matches(weightingStr, encoder)) return w; } throw new IllegalStateException("No weighting found for request " + weightingMap + ", encoder:" + encoder + ", " + algoFactories); }
Source:
<code><START> public InsightsResource(final AccountDAO accountDAO, final TrendsDAO trendsDAO, final AggregateSleepScoreDAODynamoDB scoreDAODynamoDB, final TrackerMotionDAO trackerMotionDAO) { <END> this.accountDAO = accountDAO; this.trendGraphProcessor = new TrendGraphProcessor(trendsDAO, scoreDAODynamoDB, trackerMotionDAO); }</code><technical_language>If DAOs pass TrendGraphProcessor constructor</technical_language>

Target:
public InsightsResource(final AccountDAO accountDAO, final TrendsDAO trendsDAO, final AggregateSleepScoreDAODynamoDB scoreDAODynamoDB, final TrackerMotionDAO trackerMotionDAO) { this.accountDAO = accountDAO; this.trendsDAO = trendsDAO; this.scoreDAODynamoDB = scoreDAODynamoDB; this.trackerMotionDAO = trackerMotionDAO; }
Source:
<code>public void appendRows(Page page) { <START> if (tempFiles.size() == maxTempFiles) { <END> throw new PrestoException(HIVE_TOO_MANY_BUCKET_SORT_FILES, "Too many temporary files for sorted bucket writer"); } if (!sortBuffer.canAdd(page)) { flushBuffer(); } sortBuffer.add(page); }</code><technical_language>this a strange place for this check</technical_language>

Target:
public void appendRows(Page page) { if (!sortBuffer.canAdd(page)) { flushToTempFile(); } sortBuffer.add(page); }
Source:
<code>protected Class<?> findClass(String name) throws ClassNotFoundException { if (classCache.containsKey(name)) { return classCache.get(name); } for (WeakReference<Bundle> bundle : bundles) { try { <START> final Class clazz = bundle.get().loadClass(name); <END> if (clazz != null) { classCache.put(name, clazz); return clazz; } } catch (Exception ignore) { } } throw new ClassNotFoundException("Could not load requested class : " + name); }</code><technical_language>sense check bundle state loading class? a quick test bundles uninstalled present in BundleContext able load classes/resources</technical_language>

Target:
protected Class<?> findClass(String name) throws ClassNotFoundException { if (classCache.containsKey(name)) { return classCache.get(name); } for (WeakReference<Bundle> ref : bundles) { final Bundle bundle = ref.get(); if (bundle.getState() == Bundle.ACTIVE) { try { final Class clazz = bundle.loadClass(name); if (clazz != null) { classCache.put(name, clazz); return clazz; } } catch (Exception ignore) { } } } throw new ClassNotFoundException("Could not load requested class : " + name); }
Source:
<code>public void close() throws IOException { if (closed) { return; } try { if (errorCount == 0) { if (blkInProgress) { throw new IllegalStateException("Close() called with active block appender."); } try (BlockAppender appender = prepareMetaBlock(DataIndex.BLOCK_NAME, getDefaultCompressionAlgorithm())) { dataIndex.write(appender); } long offsetIndexMeta = out.position(); metaIndex.write(out); long offsetCryptoParameter = out.position(); String es = this.encryptionStrategy.getClass().getName(); <START> out.writeUTF(es); <END> out.writeLong(offsetIndexMeta); out.writeLong(offsetCryptoParameter); API_VERSION_3.write(out); Magic.write(out); out.flush(); length = out.position(); out.close(); } } finally { closed = true; } }</code><technical_language>I encryption strategy serialized files. pluggable encryption strategy change, current strategy required able interpret previously written. So, I necessary serialize name of strategy here... permit some opportunity write some magic values/parameters (or future replacement, if swapped out) recognize</technical_language>

Target:
public void close() throws IOException { if (closed) { return; } try { if (errorCount == 0) { if (blkInProgress) { throw new IllegalStateException("Close() called with active block appender."); } try (BlockAppender appender = prepareMetaBlock(DataIndex.BLOCK_NAME, getDefaultCompressionAlgorithm())) { dataIndex.write(appender); } long offsetIndexMeta = out.position(); metaIndex.write(out); long offsetCryptoParameter = out.position(); out.writeUTF(this.encrypter.getParameters()); out.writeLong(offsetIndexMeta); out.writeLong(offsetCryptoParameter); API_VERSION_3.write(out); Magic.write(out); out.flush(); length = out.position(); out.close(); } } finally { closed = true; } }
Source:
<code>private void testWithConfiguration(LogLevel level, LogFileConfiguration config, Runnable r) { LogFileConfiguration old = Database.log.getFile().getConfig(); EnumSet<LogDomain> domains = Database.log.getConsole().getDomains(); Database.log.getFile().setConfig(config); Database.log.getFile().setLevel(level); try { r.run(); } finally { Database.log.getFile().setLevel(LogLevel.INFO); Database.log.getFile().setConfig(old); Database.log.getConsole().setDomains(domains); <START> Database.log.getConsole().setLevel(LogLevel.INFO); <END> } }</code><technical_language>default console log level is WARNING. reset WARNING</technical_language>

Target:
private void testWithConfiguration(LogLevel level, LogFileConfiguration config, Runnable r) { LogFileConfiguration old = Database.log.getFile().getConfig(); EnumSet<LogDomain> domains = Database.log.getConsole().getDomains(); Database.log.getFile().setConfig(config); Database.log.getFile().setLevel(level); try { r.run(); } finally { Database.log.getFile().setLevel(LogLevel.INFO); Database.log.getFile().setConfig(old); Database.log.getConsole().setDomains(domains); Database.log.getConsole().setLevel(LogLevel.WARNING); } }
Source:
<code>private Properties loadStringProperties(String body) { Properties properties = new Properties(); try { properties.load(new StringReader(body)); } catch (IOException e) { e.printStackTrace(); } <START> return properties; <END> }</code><technical_language>Is this intended return empty Properties object if exception occurs</technical_language>

Target:
private Properties loadStringProperties(String body) { Properties properties = new Properties(); try { properties.load(new StringReader(body)); } catch (IOException e) { } return properties; }
Source:
<code>void addAll(List<Cell> hbaseCells, List<RowCell> familyCells) { <START> if (!familyCells.isEmpty()) { <END> Collections.sort(familyCells, QUALIFIER_COMPARATOR); hbaseCells.addAll(familyCells); familyCells.clear(); } }</code><technical_language>nit: remove "if (!familyCells.isEmpty())"</technical_language>

Target:
private static void addAll(List<Cell> hbaseCells, List<RowCell> familyCells) { Collections.sort(familyCells, QUALIFIER_AND_TIMESTAMP_COMPARATOR); hbaseCells.addAll(familyCells); familyCells.clear(); }
Source:
<code>public DiscoveryResult createResult(ServiceInfo info) { DiscoveryResult result = null; ThingUID uid = getThingUID(info); if (uid != null) { InetAddress[] addrs = info.getInetAddresses(); Map<String, Object> properties = new HashMap<>(2); String label = null; if (BST_10_THING_TYPE_UID.equals(uid.getThingTypeUID())) { try { String group = DiscoveryUtil .executeUrl("http://" + addrs[0].getHostAddress() + ":8090/getGroup"); label = DiscoveryUtil.getContentOfFirstElement(group, "name"); } catch (IOException e) { logger.debug("Can't obtain label for group. Will use the default one"); } } if (label == null || label.isEmpty()) { label = info.getName(); } if (label == null || label.isEmpty()) { label = "Bose SoundTouch"; } if (addrs.length > 1) { logger.warn("Bose SoundTouch device ({}) reports multiple addresses - using the first one: {}", info.getName(), label, Arrays.toString(addrs)); } properties.put(BoseSoundTouchConfiguration.HOST, addrs[0].getHostAddress()); if (getMacAddress(info) != null) { properties.put(BoseSoundTouchConfiguration.MAC_ADDRESS, new String(getMacAddress(info))); } byte[] manufacturer = info.getPropertyBytes("MANUFACTURER"); if (manufacturer != null) { <START> properties.put(Thing.PROPERTY_VENDOR, new String(manufacturer)); <END> } return DiscoveryResultBuilder.create(uid).withProperties(properties).withLabel(label).withTTL(600).build(); } return result; }</code><technical_language>passing by, I this String(byte[] bytes) constructor, depends platform's default charset, pick a charset explicitly. of adapt existing occurrences line 95 more in this file. Edit: some refinement</technical_language>

Target:
public DiscoveryResult createResult(ServiceInfo info) { DiscoveryResult result = null; ThingUID uid = getThingUID(info); if (uid != null) { InetAddress[] addrs = info.getInetAddresses(); Map<String, Object> properties = new HashMap<>(2); String label = null; if (BST_10_THING_TYPE_UID.equals(uid.getThingTypeUID())) { try { String group = DiscoveryUtil .executeUrl("http://" + addrs[0].getHostAddress() + ":8090/getGroup"); label = DiscoveryUtil.getContentOfFirstElement(group, "name"); } catch (IOException e) { logger.debug("Can't obtain label for group. Will use the default one"); } } if (label == null || label.isEmpty()) { label = info.getName(); } if (label == null || label.isEmpty()) { label = "Bose SoundTouch"; } if (addrs.length > 1) { logger.warn("Bose SoundTouch device ({}) reports multiple addresses - using the first one: {}", info.getName(), label, Arrays.toString(addrs)); } properties.put(BoseSoundTouchConfiguration.HOST, addrs[0].getHostAddress()); if (getMacAddress(info) != null) { properties.put(BoseSoundTouchConfiguration.MAC_ADDRESS, new String(getMacAddress(info), StandardCharsets.UTF_8)); } byte[] manufacturer = info.getPropertyBytes("MANUFACTURER"); if (manufacturer != null) { properties.put(Thing.PROPERTY_VENDOR, new String(manufacturer, StandardCharsets.UTF_8)); } return DiscoveryResultBuilder.create(uid).withProperties(properties).withLabel(label).withTTL(600).build(); } return result; }
Source:
<code>private boolean couldCreateVersion(final IPublishOperationConfiguration configuration) { <START> return !newHashSet(transform(getAllVersions(getParentBranchPath()), new Function<ICodeSystemVersion, String>() { <END> @Override public String apply(final ICodeSystemVersion version) { return checkNotNull(version).getVersionId(); } })).contains(configuration.getVersionId()); }</code><technical_language>Convert this a code system version search/get request (or simplify a Map.containsKey, Collection.contains)</technical_language>

Target:
private boolean couldCreateVersion(final IPublishOperationConfiguration configuration) { return new CodeSystemRequests(getRepositoryUuid()) .prepareSearchCodeSystemVersion() .setCodeSystemShortName(configuration.getCodeSystemShortName()) .setVersionId(configuration.getVersionId()) .build(IBranchPath.MAIN_BRANCH) .executeSync(getEventBus()) .getItems() .isEmpty(); }
Source:
<code>public <T extends RunConfigurationBase> void updateJavaParameters( T configuration, JavaParameters params, RunnerSettings runnerSettings ) throws ExecutionException { final Module module = findPantsModule(configuration); if (module == null) { return; } params.setUseDynamicClasspath(true); String homePath = PathManager.getHomePath(); String jdkPath = params.getJdkPath(); String pluginPath = PathManager.getPluginsPath(); Set<String> pathsAllowed = Sets.newHashSet(jdkPath, homePath, pluginPath); if (ApplicationManager.getApplication().isUnitTestMode()) { pathsAllowed.add( Optional.ofNullable(PluginManager.getPlugin(PluginId.getId("com.intellij"))) .map(s -> s.getPath().getParentFile().getParentFile().getParentFile().getAbsolutePath()).get() ); pathsAllowed.add( Optional.ofNullable(PluginManager.getPlugin(PluginId.getId("JUnit"))) .map(s -> s.getPath().getParentFile().getParentFile().getParentFile().getAbsolutePath()).get() ); <START> } <END> final PathsList classpath = params.getClassPath(); List<String> classpathToKeep = classpath.getPathList().stream() .filter(p -> pathsAllowed.stream().anyMatch(p::contains)).collect(Collectors.toList()); classpath.clear(); classpath.addAll(classpathToKeep); VirtualFile manifestJar = PantsUtil.findProjectManifestJar(configuration.getProject()) .orElseThrow(() -> new ExecutionException("Pants supports manifest jar, but it is not found.")); classpath.add(manifestJar.getPath()); PantsExternalMetricsListenerManager.getInstance().logTestRunner(configuration); }</code><technical_language>I this easier follow if code builds pathsAllowed broken out a separate method</technical_language>

Target:
public <T extends RunConfigurationBase> void updateJavaParameters( T configuration, JavaParameters params, RunnerSettings runnerSettings ) throws ExecutionException { final Module module = findPantsModule(configuration); if (module == null) { return; } Set<String> pathsAllowed = calculatePathsAllowed(params); final PathsList classpath = params.getClassPath(); List<String> classpathToKeep = classpath.getPathList().stream() .filter(cp -> pathsAllowed.stream().anyMatch(cp::contains)).collect(Collectors.toList()); classpath.clear(); classpath.addAll(classpathToKeep); VirtualFile manifestJar = PantsUtil.findProjectManifestJar(configuration.getProject()) .orElseThrow(() -> new ExecutionException("manifest.jar is not found. It should be generated by `./pants export-classpath ...`")); classpath.add(manifestJar.getPath()); PantsExternalMetricsListenerManager.getInstance().logTestRunner(configuration); }
Source:
<code>protected Collection<String> getTableDefinitions() { ImmutableList.Builder<String> builder = ImmutableList.builder(); builder.add("CREATE TABLE indexing (" + "id int," + "id2 int," + "map_values map<text, int>," + "map_keys map<text, int>," + "map_entries map<text, int>," + "map_all map<text, int>," + "text_column text, " + "\"MixedCaseColumn\" list<text>," + (cassandraVersion.compareTo(VersionNumber.parse("2.1.3")) >= 0 ? ", map_full frozen<map<text, int>>," + "set_full frozen<set<text>>," + "list_full frozen<list<text>>," : "") + "PRIMARY KEY (id, id2));" ); <START> if(cassandraVersion.compareTo(VersionNumber.parse("3.0.0-rc1")) >= 0) { <END> builder.add("CREATE MATERIALIZED VIEW mv1 AS " + "SELECT id2, id, map_values, text_column " + "FROM indexing " + "WHERE id2 IS NOT NULL AND id IS NOT NULL AND text_column IS NOT NULL " + "PRIMARY KEY (id2, id);" ); } return builder.build(); }</code><technical_language>This is longer needed if MVs dont support indexes</technical_language>

Target:
protected Collection<String> getTableDefinitions() { ImmutableList.Builder<String> builder = ImmutableList.builder(); builder.add("CREATE TABLE indexing (" + "id int," + "id2 int," + "map_values map<text, int>," + "map_keys map<text, int>," + "map_entries map<text, int>," + "map_all map<text, int>," + "text_column text, " + "\"MixedCaseColumn\" list<text>," + (cassandraVersion.compareTo(VersionNumber.parse("2.1.3")) >= 0 ? ", map_full frozen<map<text, int>>," + "set_full frozen<set<text>>," + "list_full frozen<list<text>>," : "") + "PRIMARY KEY (id, id2));" ); return builder.build(); }
Source:
<code>public void onPartitionBecomeStandbyFromLeader(String partitionName) { logger.info("Partition state change notification from Leader to Standby received for partition {}", partitionName); rwlock1.writeLock().lock(); try { if (peerLeaderReplicasByPartition.containsKey(partitionName)) { <START> peerLeaderReplicasByPartition.remove((partitionName)); <END> } } finally { rwlock1.writeLock().unlock(); } }</code><technical_language>need check if peerLeaderReplicasByPartition contains partitionName? I feel unnecessary</technical_language>

Target:
public void onPartitionBecomeStandbyFromLeader(String partitionName) { logger.info("Partition state change notification from Leader to Standby received for partition {}", partitionName); partitionLeaderInfo.removePartition(partitionName); }
Source:
<code>private void checkRepresentation(EObject target, DRepresentation representation, boolean expected) { <START> Collection<DRepresentation> representations = DialectManager.INSTANCE.getRepresentations(target, session); assertEquals("Can " + (expected ? "not " : "") + "find " + DIAGRAM_NAME + " DRepresentation with sirius cross referencer", expected, representations.contains(representation)); <END> }</code><technical_language>I duplicate this session cross referencer. implementation of DialectManagerImpl change descriptors for example</technical_language>

Target:
private void checkRepresentation(EObject target, DRepresentation representation, boolean expected) { Collection<DRepresentation> representations = Lists.newArrayList(); ECrossReferenceAdapter xref = session.getSemanticCrossReferencer(); for (EStructuralFeature.Setting setting : xref.getInverseReferences(target)) { if (ViewpointPackage.Literals.DREPRESENTATION.isInstance(setting.getEObject()) && setting.getEStructuralFeature() == ViewpointPackage.Literals.DSEMANTIC_DECORATOR__TARGET) { representations.add((DRepresentation) setting.getEObject()); } } assertEquals("Can " + (expected ? "not " : "") + "find " + DIAGRAM_NAME + " DRepresentation with sirius cross referencer", expected, representations.contains(representation)); representations = DialectManager.INSTANCE.getRepresentations(target, session); assertEquals("Can " + (expected ? "not " : "") + "find " + DIAGRAM_NAME + " DRepresentation with DialectManager.INSTANCE.getRepresentations", expected, representations.contains(representation)); }
Source:
<code>public void onEditButtonClicked(final ClickEvent ignore) { <START> presenter.openEditModal(name.textContent, value.textContent);; <END> }</code><technical_language>need pass values presenter</technical_language>

Target:
public void onEditButtonClicked(final ClickEvent ignore) { presenter.openEditModal();; }
Source:
<code>public static long bitCount(@SqlType(StandardTypes.BIGINT) long num, @SqlType(StandardTypes.BIGINT) long bits) { if (bits == 64) { return Long.bitCount(num); } if (bits <= 1 || bits > 64) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Bits specified in bit_count must be between 2 and 64, got " + bits); } long lowBitsMask = (1L << (bits - 1)) - 1; if (num > lowBitsMask || num < ~lowBitsMask) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Number must be representable with the bits specified. " + num + " can not be represented with " + bits + " bits"); <START> } <END> long mask = lowBitsMask | 0x8000_0000_0000_0000L; return Long.bitCount(num & mask); }</code><technical_language>I mask calculation is incorrect. mask = lowBitsMask | (1L << (bits - 1));</technical_language>

Target:
public static long bitCount(@SqlType(StandardTypes.BIGINT) long num, @SqlType(StandardTypes.BIGINT) long bits) { if (bits == 64) { return Long.bitCount(num); } if (bits <= 1 || bits > 64) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Bits specified in bit_count must be between 2 and 64, got " + bits); } long lowBitsMask = (1L << (bits - 1)) - 1; if (num > lowBitsMask || num < ~lowBitsMask) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Number must be representable with the bits specified. " + num + " can not be represented with " + bits + " bits"); } long mask = (1L << bits) - 1; return Long.bitCount(num & mask); }
Source:
<code>@Override public void deactivate(ComponentContext context) { <START> handlers = null; <END> super.deactivate(context); }</code><technical_language>Remove extra empty line</technical_language>

Target:
public void deactivate(ComponentContext context) { handlers = null; super.deactivate(context); }
Source:
<code>private void startLockMonitoring() { logger.debug("Starting the lock monitor"); <START> Thread monitorThread = new Thread(new MonitorLock()); <END> monitorThread.setDaemon(true); monitorThread.start(); }</code><technical_language>thread executors. is important these. this solution a thread permanently agaisnt some of thread modelling. schedule thread executor</technical_language>

Target:
private synchronized void startLockMonitoring() { logger.debug("Starting the lock monitor"); if (scheduledLockMonitor == null) { MonitorLock monitorLock = new MonitorLock(); scheduledLockMonitor = scheduledPool.scheduleAtFixedRate(monitorLock, LOCK_MONITOR_TIMEOUT_MILLIES, LOCK_MONITOR_TIMEOUT_MILLIES, TimeUnit.MILLISECONDS); } else { logger.debug("Lock monitor was already started"); } }
Source:
<code>public @ResponseBody ExperimentDto get(@PathVariable Long experimentId) throws IOException { <START> return Dtos.asDto(experimentService.get(experimentId)); <END> }</code><technical_language>throw RestException Status.NOT_FOUND if null</technical_language>

Target:
public @ResponseBody ExperimentDto get(@PathVariable Long experimentId) throws IOException { Experiment experiment = experimentService.get(experimentId); if (experiment == null) { throw new RestException("No such experiment.", Status.NOT_FOUND); } return Dtos.asDto(experiment); }
Source:
<code>static void sendKey(View view, String keyName) { int keyCode = 0; String chars = null; switch (keyName) { case "ESC": keyCode = KeyEvent.KEYCODE_ESCAPE; break; case "TAB": keyCode = KeyEvent.KEYCODE_TAB; break; case "HOME": keyCode = KeyEvent.KEYCODE_MOVE_HOME; break; case "END": keyCode = KeyEvent.KEYCODE_MOVE_END; break; case "PGUP": keyCode = KeyEvent.KEYCODE_PAGE_UP; break; <START> case "PGDN": <END> keyCode = KeyEvent.KEYCODE_PAGE_DOWN; break; case "INS": keyCode = KeyEvent.KEYCODE_INSERT; break; case "DEL": keyCode = KeyEvent.KEYCODE_FORWARD_DEL; break; case "↑": keyCode = KeyEvent.KEYCODE_DPAD_UP; break; case "←": keyCode = KeyEvent.KEYCODE_DPAD_LEFT; break; case "→": keyCode = KeyEvent.KEYCODE_DPAD_RIGHT; break; case "↓": keyCode = KeyEvent.KEYCODE_DPAD_DOWN; break; case "↲": keyCode = KeyEvent.KEYCODE_ENTER; break; case "―": chars = "-"; break; case "-": chars = "-"; break; default: chars = keyName; } TerminalView terminalView = view.findViewById(R.id.terminal_view); if (keyCode > 0) { terminalView.onKeyDown(keyCode, new KeyEvent(KeyEvent.ACTION_UP, keyCode)); } else { TerminalSession session = terminalView.getCurrentSession(); if (session != null) session.write(chars); } }</code><technical_language>Add aliases, PAGE_DOWN, PAGEDOWN etc. People in termux.properties. for INSERT, DELETE, BACKSPACE, LEFT RIGHT etc. A short name is preffered one, longer name explicit</technical_language>

Target:
static void sendKey(View view, String keyName) { TerminalView terminalView = view.findViewById(R.id.terminal_view); if (keyCodesForString.containsKey(keyName)) { int keyCode = keyCodesForString.get(keyName); terminalView.onKeyDown(keyCode, new KeyEvent(KeyEvent.ACTION_UP, keyCode)); } else { TerminalSession session = terminalView.getCurrentSession(); if (session != null) session.write(keyName); } }
Source:
<code>public void streamData(PID pid, String dsName, AccessGroupSet principals, boolean asAttachment, <START> HttpServletResponse response) throws IOException, ResourceNotFoundException { <END> DatastreamType derivType = getByIdentifier(dsName); if (derivType == null || !derivativeService.listDerivativeTypes().contains(derivType)) { throw new IllegalArgumentException(dsName + " is not a valid derivative type."); } accessControlService.assertHasAccess("Insufficient permissions to access derivative " + dsName + " for object " + pid, pid, principals, getPermissionForDatastream(derivType)); Derivative deriv = derivativeService.getDerivative(pid, derivType); if (deriv == null) { throw new ResourceNotFoundException("Deriviatve " + dsName + " does not exist for object " + pid); } File derivFile = deriv.getFile(); response.setHeader(CONTENT_LENGTH, Long.toString(derivFile.length())); response.setHeader(CONTENT_TYPE, derivType.getMimetype()); String filename = derivFile.getName(); if (asAttachment) { response.setHeader(CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\""); } else { response.setHeader(CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\""); } OutputStream outStream = response.getOutputStream(); IOUtils.copy(new FileInputStream(derivFile), outStream, BUFFER_SIZE); }</code><technical_language>a throws declaration for IllegalArgumentException, too</technical_language>

Target:
public void streamData(PID pid, String dsName, AccessGroupSet principals, boolean asAttachment, HttpServletResponse response) throws IOException, ResourceNotFoundException { DatastreamType derivType = getByIdentifier(dsName); if (derivType == null || !listDerivativeTypes().contains(derivType)) { throw new IllegalArgumentException(dsName + " is not a valid derivative type."); } accessControlService.assertHasAccess("Insufficient permissions to access derivative " + dsName + " for object " + pid, pid, principals, getPermissionForDatastream(derivType)); Derivative deriv = derivativeService.getDerivative(pid, derivType); if (deriv == null) { throw new ResourceNotFoundException("Deriviatve " + dsName + " does not exist for object " + pid); } File derivFile = deriv.getFile(); response.setHeader(CONTENT_LENGTH, Long.toString(derivFile.length())); response.setHeader(CONTENT_TYPE, derivType.getMimetype()); String filename = derivFile.getName(); if (asAttachment) { response.setHeader(CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\""); } else { response.setHeader(CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\""); } OutputStream outStream = response.getOutputStream(); IOUtils.copy(new FileInputStream(derivFile), outStream, BUFFER_SIZE); }
Source:
<code>public void runBadCollectionSizeTest() { SystemTestEnvironment testEnvironment = systemTestEnvironmentManager.createTestEnvironment("bad-collection-size"); RandoopOptions options = createRandoopOptions(testEnvironment); options.addTestClass("collections.BadCollection"); <START> options.setOption("generated_limit", "5"); <END> options.setOption("output_limit", "5"); CoverageChecker coverageChecker = new CoverageChecker( options, "collections.BadCollection.add(java.lang.Object) exclude", "collections.BadCollection.addAll(java.util.Collection) exclude", "collections.BadCollection.clear() exclude", "collections.BadCollection.contains(java.lang.Object) exclude", "collections.BadCollection.containsAll(java.util.Collection) exclude", "collections.BadCollection.isEmpty() exclude", "collections.BadCollection.iterator() exclude", "collections.BadCollection.remove(java.lang.Object) exclude", "collections.BadCollection.removeAll(java.util.Collection) exclude", "collections.BadCollection.retainAll(java.util.Collection) exclude", "collections.BadCollection.toArray(java.lang.Object[]) exclude"); generateAndTest( testEnvironment, options, ExpectedTests.DONT_CARE, ExpectedTests.SOME, coverageChecker); }</code><technical_language>changed</technical_language>

Target:
public void runBadCollectionSizeTest() { SystemTestEnvironment testEnvironment = systemTestEnvironmentManager.createTestEnvironment("bad-collection-size"); RandoopOptions options = createRandoopOptions(testEnvironment); options.addTestClass("collections.BadCollection"); options.setOption("generated_limit", "10"); options.setOption("output_limit", "10"); CoverageChecker coverageChecker = new CoverageChecker( options, "collections.BadCollection.add(java.lang.Object) exclude", "collections.BadCollection.addAll(java.util.Collection) exclude", "collections.BadCollection.clear() exclude", "collections.BadCollection.contains(java.lang.Object) exclude", "collections.BadCollection.containsAll(java.util.Collection) exclude", "collections.BadCollection.isEmpty() exclude", "collections.BadCollection.iterator() exclude", "collections.BadCollection.remove(java.lang.Object) exclude", "collections.BadCollection.removeAll(java.util.Collection) exclude", "collections.BadCollection.retainAll(java.util.Collection) exclude", "collections.BadCollection.toArray(java.lang.Object[]) exclude"); generateAndTest( testEnvironment, options, ExpectedTests.DONT_CARE, ExpectedTests.SOME, coverageChecker); }
Source:
<code>public DynamicConfigValidator(String configDir) { File config = new File(configDir); <START> if (config.exists()) { <END> this.setConfigDir(DynamicConfigHelpers.formatFilePath(config.getAbsolutePath())); } else { this.setConfigDir(DynamicConfigHelpers.formatFilePath(formatClassPath(configDir))); this.setConfigInClassPath(true); } }</code><technical_language>I feel this is place construct spring resource URL file:// resource://. this.configDir a URL file:// resource:// for loading security, variables, tables (all spring resource loader)</technical_language>

Target:
public DynamicConfigValidator(String configDir) { File config = new File(configDir); if (config.exists()) { this.setConfigDir(FILEPATH_PATTERN + DynamicConfigHelpers.formatFilePath(config.getAbsolutePath()) + HJSON_EXTN); } else { this.setConfigDir(CLASSPATH_PATTERN + DynamicConfigHelpers.formatFilePath(formatClassPath(configDir)) + HJSON_EXTN); } }
Source:
<code>private void checkAndUpdateBlacklist() { for (Map.Entry<InetSocketAddress, Long> blacklistedEntry : blacklistedHosts.entrySet()) { long backoffTimeMillis = TimeUnit.SECONDS.toMillis(config.unresponsiveHostBackoffTimeSeconds()); if (blacklistedEntry.getValue() + backoffTimeMillis < System.currentTimeMillis()) { InetSocketAddress host = blacklistedEntry.getKey(); if (isHostHealthy(host)) { blacklistedHosts.remove(host); log.error("Added host back into the pool after a waiting period and successful health check.", <START> SafeArg.of("host", host)); <END> } } } }</code><technical_language>change this info</technical_language>

Target:
private void checkAndUpdateBlacklist() { for (Map.Entry<InetSocketAddress, Long> blacklistedEntry : blacklistedHosts.entrySet()) { long backoffTimeMillis = TimeUnit.SECONDS.toMillis(config.unresponsiveHostBackoffTimeSeconds()); if (blacklistedEntry.getValue() + backoffTimeMillis < System.currentTimeMillis()) { InetSocketAddress host = blacklistedEntry.getKey(); if (isHostHealthy(host)) { blacklistedHosts.remove(host); log.info("Added host back into the pool after a waiting period and successful health check.", SafeArg.of("host", host)); } } } }
Source:
<code>private void validateURL(HttpServletRequest request, String url) { String proxyBase = GeoServerExtensions.getProperty(PROXY_BASE_URL); if(proxyBase != null) { if(!url.startsWith(proxyBase)) { throw new IllegalArgumentException("Invalid url requested, the demo requests should be hitting: " + proxyBase); } } String requestedUrl = request.getRequestURL().toString(); if(!requestedUrl.endsWith(TEST_WFS_POST_PATH)) { throw new IllegalStateException("Unepected, the TestWfsPost was accessed by a path not ending with TestWfsPost: " + requestedUrl); <START> } <END> String base = requestedUrl.substring(0, requestedUrl.lastIndexOf(TEST_WFS_POST_PATH)); if(!url.startsWith(base)) { throw new IllegalArgumentException("Invalid url requested, the demo requests should be hitting: " + base); } }</code><technical_language>While I agree this servlet moved in 10+ years - I I this check is required/useful? I more focused urlString (since is opening a connection to)</technical_language>

Target:
private void validateURL(HttpServletRequest request, String url) { String proxyBase = GeoServerExtensions.getProperty(PROXY_BASE_URL); if(proxyBase != null) { if(!url.startsWith(proxyBase)) { throw new IllegalArgumentException("Invalid url requested, the demo requests should be hitting: " + proxyBase); } } else { String requestedUrl = request.getRequestURL().toString(); if(!requestedUrl.endsWith(TEST_WFS_POST_PATH)) { throw new IllegalStateException("Unepected, the TestWfsPost was accessed by a path not ending with TestWfsPost: " + requestedUrl); } String base = requestedUrl.substring(0, requestedUrl.lastIndexOf(TEST_WFS_POST_PATH)); if(!url.startsWith(base)) { throw new IllegalArgumentException("Invalid url requested, the demo requests should be hitting: " + base); } } }