auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void setDateTime(String date, String time, TimeZone tz) { Date dateObject = DateUtils.toDate(date, time, tz); <START> if (dateObject == null) { if (invalidDateStrategy == null) { throw new IllegalArgumentException("Date or time parameter is invalid."); } else { LOG.warn("Could not parse date/time. Attempting invalid date strategy: {}", invalidDateStrategy); switch (invalidDateStrategy.toUpperCase()) { case "USE_CURRENT": Date now = new Date(); date = new SimpleDateFormat("yyyy-MM-dd").format(now); dateObject = DateUtils.toDate(date, time, tz); if (dateObject == null) { LOG.warn("Couldn't parse time. Using current time instead."); dateObject = now; } break; default: throw new IllegalArgumentException("Date or time parameter is invalid."); } } } <END> LOG.debug("Setting date to {}", date); setDateTime(dateObject); }</code><technical_language>Consider Strategy Design pattern extracting this code class implementing strategy</technical_language>

Target:
public void setDateTime(String date, String time, TimeZone tz) { Date dateObject = DateUtils.toDate(date, time, tz); setDateTime(dateObject); }
Source:
<code>public static void saveNote(Note note) { if (note != null) { try { Note object = getNotesBucket().insertObject(note.getId(), Note.Schema.getJSON(note)); object.save(); } catch (BucketObjectNameInvalid e) { <START> e.printStackTrace(); <END> } } }</code><technical_language>log this error Log.e method</technical_language>

Target:
public static void saveNote(Note note) { if (note != null) { try { Note object = getNotesBucket().insertObject(note.getId(), Note.Schema.getJSON(note)); object.save(); } catch (BucketObjectNameInvalid e) { AppLog.e(AppLog.T.SIMPERIUM, e.getMessage()); } } }
Source:
<code>public void deleteEncounter(String id) { org.openmrs.Encounter encounter = Context.getEncounterService().getEncounterByUuid(id); if (encounter == null) { Visit visit = Context.getVisitService().getVisitByUuid(id); if (visit == null) { <START> IIdType idType = new IdDt(); <END> idType.setValue(id); throw new ResourceNotFoundException(idType); } else { Context.getVisitService().voidVisit(visit, "DELETED by FHIR request"); } } else { Context.getEncounterService().voidEncounter(encounter, "DELETED by FHIR request"); } }</code><technical_language>is this IdDt I IDType</technical_language>

Target:
public void deleteEncounter(String id) { org.openmrs.Encounter encounter = Context.getEncounterService().getEncounterByUuid(id); if (encounter == null) { Visit visit = Context.getVisitService().getVisitByUuid(id); if (visit == null) { IIdType idType = new IdType(); idType.setValue(id); throw new ResourceNotFoundException(idType); } else { Context.getVisitService().voidVisit(visit, FHIRConstants.ENCOUNTER_DELETE_MESSAGE); } } else { Context.getEncounterService().voidEncounter(encounter, FHIRConstants.ENCOUNTER_DELETE_MESSAGE); } }
Source:
<code><START> public Map<String, Object> getVariables() { <END> return variables; }</code><technical_language>return a new linkedhasmap I</technical_language>

Target:
public Map<String, Object> getVariables() { return new LinkedHashMap<>(variables); }
Source:
<code>private ProcessResult processEMLFile(AbstractFile abstractFile) { String fileName; try { fileName = getTempPath() + File.separator + abstractFile.getName() + "-" + String.valueOf(abstractFile.getId()); } catch (NoCurrentCaseException ex) { logger.log(Level.SEVERE, "Exception while getting open case.", ex); return ProcessResult.ERROR; } File file = new File(fileName); long freeSpace = services.getFreeDiskSpace(); if ((freeSpace != IngestMonitor.DISK_FREE_SPACE_UNKNOWN) && (abstractFile.getSize() >= freeSpace)) { logger.log(Level.WARNING, String.format("Not enough disk space to write file '%s' (id=%d) to disk.", abstractFile.getName(), abstractFile.getId())); return ProcessResult.OK; } try { <START> ContentUtils.writeToFile(abstractFile, file, context::fileIngestIsCancelled); <END> } catch (IOException ex) { logger.log(Level.WARNING, String.format("Failed writing the vCard file '%s' (id=%d) to disk.", abstractFile.getName(), abstractFile.getId()), ex); return ProcessResult.OK; } try { EmailMessage message = EMLParser.parse(abstractFile, fileName); if(message == null) { return ProcessResult.OK; } List<AbstractFile> derivedFiles = new ArrayList<>(); BlackboardArtifact msgArtifact = addEmailArtifact(message, abstractFile); if ((msgArtifact != null) && (message.hasAttachment())) { derivedFiles.addAll(handleAttachments(message.getAttachments(), abstractFile, msgArtifact )); } if (derivedFiles.isEmpty() == false) { for (AbstractFile derived : derivedFiles) { services.fireModuleContentEvent(new ModuleContentEvent(derived)); } } context.addFilesToJob(derivedFiles); } catch (IOException ex) { logger.log(Level.WARNING, String.format("Error reading eml file %s", abstractFile.getName()), ex); return ProcessResult.ERROR; } catch (MimeException ex) { logger.log(Level.WARNING, String.format("Error reading eml file %s", abstractFile.getName()), ex); return ProcessResult.ERROR; } return ProcessResult.OK; }</code><technical_language>Do delete local file process it</technical_language>

Target:
private ProcessResult processEMLFile(AbstractFile abstractFile) { try { EmailMessage message = EMLParser.parse(abstractFile); if (message == null) { return ProcessResult.OK; } List<AbstractFile> derivedFiles = new ArrayList<>(); BlackboardArtifact msgArtifact = addEmailArtifact(message, abstractFile); if ((msgArtifact != null) && (message.hasAttachment())) { derivedFiles.addAll(handleAttachments(message.getAttachments(), abstractFile, msgArtifact)); } if (derivedFiles.isEmpty() == false) { for (AbstractFile derived : derivedFiles) { services.fireModuleContentEvent(new ModuleContentEvent(derived)); } } context.addFilesToJob(derivedFiles); } catch (IOException ex) { logger.log(Level.WARNING, String.format("Error reading eml file %s", abstractFile.getName()), ex); return ProcessResult.ERROR; } catch (MimeException ex) { logger.log(Level.WARNING, String.format("Error reading eml file %s", abstractFile.getName()), ex); return ProcessResult.ERROR; } return ProcessResult.OK; }
Source:
<code><START> protected Integer exitStatus(FilePath workspace, TaskListener listener) throws IOException, InterruptedException { <END> FilePath status = getResultFile(workspace); return status.act(STATUS_CHECK_INSTANCE); }</code><technical_language>Add CheckForNull unboxes int FindBugs silent</technical_language>

Target:
protected @CheckForNull Integer exitStatus(FilePath workspace, TaskListener listener) throws IOException, InterruptedException { FilePath status = getResultFile(workspace); return status.act(STATUS_CHECK_INSTANCE); }
Source:
<code>public void testTriplet() { Object o1 = new Object(); Object o2 = new Object(); Object o3 = new Object(); <START> Triplet<Object, Object, Object> pair = new Triplet<Object, Object, Object>(o1, o2, o3); <END> Assert.assertEquals("Actual pair object x does not match expected, original object x.", pair.getX(), o1); Assert.assertEquals("Actual pair object y does not match expected, original object y.", pair.getY(), o2); Assert.assertEquals("Actual pair object z does not match expected, original object z.", pair.getZ(), o3); }</code><technical_language>F... rename pair -> triplet real quick. This terrible</technical_language>

Target:
public void testTriplet() { Object o1 = new Object(); Object o2 = new Object(); Object o3 = new Object(); Triplet<Object, Object, Object> triplet = new Triplet<Object, Object, Object>(o1, o2, o3); Assert.assertEquals("Actual pair object x does not match expected, original object x.", triplet.getX(), o1); Assert.assertEquals("Actual pair object y does not match expected, original object y.", triplet.getY(), o2); Assert.assertEquals("Actual pair object z does not match expected, original object z.", triplet.getZ(), o3); }
Source:
<code>protected void executeQueryCommand() { String password = null; try { final String token = sessionDataContainer.getSsoAccessToken(getParameters().getSessionId()); <START> if (StringUtils.isEmpty(token)) { <END> throw new RuntimeException("Unable to get sso access token for session."); } password = FiltersHelper.getPassword(token); } catch (Exception ex) { log.error("Unable to execute IsPasswordDelegationPossibleQuery with message {}", ex.getMessage()); log.debug("Exception", ex); } getQueryReturnValue().setReturnValue(password != null); getQueryReturnValue().setSucceeded(true); }</code><technical_language>add this check FiltersHelper.getPassword method, I twice, in VmLogonCommand.java</technical_language>

Target:
protected void executeQueryCommand() { String password = null; try { password = SsoUtils.getPassword(sessionDataContainer.getSsoAccessToken(getParameters().getSessionId())); } catch(Exception ex) { log.error("Unable to execute IsPasswordDelegationPossibleQuery with message {}", ex.getMessage()); log.debug("Exception", ex); } getQueryReturnValue().setReturnValue(password != null); getQueryReturnValue().setSucceeded(true); }
Source:
<code>public Map<Cell, byte[]> get(TableReference tableRef, Set<Cell> cells) { if (cells.isEmpty()) { return ImmutableMap.of(); } Set<Cell> toLoad = Sets.newHashSet(); Map<Cell, byte[]> cacheHit = Maps.newHashMapWithExpectedSize(cells.size()); for (Cell cell : cells) { byte[] val = getCachedCellIfPresent(tableRef, cell); if (val != null) { if (val.length > 0) { cacheHit.put(cell, val); } } else { toLoad.add(cell); } } final Map<Cell, byte[]> loaded = super.get(tableRef, toLoad); cacheLoadedCells(tableRef, toLoad, loaded); cacheHit.putAll(loaded); <START> return cacheHit; <END> }</code><technical_language>Feels refactor some shared code #get instead of copying</technical_language>

Target:
public Map<Cell, byte[]> get(TableReference tableRef, Set<Cell> cells) { try { return getWithLoader( tableRef, cells, (tableReference, toRead) -> Futures.immediateFuture(super.get(tableReference, toRead))).get(); } catch (InterruptedException | ExecutionException e) { throw Throwables.rewrapAndThrowUncheckedException(e.getCause()); } }
Source:
<code><START> private void prepareMockFileUrls() throws URISyntaxException { <END> when(fileServiceClient.getFileUri(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE + FILE)).thenReturn(new URI(SOURCE_VERSION_URL)); when(fileServiceClient.getFileUri(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE + FILE2)).thenReturn(new URI(SOURCE_VERSION_URL_FILE2)); }</code><technical_language>I this method is final while others similar are. is reason for final methods here</technical_language>

Target:
private final void prepareMockFileUrls() throws URISyntaxException { when(fileServiceClient.getFileUri(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE + FILE)).thenReturn(new URI(SOURCE_VERSION_URL)); when(fileServiceClient.getFileUri(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE + FILE2)).thenReturn(new URI(SOURCE_VERSION_URL_FILE2)); }
Source:
<code>void free(long address) { if (trace) { <START> Long prev = allocatedBlocks.remove(address); <END> if (prev == null) { throw new IllegalArgumentException(); } } UNSAFE.freeMemory(address); }</code><technical_language>Oops, good catch</technical_language>

Target:
void free(long address) { Long prev = allocatedBlocks.remove(address); if (trace) { if (prev == null) { throw new IllegalArgumentException(); } } UNSAFE.freeMemory(address); }
Source:
<code>private Optional<RevCommit> refToCommit(RevWalk walk, Ref ref) throws IOException { <START> RevObject maybehead = walk.parseAny(ref.getObjectId()); <END> if (!(maybehead instanceof RevCommit)) { return Optional.empty(); } return Optional.of((RevCommit) maybehead); }</code><technical_language>walk.parseCommit() instead</technical_language>

Target:
private Optional<RevCommit> refToCommit(RevWalk walk, Ref ref) throws IOException { try { return Optional.of(walk.parseCommit(ref.getObjectId())); } catch (IncorrectObjectTypeException e) { return Optional.empty(); } }
Source:
<code>public void onTestFail(DataRecord testData, Description description, Failure failure) { if (mDestDir == null) { return; } final String fileName = String.format( <START> "%s.%s-%d", <END> description.getClassName(), description.getMethodName(), mTestIterations.get(description.getDisplayName())); final String pngFileName = String.format("%s.png", fileName); File img = takeScreenshot(pngFileName); if (img != null) { testData.addFileMetric(String.format("%s_%s", getTag(), img.getName()), img); } if (mIncludeUiXml) { File uixFile = collectUiXml(fileName); if (uixFile != null) { testData.addFileMetric( String.format("%s_%s", getTag(), uixFile.getName()), uixFile); } } }</code><technical_language>I woud omit name-1 one, other people's results changed</technical_language>

Target:
public void onTestFail(DataRecord testData, Description description, Failure failure) { if (mDestDir == null) { return; } final String fileNameBase = String.format("%s.%s", description.getClassName(), description.getMethodName()); int iteration = mTestIterations.get(description.getDisplayName()); final String fileName = iteration == 1 ? fileNameBase : String.join("-", fileNameBase, String.valueOf(iteration)); final String pngFileName = String.format("%s.png", fileName); File img = takeScreenshot(pngFileName); if (img != null) { testData.addFileMetric(String.format("%s_%s", getTag(), img.getName()), img); } if (mIncludeUiXml) { File uixFile = collectUiXml(fileName); if (uixFile != null) { testData.addFileMetric( String.format("%s_%s", getTag(), uixFile.getName()), uixFile); } } }
Source:
<code>public void TestSerDesr() throws IOException { <START> LookupConfig lookupConfig = new LookupConfig(Files.createTempDir().getAbsolutePath()); <END> Assert.assertEquals(lookupConfig, mapper.reader(LookupConfig.class).readValue(mapper.writeValueAsString(lookupConfig))); }</code><technical_language>@Rule TemporaryFolder temporaryFolder = new TemporaryFolder() a test class field instead</technical_language>

Target:
public void TestSerDesr() throws IOException { LookupConfig lookupConfig = new LookupConfig(temporaryFolder.newFile().getAbsolutePath()); Assert.assertEquals(lookupConfig, mapper.reader(LookupConfig.class).readValue(mapper.writeValueAsString(lookupConfig))); }
Source:
<code><START> void createWithException() throws Exception <END> { XWikiDocument document = mock(XWikiDocument.class); DocumentReference documentReference = new DocumentReference("wiki", "Space", "Page"); when(this.xcontext.getWiki().getDocument(documentReference, this.xcontext)).thenThrow(new XWikiException()); this.modelBridge.create(documentReference); assertLog(Level.ERROR, "Failed to create document [{}].", documentReference); }</code><technical_language>methods throw exceptions</technical_language>

Target:
void createWithException() throws Exception { DocumentReference documentReference = new DocumentReference("wiki", "Space", "Page"); when(this.xcontext.getWiki().getDocument(documentReference, this.xcontext)).thenThrow(new XWikiException()); this.modelBridge.create(documentReference); assertLog(Level.ERROR, "Failed to create document [{}].", documentReference); }
Source:
<code>public static void main(String[] args) { Flyway flyway = new Flyway(); flyway.setDataSource(properties.getProperty("databaseUrl"), properties.getProperty("databaseUrl"), properties.getProperty("databaseUrl")); <START> flyway.setInitVersion("0"); <END> flyway.setLocations("classpath:org.cru.godtools.migration", "classpath:db.migration"); flyway.migrate(); }</code><technical_language>@ryancarlson this database, username, password</technical_language>

Target:
public static void main(String[] args) { Flyway flyway = new Flyway(); flyway.setDataSource(properties.getProperty("databaseUrl"), properties.getProperty("databaseUsername"), properties.getProperty("databasePassword")); flyway.setInitVersion("0"); flyway.setLocations("classpath:org.cru.godtools.migration", "classpath:db.migration"); flyway.migrate(); }
Source:
<code><START> Message<?> doPoll() { <END> Message<?> message = this.messageGroupStore.pollMessageFromGroup(this.groupId); this.messageStoreNotFull.signal(); return message; }</code><technical_language>happened this method? a private anymore</technical_language>

Target:
protected Message<?> doPoll() { Message<?> message = this.messageGroupStore.pollMessageFromGroup(this.groupId); this.messageStoreNotFull.signal(); return message; }
Source:
<code>private static void writeMercs(SolGame game) { String fileName = getRsrcPath("mercenaries.json"); PrintWriter writer; <START> ItemContainer mercIc = game.getHero().getTradeContainer().getMercs(); <END> List<JsonObject> jsons = new ArrayList<JsonObject>(); JsonObject json; for (List<SolItem> group : mercIc) { for (SolItem item : group) { SolShip merc = ((MercItem) item).getSolShip(); String hullName = game.getHullConfigs().getName(merc.getHull().config); int money = (int) merc.getMoney(); ArrayList<SolItem> itemsList = new ArrayList<SolItem>(); for (List<SolItem> group1 : merc.getItemContainer()) { for (SolItem i : group1) { itemsList.add(0, i); } } String items = itemsToString(itemsList); json = new JsonObject(); json.addProperty("hull", hullName); json.addProperty("money", money); json.addProperty("items", items); jsons.add(json); } } Gson gson = new GsonBuilder().setPrettyPrinting().create(); String toWrite = gson.toJson(jsons); try { writer = new PrintWriter(fileName, "UTF-8"); writer.write(toWrite); writer.close(); } catch (FileNotFoundException | UnsupportedEncodingException e) { logger.error("Could not save mercenaries, " + e.getMessage()); } }</code><technical_language>mercIc ..</technical_language>

Target:
private static void writeMercs(SolGame game) { PrintWriter writer; ItemContainer mercenaries = game.getHero().getTradeContainer().getMercs(); List<JsonObject> jsons = new ArrayList<JsonObject>(); for (List<SolItem> group : mercenaries) { for (SolItem item : group) { SolShip merc = ((MercItem) item).getSolShip(); String hullName = game.getHullConfigs().getName(merc.getHull().config); int money = (int) merc.getMoney(); ArrayList<SolItem> itemsList = new ArrayList<SolItem>(); for (List<SolItem> group1 : merc.getItemContainer()) { for (SolItem i : group1) { itemsList.add(0, i); } } String items = itemsToString(itemsList); JsonObject json = new JsonObject(); json.addProperty("hull", hullName); json.addProperty("money", money); json.addProperty("items", items); jsons.add(json); } } Gson gson = new GsonBuilder().setPrettyPrinting().create(); String toWrite = gson.toJson(jsons); try { writer = new PrintWriter(MERC_SAVE_FILE, "UTF-8"); writer.write(toWrite); writer.close(); } catch (FileNotFoundException | UnsupportedEncodingException e) { logger.error("Could not save mercenaries, " + e.getMessage()); } }
Source:
<code>private String getTracerConfiguration(DeploymentPhaseContext deploymentPhaseContext) { DeploymentUnit deploymentUnit = deploymentPhaseContext.getDeploymentUnit(); JBossWebMetaData jbossWebMetaData = getJBossWebMetaData(deploymentUnit); if (null == jbossWebMetaData || null == jbossWebMetaData.getContextParams()) { return null; } for (ParamValueMetaData param : jbossWebMetaData.getContextParams()) { <START> if (TracerInitializer.SMALLRYE_OPENTRACING_TRACER_CONFIGURATION.equals(param.getParamName())) { <END> return param.getParamValue(); } } final CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT); for (ServiceName serviceName : deploymentPhaseContext.getServiceRegistry().getServiceNames()) { if (serviceName.getCanonicalName().startsWith(TRACER_CAPABILITY_NAME) && support.hasCapability(DEFAULT_TRACER_CAPABILITY.getDynamicName(serviceName.getSimpleName()))) { return serviceName.getSimpleName(); } } return null; }</code><technical_language>read opentracing spec thoroughly... Is this users define opentracing configuration? I expect this configuration defined MP Config. Configuration servlet context parameters is retro</technical_language>

Target:
private String getTracerConfiguration(DeploymentPhaseContext deploymentPhaseContext) { DeploymentUnit deploymentUnit = deploymentPhaseContext.getDeploymentUnit(); JBossWebMetaData jbossWebMetaData = getJBossWebMetaData(deploymentUnit); if (null == jbossWebMetaData || null == jbossWebMetaData.getContextParams()) { return null; } for (ParamValueMetaData param : jbossWebMetaData.getContextParams()) { if (SMALLRYE_OPENTRACING_TRACER_CONFIGURATION.equals(param.getParamName())) { String value = param.getParamValue(); if (value != null && !value.isEmpty()) { return TRACER_CAPABILITY.getDynamicName(param.getParamValue()); } } } final CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT); if (support.hasCapability(DEFAULT_TRACER_CAPABILITY_NAME)) { return WildFlyTracerFactory.getDefaultTracerName(); } return null; }
Source:
<code>public OffsetsForLeaderEpochRequest(Struct struct, short version) { super(ApiKeys.OFFSET_FOR_LEADER_EPOCH, version); <START> replicaId = struct.get(REPLICA_ID); <END> epochsByPartition = new HashMap<>(); for (Object topicAndEpochsObj : struct.get(TOPICS)) { Struct topicAndEpochs = (Struct) topicAndEpochsObj; String topic = topicAndEpochs.get(TOPIC_NAME); for (Object partitionAndEpochObj : topicAndEpochs.get(PARTITIONS)) { Struct partitionAndEpoch = (Struct) partitionAndEpochObj; int partitionId = partitionAndEpoch.get(PARTITION_ID); int leaderEpoch = partitionAndEpoch.get(LEADER_EPOCH); Optional<Integer> currentEpoch = RequestUtils.getLeaderEpoch(partitionAndEpoch, CURRENT_LEADER_EPOCH); TopicPartition tp = new TopicPartition(topic, partitionId); epochsByPartition.put(tp, new PartitionData(currentEpoch, leaderEpoch)); } } }</code><technical_language>Hmm this fail for schema. I getOrElse</technical_language>

Target:
public OffsetsForLeaderEpochRequest(Struct struct, short version) { super(ApiKeys.OFFSET_FOR_LEADER_EPOCH, version); replicaId = struct.getOrElse(REPLICA_ID, CONSUMER_REPLICA_ID); epochsByPartition = new HashMap<>(); for (Object topicAndEpochsObj : struct.get(TOPICS)) { Struct topicAndEpochs = (Struct) topicAndEpochsObj; String topic = topicAndEpochs.get(TOPIC_NAME); for (Object partitionAndEpochObj : topicAndEpochs.get(PARTITIONS)) { Struct partitionAndEpoch = (Struct) partitionAndEpochObj; int partitionId = partitionAndEpoch.get(PARTITION_ID); int leaderEpoch = partitionAndEpoch.get(LEADER_EPOCH); Optional<Integer> currentEpoch = RequestUtils.getLeaderEpoch(partitionAndEpoch, CURRENT_LEADER_EPOCH); TopicPartition tp = new TopicPartition(topic, partitionId); epochsByPartition.put(tp, new PartitionData(currentEpoch, leaderEpoch)); } } }
Source:
<code>@Override public Enumerable<Object[]> scan(DataContext root) { root.getRootSchema().add(name, this); final AtomicBoolean cancelFlag = DataContext.Variable.CANCEL_FLAG.get(root); return new AbstractEnumerable<Object[]>() { public Enumerator<Object[]> enumerator() { return new Enumerator<Object[]>() { private final List list = new ArrayList(rows); private int i = -1; @Override public Object[] current() { Object current = list.get(i); if (current == null) { return null; <START> } <END> return current.getClass().isArray() ? (Object[]) current : new Object[]{current}; } @Override public boolean moveNext() { if (cancelFlag != null && cancelFlag.get()) { return false; } return ++i < list.size(); } @Override public void reset() { i = -1; } @Override public void close() { } }; } }; }</code><technical_language>current null</technical_language>

Target:
@Override public Enumerable<Object[]> scan(DataContext root) { root.getRootSchema().add(name, this); final AtomicBoolean cancelFlag = DataContext.Variable.CANCEL_FLAG.get(root); return new AbstractEnumerable<Object[]>() { public Enumerator<Object[]> enumerator() { return new Enumerator<Object[]>() { private final List list = new ArrayList(rows); private int i = -1; @Override public Object[] current() { Object current = list.get(i); return current != null && current.getClass().isArray() ? (Object[]) current : new Object[]{current}; } @Override public boolean moveNext() { if (cancelFlag != null && cancelFlag.get()) { return false; } return ++i < list.size(); } @Override public void reset() { i = -1; } @Override public void close() { } }; } }; }
Source:
<code>private void restoreTable( String tableName, TableBackup tableBackup, KijiMetaTable metaTable, Kiji kiji) throws IOException { Preconditions.checkNotNull(tableBackup); Preconditions.checkNotNull(tableBackup.getTableLayoutsBackup()); List<TableLayoutBackupEntry> layouts = tableBackup.getTableLayoutsBackup().getLayouts(); Preconditions.checkArgument(!layouts.isEmpty(), "Backup for table '%s' contains no layout.", tableName); LOG.info("Creating table '{}'.", tableName); long lowestTimestamp = KConstants.END_OF_TIME; TableLayoutBackupEntry initialEntry = null; for (TableLayoutBackupEntry entry : layouts) { if (entry.getTimestamp() < lowestTimestamp) { lowestTimestamp = entry.getTimestamp(); initialEntry = entry; } } final KijiTableLayout initialLayout = KijiTableLayout.newLayout(initialEntry.getLayout()); try { <START> kiji.createTable(tableName, initialLayout.getDesc()); <END> } catch (KijiAlreadyExistsException kaee) { LOG.info("Table already exists in HBase. Continuing with restore operation."); } LOG.info("Restoring layout history for table '%s' (%d layouts).", tableName, tableBackup.getTableLayoutsBackup().getLayouts().size()); metaTable.layoutsFromBackup(tableName, tableBackup.getTableLayoutsBackup()); metaTable.keyValuesFromBackup(tableName, tableBackup.getKeyValueBackup()); }</code><technical_language>I remove initialLayout initialEntry.getLayout()</technical_language>

Target:
private void restoreTable( String tableName, TableBackup tableBackup, KijiMetaTable metaTable, Kiji kiji) throws IOException { Preconditions.checkNotNull(tableBackup); Preconditions.checkNotNull(tableBackup.getTableLayoutsBackup()); List<TableLayoutBackupEntry> layouts = tableBackup.getTableLayoutsBackup().getLayouts(); Preconditions.checkArgument(!layouts.isEmpty(), "Backup for table '%s' contains no layout.", tableName); LOG.info("Creating table '{}'.", tableName); long lowestTimestamp = KConstants.END_OF_TIME; TableLayoutBackupEntry initialEntry = null; for (TableLayoutBackupEntry entry : layouts) { if (entry.getTimestamp() < lowestTimestamp) { lowestTimestamp = entry.getTimestamp(); initialEntry = entry; } } try { kiji.createTable(initialEntry.getLayout()); } catch (KijiAlreadyExistsException kaee) { LOG.info("Table already exists in HBase. Continuing with restore operation."); } LOG.info("Restoring layout history for table '%s' (%d layouts).", tableName, tableBackup.getTableLayoutsBackup().getLayouts().size()); metaTable.layoutsFromBackup(tableName, tableBackup.getTableLayoutsBackup()); metaTable.keyValuesFromBackup(tableName, tableBackup.getKeyValueBackup()); }
Source:
<code>public <U> PriorityQueue<U> flatMap(Function<? super T, ? extends Iterable<? extends U>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); <START> throw new UnsupportedOperationException(); END> }</code><technical_language>Copied TreeSet: java @Override public <U> TreeSet<U> flatMap(Comparator<? super U> comparator, Function<? super T, ? extends Iterable<? extends U>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return TreeSet.ofAll(comparator, iterator().flatMap(mapper)); } @Override public <U> TreeSet<U> flatMap(Function<? super T, ? extends Iterable<? extends U>> mapper) { return flatMap(naturalComparator(), mapper); }</technical_language>

Target:
public <U> PriorityQueue<U> flatMap(Function<? super T, ? extends Iterable<? extends U>> mapper) { return flatMap(naturalComparator(), mapper); }
Source:
<code>public boolean remove(T value) { NodePair window = find(value); <START> if (window.second.getValue().compareTo(value) != 0) return false; <END> while (true) { Node next = window.second.nextAndState.getReference(); if (!window.second.nextAndState.attemptMark(next, true)) continue; window.first.nextAndState.compareAndSet(window.second, next, false, false); return true; } }</code><technical_language>= Iteration 2 / 10 = Actors thread: [get(1), put(1), remove(4)] [remove(5), put(2), get(4), put(3), put(3), put(1)] [put(5), get(1), remove(5)] Exception in thread "main" java.lang.IllegalStateException: java.lang.reflect.InvocationTargetException com.devexperts.dxlab.lincheck.LinChecker.lambda$check$0(LinChecker.java:84) ... Caused by: java.lang.NullPointerException LockFreeSetImpl.remove(LockFreeSetImpl.java:51) com.hpcourse.ees.linCheckTester.LockFreeSetCheck.remove(LockFreeSetCheck.java:27) ... 36 more</technical_language>

Target:
public boolean remove(T value) { NodePair window = find(value); if (window.second == null || window.second.getValue().compareTo(value) != 0) return false; while (true) { Node next = window.second.nextAndState.getReference(); if (!window.second.nextAndState.attemptMark(next, true)) continue; window.first.nextAndState.compareAndSet(window.second, next, false, false); return true; } }
Source:
<code>public long createEmbeddedObject(long columnKey, RealmFieldType parentPropertyType) { switch (parentPropertyType) { case OBJECT: parent.checkImmutable(); return nativeCreateEmbeddedObject(nativePtr, columnKey); case LIST: return getModelList(columnKey).createAndAddEmbeddedObject(); default: <START> throw new IllegalArgumentException("Wrong parentPropertyType, expected OBJECT or LIST bur received " + parentPropertyType); <END> } }</code><technical_language>suggestion throw new IllegalArgumentException("Wrong parentPropertyType, expected OBJECT LIST received " + parentPropertyType);</technical_language>

Target:
public long createEmbeddedObject(long columnKey, RealmFieldType parentPropertyType) { switch (parentPropertyType) { case OBJECT: parent.checkImmutable(); return nativeCreateEmbeddedObject(nativePtr, columnKey); case LIST: return getModelList(columnKey).createAndAddEmbeddedObject(); default: throw new IllegalArgumentException("Wrong parentPropertyType, expected OBJECT or LIST but received " + parentPropertyType); } }
Source:
<code>public static boolean validateTemplateString(String template) { template = template.trim(); if (template.equals("ID")) { return true; } if (template.equals("LABEL")) { return true; } if (template.equals("TYPE")) { return true; } if (template.equals("CLASS_TYPE")) { return true; } <START> if (template.matches("^(A|>A|>AT|>AL|>AI|>>A|>>AT|>>AL|>>AI|AT|AL|AI|C|>C) .*")) { <END> return true; } if (template.equals("CI")) { return true; } return false; }</code><technical_language>Please simplify like: ^>?C|^>{0,2}(A|AT|AL|AI)</technical_language>

Target:
public static boolean validateTemplateString(String template) { template = template.trim(); if (template.equals("ID")) { return true; } if (template.equals("LABEL")) { return true; } if (template.equals("TYPE")) { return true; } if (template.equals("CLASS_TYPE")) { return true; } if (template.matches("^(>?C|>{0,2}A[L,T,I]?) .*")) { return true; } if (template.equals("CI")) { return true; } return false; }
Source:
<code>public void snapshot(String snapshotName, TableName tableName) throws IOException, SnapshotCreationException, IllegalArgumentException { <START> com.google.longrunning.Operation operation = snapshotTable(snapshotName, tableName); <END> try { waitForOperation(operation.getName()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Create snapshot operation was interrupted", e); } }</code><technical_language>Operation operation = snapshotTable(snapshotName, tableName); if (operation.isDone()) { return; }</technical_language>

Target:
public void snapshot(String snapshotName, TableName tableName) throws IOException, SnapshotCreationException, IllegalArgumentException { waitForOperation(snapshotTable(snapshotName, tableName)); }
Source:
<code>public int getWifiEnabledState() { enforceAccessPermission(); <START> mLog.trace("getWifiEnabledStated uid=%").c(Binder.getCallingUid()).flush(); <END> return mWifiStateMachine.syncGetWifiState(); }</code><technical_language>typo</technical_language>

Target:
public int getWifiEnabledState() { enforceAccessPermission(); mLog.trace("getWifiEnabledState uid=%").c(Binder.getCallingUid()).flush(); return mWifiStateMachine.syncGetWifiState(); }
Source:
<code>private void do_testGetContent_gzipEncoding_finishReading(String contentEncoding) throws IOException { byte[] dataToCompress = "abcd".getBytes(StandardCharsets.UTF_8); <START> byte[] mockBytes; <END> try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream(dataToCompress.length)) { GZIPOutputStream zipStream = new GZIPOutputStream((byteStream)); zipStream.write(dataToCompress); zipStream.close(); mockBytes = byteStream.toByteArray(); } final MockLowLevelHttpResponse mockResponse = new MockLowLevelHttpResponse(); mockResponse.setContent(mockBytes); mockResponse.setContentEncoding(contentEncoding); mockResponse.setContentType("text/plain"); HttpTransport transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, final String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { return mockResponse; } }; } }; HttpRequest request = transport.createRequestFactory().buildHeadRequest(HttpTesting.SIMPLE_GENERIC_URL); HttpResponse response = request.execute(); TestableByteArrayInputStream output = (TestableByteArrayInputStream) mockResponse.getContent(); assertFalse(output.isClosed()); assertEquals("abcd", response.parseAsString()); assertTrue(output.isClosed()); }</code><technical_language>push this (and more) try block</technical_language>

Target:
private void do_testGetContent_gzipEncoding_finishReading(String contentEncoding) throws IOException { byte[] dataToCompress = "abcd".getBytes(StandardCharsets.UTF_8); byte[] mockBytes; try ( ByteArrayOutputStream byteStream = new ByteArrayOutputStream(dataToCompress.length); GZIPOutputStream zipStream = new GZIPOutputStream((byteStream)) ) { zipStream.write(dataToCompress); zipStream.close(); mockBytes = byteStream.toByteArray(); } final MockLowLevelHttpResponse mockResponse = new MockLowLevelHttpResponse(); mockResponse.setContent(mockBytes); mockResponse.setContentEncoding(contentEncoding); mockResponse.setContentType("text/plain"); HttpTransport transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, final String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { return mockResponse; } }; } }; HttpRequest request = transport.createRequestFactory().buildHeadRequest(HttpTesting.SIMPLE_GENERIC_URL); HttpResponse response = request.execute(); try (TestableByteArrayInputStream output = (TestableByteArrayInputStream) mockResponse.getContent()) { assertFalse(output.isClosed()); assertEquals("abcd", response.parseAsString()); assertTrue(output.isClosed()); } }
Source:
<code><START> private void safeCloseStream(Closeable stream) { <END> if (stream != null) { try { stream.close(); } catch (IOException e) { Logger.e(TAG, "Failed to close the stream: ", "", ADALError.IO_EXCEPTION, e); } } }</code><technical_language>static</technical_language>

Target:
private static void safeCloseStream(Closeable stream) { if (stream != null) { try { stream.close(); } catch (IOException e) { Logger.e(TAG, "Failed to close the stream: ", "", ADALError.IO_EXCEPTION, e); } } }
Source:
<code>public static int readDelivery(Receiver receiver, ByteBuf buffer) { int initial = buffer.writerIndex(); int count; while ((count = receiver.recv(buffer.array(), buffer.arrayOffset() + buffer.writerIndex(), buffer.writableBytes())) > 0) { buffer.writerIndex(buffer.writerIndex() + count); <START> if (buffer.writableBytes() <= 0) { <END> buffer.ensureWritable(count); } } return buffer.writerIndex() - initial; }</code><technical_language>this if (buffer.writableBytes() < count) get a situation space for part of buffer coming</technical_language>

Target:
public static int readDelivery(Receiver receiver, ByteBuf buffer) { int initial = buffer.writerIndex(); int count; while ((count = receiver.recv(buffer.array(), buffer.arrayOffset() + buffer.writerIndex(), buffer.writableBytes())) > 0) { buffer.writerIndex(buffer.writerIndex() + count); buffer.ensureWritable(count); } return buffer.writerIndex() - initial; }
Source:
<code>public InputStream getInputStream(boolean buffered) { <START> if (inputStream != null) { <END> return inputStream; } InputStream inputStream = requestContext.getInputStream(); return inputStream; }</code><technical_language>a local variable shares a name a class instance variable, try explicit referencing this.inputStream (or similar appropriate). aside, instance variable is set, this check succeed</technical_language>

Target:
public InputStream getInputStream(boolean buffered) { return requestContext.getInputStream(); }
Source:
<code>void setColumns(List<String> columns) { <START> for (ListIterator<String> iterator = columns.listIterator(); iterator .hasNext();) { String string = iterator.next(); iterator.set(StringUtils.defaultIfEmpty(string, StringConstants.UNICODE_NULL)); } <END> m_columns = columns; }</code><technical_language>Editing setter is making collection dirty</technical_language>

Target:
void setColumns(List<String> columns) { m_columns = columns; }
Source:
<code>public void onEventMainThread(DiscussionCommentPostedEvent event) { <START> if (null != event.getParent() && event.getParent().getIdentifier().equalsIgnoreCase(discussionResponse.getIdentifier())) { <END> discussionCommentsAdapter.insertCommentAtEnd(event.getComment()); } }</code><technical_language>ignoring case here? Do get inconsistent capitalization? strange</technical_language>

Target:
public void onEventMainThread(DiscussionCommentPostedEvent event) { if (null != event.getParent() && event.getParent().getIdentifier().equals(discussionResponse.getIdentifier())) { discussionCommentsAdapter.insertCommentAtEnd(event.getComment()); } }
Source:
<code>private WinRm getService() { if (winrm != null) { return winrm; } else { if (context != null) { cleanupContext = false; } else { <START> context = WinRmClientContext.newInstance(); <END> cleanupContext = true; } Bus prevBus = BusFactory.getAndSetThreadDefaultBus(context.getBus()); try { return createService(); } finally { if (BusFactory.getThreadDefaultBus(false) != prevBus) { BusFactory.setThreadDefaultBus(prevBus); } } } }</code><technical_language>synchronization is a scary - for example if concurrent calls command(...) use, do multiple calls WinRmClientContext.newInstance(). However, createService is synchronized create WinRm winrm object. However, changes LGTM. improve synchronization in a separate PR some point. p.s. I hate people incorrectly double-checked locking in Java (which is code before, is for initialising winrm field)</technical_language>

Target:
private synchronized WinRm getService() { if (winrm != null) { return winrm; } else { if (context != null) { cleanupContext = false; } else { context = WinRmClientContext.newInstance(); cleanupContext = true; } Bus prevBus = BusFactory.getAndSetThreadDefaultBus(context.getBus()); try { return createService(); } finally { if (BusFactory.getThreadDefaultBus(false) != prevBus) { BusFactory.setThreadDefaultBus(prevBus); } } } }
Source:
<code>public String deployJob( @CliOption(key = { "", "name" }, help = "the name of the job to deploy", mandatory = true, optionContext = "existing-job undeployed disable-string-converter") String name, @CliOption(key = { PROPERTIES_OPTION }, help = "the properties for this deployment", mandatory = false) String properties, @CliOption(key = { PROPERTIES_FILE_OPTION }, help = "the properties for this deployment (as a File)", mandatory = false) File propertiesFile ) throws IOException { int which = Assertions.atMostOneOf(PROPERTIES_OPTION, properties, PROPERTIES_FILE_OPTION, propertiesFile); Map<String, String> propertiesToUse; switch (which) { case 0: propertiesToUse = DeploymentPropertiesFormat.parseDeploymentProperties(properties); break; case 1: Properties props = new Properties(); <START> try (FileInputStream fis = new FileInputStream(propertiesFile)) { <END> props.load(fis); } propertiesToUse = DeploymentPropertiesFormat.convert(props); break; default: throw new AssertionError(); } jobOperations().deploy(name, propertiesToUse); return String.format("Deployed stream '%s'", name); }</code><technical_language>new PatternMatchingResourceResolvert().getResource(propertiesFile).getInputStream() ?? allow file:, classpath:, http:</technical_language>

Target:
public String deployJob( @CliOption(key = { "", "name" }, help = "the name of the job to deploy", mandatory = true, optionContext = "existing-job undeployed disable-string-converter") String name, @CliOption(key = { PROPERTIES_OPTION }, help = "the properties for this deployment", mandatory = false) String properties, @CliOption(key = { PROPERTIES_FILE_OPTION }, help = "the properties for this deployment (as a File)", mandatory = false) File propertiesFile ) throws IOException { int which = Assertions.atMostOneOf(PROPERTIES_OPTION, properties, PROPERTIES_FILE_OPTION, propertiesFile); Map<String, String> propertiesToUse; switch (which) { case 0: propertiesToUse = DeploymentPropertiesFormat.parseDeploymentProperties(properties); break; case 1: Properties props = new Properties(); try (FileInputStream fis = new FileInputStream(propertiesFile)) { props.load(fis); } propertiesToUse = DeploymentPropertiesFormat.convert(props); break; default: throw new AssertionError(); } jobOperations().deploy(name, propertiesToUse); return String.format("Deployed job '%s'", name); }
Source:
<code>public PartitionedLookupSourceFactory(List<Type> types, List<Type> outputTypes, List<Integer> hashChannels, int partitionCount, Map<Symbol, Integer> layout, boolean outer) <START> { <END> this.types = ImmutableList.copyOf(requireNonNull(types, "types is null")); this.outputTypes = ImmutableList.copyOf(requireNonNull(outputTypes, "outputTypes is null")); this.layout = ImmutableMap.copyOf(layout); this.partitions = (Supplier<LookupSource>[]) new Supplier<?>[partitionCount]; this.outer = outer; hashChannelTypes = hashChannels.stream() .map(types::get) .collect(toImmutableList()); spilledLookupSource = new SpilledLookupSource(outputTypes.size()); }</code><technical_language>this @GuardedBy("rwLock")</technical_language>

Target:
public PartitionedLookupSourceFactory(List<Type> types, List<Type> outputTypes, List<Integer> hashChannels, int partitionCount, Map<Symbol, Integer> layout, boolean outer) { this.types = ImmutableList.copyOf(requireNonNull(types, "types is null")); this.outputTypes = ImmutableList.copyOf(requireNonNull(outputTypes, "outputTypes is null")); this.layout = ImmutableMap.copyOf(layout); checkArgument(partitionCount > 0); this.partitions = (Supplier<LookupSource>[]) new Supplier<?>[partitionCount]; this.outer = outer; hashChannelTypes = hashChannels.stream() .map(types::get) .collect(toImmutableList()); spilledLookupSource = new SpilledLookupSource(outputTypes.size()); }
Source:
<code>public void bindTo(MeterRegistry registry) { for (WorkspaceStatus s : WorkspaceStatus.values()) { <START> Gauge.builder("che.workspace.status", activityManager, __ -> count(s)) <END> .tag("status", s.name()) .tag("area", "workspace") .description("The number of workspaces in a given status") .register(registry); } }</code><technical_language>Do need put activityManager ignore ToDoubleFunction? rewrite Gauge#(String name, Supplier<Number> f) like: java Gauge.builder("che.workspace.status", () -> count(s)) .tag("status", s.name()) .tag("area", "workspace") .description("The number of workspaces in a status") .register(registry);</technical_language>

Target:
public void bindTo(MeterRegistry registry) { for (WorkspaceStatus s : WorkspaceStatus.values()) { Gauge.builder("che.workspace.status", () -> count(s)) .tag("status", s.name()) .tag("area", "workspace") .description("The number of workspaces in a given status") .register(registry); } }
Source:
<code>@Override public Result load(Request request, int networkPolicy) throws IOException { okhttp3.Request downloaderRequest = createRequest(request, networkPolicy); Response response = downloader.load(downloaderRequest); ResponseBody body = response.body(); <START> if (response.code() >= 300) { <END> body.close(); throw new ResponseException(response.code(), request.networkPolicy); } Picasso.LoadedFrom loadedFrom = response.cacheResponse() == null ? NETWORK : DISK; if (loadedFrom == DISK && body.contentLength() == 0) { body.close(); throw new ContentLengthException("Received response with 0 content-length header."); } if (loadedFrom == NETWORK && body.contentLength() > 0) { stats.dispatchDownloadFinished(body.contentLength()); } InputStream is = body.byteStream(); return new Result(is, loadedFrom); }</code><technical_language>!response.isSuccessful()</technical_language>

Target:
@Override public Result load(Request request, int networkPolicy) throws IOException { okhttp3.Request downloaderRequest = createRequest(request, networkPolicy); Response response = downloader.load(downloaderRequest); ResponseBody body = response.body(); if (!response.isSuccessful()) { body.close(); throw new ResponseException(response.code(), request.networkPolicy); } Picasso.LoadedFrom loadedFrom = response.cacheResponse() == null ? NETWORK : DISK; if (loadedFrom == DISK && body.contentLength() == 0) { body.close(); throw new ContentLengthException("Received response with 0 content-length header."); } if (loadedFrom == NETWORK && body.contentLength() > 0) { stats.dispatchDownloadFinished(body.contentLength()); } InputStream is = body.byteStream(); return new Result(is, loadedFrom); }
Source:
<code>public Map<String, R> merge(Map<String, R> result1, Map<String, R> result2) { <START> Aggregation<P, R, T> agg = this.result.values().stream().findAny().orElse(null); <END> if (agg == null) { return null; } return Stream.of(result1, result2).flatMap(m -> m.entrySet().stream()).collect( Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, agg::merge)); }</code><technical_language>This function ignore local result instead merge incoming maps</technical_language>

Target:
public Map<String, R> merge(Map<String, R> result1, Map<String, R> result2) { final Aggregation<P, R, T> agg = this.getHelperAggregation(); return Stream.of(result1, result2).flatMap(m -> m.entrySet().stream()).collect( Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, agg::merge)); }
Source:
<code>@Override public void setCard(@NonNull OnboardingCard card) { super.setCard(card); <START> ColorStateList colorStateList = new ColorStateList( new int[][]{new int[]{}}, new int[]{ContextCompat.getColor(getContext(), R.color.base20)} ); ViewCompat.setBackgroundTintList(headerImageView, colorStateList); <END> headerImageView.setImageResource(card.headerImage()); headerTitleView.setText(card.headerText()); imageView.setImageURI(card.fullImage()); actionViewPositive.setText(card.positiveText()); }</code><technical_language>do in xml? If a shame depend runtime</technical_language>

Target:
@Override public void setCard(@NonNull OnboardingCard card) { super.setCard(card); headerImageView.setImageResource(card.headerImage()); headerTitleView.setText(card.headerText()); imageView.setImageURI(card.fullImage()); actionViewPositive.setText(card.positiveText()); }