auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void parse(Scanner in) throws Exception { String line = null; int lineNum = 0; String sectionName = null; Map<String, String> section = null; while (in.hasNextLine()) { line = in.nextLine(); lineNum++; line = line.replaceAll("^\\s+", ""); if (line.isEmpty() || line.startsWith("#")) { continue; } else if (line.startsWith("[")) { if (!line.endsWith("]")) { String msg = MessageFormat.format("Error in service file line {0}: missing ].", lineNum); throw new Exception(msg); } sectionName = line.substring(1, line.length() - 1); section = new HashMap(); sections.put(sectionName, section); } else if (section == null) { String msg = MessageFormat.format("Error in service file line {0}: not in section.", lineNum); throw new Exception(msg); } else { <START> String[] segment = line.split("="); <END> if (segment.length != 2) { String msg = MessageFormat.format("Error in service file line {0}: bad syntax.", lineNum); throw new Exception(msg); } section.put(segment[0], segment[1]); } } }</code><technical_language>This line.split("=", 2) " in value. matters is name / identified. username=test=123 key username test=123</technical_language>

Target:
private void parse(Scanner in) throws Exception { int lineNum = 0; String sectionName = null; Map<String, String> section = null; while (in.hasNextLine()) { String line = in.nextLine(); lineNum++; line = line.replaceAll("^\\s+", ""); if (line.isEmpty() || line.startsWith("#")) { continue; } else if (line.startsWith("[")) { if (!line.endsWith("]")) { String msg = MessageFormat.format("Error in service file line {0}: missing ].", lineNum); throw new ParseException(msg, lineNum); } sectionName = line.substring(1, line.length() - 1); section = new HashMap(); sections.put(sectionName, section); } else if (section == null) { String msg = MessageFormat.format("Error in service file line {0}: not in section.", lineNum); throw new ParseException(msg, lineNum); } else { String[] segment = line.split("=", 2); if (segment.length != 2) { String msg = MessageFormat.format("Error in service file line {0}: bad syntax.", lineNum); throw new ParseException(msg, lineNum); } section.put(segment[0], segment[1]); } } }
Source:
<code>public String describeModule(Module<Flow> module) { String result; try { ModuleMetaData moduleMetaData = new ModuleMetaDataImpl(); moduleMetaData.setName(module.getName()); moduleMetaData.setDescription(module.getDescription()); moduleMetaData.setVersion(module.getVersion()); for(Flow flow: module.getFlows()) { moduleMetaData.getFlows().add(flowMetaDataProvider .deserialiseFlow(flowMetaDataProvider.describeFlow(flow))); } <START> ObjectMapper mapper = new ObjectMapper(); <END> result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(moduleMetaData); } catch (Exception e) { throw new RuntimeException("Exception has occurred creating flow meta data json!", e); } return result; }</code><technical_language>Mapper created in constructor</technical_language>

Target:
public String describeModule(Module<Flow> module) { String result; try { ModuleMetaData moduleMetaData = new ModuleMetaDataImpl(); moduleMetaData.setName(module.getName()); moduleMetaData.setDescription(module.getDescription()); moduleMetaData.setVersion(module.getVersion()); for(Flow flow: module.getFlows()) { moduleMetaData.getFlows().add(flowMetaDataProvider .deserialiseFlow(flowMetaDataProvider.describeFlow(flow))); } result = this.mapper.writerWithDefaultPrettyPrinter().writeValueAsString(moduleMetaData); } catch (Exception e) { throw new RuntimeException("Exception has occurred creating flow meta data json!", e); } return result; }
Source:
<code>public List<LunModel> getLunsToRemove() { ArrayList<LunModel> luns = new ArrayList<>(); if (!getIsGrouppedByTarget()) { List<LunModel> items = (List<LunModel>) getItems(); for (LunModel lun : items) { if (lun.getIsIncluded() && lun.isRemoveLunSelected() && <START> luns.stream().noneMatch(new <END> Linq.LunPredicate(lun))) { luns.add(lun); } } } return luns; }</code><technical_language>distinct work here? If yes, consider replace implementation like: if (getIsGrouppedByTarget()) { return Collections.emptyList(); } return ((List<LunModel>) getItems()).stream() .filter(LunModel::getIsIncluded) .filter(LunModel::isRemoveLunSelected) .distinct() .collect(Collectors.toList());</technical_language>

Target:
public List<LunModel> getLunsToRemove() { if (getIsGrouppedByTarget()) { return Collections.emptyList(); } return ((List<LunModel>) getItems()).stream() .filter(LunModel::getIsIncluded) .filter(LunModel::isRemoveLunSelected) .distinct() .collect(Collectors.toList()); }
Source:
<code>public void createUnauthorizedTest() throws Exception { context.turnOffAuthorisationSystem(); <START> <END> ObjectMapper mapper = new ObjectMapper(); CommunityRest comm = new CommunityRest(); comm.setName("Test Top-Level Community"); MetadataEntryRest title = new MetadataEntryRest(); title.setKey("dc.title"); title.setValue("Title Text"); comm.setMetadata(Arrays.asList(title)); getClient().perform(post("/api/core/communities") .content(mapper.writeValueAsBytes(comm)) .contentType(contentType)) .andExpect(status().isForbidden()); String authToken = getAuthToken(eperson.getEmail(), password); getClient(authToken).perform(post("/api/core/communities") .content(mapper.writeValueAsBytes(comm)) .contentType(contentType)) .andExpect(status().isForbidden()); }</code><technical_language>@Test is required</technical_language>

Target:
public void createUnauthorizedTest() throws Exception { context.turnOffAuthorisationSystem(); ObjectMapper mapper = new ObjectMapper(); CommunityRest comm = new CommunityRest(); comm.setName("Test Top-Level Community"); MetadataEntryRest title = new MetadataEntryRest(); title.setKey("dc.title"); title.setValue("Title Text"); comm.setMetadata(Arrays.asList(title)); getClient().perform(post("/api/core/communities") .content(mapper.writeValueAsBytes(comm)) .contentType(contentType)) .andExpect(status().isUnauthorized()); String authToken = getAuthToken(eperson.getEmail(), password); getClient(authToken).perform(post("/api/core/communities") .content(mapper.writeValueAsBytes(comm)) .contentType(contentType)) .andExpect(status().isForbidden()); }
Source:
<code>private static SslContext createSslContext() throws SSLException { SslContextBuilder builder = getSslBuilder(); <START> return builder == null ? null : builder.build(); <END> }</code><technical_language>builder null? if not, is getSslBuilder().build(), in-line it</technical_language>

Target:
private static SslContext createSslContext() throws SSLException { return getSslBuilder().build(); }
Source:
<code>public Call<MwQueryResponse<SiteInfo>> request(final Callback cb) { Retrofit retrofitClient = RetrofitFactory.newInstance(apiBaseUrl, new WikiSite(apiBaseUrl)); Service request = retrofitClient.create(Service.class); Call<MwQueryResponse<SiteInfo>> call = request.requestSiteinfo(); call.enqueue(new retrofit2.Callback<MwQueryResponse<SiteInfo>>() { @Override public void onResponse(Call<MwQueryResponse<SiteInfo>> call, Response<MwQueryResponse<SiteInfo>> response) { if (response.isSuccessful() && <START> response.body().success()) <END> { cb.onSuccess(response.body().query()); } else { cb.onFailure(new HttpStatusException(response.raw())); } } @Override public void onFailure(Call<MwQueryResponse<SiteInfo>> call, Throwable t) { cb.onFailure(t); } }); return call; }</code><technical_language>I this body null due @Required annotation in SiteInfo model. @Required removed (meaning service SiteInfo responses validated) a null-check body exist here</technical_language>

Target:
public Call<MwQueryResponse<SiteInfo>> request(final Callback cb) { Retrofit retrofitClient = RetrofitFactory.newInstance(apiBaseUrl, new WikiSite(apiBaseUrl)); Service request = retrofitClient.create(Service.class); Call<MwQueryResponse<SiteInfo>> call = request.requestSiteinfo(); call.enqueue(new retrofit2.Callback<MwQueryResponse<SiteInfo>>() { @Override public void onResponse(Call<MwQueryResponse<SiteInfo>> call, Response<MwQueryResponse<SiteInfo>> response) { if (response.isSuccessful() && response.body() != null && response.body().success()) { cb.onSuccess(response.body().query()); } else { cb.onFailure(new HttpStatusException(response.raw())); } } @Override public void onFailure(Call<MwQueryResponse<SiteInfo>> call, Throwable t) { cb.onFailure(t); } }); return call; }
Source:
<code>private void addItemWithName(Set<GenericItem> items, String itemName) { if (itemName != null) { try { <START> Item item = itemRegistry.getItem(itemName); <END> if (item instanceof GenericItem) { final GenericItem gItem = (GenericItem) item; items.add(gItem); } } catch (ItemNotFoundException e) { } } }</code><technical_language>I re-factored this code another method, I asking getItem() method is called itemRegistry itemUIregistry in case of basicui</technical_language>

Target:
private void addItemWithName(Set<GenericItem> items, String itemName) { if (itemName != null) { try { Item item = renderer.getItemUIRegistry().getItem(itemName); if (item instanceof GenericItem) { final GenericItem gItem = (GenericItem) item; items.add(gItem); } } catch (ItemNotFoundException e) { } } }
Source:
<code>public void addCommand(ReceiveCommand cmd, String rawLine) { <START> received = true; <END> commands.add(cmd); rawCommands.append(rawLine); }</code><technical_language>for addCommand,</technical_language>

Target:
public void addCommand(ReceiveCommand cmd, String rawLine) { commands.add(cmd); rawCommands.append(rawLine); }
Source:
<code>public static ISideEffectFactory createFactory(Widget disposableWidget) { <START> ICompositeSideEffect compositeSideEffect = ICompositeSideEffect.create(); <END> disposableWidget.setData(ICompositeSideEffect.class.getName(), compositeSideEffect); disposableWidget.addDisposeListener(e -> compositeSideEffect.dispose()); return ISideEffectFactory.createFactory(compositeSideEffect::add); }</code><technical_language>This disposableWidget.getData(ICompositeSideEffect.class.getName()) check if is a composite side effect attached widget create attach a new one</technical_language>

Target:
public static ISideEffectFactory createFactory(Widget disposableWidget) { ICompositeSideEffect compositeSideEffect = (ICompositeSideEffect) disposableWidget .getData(ICompositeSideEffect.class.getName()); if (compositeSideEffect == null) { ICompositeSideEffect newCompositeSideEffect = ICompositeSideEffect.create(); disposableWidget.setData(ICompositeSideEffect.class.getName(), newCompositeSideEffect); disposableWidget.addDisposeListener(e -> newCompositeSideEffect.dispose()); compositeSideEffect = newCompositeSideEffect; } return ISideEffectFactory.createFactory(compositeSideEffect::add); }
Source:
<code>protected ConsumerRecords<?, ?> pollRecords(long pollInterval) throws Exception { ConsumerRecords<?, ?> records; try { long curPollTime = System.currentTimeMillis(); _lastPolledTimeMillis = curPollTime; records = _consumer.poll(pollInterval); long pollDurationMillis = System.currentTimeMillis() - curPollTime; if (pollDurationMillis > pollInterval + POLL_BUFFER_TIME_MILLIS) { _logger.warn("ConsumerId: {}, Kafka client poll took ms (> poll timeout + buffer time ms)", _taskName, pollDurationMillis, pollInterval, POLL_BUFFER_TIME_MILLIS); _consumerMetrics.updateClientPollOverTimeout(1); } _consumerMetrics.updateNumPolls(1); _consumerMetrics.updateEventCountsPerPoll(records.count()); if (!records.isEmpty()) { _consumerMetrics.updateEventsProcessedRate(records.count()); _consumerMetrics.updateLastEventReceivedTime(Instant.now()); } _pollAttempts = 0; try { <START> sendPollInfoToPositionTracker(_consumer, records); <END> } catch (WakeupException | InterruptException e) { throw e; } catch (Exception e) { _logger.warn("Got uncaught exception while processing position tracker code (swallowing and continuing)", e); } return records; } catch (NoOffsetForPartitionException e) { handleNoOffsetForPartitionException(e); return ConsumerRecords.EMPTY; } catch (WakeupException e) { _logger.warn("Got a WakeupException, shutdown in progress.", e); return ConsumerRecords.EMPTY; } catch (Exception e) { handlePollRecordsException(e); return ConsumerRecords.EMPTY; } }</code><technical_language>nit: nicer if try/catch is sendPollInfoToPositionTracker</technical_language>

Target:
protected ConsumerRecords<?, ?> pollRecords(long pollInterval) throws Exception { ConsumerRecords<?, ?> records; try { long curPollTime = System.currentTimeMillis(); _lastPolledTimeMillis = curPollTime; records = _consumer.poll(pollInterval); long pollDurationMillis = System.currentTimeMillis() - curPollTime; if (pollDurationMillis > pollInterval + POLL_BUFFER_TIME_MILLIS) { _logger.warn("ConsumerId: {}, Kafka client poll took ms (> poll timeout + buffer time ms)", _taskName, pollDurationMillis, pollInterval, POLL_BUFFER_TIME_MILLIS); _consumerMetrics.updateClientPollOverTimeout(1); } _consumerMetrics.updateNumPolls(1); _consumerMetrics.updateEventCountsPerPoll(records.count()); if (!records.isEmpty()) { _consumerMetrics.updateEventsProcessedRate(records.count()); _consumerMetrics.updateLastEventReceivedTime(Instant.now()); } _pollAttempts = 0; sendPollInfoToPositionTracker(_consumer, records); return records; } catch (NoOffsetForPartitionException e) { handleNoOffsetForPartitionException(e); return ConsumerRecords.EMPTY; } catch (WakeupException e) { _logger.warn("Got a WakeupException, shutdown in progress.", e); return ConsumerRecords.EMPTY; } catch (Exception e) { handlePollRecordsException(e); return ConsumerRecords.EMPTY; } }
Source:
<code><START> public void initializeColumnMap(Schema schema) <END> { columnNames = schema.getFields(); keyMethodMap = new ArrayList<Getter>(); for (int i = 0; i < columnNames.size(); i++) { try { keyMethodMap.add(generateGettersForField(cls, columnNames.get(i).name())); } catch (NoSuchFieldException | SecurityException e) { throw new RuntimeException("Failed to initialize pojo class getters for field: ", e); } } }</code><technical_language>public</technical_language>

Target:
private void initializeColumnMap(Schema schema) { setColumnNames(schema.getFields()); keyMethodMap = new ArrayList<Getter>(); for (int i = 0; i < getColumnNames().size(); i++) { try { keyMethodMap.add(generateGettersForField(cls, getColumnNames().get(i).name())); } catch (NoSuchFieldException | SecurityException e) { throw new RuntimeException("Failed to initialize pojo class getters for field - ", e); } } }
Source:
<code>private void doOpen() throws IOException { try { if (invalid) throw new PackInvalidException(packFile); synchronized (readLock) { fd = new RandomAccessFile(packFile, "r"); length = fd.length(); onOpenPack(); } } catch (InterruptedIOException e) { openFail(false); throw e; } catch (FileNotFoundException fn) { openFail(!packFile.exists()); throw fn; } catch (EOFException | AccessDeniedException | NoSuchFileException | CorruptObjectException | NoPackSignatureException | PackMismatchException | UnpackException | UnsupportedPackVersionException pe) { openFail(true); throw pe; } catch (IOException | RuntimeException ge) { openFail(false); throw ge; <START> } catch (Error e) { <END> openFail(true); throw e; } }</code><technical_language>IMHO shouldn't</technical_language>

Target:
private void doOpen() throws IOException { try { if (invalid) throw new PackInvalidException(packFile); synchronized (readLock) { fd = new RandomAccessFile(packFile, "r"); length = fd.length(); onOpenPack(); } } catch (InterruptedIOException e) { openFail(false); throw e; } catch (FileNotFoundException fn) { openFail(!packFile.exists()); throw fn; } catch (EOFException | AccessDeniedException | NoSuchFileException | CorruptObjectException | NoPackSignatureException | PackMismatchException | UnpackException | UnsupportedPackIndexVersionException | UnsupportedPackVersionException pe) { openFail(true); throw pe; } catch (IOException | RuntimeException ge) { openFail(false); throw ge; } catch (Error e) { openFail(true); throw e; } }
Source:
<code>private void scanFile(InputFile inputFile) { PythonFile pythonFile = SonarQubePythonFile.create(inputFile); PythonVisitorContext visitorContext; try { AstNode astNode = parser.parse(pythonFile.content()); PyFileInputTree parse = new PythonTreeMaker().fileInput(astNode); visitorContext = new PythonVisitorContext(astNode, parse, pythonFile); <START> List<PythonSubscriptionCheck> checksBasedOnTree = checks.all().stream() <END> .filter(check -> check instanceof PythonSubscriptionCheck) .map(check -> (PythonSubscriptionCheck) check) .collect(Collectors.toList()); SubscriptionVisitor.analyze(checksBasedOnTree, visitorContext, parse); saveMeasures(inputFile, visitorContext); } catch (RecognitionException e) { visitorContext = new PythonVisitorContext(pythonFile, e); LOG.error("Unable to parse file: " + inputFile.toString()); LOG.error(e.getMessage()); context.newAnalysisError() .onFile(inputFile) .at(inputFile.newPointer(e.getLine(), 0)) .message(e.getMessage()) .save(); } for (PythonCheck check : checks.all()) { check.scanFile(visitorContext); } saveIssues(inputFile, visitorContext.getIssues()); new PythonHighlighter(context, inputFile).scanFile(visitorContext); }</code><technical_language>do instance of test in loop a lines ? need pass "parse" tree</technical_language>

Target:
private void scanFile(InputFile inputFile) { PythonFile pythonFile = SonarQubePythonFile.create(inputFile); PythonVisitorContext visitorContext; try { AstNode astNode = parser.parse(pythonFile.content()); PyFileInputTree parse = new PythonTreeMaker().fileInput(astNode); visitorContext = new PythonVisitorContext(astNode, parse, pythonFile); saveMeasures(inputFile, visitorContext); } catch (RecognitionException e) { visitorContext = new PythonVisitorContext(pythonFile, e); LOG.error("Unable to parse file: " + inputFile.toString()); LOG.error(e.getMessage()); context.newAnalysisError() .onFile(inputFile) .at(inputFile.newPointer(e.getLine(), 0)) .message(e.getMessage()) .save(); } List<PythonSubscriptionCheck> checksBasedOnTree = new ArrayList<>(); for (PythonCheck check : checks.all()) { if (check instanceof PythonSubscriptionCheck) { checksBasedOnTree.add((PythonSubscriptionCheck) check); } else { check.scanFile(visitorContext); } } SubscriptionVisitor.analyze(checksBasedOnTree, visitorContext); saveIssues(inputFile, visitorContext.getIssues()); new PythonHighlighter(context, inputFile).scanFile(visitorContext); }
Source:
<code>private synchronized boolean checkAndSubmitNextTask() { boolean submittedNewTask = false; if ((future == null) || future.isCancelled() || future.isDone()) { if ((future != null) && future.isDone()) { try { TaskResult result = future.get(); if (result.getException() != null) { log.error("Caught exception running task: ", currentTask.taskType(), result.getException()); } } catch (InterruptedException | ExecutionException e) { log.warn("{} task encountered exception.", currentTask.taskType(), e); } } currentTask = new MetricsCollectingTaskDecorator( new ShardSyncTask(shardDetector, leaseRefresher, initialPositionInStream, cleanupLeasesUponShardCompletion, ignoreUnexpectedChildShards, <START> shardSyncIdleTimeMillis, hierarchichalShardSyncer, <END> metricsFactory), metricsFactory); future = executorService.submit(currentTask); submittedNewTask = true; if (log.isDebugEnabled()) { log.debug("Submitted new task.", currentTask.taskType()); } } else { if (log.isDebugEnabled()) { log.debug("Previous task still pending. Not submitting new task.", currentTask.taskType()); } } return submittedNewTask; }</code><technical_language>follow formatting style for file include parameter a new line</technical_language>

Target:
private synchronized boolean checkAndSubmitNextTask() { boolean submittedNewTask = false; if ((future == null) || future.isCancelled() || future.isDone()) { if ((future != null) && future.isDone()) { try { TaskResult result = future.get(); if (result.getException() != null) { log.error("Caught exception running task: ", currentTask.taskType(), result.getException()); } } catch (InterruptedException | ExecutionException e) { log.warn("{} task encountered exception.", currentTask.taskType(), e); } } currentTask = new MetricsCollectingTaskDecorator( new ShardSyncTask(shardDetector, leaseRefresher, initialPositionInStream, cleanupLeasesUponShardCompletion, ignoreUnexpectedChildShards, shardSyncIdleTimeMillis, hierarchicalShardSyncer, metricsFactory), metricsFactory); future = executorService.submit(currentTask); submittedNewTask = true; if (log.isDebugEnabled()) { log.debug("Submitted new task.", currentTask.taskType()); } } else { if (log.isDebugEnabled()) { log.debug("Previous task still pending. Not submitting new task.", currentTask.taskType()); } } return submittedNewTask; }
Source:
<code>private static void validateListOfSuppressionXpathFilterIncompatibleChecks(Node subSection) { final boolean found = XmlUtil.findChildElementsByTag(subSection, "ul").stream() .anyMatch(node -> { final Set<String> checks = XmlUtil.getChildrenElements(node).stream() .map(Node::getTextContent) .collect(Collectors.toSet()); <START> return XpathRegressionTest.INCOMPATIBLE_CHECK_NAMES.equals(checks); <END> }); assertTrue(found, "Incompatible check list should match XpathRegressionTest.INCOMPATIBLE_CHECK_NAMES"); }</code><technical_language>for me, this better: .map(node -> ...) .anyMatch(XpathRegressionTest.INCOMPATIBLE_CHECK_NAMES::equals)</technical_language>

Target:
private static void validateListOfSuppressionXpathFilterIncompatibleChecks(Node subSection) { assertWithMessage( "Incompatible check list should match XpathRegressionTest.INCOMPATIBLE_CHECK_NAMES") .that(getListById(subSection, "SuppressionXpathFilter_IncompatibleChecks")) .isEqualTo(XpathRegressionTest.INCOMPATIBLE_CHECK_NAMES); assertWithMessage( "Javadoc check list should match XpathRegressionTest.INCOMPATIBLE_JAVADOC_CHECK_NAMES") .that(getListById(subSection, "SuppressionXpathFilter_JavadocChecks")) .isEqualTo(XpathRegressionTest.INCOMPATIBLE_JAVADOC_CHECK_NAMES); }
Source:
<code>public void removeNodeSource(final String sourceName) { rmdbManagerBuffer.setNodeSourceRemovedFlag(sourceName); final Collection<RMNodeData> relatedNodes = getNodesByNodeSource(sourceName); logger.debug("Removing nodes linked to the node source " + sourceName + " from the database"); removeNodes(relatedNodes); executeReadWriteTransaction(new SessionWork<Void>() { @Override public Void doInTransaction(Session session) { logger.debug("Removing the node source " + sourceName + " from the database"); <START> session.getNamedQuery("deleteNodeSourceDataByName").setParameter("name", sourceName).executeUpdate(); <END> return null; } }); }</code><technical_language>I leave this in info, important node source is removed DB</technical_language>

Target:
public void removeNodeSource(final String sourceName) { rmdbManagerBuffer.removeKnownNodeSourceAndPendingUpdates(sourceName); final Collection<RMNodeData> relatedNodes = getNodesByNodeSource(sourceName); logger.info("Removing nodes linked to the node source " + sourceName + " from the database"); removeNodes(relatedNodes); executeReadWriteTransaction(new SessionWork<Void>() { @Override public Void doInTransaction(Session session) { logger.info("Removing the node source " + sourceName + " from the database"); session.getNamedQuery("deleteNodeSourceDataByName").setParameter("name", sourceName).executeUpdate(); return null; } }); }
Source:
<code>private void verifyDetail(String expected, WebElement detailField) { if (expected.isEmpty()) { <START> assertTrue(isElementPresent(By.id("not-specified"))); <END> } else { assertEquals(expected, detailField.getText()); } }</code><technical_language>While this works, is a reader-friendly this means? e.g. asserting text content is "Not Specified", while slightly more prone change, is closer a black box more reader-friendly</technical_language>

Target:
private void verifyDetail(String expected, WebElement detailField) { if (expected.isEmpty()) { assertEquals(NOT_SPECIFIED_LABEL, detailField.getText()); } else { assertEquals(expected, detailField.getText()); } }
Source:
<code>public String toString() { <START> return "Time period " + seconds + " s."; <END> }</code><technical_language>Add factor variable toString() method</technical_language>

Target:
public String toString() { return "Time period " + seconds + " s (factor " + FACTOR + " was used)."; }
Source:
<code>public boolean execute(CommandSender sender, String[] args) { if(args.length == 0) { if(!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + "Non-players need to specify a player to look up"); return true; } sender.sendMessage(ChatColor.GREEN + "You are currently in the shard '" + MercuryAPI.serverName() + "'"); return true; } else { if(!(sender.isOp() || (sender instanceof ConsoleCommandSender))) { sender.sendMessage(ChatColor.RED + "You cannot look up the shard of another player!"); return true; } PlayerDetails details; <START> UUID player = UUID.fromString(args[0]); <END> if(player != null) { details = MercuryAPI.getServerforAccount(player); } else { details = MercuryAPI.getServerforPlayer(args[0]); } if(details == null) { sender.sendMessage(ChatColor.RED + "Player not found!"); return true; } else { sender.sendMessage(ChatColor.GREEN + args[0] + " is on the shard '" + details.getServerName() + "'"); return true; } } }</code><technical_language>need surround this in try catch. Listen for IllegalArgumentException set player = null</technical_language>

Target:
public boolean execute(CommandSender sender, String[] args) { if(args.length == 0) { if(!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + "Non-players need to specify a player to look up."); return true; } sender.sendMessage(ChatColor.GREEN + "[BetterShards] You are currently in the shard '" + MercuryAPI.serverName() + "'."); return true; } else { if(!(sender.isOp() || (sender instanceof ConsoleCommandSender))) { sender.sendMessage(ChatColor.RED + "You cannot look up the shard of another player!"); return true; } PlayerDetails details; UUID player = null; try { player = UUID.fromString(args[0]); } catch (IllegalArgumentException iaex) if(player != null) { details = MercuryAPI.getServerforAccount(player); } else { details = MercuryAPI.getServerforPlayer(args[0]); } if(details == null) { sender.sendMessage(ChatColor.RED + "Player not found!"); return true; } else { sender.sendMessage(ChatColor.GREEN + args[0] + " is on the shard '" + details.getServerName() + "'."); return true; } } }
Source:
<code><START> public final SerializableError getError() { <END> return SerializableError.of( "Refer to the server logs with this errorId: " + getErrorId(), this.getClass()); }</code><technical_language>prefer conversion exception SerializableError symmetric in ServiceExceptionMapper JsonExceptionMapper</technical_language>

Target:
public SerializableError getError() { return SerializableError.of( "Refer to the server logs with this errorId: " + getErrorId(), this.getClass()); }
Source:
<code>public int getKeyBufferValueSize() { <START> return Long.BYTES + Byte.BYTES; <END> }</code><technical_language>this new null handling unconditionally adds overhead in groupBy query processing</technical_language>

Target:
public int getKeyBufferValueSize() { return Long.BYTES; }
Source:
<code>public boolean performNextOperation(int completedChildCount) { <START> if (getParameters().getLiveDiskMigrateStage() == LiveDiskMigrateStage.IMAGE_PLACEHOLDER_CREATION) { <END> updateStage(LiveDiskMigrateStage.VM_REPLICATE_START); replicateDiskStart(); updateStage(LiveDiskMigrateStage.IMAGE_DATA_SYNC_EXEC_START); syncImageData(); updateStage(LiveDiskMigrateStage.IMAGE_DATA_SYNC_EXEC_END); return true; } if (getParameters().getLiveDiskMigrateStage() == LiveDiskMigrateStage.IMAGE_DATA_SYNC_EXEC_END) { completeLiveMigration(); updateStage(LiveDiskMigrateStage.SOURCE_IMAGE_DELETION); removeImage(getParameters().getSourceStorageDomainId()); return false; } return false; }</code><technical_language>switch/case</technical_language>

Target:
public boolean performNextOperation(int completedChildCount) { if (getParameters().getLiveDiskMigrateStage() == LiveDiskMigrateStage.IMAGE_PLACEHOLDER_CREATION) { updateStage(LiveDiskMigrateStage.VM_REPLICATE_DISK_START); replicateDiskStart(); updateStage(LiveDiskMigrateStage.IMAGE_DATA_SYNC_EXEC_START); syncImageData(); updateStage(LiveDiskMigrateStage.IMAGE_DATA_SYNC_EXEC_END); return true; } if (getParameters().getLiveDiskMigrateStage() == LiveDiskMigrateStage.IMAGE_DATA_SYNC_EXEC_END) { updateStage(LiveDiskMigrateStage.VM_REPLICATE_DISK_FINISH); completeLiveMigration(); updateStage(LiveDiskMigrateStage.SOURCE_IMAGE_DELETION); removeImage(getParameters().getSourceStorageDomainId()); return false; } return false; }
Source:
<code>private void checkoutCommit(RevCommit commit) throws IOException { try { monitor.beginTask( "Rewinding to commit " + commit.getShortMessage(), ProgressMonitor.UNKNOWN); RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD)); DirCacheCheckout dco = new DirCacheCheckout(repo, head.getTree() <START> .getId(), repo.lockDirCache(), commit.getTree().getId()); <END> dco.setFailOnConflict(true); dco.checkout(); walk.release(); RefUpdate refUpdate = repo.updateRef(Constants.HEAD, true); refUpdate.setExpectedOldObjectId(head); refUpdate.setNewObjectId(commit); Result res = refUpdate.forceUpdate(); switch (res) { case FAST_FORWARD: case NO_CHANGE: case FORCED: break; default: throw new IOException("Could not rewind to upstream commit"); } } finally { monitor.endTask(); } }</code><technical_language>FWIW .getId() calls unnecessary. able pass RevTree returned getTree() DirCacheCheckout constructor</technical_language>

Target:
private void checkoutCommit(RevCommit commit) throws IOException { try { monitor.beginTask( "Rewinding to commit " + commit.getShortMessage(), ProgressMonitor.UNKNOWN); RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD)); DirCacheCheckout dco = new DirCacheCheckout(repo, head.getTree(), repo.lockDirCache(), commit.getTree()); dco.setFailOnConflict(true); dco.checkout(); RefUpdate refUpdate = repo.updateRef(Constants.HEAD, true); refUpdate.setExpectedOldObjectId(head); refUpdate.setNewObjectId(commit); Result res = refUpdate.forceUpdate(); switch (res) { case FAST_FORWARD: case NO_CHANGE: case FORCED: break; default: throw new IOException("Could not rewind to upstream commit"); } } finally { walk.release(); monitor.endTask(); } }
Source:
<code>public double getSetupTime(Config conf) { String aoSystem = (String) conf.getItemValue(AOConstants.AO_SYSTEM_KEY); String guideStarType = (String) conf.getItemValue(AOConstants.AO_GUIDE_STAR_TYPE_KEY); <START> String slitWidth = (String) conf.getItemValue(GNIRSConstants.SLIT_WIDTH_KEY); <END> if (conf.containsItem(AOConstants.AO_SYSTEM_KEY) && aoSystem.equals(SPComponentType.AO_ALTAIR.narrowType) && guideStarType.equals(AltairParams.GuideStarType.LGS.displayValue())) { return getSetupTimeLgs(); } if (slitWidth.equals(GNIRSParams.SlitWidth.IFU)) { return getSetupTimeIfu(); } else { return getSetupTime(); } }</code><technical_language>This a GNIRSParams.SlitWidth I believe, checked equals GnirsParams.SlitWidth.IFU</technical_language>

Target:
public double getSetupTime(Config conf) { if (conf.containsItem(AOConstants.AO_SYSTEM_KEY)) { GuideStarType guideStarType = (GuideStarType) conf.getItemValue(AOConstants.AO_GUIDE_STAR_TYPE_KEY); if (guideStarType.equals(AltairParams.GuideStarType.LGS)) { return getSetupTimeLgs(); } } SlitWidth slitWidth = (SlitWidth) conf.getItemValue(GNIRSConstants.SLIT_WIDTH_KEY); if (slitWidth.equals(GNIRSParams.SlitWidth.IFU)) { return getSetupTimeIfu(); } else { return getSetupTime(); } }
Source:
<code><START> public void statisticsGeneratorStepShouldCalculateStats() throws IOException, InterruptedException { <END> jobOptions.getPipelineOptions().put(JobParametersNames.INPUT_VCF, SMALL_VCF_FILE); mongoRule.importDump(getResourceUrl(MONGO_DUMP), jobOptions.getDbName()); VariantSource source = configureVariantSource(); configureTempOutput(); File statsFile = getStatsFile(source); assertFalse(statsFile.exists()); JobExecution jobExecution = jobLauncherTestUtils.launchStep(PopulationStatisticsFlow.CALCULATE_STATISTICS); assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus()); assertTrue(statsFile.exists()); }</code><technical_language>need this new method flow, diff is helping understand change XD</technical_language>

Target:
public void statisticsGeneratorStepShouldCalculateStats() throws IOException, InterruptedException { jobOptions.getPipelineOptions().put(JobParametersNames.INPUT_VCF, SMALL_VCF_FILE); mongoRule.restoreDump(getResourceUrl(MONGO_DUMP), jobOptions.getDbName()); VariantSource source = configureVariantSource(); configureTempOutput(); File statsFile = getStatsFile(source); assertFalse(statsFile.exists()); JobExecution jobExecution = jobLauncherTestUtils.launchStep(PopulationStatisticsFlow.CALCULATE_STATISTICS); assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus()); assertTrue(statsFile.exists()); }
Source:
<code>public CommandCallback getCallback() { <START> return getParameters().isUseCinderCommandCallback() ? new GenericCinderCommandCallback<RemoveVmCommand<T>>() : null; <END> }</code><technical_language>I a problem (Not is relevant this patch). in RemoveAllVmCinderDisks execute disks active, pass a list of disks active removed (Could another bug maybe)</technical_language>

Target:
public CommandCallback getCallback() { return getParameters().isUseCommandCallback() ? new ConcurrentChildCommandsExecutionCallback() : null; }
Source:
<code>public boolean voteMatch(AffMatchAffiliation affiliation, AffMatchOrganization organization) { <START> List<String> affSections = organizationSectionsSplitter.splitToSections(affiliation.getOrganizationName()); <END> String filteredOrgName = filterName(organization.getName()); if (StringUtils.isEmpty(filteredOrgName)) { return false; } Set<String> orgWords = Sets.newHashSet(StringUtils.split(filteredOrgName)); for (String affSection : affSections) { String filteredAffSectionName = filterName(affSection); if (StringUtils.isEmpty(filteredAffSectionName)) { continue; } Set<String> affWords = Sets.newHashSet(StringUtils.split(filteredAffSectionName)); if (voteSectionMatch(affWords, orgWords)) { return true; } } return false; }</code><technical_language>I create this variable use</technical_language>

Target:
public boolean voteMatch(AffMatchAffiliation affiliation, AffMatchOrganization organization) { String filteredOrgName = stringFilter.filterCharsAndShortWords(organization.getName(), charsToFilter, wordToRemoveMaxLength); if (StringUtils.isEmpty(filteredOrgName)) { return false; } Set<String> orgWords = Sets.newHashSet(StringUtils.split(filteredOrgName)); List<String> affSections = organizationSectionsSplitter.splitToSections(affiliation.getOrganizationName()); for (String affSection : affSections) { String filteredAffSectionName = stringFilter.filterCharsAndShortWords(affSection, charsToFilter, wordToRemoveMaxLength); if (StringUtils.isEmpty(filteredAffSectionName)) { continue; } Set<String> affWords = Sets.newHashSet(StringUtils.split(filteredAffSectionName)); if (voteSectionMatch(affWords, orgWords)) { return true; } } return false; }
Source:
<code>private void checkTimeout(long timeout, TimeUnit unit) { if (timeout < 0) { <START> throw new IllegalArgumentException("'timeout' most be >= 0. It was: " + timeout); <END> } if (unit == null) { throw new IllegalArgumentException("Non-null 'unit' required"); } }</code><technical_language>></technical_language>

Target:
private void checkTimeout(long timeout, TimeUnit unit) { if (timeout <= 0) { throw new IllegalArgumentException("'timeout' must be > 0. It was: " + timeout); } if (unit == null) { throw new IllegalArgumentException("Non-null 'unit' required"); } }
Source:
<code>public void testDefault() throws Exception { CSVAssert csv = csvAssert(document); csv.has("repository").isEquals("test"); csv.has("uid").isEquals(document.getId()); csv.has("path").isEquals("/myDoc"); csv.has("type").isEquals("File"); csv.has("state").isEquals("project"); csv.has("parentRef").isEquals(document.getParentRef().toString()); csv.has("isCheckedOut").isTrue(); csv.has("isVersion").isFalse(); csv.has("isProxy").isFalse(); csv.has("isTrashed").isFalse(); csv.has("changeToken").isNull(); csv.has("title").isEquals("myDoc"); csv.has("dc:description").isEquals("There is a , in the description"); csv.has("dc:contributors").isEquals("John" + LIST_DELIMITER + "Jane"); csv.has("dc:nature").isEquals("article"); csv.has("dc:nature[label]").isEquals("Article EN"); <START> csv.has("dc:subjects[label]").isEquals("Art" + LIST_DELIMITER + NULL_PROPERTY_LABEL); <END> }</code><technical_language>In tests in general actual values of implementation. This is detect regressions. Imagine some changes NULL_PROPERTY_LABEL mistake. test detect regression</technical_language>

Target:
public void testDefault() throws Exception { CSVAssert csv = csvAssert(document); csv.has("repository").isEquals("test"); csv.has("uid").isEquals(document.getId()); csv.has("path").isEquals("/myDoc"); csv.has("type").isEquals("File"); csv.has("state").isEquals("project"); csv.has("parentRef").isEquals(document.getParentRef().toString()); csv.has("isCheckedOut").isTrue(); csv.has("isVersion").isFalse(); csv.has("isProxy").isFalse(); csv.has("isTrashed").isFalse(); csv.has("changeToken").isNull(); csv.has("title").isEquals("myDoc"); csv.has("dc:description").isEquals("There is a , in the description"); csv.has("dc:contributors").isEquals("John\nJane"); csv.has("dc:nature").isEquals("article"); csv.has("dc:nature[label]").isEquals("Article EN"); csv.has("dc:subjects[label]").isEquals("Art\nnull property"); }
Source:
<code>public PortfolioItemSummary summarize() { StringBuilder buf = new StringBuilder(96); CmsLeg mainLeg = product.getCmsLeg(); buf.append(SummarizerUtils.datePeriod(mainLeg.getStartDate().getUnadjusted(), mainLeg.getEndDate().getUnadjusted())); buf.append(' '); buf.append(SummarizerUtils.amount(mainLeg.getCurrency(), mainLeg.getNotional().getInitialValue())); buf.append(' '); if (mainLeg.getPayReceive().isReceive()) { buf.append("Rec "); summarizeMainLeg(mainLeg, buf); buf.append(getPremium().isPresent() ? " / Pay Premium" : (product.getPayLeg().isPresent() ? " / Pay Periodic" : "")); } else { buf.append("Rec "); <START> buf.append(getPremium().isPresent() ? "Premium" : (product.getPayLeg().isPresent() ? "Periodic" : "")); <END> buf.append(" / Pay "); summarizeMainLeg(mainLeg, buf); } buf.append(" : "); buf.append(SummarizerUtils.dateRange(mainLeg.getStartDate().getUnadjusted(), mainLeg.getEndDate().getUnadjusted())); return SummarizerUtils.summary(this, ProductType.CMS, buf.toString(), mainLeg.getCurrency()); }</code><technical_language>In this case main leg is pay, funding leg receive leg</technical_language>

Target:
public PortfolioItemSummary summarize() { StringBuilder buf = new StringBuilder(96); CmsLeg mainLeg = product.getCmsLeg(); buf.append(SummarizerUtils.datePeriod(mainLeg.getStartDate().getUnadjusted(), mainLeg.getEndDate().getUnadjusted())); buf.append(' '); buf.append(SummarizerUtils.amount(mainLeg.getCurrency(), mainLeg.getNotional().getInitialValue())); buf.append(' '); if (mainLeg.getPayReceive().isReceive()) { buf.append("Rec "); summarizeMainLeg(mainLeg, buf); buf.append(getPremium().isPresent() ? " / Pay Premium" : (product.getPayLeg().isPresent() ? " / Pay Periodic" : "")); } else { buf.append( getPremium().isPresent() ? "Rec Premium / Pay " : (product.getPayLeg().isPresent() ? "Rec Periodic / Pay " : "")); summarizeMainLeg(mainLeg, buf); } buf.append(" : "); buf.append(SummarizerUtils.dateRange(mainLeg.getStartDate().getUnadjusted(), mainLeg.getEndDate().getUnadjusted())); return SummarizerUtils.summary(this, ProductType.CMS, buf.toString(), mainLeg.getCurrency()); }
Source:
<code>public void testGenerateComplexTypedefStruct() throws IOException, ParserException, TypeRenamingConflictException, ResponseTypeNotFoundException, ParseException, TemplateModelException { final TestFileUtilsImpl fileUtils = new TestFileUtilsImpl(); <START> Map<String,Object> testMap = new HashMap<>(); <END> final Struct structEntry = new Struct("ds3_list_all_my_buckets_result_response", null, ImmutableList.of( new StructMember( new PrimitiveType("ds3_bucket_response*", true), "buckets"), new StructMember( new PrimitiveType("ds3_user_response*", false), "owner") ), true); testMap.put("structEntry", structEntry); final CCodeGenerator codeGenerator = new CCodeGenerator(); codeGenerator.processTemplate(testMap, "header-templates/TypedefStruct.ftl", fileUtils.getOutputStream()); final ByteArrayOutputStream bstream = (ByteArrayOutputStream) fileUtils.getOutputStream(); final String output = new String(bstream.toByteArray()); final String expectedOutput = "typedef struct {" + "\n" + " ds3_bucket_response** buckets;" + "\n" + " size_t num_buckets;" + "\n" + " ds3_user_response* owner;" + "\n" + "}ds3_list_all_my_buckets_result_response;" + "\n"; assertEquals(expectedOutput, output); }</code><technical_language>Missing final</technical_language>

Target:
public void testGenerateComplexTypedefStruct() throws IOException, ParserException, TypeRenamingConflictException, ResponseTypeNotFoundException, ParseException, TemplateModelException { final TestFileUtilsImpl fileUtils = new TestFileUtilsImpl(); final Map<String,Object> testMap = new HashMap<>(); final Struct structEntry = new Struct("ds3_list_all_my_buckets_result_response", null, ImmutableList.of( new StructMember( new PrimitiveType("ds3_bucket_response*", true), "buckets"), new StructMember( new PrimitiveType("ds3_user_response*", false), "owner") ), true); testMap.put("structEntry", structEntry); final CCodeGenerator codeGenerator = new CCodeGenerator(); codeGenerator.processTemplate(testMap, "header-templates/TypedefStruct.ftl", fileUtils.getOutputStream()); final ByteArrayOutputStream bstream = (ByteArrayOutputStream) fileUtils.getOutputStream(); final String output = new String(bstream.toByteArray()); final String expectedOutput = "typedef struct {" + "\n" + " ds3_bucket_response** buckets;" + "\n" + " size_t num_buckets;" + "\n" + " ds3_user_response* owner;" + "\n" + "}ds3_list_all_my_buckets_result_response;" + "\n"; assertEquals(expectedOutput, output); }
Source:
<code>static HaxeFunctionDescription buildForMethod(HaxeCallExpression expression) { final HaxeGenericSpecialization specialization = expression.getSpecialization(); final boolean isStaticExtension = expression.resolveIsStaticExtension(); final PsiElement target = ((HaxeReference)expression.getExpression()).resolve(); if (target instanceof HaxeMethod) { final HaxeClass targetParent = (HaxeClass)((HaxeMethod)target).getContainingClass(); <START> final HaxeClassResolveResult resolveResult = HaxeClassResolveResult.create(targetParent, specialization); <END> return build((HaxeMethod)target, resolveResult, specialization, isStaticExtension); } return null; }</code><technical_language>want [HaxeReferenceImpl.]resolveHaxeClass() instead? (for lines 33~37)</technical_language>

Target:
static HaxeFunctionDescription buildForMethod(HaxeCallExpression expression) { final HaxeGenericSpecialization specialization = expression.getSpecialization(); final boolean isStaticExtension = expression.resolveIsStaticExtension(); final HaxeReference reference = (HaxeReference)expression.getExpression(); final PsiElement target = reference.resolve(); if (target instanceof HaxeMethod) { final HaxeClass haxeClass = (HaxeClass)((HaxeMethod)target).getContainingClass(); final HaxeClassResolveResult resolveResult = HaxeClassResolveResult.create(haxeClass, specialization); return build((HaxeMethod)target, resolveResult, isStaticExtension); } return null; }
Source:
<code>private void versioningDocFromHeaderIfExists(HttpHeaders headers) { isVersioning = false; List<String> versionHeader = headers.getRequestHeader(RestConstants.X_VERSIONING_OPTION); List<String> sourceHeader = headers.getRequestHeader(RestConstants.SOURCE); if (versionHeader != null && !versionHeader.isEmpty()) { VersioningOption versioningOption = VersioningOption.valueOf(versionHeader.get(0).toUpperCase()); if (versioningOption != null && !versioningOption.equals(VersioningOption.NONE)) { doc.putContextData(VersioningService.VERSIONING_OPTION, versioningOption); isVersioning = true; } } <START> else if (sourceHeader != null && !sourceHeader.isEmpty()) { <END> doc.putContextData(CoreSession.SOURCE, sourceHeader.get(0).toUpperCase()); isVersioning = true; } }</code><technical_language>Move line } above</technical_language>

Target:
private void versioningDocFromHeaderIfExists(HttpHeaders headers) { isVersioning = false; List<String> versionHeader = headers.getRequestHeader(RestConstants.X_VERSIONING_OPTION); List<String> sourceHeader = headers.getRequestHeader(RestConstants.SOURCE); if (versionHeader != null && !versionHeader.isEmpty()) { VersioningOption versioningOption = VersioningOption.valueOf(versionHeader.get(0).toUpperCase()); if (versioningOption != null && !versioningOption.equals(VersioningOption.NONE)) { doc.putContextData(VersioningService.VERSIONING_OPTION, versioningOption); isVersioning = true; } } else if (sourceHeader != null && !sourceHeader.isEmpty()) { doc.putContextData(CoreSession.SOURCE, sourceHeader.get(0)); isVersioning = true; } }
Source:
<code><START> @Override public void publish(Payload<?, ?, ?, ?> requestPayload, String tag) { <END> publish(requestPayload, null, tag); }</code><technical_language>newline missing</technical_language>

Target:
public void publish(Payload<?, ?, ?, ?> requestPayload, String tag) { publish(requestPayload, null, tag); }
Source:
<code>public void testThumbnailFactoryContribution() throws IOException { DocumentModel root = session.getRootDocument(); DocumentModel folder = session.createDocumentModel(root.getPathAsString(), "Folder", "Folder"); folder.addFacet(FacetNames.FOLDERISH); session.createDocument(folder); session.save(); ThumbnailAdapter folderThumbnail = folder.getAdapter(ThumbnailAdapter.class); <START> Assert.assertEquals("folderish", folderThumbnail.getThumbnail(session).getString()); <END> DocumentModel doc = session.createDocumentModel(root.getPathAsString(), "File", "File"); session.createDocument(doc); session.save(); ThumbnailAdapter docThumbnail = doc.getAdapter(ThumbnailAdapter.class); Assert.assertEquals("default", docThumbnail.getThumbnail(session).getString()); }</code><technical_language>import staticly assertEquals</technical_language>

Target:
public void testThumbnailFactoryContribution() throws IOException { DocumentModel root = session.getRootDocument(); DocumentModel folder = session.createDocumentModel(root.getPathAsString(), "Folder", "Folder"); folder.addFacet(FacetNames.FOLDERISH); session.createDocument(folder); session.save(); ThumbnailAdapter folderThumbnail = folder.getAdapter(ThumbnailAdapter.class); assertEquals("folderish", folderThumbnail.getThumbnail(session).getString()); DocumentModel doc = session.createDocumentModel(root.getPathAsString(), "File", "File"); session.createDocument(doc); session.save(); ThumbnailAdapter docThumbnail = doc.getAdapter(ThumbnailAdapter.class); assertEquals("default", docThumbnail.getThumbnail(session).getString()); }