auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void setup() throws Exception { CanvasCommandManagerImpl commandManager = new CanvasCommandManagerImpl(); when(canvasHandler.getCanvas()).thenReturn(canvas); when(clientSessionManager.getCurrentSession()).thenReturn(editorSession); when(editorSession.getCanvasHandler()).thenReturn(canvasHandler); when(editorSession.getCommandRegistry()).thenReturn(commandRegistry); when(editorSession.getCommandManager()).thenReturn(commandManager); <START> this.tested = new RequestCommandManager(clientSessionManager, commandRegisteredEvent); <END> }</code><technical_language>is missing verify of commandRegisteredEvent fire tests. EventSourceMock mock event</technical_language>

Target:
public void setup() throws Exception { CanvasCommandManagerImpl commandManager = new CanvasCommandManagerImpl(); when(canvasHandler.getCanvas()).thenReturn(canvas); when(clientSessionManager.getCurrentSession()).thenReturn(editorSession); when(editorSession.getCanvasHandler()).thenReturn(canvasHandler); when(editorSession.getCommandRegistry()).thenReturn(commandRegistry); when(editorSession.getCommandManager()).thenReturn(commandManager); this.tested = new RequestCommandManager(clientSessionManager); }
Source:
<code>private Set<String> getTrashRemovedResourcesId(List<String> resourceIds, List<String> archivedResources) { Set<String> trashRemovedResources = null; Iterator<String> it = resourceIds.iterator(); String id = null; while (it.hasNext()) { id = (String)it.next(); ResourceInterface resourceInterfaceArchived = null; ResourceInterface resourceInterfaceTrashed = null; try { resourceInterfaceTrashed = this.getTrashedResourceManager().loadTrashedResource(id); resourceInterfaceArchived = this.getResourceManager().loadResource(id); if (!(null != resourceInterfaceArchived || null != resourceInterfaceTrashed)) { if (null == trashRemovedResources) { trashRemovedResources = new HashSet<String>(); } trashRemovedResources.add(id); } } catch (Throwable t) { <START> logger.error("Errore in verifica risorsa rimossa definitivamente da cestino, id " + id, t); <END> throw new RuntimeException("Errore in verifica risorsa rimossa definitivamente da cestino, id " + id, t); } } return trashRemovedResources; }</code><technical_language>Translate this log message in English please</technical_language>

Target:
private Set<String> getTrashRemovedResourcesId(List<String> resourceIds, List<String> archivedResources) { Set<String> trashRemovedResources = null; Iterator<String> it = resourceIds.iterator(); String id = null; while (it.hasNext()) { id = (String)it.next(); ResourceInterface resourceInterfaceArchived = null; ResourceInterface resourceInterfaceTrashed = null; try { resourceInterfaceTrashed = this.getTrashedResourceManager().loadTrashedResource(id); resourceInterfaceArchived = this.getResourceManager().loadResource(id); if (!(null != resourceInterfaceArchived || null != resourceInterfaceTrashed)) { if (null == trashRemovedResources) { trashRemovedResources = new HashSet<String>(); } trashRemovedResources.add(id); } } catch (Throwable t) { logger.error("Error checking resource permanently removed, id " + id, t); throw new RuntimeException("Error checking resource permanently removed, id " + id, t); } } return trashRemovedResources; }
Source:
<code><START> public static <END> void switchToExistingOrCreateUserType(ITestDevice device) throws DeviceNotAvailableException, UserSwitchFailedException { try { UserUtil.switchToUserType(device, mUserToSwitchTo); } catch (UserUtil.SecondaryUserNotFoundException attemptCreate) { CLog.d("No secondary users exist, creating one."); UserUtil.createAndSwitchToSecondaryUser(device); } }</code><technical_language>this remain private, right</technical_language>

Target:
private void switchToExistingOrCreateUserType(ITestDevice device) throws DeviceNotAvailableException, UserSwitchFailedException { try { UserUtil.switchToUserType(device, mUserToSwitchTo); } catch (UserUtil.SecondaryUserNotFoundException attemptCreate) { CLog.d("No secondary users exist, creating one."); UserUtil.createAndSwitchToSecondaryUser(device); } }
Source:
<code>public OperatorResponse execute(Operator operator, int operatorId, long windowId) throws IOException { <START> logger.debug("Receieved slowdown operator operatorId windowId {}", operator, operatorId, windowId); <END> if (operator instanceof RandomNumberGenerator) { RandomNumberGenerator generator = (RandomNumberGenerator)operator; generator.suspend(); } return new InputOperatorResponse(); }</code><technical_language>Receieved => Received {2 places}</technical_language>

Target:
public OperatorResponse execute(Operator operator, int operatorId, long windowId) throws IOException { logger.debug("Received slowdown operator operatorId windowId {}", operator, operatorId, windowId); if (operator instanceof RandomNumberGenerator) { RandomNumberGenerator generator = (RandomNumberGenerator)operator; generator.suspend(); } return new InputOperatorResponse(); }
Source:
<code>public void startingVmCompleted(Guid vmId, String cause) { <START> log.info("Startup <END> of VM completed ({})", vmId, cause); startingVms.remove(vmId); }</code><technical_language>do need this in 'info' level? log of run-vm.</technical_language>

Target:
public void startingVmCompleted(Guid vmId, String cause) { if (log.isDebugEnabled() && startingVms.contains(vmId)) { log.debug("Startup of VM completed ({})", vmId, cause); } startingVms.remove(vmId); }
Source:
<code>private void setTypeRef(Configuration conf) { String className = conf.get(CLASS_CONF_KEY); if (className == null) { throw new RuntimeException(CLASS_CONF_KEY + " is not set"); } Class<?> clazz = null; try { clazz = conf.getClassByName(className); } catch (ClassNotFoundException e) { <START> throw new RuntimeException(e); <END> } typeRef = new TypeRef<M>(clazz){}; }</code><technical_language>("could instantiate \""+className+"\" conf property "+CLASS_CONF_KEY, e)</technical_language>

Target:
private void setTypeRef(Configuration conf) { String className = conf.get(CLASS_CONF_KEY); if (className == null) { throw new RuntimeException(CLASS_CONF_KEY + " is not set"); } Class<?> clazz = null; try { clazz = conf.getClassByName(className); } catch (ClassNotFoundException e) { throw new RuntimeException("failed to instantiate class '" + className + "'", e); } typeRef = new TypeRef<M>(clazz){}; }
Source:
<code>public Result[] searchFields(String q, String f, float boost, int k) throws IOException { IndexSearcher searcher = new IndexSearcher(reader); searcher.setSimilarity(similarity); Query queryContents = new BagOfWordsQueryGenerator().buildQuery(LuceneDocumentGenerator.FIELD_BODY, analyzer, q); Query queryField = new BagOfWordsQueryGenerator().buildQuery(f, analyzer, q); BooleanQuery query = new BooleanQuery.Builder() .add(queryContents, BooleanClause.Occur.SHOULD) .add(new BoostQuery(queryField, boost), BooleanClause.Occur.SHOULD).build(); <START> <END> List<String> queryTokens = AnalyzerUtils.tokenize(analyzer, q); SearchArgs searchArgs = new SearchArgs(); searchArgs.arbitraryScoreTieBreak = false; searchArgs.hits = k; searchArgs.searchtweets = searchtweets; TopDocs rs = new TopDocs(0, new ScoreDoc[]{}, Float.NaN); RerankerContext context; if (searchtweets) { throw new UnsupportedOperationException(); } else { rs = searcher.search(query, isRerank ? searchArgs.rerankcutoff : k, BREAK_SCORE_TIES_BY_DOCID, true, true); context = new RerankerContext<>(searcher, null, query, null, q, queryTokens, null, searchArgs); } ScoredDocuments hits = cascade.run(ScoredDocuments.fromTopDocs(rs, searcher), context); Result[] results = new Result[hits.ids.length]; for (int i = 0; i < hits.ids.length; i++) { Document doc = hits.documents[i]; String docid = doc.getField(LuceneDocumentGenerator.FIELD_ID).stringValue(); IndexableField field = doc.getField(LuceneDocumentGenerator.FIELD_RAW); String content = field == null ? null : field.stringValue(); results[i] = new Result(docid, hits.ids[i], hits.scores[i], content); } return results; }</code><technical_language>lines in function search(), right? Packing function better</technical_language>

Target:
public Result[] searchFields(String q, String f, float boost, int k) throws IOException { IndexSearcher searcher = new IndexSearcher(reader); searcher.setSimilarity(similarity); Query queryContents = new BagOfWordsQueryGenerator().buildQuery(LuceneDocumentGenerator.FIELD_BODY, analyzer, q); Query queryField = new BagOfWordsQueryGenerator().buildQuery(f, analyzer, q); BooleanQuery query = new BooleanQuery.Builder() .add(queryContents, BooleanClause.Occur.SHOULD) .add(new BoostQuery(queryField, boost), BooleanClause.Occur.SHOULD).build(); List<String> queryTokens = AnalyzerUtils.tokenize(analyzer, q); return search(query, queryTokens, q, k, -1); }
Source:
<code>public void boot(final PlayerName playerName) { assertUserIsAdmin(); if (serverMessenger.getServerNode().getPlayerName().equals(playerName)) { throw new IllegalStateException("Cannot boot server node"); } final INode modNode = MessageContext.getSender(); serverMessenger.getNodes().stream() .filter(n -> n.getPlayerName().equals(playerName)) <START> .findAny() <END> .ifPresent( node -> { serverMessenger.removeConnection(node); database .getModeratorAuditHistoryDao() .addAuditRecord( ModeratorAuditHistoryDao.AuditArgs.builder() .moderatorUserId( database .getUserJdbiDao() .lookupUserIdByName(modNode.getName()) .orElseThrow( () -> new IllegalStateException( "Failed to find user: " + modNode.getName()))) .actionName(ModeratorAuditHistoryDao.AuditAction.BOOT_USER_FROM_LOBBY) .actionTarget(node.getPlayerName().getValue()) .build()); }); }</code><technical_language>this exact snippet now. create a private helper method</technical_language>

Target:
public void boot(final PlayerName playerName) { assertUserIsAdmin(); if (serverMessenger.getServerNode().getPlayerName().equals(playerName)) { throw new IllegalStateException("Cannot boot server node"); } final INode modNode = MessageContext.getSender(); findNodeByPlayerName(playerName) .ifPresent( node -> { serverMessenger.removeConnection(node); database .getModeratorAuditHistoryDao() .addAuditRecord( ModeratorAuditHistoryDao.AuditArgs.builder() .moderatorUserId( database .getUserJdbiDao() .lookupUserIdByName(modNode.getName()) .orElseThrow( () -> new IllegalStateException( "Failed to find user: " + modNode.getName()))) .actionName(ModeratorAuditHistoryDao.AuditAction.BOOT_USER_FROM_LOBBY) .actionTarget(node.getPlayerName().getValue()) .build()); }); }
Source:
<code>void processRequest(CorfuMsg msg, ChannelHandlerContext ctx, IServerRouter r) { <START> executor.submit(() -> getHandler().handle(msg, ctx, r)); <END> }</code><technical_language>move naming of threads common configuration well. is easier debugging point of view production support easily sense well</technical_language>

Target:
protected void processRequest(CorfuMsg msg, ChannelHandlerContext ctx, IServerRouter r) { executor.submit(() -> getHandler().handle(msg, ctx, r)); }
Source:
<code><START> public Collection<Object> getAppComponents(String extension, SupportedTransports type, Object... services) { <END> if (!OWNER_EXTENSION.equals(extension)) { return Collections.emptyList(); } ScenarioSimulationService scenarioSimulationService = Arrays.stream(services) .filter(elem -> ScenarioSimulationService.class.isAssignableFrom(elem.getClass())) .map(ScenarioSimulationService.class::cast) .findFirst() .orElse(null); List<Object> components = new ArrayList<Object>(1); if (SupportedTransports.REST.equals(type)) { components.add(new ScenarioSimulationResource(scenarioSimulationService)); } return components; }</code><technical_language>check services null</technical_language>

Target:
public Collection<Object> getAppComponents(String extension, SupportedTransports type, Object... services) { if (!Objects.equals(OWNER_EXTENSION, extension)) { return Collections.emptyList(); } Optional<ScenarioSimulationService> simulationService = Arrays.stream(services) .filter(elem -> ScenarioSimulationService.class.isAssignableFrom(elem.getClass())) .map(ScenarioSimulationService.class::cast) .findFirst(); List<Object> components = new ArrayList<>(1); if (SupportedTransports.REST.equals(type)) { if (simulationService.isPresent()) { components.add(new ScenarioSimulationResource(simulationService.get())); } else { logger.error("Impossible to load Test Scenario extension because of missing ScenarioSimulationService. " + "This should never happen if ScenarioSimulationKieServerExtension is properly deployed and activated"); } } return components; }
Source:
<code>public void testRemoveReadingLists() { ContentResource cr = mock(ContentResource.class); files.put("IsCitation", cr); <START> when(cr.getContentType()).thenReturn("org.sakaiproject.citation.impl.CitationList"); <END> assertEquals(0, exportUtil.removeReadingLists(files).size()); }</code><technical_language>I this cr.getResourceType()</technical_language>

Target:
public void testRemoveReadingLists() { ContentResource cr = mock(ContentResource.class); files.put("IsCitation", cr); when(cr.getResourceType()).thenReturn("org.sakaiproject.citation.impl.CitationList"); assertEquals(0, exportUtil.removeReadingLists(files).size()); }
Source:
<code>public void setKeyName(String keyName) { <START> if (keyName == null || keyName.isEmpty()) { <END> throw new IllegalArgumentException("Argument cannot be null."); } if (keyName.length() > SecurityConstants.MAX_KEY_NAME_LENGTH) { throw new IllegalArgumentException("sasKeyName cannot be greater than " + SecurityConstants.MAX_KEY_NAME_LENGTH + " characters."); } this.keyName = keyName; }</code><technical_language>I replace this Replace Objects.requireNotNull another check for isEmpty</technical_language>

Target:
public void setKeyName(String keyName) { if (keyName == null || keyName.isEmpty()) { throw new IllegalArgumentException("Argument cannot be null"); } if (keyName.length() > SecurityConstants.MAX_KEY_NAME_LENGTH) { throw new IllegalArgumentException("sasKeyName cannot be greater than " + SecurityConstants.MAX_KEY_NAME_LENGTH + " characters."); } this.keyName = keyName; }
Source:
<code>public Item[] addItem(Item... slots) { List<Item> itemSlots = new ArrayList<>(); for (Item slot : slots) { if (slot.getId() != 0 && slot.getCount() > 0) { itemSlots.add(slot.clone()); } } List<Integer> emptySlots = new ArrayList<>(); for (int i = 0; i < this.getSize(); ++i) { Item item = this.getItem(i); if (item.getId() == Item.AIR || item.getCount() <= 0) { emptySlots.add(i); } for (Item slot : new ArrayList<>(itemSlots)) { <START> if (slot.equals(item) && item.getCount() < item.getMaxStackSize() && slot.getDamage() == item.getDamage()) { <END> int amount = Math.min(item.getMaxStackSize() - item.getCount(), slot.getCount()); amount = Math.min(amount, this.getMaxStackSize()); if (amount > 0) { slot.setCount(slot.getCount() - amount); item.setCount(item.getCount() + amount); this.setItem(i, item); if (slot.getCount() <= 0) { itemSlots.remove(slot); } } } } if (itemSlots.isEmpty()) { break; } } if (!itemSlots.isEmpty() && !emptySlots.isEmpty()) { for (int slotIndex : emptySlots) { if (!itemSlots.isEmpty()) { Item slot = itemSlots.get(0); int amount = Math.min(slot.getMaxStackSize(), slot.getCount()); amount = Math.min(amount, this.getMaxStackSize()); slot.setCount(slot.getCount() - amount); Item item = slot.clone(); item.setCount(amount); this.setItem(slotIndex, item); if (slot.getCount() <= 0) { itemSlots.remove(slot); } } } } return itemSlots.stream().toArray(Item[]::new); }</code><technical_language><LINK_0></technical_language>

Target:
public Item[] addItem(Item... slots) { List<Item> itemSlots = new ArrayList<>(); for (Item slot : slots) { if (slot.getId() != 0 && slot.getCount() > 0) { itemSlots.add(slot.clone()); } } List<Integer> emptySlots = new ArrayList<>(); for (int i = 0; i < this.getSize(); ++i) { Item item = this.getItem(i); if (item.getId() == Item.AIR || item.getCount() <= 0) { emptySlots.add(i); } for (Item slot : new ArrayList<>(itemSlots)) { if (slot.equals(item) && item.getCount() < item.getMaxStackSize()) { int amount = Math.min(item.getMaxStackSize() - item.getCount(), slot.getCount()); amount = Math.min(amount, this.getMaxStackSize()); if (amount > 0) { slot.setCount(slot.getCount() - amount); item.setCount(item.getCount() + amount); this.setItem(i, item); if (slot.getCount() <= 0) { itemSlots.remove(slot); } } } } if (itemSlots.isEmpty()) { break; } } if (!itemSlots.isEmpty() && !emptySlots.isEmpty()) { for (int slotIndex : emptySlots) { if (!itemSlots.isEmpty()) { Item slot = itemSlots.get(0); int amount = Math.min(slot.getMaxStackSize(), slot.getCount()); amount = Math.min(amount, this.getMaxStackSize()); slot.setCount(slot.getCount() - amount); Item item = slot.clone(); item.setCount(amount); this.setItem(slotIndex, item); if (slot.getCount() <= 0) { itemSlots.remove(slot); } } } } return itemSlots.stream().toArray(Item[]::new); }
Source:
<code>public synchronized void onMessageProcessingFinished(TcpDiscoveryAbstractMessage msg) { assert msg != null; Long startTs = msgsProcStartTs.remove(msg.id()); <START> if (startTs == null) { <END> long duration = U.currentTimeMillis() - startTs; int totalProcMsgs = totalProcessedMessages(); if (totalProcMsgs != 0) avgMsgProcTime = (avgMsgProcTime * (totalProcMsgs - 1) + duration) / totalProcMsgs; if (duration > maxMsgProcTime) maxMsgProcTime = duration; } }</code><technical_language>Is mistake? long duration = U.currentTimeMillis() - startTs; startTs is null</technical_language>

Target:
public synchronized void onMessageProcessingFinished(TcpDiscoveryAbstractMessage msg) { assert msg != null; Long startTs = msgsProcStartTs.remove(msg.id()); if (startTs != null) { long duration = U.currentTimeMillis() - startTs; int totalProcMsgs = totalProcessedMessages(); if (totalProcMsgs != 0) avgMsgProcTime = (avgMsgProcTime * (totalProcMsgs - 1) + duration) / totalProcMsgs; if (duration > maxMsgProcTime) maxMsgProcTime = duration; } }
Source:
<code>public void testCancelSubscriptionWithInvalidRequestedDate() throws SubscriptionBaseApiException { final String prod = "Shotgun"; final BillingPeriod term = BillingPeriod.MONTHLY; final String planSet = PriceListSet.DEFAULT_PRICELIST_NAME; final DefaultSubscriptionBase subscription = testUtil.createSubscription(bundle, prod, term, planSet); PlanPhase currentPhase = subscription.getCurrentPhase(); assertEquals(currentPhase.getPhaseType(), PhaseType.TRIAL); testListener.pushExpectedEvent(NextEvent.PHASE); final Interval it = new Interval(clock.getUTCNow(), clock.getUTCNow().plusDays(31)); clock.addDeltaFromReality(it.toDurationMillis()); assertListenerStatus(); currentPhase = subscription.getCurrentPhase(); assertEquals(currentPhase.getPhaseType(), PhaseType.EVERGREEN); final DateTime invalidDate = subscription.getBundleStartDate().minusDays(3); subscription.cancelWithDate(invalidDate, callContext); assertListenerStatus(); testListener.pushExpectedEvent(NextEvent.CANCEL); <START> assertListenerStatus(); <END> }</code><technical_language>I confused that: If i understand correctly test throw line 259 (since requestedDate is invalid), expect a CANCEL event afterwards</technical_language>

Target:
public void testCancelSubscriptionWithInvalidRequestedDate() throws SubscriptionBaseApiException { final String prod = "Shotgun"; final BillingPeriod term = BillingPeriod.MONTHLY; final String planSet = PriceListSet.DEFAULT_PRICELIST_NAME; final DefaultSubscriptionBase subscription = testUtil.createSubscription(bundle, prod, term, planSet); PlanPhase currentPhase = subscription.getCurrentPhase(); assertEquals(currentPhase.getPhaseType(), PhaseType.TRIAL); testListener.pushExpectedEvent(NextEvent.PHASE); final Interval it = new Interval(clock.getUTCNow(), clock.getUTCNow().plusDays(31)); clock.addDeltaFromReality(it.toDurationMillis()); assertListenerStatus(); currentPhase = subscription.getCurrentPhase(); assertEquals(currentPhase.getPhaseType(), PhaseType.EVERGREEN); final DateTime invalidDate = subscription.getBundleStartDate().minusDays(3); subscription.cancelWithDate(invalidDate, callContext); }
Source:
<code>private String getSelectedFunctionString(String functionString) { functionString += " "; functionString = functionString.replace("(", "( "); functionString = functionString.replace(")", " )"); functionString = functionString.replace(",", " , "); <START> <END> return functionString; }</code><technical_language>id prefer: return functionString.replace("(", "( ") .replace(")", " )") .replace(",", " , ") + " "; return functionString.replace("(", "( ") .replace(")", " )") .replace(",", " , ") .concat(" ");</technical_language>

Target:
private String getSelectedFunctionString(String functionString) { return functionString.replace("(", "( ") .replace(")", " )") .replace(",", " , ") .concat(" "); }
Source:
<code>protected void executeCommand() { if (noChangesDetected()) { log.info("No changes were detected in setup networks for host '{}' (ID: '{}')", getVdsName(), getVdsId()); setSucceeded(true); return; } <START> fillInUnsetBondingOptions(); <END> int timeout = getSetupNetworksTimeout(); FutureVDSCall<VDSReturnValue> setupNetworksTask = invokeSetupNetworksCommand(timeout); try { VDSReturnValue retVal = setupNetworksTask.get(timeout, TimeUnit.SECONDS); if (retVal != null) { if (!retVal.getSucceeded() && retVal.getVdsError() == null && getParameters().rollbackOnFailure()) { throw new EngineException(EngineError.SETUP_NETWORKS_ROLLBACK, retVal.getExceptionString()); } VdsHandler.handleVdsResult(retVal); if (retVal.getSucceeded()) { try (EngineLock monitoringLock = acquireMonitorLock()) { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetCapabilities, new VdsIdAndVdsVDSCommandParametersBase(getVds())); VDS updatedHost = (VDS) returnValue.getReturnValue(); persistNetworkChanges(updatedHost); } logMonitorLockReleased("Host setup networks"); setSucceeded(true); } } } catch (TimeoutException e) { log.debug("Host Setup networks command timed out for seconds", timeout); } }</code><technical_language>completion done cando validations, HostSetupNetworksValidator.validateQosCommitment(..) NPE is case of null bondOptions (when calculate bond's speed)</technical_language>

Target:
protected void executeCommand() { if (noChangesDetected()) { log.info("No changes were detected in setup networks for host '{}' (ID: '{}')", getVdsName(), getVdsId()); setSucceeded(true); return; } int timeout = getSetupNetworksTimeout(); FutureVDSCall<VDSReturnValue> setupNetworksTask = invokeSetupNetworksCommand(timeout); try { VDSReturnValue retVal = setupNetworksTask.get(timeout, TimeUnit.SECONDS); if (retVal != null) { if (!retVal.getSucceeded() && retVal.getVdsError() == null && getParameters().rollbackOnFailure()) { throw new EngineException(EngineError.SETUP_NETWORKS_ROLLBACK, retVal.getExceptionString()); } VdsHandler.handleVdsResult(retVal); if (retVal.getSucceeded()) { try (EngineLock monitoringLock = acquireMonitorLock()) { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetCapabilities, new VdsIdAndVdsVDSCommandParametersBase(getVds())); VDS updatedHost = (VDS) returnValue.getReturnValue(); persistNetworkChanges(updatedHost); } logMonitorLockReleased("Host setup networks"); setSucceeded(true); } } } catch (TimeoutException e) { log.debug("Host Setup networks command timed out for seconds", timeout); } }
Source:
<code>public void deployPartial(String name, Set<TargetExtensions> targetExtensions) throws Exception { Bundle bundle = new BundleImpl(osgi, lookupBundle(name), null); RuntimeContext ctx = new OSGiRuntimeContext(runtime, bundle); listBundleComponents(bundle).map(URLStreamRef::new).forEach(component -> { try { this.deployPartialComponent(ctx, targetExtensions, component); } catch (IOException e) { <START> log.warn("PartialBundle: " + name + " failed to load: " + component, e); <END> } }); }</code><technical_language>If this is unexpected case log.error here</technical_language>

Target:
public void deployPartial(String name, Set<TargetExtensions> targetExtensions) throws Exception { Bundle bundle = new BundleImpl(osgi, lookupBundle(name), null); RuntimeContext ctx = new OSGiRuntimeContext(runtime, bundle); listBundleComponents(bundle).map(URLStreamRef::new).forEach(component -> { try { this.deployPartialComponent(ctx, targetExtensions, component); } catch (IOException e) { log.error("PartialBundle: " + name + " failed to load: " + component, e); } }); }
Source:
<code>private Deployment getDeploymentByName(String deploymentName) throws IOException { <START> Deployment dc = openShiftClient <END> .extensions().deployments() .inNamespace(this.cheOpenShiftProjectName) .withName(deploymentName) .get(); if (dc == null) { LOG.warn("No Deployment with name " + deploymentName + " could be found"); } return dc; }</code><technical_language>dc is meaningful</technical_language>

Target:
private Deployment getDeploymentByName(String deploymentName) throws IOException { Deployment deployment = openShiftClient .extensions().deployments() .inNamespace(this.openShiftCheProjectName) .withName(deploymentName) .get(); if (deployment == null) { LOG.warn("No Deployment with name could be found", deploymentName); } return deployment; }
Source:
<code>public String getUserName() { <START> final User user = User.get(authenticationName, false, Collections.emptyMap()); <END> return user != null ? user.getDisplayName() : authenticationName; }</code><technical_language>getById</technical_language>

Target:
public String getUserName() { final User user = User.getById(authenticationName, false); return user != null ? user.getDisplayName() : authenticationName; }
Source:
<code>public static CosmosChangeFeedFindToken fromBytes(DataInputStream inputStream) throws IOException { CosmosChangeFeedFindToken cosmosChangeFeedFindToken; DataInputStream stream = new DataInputStream(inputStream); short version = stream.readShort(); switch (version) { case VERSION_0: FindTokenType type = FindTokenType.values()[stream.readShort()]; if (type != FindTokenType.CloudBased) { throw new IllegalArgumentException( String.format("Invalid token type %s found while deserialization. Expected %s.", type, FindTokenType.CloudBased)); } long bytesRead = stream.readLong(); String startContinuationToken = Utils.readIntString(inputStream); String endContinuationToken = Utils.readIntString(inputStream); int index = inputStream.readInt(); int totalItems = inputStream.readInt(); String cacheSessionId = Utils.readIntString(inputStream); cosmosChangeFeedFindToken = <START> new CosmosChangeFeedFindToken(bytesRead, startContinuationToken, endContinuationToken, index, totalItems, <END> cacheSessionId, version); break; default: throw new IllegalStateException("Unknown version of cloud token: " + version); } return cosmosChangeFeedFindToken; }</code><technical_language>Minor: simply "return new CosmosChangeFeedFindToken(...);</technical_language>

Target:
public static CosmosChangeFeedFindToken fromBytes(DataInputStream inputStream) throws IOException { DataInputStream stream = new DataInputStream(inputStream); short version = stream.readShort(); switch (version) { case VERSION_0: FindTokenType type = FindTokenType.values()[stream.readShort()]; if (type != FindTokenType.CloudBased) { throw new IllegalArgumentException( String.format("Invalid token type %s found while deserialization. Expected %s.", type, FindTokenType.CloudBased)); } long bytesRead = stream.readLong(); String startContinuationToken = readIntString(inputStream); String endContinuationToken = readIntString(inputStream); int index = inputStream.readInt(); int totalItems = inputStream.readInt(); String cacheSessionId = readIntString(inputStream); return new CosmosChangeFeedFindToken(bytesRead, startContinuationToken, endContinuationToken, index, totalItems, cacheSessionId, version); default: throw new IllegalStateException("Unknown version of cloud token: " + version); } }
Source:
<code>public void testPutNextEntryUsingCurrentTime() throws IOException { long <START> timeBeforeZipSeconds = <END> System.currentTimeMillis() / 1000 * 1000; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (ZipOutputStream out = new ZipOutputStream(bos)) { out.putNextEntry(new ZipEntry("name")); out.closeEntry(); out.finish(); } long timeAfterZipSeconds = (System.currentTimeMillis() / 1000 + 1) * 1000; try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(bos.toByteArray()))) { ZipEntry entry = zis.getNextEntry(); assertEquals("name", entry.getName()); assertTrue(timeBeforeZipSeconds <= entry.getTime()); assertTrue(timeAfterZipSeconds >= entry.getTime()); } }</code><technical_language>is this variable (and in line 113) called ....Seconds? is in milliseconds. rename, move multiplication * 1000 left-hand side of expressions in lines 119-120</technical_language>

Target:
public void testPutNextEntryUsingCurrentTime() throws IOException { long timeBeforeZip = System.currentTimeMillis() / 1000 * 1000; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (ZipOutputStream out = new ZipOutputStream(bos)) { ZipEntry entryWithoutExplicitTime = new ZipEntry("name"); out.putNextEntry(entryWithoutExplicitTime); out.closeEntry(); out.finish(); } long timeAfterZip = (System.currentTimeMillis() / 1000 + 1) * 1000; try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(bos.toByteArray()))) { ZipEntry entry = zis.getNextEntry(); assertEquals("name", entry.getName()); assertTrue(timeBeforeZip <= entry.getTime()); assertTrue(timeAfterZip >= entry.getTime()); } }
Source:
<code>public ImportNetworksModel(SearchableListModel sourceListModel) { this.sourceListModel = sourceListModel; setTitle(ConstantsManager.getInstance().getConstants().importNetworksTitle()); setHashName("import_networks"); UICommand tempVar = new UICommand(CMD_IMPORT, this); tempVar.setTitle(ConstantsManager.getInstance().getConstants().importNetworksButton()); tempVar.setIsDefault(true); getCommands().add(tempVar); UICommand tempVar2 = new UICommand(CMD_CANCEL, this); tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar2.setIsCancel(true); getCommands().add(tempVar2); providers.getSelectedItemChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { onProviderChosen(); } <START> }); <END> AsyncDataProvider.GetAllProviders(new AsyncQuery(this, new INewAsyncCallback() { @SuppressWarnings("unchecked") @Override public void onSuccess(Object model, Object returnValue) { List<Provider> providers = Linq.toList(Linq.filterNetworkProviders((Iterable<Provider>) returnValue)); providers.add(0, null); Provider selectedProvider = (Provider) getProviders().getSelectedItem(); getProviders().setItems(providers); getProviders().setSelectedItem(selectedProvider); } })); }</code><technical_language>I start progress in onProviderChosen()</technical_language>

Target:
public ImportNetworksModel(SearchableListModel sourceListModel) { this.sourceListModel = sourceListModel; setTitle(ConstantsManager.getInstance().getConstants().importNetworksTitle()); setHashName("import_networks"); UICommand tempVar = new UICommand(CMD_IMPORT, this); tempVar.setTitle(ConstantsManager.getInstance().getConstants().importNetworksButton()); tempVar.setIsDefault(true); getCommands().add(tempVar); UICommand tempVar2 = new UICommand(CMD_CANCEL, this); tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar2.setIsCancel(true); getCommands().add(tempVar2); providers.getSelectedItemChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { onProviderChosen(); } }); initProviderList(); }
Source:
<code>public void shouldAddNodeToExplicitIndex() throws Exception { long nodeId; try ( Transaction tx = session.beginTransaction() ) { nodeId = tx.dataWrite().nodeCreate(); ExplicitIndexWrite indexWrite = tx.indexWrite(); indexWrite.nodeAddToExplicitIndex( INDEX_NAME, nodeId, KEY, VALUE ); tx.success(); } try ( org.neo4j.graphdb.Transaction ctx = graphDb.beginTx() ) { <START> IndexHits<Node> hits = graphDb.index().forNodes( INDEX_NAME ).get( KEY, "this is it" ); <END> assertThat( hits.next().getId(), equalTo( nodeId ) ); hits.close(); ctx.success(); } }</code><technical_language>Magic string "this is it"</technical_language>

Target:
public void shouldAddNodeToExplicitIndex() throws Exception { long nodeId; try ( Transaction tx = session.beginTransaction() ) { nodeId = tx.dataWrite().nodeCreate(); ExplicitIndexWrite indexWrite = tx.indexWrite(); indexWrite.nodeAddToExplicitIndex( INDEX_NAME, nodeId, KEY, VALUE ); tx.success(); } try ( org.neo4j.graphdb.Transaction ctx = graphDb.beginTx() ) { IndexHits<Node> hits = graphDb.index().forNodes( INDEX_NAME ).get( KEY, VALUE ); assertThat( hits.next().getId(), equalTo( nodeId ) ); hits.close(); ctx.success(); } }
Source:
<code>public void getAmbryBlobStorageServiceTest() throws Exception { JSONObject jsonObject = new JSONObject().put("POST", "http://uploadUrl:15158").put("GET", "http://downloadUrl:15158"); Properties properties = new Properties(); properties.setProperty(FrontendConfig.URL_SIGNER_ENDPOINTS, jsonObject.toString()); <START> properties.setProperty("clustermap.cluster.name", "CLuster-Name"); <END> properties.setProperty("clustermap.datacenter.name", "Datacenter-Name"); properties.setProperty("clustermap.host.name", "localhost"); VerifiableProperties verifiableProperties = new VerifiableProperties(properties); AmbryBlobStorageServiceFactory ambryBlobStorageServiceFactory = new AmbryBlobStorageServiceFactory(verifiableProperties, new MockClusterMap(), new MockRestRequestResponseHandler(), new InMemoryRouter(verifiableProperties, new MockClusterMap()), new InMemAccountService(false, true)); BlobStorageService ambryBlobStorageService = ambryBlobStorageServiceFactory.getBlobStorageService(); assertNotNull("No BlobStorageService returned", ambryBlobStorageService); assertEquals("Did not receive an AmbryBlobStorageService instance", AmbryBlobStorageService.class.getCanonicalName(), ambryBlobStorageService.getClass().getCanonicalName()); }</code><technical_language>minor: Cluster-Name</technical_language>

Target:
public void getAmbryBlobStorageServiceTest() throws Exception { JSONObject jsonObject = new JSONObject().put("POST", "http://uploadUrl:15158").put("GET", "http://downloadUrl:15158"); Properties properties = new Properties(); CommonTestUtils.populateRequiredRouterProps(properties); properties.setProperty(FrontendConfig.URL_SIGNER_ENDPOINTS, jsonObject.toString()); properties.setProperty("clustermap.cluster.name", "Cluster-Name"); properties.setProperty("clustermap.datacenter.name", "Datacenter-Name"); properties.setProperty("clustermap.host.name", "localhost"); VerifiableProperties verifiableProperties = new VerifiableProperties(properties); AmbryBlobStorageServiceFactory ambryBlobStorageServiceFactory = new AmbryBlobStorageServiceFactory(verifiableProperties, new MockClusterMap(), new MockRestRequestResponseHandler(), new InMemoryRouter(verifiableProperties, new MockClusterMap()), new InMemAccountService(false, true)); BlobStorageService ambryBlobStorageService = ambryBlobStorageServiceFactory.getBlobStorageService(); assertNotNull("No BlobStorageService returned", ambryBlobStorageService); assertEquals("Did not receive an AmbryBlobStorageService instance", AmbryBlobStorageService.class.getCanonicalName(), ambryBlobStorageService.getClass().getCanonicalName()); }
Source:
<code>public RecordIterator<T> readBatch() throws IOException { final ParquetReaderBatch<T> batch = getCachedEntry(); final long startingRowNum = rowsReturned; if (!nextBatch(batch)) { batch.recycle(); return null; } final RecordIterator<T> records = batch.convertAndGetIterator(startingRowNum); <START> if (recordsToSkip > 0) { <END> skipRecord(records); } return records; }</code><technical_language>this check is unnecessary</technical_language>

Target:
public RecordIterator<T> readBatch() throws IOException { final ParquetReaderBatch<T> batch = getCachedEntry(); final long rowsReturnedBefore = rowsReturned; if (!nextBatch(batch)) { batch.recycle(); return null; } final RecordIterator<T> records = batch.convertAndGetIterator(rowsReturnedBefore); skipRecord(records); return records; }
Source:
<code><START> public Flux<FileRange> listRanges() { <END> return azureFileStorageClient.files().getRangeListWithRestResponseAsync(shareName, filePath, shareSnapshot, null, null, Context.NONE) .flatMapMany(this::convertListRangesResponseToFileRangeInfo); }</code><technical_language>question other listRanges question</technical_language>

Target:
public Flux<FileRange> listRanges() { return azureFileStorageClient.files().getRangeListWithRestResponseAsync(shareName, filePath, snapshot, null, null, Context.NONE) .flatMapMany(this::convertListRangesResponseToFileRangeInfo); }
Source:
<code>public void addLogicalTypeConversion(Conversion<?> conversion) { conversions.put(conversion.getLogicalTypeName(), conversion); Class<?> type = conversion.getConvertedType(); <START> if (conversionsByClass.containsKey(type)) { <END> conversionsByClass.get(type).add(conversion); } else { List<Conversion<?>> conversions = new ArrayList<Conversion<?>>(1); conversions.add(conversion); conversionsByClass.put(type, conversions); } }</code><technical_language>GenericData is a singleton, threadsafe? changes aren't, AFAICT logical type stuff prior this patch either</technical_language>

Target:
public void addLogicalTypeConversion(Conversion<?> conversion) { conversions.put(conversion.getLogicalTypeName(), conversion); Class<?> type = conversion.getConvertedType(); if (conversionsByClass.containsKey(type)) { conversionsByClass.get(type).put( conversion.getLogicalTypeName(), conversion); } else { Map<String, Conversion<?>> conversions = new LinkedHashMap<String, Conversion<?>>(); conversions.put(conversion.getLogicalTypeName(), conversion); conversionsByClass.put(type, conversions); } }
Source:
<code>public ValidationResult update(Consumer consumer, Entitlement entitlement, Integer change) { ValidationResult result = new ValidationResult(); if (!consumer.getType().isManifest()) { Pool pool = entitlement.getPool(); if (!"yes".equalsIgnoreCase(pool.getProductAttributeValue(Pool.Attributes.MULTI_ENTITLEMENT)) && entitlement.getQuantity() + change > 1) { result.addError(new ValidationError(i18n.tr( <START> EntitlementRulesTranslator.PoolErrorKeys.MULTI_ENTITLEMENT_UNSUPPORTED))); <END> } if (!consumer.isGuest()) { String multiplier = pool.getProductAttributeValue(Product.Attributes.INSTANCE_MULTIPLIER); if (multiplier != null) { int instanceMultiplier = Integer.parseInt(multiplier); if ((entitlement.getQuantity() + change) % instanceMultiplier != 0) { result.addError(new ValidationError(i18n.tr( EntitlementRulesTranslator.PoolErrorKeys.QUANTITY_MISMATCH ))); } } } } finishValidation(result, entitlement.getPool(), change); return result; }</code><technical_language>I this is valid, is it? translating a key here</technical_language>

Target:
public ValidationResult update(Consumer consumer, Entitlement entitlement, Integer change) { ValidationResult result = new ValidationResult(); if (!consumer.getType().isManifest()) { Pool pool = entitlement.getPool(); if (!"yes".equalsIgnoreCase(pool.getProductAttributeValue(Pool.Attributes.MULTI_ENTITLEMENT)) && entitlement.getQuantity() + change > 1) { result.addError(new ValidationError( EntitlementRulesTranslator.PoolErrorKeys.MULTI_ENTITLEMENT_UNSUPPORTED)); } if (!consumer.isGuest()) { String multiplier = pool.getProductAttributeValue(Product.Attributes.INSTANCE_MULTIPLIER); if (multiplier != null) { int instanceMultiplier = Integer.parseInt(multiplier); if ((entitlement.getQuantity() + change) % instanceMultiplier != 0) { result.addError(new ValidationError( EntitlementRulesTranslator.PoolErrorKeys.QUANTITY_MISMATCH )); } } } } finishValidation(result, entitlement.getPool(), change); return result; }
Source:
<code><START> public final Statement apply( <END> final Statement base, final Description description ) { return new Statement() { @Override public void evaluate() throws Throwable { try { base.evaluate(); } catch (final IllegalStateException ex) { Logger.warn( base, String.format( "Test %s skipped due to IllegalStateException", description ) ); Assume.assumeTrue(false); } } }; }</code><technical_language>need override this method ExternalResource anymore</technical_language>

Target:
public final Statement apply( final Statement base, final Description description ) { return new Statement() { @Override public void evaluate() throws Throwable { try { base.evaluate(); } catch (final BindException ignored) { Logger.warn( base, String.format( "Test %s skipped due to no available ports", description ) ); Assume.assumeTrue(false); } } }; }
Source:
<code>public List<String> getValues() { <START> return values.stream().map(String::new).collect(Collectors.toList()); <END> }</code><technical_language>new platform default encoding. This is UTF-8, guaranteed, ASCII, problems. (Also for getBytes, Unicode application result in a mess in binary)</technical_language>

Target:
public List<String> getValues() { return values.stream() .map(b -> new String(b, StandardCharsets.US_ASCII)) .collect(Collectors.toList()); }
Source:
<code>public boolean execute(final CompileContext context) { Project project = context.getProject(); if (ErlangCompilerSettings.getInstance(project).isUseRebarCompilerEnabled()) { return true; } <START> LOG.info("Prepare build order for project "+project.getName()); <END> File projectSystemDirectory = BuildManager.getInstance().getProjectSystemDirectory(project); if (projectSystemDirectory == null) { addPrepareDependenciesFailedMessage(context); return true; } LOG.debug("Run action for preparing build order"); ErlangProjectBuildOrder projectBuildOrder = ApplicationManager.getApplication().runReadAction(new Computable<ErlangProjectBuildOrder>() { @Nullable @Override public ErlangProjectBuildOrder compute() { return getProjectBuildOrder(context); } }); if (projectBuildOrder == null) { return false; } try { LOG.debug("Serialize build order"); Document serializedDocument = new Document(XmlSerializer.serialize(projectBuildOrder, new SkipDefaultValuesSerializationFilters())); File file = new File(projectSystemDirectory, ErlangPrepareDependenciesBuilder.DEPENDENCIES_TREE_FILE_PATH); file.getParentFile().mkdirs(); LOG.debug("Write build order to "+file.getAbsolutePath()); JDOMUtil.writeDocument(serializedDocument, file, SystemProperties.getLineSeparator()); } catch (XmlSerializationException e) { LOG.warn("Can't serialize build order object."); LOG.debug(e); addPrepareDependenciesFailedMessage(context); return true; } catch (IOException e) { LOG.warn("Some I/O errors occurred while writing build orders to file"); LOG.debug(e); addPrepareDependenciesFailedMessage(context); return true; } return true; }</code><technical_language>Formatting</technical_language>

Target:
public boolean execute(final CompileContext context) { Project project = context.getProject(); if (ErlangCompilerSettings.getInstance(project).isUseRebarCompilerEnabled()) { return true; } LOG.info("Prepare build order for project " + project.getName()); File projectSystemDirectory = BuildManager.getInstance().getProjectSystemDirectory(project); if (projectSystemDirectory == null) { addPrepareDependenciesFailedMessage(context); return true; } ErlangProjectBuildOrder projectBuildOrder = ApplicationManager.getApplication().runReadAction(new Computable<ErlangProjectBuildOrder>() { @Nullable @Override public ErlangProjectBuildOrder compute() { return getProjectBuildOrder(context); } }); if (projectBuildOrder == null) { return false; } writeBuildOrder(context, projectSystemDirectory, projectBuildOrder); return true; }
Source:
<code>protected void validateMetadata(BlobMetadata metadata) throws IOException { <START> checkExtendedAttributesSupport(); <END> super.validateMetadata(metadata); }</code><technical_language>This is I mentioned in previous review -- this a test checks metadata, including non-xattr, skip. skip full tests</technical_language>

Target:
protected void validateMetadata(BlobMetadata metadata) throws IOException { if (!isMacOSX()) { super.validateMetadata(metadata); } }
Source:
<code>public ToolUseHandler getItemHandler() { return (e, tool, fortune, drops) -> { <START> if (SlimefunTag.SMELTERS_PICKAXE_BLOCKS.isTagged(e.getBlock().getType()) && !BlockStorage.hasBlockInfo(e.getBlock())) { <END> Collection<ItemStack> blockDrops = e.getBlock().getDrops(getItem()); for (ItemStack drop : blockDrops) { if (drop != null && drop.getType() != Material.AIR) { smelt(e.getBlock(), drop, fortune); drops.add(drop); } } damageItem(e.getPlayer(), tool); } }; }</code><technical_language>This some refactoring too</technical_language>

Target:
public ToolUseHandler getItemHandler() { return (e, tool, fortune, drops) -> { Block b = e.getBlock(); if (SlimefunTag.SMELTERS_PICKAXE_BLOCKS.isTagged(b.getType()) && !BlockStorage.hasBlockInfo(b)) { Collection<ItemStack> blockDrops = b.getDrops(getItem()); for (ItemStack drop : blockDrops) { if (drop != null && drop.getType() != Material.AIR) { smelt(b, drop, fortune); drops.add(drop); } } damageItem(e.getPlayer(), tool); } }; }
Source:
<code>public int execute() { try { SamInputResource resource = initInputResource(); @Cleanup <START> final SamReader reader = SamReaderFactory.makeDefault().open(resource); <END> SAMFileHeader header = reader.getFileHeader(); QueryInterval[] intervals = QueryHandler.parseQueryStrings(header, query); String outputFileName = generateFileOutputName(); @Cleanup final SAMFileWriter writer = initFileWriter(header, outputFileName); if (!headerOnly) { SAMRecordIterator iterator = reader.query(intervals, containedOnly); while (iterator.hasNext()) { val record = iterator.next(); writer.addAlignment(record); } } } catch (IOException e) { throw new RuntimeException(e); } return SUCCESS_STATUS; }</code><technical_language>Prefer of val in situations. cuts type noise in java. a gotchas val: - a closure - RHS of anonymous class assignment - array references though</technical_language>

Target:
public int execute() { try { SamInputResource resource = createInputResource(); @Cleanup val reader = SamReaderFactory.makeDefault().open(resource); SAMFileHeader header = reader.getFileHeader(); QueryInterval[] intervals = QueryHandler.parseQueryStrings(header, query); val outputFileName = generateFileOutputName(); @Cleanup val writer = createFileWriter(header, outputFileName); if (!headerOnly) { SAMRecordIterator iterator = reader.query(intervals, containedOnly); while (iterator.hasNext()) { val record = iterator.next(); writer.addAlignment(record); } } } catch (IOException e) { throw new RuntimeException(e); } return SUCCESS_STATUS; }