auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void parseDelete(final ReceiveCommand cmd) { RefControl ctl = projectControl.controlForRef(cmd.getRefName()); String refName = cmd.getRefName(); if (refName.startsWith("refs/changes/")) { errors.put(Error.DELETE_CHANGES, refName); reject(cmd, "cannot delete changes"); } else if (ctl.canDelete()) { batch.addCommand(cmd); } else { <START> if (GitRepositoryManager.REF_CONFIG.equals(refName)) { <END> reject(cmd, "cannot delete project configuration"); } else { errors.put(Error.DELETE, ctl.getRefName()); reject(cmd, "cannot delete references"); } } }</code><technical_language>This is comparing cmd.getRefName ctl.getRefName</technical_language>

Target:
private void parseDelete(final ReceiveCommand cmd) { RefControl ctl = projectControl.controlForRef(cmd.getRefName()); String refName = cmd.getRefName(); if (refName.startsWith("refs/changes/")) { errors.put(Error.DELETE_CHANGES, refName); reject(cmd, "cannot delete changes"); } else if (ctl.canDelete()) { batch.addCommand(cmd); } else { if (GitRepositoryManager.REF_CONFIG.equals(ctl.getRefName())) { reject(cmd, "cannot delete project configuration"); } else { errors.put(Error.DELETE, ctl.getRefName()); reject(cmd, "cannot delete references"); } } }
Source:
<code>private GitModelObject[] createChildren() { FileModelFactory fileModelFactory = new FileModelFactory() { @Override public GitModelBlob createFileModel(GitModelObjectContainer parent, Repository repository, Change change, IPath fullPath) { return new GitModelBlob(parent, repository, change, fullPath); } @Override public boolean isWorkingTree() { return false; } }; TreeModelFactory treeModelFactory = GitModelTree::new; return TreeBuilder.build(this, repo, commit.getChildren(), fileModelFactory, <START> treeModelFactory); <END> }</code><technical_language>GitModelTree::new remove local variable treeModelFactory altogether</technical_language>

Target:
private GitModelObject[] createChildren() { FileModelFactory fileModelFactory = new FileModelFactory() { @Override public GitModelBlob createFileModel(GitModelObjectContainer parent, Repository repository, Change change, IPath fullPath) { return new GitModelBlob(parent, repository, change, fullPath); } @Override public boolean isWorkingTree() { return false; } }; return TreeBuilder.build(this, repo, commit.getChildren(), fileModelFactory, GitModelTree::new); }
Source:
<code><START> DependencyPresenceOnStartupVerifier dependencyPresenceOnStartupVerifier() { <END> return new DefaultDependencyPresenceOnStartupVerifier(); }</code><technical_language>add public modifier</technical_language>

Target:
public DependencyPresenceOnStartupVerifier dependencyPresenceOnStartupVerifier() { return new DefaultDependencyPresenceOnStartupVerifier(); }
Source:
<code>protected void deregister() { <START> if ((getChartViewer().getControl() != null) && !getChartViewer().getControl().isDisposed()) { <END> Composite plotArea = (Composite) getChart().getPlotArea(); if (this instanceof MouseListener) { plotArea.removeMouseListener((MouseListener) this); } if (this instanceof MouseMoveListener) { plotArea.removeMouseMoveListener((MouseMoveListener) this); } if (this instanceof MouseWheelListener) { plotArea.removeMouseWheelListener((MouseWheelListener) this); } if (this instanceof MouseTrackListener) { plotArea.removeMouseTrackListener((MouseTrackListener) this); } if (this instanceof PaintListener) { plotArea.removePaintListener((PaintListener) this); } if (this instanceof ICustomPaintListener) { ((IPlotArea) plotArea).removeCustomPaintListener((ICustomPaintListener) this); } TmfAbstractToolTipHandler tooltipHandler = getTooltipHandler(); if(tooltipHandler != null) { tooltipHandler.deactivateHoverHelp(plotArea); } } }</code><technical_language>IPlotArea plotArea = getChart().getPlotArea(); Control control = plotArea.getControl()</technical_language>

Target:
protected void deregister() { IPlotArea plotArea = getChart().getPlotArea(); if (plotArea == null) { return; } Control control = plotArea.getControl(); if (!control.isDisposed()) { if (this instanceof MouseListener) { control.removeMouseListener((MouseListener) this); } if (this instanceof MouseMoveListener) { control.removeMouseMoveListener((MouseMoveListener) this); } if (this instanceof MouseWheelListener) { control.removeMouseWheelListener((MouseWheelListener) this); } if (this instanceof MouseTrackListener) { control.removeMouseTrackListener((MouseTrackListener) this); } if (this instanceof PaintListener) { control.removePaintListener((PaintListener) this); } if (this instanceof ICustomPaintListener) { plotArea.removeCustomPaintListener((ICustomPaintListener) this); } TmfAbstractToolTipHandler tooltipHandler = getTooltipHandler(); if(tooltipHandler != null) { tooltipHandler.deactivateHoverHelp(control); } } }
Source:
<code><START> private static boolean isJavaArchive(Path path) <END> { PathMatcher archiveMatcher = FileSystems.getDefault().getPathMatcher("glob:**.{ear,war,jar}"); return archiveMatcher.matches(path); }</code><technical_language>This org.jboss.windup.util.ZipUtil#getZipExtensions implementation</technical_language>

Target:
private static boolean isJavaArchive(Path path) { Set<String> archiveExtensions = ZipUtil.getZipExtensions(); StringBuffer syntaxAndPattern = new StringBuffer("glob:**.{"); boolean first = true; for(String extension: archiveExtensions) { if(first) { first = false; } else { syntaxAndPattern.append(","); } syntaxAndPattern.append(extension); } syntaxAndPattern.append("}"); PathMatcher archiveMatcher = FileSystems.getDefault().getPathMatcher(syntaxAndPattern.toString()); return archiveMatcher.matches(path); }
Source:
<code>public void createAndRegisterResources() { registerPaxosResource(); registerExceptionMappers(); leadershipCreator.registerLeaderElectionService(); registerTimeLockResourcesForClients(); <START> ClockSkewMonitorCreator.create(install, registrar).registerClockServices(); <END> }</code><technical_language>Is a separate conversation, curious in understanding this works? I assume spins of some background thread checks for clock skew? want embed a Agent allow for wiring this web servers executor service w/e</technical_language>

Target:
public void createAndRegisterResources() { registerPaxosResource(); registerExceptionMappers(); leadershipCreator.registerLeaderElectionService(); registrar.accept(new TimeLockResource(this::createInvalidatingTimeLockServices, Observables.blockingMostRecent( runtime.map(conf -> conf.maxNumberOfClients())))); ClockSkewMonitorCreator.create(install, registrar).registerClockServices(); }
Source:
<code>private synchronized KeyPair readKeyPair() throws GeneralSecurityException, IOException { if (!doesKeyPairExist()) { throw new KeyStoreException("KeyPair entry does not exist."); } Logger.v(TAG, "Reading Key entry"); final KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); try { final KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry)keyStore.getEntry( KEY_STORE_CERT_ALIAS, null); <START> return new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey()); <END> } catch (final RuntimeException e) { ClientAnalytics.logEvent(new AndroidKeyStoreFailureEvent( new InstrumentationPropertiesBuilder(e))); throw new KeyStoreException(e); } }</code><technical_language>@weijjia this line throw RuntimeException well? If so, api throw</technical_language>

Target:
private synchronized KeyPair readKeyPair() throws GeneralSecurityException, IOException { if (!doesKeyPairExist()) { throw new KeyStoreException("KeyPair entry does not exist."); } Logger.v(TAG, "Reading Key entry"); final KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); final KeyStore.PrivateKeyEntry entry; try { entry = (KeyStore.PrivateKeyEntry)keyStore.getEntry( KEY_STORE_CERT_ALIAS, null); } catch (final RuntimeException e) { ClientAnalytics.logEvent(new AndroidKeyStoreFailureEvent( new InstrumentationPropertiesBuilder(e))); throw new KeyStoreException(e); } return new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey()); }
Source:
<code>public void testEnrollmentNoConfig() { JsonObject configBase = new JsonObject(); JsonObject discoveryConfig = new JsonObject(); configBase.add(DISCOVERY, discoveryConfig); JsonObject courseDiscoveryConfig = new JsonObject(); discoveryConfig.add(COURSE_DISCOVERY, courseDiscoveryConfig); Config config = new Config(configBase); assertFalse(config.getDiscoveryConfig().getCourseDiscoveryConfig().isDiscoveryEnabled()); assertFalse(config.getDiscoveryConfig().getCourseDiscoveryConfig().isWebviewDiscoveryEnabled()); assertNull(config.getDiscoveryConfig().getCourseDiscoveryConfig().getBaseUrl()); <START> assertNull(config.getDiscoveryConfig().getCourseDiscoveryConfig().getInfoUrlTemplate()); <END> }</code><technical_language>testEnrollmentNoConfig testEnrollmentEmptyConfig methods / Test same, remove of them</technical_language>

Target:
public void testEnrollmentNoConfig() { JsonObject configBase = new JsonObject(); Config config = new Config(configBase); assertNotNull(config.getDiscoveryConfig()); assertNull(config.getDiscoveryConfig().getCourseDiscoveryConfig()); assertNull(config.getDiscoveryConfig().getProgramDiscoveryConfig()); }
Source:
<code>protected RelNode visitChild(RelNode parent, int i, RelNode child) { RelNode child2 = child.accept(this); if (child2 != child) { final List<RelNode> newInputs = new ArrayList<>(parent.getInputs()); newInputs.set(i, child2); <START> return parent.copy(parent.getTraitSet(), newInputs); <END> } return parent; }</code><technical_language>stack references Nodes objects garbage collected Java recursive visit pattern invoking. overhead</technical_language>

Target:
@Override protected RelNode visitChild(RelNode parent, int i, RelNode child) { stack.push(parent); try { return super.visitChild(parent, i, child); } finally { stack.pop(); } }
Source:
<code>public AmbrySecurityServiceTest() throws InstantiationException { <START> this.securityService = <END> new AmbrySecurityServiceFactory().getSecurityService(new VerifiableProperties(new Properties())); }</code><technical_language>this required</technical_language>

Target:
public AmbrySecurityServiceTest() throws InstantiationException { securityService = new AmbrySecurityServiceFactory() .getSecurityService(new VerifiableProperties(new Properties()), new MetricRegistry()); }
Source:
<code>private void expireSession(RaftSession session) { <START> log.debug("Expiring session due to heartbeat failure: {}", session); <END> appendAndCompact(new CloseSessionEntry(raft.getTerm(), System.currentTimeMillis(), session.sessionId().id(), true)) .whenCompleteAsync((entry, error) -> { log.trace("Appended {}", entry); appender.appendEntries(entry.index()).whenComplete((commitIndex, commitError) -> { raft.checkThread(); if (isRunning() && commitError == null) { raft.getStateMachine().<Long>apply(entry.index()); } }); }, raft.getThreadContext()); }</code><technical_language>Heart beat failure => node deactivated</technical_language>

Target:
private void expireSession(RaftSession session) { log.debug("Expiring session: {}", session); appendAndCompact(new CloseSessionEntry(raft.getTerm(), System.currentTimeMillis(), session.sessionId().id(), true)) .whenCompleteAsync((entry, error) -> { log.trace("Appended {}", entry); appender.appendEntries(entry.index()).whenComplete((commitIndex, commitError) -> { raft.checkThread(); if (isRunning() && commitError == null) { raft.getStateMachine().<Long>apply(entry.index()); } }); }, raft.getThreadContext()); }
Source:
<code>public Builder<C> configure(OperationContext context, ModelNode model) throws OperationFailedException { this.moduleName = MODULE.resolveModelAttribute(context, model).asString(); Map<String, String> map = new HashMap<>(); for (Property property : ModelNodes.optionalPropertyList(PROPERTIES.resolveModelAttribute(context, model)).orElse(Collections.emptyList())) { <START> if (map.put(property.getName(), property.getValue().asString()) != null) { <END> throw new IllegalStateException("Duplicate key"); } } this.properties = map; this.statisticsEnabled = STATISTICS_ENABLED.resolveModelAttribute(context, model).asBooleanOrNull(); return this; }</code><technical_language>Remove conditional + exception. Uniqueness is guaranteed here</technical_language>

Target:
public Builder<C> configure(OperationContext context, ModelNode model) throws OperationFailedException { this.moduleName = MODULE.resolveModelAttribute(context, model).asString(); Map<String, String> map = new HashMap<>(); for (Property property : ModelNodes.optionalPropertyList(PROPERTIES.resolveModelAttribute(context, model)).orElse(Collections.emptyList())) { map.put(property.getName(), property.getValue().asString()); } this.properties = map; this.statisticsEnabled = STATISTICS_ENABLED.resolveModelAttribute(context, model).asBooleanOrNull(); return this; }
Source:
<code>public Issue createIssue(String user, String repository, Issue issue) throws IOException { Assert.isNotNull(user, "User cannot be null"); Assert.isNotNull(repository, "Repository cannot be null"); StringBuilder uri = new StringBuilder(IGitHubConstants.SEGMENT_REPOS); uri.append('/').append(user).append('/').append(repository); uri.append(IGitHubConstants.SEGMENT_ISSUES).append( IGitHubConstants.SUFFIX_JSON); <START> Map<String, String> params = issue == null ? null : createIssueMap(issue); <END> return this.client.post(uri.toString(), params, Issue.class); }</code><technical_language>Put common case in if block: issue !=null ? createIssueMap(issue) : null;</technical_language>

Target:
public Issue createIssue(String user, String repository, Issue issue) throws IOException { Assert.isNotNull(user, "User cannot be null"); Assert.isNotNull(repository, "Repository cannot be null"); StringBuilder uri = new StringBuilder(IGitHubConstants.SEGMENT_REPOS); uri.append('/').append(user).append('/').append(repository); uri.append(IGitHubConstants.SEGMENT_ISSUES).append( IGitHubConstants.SUFFIX_JSON); Map<String, String> params = issue !=null ? createIssueMap(issue) : null; return this.client.post(uri.toString(), params, Issue.class); }
Source:
<code>public boolean testConnection() { try { getClient().execute(new OpenStackRequest<>(getClient(), HttpMethod.GET, "", null, null)); <START> return true; <END> } catch (RuntimeException e) { throw new VdcBLLException(VdcBllErrors.PROVIDER_FAILURE, e); } }</code><technical_language>do need a boolean? I mind, is needed</technical_language>

Target:
public void testConnection() { try { getClient().execute(new OpenStackRequest<>(getClient(), HttpMethod.GET, "", null, null)); } catch (RuntimeException e) { throw new VdcBLLException(VdcBllErrors.PROVIDER_FAILURE, e); } }
Source:
<code>public void fireEvents(TaskType taskType, long delay, Object entity) throws InterruptedException { final String WaitForLaunch = "WaitForLaunch".intern(); final String PoweringUp = "Powering up".intern(); final String Up = "Up".intern(); final String PoweredDown = "Powering down".intern(); final String logMsg = "VM %s set to %s state.".intern(); switch (taskType){ case START_VM: VM vm = (VM) entity; <START> vm.setStatus(VM.VMStatus.WaitForLaunch); <END> sendNotification(WaitForLaunch, vm.getId()); log.info(String.format(logMsg, vm.getImageId(), WaitForLaunch)); TimeUnit.MILLISECONDS.sleep(delay); vm.setStatus(VM.VMStatus.PoweringUp); sendNotification(PoweringUp, vm.getId()); log.info(String.format(logMsg, vm.getImageId(), PoweringUp)); break; case START_VM_AS_UP: vm = (VM) entity; TimeUnit.MILLISECONDS.sleep(delay); vm.setStatus(VM.VMStatus.Up); sendNotification(Up, vm.getId()); VdsmManager.getInstance().updateHost(vm.getHost()); log.info(String.format(logMsg, vm.getImageId(), Up)); break; case SHUTDOWN_VM: vm = (VM) entity; TimeUnit.MILLISECONDS.sleep(delay); vm.setStatus(VM.VMStatus.PoweredDown); vm.getHost().getRunningVMs().remove(vm.getId()); sendNotification(PoweredDown, vm.getId()); VdsmManager.getInstance().updateHost(vm.getHost()); log.info(String.format(logMsg, vm.getImageId(), PoweredDown)); break; default: log.error("Unhandled status detected."); break; } }</code><technical_language>This switch block contains a lot of similar code. Please combine in method(s)</technical_language>

Target:
public void fireEvents(TaskType taskType, long delay, Object entity) throws InterruptedException { final String WaitForLaunch = "WaitForLaunch".intern(); final String PoweringUp = "Powering up".intern(); final String Up = "Up".intern(); final String PoweredDown = "Powering down".intern(); switch (taskType){ case START_VM: vmUpdateStatus((VM) entity, VM.VMStatus.WaitForLaunch, delay, WaitForLaunch, false); vmUpdateStatus((VM) entity, VM.VMStatus.PoweringUp, delay, PoweringUp, false); break; case START_VM_AS_UP: vmUpdateStatus((VM) entity, VM.VMStatus.Up, delay, Up, true); break; case SHUTDOWN_VM: vmUpdateStatus((VM) entity, VM.VMStatus.PoweredDown, delay, PoweredDown, true); break; default: log.error("Unhandled status detected."); break; } }
Source:
<code>private void refresh() { Account[] accounts = Preferences.getPreferences(this).getAccounts(); BaseAccount[] allAccounts = new BaseAccount[accounts.length + 2]; BaseAccount integratedInboxAccount = new SearchAccount(this, true, null, null); integratedInboxAccount.setDescription(getString(R.string.integrated_inbox_title)); integratedInboxAccount.setEmail(getString(R.string.integrated_inbox_detail)); BaseAccount unreadAccount = new SearchAccount(this, false, null, null); unreadAccount.setDescription(getString(R.string.search_all_messages_title)); unreadAccount.setEmail(getString(R.string.search_all_messages_detail)); allAccounts[0] = integratedInboxAccount; allAccounts[1] = unreadAccount; <START> for (int i=0; i<accounts.length; i++) { <END> allAccounts[i+2] = accounts[i]; } mAdapter = new AccountsAdapter(allAccounts); getListView().setAdapter(mAdapter); }</code><technical_language>please add spaces operators. <LINK_0></technical_language>

Target:
private void refresh() { Account[] accounts = Preferences.getPreferences(this).getAccounts(); List<BaseAccount> allAccounts = new ArrayList<BaseAccount>(); if (!K9.isHideSpecialAccounts()) { BaseAccount integratedInboxAccount = new SearchAccount(this, true, null, null); integratedInboxAccount.setDescription( getString(R.string.integrated_inbox_title)); integratedInboxAccount.setEmail( getString(R.string.integrated_inbox_detail)); BaseAccount unreadAccount = new SearchAccount(this, false, null, null); unreadAccount.setDescription( getString(R.string.search_all_messages_title)); unreadAccount.setEmail( getString(R.string.search_all_messages_detail)); allAccounts.add(integratedInboxAccount); allAccounts.add(unreadAccount); } for (int i = 0; i < accounts.length; i++) { allAccounts.add(accounts[i]); } mAdapter = new AccountsAdapter(allAccounts); getListView().setAdapter(mAdapter); }
Source:
<code>public static ScanInfo getScanInfoForFlushesAndCompactions(Configuration conf, ScanInfo oldScanInfo, final Store store, ScanType type) { <START> long ttl = ScanInfoUtil.getTimeToLiveForCompactions(store.getFamily(), oldScanInfo); <END> KeepDeletedCells keepDeletedCells = getKeepDeletedCells(store, type); int minVersions = getMinVersions(oldScanInfo, store); return new ScanInfo(conf,store.getFamily().getName(), minVersions, Integer.MAX_VALUE, ttl, keepDeletedCells, oldScanInfo.getTimeToPurgeDeletes(), oldScanInfo.getComparator()); }</code><technical_language>nit: need provide class name</technical_language>

Target:
public static ScanInfo getScanInfoForFlushesAndCompactions(Configuration conf, ScanInfo oldScanInfo, final Store store, ScanType type) { long ttl = getTimeToLiveForCompactions(store.getFamily(), oldScanInfo); KeepDeletedCells keepDeletedCells = getKeepDeletedCells(store, type); int minVersions = getMinVersions(oldScanInfo, store); return new ScanInfo(conf,store.getFamily().getName(), minVersions, Integer.MAX_VALUE, ttl, keepDeletedCells, oldScanInfo.getTimeToPurgeDeletes(), oldScanInfo.getComparator()); }
Source:
<code>public boolean isConstantExpression(IASTNode point) { return fArg1.isConstantExpression(point) && fArg2.isConstantExpression(point) <START> && (getOverload(point) == null || getOverload(point).isConstexpr()); <END> }</code><technical_language>Avoid calling getOverload twice</technical_language>

Target:
public boolean isConstantExpression(IASTNode point) { return fArg1.isConstantExpression(point) && fArg2.isConstantExpression(point) && isConstexprFuncOrNull(getOverload(point)); }
Source:
<code>public AccountRetrievalService() { <START> super("AccountRetrievalService"); <END> }</code><technical_language>In order increase readability, replacing magic numbers constants a meaning</technical_language>

Target:
public AccountRetrievalService() { super(serviceName); }
Source:
<code>public static String getCurrentLoggedUsername() { String username = SecurityContextHolder.getContext().getAuthentication().getName(); <START> System.out.println(" + + + + LOGGED USERNAME: " + username); <END> return username; }</code><technical_language>system.out.println() in this project</technical_language>

Target:
public static String getCurrentLoggedUsername() { String username = SecurityContextHolder.getContext().getAuthentication().getName(); return username; }
Source:
<code>public void addFileSystemBind(final String hostPath, final String containerPath, final BindMode mode, final SelinuxContext selinuxContext) { final MountableFile mountableFile = MountableFile.forHostPath(hostPath); <START> binds.add(new Bind(mountableFile.getUnixFilesystemPath(), new Volume(containerPath), mode.accessMode, selinuxContext.selContext)); <END> }</code><technical_language>I do here. Future versions of Docker for Windows strict path (C:\foo\bar is good, /mnt/c/foo/bar is bad) I ensure pass C:\ C:/</technical_language>

Target:
public void addFileSystemBind(final String hostPath, final String containerPath, final BindMode mode, final SelinuxContext selinuxContext) { if (SystemUtils.IS_OS_WINDOWS && hostPath.startsWith("/")) { binds.add(new Bind(hostPath, new Volume(containerPath), mode.accessMode, selinuxContext.selContext)); } else { final MountableFile mountableFile = MountableFile.forHostPath(hostPath); binds.add(new Bind(mountableFile.getResolvedPath(), new Volume(containerPath), mode.accessMode, selinuxContext.selContext)); } }
Source:
<code>private void updatePropeties() { if (getEntity() == null) { return; } GlusterVolumeEntity entity = (GlusterVolumeEntity) getEntity(); setName(entity.getName()); setVolumeId(entity.getId() != null ? entity.getId().toString() : null); setVolumeType(entity.getVolumeType() != null ? entity.getVolumeType().toString() : null); setReplicaCount(entity.getReplicaCount() != null ? Integer.toString(entity.getReplicaCount()) : null); setStripeCount(entity.getStripeCount() != null ? Integer.toString(entity.getStripeCount()) : null); setNumOfBricks(entity.getBricks() != null ? Integer.toString(entity.getBricks().size()) : null); setTransportTypes(entity.getTransportTypes()); setVolumeFreeCapacity((entity.getAdvancedDetails() != null && entity.getAdvancedDetails().getCapacityInfo() != null) ?entity.getAdvancedDetails().getCapacityInfo().getFreeSize(): null); setVolumeTotalCapacity((entity.getAdvancedDetails() != null && entity.getAdvancedDetails().getCapacityInfo() != null) ? entity.getAdvancedDetails().getCapacityInfo().getTotalSize() : null); <START> setVolumeUsedCapacity((entity.getAdvancedDetails() != null && entity.getAdvancedDetails().getCapacityInfo() != null) ?entity.getAdvancedDetails().getCapacityInfo().getUsedSize(): null); <END> }</code><technical_language>statements wrapped 'if' block avoid repeating null checks</technical_language>

Target:
private void updatePropeties() { if (getEntity() == null) { return; } GlusterVolumeEntity entity = (GlusterVolumeEntity) getEntity(); setName(entity.getName()); setVolumeId(entity.getId() != null ? entity.getId().toString() : null); setVolumeType(entity.getVolumeType() != null ? entity.getVolumeType().toString() : null); setReplicaCount(entity.getReplicaCount() != null ? Integer.toString(entity.getReplicaCount()) : null); setStripeCount(entity.getStripeCount() != null ? Integer.toString(entity.getStripeCount()) : null); setNumOfBricks(entity.getBricks() != null ? Integer.toString(entity.getBricks().size()) : null); setTransportTypes(entity.getTransportTypes()); if(entity.getAdvancedDetails() != null && entity.getAdvancedDetails().getCapacityInfo() != null) { setVolumeFreeCapacity(entity.getAdvancedDetails().getCapacityInfo().getFreeSize()); setVolumeTotalCapacity(entity.getAdvancedDetails().getCapacityInfo().getTotalSize()); setVolumeUsedCapacity(entity.getAdvancedDetails().getCapacityInfo().getUsedSize()); } else { setVolumeFreeCapacity(null); setVolumeTotalCapacity(null); setVolumeUsedCapacity(null); } }
Source:
<code>private boolean isHavingPredicate(final FilterPredicate filterPredicate) { String entityName = filterPredicate.getEntityType().getName(); String fieldName = filterPredicate.getField(); try { <START> return getEntityDictionary().getFieldAnnotations(entityName, fieldName).stream() <END> .map(Annotation::annotationType) .map(annotation -> annotation.getAnnotation(MetricAggregation.class)) .anyMatch(Objects::nonNull); } catch (NoSuchFieldException exception) { String message = String.format("Field '%s' not found in entity '%s'", entityName, fieldName); log.error(message, exception); throw new IllegalStateException(message, exception); } }</code><technical_language>is a method in EntityDictionary called getAttributeOrRelationAnnotation instead</technical_language>

Target:
private boolean isHavingPredicate(final FilterPredicate filterPredicate) { Class entityClass = filterPredicate.getEntityType(); String fieldName = filterPredicate.getField(); return getSchema().isMetricField(fieldName, entityClass); }
Source:
<code>protected void sendDmxData() { if (this.thing.getStatus().equals(ThingStatus.ONLINE)) { boolean needsSending = false; long now = System.currentTimeMillis(); universe.calculateBuffer(now); if ((universe.getLastBufferChanged() > lastSend) || refreshAlways) { needsSending = true; repeatCounter = 0; } else if (now - lastSend > 800) { needsSending = true; } else if (repeatCounter < 3) { needsSending = true; repeatCounter++; } if (needsSending) { packetTemplate.setPayload(universe.getBuffer(), universe.getBufferSize()); packetTemplate.setSequence(sequenceNo); DatagramPacket sendPacket = new DatagramPacket(packetTemplate.getRawPacket(), packetTemplate.getPacketLength()); for (IpNode receiverNode : receiverNodes) { sendPacket.setAddress(receiverNode.getAddress()); sendPacket.setPort(receiverNode.getPort()); logger.trace("sending packet with length to {}", packetTemplate.getPacketLength(), receiverNode.toString()); try { socket.send(sendPacket); } catch (IOException e) { <START> logger.debug("Could not send to in {}: ", receiverNode, this.thing.getUID(), e); <END> closeConnection(ThingStatusDetail.COMMUNICATION_ERROR, "could not send DMX data"); } } lastSend = now; sequenceNo = (sequenceNo + 1) % 256; } } else { openConnection(); } }</code><technical_language>this is debug logging provide e.getMessage() instead re-add placeholder</technical_language>

Target:
protected void sendDmxData() { if (this.thing.getStatus().equals(ThingStatus.ONLINE)) { boolean needsSending = false; long now = System.currentTimeMillis(); universe.calculateBuffer(now); if ((universe.getLastBufferChanged() > lastSend) || refreshAlways) { needsSending = true; repeatCounter = 0; } else if (now - lastSend > 800) { needsSending = true; } else if (repeatCounter < 3) { needsSending = true; repeatCounter++; } if (needsSending) { packetTemplate.setPayload(universe.getBuffer(), universe.getBufferSize()); packetTemplate.setSequence(sequenceNo); DatagramPacket sendPacket = new DatagramPacket(packetTemplate.getRawPacket(), packetTemplate.getPacketLength()); for (IpNode receiverNode : receiverNodes) { sendPacket.setAddress(receiverNode.getAddress()); sendPacket.setPort(receiverNode.getPort()); logger.trace("sending packet with length to {}", packetTemplate.getPacketLength(), receiverNode.toString()); try { socket.send(sendPacket); } catch (IOException e) { logger.debug("Could not send to in {}: {}", receiverNode, this.thing.getUID(), e.getMessage()); closeConnection(ThingStatusDetail.COMMUNICATION_ERROR, "could not send DMX data"); } } lastSend = now; sequenceNo = (sequenceNo + 1) % 256; } } else { openConnection(); } }
Source:
<code>private ResponseBody callUrl(String url) throws IOException { try { Request request = new Request.Builder() .url(url) .addHeader("User-Agent", userAgent) .get() .build(); Response response = httpClient.newCall(request).execute(); if (!response.isSuccessful()) { throw new IllegalStateException(format("Status returned by url [%s] is not valid: [%s]", response.request().url(), response.code())); } return response.body(); } catch (Exception e) { <START> logger.error(format("%s server [%s] can not be reached", url.toLowerCase(Locale.getDefault()).contains("sonarcloud") ? "SonarCloud" : "SonarQube", baseUrlWithoutTrailingSlash)); <END> throw e; } }</code><technical_language>constant Locale.EN URL supposed contains localized characters (or care)</technical_language>

Target:
private ResponseBody callUrl(String url) throws IOException { try { Request request = new Request.Builder() .url(url) .addHeader("User-Agent", userAgent) .get() .build(); Response response = httpClient.newCall(request).execute(); if (!response.isSuccessful()) { throw new IllegalStateException(format("Status returned by url [%s] is not valid: [%s]", response.request().url(), response.code())); } return response.body(); } catch (Exception e) { logger.error(format("%s server [%s] can not be reached", url.toLowerCase(Locale.ENGLISH).contains("sonarcloud") ? "SonarCloud" : "SonarQube", baseUrlWithoutTrailingSlash)); throw e; } }
Source:
<code>public void setup() { final OptionalLimit groupLimit = OptionalLimit.empty(); final OptionalLimit seriesLimit = OptionalLimit.empty(); final OptionalLimit aggregationLimit = OptionalLimit.empty(); final OptionalLimit dataLimit = OptionalLimit.empty(); final int fetchParallelism = 20; final boolean failOnLimits = true; final Groups groups = Groups.of("foo"); doReturn(groups).when(metricBackend).groups(); final GroupSet<MetricBackend> groupSet = GroupSet.build(Collections.singletonList(metricBackend), Optional.empty()); <START> QueryLogger queryLogger = mock(QueryLogger.class); <END> QueryLoggerFactory queryLoggerFactory = mock(QueryLoggerFactory.class); when(queryLoggerFactory.create(any())).thenReturn(queryLogger); manager = new LocalMetricManager(groupLimit, seriesLimit, aggregationLimit, dataLimit, fetchParallelism, failOnLimits, async, groupSet, metadata, reporter, queryLoggerFactory); }</code><technical_language>final</technical_language>

Target:
public void setup() { final OptionalLimit groupLimit = OptionalLimit.empty(); final OptionalLimit seriesLimit = OptionalLimit.empty(); final OptionalLimit aggregationLimit = OptionalLimit.empty(); final OptionalLimit dataLimit = OptionalLimit.empty(); final int fetchParallelism = 20; final boolean failOnLimits = true; final Groups groups = Groups.of("foo"); doReturn(groups).when(metricBackend).groups(); final GroupSet<MetricBackend> groupSet = GroupSet.build(Collections.singletonList(metricBackend), Optional.empty()); final QueryLogger queryLogger = mock(QueryLogger.class); final QueryLoggerFactory queryLoggerFactory = mock(QueryLoggerFactory.class); when(queryLoggerFactory.create(any())).thenReturn(queryLogger); manager = new LocalMetricManager(groupLimit, seriesLimit, aggregationLimit, dataLimit, fetchParallelism, failOnLimits, async, groupSet, metadata, reporter, queryLoggerFactory); }
Source:
<code>private TableScanNode tableScan(String id, String... symbols) { List<Symbol> symbolsList = Arrays.stream(symbols).map(Symbol::new).collect(toImmutableList()); ImmutableMap.Builder<Symbol, ColumnHandle> assignments = ImmutableMap.builder(); for (Symbol symbol : symbolsList) { assignments.put(symbol, new TpchColumnHandle("orderkey", BIGINT)); } TpchTableHandle tableHandle = new TpchTableHandle("orders", 1.0); return new TableScanNode( new PlanNodeId(id), new TableHandle( new ConnectorId("tpch"), <START> new TpchTableHandle("orders", 1.0), <END> TestingTransactionHandle.create(), Optional.of(TestingHandle.INSTANCE)), symbolsList, assignments.build(), Optional.of(new TableLayoutHandle(new ConnectorId("tpch"), INSTANCE, new TpchTableLayoutHandle(tableHandle, TupleDomain.all()))), TupleDomain.all(), TupleDomain.all()); }</code><technical_language>nit: tableHandle defined in line 748</technical_language>

Target:
private TableScanNode tableScan(String id, String... symbols) { List<Symbol> symbolsList = Arrays.stream(symbols).map(Symbol::new).collect(toImmutableList()); ImmutableMap.Builder<Symbol, ColumnHandle> assignments = ImmutableMap.builder(); for (Symbol symbol : symbolsList) { assignments.put(symbol, new TpchColumnHandle("orderkey", BIGINT)); } TpchTableHandle tableHandle = new TpchTableHandle("orders", 1.0); return new TableScanNode( new PlanNodeId(id), new TableHandle( new ConnectorId("tpch"), tableHandle, TpchTransactionHandle.INSTANCE, Optional.of(new TpchTableLayoutHandle(tableHandle, TupleDomain.all()))), symbolsList, assignments.build(), TupleDomain.all(), TupleDomain.all()); }
Source:
<code>String[] toColumns(String tableAlias, String path, boolean inSelect, boolean forceAlias) { checkInitialized(); PropertyMapping propertyMapping = getPropertyMapping( path ); if ( !inSelect && queryableCollection != null && CollectionProperties.isCollectionProperty( path ) ) { if ( persister != propertyMapping ) { return getCollectionPropertyReference( path ).toColumns( tableAlias ); } } if ( forceAlias ) { return propertyMapping.toColumns( tableAlias, path ); } if ( fromElement.getWalker().getStatementType() == HqlSqlTokenTypes.SELECT ) { return propertyMapping.toColumns( tableAlias, path ); } if ( fromElement.getWalker().isSubQuery() ) { if ( isCorrelation() ) { if (isMultiTable() && (!isUpdateQuery() || fromElement.getWalker().getCurrentTopLevelClauseType() == HqlSqlTokenTypes.WHERE)) { return propertyMapping.toColumns(tableAlias, path); } <START> else if (isInsertQuery()) { <END> return propertyMapping.toColumns( tableAlias, path ); } return propertyMapping.toColumns( extractTableName(), path ); } return propertyMapping.toColumns( tableAlias, path ); } if ( fromElement.getWalker().getCurrentTopLevelClauseType() == HqlSqlTokenTypes.SELECT ) { return propertyMapping.toColumns( tableAlias, path ); } if ( isManipulationQuery() && isMultiTable() && inWhereClause() ) { return propertyMapping.toColumns( tableAlias, path ); } String[] columns = propertyMapping.toColumns( path ); LOG.tracev( "Using non-qualified column reference [{0} -> ({1})]", path, ArrayHelper.toString( columns ) ); return columns; }</code><technical_language>this check for isMultiTable()</technical_language>

Target:
String[] toColumns(String tableAlias, String path, boolean inSelect, boolean forceAlias) { checkInitialized(); PropertyMapping propertyMapping = getPropertyMapping( path ); if ( !inSelect && queryableCollection != null && CollectionProperties.isCollectionProperty( path ) ) { if ( persister != propertyMapping ) { return getCollectionPropertyReference( path ).toColumns( tableAlias ); } } if ( forceAlias ) { return propertyMapping.toColumns( tableAlias, path ); } if ( fromElement.getWalker().getStatementType() == HqlSqlTokenTypes.SELECT ) { return propertyMapping.toColumns( tableAlias, path ); } if ( fromElement.getWalker().isSubQuery() ) { if ( isCorrelation() ) { if ( isMultiTable() && ( !isUpdateQuery() || inWhereClause() ) ) { return propertyMapping.toColumns( tableAlias, path ); } else if ( isInsertQuery() ) { return propertyMapping.toColumns( tableAlias, path ); } return propertyMapping.toColumns( extractTableName(), path ); } return propertyMapping.toColumns( tableAlias, path ); } if ( fromElement.getWalker().getCurrentTopLevelClauseType() == HqlSqlTokenTypes.SELECT ) { return propertyMapping.toColumns( tableAlias, path ); } if ( isManipulationQuery() && isMultiTable() && inWhereClause() ) { return propertyMapping.toColumns( tableAlias, path ); } String[] columns = propertyMapping.toColumns( path ); LOG.tracev( "Using non-qualified column reference [{0} -> ({1})]", path, ArrayHelper.toString( columns ) ); return columns; }
Source:
<code><START> public boolean DoesEntryExist(final String x, final String y) { <END> try { return threadRunner.submit(new Callable<Boolean>() { @Override public Boolean call() { YailList pair = YailList.makeList(Arrays.asList(x, y)); return chartDataModel.doesEntryExist(pair); } }).get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return false; }</code><technical_language>if I want check a single X caring Y value, if I want if a datapoint for a specific time stamp</technical_language>

Target:
public boolean DoesEntryExist(final String x, final String y) { try { return threadRunner.submit(new Callable<Boolean>() { @Override public Boolean call() { YailList pair = YailList.makeList(Arrays.asList(x, y)); return chartDataModel.doesEntryExist(pair); } }).get(); } catch (InterruptedException e) { Log.e(this.getClass().getName(), e.getMessage()); } catch (ExecutionException e) { Log.e(this.getClass().getName(), e.getMessage()); } return false; }
Source:
<code><START> private void clearCaches() <END> { for (int i = 0; i < this.longs.length; ++i) { this.longs[i] = null; } for (int i = 0; i < this.doubles.length; ++i) { this.doubles[i] = null; } for (int i = 0; i < this.slices.length; ++i) { this.slices[i] = null; } for (int i = 0; i < this.nulls.length; ++i) { this.nulls[i] = null; } }</code><technical_language>Arrays.fill instead for loops</technical_language>

Target:
private void clearCaches() { Arrays.fill(this.longs, null); Arrays.fill(this.doubles, null); Arrays.fill(this.slices, null); Arrays.fill(this.nulls, null); }
Source:
<code>private void createFullHistory(ITmfStateProvider provider, File htFile) throws TmfTraceException { if (htFile.exists()) { final int version = provider.getVersion(); try { <START> fHtBackend = new HistoryTreeBackend(htFile, version); <END> fStateSystem = new StateSystem(fHtBackend, false); return; } catch (IOException e) { } } final int QUEUE_SIZE = 10000; try { fHtBackend = new ThreadedHistoryTreeBackend(htFile, provider.getStartTime(), provider.getVersion(), QUEUE_SIZE); fStateSystem = new StateSystem(fHtBackend); provider.assignTargetStateSystem(fStateSystem); build(provider); } catch (IOException e) { throw new TmfTraceException(e.toString(), e); } }</code><technical_language>countdown latch is decreased waitForInitialization hangs</technical_language>

Target:
private void createFullHistory(ITmfStateProvider provider, File htFile) throws TmfTraceException { if (htFile.exists()) { final int version = provider.getVersion(); try { fHtBackend = new HistoryTreeBackend(htFile, version); fStateSystem = new StateSystem(fHtBackend, false); fInitialized.countDown(); return; } catch (IOException e) { } } final int QUEUE_SIZE = 10000; try { fHtBackend = new ThreadedHistoryTreeBackend(htFile, provider.getStartTime(), provider.getVersion(), QUEUE_SIZE); fStateSystem = new StateSystem(fHtBackend); provider.assignTargetStateSystem(fStateSystem); build(provider); } catch (IOException e) { throw new TmfTraceException(e.toString(), e); } }
Source:
<code>public void visitNode(Tree tree) { StatementTree elseStmt = ((IfStatementTree) tree).elseStatement(); if (elseStmt != null && elseStmt.is(Tree.Kind.IF_STATEMENT) && ((IfStatementTree) elseStmt).elseStatement() == null) { <START> reportIssue(elseStmt, "\"if ... else if\" constructs should end with \"else\" clauses."); <END> } }</code><technical_language>**not** report else statement. is do noise in SonarQube UI, put issue line, while want else if line. Please report else if (the else keyword is a token in parent IfStatementTree, if keyword in child ifStatementTree) Currently, in code for instance, highlight in red 8 lines else! java if (c == '\'') inQuote = true; else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { int ci = from.indexOf(c); if (ci == -1) throw new IllegalArgumentException("Illegal pattern " + " character '" + c + "'"); c = to.charAt(ci); } } ![image](<LINK_0></technical_language>

Target:
public void visitNode(Tree tree) { IfStatementTree treeIfStmt = (IfStatementTree) tree; StatementTree elseStmt = treeIfStmt.elseStatement(); if (elseStmt != null && elseStmt.is(Tree.Kind.IF_STATEMENT)) { IfStatementTree ifStmt = (IfStatementTree) elseStmt; if (ifStmt.elseStatement() == null) { reportIssue(treeIfStmt.elseKeyword(), ifStmt.ifKeyword(), "\"if ... else if\" constructs should end with \"else\" clauses."); } } }
Source:
<code>private void setPosition() { optionalTotalMap.ifPresent(totalMap -> { List<List<Integer>> list = positionProperty.get().stream() .map(totalMap::get) .filter(Objects::nonNull) .collect(Collectors.toList()); int min = list.stream() .mapToInt(x -> x.get(0)) .min().getAsInt() - minRefPosition; int max = list.stream() .mapToInt(x -> x.get(1)) .max().getAsInt(); double scale = locator.getWidth() / maxRefPosition; locatorIndicator.setTranslateX(min * scale); locatorIndicator.setWidth((max - min) * scale); }); <START> if (width != locator.getWidth()) { <END> width = locator.getWidth(); graphController.showMutationsInLocator(); } }</code><technical_language>solved a property. call a function in other controller calls again. need graph controller dependency in this locator yet</technical_language>

Target:
private void setPosition() { optionalTotalMap.ifPresent(totalMap -> { List<List<Integer>> list = positionProperty.get().stream() .map(totalMap::get) .filter(Objects::nonNull) .collect(Collectors.toList()); int min = list.stream() .mapToInt(x -> x.get(0)) .min().getAsInt() - minRefPosition; int max = list.stream() .mapToInt(x -> x.get(1)) .max().getAsInt(); double scale = locator.getWidth() / maxRefPosition; locatorIndicator.setTranslateX(min * scale); locatorIndicator.setWidth((max - min) * scale); }); }
Source:
<code>private List<NetworkCluster> createNetworkAttachments() { List<NetworkCluster> networkAttachments = new ArrayList<>(); <START> getClustersToAttach().stream().forEach(networkClusterModel <END> -> { NetworkCluster networkCluster = new NetworkCluster(); networkCluster.setClusterId(networkClusterModel.getEntity().getId()); networkCluster.setRequired(networkClusterModel.isRequired()); networkAttachments.add(networkCluster); }); return networkAttachments; }</code><technical_language>forEach() is for Arrays, please remove .stream()</technical_language>

Target:
private List<NetworkCluster> createNetworkAttachments() { List<NetworkCluster> networkAttachments = new ArrayList<>(); getClustersToAttach().forEach(networkClusterModel -> { NetworkCluster networkCluster = new NetworkCluster(); networkCluster.setClusterId(networkClusterModel.getEntity().getId()); networkCluster.setRequired(networkClusterModel.isRequired()); networkAttachments.add(networkCluster); }); return networkAttachments; }
Source:
<code>public String getBestTitle(Activity activity) { String bestTitle = null; try { AndroidSessionWrapper asw = CommCareApplication._().getCurrentSessionWrapper(); CommCareSession session = asw.getSession(); String[] stepTitles = session.getHeaderTitles(); Vector<String[]> v = session.getFrame().getSteps(); for(int i = v.size() -1 ; i >= 0; i--){ if(bestTitle != null) { break;} String[] step = v.elementAt(i); <START> if(!SessionFrame.STATE_DATUM_VAL.equals(step[0]) && bestTitle == null) { <END> bestTitle = stepTitles[i]; } } } catch(SessionUnavailableException sue) { } if(bestTitle == null || bestTitle == "") { bestTitle = CommCareActivity.getTopLevelTitleName(activity); } if(bestTitle == null || bestTitle == "") { bestTitle = "CommCare"; } return bestTitle; }</code><technical_language>Confused this condition. this title if current step's is session's datum value? expect opposite</technical_language>

Target:
public String getBestTitle(Activity activity) { String bestTitle = null; try { AndroidSessionWrapper asw = CommCareApplication._().getCurrentSessionWrapper(); CommCareSession session = asw.getSession(); String[] stepTitles = session.getHeaderTitles(); Vector<String[]> v = session.getFrame().getSteps(); for(int i = v.size() -1 ; i >= 0; i--){ if(bestTitle != null) { break;} String[] step = v.elementAt(i); if(!SessionFrame.STATE_DATUM_VAL.equals(step[0]) && bestTitle == null) { bestTitle = stepTitles[i]; } } } catch(SessionUnavailableException sue) { } if(bestTitle == null || "".equals(bestTitle)) { bestTitle = CommCareActivity.getTopLevelTitleName(activity); } if(bestTitle == null || "".equals(bestTitle)) { bestTitle = "CommCare"; } return bestTitle; }
Source:
<code>public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (!isAdded()) { return; } <START> if (getResources().getDisplayMetrics().widthPixels < originalWidth) { <END> rootView.getLayoutParams().width = getDialogWidth(); } }</code><technical_language>Is this conditional necessary? set width unconditionally</technical_language>

Target:
public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); setWindowLayout(); spaceView.getLayoutParams().height = dialogHeightPx(); listView.getLayoutParams().width = dialogWidthPx(); listView.post(new Runnable() { @Override public void run() { setContentPeekHeight(); } }); }
Source:
<code>private String getDurationTime(IRepositoryElement element) { if (element instanceof IRepositoryQuery) { RepositoryQuery query = (RepositoryQuery) element; <START> String duration_min_string = query.getAttribute("duration_min"); END> String duration_max_string = query.getAttribute("duration_max"); String duration_avg_string = query.getAttribute("duration_avg"); String duration_anz_string = query.getAttribute("duration_anz"); String erg = "Min: " + (duration_min_string == null ? "" : duration_min_string) + " Max: " + (duration_max_string == null ? "" : duration_max_string) + " Anz: " + (duration_anz_string == null ? "" : duration_anz_string) + " Avg: " + (duration_avg_string == null ? "" : duration_avg_string); return erg; } return null; }</code><technical_language>I if sense show for queries run longer others. hide info, display a warning if detect average query exceeds a threshold e.g. 1/3 of sync interval</technical_language>

Target:
private String getDurationTime(IRepositoryElement element) { if (element instanceof IRepositoryQuery) { RepositoryQuery query = (RepositoryQuery) element; long duration_max = parseLongFromString(query.getAttribute("duration_max")); if (duration_max > 2 * 60 * 1000) { long duration_min = parseLongFromString(query.getAttribute("duration_min")); long duration_avg = parseLongFromString(query.getAttribute("duration_avg")); long duration_anz = parseLongFromString(query.getAttribute("duration_anz")); String erg = "Min: " + (duration_min == 0 ? "" : "" + duration_min / 1000 + "s") + " Max: " + (duration_max == 0 ? "" : "" + duration_max / 1000 + "s") + " Anz: " + (duration_anz == 0 ? "" : "" + duration_anz) + " Avg: " + (duration_avg == 0 ? "" : "" + duration_avg / 1000 + "s"); return erg; } } return null; }
Source:
<code><START> protected void checkStarted() throws StoreException { <END> if (!started) { throw new StoreException("Store not started", StoreErrorCodes.Store_Not_Started); } }</code><technical_language>is this necessary</technical_language>

Target:
private void checkStarted() throws StoreException { if (!started) { throw new StoreException("Store not started", StoreErrorCodes.Store_Not_Started); } }