auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<ElementT> decode( @Nullable ByteBuffer bytes, @NonNull ProtocolVersion protocolVersion) { if (bytes == null || bytes.remaining() == 0) { return new ArrayList<>(0); } else { ByteBuffer input = bytes.duplicate(); int size = input.getInt(); List<ElementT> result = new ArrayList<>(size); for (int i = 0; i < size; i++) { ElementT element; int elementSize = input.getInt(); if (elementSize < 0) { element = null; } else { ByteBuffer encodedElement = input.slice(); encodedElement.limit(elementSize); <START> input.position(input.position() + elementSize); <END> element = elementCodec.decode(encodedElement, protocolVersion); } result.add(element); } return result; } }</code><technical_language>Nit: a bit easier understand this code if invert lines: element = elementCodec.decode(encodedElement, protocolVersion); input.position(input.position() + elementSize); (I initially thought updating position of input required element decoded.)</technical_language>

Target:
public List<ElementT> decode( @Nullable ByteBuffer bytes, @NonNull ProtocolVersion protocolVersion) { if (bytes == null || bytes.remaining() == 0) { return new ArrayList<>(0); } else { ByteBuffer input = bytes.duplicate(); int size = input.getInt(); List<ElementT> result = new ArrayList<>(size); for (int i = 0; i < size; i++) { ElementT element; int elementSize = input.getInt(); if (elementSize < 0) { element = null; } else { ByteBuffer encodedElement = input.slice(); encodedElement.limit(elementSize); element = elementCodec.decode(encodedElement, protocolVersion); input.position(input.position() + elementSize); } result.add(element); } return result; } }
Source:
<code><START> public boolean canPlaceAt(GlowPlayer player, GlowBlock block, BlockFace against) { <END> return canPlaceAt(block, against); }</code><technical_language>Redundant player arg</technical_language>

Target:
public boolean canPlaceAt(GlowPlayer player, GlowBlock block, BlockFace against) { return true; }
Source:
<code>public synchronized Headers takeHeaders() throws IOException { readTimeout.enter(); try { while (headersQueue.isEmpty() && errorCode == null) { waitForIo(); } } finally { readTimeout.exitAndThrowIfTimedOut(); } if (!headersQueue.isEmpty()) { return headersQueue.removeFirst(); } if (errorException == null) throw new StreamResetException(errorCode); <START> throw errorException; <END> }</code><technical_language>nit: consider making this other occurrences more concise: throw errorException != null ? errorException : new StreamResetException(errorCode);</technical_language>

Target:
public synchronized Headers takeHeaders() throws IOException { readTimeout.enter(); try { while (headersQueue.isEmpty() && errorCode == null) { waitForIo(); } } finally { readTimeout.exitAndThrowIfTimedOut(); } if (!headersQueue.isEmpty()) { return headersQueue.removeFirst(); } throw errorException != null ? errorException : new StreamResetException(errorCode); }
Source:
<code>public void isDiscontinued_shouldReturnTrueIfTheOrderIsScheduledForTheFutureAndActivatedOnCheckDateButTheCheckDateIsAfterDateStopped() throws Exception { Order order = new Order(); order.setUrgency(Urgency.ON_SCHEDULED_DATE); <START> Date scheduledDateInFuture = DateUtils.addMonths(new Date(), 2); <END> order.setScheduledDate(scheduledDateInFuture); Date activationDate = DateUtils.addDays(new Date(), -2); order.setDateActivated(activationDate); Date stopDate = new Date(); OrderUtilTest.setDateStopped(order, stopDate); assertNotNull(order.getDateActivated()); assertNotNull(order.getDateStopped()); assertNull(order.getAutoExpireDate()); assertTrue(order.isDiscontinued(DateUtils.addSeconds(stopDate, 1))); }</code><technical_language>add a local variable assign new Date() it? re-use instead of creating multiple instances</technical_language>

Target:
public void isDiscontinued_shouldReturnTrueIfTheOrderIsScheduledForTheFutureAndActivatedOnCheckDateButTheCheckDateIsAfterDateStopped() throws Exception { Order order = new Order(); order.setUrgency(Urgency.ON_SCHEDULED_DATE); Date today = new Date(); Date scheduledDateInFuture = DateUtils.addMonths(today, 2); order.setScheduledDate(scheduledDateInFuture); Date activationDate = DateUtils.addDays(today, -2); order.setDateActivated(activationDate); Date stopDate = new Date(); OrderUtilTest.setDateStopped(order, stopDate); assertNotNull(order.getDateActivated()); assertNotNull(order.getDateStopped()); assertNull(order.getAutoExpireDate()); assertTrue(order.isDiscontinued(DateUtils.addSeconds(stopDate, 1))); }
Source:
<code>public static ArrayExpressionIn any(@NonNull VariableExpression variable) { <START> if(variable == null) { <END> throw new IllegalArgumentException("variable is null"); } return new ArrayExpressionIn(QuantifiesType.ANY, variable); }</code><technical_language>Please place a space b/t if (. if (variable == null) Please check others well</technical_language>

Target:
public static ArrayExpressionIn any(@NonNull VariableExpression variable) { if (variable == null) { throw new IllegalArgumentException("variable is null."); } return new ArrayExpressionIn(QuantifiesType.ANY, variable); }
Source:
<code>public int hashCode() { int result = factType.hashCode(); <START> result = 31 * result + name.hashCode(); <END> return result; }</code><technical_language>scared stupid result = ~~result in hashCode implementations.. if happy.. then.... scratching head _if_ JIRAs start rolling in V&V crazy a while.</technical_language>

Target:
public int hashCode() { int result = ~~factType.hashCode(); result = 31 * result + ~~name.hashCode(); return ~~result; }
Source:
<code>public void commitEmptyCommits() throws Exception { <START> Git git = new Git(db); <END> writeTrashFile("file1", "file1"); git.add().addFilepattern("file1").call(); RevCommit initial = git.commit().setMessage("initial commit").call(); RevCommit emptyFollowUp = git.commit() .setAuthor("New Author", "newauthor@example.org") .setMessage("no change").call(); assertNotEquals(initial.getId(), emptyFollowUp.getId()); assertEquals(initial.getTree().getId(), emptyFollowUp.getTree().getId()); try { git.commit().setAuthor("New Author", "newauthor@example.org") .setMessage("again no change").setAllowEmpty(false) .call(); fail("Didn't got the expected EmtpyCommitException"); } catch (EmtpyCommitException e) { } }</code><technical_language>try-with-resource avoid warning</technical_language>

Target:
public void commitEmptyCommits() throws Exception { try (Git git = new Git(db)) { writeTrashFile("file1", "file1"); git.add().addFilepattern("file1").call(); RevCommit initial = git.commit().setMessage("initial commit") .call(); RevCommit emptyFollowUp = git.commit() .setAuthor("New Author", "newauthor@example.org") .setMessage("no change").call(); assertNotEquals(initial.getId(), emptyFollowUp.getId()); assertEquals(initial.getTree().getId(), emptyFollowUp.getTree().getId()); try { git.commit().setAuthor("New Author", "newauthor@example.org") .setMessage("again no change").setAllowEmpty(false) .call(); fail("Didn't get the expected EmtpyCommitException"); } catch (EmtpyCommitException e) { } } }
Source:
<code>private void checkAndMaybeComplete() { if (operationTracker.isDone()) { if (operationTracker.hasSucceeded()) { operationException.set(null); } operationCompleted = true; } if (operationCompleted) { Exception e = operationException.get(); if (operationResult == null && e == null) { <START> e = new RouterException("Operation failed, but exception was not set", RouterErrorCode.UnexpectedInternalError); <END> } if (e != null) { operationResult = null; routerMetrics.onGetBlobInfoError(e); } routerMetrics.getBlobInfoOperationLatencyMs.update(time.milliseconds() - submissionTimeMs); operationCompleteCallback.completeOperation(operationFuture, operationCallback, operationResult, e); } }</code><technical_language>need update metrics for this well</technical_language>

Target:
private void checkAndMaybeComplete() { if (operationTracker.isDone()) { if (operationTracker.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.onGetBlobInfoError(e); } routerMetrics.getBlobInfoOperationLatencyMs.update(time.milliseconds() - submissionTimeMs); operationCompleteCallback.completeOperation(operationFuture, operationCallback, operationResult, e); } }
Source:
<code>public void canSupportGuaranteedSize() throws InterruptedException, CameraInfoUnavailableException { for (int i = 0; i <= 1; i++) { final int lensFacing = i; <START> if (CameraUtil.hasCameraWithLensFacing(lensFacing)) { <END> continue; } String cameraId = CameraX.getCameraFactory().cameraIdForLensFacing(lensFacing); boolean isRotateNeeded = (CameraX.getCameraInfo(cameraId).getSensorRotationDegrees( Surface.ROTATION_0) % 180) != 0; ImageAnalysis useCase = new ImageAnalysis.Builder().setTargetResolution( GUARANTEED_RESOLUTION).setTargetRotation( isRotateNeeded ? Surface.ROTATION_90 : Surface.ROTATION_0).build(); mInstrumentation.runOnMainSync(() -> { CameraSelector cameraSelector = new CameraSelector.Builder().requireLensFacing( lensFacing).build(); CameraX.bindToLifecycle(mLifecycleOwner, cameraSelector, useCase); mLifecycleOwner.startAndResume(); useCase.setAnalyzer(CameraXExecutors.newHandlerExecutor(mHandler), mAnalyzer); }); assertTrue(mAnalysisResultsSemaphore.tryAcquire(5, TimeUnit.SECONDS)); synchronized (mAnalysisResultLock) { assertEquals(GUARANTEED_RESOLUTION, mAnalysisResults.iterator().next().mResolution); } } }</code><technical_language>"if (!CameraUtil.hasCameraWithLensFacing(lensFacing)) {" ? miss "!"</technical_language>

Target:
public void canSupportGuaranteedSize() throws InterruptedException, CameraInfoUnavailableException { for (int i = 0; i <= 1; i++) { final int lensFacing = i; if (!CameraUtil.hasCameraWithLensFacing(lensFacing)) { continue; } String cameraId = CameraX.getCameraFactory().cameraIdForLensFacing(lensFacing); boolean isRotateNeeded = (CameraX.getCameraInfo(cameraId).getSensorRotationDegrees( Surface.ROTATION_0) % 180) != 0; ImageAnalysis useCase = new ImageAnalysis.Builder().setTargetResolution( GUARANTEED_RESOLUTION).setTargetRotation( isRotateNeeded ? Surface.ROTATION_90 : Surface.ROTATION_0).build(); mInstrumentation.runOnMainSync(() -> { CameraSelector cameraSelector = new CameraSelector.Builder().requireLensFacing( lensFacing).build(); CameraX.bindToLifecycle(mLifecycleOwner, cameraSelector, useCase); mLifecycleOwner.startAndResume(); useCase.setAnalyzer(CameraXExecutors.newHandlerExecutor(mHandler), mAnalyzer); }); assertTrue(mAnalysisResultsSemaphore.tryAcquire(5, TimeUnit.SECONDS)); synchronized (mAnalysisResultLock) { assertEquals(GUARANTEED_RESOLUTION, mAnalysisResults.iterator().next().mResolution); } mInstrumentation.runOnMainSync(() -> { CameraX.unbindAll(); mLifecycleOwner.pauseAndStop(); }); } }
Source:
<code>public static boolean isPem(String data) { <START> if (CERT_PATTERN.matcher(data).find()) { <END> return true; } if (PUBLIC_KEY_PATTERN.matcher(data).find()) { return true; } if (PRIVATE_KEY_PATTERN.matcher(data).find()) { return true; } return false; }</code><technical_language>java return CERT_PATTERN.matcher(data).find() || PUBLIC_KEY_PATTERN.matcher(data).find() || PRIVATE_KEY_PATTERN.matcher(data).find();</technical_language>

Target:
public static boolean isPem(String data) { return CERT_PATTERN.matcher(data).find() || PUBLIC_KEY_PATTERN.matcher(data).find() || PRIVATE_KEY_PATTERN.matcher(data).find(); }
Source:
<code>public void testDeploymentArtifacts() { String templateUrl = getClasspathUrlForResource(TEMPLATES_FOLDER + "deployment-artifact.tosca.yaml"); EntitySpec<? extends Application> app = transformer.createApplicationSpec( new ResourceUtils(mgmt).getResourceAsString(templateUrl)); assertNotNull(app); assertEquals(app.getChildren().size(), 1); EntitySpec<TomcatServer> tomcatServer = <START> (EntitySpec<TomcatServer>) ToscaPlanToSpecTransformer <END> .findChildEntitySpecByPlanId(app, "tomcat_server"); assertEquals(tomcatServer.getConfig().get(TomcatServer.ROOT_WAR), "<LINK_0>" + "brooklyn-example-hello-world-sql-webapp/0.6.0/" + "brooklyn-example-hello-world-sql-webapp-0.6.0.war"); }</code><technical_language>need cast TomcatServer here</technical_language>

Target:
public void testDeploymentArtifacts() { String templateUrl = getClasspathUrlForResource(TEMPLATES_FOLDER + "deployment-artifact.tosca.yaml"); EntitySpec<? extends Application> app = transformer.createApplicationSpec( new ResourceUtils(mgmt).getResourceAsString(templateUrl)); assertNotNull(app); assertEquals(app.getChildren().size(), 1); EntitySpec<?> tomcatServer = ToscaPlanToSpecTransformer .findChildEntitySpecByPlanId(app, "tomcat_server"); assertEquals(tomcatServer.getConfig().get(TomcatServer.ROOT_WAR), "<LINK_0>" + "brooklyn-example-hello-world-sql-webapp/0.6.0/" + "brooklyn-example-hello-world-sql-webapp-0.6.0.war"); }
Source:
<code>public void onAuditedFieldChange( String newValue ) { if ( getDataObject() != null ) { <START> Boolean doAdd = Boolean.TRUE.toString().equals( newValue ); <END> DataModelCommand command; if ( doAdd ) { List<ValuePair> defaultValues = new ArrayList<>( ); defaultValues.add( new ValuePair( "targetAuditMode", "NOT_AUDITED" ) ); command = commandBuilder.buildDataObjectAddAnnotationCommand( getContext(), getName(), getDataObject(), JPADomainAnnotations.HIBERNATE_ENVERS_AUDITED, defaultValues ); } else { command = commandBuilder.buildDataObjectRemoveAnnotationCommand( getContext(), getName(), getDataObject(), JPADomainAnnotations.HIBERNATE_ENVERS_AUDITED ); } command.execute(); } }</code><technical_language>Boolean.parseBoolean(...) is (as handles case insensitivity). doAdd a boolean a Boolean.. is a bit picky ;-)</technical_language>

Target:
public void onAuditedFieldChange( String newValue ) { if ( getDataObject() != null ) { Boolean doAdd = Boolean.parseBoolean( newValue ); DataModelCommand command; if ( doAdd ) { List<ValuePair> defaultValues = new ArrayList<>( ); defaultValues.add( new ValuePair( "targetAuditMode", "NOT_AUDITED" ) ); command = commandBuilder.buildDataObjectAddAnnotationCommand( getContext(), getName(), getDataObject(), JPADomainAnnotations.HIBERNATE_ENVERS_AUDITED, defaultValues ); } else { command = commandBuilder.buildDataObjectRemoveAnnotationCommand( getContext(), getName(), getDataObject(), JPADomainAnnotations.HIBERNATE_ENVERS_AUDITED ); } command.execute(); } }
Source:
<code>private boolean performLiveSnapshot(final Snapshot snapshot) { <START> if(FeatureSupported.isAsyncLiveSnapshotSupported(getVm().getClusterCompatibilityVersion())) { <END> ActionReturnValue actionReturnValue = runInternalAction(ActionType.CreateLiveSnapshotForVm, createLiveSnapshotParameters(snapshot), ExecutionHandler.createDefaultContextForTasks(getContext())); if (actionReturnValue.getSucceeded()) { setSucceeded(true); return true; } else { log.error("Failed to start live snapshot on VDS"); return false; } } else { return performLiveSnapshotDeprecated(snapshot); } }</code><technical_language>missing space</technical_language>

Target:
private boolean performLiveSnapshot(final Snapshot snapshot) { if (!FeatureSupported.isAsyncLiveSnapshotSupported(getVm().getClusterCompatibilityVersion())) { return performLiveSnapshotDeprecated(snapshot); } else { ActionReturnValue actionReturnValue = runInternalAction(ActionType.CreateLiveSnapshotForVm, createLiveSnapshotParameters(snapshot), ExecutionHandler.createDefaultContextForTasks(getContext())); if (actionReturnValue.getSucceeded()) { setSucceeded(true); return true; } else { log.error("Failed to start live snapshot on VDS"); return false; } } }
Source:
<code>void verifyForLoopOpenBraceStyle(ForStatementContext ctx) { int numChildren = ctx.getChildCount(); Location loopEndLocation; <START> Object constructBeforeOpenBrace = ctx.getChild(numChildren - 2); <END> if (constructBeforeOpenBrace instanceof TerminalNodeImpl) { Token semicolon = ((TerminalNodeImpl) constructBeforeOpenBrace).getSymbol(); loopEndLocation = getTokenLocation(semicolon); } else { ExpressionContext expressionContext = (ExpressionContext) constructBeforeOpenBrace; loopEndLocation = getContextStopLocation(expressionContext); } verifyCodeBlockOpenBraceStyle(Messages.FOR_LOOP, loopEndLocation, ctx.codeBlock()); }</code><technical_language>Object ParseTree</technical_language>

Target:
void verifyForLoopOpenBraceStyle(ForStatementContext ctx) { int numChildren = ctx.getChildCount(); Location loopEndLocation; ParseTree constructBeforeOpenBrace = ctx.getChild(numChildren - 2); if (constructBeforeOpenBrace instanceof TerminalNodeImpl) { Token semicolon = ((TerminalNodeImpl) constructBeforeOpenBrace).getSymbol(); loopEndLocation = getTokenLocation(semicolon); } else { ExpressionContext expressionContext = (ExpressionContext) constructBeforeOpenBrace; loopEndLocation = getContextStopLocation(expressionContext); } verifyCodeBlockOpenBraceStyle(Messages.FOR_LOOP, loopEndLocation, ctx.codeBlock()); }
Source:
<code>protected void beforeTest() { <START> final String queueName = "hemant-test2"; END> Assertions.assertNotNull(queueName, "'queueName' cannot be null."); sender = createBuilder().sender().queueName(queueName).buildAsyncClient(); receiver = createBuilder() .receiver() .queueName(queueName) .isAutoComplete(true) .buildAsyncClient(); receiverManualComplete = createBuilder() .receiver() .queueName(queueName) .isAutoComplete(false) .buildAsyncClient(); receiveDeleteModeReceiver = createBuilder() .receiver() .queueName(queueName) .isAutoComplete(false) .receiveMode(ReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient(); }</code><technical_language>getQueueName(). running test if set right environment variables, need manual changes</technical_language>

Target:
protected void beforeTest() { final String queueName = getQueueName(); Assertions.assertNotNull(queueName, "'queueName' cannot be null."); sender = createBuilder().sender().queueName(queueName).buildAsyncClient(); receiver = createBuilder() .receiver() .queueName(queueName) .buildAsyncClient(); receiverManualComplete = createBuilder() .receiver() .queueName(queueName) .buildAsyncClient(); receiveDeleteModeReceiver = createBuilder() .receiver() .queueName(queueName) .receiveMode(ReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient(); }
Source:
<code>public void setBucketLifeCycle(String bucketName, String lifeCycle) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException { if (lifeCycle == null || "".equals(lifeCycle)) { <START> deleteBucketLifeCycle(bucketName); <END> } else { Map<String, String> headerMap = new HashMap<>(); headerMap.put("Content-Length", Integer.toString(lifeCycle.length())); Map<String, String> queryParamMap = new HashMap<>(); queryParamMap.put("lifecycle", ""); HttpResponse response = executePut(bucketName, null, headerMap, queryParamMap, lifeCycle, 0); response.body().close(); } }</code><technical_language>need error out S3 service error out, delete Set()</technical_language>

Target:
public void setBucketLifeCycle(String bucketName, String lifeCycle) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException,InvalidArgumentException { if ((lifeCycle == null) || "".equals(lifeCycle)) { throw new InvalidArgumentException("life cycle cannot be empty"); } Map<String, String> headerMap = new HashMap<>(); headerMap.put("Content-Length", Integer.toString(lifeCycle.length())); Map<String, String> queryParamMap = new HashMap<>(); queryParamMap.put("lifecycle", ""); HttpResponse response = executePut(bucketName, null, headerMap, queryParamMap, lifeCycle, 0); response.body().close(); }
Source:
<code>public String toString() { StringBuilder sb = new StringBuilder(25); sb.append(year).append('-').append(month).append('-').append(day) .append(' ').append(hour).append(':').append(minute) <START> .append(':').append(second).append('.').append(millisecond); <END> return sb.toString(); }</code><technical_language>return new StringBuilder().append()....toString();</technical_language>

Target:
public String toString() { return new StringBuilder(25).append(year).append('-').append(month) .append('-').append(day).append(' ').append(hour).append(':') .append(minute).append(':').append(second).append('.') .append(millisecond).toString(); }
Source:
<code>public AffinityLabelListModel(VdcQueryType queryType) { this.queryType = queryType; setTitle(ConstantsManager.getInstance().getConstants().affinityLabelsTitle()); setHelpTag(HelpTag.affinity_groups); setHashName("affinity_labels"); setNewCommand(new UICommand("New", this)); setEditCommand(new UICommand("Edit", this)); setRemoveCommand(new UICommand("Remove", this)); entitiesNameMap = new EntityModel<>(); entitiesNameMap.setEntity(new HashMap<>()); updateActionAvailability(); <START> startProgress(); <END> loadEntitiesNameMap(); getItemsChangedEvent().addListener((ev, sender, args) -> loadEntitiesNameMap()); getSelectedItemsChangedEvent().addListener((ev, sender, args) -> loadEntitiesNameMap()); getEntityChangedEvent().addListener((ev, sender, args) -> loadEntitiesNameMap()); }</code><technical_language>is progress stopped</technical_language>

Target:
public AffinityLabelListModel(VdcQueryType queryType) { this.queryType = queryType; setTitle(ConstantsManager.getInstance().getConstants().affinityLabelsTitle()); setHelpTag(HelpTag.affinity_groups); setHashName("affinity_labels"); setNewCommand(new UICommand("New", this)); setEditCommand(new UICommand("Edit", this)); setRemoveCommand(new UICommand("Remove", this)); entitiesNameMap = new EntityModel<>(); entitiesNameMap.setEntity(new HashMap<>()); updateActionAvailability(); loadEntitiesNameMap(); getItemsChangedEvent().addListener((ev, sender, args) -> loadEntitiesNameMap()); getSelectedItemsChangedEvent().addListener((ev, sender, args) -> loadEntitiesNameMap()); getEntityChangedEvent().addListener((ev, sender, args) -> loadEntitiesNameMap()); }
Source:
<code>private <T> FeedResponse<T> prepareFeedResponse(FeedResponse<Document> response, Class<T> classType) { QueryInfo queryInfo = ModelBridgeInternal.getQueryInfoFromFeedResponse(response); if (queryInfo != null && queryInfo.hasSelectValue()) { List<T> transformedResults = response.getResults() .stream() .map(d -> { if (d.has(Constants.Properties.VALUE)) { <START> return d.get(Constants.Properties.VALUE); <END> } else { return d; } }) .map(object -> transform(object, classType)) .collect(Collectors.toList()); return BridgeInternal.createFeedResponseWithQueryMetrics(transformedResults, response.getResponseHeaders(), ModelBridgeInternal.queryMetrics(response)); } return BridgeInternal.createFeedResponseWithQueryMetrics( (response.getResults().stream().map(document -> ModelBridgeInternal.toObjectFromJsonSerializable(document , classType)) .collect(Collectors.toList())), response.getResponseHeaders(), ModelBridgeInternal.queryMetrics(response)); }</code><technical_language>return in if else. Predeclare variablee return end</technical_language>

Target:
private <T> FeedResponse<T> prepareFeedResponse(FeedResponse<Document> response, Class<T> classType) { QueryInfo queryInfo = ModelBridgeInternal.getQueryInfoFromFeedResponse(response); if (queryInfo != null && queryInfo.hasSelectValue()) { List<T> transformedResults = response.getResults() .stream() .map(d -> d.has(Constants.Properties.VALUE) ? transform(d.get(Constants.Properties.VALUE), classType) : ModelBridgeInternal.toObjectFromJsonSerializable(d, classType)) .collect(Collectors.toList()); return BridgeInternal.createFeedResponseWithQueryMetrics(transformedResults, response.getResponseHeaders(), ModelBridgeInternal.queryMetrics(response)); } return BridgeInternal.createFeedResponseWithQueryMetrics( (response.getResults().stream().map(document -> ModelBridgeInternal.toObjectFromJsonSerializable(document , classType)) .collect(Collectors.toList())), response.getResponseHeaders(), ModelBridgeInternal.queryMetrics(response)); }
Source:
<code>protected TransportConfiguration addAcceptorConfiguration(ActiveMQServer server, int port) { HashMap<String, Object> params = new HashMap<>(); params.put(TransportConstants.PORT_PROP_NAME, String.valueOf(port)); params.put(TransportConstants.PROTOCOLS_PROP_NAME, getConfiguredProtocols()); <START> params.put(TransportConstants.NETTY_READ_TIMEOUT, readTimeout); <END> HashMap<String, Object> amqpParams = new HashMap<>(); configureAMQPAcceptorParameters(amqpParams); return new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params, "netty-acceptor", amqpParams); }</code><technical_language>3 ms small for test case, test test setting this error occur. assert problem exists setting</technical_language>

Target:
protected TransportConfiguration addAcceptorConfiguration(ActiveMQServer server, int port) { HashMap<String, Object> params = new HashMap<>(); params.put(TransportConstants.PORT_PROP_NAME, String.valueOf(port)); params.put(TransportConstants.PROTOCOLS_PROP_NAME, getConfiguredProtocols()); HashMap<String, Object> amqpParams = new HashMap<>(); configureAMQPAcceptorParameters(amqpParams); return new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params, "netty-acceptor", amqpParams); }
Source:
<code>public Function newInstance(ObjList<Function> args, int position, CairoConfiguration configuration) { Function scale = args.getQuick(1); if (scale.isConstant()) { int scaleValue = scale.getInt(null); if (scaleValue != Numbers.INT_NaN) { <START> if (scaleValue > -1 && scaleValue < Numbers.pow10max + 2) { <END> return new FuncPosConst(position, args.getQuick(0), scaleValue); } if (scaleValue < 0 && scaleValue > -Numbers.pow10max) { return new FuncNegConst(position, args.getQuick(0), -scaleValue); } } return new DoubleConstant(position, Double.NaN); } return new Func(position, args.getQuick(0), args.getQuick(1)); }</code><technical_language>need add 2 scale. Pow2max is 14. check scale = 15 is allowed., this fail line 15+2 > 14</technical_language>

Target:
public Function newInstance(ObjList<Function> args, int position, CairoConfiguration configuration) { Function scale = args.getQuick(1); if (scale.isConstant()) { int scaleValue = scale.getInt(null); if (scaleValue != Numbers.INT_NaN) { if (scaleValue > -1 && scaleValue + 2 < Numbers.pow10max) { return new FuncPosConst(position, args.getQuick(0), scaleValue); } if (scaleValue < 0 && scaleValue > -Numbers.pow10max) { return new FuncNegConst(position, args.getQuick(0), -scaleValue); } } return new DoubleConstant(position, Double.NaN); } return new Func(position, args.getQuick(0), args.getQuick(1)); }
Source:
<code>public PlanNodeCostEstimate visitExchange(ExchangeNode node, Void context) { <START> return calculateExchangeCost(numberOfNodes, getStats(node), node.getType(), node.getScope()); <END> }</code><technical_language>need for if 1 - 1 0 add cpuCost</technical_language>

Target:
public PlanNodeCostEstimate visitExchange(ExchangeNode node, Void context) { return calculateExchangeCost(numberOfNodes, getStats(node), node.getOutputSymbols(), node.getType(), node.getScope()); }
Source:
<code>private boolean _isWaterSafe() { <START> boolean isWaterSafe = config.getBoolean("is-water-safe", false); <END> LocationUtil.setIsWaterSafe(isWaterSafe); return isWaterSafe; }</code><technical_language>rename this _isWaterSafe aid readability</technical_language>

Target:
private boolean _isWaterSafe() { boolean _isWaterSafe = config.getBoolean("is-water-safe", false); LocationUtil.setIsWaterSafe(_isWaterSafe); return _isWaterSafe; }
Source:
<code>PropertiesHolder(final File file) { <START> this.m_file = file; <END> this.m_properties = null; }</code><technical_language>Is reason add this. prefixes? redundant member variables prefixed m_</technical_language>

Target:
PropertiesHolder(final File file) { m_file = file; m_properties = null; }
Source:
<code>public Map<String,String> loadAll() { try (DbSession dbSession = dbClient.openSession(false)) { Map<String,String> result = new HashMap<>(); dbClient.propertiesDao().selectGlobalProperties(dbSession) .forEach(p -> result.put(p.getKey(), defaultString(p.getValue()))); <START> return Collections.unmodifiableMap(result); <END> } }</code><technical_language>simplify this code this (it return immutable map) : return dbClient.propertiesDao().selectGlobalProperties(dbSession) .stream() .collect(MoreCollectors.uniqueIndex(PropertyDto::getKey, p -> defaultString(p.getValue())));</technical_language>

Target:
public Map<String, String> loadAll() { try (DbSession dbSession = dbClient.openSession(false)) { return dbClient.propertiesDao().selectGlobalProperties(dbSession) .stream() .collect(MoreCollectors.uniqueIndex(PropertyDto::getKey, p -> defaultString(p.getValue()))); } }
Source:
<code>public boolean ping() { return (subscription != null) && (subscription.getDeliveryMethod() instanceof Pingable) <START> && ((Pingable) subscription.getDeliveryMethod()).ping(); <END> }</code><technical_language>Technically this condition is before. For instance, this return false (and color row red) if subscription instance of Pingable color row red if entry **_was_** instance of Pingable **and** ping failed. this change intentional</technical_language>

Target:
public boolean ping() { return (subscription == null) || !(subscription.getDeliveryMethod() instanceof Pingable) || ((Pingable) subscription.getDeliveryMethod()).ping(); }
Source:
<code>protected ServerOperation<HttpClientResponse<O>> requestToOperation(final HttpClientRequest<I> request, final ClientConfig rxClientConfig) { Preconditions.checkNotNull(request); return new ServerOperation<HttpClientResponse<O>>() { @Override public Observable<HttpClientResponse<O>> call(Server server) { HttpClient<I,O> rxClient = getOrCreateRxClient(server); setHostHeader(request, server.getHost()); Observable<HttpClientResponse<O>> o; if (rxClientConfig != null) { o = rxClient.submit(request, rxClientConfig); } else { o = rxClient.submit(request); } <START> return o.concatMap(new Func1<HttpClientResponse<O>, Observable<HttpClientResponse<O>>>() { <END> @Override public Observable<HttpClientResponse<O>> call(HttpClientResponse<O> t1) { if (t1.getStatus().equals(HttpResponseStatus.SERVICE_UNAVAILABLE)) { return Observable.error(new ClientException(ClientException.ErrorType.SERVER_THROTTLED)); } return Observable.just(t1); } }); } }; }</code><technical_language>performance penalty pay for concatMap() operation? work if map() throws exception if status is 503</technical_language>

Target:
protected ServerOperation<HttpClientResponse<O>> requestToOperation(final HttpClientRequest<I> request, final ClientConfig rxClientConfig) { Preconditions.checkNotNull(request); return new ServerOperation<HttpClientResponse<O>>() { final AtomicInteger count = new AtomicInteger(0); @Override public Observable<HttpClientResponse<O>> call(Server server) { HttpClient<I,O> rxClient = getOrCreateRxClient(server); setHostHeader(request, server.getHost()); Observable<HttpClientResponse<O>> o; if (rxClientConfig != null) { o = rxClient.submit(request, rxClientConfig); } else { o = rxClient.submit(request); } return o.concatMap(new Func1<HttpClientResponse<O>, Observable<HttpClientResponse<O>>>() { @Override public Observable<HttpClientResponse<O>> call(HttpClientResponse<O> t1) { if (t1.getStatus().code()/100 == 4 || t1.getStatus().code()/100 == 5) return responseToErrorPolicy.call(t1, backoffStrategy.call(count.getAndIncrement())); else return Observable.just(t1); } }); } }; }
Source:
<code>private Boolean checkDomainVersionSupport() { StorageFormatType numericDomainFormat = getStorageDomain().getStorageFormat(); List<VDS> haveNotSupportedVDSes = vdsDao.getAllForStoragePool(getStorageDomain().getStoragePoolId()) .stream() .filter(vds -> !vds.getSupportedDomainVersions().contains(numericDomainFormat)) .collect(Collectors.toList()); if (!haveNotSupportedVDSes.isEmpty()) { List<String> replacements = new ArrayList<>(2); <START> List<String> vdsNames = haveNotSupportedVDSes.stream().map(VDS::getName).collect(Collectors.toList()); <END> replacements.add(ReplacementUtils.createSetVariableString("hosts", vdsNames)); replacements.add(ReplacementUtils.createSetVariableString("formatversion", numericDomainFormat)); return failValidation(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_VERSION_UNSUPPORTED, replacements); } return true; }</code><technical_language>Sorry, I missed before, iterating VDS list again. convert VDS name in iteration it</technical_language>

Target:
private Boolean checkDomainVersionSupport() { StorageFormatType numericDomainFormat = getStorageDomain().getStorageFormat(); List<String> haveNotSupportedVDSes = vdsDao.getAllForStoragePool(getStorageDomain().getStoragePoolId()) .stream() .filter(vds -> !vds.getSupportedDomainVersions().contains(numericDomainFormat)) .map(VDS::getName) .collect(Collectors.toList()); if (!haveNotSupportedVDSes.isEmpty()) { List<String> replacements = new ArrayList<>(2); replacements.add(ReplacementUtils.createSetVariableString("hosts", haveNotSupportedVDSes)); replacements.add(ReplacementUtils.createSetVariableString("formatversion", numericDomainFormat)); return failValidation(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_VERSION_UNSUPPORTED, replacements); } return true; }
Source:
<code>public TextArgs with(String name, Object arg) { if (positionedArgsBuilder == null) { throw new IllegalArgumentException("Named arguments were already accessed, to add" + <START> "more arguments use TextArgs.copy()"); <END> } namedArgsBuilder.put(name, arg); return this; }</code><technical_language>Another space add</technical_language>

Target:
public TextArgs with(String name, Object arg) { return new TextArgs( positionedArgs, ImmutableMap.<String, Object>builder().putAll(namedArgs).put(name, arg).build() ); }
Source:
<code>public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) { String jsonPatch = null; Service service = (Service) postParams.get("service"); <START> Json json = Guice.createInjector(new GsonModule()).getInstance(Json.class); <END> String targetService = json.toJson(postParams.get("updateService")); String sourceService = json.toJson(service.toUpdatableService().build()); ObjectMapper mapper = new ObjectMapper(); try { jsonPatch = JsonDiff.asJson(mapper.readTree(sourceService), mapper.readTree(targetService)).toString(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Could not create a JSONPatch"); } return bindToRequest(request, (Object) jsonPatch); }</code><technical_language>Inject Json object instead of creating a new entire injector</technical_language>

Target:
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) { String jsonPatch = null; Service service = (Service) postParams.get("service"); String targetService = json.toJson(postParams.get("updateService")); String sourceService = json.toJson(service.toUpdatableService().build()); ObjectMapper mapper = new ObjectMapper(); try { jsonPatch = JsonDiff.asJson(mapper.readTree(sourceService), mapper.readTree(targetService)).toString(); } catch (IOException e) { throw new RuntimeException("Could not create a JSONPatch", e); } return bindToRequest(request, (Object) jsonPatch); }
Source:
<code>public void bindView(View view, Context context, Cursor cursor) { super.bindView(view, context, cursor); final Cursor c = cursor; final CheckedTextView ctv = (CheckedTextView) view.findViewById(R.id.checkmark); final Activity curActivity = (Activity) context; ctv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { CheckedTextView cview = (CheckedTextView) v.findViewById(R.id.checkmark); cview.toggle(); curActivity.runOnUiThread(new Runnable() { @Override public void run() { <START> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) <END> curActivity.invalidateOptionsMenu(); } }); } }); }</code><technical_language>Is this project specific? is generally ok do so</technical_language>

Target:
public void bindView(View view, Context context, Cursor cursor) { super.bindView(view, context, cursor); final CheckedTextView ctv = (CheckedTextView) view.findViewById(R.id.checkmark); final Activity curActivity = (Activity) context; ctv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { CheckedTextView cview = (CheckedTextView) v.findViewById(R.id.checkmark); cview.toggle(); curActivity.runOnUiThread(new Runnable() { @Override public void run() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { curActivity.invalidateOptionsMenu(); } } }); } }); }
Source:
<code><START> public Key(byte row[], int rOff, int rLen, byte cf[], int cfOff, int cfLen, byte cq[], int cqOff, int cqLen, byte cv[], int cvOff, int cvLen, long ts, boolean deleted, boolean copy) { <END> init(row, rOff, rLen, cf, cfOff, cfLen, cq, cqOff, cqLen, cv, cvOff, cvLen, ts, deleted, copy); }</code><technical_language>new support forever. 15 arguments is a user error waiting happen. If I in time drop other constructors in favor of a builder pattern, I would. point of is avoid exposing additional combinatorial explosion of parameters</technical_language>

Target:
Key(byte row[], int rOff, int rLen, byte cf[], int cfOff, int cfLen, byte cq[], int cqOff, int cqLen, byte cv[], int cvOff, int cvLen, long ts, boolean deleted, boolean copy) { init(row, rOff, rLen, cf, cfOff, cfLen, cq, cqOff, cqLen, cv, cvOff, cvLen, ts, deleted, copy); }
Source:
<code>private <T> T readSinglePositionFromArray(PortablePosition position) throws IOException { assert position.getType() != null : "Unsupported type read: null"; switch (position.getType()) { case BYTE: case BYTE_ARRAY: <START> return (T) Byte.valueOf(in.readByte(position.getStreamPosition())); <END> case SHORT: case SHORT_ARRAY: return (T) Short.valueOf(in.readShort(position.getStreamPosition())); case INT: case INT_ARRAY: return (T) Integer.valueOf(in.readInt(position.getStreamPosition())); case LONG: case LONG_ARRAY: return (T) Long.valueOf(in.readLong(position.getStreamPosition())); case FLOAT: case FLOAT_ARRAY: return (T) Float.valueOf(in.readFloat(position.getStreamPosition())); case DOUBLE: case DOUBLE_ARRAY: return (T) Double.valueOf(in.readDouble(position.getStreamPosition())); case BOOLEAN: case BOOLEAN_ARRAY: return (T) Boolean.valueOf(in.readBoolean(position.getStreamPosition())); case CHAR: case CHAR_ARRAY: return (T) Character.valueOf(in.readChar(position.getStreamPosition())); case UTF: case UTF_ARRAY: in.position(position.getStreamPosition()); return (T) in.readUTF(); case PORTABLE: case PORTABLE_ARRAY: in.position(position.getStreamPosition()); return (T) serializer.readAndInitialize(in, position.getFactoryId(), position.getClassId()); default: throw new IllegalArgumentException("Unsupported type: " + position.getType()); } }</code><technical_language>is position is n array element element is array, I expecting a recursive kind of call here, is this correct code path? Is a test array array (do support it)</technical_language>

Target:
private <T> T readSinglePositionFromArray(PortablePosition position) throws IOException { assert position.getType() != null : "Unsupported type read: null"; in.position(position.getStreamPosition()); switch (position.getType()) { case BYTE: case BYTE_ARRAY: return (T) Byte.valueOf(in.readByte()); case SHORT: case SHORT_ARRAY: return (T) Short.valueOf(in.readShort()); case INT: case INT_ARRAY: return (T) Integer.valueOf(in.readInt()); case LONG: case LONG_ARRAY: return (T) Long.valueOf(in.readLong()); case FLOAT: case FLOAT_ARRAY: return (T) Float.valueOf(in.readFloat()); case DOUBLE: case DOUBLE_ARRAY: return (T) Double.valueOf(in.readDouble()); case BOOLEAN: case BOOLEAN_ARRAY: return (T) Boolean.valueOf(in.readBoolean()); case CHAR: case CHAR_ARRAY: return (T) Character.valueOf(in.readChar()); case UTF: case UTF_ARRAY: return (T) in.readUTF(); case PORTABLE: case PORTABLE_ARRAY: return (T) serializer.readAndInitialize(in, position.getFactoryId(), position.getClassId()); default: throw new IllegalArgumentException("Unsupported type: " + position.getType()); } }
Source:
<code>public Defaults getDefaults() { return new Defaults() .withSemanticZoomLevel(0) .withPreferredLayout("Hierarchy Layout") .withCriteria(() -> { List<VertexHopGraphProvider.VertexHopCriteria> focusCriteria = new ArrayList<>(); <START> for (Vertex vertex : this.getVertices()) { <END> Status status = statusProvider.getStatusForSingleVertex(this, vertex); if (!status.computeStatus().equalsIgnoreCase(OnmsSeverity.NORMAL.getLabel())) { focusCriteria.addAll(FocusStrategy.SPECIFIC.getFocusCriteria(PathOutageProvider.this, vertex.getId())); } } return Lists.newArrayList(focusCriteria); }); }</code><technical_language>default focus vertex worst severity. moment vertices a severity != NORMAL selected. In addition if is okay, default focus results in vertices if problems. beeing said, easier calculate status of vertices invoke statusProvider.getVertices(...), sort severity select worst one</technical_language>

Target:
public Defaults getDefaults() { return new Defaults() .withSemanticZoomLevel(0) .withPreferredLayout("Hierarchy Layout") .withCriteria(() -> { Map<VertexRef, Status> resultMap = statusProvider.getStatusForVertices(this, Lists.newArrayList(this.getVertices()), new Criteria[0]); Optional<Map.Entry<VertexRef, Status>> max = resultMap.entrySet().stream().max(Comparator.comparing(e -> OnmsSeverity.get(e.getValue().computeStatus()))); if (max.isPresent()) { return Lists.newArrayList(new VertexHopGraphProvider.DefaultVertexHopCriteria(max.get().getKey())); } else if (this.getVertexTotalCount() > 0) { return Lists.newArrayList(new VertexHopGraphProvider.DefaultVertexHopCriteria(this.getVertices().get(0))); } else { return Lists.newArrayList(); } }); }
Source:
<code>private void readFirstLocalFileHeader(final byte[] lfh) throws IOException { readFully(lfh); final ZipLong sig = new ZipLong(lfh); <START> <END> if (sig.equals(ZipLong.SINGLE_SEGMENT_SPLIT_MARKER) || sig.equals(ZipLong.DD_SIG)) { final byte[] missedLfhBytes = new byte[4]; readFully(missedLfhBytes); System.arraycopy(lfh, 4, lfh, 0, LFH_LEN - 4); System.arraycopy(missedLfhBytes, 0, lfh, LFH_LEN - 4, 4); } }</code><technical_language>I prefer this conditional explicit flag passed in constructor people do expect split archives incomplete archives indication of problem</technical_language>

Target:
private void readFirstLocalFileHeader(final byte[] lfh) throws IOException { readFully(lfh); final ZipLong sig = new ZipLong(lfh); if (sig.equals(ZipLong.SINGLE_SEGMENT_SPLIT_MARKER) || (skipSplitSig && sig.equals(ZipLong.DD_SIG))) { final byte[] missedLfhBytes = new byte[4]; readFully(missedLfhBytes); System.arraycopy(lfh, 4, lfh, 0, LFH_LEN - 4); System.arraycopy(missedLfhBytes, 0, lfh, LFH_LEN - 4, 4); } }
Source:
<code>private ArrayList<ILaunchConfiguration> collectAssociatedLaunches(IResource resource) { ArrayList<ILaunchConfiguration> list = new ArrayList<>(); try { ILaunchConfiguration[] configs = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurations(); IResource[] resources = null; for (ILaunchConfiguration config : configs) { if(config.isLocal()) { resources = config.getMappedResources(); if(resources != null) { for (IResource <START> resource2 : <END> resources) { if(resource.equals(resource2) || resource.getFullPath().isPrefixOf(resource2.getFullPath())) { list.add(config); break; } } } } } } catch (CoreException e) { DebugPlugin.log(e); } return list; }</code><technical_language>rename res</technical_language>

Target:
private ArrayList<ILaunchConfiguration> collectAssociatedLaunches(IResource resource) { ArrayList<ILaunchConfiguration> list = new ArrayList<>(); try { ILaunchConfiguration[] configs = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurations(); IResource[] resources = null; for (ILaunchConfiguration config : configs) { if(config.isLocal()) { resources = config.getMappedResources(); if(resources != null) { for (IResource res : resources) { if(resource.equals(res) || resource.getFullPath().isPrefixOf(res.getFullPath())) { list.add(config); break; } } } } } } catch (CoreException e) { DebugPlugin.log(e); } return list; }
Source:
<code>private static String _imgLink(Collection col, String latex, JSONObject model) { String txt = _latexFromHtml(col, latex); String ext = "png"; <START> if (model.optBoolean("latexsvg", false)) <END> ext = "svg"; String fname = "latex-" + Utils.checksum(txt) + "." + ext; return "<img class=latex src=\"" + fname + "\">"; }</code><technical_language>Please braces</technical_language>

Target:
private static String _imgLink(Collection col, String latex, JSONObject model) { String txt = _latexFromHtml(col, latex); String ext = "png"; if (model.optBoolean("latexsvg", false)) { ext = "svg"; } String fname = "latex-" + Utils.checksum(txt) + "." + ext; return "<img class=latex src=\"" + fname + "\">"; }
Source:
<code>public ContentAuditLogSupportImpl( final ContentConfig config, @Reference(service = ContentAuditLogExecutor.class) final Executor executor, @Reference AuditLogService auditLogService ) { <START> this.executor = config.auditlog_enabled() ? executor : null; <END> this.auditLogService = auditLogService; }</code><technical_language>Instead of null c -> remove null checks if ( executor != null )</technical_language>

Target:
public ContentAuditLogSupportImpl( final ContentConfig config, @Reference(service = ContentAuditLogExecutor.class) final Executor executor, @Reference AuditLogService auditLogService ) { this.executor = config.auditlog_enabled() ? executor : c -> { }; this.auditLogService = auditLogService; }
Source:
<code>public void run() { T instance = null; final AtomicBoolean taskCanceled = new AtomicBoolean(false); try { instance = createRealmOrGetFromCache(configuration, realmClass); boolean results = notifier.post(new Runnable() { @Override public void run() { if (taskCanceled.get()) { return; } T instanceToReturn = null; try { instanceToReturn = createRealmOrGetFromCache(configuration, realmClass); <START> }catch (RuntimeException e) { <END> callback.onError(e); } finally { fgRealmCreatedLatch.countDown(); } if (instanceToReturn != null) { callback.onSuccess(instanceToReturn); } } }); if (!results) { fgRealmCreatedLatch.countDown(); } if (!fgRealmCreatedLatch.await(5, TimeUnit.SECONDS)) { RealmLog.warn("Timeout for creating Realm instance in foreground thread in `CreateRealmRunnable` "); } } catch (InterruptedException e) { taskCanceled.set(true); RealmLog.warn(e, "`CreateRealmRunnable` has been interrupted."); } catch (final RuntimeException e) { RealmLog.error(e, "`CreateRealmRunnable` failed."); notifier.post(new Runnable() { @Override public void run() { callback.onError(e); } }); } finally { if (instance != null) { instance.close(); } } }</code><technical_language>whitespace</technical_language>

Target:
public void run() { T instance = null; try { instance = createRealmOrGetFromCache(configuration, realmClass); boolean results = notifier.post(new Runnable() { @Override public void run() { if (future == null || future.isCancelled()) { canReleaseBackgroundInstanceLatch.countDown(); return; } T instanceToReturn = null; Throwable throwable = null; try { instanceToReturn = createRealmOrGetFromCache(configuration, realmClass); } catch (Throwable e) { throwable = e; } finally { canReleaseBackgroundInstanceLatch.countDown(); } if (instanceToReturn != null) { callback.onSuccess(instanceToReturn); } else { callback.onError(throwable); } } }); if (!results) { canReleaseBackgroundInstanceLatch.countDown(); } if (!canReleaseBackgroundInstanceLatch.await(2, TimeUnit.SECONDS)) { RealmLog.warn("Timeout for creating Realm instance in foreground thread in `CreateRealmRunnable` "); } } catch (InterruptedException e) { RealmLog.warn(e, "`CreateRealmRunnable` has been interrupted."); } catch (final Throwable e) { RealmLog.error(e, "`CreateRealmRunnable` failed."); notifier.post(new Runnable() { @Override public void run() { callback.onError(e); } }); } finally { if (instance != null) { instance.close(); } } }