auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public TimestampedValue<V> fromBytes(byte[] bytes) { ByteBuffer bb = ByteBuffer.wrap(bytes); <START> byte[] vBytes = new byte[bytes.length - 8 ]; <END> bb.get(vBytes, 0, vBytes.length); V v = vSerde.fromBytes(vBytes); long ts = bb.getLong(); return new TimestampedValue<>(v, ts); }</code><technical_language>Minor: a constant TIMESTAMP_LEN instead of 8</technical_language>

Target:
public TimestampedValue<V> fromBytes(byte[] bytes) { ByteBuffer bb = ByteBuffer.wrap(bytes); byte[] vBytes = new byte[bytes.length - TIMESTAMP_BYTES]; bb.get(vBytes, 0, vBytes.length); V v = vSerde.fromBytes(vBytes); long ts = bb.getLong(); return new TimestampedValue<>(v, ts); }
Source:
<code>public synchronized void modified(Map<String, Object> config) { String primaryAddressConf = (String) config.get(PRIMARY_ADDRESS); try { primaryAddress = new CidrAddress(primaryAddressConf); <START> } catch (IllegalArgumentException e) { <END> } }</code><technical_language>sense log a warning? I mean, in end user accidentally a mistake/typo, service silently "accepts" this configuration work expected. I miss anything</technical_language>

Target:
public synchronized void modified(Map<String, Object> config) { final @Nullable String primaryAddressConf = (String) config.get(PRIMARY_ADDRESS); if (primaryAddressConf != null) { try { primaryAddress = new CidrAddress(primaryAddressConf); } catch (IllegalArgumentException e) { LOGGER.warn("Primary address configuration value invalid", e); } } }
Source:
<code>protected List<MethodMatcher> getMethodInvocationMatchers() { <START> return ImmutableList.of( <END> MethodMatcher.create().typeDefinition("javax.crypto.spec.IvParameterSpec").name("<init>").withAnyParameters()); }</code><technical_language>Collections.singletonList() avoid adding a dependency guava</technical_language>

Target:
protected List<MethodMatcher> getMethodInvocationMatchers() { return Collections.singletonList( MethodMatcher.create().typeDefinition("javax.crypto.spec.IvParameterSpec").name("<init>").withAnyParameters()); }
Source:
<code>protected void register() { <START> Composite plotArea = (Composite) getChart().getPlotArea(); <END> if (this instanceof MouseListener) { plotArea.addMouseListener((MouseListener) this); } if (this instanceof MouseMoveListener) { plotArea.addMouseMoveListener((MouseMoveListener) this); } if (this instanceof MouseWheelListener) { plotArea.addMouseWheelListener((MouseWheelListener) this); } if (this instanceof MouseTrackListener) { plotArea.addMouseTrackListener((MouseTrackListener) this); } if (this instanceof PaintListener) { plotArea.addPaintListener((PaintListener) this); } if (this instanceof ICustomPaintListener) { ((IPlotArea) plotArea).addCustomPaintListener((ICustomPaintListener) this); } TmfAbstractToolTipHandler tooltipHandler = getTooltipHandler(); if(tooltipHandler != null) { tooltipHandler.activateHoverHelp(plotArea); } }</code><technical_language>IPlotArea plotArea = getChart().getPlotArea(); Control control = plotArea.getControl();</technical_language>

Target:
protected void register() { IPlotArea plotArea = getChart().getPlotArea(); Control control = plotArea.getControl(); if (this instanceof MouseListener) { control.addMouseListener((MouseListener) this); } if (this instanceof MouseMoveListener) { control.addMouseMoveListener((MouseMoveListener) this); } if (this instanceof MouseWheelListener) { control.addMouseWheelListener((MouseWheelListener) this); } if (this instanceof MouseTrackListener) { control.addMouseTrackListener((MouseTrackListener) this); } if (this instanceof PaintListener) { control.addPaintListener((PaintListener) this); } if (this instanceof ICustomPaintListener) { plotArea.addCustomPaintListener((ICustomPaintListener) this); } TmfAbstractToolTipHandler tooltipHandler = getTooltipHandler(); if(tooltipHandler != null) { tooltipHandler.activateHoverHelp(control); } }
Source:
<code><START> public void addConfiguration(File configFile) throws ConfigException { <END> { LOG.info("Reading configuration from: {}", configFile.getAbsolutePath()); try { configFile = (new VerifyingFileFactory.Builder(LOG).warnForRelativePath().failForNonExistingPath() .build()).validate(configFile); Properties cfg = new Properties(); FileInputStream in = new FileInputStream(configFile); try { cfg.load(in); } finally { in.close(); } parseProperties(cfg); } catch (IOException | IllegalArgumentException e) { LOG.error("Error while configuration from: {}", configFile.getAbsolutePath(), e); throw new ConfigException("Error while processing " + configFile.getAbsolutePath(), e); } } }</code><technical_language>This method is adding properties top of existing ones, if any. wondering if need of loading propertied a file scratch, dropping previous properties</technical_language>

Target:
public void addConfiguration(File configFile) throws ConfigException { LOG.info("Reading configuration from: {}", configFile.getAbsolutePath()); try { configFile = (new VerifyingFileFactory.Builder(LOG).warnForRelativePath().failForNonExistingPath().build()) .validate(configFile); Properties cfg = new Properties(); FileInputStream in = new FileInputStream(configFile); try { cfg.load(in); } finally { in.close(); } parseProperties(cfg); } catch (IOException | IllegalArgumentException e) { LOG.error("Error while configuration from: {}", configFile.getAbsolutePath(), e); throw new ConfigException("Error while processing " + configFile.getAbsolutePath(), e); } }
Source:
<code>public static String conjoinSolrQueries(String q1, String q2){ <START> if(q1.isEmpty()){ return q2; } <END> if(q2.isEmpty()){ return q1; } return q1 + " AND " + q2 ; }</code><technical_language>is q1 == null? StringUtils.isEmpty care of cases</technical_language>

Target:
public static String conjoinSolrQueries(String q1, String q2){ if(StringUtils.isEmpty(q1)){ return q2; } if(StringUtils.isEmpty(q2)){ return q1; } return q1 + " AND " + q2 ; }
Source:
<code>private void copyTemplatePermissions() { <START> if (!getParameters().isCopyTemplatePermissions()) { <END> return; } PermissionDAO dao = getDbFacade().getPermissionDao(); List<permissions> templatePermissions = dao.getAllForEntity(getVmTemplateId(), getCurrentUser().getUserId(), false); List<permissions> vmPermissions = new ArrayList<permissions>(); for (permissions templatePermission : templatePermissions) { boolean templateOwnerRole = templatePermission.getrole_id().equals(PredefinedRoles.TEMPLATE_OWNER.getId()); boolean templateUserRole = templatePermission.getrole_id().equals(PredefinedRoles.TEMPLATE_USER.getId()); if (templateOwnerRole || templateUserRole) { continue; } vmPermissions.add(new permissions(getCurrentUser().getUserId(), templatePermission.getrole_id(), getVmId(), VdcObjectType.VM)); } if (vmPermissions.size() > 0) { MultiLevelAdministrationHandler.addPermission(vmPermissions.toArray(new permissions[vmPermissions.size()])); } }</code><technical_language>caller check for parameter, redundant (unless i missed something)</technical_language>

Target:
private void copyTemplatePermissions() { PermissionDAO dao = getDbFacade().getPermissionDao(); List<permissions> templatePermissions = dao.getAllForEntity(getVmTemplateId(), getCurrentUser().getUserId(), false); List<permissions> vmPermissions = new ArrayList<permissions>(); for (permissions templatePermission : templatePermissions) { boolean templateOwnerRole = templatePermission.getrole_id().equals(PredefinedRoles.TEMPLATE_OWNER.getId()); boolean templateUserRole = templatePermission.getrole_id().equals(PredefinedRoles.TEMPLATE_USER.getId()); if (templateOwnerRole || templateUserRole) { continue; } vmPermissions.add(new permissions(getCurrentUser().getUserId(), templatePermission.getrole_id(), getVmId(), VdcObjectType.VM)); } if (vmPermissions.size() > 0) { MultiLevelAdministrationHandler.addPermission(vmPermissions.toArray(new permissions[vmPermissions.size()])); } }
Source:
<code>public void diagnostic(String expression, Diagnostic diagnostic) { final String ls = System.getProperty("line.separator"); StringBuilder messageToLog = new StringBuilder(); if <START> (diagnostic.getMessage() != null && diagnostic.getMessage().trim().length() > 0) { <END> messageToLog.append(diagnostic.getMessage()); messageToLog.append(ls); } List<Diagnostic> children = diagnostic.getChildren(); for (Diagnostic childDiagnostic : children) { if (childDiagnostic.getMessage() != null && childDiagnostic.getMessage().trim().length() > 0) { messageToLog.append(childDiagnostic.getMessage()); messageToLog.append(ls); } } String message = MessageFormat.format(Messages.AbstractEEFEclipsePlugin_InvalidEvaluation, expression, messageToLog); IStatus status = new Status(diagnostic.getSeverity(), this.bundleSymbolicName, message); this.getLog().log(status); }</code><technical_language>moving Util.isBlank eef.common it</technical_language>

Target:
public void diagnostic(String expression, Diagnostic diagnostic) { final String ls = System.getProperty("line.separator"); StringBuilder messageToLog = new StringBuilder(); if (!Util.isBlank(diagnostic.getMessage())) { messageToLog.append(diagnostic.getMessage()); messageToLog.append(ls); } List<Diagnostic> children = diagnostic.getChildren(); for (Diagnostic childDiagnostic : children) { if (!Util.isBlank(childDiagnostic.getMessage())) { messageToLog.append(childDiagnostic.getMessage()); messageToLog.append(ls); } } String message = MessageFormat.format(Messages.AbstractEEFEclipsePlugin_InvalidEvaluation, expression, messageToLog); IStatus status = new Status(diagnostic.getSeverity(), this.bundleSymbolicName, message); this.getLog().log(status); }
Source:
<code>public void renderState(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setHeader("pragma", "no-cache"); res.setHeader("Cache-Control", "no-cache, max-age=0, must-revalidate"); res.setDateHeader("Expires", 0); final long startTime = System.nanoTime(); final PipelineEventReader<CharacterEventReader, CharacterEvent> pipelineEventReader = this.pipeline.getEventReader(req, res); final String contentType = "application/json; charset=" + CHARACTER_SET; res.setContentType(contentType); final PrintWriter writer = res.getWriter(); if (pipelineEventReader != null) { for (final CharacterEvent event : pipelineEventReader) { if (CharacterEventTypes.CHARACTER != event.getEventType()) { throw new RenderingPipelineConfigurationException( "Only " + CharacterEventTypes.CHARACTER + " events are supported in the top level renderer. " + event.getEventType() + " is not supported."); } final String data = ((CharacterDataEvent) event).getData(); writer.print(data); writer.flush(); res.flushBuffer(); <START> } <END> } final long executionTime = System.nanoTime() - startTime; final IPortalRequestInfo portalRequestInfo = this.urlSyntaxProvider.getPortalRequestInfo(req); this.portalEventFactory.publishPortalRenderEvent( req, this, req.getPathInfo(), executionTime, portalRequestInfo); }</code><technical_language>a design perspective, a pipelineEventReader? If so, throwing IllegalStateException in order, returning null? Suggest warn in logs</technical_language>

Target:
public void renderState(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, IllegalStateException { res.setHeader("pragma", "no-cache"); res.setHeader("Cache-Control", "no-cache, max-age=0, must-revalidate"); res.setDateHeader("Expires", 0); final long startTime = System.nanoTime(); final PipelineEventReader<CharacterEventReader, CharacterEvent> pipelineEventReader = this.pipeline.getEventReader(req, res); final String contentType = "application/json; charset=" + CHARACTER_SET; res.setContentType(contentType); final PrintWriter writer = res.getWriter(); if (pipelineEventReader != null) { for (final CharacterEvent event : pipelineEventReader) { if (CharacterEventTypes.CHARACTER != event.getEventType()) { throw new RenderingPipelineConfigurationException( "Only " + CharacterEventTypes.CHARACTER + " events are supported in the top level renderer. " + event.getEventType() + " is not supported."); } final String data = ((CharacterDataEvent) event).getData(); writer.print(data); writer.flush(); res.flushBuffer(); } } else { logger.warn("PipelineEventReader is null"); throw new IllegalStateException("PipelineEventReader is null"); } final long executionTime = System.nanoTime() - startTime; final IPortalRequestInfo portalRequestInfo = this.urlSyntaxProvider.getPortalRequestInfo(req); this.portalEventFactory.publishPortalRenderEvent( req, this, req.getPathInfo(), executionTime, portalRequestInfo); }
Source:
<code>private void setBatteryLevel(int newBatteryLevel, View source) { mBatteryLevelCharacteristic.setValue(newBatteryLevel, BluetoothGattCharacteristic.FORMAT_UINT8, 0); if (source instanceof TextView) { <START> mBatteryLevelSeekBar.setProgress(newBatteryLevel); <END> } else if (source instanceof SeekBar) { mBatteryLevelEditText.setText(Integer.toString(newBatteryLevel)); } else { mBatteryLevelSeekBar.setProgress(newBatteryLevel); mBatteryLevelEditText.setText(Integer.toString(newBatteryLevel)); } }</code><technical_language>Maybe: java if (source != mBatteryLevelSeekBar) { mBatteryLevelSeekBar.setProgress(newBatteryLevel); } if (source != mBatteryLevelEditText) { mBatteryLevelEditText.setText(Integer.toString(newBatteryLevel)); }</technical_language>

Target:
private void setBatteryLevel(int newBatteryLevel, View source) { mBatteryLevelCharacteristic.setValue(newBatteryLevel, BluetoothGattCharacteristic.FORMAT_UINT8, 0); if (source != mBatteryLevelSeekBar) { mBatteryLevelSeekBar.setProgress(newBatteryLevel); } if (source != mBatteryLevelEditText) { mBatteryLevelEditText.setText(Integer.toString(newBatteryLevel)); } }
Source:
<code>protected int run() throws Exception { Jenkins jenkins = Jenkins.get(); final HashSet<String> names = new HashSet<>(); names.addAll(jobNames); final StringBuilder resultBuilder = new StringBuilder(); for (final String jobName : names) { Item item = jenkins.getItemByFullName(jobName); if (item instanceof Job) { stopJobBuilds((Job) item, jobName, resultBuilder); } else if (item != null) { <START> resultBuilder.append(String.format("Cannot abort runs for %s. Unsupported job type: %s\n", item, item.getClass())); <END> } else { resultBuilder.append(String.format("Job with name %s not found.\n", jobName)); } } stdout.print(resultBuilder.toString()); return 0; }</code><technical_language>I suggest checking arguments first, collecting a List<Job> process, throwing IllegalArgumentException if argument is encountered is a valid Job</technical_language>

Target:
protected int run() throws Exception { Jenkins jenkins = Jenkins.get(); final HashSet<String> names = new HashSet<>(); names.addAll(jobNames); final List<Job> jobsToStop = new ArrayList<>(); for (final String jobName : names) { Item item = jenkins.getItemByFullName(jobName); if (item instanceof Job) { jobsToStop.add((Job) item); } else { throw new IllegalArgumentException("Job not found: '" + jobName + "'"); } } for (final Job job : jobsToStop) { stopJobBuilds(job); } if (!isAnyBuildStopped) { stdout.println("No builds stopped"); } return 0; }
Source:
<code>public void onFailure(WorkflowExecutionContext context) throws FalconException { if (context.isWorkflowKilledManually()) { <START> LOG.debug("User workflow: killed manually of instance: belongs to entity: {}, so retry won't happen ", <END> context.getWorkflowId(), context.getNominalTimeAsISO8601(), context.getEntityName()); return; } else if (context.hasWorkflowTimedOut()) { Entity entity = EntityUtil.getEntity(context.getEntityType(), context.getEntityName()); Retry retry = getRetry(entity); if (!retry.isOnTimeout()) { return; } } handleRerun(context.getClusterName(), context.getEntityType(), context.getEntityName(), context.getNominalTimeAsISO8601(), context.getWorkflowRunIdString(), context.getWorkflowId(), context.getWorkflowParentId(), context.getWorkflowUser(), context.getExecutionCompletionTime()); }</code><technical_language>Minor phrasing of message. rephrase "Workflow {}; Instance {}; Entity {}, killed manually user. retry."</technical_language>

Target:
public void onFailure(WorkflowExecutionContext context) throws FalconException { if (context.isWorkflowKilledManually()) { LOG.debug("Workflow: Instance: Entity: {}, killed manually by user. Will not retry.", context.getWorkflowId(), context.getNominalTimeAsISO8601(), context.getEntityName()); return; } else if (context.hasWorkflowTimedOut()) { Entity entity = EntityUtil.getEntity(context.getEntityType(), context.getEntityName()); Retry retry = getRetry(entity); if (!retry.isOnTimeout()) { return; } } handleRerun(context.getClusterName(), context.getEntityType(), context.getEntityName(), context.getNominalTimeAsISO8601(), context.getWorkflowRunIdString(), context.getWorkflowId(), context.getWorkflowParentId(), context.getWorkflowUser(), context.getExecutionCompletionTime()); }
Source:
<code>private void exitLocked() { final ConnectivityManager cm = ConnectivityManager.from(mContext); cm.unregisterNetworkCallback(mNetworkCallback); agentDisconnect(); resetIkeStateLocked(); mActiveNetwork = null; <START> updateState(DetailedState.DISCONNECTED, "Platform VPN exit"); <END> }</code><technical_language>agentDisconnect sets this state</technical_language>

Target:
private void exitLocked() { final ConnectivityManager cm = ConnectivityManager.from(mContext); cm.unregisterNetworkCallback(mNetworkCallback); agentDisconnect(); resetIkeStateLocked(); mActiveNetwork = null; }
Source:
<code>private void addFailureCauseRepresentation(final StringBuilder stringBuilder, final IndicationUrlBuilder indicationUrlBuilder, final FoundFailureCause cause, final int indentLevel) { final int nextIndentLevel = indentLevel + LIST_INCREMENT; if (useHtmlFormat) { stringBuilder.append("<li>"); stringBuilder.append(cause.getName()); stringBuilder.append(": "); <START> stringBuilder.append(cause.getDescription()); <END> if (includeIndications) { addIndicationsRepresentation(stringBuilder, indicationUrlBuilder, cause.getIndications(), nextIndentLevel); } stringBuilder.append("</li>"); } else { stringBuilder.append(indentForDepth(indentLevel)); stringBuilder.append("* "); stringBuilder.append(cause.getName()); stringBuilder.append(": "); stringBuilder.append(cause.getDescription()); stringBuilder.append("\n"); if (includeIndications) { addIndicationsRepresentation(stringBuilder, indicationUrlBuilder, cause.getIndications(), nextIndentLevel); } } }</code><technical_language>description multiline, get a bit "ugly" formatted. put description a new line</technical_language>

Target:
private void addFailureCauseRepresentation(final StringBuilder stringBuilder, final IndicationUrlBuilder indicationUrlBuilder, final FoundFailureCause cause, final int indentLevel) { final int nextIndentLevel = indentLevel + LIST_INCREMENT; if (useHtmlFormat) { stringBuilder.append("<li>"); try { stringBuilder.append(Jenkins.getInstance().getMarkupFormatter().translate(cause.getName())); } catch (final IOException exception) { stringBuilder.append("cause-name"); } stringBuilder.append(": "); try { stringBuilder.append(Jenkins.getInstance().getMarkupFormatter().translate(cause.getDescription())); } catch (final IOException exception) { stringBuilder.append("cause-description"); } if (includeIndications) { addIndicationsRepresentation(stringBuilder, indicationUrlBuilder, cause.getIndications(), nextIndentLevel); } stringBuilder.append("</li>"); } else { final List<String> lines = wrap( cause.getName() + ": " + cause.getDescription(), wrapWidth - indentForDepth(indentLevel).length() - LIST_BULLET.length()); for (int lineIndex = 0, lineCount = lines.size(); lineIndex < lineCount; ++lineIndex) { if (lineIndex == 0) { stringBuilder.append(LIST_BULLET); } else { stringBuilder.append(LIST_BULLET_SPACE); } stringBuilder.append(lines.get(lineIndex)); stringBuilder.append("\n"); } if (includeIndications) { addIndicationsRepresentation(stringBuilder, indicationUrlBuilder, cause.getIndications(), nextIndentLevel); } } }
Source:
<code>private void unlockEntities() { getSnapshotDao().updateStatus(sourceSnapshotId, SnapshotStatus.OK); getVmDynamicDao().updateStatus(getVmId(), VMStatus.Down); <START> freeLock(); <END> }</code><technical_language>This</technical_language>

Target:
private void unlockEntities() { getSnapshotDao().updateStatus(sourceSnapshotId, SnapshotStatus.OK); getVmDynamicDao().updateStatus(getVmId(), VMStatus.Down); }
Source:
<code>private boolean isChangeRecent(Change change) { if <START> (revisionCutoff == <END> 0) { return false; } return change.timestamp() != null && change.timestamp().isAfter(Instant.now().minus(revisionCutoff, ChronoUnit.HOURS)); }</code><technical_language>Instead of 0 a guard, Integer.MAX_VALUE remove this condition completely</technical_language>

Target:
private boolean isChangeRecent(Change change) { if (revisionCutoff == null || revisionCutoff.isZero()) { return false; } return change.timestamp() != null && change.timestamp().isAfter(Instant.now().minus(revisionCutoff)); }
Source:
<code>@Override public void clear() { try { lockWriteLocks(); replaceOldSegments(); } finally { <START> unlockWriteLocks(); <END> } }</code><technical_language>If exception thrown lock acquire try unlock locks acquired</technical_language>

Target:
@Override public void clear() { for (Segment<K, V> segment : segments) segment.writeLock().lock(); try { for (int i = 0; i < segments.length; i++) segments[i] = new Segment<>(segmentInitCap, loadFactor); modCnt.increment(); } finally { for (Segment<K, V> segment : segments) segment.writeLock().unlock(); } }
Source:
<code>public void testDateExtendingFact() { <START> <END> final Resource resource = KieServices.Factory.get().getResources().newReaderResource(new StringReader(DRL)); resource.setTargetPath(TestConstants.DRL_TEST_TARGET_PATH); final KieBuilder kbuilder = KieBaseUtil.getKieBuilderFromResources(true, resource); }</code><technical_language>Useless empty line</technical_language>

Target:
public void testDateExtendingFact() { final Resource resource = KieServices.Factory.get().getResources().newReaderResource(new StringReader(DRL)); resource.setTargetPath(TestConstants.DRL_TEST_TARGET_PATH); final KieBuilder kbuilder = KieBaseUtil.getKieBuilderFromResources(true, resource); Assertions.assertThat(kbuilder.getResults().getMessages(Message.Level.ERROR)).isEmpty(); }
Source:
<code>private void invalidateDisposedFlowFromCaches(String flowName) { sourcePolicyOuterCache.asMap().keySet().stream() .filter(pair -> pair.getFirst().equals(flowName)) .forEach(matchingPair -> sourcePolicyOuterCache.invalidate(matchingPair)); sourcePolicyInnerCache.asMap().keySet().stream() .filter(pair -> pair.getFirst().equals(flowName)) .forEach(matchingPair -> sourcePolicyInnerCache.invalidate(matchingPair)); <START> noPolicySourceInstances.asMap().keySet().stream() <END> .filter(key -> key.equals(flowName)) .forEach(matchingPair -> noPolicySourceInstances.invalidate(matchingPair)); }</code><technical_language>invalidate(key) for this instead of asMap rest of stuff</technical_language>

Target:
private void invalidateDisposedFlowFromCaches(String flowName) { noPolicySourceInstances.invalidate(flowName); sourcePolicyOuterCache.asMap().keySet().stream() .filter(pair -> pair.getFirst().equals(flowName)) .forEach(matchingPair -> sourcePolicyOuterCache.invalidate(matchingPair)); sourcePolicyInnerCache.asMap().keySet().stream() .filter(pair -> pair.getFirst().equals(flowName)) .forEach(matchingPair -> sourcePolicyInnerCache.invalidate(matchingPair)); }
Source:
<code>public void setLength(int length) { <START> if (offset + length > buffer.length) <END> { throw new IllegalArgumentException("length"); } this.length = length; }</code><technical_language>do care check length positive here</technical_language>

Target:
public void setLength(int length) { if (offset + length > buffer.length || length < 0) { throw new IllegalArgumentException("length"); } this.length = length; }
Source:
<code>public Value evaluate(DataSourceFactory dsf, Value... values) throws FunctionException { if (gpr == null) { final int nbDec = values[1].getAsInt(); if (nbDec < 0) { throw new FunctionException("Decimal_places has to be >= 0."); } PrecisionModel pm = new PrecisionModel(scaleFactorForDecimalPlaces(nbDec)); gpr = new GeometryPrecisionReducer(pm); } Geometry geom = gpr.reduce(values[0].getAsGeometry()); <START> return ValueFactory.createValue(geom, values[0].getCRS()); <END> }</code><technical_language>need for a local reference here. combine lines following: java return ValueFactory.createValue(gpr.reduce(values[0].getAsGeometry()), values[0].getCRS()); a big deal though</technical_language>

Target:
public Value evaluate(DataSourceFactory dsf, Value... values) throws FunctionException { if (gpr == null) { final int nbDec = values[1].getAsInt(); if (nbDec < 0) { throw new FunctionException("Decimal_places has to be >= 0."); } PrecisionModel pm = new PrecisionModel(scaleFactorForDecimalPlaces(nbDec)); gpr = new GeometryPrecisionReducer(pm); } return ValueFactory.createValue(gpr.reduce(values[0].getAsGeometry()), values[0].getCRS()); }
Source:
<code>public void delete(String id) { <START> CuratorFramework client = zkConnection.getClient(); <END> String path = Paths.build(Paths.CONTAINERS, id); try { client.delete().forPath(path); } catch (Exception e) { ZooKeeperUtils.wrapAndThrowIgnoring(e, KeeperException.NoNodeException.class); } }</code><technical_language>I calling this explicitly. removal of Paths.build(Paths.CONTAINERS, id) happen ephemeral node removal</technical_language>

Target:
public void delete(String id) { }
Source:
<code>private void validateDataset(final Integer studyId, final DatasetDTO dataSet, final Boolean shouldBeSubobservationDataset) { if (dataSet == null) { this.errors.reject("dataset.does.not.exist", ""); throw new ResourceNotFoundException(this.errors.getAllErrors().get(0)); } this.validateDatasetBelongsToStudy(studyId, dataSet.getDatasetId()); final DatasetType datasetType = this.datasetTypeService.getDatasetTypeById(dataSet.getDatasetTypeId()); <START> if (shouldBeSubobservationDataset && !DatasetTypeEnum.isSubObservationType(datasetType.getDatasetTypeId())) { <END> this.errors.reject("dataset.type.not.subobservation", ""); throw new NotSupportedException(this.errors.getAllErrors().get(0)); } }</code><technical_language>datasetType able answer this question</technical_language>

Target:
private void validateDataset(final Integer studyId, final DatasetDTO dataSet, final Boolean shouldBeSubobservationDataset) { if (dataSet == null) { this.errors.reject("dataset.does.not.exist", ""); throw new ResourceNotFoundException(this.errors.getAllErrors().get(0)); } this.validateDatasetBelongsToStudy(studyId, dataSet.getDatasetId()); final DatasetTypeDTO datasetType = this.datasetTypeService.getDatasetTypeById(dataSet.getDatasetTypeId()); if (shouldBeSubobservationDataset && !datasetType.isSubObservationType()) { this.errors.reject("dataset.type.not.subobservation", ""); throw new NotSupportedException(this.errors.getAllErrors().get(0)); } }
Source:
<code>private void updateTaggedMemoryAllocations(QueryId queryId, String allocationTag, long delta, boolean putQueryIdIfAbsent) { if (delta == 0) { return; } <START> if (!putQueryIdIfAbsent && !taggedMemoryAllocations.containsKey(queryId)) { <END> return; } Map<String, Long> allocations = taggedMemoryAllocations.computeIfAbsent(queryId, ignored -> new ConcurrentHashMap<>()); allocations.compute(allocationTag, (ignored, oldValue) -> { if (oldValue == null) { return delta; } long newValue = oldValue.longValue() + delta; if (newValue == 0) { return null; } return newValue; }); }</code><technical_language>call containsKey, switch merge computeIfPresent. Avoids repeating map lookup</technical_language>

Target:
private void updateTaggedMemoryAllocations(QueryId queryId, String allocationTag, long delta, boolean putQueryIdIfAbsent) { if (delta == 0) { return; } Map<String, Long> allocations; if (putQueryIdIfAbsent) { allocations = taggedMemoryAllocations.computeIfAbsent(queryId, ignored -> new ConcurrentHashMap<>()); } else { allocations = taggedMemoryAllocations.get(queryId); if (allocations == null) { return; } } allocations.compute(allocationTag, (ignored, oldValue) -> { if (oldValue == null) { return delta; } long newValue = oldValue.longValue() + delta; if (newValue == 0) { return null; } return newValue; }); }
Source:
<code>public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof MediaUnit)) { return false; } MediaUnit other = (MediaUnit) obj; if (mediaFiles == null) { if (other.mediaFiles != null) { return false; } } else if (!mediaFiles.equals(other.mediaFiles)) { return false; } if (order != other.order) { return false; } if (orderlabel == null) { if (other.orderlabel != null) { return false; } } else if (!orderlabel.equals(other.orderlabel)) { return false; } <START> if (type == null) { <END> if (other.type != null) { return false; } } else if (!type.equals(other.type)) { return false; } return true; }</code><technical_language>decided Objects.isNull</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof MediaUnit)) { return false; } MediaUnit other = (MediaUnit) obj; if (mediaFiles == null) { if (other.mediaFiles != null) { return false; } } else if (!mediaFiles.equals(other.mediaFiles)) { return false; } if (order != other.order) { return false; } if (orderlabel == null) { if (other.orderlabel != null) { return false; } } else if (!orderlabel.equals(other.orderlabel)) { return false; } if (Objects.isNull(type)) { if (Objects.nonNull(other.type)) { return false; } } else if (!type.equals(other.type)) { return false; } return true; }
Source:
<code>public void testReadAheadManagerForOlderReadAheadFailure() throws Exception { AbfsClient client = getMockAbfsClient(); AbfsRestOperation successOp = getMockRestOp(); doThrow(new TimeoutException("Internal Server error for RAH-X")) .doThrow(new TimeoutException("Internal Server error for RAH-X")) .doThrow(new TimeoutException("Internal Server error for RAH-X")) .doReturn(successOp) .doReturn(successOp) .when(client) .read(any(String.class), any(Long.class), any(byte[].class), any(Integer.class), any(Integer.class), any(String.class)); AbfsInputStream inputStream = getAbfsInputStream(client, "testReadAheadManagerForOlderReadAheadFailure.txt"); queueReadAheads(inputStream); Thread.sleep(ReadBufferManager.getBufferManager().getThresholdAgeMilliseconds()); verifyReadCallCount(client, 3); int bytesRead = ReadBufferManager.getBufferManager().getBlock( inputStream, 1 * KILOBYTE, 1 * KILOBYTE, new byte[1 * KILOBYTE]); <START> Assert.assertTrue("bytesRead should be zero when previously read " <END> + "ahead buffer had failed", bytesRead == 0); checkEvictedStatus(inputStream, 0, false); }</code><technical_language>assertEquals for equality checks</technical_language>

Target:
public void testReadAheadManagerForOlderReadAheadFailure() throws Exception { AbfsClient client = getMockAbfsClient(); AbfsRestOperation successOp = getMockRestOp(); doThrow(new TimeoutException("Internal Server error for RAH-X")) .doThrow(new TimeoutException("Internal Server error for RAH-X")) .doThrow(new TimeoutException("Internal Server error for RAH-X")) .doReturn(successOp) .doReturn(successOp) .when(client) .read(any(String.class), any(Long.class), any(byte[].class), any(Integer.class), any(Integer.class), any(String.class), any(String.class)); AbfsInputStream inputStream = getAbfsInputStream(client, "testReadAheadManagerForOlderReadAheadFailure.txt"); queueReadAheads(inputStream); Thread.sleep(ReadBufferManager.getBufferManager().getThresholdAgeMilliseconds()); verifyReadCallCount(client, 3); int bytesRead = ReadBufferManager.getBufferManager().getBlock( inputStream, ONE_KB, ONE_KB, new byte[ONE_KB]); Assert.assertEquals("bytesRead should be zero when previously read " + "ahead buffer had failed", 0, bytesRead); checkEvictedStatus(inputStream, 0, false); }
Source:
<code>public static TimeZone getTimeZone() { if (System.getProperty("testng.timezone", "").trim().isEmpty()) { return TimeZone.getDefault(); } <START> return TimeZone.getTimeZone(System.getProperty("testng.timezone")); <END> }</code><technical_language>extract System.getProperty("testng.timezone", "") in a variable avoid repetition</technical_language>

Target:
public static TimeZone getTimeZone() { String timeZone = System.getProperty("testng.timezone", ""); if (timeZone.trim().isEmpty()) { return TimeZone.getDefault(); } return TimeZone.getTimeZone(timeZone); }
Source:
<code>private File createInputFile(final String extension) throws IOException { final File input = new File(outputDir, "input" + extension); final SAMFileWriterFactory samFileWriterFactory = new SAMFileWriterFactory(); final SAMFileWriter writer; <START> if(extension.equals(".cram")) { <END> final Path fasta = IOUtil.getPath("Testinput.fasta"); IOUtil.deleteOnExit(fasta); IOUtil.deleteOnExit(ReferenceSequenceFileFactory.getFastaIndexFileName(fasta)); IOUtil.deleteOnExit(ReferenceSequenceFileFactory.getDefaultDictionaryForReferenceSequence(fasta)); samRecordSetBuilder.writeRandomReference(fasta); writer = samFileWriterFactory.makeWriter(samRecordSetBuilder.getHeader(), true, input, fasta.toFile()); } else { writer = samFileWriterFactory.makeWriter(samRecordSetBuilder.getHeader(), true, input, null); } samRecordSetBuilder.getRecords().forEach(writer::addAlignment); writer.close(); return input; }</code><technical_language>suggestion if (extension.equals(".cram")) {</technical_language>

Target:
private File createInputFile(final String extension) throws IOException { final File input = new File(outputDir, "input" + extension); final SAMFileWriterFactory samFileWriterFactory = new SAMFileWriterFactory(); final SAMFileWriter writer; if (extension.equals(".cram")) { final Path fasta = fastaFiles.computeIfAbsent(samRecordSetBuilder.getHeader(), h -> { final Path fastaDir = IOUtil.createTempDir("SamFileTester", "").toPath(); IOUtil.deleteOnExit(fastaDir); final Path newFasta = fastaDir.resolve("input.fasta"); IOUtil.deleteOnExit(newFasta); IOUtil.deleteOnExit(ReferenceSequenceFileFactory.getFastaIndexFileName(newFasta)); IOUtil.deleteOnExit(ReferenceSequenceFileFactory.getDefaultDictionaryForReferenceSequence(newFasta)); try { long sum = samRecordSetBuilder.getHeader() .getSequenceDictionary().getSequences().stream() .mapToLong(SAMSequenceRecord::getSequenceLength) .sum(); Assert.assertFalse(sum >= 10_000_000, "Sequence dictionary is very large (total size " + sum + "). In a Cram test this could be a problem leading to writing lots" + "of bases to disk. please modify the tester using 'ModifyTesterForCramTests'. " + "For exmaple look at testBulkFragmentsNoDuplicates in AbstractMarkDuplicatesCommandLineProgramTest"); samRecordSetBuilder.writeRandomReference(newFasta); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("failed to create fasta file"); } return newFasta; }); writer = samFileWriterFactory.makeWriter(samRecordSetBuilder.getHeader(), true, input, fasta.toFile()); } else { writer = samFileWriterFactory.makeWriter(samRecordSetBuilder.getHeader(), true, input, null); } samRecordSetBuilder.getRecords().forEach(writer::addAlignment); writer.close(); return input; }
Source:
<code>protected static String read(Path file) { try { <START> return Files.lines(file).collect(joining("\n")); <END> } catch (IOException e) { throw new RuntimeException(e); } }</code><technical_language>Files.asCharSource(file, UTF8).read()</technical_language>

Target:
private static String read(Path file) { try { return Files.asCharSource(file.toFile(), UTF_8).read(); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
<code>public List<Integer> anyInsertQuery(QueryBuilder query) { try (Connection c = ds.getConnection()) { LOGGER.log(Level.FINEST, query.toString()); PreparedStatement stmt = query.toStatement(c, Statement.RETURN_GENERATED_KEYS); try { if (stmt.executeUpdate() <= 0) { return null; } ResultSet rs = stmt.getGeneratedKeys(); List<Integer> list = new ArrayList<Integer>(); while (rs.next()) { list.add(rs.getInt(1)); } <START> rs.close(); <END> return list; } finally { stmt.close(); } } catch (SQLException ex) { throw new IllegalStateException("InsertQuery Failed", ex); } }</code><technical_language>Resource leak? If rs.next throws. rs closed</technical_language>

Target:
public List<Integer> anyInsertQuery(QueryBuilder query) { LOGGER.log(Level.FINEST, query.toString()); try (Connection c = ds.getConnection()) { try (PreparedStatement stmt = query.toStatement(c, Statement.RETURN_GENERATED_KEYS)) { if (stmt.executeUpdate() <= 0) { return null; } try (ResultSet rs = stmt.getGeneratedKeys()) { List<Integer> list = new ArrayList<Integer>(); while (rs.next()) { list.add(rs.getInt(1)); } return list; } } } catch (SQLException ex) { throw new IllegalStateException("InsertQuery Failed", ex); } }
Source:
<code>public String exportExecutionCoursesEffortRates(Model model, @ModelAttribute ExecutionYear executionYear, final HttpServletResponse response) throws IOException { if (executionYear != null) { List<ExecutionCourse> executionCourses = executionYear.getExecutionPeriodsSet().stream() .flatMap(es -> es.getAssociatedExecutionCoursesSet().stream()).filter(ec -> !ec.getProjectTutorialCourse()) .sorted(ExecutionCourse.EXECUTION_COURSE_COMPARATOR_BY_EXECUTION_PERIOD_AND_NAME) .collect(Collectors.toList()); SpreadsheetBuilder builder = new SpreadsheetBuilder(); builder.addSheet(executionYear.getName(), new SheetData<ExecutionCourse>(executionCourses) { @Override protected void makeLine(ExecutionCourse executionCourse) { <START> addCell(executionCourse.getExternalId()); <END> addCell(executionCourse.getName() + " (" + executionCourse.getSigla() + ")"); addCell(executionCourse.getDegreePresentationString()); addCell(executionCourse.getEffortRate()); } }); response.setContentType("text/csv"); String fileName = BundleUtil.getString("resources.TeacherCreditsSheetResources", "label.effortRate").replaceAll(" ", "_") + "_" + executionYear.getName().replaceAll("/", "_") + ".csv"; response.setHeader("Content-Disposition", "filename=" + fileName); builder.build(WorkbookExportFormat.CSV, response.getOutputStream()); response.flushBuffer(); } return null; }</code><technical_language>External IDs exporting/importing information</technical_language>

Target:
public String exportExecutionCoursesEffortRates(Model model, @ModelAttribute ExecutionYear executionYear, final HttpServletResponse response) throws IOException { if (executionYear != null) { List<ExecutionCourse> executionCourses = executionYear.getExecutionPeriodsSet().stream() .flatMap(es -> es.getAssociatedExecutionCoursesSet().stream()).filter(ec -> !ec.getProjectTutorialCourse()) .sorted(ExecutionCourse.EXECUTION_COURSE_COMPARATOR_BY_EXECUTION_PERIOD_AND_NAME) .collect(Collectors.toList()); SpreadsheetBuilder builder = new SpreadsheetBuilder(); builder.addSheet(executionYear.getName(), new SheetData<ExecutionCourse>(executionCourses) { @Override protected void makeLine(ExecutionCourse executionCourse) { addCell(GepReportFile.getExecutionCourseCode(executionCourse)); addCell(executionCourse.getEffortRate()); } }); response.setContentType("text/csv"); String fileName = BundleUtil.getString("resources.TeacherCreditsSheetResources", "label.effortRate").replaceAll(" ", "_") + "_" + executionYear.getName().replaceAll("/", "_") + ".csv"; response.setHeader("Content-Disposition", "filename=" + fileName); builder.build(WorkbookExportFormat.CSV, response.getOutputStream()); response.flushBuffer(); } return null; }
Source:
<code>public static void eventNewConnection( final String channel, final int streamId, final int sessionId, final long position, final String sourceInformation) { <START> System.out.println( <END> String.format( "new connection on %s streamId %x sessionId %x from %s", channel, streamId, sessionId, sourceInformation)); }</code><technical_language>System.out.format instead</technical_language>

Target:
public static void eventNewConnection( final String channel, final int streamId, final int sessionId, final long position, final String sourceInformation) { System.out.format( "new connection on %s streamId %x sessionId %x from %s%n", channel, streamId, sessionId, sourceInformation); }
Source:
<code>public AckMsg(String rawMsg) { super(rawMsg); if (this.payload.length == ACK_MSG_PAYLOAD_LEN) { isNack = (this.payload[0] == 0x81); } <START> else logger.error("Got "+this.msgType+" message with incorrect length!"); <END> }</code><technical_language>please add curly braces</technical_language>

Target:
public AckMsg(String rawMsg) { super(rawMsg); if (this.payload.length == ACK_MSG_PAYLOAD_LEN) { isNack = (this.payload[0] == 0x81); } else { logger.error("Got " + this.msgType + " message with incorrect length!"); } }
Source:
<code>public void search(View view) { ArrayList<MKOLSearchRecord> records = mOffline.searchCity(mCityNameView .getText().toString()); <START> if (records == null || records.size() != 1) { <END> return; } mCidView.setText(String.valueOf(records.get(0).cityID)); }</code><technical_language>@droneboost reason size of records is restricted 1? If more results, grab below</technical_language>

Target:
public void search(View view) { ArrayList<MKOLSearchRecord> records = mOffline.searchCity(mCityNameView .getText().toString()); if (records == null) { return; } mCidView.setText(String.valueOf(records.get(0).cityID)); }
Source:
<code>public Object get(boolean preferJson, String application, String entityToken, String configKeyName) { EntityLocal entity = brooklyn().getEntity(application, entityToken); ConfigKey<?> ck = entity.getEntityType().getConfigKey(configKeyName); if (ck==null) ck = new BasicConfigKey<Object>(Object.class, configKeyName); <START> return getValueForDisplay(entity.getConfig(ck), preferJson, true); <END> }</code><technical_language>I getConfigMap().getRawConfig() avoid blocking if config is attributeWhenReady() task. reasoning this change</technical_language>

Target:
public Object get(boolean preferJson, String application, String entityToken, String configKeyName) { EntityLocal entity = brooklyn().getEntity(application, entityToken); ConfigKey<?> ck = entity.getEntityType().getConfigKey(configKeyName); if (ck==null) ck = new BasicConfigKey<Object>(Object.class, configKeyName); return getValueForDisplay(((EntityInternal)entity).getConfigMap().getRawConfig(ck), preferJson, true); }
Source:
<code>public BufferConsumer createBufferConsumer() { <START> if (buffer == null) { buffer = new NetworkBuffer(memorySegment, recycler); } else { buffer.retainBuffer(); } <END> return new BufferConsumer( buffer, positionMarker, positionMarker.cachedPosition); }</code><technical_language>I this leaves a window for error happen. buffer == null, returned BufferConsumer recycled next call BufferBuilder#createBufferConsumer. besides that, other proposal: public BufferConsumer copyAndSync(BufferBuilder builder) { return new BufferConsumer(buffer.retainBuffer(), builder.positionMarker, builder.positionMarker.cachedPosition); } I cleaner avoids adding more mutable state in BufferBuilder</technical_language>

Target:
public BufferConsumer createBufferConsumer() { checkState(!bufferConsumerCreated, "Two BufferConsumer shouldn't exist for one BufferBuilder"); bufferConsumerCreated = true; return new BufferConsumer( memorySegment, recycler, positionMarker, positionMarker.cachedPosition); }
Source:
<code>void startLocationPolling(PollSensorAction action) { synchronized (actions) { actions.add(action); } resetTimeoutTimer(); new Handler(Looper.getMainLooper()).post(() -> { Context context = CommCareApplication.instance(); mLocationController = CommCareLocationControllerFactory.getLocationController(context, this); <START> mLocationController.start(); <END> }); }</code><technical_language>nit: good delegate requestLocationUpdates</technical_language>

Target:
void startLocationPolling(PollSensorAction action) { synchronized (actions) { actions.add(action); } resetTimeoutTimer(); new Handler(Looper.getMainLooper()).post(() -> { Context context = CommCareApplication.instance(); mLocationController = CommCareLocationControllerFactory.getLocationController(context, this); requestLocationUpdates(); }); }
Source:
<code>S3ABlockOutputStream(S3AFileSystem fs, String key, ExecutorService executorService, Progressable progress, long blockSize, S3ADataBlocks.BlockFactory blockFactory, S3AInstrumentation.OutputStreamStatistics statistics, S3AFileSystem.WriteOperationHelper writeOperationHelper) throws IOException { this.fs = fs; this.key = key; this.blockFactory = blockFactory; this.blockSize = (int) blockSize; this.statistics = statistics; this.writeOperationHelper = writeOperationHelper; Preconditions.checkArgument(blockSize >= Constants.MULTIPART_MIN_SIZE, "Block size is too small: %d", blockSize); this.executorService = MoreExecutors.listeningDecorator(executorService); this.multiPartUpload = null; this.progressListener = (progress instanceof ProgressListener) ? (ProgressListener) progress : new ProgressableListener(progress); <START> LOG.debug("Initialized S3ABlockOutputStream for {}" + <END> " output to {}", writeOperationHelper, activeBlock); maybeCreateBlock(); }</code><technical_language>I activeBlock is null this log statement executes</technical_language>

Target:
S3ABlockOutputStream(S3AFileSystem fs, String key, ExecutorService executorService, Progressable progress, long blockSize, S3ADataBlocks.BlockFactory blockFactory, S3AInstrumentation.OutputStreamStatistics statistics, S3AFileSystem.WriteOperationHelper writeOperationHelper) throws IOException { this.fs = fs; this.key = key; this.blockFactory = blockFactory; this.blockSize = (int) blockSize; this.statistics = statistics; this.writeOperationHelper = writeOperationHelper; Preconditions.checkArgument(blockSize >= Constants.MULTIPART_MIN_SIZE, "Block size is too small: %d", blockSize); this.executorService = MoreExecutors.listeningDecorator(executorService); this.multiPartUpload = null; this.progressListener = (progress instanceof ProgressListener) ? (ProgressListener) progress : new ProgressableListener(progress); createBlockIfNeeded(); LOG.debug("Initialized S3ABlockOutputStream for {}" + " output to {}", writeOperationHelper, activeBlock); }
Source:
<code>public void close() { try { for (RFileSource source : opts.in.getSources()) { source.getInputStream().close(); } } catch (IOException e) { throw new RuntimeException(e); } try { if (this.blockCacheManager != null) { this.blockCacheManager.stop(); } <START> } catch (RuntimeException e1) { <END> throw new RuntimeException(e1); } }</code><technical_language>This catch block removed</technical_language>

Target:
public void close() { try { for (RFileSource source : opts.in.getSources()) { source.getInputStream().close(); } } catch (IOException e) { throw new RuntimeException(e); } if (this.blockCacheManager != null) { this.blockCacheManager.stop(); } }