auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void halt() throws InterruptedException { for (;;) { join(250 ); if (isAlive()) { done = true; interrupt(); <START> process.destroy(); <END> } else break; } }</code><technical_language>convinced this is right place destroy process. If join() throws InterrupedException, caller deal process destruction, if necessary, anyway. If hang in this loop in bug 529463 bug 529380 bug 470555, destroying process calling halt()? I notice TransportLocal() waits for process halts errorThread, TransportGitSsh halt errorThread destroys process. idea; try it</technical_language>

Target:
public void halt() throws InterruptedException { for (;;) { join(250 ); if (isAlive()) { done = true; interrupt(); if (process != null) { process.destroy(); } } else break; } }
Source:
<code><START> public Set<Map.Entry<String, JsonNode>> fields() { <END> return Collections.emptySet(); }</code><technical_language>I this fieldSet, is existing fields method (that returns Iterator)</technical_language>

Target:
public Iterator<Map.Entry<String, JsonNode>> fields() { return ClassUtil.emptyIterator(); }
Source:
<code>protected IStructuredSelection getSelection(ReflogView view) { ISelection pageSelection = view.getSelectionProvider().getSelection(); <START> if (pageSelection instanceof IStructuredSelection) { <END> return (IStructuredSelection) pageSelection; } else return new StructuredSelection(); }</code><technical_language>style-nit: remove curly brackets single line block</technical_language>

Target:
protected IStructuredSelection getSelection(ReflogView view) { ISelection pageSelection = view.getSelectionProvider().getSelection(); if (pageSelection instanceof IStructuredSelection) return (IStructuredSelection) pageSelection; else return new StructuredSelection(); }
Source:
<code>public String getLevel(String loggerName) { <START> java.util.logging.Logger logger = getLogger(loggerName); <END> return getEffectiveLevel(logger).toString(); }</code><technical_language>Inline this</technical_language>

Target:
public String getLevel(String loggerName) { return logging.getLevel(loggerName).toString(); }
Source:
<code>public void return_minimal_user_info() { db.users().insertUser(user -> user .setLogin("obiwan.kenobi") .setName("Obiwan Kenobi") .setEmail(null) .setLocal(true) .setExternalIdentity("obiwan") .setExternalIdentityProvider("sonarqube") .setScmAccounts((String) null)); userSessionRule.logIn("obiwan.kenobi"); CurrentWsResponse response = call(); assertThat(response) <START> .extracting(CurrentWsResponse::getIsLoggedIn, CurrentWsResponse::getLogin, CurrentWsResponse::getName, CurrentWsResponse::getAvatar, CurrentWsResponse::getLocal, <END> CurrentWsResponse::getExternalIdentity, CurrentWsResponse::getExternalProvider) .containsExactly(true, "obiwan.kenobi", "Obiwan Kenobi", "", true, "obiwan", "sonarqube"); assertThat(response.hasEmail()).isFalse(); assertThat(response.getScmAccountsList()).isEmpty(); assertThat(response.getGroupsList()).isEmpty(); assertThat(response.getPermissions().getGlobalList()).isEmpty(); }</code><technical_language>Please do check CurrentWsResponse::getAvatar CurrentWsResponse::hasAvatar expect false</technical_language>

Target:
public void return_minimal_user_info() { db.users().insertUser(user -> user .setLogin("obiwan.kenobi") .setName("Obiwan Kenobi") .setEmail(null) .setLocal(true) .setExternalIdentity("obiwan") .setExternalIdentityProvider("sonarqube") .setScmAccounts((String) null)); userSessionRule.logIn("obiwan.kenobi"); CurrentWsResponse response = call(); assertThat(response) .extracting(CurrentWsResponse::getIsLoggedIn, CurrentWsResponse::getLogin, CurrentWsResponse::getName, CurrentWsResponse::hasAvatar, CurrentWsResponse::getLocal, CurrentWsResponse::getExternalIdentity, CurrentWsResponse::getExternalProvider) .containsExactly(true, "obiwan.kenobi", "Obiwan Kenobi", false, true, "obiwan", "sonarqube"); assertThat(response.hasEmail()).isFalse(); assertThat(response.getScmAccountsList()).isEmpty(); assertThat(response.getGroupsList()).isEmpty(); assertThat(response.getPermissions().getGlobalList()).isEmpty(); }
Source:
<code>public byte[] toBytes(Object object) { if (object == null) { return ByteUtil.EMPTY_BYTE_ARRAY; } PhoenixJson phoenixJson = (PhoenixJson) object; <START> return PVarchar.INSTANCE.toBytes(phoenixJson.toString()); <END> }</code><technical_language>if delegate toBytes() call PhoenixJson. give flexibility cache byte[] if wanted to</technical_language>

Target:
public byte[] toBytes(Object object) { if (object == null) { return ByteUtil.EMPTY_BYTE_ARRAY; } PhoenixJson phoenixJson = (PhoenixJson) object; return phoenixJson.toBytes(); }
Source:
<code>private synchronized void enqueueMissingShards() { try { for (ShardMetadata shard : getMissingShards()) { stats.incrementBackgroundShardRecovery(); Futures.addCallback( shardQueue.submit(new MissingShard(shard.getShardUuid(), shard.getCompressedSize(), shard.getXxhash64(), false)), <START> failureCallback(t -> log.warn(t, "Error recovering shard: %s", shard.getShardUuid())), <END> directExecutor()); } } catch (Throwable t) { log.error(t, "Error creating shard recovery tasks"); } }</code><technical_language>if switch this addExceptionCallback() MoreFutures, delete failureCallback()</technical_language>

Target:
private synchronized void enqueueMissingShards() { try { for (ShardMetadata shard : getMissingShards()) { stats.incrementBackgroundShardRecovery(); ListenableFuture<?> future = shardQueue.submit(new MissingShard(shard.getShardUuid(), shard.getCompressedSize(), shard.getXxhash64(), false)); addExceptionCallback(future, t -> log.warn(t, "Error recovering shard: %s", shard.getShardUuid())); } } catch (Throwable t) { log.error(t, "Error creating shard recovery tasks"); } }
Source:
<code>public Observable<DeleteResult> createObservable() { <START> try { <END> throwExceptionIfRxJavaIsNotAvailable("createObservable()"); return Observable .create(OnSubscribeExecuteAsBlocking.newInstance(this)) .subscribeOn(Schedulers.io()); } catch (Throwable throwable) { throw new StorIOException(throwable); } }</code><technical_language>need try/catch in other createObservable() :)</technical_language>

Target:
public Observable<DeleteResult> createObservable() { throwExceptionIfRxJavaIsNotAvailable("createObservable()"); return Observable .create(OnSubscribeExecuteAsBlocking.newInstance(this)) .subscribeOn(Schedulers.io()); }
Source:
<code>public void clusteredCacheManagerExample() throws Exception { final CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder = CacheManagerBuilder.newCacheManagerBuilder() <START> .with(ClusteringServiceConfigurationBuilder.cluster(URI.create("<LINK_0>")).build()) <END> .withCache("simple-cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class) .withResourcePools(ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(10, EntryUnit.ENTRIES)) .build()); final PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true); cacheManager.close(); }</code><technical_language>build() is optional removed this doc sample</technical_language>

Target:
public void clusteredCacheManagerExample() throws Exception { final CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder = CacheManagerBuilder.newCacheManagerBuilder() .with(ClusteringServiceConfigurationBuilder.cluster(URI.create("<LINK_0>"))) .withCache("simple-cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class) .withResourcePools(ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(10, EntryUnit.ENTRIES))); final PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true); cacheManager.close(); }
Source:
<code>public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { String resourceName = request.getPathInfo().replaceFirst("^\\/", ""); String resourceFilePath = brandingManager.getCascadedResource(resourceName); ServletUtils.sendFile(request, response, <START> BrandingUtils.getFile(brandingManager.getBrandingRootPath(), resourceFilePath), null); <END> }</code><technical_language>XXX: Resource x = xxxx.getResource(resourceName) ServletUtils.sendFile(request, response, x.getFile(), x.getMimeType);</technical_language>

Target:
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { String resourceName = request.getPathInfo().replaceFirst("^\\/", ""); CascadingResource resource = brandingManager.getCascadingResource(resourceName); if (resource == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } else { ServletUtils.sendFile(request, response, resource.getFile(), resource.getContentType()); } }
Source:
<code>private static String indent(final int depth) { <START> String curIndent = new String(); <END> if (depth <= 0) { return null; } for (int i = 0; i < depth; i++) { curIndent += indent; } return curIndent; }</code><technical_language>a StringBuilder instead of a new String</technical_language>

Target:
private static String indent(final int depth) { StringBuilder stringBuilder = new StringBuilder(); if (depth <= 0) { return null; } for (int i = 0; i < depth; i++) { stringBuilder.append(indent); } return stringBuilder.toString(); }
Source:
<code>public BuildPlan getPlanById(List<IBuildPlan> plans, String id) { if (plans != null && id != null) { for (IBuildPlan plan : plans) { <START> if (id.equals(plan.getId())) { <END> return (BuildPlan) plan; } BuildPlan maybePlan = getPlanById(plan.getChildren(), id); if (maybePlan != null) { return maybePlan; } } } return null; }</code><technical_language>this benefit new flattened method (once moved I suggested) eg. for (plan : plans) { = flatten(plan).findAny(p -> id.equals(p.getId())); if (found.isPresent()) {return found.get();} }</technical_language>

Target:
public BuildPlan getPlanById(List<IBuildPlan> plans, String id) { if (plans != null && id != null) { for (IBuildPlan plan : plans) { for (IBuildPlan planOrChild : plan.getPlanAndAllChildren()) { if (id.equals(planOrChild.getId())) { return (BuildPlan) planOrChild; } } } } return null; }
Source:
<code>public boolean applyEffectBlock(ItemStack stack, World world, BlockPos pos, EnumFacing facing, double impactX, double impactY, double impactZ, EntityLivingBase caster) { switch (facing){ case EAST: pos = pos.east(); break; case NORTH: pos = pos.north(); break; case SOUTH: pos = pos.south(); break; case WEST: pos = pos.west(); <START> break; <END> } Block block = world.getBlockState(pos).getBlock(); if (world.isAirBlock(pos) || block == Blocks.snow || block instanceof BlockFlower){ if (!world.isRemote) world.setBlockState(pos, Blocks.fire.getDefaultState()); return true; }else{ pos = pos.up(); block = world.getBlockState(pos).getBlock(); if (world.isAirBlock(pos) || block == Blocks.snow || block instanceof BlockFlower){ if (!world.isRemote) world.setBlockState(pos, Blocks.fire.getDefaultState()); return true; } } return false; }</code><technical_language>pos = pos.offset(facing)</technical_language>

Target:
public boolean applyEffectBlock(ItemStack stack, World world, BlockPos pos, EnumFacing facing, double impactX, double impactY, double impactZ, EntityLivingBase caster) { pos = pos.offset(facing); Block block = world.getBlockState(pos).getBlock(); if (world.isAirBlock(pos) || block == Blocks.snow || block instanceof BlockFlower){ if (!world.isRemote) world.setBlockState(pos, Blocks.fire.getDefaultState()); return true; }else{ pos = pos.up(); block = world.getBlockState(pos).getBlock(); if (world.isAirBlock(pos) || block == Blocks.snow || block instanceof BlockFlower){ if (!world.isRemote) world.setBlockState(pos, Blocks.fire.getDefaultState()); return true; } } return false; }
Source:
<code>boolean exists(String name) { <START> for (V data : getDataList()) { <END> if (getDataName(data).equals(name)) { return true; } } return false; }</code><technical_language>this method a oneLiner: return find(...) != null</technical_language>

Target:
boolean exists(String name) { return find(name) != null; }
Source:
<code><START> private void prepareAuthForBrokerCall() throws NoSuchAlgorithmException { <END> AuthenticationSettings.INSTANCE.setUseBroker(true); }</code><technical_language>this function throw NoSuchAlgorithmException</technical_language>

Target:
private void prepareAuthForBrokerCall() { AuthenticationSettings.INSTANCE.setUseBroker(true); }
Source:
<code>public VSizeIndexedIntsWriter( final IOPeon ioPeon, final String filenameBase, final int maxValue ) { this.ioPeon = ioPeon; <START> this.filenameBase = filenameBase; <END> this.numBytes = VSizeIndexedInts.getNumBytesForMax(maxValue); }</code><technical_language>store filename = String.format("%s.%s", filenameBase, "values"); makeFilename called in multiple places</technical_language>

Target:
public VSizeIndexedIntsWriter( final IOPeon ioPeon, final String filenameBase, final int maxValue ) { this.ioPeon = ioPeon; this.valueFileName = String.format("%s.values", filenameBase); this.numBytes = VSizeIndexedInts.getNumBytesForMax(maxValue); }
Source:
<code>boolean taskIsCaughtUpOnClient(final TaskId task, final ID client) { boolean hasNoCaughtUpClients = true; final SortedSet<RankedClient<ID>> rankedClients = statefulTasksToRankedCandidates.get(task); if (rankedClients == null) { return true; } <START> for (final RankedClient rankedClient : rankedClients) { <END> if (rankedClient.rank() <= 0L) { if (rankedClient.clientId().equals(client)) { return true; } else { hasNoCaughtUpClients = false; } } if (rankedClient.rank() > 0L) { break; } } return hasNoCaughtUpClients; }</code><technical_language>Please avoid raw types, need type bound. suggestion for (final RankedClient<ID> rankedClient : rankedClients) {</technical_language>

Target:
boolean taskIsCaughtUpOnClient(final TaskId task, final ID client) { boolean hasNoCaughtUpClients = true; final SortedSet<RankedClient<ID>> rankedClients = statefulTasksToRankedCandidates.get(task); if (rankedClients == null) { return true; } for (final RankedClient<ID> rankedClient : rankedClients) { if (rankedClient.rank() <= 0L) { if (rankedClient.clientId().equals(client)) { return true; } else { hasNoCaughtUpClients = false; } } if (rankedClient.rank() > 0L) { break; } } return hasNoCaughtUpClients; }
Source:
<code>public void Union() throws SQLException { SubQueryExpression<Integer> sq1 = query().from(employee).select(employee.id.max()); SubQueryExpression<Integer> sq2 = query().from(employee).select(employee.id.min()); <START> List<Integer> list = query().union(sq1, sq2).fetch(); <END> assertFalse(list.isEmpty()); }</code><technical_language>list() is do need tests for it</technical_language>

Target:
public void Union() throws SQLException { SubQueryExpression<Integer> sq1 = query().from(employee).select(employee.id.max().as("ID")); SubQueryExpression<Integer> sq2 = query().from(employee).select(employee.id.min().as("ID")); assertEquals( ImmutableList.of(query().select(employee.id.min()).from(employee).fetchFirst(), query().select(employee.id.max()).from(employee).fetchFirst()), query().union(sq1, sq2).orderBy(employee.id.asc()).fetch()); }
Source:
<code>public void setImageServerContent(Map<String, String> imageServerContent) { this.imageServerContent = <START> imageServerContent; <END> }</code><technical_language>UmmutableMap.copyOf</technical_language>

Target:
public void setImageServerContent(Map<String, String> imageServerContent) { this.imageServerContent = ImmutableMap.copyOf(imageServerContent); }
Source:
<code>public void channelUnlinked(ChannelUID channelUID) { switch (channelUID.getId()) { case CHANNEL_SWITCH: for (Channel channel : channels) { channel.removeListener(channelUID); } break; default: <START> logger.warn("channel not supported in thing {}", channelUID.getId(), this.thing.getUID()); <END> } }</code><technical_language>a CHANNEL_CONTROL unlinked</technical_language>

Target:
public void channelUnlinked(ChannelUID channelUID) { switch (channelUID.getId()) { case CHANNEL_SWITCH: for (Channel channel : channels) { channel.removeListener(channelUID); } break; case CHANNEL_CONTROL: break; default: logger.debug("channel not supported in thing {}", channelUID.getId(), this.thing.getUID()); } }
Source:
<code>public Role build() { ImmutableMap.Builder<String, List<String>> immutableEnvRunList = ImmutableMap.builder(); for (Entry<String, List<String>> e : envRunList.entrySet()) { ImmutableList.Builder<String> value = ImmutableList.builder(); value.addAll(e.getValue()); <START> immutableEnvRunList.put(e.getKey(), value.build()); <END> } return new Role(name, description, defaultAttributes.build(), runList.build(), overrideAttributes.build(), immutableEnvRunList.build()); }</code><technical_language>need for a builder a list here. is more concise easier read? java immutableEnvRunList.put(e.getKey(), ImmutableList.copyOf(e.getValue())); more functional approach: java immutableEnv = Maps.transformValues(envRunList, new Function<List<String>, List<String>>() { @Override public List<String> apply(List<String> input) { return ImmutableList.copyOf(input); } });</technical_language>

Target:
public Role build() { Map<String, List<String>> immutableEnvRunList = Maps.transformValues(envRunList, new Function<List<String>, List<String>>() { @Override public List<String> apply(List<String> input) { return ImmutableList.copyOf(input); } }); return new Role(name, description, defaultAttributes.build(), runList.build(), overrideAttributes.build(), immutableEnvRunList); }
Source:
<code>private void startStatusReader() { final BufferedReader errorReader = new BufferedReader(new InputStreamReader(this.process.getErrorStream())); this.getTaskExecutor().execute(new Runnable() { @Override public void run() { String statusMessage; try { while ((statusMessage = errorReader.readLine()) != null) { publish(statusMessage); if (logger.isTraceEnabled()) { logger.trace(statusMessage); } } } catch (IOException e) { logger.error("Exception on tail error reader", e); } finally { try { errorReader.close(); } catch (IOException e) { <START> e.printStackTrace(); <END> } } } }); }</code><technical_language>this a logger call instead of printStackTrace</technical_language>

Target:
private void startStatusReader() { Process process = this.process; if (process == null) { if (logger.isDebugEnabled()) { logger.debug("Process destroyed before starting stderr reader"); } return; } final BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); this.getTaskExecutor().execute(new Runnable() { @Override public void run() { String statusMessage; if (logger.isDebugEnabled()) { logger.debug("Reading stderr"); } try { while ((statusMessage = errorReader.readLine()) != null) { publish(statusMessage); if (logger.isTraceEnabled()) { logger.trace(statusMessage); } } } catch (IOException e) { logger.error("Exception on tail error reader", e); } finally { try { errorReader.close(); } catch (IOException e) { logger.error("Exception while closing stderr", e); } } } }); }
Source:
<code>public void killBubble() { <START> timeEmpty++; <END> if(timeEmpty >= TIME_KILL) { this.kill(); addToLog("[BUBBLE]\t was empty and popped"); } }</code><technical_language>timeEmpty for of them, do reset this anywhere... this in mind constants? changing time affects time pops up. < bug</technical_language>

Target:
public void killBubble() { if(timeEmpty >= TIME_KILL) { this.kill(); addToLog("[BUBBLE]\t was empty and popped"); } }
Source:
<code>public Object evaluate(DeferredObject[] arguments) throws HiveException { result.clear(); try { if (arguments.length == 1 && argumentOI != null && arguments[0] != null) { String ip = ((StringObjectInspector) argumentOI).getPrimitiveJavaObject(arguments[0].get()); Map<String, Object> geoDataResult = geocode.getGeocodedData(ip); if (geoDataResult != null) { Object[] values = new Object[geoDataResult.keySet().size()]; int ct = 0; <START> for (String field : geoDataResult.keySet()) { <END> result.put(field, geoDataResult.get(field).toString()); } } } } catch (Exception ex) { LOG.error(ex); } return result; }</code><technical_language>ct values used</technical_language>

Target:
public Object evaluate(DeferredObject[] arguments) throws HiveException { result.clear(); try { if (arguments.length == 1 && argumentOI != null && arguments[0] != null) { String ip = ((StringObjectInspector) argumentOI).getPrimitiveJavaObject(arguments[0].get()); Map<String, Object> geoDataResult = geocode.getGeocodedData(ip); if (geoDataResult != null) { for (String field : geoDataResult.keySet()) { result.put(field, geoDataResult.get(field).toString()); } } } } catch (Exception ex) { LOG.error(ex); } return result; }
Source:
<code>private FilterIndexingServiceProvider findIndexingServiceProvider(IndexedFilter indexedFilter) { for (FilterIndexingServiceProvider provider : filterIndexingServiceProviders) { if (provider.supportsFilter(indexedFilter)) { return provider; } } <START> log.warnf("No indexing service provider found for indexed filter of type %s", indexedFilter.getClass().getName()); <END> return null; }</code><technical_language>Needs a Log method for internationalization</technical_language>

Target:
private FilterIndexingServiceProvider findIndexingServiceProvider(IndexedFilter indexedFilter) { for (FilterIndexingServiceProvider provider : filterIndexingServiceProviders) { if (provider.supportsFilter(indexedFilter)) { return provider; } } log.noFilterIndexingServiceProviderFound(indexedFilter.getClass().getName()); return null; }
Source:
<code>private void checkSequenceOfJavaInfo(Sequence<?> seq, String field) throws EvalException { <START> if (seq.stream().anyMatch(v -> !(v instanceof JavaInfo))) { <END> throw Starlark.errorf("Expected 'sequence of JavaInfo' for '%s'", field); } }</code><technical_language>opt: consider Streams. some amount of GC churn (or superstitious, "opt" tag)</technical_language>

Target:
private void checkSequenceOfJavaInfo(Sequence<?> seq, String field) throws EvalException { for (Object v : seq) { if (!(v instanceof JavaInfo)) { throw Starlark.errorf("Expected 'sequence of JavaInfo' for '%s'", field); } } }
Source:
<code>protected boolean canDoAction() { StorageServerConnectionExtension conn = getParameters().getStorageServerConnectionExtension(); return validate(getConnectionExtensionValidator().isConnectionExtensionExists(conn.getId())) && <START> validate(getConnectionExtensionValidator().isConnectionDoesNotExistForHostAndTarget(conn.getHostId(), <END> conn.getIqn())); }</code><technical_language>do this in previous patch already</technical_language>

Target:
protected boolean canDoAction() { StorageServerConnectionExtension conn = getParameters().getStorageServerConnectionExtension(); return validate(getConnectionExtensionValidator().isConnectionExtensionExists(conn.getId())) && validate(getConnectionExtensionValidator().isConnectionDoesNotExistForHostAndTarget(conn)); }
Source:
<code><START> public Boolean call() { <END> try { String expectedValue = generateDataString(ledgerId, entryId); ByteBuf byteBuf = ledgerStorage.getEntry(ledgerId, entryId); long actualLedgerId = byteBuf.readLong(); long actualEntryId = byteBuf.readLong(); byte[] data = new byte[byteBuf.readableBytes()]; byteBuf.readBytes(data); if (ledgerId != actualLedgerId) { LOG.error("For ledgerId: entryId: readRequest, actual ledgerId: {}", ledgerId, entryId, actualLedgerId); return false; } if (entryId != actualEntryId) { LOG.error("For ledgerId: entryId: readRequest, actual entryId: {}", ledgerId, entryId, actualEntryId); return false; } if (!expectedValue.equals(new String(data))) { LOG.error("For ledgerId: entryId: readRequest, actual Data: {}", ledgerId, entryId, new String(data)); return false; } } catch (IOException e) { LOG.error("Got Exception for GetEntry call. LedgerId: " + ledgerId + " entryId: " + entryId, e); return false; } return true; }</code><technical_language>Instead of returning false errors, throw Exception, carry context of error (ledger id, entry id etc). This simplify loops in test itself, do get ledger entry id, in exception message. In fact, loop reduced executor.invokeAll(writeTasks, 6, TimeUnit.SECONDS).forEach(f -> f.join())</technical_language>

Target:
public Boolean call() throws IOException { try { ByteBuf expectedByteBuf = generateEntry(ledgerId, entryId); ByteBuf actualByteBuf = ledgerStorage.getEntry(ledgerId, entryId); if (!expectedByteBuf.equals(actualByteBuf)) { LOG.error("Expected Entry: Actual Entry: {}", expectedByteBuf.toString(Charset.defaultCharset()), actualByteBuf.toString(Charset.defaultCharset())); throw new IOException("Expected Entry: " + expectedByteBuf.toString(Charset.defaultCharset()) + " Actual Entry: " + actualByteBuf.toString(Charset.defaultCharset())); } } catch (IOException e) { LOG.error("Got Exception for GetEntry call. LedgerId: " + ledgerId + " entryId: " + entryId, e); throw new IOException("Got Exception for GetEntry call. LedgerId: " + ledgerId + " entryId: " + entryId, e); } return true; }
Source:
<code>public void addContents(@NonNull Container container) { container.add(new PrintedContent("loggers.md") { @Override protected void printTo(PrintWriter out) throws IOException { out.println("Loggers currently enabled"); out.println("========================="); LogManager logManager = LogManager.getLogManager(); Enumeration<String> loggerNames = logManager.getLoggerNames(); while (loggerNames.hasMoreElements()) { String loggerName = loggerNames.nextElement(); if (logManager.getLogger(loggerName) != null) { <START> Level level = logManager.getLogger(loggerName).getLevel(); <END> if (level != null) { out.println(loggerName + " - " + level); } } } } }); }</code><technical_language>logManager.getLogger(loggerName) a variable</technical_language>

Target:
public void addContents(@NonNull Container container) { container.add(new PrintedContent("loggers.md") { @Override protected void printTo(PrintWriter out) throws IOException { out.println("Loggers currently enabled"); out.println("========================="); LogManager logManager = LogManager.getLogManager(); Enumeration<String> loggerNames = logManager.getLoggerNames(); while (loggerNames.hasMoreElements()) { String loggerName = loggerNames.nextElement(); Logger loggerByName = logManager.getLogger(loggerName); if (loggerByName != null) { Level level = loggerByName.getLevel(); if (level != null) { out.println(loggerName + " - " + level); } } } } }); }
Source:
<code>public void run() { while (!Thread.currentThread().isInterrupted()) { try { TellstickSendEvent sendEvent; END synchronized (messageQue) { while (messageQue.isEmpty()) { messageQue.wait(); } sendEvent = messageQue.remove(messageQue.firstKey()); } END EVENT try { handleSendEvent(sendEvent.getConfig(), sendEvent.getDev(), sendEvent.getCommand()); } catch (TellstickException e) { <START> logger.error("Failed to send msg to " + sendEvent.getConfig(), e); <END> } } catch (InterruptedException ie) { break; } } }</code><technical_language>parameterized logging instead of string concatenation</technical_language>

Target:
public void run() { while (!Thread.currentThread().isInterrupted()) { try { TellstickSendEvent sendEvent; END synchronized (messageQue) { while (messageQue.isEmpty()) { messageQue.wait(); } sendEvent = messageQue.remove(messageQue.firstKey()); } END EVENT try { handleSendEvent(sendEvent.getConfig(), sendEvent.getDev(), sendEvent.getCommand()); } catch (TellstickException e) { logger.error("Failed to send msg to {}, error: {}", sendEvent.getConfig(), e); } } catch (InterruptedException ie) { break; } } }
Source:
<code>protected FeatureWriter<SimpleFeatureType, SimpleFeature> getWriterInternal( Query query, int flags) throws IOException { if (flags == 0) { throw new IllegalArgumentException("no write flags set"); } ShapefileFeatureReader reader = (ShapefileFeatureReader) delegate.getReaderInternal(Query.ALL); ShapefileFeatureWriter writer; ShapefileDataStore ds = getDataStore(); if (ds.indexManager.hasFidIndex(false) || ds.isFidIndexed() && ds.indexManager.hasFidIndex(true)) { writer = new IndexedShapefileFeatureWriter( ds.indexManager, reader, ds.getCharset(), ds.getTimeZone()); } else { <START> if (ds.indexManager.isIndexStale(ShpFileType.FIX)) { <END> ds.indexManager.createFidIndex(); } writer = new ShapefileFeatureWriter( delegate.shpFiles, reader, ds.getCharset(), ds.getTimeZone()); } writer.setMaxShpSize(getDataStore().getMaxShpSize()); writer.setMaxDbfSize(getDataStore().getMaxDbfSize()); if ((flags | WRITER_ADD) == WRITER_ADD) { while (writer.hasNext()) { writer.next(); } } Filter filter = query.getFilter(); if (filter != null && !Filter.INCLUDE.equals(filter)) { return new FilteringFeatureWriter(writer, filter); } else { return writer; } }</code><technical_language>This create fix file if missing, if missing fid remapping, waste time create a fid index in place? least, check if file exists (maybe isIndexStyle needs a flag check if file exists stating outdate)</technical_language>

Target:
protected FeatureWriter<SimpleFeatureType, SimpleFeature> getWriterInternal( Query query, int flags) throws IOException { if (flags == 0) { throw new IllegalArgumentException("no write flags set"); } ShapefileFeatureReader reader = (ShapefileFeatureReader) delegate.getReaderInternal(Query.ALL); ShapefileFeatureWriter writer; ShapefileDataStore ds = getDataStore(); if (ds.indexManager.hasFidIndex(false) || ds.isFidIndexed() && ds.indexManager.hasFidIndex(true)) { writer = new IndexedShapefileFeatureWriter( ds.indexManager, reader, ds.getCharset(), ds.getTimeZone()); } else { writer = new ShapefileFeatureWriter( delegate.shpFiles, reader, ds.getCharset(), ds.getTimeZone()); } writer.setMaxShpSize(getDataStore().getMaxShpSize()); writer.setMaxDbfSize(getDataStore().getMaxDbfSize()); if ((flags | WRITER_ADD) == WRITER_ADD) { while (writer.hasNext()) { writer.next(); } } Filter filter = query.getFilter(); if (filter != null && !Filter.INCLUDE.equals(filter)) { return new FilteringFeatureWriter(writer, filter); } else { return writer; } }
Source:
<code>public void testQueryDirectSqlQuery() { final ContentResolver cr = getContext().getContentResolver(); Cursor cursor = cr.query(FlashCardsContract.Note.SQL_QUERY_URI, null, String.format("mid=%d", mModelId), null, null); assertNotNull(cursor); try { assertEquals("Check number of results", mCreatedNotes.size(), cursor.getCount()); } finally { cursor.close(); } <START> cursor = cr.query(FlashCardsContract.Note.SQL_QUERY_URI, null, "mid=0", null, null); <END> assertNotNull(cursor); try { assertEquals("Check number of results", 0, cursor.getCount()); } finally { cursor.close(); } }</code><technical_language>add a check for "mid=?", new String[] {"0"}</technical_language>

Target:
public void testQueryDirectSqlQuery() { final ContentResolver cr = getContext().getContentResolver(); Cursor cursor = cr.query(FlashCardsContract.Note.CONTENT_URI_V2, null, String.format("mid=%d", mModelId), null, null); assertNotNull(cursor); try { assertEquals("Check number of results", mCreatedNotes.size(), cursor.getCount()); } finally { cursor.close(); } cursor = cr.query(FlashCardsContract.Note.CONTENT_URI_V2, null, "mid=0", null, null); assertNotNull(cursor); try { assertEquals("Check number of results", 0, cursor.getCount()); } finally { cursor.close(); } cursor = cr.query(FlashCardsContract.Note.CONTENT_URI_V2, null, "mid=?", new String[]{"0"}, null); assertNotNull(cursor); }
Source:
<code>public void testStaticWebsiteListingsCSS() { Multimap<String, String> headers = ImmutableMultimap.of(STATIC_WEB_LISTINGS_CSS, "listings.css"); UpdateContainerOptions options = new UpdateContainerOptions().headers(headers); <START> assertEquals(ImmutableList.of("listings.css"), options.buildRequestHeaders().get(STATIC_WEB_LISTINGS_CSS)); <END> }</code><technical_language>above, assertions wrong around</technical_language>

Target:
public void testStaticWebsiteListingsCSS() { Multimap<String, String> headers = ImmutableMultimap.of(STATIC_WEB_LISTINGS_CSS, "listings.css"); UpdateContainerOptions options = new UpdateContainerOptions().headers(headers); assertEquals(options.buildRequestHeaders().get(STATIC_WEB_LISTINGS_CSS), ImmutableList.of("listings.css")); }
Source:
<code>public void sendRequest(Exchange exchange, Request request){ Request req = request; if(shouldProtectRequest(request)){ try { String uri = request.getURI(); OSCoreCtxDB db = HashMapCtxDB.getInstance(); if(uri == null){ LOGGER.severe(OSExceptionHandler.URI_NULL); throw new IllegalArgumentException(OSExceptionHandler.URI_NULL); } if(db == null){ LOGGER.severe(OSExceptionHandler.DB_NULL); throw new IllegalArgumentException(OSExceptionHandler.DB_NULL); } OSCoreCtx ctx = db.getContext(uri); if( ctx == null){ LOGGER.severe(OSExceptionHandler.CTX_NULL); throw new IllegalArgumentException(OSExceptionHandler.CTX_NULL); } exchange.setCryptographicContextID(ctx.getRecipientId()); int seqByToken = ctx.getSenderSeq(); <START> int realCode = request.getCode().value; <END> request = OptionJuggle.setFakeCodeRequest(request); req = prepareSend(request, ctx, realCode); if (req.getToken() != null) { db.addContext(request.getToken(), ctx); db.addSeqByToken(request.getToken(), seqByToken); } else { Token token = db.generateToken(); req.setToken(token); db.addContext(req.getToken(), ctx); db.addSeqByToken(token, seqByToken); } } catch (OSException e) { LOGGER.severe("Error sending request: " + e.getMessage()); return; } catch (IllegalArgumentException e){ LOGGER.severe("Unable to send request because of illegal argument: " + e.getMessage()); return; } } LOGGER.finest("Request: " + exchange.getRequest().toString()); super.sendRequest(exchange, req); }</code><technical_language>is realCode extracted passed methods request</technical_language>

Target:
public void sendRequest(Exchange exchange, Request request) { Request req = request; if (shouldProtectRequest(request)) { try { String uri = request.getURI(); final OSCoreCtxDB db = HashMapCtxDB.getInstance(); if (uri == null) { LOGGER.error(Error.URI_NULL); throw new OSException(Error.URI_NULL); } if (db == null) { LOGGER.error(Error.DB_NULL); throw new OSException(Error.DB_NULL); } final OSCoreCtx ctx = db.getContext(uri); if (ctx == null) { LOGGER.error(Error.CTX_NULL); throw new OSException(Error.CTX_NULL); } exchange.setCryptographicContextID(ctx.getRecipientId()); final int seqByToken = ctx.getSenderSeq(); final Request preparedRequest = prepareSend(request, ctx); preparedRequest.addMessageObserver(new MessageObserverAdapter() { @Override public void onReadyToSend() { Token token = preparedRequest.getToken(); db.addContext(token, ctx); db.addSeqByToken(token, seqByToken); } }); req = preparedRequest; if (req.getToken() != null) { db.addContext(request.getToken(), ctx); db.addSeqByToken(request.getToken(), seqByToken); } } catch (OSException e) { LOGGER.error("Error sending request: " + e.getMessage()); return; } catch (IllegalArgumentException e) { LOGGER.error("Unable to send request because of illegal argument: " + e.getMessage()); return; } } LOGGER.info("Request: " + exchange.getRequest().toString()); super.sendRequest(exchange, req); }
Source:
<code>private void showNewPostsBar() { if (!isAdded() || isNewPostsBarShowing()) { return; } AniUtils.startAnimation(mNewPostsBar, R.anim.reader_top_bar_in); mNewPostsBar.setVisibility(View.VISIBLE); mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); if (dy >= mHideNewPostsBarOnScrollOffset) { hideNewPostsBar(); <START> } <END> } }); getPostAdapter().removeGapMarker(); }</code><technical_language>I onScrolled callback called repeatedly hideNewPostsBar called repeatedly (even do if animation is performed, I method). Also, a new listener is created added time showNewPostsBar is called, leading potentially onScrolled listeners living there. I this covered clearOnScrollListeners call in hideNewPostsBar, a potential bug in case adds a new onScrolled listener for a purpose in future. a good instance of scroll listener a reference in a class member (then add recycler view in onStart call removeOnScrollListener in onStop) , continue anonymous instance removed this fx hideNewPostsBar() called</technical_language>

Target:
private void showNewPostsBar() { if (!isAdded() || isNewPostsBarShowing()) { return; } AniUtils.startAnimation(mNewPostsBar, R.anim.reader_top_bar_in); mNewPostsBar.setVisibility(View.VISIBLE); mRecyclerView.postDelayed(new Runnable() { @Override public void run() { if (isAdded() && isNewPostsBarShowing()) { mRecyclerView.addOnScrollListener(mOnScrollListener); } } }, 1000L); getPostAdapter().removeGapMarker(); }
Source:
<code>public void setComparator(Comparator<Format> comparator) { <START> if(this.comparator != comparator) { <END> this.comparator = comparator; } }</code><technical_language>real benefit this check, get rid of do this.comparator = comparator directly)</technical_language>

Target:
public void setComparator(Comparator<Format> comparator) { this.comparator = comparator; }
Source:
<code>private void addRemoveRowColumn() { ButtonCell buttonCell = new ButtonCell(IconType.TRASH, ButtonType.DANGER, ButtonSize.SMALL); Column<ObjectProperty, String> column = new Column<ObjectProperty, String>(buttonCell) { @Override public String getValue(ObjectProperty objectProperty) { return Constants.INSTANCE.objectBrowser_action_delete(); } }; column.setFieldUpdater(new FieldUpdater<ObjectProperty, String>() { @Override public void update(int index, ObjectProperty objectProperty, String value) { if (!readonly) { safeObjectPropertyDelete(objectProperty, index); } } }); <START> <END> propertiesTable.addColumn(column, ""); propertiesTable.setColumnWidth(column, calculateButtonSize(Constants.INSTANCE.objectBrowser_action_delete()), Style.Unit.PX); }</code><technical_language>@mcimbora I changes approach is good, invocation ValidatonService this logic in Presenter</technical_language>

Target:
private void addRemoveRowColumn() { ButtonCell buttonCell = new ButtonCell(IconType.TRASH, ButtonType.DANGER, ButtonSize.SMALL); Column<ObjectProperty, String> column = new Column<ObjectProperty, String>(buttonCell) { @Override public String getValue(ObjectProperty objectProperty) { return Constants.INSTANCE.objectBrowser_action_delete(); } }; column.setFieldUpdater(new FieldUpdater<ObjectProperty, String>() { @Override public void update(int index, ObjectProperty objectProperty, String value) { if (!readonly) { presenter.onDeleteProperty(objectProperty, index); } } }); propertiesTable.addColumn(column, ""); propertiesTable.setColumnWidth(column, calculateButtonSize(Constants.INSTANCE.objectBrowser_action_delete()), Style.Unit.PX); }
Source:
<code><START> public String canonicalID() { <END> return canonical; }</code><technical_language>this non-final? important this method is for serialization/internal representation, pretty important overridden</technical_language>

Target:
public final String canonicalID() { return canonical; }
Source:
<code>public <T extends Info> T getById(final String id, final Class<T> type) { Assert.notNull(id, "id"); Info info = null; try { final Callable<? extends Info> valueLoader; if (CatalogInfo.class.isAssignableFrom(type)) { valueLoader = new CatalogLoader(id); } else { valueLoader = new ConfigLoader(id); } Semaphore lock = locks.get(id); if (lock == null) { lock = new Semaphore(1); locks.put(id, lock); <START> } <END> info = cache.getIfPresent(id); if (info == null) { if (lock.tryAcquire()) { try { info = cache.get(id, valueLoader); } finally { lock.release(); } } } if (info == null) { try { info = valueLoader.call(); } catch (Exception e) { throw new ExecutionException(e); } } } catch (CacheLoader.InvalidCacheLoadException notFound) { return null; } catch (ExecutionException e) { Throwables.propagate(e.getCause()); } if (info == null) { return null; } if (info instanceof CatalogInfo) { info = resolveCatalog((CatalogInfo) info); } else if (info instanceof ServiceInfo) { resolveTransient((ServiceInfo) info); } if (type.isAssignableFrom(info.getClass())) { return ModificationProxy.create(type.cast(info), type); } return null; }</code><technical_language>matter this code block (and in acquireWriteLock) performed atomically using: java.util.concurrent.ConcurrentHashMap.computeIfAbsent(K, Function<? super K, ? extends V>) Semaphore lock = locks.computeIfAbsent(id, x -> new Semaphore(1));</technical_language>

Target:
public <T extends Info> T getById(final String id, final Class<T> type) { Assert.notNull(id, "id"); Info info = null; try { final Callable<? extends Info> valueLoader; if (CatalogInfo.class.isAssignableFrom(type)) { valueLoader = new CatalogLoader(id); } else { valueLoader = new ConfigLoader(id); } Semaphore lock = locks.computeIfAbsent(id, x -> new Semaphore(1)); info = cache.getIfPresent(id); if (info == null) { if (lock.tryAcquire()) { try { info = cache.get(id, valueLoader); } finally { lock.release(); } } } if (info == null) { try { info = valueLoader.call(); } catch (Exception e) { throw new ExecutionException(e); } } } catch (CacheLoader.InvalidCacheLoadException notFound) { return null; } catch (ExecutionException e) { Throwables.propagate(e.getCause()); } if (info == null) { return null; } if (info instanceof CatalogInfo) { info = resolveCatalog((CatalogInfo) info); } else if (info instanceof ServiceInfo) { resolveTransient((ServiceInfo) info); } if (type.isAssignableFrom(info.getClass())) { return ModificationProxy.create(type.cast(info), type); } return null; }
Source:
<code>public ExtensionEntry(File file) throws IOException { this.file = file; context = new EnumMap<>(ExtensionProperties.class); Properties props = new Properties(); try (FileInputStream inputStream = new FileInputStream(file)) { props.load(inputStream); context.put(ExtensionProperties.CONFIGURATION, props); context.put(ExtensionProperties.NAME, props.getProperty(NAME)); context.put(ExtensionProperties.PROVIDES, props.getProperty(PROVIDES)); <START> Module module = loadModule(props.getProperty(MODULE)); <END> this.extension = createExtension(module); } }</code><technical_language>do ned module temp variable</technical_language>

Target:
public ExtensionEntry(File file) throws IOException { this.file = file; context = new EnumMap<>(ExtensionProperties.class); Properties props = new Properties(); try (FileInputStream inputStream = new FileInputStream(file)) { enabled = props.get(ENABLED) != null ? Boolean.parseBoolean((String) props.get(ENABLED)) : true; props.load(inputStream); context.put(ExtensionProperties.CONFIGURATION, props); context.put(ExtensionProperties.NAME, props.getProperty(NAME)); context.put(ExtensionProperties.PROVIDES, props.getProperty(PROVIDES)); } }
Source:
<code>private void initializeSlot(int dimIndex) { <START> final int index = dimIndex / 8; <END> final int extraIndex = dimIndex % 8; usedFlagBuffer.put(index, (byte) (usedFlagBuffer.get(index) | 1 << extraIndex)); final int recordOffset = dimIndex * recordSize; for (int i = 0; i < aggregators.length; i++) { aggregators[i].init(valBuffer, recordOffset + aggregatorOffsets[i]); } }</code><technical_language>Byte.SIZE</technical_language>

Target:
private void initializeSlot(int dimIndex) { final int index = dimIndex / Byte.SIZE; final int extraIndex = dimIndex % Byte.SIZE; usedFlagBuffer.put(index, (byte) (usedFlagBuffer.get(index) | (1 << extraIndex))); final int recordOffset = dimIndex * recordSize; for (int i = 0; i < aggregators.length; i++) { aggregators[i].init(valBuffer, recordOffset + aggregatorOffsets[i]); } }
Source:
<code>private void drawVariables(List<UserVariable> variableList, Batch batch) { if (variableList == null) { return; } if (variableToShow.isDummy()) { drawText(batch, Constants.NO_VARIABLE_SELECTED, xPosition, yPosition); } else { for (UserVariable variable : variableList) { if (variable.getName().equals(variableToShow.getName())) { String variableValue = variable.getValue().toString(); if (variable.getVisible()) { if (isNumberAndInteger(variableValue)) { drawText(batch, variableValueWithoutDecimal, xPosition, yPosition); } else if (variable.getValue().toString().isEmpty()) { <START> drawText(batch, Constants.NO_VALUE_SET, xPosition - 200, yPosition); <END> } else { drawText(batch, variableValue, xPosition, yPosition); } } break; } } } }</code><technical_language>200. If list multiple variables (same x position, other), arranged nicely. positioning inconsistent other options (number, text, variable set)</technical_language>

Target:
private void drawVariables(List<UserVariable> variableList, Batch batch) { if (variableList == null) { return; } if (variableToShow.isDummy()) { drawText(batch, Constants.NO_VARIABLE_SELECTED, xPosition, yPosition); } else { for (UserVariable variable : variableList) { if (variable.getName().equals(variableToShow.getName())) { String variableValue = variable.getValue().toString(); if (variable.getVisible()) { if (isNumberAndInteger(variableValue)) { drawText(batch, variableValueWithoutDecimal, xPosition, yPosition); } else if (variableValue.isEmpty()) { drawText(batch, Constants.NO_VALUE_SET, xPosition, yPosition); } else { drawText(batch, variableValue, xPosition, yPosition); } } break; } } } }
Source:
<code>public void testNaNValuesResult() { String url = UriComponentsBuilder.fromUriString(urlPattern).buildAndExpand(ARABIDOPSIS_SPECIES, GENE_IDS).encode().toUriString(); mockServer.expect(requestTo(url)) .andExpect(method(HttpMethod.GET)) .andRespond(withSuccess(TSV_WITH_NAN, MediaType.TEXT_PLAIN)); List<String> bioentityIdentifiers = Arrays.asList(GENE_IDS.split("\\W+")); Pair<Optional<Exception>, Optional<JsonArray>> result = subject.fetchEnrichedGenes(ARABIDOPSIS_SPECIES, bioentityIdentifiers); assertThat(jsonPath("$", hasSize(2))); <START> assertThat(jsonPath("$[0].effect_size", is(Double.NaN))); <END> assertThat(jsonPath("$[1].effect_size", is(3.2))); }</code><technical_language>This produce incorrect JSON: {..., "effect_size": NaN, ...} I guess a alternative avoid a SyntaxError DataTables is for NaN a string</technical_language>

Target:
public void testNaNValuesResult() { String url = UriComponentsBuilder.fromUriString(urlPattern).buildAndExpand(ARABIDOPSIS_SPECIES, GENE_IDS).encode().toUriString(); mockServer.expect(requestTo(url)) .andExpect(method(HttpMethod.GET)) .andRespond(withSuccess(TSV_WITH_NAN, MediaType.TEXT_PLAIN)); List<String> bioentityIdentifiers = Arrays.asList(GENE_IDS.split("\\W+")); Pair<Optional<Exception>, Optional<JsonArray>> result = subject.fetchEnrichedGenes(ARABIDOPSIS_SPECIES, bioentityIdentifiers); assertThat(jsonPath("$", hasSize(2))); assertThat(jsonPath("$[0].effect_size", is("NaN"))); assertThat(jsonPath("$[1].effect_size", is(3.2))); }
Source:
<code>private static QualifiedName getPrefix(UseStatementTree useStatementTree) { QualifiedName namespacePrefix; if (useStatementTree.prefix() != null) { namespacePrefix = QualifiedName.create(useStatementTree.prefix()); } else { namespacePrefix = null; } <START> return namespacePrefix; <END> }</code><technical_language>following? NamespaceNameTree prefix = useStatementTree.prefix(); return prefix == null ? null : QualifiedName.create(prefix);</technical_language>

Target:
private static QualifiedName getPrefix(UseStatementTree useStatementTree) { NamespaceNameTree prefix = useStatementTree.prefix(); return prefix == null ? null : QualifiedName.create(prefix); }
Source:
<code>public byte[] generateByteArray() { <START> checksum = new XBeeChecksum(); <END> checksum.reset(); byte[] packetData = getPacketData(); ByteArrayOutputStream os = new ByteArrayOutputStream(); os.write(SpecialByte.HEADER_BYTE.getValue()); if (packetData != null) { byte[] length = ByteUtils.shortToByteArray((short)packetData.length); int msb = length[0]; int lsb = length[1]; os.write(msb); os.write(lsb); for (int i = 0; i < packetData.length; i++) { checksum.add(packetData[i]); os.write(packetData[i]); } } else { os.write(0); os.write(0); } os.write((byte)checksum.generate() & 0xFF); return os.toByteArray(); }</code><technical_language>If generate checksum field in constructor, reset enough regenerate</technical_language>

Target:
public byte[] generateByteArray() { checksum.reset(); byte[] packetData = getPacketData(); ByteArrayOutputStream os = new ByteArrayOutputStream(); os.write(SpecialByte.HEADER_BYTE.getValue()); if (packetData != null) { byte[] length = ByteUtils.shortToByteArray((short)packetData.length); int msb = length[0]; int lsb = length[1]; os.write(msb); os.write(lsb); for (int i = 0; i < packetData.length; i++) { checksum.add(packetData[i]); os.write(packetData[i]); } } else { os.write(0); os.write(0); } os.write((byte)checksum.generate() & 0xFF); return os.toByteArray(); }