auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static void writeValue(ByteBuf buf, Object value, MetadataType type) throws IOException { switch (type) { case BYTE: buf.writeByte((Byte) value); break; case INT: ByteBufUtils.writeVarInt(buf, (Integer) value); break; case FLOAT: buf.writeFloat((Float) value); break; case STRING: ByteBufUtils.writeUTF8(buf, (String) value); break; case CHAT: writeChat(buf, (TextMessage) value); break; case OPTCHAT: <START> writeChat(buf, (TextMessage) value); <END> case ITEM: writeSlot(buf, (ItemStack) value); break; case BOOLEAN: buf.writeBoolean((Boolean) value); break; case VECTOR: EulerAngle angle = (EulerAngle) value; buf.writeFloat((float) Math.toDegrees(angle.getX())); buf.writeFloat((float) Math.toDegrees(angle.getY())); buf.writeFloat((float) Math.toDegrees(angle.getZ())); break; case POSITION: case OPTPOSITION: BlockVector vector = (BlockVector) value; buf.writeLong(Position.getPosition(vector)); break; case DIRECTION: ByteBufUtils.writeVarInt(buf, (Integer) value); break; case OPTUUID: writeUuid(buf, (UUID) value); break; case BLOCKID: ByteBufUtils.writeVarInt(buf, (Integer) value); break; case NBTTAG: writeCompound(buf, (CompoundTag) value); break; case PARTICLE: writeParticle(buf, (ParticleBuilder) value); break; default: } }</code><technical_language>Missing a break. Merge previous case</technical_language>

Target:
private static void writeValue(ByteBuf buf, Object value, MetadataType type) throws IOException { switch (type) { case BYTE: buf.writeByte((Byte) value); break; case INT: ByteBufUtils.writeVarInt(buf, (Integer) value); break; case FLOAT: buf.writeFloat((Float) value); break; case STRING: ByteBufUtils.writeUTF8(buf, (String) value); break; case CHAT: case OPTCHAT: writeChat(buf, (TextMessage) value); break; case ITEM: writeSlot(buf, (ItemStack) value); break; case BOOLEAN: buf.writeBoolean((Boolean) value); break; case VECTOR: EulerAngle angle = (EulerAngle) value; buf.writeFloat((float) Math.toDegrees(angle.getX())); buf.writeFloat((float) Math.toDegrees(angle.getY())); buf.writeFloat((float) Math.toDegrees(angle.getZ())); break; case POSITION: case OPTPOSITION: BlockVector vector = (BlockVector) value; buf.writeLong(Position.getPosition(vector)); break; case DIRECTION: ByteBufUtils.writeVarInt(buf, (Integer) value); break; case OPTUUID: writeUuid(buf, (UUID) value); break; case BLOCKID: ByteBufUtils.writeVarInt(buf, (Integer) value); break; case NBTTAG: writeCompound(buf, (CompoundTag) value); break; case PARTICLE: writeParticle(buf, (ParticleBuilder) value); break; default: } }
Source:
<code>public void handleDaemonConfigChanged(final Event event) { DaemonTools.handleReloadEvent(event, "PollerBackEnd", (e)->{ m_pollerBackEnd.configurationUpdated(); <START> }); <END> }</code><technical_language>short version of closure, is a liner, needed</technical_language>

Target:
public void handleDaemonConfigChanged(final Event event) { DaemonTools.handleReloadEvent(event, "PollerBackEnd", (e)-> m_pollerBackEnd.configurationUpdated()); }
Source:
<code>public PiecewisePolynomialResult interpolate(final double[] xValues, final double[] yValues) { <START> return (new PiecewiseCubicHermiteSplineInterpolator()).interpolate(xValues, yValues); <END> }</code><technical_language>Is a new object needed time</technical_language>

Target:
public PiecewisePolynomialResult interpolate(final double[] xValues, final double[] yValues) { return INTERP.interpolate(xValues, yValues); }
Source:
<code>public void run() { for(String file : reader.getFiles()) { S3ObjectInputStreamWrapper is = new S3ObjectInputStreamWrapper(reader.getAmazonS3Client().getObject(reader.getBucketName(), file)); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is)); LOGGER.info("Reading: ", file); String line = ""; try { while((line = bufferedReader.readLine()) != null) { if( !Strings.isNullOrEmpty(line) ) { <START> reader.countersCurrent.incrementAttempt(); <END> String[] fields = line.split(Character.toString(reader.DELIMITER)); StreamsDatum entry = new StreamsDatum(fields[3], fields[0]); write( entry ); reader.countersCurrent.incrementStatus(DatumStatus.SUCCESS); } } } catch (Exception e) { e.printStackTrace(); LOGGER.warn(e.getMessage()); reader.countersCurrent.incrementStatus(DatumStatus.FAIL); } LOGGER.info("Completed: " + file); try { closeSafely(file, is); } catch (Exception e) { e.printStackTrace(); LOGGER.error(e.getMessage()); } } }</code><technical_language>Direct field access lead issues, preferable encapsulate this in reader class. give more control management of fields</technical_language>

Target:
public void run() { for(String file : reader.getFiles()) { S3ObjectInputStreamWrapper is = new S3ObjectInputStreamWrapper(reader.getAmazonS3Client().getObject(reader.getBucketName(), file)); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is)); LOGGER.info("Reading: ", file); String line = ""; try { while((line = bufferedReader.readLine()) != null) { if( !Strings.isNullOrEmpty(line) ) { reader.countersCurrent.incrementAttempt(); String[] fields = line.split(Character.toString(reader.DELIMITER)); StreamsDatum entry = new StreamsDatum(fields[3], fields[0]); ComponentUtils.offerUntilSuccess(entry, reader.persistQueue); reader.countersCurrent.incrementStatus(DatumStatus.SUCCESS); } } } catch (Exception e) { e.printStackTrace(); LOGGER.warn(e.getMessage()); reader.countersCurrent.incrementStatus(DatumStatus.FAIL); } LOGGER.info("Completed: " + file); try { closeSafely(file, is); } catch (Exception e) { LOGGER.error(e.getMessage()); } } }
Source:
<code>protected void executeCommand() { T bckndCmdParams = getParameters(); final SetupNetworksVdsCommandParameters vdsCmdParams = new SetupNetworksVdsCommandParameters( getVdsId(), getNetworks(), getRemovedNetworks(), getBonds(), getRemovedBonds(), getInterfaces()); vdsCmdParams.setForce(bckndCmdParams.isForce()); vdsCmdParams.setCheckConnectivity(bckndCmdParams.isCheckConnectivity()); int timeout = bckndCmdParams.getConectivityTimeout() != null ? bckndCmdParams.getConectivityTimeout() : Config.<Integer> GetValue(ConfigValues.NetworkConnectivityCheckTimeoutInSeconds); vdsCmdParams.setConectivityTimeout(timeout); FutureVDSCall<VDSReturnValue> setupNetworksTask = createFutureTask(vdsCmdParams); if (bckndCmdParams.isCheckConnectivity()) { pollInterruptively(setupNetworksTask); } try { VDSReturnValue retVal = setupNetworksTask.get(timeout, TimeUnit.SECONDS); if (retVal != null) { <START> VDSBrokerFrontendImpl.handleVdsResult(retVal); <END> if (retVal.getSucceeded()) { setSucceeded(TransactionSupport.executeInNewTransaction(updateVdsNetworksInTx(bckndCmdParams))); } } } catch (TimeoutException e) { log.debugFormat("Setup networks command timed out for {0} seconds", timeout); } }</code><technical_language>I handleVdsResult() remain non-static if Backend.getInstance().getResourceManager().handleVdsResult()</technical_language>

Target:
protected void executeCommand() { T bckndCmdParams = getParameters(); final SetupNetworksVdsCommandParameters vdsCmdParams = new SetupNetworksVdsCommandParameters( getVdsId(), getNetworks(), getRemovedNetworks(), getBonds(), getRemovedBonds(), getInterfaces()); vdsCmdParams.setForce(bckndCmdParams.isForce()); vdsCmdParams.setCheckConnectivity(bckndCmdParams.isCheckConnectivity()); int timeout = bckndCmdParams.getConectivityTimeout() != null ? bckndCmdParams.getConectivityTimeout() : Config.<Integer> GetValue(ConfigValues.NetworkConnectivityCheckTimeoutInSeconds); vdsCmdParams.setConectivityTimeout(timeout); FutureVDSCall<VDSReturnValue> setupNetworksTask = createFutureTask(vdsCmdParams); if (bckndCmdParams.isCheckConnectivity()) { pollInterruptively(setupNetworksTask); } try { VDSReturnValue retVal = setupNetworksTask.get(timeout, TimeUnit.SECONDS); if (retVal != null) { VdsHandler.handleVdsResult(retVal); if (retVal.getSucceeded()) { setSucceeded(TransactionSupport.executeInNewTransaction(updateVdsNetworksInTx(bckndCmdParams))); } } } catch (TimeoutException e) { log.debugFormat("Setup networks command timed out for {0} seconds", timeout); } }
Source:
<code>public void givenASingleGetRequestWhenResponseThenBlockWithCompletableAndLog() <START> throws InterruptedException, ExecutionException { <END> AtomicInteger completedReqs = new AtomicInteger(0); WSClient ws = play.test.WSTestClient.newClient(port); WSResponse wsResponse = ws.url(url) .setRequestFilter(new AhcCurlRequestLogger()) .addHeader("key", "value") .addQueryParameter("num", "" + 1) .get() .toCompletableFuture() .get(); log.debug("Thread#" + Thread.currentThread() .getId() + " Request complete: Response code = " + wsResponse.getStatus() + " | Response: " + wsResponse.getBody() + " | Current Time:" + System.currentTimeMillis()); }</code><technical_language>Tests throws Exception, a specific one, multiple ones</technical_language>

Target:
public void givenASingleGetRequestWhenResponseThenBlockWithCompletableAndLog() throws Exception { WSClient ws = play.test.WSTestClient.newClient(port); WSResponse wsResponse = ws.url(url) .setRequestFilter(new AhcCurlRequestLogger()) .addHeader("key", "value") .addQueryParameter("num", "" + 1) .get() .toCompletableFuture() .get(); log.debug("Thread#" + Thread.currentThread() .getId() + " Request complete: Response code = " + wsResponse.getStatus() + " | Response: " + wsResponse.getBody() + " | Current Time:" + System.currentTimeMillis()); assert (HttpStatus.SC_OK == wsResponse.getStatus()); }
Source:
<code>public static Throwable create() { <START> if (System.getProperty("rxjava.captureSchedulerContext", "false").equals("true")) { <END> return new SchedulerContextException(); } return null; }</code><technical_language>Better. Do want this changeable runtime</technical_language>

Target:
public static Throwable create() { String def = "false"; String setTo = System.getProperty("rxjava.captureSchedulerContext", def); return setTo != def && "true".equals(setTo) ? new SchedulerContextException("Asynchronous work scheduled at") : CONTEXT_MISSING; }
Source:
<code>public boolean matches(MethodParams params) { <START> return params.is(CommandMessage.class) && params.is(GeneratedMessageV3.class); <END> }</code><technical_language>GeneratedMessageV3? I suppose, Message provides a sufficient interface. CommandMessage extends Message</technical_language>

Target:
public boolean matches(MethodParams params) { return params.match(criteria); }
Source:
<code>public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) { Matcher matcher = PATTERN.matcher(spec); if (!matcher.matches()) { throw new IllegalArgumentException("Invalid location '" + spec + "'; must specify something like single(named:foo)"); } String args = matcher.group(2); Map locationArgs = KeyValueParser.parseMap(args); String target = locationArgs.get("target").toString(); locationArgs.remove("target"); for (Object key : locationArgs.keySet()) { Object value = locationArgs.get(key); if (value instanceof String) { <START> Matcher listMatcher = LIST_PATTERN.matcher(value.toString()); <END> if (listMatcher.matches()) { List<String> strings = KeyValueParser.parseList(listMatcher.group(1)); List<Integer> integers = new ArrayList<Integer>(); boolean intList = true; for (String string : strings) { if (INTEGER_PATTERN.matcher(string).matches()) { integers.add(Integer.parseInt(string)); } else { intList = false; break; } } locationArgs.put(key, intList ? integers : strings); } } } if (!managementContext.getLocationRegistry().canResolve(target)) { throw new IllegalArgumentException("Invalid target location '" + target + "'; must be resolvable location"); } return new SingleMachineProvisioningLocation<MachineLocation>(target, locationArgs); }</code><technical_language>put this in JcloudsLocation.toIntArray(Object). called if expected a list of integers. "[1]" get converted (I think). is fine. imagine unexpected set a tag of "[1]" a VM, failing of this conversion..</technical_language>

Target:
public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) { Matcher matcher = PATTERN.matcher(spec); if (!matcher.matches()) { throw new IllegalArgumentException("Invalid location '" + spec + "'; must specify something like single(named:foo)"); } String args = matcher.group(2); Map locationArgs = KeyValueParser.parseMap(args); if (locationArgs == null || locationArgs.get("target") == null) { throw new IllegalArgumentException("target must be specified in spec"); } String target = locationArgs.get("target").toString(); locationArgs.remove("target"); if (!managementContext.getLocationRegistry().canResolve(target)) { throw new IllegalArgumentException("Invalid target location '" + target + "'; must be resolvable location"); } return new SingleMachineProvisioningLocation<MachineLocation>(target, locationArgs); }
Source:
<code>public void enforceCpuLimits() { for (QueryExecution query : queries.values()) { Duration cpuTime = query.getTotalCpuTime(); Duration sessionLimit = getQueryMaxCpuTime(query.getSession()); <START> Duration limit = maxQueryCpuTime.compareTo(sessionLimit) < 0 ? maxQueryCpuTime : sessionLimit; <END> if (cpuTime.compareTo(limit) > 0) { query.fail(new ExceededCpuLimitException(limit)); } } }</code><technical_language>Duration limit = Ordering.natural().min(maxQueryCpuTime, sessionLimit) highlight of two</technical_language>

Target:
public void enforceCpuLimits() { for (QueryExecution query : queries.values()) { Duration cpuTime = query.getTotalCpuTime(); Duration sessionLimit = getQueryMaxCpuTime(query.getSession()); Duration limit = Ordering.natural().min(maxQueryCpuTime, sessionLimit); if (cpuTime.compareTo(limit) > 0) { query.fail(new ExceededCpuLimitException(limit)); } } }
Source:
<code>public void testServerIsNotifiedAboutNewAttributesAndTheirPms() { <START> final AtomicReference<Command> receivedCommand = new AtomicReference<Command>(null); <END> CommandHandler testServerAction = new CommandHandler<CreatePresentationModelCommand>() { @Override public void handleCommand(CreatePresentationModelCommand command, List<Command> response) { receivedCommand.set(command); } }; serverConnector.getRegistry().register(CreatePresentationModelCommand.class, testServerAction); clientModelStore.add(new ClientPresentationModel("testPm", Arrays.asList(new ClientAttribute("name", null)))); clientDolphin.sync(new Runnable() { @Override public void run() { Assert.assertNotNull(receivedCommand.get()); Assert.assertEquals("CreatePresentationModel", receivedCommand.get().getId()); Assert.assertEquals(CreatePresentationModelCommand.class, receivedCommand.get().getClass()); CreatePresentationModelCommand cmd = (CreatePresentationModelCommand) receivedCommand.get(); Assert.assertEquals("testPm", cmd.getPmId()); config.assertionsDone(); } }); }</code><technical_language>remove Command <> right side</technical_language>

Target:
public void testServerIsNotifiedAboutNewAttributesAndTheirPms() { final AtomicReference<Command> receivedCommand = new AtomicReference<>(null); CommandHandler<CreatePresentationModelCommand> testServerAction = new CommandHandler<CreatePresentationModelCommand>() { @Override public void handleCommand(CreatePresentationModelCommand command, List<Command> response) { receivedCommand.set(command); } }; serverConnector.getRegistry().register(CreatePresentationModelCommand.class, testServerAction); clientModelStore.add(new ClientPresentationModel("testPm", Arrays.asList(new ClientAttribute("name", null)))); clientDolphin.sync(new Runnable() { @Override public void run() { Assert.assertNotNull(receivedCommand.get()); Assert.assertEquals("CreatePresentationModel", receivedCommand.get().getId()); Assert.assertEquals(CreatePresentationModelCommand.class, receivedCommand.get().getClass()); CreatePresentationModelCommand cmd = (CreatePresentationModelCommand) receivedCommand.get(); Assert.assertEquals("testPm", cmd.getPmId()); config.assertionsDone(); } }); }
Source:
<code>public BigInteger getPrivKey() { if (privKey == null) { throw new MissingPrivateKeyException(); } else if (privKey instanceof BCECPrivateKey) { <START> return ((BCECPrivateKey) privKey).getS(); <END> } else { throw new MissingPrivateKeyException(); } }</code><technical_language>I BCECPrivateKey.getS() BCECPrivateKey.getD() return value. of used, is intentionally? wondering if this is matter names in interfaces is a subtlety</technical_language>

Target:
public BigInteger getPrivKey() { if (privKey == null) { throw new MissingPrivateKeyException(); } else if (privKey instanceof BCECPrivateKey) { return ((BCECPrivateKey) privKey).getD(); } else { throw new MissingPrivateKeyException(); } }
Source:
<code><START> public void whenStreamTimeoutReachedThenEventsFlushed() throws Exception { <END> final TestStreamingClient client = TestStreamingClient .create(URL, subscription.getId(), "batch_flush_timeout=600&batch_limit=1000&stream_timeout=2&max_uncommitted_events=3") .start(); waitFor(() -> assertThat(client.getSessionId(), not(equalTo(SESSION_ID_UNKNOWN)))); publishEvents(eventType.getName(), 4, x -> "{\"foo\":\"bar\"}"); waitFor(() -> assertThat(client.getBatches(), hasSize(2))); assertThat(client.getBatches().get(0).getEvents(), hasSize(3)); assertThat(client.getBatches().get(1).getEvents(), hasSize(0)); }</code><technical_language>I tested streaming this parameter in stack new behave way. 2 batches, 3 events other debug message. this test exercise prove fix works</technical_language>

Target:
public void whenStreamTimeoutReachedThenEventsFlushed() throws Exception { final TestStreamingClient client = TestStreamingClient .create(URL, subscription.getId(), "batch_flush_timeout=600&batch_limit=1000&stream_timeout=2&max_uncommitted_events=1000") .start(); waitFor(() -> assertThat(client.getSessionId(), not(equalTo(SESSION_ID_UNKNOWN)))); publishEvents(eventType.getName(), 4, x -> "{\"foo\":\"bar\"}"); waitFor(() -> assertThat(client.getBatches(), hasSize(2))); assertThat(client.getBatches().get(0).getEvents(), hasSize(4)); assertThat(client.getBatches().get(1).getEvents(), hasSize(0)); System.out.println(client.getBatches()); }
Source:
<code>public void afterPropertiesSet() { eventBus.register(this); <START> faWindowTitle = clientProperties.getForgedAlliance().getWindowTitle(); currentGame.addListener((observable, oldValue, newValue) -> { if (newValue == null) { discordRichPresenceService.clearGameInfo(); return; } InvalidationListener listener = generateNumberOfPlayersChangeListener(newValue); JavaFxUtil.addListener(newValue.numPlayersProperty(), listener); listener.invalidated(newValue.numPlayersProperty()); ChangeListener<GameStatus> statusChangeListener = generateGameStatusListener(newValue); JavaFxUtil.addListener(newValue.statusProperty(), statusChangeListener); statusChangeListener.changed(newValue.statusProperty(), newValue.getStatus(), newValue.getStatus()); }); games = FXCollections.observableList(new ArrayList<>(), item -> new Observable[]{item.statusProperty(), item.getTeams()} ); JavaFxUtil.attachListToMap(games, uidToGameInfoBean); <END> fafService.addOnMessageListener(GameInfoMessage.class, message -> Platform.runLater(() -> onGameInfo(message))); fafService.addOnMessageListener(LoginMessage.class, message -> onLoggedIn()); JavaFxUtil.addListener(fafService.connectionStateProperty(), (observable, oldValue, newValue) -> { if (newValue == ConnectionState.DISCONNECTED) { synchronized (uidToGameInfoBean) { uidToGameInfoBean.clear(); } } }); }</code><technical_language>add constructor</technical_language>

Target:
public void afterPropertiesSet() { eventBus.register(this); fafService.addOnMessageListener(GameInfoMessage.class, message -> Platform.runLater(() -> onGameInfo(message))); fafService.addOnMessageListener(LoginMessage.class, message -> onLoggedIn()); JavaFxUtil.addListener(fafService.connectionStateProperty(), (observable, oldValue, newValue) -> { if (newValue == ConnectionState.DISCONNECTED) { synchronized (uidToGameInfoBean) { uidToGameInfoBean.clear(); } } }); }
Source:
<code>public ResponseEntity<String> visualizeNetworks(@ProjectIdentifier @PathVariable("projectUnixName") String unixName, @PathVariable("networkId") String networkId, Principal principal, @CheckAccess @InjectProject IProject project, @RequestParam("projectId") String projectId) { ITransformedNetwork transformedNetwork = null; try { transformedNetwork = transformationManager.getTransformedNetwork(networkId); } catch (QuadrigaStorageException qse) { <START> logger.error("Error:" + qse.getMessage()); <END> return new ResponseEntity<String>("", HttpStatus.INTERNAL_SERVER_ERROR); } String json = null; if (transformedNetwork != null) { json = jsonCreator.getJson(transformedNetwork.getNodes(), transformedNetwork.getLinks()); } else { return new ResponseEntity<String>(json, HttpStatus.NOT_FOUND); } return new ResponseEntity<String>(json, HttpStatus.OK); }</code><technical_language>please log stack trace. Otherwise, this helpful</technical_language>

Target:
public ResponseEntity<String> visualizeNetworks(@ProjectIdentifier @PathVariable("projectUnixName") String unixName, @PathVariable("networkId") String networkId, Principal principal, @CheckAccess @InjectProject IProject project, @RequestParam("projectId") String projectId) { ITransformedNetwork transformedNetwork = null; try { transformedNetwork = transformationManager.getTransformedNetwork(networkId); } catch (QuadrigaStorageException qse) { logger.error("Error:" + qse); return new ResponseEntity<String>("", HttpStatus.INTERNAL_SERVER_ERROR); } String json = null; if (transformedNetwork != null) { json = jsonCreator.getJson(transformedNetwork.getNodes(), transformedNetwork.getLinks()); } else { return new ResponseEntity<String>(json, HttpStatus.NOT_FOUND); } return new ResponseEntity<String>(json, HttpStatus.OK); }
Source:
<code>public void testBasicLocalDistributedCallable() throws Exception { long taskTimeout = TimeUnit.SECONDS.toMillis(15); EmbeddedCacheManager cacheManager1 = manager(0); final EmbeddedCacheManager cacheManager2 = manager(1); final EmbeddedCacheManager cacheManager3 = manager(2); TestingUtil.killCacheManagers(cacheManager2); TestingUtil.killCacheManagers(cacheManager3); Cache<Object, Object> cache1 = cacheManager1.getCache(); DistributedExecutorService des = null; try { des = new DefaultExecutorService(cache1); SameNodeTaskFailoverPolicy sameNodeTaskFailoverPolicy = new SameNodeTaskFailoverPolicy(2); DistributedTaskBuilder<Void> builder = des .createDistributedTaskBuilder(new TestCallable()) .failoverPolicy(sameNodeTaskFailoverPolicy) .timeout(taskTimeout, TimeUnit.MILLISECONDS); CompletableFuture<Void> future = des.submit(builder.build()); future.whenComplete((aVoid,throwable) -> { Executors.newSingleThreadExecutor().submit((Callable<Void>)() -> { future.get(); <START> AssertJUnit.assertEquals(sameNodeTaskFailoverPolicy.failoverCount, 2); <END> return null; }); }); } catch (Exception ex) { AssertJUnit.fail("Task did not failover properly " + ex); } finally { des.shutdown(); } }</code><technical_language>This needs happen main thread, TestNG report it</technical_language>

Target:
public void testBasicLocalDistributedCallable() throws Exception { long taskTimeout = TimeUnit.SECONDS.toMillis(15); EmbeddedCacheManager cacheManager1 = manager(0); Cache<Object, Object> cache1 = cacheManager1.getCache(); DistributedExecutorService des = null; try { des = new DefaultExecutorService(cache1); SameNodeTaskFailoverPolicy sameNodeTaskFailoverPolicy = new SameNodeTaskFailoverPolicy(3); DistributedTaskBuilder<Void> builder = des .createDistributedTaskBuilder(new TestCallable()) .failoverPolicy(sameNodeTaskFailoverPolicy) .timeout(taskTimeout, TimeUnit.MILLISECONDS); CompletableFuture<Void> future = des.submit(builder.build()); TriggerFailover(future); eventuallyEquals(3, () -> sameNodeTaskFailoverPolicy.failoverCount.get()); } catch (Exception ex) { AssertJUnit.fail("Task did not failover properly " + ex); } finally { des.shutdown(); } }
Source:
<code>static String guessEntityTypeFromId(String id, boolean returnJsonEntity) { if(id.isEmpty()) { throw new IllegalArgumentException("Entity ids should not be empty."); } switch (id.charAt(0)) { case 'L': if(id.contains("-F")) { return returnJsonEntity ? JSON_ENTITY_TYPE_FORM : DatatypeIdValue.DT_FORM; } else if(id.contains("-S")) { return returnJsonEntity ? JSON_ENTITY_TYPE_SENSE : DatatypeIdValue.DT_SENSE; } else { return returnJsonEntity ? JSON_ENTITY_TYPE_LEXEME : DatatypeIdValue.DT_LEXEME; } case 'M': <START> return JSON_ENTITY_TYPE_MEDIA_INFO; <END> case 'P': return returnJsonEntity ? JSON_ENTITY_TYPE_PROPERTY : DatatypeIdValue.DT_PROPERTY; case 'Q': return returnJsonEntity ? JSON_ENTITY_TYPE_ITEM : DatatypeIdValue.DT_ITEM; default: throw new IllegalArgumentException("Entity id \"" + id + "\" is not supported."); } }</code><technical_language>want return DatatypeIdValue.DT_MEDIA_INFO, no</technical_language>

Target:
static String guessEntityTypeFromId(String id, boolean returnJsonEntity) { if(id.isEmpty()) { throw new IllegalArgumentException("Entity ids should not be empty."); } switch (id.charAt(0)) { case 'L': if(id.contains("-F")) { return returnJsonEntity ? JSON_ENTITY_TYPE_FORM : DatatypeIdValue.DT_FORM; } else if(id.contains("-S")) { return returnJsonEntity ? JSON_ENTITY_TYPE_SENSE : DatatypeIdValue.DT_SENSE; } else { return returnJsonEntity ? JSON_ENTITY_TYPE_LEXEME : DatatypeIdValue.DT_LEXEME; } case 'M': return returnJsonEntity ? JSON_ENTITY_TYPE_MEDIA_INFO : DatatypeIdValue.DT_MEDIA_INFO; case 'P': return returnJsonEntity ? JSON_ENTITY_TYPE_PROPERTY : DatatypeIdValue.DT_PROPERTY; case 'Q': return returnJsonEntity ? JSON_ENTITY_TYPE_ITEM : DatatypeIdValue.DT_ITEM; default: throw new IllegalArgumentException("Entity id \"" + id + "\" is not supported."); } }
Source:
<code>protected ImageDescriptor decorateImage(ImageDescriptor input, Object element) { ImageDescriptor <START> res = <END> super.decorateImage(input, element); if (res == null) { return null; } IResource resource = Adapters.adapt(element, IResource.class); if (resource != null && (resource.getType() != IResource.PROJECT || ((IProject) resource).isOpen())) { ImageDescriptor overlay = null; switch (getHighestProblemSeverity(resource)) { case IMarker.SEVERITY_ERROR: overlay = PlatformUI.getWorkbench().getSharedImages() .getImageDescriptor(ISharedImages.IMG_DEC_FIELD_ERROR); break; case IMarker.SEVERITY_WARNING: overlay = PlatformUI.getWorkbench().getSharedImages() .getImageDescriptor(ISharedImages.IMG_DEC_FIELD_WARNING); break; } if (overlay != null) { res = new DecorationOverlayIcon(res, overlay, IDecoration.BOTTOM_LEFT); } } return res; }</code><technical_language>please name "descriptor"? "res" is for IResource friends</technical_language>

Target:
protected ImageDescriptor decorateImage(ImageDescriptor input, Object element) { ImageDescriptor descriptor = super.decorateImage(input, element); if (descriptor == null) { return null; } IResource resource = Adapters.adapt(element, IResource.class); if (resource != null && (resource.getType() != IResource.PROJECT || ((IProject) resource).isOpen())) { ImageDescriptor overlay = null; switch (getHighestProblemSeverity(resource)) { case IMarker.SEVERITY_ERROR: overlay = PlatformUI.getWorkbench().getSharedImages() .getImageDescriptor(ISharedImages.IMG_DEC_FIELD_ERROR); break; case IMarker.SEVERITY_WARNING: overlay = PlatformUI.getWorkbench().getSharedImages() .getImageDescriptor(ISharedImages.IMG_DEC_FIELD_WARNING); break; } if (overlay != null) { descriptor = new DecorationOverlayIcon(descriptor, overlay, IDecoration.BOTTOM_LEFT); } } return descriptor; }
Source:
<code>private void initLocalizationEditor() { localeBox = new ListBox(); selectedLocale = new Label(); String currentLocale = LocaleInfo.getCurrentLocale().getLocaleName(); String[] localeNames = LocaleInfo.getAvailableLocaleNames(); boolean foundDefaultLocale = false; for (String localeName : localeNames) { if (!DEFAULT_LOCALE.equals(localeName)) { String nativeName = LocaleInfo.getLocaleNativeDisplayName(localeName); localeBox.addItem(nativeName, localeName); if (localeName.equals(currentLocale)) { setSelectedLocale(localeBox.getItemCount() - 1); foundDefaultLocale = true; } } } if (!foundDefaultLocale && localeNames.length > 0) { setSelectedLocale(0); } if (clientAgentType.isIE8OrBelow()) { selectedLocale.getElement().getStyle().setOpacity(0); } localeBox.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { <START> String localeString = "?locale=" + localeBox.getValue(localeBox.getSelectedIndex()); END> Window.open(FrontendUrlUtils.getCurrentPageURL() + localeString, "_self", ""); } }); }</code><technical_language>LocaleInfo.getLocaleQueryParam() instead of hard-coded "locale" string</technical_language>

Target:
private void initLocalizationEditor() { localeBox = new ListBox(); selectedLocale = new Label(); String currentLocale = LocaleInfo.getCurrentLocale().getLocaleName(); String[] localeNames = LocaleInfo.getAvailableLocaleNames(); boolean foundDefaultLocale = false; for (String localeName : localeNames) { if (!DEFAULT_LOCALE.equals(localeName)) { String nativeName = LocaleInfo.getLocaleNativeDisplayName(localeName); localeBox.addItem(nativeName, localeName); if (localeName.equals(currentLocale)) { setSelectedLocale(localeBox.getItemCount() - 1); foundDefaultLocale = true; } } } if (!foundDefaultLocale && localeNames.length > 0) { setSelectedLocale(0); } if (clientAgentType.isIE8OrBelow()) { selectedLocale.getElement().getStyle().setOpacity(0); } localeBox.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { String localeQueryParam = LocaleInfo.getLocaleQueryParam(); String localeString = "?" + localeQueryParam + "=" + localeBox.getValue(localeBox.getSelectedIndex()); Window.open(FrontendUrlUtils.getCurrentPageURL() + localeString, "_self", ""); } }); }
Source:
<code>public DefaultControlFlowConfigurator() { <START> GeoServerResourceLoader loader = (GeoServerResourceLoader) GeoServerExtensions.bean( "resourceLoader"); <END> Resource controlflow = loader.get(PROPERTYFILENAME); configFile = new PropertyFileWatcher(controlflow); }</code><technical_language>Nitpick: GeoServerExtensions.bean(GeoServerResourceLoader.class) refactor safe avoids cast. I a single GeoServerResourceLoader in GS (or not?)</technical_language>

Target:
public DefaultControlFlowConfigurator() { GeoServerResourceLoader loader = GeoServerExtensions.bean(GeoServerResourceLoader.class); Resource controlflow = loader.get(PROPERTYFILENAME); configFile = new PropertyFileWatcher(controlflow); }
Source:
<code><START> public void setAccountId(Long accountId) { <END> this.accountId = accountId; }</code><technical_language>Is a public setter necessary? abstraction CentralRepositoryAccount instance itself, primitive</technical_language>

Target:
void setAccountId(Long accountId) { this.accountId = accountId; }
Source:
<code>public List<Task> getTasks() { <START> return tasks; <END> }</code><technical_language>unmodifiable list</technical_language>

Target:
public List<Task> getTasks() { return Collections.unmodifiableList(tasks); }
Source:
<code>public void testAbortAndRestartOnce() throws Exception { FreeStyleProject testproject = j.createFreeStyleProject(); QuickBuildTimeOutStrategy strategy = new QuickBuildTimeOutStrategy(5000); AbortAndRestartOperation operation = new AbortAndRestartOperation(1); LinkedList<BuildTimeOutOperation> list = new LinkedList<BuildTimeOutOperation>(); list.add(operation); BuildTimeoutWrapper wrapper = new BuildTimeoutWrapper(strategy,list,""); testproject.getBuildWrappersList().add(wrapper); testproject.getBuildersList().add(new SleepBuilder(5*60*1000)); testproject.scheduleBuild(new Cause.UserIdCause()); j.waitUntilNoActivityUpTo(25000); <START> assertTrue(testproject.getFirstBuild() != null); <END> assertFalse(testproject.getFirstBuild().equals(testproject.getLastBuild())); assertEquals(testproject.getBuilds().size(), 2); assertEquals(Result.ABORTED, testproject.getFirstBuild().getResult()); assertEquals(Result.ABORTED, testproject.getLastBuild().getResult()); }</code><technical_language>assertNotNull. helps test fails unexpectedly displays actual unexpected in log</technical_language>

Target:
public void testAbortAndRestartOnce() throws Exception { FreeStyleProject testproject = j.createFreeStyleProject(); QuickBuildTimeOutStrategy strategy = new QuickBuildTimeOutStrategy(5000); AbortAndRestartOperation operation = new AbortAndRestartOperation("1"); LinkedList<BuildTimeOutOperation> list = new LinkedList<BuildTimeOutOperation>(); list.add(operation); BuildTimeoutWrapper wrapper = new BuildTimeoutWrapper(strategy,list,""); testproject.getBuildWrappersList().add(wrapper); testproject.getBuildersList().add(new SleepBuilder(5*60*1000)); testproject.scheduleBuild(new Cause.UserIdCause()); j.waitUntilNoActivityUpTo(25000); assertNotNull(testproject.getFirstBuild()); assertFalse(testproject.getFirstBuild().equals(testproject.getLastBuild())); assertEquals(testproject.getBuilds().size(), 2); assertEquals(Result.ABORTED, testproject.getFirstBuild().getResult()); assertEquals(Result.ABORTED, testproject.getLastBuild().getResult()); }
Source:
<code>protected List<DocumentModel> queryClients() { DirectoryService service = Framework.getService(DirectoryService.class); return Framework.doPrivileged(() -> { try (Session session = service.open(OAUTH2CLIENT_DIRECTORY_NAME)) { return session.query(Collections.emptyMap()); } catch (DirectoryException e) { log.error("Error while fetching provider directory", e); <START> return Collections.emptyList(); <END> } }); }</code><technical_language>throw a NuxeoException return empty list. If this happen throw</technical_language>

Target:
protected List<DocumentModel> queryClients() { DirectoryService service = Framework.getService(DirectoryService.class); return Framework.doPrivileged(() -> { try (Session session = service.open(OAUTH2CLIENT_DIRECTORY_NAME)) { return session.query(Collections.emptyMap()); } catch (DirectoryException e) { throw new NuxeoException("Error while fetching client directory", e); } }); }
Source:
<code>public void performRitual(IMasterRitualStone masterRitualStone) { AxisAlignedBB aabb = getBlockRange(FLIGHT_RANGE).getAABB(masterRitualStone.getBlockPos()).expand(-10, 0, -10); <START> System.out.println(aabb); <END> World world = masterRitualStone.getWorldObj(); int currentEssence = masterRitualStone.getOwnerNetwork().getCurrentEssence(); List<EntityPlayer> entityPlayers = world.getEntitiesWithinAABB(EntityPlayer.class, aabb); int entityCount = entityPlayers.size(); if (currentEssence < getRefreshCost() * entityCount) { masterRitualStone.getOwnerNetwork().causeNausea(); return; } else { entityCount = 0; for (EntityPlayer player : entityPlayers) { player.addPotionEffect(new PotionEffect(RegistrarBloodMagic.FLIGHT, 20, 0)); } } masterRitualStone.getOwnerNetwork().syphon(masterRitualStone.ticket(getRefreshCost() * entityCount)); }</code><technical_language>pls</technical_language>

Target:
public void performRitual(IMasterRitualStone masterRitualStone) { AxisAlignedBB aabb = getBlockRange(FLIGHT_RANGE).getAABB(masterRitualStone.getBlockPos()).expand(-10, 0, -10); World world = masterRitualStone.getWorldObj(); int currentEssence = masterRitualStone.getOwnerNetwork().getCurrentEssence(); List<EntityPlayer> entityPlayers = world.getEntitiesWithinAABB(EntityPlayer.class, aabb); int entityCount = entityPlayers.size(); if (currentEssence < getRefreshCost() * entityCount) { masterRitualStone.getOwnerNetwork().causeNausea(); return; } else { entityCount = 0; for (EntityPlayer player : entityPlayers) { player.addPotionEffect(new PotionEffect(RegistrarBloodMagic.FLIGHT, 20, 0)); } } masterRitualStone.getOwnerNetwork().syphon(masterRitualStone.ticket(getRefreshCost() * entityCount)); }
Source:
<code>public EditSession createEditSession(Actor actor) { checkNotNull(actor); World world = null; if (hasWorldOverride()) { world = getWorldOverride(); } else if (actor.isPlayer() && actor instanceof Player) { <START> world = ((Player) actor).getWorld(); <END> } EditSession editSession; if (actor.isPlayer() && actor instanceof Player) { BlockBag blockBag = getBlockBag((Player) actor); editSession = WorldEdit.getInstance().getEditSessionFactory().getEditSession( world, getBlockChangeLimit(), blockBag, actor ); } else { editSession = WorldEdit.getInstance().getEditSessionFactory() .getEditSession(world, getBlockChangeLimit()); } Request.request().setEditSession(editSession); editSession.setFastMode(fastMode); editSession.setReorderMode(reorderMode); editSession.setMask(mask); if (editSession.getSurvivalExtent() != null) { editSession.getSurvivalExtent().setStripNbt(!actor.hasPermission("worldedit.setnbt")); } return editSession; }</code><technical_language>This redundant? Is a case "Player" "isPlayer"</technical_language>

Target:
public EditSession createEditSession(Actor actor) { checkNotNull(actor); World world = null; if (hasWorldOverride()) { world = getWorldOverride(); } else if (actor instanceof Locatable && ((Locatable) actor).getExtent() instanceof World) { world = (World) ((Locatable) actor).getExtent(); } EditSession editSession; if (actor.isPlayer() && actor instanceof Player) { BlockBag blockBag = getBlockBag((Player) actor); editSession = WorldEdit.getInstance().getEditSessionFactory().getEditSession( world, getBlockChangeLimit(), blockBag, actor ); } else { editSession = WorldEdit.getInstance().getEditSessionFactory() .getEditSession(world, getBlockChangeLimit()); } Request.request().setEditSession(editSession); editSession.setFastMode(fastMode); editSession.setReorderMode(reorderMode); editSession.setMask(mask); if (editSession.getSurvivalExtent() != null) { editSession.getSurvivalExtent().setStripNbt(!actor.hasPermission("worldedit.setnbt")); } return editSession; }
Source:
<code>public void parseGeoLocation() { String[] geoParts = StringUtils.split(geolocation, ","); if (geoParts.length == 2) { latitude = toDouble(geoParts[0]); longitude = toDouble(geoParts[1]); } else if (geoParts.length == 3) { latitude = toDouble(geoParts[0]); longitude = toDouble(geoParts[1]); <START> altitude = Integer.parseInt(geoParts[2]); <END> } }</code><technical_language>do assume is int? PointType BigDecimal for altitude, support this</technical_language>

Target:
public void parseGeoLocation() { String[] geoParts = StringUtils.split(geolocation, ","); if (geoParts.length == 2) { latitude = toDouble(geoParts[0]); longitude = toDouble(geoParts[1]); } else if (geoParts.length == 3) { latitude = toDouble(geoParts[0]); longitude = toDouble(geoParts[1]); altitude = toDouble(geoParts[2]); } }
Source:
<code>public void testSchemaStoreRetrieval() { <START> Assert.assertNotNull(Framework.getService(SchemaStore.class)); <END> }</code><technical_language>work for org.nuxeo.runtime.avro.AvroSchemaStoreService</technical_language>

Target:
public void testSchemaStoreRetrieval() { assertNotNull(Framework.getService(SchemaStore.class)); assertNotNull(Framework.getService(AvroSchemaStoreService.class)); }
Source:
<code>public void setRange(final int minRow, final int maxRow) { this.minRow = minRow; this.maxRow = maxRow; <START> Preconditions.checkArgument(maxRow > 0); <END> Preconditions.checkState(minRow < maxRow, "minRow >= maxRow. (minRow=%s, ,maxRow=%s)", minRow, maxRow); }</code><technical_language>a message good here</technical_language>

Target:
public void setRange(final int minRow, final int maxRow) { this.minRow = minRow; this.maxRow = maxRow; Preconditions.checkArgument(maxRow > 0, "maxRow: %s", maxRow); Preconditions.checkState(minRow < maxRow, "minRow >= maxRow. (minRow=%s, ,maxRow=%s)", minRow, maxRow); }
Source:
<code>static StatsDEmitter of(StatsDEmitterConfig config, ObjectMapper mapper) { NonBlockingStatsDClient client = new NonBlockingStatsDClient( config.getPrefix(), config.getHostname(), config.getPort(), <START> config.getDogstatsd() ? config.getDogstatsdConstantTags().toArray(new String[0]) : EMPTY_ARRAY, <END> new StatsDClientErrorHandler() { private int exceptionCount = 0; @Override public void handle(Exception exception) { if (exceptionCount % 1000 == 0) { log.error(exception, "Error sending metric to StatsD."); } exceptionCount += 1; } } ); return new StatsDEmitter(config, mapper, client); }</code><technical_language>For boolean field, I prefer Getter method isXXX, change StatsDEmitterConfig#getDogstatsd StatsDEmitterConfig#isDogstatsd better</technical_language>

Target:
static StatsDEmitter of(StatsDEmitterConfig config, ObjectMapper mapper) { NonBlockingStatsDClient client = new NonBlockingStatsDClient( config.getPrefix(), config.getHostname(), config.getPort(), config.isDogstatsd() ? config.getDogstatsdConstantTags().toArray(new String[0]) : EMPTY_ARRAY, new StatsDClientErrorHandler() { private int exceptionCount = 0; @Override public void handle(Exception exception) { if (exceptionCount % 1000 == 0) { log.error(exception, "Error sending metric to StatsD."); } exceptionCount += 1; } } ); return new StatsDEmitter(config, mapper, client); }
Source:
<code><START> public void testGetActiveNotifications() throws Exception { <END> if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return; } notificationManager.notify(1, notification1); notificationManager.notify(31, notification2); StatusBarNotification[] statusBarNotifications = shadowOf(notificationManager).getActiveNotifications(); assertEquals(2, statusBarNotifications.length); boolean hasNotification1 = false; boolean hasNotification2 = false; for (StatusBarNotification notification : statusBarNotifications) { if (notification.getId() == 1) { hasNotification1 = true; assertEquals(notification1, notification.getNotification()); } else if (notification.getId() == 31) { hasNotification2 = true; assertEquals(notification2, notification.getNotification()); } else { fail("Unexpected notification id " + notification.getId()); } } assertTrue(hasNotification1 && hasNotification2); }</code><technical_language>@Config(minSdk = Build.VERSION_CODES.M) instead of test short circuit</technical_language>

Target:
public void testGetActiveNotifications() throws Exception { notificationManager.notify(1, notification1); notificationManager.notify(31, notification2); StatusBarNotification[] statusBarNotifications = shadowOf(notificationManager).getActiveNotifications(); assertThat(statusBarNotifications) .extractingResultOf("getNotification", Notification.class) .containsOnly(notification1, notification2); }
Source:
<code>private ConnectorSession sampleSize(int sampleSize) { <START> return new TestingConnectorSession(new HiveSessionProperties(getHiveClientConfig().setPartitionStatisticsSampleSize(sampleSize), new OrcFileWriterConfig()).getSessionProperties()); <END> }</code><technical_language>nit: wrap this</technical_language>

Target:
private ConnectorSession sampleSize(int sampleSize) { HiveSessionProperties properties = new HiveSessionProperties( getHiveClientConfig().setPartitionStatisticsSampleSize(sampleSize), new OrcFileWriterConfig()); return new TestingConnectorSession(properties.getSessionProperties()); }
Source:
<code>public void testBedTabixIndex( final File inputBed, final List<Interval> queryIntervals ) throws Exception { <START> final File tmpBed = new File(IOUtil.createTempDir("testBedTabixIndex", null), inputBed.getName()); <END> Files.copy(inputBed, tmpBed); final TabixIndex tabixIndexGz = IndexFactory.createTabixIndex(tmpBed, new BEDCodec(), null); tabixIndexGz.writeBasedOnFeatureFile(tmpBed); try(final FeatureReader<BEDFeature> originalReader = AbstractFeatureReader.getFeatureReader(inputBed.getAbsolutePath(), new BEDCodec()); final FeatureReader<BEDFeature> createdReader = AbstractFeatureReader.getFeatureReader(tmpBed.getAbsolutePath(), new BEDCodec())) { for (final Interval interval: queryIntervals) { Iterator<BEDFeature> originalIt = originalReader.query(interval.getContig(), interval.getStart(), interval.getEnd()); Iterator<BEDFeature> createdIt = createdReader.query(interval.getContig(), interval.getStart(), interval.getEnd()); while(originalIt.hasNext()) { Assert.assertTrue(createdIt.hasNext(), "some features not returned from query"); BEDFeature bedOrig = originalIt.next(); BEDFeature bedTmp = createdIt.next(); Assert.assertEquals(bedOrig.getContig(), bedTmp.getContig()); Assert.assertEquals(bedOrig.getStart(), bedTmp.getStart()); Assert.assertEquals(bedOrig.getEnd(), bedTmp.getEnd()); } } } }</code><technical_language>temp dirs place</technical_language>

Target:
public void testBedTabixIndex( final File inputBed, final List<Interval> queryIntervals ) throws Exception { final File tempDir = IOUtil.createTempDir("testBedTabixIndex", null); tempDir.deleteOnExit(); final File tmpBed = new File(tempDir, inputBed.getName()); Files.copy(inputBed, tmpBed); tmpBed.deleteOnExit(); final TabixIndex tabixIndexGz = IndexFactory.createTabixIndex(tmpBed, new BEDCodec(), null); tabixIndexGz.writeBasedOnFeatureFile(tmpBed); final File tmpIndex = Tribble.tabixIndexFile(tmpBed); tmpIndex.deleteOnExit(); try(final FeatureReader<BEDFeature> originalReader = AbstractFeatureReader.getFeatureReader(inputBed.getAbsolutePath(), new BEDCodec()); final FeatureReader<BEDFeature> createdReader = AbstractFeatureReader.getFeatureReader(tmpBed.getAbsolutePath(), new BEDCodec())) { for (final Interval interval: queryIntervals) { final Iterator<BEDFeature> originalIt = originalReader.query(interval.getContig(), interval.getStart(), interval.getEnd()); final Iterator<BEDFeature> createdIt = createdReader.query(interval.getContig(), interval.getStart(), interval.getEnd()); while(originalIt.hasNext()) { Assert.assertTrue(createdIt.hasNext(), "some features not returned from query"); BEDFeature bedOrig = originalIt.next(); BEDFeature bedTmp = createdIt.next(); Assert.assertEquals(bedOrig.getContig(), bedTmp.getContig()); Assert.assertEquals(bedOrig.getStart(), bedTmp.getStart()); Assert.assertEquals(bedOrig.getEnd(), bedTmp.getEnd()); } } } }
Source:
<code>private void loadPreviousTimings() { processes.fetchProcess(processId) <START> .ifPresent(process -> process.getPerformanceCounters().data().keySet().forEach(key -> { <END> int counter = process.getPerformanceCounters().get(key).orElse(0); int timing = process.getTimings().get(key).orElse(0); Average average = new Average(); average.addValues(counter, (double) counter * timing); timings.put(key, average); })); }</code><technical_language>please check code format settings - maven apply "sirius" scheme? (this alright, code style shoudln't change...)</technical_language>

Target:
private void loadPreviousTimings() { processes.fetchProcess(processId).ifPresent(process -> { process.getPerformanceCounters().data().keySet().forEach(key -> { int counter = process.getPerformanceCounters().get(key).orElse(0); int timing = process.getTimings().get(key).orElse(0); Average average = new Average(); average.addValues(counter, (double) counter * timing); timings.put(key, average); }); }); }
Source:
<code>protected void saveData(String filename) { IPath newDataLoc = getNewDataLocation(filename, DATA_EXT); StatData statData = PerfPlugin.getDefault().getStatData(); File statsData = new File(newDataLoc.toOSString()); if (verifyFile(statsData)) { BufferedWriter bw = null; try { statsData.createNewFile(); FileWriter fw = new FileWriter(statsData.getAbsoluteFile()); bw = new BufferedWriter(fw); bw.write(statData.getPerfData()); bw.close(); } catch (IOException e) { String errorMsg = MessageFormat.format( Messages.PerfSaveStat_error_msg, <START> new Object[] { statsData.getName() }); <END> MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.PerfSaveStat_error_title, errorMsg); } } }</code><technical_language>I a try-catch-finally used, buffer closed in finally block</technical_language>

Target:
protected void saveData(String filename) { IPath newDataLoc = getNewDataLocation(filename, DATA_EXT); StatData statData = PerfPlugin.getDefault().getStatData(); File statsData = new File(newDataLoc.toOSString()); if (canSave(statsData)) { BufferedWriter bw = null; try { statsData.createNewFile(); FileWriter fw = new FileWriter(statsData.getAbsoluteFile()); bw = new BufferedWriter(fw); bw.write(statData.getPerfData()); } catch (IOException e) { String errorMsg = MessageFormat.format( Messages.PerfSaveStat_error_msg, new Object[] { statsData.getName() }); MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.PerfSaveStat_error_title, errorMsg); } finally { if (bw != null) { try { bw.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } }