auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void addGrinderRecipes( IAppEngApi api, ItemStack grindstone, RecipeGenerator generator ) { ItemStack handle = api.definitions().blocks().crankHandle().maybeStack(1).orNull(); Slot[] grinderSlots = new ItemSlot[] { new ItemSlot( 3, 21, 16, 16 ).drawOwnBackground(), new ItemSlot( 41, 21, 16, 16, true ).drawOwnBackground().setSlotType( SlotType.OUTPUT_SLOT ), new ChanceSlot( 59, 12, 16, 16, true).setRatio( 10000 ).setFormatString( " (%1$.2f%% chance)" ).drawOwnBackground().setSlotType( SlotType.OUTPUT_SLOT ), new ChanceSlot( 59, 30, 16, 16, true).setRatio( 10000 ).setFormatString( " (%1$.2f%% chance)" ).drawOwnBackground().setSlotType( SlotType.OUTPUT_SLOT ), new ExtraSlot( 22, 12, 16, 16, handle ).clickable( true ).showName( true ).setSlotType( SlotType.MACHINE_SLOT ), <START> new ExtraSlot( 22, 30, 16, 16, grindstone ).clickable( true ).showName( true ).setSlotType( SlotType.MACHINE_SLOT ) }; <END> RecipeTemplate grinderTemplate = generator.createRecipeTemplate( grinderSlots, grindstone ); for( IGrinderEntry recipe : api.registries().grinder().getRecipes() ) { generator.addRecipe( grinderTemplate, new Object[] { recipe.getInput(), recipe.getOutput(), new Object[] { recipe.getOptionalOutput(), (int)(recipe.getOptionalChance() * 10000) }, new Object[] { recipe.getSecondOptionalOutput(), (int)(recipe.getOptionalChance() * 10000) }, handle, grindstone }); } }</code><technical_language>extracted a constant similar smallCraftingSlots? share instance, smallCraftingSlots questionable? is a slight performance memory regression creating actual constant object for recipe</technical_language>

Target:
private void addGrinderRecipes( IAppEngApi api, ItemStack grindstone, RecipeGenerator generator ) { ItemStack handle = api.definitions().blocks().crankHandle().maybeStack(1).orNull(); RecipeTemplate grinderTemplate = generator.createRecipeTemplate( grinderSlots, grindstone ); for( IGrinderEntry recipe : api.registries().grinder().getRecipes() ) { generator.addRecipe( grinderTemplate, new Object[] { recipe.getInput(), recipe.getOutput(), new Object[] { recipe.getOptionalOutput(), (int)(recipe.getOptionalChance() * 10000) }, new Object[] { recipe.getSecondOptionalOutput(), (int)(recipe.getOptionalChance() * 10000) }, handle, grindstone }); } }
Source:
<code>public static void stop(String igniteInstanceName, boolean cancel) { final IgniteProcessProxy proxy = gridProxies.get(igniteInstanceName); if (proxy != null) { final CountDownLatch rmtNodeStoppedLatch = new CountDownLatch(1); final UUID rmNodeId = proxy.id; proxy.locJvmGrid.events().localListen(new IgnitePredicateX<Event>() { @Override public boolean applyx(Event e) { if (((DiscoveryEvent)e).eventNode().id().equals(rmNodeId)) { rmtNodeStoppedLatch.countDown(); return false; } return true; } }, EventType.EVT_NODE_LEFT); proxy.remoteCompute().runAsync(new StopGridTask(igniteInstanceName, cancel)); try { <START> assert rmtNodeStoppedLatch.await(NODE_LEFT_TIMEOUT, TimeUnit.MILLISECONDS) : "Remote node has not stopped [id=" + rmNodeId + ']'; <END> } catch (InterruptedException e) { throw new IgniteException(e); } gridProxies.remove(igniteInstanceName, proxy); } }</code><technical_language>long string</technical_language>

Target:
public static void stop(String igniteInstanceName, boolean cancel) throws Exception { final IgniteProcessProxy proxy = gridProxies.get(igniteInstanceName); if (proxy != null) { final CountDownLatch rmtNodeStoppedLatch = new CountDownLatch(1); final UUID rmNodeId = proxy.getId(); proxy.locJvmGrid.events().localListen(new IgnitePredicateX<Event>() { @Override public boolean applyx(Event e) { if (((DiscoveryEvent)e).eventNode().id().equals(rmNodeId)) { rmtNodeStoppedLatch.countDown(); return false; } return true; } }, EventType.EVT_NODE_LEFT); try { proxy.remoteCompute().runAsync(new StopGridTask(igniteInstanceName, cancel)); if (!rmtNodeStoppedLatch.await(NODE_LEFT_TIMEOUT, TimeUnit.MILLISECONDS)) throw new IllegalStateException("Remote node has not stopped [id=" + rmNodeId + ']'); } catch (Throwable t) { proxy.log().error("Failed to stop grid [igniteInstanceName=" + igniteInstanceName + ", cancel=" + cancel + ']', t); throw t; } gridProxies.remove(igniteInstanceName, proxy); } }
Source:
<code>public boolean matches(final URI uri, final String abstractType, final String abstractTypeAuthority, final String purpose) { String host = uri.getHost(); if (host.startsWith("[") && host.endsWith("]")) { try { <START> host = InetAddress.getByName(host).getCanonicalHostName(); <END> } catch (UnknownHostException e) { log.warnf(e, "Invalid IPv6 address: %s", host); } } return host != null && host.startsWith(hostSpec) && super.matches(uri, abstractType, abstractTypeAuthority, purpose); }</code><technical_language>This a reverse DNS lookup - do *not* want</technical_language>

Target:
public boolean matches(final URI uri, final String abstractType, final String abstractTypeAuthority, final String purpose) { String host = uri.getHost(); if (host == null) { return false; } byte[] hostBytes; if (host.startsWith("[") && host.endsWith("]")) { hostBytes = Inet.parseInet6AddressToBytes(host); } else { hostBytes = Inet.parseInet4AddressToBytes(host); } if (hostBytes != null && this.hostSpecBytes != null) { return Arrays.equals(hostBytes, this.hostSpecBytes) && super.matches(uri, abstractType, abstractTypeAuthority, purpose); } else { return host.toLowerCase(Locale.ROOT).equals(hostSpec) && super.matches(uri, abstractType, abstractTypeAuthority, purpose); } }
Source:
<code>public boolean sleep() { attempt++; long currentTimeMillis = Clock.currentTimeMillis(); if (currentTimeMillis > clusterConnectDeadline) { <START> logger.warning(String.format("Unable to get live cluster connection, cluster connect timeout %d seconds is " <END> + "reached. Attempt %d.", clusterConnectTimeoutSeconds, attempt)); return false; } long actualSleepTime = (long) (currentBackoffMillis - (currentBackoffMillis * jitter) + (currentBackoffMillis * jitter * random.nextDouble())); actualSleepTime = Math.min(actualSleepTime, clusterConnectDeadline - currentTimeMillis); logger.warning(String.format("Unable to get live cluster connection, retry in %d ms, attempt %d " + ", cluster connect timeout seconds %d " + ", retry timeout millis %d cap", actualSleepTime, attempt, clusterConnectTimeoutSeconds, maxBackoffMillis)); try { Thread.sleep(actualSleepTime); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } currentBackoffMillis = (int) Math.min(currentBackoffMillis * multiplier, maxBackoffMillis); return true; }</code><technical_language>re-wording timeout --> of timeout</technical_language>

Target:
public boolean sleep() { attempt++; long currentTimeMillis = Clock.currentTimeMillis(); long timePassed = currentTimeMillis - clusterConnectAttemptBegin; if (timePassed > clusterConnectTimeoutMillis) { logger.warning(String.format("Unable to get live cluster connection, cluster connect timeout (%d millis) is " + "reached. Attempt %d.", clusterConnectTimeoutMillis, attempt)); return false; } long actualSleepTime = (long) (currentBackoffMillis - (currentBackoffMillis * jitter) + (currentBackoffMillis * jitter * random.nextDouble())); actualSleepTime = Math.min(actualSleepTime, clusterConnectTimeoutMillis - timePassed); logger.warning(String.format("Unable to get live cluster connection, retry in %d ms, attempt: %d " + ", cluster connect timeout: %d seconds " + ", max backoff millis: %d", actualSleepTime, attempt, clusterConnectTimeoutMillis, maxBackoffMillis)); try { Thread.sleep(actualSleepTime); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } currentBackoffMillis = (int) Math.min(currentBackoffMillis * multiplier, maxBackoffMillis); return true; }
Source:
<code>private Object fetchObjects(Environment context) { if(context.data.isPresent()) { throw new BadRequestException("FETCH must not include data"); } <START> if (context.isRoot() || context.outputType instanceof GraphQLList) { <END> GraphQLObjectType graphQLType = (GraphQLObjectType) ((GraphQLList) context.outputType).getWrappedType(); String entityType = graphQLType.getName(); Class recordType = context.requestScope.getDictionary().getEntityClass(entityType); if (recordType == null) { throw new UnknownEntityException(entityType); } return fetchObject(context.requestScope, recordType, context.ids, context.sort, context.offset, context.first, context.filters); } else { return fetchObject(context.requestScope, context.parentResource, context.field, context.outputType, context.ids, context.sort, context.offset, context.first, context.filters); } }</code><technical_language>I logic more like: if (context.isRoot()) { fetch root object } else { if (field is attribute) { fetch attribute } else { fetch relationship } }</technical_language>

Target:
private Object fetchObjects(Environment context) { if(context.data.isPresent()) { throw new BadRequestException("FETCH must not include data"); } if (context.isRoot()) { return fetchObject(context); } else { EntityDictionary dictionary = context.requestScope.getDictionary(); Class parentClass = context.parentResource.getResourceClass(); String fieldName = context.field.getName(); if(dictionary.isAttribute(parentClass, fieldName)) { return fetchAttribute(context.parentResource, context.field); } else if(dictionary.isRelation(parentClass, fieldName)){ return fetchRelationship(context); } else { throw new BadRequestException("Unrecognized object type: " + context.outputType.getClass().getName()); } } }
Source:
<code>public void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> maps.assertContainsOnlyKeys(someInfo(), null, <START> Arrays.asList("name"))) <END> .withMessage(actualIsNull()); }</code><technical_language>replace Arrays.asList org.assertj.core.util.Lists.list static import for readability</technical_language>

Target:
public void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> maps.assertContainsOnlyKeys(someInfo(), null, list("name"))) .withMessage(actualIsNull()); }
Source:
<code>private String getForwardToEmail() { <START> return env.getProperty("emailBuilder.config.forwardAddress"); <END> }</code><technical_language>"_" servers set values in setenv.sh. I environment variables "." do work in *nix environments. <LINK_0></technical_language>

Target:
private String getForwardToEmail() { return env.getProperty("emailBuilder_config_forwardAddress"); }
Source:
<code>public void start() { try { String hostName = System.getProperty("fake.host"); if (hostName == null) { hostName = "localhost"; } log.debug("Opening a Stomp server " + hostName + ":" + jsonPort); Reactor reactor; if (!encrypted) { reactor = ReactorFactory.getReactor(null, ReactorType.STOMP); } else { <START> Runtime.getRuntime().exec("<dir>/generate-certs.sh 1 2 3"); <END> reactor = ReactorFactory.getReactor(new VdsmProvider(AppConfig.getInstance().getCertspath(), log), ReactorType.STOMP); } final Future<ReactorListener> futureListener = reactor.createListener(hostName, jsonPort, new ReactorListener.EventListener() { @Override public void onAcccept(final ReactorClient client) { client.addEventListener(new MessageListener() { @Override public void onMessageReceived(byte[] message) { MessageHandler handler = new MessageHandler(client, message); service.submit(handler); } }); } }); listener = futureListener.get(TIMEOUT, TimeUnit.MILLISECONDS); } catch (Exception e) { log.error("Failure to start json server socket", e); } }</code><technical_language>please finish this part</technical_language>

Target:
public void start() { try { String hostName = System.getProperty("fake.host"); if (hostName == null) { hostName = "localhost"; } log.debug("Opening a Stomp server " + hostName + ":" + jsonPort); Reactor reactor; if (!encrypted) { reactor = ReactorFactory.getReactor(null, ReactorType.STOMP); } else { reactor = ReactorFactory.getReactor(new VdsmProvider(AppConfig.getInstance().getCertspath(), log), ReactorType.STOMP); } final Future<ReactorListener> futureListener = reactor.createListener(hostName, jsonPort, new ReactorListener.EventListener() { @Override public void onAcccept(final ReactorClient client) { client.addEventListener(new MessageListener() { @Override public void onMessageReceived(byte[] message) { MessageHandler handler = new MessageHandler(client, message); service.submit(handler); } }); } }); listener = futureListener.get(TIMEOUT, TimeUnit.MILLISECONDS); } catch (Exception e) { log.error("Failure to start json server socket", e); } }
Source:
<code>public void testRemoteSnapshotRequestedNodeLeft() throws Exception { IgniteEx ig0 = startGridWithCache(defaultCacheCfg, CACHE_KEYS_RANGE); IgniteEx ig1 = startGrid(1); ig0.cluster().setBaselineTopology(ig0.cluster().forServers().nodes()); awaitPartitionMapExchange(); CountDownLatch hold = new CountDownLatch(1); ((GridCacheDatabaseSharedManager)ig1.context() .cache() .context() .database()) .waitForCheckpoint("Snapshot before request", f -> { try { <START> U.await(hold); <END> } catch (IgniteCheckedException e) { throw new IgniteException(e); } }); UUID rmtNodeId = ig1.localNode().id(); ig0.context() .cache() .context() .snapshotMgr() .createRemoteSnapshot(rmtNodeId, owningParts(ig0, new HashSet<>(Collections.singletonList(CU.cacheId(DEFAULT_CACHE_NAME))), rmtNodeId), (part, grp) -> {}); IgniteInternalFuture<?>[] futs = new IgniteInternalFuture[1]; GridTestUtils.waitForCondition(new GridAbsPredicate() { @Override public boolean apply() { IgniteInternalFuture<Boolean> snpFut = ig1.context() .cache() .context() .snapshotMgr() .lastScheduledRemoteSnapshotTask(ig0.localNode().id()); if (snpFut == null) return false; else futs[0] = snpFut; return true; } }, 5_000L); stopGrid(0); hold.countDown(); futs[0].get(); }</code><technical_language>I understand this block checkpoint snapshot called checkpoint complete. checkpoint listener. I miss something</technical_language>

Target:
public void testRemoteSnapshotRequestedNodeLeft() throws Exception { IgniteEx ig0 = startGridWithCache(dfltCacheCfg, CACHE_KEYS_RANGE); IgniteEx ig1 = startGrid(1); ig0.cluster().setBaselineTopology(ig0.cluster().forServers().nodes()); awaitPartitionMapExchange(); CountDownLatch hold = new CountDownLatch(1); ((GridCacheDatabaseSharedManager)ig1.context().cache().context().database()) .addCheckpointListener(new DbCheckpointListener() { @Override public void beforeCheckpointBegin(Context ctx) throws IgniteCheckedException { U.await(hold); } @Override public void onMarkCheckpointBegin(Context ctx) { } @Override public void onCheckpointBegin(Context ctx) { } }); UUID rmtNodeId = ig1.localNode().id(); Map<Integer, Set<Integer>> parts = new HashMap<>(); parts.put(CU.cacheId(DEFAULT_CACHE_NAME), null); snp(ig0).createRemoteSnapshot(rmtNodeId, parts, (part, grp) -> {}); IgniteInternalFuture<?>[] futs = new IgniteInternalFuture[1]; assertTrue(GridTestUtils.waitForCondition(new GridAbsPredicate() { @Override public boolean apply() { IgniteInternalFuture<Boolean> snpFut = snp(ig1) .lastScheduledRemoteSnapshotTask(ig0.localNode().id()); if (snpFut == null) return false; else futs[0] = snpFut; return true; } }, 5_000L)); stopGrid(0); hold.countDown(); futs[0].get(); }
Source:
<code>public void attachNodeFailingBecauseOfNodeGoingDownInPreparePhase() throws Exception { <START> waitForNPassives(1, 2); <END> int activeId = findActive(1).getAsInt(); int passiveId1 = findPassives(1)[0]; int passiveId2 = findPassives(1)[1]; startNode(1, 4); waitForDiagnostic(1, 4); assertThat(getUpcomingCluster("localhost", getNodePort(1, 4)).getNodeCount(), is(equalTo(1))); String propertySettingString = "stripe.1.node." + activeId + ".tc-properties.failoverAddition=killAddition-prepare"; invokeConfigTool("set", "-s", "localhost:" + getNodePort(1, 1), "-c", propertySettingString); assertThat( () -> invokeConfigTool("attach", "-f", "-d", "localhost:" + getNodePort(1, activeId), "-s", "localhost:" + getNodePort(1, 4)), exceptionMatcher("Two-Phase commit failed")); assertThat(getUpcomingCluster("localhost", getNodePort(1, passiveId1)).getNodeCount(), is(equalTo(3))); assertThat(getUpcomingCluster("localhost", getNodePort(1, passiveId2)).getNodeCount(), is(equalTo(3))); assertThat(getUpcomingCluster("localhost", getNodePort(1, 4)).getNodeCount(), is(equalTo(1))); withTopologyService(1, passiveId1, topologyService -> assertTrue(topologyService.isActivated())); withTopologyService(1, passiveId2, topologyService -> assertTrue(topologyService.isActivated())); withTopologyService(1, 4, topologyService -> assertFalse(topologyService.isActivated())); startNode(1, activeId, "-r", getNode(1, activeId).getConfigRepo()); waitForPassive(1, activeId); withTopologyService(1, activeId, topologyService -> assertTrue(topologyService.isActivated())); }</code><technical_language>care of in setup method</technical_language>

Target:
public void attachNodeFailingBecauseOfNodeGoingDownInPreparePhase() throws Exception { int activeId = findActive(1).getAsInt(); int passiveId1 = findPassives(1)[0]; int passiveId2 = findPassives(1)[1]; startNode(1, 4); waitForDiagnostic(1, 4); assertThat(getUpcomingCluster("localhost", getNodePort(1, 4)).getNodeCount(), is(equalTo(1))); String propertySettingString = "stripe.1.node." + activeId + ".tc-properties.failoverAddition=killAddition-prepare"; invokeConfigTool("set", "-s", "localhost:" + getNodePort(1, 1), "-c", propertySettingString); assertThat( () -> invokeConfigTool("attach", "-f", "-d", "localhost:" + getNodePort(1, activeId), "-s", "localhost:" + getNodePort(1, 4)), exceptionMatcher("Two-Phase commit failed")); assertThat(getUpcomingCluster("localhost", getNodePort(1, passiveId1)).getNodeCount(), is(equalTo(3))); assertThat(getUpcomingCluster("localhost", getNodePort(1, passiveId2)).getNodeCount(), is(equalTo(3))); assertThat(getUpcomingCluster("localhost", getNodePort(1, 4)).getNodeCount(), is(equalTo(1))); withTopologyService(1, passiveId1, topologyService -> assertTrue(topologyService.isActivated())); withTopologyService(1, passiveId2, topologyService -> assertTrue(topologyService.isActivated())); withTopologyService(1, 4, topologyService -> assertFalse(topologyService.isActivated())); startNode(1, activeId, "-r", getNode(1, activeId).getConfigRepo()); waitForPassive(1, activeId); withTopologyService(1, activeId, topologyService -> assertTrue(topologyService.isActivated())); }
Source:
<code>static LocalDate parseDate(String str) { try { if (str.length() == 10 && str.charAt(4) == '-' && str.charAt(7) == '-') { return LocalDate.parse(str, YYYY_MM_DD_DASH); } if (str.length() == 10 && str.charAt(4) == '/' && str.charAt(7) == '/') { return LocalDate.parse(str, YYYY_MM_DD_SLASH); } <START> if (str.length() >= 6 && str.charAt(2) == '/' && str.charAt(5) == '/') { <END> if (str.length() == 8) { return LocalDate.parse(str, DD_MM_YY_SLASH); } else { return LocalDate.parse(str, DD_MM_YYYY_SLASH); } } if (str.length() >= 10 && str.charAt(str.length() - 5) == '-') { return LocalDate.parse(str, D_MMM_YYYY_DASH); } if (str.length() == 8 && Character.isDigit(str.charAt(2))) { return LocalDate.parse(str, YYYYMMDD); } return LocalDate.parse(str, D_MMM_YYYY_NODASH); } catch (DateTimeParseException ex) { throw new IllegalArgumentException( "Unknown date format, must be formatted as " + "yyyy-MM-dd, yyyyMMdd, dd/MM/yyyy, yyyy/MM/dd, 'd-MMM-yyyy' or 'dMMMyyyy' but was: " + str, ex); } }</code><technical_language>This 8 6</technical_language>

Target:
static LocalDate parseDate(String str) { try { if (str.length() == 10 && str.charAt(4) == '-' && str.charAt(7) == '-') { return LocalDate.parse(str, YYYY_MM_DD_DASH); } if (str.length() == 10 && str.charAt(4) == '/' && str.charAt(7) == '/') { return LocalDate.parse(str, YYYY_MM_DD_SLASH); } if (str.length() >= 8 && str.charAt(2) == '/' && str.charAt(5) == '/') { if (str.length() == 8) { return LocalDate.parse(str, DD_MM_YY_SLASH); } else { return LocalDate.parse(str, DD_MM_YYYY_SLASH); } } if (str.length() >= 10 && str.charAt(str.length() - 5) == '-') { return LocalDate.parse(str, D_MMM_YYYY_DASH); } if (str.length() == 8 && Character.isDigit(str.charAt(2))) { return LocalDate.parse(str, YYYYMMDD); } return LocalDate.parse(str, D_MMM_YYYY_NODASH); } catch (DateTimeParseException ex) { throw new IllegalArgumentException( "Unknown date format, must be formatted as " + "yyyy-MM-dd, yyyyMMdd, dd/MM/yyyy, yyyy/MM/dd, 'd-MMM-yyyy' or 'dMMMyyyy' but was: " + str, ex); } }
Source:
<code>private void displayCurrentInfo() { DecimalFormat df = new DecimalFormat("#"); df.setMaximumFractionDigits(0); boolean isDexbridge = CollectionServiceStarter.isDexbridgeWixel(getApplicationContext()); boolean displayBattery = prefs.getBoolean("display_bridge_battery",false); int bridgeBattery = prefs.getInt("bridge_battery", 0); if (isDexbridge && displayBattery) { if (bridgeBattery == 0) { dexbridgeBattery.setText("xBridge Battery: Unknown, Waiting for packet"); dexbridgeBattery.setTextColor(Color.WHITE); } else { dexbridgeBattery.setText("xBridge Battery: " + bridgeBattery + "%"); } if (bridgeBattery < 50 && bridgeBattery >25) dexbridgeBattery.setTextColor(Color.YELLOW); if (bridgeBattery <= 25) dexbridgeBattery.setTextColor(Color.RED); <START> else dexbridgeBattery.setTextColor(Color.GREEN); <END> dexbridgeBattery.setVisibility(View.VISIBLE); } else { dexbridgeBattery.setText(""); dexbridgeBattery.setVisibility(View.INVISIBLE); } if ((currentBgValueText.getPaintFlags() & Paint.STRIKE_THRU_TEXT_FLAG) > 0) { currentBgValueText.setPaintFlags(currentBgValueText.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG)); dexbridgeBattery.setPaintFlags(dexbridgeBattery.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG)); } BgReading lastBgReading = BgReading.lastNoSenssor(); boolean predictive = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean("predictive_bg", false); if (isBTShare) { predictive = false; } if (lastBgReading != null) { displayCurrentInfoFromReading(lastBgReading, predictive); } }</code><technical_language>note wil reset green whenver > 25, yellow bridgeBattery = 0, set Red</technical_language>

Target:
private void displayCurrentInfo() { DecimalFormat df = new DecimalFormat("#"); df.setMaximumFractionDigits(0); boolean isDexbridge = CollectionServiceStarter.isDexbridgeWixel(getApplicationContext()); boolean displayBattery = prefs.getBoolean("display_bridge_battery",false); int bridgeBattery = prefs.getInt("bridge_battery", 0); if (isDexbridge && displayBattery) { if (bridgeBattery == 0) { dexbridgeBattery.setText("xBridge Battery: Unknown, Waiting for packet"); dexbridgeBattery.setTextColor(Color.WHITE); } else { dexbridgeBattery.setText("xBridge Battery: " + bridgeBattery + "%"); } dexbridgeBattery.setTextColor(Color.GREEN); if (bridgeBattery < 50 && bridgeBattery >30) dexbridgeBattery.setTextColor(Color.YELLOW); if (bridgeBattery <= 30) dexbridgeBattery.setTextColor(Color.RED); dexbridgeBattery.setVisibility(View.VISIBLE); } else { dexbridgeBattery.setText(""); dexbridgeBattery.setVisibility(View.INVISIBLE); } if ((currentBgValueText.getPaintFlags() & Paint.STRIKE_THRU_TEXT_FLAG) > 0) { currentBgValueText.setPaintFlags(currentBgValueText.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG)); dexbridgeBattery.setPaintFlags(dexbridgeBattery.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG)); } BgReading lastBgReading = BgReading.lastNoSenssor(); boolean predictive = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean("predictive_bg", false); if (isBTShare) { predictive = false; } if (lastBgReading != null) { displayCurrentInfoFromReading(lastBgReading, predictive); } }
Source:
<code>public void execute(Database database) throws CustomChangeException { JdbcConnection connection = (JdbcConnection) database.getConnection(); try { List<String> uniqueUnits = getUniqueUnits(connection); for (String unit : uniqueUnits) { <START> migrateUnitsToCodedValue(connection, unit); <END> } } catch (SQLException e) { throw new CustomChangeException(e); } }</code><technical_language>a PreparedStatement below, sense move this loop migrateUnitsToCodedValue() method prepare close PreparedStatement object once, means do update turning auto commit commit/rollback in go</technical_language>

Target:
public void execute(Database database) throws CustomChangeException { JdbcConnection connection = (JdbcConnection) database.getConnection(); try { List<String> uniqueUnits = getUniqueUnits(connection); migrateUnitsToCodedValue(connection, uniqueUnits); } catch (SQLException e) { throw new CustomChangeException(e); } catch (DatabaseException e) { throw new CustomChangeException(e); } }
Source:
<code>public static <T extends WeightedElement> T randomMemberWeighted( SimpleList<T> list, Map<T, Double> weights, double totalWeight) { incrementCallsToRandom("randomMemberWeighted(SimpleList)"); double chosenPoint = Randomness.random.nextDouble() * totalWeight; if (GenInputsAbstract.selection_log != null) { try { GenInputsAbstract.selection_log.write(String.format("chosenPoint = %s%n", chosenPoint)); } catch (IOException e) { throw new Error("Problem writing to selection-log", e); } } double currentPoint = 0; for (int i = 0; i < list.size(); i++) { currentPoint += getWeight(list.get(i), weights); <START> if (currentPoint >= chosenPoint) { <END> logSelection(i, "randomMemberWeighted", list); return list.get(i); } } throw new BugInRandoopException("Unable to select random member"); }</code><technical_language>Mike, wondering case elements weights of zero. I thinking Randomness select element a weight of zero? However, if list's element a weight of zero chosenPoint zero, this code select element</technical_language>

Target:
public static <T extends WeightedElement> T randomMemberWeighted( SimpleList<T> list, Map<T, Double> weights, double totalWeight) { incrementCallsToRandom("randomMemberWeighted(SimpleList)"); double chosenPoint = Randomness.random.nextDouble() * totalWeight; if (GenInputsAbstract.selection_log != null) { try { GenInputsAbstract.selection_log.write(String.format("chosenPoint = %s%n", chosenPoint)); } catch (IOException e) { throw new Error("Problem writing to selection-log", e); } } double currentPoint = 0; for (int i = 0; i < list.size(); i++) { currentPoint += getWeight(list.get(i), weights); if (currentPoint > chosenPoint) { logSelection(i, "randomMemberWeighted", list); return list.get(i); } } throw new BugInRandoopException("Unable to select random member"); }
Source:
<code>public CreateTaskVariablePayload handleCreateTaskVariablePayload(CreateTaskVariablePayload createTaskVariablePayload) { String name = createTaskVariablePayload.getName(); <START> if (!variableNameValidator.validate(name)) { <END> throw new IllegalStateException("Variable has not a valid name: " + (name != null ? name : "null" )); } Object value = createTaskVariablePayload.getValue(); if (value instanceof String) { handleAsDate((String)value).ifPresent(createTaskVariablePayload::setValue); } return createTaskVariablePayload; }</code><technical_language>part of code in this class repeated, evaluate refactoring</technical_language>

Target:
public CreateTaskVariablePayload handleCreateTaskVariablePayload(CreateTaskVariablePayload createTaskVariablePayload) { checkNotValidCharactersInVariableName(createTaskVariablePayload.getName(), "Variable has not a valid name: "); Object value = createTaskVariablePayload.getValue(); if (value instanceof String) { handleAsDate((String)value).ifPresent(createTaskVariablePayload::setValue); } return createTaskVariablePayload; }
Source:
<code>public InetSocketAddress next(long spinDelay) { <START> if (!connectedSinceNext) { <END> InetSocketAddress curAddr = serverAddresses.get(currentIndex); String curHostString = getHostString(curAddr); if (!curHostString.equals(curAddr.getAddress().getHostAddress())) { LOG.info("Resolving again hostname: {}", getHostString(curAddr)); try { int thePort = curAddr.getPort(); InetAddress resolvedAddresses[] = InetAddress.getAllByName(curHostString); nextAdded = 0; nextRemoved = 0; if (resolvedAddresses.length == 1) { serverAddresses.set(currentIndex, new InetSocketAddress(resolvedAddresses[0], thePort)); nextAdded = nextRemoved = 1; LOG.debug("Newly resolved address: {}", resolvedAddresses[0]); } else { int i = 0; while (i < serverAddresses.size()) { if (getHostString(serverAddresses.get(i)).equals(curHostString) && serverAddresses.get(i).getPort() == curAddr.getPort()) { LOG.debug("Removing address: {}", serverAddresses.get(i)); serverAddresses.remove(i); nextRemoved++; } else { i++; } } for (InetAddress resolvedAddress : resolvedAddresses) { InetSocketAddress newAddr = new InetSocketAddress(resolvedAddress, thePort); if (!serverAddresses.contains(newAddr)) { LOG.debug("Adding address: {}", newAddr); serverAddresses.add(newAddr); nextAdded++; } } } } catch (UnknownHostException e) { LOG.warn("Cannot re-resolve server: {}", curAddr, e); } } } connectedSinceNext = false; currentIndex = ++currentIndex % serverAddresses.size(); if (currentIndex == lastIndex && spinDelay > 0) { try { Thread.sleep(spinDelay); } catch (InterruptedException e) { LOG.warn("Unexpected exception", e); } } else if (lastIndex == -1) { lastIndex = 0; } return serverAddresses.get(currentIndex); }</code><technical_language>mind explaining conditions reresolve hostname conditions try next in host list? reading is this reresolves if client fails connect hosts in a row. Is this desired behavior? do reresolve serverAddresses</technical_language>

Target:
public InetSocketAddress next(long spinDelay) { currentIndex = ++currentIndex % serverAddresses.size(); if (currentIndex == lastIndex && spinDelay > 0) { try { Thread.sleep(spinDelay); } catch (InterruptedException e) { LOG.warn("Unexpected exception", e); } } else if (lastIndex == -1) { lastIndex = 0; } InetSocketAddress curAddr = serverAddresses.get(currentIndex); try { String curHostString = getHostString(curAddr); List<InetAddress> resolvedAddresses = new ArrayList<InetAddress>(Arrays.asList(this.resolver.getAllByName(curHostString))); if (resolvedAddresses.isEmpty()) { return curAddr; } Collections.shuffle(resolvedAddresses); return new InetSocketAddress(resolvedAddresses.get(0), curAddr.getPort()); } catch (UnknownHostException e) { return curAddr; } }
Source:
<code>public void testGetSuggestedDiskAliasNullDisk() { <START> assertEquals("null disk does not give the default name", <END> prefix + "_Disk1", ImagesHandler.getSuggestedDiskAlias(null, prefix, 1)); }</code><technical_language>of constants declared in images handler? DISK/DefaultDriveName changing constants need change test well</technical_language>

Target:
public void testGetSuggestedDiskAliasNullDisk() { assertEquals("null disk does not give the default name", prefix + ImagesHandler.DISK + ImagesHandler.DefaultDriveName, ImagesHandler.getSuggestedDiskAlias(null, prefix, 1)); }
Source:
<code>public List<PortalNodeSummary> getNodesFromRootForSite(EntityView view, Map<String, Object> params){ String siteId = (String)params.get("siteid"); if(StringUtils.isBlank(siteId)){ throw new IllegalArgumentException("site ID must be set in order to get the site node locations"); } List<PortalNodeSummary> portalNodeSummaries = new ArrayList<>(); if (portalHierarchyService.siteExists(siteId)) { List<PortalNode> portalNodes = portalHierarchyService.getNodesWithSite(siteId); PortalNode portalNodePrimary = portalHierarchyService.getDefaultNode(siteId); if (portalNodes.isEmpty()) { return portalNodeSummaries; } for (PortalNode pn : portalNodes) { if (pn.canView()) { PortalNodeSummary pne = new PortalNodeSummary(pn); if ((pn.getId()).equals(portalNodePrimary.getId())) { pne.setPrimary(true); } portalNodeSummaries.add(pne); } } if (portalNodeSummaries.size() == 0) { throw new IllegalArgumentException("You do not have permission to view any pages that include this site"); } } else { <START> throw new IllegalArgumentException("No site found for the given site ID"); <END> } return portalNodeSummaries; }</code><technical_language>message site ID exist</technical_language>

Target:
public List<PortalNodeSummary> getNodesFromRootForSite(EntityView view, Map<String, Object> params){ String siteId = (String)params.get("siteid"); if(StringUtils.isBlank(siteId)){ throw new IllegalArgumentException("site ID must be set in order to get the site node locations"); } List<PortalNodeSummary> portalNodeSummaries = new ArrayList<>(); if (siteService.siteExists(siteId)) { List<PortalNode> portalNodes = portalHierarchyService.getNodesWithSite(siteId); PortalNode portalNodePrimary = portalHierarchyService.getDefaultNode(siteId); if (portalNodes.isEmpty()) { return portalNodeSummaries; } for (PortalNode pn : portalNodes) { PortalNodeSummary pne = new PortalNodeSummary(pn); if (pn.equals(portalNodePrimary)) { pne.setPrimary(true); } portalNodeSummaries.add(pne); } } else { throw new IllegalArgumentException("The site ID is not valid"); } return portalNodeSummaries; }
Source:
<code>protected void checkAllowQueriesOnUiThread() { if (getSharedRealm().capabilities.isMainThread()) { if (!getConfiguration().isAllowQueriesOnUiThread()) { <START> throw new RealmException("There exists an opt-out for running queries on the UI thread. By default Realm allows queries from the UI thread. You can alternatively opt in by using 'RealmConfiguration.allowQueriesOnUiThread'."); <END> } } }</code><technical_language>suggestion throw new RealmException("Queries UI thread disabled. enabled setting 'RealmConfiguration.Builder.allowQueriesOnUiThread(true)'.");</technical_language>

Target:
protected void checkAllowQueriesOnUiThread() { if (getSharedRealm().capabilities.isMainThread()) { if (!getConfiguration().isAllowQueriesOnUiThread()) { throw new RealmException("Queries on the UI thread have been disabled. They can be enabled by setting 'RealmConfiguration.Builder.allowQueriesOnUiThread(true)'."); } } }
Source:
<code>public void shutdown() { shuttingDown.set(true); logger.info("Compactor received shutdown request, waiting up to seconds for in-flight operations to finish", shutDownTimeoutSecs); try { doneLatch.get().await(shutDownTimeoutSecs, TimeUnit.SECONDS); logger.info("Compactor shut down successfully."); } catch (InterruptedException ex) { <START> logger.warn("Timed out waiting for operations to finish. If cloud provider uses separate stores for " <END> + "data and metadata, some inconsistencies may be present."); } }</code><technical_language>log a metric here? easier track. this get lost in log messages</technical_language>

Target:
public void shutdown() { shuttingDown.set(true); logger.info("Compactor received shutdown request, waiting up to seconds for in-flight operations to finish", shutDownTimeoutSecs); boolean success = false; try { success = doneLatch.get().await(shutDownTimeoutSecs, TimeUnit.SECONDS); } catch (InterruptedException ex) { } if (success) { logger.info("Compactor shut down successfully."); } else { logger.warn("Timed out or interrupted waiting for operations to finish. If cloud provider uses separate stores" + " for data and metadata, some inconsistencies may be present."); vcrMetrics.compactionShutdownTimeoutCount.inc(); } }
Source:
<code>public void setup() throws Exception { <START> String propFileName = "test.properties"; <END> Properties props = new Properties(); try (InputStream input = this.getClass().getClassLoader().getResourceAsStream(propFileName)) { if (input == null) { throw new IllegalStateException("Could not find resource: " + propFileName); } props.load(input); } catch (IOException ex) { throw new IllegalStateException("Could not load properties from resource: " + propFileName); } VerifiableProperties verProps = new VerifiableProperties(props); azureDest = (AzureCloudDestination) new AzureCloudDestinationFactory(verProps, new MetricRegistry()).getCloudDestination(); cosmosCollectionLink = verProps.getString(AzureCloudConfig.COSMOS_COLLECTION_LINK); }</code><technical_language>is this file</technical_language>

Target:
public void setup() throws Exception { String propFileName = "azure-test.properties"; Properties props = new Properties(); try (InputStream input = this.getClass().getClassLoader().getResourceAsStream(propFileName)) { if (input == null) { throw new IllegalStateException("Could not find resource: " + propFileName); } props.load(input); } catch (IOException ex) { throw new IllegalStateException("Could not load properties from resource: " + propFileName); } VerifiableProperties verProps = new VerifiableProperties(props); azureDest = (AzureCloudDestination) new AzureCloudDestinationFactory(verProps, new MetricRegistry()).getCloudDestination(); cosmosCollectionLink = verProps.getString(AzureCloudConfig.COSMOS_COLLECTION_LINK); }
Source:
<code>public void deleteAttachment(Long attachmentId) throws IOException { Attachment attachment = attachments.load(attachmentId); if (attachment == null) { result.notFound(); return; <START> } <END> User current = loggedUser.getCurrent(); detachFromQuestion(attachment); detachFromAnswer(attachment); if (!attachment.canDelete(current) && !current.isModerator()) { result.use(http()).sendError(403); return; } attachments.delete(attachment); fileStorage.delete(attachment); result.nothing(); }</code><technical_language>skull:</technical_language>

Target:
public void deleteAttachment(Long attachmentId) throws IOException { Attachment attachment = attachments.load(attachmentId); User current = loggedUser.getCurrent(); if (!attachment.canDelete(current) && !current.isModerator()) { validator.add(messageFactory.build("error", "unauthorized.title")); result.use(http()).sendError(403); return; } attachments.delete(attachment); result.nothing(); }
Source:
<code>public void stop(ComponentContext context) throws InterruptedException { <START> getLog().debug("Stoping component"); <END> }</code><technical_language>Stopping</technical_language>

Target:
public void stop(ComponentContext context) throws InterruptedException { getLog().debug("Stopping component " + getName()); }
Source:
<code><START> public BluetoothServerSocket listenUsingL2capCoc(int transport) throws IOException { if (transport != BluetoothDevice.TRANSPORT_LE) { throw new IllegalArgumentException("Unsupported transport: " + transport); } <END> BluetoothServerSocket socket = new BluetoothServerSocket(BluetoothSocket.TYPE_L2CAP_LE, true, true, SOCKET_CHANNEL_AUTO_STATIC_NO_SDP, false, false); int errno = socket.mSocket.bindListen(); if (errno != 0) { throw new IOException("Error: " + errno); } int assignedPsm = socket.mSocket.getPort(); if (assignedPsm == 0) { throw new IOException("Error: Unable to assign PSM value"); } if (DBG) { Log.d(TAG, "listenUsingL2capCoc: set assigned PSM to " + assignedPsm); } socket.setChannel(assignedPsm); return socket; }</code><technical_language>A couple thoughts: sense expose transport argument, separate methods? e.g. listenUsingLeL2capCoC, listenUsingL2capCoC exposing LE version for now, expose BR/EDR? future of listenUsingL2capOn, etc, methods in BluetoothAdapter? CoC is implied in l2cap part of name, sense listenUsingL2cap listenUsingLeL2cap ...etc</technical_language>

Target:
public BluetoothServerSocket listenUsingL2capCoc(int transport) throws IOException { Log.e(TAG, "listenUsingL2capCoc: PLEASE USE THE OFFICIAL API, listenUsingL2cap"); return listenUsingL2cap(transport); }
Source:
<code>public void execute() { Resource umlResource = UmlUtils.getUmlModel(modelSet).getResource(); model = (org.eclipse.uml2.uml.Model) umlResource.getContents().get(0); <START> URI qudvURI = URI.createURI(SysMLResource.LIBRARY_PATH).appendFragment("SysML.package_packagedElement_Libraries"); END> libraries = modelSet.getEObject(qudvURI, true); this.getCommandStack(modelSet).execute(new RecordingCommand(modelSet.getTransactionalEditingDomain()) { @Override protected void doExecute() { PackageImport importPrimitivePack = model.createPackageImport((org.eclipse.uml2.uml.Package) libraries); if (!model.getPackageImports().contains(importPrimitivePack)) { model.getPackageImports().add(importPrimitivePack); } try { model.eResource().save(Collections.EMPTY_MAP); } catch (IOException e) { Activator.getLogHelper().error(e); } } }); }</code><technical_language>strange for appendFragment, I propose SysMLResource.LIBRARY_ROOTPATH SysMLResource.LIBRARY_PATH</technical_language>

Target:
public void execute() { Resource umlResource = UmlUtils.getUmlModel(modelSet).getResource(); root = (org.eclipse.uml2.uml.Package) umlResource.getContents().get(0); URI qudvURI = URI.createURI(SysMLResource.LIBRARY_PATH).appendFragment(SysMLResource.LIBRARY_ROOT_ID); libraries = (org.eclipse.uml2.uml.Package) modelSet.getEObject(qudvURI, true); this.getCommandStack(modelSet).execute(new RecordingCommand(modelSet.getTransactionalEditingDomain()) { @Override protected void doExecute() { PackageImport importPrimitivePack = root.createPackageImport( libraries); if (!root.getPackageImports().contains(importPrimitivePack)) { root.getPackageImports().add(importPrimitivePack); } try { root.eResource().save(Collections.EMPTY_MAP); } catch (IOException e) { Activator.getLogHelper().error(e); } } }); }
Source:
<code>public String footerFull(Model model) { <START> String footerExtraData = Context.getMessageSourceService().getMessage("legacyui.footer.extradata", null, null, <END> Locale.getDefault()); if (footerExtraData.equals("legacyui.footer.extradata")) { footerExtraData = null; } model.addAttribute("footerExtraData", footerExtraData); return "module/legacyui/template/footerFull"; }</code><technical_language>footer's extra data is supposed a runtime property. end like: java String footerExtraData = Context.getRuntimeProperties() .getProperty("legacyui.footer.extradata", "");</technical_language>

Target:
public String footerFull(Model model) { String footerExtraData = Context.getRuntimeProperties().getProperty("legacyui.footer.extradata", ""); model.addAttribute("extraData", footerExtraData); return "module/legacyui/template/footerFull"; }
Source:
<code>public boolean createExpiredObject(ExpiredObject obj) { try { int objectExpirationInMinutes = 0; if(obj.getType() == ExpiredObjectType.STATE){ objectExpirationInMinutes = configuration.getStateExpirationInMinutes(); } else if(obj.getType() == ExpiredObjectType.NONCE){ objectExpirationInMinutes = configuration.getNonceExpirationInMinutes(); } <START> put(objectExpirationInMinutes * 60, obj.getKey(), obj.getType().getValue()); <END> return true; } catch (Exception e) { LOG.error("Failed to create ExpiredObject: " + obj.getKey(), e); return false; } }</code><technical_language>put value, obj.getValue(), type value</technical_language>

Target:
public boolean createExpiredObject(ExpiredObject obj) { try { int objectExpirationInMinutes = 0; if (obj.getType() == ExpiredObjectType.STATE) { objectExpirationInMinutes = configuration.getStateExpirationInMinutes(); } else if (obj.getType() == ExpiredObjectType.NONCE) { objectExpirationInMinutes = configuration.getNonceExpirationInMinutes(); } put(objectExpirationInMinutes * 60, obj.getKey(), obj.getValue()); return true; } catch (Exception e) { LOG.error("Failed to create ExpiredObject: " + obj.getKey(), e); return false; } }
Source:
<code>public void write(byte b[], int off, int len) throws IOException { count += len; if (count > maxOutputSize) { throw new IOException("Attempt to write " + count + " bytes was made. A maximum of " + maxOutputSize + " is allowed for an encryption stream."); } <START> obuffer = cipher.update(b, off, len); <END> if (obuffer != null) { output.write(obuffer); obuffer = null; } }</code><technical_language>call super.write here</technical_language>

Target:
public void write(byte b[], int off, int len) throws IOException { count += len; if (count > maxOutputSize) { throw new IOException("Attempt to write " + count + " bytes was made. A maximum of " + maxOutputSize + " is allowed for an encryption stream."); } super.write(b, off, len); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Mapbox.getInstance(this, getString(R.string.access_token)); setContentView(R.layout.activity_inset_map); mainMapMapView = (MapView) findViewById(R.id.main_mapView); mainMapMapView.onCreate(savedInstanceState); mainMapMapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(MapboxMap mapboxMap) { InsetMapActivity.this.mainLargeMapboxMap = mapboxMap; <START> mainLargeMapboxMap.addOnCameraMoveListener(new MapboxMap.OnCameraMoveListener() { <END> @Override public void onCameraMove() { onMapMovedFragmentInterfaceListener.onMapMoved(mainLargeMapboxMap.getCameraPosition()); } }); } }); CustomSupportMapFragment customSupportMapFragment; if (savedInstanceState == null) { final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); MapboxMapOptions options = new MapboxMapOptions(); options.styleUrl("mapbox://styles/mapbox/cj5l80zrp29942rmtg0zctjto"); options.attributionEnabled(false); options.logoEnabled(false); options.compassEnabled(false); options.scrollGesturesEnabled(false); options.tiltGesturesEnabled(false); options.rotateGesturesEnabled(false); options.camera(new CameraPosition.Builder() .target(new LatLng(11.302318, 106.025839)) .zoom(2) .build()); customSupportMapFragment = CustomSupportMapFragment.newInstance(options); transaction.add(R.id.mini_map_fragment_container, customSupportMapFragment, "com.mapbox.fragmentMap"); transaction.commit(); } else { customSupportMapFragment = (CustomSupportMapFragment) getSupportFragmentManager().findFragmentByTag("com.mapbox.fragmentMap"); } }</code><technical_language>if add a listener, listener removed map destruction avoid leaking listeners</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Mapbox.getInstance(this, getString(R.string.access_token)); setContentView(R.layout.activity_inset_map); mainMapMapView = findViewById(R.id.main_mapView); mainMapMapView.onCreate(savedInstanceState); mainMapMapView.getMapAsync(this); CustomSupportMapFragment customSupportMapFragment; if (savedInstanceState == null) { final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); MapboxMapOptions options = new MapboxMapOptions(); options.styleUrl("mapbox://styles/mapbox/cj5l80zrp29942rmtg0zctjto"); options.attributionEnabled(false); options.logoEnabled(false); options.compassEnabled(false); options.scrollGesturesEnabled(false); options.tiltGesturesEnabled(false); options.rotateGesturesEnabled(false); options.camera(new CameraPosition.Builder() .target(new LatLng(11.302318, 106.025839)) .zoom(2) .build()); customSupportMapFragment = CustomSupportMapFragment.newInstance(options); transaction.add(R.id.mini_map_fragment_container, customSupportMapFragment, "com.mapbox.fragmentMap"); transaction.commit(); } else { customSupportMapFragment = (CustomSupportMapFragment) getSupportFragmentManager().findFragmentByTag("com.mapbox.fragmentMap"); } }
Source:
<code>public void testGetCurrentThread() { HANDLE h = Kernel32.INSTANCE.GetCurrentThread(); assertNotNull("No current thread handle", h); <START> assertFalse("Null current thread handle", h.getPointer().equals(Pointer.NULL)); <END> }</code><technical_language>Please this java assertNotNull("Null current thread handle", h.getValue()); version raise a NullPointerException in failure case. I consider Pointer.NULL a bad idea - illusion if object, in fact is null. If want version, needs be: java assertFalse("Null current thread handle", h.getPointer() == Pointer.NULL);</technical_language>

Target:
public void testGetCurrentThread() { HANDLE h = Kernel32.INSTANCE.GetCurrentThread(); assertNotNull("No current thread handle", h); assertNotNull("Null current thread handle", h.getPointer()); }
Source:
<code>public void cannotModifyReadOnlyConfiguration() throws Exception { HtmlPage configure = webClient.login(SYSTEM_READER_AND_MANAGER) .goTo("configure"); HtmlForm form = configure.getFormByName("config"); j.submit(form); Config config = GlobalConfiguration.all().get(Config.class); assert config != null; <START> assertNull("shouldn't be allowed to change the number of executors", config.getNumber()); <END> }</code><technical_language>nice Tested locally public Permission getRequiredGlobalConfigPagePermission() { return Jenkins.MANAGE; } failed expected</technical_language>

Target:
public void cannotModifyReadOnlyConfiguration() throws Exception { HtmlPage configure = webClient.login(SYSTEM_READER_AND_MANAGER) .goTo("configure"); HtmlForm form = configure.getFormByName("config"); j.submit(form); Config config = GlobalConfiguration.all().get(Config.class); assert config != null; assertNull("shouldn't be allowed to change a GlobalConfiguration that needs Overall/Administer", config.getNumber()); }