auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static String formatTimeRelative(long time, Resolution resolution) { StringBuffer str = new StringBuffer(); if (time < 0) { str.append('-'); } long totalSecond = 0; long ns = Math.abs(time); long seconds = TimeUnit.NANOSECONDS.toSeconds(ns); long minutes = TimeUnit.NANOSECONDS.toMinutes(ns); long hours = TimeUnit.NANOSECONDS.toHours(ns); long days = TimeUnit.NANOSECONDS.toDays(ns); if (days > 0) { totalSecond = days * SECONDS_PER_DAY; } if (hours > 0) { totalSecond = hours * SECONDS_PER_HOUR; } if (minutes > 0) { totalSecond = minutes * SECONDS_PER_MIN; } str.append(totalSecond + seconds); str.append('.'); str.append(formatNs(time, resolution)); <START> str.append("s"); END> if (seconds == 0) { str.append(" ("); str.append(new DecimalUnitFormat(1.0 / SEC_IN_NS).format(time)); str.append("s)"); } return str.toString(); }</code><technical_language>char, externalize seconds... I prefer char tbh</technical_language>

Target:
private static String formatTimeRelative(long time, Resolution resolution) { StringBuffer str = new StringBuffer(); if (time < 0) { str.append('-'); } long ns = Math.abs(time); long seconds = TimeUnit.NANOSECONDS.toSeconds(ns); str.append(seconds); str.append('.'); str.append(formatNs(time, resolution)); str.append('s'); if (seconds == 0) { str.append(" ("); str.append(new DecimalUnitFormat(1.0 / SEC_IN_NS).format(time)); str.append("s)"); } return str.toString(); }
Source:
<code>public void setPlayerTest() { worldManager.setPlayer(p1); <START> assertTrue(worldManager.getPlayer().equals(new Player(physicsWorld, new Vector2(0, 0), new Vector2(20, 20)))); <END> worldManager.setPlayer(new Player(physicsWorld, new Vector2(1, 0), new Vector2(20, 20))); assertTrue(worldManager.getPlayer().equals(new Player(physicsWorld, new Vector2(1, 0), new Vector2(20, 20)))); }</code><technical_language>assertEquals here</technical_language>

Target:
public void setPlayerTest() { worldManager.setPlayer(p1); assertEquals(worldManager.getPlayer(), new Player(physicsWorld, new Vector2(0, 0), new Vector2(20, 20))); worldManager.setPlayer(new Player(physicsWorld, new Vector2(1, 0), new Vector2(20, 20))); assertEquals(worldManager.getPlayer(), new Player(physicsWorld, new Vector2(1, 0), new Vector2(20, 20))); }
Source:
<code>public void <START> performFiltering() <END> { CallFilter dummyStart = new CallFilter(); mDummyComplete = new CallFilter(); for (CallFilter filter : mFiltersList) { addEdge(dummyStart, filter); } for (CallFilter filter : mFiltersList) { addEdge(filter, mDummyComplete); } addEdge(dummyStart, mDummyComplete); mHandler.post(() -> scheduleFilter(dummyStart)); }</code><technical_language>lost timeout some point reshuffling -- want put handler. timeout code in current IncomingCallFilter class done</technical_language>

Target:
public void performFiltering() { CallFilter dummyStart = new CallFilter(); mDummyComplete = new CallFilter(); for (CallFilter filter : mFiltersList) { addEdge(dummyStart, filter); } for (CallFilter filter : mFiltersList) { addEdge(filter, mDummyComplete); } addEdge(dummyStart, mDummyComplete); scheduleFilter(dummyStart); mHandler.postDelayed(() -> { if (!mFinished) { Log.i(this, "Graph timed out when perform filtering."); mListener.onCallFilteringComplete(mCall, mCurrentResult); mFinished = true; } }, mTimeoutsAdapter.getCallScreeningTimeoutMillis(mContext.getContentResolver())); }
Source:
<code>public Object[] transform(InputRow inputRow) { final Charset usedCharset = Charset.forName(charset); final String requestBody = applyVariablesToString(this.requestBody, inputRow); final String url = applyVariablesToString(this.url, inputRow); final HttpUriRequest request = method.createRequest(url); <START> if (requestBody != null && request instanceof HttpEntityEnclosingRequest) { <END> HttpEntity entity = new StringEntity(requestBody, usedCharset); ((HttpEntityEnclosingRequest) request).setEntity(entity); } if (headers != null) { final Set<Entry<String, String>> entries = headers.entrySet(); for (Entry<String, String> entry : entries) { request.setHeader(entry.getKey(), entry.getValue()); } } final ServiceResult<Object[]> result = _session.invokeService(new Callable<Object[]>() { @Override public Object[] call() throws Exception { final HttpResponse response = _httpClient.execute(request); final int statusCode = response.getStatusLine().getStatusCode(); final String body = EntityUtils.toString(response.getEntity(), usedCharset); return new Object[] { statusCode, body }; } }); if (!result.isSuccesfull()) { final Throwable error = result.getError(); if (error instanceof RuntimeException) { throw (RuntimeException) error; } throw new RuntimeException(error); } return result.getResponse(); }</code><technical_language>I prefer additional "(" ")" prevent errors in order of execution enhances readibility. : if ((requestBody != null)) && (..))</technical_language>

Target:
public Object[] transform(InputRow inputRow) { final Charset usedCharset = Charset.forName(charset); final String requestBody = applyVariablesToString(this.requestBody, inputRow); final String url = applyVariablesToString(this.url, inputRow); final HttpUriRequest request = method.createRequest(url); if (!Strings.isNullOrEmpty(requestBody) && request instanceof HttpEntityEnclosingRequest) { final HttpEntity entity = new StringEntity(requestBody, usedCharset); ((HttpEntityEnclosingRequest) request).setEntity(entity); } if (headers != null) { final Set<Entry<String, String>> entries = headers.entrySet(); for (Entry<String, String> entry : entries) { request.setHeader(entry.getKey(), entry.getValue()); } } final ServiceResult<Object[]> result = _session.invokeService(new Callable<Object[]>() { @Override public Object[] call() throws Exception { final HttpResponse response = _httpClient.execute(request); final int statusCode = response.getStatusLine().getStatusCode(); final String body = EntityUtils.toString(response.getEntity(), usedCharset); return new Object[] { statusCode, body }; } }); if (!result.isSuccesfull()) { final Throwable error = result.getError(); if (error instanceof RuntimeException) { throw (RuntimeException) error; } throw new RuntimeException(error); } return result.getResponse(); }
Source:
<code><START> private void setCohort(Cohort cohort) { <END> this.cohort = cohort; }</code><technical_language>access set field in hbm file need this private setter</technical_language>

Target:
protected void setCohort(Cohort cohort) { this.cohort = cohort; }
Source:
<code>public void testSplitKeys() throws IOException { byte[][] splits = new byte[][] { Bytes.toBytes("AAA"), Bytes.toBytes("BBB"), Bytes.toBytes("CCC"), }; Admin admin = getConnection().getAdmin(); TableName tableName = TableName.valueOf("TestTableWithSplits"); HTableDescriptor descriptor = new HTableDescriptor(tableName); descriptor.addFamily(new HColumnDescriptor(COLUMN_FAMILY)); try { if (admin.tableExists(tableName)) { LOG.warn("Not creating the table since it exists: %s", tableName); } else { admin.createTable(descriptor, splits); <START> RegionLocator locator = getConnection().getRegionLocator(tableName); <END> List<HRegionLocation> regions = locator.getAllRegionLocations(); Assert.assertEquals(splits.length + 1, regions.size()); for (int i = 0; i < regions.size(); i++) { HRegionLocation region = regions.get(i); String start_key = new String(region.getRegionInfo().getStartKey()); String end_key = new String(region.getRegionInfo().getEndKey()); if (i == 0) { Assert.assertEquals(new String(splits[0]), end_key); } else if (i == regions.size() - 1) { Assert.assertEquals(new String(splits[splits.length - 1]), start_key); } else { Assert.assertEquals(new String(splits[i-1]), start_key); Assert.assertEquals(new String(splits[i]), end_key); } } } } finally { try { admin.disableTable(tableName); admin.deleteTable(tableName); } catch (Throwable t) { LOG.warn("Error cleaning up the table", t); } } }</code><technical_language>locator closed</technical_language>

Target:
public void testSplitKeys() throws IOException { byte[][] splits = new byte[][] { Bytes.toBytes("AAA"), Bytes.toBytes("BBB"), Bytes.toBytes("CCC"), }; Admin admin = getConnection().getAdmin(); TableName tableName = TableName.valueOf("TestTableWithSplits"); HTableDescriptor descriptor = new HTableDescriptor(tableName); descriptor.addFamily(new HColumnDescriptor(COLUMN_FAMILY)); try { if (admin.tableExists(tableName)) { LOG.warn("Not creating the table since it exists: %s", tableName); } else { admin.createTable(descriptor, splits); List<HRegionLocation> regions = null; try (RegionLocator locator = getConnection().getRegionLocator(tableName)) { regions = locator.getAllRegionLocations(); } Assert.assertEquals(splits.length + 1, regions.size()); for (int i = 0; i < regions.size(); i++) { HRegionLocation region = regions.get(i); String start_key = Bytes.toString( region.getRegionInfo().getStartKey()); String end_key = Bytes.toString(region.getRegionInfo().getEndKey()); if (i == 0) { Assert.assertEquals(Bytes.toString(splits[0]), end_key); } else if (i == regions.size() - 1) { Assert.assertEquals(Bytes.toString(splits[splits.length - 1]), start_key); } else { Assert.assertEquals(Bytes.toString(splits[i-1]), start_key); Assert.assertEquals(Bytes.toString(splits[i]), end_key); } } } } finally { try { admin.disableTable(tableName); admin.deleteTable(tableName); } catch (Throwable t) { LOG.warn("Error cleaning up the table", t); } } }
Source:
<code>public void set(Subscription s) { if (s == null) { throw new IllegalArgumentException("Subscription can not be null"); } State oldState; State newState; do { <START> oldState = state.get(); <END> if (oldState.isUnsubscribed) { s.unsubscribe(); return; } else { newState = oldState.set(s); } } while (!state.compareAndSet(oldState, newState)); }</code><technical_language>field state read a local variable loop</technical_language>

Target:
public void set(Subscription s) { if (s == null) { throw new IllegalArgumentException("Subscription can not be null"); } State oldState; State newState; final AtomicReference<State> localState = this.state; do { oldState = localState.get(); if (oldState.isUnsubscribed) { s.unsubscribe(); return; } else { newState = oldState.set(s); } } while (!localState.compareAndSet(oldState, newState)); }
Source:
<code>protected void applyRow(SnomedAssociationRefSetMember member, AssociatingRefSetRow row, Collection<SnomedAssociationRefSetMember> componentsToAttach) { <START> member.setUuid(row.getUuid().toString()); <END> if (row.getEffectiveTime() != null) { member.setEffectiveTime(row.getEffectiveTime()); member.setReleased(true); } else { member.unsetEffectiveTime(); } member.setRefSet(getOrCreateRefSet(row.getRefSetId(), row.getReferencedComponentId())); member.setActive(row.isActive()); member.setModuleId(row.getModuleId()); member.setReferencedComponentId(row.getReferencedComponentId()); member.setTargetComponentId(row.getAssociatedComponentId()); }</code><technical_language>AbstractSnomedRefSetImporter.createComponent(String) initializes UUID property (probably applies core components, reference set members). removed classes implementing applyRow</technical_language>

Target:
protected void applyRow(SnomedAssociationRefSetMember member, AssociatingRefSetRow row, Collection<SnomedAssociationRefSetMember> componentsToAttach) { if (row.getEffectiveTime() != null) { member.setEffectiveTime(row.getEffectiveTime()); member.setReleased(true); } else { member.unsetEffectiveTime(); } member.setRefSet(getOrCreateRefSet(row.getRefSetId(), row.getReferencedComponentId())); member.setActive(row.isActive()); member.setModuleId(row.getModuleId()); member.setReferencedComponentId(row.getReferencedComponentId()); member.setTargetComponentId(row.getAssociatedComponentId()); }
Source:
<code><START> public Object getRecordState(Object record, Schema schema) { return null; } <END></code><technical_language>writer change, I this needs exposed longer</technical_language>

Target:
protected Object getRecordState(Object record, Schema schema) { return null; }
Source:
<code>public ValueType get(final Object key) { if (key instanceof Tuple) { final Object value = ((Tuple) <START> key).get(((Tuple) key).getSize() - 1); <END> final Object unwrappedValue = this.runtimeContext.unwrapElement(value); return this.mappings.get(unwrappedValue); } else { return null; } }</code><technical_language>this statically computed based tuple 'group', if want save space store it, group.size() do</technical_language>

Target:
public ValueType get(final Object key) { if (key instanceof Tuple) { final Object value = ((Tuple) key).get(this.groupSize); final Object unwrappedValue = this.runtimeContext.unwrapElement(value); return this.mappings.get(unwrappedValue); } else { return null; } }
Source:
<code>private HashSet<String> getIgnoredViews() { if (ignoredViews == null) { ignoredViews = new HashSet<>(); IExtensionRegistry registry = RegistryFactory.getRegistry(); IExtensionPoint ep = registry.getExtensionPoint(EXT_POINT); if (ep != null) { IExtension[] extensions = ep.getExtensions(); for (int i = 0; i < extensions.length; i++) { <START> IConfigurationElement[] elements = extensions[i].getConfigurationElements(); <END> for (int j = 0; j < elements.length; j++) { if ("excludeSources".equalsIgnoreCase(elements[j].getName())) { String id = elements[j].getAttribute("id"); if (id != null) ignoredViews.add(id); } } } } } return ignoredViews; }</code><technical_language>for loop</technical_language>

Target:
private Set<String> getIgnoredViews() { if (ignoredViews == null) { ignoredViews = new HashSet<>(); IExtensionRegistry registry = RegistryFactory.getRegistry(); IExtensionPoint ep = registry.getExtensionPoint(EXT_POINT); if (ep != null) { IExtension[] extensions = ep.getExtensions(); for (IExtension extension : extensions) { IConfigurationElement[] elements = extension.getConfigurationElements(); for (IConfigurationElement element : elements) { if ("excludeSources".equalsIgnoreCase(element.getName())) { String id = element.getAttribute("id"); if (id != null) ignoredViews.add(id); } } } } } return ignoredViews; }
Source:
<code>public FilterBuilder withVariantTypes(VariantType variantType) { if (variantType != null) { <START> filters.add(new VariantRepositoryTypeFilter(new ArrayList<>(Arrays.asList(variantType)))); <END> } return this; }</code><technical_language>I suggest change for filters.add(new VariantRepositoryTypeFilter(Collections.singletonList(variantType))); If do need include import java.util.Collections; applies for withAlternates withReferenceBases</technical_language>

Target:
public FilterBuilder withVariantTypes(VariantType variantType) { if (variantType != null) { filters.add(new VariantRepositoryTypeFilter(Collections.singletonList(variantType))); } return this; }
Source:
<code>private boolean shouldProcessAuthorizationResponse(HttpServletRequest request) { OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository.loadAuthorizationRequest(request); if (authorizationRequest == null) { return false; } MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap()); <START> if (isValidRedirectUrl(request, authorizationRequest.getRedirectUri()) && <END> OAuth2AuthorizationResponseUtils.isAuthorizationResponse(params)) { return true; } return false; }</code><technical_language>@ttddyy This simplified follows: java String requestUrl = UrlUtils.buildFullRequestUrl(request); MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap()); if (requestUrl.startsWith(authorizationRequest.getRedirectUri()) && OAuth2AuthorizationResponseUtils.isAuthorizationResponse(params)) { return true; }</technical_language>

Target:
private boolean shouldProcessAuthorizationResponse(HttpServletRequest request) { OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository.loadAuthorizationRequest(request); if (authorizationRequest == null) { return false; } MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap()); if (OAuth2AuthorizationResponseUtils.isAuthorizationResponse(params) && isValidRedirectUrl(request, authorizationRequest.getRedirectUri())) { return true; } return false; }
Source:
<code>private static RealMatrix tangentNormalize(final RealMatrix normals, final RealMatrix input, final RealMatrix betaHats) { <START> if (input.getColumnDimension() != betaHats.getColumnDimension()) { <END> throw new IllegalArgumentException(String.format("the input count column count (%d) does not match the number of columns in the beta-hats (%d)", input.getColumnDimension(), betaHats.getColumnDimension())); } if (normals.getColumnDimension() != betaHats.getRowDimension()) { throw new IllegalArgumentException(String.format("beta-hats component count (%d) does not match the number of samples in the PoN (%d)", normals.getRowDimension(), normals.getColumnDimension())); } final RealMatrix projection = normals.multiply(betaHats); return input.subtract(projection); }</code><technical_language>Utils.validateArg x 2</technical_language>

Target:
private static RealMatrix tangentNormalize(final RealMatrix normals, final RealMatrix input, final RealMatrix betaHats) { Utils.validateArg(input.getColumnDimension() == betaHats.getColumnDimension(), String.format("the input count column count (%d) does not match the number of columns in the beta-hats (%d)", input.getColumnDimension(), betaHats.getColumnDimension())); Utils.validateArg(normals.getColumnDimension() == betaHats.getRowDimension(), String.format("beta-hats component count (%d) does not match the number of samples in the PoN (%d)", normals.getRowDimension(), normals.getColumnDimension())); final RealMatrix projection = normals.multiply(betaHats); return input.subtract(projection); }
Source:
<code>private static ExecutorService createInstrumentedFixedThreadPool(CassandraKeyValueServiceConfig config, MetricRegistry registry) { return new InstrumentedExecutorService( createFixedThreadPool("Atlas Cassandra KVS", <START> config.poolSize() * config.servers().thrift().size()), <END> registry, MetricRegistry.name(CassandraKeyValueService.class, "executorService")); }</code><technical_language>this usage feels awkward, put size() CassandraServersConfig, I feel this</technical_language>

Target:
private static ExecutorService createInstrumentedFixedThreadPool(CassandraKeyValueServiceConfig config, MetricRegistry registry) { return new InstrumentedExecutorService( createFixedThreadPool("Atlas Cassandra KVS", config.poolSize() * config.servers().numberOfHosts()), registry, MetricRegistry.name(CassandraKeyValueService.class, "executorService")); }
Source:
<code>public static Comparator<SimpleFeature> sortComparator(SortBy sortBy) { if (sortBy == null) { sortBy = SortBy.NATURAL_ORDER; } if (sortBy == SortBy.NATURAL_ORDER) { return new Comparator<SimpleFeature>() { public int compare(SimpleFeature f1, SimpleFeature f2) { return f1.getID().compareTo(f2.getID()); } }; } else if (sortBy == SortBy.REVERSE_ORDER) { return new Comparator<SimpleFeature>() { public int compare(SimpleFeature f1, SimpleFeature f2) { int compare = f1.getID().compareTo(f2.getID()); return -compare; } }; } else { final PropertyName PROPERTY = sortBy.getPropertyName(); <START> final SortOrder ORDER = sortBy.getSortOrder(); <END> return new Comparator<SimpleFeature>() { @SuppressWarnings("unchecked") public int compare(SimpleFeature f1, SimpleFeature f2) { Object value1 = PROPERTY.evaluate(f1, Comparable.class); Object value2 = PROPERTY.evaluate(f2, Comparable.class); if (value1 == null || value2 == null) { return 0; } if (value1 instanceof Comparable && value1.getClass().isInstance(value2)) { if(ORDER == SortOrder.ASCENDING) { return ((Comparable<Object>) value1).compareTo(value2); }else { return ((Comparable<Object>) value2).compareTo(value1); } } else { return 0; } } }; } }</code><technical_language>@ianturton of local final variables uppercase; final, varies invocations, lexically constant. I consistent, this practice violates code conventions. change propertyName sortOrder respectively</technical_language>

Target:
public static Comparator<SimpleFeature> sortComparator(SortBy sortBy) { if (sortBy == null) { sortBy = SortBy.NATURAL_ORDER; } if (sortBy == SortBy.NATURAL_ORDER) { return new Comparator<SimpleFeature>() { public int compare(SimpleFeature f1, SimpleFeature f2) { return f1.getID().compareTo(f2.getID()); } }; } else if (sortBy == SortBy.REVERSE_ORDER) { return new Comparator<SimpleFeature>() { public int compare(SimpleFeature f1, SimpleFeature f2) { int compare = f1.getID().compareTo(f2.getID()); return -compare; } }; } else { final PropertyName propertyName = sortBy.getPropertyName(); final SortOrder sortOrder = sortBy.getSortOrder(); return new Comparator<SimpleFeature>() { @SuppressWarnings("unchecked") public int compare(SimpleFeature f1, SimpleFeature f2) { Object value1 = propertyName.evaluate(f1, Comparable.class); Object value2 = propertyName.evaluate(f2, Comparable.class); if (value1 == null || value2 == null) { return 0; } if (value1 instanceof Comparable && value1.getClass().isInstance(value2)) { if (sortOrder == SortOrder.ASCENDING) { return ((Comparable<Object>) value1).compareTo(value2); } else { return ((Comparable<Object>) value2).compareTo(value1); } } else { return 0; } } }; } }
Source:
<code>public void deleteS3Bucket(String bucketName) throws IOException { Preconditions.checkArgument( Strings.isNotBlank(bucketName), "Bucket name cannot be null or empty"); <START> <END> omMetadataManager.getLock().acquireS3BucketLock(bucketName); try { String map = omMetadataManager.getS3Table().get(bucketName); if (map == null) { throw new OMException("No such S3 bucket. " + bucketName, OMException.ResultCodes.S3_BUCKET_NOT_FOUND); } bucketManager.deleteBucket(getOzoneVolumeName(bucketName), bucketName); omMetadataManager.getS3Table().delete(bucketName); } catch(IOException ex) { throw ex; } finally { omMetadataManager.getLock().releaseS3BucketLock(bucketName); } }</code><technical_language>I get removed acquire/release bucket lock. Is caller supposed get lock</technical_language>

Target:
public void deleteS3Bucket(String bucketName) throws IOException { Preconditions.checkArgument( Strings.isNotBlank(bucketName), "Bucket name cannot be null or empty"); omMetadataManager.getLock().acquireLock(S3_BUCKET_LOCK, bucketName); try { String map = omMetadataManager.getS3Table().get(bucketName); if (map == null) { throw new OMException("No such S3 bucket. " + bucketName, OMException.ResultCodes.S3_BUCKET_NOT_FOUND); } bucketManager.deleteBucket(getOzoneVolumeName(bucketName), bucketName); omMetadataManager.getS3Table().delete(bucketName); } catch(IOException ex) { throw ex; } finally { omMetadataManager.getLock().releaseLock(S3_BUCKET_LOCK, bucketName); } }
Source:
<code>public CompletableFuture<JobExecutionResult> getJobExecutionResult() { checkNotNull(classLoader); final Time retryPeriod = Time.milliseconds(100L); return JobStatusPollingUtils.getJobResult(dispatcherGateway, jobId, retryExecutor, timeout, retryPeriod) .thenApply((jobResult) -> { try { return jobResult.toJobExecutionResult(classLoader); } catch (Throwable t) { <START> throw new CompletionException( ApplicationFailureException.fromJobResult(jobResult, classLoader)); <END> } }); }</code><technical_language>Is this actual change fixes problem</technical_language>

Target:
public CompletableFuture<JobExecutionResult> getJobExecutionResult() { checkNotNull(classLoader); final Time retryPeriod = Time.milliseconds(100L); return JobStatusPollingUtils.getJobResult(dispatcherGateway, jobId, retryExecutor, timeout, retryPeriod) .thenApply((jobResult) -> { try { return jobResult.toJobExecutionResult(classLoader); } catch (Throwable t) { throw new CompletionException( UnsuccessfulExecutionException.fromJobResult(jobResult, classLoader)); } }); }
Source:
<code>public synchronized IndexWriter getTimestampsWriter() { <START> if (fTimestampsWriter == null) { try { Directory indexDir = new IndexDirectory( Paths.get(fIndexRoot, fContainerId, TIMESTAMPS_DIR)); IndexWriterConfig config = new IndexWriterConfig( new SimpleAnalyzer()); ConcurrentMergeScheduler mergeScheduler = new ConcurrentMergeScheduler(); mergeScheduler.setDefaultMaxMergesAndThreads(true); config.setMergeScheduler(mergeScheduler); config.setOpenMode(OpenMode.CREATE_OR_APPEND); fTimestampsWriter = new IndexWriter(indexDir, config); } catch (IOException e) { Logger.logException(e); } } <END> return fTimestampsWriter; }</code><technical_language>This is a duplicated code in getIndexWriter() method. refactor it</technical_language>

Target:
public synchronized IndexWriter getTimestampsWriter() { if (fTimestampsWriter == null) { Path writerPath = Paths.get(fIndexRoot, fContainerId, TIMESTAMPS_DIR); fTimestampsWriter = createIndexWriter(writerPath); } return fTimestampsWriter; }
Source:
<code>CompletableFuture<Void> sendLeavePresenceToExistingOccupants(MUCRole leaveRole) { <START> if (!leaveRole.isLocal() || leaveRole.isRemoteFmuc()) <END> return CompletableFuture.completedFuture(null); Log.trace( "Send presence of leaving occupant '{}' to existing occupants of room '{}'.", leaveRole.getUserAddress(), leaveRole.getChatRoom().getJID() ); try { Presence originalPresence = leaveRole.getPresence(); Presence presence = originalPresence.createCopy(); presence.setType(Presence.Type.unavailable); presence.setStatus(null); Element childElement = presence.getChildElement("x", "<LINK_0>"); if (childElement == null) { childElement = presence.addChildElement("x", "<LINK_0>"); } Element item = childElement.element("item"); if (item == null) { item = childElement.addElement("item"); } item.addAttribute("role", "none"); if(!shouldBroadcastPresence(originalPresence)){ leaveRole.send(presence); return CompletableFuture.completedFuture(null); } else { if (getOccupantsByNickname(leaveRole.getNickname()).size() <= 1) { if (JOIN_PRESENCE_ENABLE.getValue()) { return broadcastPresence(presence, false, leaveRole); } } } } catch (Exception e) { Log.error( "An exception occurred while sending leave presence of occupant '"+leaveRole.getUserAddress()+"' to the other occupants of room: '"+leaveRole.getChatRoom().getJID()+"'.", e); } return CompletableFuture.completedFuture(null); }</code><technical_language>This is picky style thing, I know, braces statement for this if() statement please? prevent bugs in future this code changes</technical_language>

Target:
CompletableFuture<Void> sendLeavePresenceToExistingOccupants(MUCRole leaveRole) { if (!leaveRole.isLocal() || leaveRole.isRemoteFmuc()) { return CompletableFuture.completedFuture(null); } Log.trace( "Send presence of leaving occupant '{}' to existing occupants of room '{}'.", leaveRole.getUserAddress(), leaveRole.getChatRoom().getJID() ); try { Presence originalPresence = leaveRole.getPresence(); Presence presence = originalPresence.createCopy(); presence.setType(Presence.Type.unavailable); presence.setStatus(null); Element childElement = presence.getChildElement("x", "<LINK_0>"); if (childElement == null) { childElement = presence.addChildElement("x", "<LINK_0>"); } Element item = childElement.element("item"); if (item == null) { item = childElement.addElement("item"); } item.addAttribute("role", "none"); if(!shouldBroadcastPresence(originalPresence)){ leaveRole.send(presence); return CompletableFuture.completedFuture(null); } else { if (getOccupantsByNickname(leaveRole.getNickname()).size() <= 1) { if (JOIN_PRESENCE_ENABLE.getValue()) { return broadcastPresence(presence, false, leaveRole); } } } } catch (Exception e) { Log.error( "An exception occurred while sending leave presence of occupant '"+leaveRole.getUserAddress()+"' to the other occupants of room: '"+leaveRole.getChatRoom().getJID()+"'.", e); } return CompletableFuture.completedFuture(null); }
Source:
<code>public void add(Object obj) throws IOException { if (obj == null) { addValue(0); } else if (obj instanceof Integer) { addValue(((Number) obj).intValue()); } else if (obj instanceof int[]) { int[] vals = (int[]) obj; if (vals.length == 0) { addValue(0); } else { addValue(vals[0]); } } else { <START> throw new IAE("unsupported object type"); <END> } }</code><technical_language>here, print unsupported type</technical_language>

Target:
public void add(Object obj) throws IOException { if (obj == null) { addValue(0); } else if (obj instanceof Integer) { addValue(((Number) obj).intValue()); } else if (obj instanceof int[]) { int[] vals = (int[]) obj; if (vals.length == 0) { addValue(0); } else { addValue(vals[0]); } } else { throw new IAE("Unsupported single value type: " + obj.getClass()); } }
Source:
<code>public static void received(Channel channel, Response response, boolean timeout) { try { DefaultFuture future = FUTURES.remove(response.getId()); if (future != null) { Timeout t = future.timeoutCheckTask; <START> if (t != null) { <END> t.cancel(); } future.doReceived(response); } else { logger.warn("The timeout response finally returned at " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())) + ", response " + response + (channel == null ? "" : ", channel: " + channel.getLocalAddress() + " -> " + channel.getRemoteAddress())); } } finally { CHANNELS.remove(response.getId()); } }</code><technical_language>if (t != null) if (!timeout)</technical_language>

Target:
public static void received(Channel channel, Response response, boolean timeout) { try { DefaultFuture future = FUTURES.remove(response.getId()); if (future != null) { Timeout t = future.timeoutCheckTask; if (!timeout) { t.cancel(); } future.doReceived(response); } else { logger.warn("The timeout response finally returned at " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())) + ", response " + response + (channel == null ? "" : ", channel: " + channel.getLocalAddress() + " -> " + channel.getRemoteAddress())); } } finally { CHANNELS.remove(response.getId()); } }
Source:
<code>private byte[] serialize(MetacardType anywhereMType) throws MetacardCreationException { try { return OBJECT_MAPPER.writeValueAsBytes(anywhereMType); } catch (JsonProcessingException e) { <START> throw new MetacardCreationException(COULD_NOT_READ_METACARD_TYPE_MESSAGE, e); <END> } }</code><technical_language>is serializer defined? relying a deserializer a serializer? relying reflection serialize a deserializer deserialize. This lead problems reflection potentially serialize a lot more interface defines. In addition, tightly coupling field names Json format</technical_language>

Target:
private byte[] serialize(MetacardType anywhereMType) throws MetacardCreationException { try { return METACARD_TYPE_MAPPER.writeValueAsBytes(anywhereMType); } catch (JsonProcessingException e) { throw new MetacardCreationException(COULD_NOT_READ_METACARD_TYPE_MESSAGE, e); } }
Source:
<code>public ModelServiceImpl(IEclipseContext appContext) { if (appContext == null) { throw new NullPointerException("No application context given!"); } this.appContext = appContext; Bundle bundle = FrameworkUtil.getBundle(getClass()); if (bundle != null) { BundleContext bundleContext = bundle.getBundleContext(); <START> if (bundleContext != null) <END> { Dictionary<String, Object> properties = new Hashtable<>(); properties.put(EventConstants.EVENT_TOPIC, new String[] { UIEvents.UIElement.TOPIC_WIDGET }); bundleContext.registerService(EventHandler.class.getName(), ContextInjectionFactory.make(HostedElementEventHandler.class, appContext), properties); } } else { IEventBroker eventBroker = appContext.get(IEventBroker.class); if (eventBroker == null) { throw new IllegalStateException( "Could not get an IEventBroker instance. Please check your configuration that a providing bundle is present and active."); } eventBroker.subscribe(UIEvents.UIElement.TOPIC_WIDGET, null, ContextInjectionFactory.make(HostedElementEventHandler.class, appContext), true); } mApplicationElementFactory = new GenericMApplicationElementFactoryImpl( appContext.get(IExtensionRegistry.class)); }</code><technical_language>else? I raise error then</technical_language>

Target:
public ModelServiceImpl(IEclipseContext appContext) { if (appContext == null) { throw new NullPointerException("No application context given!"); } this.appContext = appContext; Bundle bundle = FrameworkUtil.getBundle(getClass()); if (bundle != null && bundle.getBundleContext() != null) { Dictionary<String, Object> properties = new Hashtable<>(); properties.put(EventConstants.EVENT_TOPIC, new String[] { UIEvents.UIElement.TOPIC_WIDGET }); bundle.getBundleContext().registerService(EventHandler.class.getName(), ContextInjectionFactory.make(HostedElementEventHandler.class, appContext), properties); } else { IEventBroker eventBroker = appContext.get(IEventBroker.class); if (eventBroker == null) { throw new IllegalStateException( "Could not get an IEventBroker instance. Please check your configuration that a providing bundle is present and active."); } eventBroker.subscribe(UIEvents.UIElement.TOPIC_WIDGET, null, ContextInjectionFactory.make(HostedElementEventHandler.class, appContext), true); } mApplicationElementFactory = new GenericMApplicationElementFactoryImpl( appContext.get(IExtensionRegistry.class)); }
Source:
<code>private void toggleStickyField() { <START> try { JSONObject field = (JSONObject) mNoteFields.get(mCurrentPos); if (field.getBoolean("sticky")){ field.put("sticky", false); } else { field.put("sticky", true); } } catch (JSONException e) { throw new RuntimeException(e); } <END> }</code><technical_language>Hey @sudomain ! Thanks for patience this. close working PR backlog I finally looked this :-). prepared merge is, change I suggest is I need try/catch boilerplate JSON access now, a change Arthur Milchior in #5550 - this suggestion removes that. try committing this passes CI checks if merge suggestion // Get current field JSONObject field = (JSONObject) mNoteFields.get(mCurrentPos); // If sticky setting is enabled disable it, enable if (field.getBoolean("sticky")) { field.put("sticky", false); } else { field.put("sticky", true); }</technical_language>

Target:
private void toggleStickyField() { JSONObject field = (JSONObject) mNoteFields.get(mCurrentPos); if (field.getBoolean("sticky")) { field.put("sticky", false); } else { field.put("sticky", true); } }
Source:
<code><START> private ListenableFuture<Map<Long, Long>> loadCommitTimestamps( <END> AsyncTransactionService asyncTransactionService, Set<Long> startTimestamps) { if (startTimestamps.size() == 1) { long singleTs = startTimestamps.iterator().next(); return Futures.transform(asyncTransactionService.getAsync(singleTs), commitTsOrNull -> commitTsOrNull == null ? ImmutableMap.of() : ImmutableMap.of(singleTs, commitTsOrNull), MoreExecutors.directExecutor()); } else { return asyncTransactionService.getAsync(startTimestamps); } }</code><technical_language>static</technical_language>

Target:
private static ListenableFuture<Map<Long, Long>> loadCommitTimestamps( AsyncTransactionService asyncTransactionService, Set<Long> startTimestamps) { if (startTimestamps.size() == 1) { long singleTs = startTimestamps.iterator().next(); return Futures.transform(asyncTransactionService.getAsync(singleTs), commitTsOrNull -> commitTsOrNull == null ? ImmutableMap.of() : ImmutableMap.of(singleTs, commitTsOrNull), MoreExecutors.directExecutor()); } else { return asyncTransactionService.getAsync(startTimestamps); } }
Source:
<code>public void testIncludePattern() throws IOException { ReliableEventReader reader = new ReliableSpoolingFileEventReader.Builder() .spoolDirectory(WORK_DIR) .includePattern("^file2$") .deletePolicy(DeletePolicy.IMMEDIATE.toString()) .build(); List<File> before = listFiles(WORK_DIR); Assert.assertEquals("Expected 5, not: " + before, 5, before.size()); <START> List<Event> events; <END> do { events = reader.readEvents(10); reader.commit(); } while (!events.isEmpty()); List<File> after = listFiles(WORK_DIR); Assert.assertEquals("Expected 4, not: " + after, 4, after.size()); Set<String> expectedLeftFiles = new HashSet<String>(Arrays.asList("file0", "file1", "file3", "emptylineFile")); for (File f: after) { expectedLeftFiles.remove(f.getName()); } Assert.assertTrue("Unexpected files were sent", expectedLeftFiles.isEmpty()); List<File> trackerFiles = listFiles(new File(WORK_DIR, SpoolDirectorySourceConfigurationConstants.DEFAULT_TRACKER_DIR)); Assert.assertEquals("Expected 0, not: " + trackerFiles, 0, trackerFiles.size()); }</code><technical_language>a couple of copy-paste lines there, please refactor a bit? e.g. extract reader.readEvents-reader.commit loops a method. assertion part (listFiles, checking count, removing expectedLeftFiles, checking emptiness of it) extract too, improve readability of code. (e.g. void assertExpectedLeftFiles(String... expectedFileNames))</technical_language>

Target:
public void testIncludePattern() throws IOException { ReliableEventReader reader = new ReliableSpoolingFileEventReader.Builder() .spoolDirectory(WORK_DIR) .includePattern("^file2$") .deletePolicy(DeletePolicy.IMMEDIATE.toString()) .build(); String[] beforeFiles = { "file0", "file1", "file2", "file3", "emptylineFile" }; Assert.assertTrue("Expected " + beforeFiles.length + " files in working dir", checkLeftFilesInDir(WORK_DIR, beforeFiles)); processEventsWithReader(reader, 10); String[] afterFiles = { "file0", "file1", "file3", "emptylineFile" }; Assert.assertTrue("Expected " + afterFiles.length + " files left in working dir", checkLeftFilesInDir(WORK_DIR, afterFiles)); Assert.assertTrue("Expected no files left in tracker dir", checkLeftFilesInDir(TRACKER_DIR, new String[0])); }
Source:
<code>private GridCoverage2D prepareForBandMerge(GridCoverage2D coverage) { RenderedImage ri = coverage.getRenderedImage(); SampleModel sampleModel = ri.getSampleModel(); if (sampleModel.getNumBands() == 1 && ri.getColorModel() instanceof IndexColorModel) { final ParameterBlock paramBlk = new ParameterBlock().addSource(ri); int dataType = sampleModel.getDataType(); paramBlk.add(dataType); ComponentColorModel targetColorModel = new ComponentColorModel( ColorSpace.getInstance(ColorSpace.CS_GRAY), false, false, Transparency.OPAQUE, dataType); ImageLayout layout = new ImageLayout(ri); layout.setColorModel(targetColorModel); if (!targetColorModel.isCompatibleSampleModel(sampleModel)) { SampleModel targetSampleModel = targetColorModel.createCompatibleSampleModel( sampleModel.getWidth(), sampleModel.getHeight()); layout.setSampleModel(targetSampleModel); } Hints localHints = new Hints(hints); localHints.put(JAI.KEY_IMAGE_LAYOUT, layout); RenderedOp formatted = JAI.create("Format", paramBlk, localHints); return new GridCoverageFactory() .create( coverage.getName(), formatted, coverage.getGridGeometry(), <START> coverage.getSampleDimensions(), <END> new GridCoverage[] {coverage}, coverage.getProperties()); } return coverage; }</code><technical_language>this is correct, I mean, suere original coverage 3 SD 1. checking</technical_language>

Target:
private GridCoverage2D prepareForBandMerge(GridCoverage2D coverage) { RenderedImage ri = coverage.getRenderedImage(); SampleModel sampleModel = ri.getSampleModel(); if (sampleModel.getNumBands() == 1 && ri.getColorModel() instanceof IndexColorModel) { ImageWorker worker = new ImageWorker(ri); worker.removeIndexColorModel(); RenderedImage formatted = worker.getRenderedImage(); return new GridCoverageFactory() .create( coverage.getName(), formatted, coverage.getGridGeometry(), coverage.getSampleDimensions(), new GridCoverage[] {coverage}, coverage.getProperties()); } return coverage; }
Source:
<code>protected static String printResults(Statement stmt, String selection, int columnVerificationNumber) throws SQLException{ ResultSet res; String sql= selection; res=stmt.executeQuery(sql); System.out.println("\n"+"Printing Results: "+sql+"\n"); ResultSetMetaData rsmd = res.getMetaData(); int columnsNumber = rsmd.getColumnCount(); for (int q=1; q<=columnsNumber; q++){ System.out.print(rsmd.getColumnName(q) +" "); } <START> System.out.println(); <END> System.out.println(); while (res.next()) { for (int i = 1; i <= columnsNumber; i++) { String columnValue = res.getString(i); System.out.print(columnValue +" "); } System.out.println(""); } res=stmt.executeQuery(sql); return resultSetVerification(res, columnVerificationNumber); }</code><technical_language>println() calls replaced a single println("\n\n")</technical_language>

Target:
static String printResults(Statement stmt, String selection, int columnVerificationNumber) throws SQLException { ResultSet res; String sql = selection; res = stmt.executeQuery(sql); System.out.println("\n" + "Printing Results: " + sql + "\n"); ResultSetMetaData rsmd = res.getMetaData(); int columnsNumber = rsmd.getColumnCount(); for (int q = 1; q <= columnsNumber; q++) { System.out.print(rsmd.getColumnName(q) + " "); } System.out.println("\n"); while (res.next()) { for (int i = 1; i <= columnsNumber; i++) { String columnValue = res.getString(i); System.out.print(columnValue + " "); } System.out.println(""); } res = stmt.executeQuery(sql); return resultSetVerification(res, columnVerificationNumber); }
Source:
<code>ClientInfoResourceTestClient( ObjectMapper jsonMapper, @TestClient HttpClient httpClient, IntegrationTestingConfig config ) { this.jsonMapper = jsonMapper; this.httpClient = httpClient; <START> this.broker = config.getBrokerUrl(); <END> this.responseHandler = new StatusResponseHandler(Charsets.UTF_8); }</code><technical_language>rename this brokerUrl</technical_language>

Target:
ClientInfoResourceTestClient( ObjectMapper jsonMapper, @TestClient HttpClient httpClient, IntegrationTestingConfig config ) { this.jsonMapper = jsonMapper; this.httpClient = httpClient; this.brokerUrl = config.getBrokerUrl(); this.responseHandler = new StatusResponseHandler(Charsets.UTF_8); }
Source:
<code>public void pidFileForStaleProcessIsIgnored() throws Exception { Files.write(getPidFile().toPath(), "66000".getBytes()); TestUtils.SwarmClientProcessWrapper node = TestUtils.runSwarmClient( "agent0", j, processDestroyer, temporaryFolder, "-pidFile", getPidFile().getAbsolutePath()); <START> TestUtils.waitForNode("agent0", j); <END> int newPid = NumberUtils.toInt( new String(Files.readAllBytes(getPidFile().toPath()), UTF_8)); OSProcess[] childProcesses = os.getChildProcesses(os.getProcessId(), 0, null); assertTrue("Pid in pidFile must match our new pid", Arrays.stream(childProcesses).anyMatch(proc -> proc.getProcessID() == newPid)); }</code><technical_language>[nit] combine calls TestUtils.runSwarmClient TestUtils.waitForNode a single call TestUtils.createSwarmClient</technical_language>

Target:
public void pidFileForStaleProcessIsIgnored() throws Exception { File pidFile = getPidFile(); Files.write(pidFile.toPath(), "66000".getBytes()); TestUtils.createSwarmClient( j, processDestroyer, temporaryFolder, "-pidFile", pidFile.getAbsolutePath()); int newPid = readPidFromFile(pidFile); OSProcess[] childProcesses = os.getChildProcesses(os.getProcessId(), 0, null); assertTrue( "PID in PID file must match our new PID", Arrays.stream(childProcesses).anyMatch(proc -> proc.getProcessID() == newPid)); }
Source:
<code>private MojoParameters buildParameters(String projectDir, String sourceDir, String outputDir) { MavenProject mavenProject = new MavenProject(); <START> mavenProject.setFile(new File(projectDir + File.separator + "pom.xml")); <END> return new MojoParameters(null, mavenProject, null, null, null, null, sourceDir, outputDir); }</code><technical_language>Recommend new File(projectDir, "pom.xml") here</technical_language>

Target:
private MojoParameters buildParameters(String projectDir, String sourceDir, String outputDir) { MavenProject mavenProject = new MavenProject(); mavenProject.setFile(new File(projectDir, "pom.xml")); return new MojoParameters(null, mavenProject, null, null, null, null, sourceDir.replace("/", File.separator), outputDir.replace("/", File.separator)); }
Source:
<code>public void deleteGermplasmListFolder(final Integer folderId) { final GermplasmList folder = this.getGermplasmListById(folderId) <START> .orElseThrow(() -> new MiddlewareException("FolderId does not exist")); <END> this.daoFactory.getGermplasmListDAO().makeTransient(folder); }</code><technical_language>Please MiddlewareRequestException add message in mw_messages_es.properties</technical_language>

Target:
public void deleteGermplasmListFolder(final Integer folderId) { final GermplasmList folder = this.getGermplasmListById(folderId) .orElseThrow(() -> new MiddlewareRequestException("", "list.folder.not.found")); this.daoFactory.getGermplasmListDAO().makeTransient(folder); }
Source:
<code>public ListenableFuture<AckingContainer> poll(boolean forcePollSchema) { final SettableFuture<AckingContainer> fut = SettableFuture.create(); PollTask pollTask = new PollTask(fut, forcePollSchema); try { m_es.execute(new Runnable() { @Override public void run() { if (!m_mastershipAccepted.get()) { pollTask.clear(); m_pollTask = null; return; } try { if (m_pendingContainer.get() != null) { pollTask.setFuture(m_pendingContainer.getAndSet(null)); if (m_pollTask != null) { if (exportLog.isDebugEnabled()) { exportLog.debug("Pick up work from pending container, set poll future to null"); } m_pollTask = null; } return; } if (m_pollTask != null) { <START> fut.setException(new ReentrantPollException("Reentrant poll detected: InCat = " + m_isInCatalog + <END> " In ExportDataSource for Table " + getTableName() + ", Partition " + getPartitionId())); return; } if (!m_es.isShutdown()) { pollImpl(pollTask); } } catch (Exception e) { exportLog.error("Exception polling export buffer", e); } catch (Error e) { VoltDB.crashLocalVoltDB("Error polling export buffer", true, e); } } }); } catch (RejectedExecutionException rej) { exportLog.info("Polling from export data source rejected, this should be harmless"); } return fut; }</code><technical_language>this set exception pollTask for consistency</technical_language>

Target:
public ListenableFuture<AckingContainer> poll(boolean forcePollSchema) { final SettableFuture<AckingContainer> fut = SettableFuture.create(); PollTask pollTask = new PollTask(fut, forcePollSchema); try { m_es.execute(new Runnable() { @Override public void run() { if (!m_mastershipAccepted.get()) { pollTask.clear(); m_pollTask = null; return; } try { if (m_pendingContainer.get() != null) { AckingContainer cont = m_pendingContainer.getAndSet(null); boolean hasSchema = cont.schema() != null; if (!hasSchema) { BBContainer schemaContainer = m_committedBuffers.pollSchema(); if (schemaContainer == null) { pollTask.setException(new IOException("No schema for committedSeqNo " + cont)); return; } else { cont.setSchema(schemaContainer); } } pollTask.setFuture(cont); if (m_pollTask != null) { if (exportLog.isDebugEnabled()) { exportLog.debug("Pick up work from pending container, set poll future to null"); } m_pollTask = null; } return; } if (m_pollTask != null) { fut.setException(new ReentrantPollException("Reentrant poll detected: InCat = " + m_isInCatalog + " In ExportDataSource for Table " + getTableName() + ", Partition " + getPartitionId())); return; } if (!m_es.isShutdown()) { pollImpl(pollTask); } } catch (Exception e) { exportLog.error("Exception polling export buffer", e); } catch (Error e) { VoltDB.crashLocalVoltDB("Error polling export buffer", true, e); } } }); } catch (RejectedExecutionException rej) { exportLog.info("Polling from export data source rejected, this should be harmless"); } return fut; }
Source:
<code>public int read(byte[] bs, int off, int len) throws IOException { if (len == 0) return 0; if (cnt == -1) return -1; final int startOff = off; final int end = off + len; while (off < end) { <START> if (ptr == cnt && !fillBuffer()) { <END> break; } byte b = buf[ptr++]; if (isBinary || b != '\n') { bs[off++] = last = b; continue; } if (b == '\n') { if (last == '\r') { bs[off++] = last = b; continue; } bs[off++] = last = '\r'; ptr--; } else { bs[off++] = last = b; } } int n = startOff == off ? -1 : off - startOff; if (n > 0) last = bs[off - 1]; return n; }</code><technical_language>style nit: braces single line block</technical_language>

Target:
public int read(byte[] bs, int off, int len) throws IOException { if (len == 0) return 0; if (cnt == -1) return -1; final int startOff = off; final int end = off + len; while (off < end) { if (ptr == cnt && !fillBuffer()) break; byte b = buf[ptr++]; if (isBinary || b != '\n') { bs[off++] = last = b; continue; } if (b == '\n') { if (last == '\r') { bs[off++] = last = b; continue; } bs[off++] = last = '\r'; ptr--; } else bs[off++] = last = b; } int n = startOff == off ? -1 : off - startOff; if (n > 0) last = bs[off - 1]; return n; }