auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Take route(final Request req) throws IOException { final Href href = new RqHref(req).href(); final String key = "file"; <START> final Iterator<String> param = href.param(key).iterator(); <END> final String file = this.filename(req, key, param); final Doc doc = this.base.user( new RqAuth(req).identity().urn() ).docs().doc(file); return new TsFork( new FkRegex("/doc/read", new TkRead(doc)), new FkRegex("/doc/delete", new TkDelete(doc)), new FkRegex( "/doc/write", new Takes() { @Override public Take route(final Request request) { return new TkWrite(doc, req); } } ), new FkRegex( "/doc/add-friend", new Takes() { @Override public Take route(final Request rst) throws IOException { return new TkAddFriend( doc, new RqForm(rst).param("friend").iterator().next() ); } } ), new FkRegex( "/doc/eject-friend", new Takes() { @Override public Take route(final Request rst) { return new TkEjectFriend( doc, href.param("friend").iterator().next() ); } } ) ).route(req); }</code><technical_language>@caarlos0 param inlined</technical_language>

Target:
public Take route(final Request req) throws IOException { final Href href = new RqHref(req).href(); final String key = "file"; final String file = this.filename( req, key, href.param(key).iterator() ); final Doc doc = this.base.user( new RqAuth(req).identity().urn() ).docs().doc(file); return new TsFork( new FkRegex("/doc/read", new TkRead(doc)), new FkRegex("/doc/delete", new TkDelete(doc)), new FkRegex( "/doc/write", new Takes() { @Override public Take route(final Request request) { return new TkWrite(doc, req); } } ), new FkRegex( "/doc/add-friend", new Takes() { @Override public Take route(final Request rst) throws IOException { return new TkAddFriend( doc, new RqForm(rst).param("friend").iterator().next() ); } } ), new FkRegex( "/doc/eject-friend", new Takes() { @Override public Take route(final Request rst) { return new TkEjectFriend( doc, href.param("friend").iterator().next() ); } } ) ).route(req); }
Source:
<code>private void addPropertyMapping(ElasticsearchMappingBuilder mappingBuilder, DocumentFieldMetadata fieldMetadata) { if ( fieldMetadata.getAbsoluteName().isEmpty() || fieldMetadata.getAbsoluteName().endsWith( "." ) || fieldMetadata.isSpatial() ) { return; } String propertyPath = fieldMetadata.getAbsoluteName(); PropertyMapping propertyMapping = new PropertyMapping(); addTypeOptions( propertyMapping, fieldMetadata ); propertyMapping.setStore( fieldMetadata.getStore() == Store.NO ? false : true ); addIndexOptions( propertyMapping, mappingBuilder, fieldMetadata.getSourceProperty(), fieldMetadata.getAbsoluteName(), fieldMetadata.getIndex(), fieldMetadata.getAnalyzerReference() ); propertyMapping.setBoost( mappingBuilder.getBoost( fieldMetadata.getBoost() ) ); logDynamicBoostWarning( mappingBuilder, fieldMetadata.getSourceType().getDynamicBoost(), propertyPath ); PropertyMetadata sourceProperty = fieldMetadata.getSourceProperty(); if ( sourceProperty != null ) { logDynamicBoostWarning( mappingBuilder, sourceProperty.getDynamicBoostStrategy(), propertyPath ); } addNullValue( propertyMapping, fieldMetadata ); for ( FacetMetadata facetMetadata : fieldMetadata.getFacetMetadata() ) { try { addFieldMapping( propertyMapping, mappingBuilder, facetMetadata ); } catch (IncompleteDataException e) { <START> LOG.debug( "Not adding a mapping for facet " + facetMetadata.getAbsoluteName() + " because of incomplete data", e ); <END> } } mappingBuilder.setPropertyAbsolute( propertyPath, propertyMapping ); }</code><technical_language>a debug level message</technical_language>

Target:
private void addPropertyMapping(ElasticsearchMappingBuilder mappingBuilder, DocumentFieldMetadata fieldMetadata) { if ( fieldMetadata.getAbsoluteName().isEmpty() || fieldMetadata.getAbsoluteName().endsWith( "." ) || fieldMetadata.isSpatial() ) { return; } String propertyPath = fieldMetadata.getAbsoluteName(); PropertyMapping propertyMapping = new PropertyMapping(); addTypeOptions( propertyMapping, fieldMetadata ); propertyMapping.setStore( fieldMetadata.getStore() == Store.NO ? false : true ); addIndexOptions( propertyMapping, mappingBuilder, fieldMetadata.getSourceProperty(), fieldMetadata.getAbsoluteName(), fieldMetadata.getIndex(), fieldMetadata.getAnalyzerReference() ); propertyMapping.setBoost( mappingBuilder.getBoost( fieldMetadata.getBoost() ) ); logDynamicBoostWarning( mappingBuilder, fieldMetadata.getSourceType().getDynamicBoost(), propertyPath ); PropertyMetadata sourceProperty = fieldMetadata.getSourceProperty(); if ( sourceProperty != null ) { logDynamicBoostWarning( mappingBuilder, sourceProperty.getDynamicBoostStrategy(), propertyPath ); } addNullValue( propertyMapping, fieldMetadata ); for ( FacetMetadata facetMetadata : fieldMetadata.getFacetMetadata() ) { try { addSubfieldMapping( propertyMapping, mappingBuilder, facetMetadata ); } catch (IncompleteDataException e) { LOG.debug( "Not adding a mapping for facet " + facetMetadata.getAbsoluteName() + " because of incomplete data", e ); } } mappingBuilder.setPropertyAbsolute( propertyPath, propertyMapping ); }
Source:
<code>public boolean matches(String packageName) { if (packageName == null || packageName.isEmpty()) { return false; } boolean result = false; for (Pattern pattern : patterns) { <START> result |= pattern.matcher(packageName).matches(); <END> } return result; }</code><technical_language>a otimization: if pattern matches, need check others. do this, write if (pattern.matcher(packageName).matches()) return true;</technical_language>

Target:
public boolean matches(String packageName) { if (StringUtils.isEmpty(packageName)) { return false; } for (Pattern pattern : patterns) { if (pattern.matcher(packageName).matches()) { return true; } } return false; }
Source:
<code><START> private static Filter pushDownNot(Filter current) <END> { if (current instanceof NotFilter) { Filter child = ((NotFilter) current).getBaseFilter(); if (child instanceof NotFilter) { return pushDownNot(((NotFilter) child).getBaseFilter()); } if (child instanceof AndFilter) { List<Filter> children = Lists.newArrayList(); for (Filter grandChild : ((AndFilter) child).getFilters()) { children.add(pushDownNot(new NotFilter(grandChild))); } return new OrFilter(children); } if (child instanceof OrFilter) { List<Filter> children = Lists.newArrayList(); for (Filter grandChild : ((OrFilter) child).getFilters()) { children.add(pushDownNot(new NotFilter(grandChild))); } return new AndFilter(children); } } if (current instanceof AndFilter) { List<Filter> children = Lists.newArrayList(); for (Filter child : ((AndFilter) current).getFilters()) { children.add(pushDownNot(child)); } return new AndFilter(children); } if (current instanceof OrFilter) { List<Filter> children = Lists.newArrayList(); for (Filter child : ((OrFilter) current).getFilters()) { children.add(pushDownNot(child)); } return new OrFilter(children); } return current; }</code><technical_language>mention part of NOTICE file this contains code adapted Apache Hive</technical_language>

Target:
private static Filter pushDownNot(Filter current) { if (current instanceof NotFilter) { Filter child = ((NotFilter) current).getBaseFilter(); if (child instanceof NotFilter) { return pushDownNot(((NotFilter) child).getBaseFilter()); } if (child instanceof AndFilter) { List<Filter> children = Lists.newArrayList(); for (Filter grandChild : ((AndFilter) child).getChildren()) { children.add(pushDownNot(new NotFilter(grandChild))); } return new OrFilter(children); } if (child instanceof OrFilter) { List<Filter> children = Lists.newArrayList(); for (Filter grandChild : ((OrFilter) child).getChildren()) { children.add(pushDownNot(new NotFilter(grandChild))); } return new AndFilter(children); } } if (current instanceof AndFilter) { List<Filter> children = Lists.newArrayList(); for (Filter child : ((AndFilter) current).getChildren()) { children.add(pushDownNot(child)); } return new AndFilter(children); } if (current instanceof OrFilter) { List<Filter> children = Lists.newArrayList(); for (Filter child : ((OrFilter) current).getChildren()) { children.add(pushDownNot(child)); } return new OrFilter(children); } return current; }
Source:
<code>private static File createTempStore(String storePath) { File f = null; try (InputStream trustStoreIs = CcmBridge.class.getResourceAsStream(storePath)) { f = File.createTempFile("server", ".store"); logger.debug("Created store file for {}.", f, storePath); try (OutputStream trustStoreOs = new FileOutputStream(f)) { byte[] buffer = new byte[1024]; int len; while ((len = trustStoreIs.read(buffer)) != -1) { trustStoreOs.write(buffer, 0, len); } } } catch (IOException e) { logger.warn("Failure to write keystore, SSL-enabled servers may fail to start.", e); } <START> if (f != null) { <END> f.deleteOnExit(); } return f; }</code><technical_language>This in a finally block for preceding try, I expect runtime exceptions out of block, this is fine is too</technical_language>

Target:
private static File createTempStore(String storePath) { File f = null; try (OutputStream os = new FileOutputStream(f = File.createTempFile("server", ".store"))) { f.deleteOnExit(); Resources.copy(CcmBridge.class.getResource(storePath), os); } catch (IOException e) { logger.warn("Failure to write keystore, SSL-enabled servers may fail to start.", e); } return f; }
Source:
<code>void onFillComplete() { buf.flip(); prepareForSending(); chunkReadyAtMs = time.milliseconds(); <START> routerMetrics.chunkFillTimeMs.update(chunkReadyAtMs - chunkFreeAtMs); <END> }</code><technical_language>metadata chunk data chunk treated in way, is a single metric reports chunkFillTime for chunk types</technical_language>

Target:
void onFillComplete() { buf.flip(); prepareForSending(); chunkReadyAtMs = time.milliseconds(); }
Source:
<code>public T getRowData() { <START> System.out.println("Hello"); <END> return null; }</code><technical_language>remove this</technical_language>

Target:
public T getRowData() { return this.rowVo; }
Source:
<code>public void setEnabled(boolean enabled) { if (isEnforcedDisabled()) { <START> this.enabled = SupportPlugin.AUTO_BUNDLE_PERIOD_HOURS >= 1; <END> } else { this.enabled = enabled; } }</code><technical_language>This is happen if is checking period hours is <= 0</technical_language>

Target:
public void setEnabled(boolean enabled) { this.enabled = !isEnforcedDisabled() && enabled; }
Source:
<code>public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); discussionResponsesRecyclerView.setLayoutManager(linearLayoutManager); courseDiscussionResponsesAdapter.setPaginationHandler(this); courseDiscussionResponsesAdapter.setDiscussionThread(discussionThread); discussionResponsesRecyclerView.setAdapter(courseDiscussionResponsesAdapter); getCommentList(true); if (discussionThread.isClosed()) { addResponseTextView.setText(R.string.discussion_add_response_disabled_title); <START> addResponseTextView.setCompoundDrawables( <END> new IconDrawable(getActivity(), Iconify.IconValue.fa_lock) .sizeRes(R.dimen.icon_view_standard_width_height) .colorRes(R.color.edx_grayscale_neutral_white_t), null, null, null ); addResponseLayout.setEnabled(false); } else { addResponseTextView.setText(R.string.discussion_responses_add_response_button); addResponseTextView.setCompoundDrawables( new IconDrawable(getActivity(), Iconify.IconValue.fa_plus_circle) .sizeRes(R.dimen.icon_view_standard_width_height) .colorRes(R.color.edx_grayscale_neutral_white_t), null, null, null ); addResponseLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { router.showCourseDiscussionAddResponse(getActivity(), discussionThread); } }); } }</code><technical_language>TextViewCompat.setCompoundDrawablesRelative() utility method set icon relatively, in a backward-compatible manner</technical_language>

Target:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); discussionResponsesRecyclerView.setLayoutManager(linearLayoutManager); courseDiscussionResponsesAdapter = new CourseDiscussionResponsesAdapter( getActivity().getApplicationContext(), this, discussionThread); discussionResponsesRecyclerView.setAdapter(courseDiscussionResponsesAdapter); getCommentList(true); DiscussionUtils.setStateOnTopicClosed(discussionThread.isClosed(), addResponseTextView, R.string.discussion_responses_add_response_button, R.string.discussion_add_response_disabled_title, addResponseLayout, new View.OnClickListener() { @Override public void onClick(View v) { router.showCourseDiscussionAddResponse(getActivity(), discussionThread); } }); }
Source:
<code>private void insertHorizontalLine() { addRow(new SafeHtml() { @Override public String asString() { <START> return "<p><hr size=\"2\" width=\"100%\"></p>"; END> } }); }</code><technical_language>please extract ApplicationTemplates.java for re-usage</technical_language>

Target:
private void insertHorizontalLine() { addRow(templates.horizontalLine()); }
Source:
<code><START> public boolean useLoginShell() { <END> String str = fRemoteConnection.getAttribute(USE_LOGIN_SHELL_ATTR); return str != null ? Boolean.parseBoolean(str) : DEFAULT_USE_LOGIN_SHELL; }</code><technical_language>some time track down, this is returning false return true. This is causing remote commands break escaped properly. is a separate problem (a bug in original implementation, I think), this attribute needs fixed also</technical_language>

Target:
public boolean useLoginShell() { String str = fRemoteConnection.getAttribute(USE_LOGIN_SHELL_ATTR); return !str.isEmpty() ? Boolean.parseBoolean(str) : DEFAULT_USE_LOGIN_SHELL; }
Source:
<code>private KieCompilationResponse handleNormalBuild(final CompilationRequest req, final CompilationResponse res) { final List<String> targetContent = getStringFromTargets(req.getInfo().getPrjPath()); if (res.isSuccessful()) { return new DefaultKieCompilationResponse(res.isSuccessful(), null, null, null, res.getMavenOutput(), targetContent, res.getDependencies(), req.getInfo().getPrjPath(), null); } else { <START> return new DefaultKieCompilationResponse(res.isSuccessful(), new ArrayList<>(res.getMavenOutput()), req.getInfo().getPrjPath()); <END> } }</code><technical_language>downcast ArrayList? constructor expects List res.getMavenOutput returns List.</technical_language>

Target:
private KieCompilationResponse handleNormalBuild(final CompilationRequest req, final CompilationResponse res) { final List<String> targetContent = getStringFromTargets(req.getInfo().getPrjPath()); if (res.isSuccessful()) { return new DefaultKieCompilationResponse(res.isSuccessful(), res.getMavenOutput(), targetContent, res.getDependencies(), req.getInfo().getPrjPath()); } else { return new DefaultKieCompilationResponse(res.isSuccessful(), res.getMavenOutput(), req.getInfo().getPrjPath()); } }
Source:
<code>private static void checkMessages() { AuditLogType[] values = AuditLogType.values(); if (values.length != messages.size()) { for (AuditLogType value : values) { if (!messages.containsKey(value)) { <START> log.info("AuditLogType: '{}' not exist in string table", value.toString()); <END> } } } }</code><technical_language>drop toString()</technical_language>

Target:
private static void checkMessages() { AuditLogType[] values = AuditLogType.values(); if (values.length != messages.size()) { for (AuditLogType value : values) { if (!messages.containsKey(value)) { log.info("AuditLogType: '{}' not exist in string table", value); } } } }
Source:
<code>protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { String type = "fireball"; double speed = 2; boolean ride = false; if (args.length > 0 && types.containsKey(args[0])) { type = args[0]; } if (args.length > 1) { try { speed = FloatUtil.parseDouble(args[1]); speed = Double.max(0, Double.min(speed, ess.getSettings().getMaxProjectileSpeed())); } catch (Exception ignored) { } } if (args.length > 2 && args[2].equalsIgnoreCase("ride") && user.isAuthorized("essentials.fireball.ride")) { ride = true; } if (!user.isAuthorized("essentials.fireball." + type)) { throw new Exception(tl("noPerm", "essentials.fireball." + type)); } final Vector direction = user.getBase().getEyeLocation().getDirection().multiply(speed); Projectile projectile = user.getWorld().spawn(user.getBase().getEyeLocation().add(direction.getX(), direction.getY(), direction.getZ()), types.get(type)); projectile.setShooter(user.getBase()); projectile.setVelocity(direction); projectile.setCustomName("Fireball Arrow"); <START> projectile.setCustomNameVisible(false); <END> if (ride) { projectile.addPassenger(user.getBase()); } }</code><technical_language>I suggest metadata check item is checked correctly similar other items "Fireball Arrow" name</technical_language>

Target:
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { String type = "fireball"; double speed = 2; boolean ride = false; if (args.length > 0 && types.containsKey(args[0])) { type = args[0]; } if (args.length > 1) { try { speed = FloatUtil.parseDouble(args[1]); speed = Double.max(0, Double.min(speed, ess.getSettings().getMaxProjectileSpeed())); } catch (Exception ignored) { } } if (args.length > 2 && args[2].equalsIgnoreCase("ride") && user.isAuthorized("essentials.fireball.ride")) { ride = true; } if (!user.isAuthorized("essentials.fireball." + type)) { throw new Exception(tl("noPerm", "essentials.fireball." + type)); } final Vector direction = user.getBase().getEyeLocation().getDirection().multiply(speed); Projectile projectile = user.getWorld().spawn(user.getBase().getEyeLocation().add(direction.getX(), direction.getY(), direction.getZ()), types.get(type)); projectile.setShooter(user.getBase()); projectile.setVelocity(direction); projectile.setMetadata("Ess_Fireball_Projectile", new FixedMetadataValue(ess, true)); if (ride) { projectile.addPassenger(user.getBase()); } }
Source:
<code>public DocumentModel createEntry(Map<String, Object> fieldMap) throws DirectoryException { checkPermission(SecurityConstants.WRITE); DocumentModel docModel = createEntryWithoutReferences(fieldMap); String idFieldName = schemaFieldMap != null ? schemaFieldMap.get(getIdField()).getName().getPrefixedName() : getIdField(); String sourceId = docModel.getId(); for (Reference reference : getDirectory().getReferences()) { String referenceFieldName = schemaFieldMap.get(reference.getFieldName()).getName().getPrefixedName(); if (getDirectory().getReferences(reference.getFieldName()).size() > 1) { log.warn("Directory " + getDirectory().getName() + " cannot create field " + reference.getFieldName() + " for entry " + fieldMap.get(idFieldName) + ": this field is associated with more than one reference"); continue; } @SuppressWarnings("unchecked") List<String> targetIds = (List<String>) fieldMap.get(referenceFieldName); <START> if (reference.getClass() == referenceClassName) { <END> reference.addLinks(sourceId, targetIds, this); } else { reference.addLinks(sourceId, targetIds); } } getDirectory().invalidateCaches(); return docModel; }</code><technical_language>Do support a reference instance extending referenceClassName</technical_language>

Target:
public DocumentModel createEntry(Map<String, Object> fieldMap) throws DirectoryException { checkPermission(SecurityConstants.WRITE); DocumentModel docModel = createEntryWithoutReferences(fieldMap); String idFieldName = schemaFieldMap != null ? schemaFieldMap.get(getIdField()).getName().getPrefixedName() : getIdField(); Object entry = fieldMap.get(idFieldName); String sourceId = docModel.getId(); for (Reference reference : getDirectory().getReferences()) { String referenceFieldName = schemaFieldMap.get(reference.getFieldName()).getName().getPrefixedName(); if (getDirectory().getReferences(reference.getFieldName()).size() > 1) { if (log.isWarnEnabled()) { log.warn("Directory " + directoryName + " cannot create field " + reference.getFieldName() + " for entry " + entry + ": this field is associated with more than one reference"); } continue; } @SuppressWarnings("unchecked") List<String> targetIds = (List<String>) fieldMap.get(referenceFieldName); if (reference.getClass() == referenceClass) { reference.addLinks(sourceId, targetIds, this); } else { reference.addLinks(sourceId, targetIds); } } getDirectory().invalidateCaches(); return docModel; }
Source:
<code>public List<VariableMetadata> findByDataVarIdAndFileMetaId(Long datVarId, Long metaId) { TypedQuery<VariableMetadata> query = em.createQuery("SELECT object(o) FROM VariableMetadata as o where o.dataVariable.id =:value1 and o.fileMetadata.id =:value2", VariableMetadata.class); query.setParameter("value1", datVarId); <START> query.setParameter("value2", metaId); <END> return query.getResultList(); }</code><technical_language>Is a reason called "value1" "value2" instead of more meaningful names</technical_language>

Target:
public List<VariableMetadata> findByDataVarIdAndFileMetaId(Long datVarId, Long metaId) { TypedQuery<VariableMetadata> query = em.createQuery("SELECT object(o) FROM VariableMetadata as o where o.dataVariable.id =:dvId and o.fileMetadata.id =:fmId", VariableMetadata.class); query.setParameter("dvId", datVarId); query.setParameter("fmId", metaId); return query.getResultList(); }
Source:
<code>private Map<String, ResourceAssignment> getBaselineAssignment( AssignmentMetadataStore assignmentMetadataStore, CurrentStateOutput currentStateOutput, Set<String> resources) throws HelixRebalanceException { Map<String, ResourceAssignment> currentBaseline = Collections.emptyMap(); if (assignmentMetadataStore != null) { try { LatencyMetric stateReadLatency = _metricCollector.getMetric( WagedRebalancerMetricCollector.WagedRebalancerMetricNames.StateReadLatencyGauge.name(), LatencyMetric.class); stateReadLatency.startMeasuringLatency(); currentBaseline = assignmentMetadataStore.getBaseline(); stateReadLatency.endMeasuringLatency(); } catch (Exception ex) { throw new HelixRebalanceException( "Failed to get the current baseline assignment because of unexpected error.", HelixRebalanceException.Type.INVALID_REBALANCER_STATUS, ex); } } if (currentBaseline.isEmpty()) { LOG.warn("The current baseline assignment record is empty. Use the current states instead."); <START> currentBaseline = currentStateOutput.getCurrentStateAssignment(resources); <END> } currentBaseline.keySet().retainAll(resources); return currentBaseline; }</code><technical_language>This method name is verbose, call getAssignment()</technical_language>

Target:
private Map<String, ResourceAssignment> getBaselineAssignment( AssignmentMetadataStore assignmentMetadataStore, CurrentStateOutput currentStateOutput, Set<String> resources) throws HelixRebalanceException { Map<String, ResourceAssignment> currentBaseline = Collections.emptyMap(); if (assignmentMetadataStore != null) { try { LatencyMetric stateReadLatency = _metricCollector.getMetric( WagedRebalancerMetricCollector.WagedRebalancerMetricNames.StateReadLatencyGauge.name(), LatencyMetric.class); stateReadLatency.startMeasuringLatency(); currentBaseline = assignmentMetadataStore.getBaseline(); stateReadLatency.endMeasuringLatency(); } catch (Exception ex) { throw new HelixRebalanceException( "Failed to get the current baseline assignment because of unexpected error.", HelixRebalanceException.Type.INVALID_REBALANCER_STATUS, ex); } } if (currentBaseline.isEmpty()) { LOG.warn("The current baseline assignment record is empty. Use the current states instead."); currentBaseline = currentStateOutput.getAssignment(resources); } currentBaseline.keySet().retainAll(resources); return currentBaseline; }
Source:
<code>public void getConceptsCount_shouldGetCorrectConceptCount() { mDatabase.conceptRoomDAO().addConcept(expectedConceptEntity1); mDatabase.conceptRoomDAO().addConcept(expectedConceptEntity2); long count = mDatabase.conceptRoomDAO().getConceptsCount(); Assert.assertEquals(count, 2L); <START> } <END></code><technical_language>do local variable @rishabh-997</technical_language>

Target:
public void getConceptsCount_shouldGetCorrectConceptCount() { mDatabase.conceptRoomDAO().addConcept(expectedConceptEntity1); mDatabase.conceptRoomDAO().addConcept(expectedConceptEntity2); Assert.assertEquals(mDatabase.conceptRoomDAO().getConceptsCount(), 2L); }
Source:
<code>public void testFindAllByOrderByCacheVersionDescVepVersionDescCacheVersionOrder() throws Exception { List<AnnotationMetadata> annotationMetadataList = repository.findAllByOrderByCacheVersionDescVepVersionDesc(); AnnotationMetadata prevAnnotationMetadata = annotationMetadataList.get(0); for (AnnotationMetadata curAnnotationMetadata : annotationMetadataList.subList(1, annotationMetadataList.size())) { assertTrue(Integer.parseInt(curAnnotationMetadata.getCacheVersion()) <START> <= Integer.parseInt(prevAnnotationMetadata.getCacheVersion())); <END> } }</code><technical_language>If force this a numeric comparison some values fail: * 99 < 100 numbers * 100 < 99 strings string comparison, database do. applies method below</technical_language>

Target:
public void testFindAllByOrderByCacheVersionDescVepVersionDescCacheVersionOrder() throws Exception { List<AnnotationMetadata> annotationMetadataList = repository.findAllByOrderByCacheVersionDescVepVersionDesc(); AnnotationMetadata prevAnnotationMetadata = annotationMetadataList.get(0); for (AnnotationMetadata curAnnotationMetadata : annotationMetadataList.subList(1, annotationMetadataList.size())) { assertTrue(curAnnotationMetadata.getCacheVersion().compareTo(prevAnnotationMetadata.getCacheVersion()) <= 0); } }
Source:
<code>protected boolean executeAnalysis(@Nullable IProgressMonitor monitor) { ITmfTrace trace = getTrace(); if (monitor == null || trace == null) { return false; } for (IAnalysisModule module : getDependentAnalyses()) { if (!(module instanceof AbstractCallStackAnalysis)) { return false; } <START> AbstractCallStackAnalysis callstackModule = (AbstractCallStackAnalysis) module; <END> callstackModule.waitForCompletion(); ITmfStateSystem ss = callstackModule.getStateSystem(); if (ss == null) { return false; } List<Integer> processQuarks = ss.getQuarks(callstackModule.getProcessesPattern()); String @NonNull callStackPath = callstackModule.getCallStackPath(); for (int processQuark : processQuarks) { for (int threadQuark : ss.getQuarks(processQuark, callstackModule.getThreadsPattern())) { if (!iterateOverQuark(ss, threadQuark, callStackPath, monitor)) { return false; } } } sendUpdate(fStore); } monitor.worked(1); monitor.done(); return true; }</code><technical_language>schedule analysis</technical_language>

Target:
protected boolean executeAnalysis(@Nullable IProgressMonitor monitor) { ITmfTrace trace = getTrace(); if (monitor == null || trace == null) { return false; } for (IAnalysisModule module : getDependentAnalyses()) { if (!(module instanceof AbstractCallStackAnalysis)) { return false; } AbstractCallStackAnalysis callstackModule = (AbstractCallStackAnalysis) module; callstackModule.schedule(); callstackModule.waitForCompletion(); ITmfStateSystem ss = callstackModule.getStateSystem(); if (ss == null) { return false; } List<Integer> processQuarks = ss.getQuarks(callstackModule.getProcessesPattern()); String @NonNull callStackPath = callstackModule.getCallStackPath(); for (int processQuark : processQuarks) { for (int threadQuark : ss.getQuarks(processQuark, callstackModule.getThreadsPattern())) { if (!iterateOverQuark(ss, threadQuark, callStackPath, monitor)) { return false; } } } sendUpdate(fStore); } monitor.worked(1); monitor.done(); return true; }
Source:
<code>public int hashCode() { int result = 17; result += 37 * Long.hashCode(duration); <START> result += 37 * Arrays.hashCode(channels); <END> return result; }</code><technical_language>If polynomial hash function, 37 * 37 instead of 37</technical_language>

Target:
public int hashCode() { int result = 17; result += 37 * 37 * Long.hashCode(duration); result += 37 * Arrays.hashCode(channels); return result; }
Source:
<code>ServiceBusReceiverException(Throwable throwable, ServiceBusErrorSource errorSource) { <START> super(throwable.getMessage(), throwable.getCause()); <END> this.errorSource = errorSource; }</code><technical_language>wrapping exception, throwable cause</technical_language>

Target:
ServiceBusReceiverException(Throwable throwable, ServiceBusErrorSource errorSource) { super(throwable.getMessage(), throwable); this.errorSource = errorSource; }
Source:
<code>public Iterator<T> iterator() { if (isClosed()) { throw new IllegalStateException("A Cursor is already closed."); } if (iteratorRetrieved) { throw new IllegalStateException("Cannot open more than one iterator on a Cursor"); <START> } <END> iteratorRetrieved = true; return cursorIterator; }</code><technical_language>check isClosed() checking iteratorRetrieved error message is more specific</technical_language>

Target:
public Iterator<T> iterator() { if (iteratorRetrieved) { throw new IllegalStateException("Cannot open more than one iterator on a Cursor"); } if (isClosed()) { throw new IllegalStateException("A Cursor is already closed."); } iteratorRetrieved = true; return cursorIterator; }
Source:
<code>public void placeNewOrder(Market m, String symbol, int volume, double price, OrderType orderType) throws StockMarketException { double costOfPurchase = price * volume; switch (orderType){ <START> case BUY: <END> StockMarketAssert.AssertOrderDoesNotExist(symbol, this.name, ordersPlaced); StockMarketAssert.AssertCashIsAvailable(symbol, this.name, costOfPurchase, cashInHand); BuyOrder newBuyOrder = new BuyOrder(symbol, volume, price, this); ordersPlaced.add(newBuyOrder); m.addBuyOrder(newBuyOrder); break; case SELL: StockMarketAssert.AssertOrderDoesNotExist(symbol, this.name, ordersPlaced); StockMarketAssert.AssertTraderOwnsEnoughStock(symbol, this.name, this.position, volume); SellOrder newSellOrder = new SellOrder(symbol, volume, price, this); ordersPlaced.add(newSellOrder); m.addSellOrder(newSellOrder); break; } }</code><technical_language>consider extracting method for buy sell cases</technical_language>

Target:
public void placeNewOrder(Market m, String symbol, int volume, double price, OrderType orderType) throws StockMarketException { double costOfPurchase = price * volume; switch (orderType){ case BUY: placeNewBuyOrder(m, symbol, volume, price); break; case SELL: placeNewSellOrder(m, symbol, volume, price); break; } }
Source:
<code>public void setTrace(ITmfTrace trace) throws TmfAnalysisException { if (trace == null) { throw new TmfAnalysisException(Messages.TmfAbstractAnalysisModule_NullTrace); } <START> ITmfTrace prevTrace = getTrace(); <END> if (prevTrace != null) { throw new TmfAnalysisException(NLS.bind(Messages.TmfAbstractAnalysisModule_TraceSetMoreThanOnce, getName())); } if (!canExecute(trace)) { throw new TmfAnalysisException(NLS.bind(Messages.TmfAbstractAnalysisModule_AnalysisCannotExecute, getName())); } synchronized (syncObj) { fTrace = trace; } fParameterProviders = TmfAnalysisManager.getParameterProviders(this, trace); for (IAnalysisParameterProvider provider : fParameterProviders) { provider.registerModule(this); } resetAnalysis(); fStarted = false; }</code><technical_language>I reference assignment is atomic this change some other difference</technical_language>

Target:
public void setTrace(ITmfTrace trace) throws TmfAnalysisException { if (trace == null) { throw new TmfAnalysisException(Messages.TmfAbstractAnalysisModule_NullTrace); } if (fTrace != null) { throw new TmfAnalysisException(NLS.bind(Messages.TmfAbstractAnalysisModule_TraceSetMoreThanOnce, getName())); } if (!canExecute(trace)) { throw new TmfAnalysisException(NLS.bind(Messages.TmfAbstractAnalysisModule_AnalysisCannotExecute, getName())); } fTrace = trace; fParameterProviders = TmfAnalysisManager.getParameterProviders(this, trace); for (IAnalysisParameterProvider provider : fParameterProviders) { provider.registerModule(this); } resetAnalysis(); fStarted = false; }
Source:
<code>public void processTuple(byte[] tuple) { if (tuple == null) { if (err.isConnected()) { err.emit(new KeyValPair<String, String>(null, "null tuple")); } errorTupleCount++; return; } String incomingString = new String(tuple); try { <START> if (schema != null) { <END> ProcessingReport report = null; JsonNode data = JsonLoader.fromString(incomingString); report = schema.validate(data); if (report != null && !report.isSuccess()) { Iterator<ProcessingMessage> iter = report.iterator(); StringBuilder s = new StringBuilder(); while (iter.hasNext()) { ProcessingMessage pm = iter.next(); s.append(pm.asJson().get("instance").findValue("pointer")).append(":").append(pm.asJson().get("message")) .append(","); } s.setLength(s.length() - 1); errorTupleCount++; err.emit(new KeyValPair<String, String>(incomingString, s.toString())); return; } } if (parsedOutput.isConnected()) { parsedOutput.emit(new JSONObject(incomingString)); parsedOutputCount++; } if (out.isConnected()) { out.emit(objMapper.readValue(tuple, clazz)); emittedObjectCount++; } } catch (JSONException | ProcessingException | IOException e) { errorTupleCount++; err.emit(new KeyValPair<String, String>(incomingString, e.getMessage())); logger.error("Failed to parse json tuple {}, Exception = ", tuple, e); } }</code><technical_language>validation is required if error port is connected, condition schema != null && err.isConnected()</technical_language>

Target:
public void processTuple(byte[] tuple) { if (tuple == null) { if (err.isConnected()) { err.emit(new KeyValPair<String, String>(null, "null tuple")); } errorTupleCount++; return; } String incomingString = new String(tuple); try { if (schema != null) { ProcessingReport report = null; JsonNode data = JsonLoader.fromString(incomingString); report = schema.validate(data); if (report != null && !report.isSuccess()) { Iterator<ProcessingMessage> iter = report.iterator(); StringBuilder s = new StringBuilder(); while (iter.hasNext()) { ProcessingMessage pm = iter.next(); s.append(pm.asJson().get("instance").findValue("pointer")).append(":").append(pm.asJson().get("message")) .append(","); } s.setLength(s.length() - 1); errorTupleCount++; if (err.isConnected()) { err.emit(new KeyValPair<String, String>(incomingString, s.toString())); } return; } } if (parsedOutput.isConnected()) { parsedOutput.emit(new JSONObject(incomingString)); parsedOutputCount++; } if (out.isConnected()) { out.emit(objMapper.readValue(tuple, clazz)); emittedObjectCount++; } } catch (JSONException | ProcessingException | IOException e) { errorTupleCount++; if (err.isConnected()) { err.emit(new KeyValPair<String, String>(incomingString, e.getMessage())); } logger.error("Failed to parse json tuple {}, Exception = ", tuple, e); } }
Source:
<code>private void display() throws Failure { final PrintWriter stdout = toPrintWriter(out); try { for (final Project p : db.projects().all()) { if (p.getNameKey().equals(wildProject)) { continue; } final ProjectState e = projectCache.get(p.getNameKey()); if (e != null && e.controlFor(currentUser).isVisible()) { if (showBranch != null) { ObjectId id = getObjectIdForBranch(p.getNameKey(), showBranch); <START> if (id != null) { <END> stdout.print(ObjectId.toString(id) + " "); } } stdout.print(p.getName()); stdout.println(); } } } catch (OrmException e) { throw new Failure(1, "fatal: database error", e); } finally { stdout.flush(); } }</code><technical_language>If id is null, resolution failed. show project? If do, show unambiguous branch exist? E.g. display 40 "0" instead of ObjectId</technical_language>

Target:
private void display() throws Failure { final PrintWriter stdout = toPrintWriter(out); try { for (final Project p : db.projects().all()) { if (p.getNameKey().equals(wildProject)) { continue; } final ProjectState e = projectCache.get(p.getNameKey()); if (e != null && e.controlFor(currentUser).isVisible()) { if (showBranch != null) { ObjectId id = getObjectIdForBranch(p.getNameKey(), showBranch); if (id != null) { stdout.print(id.name() + " "); stdout.print(p.getName()); stdout.println(); } } } } catch (OrmException e) { throw new Failure(1, "fatal: database error", e); } finally { stdout.flush(); } } }
Source:
<code>public void add(int[] values, int length) { for (int i = 0; i < length; i++) { addValueToBuffer(values[i]); <START> nextDoc(); <END> } nextDoc(); }</code><technical_language>(CRITICAL) This is correct. add _nextValueId instead of _nextDocId</technical_language>

Target:
public void add(int[] values, int length) { for (int i = 0; i < length; i++) { _numberValueBuffer.put(_nextValueId, values[i]); _docIdBuffer.put(_nextValueId, _nextDocId); _nextValueId++; } _nextDocId++; }
Source:
<code>public boolean equals(final Object obj) { if (obj == this) { return true; } if (obj instanceof List == false) { return false; } final List<?> other = (List<?>) obj; if (other.size() != size()) { return false; } final ListIterator<?> it1 = listIterator(); final ListIterator<?> it2 = other.listIterator(); while (it1.hasNext() && it2.hasNext()) { final Object o1 = it1.next(); final Object o2 = it2.next(); <START> if (!(Objects.equals(o1, o2))) { <END> return false; } } return !(it1.hasNext() || it2.hasNext()); }</code><technical_language>in-lining o1 o2 reused</technical_language>

Target:
public boolean equals(final Object obj) { if (obj == this) { return true; } if (obj instanceof List == false) { return false; } final List<?> other = (List<?>) obj; if (other.size() != size()) { return false; } final ListIterator<?> it1 = listIterator(); final ListIterator<?> it2 = other.listIterator(); while (it1.hasNext() && it2.hasNext()) { if (!(Objects.equals(it1.next(), it2.next()))) { return false; } } return !(it1.hasNext() || it2.hasNext()); }
Source:
<code>public static IssuerFraudRecord retrieve(String id) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { String url = instanceURL(IssuerFraudRecord.class, id); return request(RequestMethod.GET, url, null, IssuerFraudRecord.class, null); <START> } <END></code><technical_language>add a variant for retrieve takes a RequestOptions for list below? Thanks</technical_language>

Target:
public static IssuerFraudRecord retrieve(String id) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return retrieve(id, null); }
Source:
<code>public ArrayList<DiskInterface> getDiskInterfaceList() { return new ArrayList<>( Arrays.asList( <START> DiskInterface.IDE, DiskInterface.VirtIO, DiskInterface.VirtIO_SCSI, DiskInterface.SPAPR_VSCSI, DiskInterface.SATA <END> )); }</code><technical_language>reason replace DiskInterface.values()</technical_language>

Target:
public ArrayList<DiskInterface> getDiskInterfaceList() { return new ArrayList<>(Arrays.asList(DiskInterface.values())); }
Source:
<code><START> public void setValue(long value) { <END> this.value = value; }</code><technical_language>setters anywhere</technical_language>

Target:
void setValue(long value) { this.value = value; }
Source:
<code>public List<SourceWithKeys> splitIntoBundles( long desiredBundleSizeBytes, PipelineOptions options) throws Exception { Scan scan = configuration.getScan(); byte[] scanStartKey = scan.getStartRow(); byte[] scanEndKey = scan.getStopRow(); List<SourceWithKeys> splits = new ArrayList<>(); byte[] startKey = HConstants.EMPTY_START_ROW; long lastOffset = 0; for (SampleRowKeysResponse response : getSampleRowKeys()) { byte[] endKey = response.getRowKey().toByteArray(); if (Bytes.equals(startKey, endKey) && startKey.length > 0) { continue; } long offset = response.getOffsetBytes(); if (isWithinRange(scanStartKey, scanEndKey, startKey, endKey)) { byte[] splitStart = null; byte[] splitStop = null; if (scanStartKey.length == 0 || Bytes.compareTo(startKey, scanStartKey) >= 0) { splitStart = startKey; } else { splitStart = scanStartKey; } if ((scanEndKey.length == 0 || Bytes.compareTo(endKey, scanEndKey) <= 0) && endKey.length > 0) { splitStop = endKey; } else { splitStop = scanEndKey; } splits.addAll(split(offset - lastOffset, desiredBundleSizeBytes, splitStart, splitStop)); } lastOffset = offset; startKey = endKey; } byte[] endKey = HConstants.EMPTY_END_ROW; if (!Bytes.equals(startKey, endKey) && scanEndKey.length == 0) { splits.add(new SourceWithKeys(startKey, endKey, 0)); } LOG.info(String.format("Creating %d splits.", splits.size())); if (LOG.isDebugEnabled()) { <START> for (SourceWithKeys split : splits) { <END> LOG.debug("Created split {}", split); } } return splits; }</code><technical_language>LOG.debug("Created splits {}", splits);</technical_language>

Target:
public List<SourceWithKeys> splitIntoBundles( long desiredBundleSizeBytes, PipelineOptions options) throws Exception { Scan scan = configuration.getScan(); byte[] scanStartKey = scan.getStartRow(); byte[] scanEndKey = scan.getStopRow(); List<SourceWithKeys> splits = new ArrayList<>(); byte[] startKey = HConstants.EMPTY_START_ROW; long lastOffset = 0; for (SampleRowKeysResponse response : getSampleRowKeys()) { byte[] endKey = response.getRowKey().toByteArray(); if (Bytes.equals(startKey, endKey) && startKey.length > 0) { continue; } long offset = response.getOffsetBytes(); if (isWithinRange(scanStartKey, scanEndKey, startKey, endKey)) { byte[] splitStart = null; byte[] splitStop = null; if (scanStartKey.length == 0 || Bytes.compareTo(startKey, scanStartKey) >= 0) { splitStart = startKey; } else { splitStart = scanStartKey; } if ((scanEndKey.length == 0 || Bytes.compareTo(endKey, scanEndKey) <= 0) && endKey.length > 0) { splitStop = endKey; } else { splitStop = scanEndKey; } splits.addAll(split(offset - lastOffset, desiredBundleSizeBytes, splitStart, splitStop)); } lastOffset = offset; startKey = endKey; } byte[] endKey = HConstants.EMPTY_END_ROW; if (!Bytes.equals(startKey, endKey) && scanEndKey.length == 0) { splits.add(new SourceWithKeys(startKey, endKey, 0)); } LOG.info("Creating splits.", splits.size()); LOG.debug("Created splits {}.", splits); return splits; }
Source:
<code>public void configure(HttpSecurity http) throws Exception { ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests(); for (String protectedPath : PROTECTED_PATHS) { registry = registry.antMatchers(protectedPath).hasRole(TokenAuthentication.ROLE); } for (PathMappedEndpoint actuatorEndpoint : actuatorEndpoints) { final String rootPath = actuatorEndpoint.getRootPath(); final boolean enforceTokenUsage; <START> if (allowPrometheusUnauthenticatedAccess && "prometheus".equals(rootPath)) { <END> enforceTokenUsage = false; LOGGER.info("======= ALLOW UNAUTHENTICATED ACCESS TO PROMETHEUS (DEV MODE ONLY!) ======="); } else { enforceTokenUsage = true; } final ExpressionUrlAuthorizationConfigurer<HttpSecurity>.AuthorizedUrl matcher = registry.antMatchers(webEndpointProperties.getBasePath() + "/" + rootPath + "**"); if (enforceTokenUsage) { registry = matcher.hasRole(TokenAuthentication.ROLE); } else { registry = matcher.permitAll(); } } registry.and().addFilterAfter(tokenAuthenticationFilter, BasicAuthenticationFilter.class); }</code><technical_language>This condition work in current kubernetes setup for example. For spring-boot service deployed in kubernetes want automatically integrated prometheus collector this in service configuration yaml management: server: port: 9002 endpoints: web: base-path: / exposure: include: health,info,prometheus,bindings path-mapping: prometheus: metrics In current setup of operator custom configuration override path for prometheus endpoint. equals root path is nice work for of talend services. proposal EndpointId abstraction java if (allowPrometheusUnauthenticatedAccess && actuatorEndpoint.equals(actuatorEndpoints.get(EndpointId.of("prometheus"))) { ... }</technical_language>

Target:
public void configure(HttpSecurity http) throws Exception { ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests(); for (String protectedPath : PROTECTED_PATHS) { registry = registry.antMatchers(protectedPath).hasRole(TokenAuthentication.ROLE); } final PathMappedEndpoint prometheus = actuatorEndpoints.getEndpoint(EndpointId.of("prometheus")); for (PathMappedEndpoint actuatorEndpoint : actuatorEndpoints) { final String rootPath = actuatorEndpoint.getRootPath(); final boolean enforceTokenUsage; if (allowPrometheusUnauthenticatedAccess && actuatorEndpoint.equals(prometheus)) { enforceTokenUsage = false; LOGGER.info("======= ALLOW UNAUTHENTICATED ACCESS TO PROMETHEUS (DEV MODE ONLY!) ======="); } else { enforceTokenUsage = true; } final ExpressionUrlAuthorizationConfigurer<HttpSecurity>.AuthorizedUrl matcher = registry .antMatchers(webEndpointProperties.getBasePath() + "/" + rootPath + "**"); if (enforceTokenUsage) { registry = matcher.hasRole(TokenAuthentication.ROLE); } else { registry = matcher.permitAll(); } } registry.and().addFilterAfter(tokenAuthenticationFilter, BasicAuthenticationFilter.class); }
Source:
<code>public void testUpsertingDeletedRowWithNullCoveredColumn(boolean multiCf) throws Exception { String tableName = "TBL_" + generateUniqueName(); String indexName = "IDX_" + generateUniqueName(); String columnFamily1 = "cf1"; String columnFamily2 = "cf2"; String fullTableName = SchemaUtil.getTableName(TestUtil.DEFAULT_SCHEMA_NAME, tableName); String fullIndexName = SchemaUtil.getTableName(TestUtil.DEFAULT_SCHEMA_NAME, indexName); try (Connection conn = getConnection()) { conn.createStatement() .execute("create table " + fullTableName + " (id integer primary key, " <START> + (multiCf ? columnFamily1 : "") + "f varchar, " <END> + (multiCf ? columnFamily2 : "") + "s varchar)" + tableDDLOptions); conn.createStatement() .execute("create " + (localIndex ? "LOCAL" : "") + " index " + indexName + " on " + fullTableName + " (" + (multiCf ? columnFamily1 : "") + "f) include (" + (multiCf ? columnFamily2 : "") + "s)"); conn.createStatement() .execute("upsert into " + fullTableName + " values (1, 'foo', 'bar')"); conn.commit(); conn.createStatement().execute("delete from " + fullTableName + " where id = 1"); conn.commit(); conn.createStatement() .execute("upsert into " + fullTableName + " values (1, null, 'bar')"); conn.commit(); ResultSet rs = conn.createStatement().executeQuery("select * from " + fullIndexName); assertTrue(rs.next()); assertEquals(1, rs.getInt(2)); assertEquals(null, rs.getString(1)); assertEquals("bar", rs.getString(3)); } }</code><technical_language>this read : + (multiCf ? columnFamily1 + ".": "") + "f varchar, " if so, remaining references change too</technical_language>

Target:
public void testUpsertingDeletedRowWithNullCoveredColumn(boolean multiCf) throws Exception { String tableName = "TBL_" + generateUniqueName(); String indexName = "IDX_" + generateUniqueName(); String columnFamily1 = "cf1"; String columnFamily2 = "cf2"; String fullTableName = SchemaUtil.getTableName(TestUtil.DEFAULT_SCHEMA_NAME, tableName); String fullIndexName = SchemaUtil.getTableName(TestUtil.DEFAULT_SCHEMA_NAME, indexName); try (Connection conn = getConnection()) { conn.createStatement() .execute("create table " + fullTableName + " (id integer primary key, " + (multiCf ? columnFamily1 + "." : "") + "f varchar, " + (multiCf ? columnFamily2 + "." : "") + "s varchar)" + tableDDLOptions); conn.createStatement() .execute("create " + (localIndex ? "LOCAL" : "") + " index " + indexName + " on " + fullTableName + " (" + (multiCf ? columnFamily1 + "." : "") + "f) include (" + (multiCf ? columnFamily2 + "." : "") + "s)"); conn.createStatement() .execute("upsert into " + fullTableName + " values (1, 'foo', 'bar')"); conn.commit(); conn.createStatement().execute("delete from " + fullTableName + " where id = 1"); conn.commit(); conn.createStatement() .execute("upsert into " + fullTableName + " values (1, null, 'bar')"); conn.commit(); ResultSet rs = conn.createStatement().executeQuery("select * from " + fullIndexName); assertTrue(rs.next()); assertEquals(1, rs.getInt(2)); assertEquals(null, rs.getString(1)); assertEquals("bar", rs.getString(3)); } }