auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void setProjectProgress(int projectId, int progress) { final String whereClause = String.format("%s=?", ProjectContract.ProjectEntry._ID); String projectIdString = String.valueOf(projectId); SQLiteDatabase db = getReadableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(ProjectContract.ProjectEntry.PROJECT_PROGRESS, progress); <START> db.update(ProjectContract.ProjectEntry.TABLE_PROJECT, contentValues, whereClause, new String[]{projectIdString}); <END> db.close(); }</code><technical_language>line length</technical_language>

Target:
public void setProjectProgress(int projectId, int progress) { final String whereClause = String.format("%s=?", ProjectContract.ProjectEntry._ID); String projectIdString = String.valueOf(projectId); SQLiteDatabase db = getReadableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(ProjectContract.ProjectEntry.PROJECT_PROGRESS, progress); db.update(ProjectContract.ProjectEntry.TABLE_PROJECT, contentValues, whereClause, new String[]{projectIdString}); }
Source:
<code>public void addTreatment(String experimentName, String treatmentName, String description) { resource( ENDPOINT_TREATMENTS, ImmutableMap.of( PARAM_EXPERIMENT_NAME, experimentName ) <START> ).put(Entity.entity(new TreatmentDto(treatmentName, description), MediaType.APPLICATION_JSON_TYPE)); <END> }</code><technical_language>for Entity.json() argument is needed</technical_language>

Target:
public void addTreatment(String experimentName, String treatmentName, String description) { resource( ENDPOINT_TREATMENTS, ImmutableMap.of( PARAM_EXPERIMENT_NAME, experimentName ) ).put(Entity.json(new TreatmentDto(treatmentName, description))); }
Source:
<code><START> public Histogram<HKEY> getHistogram(final int index) { <END> if (histograms.size() > 0 && index < this.histograms.size()) return this.histograms.get(index); else return null; }</code><technical_language>personal preference is throw exception if out of bounds</technical_language>

Target:
public Histogram<HKEY> getHistogram(final int index) { try { return this.histograms.get(index); } catch (final ArrayIndexOutOfBoundsException excep) { throw new SAMException("Index is out of bounds: " + index); } }
Source:
<code>public StateChange getDefaultInstance() { <START> return new SetViewportToSizeOf(new ResourceUrn("engine:sceneOpaque"), CoreRegistry.get(DisplayResolutionDependentFBOs.class)); <END> }</code><technical_language>creating a new instance of SetViewportToSizeOf time this method is called. instantiation happen for a default instance</technical_language>

Target:
public StateChange getDefaultInstance() { if (defaultInstance == null) { defaultInstance = new SetViewportToSizeOf(READONLY_GBUFFER, CoreRegistry.get(DisplayResolutionDependentFBOs.class)); } return defaultInstance; }
Source:
<code>public boolean filter(ScriptDTO script) { boolean result = true; if (!containCommercialApplications.getValue()) { result &= script.isFree(); } if (containRequiresPatchApplications.getValue()) { result &= !script.isRequiresPatch(); } if (!containTestingApplications.getValue()) { result &= CollectionUtils.isEmpty(script.getTestingOperatingSystems()); } if (!containAllOSCompatibleApplications.getValue()) { <START> result &= script.getCompatibleOperatingSystems() <END> .contains(operatingSystemFetcher.fetchCurrentOperationSystem()); } return result; }</code><technical_language>I guess this crash if getCompatibleOperatingSystems() returns null</technical_language>

Target:
public boolean filter(ScriptDTO script) { boolean result = true; if (!containCommercialApplications.getValue()) { result &= script.isFree(); } if (containRequiresPatchApplications.getValue()) { result &= !script.isRequiresPatch(); } if (!containTestingApplications.getValue()) { result &= CollectionUtils.isEmpty(script.getTestingOperatingSystems()); } if (!containAllOSCompatibleApplications.getValue()) { result &= !CollectionUtils.isEmpty(script.getCompatibleOperatingSystems()) && script .getCompatibleOperatingSystems().contains(operatingSystemFetcher.fetchCurrentOperationSystem()); } return result; }
Source:
<code>public String createLoadBalancer(String name){ <START> <END> CreateLoadBalancerRequest lbRequest = new CreateLoadBalancerRequest(); lbRequest.setLoadBalancerName(name); lbRequest.withAvailabilityZones(elbAzs.split(",")); List<Listener> listeners = new ArrayList(); listeners.add(new Listener(elbProtocol, elbPortIn, elbPortOut)); lbRequest.setListeners(listeners); CreateLoadBalancerResult lbResult=elb.createLoadBalancer(lbRequest); lbResult.getDNSName(); appendText(lbResult.getDNSName() + "\n", elbFile); return lbRequest.getLoadBalancerName(); }</code><technical_language>need for this empty line</technical_language>

Target:
public String createLoadBalancer(String name){ CreateLoadBalancerRequest lbRequest = new CreateLoadBalancerRequest(); lbRequest.setLoadBalancerName(name); lbRequest.withAvailabilityZones(elbAvailabilityZones.split(",")); List<Listener> listeners = new ArrayList(); listeners.add(new Listener(elbProtocol, elbPortIn, elbPortOut)); lbRequest.setListeners(listeners); CreateLoadBalancerResult lbResult=elb.createLoadBalancer(lbRequest); lbResult.getDNSName(); appendText(lbResult.getDNSName() + "\n", elbFile); return lbRequest.getLoadBalancerName(); }
Source:
<code>public SignatureKeyPairImpl create(SignatureKeyPairImpl keyPair) throws ConflictException, ServerException { requireNonNull(keyPair, "Required non-null key pair"); try { doCreate(keyPair); <START> } catch (org.eclipse.che.core.db.jpa.IntegrityConstraintViolationException x) { <END> throw new ConflictException( format( "Workspace with id '%s' referenced by signature key pair doesn't exist", keyPair.getWorkspaceId())); } catch (DuplicateKeyException dkEx) { throw new ConflictException( format("Signature key pair for workspace '%s' already exists", keyPair.getWorkspaceId())); } catch (RuntimeException ex) { throw new ServerException(ex.getMessage(), ex); } return new SignatureKeyPairImpl(keyPair); }</code><technical_language>import here</technical_language>

Target:
public SignatureKeyPairImpl create(SignatureKeyPairImpl keyPair) throws ConflictException, ServerException { requireNonNull(keyPair, "Required non-null key pair"); try { doCreate(keyPair); } catch (IntegrityConstraintViolationException x) { throw new ConflictException( format( "Unable to create signature key pair because referenced workspace with id '%s' doesn't exist", keyPair.getWorkspaceId())); } catch (DuplicateKeyException dkEx) { throw new ConflictException( format("Signature key pair for workspace '%s' already exists", keyPair.getWorkspaceId())); } catch (RuntimeException ex) { throw new ServerException(ex.getMessage(), ex); } return new SignatureKeyPairImpl(keyPair); }
Source:
<code><START> void start() { <END> if (!started) { log.info("Starting prefetching thread."); executorService.execute(new DefaultGetRecordsCacheDaemon()); } started = true; }</code><technical_language>This public, in interface</technical_language>

Target:
public void start() { if (!started) { log.info("Starting prefetching thread."); executorService.execute(new DefaultGetRecordsCacheDaemon()); } started = true; }
Source:
<code>private void handleTask(Task task, Map<String, Object> parameters, boolean isRetry) { long activityId = activityService.addTaskStarted(task, parameters); Map<String, Object> metadata = prepareTaskMetadata(task.getId(), activityId, isRetry); <START> taskContext = new TaskContext(task, parameters, metadata, activityService); <END> TaskInitializer initializer = new TaskInitializer(taskContext); try { LOGGER.info("Executing all actions from task: {}", task.getName()); if (initializer.evalConfigSteps(dataProviders)) { for (int i = 0; i < task.getActions().size(); i++) { executor.execute(task, task.getActions().get(i), i, taskContext, activityId); } } LOGGER.warn("Actions from task: weren't executed, because config steps didn't pass the evaluation", task.getName()); } catch (TaskHandlerException e) { postExecutionHandler.handleError(parameters, metadata, task, e, activityId); } catch (RuntimeException e) { postExecutionHandler.handleError(parameters, metadata, task, new TaskHandlerException(TRIGGER, "task.error.unrecognizedError", e), activityId); } }</code><technical_language>remove changes in this class</technical_language>

Target:
private void handleTask(Task task, Map<String, Object> parameters, boolean isRetry) { long activityId = activityService.addTaskStarted(task, parameters); Map<String, Object> metadata = prepareTaskMetadata(task.getId(), activityId, isRetry); TaskContext taskContext = new TaskContext(task, parameters, metadata, activityService); TaskInitializer initializer = new TaskInitializer(taskContext); try { LOGGER.info("Executing all actions from task: {}", task.getName()); if (initializer.evalConfigSteps(dataProviders)) { for (int i = 0; i < task.getActions().size(); i++) { executor.execute(task, task.getActions().get(i), i, taskContext, activityId); } } LOGGER.warn("Actions from task: weren't executed, because config steps didn't pass the evaluation", task.getName()); } catch (TaskHandlerException e) { postExecutionHandler.handleError(parameters, metadata, task, e, activityId); } catch (RuntimeException e) { postExecutionHandler.handleError(parameters, metadata, task, new TaskHandlerException(TRIGGER, "task.error.unrecognizedError", e), activityId); } }
Source:
<code>public ResponseEntity<Loan> create(@RequestBody @Valid Loan loan) { try { <START> Loan createdLoan = loanDao.saveAndFlush(loan); <END> return new ResponseEntity<>(createdLoan, HttpStatus.OK); } catch (DataIntegrityViolationException dive) { throw new ConflictException(dive.getMostSpecificCause().getMessage()); } }</code><technical_language>attach logged AppUser Loan Entity, check if Counterparty is attached entity</technical_language>

Target:
public ResponseEntity<Loan> create(@RequestBody @Valid Loan loan) { try { loan.setActive(true); if(loan.getCounterparty().getId() == 0){ counterpartyDao.saveAndFlush(loan.getCounterparty()); } loan.setUser(userUtil.extractLoggedAppUserFromDatabase()); Loan createdLoan = loanDao.saveAndFlush(loan); return new ResponseEntity<>(createdLoan, HttpStatus.OK); } catch (DataIntegrityViolationException dive) { throw new ConflictException(dive.getMostSpecificCause().getMessage()); } }
Source:
<code>public void setAlternativeSequenceName(final Collection<String> alternativeSequences) { if (alternativeSequences == null) { setAttribute(ALTERNATIVE_SEQUENCE_NAME_TAG, null); } else { <START> alternativeSequences.forEach(SAMSequenceRecord::validateAltRegExp); <END> encodeAltSequences(alternativeSequences); } }</code><technical_language>remove this validation done encodeAltSequences</technical_language>

Target:
public void setAlternativeSequenceName(final Collection<String> alternativeSequences) { if (alternativeSequences == null) { setAttribute(ALTERNATIVE_SEQUENCE_NAME_TAG, null); } else { encodeAltSequences(alternativeSequences); } }
Source:
<code>public TemplateDataStoreVO getReadyBypassedTemplate(long templateId) { SearchCriteria<TemplateDataStoreVO> sc = directDownloadTemplateSeach.create(); sc.setParameters("template_id", templateId); sc.setParameters("download_state", Status.BYPASSED); sc.setParameters("state", State.Ready); List<TemplateDataStoreVO> list = search(sc, null); <START> if (list == null || list.isEmpty() || list.size() > 1) { <END> return null; } return list.get(0); }</code><technical_language>CollectionUtils.isEmpty() || list.size >1</technical_language>

Target:
public TemplateDataStoreVO getReadyBypassedTemplate(long templateId) { SearchCriteria<TemplateDataStoreVO> sc = directDownloadTemplateSeach.create(); sc.setParameters("template_id", templateId); sc.setParameters("download_state", Status.BYPASSED); sc.setParameters("state", State.Ready); List<TemplateDataStoreVO> list = search(sc, null); if (CollectionUtils.isEmpty(list) || list.size() > 1) { return null; } return list.get(0); }
Source:
<code><START> private ICPPEvaluation deref(ICPPEvaluation ptr, boolean isRef, ActivationRecord record, ConstexprEvaluationContext context) { <END> ICPPEvaluation derefEval = new EvalUnary(ICPPASTUnaryExpression.op_star, ptr, null, context.getPoint()).computeForFunctionCall(record, context); if(isRef) { return derefEval; } else { return new EvalFixed(derefEval.getType(null), derefEval.getValueCategory(null), derefEval.getValue(null)); } }</code><technical_language>This static isEqual()</technical_language>

Target:
private static ICPPEvaluation deref(ICPPEvaluation ptr, boolean isRef, ActivationRecord record, ConstexprEvaluationContext context) { ICPPEvaluation derefEval = new EvalUnary(ICPPASTUnaryExpression.op_star, ptr, null, context.getPoint()).computeForFunctionCall(record, context); if(isRef) { return derefEval; } else { return new EvalFixed(derefEval.getType(context.getPoint()), derefEval.getValueCategory(context.getPoint()), derefEval.getValue(context.getPoint())); } }
Source:
<code>private void reportError(BuildStep bs, Throwable e, BuildListener listener, boolean phase) { final String buildStep; if (bs instanceof Publisher) { buildStep = ((Publisher) bs).getDescriptor().getDisplayName(); } else { <START> buildStep = bs.getClass().getName(); <END> } if (e instanceof AbortException) { LOGGER.log(Level.FINE, "{0} : {1} failed", new Object[] {AbstractBuild.this, buildStep}); listener.error(buildStep + "' failed: " + e.getMessage()); } else { String msg = buildStep + "' aborted due to exception: "; e.printStackTrace(listener.error(msg)); LOGGER.log(WARNING, msg, e); } if (phase) { setResult(Result.FAILURE); } }</code><technical_language>display name for builder for publisher</technical_language>

Target:
private void reportError(BuildStep bs, Throwable e, BuildListener listener, boolean phase) { final String buildStep; if (bs instanceof Describable) { buildStep = ((Describable) bs).getDescriptor().getDisplayName(); } else { buildStep = bs.getClass().getName(); } if (e instanceof AbortException) { LOGGER.log(Level.FINE, "{0} : {1} failed", new Object[] {AbstractBuild.this, buildStep}); listener.error("Step ‘" + buildStep + "’ failed: " + e.getMessage()); } else { String msg = "Step ‘" + buildStep + "’ aborted due to exception: "; e.printStackTrace(listener.error(msg)); LOGGER.log(WARNING, msg, e); } if (phase) { setResult(Result.FAILURE); } }
Source:
<code>public final void run() { if (allowedCpus != null) { Affinity.setAffinity(allowedCpus); BitSet actualCpus = Affinity.getAffinity(); if (!actualCpus.equals(allowedCpus)) { <START> System.out.println(getName() + " affinity was not applied successfully. " <END> + "Expected cpus:" + allowedCpus + ". Actual cpus:" + actualCpus); } else { System.out.println(getName() + " has affinity for cpus:" + allowedCpus); } } try { beforeRun(); executeRun(); } catch (OutOfMemoryError e) { OutOfMemoryErrorDispatcher.onOutOfMemory(e); } finally { afterRun(); } }</code><technical_language>logging below</technical_language>

Target:
public final void run() { if (allowedCpus != null) { Affinity.setAffinity(allowedCpus); BitSet actualCpus = Affinity.getAffinity(); ILogger logger = Logger.getLogger(HazelcastManagedThread.class); if (!actualCpus.equals(allowedCpus)) { logger.warning(getName() + " affinity was not applied successfully. " + "Expected CPUs:" + allowedCpus + ". Actual CPUs:" + actualCpus); } else { logger.info(getName() + " has affinity for CPUs:" + allowedCpus); } } try { beforeRun(); executeRun(); } catch (OutOfMemoryError e) { OutOfMemoryErrorDispatcher.onOutOfMemory(e); } finally { afterRun(); } }
Source:
<code>private String pathToFolder(File file) { String path = file.getAbsolutePath(); try { <START> return path.substring(path.indexOf("GUIData") + "GUIData".length() + 1, path.lastIndexOf(File.separator)) <END> .trim(); } catch(StringIndexOutOfBoundsException ex) { return ""; } }</code><technical_language>do I detect a TAB character here</technical_language>

Target:
private String pathToFolder(File file) { String path = file.getAbsolutePath(); try { return path.substring(path.indexOf(baseFolder) + baseFolder.length() + 1, path.lastIndexOf(File.separator)) .trim(); } catch(StringIndexOutOfBoundsException ex) { return ""; } }
Source:
<code>private static void validateValidationConfig(TableConfig tableConfig) { SegmentsValidationAndRetentionConfig validationConfig = tableConfig.getValidationConfig(); if (validationConfig != null) { String peerSegmentDownloadScheme = validationConfig.getPeerSegmentDownloadScheme(); if (peerSegmentDownloadScheme != null) { <START> if (!"http".equals(peerSegmentDownloadScheme) && !"https".equals(peerSegmentDownloadScheme)) { <END> throw new IllegalStateException("peerSegmentDownloadScheme: " + peerSegmentDownloadScheme + " is not http nor https" ); } } } }</code><technical_language>suggestion if (!"http".equalsIgnoreCase(peerSegmentDownloadScheme) && !"https".equalsIgnoreCase(peerSegmentDownloadScheme)) {</technical_language>

Target:
private static void validateValidationConfig(TableConfig tableConfig) { SegmentsValidationAndRetentionConfig validationConfig = tableConfig.getValidationConfig(); if (validationConfig != null) { String peerSegmentDownloadScheme = validationConfig.getPeerSegmentDownloadScheme(); if (peerSegmentDownloadScheme != null) { if (!"http".equalsIgnoreCase(peerSegmentDownloadScheme) && !"https".equalsIgnoreCase(peerSegmentDownloadScheme)) { throw new IllegalStateException("Invalid value '" + peerSegmentDownloadScheme + "' for peerSegmentDownloadScheme. Must be one of http nor https" ); } } } }
Source:
<code>private String getFolderSizeHuman(String path) { File dir = new File(path); if(dir.exists()) { long bytes = getFolderSize(dir); <START> if (bytes < 1024) return bytes + " B"; <END> int exp = (int) (Math.log(bytes) / Math.log(1024)); String pre = ("KMGTPE").charAt(exp-1) + ""; return String.format("%.1f %sB", bytes / Math.pow(1024, exp), pre); } return "0 B"; }</code><technical_language>adding this formatting? easier pass result of getFolderSize(dir) DisplayUtils.bytesHumanReadable(long bytes)</technical_language>

Target:
private String getFolderSizeHuman(String path) { File dir = new File(path); if (dir.exists()) { long bytes = getFolderSize(dir); return DisplayUtils.bytesToHumanReadable(bytes); } return "0 B"; }
Source:
<code>public Void visitTableScan(TableScanNode node, IOPlanBuilder context) { TableMetadata tableMetadata = metadata.getTableMetadata(session, node.getTable()); context.addInputTableColumnInfo(new IOPlan.TableColumnInfo( new QualifiedTablePrefix( tableMetadata.getConnectorId().getCatalogName(), tableMetadata.getTable().getSchemaName(), tableMetadata.getTable().getTableName()), parseConstraints(node.getTable(), node.getCurrentConstraint()))); <START> node.getSources().forEach(plan -> plan.accept(this, context)); <END> return null; }</code><technical_language>Change this assertion node.getSources() is empty</technical_language>

Target:
public Void visitTableScan(TableScanNode node, IOPlanBuilder context) { TableMetadata tableMetadata = metadata.getTableMetadata(session, node.getTable()); context.addInputTableColumnInfo(new IOPlan.TableColumnInfo( new CatalogSchemaTableName( tableMetadata.getConnectorId().getCatalogName(), tableMetadata.getTable().getSchemaName(), tableMetadata.getTable().getTableName()), parseConstraints(node.getTable(), node.getCurrentConstraint()))); return null; }
Source:
<code>Box(Corner upperLeft, Corner upperRight, Corner lowerRight, Corner lowerLeft) { this.upperLeft = upperLeft; this.upperRight = upperRight; this.lowerRight = lowerRight; this.lowerLeft = lowerLeft; top = false; right = false; bottom = false; left = false; <START> owner = null; <END> }</code><technical_language>Hmmm... null</technical_language>

Target:
Box(Corner upperLeft, Corner upperRight, Corner lowerRight, Corner lowerLeft) { this.upperLeft = upperLeft; this.upperRight = upperRight; this.lowerRight = lowerRight; this.lowerLeft = lowerLeft; top = false; right = false; bottom = false; left = false; owner = NO_OWNER; }
Source:
<code>public boolean equals(Object o) { <START> if (this == o) return true; <END> if (!(o instanceof JksOptions)) return false; JksOptions that = (JksOptions) o; if (password != null ? !password.equals(that.password) : that.password != null) return false; if (path != null ? !path.equals(that.path) : that.path != null) return false; if (value != null ? !value.equals(that.value) : that.value != null) return false; return true; }</code><technical_language>please braces</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof JksOptions)) { return false; } JksOptions that = (JksOptions) o; if (password != null ? !password.equals(that.password) : that.password != null) { return false; } if (path != null ? !path.equals(that.path) : that.path != null) { return false; } if (value != null ? !value.equals(that.value) : that.value != null) { return false; } return true; }
Source:
<code><START> public void vlanOverBond() { <END> VdsNetworkInterface bond = createBond(null); List<VdsNetworkInterface> ifacesToBond = createBondSlaves(null); SetupNetworksParameters parameters = createParametersForBond(bond, ifacesToBond); String networkName = "net"; parameters.getInterfaces().add(createVlan(bond.getName(), 100, networkName)); SetupNetworksHelper helper = createHelper(parameters); mockExistingIfacesWithBond(bond, ifacesToBond); network network = mockExistingNetwork(networkName); validateAndExpectNoViolations(helper); assertBondModified(helper, bond); assertNetworkModified(helper, network); assertNoBondsRemoved(helper); assertNoNetworksRemoved(helper); }</code><technical_language>please reorder this test in previous tests: -create parameters -mock -create helper -validate</technical_language>

Target:
public void vlanOverBond() { VdsNetworkInterface bond = createBond(BOND_NAME, null); List<VdsNetworkInterface> ifacesToBond = createNics(null); mockExistingIfacesWithBond(bond, ifacesToBond); SetupNetworksParameters parameters = createParametersForBond(bond, ifacesToBond); String networkName = "net"; parameters.getInterfaces().add(createVlan(bond.getName(), 100, networkName)); network network = mockExistingNetwork(networkName); SetupNetworksHelper helper = createHelper(parameters); validateAndExpectNoViolations(helper); assertBondModified(helper, bond); assertNetworkModified(helper, network); assertNoBondsRemoved(helper); assertNoNetworksRemoved(helper); }
Source:
<code><START> synchronized public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception { <END> if (obj instanceof Reference && "javax.sql.DataSource".equals(((Reference) obj).getClassName())) { Reference ref = (Reference) obj; Set<String> hikariPropSet = PropertyElf.getPropertyNames(HikariConfig.class); Properties properties = new Properties(); Enumeration<RefAddr> enumeration = ref.getAll(); while (enumeration.hasMoreElements()) { RefAddr element = enumeration.nextElement(); String type = element.getType(); if (type.startsWith("dataSource.") || hikariPropSet.contains(type)) { properties.setProperty(type, element.getContent().toString()); } } return createDataSource(properties, nameCtx); } else { return null; } }</code><technical_language>HikariCP's code style is open brace a new line method declaration, open brace line in method</technical_language>

Target:
synchronized public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception { if (obj instanceof Reference && "javax.sql.DataSource".equals(((Reference) obj).getClassName())) { Reference ref = (Reference) obj; Set<String> hikariPropSet = PropertyElf.getPropertyNames(HikariConfig.class); Properties properties = new Properties(); Enumeration<RefAddr> enumeration = ref.getAll(); while (enumeration.hasMoreElements()) { RefAddr element = enumeration.nextElement(); String type = element.getType(); if (type.startsWith("dataSource.") || hikariPropSet.contains(type)) { properties.setProperty(type, element.getContent().toString()); } } return createDataSource(properties, nameCtx); } return null; }
Source:
<code>public static String getObservationStrategy() { <START> return Context.getAdministrationService().getGlobalProperty("fhit.observation.observationStrategy"); <END> }</code><technical_language>get custom strategy of a typo. Please change fhit -> fhir</technical_language>

Target:
public static String getObservationStrategy() { return Context.getAdministrationService().getGlobalProperty("fhir.observation.observationStrategy"); }
Source:
<code>private void parse(HwpStreamReader reader, XHTMLContentHandler xhtml) throws IOException, SAXException { StringBuffer buf = new StringBuffer(1024); TagInfo tag = new TagInfo(); while (true) { if (!readTag(reader, tag)) break; buf.setLength(0); if (HWPTAG_BEGIN + 50 == tag.id) { writeParaHeader(reader, tag.length, buf); } else if (HWPTAG_BEGIN + 51 == tag.id) { if (tag.length % 2 != 0) throw new IOException("Invalid block size"); writeParaText(reader, tag.length, buf); if (buf.length() > 0) { buf.append('\n'); <START> xhtml.characters(buf.toString()); <END> } } else { reader.ensureSkip(tag.length); } if (buf.length() > 0) { log.debug("TAG[{}]({}):{} [{}]", new Object[] { tag.id, tag.level, tag.length, buf }); } } }</code><technical_language>Add xhtml p element <p></technical_language>

Target:
private void parse(HwpStreamReader reader, XHTMLContentHandler xhtml) throws IOException, SAXException { StringBuffer buf = new StringBuffer(1024); TagInfo tag = new TagInfo(); while (true) { if (!readTag(reader, tag)) break; if (HWPTAG_BEGIN + 51 == tag.id) { if (tag.length % 2 != 0) throw new IOException("Invalid block size"); buf.setLength(0); writeParaText(reader, tag.length, buf); if (buf.length() > 0) { buf.append('\n'); xhtml.startElement("p"); xhtml.characters(buf.toString()); xhtml.endElement("p"); } } else { reader.ensureSkip(tag.length); } } }
Source:
<code>Request(Builder builder) { this.uri = builder.uri; this.resourceId = builder.resourceId; this.stableKey = builder.stableKey; if (builder.transformations == null) { <START> this.transformations = new ArrayList<>(); <END> } else { this.transformations = Collections.unmodifiableList(new ArrayList<>(builder.transformations)); } this.targetWidth = builder.targetWidth; this.targetHeight = builder.targetHeight; this.centerCrop = builder.centerCrop; this.centerInside = builder.centerInside; this.centerCropGravity = builder.centerCropGravity; this.onlyScaleDown = builder.onlyScaleDown; this.rotationDegrees = builder.rotationDegrees; this.rotationPivotX = builder.rotationPivotX; this.rotationPivotY = builder.rotationPivotY; this.hasRotationPivot = builder.hasRotationPivot; this.purgeable = builder.purgeable; this.config = builder.config; this.priority = builder.priority; if (Looper.myLooper() == Looper.getMainLooper()) { this.key = createKey(); } else { this.key = createKey(new StringBuilder()); } this.tag = builder.tag; this.memoryPolicy = builder.memoryPolicy; this.networkPolicy = builder.networkPolicy; }</code><technical_language>Collections.emptyList()</technical_language>

Target:
Request(Builder builder) { this.uri = builder.uri; this.resourceId = builder.resourceId; this.stableKey = builder.stableKey; if (builder.transformations == null) { this.transformations = Collections.emptyList(); } else { this.transformations = Collections.unmodifiableList(new ArrayList<>(builder.transformations)); } this.targetWidth = builder.targetWidth; this.targetHeight = builder.targetHeight; this.centerCrop = builder.centerCrop; this.centerInside = builder.centerInside; this.centerCropGravity = builder.centerCropGravity; this.onlyScaleDown = builder.onlyScaleDown; this.rotationDegrees = builder.rotationDegrees; this.rotationPivotX = builder.rotationPivotX; this.rotationPivotY = builder.rotationPivotY; this.hasRotationPivot = builder.hasRotationPivot; this.purgeable = builder.purgeable; this.config = builder.config; this.priority = builder.priority; if (Looper.myLooper() == Looper.getMainLooper()) { this.key = createKey(); } else { this.key = createKey(new StringBuilder()); } this.tag = builder.tag; this.memoryPolicy = builder.memoryPolicy; this.networkPolicy = builder.networkPolicy; }
Source:
<code>public Object apply(AccountResource rsrc, Input input) throws OrmException, MethodNotAllowedException { if (!realm.allowsEdit(FieldName.FULL_NAME)) { throw new MethodNotAllowedException("The realm doesn't allow editing names"); } if (input == null) { input = new Input(); } Account a = rsrc.getUser().getAccount(); a.setFullName(input.name); <START> dbProvider.get().accounts().update(Collections.singleton(a)); <END> byIdCache.evict(a.getId()); return Strings.isNullOrEmpty(a.getFullName()) ? Response.none() : a .getFullName(); }</code><technical_language>falling victim this. object get AccountResource is in-memory cache. possibly stale relative database. re-read entity database, set full name, update avoid overwriting stale information cache</technical_language>

Target:
public Object apply(AccountResource rsrc, Input input) throws MethodNotAllowedException, ResourceNotFoundException, OrmException { if (!realm.allowsEdit(FieldName.FULL_NAME)) { throw new MethodNotAllowedException("The realm doesn't allow editing names"); } if (input == null) { input = new Input(); } Account a = dbProvider.get().accounts().get(rsrc.getUser().getAccountId()); if (a == null) { throw new ResourceNotFoundException("No such account: " + rsrc.getUser().getAccountId()); } a.setFullName(input.name); dbProvider.get().accounts().update(Collections.singleton(a)); byIdCache.evict(a.getId()); return Strings.isNullOrEmpty(a.getFullName()) ? Response.none() : a.getFullName(); }
Source:
<code>public static void testDataInfo() throws IOException, TasteException { <START> MovieRecommender recommender = new MovieRecommender("/Users/csuarez/Downloads/movies.txt.gz"); <END> assertEquals(7911684, recommender.getTotalReviews()); assertEquals(253059, recommender.getTotalProducts()); assertEquals(889176, recommender.getTotalUsers()); List<String> recommendations = recommender.getRecommendationsForUser("A141HP4LYPWMSR"); assertThat(recommendations, hasItem("B0002O7Y8U")); assertThat(recommendations, hasItem("B00004CQTF")); assertThat(recommendations, hasItem("B000063W82")); }</code><technical_language>this path a placeholder is good option,</technical_language>

Target:
public static void testDataInfo() throws IOException, TasteException { MovieRecommender recommender = new MovieRecommender("/path/to/movies.txt.gz"); assertEquals(7911684, recommender.getTotalReviews()); assertEquals(253059, recommender.getTotalProducts()); assertEquals(889176, recommender.getTotalUsers()); List<String> recommendations = recommender.getRecommendationsForUser("A141HP4LYPWMSR"); assertThat(recommendations, hasItem("B0002O7Y8U")); assertThat(recommendations, hasItem("B00004CQTF")); assertThat(recommendations, hasItem("B000063W82")); }
Source:
<code>public Collection<UfsStatus> fetchChildrenIfAbsent(AlluxioURI path, MountTable mountTable, boolean useFallback) throws IOException, InvalidPathException { Collection<UfsStatus> children = getChildren(path); if (children != null) { return children; } <START> Future<Collection<UfsStatus>> prefetchJob = mActivePrefetchJobs.remove(path); <END> if (prefetchJob != null) { try { return prefetchJob.get(); } catch (InterruptedException | ExecutionException e) { LOG.warn("Failed waiting to fetch children at {}", path); if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } throw new IOException(e); } } if (useFallback) { return getChildrenIfAbsent(path, mountTable); } return null; }</code><technical_language>Removing means other callers call this method prefetch jobs? Is intended</technical_language>

Target:
public Collection<UfsStatus> fetchChildrenIfAbsent(AlluxioURI path, MountTable mountTable, boolean useFallback) throws InterruptedException, InvalidPathException { Future<Collection<UfsStatus>> prefetchJob = mActivePrefetchJobs.get(path); if (prefetchJob != null) { try { return prefetchJob.get(); } catch (InterruptedException | ExecutionException e) { LogUtils.warnWithException(LOG, "Failed to get result for prefetch job on alluxio path {}", path, e); if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); throw (InterruptedException) e; } } finally { mActivePrefetchJobs.remove(path); } } Collection<UfsStatus> children = getChildren(path); if (children != null) { return children; } if (useFallback) { return getChildrenIfAbsent(path, mountTable); } return null; }
Source:
<code>public Iterable<RevCommit> call() throws NoHeadException, JGitInternalException { checkCallable(); if (pathFilters.size() > 0) walk.setTreeFilter(AndTreeFilter.create( PathFilterGroup.create(pathFilters), TreeFilter.ANY_DIFF)); if (skip > -1) <START> walk.setRevFilter(SkipRevFilter.create(skip)); <END> if (maxCount > -1) walk.setRevFilter(MaxCountRevFilter.create(maxCount)); if (!startSpecified) { try { ObjectId headId = repo.resolve(Constants.HEAD); if (headId == null) throw new NoHeadException( JGitText.get().noHEADExistsAndNoExplicitStartingRevisionWasSpecified); add(headId); } catch (IOException e) { throw new JGitInternalException( JGitText.get().anExceptionOccurredWhileTryingToAddTheIdOfHEAD, e); } } setCallable(false); return walk; }</code><technical_language>AndRevFilter skip maxCount set? I misunderstanding combined usage of two</technical_language>

Target:
public Iterable<RevCommit> call() throws NoHeadException, JGitInternalException { checkCallable(); if (pathFilters.size() > 0) walk.setTreeFilter(AndTreeFilter.create( PathFilterGroup.create(pathFilters), TreeFilter.ANY_DIFF)); if (skip > -1 && maxCount > -1) walk.setRevFilter(AndRevFilter.create(SkipRevFilter.create(skip), MaxCountRevFilter.create(maxCount))); else if (skip > -1) walk.setRevFilter(SkipRevFilter.create(skip)); else if (maxCount > -1) walk.setRevFilter(MaxCountRevFilter.create(maxCount)); if (!startSpecified) { try { ObjectId headId = repo.resolve(Constants.HEAD); if (headId == null) throw new NoHeadException( JGitText.get().noHEADExistsAndNoExplicitStartingRevisionWasSpecified); add(headId); } catch (IOException e) { throw new JGitInternalException( JGitText.get().anExceptionOccurredWhileTryingToAddTheIdOfHEAD, e); } } setCallable(false); return walk; }
Source:
<code>protected void executeCommand() { try { reconstructOpSucceeded = reconstructMaster(); connectAndRefreshAllUpHosts(reconstructOpSucceeded); if (!_isLastMaster && reconstructOpSucceeded) { SearchParameters p = new SearchParameters( MessageFormat.format(DesktopsInStoragePoolQuery, getStoragePool().getname()), SearchType.VM); p.setMaxCount(Integer.MAX_VALUE); @SuppressWarnings("unchecked") final List<VM> vmsInPool = (List<VM>) Backend.getInstance() .runInternalQuery(VdcQueryType.Search, p).getReturnValue(); <START> executeInNewTransaction(new TransactionMethod<Object>() { <END> @Override public Void runInTransaction() { for (VM vm : vmsInPool) { getVmDAO().updateVmOvfGeneration(vm.getId(), 0); } return null; } }); } setSucceeded(reconstructOpSucceeded); } finally { Backend.getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.MarkPoolInReconstructMode, new MarkPoolInReconstructModeVDSCommandParameters(getStoragePoolId() .getValue(), ReconstructMarkAction.ClearCache)); } }</code><technical_language>write a query update generations of vms of pool. I you, that: UPDATE vm_static set ovf_generation = 0 pool_id = ....; Simple</technical_language>

Target:
protected void executeCommand() { try { reconstructOpSucceeded = reconstructMaster(); connectAndRefreshAllUpHosts(reconstructOpSucceeded); if (!_isLastMaster && reconstructOpSucceeded) { getVmAndTemplatesGenerationsDAO().incrementDbGenerationForAllInStoragePool(getStoragePoolId().getValue()); } setSucceeded(reconstructOpSucceeded); } finally { Backend.getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.MarkPoolInReconstructMode, new MarkPoolInReconstructModeVDSCommandParameters(getStoragePoolId() .getValue(), ReconstructMarkAction.ClearCache)); } }
Source:
<code>public boolean shouldBeRetried(URI uri, int retryCount, ClientResponse response, Throwable exception, Mode mode) { if (retryCount >= maxRetries) { LOG.warning(String.format("Retries exceeded. retryCount: %d - maxRetries: %d", retryCount+1, maxRetries)); return false; } if ((response != null) && (mode == Mode.RETRY_ALL)) { <START> if (response.getStatusInfo().getFamily() == Response.Status.Family.SERVER_ERROR) <END> { LOG.info(String.format("Retrying request due to Status %d. retryCount: %d - request: %s", response.getStatus(), retryCount+1, uri)); return true; } } if (response != null) { int responseStatus = response.getStatus(); if (responseStatus == 429 || responseStatus == 502 || responseStatus == 503 || responseStatus == 504) { LOG.info(String.format("Retrying request due to status %d, retryCount: %d - request: %s", responseStatus, retryCount+1, uri)); return true; } } return shouldBeRetried(uri, exception, mode); }</code><technical_language>I rewrite this if (responseStatus == 429 || responseStatus == 500 || responseStatus == 502 || responseStatus == 503 || responseStatus == 504) retrying 5xx error codes</technical_language>

Target:
public boolean shouldBeRetried(URI uri, int retryCount, ClientResponse response, Throwable exception, Mode mode) { if (retryCount >= maxRetries) { LOG.warning(String.format("Retries exceeded. retryCount: %d - maxRetries: %d", retryCount+1, maxRetries)); return false; } if (response != null) { int responseStatus = response.getStatus(); if (responseStatus == 429 || responseStatus == 503) { LOG.info(String.format("Retrying request due to status %d, retryCount: %d - request: %s", responseStatus, retryCount+1, uri)); return true; } } if ((response != null) && (mode == Mode.RETRY_ALL)) { if (response.getStatusInfo().getFamily() == Response.Status.Family.SERVER_ERROR) { LOG.info(String.format("Retrying request due to Status %d. retryCount: %d - request: %s", response.getStatus(), retryCount+1, uri)); return true; } } return shouldBeRetried(uri, exception, mode); }
Source:
<code>public StreamTableDefinitionBuilder hashFirstNRowComponents(int numberOfComponentsHashed) { Preconditions.checkArgument(numberOfComponentsHashed <= 2, <START> "Can hash at most two row components for any StreamStore table."); <END> this.numberOfComponentsHashed = numberOfComponentsHashed; return this; }</code><technical_language>Lets standardize messages above. "The number of components " + "StreamStore internal tables row components.");</technical_language>

Target:
public StreamTableDefinitionBuilder hashFirstNRowComponents(int numberOfComponentsHashed) { Preconditions.checkArgument(numberOfComponentsHashed <= 2, "The number of components specified must be less than two as " + "StreamStore internal tables use at most two row components."); this.numberOfComponentsHashed = numberOfComponentsHashed; return this; }
Source:
<code>static void tryDestroy(final MultiUserChat muc) { try { if (muc != null) { muc.destroy("test fixture teardown", null); } } catch (Exception e) { } <START> } <END></code><technical_language>Try try-block small possible, swallow exceptions, catch Exception, instead try catch exception types possible. This java if (muc == null) { return; } try { muc.destory("test fixture teardown", null); } catch (XMPPErrorException | NoResponseException | NotConnectedException | InterruptedException e) { LOGGER.log(Level.FINE, "Exception while destroing MUC", e); }</technical_language>

Target:
static void tryDestroy(final MultiUserChat muc) { if (muc == null) { return; } try { muc.destroy("test fixture teardown", null); } catch (Exception ignore) { } }
Source:
<code>protected void awaitConsistency() { <START> if (!initialized) { <END> return; } if (view.getConsistencyModel() == ConsistencyModel.EVENTUAL) { Uninterruptibles.sleepUninterruptibly(AWAIT_CONSISTENCY_TIMEOUT_SECONDS, TimeUnit.SECONDS); } }</code><technical_language>This magical. Instead pass a flag createContainerAndEnsureEmpty controls call awaitConsistency</technical_language>

Target:
protected void awaitConsistency() { if (view.getConsistencyModel() == ConsistencyModel.EVENTUAL) { Uninterruptibles.sleepUninterruptibly(AWAIT_CONSISTENCY_TIMEOUT_SECONDS, TimeUnit.SECONDS); } }
Source:
<code>public void write(final A item) { if (this.isClosed) throw new RuntimeIOException("Attempt to add record to closed writer."); <START> this.nonBlockingCheckAndRethrow(); <END> try { while (!this.isClosed && !this.queue.offer(item, 5, TimeUnit.SECONDS)) { } } catch (InterruptedException e) { throw new RuntimeException("Exception while placing item in queue", e); } if (queue.size() >= this.writeThreshold && this.currentTask == null) { this.drain(); } }</code><technical_language>suggestion nonBlockingCheckAndRethrow(); FYI common practise in Java is prefix member _variables_ this. omit this. for method calls</technical_language>

Target:
public void write(final A item) { if (this.isClosed) throw new RuntimeIOException("Attempt to add record to closed writer."); nonBlockingCheckAndRethrow(); try { while (!this.isClosed && !this.queue.offer(item, 5, TimeUnit.SECONDS)) { } } catch (InterruptedException e) { throw new RuntimeException("Exception while placing item in queue", e); } if (this.currentTask == null && queue.size() >= this.writeThreshold) { drain(); } }
Source:
<code>public void testABlackHoleUrl() throws Exception { assumeThat(getAvailableNetworkInterface(), isAvailable()); Callable<String> downloadAttempt = () -> { AttachmentContent attachmentContent = mock(AttachmentContent.class); when(attachmentContent.getRemoteUrl()).thenReturn("http://" + BLACK_HOLE_ADDRESS + "/filename"); try (InputStream download = attachmentContentDownloader .download(attachmentContent, downloadTimeout)) { return CharStreams.toString(new InputStreamReader(download)); } }; ExecutorService executor = newSingleThreadExecutor(); try { Future<String> future = executor.submit(downloadAttempt); try { try { String read = future.get(1, TimeUnit.MINUTES); fail("downloader managed to escape with '" + read + "' from the black hole! " + "Try this test again with a more massive black hole"); } catch (ExecutionException e) { Throwable futureException = e.getCause(); assertThat(futureException, is(notNullValue())); <START> assertTrue(futureException instanceof SocketTimeoutException); <END> } } catch (TimeoutException e) { fail("downloader got stuck on a black hole"); throw e; } } finally { executor.shutdown(); executor.awaitTermination(1, TimeUnit.MINUTES); } }</code><technical_language>add SocketException IOException</technical_language>

Target:
public void testABlackHoleUrl() throws Exception { assumeThat(getAvailableNetworkInterface(), isAvailable()); Callable<String> downloadAttempt = () -> { AttachmentContent attachmentContent = mock(AttachmentContent.class); when(attachmentContent.getRemoteUrl()).thenReturn("http://" + BLACK_HOLE_ADDRESS + "/filename"); try (InputStream download = attachmentContentDownloader .download(attachmentContent, downloadTimeout)) { return CharStreams.toString(new InputStreamReader(download)); } }; ExecutorService executor = newSingleThreadExecutor(); try { Future<String> future = executor.submit(downloadAttempt); try { try { String read = future.get(1, TimeUnit.MINUTES); fail("downloader managed to escape with '" + read + "' from the black hole! " + "Try this test again with a more massive black hole"); } catch (ExecutionException e) { Throwable futureException = e.getCause(); assertThat(futureException, is(notNullValue())); assertTrue(futureException instanceof SocketException || futureException instanceof SocketTimeoutException); } } catch (TimeoutException e) { fail("downloader got stuck on a black hole"); throw e; } } finally { executor.shutdown(); executor.awaitTermination(1, TimeUnit.MINUTES); } }
Source:
<code>public IterableStream<T> getElements() { <START> return items == null <END> ? null : new IterableStream<T>(items); }</code><technical_language>question returning a null instead of empty collection type</technical_language>

Target:
public IterableStream<T> getElements() { return IterableStream.of(items); }
Source:
<code>public BitmapFontCache newFontCache () { for (int i = 0; i < regions.size; i++) { getRegion(i).getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear); <START> } <END> return new DistanceFieldFontCache(this, integer); }</code><technical_language>Bit strange do this time a font cache is created</technical_language>

Target:
public BitmapFontCache newFontCache () { return new DistanceFieldFontCache(this, integer); }
Source:
<code>Mono<PagedResponse<ModelData>> createModelsSinglePageAsync(List<String> models, Context context) { List<Object> modelsPayload = new ArrayList<>(); for (String model: models) { try { modelsPayload.add(mapper.readValue(model, Object.class)); } catch (JsonProcessingException e) { logger.error("Could not parse the model payload [%s]: %s", model, e); return Mono.error(e); } } return protocolLayer.getDigitalTwinModels().addWithResponseAsync(modelsPayload, context) .map( objectPagedResponse -> { List<ModelData> convertedList = objectPagedResponse.getValue().stream() <START> .map(object -> ModelDataConverter.map(object)) <END> .filter(Objects::nonNull) .collect(Collectors.toList()); return new PagedResponseBase<>( objectPagedResponse.getRequest(), objectPagedResponse.getStatusCode(), objectPagedResponse.getHeaders(), convertedList, null, ((PagedResponseBase) objectPagedResponse).getDeserializedHeaders()); } ); }</code><technical_language>method reference: .map(ModelDataConverter::map)</technical_language>

Target:
Mono<PagedResponse<ModelData>> createModelsSinglePageAsync(List<String> models, Context context) { List<Object> modelsPayload = new ArrayList<>(); for (String model: models) { try { modelsPayload.add(mapper.readValue(model, Object.class)); } catch (JsonProcessingException e) { logger.error("Could not parse the model payload [%s]: %s", model, e); return Mono.error(e); } } return protocolLayer.getDigitalTwinModels().addWithResponseAsync(modelsPayload, context) .map( objectPagedResponse -> { List<ModelData> convertedList = objectPagedResponse.getValue().stream() .map(ModelDataConverter::map) .filter(Objects::nonNull) .collect(Collectors.toList()); return new PagedResponseBase<>( objectPagedResponse.getRequest(), objectPagedResponse.getStatusCode(), objectPagedResponse.getHeaders(), convertedList, null, ((PagedResponseBase) objectPagedResponse).getDeserializedHeaders()); } ); }
Source:
<code>public synchronized void run() { if (operationsAreComplete()) { setRetryComplete(); return; } try { if (retryId == null) { retryId = Long.valueOf( asyncExecutor.getOperationAccountant().registerComplexOperation(createRetryHandler())); } long start = clock.nanoTime(); mutateRowsFuture = asyncExecutor.mutateRowsAsync(currentRequestManager.build()); long now = clock.nanoTime(); <START> BulkMutationsStats.getInstance().markThrottling(now - start); <END> currentRequestManager.lastRpcSentTimeNanos = now; } catch (InterruptedException e) { Thread.currentThread().interrupt(); mutateRowsFuture = Futures.<List<MutateRowsResponse>> immediateFailedFuture(e); } catch (Throwable e) { mutateRowsFuture = Futures.<List<MutateRowsResponse>> immediateFailedFuture(e); } finally { addCallback(mutateRowsFuture); } }</code><technical_language>This a bit weird. intending mutateRowsAsync blocking achieve throttling</technical_language>

Target:
public synchronized void run() { if (operationsAreComplete()) { setRetryComplete(); return; } try { if (retryId == null) { retryId = Long.valueOf( asyncExecutor.getOperationAccountant().registerComplexOperation(createRetryHandler())); } MutateRowsRequest request = currentRequestManager.build(); long start = clock.nanoTime(); long operationId = asyncExecutor.getOperationAccountant() .registerOperationWithHeapSize(request.getSerializedSize()); long now = clock.nanoTime(); BulkMutationsStats.getInstance().markThrottling(now - start); mutateRowsFuture = asyncExecutor.mutateRowsAsync(request, operationId); currentRequestManager.lastRpcSentTimeNanos = now; } catch (InterruptedException e) { Thread.currentThread().interrupt(); mutateRowsFuture = Futures.<List<MutateRowsResponse>> immediateFailedFuture(e); } catch (Throwable e) { mutateRowsFuture = Futures.<List<MutateRowsResponse>> immediateFailedFuture(e); } finally { addCallback(mutateRowsFuture); } }