auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private long sendEligibleCalls(long now) { long pollTimeout = Long.MAX_VALUE; for (Iterator<Map.Entry<Node, List<Call>>> iter = callsToSend.entrySet().iterator(); iter.hasNext(); ) { Map.Entry<Node, List<Call>> entry = iter.next(); List<Call> calls = entry.getValue(); if (calls.isEmpty()) { iter.remove(); continue; } Node node = entry.getKey(); if (!client.ready(node, now)) { long nodeTimeout = client.pollDelayMs(node, now); pollTimeout = Math.min(pollTimeout, nodeTimeout); log.trace("Client is not ready to send to {}. Must delay ms", node, nodeTimeout); AuthenticationException authenticationException = client.authenticationException(node); <START> if (authenticationException != null) { <END> Call call = calls.remove(0); call.fail(now, authenticationException); } continue; } Call call = calls.remove(0); int timeoutMs = calcTimeoutMsRemainingAsInt(now, call.deadlineMs); AbstractRequest.Builder<?> requestBuilder; try { requestBuilder = call.createRequest(timeoutMs); } catch (Throwable throwable) { call.fail(now, new KafkaException(String.format( "Internal error sending %s to %s.", call.callName, node))); continue; } ClientRequest clientRequest = client.newClientRequest(node.idString(), requestBuilder, now, true); log.trace("Sending to {}. correlationId={}", requestBuilder, node, clientRequest.correlationId()); client.send(clientRequest, now); getOrCreateListValue(callsInFlight, node.idString()).add(call); correlationIdToCalls.put(clientRequest.correlationId(), call); } return pollTimeout; }</code><technical_language>Do tests for this</technical_language>

Target:
private long sendEligibleCalls(long now) { long pollTimeout = Long.MAX_VALUE; for (Iterator<Map.Entry<Node, List<Call>>> iter = callsToSend.entrySet().iterator(); iter.hasNext(); ) { Map.Entry<Node, List<Call>> entry = iter.next(); List<Call> calls = entry.getValue(); if (calls.isEmpty()) { iter.remove(); continue; } Node node = entry.getKey(); if (!client.ready(node, now)) { long nodeTimeout = client.pollDelayMs(node, now); pollTimeout = Math.min(pollTimeout, nodeTimeout); log.trace("Client is not ready to send to {}. Must delay ms", node, nodeTimeout); continue; } Call call = calls.remove(0); int timeoutMs = calcTimeoutMsRemainingAsInt(now, call.deadlineMs); AbstractRequest.Builder<?> requestBuilder; try { requestBuilder = call.createRequest(timeoutMs); } catch (Throwable throwable) { call.fail(now, new KafkaException(String.format( "Internal error sending %s to %s.", call.callName, node))); continue; } ClientRequest clientRequest = client.newClientRequest(node.idString(), requestBuilder, now, true); log.trace("Sending to {}. correlationId={}", requestBuilder, node, clientRequest.correlationId()); client.send(clientRequest, now); getOrCreateListValue(callsInFlight, node.idString()).add(call); correlationIdToCalls.put(clientRequest.correlationId(), call); } return pollTimeout; }
Source:
<code>private void checkAndMaybeComplete() { if (progressTracker.isDone()) { if (progressTracker.hasSucceeded()) { operationException.set(null); } operationCompleted = true; } if (operationCompleted) { Exception e = operationException.get(); if (operationResult == null && e == null) { e = new RouterException("Operation failed, but exception was not set", RouterErrorCode.UnexpectedInternalError); routerMetrics.operationFailureWithUnsetExceptionCount.inc(); } if (e != null) { boolean encrypted = operationResult != null && operationResult.getBlobResult != null && operationResult.getBlobResult.getBlobInfo() != null && operationResult.getBlobResult.getBlobInfo() .getBlobProperties() .isEncrypted(); operationResult = null; routerMetrics.onGetBlobError(e, options, encrypted); } long operationLatencyMs = time.milliseconds() - submissionTimeMs; <START> routerMetrics.getBlobInfoOperationLatencyMs.update(operationLatencyMs); <END> if (operationResult != null && operationResult.getBlobResult != null && operationResult.getBlobResult.getBlobInfo() != null && operationResult.getBlobResult.getBlobInfo() .getBlobProperties() .isEncrypted()) { routerMetrics.getEncryptedBlobInfoOperationLatencyMs.update(operationLatencyMs); } NonBlockingRouter.completeOperation(null, getOperationCallback, operationResult, e); } }</code><technical_language>if update main anyway, goal of separate encrypted encrypted metrics</technical_language>

Target:
private void checkAndMaybeComplete() { if (progressTracker.isDone()) { if (progressTracker.hasSucceeded()) { operationException.set(null); } operationCompleted = true; } if (operationCompleted) { Exception e = operationException.get(); if (operationResult == null && e == null) { e = new RouterException("Operation failed, but exception was not set", RouterErrorCode.UnexpectedInternalError); routerMetrics.operationFailureWithUnsetExceptionCount.inc(); } if (e != null) { operationResult = null; routerMetrics.onGetBlobError(e, options, blobId.isEncrypted()); } long operationLatencyMs = time.milliseconds() - submissionTimeMs; if (blobId.isEncrypted()) { routerMetrics.getEncryptedBlobInfoOperationLatencyMs.update(operationLatencyMs); } else { routerMetrics.getBlobInfoOperationLatencyMs.update(operationLatencyMs); } NonBlockingRouter.completeOperation(null, getOperationCallback, operationResult, e); } }
Source:
<code>protected IWorkingSet[][] splitSets() { IWorkingSet[] allSets = getWindow().getWorkbench().getWorkingSetManager().getWorkingSets(); Map<String, List<IWorkingSet>> map = new HashMap<>(); WorkingSetRegistry registry = WorkbenchPlugin.getDefault().getWorkingSetRegistry(); for (IWorkingSet allSet : allSets) { String setType = allSet.getId(); if (WorkbenchActivityHelper.filterItem(registry.getWorkingSetDescriptor(setType))) { continue; } List<IWorkingSet> setsOfType = map.get(setType); if (setsOfType == null) { setsOfType = new ArrayList<>(); map.put(setType, setsOfType); } setsOfType.add(allSet); } IWorkingSet[][] typedSets = new IWorkingSet[map.keySet().size()][]; int i = 0; for (String <START> string : <END> map.keySet()) { List<IWorkingSet> setsOfType = map.get(string); typedSets[i] = new IWorkingSet[setsOfType.size()]; setsOfType.toArray(typedSets[i++]); } return typedSets; }</code><technical_language>rename setType</technical_language>

Target:
protected IWorkingSet[][] splitSets() { IWorkingSet[] allSets = getWindow().getWorkbench().getWorkingSetManager().getWorkingSets(); Map<String, List<IWorkingSet>> map = new HashMap<>(); WorkingSetRegistry registry = WorkbenchPlugin.getDefault().getWorkingSetRegistry(); for (IWorkingSet allSet : allSets) { String setType = allSet.getId(); if (WorkbenchActivityHelper.filterItem(registry.getWorkingSetDescriptor(setType))) { continue; } List<IWorkingSet> setsOfType = map.get(setType); if (setsOfType == null) { setsOfType = new ArrayList<>(); map.put(setType, setsOfType); } setsOfType.add(allSet); } IWorkingSet[][] typedSets = new IWorkingSet[map.keySet().size()][]; int i = 0; for (String setType : map.keySet()) { List<IWorkingSet> setsOfType = map.get(setType); typedSets[i] = new IWorkingSet[setsOfType.size()]; setsOfType.toArray(typedSets[i++]); } return typedSets; }
Source:
<code>public DocumentModel toFields(DocumentModel inDoc, HashMap<String, String> inMapping, boolean inSave, CoreSession inSession) { run(); <START> HashMap<String, String> values = toHashMap(); <END> for (String inXPath : inMapping.keySet()) { String value = values.get(inMapping.get(inXPath)); inDoc.setPropertyValue(inXPath, value); } if (inSave) { inDoc = inSession.saveDocument(inDoc); } return inDoc; }</code><technical_language>Map<String, String></technical_language>

Target:
public DocumentModel toFields(DocumentModel inDoc, HashMap<String, String> inMapping, boolean inSave, CoreSession inSession) { run(); Map<String, String> values = toHashMap(); for (String inXPath : inMapping.keySet()) { String value = values.get(inMapping.get(inXPath)); inDoc.setPropertyValue(inXPath, value); } if (inSave) { inDoc = inSession.saveDocument(inDoc); } return inDoc; }
Source:
<code><START> public String getScript(@Nonnull Location l) { <END> String script = BlockStorage.getLocationInfo(l, "script"); return script != null ? script : DEFAULT_SCRIPT; }</code><technical_language>open sufficient parameter validation, @Nonnull is enforced internal method, need add a Validate call here</technical_language>

Target:
public String getScript(@Nonnull Location l) { Validate.notNull(l, "Location for android not specified"); String script = BlockStorage.getLocationInfo(l, "script"); return script != null ? script : DEFAULT_SCRIPT; }
Source:
<code>public Spec drain() { try { return new Spec.Simple( <START> new JdkRequest(UriBuilder.fromUri(this.home).build()) <END> .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML) .header(HttpHeaders.AUTHORIZATION, this.token) .method(Request.GET) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .xml() .xpath("/page/rule/drain/text()") .get(0) ); } catch (IOException ex) { throw new IllegalStateException(ex); } }</code><technical_language>need UriBuilder</technical_language>

Target:
public Spec drain() { try { return new Spec.Simple( new JdkRequest(this.home) .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML) .header(HttpHeaders.AUTHORIZATION, this.token) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .xml() .xpath("/page/rule/drain/text()") .get(0) ); } catch (IOException ex) { throw new IllegalStateException(ex); } }
Source:
<code>public LogReplicationRuntimeState processEvent(LogReplicationRuntimeEvent event) throws IllegalTransitionException { switch (event.getType()) { case REMOTE_LEADER_FOUND: ((NegotiatingState)fsm.getStates().get(LogReplicationRuntimeStateType.NEGOTIATING)).setLeaderEndpoint(event.getEndpoint()); return fsm.getStates().get(LogReplicationRuntimeStateType.NEGOTIATING); case ON_CONNECTION_DOWN: String endpointDown = event.getEndpoint(); fsm.updateDisconnectedEndpoints(endpointDown); if (fsm.getConnectedEndpoints().size() == 0) { return fsm.getStates().get(LogReplicationRuntimeStateType.WAITING_FOR_CONNECTIVITY); } return this; case REMOTE_LEADER_LOSS: <START> this.worker.submit(this::verifyLeadership); <END> return this; case REMOTE_LEADER_NOT_FOUND: return this; case ON_CONNECTION_UP: fsm.updateConnectedEndpoints(event.getEndpoint()); return this; case LOCAL_LEADER_LOSS: return fsm.getStates().get(LogReplicationRuntimeStateType.STOPPED); default: { log.warn("Unexpected communication event when in init state.", event.getType()); throw new IllegalTransitionException(event.getType(), getType()); } } }</code><technical_language>this.worker.submit(this::verifyLeadership); removed right? returning this? re-enter this state execute logic in onEntry.</technical_language>

Target:
public LogReplicationRuntimeState processEvent(LogReplicationRuntimeEvent event) throws IllegalTransitionException { switch (event.getType()) { case REMOTE_LEADER_FOUND: ((NegotiatingState)fsm.getStates().get(LogReplicationRuntimeStateType.NEGOTIATING)).setLeaderEndpoint(event.getEndpoint()); return fsm.getStates().get(LogReplicationRuntimeStateType.NEGOTIATING); case ON_CONNECTION_DOWN: String endpointDown = event.getEndpoint(); fsm.updateDisconnectedEndpoints(endpointDown); if (fsm.getConnectedEndpoints().size() == 0) { return fsm.getStates().get(LogReplicationRuntimeStateType.WAITING_FOR_CONNECTIVITY); } return this; case REMOTE_LEADER_LOSS: case REMOTE_LEADER_NOT_FOUND: return this; case ON_CONNECTION_UP: fsm.updateConnectedEndpoints(event.getEndpoint()); return this; case LOCAL_LEADER_LOSS: return fsm.getStates().get(LogReplicationRuntimeStateType.STOPPED); default: { log.warn("Unexpected communication event when in init state.", event.getType()); throw new IllegalTransitionException(event.getType(), getType()); } } }
Source:
<code>public List<Capability> getCapabilities() { <START> throw new UnsupportedOperationException("Must first be build"); <END> }</code><technical_language>This a breaking API change previous warning</technical_language>

Target:
public List<Capability> getCapabilities() { return new ArrayList<>(capabilities.values()); }
Source:
<code>private void showAlertMenu(final View alertView, final int alertPosition) { PopupMenu alertMenu = new PopupMenu(this, alertView); alertMenu.getMenuInflater().inflate(R.menu.menu_alerts, alertMenu.getMenu()); alertMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.menu_resolve: removeAlert(alertPosition); return true; case R.id.menu_acknowledge: <START> removeAlert(alertPosition); <END> return true; default: return false; } } }); alertMenu.show(); }</code><technical_language>odd - actions</technical_language>

Target:
private void showAlertMenu(final View alertView, final int alertPosition) { PopupMenu alertMenu = new PopupMenu(this, alertView); alertMenu.getMenuInflater().inflate(R.menu.menu_alerts, alertMenu.getMenu()); alertMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.menu_resolve: Timber.d("Alert %d was not deleted intentionally.", alertPosition); return true; case R.id.menu_acknowledge: Timber.d("Alert %d was not removed intentionally.", alertPosition); return true; default: return false; } } }); alertMenu.show(); }
Source:
<code>public void testIoException() throws Exception { <START> when(mockedMapper.readValue(any(String.class), eq(User.class))).thenThrow(IOException.class); <END> Assertions.assertThrows(RuntimeException.class, () -> { UsersDao.fromJson(mockedMapper, mapper.writeValueAsString(testUser)); }); }</code><technical_language>Thanks for adding eq() here, good catch</technical_language>

Target:
public void testIoException() throws Exception { when(mockedMapper.readValue(any(String.class), eq(User.class))).thenThrow(IOException.class); assertThrows(RuntimeException.class, () -> { UsersDao.fromJson(mockedMapper, mapper.writeValueAsString(testUser)); }); }
Source:
<code>public JsonObject json() throws IOException { final JsonObject obj = new JsonNode( this.storage.xml().nodes(this.xpath()).get(0) ).json(); JsonObjectBuilder builder = Json.createObjectBuilder() .add("id", this.num) .add( "url", String.format( "<LINK_0>", this.coords, this.num ) ) .add("commit_id", JsonValue.NULL) .add("event", obj.getString("event")) .add( "actor", Json.createObjectBuilder() .add("login", obj.getString("login")) .build() ) <START> .add("created_at", obj.getString("created_at")); <END> final String label = "label"; if (obj.containsKey(label)) { builder = builder.add( label, Json.createObjectBuilder() .add("name", obj.getString(label)) .build() ); } return builder.build(); }</code><technical_language>@cvrebert this string literal a variable. static package visible tests it</technical_language>

Target:
public JsonObject json() throws IOException { final JsonObject obj = new JsonNode( this.storage.xml().nodes(this.xpath()).get(0) ).json(); JsonObjectBuilder builder = Json.createObjectBuilder() .add("id", this.num) .add( "url", String.format( "<LINK_0>", this.coords, this.num ) ) .add("commit_id", JsonValue.NULL) .add(MkEvent.EVENT, obj.getString(MkEvent.EVENT)) .add( "actor", Json.createObjectBuilder() .add(MkEvent.LOGIN, obj.getString(MkEvent.LOGIN)) .build() ) .add(MkEvent.CREATED_AT, obj.getString(MkEvent.CREATED_AT)); final String label = "label"; if (obj.containsKey(label)) { builder = builder.add( label, Json.createObjectBuilder() .add("name", obj.getString(label)) .build() ); } return builder.build(); }
Source:
<code>private void usingIsEmpty() { <START> Optional<Object> op = Optional.emtpy(); <END> if (!op.isEmpty()) { op.get(); } }</code><technical_language>typo in name of invoked method, Optional.empty()</technical_language>

Target:
private void usingIsEmpty() { Optional<Object> op = Optional.empty(); if (!op.isEmpty()) { op.get(); } }
Source:
<code>public SSLHandshaker(SocketChannel sc, SSLEngine engine) { m_sc = sc; m_sslEngine = engine; SSLSession dummySession = engine.getSession(); <START> m_localClearData = ByteBuffer.allocate(dummySession.getApplicationBufferSize() + 50); <END> m_localEncData = ByteBuffer.allocate(dummySession.getPacketBufferSize()); m_netClearData = ByteBuffer.allocate(dummySession.getApplicationBufferSize() + 50); m_netEncData = ByteBuffer.allocate(dummySession.getPacketBufferSize()); dummySession.invalidate(); }</code><technical_language>wrap unwrap called simultaneously threads, if need pair of byte buffers</technical_language>

Target:
public SSLHandshaker(SocketChannel sc, SSLEngine engine) { m_sc = sc; m_sslEngine = engine; SSLSession dummySession = engine.getSession(); m_clear = ByteBuffer.allocate(dummySession.getApplicationBufferSize() + 50); m_encrypted = ByteBuffer.allocate(dummySession.getPacketBufferSize()); dummySession.invalidate(); }
Source:
<code>public void testChronologizeWithStartTimestampBeforeAndEndTimestampAfterAnyValuesChangeInKeyInRecord() { long record = Variables.register("record", client.create()); String key = Variables.register("key", TestData.getString()); int testSize = Variables.register("testSize", 5); Set<Object> initValues = Variables.register("initValues", Sets.newHashSet()); Timestamp startTimestamp = Variables.register("startTimestamp", Timestamp.now()); <START> for (int i = 0; i < 100000000; i++); <END> for (int i = 0; i < testSize; i++) { Object value = null; while (value == null || initValues.contains(value)) { value = TestData.getObject(); } initValues.add(value); client.add(key, value, record); } Timestamp endTimestamp = Variables.register("endTimestamp", Timestamp.now()); for (int i = 0; i < 100000000; i++); for (int i = 0; i < testSize; i++) { Object value = null; while (value == null || initValues.contains(value)) { value = TestData.getObject(); } initValues.add(value); client.add(key, value, record); } Map<Timestamp, Set<Object>> result = client.chronologize( key, record, startTimestamp, endTimestamp); Set<Object> lastResultSet = Iterables.getLast( result.values()); assertEquals(testSize, result.size()); assertEquals(testSize, lastResultSet.size()); }</code><technical_language>StandardActions.wait(int, TimeUnit) introduce a delay in tests</technical_language>

Target:
public void testChronologizeWithStartTimestampBeforeAndEndTimestampAfterAnyValuesChangeInKeyInRecord() { long record = Variables.register("record", client.create()); String key = Variables.register("key", TestData.getString()); int testSize = Variables.register("testSize", 5); Set<Object> initValues = Variables.register("initValues", Sets.newHashSet()); Timestamp startTimestamp = Variables.register("startTimestamp", Timestamp.now()); StandardActions.wait(200, TimeUnit.MILLISECONDS); for (int i = 0; i < testSize; i++) { Object value = null; while (value == null || initValues.contains(value)) { value = TestData.getObject(); } initValues.add(value); client.add(key, value, record); } Timestamp endTimestamp = Variables.register("endTimestamp", Timestamp.now()); StandardActions.wait(200, TimeUnit.MILLISECONDS); for (int i = 0; i < testSize; i++) { Object value = null; while (value == null || initValues.contains(value)) { value = TestData.getObject(); } initValues.add(value); client.add(key, value, record); } Map<Timestamp, Set<Object>> result = client.chronologize(key, record, startTimestamp, endTimestamp); Set<Object> lastResultSet = Iterables.getLast(result.values()); result = Variables.register("result", result); assertEquals(testSize, result.size()); assertEquals(testSize, lastResultSet.size()); }
Source:
<code>protected boolean migrateVm(VM vm, ExecutionContext parentContext) { boolean forceMigration = !getParameters().isInternal(); MigrateVmParameters parameters = new MigrateVmParameters(forceMigration, vm.getId()); <START> ArrayList<Guid> dedicatedList = new ArrayList<>(vm.getDedicatedVmForVdsList()); <END> if (dedicatedList != null && !dedicatedList.isEmpty()) { dedicatedList.remove(vm.getRunOnVds()); if (dedicatedList.isEmpty()) { setVm(vm); auditLogDirector.log(this, AuditLogType.VM_MIGRATION_NO_VDS_TO_MIGRATE_TO); return false; } parameters.setInitialHosts(dedicatedList); } parameters.setReason(MessageBundler.getMessage(AuditLogType.MIGRATION_REASON_HOST_IN_MAINTENANCE)); return runInternalAction(ActionType.MigrateVm, parameters, createMigrateVmContext(parentContext, vm)) .getSucceeded(); }</code><technical_language>a problem this line in code need decide handle for pinned/HP VMs: AFAIK scheduler/LB migrate a vm suitable destination host hosts in cluster (regardless hosts configured in 'Specific Host(s)' list). This works for HP/pinned vms assigned specific host in 'Specific Host(s)' list. (one specific - pinning configuration is allowed, more numa pinning is allowed). problem this line in code is MaintenanceVdsCommand acts differently search for migrate-able destination host hosts in 'Specific Host(s)' list in cluster. for pinned vms is host explain migration is switch maintenance fail. want handle that? 1. remove this dedicated list limitation for hp/pinned vms for vms - switch maintenance logic scheduler. 2. leave is assumption for cases of pinned/hp vms fail switch maintenance operation, regadless migration mode type</technical_language>

Target:
protected boolean migrateVm(VM vm, ExecutionContext parentContext) { boolean forceMigration = !getParameters().isInternal(); MigrateVmParameters parameters = new MigrateVmParameters(forceMigration, vm.getId()); parameters.setReason(MessageBundler.getMessage(AuditLogType.MIGRATION_REASON_HOST_IN_MAINTENANCE)); return runInternalAction(ActionType.MigrateVm, parameters, createMigrateVmContext(parentContext, vm)) .getSucceeded(); }
Source:
<code>public boolean isEs6OrHigher() { Preconditions.checkState(this != NO_TRANSPILE); <START> return this.toInteger() >= 6; <END> }</code><technical_language>return this.toInteger() == 6; toInteger returns > 6, I find >= a bit confusing (even more future-proof)</technical_language>

Target:
public boolean isEs6OrHigher() { Preconditions.checkState(this != NO_TRANSPILE); switch (this) { case ECMASCRIPT6: case ECMASCRIPT6_STRICT: case ECMASCRIPT6_TYPED: return true; default: return false; } }
Source:
<code>public static Optional<Path> getCurrentSavesDirectory() { final Optional<WorldServer> optWorldServer = getWorldByDimensionId(0); if (optWorldServer.isPresent()) { return Optional.of(optWorldServer.get().getSaveHandler().getWorldDirectory().toPath()); } else if (SpongeImpl.getGame().getState().ordinal() >= GameState.SERVER_ABOUT_TO_START.ordinal()) { <START> MinecraftServer server = SpongeImpl.getServer(); <END> return Optional.of(((MinecraftServerAccessor) server).accessor$getAnvilFile().toPath().resolve(server.getFolderName())); } return Optional.empty(); }</code><technical_language>Variable final</technical_language>

Target:
public static Optional<Path> getCurrentSavesDirectory() { final Optional<WorldServer> optWorldServer = getWorldByDimensionId(0); if (optWorldServer.isPresent()) { return Optional.of(optWorldServer.get().getSaveHandler().getWorldDirectory().toPath()); } else if (SpongeImpl.getGame().getState().ordinal() >= GameState.SERVER_ABOUT_TO_START.ordinal()) { final MinecraftServer server = SpongeImpl.getServer(); return Optional.of(((MinecraftServerAccessor) server).accessor$getAnvilFile().toPath().resolve(server.getFolderName())); } return Optional.empty(); }
Source:
<code>public StringType(StreamInput in) throws IOException { if (in.getVersion().onOrAfter(Version.V_4_2_0)) { if (in.readBoolean()) { <START> lengthLimit = Integer.MAX_VALUE; } else { lengthLimit = in.readInt(); <END> } } else { lengthLimit = Integer.MAX_VALUE; } }</code><technical_language>readInt /writeInt instead of vInt variants, write MAX_VALUE avoid boolean</technical_language>

Target:
public StringType(StreamInput in) throws IOException { if (in.getVersion().onOrAfter(Version.V_4_2_0)) { lengthLimit = in.readInt(); } else { lengthLimit = Integer.MAX_VALUE; } }
Source:
<code>private void initializeBuyClient() { Bundle bundle = getArguments(); String apiKey = bundle.getString(ProductDetailsConfig.EXTRA_SHOP_API_KEY); String appId = bundle.getString(ProductDetailsConfig.EXTRA_SHOP_APP_ID); String shopDomain = bundle.getString(ProductDetailsConfig.EXTRA_SHOP_DOMAIN); String applicationName = bundle.getString(ProductDetailsConfig.EXTRA_SHOP_APPLICATION_NAME); <START> productId = bundle.getLong(ProductDetailsConfig.EXTRA_SHOP_PRODUCT_ID, -1); <END> if (productId == -1) { productId = null; } if (bundle.containsKey(ProductDetailsConfig.EXTRA_SHOP_PRODUCT)) { product = Product.fromJson(bundle.getString(ProductDetailsConfig.EXTRA_SHOP_PRODUCT)); variant = product.getVariants().get(0); } if (bundle.containsKey(ProductDetailsConfig.EXTRA_SHOP_SHOP)) { shop = Shop.fromJson(bundle.getString(ProductDetailsConfig.EXTRA_SHOP_SHOP)); } final HttpLoggingInterceptor logging = new HttpLoggingInterceptor().setLevel(BuildConfig.OKHTTP_LOG_LEVEL); buyClient = new BuyClientBuilder() .shopDomain(shopDomain) .apiKey(apiKey) .appId(appId) .applicationName(applicationName) .interceptors(logging) .build(); }</code><technical_language>lets consistent location get collectionId</technical_language>

Target:
private void initializeBuyClient() { Bundle bundle = getArguments(); String apiKey = bundle.getString(ProductDetailsConfig.EXTRA_SHOP_API_KEY); String appId = bundle.getString(ProductDetailsConfig.EXTRA_SHOP_APP_ID); String shopDomain = bundle.getString(ProductDetailsConfig.EXTRA_SHOP_DOMAIN); String applicationName = bundle.getString(ProductDetailsConfig.EXTRA_SHOP_APPLICATION_NAME); if (bundle.containsKey(ProductDetailsConfig.EXTRA_SHOP_PRODUCT_ID)) { productId = bundle.getLong(ProductDetailsConfig.EXTRA_SHOP_PRODUCT_ID, -1); } if (bundle.containsKey(ProductDetailsConfig.EXTRA_SHOP_PRODUCT)) { product = Product.fromJson(bundle.getString(ProductDetailsConfig.EXTRA_SHOP_PRODUCT)); variant = product.getVariants().get(0); } if (bundle.containsKey(ProductDetailsConfig.EXTRA_SHOP_SHOP)) { shop = Shop.fromJson(bundle.getString(ProductDetailsConfig.EXTRA_SHOP_SHOP)); } final HttpLoggingInterceptor logging = new HttpLoggingInterceptor().setLevel(BuildConfig.OKHTTP_LOG_LEVEL); buyClient = new BuyClientBuilder() .shopDomain(shopDomain) .apiKey(apiKey) .appId(appId) .applicationName(applicationName) .interceptors(logging) .build(); }
Source:
<code>public void activateHoverHelp(final Control control) { control.addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseHover(MouseEvent event) { if ((event.stateMask & SWT.BUTTON_MASK) != 0) { return; } Point pt = new Point(event.x, event.y); Control timeGraphControl = (Control) event.widget; Point ptInDisplay = control.toDisplay(event.x, event.y); fInitialDeadzone = new Rectangle(ptInDisplay.x - MOUSE_DEADZONE, ptInDisplay.y - MOUSE_DEADZONE, 2 * MOUSE_DEADZONE, 2 * MOUSE_DEADZONE); createTooltipShell(timeGraphControl.getShell()); for (Control child : fTipComposite.getChildren()) { child.dispose(); } fill(control, event, pt); if (fTipComposite.getChildren().length == 0) { return; } fTipShell.pack(); Point tipPosition = control.toDisplay(pt); setHoverLocation(fTipShell, tipPosition); fTipShell.setVisible(true); <START> Display.getDefault().addFilter(SWT.MouseMove, fListener); <END> } }); }</code><technical_language>StickyHoverManager added a filter for SWT.FocusOut, I why, I figured out: If move out of tool tip another non-Eclipse application, tool tip close. worst, if click Alt-Tab another application front, tool tip remains 'always top' hides other application. Eclipse mouse move away</technical_language>

Target:
public void activateHoverHelp(final Control control) { control.addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseHover(MouseEvent event) { if ((event.stateMask & SWT.BUTTON_MASK) != 0) { return; } Point pt = new Point(event.x, event.y); Control timeGraphControl = (Control) event.widget; Point ptInDisplay = control.toDisplay(event.x, event.y); fInitialDeadzone = new Rectangle(ptInDisplay.x - MOUSE_DEADZONE, ptInDisplay.y - MOUSE_DEADZONE, 2 * MOUSE_DEADZONE, 2 * MOUSE_DEADZONE); createTooltipShell(timeGraphControl.getShell()); for (Control child : fTipComposite.getChildren()) { child.dispose(); } fill(control, event, pt); if (fTipComposite.getChildren().length == 0) { return; } fTipShell.pack(); Point tipPosition = control.toDisplay(pt); setHoverLocation(fTipShell, tipPosition); fTipShell.setVisible(true); Display display = Display.getDefault(); display.addFilter(SWT.MouseMove, fListener); display.addFilter(SWT.FocusOut, fListener); } }); }
Source:
<code>private void onLoginFailed(Throwable e) { logger.warn("Login failed", e); Platform.runLater(() -> { if (!(e instanceof CancellationException)) { <START> loginErrorLabel.setText(e.getCause().getLocalizedMessage().toString().replace(". ",".\n")); <END> loginErrorLabel.setVisible(true); } else { loginErrorLabel.setVisible(false); } setShowLoginProgress(false); }); }</code><technical_language>* Is formatter disabled commit? * getLocalizedMessage() is a String, toString() is redundant. * Replacing . .\n a hacky fix wrapping issues in UI done</technical_language>

Target:
private void onLoginFailed(Throwable e) { logger.warn("Login failed", e); Platform.runLater(() -> { if (!(e instanceof CancellationException)) { loginErrorLabel.setText(e.getCause().getLocalizedMessage()); loginErrorLabel.setVisible(true); } else { loginErrorLabel.setVisible(false); } setShowLoginProgress(false); }); }
Source:
<code>public void shouldNotAllowInvalidTopicNames() { final String invalidName = "not:valid"; final TopologyException e = assertThrows(TopologyException.class, () -> Materialized.as(invalidName)); <START> assert e.getMessage().equals("Invalid topology: Name \"" + invalidName + <END> "\" is illegal, it contains a character other than " + "ASCII alphanumerics, '.', '_' and '-'"); }</code><technical_language>Java assert statement proper unit testing asserts, ie, assertThat(e.getMessage(), equalTo("..."));</technical_language>

Target:
public void shouldNotAllowInvalidTopicNames() { final String invalidName = "not:valid"; final TopologyException e = assertThrows(TopologyException.class, () -> Materialized.as(invalidName)); assertEquals(e.getMessage(), "Invalid topology: Name \"" + invalidName + "\" is illegal, it contains a character other than " + "ASCII alphanumerics, '.', '_' and '-'"); }
Source:
<code>public void testCanParseTab() throws Exception { String sampleJson = "{\"field\":\"\tvalue\"}"; String sampleJson2 = "{\"\tfield\":{}}"; JSONTreeReader parser = new JSONTreeReader(new ByteArrayInputStream(sampleJson.getBytes("UTF-8"))); Token token = Token.Ignorable; int i = 0; try { while (token != null) { token = parser.next(); if (token == null) { break; } i++; if (i == 3) { Assert.assertEquals(Token.Value, token); <START> Assert.assertEquals("field", parser.getFieldName()); <END> } } } catch (Exception e) { Assert.fail(); } parser = new JSONTreeReader(new ByteArrayInputStream(sampleJson2.getBytes("UTF-8"))); token = Token.Ignorable; i = 0; try{ while(token != null){ token = parser.next(); if(token == null) { break; } i++; if(i == 3){ Assert.assertEquals(Token.StartEntity, token); Assert.assertEquals(parser.getFieldName(), "\tfield"); } } }catch(Exception e){ Assert.fail(); } }</code><technical_language>I tests for "\tvalue" original bug about</technical_language>

Target:
public void testCanParseTab() throws Exception { String sampleJson = "{\"\tfield\":\t\"\tvalue\"}"; JSONTreeReader parser = new JSONTreeReader(new ByteArrayInputStream(sampleJson.getBytes("UTF-8"))); Token token = Token.Ignorable; int i = 0; try { while (token != null) { token = parser.next(); if (token == null) { break; } i++; if (i == 3) { Assert.assertEquals(Token.Value, token); Assert.assertEquals("\tfield", parser.getFieldName()); Assert.assertEquals("\tvalue", parser.getFieldValue()); } } }catch(Exception e){ Assert.fail(); } }
Source:
<code>public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { switch (requestCode) { case CAMERA_AND_MEDIA_PERMISSION_REQUEST_CODE: if (permissions == null || permissions.length == 0) { AnalyticsTracker.track(AnalyticsTracker.Stat.ME_GRAVATAR_PERMISSIONS_INTERRUPTED); } else { for (int i = 0; i < grantResults.length; i++) { if (grantResults[i] == PackageManager.PERMISSION_DENIED) { ToastUtils.showToast(this.getActivity(), getString(R.string .gravatar_camera_and_media_permission_required), ToastUtils.Duration.LONG); Map<String, Object> properties = new HashMap<>(); properties.put("permission denied", permissions[i]); AnalyticsTracker.track(AnalyticsTracker.Stat.ME_GRAVATAR_PERMISSIONS_DENIED, properties); <START> return; <END> } } AnalyticsTracker.track(AnalyticsTracker.Stat.ME_GRAVATAR_PERMISSIONS_ACCEPTED); askForCameraOrGallery(); } break; } }</code><technical_language>this returns here, denied permission is tracked. Do want track permissions (WRITE_EXTERNAL_STORAGE CAMERA) denied</technical_language>

Target:
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { switch (requestCode) { case CAMERA_AND_MEDIA_PERMISSION_REQUEST_CODE: if (permissions.length == 0) { AnalyticsTracker.track(AnalyticsTracker.Stat.ME_GRAVATAR_PERMISSIONS_INTERRUPTED); } else { List<String> granted = new ArrayList<>(); List<String> denied = new ArrayList<>(); for (int i = 0; i < grantResults.length; i++) { if (grantResults[i] == PackageManager.PERMISSION_GRANTED) { granted.add(permissions[i]); } else { denied.add(permissions[i]); } } if (denied.size() == 0) { AnalyticsTracker.track(AnalyticsTracker.Stat.ME_GRAVATAR_PERMISSIONS_ACCEPTED); askForCameraOrGallery(); } else { ToastUtils.showToast(this.getActivity(), getString(R.string .gravatar_camera_and_media_permission_required), ToastUtils.Duration.LONG); Map<String, Object> properties = new HashMap<>(); properties.put("permissions granted", granted.size() == 0 ? "[none]" : TextUtils .join(",", granted)); properties.put("permissions denied", TextUtils.join(",", denied)); AnalyticsTracker.track(AnalyticsTracker.Stat.ME_GRAVATAR_PERMISSIONS_DENIED, properties); } } break; } }
Source:
<code>public void loadFromIntent(Intent intent) { if (intent.hasExtra(KEY_FORM_RECORD_DESTINATION)) { this.mFormRecordDestination = intent.getStringExtra(KEY_FORM_RECORD_DESTINATION); } else { <START> throw new RuntimeException("Access outside scoped storage in loading current form."); <END> } }</code><technical_language>wordings of this sense code access scope storage deleted. more lines of "Invalid Intent definition, extra name 'KEY_FORM_RECORD_DESTINATION present in intent"</technical_language>

Target:
public void loadFromIntent(Intent intent) { if (intent.hasExtra(KEY_FORM_RECORD_DESTINATION)) { this.mFormRecordDestination = intent.getStringExtra(KEY_FORM_RECORD_DESTINATION); } else { throw new RuntimeException("Invalid intent definition, no extra key instancedestination present in the intent."); } }
Source:
<code>protected void createAndGetPDF(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { TempFile tempFile = null; String spec = null; try { httpServletRequest.setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } if (httpServletRequest.getMethod() == "POST") { try { purgeOldTemporaryFiles(); spec = getSpecFromPostBody(httpServletRequest); <START> tempFile = doCreatePDFFile(spec, httpServletRequest); <END> if (tempFile == null) { error(httpServletResponse, "Missing 'spec' parameter", 500); return; } } catch (Throwable e) { deleteFile(tempFile); error(httpServletResponse, e); return; } } else { spec = httpServletRequest.getParameter("spec"); } if (spec == null) { error(httpServletResponse, "Missing 'spec' parameter", 500); return; } try { tempFile = doCreatePDFFile(spec, httpServletRequest); sendPdfFile(httpServletResponse, tempFile, Boolean.parseBoolean(httpServletRequest.getParameter("inline"))); } catch (Throwable e) { error(httpServletResponse, e); } finally { deleteFile(tempFile); } }</code><technical_language>doCreatePDFFile get called twice? (line 162)</technical_language>

Target:
protected void createAndGetPDF(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { TempFile tempFile = null; String spec = null; try { httpServletRequest.setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } if (httpServletRequest.getMethod() == "POST") { try { spec = getSpecFromPostBody(httpServletRequest); } catch (IOException e) { error(httpServletResponse, "Missing 'spec' in request body", 500); return; } } else { spec = httpServletRequest.getParameter("spec"); } if (spec == null) { error(httpServletResponse, "Missing 'spec' parameter", 500); return; } try { tempFile = doCreatePDFFile(spec, httpServletRequest); sendPdfFile(httpServletResponse, tempFile, Boolean.parseBoolean(httpServletRequest.getParameter("inline"))); } catch (Throwable e) { error(httpServletResponse, e); } finally { deleteFile(tempFile); } }
Source:
<code>private void checkIfPartOfBuilding(Vector3f blockPos, EntityRef player) { HoldingComponent holdingComponent = player.getComponent(HoldingComponent.class); List<EntityRef> buildings = holdingComponent.constructedBuildings; for (EntityRef building : buildings) { ConstructedBuildingComponent buildingComponent = building.getComponent(ConstructedBuildingComponent.class); List<BlockRegion> buildingRegions = buildingComponent.boundingRegions; for (BlockRegion buildingRegion : buildingRegions) { <START> Vector3i target = new Vector3i(blockPos, RoundingMode.FLOOR); <END> if (buildingRegion.contains(target)) { this.buildingToUpgrade = building; holdingComponent.lastBuildingInteractedWith = building; player.saveComponent(holdingComponent); building.send(new OpenUpgradeScreenEvent()); } } } }</code><technical_language>move this out of for loop</technical_language>

Target:
private void checkIfPartOfBuilding(Vector3f blockPos, EntityRef player) { HoldingComponent holdingComponent = player.getComponent(HoldingComponent.class); List<EntityRef> buildings = holdingComponent.constructedBuildings; for (EntityRef building : buildings) { ConstructedBuildingComponent buildingComponent = building.getComponent(ConstructedBuildingComponent.class); List<BlockRegion> buildingRegions = buildingComponent.boundingRegions; final Vector3i target = new Vector3i(blockPos, RoundingMode.FLOOR); for (BlockRegion buildingRegion : buildingRegions) { if (buildingRegion.contains(target)) { this.buildingToUpgrade = building; holdingComponent.lastBuildingInteractedWith = building; player.saveComponent(holdingComponent); building.send(new OpenUpgradeScreenEvent()); } } } }
Source:
<code>public void usedExternalIdThrows() { mockHealthCodeAndAccountRetrieval(); STUDY.setExternalIdValidationEnabled(true); ExternalIdentifier identifier = ExternalIdentifier.create(STUDY.getStudyIdentifier(), EXTERNAL_ID); identifier.setHealthCode("AAA"); when(externalIdService.getExternalId(STUDY.getStudyIdentifier(), EXTERNAL_ID, false)).thenReturn(identifier); <START> <END> doThrow(new EntityAlreadyExistsException(Account.class, (String) null, (Map<String, Object>) null)) .when(accountDao).createAccount(any(), any(), any()); try { participantService.createParticipant(STUDY, PARTICIPANT, false); fail("Should have thrown exception"); } catch(EntityAlreadyExistsException e) { verify(accountWorkflowService, never()).sendEmailVerificationToken(any(), any(), any()); } }</code><technical_language>verify commitAssign() is called</technical_language>

Target:
public void usedExternalIdThrows() { mockHealthCodeAndAccountRetrieval(); STUDY.setExternalIdValidationEnabled(true); ExternalIdentifier identifier = ExternalIdentifier.create(STUDY.getStudyIdentifier(), EXTERNAL_ID); identifier.setHealthCode("AAA"); when(externalIdService.getExternalId(STUDY.getStudyIdentifier(), EXTERNAL_ID, false)).thenReturn(identifier); doThrow(new EntityAlreadyExistsException(Account.class, (String) null, (Map<String, Object>) null)) .when(accountDao).createAccount(any(), any(), any()); try { participantService.createParticipant(STUDY, PARTICIPANT, false); fail("Should have thrown exception"); } catch(EntityAlreadyExistsException e) { verify(accountDao, never()).createAccount(any(), any(), any()); verify(externalIdService, never()).commitAssignExternalId(any()); verify(accountWorkflowService, never()).sendEmailVerificationToken(any(), any(), any()); } }
Source:
<code>public BlobItem(BlobItemInternal blobItemInternal) { this.name = blobItemInternal.getName(); this.deleted = blobItemInternal.isDeleted(); this.snapshot = blobItemInternal.getSnapshot(); this.properties = blobItemInternal.getProperties(); this.metadata = blobItemInternal.getMetadata(); this.versionId = blobItemInternal.getVersionId(); this.isCurrentVersion = blobItemInternal.isCurrentVersion(); this.isPrefix = blobItemInternal.isPrefix(); <START> this.tags = new HashMap<>(); <END> if (blobItemInternal.getBlobTags() != null && blobItemInternal.getBlobTags().getBlobTagSet() != null) { for (BlobTag tag : blobItemInternal.getBlobTags().getBlobTagSet()) { this.tags.put(tag.getKey(), tag.getValue()); } } }</code><technical_language>do tags get populated in swagger? Is similar metadata? completely different. do need do this set thing</technical_language>

Target:
public BlobItem(BlobItemInternal blobItemInternal) { this.name = blobItemInternal.getName(); this.deleted = blobItemInternal.isDeleted(); this.snapshot = blobItemInternal.getSnapshot(); this.properties = new BlobItemProperties(blobItemInternal.getProperties()); this.metadata = blobItemInternal.getMetadata(); this.versionId = blobItemInternal.getVersionId(); this.isCurrentVersion = blobItemInternal.isCurrentVersion(); this.isPrefix = blobItemInternal.isPrefix(); this.tags = new HashMap<>(); if (blobItemInternal.getBlobTags() != null && blobItemInternal.getBlobTags().getBlobTagSet() != null) { for (BlobTag tag : blobItemInternal.getBlobTags().getBlobTagSet()) { this.tags.put(tag.getKey(), tag.getValue()); } } }
Source:
<code>public synchronized void transferMemory(LocalMemoryContext to) { checkArgument(to instanceof SimpleLocalMemoryContext, "to must be an instance of SimpleLocalMemoryContext"); checkState(!closed, "SimpleLocalMemoryContext is already closed"); SimpleLocalMemoryContext target = (SimpleLocalMemoryContext) to; AggregatedMemoryContext parent = parentMemoryContext; while (parent != null && parent != target.parentMemoryContext) { <START> synchronized (parent) { <END> parent.usedBytes -= usedBytes; } parent = parent.parentMemoryContext; } checkState(parent != null, "memory context state is corrupt"); synchronized (target) { target.usedBytes = AggregatedMemoryContext.addExact(target.usedBytes, usedBytes); } usedBytes = 0; }</code><technical_language>parent handle synchronization of field</technical_language>

Target:
public synchronized void transferMemory(LocalMemoryContext to) { checkArgument(to instanceof SimpleLocalMemoryContext, "to must be an instance of SimpleLocalMemoryContext"); checkState(!closed, "already closed"); SimpleLocalMemoryContext target = (SimpleLocalMemoryContext) to; checkMemoryContextState(target); AggregatedMemoryContext parent = parentMemoryContext; while (parent != null && parent != target.parentMemoryContext) { parent.addBytes(-usedBytes); parent = parent.getParent(); } target.addBytes(usedBytes); usedBytes = 0; }
Source:
<code>public void testAbsolute() { DatasetRepository repo = DatasetRepositories.open("repo:file:/tmp/data"); repo.delete("test"); repo.create("test", descriptor); <START> Dataset<Object> ds = Datasets.load("dataset:file:/tmp/data/test", Object.class); <END> Assert.assertNotNull("Should load dataset", ds); Assert.assertTrue(ds instanceof FileSystemDataset); Assert.assertEquals("Locations should match", URI.create("file:/tmp/data/test"), ds.getDescriptor().getLocation()); Assert.assertEquals("Descriptors should match", repo.load("test").getDescriptor(), ds.getDescriptor()); repo.delete("test"); }</code><technical_language>test GenericData.Record some of fail for parquet datasets support reflect</technical_language>

Target:
public void testAbsolute() { DatasetRepository repo = DatasetRepositories.open("repo:file:/tmp/data"); repo.delete("test"); repo.create("test", descriptor); Dataset<Record> ds = Datasets.<Record, Dataset<Record>> load("dataset:file:/tmp/data/test", Record.class); Assert.assertNotNull("Should load dataset", ds); Assert.assertTrue(ds instanceof FileSystemDataset); Assert.assertEquals("Locations should match", URI.create("file:/tmp/data/test"), ds.getDescriptor().getLocation()); Assert.assertEquals("Descriptors should match", repo.load("test").getDescriptor(), ds.getDescriptor()); repo.delete("test"); }
Source:
<code>public CompletionTime processOneToOne(String tenantId, CompletionTimeProcessing completionTimeProcessing) throws RetryAttemptException{ if (completionTimeProcessing.getNumberOfRetries() < 1) { completionTimeProcessing.setNumberOfRetries(completionTimeProcessing.getNumberOfRetries() + 1); return null; <START> } <END> Span rootSpan = completionTimeProcessing.getRootSpan(); List<Span> trace = spanCache.getTrace(tenantId, rootSpan.getTraceId()); Annotation lastAnnotation = extractLastAnnotation(trace); CompletionTime completionTime = CompletionTimeUtil.spanToCompletionTime(rootSpan); if (lastAnnotation != null) { completionTime.setDuration(getTraceDuration(rootSpan, lastAnnotation.getTimestamp())); } completionTime.setProperties(extractProperties(trace)); log.debugf("SpanTraceCompletionTimeDeriver completionTime[%s]", completionTime); return completionTime; }</code><technical_language>Issue this approach is wait a fixed interval receiving span for a trace, derive completion time for trace. obtain spans for a trace, identify 'end time' (i.e. timestamp+duration), leave a specific interval. If spans received for trace interval, derive completion time. This - if a trace (especially async) lives a long time, completion time prematurely created, instead wait a interval span received</technical_language>

Target:
public CompletionTime processOneToOne(String tenantId, CompletionTimeProcessing completionTimeProcessing) throws RetryAttemptException { if (completionTimeProcessing.getCompletionTime() == null) { return null; } log.debugf("SpanTraceCompletionTimeDeriver completionTime[%s]", completionTimeProcessing.getCompletionTime()); return completionTimeProcessing.getCompletionTime(); }