auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Gff3BaseData(final String contig, final String source, final String type, final int start, final int end, final Double score, final Strand strand, final int phase, final Map<String, List<String>> attributes) { this.contig = contig; this.source = source; this.type = type; this.start = start; this.end = end; this.score = score; this.phase = phase; this.strand = strand; this.attributes = Collections.unmodifiableMap(new LinkedHashMap<>(attributes)); this.id = Gff3Codec.extractSingleAttribute(attributes.get(ID_ATTRIBUTE_KEY)); this.name = Gff3Codec.extractSingleAttribute(attributes.get(NAME_ATTRIBUTE_KEY)); <START> this.aliases = attributes.containsKey(ALIAS_ATTRIBUTE_KEY)? attributes.get(ALIAS_ATTRIBUTE_KEY) : Collections.emptyList(); this.hashCode = computeHashCode(); <END> }</code><technical_language>suggestions here: 1. lost a linebreak I think. 2. getOrDefault instead of ternary</technical_language>

Target:
public Gff3BaseData(final String contig, final String source, final String type, final int start, final int end, final Double score, final Strand strand, final int phase, final Map<String, List<String>> attributes) { this.contig = contig; this.source = source; this.type = type; this.start = start; this.end = end; this.score = score; this.phase = phase; this.strand = strand; this.attributes = copyAttributesSafely(attributes); this.id = Gff3Codec.extractSingleAttribute(attributes.get(ID_ATTRIBUTE_KEY)); this.name = Gff3Codec.extractSingleAttribute(attributes.get(NAME_ATTRIBUTE_KEY)); this.aliases = attributes.getOrDefault(ALIAS_ATTRIBUTE_KEY, Collections.emptyList()); this.hashCode = computeHashCode(); }
Source:
<code>public boolean verify() throws ConstructorException { try { HttpUrl url = this.makeUrl("v1/verify"); <START> Builder builder = this.makeAuthorizedRequestBuilder(); <END> Request request = builder .url(url) .get() .build(); Response response = clientWithRetry.newCall(request).execute(); getResponseBody(response); return true; } catch (Exception exception) { throw new ConstructorException(exception); } }</code><technical_language>inline builder like: Request request = this.makeAuthorizedRequestBuilder() .url(url) ..</technical_language>

Target:
public boolean verify() throws ConstructorException { try { HttpUrl url = this.makeUrl("v1/verify"); Request request = this.makeAuthorizedRequestBuilder() .url(url) .get() .build(); Response response = clientWithRetry.newCall(request).execute(); getResponseBody(response); return true; } catch (Exception exception) { throw new ConstructorException(exception); } }
Source:
<code>void setFailed() { <START> done = true; <END> }</code><technical_language>prefer explicitly setting succeeded = false</technical_language>

Target:
void setFailed() { done = true; succeeded = false; }
Source:
<code>private void putlightDimmer(String message) { coapClient.setURI( "coap://" + COAP_SERVER_IP_ADDRESS + ":" + COAP_SERVER_PORT + "/InternetOfTiny/actuators/actuator1"); StringBuilder coapLightSwitch = new StringBuilder(); <START> coapLightSwitch.append(",1,pp," + message + ","); <END> CoapResponse clientResponse = coapClient.put(coapLightSwitch.toString(), TEXT_PLAIN); logger.debug(clientResponse.advanced().getSource().toString()); }</code><technical_language>a StringBuilder #append method feels a bit strange. coapLightSwitch.append(",1,pp,").append(message).append(",");</technical_language>

Target:
private void putlightDimmer(String message) { coapClient .setURI("coap://" + coapServerIpAddress + ":" + coapServerPort + "/InternetOfTiny/actuators/actuator1"); StringBuilder coapLightSwitch = new StringBuilder(); coapLightSwitch.append(",1,pp,").append(message).append(","); CoapResponse clientResponse = coapClient.put(coapLightSwitch.toString(), TEXT_PLAIN); logger.debug(clientResponse.advanced().getSource().toString()); }
Source:
<code>public void load(final List<String> entryIds, boolean periodic) { boolean setLastUpdatedAt = periodic || lastUpdatedCuePoint == 0; KalturaCuePointFilter filter = new KalturaCuePointFilter(); filter.entryIdEqual = StringUtils.join(entryIds); filter.statusEqual = KalturaCuePointStatus.READY; filter.triggeredAtGreaterThanOrEqual = 1; if(periodic){ filter.updatedAtGreaterThanOrEqual = lastUpdatedCuePoint; } filter.orderBy = KalturaCuePointOrderBy.UPDATED_AT_ASC.hashCode; KalturaFilterPager pager = new KalturaFilterPager(); pager.pageIndex = 1; pager.pageSize = 100; Timer timer; TimerTask timerTask; Date date = new Date(); try{ while(true){ KalturaCuePointListResponse CuePointsList = client.getCuePointService().list(filter , pager); if(CuePointsList.objects.size() == 0){ break; } for(final KalturaCuePoint cuePoint : CuePointsList.objects){ if(setLastUpdatedAt){ lastUpdatedCuePoint = Math.max(lastUpdatedCuePoint, cuePoint.updatedAt); } <START> long scheduledTime = (cuePoint.triggeredAt / 1000) - 30000; <END> if (scheduledTime < 0) { logger.error("Cue-point was set with illegal triggered at time " + cuePoint.triggeredAt + ", setting time to zero" ); scheduledTime =0 ; } date.setTime(scheduledTime); timerTask = new TimerTask(){ @Override public void run() { createSyncPoint(cuePoint.entryId); } }; timer = new Timer(true); timer.schedule(timerTask, date); } } } catch (KalturaApiException e) { logger.error("Failed to list entries cue-points: " + e.getMessage()); } }</code><technical_language>This test is needed triggeredAt is timestamp larger 1980 is a large number</technical_language>

Target:
public void load(final List<String> entryIds, boolean periodic) { boolean setLastUpdatedAt = periodic || lastUpdatedCuePoint == 0; KalturaCuePointFilter filter = new KalturaCuePointFilter(); filter.entryIdEqual = StringUtils.join(entryIds); filter.statusEqual = KalturaCuePointStatus.READY; filter.triggeredAtGreaterThanOrEqual = 1; if(periodic){ filter.updatedAtGreaterThanOrEqual = lastUpdatedCuePoint; } filter.orderBy = KalturaCuePointOrderBy.UPDATED_AT_ASC.hashCode; KalturaFilterPager pager = new KalturaFilterPager(); pager.pageIndex = 1; pager.pageSize = 100; Timer timer; TimerTask timerTask; Date date = new Date(); try{ while(true){ KalturaCuePointListResponse CuePointsList = client.getCuePointService().list(filter , pager); if(CuePointsList.objects.size() == 0){ break; } for(final KalturaCuePoint cuePoint : CuePointsList.objects){ if(setLastUpdatedAt){ lastUpdatedCuePoint = Math.max(lastUpdatedCuePoint, cuePoint.updatedAt); } long scheduledTime = (cuePoint.triggeredAt / 1000) - 30000; if (scheduledTime < 0) { logger.error("Cue-point was set with illegal triggered at time " + cuePoint.triggeredAt + ", seems that the filter does not work" ); } date.setTime(scheduledTime); timerTask = new TimerTask(){ @Override public void run() { createSyncPoint(cuePoint.entryId); } }; timer = new Timer(true); timer.schedule(timerTask, date); } } } catch (KalturaApiException e) { logger.error("Failed to list entries cue-points: " + e.getMessage()); } }
Source:
<code>public long getSessionId() { long sessionId = -1; if (isConnected()) { try { <START> sessionId = getZooKeeper().getSessionId(); <END> } catch (Exception e) { } } return sessionId; }</code><technical_language>This is expensive call. Is necessary? get session ID cheaper a direct call zooKeeper.getZooKeeper() - (checking for nulls)</technical_language>

Target:
public long getSessionId() { long sessionId = -1; if (isConnected()) { try { ZooKeeper zk = zooKeeper.getZooKeeper(); if (zk != null) { sessionId = zk.getSessionId(); } } catch (Exception e) { } } return sessionId; }
Source:
<code>public Collection<EPackage> getPackagesToImport() { Collection<EPackage> superResult = super.getPackagesToImport(); <START> superResult.add(DiagramPackage.eINSTANCE); <END> return superResult; }</code><technical_language>consistent Tree Table: add DescriptionPackage subPackages. diagram types ? SequenceDiagramTypeProvider "interpreterswitch". getPackageToImport allow retrieve Sequence diagram ype metamodels</technical_language>

Target:
public Collection<EPackage> getPackagesToImport() { Collection<EPackage> superResult = super.getPackagesToImport(); superResult.add(DiagramPackage.eINSTANCE); superResult.add(DescriptionPackage.eINSTANCE); superResult.add(StylePackage.eINSTANCE); superResult.add(org.eclipse.sirius.diagram.description.tool.ToolPackage.eINSTANCE); superResult.add(FilterPackage.eINSTANCE); superResult.add(ConcernPackage.eINSTANCE); return superResult; }
Source:
<code>private ReferenceGenome createReferenceGenome() { ReferenceGenome referenceGenome = new ReferenceGenomeImpl(); referenceGenome.setAlias("Human hg19"); <START> referenceGenome.setId(1L); <END> return referenceGenome; }</code><technical_language>need ID anymore</technical_language>

Target:
private ReferenceGenome createReferenceGenome() { ReferenceGenome referenceGenome = new ReferenceGenomeImpl(); referenceGenome.setAlias("Human hg19"); return referenceGenome; }
Source:
<code>default List<String> getNewFieldNames( final String[] incomingFieldNames ) { final Set<String> fieldNamesInTable = new HashSet<>(); for ( int i = 0; i < getFieldsTable().table.getItemCount(); i++ ) { final TableItem item = getFieldsTable().table.getItem( i ); int fieldNameIndex = getFieldsTable().hasIndexColumn() ? 1 : 0; fieldNamesInTable.add( item.getText( fieldNameIndex ) ); } <START> return Arrays <END> .stream( incomingFieldNames ) .filter( fieldName -> !fieldNamesInTable.contains( fieldName ) ) .collect( Collectors.toList() ); }</code><technical_language>This is actual fix</technical_language>

Target:
default List<String> getNewFieldNames( final String[] incomingFieldNames ) { final Set<String> fieldNamesInTable = new HashSet<>(); for ( int i = 0; i < getFieldsTable().getTable().getItemCount(); i++ ) { final TableItem item = getFieldsTable().getTable().getItem( i ); int fieldNameIndex = getFieldsTable().hasIndexColumn() ? 1 : 0; fieldNamesInTable.add( item.getText( fieldNameIndex ) ); } return Arrays .stream( incomingFieldNames ) .filter( fieldName -> !fieldNamesInTable.contains( fieldName ) ) .collect( Collectors.toList() ); }
Source:
<code><START> public static void loadTextures() { <END> Image brickTexture = new Image( "nl/tudelft/ti2206/group9/gui/texture_brick.png"); BRICK.setDiffuseMap(brickTexture); Image mossTexture = new Image( "nl/tudelft/ti2206/group9/gui/texture_moss.png"); MOSS.setDiffuseMap(mossTexture); Image crackTexture = new Image( "nl/tudelft/ti2206/group9/gui/texture_crack.png"); CRACK.setDiffuseMap(crackTexture); Image floorTexture = new Image( "nl/tudelft/ti2206/group9/gui/texture_cobblestone.png"); FLOOR.setDiffuseMap(floorTexture); Image coinTexture = new Image( "nl/tudelft/ti2206/group9/gui/texture_coin.png"); COIN.setDiffuseMap(coinTexture); Image woodTexture = new Image( "nl/tudelft/ti2206/group9/gui/texture_wood.png"); WOOD.setDiffuseMap(woodTexture); Image pillarTexture = new Image( "nl/tudelft/ti2206/group9/gui/texture_pillar.png"); PILLAR.setDiffuseMap(pillarTexture); Image fenceTexture = new Image( "nl/tudelft/ti2206/group9/gui/texture_fence.png"); FENCE.setDiffuseMap(fenceTexture); Image playerTexture = new Image( "nl/tudelft/ti2206/group9/gui/texture_player.png"); PLAYER.setDiffuseMap(playerTexture); }</code><technical_language>Method is long. I suggest putting "nl/tudelft/ti2206/group9/gui/" in a local variable, split lines. <layout</technical_language>

Target:
public static void loadTextures() { String path = "nl/tudelft/ti2206/group9/gui/"; Image brickTexture = new Image(path + "texture_brick.png"); BRICK.setDiffuseMap(brickTexture); Image mossTexture = new Image(path + "texture_moss.png"); MOSS.setDiffuseMap(mossTexture); Image crackTexture = new Image(path + "texture_crack.png"); CRACK.setDiffuseMap(crackTexture); Image floorTexture = new Image(path + "texture_cobblestone.png"); FLOOR.setDiffuseMap(floorTexture); Image coinTexture = new Image(path + "texture_coin.png"); COIN.setDiffuseMap(coinTexture); Image woodTexture = new Image(path + "texture_wood.png"); WOOD.setDiffuseMap(woodTexture); Image pillarTexture = new Image(path + "texture_pillar.png"); PILLAR.setDiffuseMap(pillarTexture); Image fenceTexture = new Image(path + "texture_fence.png"); FENCE.setDiffuseMap(fenceTexture); Image playerTexture = new Image(path + "texture_player.png"); PLAYER.setDiffuseMap(playerTexture); }
Source:
<code>public synchronized ProcessingResult insert(Beacon block) { ValidationResult vRes; if ((vRes = beaconValidator.validateAndLog(block)) != ValidationResult.Success) return ProcessingResult.fromValidation(vRes); Beacon parent = pullParent(block); BeaconState currentState = pullState(parent); if ((vRes = proposerValidator.validateAndLog(block, parent, currentState)) != ValidationResult.Success) return ProcessingResult.fromValidation(vRes); <START> if ((vRes = attestationsValidator.validateAndLog(block, parent, currentState)) != ValidationResult.Success) <END> return ProcessingResult.fromValidation(vRes); BeaconState newState = transitionFunction.applyBlock(block, currentState); if ((vRes = stateValidator.validateAndLog(block, newState)) != ValidationResult.Success) return ProcessingResult.fromValidation(vRes); BigInteger blockScore = scoreFunction.apply(block, newState); BigInteger chainScore = store.getChainScore(parent.getHash()).add(blockScore); ScoredChainHead newHead = new ScoredChainHead(block, chainScore, newState); beaconDbFlusher.commit(() -> { repository.insert(newHead.state); repository.commit(); store.save(newHead.block, newHead.score, canonicalHead.isParentOf(newHead)); if (canonicalHead.shouldReorgTo(newHead)) { store.reorgTo(newHead.block); } if (canonicalHead.isParentOf(newHead) || canonicalHead.shouldReorgTo(newHead)) { canonicalHead = newHead; } }); ProcessingResult res = canonicalHead.equals(newHead) ? ProcessingResult.Best : ProcessingResult.NotBest; publish(onBeaconBlock(block, newState, res == ProcessingResult.Best)); logger.info("Process block {}, status: {}", block.toString(), res); return res; }</code><technical_language>if merge attestationsValidator proposerValidator validator a couple of rules</technical_language>

Target:
public synchronized ProcessingResult insert(Beacon block) { ValidationResult vRes; if ((vRes = beaconValidator.validateAndLog(block)) != ValidationResult.Success) return ProcessingResult.fromValidation(vRes); Beacon parent = pullParent(block); BeaconState currentState = pullState(parent); BeaconState newState = transitionFunction.applyBlock(block, currentState); if ((vRes = stateValidator.validateAndLog(block, newState)) != ValidationResult.Success) return ProcessingResult.fromValidation(vRes); BigInteger chainScore = scoreFunction.apply(block, newState); ScoredChainHead newHead = new ScoredChainHead(block, chainScore, newState); beaconDbFlusher.commit(() -> { repository.insert(newHead.state); repository.commit(); store.save(newHead.block, newHead.score, canonicalHead.isParentOf(newHead)); if (canonicalHead.shouldReorgTo(newHead)) { store.reorgTo(newHead.block); } if (canonicalHead.isParentOf(newHead) || canonicalHead.shouldReorgTo(newHead)) { canonicalHead = newHead; } }); ProcessingResult res = canonicalHead.equals(newHead) ? ProcessingResult.Best : ProcessingResult.NotBest; publish(onBeaconBlock(block, newState, res == ProcessingResult.Best)); logger.info("Process block {}, status: {}", block.toString(), res); return res; }
Source:
<code>private VView loadView(IPath path) { final ResourceSet resourceSet = new ResourceSetImpl(); final Resource resource = resourceSet .createResource(URI.createPlatformResourceURI(path.toOSString(), true)); try { resource.load(null); <START> return (VView) <END> resource.getContents().get(0); } catch (final IOException ex) { throw new IllegalArgumentException(ex); } }</code><technical_language>ClassCastException, is check loaded resource is a view</technical_language>

Target:
private VView loadView(IPath path) { final ResourceSet resourceSet = new ResourceSetImpl(); final Resource resource = resourceSet .createResource(URI.createPlatformResourceURI(path.toOSString(), true)); try { resource.load(null); final EObject eObject = resource.getContents().get(0); if (!VView.class.isInstance(eObject)) { throw new IllegalArgumentException( "The provided path " + path.toString() + " doesn't contain a VView."); } return (VView) eObject; } catch (final IOException ex) { throw new IllegalArgumentException(ex); } }
Source:
<code>private void setWatchAction(UserFeed feed) { int seriesNumber = feed.getEpisodes(); String showName = feed.getShow(); String actionText; if (seriesNumber == 1) { setWatchOneSeriesAction(feed, showName); } else { int pluralsId = feed.getGender() == Gender.FEMALE ? R.plurals.f_watch_series : R.plurals.m_watch_series; <START> actionText = itemView.getResources().getQuantityString(pluralsId, seriesNumber, seriesNumber, showName); <END> setShowActionText(actionText, feed); } }</code><technical_language>String actionText = ... remove line 199</technical_language>

Target:
private void setWatchAction(UserFeed feed) { Spannable spannable = feed.getEpisodes() == 1 ? getOneEpisodeSpannable(feed) : getManyEpisodeSpannable(feed); action.setText(spannable, TextView.BufferType.SPANNABLE); }
Source:
<code>public void testNonPartition() throws Exception { tEnv().executeSql("CREATE TABLE sink_table (a int, b string, c string) with (" + options() + ")"); tEnv().executeSql("insert into sink_table select * from my_table").await(); List<Row> results = toListAndClose(tEnv().executeSql("select * from sink_table").collect()); results.sort(Comparator.comparingInt(o -> (Integer) o.getField(0))); assertEquals(rows, results); File[] files = new File(URI.create(resultPath)).listFiles( <START> (dir, name) -> name.startsWith("compacted-part-")); <END> assertEquals(Arrays.toString(files), 1, files.length); String fileName = files[0].getName(); assertTrue(fileName, fileName.startsWith("compacted-part-")); }</code><technical_language>reuse COMPACTED_PREFIX defined in CompactOperator</technical_language>

Target:
public void testNonPartition() throws Exception { tEnv().executeSql("CREATE TABLE sink_table (a int, b string, c string) with (" + options() + ")"); tEnv().executeSql("insert into sink_table select * from my_table").await(); assertIterator(tEnv().executeSql("select * from sink_table").collect()); assertFiles(new File(URI.create(resultPath)).listFiles(), false); }
Source:
<code>private void emit() { if (isUnsubscribed()) { last = null; return; } synchronized (this) { if (last != ABSENT) { T t = last; last = null; <START> child.onNext(t); <END> } } if (!isUnsubscribed()) child.onCompleted(); }</code><technical_language>call onNext while holding a lock</technical_language>

Target:
private void emit() { if (isUnsubscribed()) { last = null; return; } T t = last; last = null; if (t != ABSENT) { try { child.onNext(t); } catch (Throwable e) { child.onError(e); return; } } if (!isUnsubscribed()) child.onCompleted(); }
Source:
<code>public void testParsingHPOOBO() throws Exception { OboParser parser = new OboParser(); <START> InputStream inStream = parser.getClass().getResourceAsStream("/ontology/hp.obo"); <END> Assert.assertNotNull(inStream); BufferedReader oboFile = new BufferedReader ( new InputStreamReader ( inStream ) ); Ontology ontology; ontology = parser.parseOBO(oboFile, "Human_phenotype", "the Human Phenotype ontology"); Set<Term> keys = ontology.getTerms(); Assert.assertTrue(keys.size() > 4000); }</code><technical_language>If gzip hp.obo file, need gzip filter read it, i.e. java InputStream inStream = new GZIPInputStream(parser.getClass().getResourceAsStream("/ontology/hp.obo"));</technical_language>

Target:
public void testParsingHPOOBO() throws Exception { OboParser parser = new OboParser(); InputStream inStream = parser.getClass().getResourceAsStream("/ontology/hp.obo"); Assert.assertNotNull(inStream); BufferedReader oboFile = new BufferedReader ( new InputStreamReader ( inStream ) ); Ontology ontology; ontology = parser.parseOBO(oboFile, "Human_phenotype", "the Human Phenotype ontology"); Set<Term> keys = ontology.getTerms(); Iterator iter = keys.iterator(); while (iter.hasNext()){ Term term = (Term) iter.next(); if(term.getName().equals("HP:0000057")) { Annotation anno = term.getAnnotation(); Assert.assertTrue(anno.containsProperty("replaced_by")); Assert.assertEquals("HP:0008665", anno.getProperty("replaced_by")); } } }
Source:
<code>public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BlueprintConfigurations that = (BlueprintConfigurations) o; if (properties != null ? !properties.equals(that.properties) : that.properties != null) return false; <START> return propertyAttributes != null ? propertyAttributes.equals(that.propertyAttributes) : that.propertyAttributes == null; <END> }</code><technical_language>Simplify Objects.equals</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BlueprintConfigurations that = (BlueprintConfigurations) o; return Objects.equals(properties, that.properties) && Objects.equals(propertyAttributes, that.propertyAttributes); }
Source:
<code>public Set<Firmware> getFirmwares(final ThingTypeUID thingTypeUID, Locale locale) { Preconditions.checkArgument(thingTypeUID != null); if (locale == null) { locale = Locale.getDefault(); } final Locale myLocale = locale; Path thingTypePath = Paths.get(rootPath, thingTypeUID.getBindingId(), thingTypeUID.getId()); final Set<Firmware> firmwareSet = new HashSet<>(); try { Files.walkFileTree(thingTypePath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (PROPERTY_FILE_MATCHER.matches(file)) { FirmwareUID firmwareUID = getFirmwareUIDFromFileName(thingTypeUID, getBaseName(file.getFileName().toString())); if (firmwareUID != null) { Firmware firmware = getFirmware(firmwareUID, myLocale); if (firmware != null) { firmwareSet.add(firmware); } } } return FileVisitResult.CONTINUE; } }); } catch (IOException e) { <START> logger.error("Error searching firmwares for thing type " + thingTypeUID, e); <END> } return firmwareSet; }</code><technical_language>log IOException error. E.g. if invoke operation for a type UID for firmware exists a NoSuchFileException is thrown. I print a debug message for this exception stack trace</technical_language>

Target:
public Set<Firmware> getFirmwares(final ThingTypeUID thingTypeUID, Locale locale) { Preconditions.checkArgument(thingTypeUID != null); if (locale == null) { locale = Locale.getDefault(); } final Locale myLocale = locale; Path thingTypePath = Paths.get(rootPath, thingTypeUID.getBindingId(), thingTypeUID.getId()); final Set<Firmware> firmwareSet = new HashSet<>(); try { Files.walkFileTree(thingTypePath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (PROPERTY_FILE_MATCHER.matches(file)) { FirmwareUID firmwareUID = getFirmwareUIDFromFileName(thingTypeUID, getBaseName(file.getFileName().toString())); if (firmwareUID != null) { Firmware firmware = getFirmware(firmwareUID, myLocale); if (firmware != null) { firmwareSet.add(firmware); } } } return FileVisitResult.CONTINUE; } }); } catch (IOException e) { logger.debug("Cannot find firmwares for thing type " + thingTypeUID); } return firmwareSet; }
Source:
<code>public void postCollectionSubmittersGroupCreateSubmittersGroupDcTitleUnprocessable() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); metadataRest.put("dc.title", new MetadataValueRest("testTitle")); groupRest.setMetadata(metadataRest); AtomicReference<UUID> idRef = new AtomicReference<>(); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(post("/api/core/collections/" + collection.getID() + "/submittersGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isUnprocessableEntity()); <START> <END> }</code><technical_language>double check group created</technical_language>

Target:
public void postCollectionSubmittersGroupCreateSubmittersGroupDcTitleUnprocessable() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); metadataRest.put("dc.title", new MetadataValueRest("testTitle")); groupRest.setMetadata(metadataRest); AtomicReference<UUID> idRef = new AtomicReference<>(); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(post("/api/core/collections/" + collection.getID() + "/submittersGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isUnprocessableEntity()); getClient(token).perform(get("/api/core/collections/" + collection.getID() + "/submittersGroup")) .andExpect(status().isNoContent()); }
Source:
<code>public static ColumnType parseColumnType(String dimensionField, Class<?> cls, EntityDictionary entityDictionary) { <START> if (entityDictionary.attributeOrRelationAnnotationExists(cls, dimensionField, Id.class)) { <END> return ColumnType.PRIMARY_KEY; } else { return ColumnType.FIELD; } }</code><technical_language>Replace with: entityDictionary.getIdFieldName(cls).equals(dimensionField)</technical_language>

Target:
public static ColumnType parseColumnType(String dimensionField, Class<?> cls, EntityDictionary entityDictionary) { if (entityDictionary.getIdFieldName(cls).equals(dimensionField)) { return ColumnType.PRIMARY_KEY; } else { return ColumnType.FIELD; } }
Source:
<code><START> private IterableResponse<ConfigurationSetting> listSettingRevisions(SettingSelector selector, Context context) { <END> return new IterableResponse<ConfigurationSetting>(client.listSettingRevisions(selector, context)); }</code><technical_language>This API changed public private</technical_language>

Target:
public PagedIterable<ConfigurationSetting> listSettingRevisions(SettingSelector selector, Context context) { return new PagedIterable<>(client.listSettingRevisions(selector, context)); }
Source:
<code>protected void endWithFailure() { setVmTemplateId(getParameters().getVmTemplateId()); setVmId(getVmIdFromImageParameters()); for (VdcActionParametersBase p : getParameters().getImagesParameters()) { p.setTaskGroupSuccess(false); Backend.getInstance().endAction(VdcActionType.CreateImageTemplate, p, <START> cloneContext().withoutCompensationContext().withoutExecutionContext().withoutLock()); <END> } if (getVmTemplate() != null) { DbFacade.getInstance().getVmTemplateDao().remove(getVmTemplateId()); removeNetwork(); } if (!getVmId().equals(Guid.Empty) && getVm() != null) { VmHandler.unLockVm(getVm()); } setSucceeded(true); }</code><technical_language>detach</technical_language>

Target:
protected void endWithFailure() { setVmTemplateId(getParameters().getVmTemplateId()); setVmId(getVmIdFromImageParameters()); for (VdcActionParametersBase p : getParameters().getImagesParameters()) { p.setTaskGroupSuccess(false); Backend.getInstance().endAction(VdcActionType.CreateImageTemplate, p, cloneContextAndDetachFromParent()); } if (getVmTemplate() != null) { DbFacade.getInstance().getVmTemplateDao().remove(getVmTemplateId()); removeNetwork(); } if (!getVmId().equals(Guid.Empty) && getVm() != null) { VmHandler.unLockVm(getVm()); } setSucceeded(true); }
Source:
<code><START> public Object cors() throws Exception { <END> return getOrApply(new CorsConfigurer<HttpSecurity>()); }</code><technical_language>return type CorsConfigurer<HttpSecurity></technical_language>

Target:
public CorsConfigurer<HttpSecurity> cors() throws Exception { return getOrApply(new CorsConfigurer<HttpSecurity>()); }
Source:
<code>public CoupleMbusDeviceByChannelAsyncResponse coupleMbusDeviceByChannel( @OrganisationIdentification final String organisationIdentification, @RequestPayload final CoupleMbusDeviceByChannelRequest request, @MessagePriority final String messagePriority, @ScheduleTime final String scheduleTime, @ResponseUrl final String responseUrl) throws OsgpException { final String deviceIdentification = request.getDeviceIdentification(); final short channel = request.getCoupleMbusDeviceByChannelRequestData().getChannel(); LOGGER.info("Incoming CoupleMbusDeviceByChannellRequest for meter: and channel {}.", deviceIdentification, <START> channel); <END> CoupleMbusDeviceByChannelAsyncResponse response = null; try { response = new CoupleMbusDeviceByChannelAsyncResponse(); final String correlationUid = this.installationService.enqueueCoupleMbusDeviceByChannelRequest( organisationIdentification, deviceIdentification, MessagePriorityEnum.getMessagePriority(messagePriority), this.installationMapper.map(scheduleTime, Long.class), channel); response.setCorrelationUid(correlationUid); response.setDeviceIdentification(deviceIdentification); this.saveResponseUrlIfNeeded(correlationUid, responseUrl); } catch (final Exception e) { LOGGER.error("Exception while coupling on channel: for device: for organisation {}.", channel, deviceIdentification, organisationIdentification, e); this.handleException(e); } return response; }</code><technical_language>I write 'for device' instead of meter</technical_language>

Target:
public CoupleMbusDeviceByChannelAsyncResponse coupleMbusDeviceByChannel( @OrganisationIdentification final String organisationIdentification, @RequestPayload final CoupleMbusDeviceByChannelRequest request, @MessagePriority final String messagePriority, @ScheduleTime final String scheduleTime, @ResponseUrl final String responseUrl) throws OsgpException { final String deviceIdentification = request.getDeviceIdentification(); final short channel = request.getCoupleMbusDeviceByChannelRequestData().getChannel(); LOGGER.info("Incoming CoupleMbusDeviceByChannelRequest for device: and channel {}.", deviceIdentification, channel); CoupleMbusDeviceByChannelAsyncResponse response = null; try { response = new CoupleMbusDeviceByChannelAsyncResponse(); final String correlationUid = this.installationService.enqueueCoupleMbusDeviceByChannelRequest( organisationIdentification, deviceIdentification, MessagePriorityEnum.getMessagePriority(messagePriority), this.installationMapper.map(scheduleTime, Long.class), channel); response.setCorrelationUid(correlationUid); response.setDeviceIdentification(deviceIdentification); this.saveResponseUrlIfNeeded(correlationUid, responseUrl); } catch (final Exception e) { LOGGER.error("Exception while coupling on channel: for device: for organisation {}.", channel, deviceIdentification, organisationIdentification, e); this.handleException(e); } return response; }
Source:
<code>protected void run() throws Failure { if (all && projectNames.size() > 0) { throw new UnloggedFailure(1, "error: cannot combine --all and PROJECT"); } ReplicationState state = new ReplicationState(ReplicationType.COMMAND, this); Future<?> future = null; if (all) { future = pushAllFactory.create(urlMatch, state).schedule(0, TimeUnit.SECONDS); } else { for (String name : projectNames) { Project.NameKey key = new Project.NameKey(name); if (projectCache.get(key) != null) { replication.scheduleFullSync(key, urlMatch, state); } else { writeStdErrSync("error: '" + name + "': not a Gerrit project"); } } state.markAllPushTasksScheduled(); } if (wait) { if (future != null) { try { future.get(); } catch (InterruptedException e) { <START> log.warn("Thread was interrupted while waiting for PushAll operation to finish", e); <END> } catch (ExecutionException e) { log.warn("An exception was thrown in PushAll operation", e); } } if (state.hasPushTask()) { state.waitForReplication(); } else { writeStdOutSync("Nothing to replicate"); } } }</code><technical_language>If reach this code path, exception is written log. fine. visible user [1]. If exception occurs push task scheduled, user sees "Nothing replicate" command exits status 0. If exception occurs task pushed, outcomes varies a bit for example thread hang. [1] Note PushAll.run rethrow, InterruptedException, ... PushAll.run's try/catch block</technical_language>

Target:
protected void run() throws Failure { if (all && projectNames.size() > 0) { throw new UnloggedFailure(1, "error: cannot combine --all and PROJECT"); } ReplicationState state = new ReplicationState(ReplicationType.COMMAND, this); Future<?> future = null; if (all) { future = pushAllFactory.create(urlMatch, state).schedule(0, TimeUnit.SECONDS); } else { for (String name : projectNames) { Project.NameKey key = new Project.NameKey(name); if (projectCache.get(key) != null) { replication.scheduleFullSync(key, urlMatch, state); } else { writeStdErrSync("error: '" + name + "': not a Gerrit project"); } } state.markAllPushTasksScheduled(); } if (wait) { if (future != null) { try { future.get(); } catch (InterruptedException e) { wrappedLog.error("Thread was interrupted while waiting for PushAll operation to finish", e, state); } catch (ExecutionException e) { wrappedLog.error("An exception was thrown in PushAll operation", e, state); } } if (state.hasPushTask()) { try { state.waitForReplication(); } catch (InterruptedException e) { wrappedLog.error("We are interrupted while waiting replication to complete", state); } } else { writeStdOutSync("Nothing to replicate"); } } }
Source:
<code>public void setTimeGraphScale(TimeGraphScale timeGraphScale) { fTimeGraphScale = timeGraphScale; <START> setHeaderHeight(timeGraphScale.getBounds().height); <END> }</code><technical_language>This necessary anymore</technical_language>

Target:
public void setTimeGraphScale(TimeGraphScale timeGraphScale) { fTimeGraphScale = timeGraphScale; }
Source:
<code>public String injectMgwThrottlingExtensionsToDefault(String swaggerContent) throws APIManagementException { Swagger swagger = getSwagger(swaggerContent); Map<String, Path> paths = swagger.getPaths(); for (String pathKey : paths.keySet()) { Map<HttpMethod, Operation> operationsMap = paths.get(pathKey).getOperationMap(); for (Map.Entry<HttpMethod, Operation> entry : operationsMap.entrySet()) { Operation operation = entry.getValue(); Map<String, Object> extensions = operation.getVendorExtensions(); if (extensions.containsKey(APIConstants.X_WSO2_THROTTLING_TIER)) { Object tier = extensions.get(APIConstants.X_WSO2_THROTTLING_TIER); extensions.remove(APIConstants.X_WSO2_THROTTLING_TIER); extensions.put(APIConstants.SWAGGER_X_THROTTLING_TIER, tier); } <START> operation.setVendorExtensions(extensions); entry.setValue(operation); operationsMap.put(entry.getKey(), operation); <END> } paths.put(pathKey, paths.get(pathKey)); } swagger.setPaths(paths); return getSwaggerJsonString(swagger); }</code><technical_language>Do need 3 lines</technical_language>

Target:
public String injectMgwThrottlingExtensionsToDefault(String swaggerContent) throws APIManagementException { Swagger swagger = getSwagger(swaggerContent); Map<String, Path> paths = swagger.getPaths(); for (String pathKey : paths.keySet()) { Map<HttpMethod, Operation> operationsMap = paths.get(pathKey).getOperationMap(); for (Map.Entry<HttpMethod, Operation> entry : operationsMap.entrySet()) { Operation operation = entry.getValue(); Map<String, Object> extensions = operation.getVendorExtensions(); if (extensions != null && extensions.containsKey(APIConstants.X_WSO2_THROTTLING_TIER)) { Object tier = extensions.get(APIConstants.X_WSO2_THROTTLING_TIER); extensions.remove(APIConstants.X_WSO2_THROTTLING_TIER); extensions.put(APIConstants.SWAGGER_X_THROTTLING_TIER, tier); } } } return getSwaggerJsonString(swagger); }
Source:
<code>public void shouldNotRecordSuccessTestExecutionByDefault() { final String oldMode = updateRecorderToDefaultOption(); Description desc = description("shouldNotRecordSuccessTestExecutionByDefault"); TestRecorderRule testRecorderRule = rule(desc); testRecorderRule.starting(desc); System.out.println("Hello World"); testRecorderRule.succeeded(desc); testRecorderRule.finished(desc); File outputFile = outputFile(desc); assertThat(outputFile.exists(), is(false)); outputFile.delete(); <START> restoreRecorderOption(oldMode); <END> }</code><technical_language>do @Before / @After</technical_language>

Target:
public void shouldNotRecordSuccessTestExecutionByDefault() { final String oldMode = updateRecorderToDefaultOption(); try { Description desc = description("shouldNotRecordSuccessTestExecutionByDefault"); TestRecorderRule testRecorderRule = rule(desc); testRecorderRule.starting(desc); System.out.println("Hello World"); testRecorderRule.succeeded(desc); testRecorderRule.finished(desc); File outputFile = outputFile(desc); assertThat(outputFile.exists(), is(false)); outputFile.delete(); } finally { restoreRecorderOption(oldMode); } }
Source:
<code>public OAHashSet(int initialCapacity, float loadFactor) { checkNotNegative(initialCapacity, "Illegal initial capacity: " + initialCapacity); <START> checkFalse(loadFactor <= 0 || Float.isNaN(loadFactor), "Illegal load factor: " + loadFactor); <END> this.capacity = QuickMath.nextPowerOfTwo(initialCapacity); this.loadFactor = loadFactor; this.resizeThreshold = (int) (capacity * loadFactor); this.mask = capacity - 1; this.hashes = new int[capacity]; this.table = new Object[capacity]; }</code><technical_language>check load factor is smaller 1</technical_language>

Target:
public OAHashSet(int initialCapacity, float loadFactor) { checkNotNegative(initialCapacity, "Illegal initial capacity: " + initialCapacity); checkFalse(loadFactor <= 0 || loadFactor >= 1 || Float.isNaN(loadFactor), "Illegal load factor: " + loadFactor); this.capacity = QuickMath.nextPowerOfTwo(initialCapacity); this.loadFactor = loadFactor; this.resizeThreshold = (int) (capacity * loadFactor); this.mask = capacity - 1; this.hashes = new int[capacity]; this.table = new Object[capacity]; }
Source:
<code>public void setUp() throws Exception { <START> world = new PhysicsWorld(1920, 1600); <END> sprite = new SingleSprite("TestSprite"); physicsObject = world.getPhysicsObject(sprite); physicsLook = new PhysicsLook(sprite, world); }</code><technical_language>Please mock PhysicsWorld if</technical_language>

Target:
public void setUp() throws Exception { Sprite sprite = mock(Sprite.class); physicsObject = mock(PhysicsObject.class); physicsWorldSpy = Mockito.spy(new PhysicsWorld(1920, 1600)); when(physicsWorldSpy.getPhysicsObject(sprite)).thenReturn(physicsObject); physicsLook = new PhysicsLook(sprite, physicsWorldSpy); }
Source:
<code>public void removePublicLink(OCShare share) { <START> Log_OC.d(TAG, "Unsharing " + share.getName()); <END> mListener.removeShare(share); }</code><technical_language>Removing instead of Unsharing...</technical_language>

Target:
public void removePublicLink(OCShare share) { Log_OC.d(TAG, "Removing public share " + share.getName()); mListener.removeShare(share); }
Source:
<code>public void readJournalListFromResource(String resourceFileName) { try { InputStream stream = JournalAbbreviationRepository.class.getResourceAsStream(resourceFileName); <START> readJournalList(new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))); <END> } catch (IOException e) { LOGGER.error(String.format("Could not read journal list from file %s", resourceFileName), e); } }</code><technical_language>resource leak? I reader is closed</technical_language>

Target:
public void readJournalListFromResource(String resourceFileName) { try (InputStream stream = JournalAbbreviationRepository.class.getResourceAsStream(resourceFileName); BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) { readJournalList(reader); } catch (IOException e) { LOGGER.error(String.format("Could not read journal list from file %s", resourceFileName), e); } }
Source:
<code>public void should_create_job_with_description() { String jobName = "MyJob"; String jobDescription = "My sample despription"; String jobDslScript = String.format("job('%s') { description('%s') }", jobName, jobDescription); Job seed = createSeedJobWithJobDsl(jobDslScript); seed.startBuild().waitUntilFinished(); Job job = jenkins.jobs.get(Job.class, jobName); job.open(); <START> WebElement descriptionElement = job.find(by.xpath(" END> assertEquals(descriptionElement.getText(), jobDescription); }</code><technical_language>move this code TopLevelItem.getDescription write assertThat(job.getDescription(), containsString("bla")</technical_language>

Target:
public void should_create_job_with_description() { String jobName = "MyJob"; String jobDescription = "My sample despription"; String jobDslScript = String.format("job('%s') { description('%s') }", jobName, jobDescription); Job seed = createSeedJobWithJobDsl(jobDslScript); seed.startBuild().waitUntilFinished(); Job job = jenkins.jobs.get(Job.class, jobName); job.open(); assertThat(job.getDescription(), containsString(jobDescription)); }
Source:
<code>protected static Set<Cache> getRunningCaches(EmbeddedCacheManager cacheContainer) { Set<Cache> running = new HashSet<Cache>(); if (cacheContainer == null || !cacheContainer.getStatus().allowInvocations()) return running; for (String cacheName : cacheContainer.getCacheNames()) { if (cacheContainer.isRunning(cacheName)) { Cache c = cacheContainer.getCache(cacheName); if (c.getStatus().allowInvocations()) running.add(c); } } Cache defaultCache = cacheContainer.getCache(EmbeddedCacheManager.DEFAULT_CACHE_NAME); <START> if (defaultCache != null) { <END> if (defaultCache.getStatus().allowInvocations()) running.add(defaultCache); } return running; }</code><technical_language>I return null</technical_language>

Target:
protected static Set<Cache> getRunningCaches(EmbeddedCacheManager cacheContainer) { Set<Cache> running = new HashSet<Cache>(); if (cacheContainer == null || !cacheContainer.getStatus().allowInvocations()) return running; for (String cacheName : cacheContainer.getCacheNames()) { if (cacheContainer.isRunning(cacheName)) { Cache c = cacheContainer.getCache(cacheName, false); if (c != null && c.getStatus().allowInvocations()) { running.add(c); } } } if (cacheContainer.isDefaultRunning()) { Cache defaultCache = cacheContainer.getCache(EmbeddedCacheManager.DEFAULT_CACHE_NAME, false); if (defaultCache != null && defaultCache.getStatus().allowInvocations()) { running.add(defaultCache); } } return running; }
Source:
<code><START> public InputStreamWithFilename extractJudgmentContent(File archiveFile, String judgmentSourceId) { <END> if (FilenameUtils.getExtension(archiveFile.getName()).equals("zip")) { ZipInputStream inputStream = null; try { inputStream = new ZipInputStream(new FileInputStream(archiveFile)); ZipEntry entry = inputStream.getNextEntry(); while(true) { if (entry == null) { break; } if (FilenameUtils.getBaseName(entry.getName()).equals(judgmentSourceId)) { return new InputStreamWithFilename(inputStream, entry.getName()); } entry = inputStream.getNextEntry(); } throw new ImportException("Content for judgment with sourceId " + judgmentSourceId + " not found in file " + archiveFile.getName()); } catch (IOException e) { IOUtils.closeQuietly(inputStream); throw new ImportException(e); } } throw new ImportException("File " + archiveFile.getName() + " is of type that is not supported"); }</code><technical_language>Params described</technical_language>

Target:
public InputStreamWithFilename extractJudgmentContent(File archiveFile, String judgmentSourceId) throws IOException { if (FilenameUtils.getExtension(archiveFile.getName()).equals("zip")) { ZipInputStream inputStream = null; try { inputStream = new ZipInputStream(new FileInputStream(archiveFile)); ZipEntry entry = inputStream.getNextEntry(); while(true) { if (entry == null) { break; } if (FilenameUtils.getBaseName(entry.getName()).equals(judgmentSourceId)) { return new InputStreamWithFilename(inputStream, entry.getName()); } entry = inputStream.getNextEntry(); } throw new ImportException("Content for judgment with sourceId " + judgmentSourceId + " not found in file " + archiveFile.getName()); } catch (IOException | ImportException e) { if (inputStream != null) { inputStream.close(); } throw e; } } throw new ImportException("File " + archiveFile.getName() + " is of type that is not supported"); }
Source:
<code>public void markCertificatesDirtyForPoolsWithProducts(Owner owner, Collection<String> productIds) { if (productIds.size() <= MAX_IN_CLAUSE_VALUES) { markCertificatesDirtyForPoolsWithNormalProducts(owner, productIds); markCertificatesDirtyForPoolsWithProvidedProducts(owner, productIds); } else { Iterator<String> productIdIter = productIds.iterator(); <START> List<String> batch = new ArrayList<String>(); <END> while (productIdIter.hasNext()) { batch.add(productIdIter.next()); if (batch.size() == MAX_IN_CLAUSE_VALUES) { markCertificatesDirtyForPoolsWithProducts(owner, batch); batch.clear(); } } if (batch.size() > 0) { markCertificatesDirtyForPoolsWithProducts(owner, batch); } } }</code><technical_language>Iterables.partition method here, creates a view sections of original collection instead of copy blocks a new list. reduce this (something close to) example: for (List<String> block : Iterables.partition(productIds, IN_OPERATOR_BLOCK_SIZE)) { this.markCertificatesDirtyForPoolsWithNormalProducts(owner, block); this.markCertificatesDirtyForPoolsWithProvidedProducts(owner, block); }</technical_language>

Target:
public void markCertificatesDirtyForPoolsWithProducts(Owner owner, Collection<String> productIds) { for (List<String> batch : Iterables.partition(productIds, IN_OPERATOR_BLOCK_SIZE)) { markCertificatesDirtyForPoolsWithNormalProducts(owner, batch); markCertificatesDirtyForPoolsWithProvidedProducts(owner, batch); } }
Source:
<code>public <T> T construct(Class<T> componentType) { if (!configuration.transaction().transactionMode().isTransactional()) { return null; } TransactionManager transactionManager = null; <START> if (transactionManager == null) { <END> TransactionManagerLookup lookup = configuration.transaction().transactionManagerLookup(); try { if (lookup != null) { componentRegistry.wireDependencies(lookup); transactionManager = lookup.getTransactionManager(); } } catch (Exception e) { log.couldNotInstantiateTransactionManager(e); } } if (transactionManager == null && configuration.invocationBatching().enabled()) { log.usingBatchModeTransactionManager(); transactionManager = BatchModeTransactionManager.getInstance(); } if (transactionManager == null) { throw new CacheException("This is transactional cache but no transaction manager could be found. " + "Configure the transaction manager lookup properly."); } return componentType.cast(transactionManager); }</code><technical_language>this condition true</technical_language>

Target:
public <T> T construct(Class<T> componentType) { if (!configuration.transaction().transactionMode().isTransactional()) { return null; } TransactionManager transactionManager = null; TransactionManagerLookup lookup = configuration.transaction().transactionManagerLookup(); try { if (lookup != null) { componentRegistry.wireDependencies(lookup); transactionManager = lookup.getTransactionManager(); } } catch (Exception e) { log.couldNotInstantiateTransactionManager(e); } if (transactionManager == null && configuration.invocationBatching().enabled()) { log.usingBatchModeTransactionManager(); transactionManager = BatchModeTransactionManager.getInstance(); } if (transactionManager == null) { throw new CacheException("This is transactional cache but no transaction manager could be found. " + "Configure the transaction manager lookup properly."); } return componentType.cast(transactionManager); }