auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected HeaderParams writeHeader( Transport transport, HeaderParams params, byte version) { transport.writeByte(HotRodConstants.REQUEST_MAGIC); transport.writeVLong(params.messageId(MSG_ID.incrementAndGet()).messageId); transport.writeByte(version); transport.writeByte(params.opCode); transport.writeArray(params.cacheName); int flagInt = 0; if (params.flags != null) { for (Flag flag : params.flags) { <START> flagInt = flag.getFlagInt() | flagInt; <END> } } transport.writeVInt(flagInt); transport.writeByte(params.clientIntel); transport.writeVInt(params.topologyId.get()); getLog().tracef("Wrote header for message %d. Operation code: %#04x. Flags: %#x", params.messageId, params.opCode, flagInt); return params; }</code><technical_language>Extract method</technical_language>

Target:
protected HeaderParams writeHeader( Transport transport, HeaderParams params, byte version) { transport.writeByte(HotRodConstants.REQUEST_MAGIC); transport.writeVLong(params.messageId(MSG_ID.incrementAndGet()).messageId); transport.writeByte(version); transport.writeByte(params.opCode); transport.writeArray(params.cacheName); int joinedFlags = HeaderParams.joinFlags(params.flags); transport.writeVInt(joinedFlags); transport.writeByte(params.clientIntel); transport.writeVInt(params.topologyId.get()); if (trace) getLog().tracef("Wrote header for message %d. Operation code: %#04x. Flags: %#x", params.messageId, params.opCode, joinedFlags); return params; }
Source:
<code>@Override public void clearFeatures() { map.getOverlays().clear(); <START> map.getOverlays().add(new AttributionOverlay(getContext())); <END> map.getOverlays().add(new MapEventsOverlay(this)); map.getOverlays().add(myLocationOverlay); map.invalidate(); features.clear(); }</code><technical_language>duplicated work need do set view in clearFeatures onCreateView (this line line for instance). I good extract this a shared method run inconsistencies in future. sense</technical_language>

Target:
@Override public void clearFeatures() { map.getOverlays().clear(); addAttributionAndMapEventsOverlays(); map.getOverlays().add(myLocationOverlay); map.invalidate(); features.clear(); }
Source:
<code>public void onEventMainThread(DownloadEvent event) { Log.d(TAG, "onEventMainThread() called with: " + "event = [" + event + "]"); DownloaderUpdate update = event.update; <START> if (isUpdatingFeeds != update.feedIds.length > 0) { <END> getActivity().invalidateOptionsMenu(); } }</code><technical_language>Refactoring suggestion: centralize update check condition a more descriptive method shared fragments, e.g., java if (event.hasFeedsUpdateStatusChanged(isUpdatingFeeds)) {</technical_language>

Target:
public void onEventMainThread(DownloadEvent event) { Log.d(TAG, "onEventMainThread() called with: " + "event = [" + event + "]"); if (event.hasChangedFeedUpdateStatus(isUpdatingFeeds)) { getActivity().invalidateOptionsMenu(); } }
Source:
<code>public Map<IPath, RepositoryMapping> getRepositoryMappings() { <START> return mappings; <END> }</code><technical_language>want return a read-only view of mappings</technical_language>

Target:
public final Map<IPath, RepositoryMapping> getRepositoryMappings() { return mappings; }
Source:
<code>public void testReadingAllEntries() { writeBulkSets(); List<Integer> matches = storage.getIDsForValues(new String[]{}, new String[]{}); Set<Integer> expectedMatches = getIdsFromModels(tenSizesOfMensNikes); expectedMatches.addAll(getIdsFromModels(eightSizesOfWomensNikes)); expectedMatches.addAll(getIdsFromModels(fiveSizesOfMensVans)); <START> Assert.assertEquals("Failed index match [brand,style][nike,mens]", expectedMatches, new HashSet<>(matches)); <END> }</code><technical_language>I this assert wrong text</technical_language>

Target:
public void testReadingAllEntries() { writeBulkSets(); List<Integer> matches = storage.getIDsForValues(new String[0], new String[0]); Set<Integer> expectedMatches = getIdsFromModels(tenSizesOfMensNikes); expectedMatches.addAll(getIdsFromModels(eightSizesOfWomensNikes)); expectedMatches.addAll(getIdsFromModels(fiveSizesOfMensVans)); Assert.assertEquals("Failed index match for all entries", expectedMatches, new HashSet<>(matches)); }
Source:
<code>public void deleteAllDLCMessages() { String deletingMessageID = null; try { deletingMessageID = driver.findElement(By.xpath(UIElementMapper.getInstance() .getElement("mb.dlc.first.message.id"))).getText(); if(StringUtils.isNotBlank(deletingMessageID)) { log.info("delete all dlc messages"); driver.findElement(By.xpath(UIElementMapper.getInstance() .getElement("mb.dlc.browse.table.choose.all.box.xpath"))) .click(); driver.findElement(By.xpath(UIElementMapper.getInstance() .getElement("mb.dlc.browse.table.delete.button"))).click(); driver.findElement(By.xpath(UIElementMapper.getInstance() .getElement("mb.dlc.browse.function.confirm"))).click(); driver.findElement(By.xpath(UIElementMapper.getInstance() .getElement("mb.dlc.browse.function.success"))).click(); } }catch (Exception e) { <START> log.error("unable to find any valid messages in dead letter channel."); <END> } }</code><technical_language>Do need throw exception here</technical_language>

Target:
public void deleteAllDLCMessages() { WebElement dlcTable = driver.findElement(By.xpath(UIElementMapper.getInstance() .getElement("mb.dlc.browse.content.table"))); List<WebElement> allDlcRows = dlcTable.findElements(By.tagName("tr")); if(allDlcRows.size() > 0) { log.info("delete all dlc messages"); driver.findElement(By.xpath(UIElementMapper.getInstance() .getElement("mb.dlc.browse.table.choose.all.box.xpath"))) .click(); driver.findElement(By.xpath(UIElementMapper.getInstance() .getElement("mb.dlc.browse.table.delete.button"))) .click(); driver.findElement(By.xpath(UIElementMapper.getInstance() .getElement("mb.dlc.browse.function.confirm"))).click(); driver.findElement(By.xpath(UIElementMapper.getInstance() .getElement("mb.dlc.browse.function.success"))).click(); } }
Source:
<code>public static void teardown() { if (threadPoolSize != null) { System.setProperty("org.codice.ddf.system.threadPoolSize", threadPoolSize); } if (cipherSuites != null) { <START> System.setProperty("https.cipherSuites", cipherSuites); <END> } else { System.clearProperty("https.cipherSuites"); } if (protocols != null) { System.setProperty("https.protocols", protocols); } else { System.clearProperty("https.protocols"); } }</code><technical_language>clear property if start with</technical_language>

Target:
public static void teardown() { if (threadPoolSize != null) { System.setProperty("org.codice.ddf.system.threadPoolSize", threadPoolSize); } else { System.clearProperty("org.codice.ddf.system.threadPoolSize"); } if (cipherSuites != null) { System.setProperty("https.cipherSuites", cipherSuites); } else { System.clearProperty("https.cipherSuites"); } if (protocols != null) { System.setProperty("https.protocols", protocols); } else { System.clearProperty("https.protocols"); } }
Source:
<code>protected void simulateError(int hostNumber, Result result, Config config) { PrimingRequestBuilder builder = PrimingRequest.queryBuilder() .withQuery("mock query") <START> .withThen(then().withResult(result)); <END> if (config != null) builder = builder.withThen(then().withConfig(config)); scassandras.node(hostNumber).primingClient().prime(builder.build()); }</code><technical_language>Guessing test failures do this, is odd functionaly same. issue scassandra...diving.</technical_language>

Target:
protected void simulateError(int hostNumber, Result result, Config config) { PrimingRequest.Then.ThenBuilder then = then().withResult(result); PrimingRequestBuilder builder = PrimingRequest.queryBuilder().withQuery("mock query"); if (config != null) then = then.withConfig(config); builder = builder.withThen(then); scassandras.node(hostNumber).primingClient().prime(builder.build()); }
Source:
<code><START> private static final ModelContext getModelContext() { <END> return Utils.getComponent(ModelContext.class); }</code><technical_language>needs this method static</technical_language>

Target:
private final ModelContext getModelContext() { return Utils.getComponent(ModelContext.class); }
Source:
<code>public void shouldDecreaseIdleWhenClosedInsidePool() throws Throwable { Channel channel = newChannel(); tracker.channelCreated( channel, null ); assertEquals( 1, tracker.inUseChannelCount( address ) ); assertEquals( 0, tracker.idleChannelCount( address ) ); tracker.channelReleased( channel ); assertEquals( 0, tracker.inUseChannelCount( address ) ); assertEquals( 1, tracker.idleChannelCount( address ) ); <START> channel.close(); <END> assertEquals( 0, tracker.inUseChannelCount( address ) ); assertEquals( 0, tracker.idleChannelCount( address ) ); }</code><technical_language>channel.close().sync();</technical_language>

Target:
public void shouldDecreaseIdleWhenClosedInsidePool() throws Throwable { Channel channel = newChannel(); tracker.channelCreated( channel, null ); assertEquals( 1, tracker.inUseChannelCount( address ) ); assertEquals( 0, tracker.idleChannelCount( address ) ); tracker.channelReleased( channel ); assertEquals( 0, tracker.inUseChannelCount( address ) ); assertEquals( 1, tracker.idleChannelCount( address ) ); channel.close().sync(); assertEquals( 0, tracker.inUseChannelCount( address ) ); assertEquals( 0, tracker.idleChannelCount( address ) ); }
Source:
<code>public String getEntityType() { <START> return ET_UNSUPPORTED; <END> }</code><technical_language>relevant return null build entityType</technical_language>

Target:
public String getEntityType() { if (value.entityType == null) { return ET_UNSUPPORTED; } String[] parts = value.entityType.split("-"); for(int i = 0; i < parts.length; i++) { parts[i] = StringUtils.capitalize(parts[i]); } return "<LINK_0>" + StringUtils.join(parts); }
Source:
<code>public FormulaDto save(final FormulaDto formulaDto) { Formula formula = FormulaUtils.convertToFormula(formulaDto); <START> formula = this.daoFactory.getFormulaDAO().save(formula); <END> final FormulaDto result = FormulaUtils.convertToFormulaDto(formula); return result; }</code><technical_language>@nahuel-soldevilla hibernate set id object transaction is committed</technical_language>

Target:
public FormulaDto save(final FormulaDto formulaDto) { final Formula formula = FormulaUtils.convertToFormula(formulaDto); this.daoFactory.getFormulaDAO().save(formula); final FormulaDto result = FormulaUtils.convertToFormulaDto(formula); return result; }
Source:
<code>protected static GenotypesContext fixGenotypes(final GenotypesContext originals, final List<Allele> originalAlleles, final List<Allele> newAlleles) { if (originalAlleles.equals(newAlleles)) { return originals; } if (originalAlleles.size() != newAlleles.size()) { throw new IllegalStateException("Error in allele lists: the original and new allele lists are not the same length: " + originalAlleles.toString() + " / " + newAlleles.toString()); } final Map<Allele, Allele> alleleMap = new HashMap<>(); for (int idx = 0; idx < originalAlleles.size(); idx++) { alleleMap.put(originalAlleles.get(idx), newAlleles.get(idx)); } final GenotypesContext fixedGenotypes = GenotypesContext.create(originals.size()); for (final Genotype genotype : originals) { final List<Allele> fixedAlleles = new ArrayList<>(); for (final Allele allele : genotype.getAlleles()) { if (allele.isSymbolic() || allele.isNoCall()) { fixedAlleles.add(allele); } else { <START> Allele newAllele = alleleMap.get(allele); <END> if (newAllele == null) { throw new IllegalStateException("Allele not found: " + allele.toString() + ", " + originalAlleles + "/ " + newAlleles); } fixedAlleles.add(newAllele); } } fixedGenotypes.add(new GenotypeBuilder(genotype).alleles(fixedAlleles).make()); } return fixedGenotypes; }</code><technical_language>need for this check</technical_language>

Target:
protected static GenotypesContext fixGenotypes(final GenotypesContext originals, final List<Allele> originalAlleles, final List<Allele> newAlleles) { if (originalAlleles.equals(newAlleles)) { return originals; } if (originalAlleles.size() != newAlleles.size()) { throw new IllegalStateException("Error in allele lists: the original and new allele lists are not the same length: " + originalAlleles.toString() + " / " + newAlleles.toString()); } final Map<Allele, Allele> alleleMap = new HashMap<>(); for (int idx = 0; idx < originalAlleles.size(); idx++) { alleleMap.put(originalAlleles.get(idx), newAlleles.get(idx)); } final GenotypesContext fixedGenotypes = GenotypesContext.create(originals.size()); for (final Genotype genotype : originals) { final List<Allele> fixedAlleles = new ArrayList<>(); for (final Allele allele : genotype.getAlleles()) { if (allele.isNoCall()) { fixedAlleles.add(allele); } else { Allele newAllele = alleleMap.get(allele); if (newAllele == null) { throw new IllegalStateException("Allele not found: " + allele.toString() + ", " + originalAlleles + "/ " + newAlleles); } fixedAlleles.add(newAllele); } } fixedGenotypes.add(new GenotypeBuilder(genotype).alleles(fixedAlleles).make()); } return fixedGenotypes; }
Source:
<code><START> public ActionMetadataProviderGenerator( <END> TypeOracle typeOracle, Logger logger, Provider<VelocityContext> velocityContextProvider, VelocityEngine velocityEngine, GeneratorUtil generatorUtil, EventBus eventBus) { super(typeOracle, logger, velocityContextProvider, velocityEngine, generatorUtil); eventBus.register(this); }</code><technical_language>rm public</technical_language>

Target:
ActionMetadataProviderGenerator(TypeOracle typeOracle, Logger logger, Provider<VelocityContext> velocityContextProvider, VelocityEngine velocityEngine, GeneratorUtil generatorUtil, EventBus eventBus) { super(typeOracle, logger, velocityContextProvider, velocityEngine, generatorUtil); eventBus.register(this); }
Source:
<code>List<File> parseGroovyScripts( final String value ) throws ManipulationException { if ( isEmpty( value ) ) { return Collections.emptyList(); } else { final List<File> result = new ArrayList<>(); logger.debug( "Processing groovy scripts ", value ); try { final String[] scripts = value.split( "," ); for ( final String script : scripts ) { File found; logger.info( "Processing groovy script {}", script ); if ( script.startsWith( "http:" ) || script.startsWith( "file:" ) ) { URL url = new URL( script ); logger.info( "Attempting to read URL {}", url ); <START> found = fileIO.resolveURL( url ); <END> } else { final ArtifactRef ar = SimpleArtifactRef.parse( script ); logger.info( "Attempting to read GAV with classifier and type ", ar.asProjectVersionRef(), ar.getClassifier(), ar.getType() ); found = modelBuilder.resolveRawFile( ar ); } result.add( found ); } } catch ( IOException e ) { throw new ManipulationException( "Unable to parse groovyScripts", e ); } return result; } }</code><technical_language>I this is needed</technical_language>

Target:
List<File> parseGroovyScripts( final String value ) throws ManipulationException { if ( isEmpty( value ) ) { return Collections.emptyList(); } else { final List<File> result = new ArrayList<>(); logger.debug( "Processing groovy scripts ", value ); try { final String[] scripts = value.split( "," ); for ( final String script : scripts ) { File found; if ( script.startsWith( "http:" ) || script.startsWith( "https:" ) || script.startsWith( "file:" )) { logger.info( "Attempting to read URL ", script ); found = fileIO.resolveURL( new URL( fixFileURL( script ) ) ); } else { final ArtifactRef ar = SimpleArtifactRef.parse( script ); logger.info( "Attempting to read GAV with classifier and type ", ar.asProjectVersionRef(), ar.getClassifier(), ar.getType() ); found = modelBuilder.resolveRawFile( ar ); } result.add( found ); } } catch ( IOException e ) { throw new ManipulationException( "Unable to parse groovyScripts", e ); } return result; } }
Source:
<code>public void getAllChannelsShouldReturnSingleElementListWhenThereIsOneChannel() { List<ChannelEntity> channels = Arrays.asList(facebookEntity); Collection<ChannelDTO> expected = Arrays.asList(facebookDto); given(channelRepository.findAll()).willReturn(channels); given(modelMapper.map(channels, CHANNEL_DTO_LIST_TYPE)).willReturn(expected); Collection<ChannelDTO> result = channelService.getAllChannels(); assertEquals(result, expected); <START> then(channelRepository).should(times(1)).findAll(); <END> }</code><technical_language>modelMapper invocation is verified</technical_language>

Target:
public void getAllChannelsShouldReturnSingleElementListWhenThereIsOneChannel() { List<ChannelEntity> channels = Arrays.asList(facebookEntity); Collection<ChannelDTO> expected = Arrays.asList(facebookDto); given(channelRepository.findAll()).willReturn(channels); given(modelMapper.map(channels, CHANNEL_DTO_LIST_TYPE)).willReturn(expected); Collection<ChannelDTO> result = channelService.getAllChannels(); assertEquals(result, expected); then(channelRepository).should().findAll(); then(modelMapper).should().map(channels, CHANNEL_DTO_LIST_TYPE); }
Source:
<code><START> public ColorStateList getTextColor() { <END> return super.getTextColors(); }</code><technical_language>this return int ? match setter</technical_language>

Target:
public int getTextColor() { return super.getCurrentTextColor(); }
Source:
<code>public static Configuration grabConfig(File content) { try { <START> final ArrayList<String> strings = new ArrayList<>( <END> Arrays.asList("java", "-jar", getNextFlowTargetFile().getAbsolutePath(), "config", "-properties")); final String join = Joiner.on(" ").join(strings); LOG.info("running: " + join); final ImmutablePair<String, String> execute = Utilities.executeCommand(join, content.getParentFile()); String stdout = execute.getLeft(); Properties properties = new Properties(); properties.load(new StringReader(stdout)); return ConfigurationConverter.getConfiguration(properties); } catch (RuntimeException | IOException e) { LOG.error("Problem running NextFlow: ", e); throw new NextflowParsingException("Could not run NextFlow", e); } }</code><technical_language>Arrays.asList directly, e.g., final List<String> strings = Arrays.asList(..</technical_language>

Target:
public static Configuration grabConfig(File content) { try { final List<String> strings = Arrays.asList("java", "-jar", getNextFlowTargetFile().getAbsolutePath(), "config", "-properties"); final String join = Joiner.on(" ").join(strings); LOG.info("running: " + join); final ImmutablePair<String, String> execute = Utilities.executeCommand(join, content.getParentFile()); String stdout = execute.getLeft(); Properties properties = new Properties(); properties.load(new StringReader(stdout)); return ConfigurationConverter.getConfiguration(properties); } catch (RuntimeException | IOException e) { LOG.error("Problem running NextFlow: ", e); throw new NextflowParsingException("Could not run NextFlow", e); } }
Source:
<code>protected Short getNetworkAccessPointTypeCode(String hostAddress) { if (InetAddressValidator.getInstance().isValid(hostAddress)) { return AuditTransformConstants.NETWORK_ACCESSOR_PT_TYPE_CODE_IP; <START> } else { <END> return AuditTransformConstants.NETWORK_ACCESSOR_PT_TYPE_CODE_NAME; } }</code><technical_language>This is place put "else" "if" returns -- for consistency, change this else statement</technical_language>

Target:
protected Short getNetworkAccessPointTypeCode(String hostAddress) { if (InetAddressValidator.getInstance().isValid(hostAddress)) { return AuditTransformConstants.NETWORK_ACCESSOR_PT_TYPE_CODE_IP; } return AuditTransformConstants.NETWORK_ACCESSOR_PT_TYPE_CODE_NAME; }
Source:
<code>public void testListTableNamesWithEmptyElement() throws IOException { try (Admin admin = getConnection().getAdmin()) { sharedTestEnv.createTable(sharedTestEnv.newTestTableName()); Exception actualError = null; <START> try { <END> TableName[] tableNames = admin.listTableNames((Pattern) null); assertTrue(tableNames.length > 0); } catch (Exception e) { actualError = e; } assertNull(actualError); try { admin.listTableNames((String) null); } catch (Exception e) { actualError = e; } assertNotNull(actualError); assertTrue(actualError instanceof NullPointerException); actualError = null; try { assertEquals(0, admin.listTableNames("").length); } catch (Exception e) { actualError = e; } assertNull(actualError); } }</code><technical_language>I try is necessary here. please move actualError assertTrue</technical_language>

Target:
public void testListTableNamesWithEmptyElement() throws IOException { try (Admin admin = getConnection().getAdmin()) { sharedTestEnv.createTable(sharedTestEnv.newTestTableName()); TableName[] tableNames = admin.listTableNames((Pattern) null); assertTrue(tableNames.length > 0); Exception actualError = null; try { admin.listTableNames((String) null); } catch (Exception e) { actualError = e; } assertNotNull(actualError); assertTrue(actualError instanceof NullPointerException); assertEquals(0, admin.listTableNames("").length); } }
Source:
<code>private void fillDefaults(Map<String, Object> argMap) { for(ParserArgument arg : arguments.values()) { if (!argMap.containsKey(arg.getName())) { if (arg.getDefaultValue() != null) { argMap.put( arg.getName(), Util.getObjectValueByString(arg.getConvert(), arg.getDefaultValue()) ); } if (arg.getType() == ArgumentType.no_argument) { argMap.put(arg.getName(), arg.isValue()); <START> } <END> } } }</code><technical_language>need this conditional. if I put no_argument default False, True converter Boolean I achieve in properties file in special in implementation, no</technical_language>

Target:
private void fillDefaults(Map<String, Object> argMap) { for(ParserArgument arg : arguments.values()) { if (!argMap.containsKey(arg.getName())) { if (arg.getDefaultValue() != null) { argMap.put( arg.getName(), Util.getObjectValueByString(arg.getConvert(), arg.getDefaultValue()) ); } } } }
Source:
<code>public void toJson() throws Exception { Person person = new Person("Emil", 27); String got = gson.toJson(person); String want = "{\"name\":\"Emil\",\"age\":27}"; <START> assertThat(got, deepEquals(want)); <END> }</code><technical_language>assertThat(got, is(want));</technical_language>

Target:
public void toJson() throws Exception { Person person = new Person("Emil", 27); String got = json.toJson(person); String want = "{\"name\":\"Emil\",\"age\":27}"; assertThat(got, is(want)); }
Source:
<code>public Embedding deserialize(JsonNode rootNode, Configuration configuration) { String data = rootNode.get("data").asText(); <START> JsonNode media = rootNode.get("media"); <END> String mimeType; if (media != null) { mimeType = media.get("type").asText(); } else { mimeType = rootNode.get("mime_type").asText(); } Embedding embedding = new Embedding(mimeType, data); storeEmbedding(embedding, configuration.getEmbeddingDirectory()); return embedding; }</code><technical_language>extract media static attribute</technical_language>

Target:
public Embedding deserialize(JsonNode rootNode, Configuration configuration) { String data = rootNode.get("data").asText(); String mimeType = findMimeType(rootNode); Embedding embedding = new Embedding(mimeType, data); storeEmbedding(embedding, configuration.getEmbeddingDirectory()); return embedding; }
Source:
<code>public static DataHandler reassembledStringMessage2(final int streamId) throws Exception { return (buffer, offset, length, header) -> { final byte[] data = new byte[length]; buffer.getBytes(offset, data); System.out.format( "message to stream %d from session %x term id %x term offset %d (%d@%d)%n", streamId, header.sessionId(), header.termId(), header.termOffset(), length, offset); if (length != 9000) { try { <START> throw new Exception( <END> "Received message is not assembled properly, received lenth " + length + " Expecting " + "9000"); } catch (final Exception e) { e.printStackTrace(); } } }; }</code><technical_language>throw immediately catch</technical_language>

Target:
public static DataHandler reassembledStringMessage2(final int streamId) throws Exception { return (buffer, offset, length, header) -> { final byte[] data = new byte[length]; buffer.getBytes(offset, data); System.out.format( "message to stream %d from session %x term id %x term offset %d (%d@%d)%n", streamId, header.sessionId(), header.termId(), header.termOffset(), length, offset); if (length != 9000) { System.out.format("Received message was not assembled properly; received length was %d," + " but was expecting 9000%n", length); } }; }
Source:
<code>public void close() throws IOException { <START> workbook.write(new FileOutputStream(target)); <END> workbook.close(); }</code><technical_language>write call throw exception results in close called</technical_language>

Target:
public void close() throws IOException { try { workbook.write(Files.newOutputStream(target)); } catch (IOException e) { throw e; } finally { workbook.close(); } }
Source:
<code>private void populateTagsInFilterPanel(Target target) { Set<String> tags = new LinkedHashSet<>(); <START> SiteNode siteNode = target.getStartNode(); <END> if (siteNode != null) { this.addTagsInFilterPanel(siteNode, tags); } else if (target.getContext() != null || target.isInScopeOnly()) { List<SiteNode> nodes = Collections.emptyList(); if (target.isInScopeOnly()) { nodes = Model.getSingleton().getSession().getTopNodesInScopeFromSiteTree(); } else if (target.getContext() != null) { nodes = target.getContext().getTopNodesInContextFromSiteTree(); } for (SiteNode node : nodes) { this.addTagsInFilterPanel(node, tags); } } this.setAllTags(new ArrayList<String>(tags)); }</code><technical_language>target null</technical_language>

Target:
private void populateTagsInFilterPanel(Target target) { Set<String> tags = new LinkedHashSet<>(); if (target != null) { SiteNode siteNode = target.getStartNode(); if (siteNode != null) { this.addTagsInFilterPanel(siteNode, tags); } else if (target.getContext() != null || target.isInScopeOnly()) { List<SiteNode> nodes = Collections.emptyList(); if (target.isInScopeOnly()) { nodes = Model.getSingleton().getSession().getTopNodesInScopeFromSiteTree(); } else if (target.getContext() != null) { nodes = target.getContext().getTopNodesInContextFromSiteTree(); } for (SiteNode node : nodes) { this.addTagsInFilterPanel(node, tags); } } } this.setAllTags(new ArrayList<String>(tags)); }
Source:
<code>public Collection<? extends Action> getProjectActions() { <START> return Collections.singleton(new CucumberReportProjectAction(run.getParent(), title, directoryQualifier)); <END> }</code><technical_language>Is a change allows define more instance of this plugin configuration page</technical_language>

Target:
public Collection<? extends Action> getProjectActions() { return Collections.singleton(new CucumberReportProjectAction(run.getParent(), getDisplayName(), directorySuffix)); }
Source:
<code>private <T> void setValueInternal(IPreferenceStore store, String name, T value, Function<String, T> prefGetter, BiConsumer<String, T> prefSetter) { <START> Map<String, Object> knownValues = savedPreferences.get(store); <END> if (knownValues == null) { knownValues = new HashMap<>(); savedPreferences.put(store, knownValues); } if (!knownValues.containsKey(name)) { knownValues.put(name, prefGetter.apply(name)); } prefSetter.accept(name, value); }</code><technical_language>shortened to: Map<String, Object> knownValues = savedPreferences.computeIfAbsent(store, key -> new HashMap<>());</technical_language>

Target:
private <T> void setValueInternal(IPreferenceStore store, String name, T value, Function<String, T> prefGetter, BiConsumer<String, T> prefSetter) { Map<String, Object> knownValues = savedPreferences.computeIfAbsent(store, key -> new HashMap<>()); if (!knownValues.containsKey(name)) { knownValues.put(name, prefGetter.apply(name)); } prefSetter.accept(name, value); }
Source:
<code>private <T> Publisher<? extends T> readResponseBody(Request request, ClientResponse response, Class<T> responseType) { if (RawActionResponse.class.equals(responseType)) { return Mono.just((T) new RawActionResponse(response)); } if (response.statusCode().is5xxServerError()) { throw new HttpClientErrorException(response.statusCode(), String.format("%s request to %s returned error code %s.", request.getMethod(), request.getEndpoint(), response.statusCode().value())); } <START> return response.body(BodyExtractors.toDataBuffers()).flatMap(it -> { <END> try { String content = StreamUtils.copyToString(it.asInputStream(true), StandardCharsets.UTF_8); try { XContentParser contentParser = XContentType .fromMediaTypeOrFormat( response.headers().contentType().map(MediaType::toString).orElse(XContentType.JSON.mediaType())) .xContent() .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, content); Method fromXContent = ReflectionUtils.findMethod(responseType, "fromXContent", XContentParser.class); return Mono.just((T) ReflectionUtils.invokeMethod(fromXContent, responseType, contentParser)); } catch (Exception parseFailure) { try { XContentParser errorParser = XContentType .fromMediaTypeOrFormat( response.headers().contentType().map(MediaType::toString).orElse(XContentType.JSON.mediaType())) .xContent() .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, content); return Mono.error(BytesRestResponse.errorFromXContent(errorParser)); } catch (Exception errorParseFailure) { return Mono.error(new ElasticsearchStatusException("Unable to parse response body", RestStatus.fromCode(response.statusCode().value()))); } } } catch (IOException e) { throw new DataAccessResourceFailureException("Error parsing XContent.", e); } }); }</code><technical_language>toDataBuffers streams response chunks resulting in multiple contents. this await full response completion decode bytes a single String</technical_language>

Target:
private <T> Publisher<? extends T> readResponseBody(Request request, ClientResponse response, Class<T> responseType) { if (RawActionResponse.class.equals(responseType)) { return Mono.just(responseType.cast(RawActionResponse.create(response))); } if (response.statusCode().is5xxServerError()) { return handleServerError(request, response); } return response.body(BodyExtractors.toMono(byte[].class)) .map(it -> new String(it, StandardCharsets.UTF_8)) .flatMap(content -> doDecode(response, responseType, content)); }
Source:
<code>public void testSendAndReceive() throws Exception { ChannelRegistry registry = getRegistry(); DirectChannel moduleOutputChannel = new DirectChannel(); QueueChannel moduleInputChannel = new QueueChannel(); QueueChannel tapChannel = new QueueChannel(); registry.createOutbound("foo.0", moduleOutputChannel, false); registry.createInbound("foo.0", moduleInputChannel, ALL, false); registry.tap("tapper", "foo.0", tapChannel); Message<?> message = MessageBuilder.withPayload("foo").setHeader(MessageHeaders.CONTENT_TYPE, "foo/bar").build(); boolean tapSuccess = false; boolean retried = false; while (!tapSuccess) { moduleOutputChannel.send(message); Message<?> inbound = moduleInputChannel.receive(5000); assertNotNull(inbound); assertEquals("foo", new String((byte[]) inbound.getPayload())); assertNull(inbound.getHeaders().get(ChannelRegistrySupport.ORIGINAL_CONTENT_TYPE_HEADER)); assertEquals("foo/bar", inbound.getHeaders().get(MessageHeaders.CONTENT_TYPE)); Message<?> tapped = tapChannel.receive(5000); if (tapped == null) { assertFalse("Failed to receive tap after retry", retried); retried = true; continue; } tapSuccess = true; assertEquals("foo", new String((byte[]) tapped.getPayload())); assertNull(tapped.getHeaders().get(ChannelRegistrySupport.ORIGINAL_CONTENT_TYPE_HEADER)); assertEquals("foo/bar", tapped.getHeaders().get(MessageHeaders.CONTENT_TYPE)); } registry.deleteInbound("foo.0"); registry.deleteOutbound("foo.0"); <START> } <END></code><technical_language>needs registry.deleteInbound("tapper");</technical_language>

Target:
public void testSendAndReceive() throws Exception { ChannelRegistry registry = getRegistry(); DirectChannel moduleOutputChannel = new DirectChannel(); QueueChannel moduleInputChannel = new QueueChannel(); QueueChannel tapChannel = new QueueChannel(); registry.createOutbound("foo.0", moduleOutputChannel, false); registry.createInbound("foo.0", moduleInputChannel, ALL, false); registry.tap("tapper", "foo.0", tapChannel); Message<?> message = MessageBuilder.withPayload("foo").setHeader(MessageHeaders.CONTENT_TYPE, "foo/bar").build(); boolean tapSuccess = false; boolean retried = false; while (!tapSuccess) { moduleOutputChannel.send(message); Message<?> inbound = moduleInputChannel.receive(5000); assertNotNull(inbound); assertEquals("foo", inbound.getPayload()); assertNull(inbound.getHeaders().get(ChannelRegistrySupport.ORIGINAL_CONTENT_TYPE_HEADER)); assertEquals("foo/bar", inbound.getHeaders().get(MessageHeaders.CONTENT_TYPE)); Message<?> tapped = tapChannel.receive(5000); if (tapped == null) { assertFalse("Failed to receive tap after retry", retried); retried = true; continue; } tapSuccess = true; assertEquals("foo", tapped.getPayload()); assertNull(tapped.getHeaders().get(ChannelRegistrySupport.ORIGINAL_CONTENT_TYPE_HEADER)); assertEquals("foo/bar", tapped.getHeaders().get(MessageHeaders.CONTENT_TYPE)); } registry.deleteInbound("foo.0"); registry.deleteOutbound("foo.0"); registry.deleteInbound("tapper"); }
Source:
<code>public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == CHOOSE_ACCOUNT_SSO) { importedAccount = null; try { AccountImporter.requestAuthToken(LoginDialogFragment.this, data); } catch (NextcloudFilesAppNotSupportedException e) { UiExceptionManager.showDialogForException(getActivity(), e); } } else if(requestCode == REQUEST_AUTH_TOKEN__SSO) { SingleSignOnAccount singleSignOnAccount = AccountImporter.extractSingleSignOnAccountFromResponse(data, getActivity()); accountAccessGranted(singleSignOnAccount); } } else if (resultCode == RESULT_CANCELED) { if (requestCode == CHOOSE_ACCOUNT_SSO) { Toast.makeText(getActivity(), "Unknown error.. please report!", Toast.LENGTH_LONG).show(); } else if (requestCode == REQUEST_AUTH_TOKEN__SSO) { try { AccountImporter.handleFailedAuthRequest(data); } catch (SSOException e) { UiExceptionManager.showDialogForException(getActivity(), e); } catch (Exception e) { Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show(); <START> e.printStackTrace(); <END> } } } }</code><technical_language>a log statement :)</technical_language>

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); AccountImporter.onActivityResult(requestCode, resultCode, data, LoginDialogFragment.this, new AccountImporter.IAccountAccessGranted() { @Override public void accountAccessGranted(SingleSignOnAccount account) { mUsernameView.setText(account.username); mPasswordView.setText(""); mOc_root_path_View.setText(account.url); mPasswordContainerView.setVisibility(View.GONE); mImageViewShowPwd.setVisibility(View.GONE); mCbDisableHostnameVerificationView.setVisibility(View.GONE); LoginDialogFragment.getInstance().importedAccount = account; attemptLogin(); } }); }
Source:
<code>public List<SimpleObject> searchNonCoded(UiSessionContext context, UiUtils ui, @SpringBean("emrApiProperties") EmrApiProperties emrApiProperties, @SpringBean("emrConceptService") EmrConceptService emrConceptService, @SpringBean("conceptService") ConceptService conceptService, @RequestParam("term") String query, @RequestParam(value = "start", defaultValue = "0") Integer start, @RequestParam(value = "size", defaultValue = "50") Integer size) throws Exception { <START> List<SimpleObject> ret = search(context, ui, emrApiProperties, emrConceptService, conceptService, query, null, null, start, size); <END> return ret; }</code><technical_language>Ah thanks for this. I return directly: java return search(context, ui, emrApiProperties, emrConceptService, conceptService, query, null, null, start, size); leave absolutely zero logic in deprecated function</technical_language>

Target:
public List<SimpleObject> searchNonCoded(UiSessionContext context, UiUtils ui, @SpringBean("emrApiProperties") EmrApiProperties emrApiProperties, @SpringBean("emrConceptService") EmrConceptService emrConceptService, @SpringBean("conceptService") ConceptService conceptService, @RequestParam("term") String query, @RequestParam(value = "start", defaultValue = "0") Integer start, @RequestParam(value = "size", defaultValue = "50") Integer size) throws Exception { return search(context, ui, emrApiProperties, emrConceptService, conceptService, query, null, null, start, size); }
Source:
<code>public void testParseFail() { List<JSONPathParser.FieldSpec> fields = new ArrayList<>(); try { final Parser<String, Object> jsonParser = new JSONPathParser(fields, true, null); final Map<String, Object> jsonMap = jsonParser.parse(notJson); } catch (Exception e) { <START> Assert.assertEquals(ParseException.class, e.getClass()); <END> return; } Assert.fail("Invalid JSON did not trigger ParseException."); }</code><technical_language>(non blocking) simply @Test(expected = ParseException.class) that, I forget exact name</technical_language>

Target:
public void testParseFail() { List<JSONPathParser.FieldSpec> fields = new ArrayList<>(); thrown.expect(ParseException.class); thrown.expectMessage("Unable to parse row [" + notJson + "]"); final Parser<String, Object> jsonParser = new JSONPathParser(fields, true, null); final Map<String, Object> jsonMap = jsonParser.parse(notJson); }
Source:
<code>public Map<String, String> getAllMappingUnderPath(String namespace, String path) { if (!_routingDataMap.containsKey(namespace)) { <START> throw new IllegalArgumentException( "Failed to get all mapping under path: Namespace " + namespace + " is not found!"); } return _routingDataMap.get(namespace).getAllMappingUnderPath(path); <END> }</code><technical_language>Nit: NoSuchElementException consistent other methods in MSD</technical_language>

Target:
public Map<String, String> getAllMappingUnderPath(String namespace, String path) { if (!_routingDataMap.containsKey(namespace)) { throw new NoSuchElementException( "Failed to get all mapping under path: Namespace " + namespace + " is not found!"); } return _routingDataMap.get(namespace).getAllMappingUnderPath(path); }
Source:
<code>public static Tip loadTip(int pId) { assert pId >= 1 && pId <= NUM_TIPS; String tipFileName = String.format(TIP_FILE_PATH_FORMAT, pId); InputStream tipsInputStream = TipLoader.class.getResourceAsStream(tipFileName); InputStreamReader tipsReader = new InputStreamReader(tipsInputStream); JSONTokener jsonTokener = new JSONTokener(tipsReader); JSONObject jsonObject = new JSONObject(jsonTokener); <START> Tip tip = new Tip(pId, jsonObject); <END> return tip; }</code><technical_language>input stream read in UTF-8 Characters: new InputStreamReader(..., StandardCharsets.UTF_8)</technical_language>

Target:
public static Tip loadTip(int pId) { assert pId >= 1 && pId <= NUM_TIPS; String tipFileName = String.format(TIP_FILE_PATH_FORMAT, pId); InputStream tipsInputStream = TipLoader.class.getResourceAsStream(tipFileName); InputStreamReader tipsReader = new InputStreamReader(tipsInputStream, StandardCharsets.UTF_8); JSONTokener jsonTokener = new JSONTokener(tipsReader); JSONObject jsonObject = new JSONObject(jsonTokener); Tip tip = new Tip(pId, jsonObject); return tip; }
Source:
<code>private List<List<Expression>> analyzeGroupBy(QuerySpecification node, Scope scope, List<Expression> outputExpressions) { List<Set<Expression>> computedGroupingSets = ImmutableList.of(); if (node.getGroupBy().isPresent()) { List<List<Set<Expression>>> enumeratedGroupingSets = node.getGroupBy().get().getGroupingElements().stream() .map(GroupingElement::enumerateGroupingSets) .collect(toImmutableList()); <START> checkGroupingElementCount(node.getGroupBy().get(), enumeratedGroupingSets); <END> computedGroupingSets = computeGroupingSetsCrossProduct(enumeratedGroupingSets, node.getGroupBy().get().isDistinct()); checkState(!computedGroupingSets.isEmpty(), "computed grouping sets cannot be empty"); } else if (hasAggregates(node)) { computedGroupingSets = ImmutableList.of(ImmutableSet.of()); } List<List<Expression>> analyzedGroupingSets = computedGroupingSets.stream() .map(groupingSet -> analyzeGroupingColumns(groupingSet, node, scope, outputExpressions)) .collect(toImmutableList()); analysis.setGroupingSets(node, analyzedGroupingSets); return analyzedGroupingSets; }</code><technical_language>this point, late. A single big CUBE generate a huge number of entries in enumeratedGroupingSets. This needs happen GroupingElement::enumerateGroupingSets is called above</technical_language>

Target:
private List<List<Expression>> analyzeGroupBy(QuerySpecification node, Scope scope, List<Expression> outputExpressions) { List<Set<Expression>> computedGroupingSets = ImmutableList.of(); if (node.getGroupBy().isPresent()) { checkGroupingSetsCount(node.getGroupBy().get()); List<List<Set<Expression>>> enumeratedGroupingSets = node.getGroupBy().get().getGroupingElements().stream() .map(GroupingElement::enumerateGroupingSets) .collect(toImmutableList()); computedGroupingSets = computeGroupingSetsCrossProduct(enumeratedGroupingSets, node.getGroupBy().get().isDistinct()); checkState(!computedGroupingSets.isEmpty(), "computed grouping sets cannot be empty"); } else if (hasAggregates(node)) { computedGroupingSets = ImmutableList.of(ImmutableSet.of()); } List<List<Expression>> analyzedGroupingSets = computedGroupingSets.stream() .map(groupingSet -> analyzeGroupingColumns(groupingSet, node, scope, outputExpressions)) .collect(toImmutableList()); analysis.setGroupingSets(node, analyzedGroupingSets); return analyzedGroupingSets; }
Source:
<code>private HashMap<String, String> arrayToMap(String[] input) { if (input == null || input.length == 0) { return new HashMap<String, String>(); } <START> HashMap<String, String> hm = new HashMap<String, String>(); <END> for (int i = 0; i < input.length; i++) { if (!"".equals(input[i].trim())) { hm.put(input[i], input[i]); } } return hm; }</code><technical_language>diamond operator RHS</technical_language>

Target:
private HashMap<String, String> arrayToMap(String[] input) { if (input == null || input.length == 0) { return new HashMap<String, String>(); } HashMap<String, String> hm = new HashMap<>(); for (int i = 0; i < input.length; i++) { if (!"".equals(input[i].trim())) { hm.put(input[i], input[i]); } } return hm; }
Source:
<code><START> public void sendMessage_namedDestination_doesNotSendFirebaseMessage() <END> { Message message = Mockito.mock(Message.class); MessageDestination namedMessageDestination = Mockito.mock(MessageDestination.class); User user = Mockito.mock(User.class); when(user.getNamedMessageDestination()).thenReturn(namedMessageDestination); service.sendNamedMessage(message, user); verify(mockFirebaseService, never()).sendMessage("Firebase-12345", message); }</code><technical_language>thought of this. For direct messages, send a notification, do anonymized device ID. consider sending SMS message for direct messages</technical_language>

Target:
public void sendMessage_namedDestination_doesNotSendFirebaseMessage() { Message message = Mockito.mock(Message.class); MessageDestination namedMessageDestination = Mockito.mock(MessageDestination.class); User user = Mockito.mock(User.class); when(user.getNamedMessageDestination()).thenReturn(namedMessageDestination); service.sendDirectMessage(message, user); verify(mockFirebaseService, never()).sendMessage(FIREBASE_REGISTRATION_TOKEN, message); }
Source:
<code>public void setPreferredApiVersion(@Nullable String availableApiVersions) { try { if(availableApiVersions == null) { this.preferredApiVersion = null; return; } JSONArray versionsArray = new JSONArray(availableApiVersions); Collection<ApiVersion> supportedApiVersions = new ArrayList<>(versionsArray.length()); for (int i = 0; i < versionsArray.length(); i++) { ApiVersion parsedApiVersion = ApiVersion.of(versionsArray.getString(i)); for (ApiVersion temp : NotesClient.SUPPORTED_API_VERSIONS) { <START> if (temp.compareTo(parsedApiVersion) == 0) { supportedApiVersions.add(parsedApiVersion); <END> break; } } } this.preferredApiVersion = Collections.max(supportedApiVersions); } catch (JSONException | NoSuchElementException e) { e.printStackTrace(); this.preferredApiVersion = null; } }</code><technical_language>compareTo is implemented equal-like functionality. This is intended get supported API versions. check major version of API. Example: server provides "1.4, 2.1". Then, chose "1.4", support major version "1" "2". Due backward/forward compatibility, implementation for "1.0" work "1.4" API endpoint. Example 2: server provides "0.2, 1.4" app implemented API for "0.2" "1.7". Then, chose "1.4" (since support major version "1"). Requests work, aware, result miss some fields defined in "1.4" in "1.7". (API 0.2 is a special case, major version of 0.2 is 0.2 0.)</technical_language>

Target:
public void setPreferredApiVersion(@Nullable String availableApiVersions) { try { if (availableApiVersions == null) { this.preferredApiVersion = null; return; } JSONArray versionsArray = new JSONArray(availableApiVersions); Collection<ApiVersion> supportedApiVersions = new HashSet<>(versionsArray.length()); for (int i = 0; i < versionsArray.length(); i++) { ApiVersion parsedApiVersion = ApiVersion.of(versionsArray.getString(i)); for (ApiVersion temp : NotesClient.SUPPORTED_API_VERSIONS) { if (temp.compareTo(parsedApiVersion) == 0) { supportedApiVersions.add(parsedApiVersion); break; } } } this.preferredApiVersion = Collections.max(supportedApiVersions); } catch (JSONException | NoSuchElementException e) { e.printStackTrace(); this.preferredApiVersion = null; } }
Source:
<code>protected void scanFile(XmlFile xmlFile) { evaluateAsList(actionsExpression, xmlFile.getNamespaceUnawareDocument()) .forEach(node -> { <START> List<Secondary> secondaries = new ArrayList<>(); <END> evaluateAsList(forwardsFromActionExpression, node).stream().skip(maximumForwards) .forEach(forward -> { Secondary secondary = new Secondary(forward, "Move this forward to another action."); secondaries.add(secondary); }); if (!secondaries.isEmpty()) { int cost = secondaries.size(); int numberForward = maximumForwards + cost; String message = "Reduce the number of forwards in this action from " + numberForward + " to at most " + maximumForwards + "."; reportIssue(XmlFile.nodeLocation(node), message, secondaries); } }); }</code><technical_language>instead of adding element list, a map build this list: java List<Secondary> secondaries = evaluateAsList(forwardsFromActionExpression, node).stream() .skip(maximumForwards) .map(forward -> new Secondary(forward, "Move this another action.")) .collect(Collectors.toList());</technical_language>

Target:
protected void scanFile(XmlFile xmlFile) { evaluateAsList(actionsExpression, xmlFile.getNamespaceUnawareDocument()) .forEach(this::checkAction); }