auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private <N extends Number> void registerStatistic(String statNameSuffix, StatisticType type, final ValueStatisticDescriptor descriptor) { if (contextObject == null) { return; } Set<TreeNode> result = queryBuilder() .descendants() .filter(context(attributes(Matchers.<Map<String, Object>>allOf( hasAttribute("name", descriptor.getObserverName()), <START> hasAttribute("tags", new Matcher<Set<String>>() { <END> @Override protected boolean matchesSafely(Set<String> object) { return object.containsAll(descriptor.getTags()); } }))))) .filter(context(identifier(subclassOf(ValueStatistic.class)))) .build().execute(Collections.singleton(ContextManager.nodeFor(contextObject))); if (!result.isEmpty()) { for (TreeNode node : result) { String discriminator = null; Map<String, Object> properties = (Map<String, Object>) node.getContext().attributes().get("properties"); if (properties != null && properties.containsKey("discriminator")) { discriminator = properties.get("discriminator").toString(); } String fullStatName = (discriminator == null ? "" : (discriminator + ":")) + statNameSuffix; ValueStatistic<N> statistic = (ValueStatistic<N>) node.getContext().attributes().get("this"); registerStatistic(fullStatName, type, statistic); } } }</code><technical_language>mutualize a hasTag (probably in stats)</technical_language>

Target:
private <N extends Number> void registerStatistic(String statNameSuffix, StatisticType type, final ValueStatisticDescriptor descriptor) { if (contextObject == null) { return; } Set<TreeNode> result = queryBuilder() .descendants() .filter(context(attributes(Matchers.<Map<String, Object>>allOf( hasAttribute("name", descriptor.getObserverName()), hasTags(descriptor.getTags()))))) .filter(context(identifier(subclassOf(ValueStatistic.class)))) .build().execute(Collections.singleton(ContextManager.nodeFor(contextObject))); if (!result.isEmpty()) { for (TreeNode node : result) { String discriminator = null; Map<String, Object> properties = (Map<String, Object>) node.getContext().attributes().get("properties"); if (properties != null && properties.containsKey("discriminator")) { discriminator = properties.get("discriminator").toString(); } String fullStatName = (discriminator == null ? "" : (discriminator + ":")) + statNameSuffix; ValueStatistic<N> statistic = (ValueStatistic<N>) node.getContext().attributes().get("this"); registerStatistic(fullStatName, type, statistic); } } }
Source:
<code>public MVMap.Decision decide(VersionedValue existingValue, VersionedValue providedValue) { assert decision == null; if (existingValue == null) { decision = MVMap.Decision.ABORT; } else { <START> if (existingValue.getOperationId() == undoKey) { <END> if (existingValue.value == null) { decision = MVMap.Decision.REMOVE; } else { decision = MVMap.Decision.PUT; } } else { decision = MVMap.Decision.ABORT; } } return decision; }</code><technical_language>This if chained else if reduce indentation, matter</technical_language>

Target:
public MVMap.Decision decide(VersionedValue existingValue, VersionedValue providedValue) { assert decision == null; if (existingValue == null || existingValue.getOperationId() != undoKey) { decision = MVMap.Decision.ABORT; } else if (existingValue.value == null) { decision = MVMap.Decision.REMOVE; } else { decision = MVMap.Decision.PUT; } return decision; }
Source:
<code>private List<OSInfluence> getInfluences() { List<OSInfluence> influences = new ArrayList<>(); <START> Set<String> influencesString = OneSignalPrefs.getStringSet( <END> OneSignalPrefs.PREFS_ONESIGNAL, OneSignalPrefs.PREFS_OS_ATTRIBUTED_INFLUENCES, new HashSet<String>() ); for (String influenceJSONString : influencesString) { try { influences.add(new OSInfluence(influenceJSONString)); } catch (JSONException exception) { OneSignal.Log(OneSignal.LOG_LEVEL.ERROR, this.getClass().getSimpleName() + ": error generation OSInfluence from json object: " + exception); } } return influences; }</code><technical_language>influencesString influenceStrings lets rename influenceJsons</technical_language>

Target:
private List<OSInfluence> getInfluences() { List<OSInfluence> influences = new ArrayList<>(); Set<String> influenceJSONs = OneSignalPrefs.getStringSet( OneSignalPrefs.PREFS_ONESIGNAL, OneSignalPrefs.PREFS_OS_ATTRIBUTED_INFLUENCES, new HashSet<String>() ); for (String influenceJSON : influenceJSONs) { try { influences.add(new OSInfluence(influenceJSON)); } catch (JSONException exception) { OneSignal.Log(OneSignal.LOG_LEVEL.ERROR, this.getClass().getSimpleName() + ": error generation OSInfluence from json object: " + exception); } } return influences; }
Source:
<code>public int read() throws IOException { if ( closed ) { throw new IOException( "Joint: " + jointIdx + ": Cannot read from closed stream!" ); } synchronized ( JoinableFile.this ) { while ( read == flushed ) { if ( output == null || JoinableFile.this.closed ) { return -1; } try { JoinableFile.this.wait( 100 ); } catch ( final InterruptedException e ) { return -1; } } } if ( buf.position() == buf.limit() ) { buf = channel.map( MapMode.READ_ONLY, read, flushed > MAX_BUFFER_SIZE ? MAX_BUFFER_SIZE : flushed - read ); } if ( buf.position() == buf.limit() ) { return -1; } final int result = buf.get(); read++; <START> return result < 0 ? result + 256 : result; <END> }</code><technical_language>I this solution is some counting magic :-) changing this return result & 0xff</technical_language>

Target:
public int read() throws IOException { if ( closed ) { throw new IOException( "Joint: " + jointIdx + ": Cannot read from closed stream!" ); } synchronized ( JoinableFile.this ) { while ( read == flushed ) { if ( output == null || JoinableFile.this.closed ) { return -1; } try { JoinableFile.this.wait( 100 ); } catch ( final InterruptedException e ) { return -1; } } } if ( buf.position() == buf.limit() ) { buf = channel.map( MapMode.READ_ONLY, read, flushed > MAX_BUFFER_SIZE ? MAX_BUFFER_SIZE : flushed - read ); } if ( buf.position() == buf.limit() ) { return -1; } final int result = buf.get(); read++; return result & 0xff; }
Source:
<code>private Transition(final InternalStatus to) { if(to == null) { throw new NullPointerException(); } <START> this.from = InternalStatus.this; <END> this.to = to; }</code><technical_language>This field appears redundant, this is class</technical_language>

Target:
private Transition(final InternalStatus to) { if(to == null) { throw new NullPointerException(); } this.to = to; }
Source:
<code>public String getTimeForDisplay() { return TimeHelper.formatTime12H(TimeHelper.convertInstantToLocalDateTime( <START> Instant.ofEpochMilli(emailEntry.getTime()), Const.SystemParams.ADMIN_TIME_ZONE_ID)); <END> }</code><technical_language>Is a do get time for display is unix time? I dig investigate</technical_language>

Target:
public String getTimeForDisplay() { return TimeHelper.formatTime12H(TimeHelper.convertInstantToLocalDateTime( Instant.ofEpochMilli(emailEntry.getTime()), Const.SystemParams.ADMIN_TIME_ZONE)); }
Source:
<code>private void onLightAddedInternal(FullLight light) { ThingUID thingUID = getThingUID(light); ThingTypeUID thingTypeUID = getThingTypeUID(light); String modelId = light.getModelID().replaceAll(HueLightHandler.NORMALIZE_ID_REGEX, "_"); if (thingUID != null && thingTypeUID != null) { ThingUID bridgeUID = hueBridgeHandler.getThing().getUID(); Map<String, Object> properties = new HashMap<>(1); properties.put(LIGHT_ID, light.getId()); properties.put(MODEL_ID, modelId); DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID) .withProperties(properties).withBridge(bridgeUID).withLabel(light.getName()).build(); thingDiscovered(discoveryResult); } else { <START> logger.debug("discovered unsupported light of type '{}' with id {}", modelId, light.getId()); <END> } }</code><technical_language>this thingType id instead of modelId (modelId logged well, primary information imho type)</technical_language>

Target:
private void onLightAddedInternal(FullLight light) { ThingUID thingUID = getThingUID(light); ThingTypeUID thingTypeUID = getThingTypeUID(light); String modelId = light.getModelID().replaceAll(HueLightHandler.NORMALIZE_ID_REGEX, "_"); if (thingUID != null && thingTypeUID != null) { ThingUID bridgeUID = hueBridgeHandler.getThing().getUID(); Map<String, Object> properties = new HashMap<>(1); properties.put(LIGHT_ID, light.getId()); properties.put(MODEL_ID, modelId); DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID) .withProperties(properties).withBridge(bridgeUID).withLabel(light.getName()).build(); thingDiscovered(discoveryResult); } else { logger.debug("discovered unsupported light of type '{}' and model '{}' with id {}", light.getType(), modelId, light.getId()); } }
Source:
<code><START> protected CommandResult(boolean processed, @Nullable Integer successCount, @Nullable Integer affectedBlocks, @Nullable Integer affectedEntities, <END> @Nullable Integer affectedItems, @Nullable Integer queryResult, @Nullable Map<String, Object> resultInfo) { this.processed = processed; this.successCount = Optional.fromNullable(successCount); this.affectedBlocks = Optional.fromNullable(affectedBlocks); this.affectedEntities = Optional.fromNullable(affectedEntities); this.affectedItems = Optional.fromNullable(affectedItems); this.queryResult = Optional.fromNullable(queryResult); this.resultInfo = resultInfo != null ? Collections.unmodifiableMap(resultInfo) : Collections.<String, Object>emptyMap(); }</code><technical_language>This private package-local (no spec) this class marked final. want people instantiating builder</technical_language>

Target:
CommandResult(boolean processed, @Nullable Integer successCount, @Nullable Integer affectedBlocks, @Nullable Integer affectedEntities, @Nullable Integer affectedItems, @Nullable Integer queryResult, @Nullable Map<String, Object> resultInfo) { this.processed = processed; this.successCount = Optional.fromNullable(successCount); this.affectedBlocks = Optional.fromNullable(affectedBlocks); this.affectedEntities = Optional.fromNullable(affectedEntities); this.affectedItems = Optional.fromNullable(affectedItems); this.queryResult = Optional.fromNullable(queryResult); this.resultInfo = resultInfo != null ? Collections.unmodifiableMap(resultInfo) : Collections.<String, Object>emptyMap(); }
Source:
<code>private static String getHeaderValue(Header[] headers, String headerName) { if (headers != null) { <START> for (int i = 0; i < headers.length; i++) { <END> if (headerName.equals(headers[i].getName())) { return headers[i].getValue(); } } } return null; }</code><technical_language>enhanced for loop here: for (Header header : headers)</technical_language>

Target:
private static String getHeaderValue(Header[] headers, String headerName) { if (headers != null) { for (Header header : headers) { if (headerName.equals(header.getName())) { return header.getValue(); } } } return null; }
Source:
<code>public boolean newDue() { <START> return mCol.getDb().queryScalar("SELECT 1 FROM cards WHERE did IN " + _deckLimit() + " AND queue = " + Consts.QUEUE_TYPE_NEW + " LIMIT 1", new Object[] {_deckLimit()}) != 0; <END> }</code><technical_language>parameter wrong</technical_language>

Target:
public boolean newDue() { return mCol.getDb().queryScalar("SELECT 1 FROM cards WHERE did IN " + _deckLimit() + " AND queue = " + Consts.QUEUE_TYPE_NEW + " LIMIT 1") != 0; }
Source:
<code>public static final byte[] readFully(final File path, final int max) throws FileNotFoundException, IOException { final FileInputStream in = new FileInputStream(path); try { long sz = path.length(); if (sz > max) throw new IOException(MessageFormat.format( JGitText.get().fileIsTooLarge, path)); byte[] buf = new byte[(int) sz]; int valid = 0; for (;;) { if (buf.length == valid) { int nsz = Math.min(max, buf.length * 2); <START> if (nsz > max) <END> throw new IOException(MessageFormat.format( JGitText.get().fileIsTooLarge, path)); byte[] nb = new byte[nsz]; System.arraycopy(buf, 0, nb, 0, valid); buf = nb; } int n = in.read(buf, valid, buf.length - valid); if (n < 0) break; valid += n; } if (valid < buf.length) { byte[] nb = new byte[valid]; System.arraycopy(buf, 0, nb, 0, valid); buf = nb; } return buf; } finally { try { in.close(); } catch (IOException ignored) { } } }</code><technical_language>This true, Math.min() return max if nsz > maz. :-) I meant write: if (buf.length == valid) { if (buf.length == max) throw buf.length == valid grow buffer read more data file, grow buffer growing put buffer larger maximum size caller wants this method read return. is a small issue file fit EOF yet, if read more EOF. work checking for EOF throwing: if (buf.length == valid) { if (buf.length == max) { int next = in.read(); if (next < -1) break; throw ..</technical_language>

Target:
public static final byte[] readFully(final File path, final int max) throws FileNotFoundException, IOException { final FileInputStream in = new FileInputStream(path); try { long sz = path.length(); if (sz > max) throw new IOException(MessageFormat.format( JGitText.get().fileIsTooLarge, path)); byte[] buf = new byte[(int) sz]; int valid = 0; for (;;) { if (buf.length == valid) { if (buf.length == max) { int next = in.read(); if (next < 0) break; throw new IOException(MessageFormat.format( JGitText.get().fileIsTooLarge, path)); } byte[] nb = new byte[buf.length * 2]; System.arraycopy(buf, 0, nb, 0, valid); buf = nb; } int n = in.read(buf, valid, buf.length - valid); if (n < 0) break; valid += n; } if (valid < buf.length) { byte[] nb = new byte[valid]; System.arraycopy(buf, 0, nb, 0, valid); buf = nb; } return buf; } finally { try { in.close(); } catch (IOException ignored) { } } }
Source:
<code>public void shouldInjectOnlyAttributesWithSameType() throws Exception { Object result = mock(Result.class); when(request.getAttribute("result")).thenReturn(result); when(request.getParameter("result")).thenReturn("buggy"); ControllerMethod method = DefaultControllerMethod.instanceFor(OtherResource.class, OtherResource.class.getDeclaredMethod("logic", String.class)); List<Message> errors = new ArrayList<Message>(); Object[] out = provider.getParametersFor(method, errors); <START> assertThat(out[0], not(is(result))); <END> }</code><technical_language>is(not(result))</technical_language>

Target:
public void shouldInjectOnlyAttributesWithSameType() throws Exception { Result result = mock(Result.class); when(request.getAttribute("result")).thenReturn(result); when(request.getParameterMap()).thenReturn(singletonMap("result", new String[] { "buggy" })); ControllerMethod method = DefaultControllerMethod.instanceFor(OtherResource.class, OtherResource.class.getDeclaredMethod("logic", String.class)); List<Message> errors = new ArrayList<Message>(); Object[] out = provider.getParametersFor(method, errors); assertThat(out[0], is(not((Object) result))); assertThat(out[0], is((Object) "buggy")); }
Source:
<code>public void reloadConfig() { <START> new GetRequest(mContext, mUrl, GetRequest.URI_CONFIG, mApiKey, null, result -> { <END> Log.v(TAG, "onWebGuiAvailable: " + result); mConfig = new Gson().fromJson(result, Config.class); if (mConfig == null) { throw new RuntimeException("config is null: " + result); } tryIsAvailable(); }); }</code><technical_language>I tryIsAvailable in case of configSaved</technical_language>

Target:
public void reloadConfig() { new GetRequest(mContext, mUrl, GetRequest.URI_CONFIG, mApiKey, null, result -> { Log.v(TAG, "reloadConfig: " + result); mConfig = new Gson().fromJson(result, Config.class); if (mConfig == null) { throw new RuntimeException("config is null: " + result); } }); }
Source:
<code>public void destroy() { for (Component root: this.getRoots()) { <START> getDesktop().getWebApp().getConfiguration().invokeDestroy(root); <END> } super.destroy(); try { if (_ips != null) { final List<Interpreter> ips = new ArrayList<Interpreter>(_ips.values()); _ips.clear(); _ips = null; for (Interpreter ip : ips) { try { ip.destroy(); } catch (Throwable ex) { log.warn("Failed to destroy " + ip, ex); } } } } catch (Throwable ex) { log.warn("Failed to clean up interpreters of " + this, ex); } _desktop = null; _owner = null; _listeners = null; _resolvers = null; _mappers = null; _attrs.getAttributes().clear(); }</code><technical_language>1. aware of NPE of chaining getter 2. call afterComponentDetached(root, null);</technical_language>

Target:
public void destroy() { Configuration config = WebApps.getCurrent().getConfiguration(); for (Component root: this.getRoots()) { config.invokeCallback("destroy", root); } super.destroy(); try { if (_ips != null) { final List<Interpreter> ips = new ArrayList<Interpreter>(_ips.values()); _ips.clear(); _ips = null; for (Interpreter ip : ips) { try { ip.destroy(); } catch (Throwable ex) { log.warn("Failed to destroy " + ip, ex); } } } } catch (Throwable ex) { log.warn("Failed to clean up interpreters of " + this, ex); } _desktop = null; _owner = null; _listeners = null; _resolvers = null; _mappers = null; _attrs.getAttributes().clear(); }
Source:
<code>private void processPaymentDetailEnteredEvent(List<ChargeEventEntity> chargeEventEntities) { chargeEventEntities .stream() .filter(event -> TERMINAL_AUTHENTICATION_STATES.contains(event.getStatus())) <START> .filter(event -> isNotAuthSuccessEventOrAuthSuccessEventWithOut3DSEvent(chargeEventEntities, event)) <END> .map(PaymentDetailsEntered::from) .filter(event -> !emittedEventDao.hasBeenEmittedBefore(event)) .forEach(this::emitAndPersistEvent); }</code><technical_language>I 3 nested checks read a lot more call methods do. For example: java chargeEventEntities .stream() .filter(event -> isValidPaymentDetailsEnteredTransition(chargeEventEntities, event)) .map(PaymentDetailsEntered::from) .filter(event -> !emittedEventDao.hasBeenEmittedBefore(event)) .forEach(this::emitAndPersistEvent); more complex logic conveyed with: java private boolean isValidPaymentDetailsEnteredTransition(List<ChargeEventEntity> chargeEvents, ChargeEventEntity currentEvent) { return TERMINAL_AUTHENTICATION_STATES.contains(currentEvent.getStatus()) && isNotDuplicatePaymentDetailsEvent() && // ... }</technical_language>

Target:
private void processPaymentDetailEnteredEvent(List<ChargeEventEntity> chargeEventEntities) { chargeEventEntities .stream() .filter(event -> isValidPaymentDetailsEnteredTransition(chargeEventEntities, event)) .map(PaymentDetailsEntered::from) .filter(event -> !emittedEventDao.hasBeenEmittedBefore(event)) .forEach(this::emitAndPersistEvent); }
Source:
<code>private boolean determineIfUserIsAdminInHierarchy(int userCanvasId, int courseAccountId) { M_log.debug("determineIfUserIsAdminInHierarchy() call"); <START> String url = Utils.urlConstructor("/accounts/", String.valueOf(courseAccountId), <END> "/admins/?user_id[]=", String.valueOf(userCanvasId)); ApiResultWrapper arw = Utils.makeApiCall(new HttpGet(url)); String errMsg = String.format("check user %s is an admin in the course account %s had null response, with status %s, due to:%s" , userCanvasId, courseAccountId, arw.getStatus(), (arw.getApiResp().isEmpty()) ? arw.getMessage() : arw.getApiResp()); if (!Utils.didApiReturnedWithOutErrors(errMsg, arw)) { return false; } JSONArray subAccountAdminsJson = new JSONArray(arw.getApiResp()); if (subAccountAdminsJson.length() > 0) { return true; } int parentAccount = getParentAccount(courseAccountId); if (parentAccount == 0) { return false; } return determineIfUserIsAdminInHierarchy(userCanvasId, parentAccount); }</code><technical_language>Consider making constant strings in url construction constants. moving a new version of API easier setting new urls easier</technical_language>

Target:
private boolean determineIfUserIsAdminInHierarchy(int userCanvasId, int courseAccountId) { M_log.debug("determineIfUserIsAdminInHierarchy() call"); String url = Utils.urlConstructor(Utils.URL_CHUNK_ACCOUNTS, String.valueOf(courseAccountId), URL_CHUNK_ADMINS_USER_ID, String.valueOf(userCanvasId)); ApiResultWrapper arw = Utils.makeApiCall(new HttpGet(url)); String errMsg = String.format("check user %s is an admin in the course account %s had null response, with status %s, due to:%s" , userCanvasId, courseAccountId, arw.getStatus(), (arw.getApiResp().isEmpty()) ? arw.getMessage() : arw.getApiResp()); if (!Utils.didApiReturnedWithOutErrors(errMsg, arw)) { return false; } JSONArray subAccountAdminsJson = new JSONArray(arw.getApiResp()); if (subAccountAdminsJson.length() > 0) { return true; } int parentAccount = getParentAccount(courseAccountId); if (parentAccount == 0) { return false; } return determineIfUserIsAdminInHierarchy(userCanvasId, parentAccount); }
Source:
<code>private List<Cell> doGetCells(Mapper<?, ? extends Cell> mapper, Object actualSource) { if (mapper.getSource() == actualSource) { <START> return Collections.singletonList(mapper.getTarget()); <END> } List<Cell> result = null; for (Synchronizer sync : mapper.synchronizers()) { List<Cell> cells = getCells(sync, actualSource); if (cells != null && !cells.isEmpty()) { if (result == null) { result = new ArrayList<>(cells.size()); } result.addAll(cells); } } return result == null ? Collections.<Cell>emptyList() : result; }</code><technical_language>GWT needs explicit type parameter for successful compilation. Get back, please</technical_language>

Target:
private List<Cell> doGetCells(Mapper<?, ? extends Cell> mapper, Object actualSource) { if (mapper.getSource() == actualSource) { return Collections.<Cell>singletonList(mapper.getTarget()); } List<Cell> result = null; for (Synchronizer sync : mapper.synchronizers()) { List<Cell> cells = getCells(sync, actualSource); if (cells != null && !cells.isEmpty()) { if (result == null) { result = new ArrayList<>(cells.size()); } result.addAll(cells); } } return result == null ? Collections.<Cell>emptyList() : result; }
Source:
<code>@Override public void run(JsonNode jsonNode) { <START> assert false; <END> }</code><technical_language>Add markInitialized() assertion, in case of "-ea" is disabled ducktape hungs while waiting service</technical_language>

Target:
@Override public void run(JsonNode jsonNode) { assert false; markInitialized(); markFinished(); }
Source:
<code>public Object executeGeneric(final VirtualFrame frame) { SAbstractObject rcvr = (SAbstractObject) SArguments.rcvr(frame); SObjectWithClass outer; if (rcvr instanceof SObjectWithClass) { outer = (SObjectWithClass) rcvr; } else if (rcvr instanceof SBlock) { outer = (SObjectWithClass) ((SBlock) rcvr).getOuterSelf(); <START> } else { <END> throw new RuntimeException(rcvr + " cannot be the receiver when instantiating an object literal?"); } Object superclassAndMixins = superClassResolver.call(outer); SClass sClass = mixinDef.instantiateClass(outer, superclassAndMixins); sClass.setContext(frame.materialize()); Object[] args = {sClass}; return newMessage.doPreEvaluated(frame, args); }</code><technical_language>a node right thing? a node read outer, need duplicate logic here, is special</technical_language>

Target:
public Object executeGeneric(final VirtualFrame frame) { SObjectWithClass outer = (SObjectWithClass) outerRead.executeGeneric(frame); Object superclassAndMixins = superClassResolver.call(outer); SClass sClassObject = instantiation.execute(outer, superclassAndMixins, frame.materialize()); return newMessage.doPreEvaluated(frame, new Object[] {sClassObject}); }
Source:
<code>void testCreateVolumeFromSnapshotInAvailabilityZoneWithOptions() { Volume volume = client.createVolumeInAvailabilityZone(defaultZone, <START> CreateVolumeOptions.Builder.fromSnapshotId(snapshot.getId())); <END> assertNotNull(volume); Predicate<Volume> availabile = retry(new VolumeAvailable(client), 600, 10, SECONDS); assert availabile.apply(volume); Volume result = Iterables.getOnlyElement(client.describeVolumesInRegion(snapshot.getRegion(), volume.getId())); assertEquals(volume.getId(), result.getId()); assertEquals(volume.getSnapshotId(), snapshot.getId()); assertEquals(volume.getAvailabilityZone(), defaultZone); assertEquals(result.getStatus(), Volume.Status.AVAILABLE); client.deleteVolumeInRegion(snapshot.getRegion(), volume.getId()); }</code><technical_language>nit: cluttery, statik import mofo</technical_language>

Target:
void testCreateVolumeFromSnapshotInAvailabilityZoneWithOptions() { Volume volume = client.createVolumeInAvailabilityZone(defaultZone, fromSnapshotId(snapshot.getId())); assertNotNull(volume); Predicate<Volume> availabile = retry(new VolumeAvailable(client), 600, 10, SECONDS); assert availabile.apply(volume); Volume result = Iterables.getOnlyElement(client.describeVolumesInRegion(snapshot.getRegion(), volume.getId())); assertEquals(volume.getId(), result.getId()); assertEquals(volume.getSnapshotId(), snapshot.getId()); assertEquals(volume.getAvailabilityZone(), defaultZone); assertEquals(result.getStatus(), Volume.Status.AVAILABLE); client.deleteVolumeInRegion(snapshot.getRegion(), result.getId()); }
Source:
<code>private void runAllParagraphs(final NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook, final Message fromMessage) throws IOException { final String noteId = (String) fromMessage.get("noteId"); if (StringUtils.isBlank(noteId)) { return; } if (!hasParagraphRunnerPermission(conn, notebook, noteId, userAndRoles, fromMessage.principal, "run all paragraphs")) { return; } final Note note = notebook.getNote(noteId); final List<Map<String, Object>> paragraphs = gson.fromJson(String.valueOf(fromMessage.data.get("paragraphs")), new TypeToken<List<Map<String, Object>>>() {}.getType()); runAllStatusBroadcast(note, true); Thread runAllThread = new Thread(new Runnable() { @Override public void run() { for (Map<String, Object> raw : paragraphs) { String paragraphId = (String) raw.get("id"); if (paragraphId == null) { continue; } String text = (String) raw.get("paragraph"); String title = (String) raw.get("title"); Map<String, Object> params = (Map<String, Object>) raw.get("params"); Map<String, Object> config = (Map<String, Object>) raw.get("config"); Paragraph p = setParagraphUsingMessage(note, fromMessage, paragraphId, text, title, params, config); try { if (!persistAndExecuteSingleParagraph(conn, note, p, true)) { runAllStatusBroadcast(note, false); break; } } catch (Exception e) { <START> LOG.error("Error in runAllParagraphs(). Error: " + e.toString()); <END> runAllStatusBroadcast(note, false); } } runAllStatusBroadcast(note, false); } }); runAllThread.start(); }</code><technical_language>LOG.error("Error in runAllParagraphs()", e);</technical_language>

Target:
private void runAllParagraphs(final NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook, final Message fromMessage) throws IOException { final String noteId = (String) fromMessage.get("noteId"); if (StringUtils.isBlank(noteId)) { return; } if (!hasParagraphRunnerPermission(conn, notebook, noteId, userAndRoles, fromMessage.principal, "run all paragraphs")) { return; } final Note note = notebook.getNote(noteId); final List<Map<String, Object>> paragraphs = gson.fromJson(String.valueOf(fromMessage.data.get("paragraphs")), new TypeToken<List<Map<String, Object>>>() {}.getType()); runAllStatusBroadcast(note, true); Thread runAllThread = new Thread(new Runnable() { @Override public void run() { for (Map<String, Object> raw : paragraphs) { String paragraphId = (String) raw.get("id"); if (paragraphId == null) { continue; } String text = (String) raw.get("paragraph"); String title = (String) raw.get("title"); Map<String, Object> params = (Map<String, Object>) raw.get("params"); Map<String, Object> config = (Map<String, Object>) raw.get("config"); Paragraph p = setParagraphUsingMessage(note, fromMessage, paragraphId, text, title, params, config); try { if (p.isEnabled() && !persistAndExecuteSingleParagraph(conn, note, p, true)) { runAllStatusBroadcast(note, false); break; } } catch (Exception e) { LOG.error("Error in runAllParagraphs()", e); runAllStatusBroadcast(note, false); } } runAllStatusBroadcast(note, false); } }); runAllThread.start(); }
Source:
<code>private int calculateK(IntervalDouble delta, IntervalDouble epsilon, IntervalDouble beta) throws IntervalArithmeticException { IntervalDouble gamma = calculateGamma(epsilon, beta); <START> <END> int k = 1; IntervalDouble delta_k = arithmetic.createInterval(Double.MAX_VALUE); for (; !arithmetic.lessThan(delta_k, delta); ++k) { delta_k = calculateDelta(k, epsilon, beta, gamma); } return k; }</code><technical_language>Define caches pass argument</technical_language>

Target:
private int calculateK(IntervalDouble delta, IntervalDouble epsilon, IntervalDouble beta) throws IntervalArithmeticException { IntervalDouble gamma = calculateGamma(epsilon, beta); final int CACHE_SIZE = 1000; @SuppressWarnings({ "serial" }) LinkedHashMap<Integer, IntervalDouble> aCache = new LinkedHashMap<Integer, IntervalDouble>(CACHE_SIZE) { @Override protected boolean removeEldestEntry(Map.Entry<Integer, IntervalDouble> eldest) { return size() > CACHE_SIZE; } }; @SuppressWarnings({ "serial" }) LinkedHashMap<Integer, IntervalDouble> cCache = new LinkedHashMap<Integer, IntervalDouble>(CACHE_SIZE) { @Override protected boolean removeEldestEntry(Map.Entry<Integer, IntervalDouble> eldest) { return size() > CACHE_SIZE; } }; int k = 1; IntervalDouble delta_k = arithmetic.createInterval(Double.MAX_VALUE); for (; !arithmetic.lessThan(delta_k, delta); ++k) { delta_k = calculateDelta(k, epsilon, beta, gamma, aCache, cCache); } return k; }
Source:
<code>public Filter rewriteRequiredColumns(Map<String, String> columnRewrites) { if (columnRewrites.get(dimension) == null) { throw new IAE("Received a non-applicable rewrite: %s, filter's dimension: %s", columnRewrites, dimension); } return new InFilter( <START> columnRewrites.get(dimension), <END> values, longPredicateSupplier, floatPredicateSupplier, doublePredicateSupplier, extractionFn, filterTuning ); }</code><technical_language>nit: columnRewrites.get(dimension) cached a local variable above. for other filters</technical_language>

Target:
public Filter rewriteRequiredColumns(Map<String, String> columnRewrites) { String rewriteDimensionTo = columnRewrites.get(dimension); if (rewriteDimensionTo == null) { throw new IAE("Received a non-applicable rewrite: %s, filter's dimension: %s", columnRewrites, dimension); } return new InFilter( rewriteDimensionTo, values, longPredicateSupplier, floatPredicateSupplier, doublePredicateSupplier, extractionFn, filterTuning ); }
Source:
<code><START> public void testAssignVariable() throws MultipleDefinitionException, <END> MultipleAssignmentException, VariableNotDefinedException { Scope s = new Scope(); try { s.assignVariable(getIdentifier(), getTypeExpression()); fail("assigned to a variable that doesn't exist"); } catch (VariableNotDefinedException vnde) { } s.defineVariable(getIdentifier(), getTypeExpression()); try { s.assignVariable(getIdentifier(), getTypeExpression()); } catch (MultipleAssignmentException mae) { fail("MultipleAssignmentException thrown, but variable only assigned once"); } try { s.assignVariable(getIdentifier(), getTypeExpression()); fail("multiple assignment to a variable was allowed"); } catch (MultipleAssignmentException mae) { } }</code><technical_language>do atomic "test" method in this class. break this - testAssignVariable - testAssignVariableMultipleAssignment - testAssignVariableNotDefined note junit some built-in exception checkers <LINK_0></technical_language>

Target:
public void testAssignVariable() throws MultipleDefinitionException, VariableNotDefinedException, MultipleAssignmentException, VariableNotAssignedException { Scope s = new Scope(); s.defineVariable(getVariableIdentifier(), getTypeExpression()); s.assignVariable(getVariableIdentifier(), getValueExpression()); assertEquals(s.getVariableValue(getVariableIdentifier()), getValueExpression().evaluate()); }
Source:
<code>private void handlePotentialTimeout(Invocation invocation) { Object identifier = invocation.getIdentifier(); Invocation activeAsyncInvocation = activeAsyncInvocations.get(identifier); <START> if (activeAsyncInvocation.equals(invocation)) { <END> Invocation activeInvocation = activeIdentifiers.get(identifier); if (activeInvocation != null) { invocation.getInvocationHandler().handleTimeout(invocation.getMethod(), activeInvocation); } } }</code><technical_language>nope</technical_language>

Target:
private void handlePotentialTimeout(Invocation invocation) { Object identifier = invocation.getIdentifier(); Invocation activeAsyncInvocation = activeAsyncInvocations.get(identifier); if (activeAsyncInvocation == invocation) { Invocation activeInvocation = activeIdentifiers.get(identifier); if (activeInvocation != null) { invocation.getInvocationHandler().handleTimeout(invocation.getMethod(), activeInvocation); } } }
Source:
<code>protected void ExecuteVdsBrokerCommand() { boolean filteringLUNsEnabled = <START> getParameters().getcompatibility_version().compareTo(Version.v3_1) < 0; <END> XmlRpcStruct options = new XmlRpcStruct(); options.add(VdsProperties.includePartitioned, Boolean.toString(filteringLUNsEnabled)); int storageType = (int) getParameters().getStorageType().getValue(); _result = getBroker().getDeviceList(storageType, options); ProceedProxyReturnValue(); setReturnValue(ParseLUNList(_result.lunList)); }</code><technical_language>compatibility infrastructure configuration</technical_language>

Target:
protected void ExecuteVdsBrokerCommand() { boolean filteringLUNsEnabled = Config.<Boolean> GetValue(ConfigValues.FilteringLUNsEnabled, getParameters().getcompatibility_version().getValue()); XmlRpcStruct options = new XmlRpcStruct(); options.add(VdsProperties.includePartitioned, Boolean.toString(filteringLUNsEnabled)); int storageType = (int) getParameters().getStorageType().getValue(); _result = getBroker().getDeviceList(storageType, options); ProceedProxyReturnValue(); setReturnValue(ParseLUNList(_result.lunList)); }
Source:
<code>public void fluentInterface() { ModuleDeclaration moduleDeclaration = new CompilationUnit() .addModule("org.javacord.api") .addSingleMemberAnnotation(Generated.class, "generator") .addSingleMemberAnnotation(SuppressWarnings.class, "\"module\"") .addDirective("requires transitive java.desktop;") .addDirective("exports org.javacord.api.entity.channel;") .addDirective("exports org.javacord.api.entity.channel.internal to org.javacord.core;") .addDirective("uses org.javacord.api.util.internal.DelegateFactoryDelegate;"); assertEqualsNoEol("@Generated(generator) @SuppressWarnings(\"module\") \n" + "module org.javacord.api {\n" + " requires transitive java.desktop;\n" + " exports org.javacord.api.entity.channel;\n" + " exports org.javacord.api.entity.channel.internal to org.javacord.core;\n" + " uses org.javacord.api.util.internal.DelegateFactoryDelegate;\n" + "}\n", moduleDeclaration.toString()); <START> } <END></code><technical_language>mind replacing dummy names? sure, a good practice other projects code in tests. remove Generated, compiler complains Generated (neither old, new one) target modules</technical_language>

Target:
public void fluentInterface() { ModuleDeclaration moduleDeclaration = new CompilationUnit() .addModule("com.laamella.base") .addSingleMemberAnnotation(SuppressWarnings.class, "\"module\"") .addDirective("requires transitive java.desktop;") .addDirective("exports com.laamella.base.entity.channel;") .addDirective("exports com.laamella.base.entity.channel.internal to com.laamella.core;") .addDirective("uses com.laamella.base.util.internal.FactoryDelegate;"); moduleDeclaration.getModuleStmts() .addLast(new ModuleExportsStmt() .setName("foo.bar") .addModuleName("other.foo") .addModuleName("other.bar") ); moduleDeclaration .addDirective(new ModuleExportsStmt() .setName("foo.bar.x") .addModuleName("other.foo") .addModuleName("other.bar") ); assertEqualsNoEol("@SuppressWarnings(\"module\")\n" + "module com.laamella.base {\n" + " requires transitive java.desktop;\n" + " exports com.laamella.base.entity.channel;\n" + " exports com.laamella.base.entity.channel.internal to com.laamella.core;\n" + " uses com.laamella.base.util.internal.FactoryDelegate;\n" + " exports foo.bar to other.foo, other.bar;\n" + " exports foo.bar.x to other.foo, other.bar;\n" + "}\n", moduleDeclaration.toString()); }
Source:
<code>private void testGracePeriodAccessControlForStudents() { FeedbackSessionAttributes fs = typicalBundle.feedbackSessions.get("gracePeriodSession"); fs.setEndTime(TimeHelper.convertLocalDateTimeToInstant( <START> TimeHelperExtension.now(), TimeHelper.convertToZoneId(fs.getTimeZone()))); <END> typicalBundle.feedbackSessions.put("gracePeriodSession", fs); assertFalse(fs.isOpened()); assertTrue(fs.isInGracePeriod()); assertFalse(fs.isClosed()); FeedbackResponseAttributes fr = typicalBundle.feedbackResponses.get("response1GracePeriodFeedback"); String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, fs.getCourseId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fs.getFeedbackSessionName(), Const.ParamsNames.FEEDBACK_QUESTION_ID + "-1", fr.feedbackQuestionId, Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-1-0", fr.recipient, Const.ParamsNames.FEEDBACK_QUESTION_TYPE + "-1", fr.feedbackQuestionType.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_TEXT + "-1-0", fr.getResponseDetails().getAnswerString() }; verifyOnlyStudentsOfTheSameCourseCanAccess(submissionParams); }</code><technical_language>This logic long winded, a result of fact times in local time instead of UTC. fs.setEndTime(Instant.now()) sufficient here. Personally, I find TimeHelperExtension.now awkward, i.e. there. used, I feel of long-winded logic this</technical_language>

Target:
private void testGracePeriodAccessControlForStudents() { FeedbackSessionAttributes fs = typicalBundle.feedbackSessions.get("gracePeriodSession"); fs.setEndTime(Instant.now()); typicalBundle.feedbackSessions.put("gracePeriodSession", fs); assertFalse(fs.isOpened()); assertTrue(fs.isInGracePeriod()); assertFalse(fs.isClosed()); FeedbackResponseAttributes fr = typicalBundle.feedbackResponses.get("response1GracePeriodFeedback"); String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, fs.getCourseId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fs.getFeedbackSessionName(), Const.ParamsNames.FEEDBACK_QUESTION_ID + "-1", fr.feedbackQuestionId, Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-1-0", fr.recipient, Const.ParamsNames.FEEDBACK_QUESTION_TYPE + "-1", fr.feedbackQuestionType.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_TEXT + "-1-0", fr.getResponseDetails().getAnswerString() }; verifyOnlyStudentsOfTheSameCourseCanAccess(submissionParams); }
Source:
<code>protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception { seenMessages.incrementAndGet(); byte[] payload = msg.asBytes(); if (encryptionConfig != null) { try { payload = encrypt(payload); } catch (Exception e) { <START> log.error("Fail to encrypt message: ", e); <END> } } boolean sawKtTag = false; for (String tag : msg.getTags()) { if (tag.startsWith("kt:")) { sawKtTag = true; sendOrReportFailure(tag.substring(3), payload); } } if (!sawKtTag) { sendOrReportFailure(defaultTopic, payload); } if (propagate) { msg.retain(); ctx.fireChannelRead(msg); } }</code><technical_language>this print useful information, i guess print like, "Fail entry message: XXException@fjdsl"</technical_language>

Target:
protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception { seenMessages.incrementAndGet(); byte[] payload = msg.asBytes(); if (encryptionConfig != null) { try { payload = encrypt(payload); } catch (Exception e) { log.error("Fail to encrypt message: ", e.getMessage()); } } boolean sawKtTag = false; for (String tag : msg.getTags()) { if (tag.startsWith("kt:")) { sawKtTag = true; sendOrReportFailure(tag.substring(3), payload); } } if (!sawKtTag) { sendOrReportFailure(defaultTopic, payload); } if (propagate) { msg.retain(); ctx.fireChannelRead(msg); } }
Source:
<code>public ITmfStateValue popAttribute(long t, int attributeQuark) throws TimeRangeException, StateValueTypeException { ITmfStateValue previousSV = transState.getOngoingStateValue(attributeQuark); if (previousSV.isNull()) { return null; } if (previousSV.getType() != Type.INTEGER) { throw new StateValueTypeException(getSSID() + " Quark:" + attributeQuark + ", Type:" + previousSV.getType() + ", Expected:" + Type.INTEGER); } int stackDepth = previousSV.unboxInt(); if (stackDepth <= 0) { throw new StateValueTypeException(getSSID() + " Quark:" + attributeQuark + ", Stack depth:" + stackDepth); } <START> int subAttributeQuark = INVALID_ATTRIBUTE; <END> try { subAttributeQuark = getQuarkRelative(attributeQuark, String.valueOf(stackDepth)); } catch (AttributeNotFoundException e) { String message = " Stack attribute missing sub-attribute for depth:" + stackDepth; throw new IllegalStateException(getSSID() + " Quark:" + attributeQuark + message); } ITmfStateValue poppedValue = queryOngoingState(subAttributeQuark); ITmfStateValue nextSV; if (--stackDepth == 0) { nextSV = TmfStateValue.nullValue(); } else { nextSV = TmfStateValue.newValueInt(stackDepth); } modifyAttribute(t, nextSV, attributeQuark); removeAttribute(t, subAttributeQuark); return poppedValue; }</code><technical_language>want INVALID_ATTRIBUTE here. safer initialize variable all. compiler try successfully is of initializing variable</technical_language>

Target:
public ITmfStateValue popAttribute(long t, int attributeQuark) throws TimeRangeException, StateValueTypeException { ITmfStateValue previousSV = transState.getOngoingStateValue(attributeQuark); if (previousSV.isNull()) { return null; } if (previousSV.getType() != Type.INTEGER) { throw new StateValueTypeException(getSSID() + " Quark:" + attributeQuark + ", Type:" + previousSV.getType() + ", Expected:" + Type.INTEGER); } int stackDepth = previousSV.unboxInt(); if (stackDepth <= 0) { throw new StateValueTypeException(getSSID() + " Quark:" + attributeQuark + ", Stack depth:" + stackDepth); } int subAttributeQuark; try { subAttributeQuark = getQuarkRelative(attributeQuark, String.valueOf(stackDepth)); } catch (AttributeNotFoundException e) { String message = " Stack attribute missing sub-attribute for depth:" + stackDepth; throw new IllegalStateException(getSSID() + " Quark:" + attributeQuark + message); } ITmfStateValue poppedValue = queryOngoingState(subAttributeQuark); ITmfStateValue nextSV; if (--stackDepth == 0) { nextSV = TmfStateValue.nullValue(); } else { nextSV = TmfStateValue.newValueInt(stackDepth); } modifyAttribute(t, nextSV, attributeQuark); removeAttribute(t, subAttributeQuark); return poppedValue; }
Source:
<code>public void handleException(Exception cce, EventLoop el) { <START> logger.error("Exception in the event loop on the attachment {}", el, this, cce); <END> }</code><technical_language>Do want word "listener" instead of "attachment"</technical_language>

Target:
public void handleException(Exception cce, EventLoop el) { logger.error("Exception in the on the {}", el, this, cce); }
Source:
<code>public static String toResolvedType(String type, Importer<?> importer) { requireNonNull(type); requireNonNull(importer); if (Types.isPrimitive(type)) { return type; } String typeToUse; String strippedType = stripGenerics(stripArray(type)); StringBuilder builder = new StringBuilder(); if (isJavaLang(type)) { typeToUse = toSimpleName(strippedType); } else { Import imprt = importer.getImport(type); typeToUse = imprt != null ? imprt.getSimpleName() : strippedType; } builder.append(typeToUse); if (Types.isGeneric(type)) { StringJoiner genericJoiner = new StringJoiner(","); for (String genericPart : splitGenerics(type)) { genericJoiner.add(toResolvedType(genericPart, importer)); } String genericParts = genericJoiner.toString(); <START> genericParts = genericParts.replace("?extends", "? extends "); <END> genericParts = genericParts.replace("?super", "? super "); builder.append("<").append(genericParts).append(">"); } return builder.append(getArraySuffix(type)).toString(); }</code><technical_language>perform replace for loop splitGenerics returns expected output</technical_language>

Target:
public static String toResolvedType(String type, Importer<?> importer) { requireNonNull(type); requireNonNull(importer); if (Types.isPrimitive(type)) { return type; } String typeToUse; String strippedType = stripGenerics(stripArray(type)); StringBuilder builder = new StringBuilder(); if (isJavaLang(type)) { typeToUse = toSimpleName(strippedType); } else { Import imprt = importer.getImport(type); typeToUse = imprt != null ? imprt.getSimpleName() : strippedType; } builder.append(typeToUse); if (Types.isGeneric(type)) { StringJoiner genericJoiner = new StringJoiner(","); for (String genericPart : splitGenerics(type)) { String resolved = toResolvedType(genericPart, importer); resolved = resolved.replace("?extends", "? extends "); resolved = resolved.replace("?super", "? super "); genericJoiner.add(resolved); } builder.append("<").append(genericJoiner.toString()).append(">"); } return builder.append(getArraySuffix(type)).toString(); }
Source:
<code>public void tearDown() throws Exception { _engine.shutdown(); <START> _engine.awaitTermination(200, TimeUnit.MILLISECONDS); <END> _engine = null; _scheduler.shutdownNow(); _scheduler = null; _asyncExecutor.shutdownNow(); _asyncExecutor = null; _loggerFactory.reset(); _loggerFactory = null; }</code><technical_language>this 200 configurable</technical_language>

Target:
public void tearDown() throws Exception { _engine.shutdown(); _engine.awaitTermination(60, TimeUnit.SECONDS); _engine = null; _scheduler.shutdownNow(); _scheduler = null; _asyncExecutor.shutdownNow(); _asyncExecutor = null; _loggerFactory.reset(); _loggerFactory = null; }
Source:
<code>private void tryFlushQueue() { <START> manager.sendBulk(logQueue); <END> }</code><technical_language>want [BlockingQueue.drainTo](<LINK_0> in this call</technical_language>

Target:
private void tryFlushQueue() { List<String> logEvents = new ArrayList<>(); logQueue.drainTo(logEvents); manager.sendBulk(logEvents); }
Source:
<code>protected HttpClientConnection leaseConnection(Future<CPoolEntry> future, long timeout, TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException { final Optional<ScheduledFuture<?>> warnFuture; if (warnTimeMs > 0 && warnTimeMs < timeout) { final Runnable warnCommand = () -> lastBlockedAt = Instant.now(); warnFuture = Optional.of(scheduler.schedule(warnCommand, warnTimeMs, TimeUnit.MILLISECONDS)); } else { warnFuture = Optional.empty(); } final Instant start = Instant.now(); final HttpClientConnection result = super.leaseConnection(future, timeout, tunit); final Duration time = Duration.between(start, Instant.now()); if (future.isDone()) { knownRoutes.add(future.get().getRoute()); } warnFuture.ifPresent(f -> f.cancel(false)); Throwable t = null; if (LOG.isTraceEnabled()) { t = new Throwable(); t.fillInStackTrace(); allocationSites.put(result, t); } <START> if (time.toMillis() > warnTimeMs) { <END> LOG.warn("Checkout from pool \"{}\" took {}", clientName, time, t); } return result; }</code><technical_language>I this before, I warnTimeMs is initialized -1. In another check, do warnTimeMs > 0 &&; do too</technical_language>

Target:
protected HttpClientConnection leaseConnection(Future<CPoolEntry> future, long timeout, TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException { final Optional<ScheduledFuture<?>> warnFuture; if (warnTimeMs > 0 && warnTimeMs < timeout) { final Runnable warnCommand = () -> lastBlockedAt = Instant.now(); warnFuture = Optional.of(scheduler.schedule(warnCommand, warnTimeMs, TimeUnit.MILLISECONDS)); } else { warnFuture = Optional.empty(); } final Instant start = Instant.now(); final HttpClientConnection result = super.leaseConnection(future, timeout, tunit); final Duration time = Duration.between(start, Instant.now()); if (future.isDone()) { knownRoutes.add(future.get().getRoute()); } warnFuture.ifPresent(f -> f.cancel(false)); Throwable t = null; if (LOG.isTraceEnabled()) { t = new Throwable(); t.fillInStackTrace(); allocationSites.put(result, t); } if (warnTimeMs > 0 && time.toMillis() > warnTimeMs) { LOG.warn("Checkout from pool \"{}\" took {}", clientName, time, t); } return result; }