auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean purgeBlob(CloudBlobMetadata blobMetadata) throws CloudStorageException { String blobId = blobMetadata.getId(); String blobFileName = blobMetadata.getCloudBlobName(); String partitionPath = blobMetadata.getPartitionId(); String containerName = getAzureContainerName(partitionPath); RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(partitionPath)); azureMetrics.blobDeleteRequestCount.inc(); Timer.Context deleteTimer = azureMetrics.blobDeletionTime.time(); try { CloudBlobContainer azureContainer = azureBlobClient.getContainerReference(containerName); CloudBlockBlob azureBlob = azureContainer.getBlockBlobReference(blobFileName); azureBlob.deleteIfExists(); String docLink = cosmosCollectionLink + "/docs/" + blobId; documentClient.deleteDocument(docLink, options); azureMetrics.blobDeletedCount.inc(); <START> return true; <END> } catch (Exception e) { azureMetrics.blobDeleteErrorCount.inc(); String error = (e instanceof DocumentClientException) ? "Failed to delete metadata document for blob " + blobId : "Failed to delete blob " + blobId + ", storage path: " + containerName + "/" + blobFileName; throw new CloudStorageException(error, e); } finally { deleteTimer.stop(); } }</code><technical_language>this method returns false</technical_language>

Target:
public boolean purgeBlob(CloudBlobMetadata blobMetadata) throws CloudStorageException { String blobId = blobMetadata.getId(); String blobFileName = blobMetadata.getCloudBlobName(); String partitionPath = blobMetadata.getPartitionId(); String containerName = getAzureContainerName(partitionPath); RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(partitionPath)); azureMetrics.blobDeleteRequestCount.inc(); Timer.Context deleteTimer = azureMetrics.blobDeletionTime.time(); try { CloudBlobContainer azureContainer = azureBlobClient.getContainerReference(containerName); CloudBlockBlob azureBlob = azureContainer.getBlockBlobReference(blobFileName); boolean deletionDone = azureBlob.deleteIfExists(); String docLink = cosmosCollectionLink + "/docs/" + blobId; try { documentClient.deleteDocument(docLink, options); deletionDone = true; logger.debug("Purged blob from partition {}.", blobId, partitionPath); } catch (DocumentClientException dex) { if (dex.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { logger.warn("Could not find metadata for blob to delete", blobId); } else { throw dex; } } azureMetrics.blobDeletedCount.inc(deletionDone ? 1 : 0); return deletionDone; } catch (Exception e) { azureMetrics.blobDeleteErrorCount.inc(); String error = (e instanceof DocumentClientException) ? "Failed to delete metadata document for blob " + blobId : "Failed to delete blob " + blobId + ", storage path: " + containerName + "/" + blobFileName; throw new CloudStorageException(error, e); } finally { deleteTimer.stop(); } }
Source:
<code>private static void appendOptionalMatchOwnerEmbeddedNodes(StringBuilder queryBuilder) { <START> queryBuilder.append( " OPTIONAL MATCH (owner) -[r*]->(:" ); <END> queryBuilder.append( NodeLabel.EMBEDDED ); queryBuilder.append( ")" ); }</code><technical_language>here. get idea! a couple more occurrences that</technical_language>

Target:
private static void appendOptionalMatchOwnerEmbeddedNodes(StringBuilder queryBuilder) { queryBuilder.append( " OPTIONAL MATCH (" ); queryBuilder.append( ENTITY_ALIAS ); queryBuilder.append( ") -[r*]->(:" ); queryBuilder.append( NodeLabel.EMBEDDED ); queryBuilder.append( ")" ); }
Source:
<code>public void testPolicies() throws Exception { String permission = WRITE; String[] permissions = { WRITE }; Document doc = mockery.mock(Document.class, "document1"); mockery.checking(new Expectations() { { allowing(doc).getLock(); will(returnValue(null)); } }); assertSame(UNKNOWN, service.checkPermission(doc, null, creatorPrincipal, permission, permissions, null)); assertSame(UNKNOWN, service.checkPermission(doc, null, userPrincipal, permission, permissions, null)); Lock lock = new Lock(user, new GregorianCalendar()); Document doc2 = mockery.mock(Document.class, "document2"); mockery.checking(new Expectations() { { allowing(doc2).getLock(); will(returnValue(lock)); allowing(doc2).getPropertyValue("dc:creator"); will(returnValue(creator)); } }); assertSame(DENY, service.checkPermission(doc2, null, creatorPrincipal, permission, permissions, null)); assertSame(UNKNOWN, service.checkPermission(doc2, null, userPrincipal, permission, permissions, null)); deployContrib(CORE_TESTS_BUNDLE, "test-security-policy-contrib.xml"); <START> applyInlineDeployments(); <END> postSetUp(); assertSame(GRANT, service.checkPermission(doc2, null, creatorPrincipal, permission, permissions, null)); assertSame(UNKNOWN, service.checkPermission(doc2, null, userPrincipal, permission, permissions, null)); }</code><technical_language>postSetUp called applyInlineDeployments - pushInlineDeployments ? - of deployContrib a test bundle</technical_language>

Target:
public void testPolicies() throws Exception { String permission = WRITE; String[] permissions = { WRITE }; Document doc = mockery.mock(Document.class, "document1"); mockery.checking(new Expectations() { { allowing(doc).getLock(); will(returnValue(null)); } }); assertSame(UNKNOWN, service.checkPermission(doc, null, creatorPrincipal, permission, permissions, null)); assertSame(UNKNOWN, service.checkPermission(doc, null, userPrincipal, permission, permissions, null)); Lock lock = new Lock(user, new GregorianCalendar()); Document doc2 = mockery.mock(Document.class, "document2"); mockery.checking(new Expectations() { { allowing(doc2).getLock(); will(returnValue(lock)); allowing(doc2).getPropertyValue("dc:creator"); will(returnValue(creator)); } }); assertSame(DENY, service.checkPermission(doc2, null, creatorPrincipal, permission, permissions, null)); assertSame(UNKNOWN, service.checkPermission(doc2, null, userPrincipal, permission, permissions, null)); pushInlineDeployments(CORE_TESTS_BUNDLE + ":test-security-policy-contrib.xml"); assertSame(GRANT, service.checkPermission(doc2, null, creatorPrincipal, permission, permissions, null)); assertSame(UNKNOWN, service.checkPermission(doc2, null, userPrincipal, permission, permissions, null)); }
Source:
<code>public String selector() { <START> return FAILED_ENV_STACK_CONIFG_UPDATES_EVENT.name(); <END> }</code><technical_language>nit: this event()</technical_language>

Target:
public String selector() { return FAILED_ENV_STACK_CONIFG_UPDATES_EVENT.event(); }
Source:
<code>public CloseableReference<Bitmap> decodeFromEncodedImageWithColorSpace( final EncodedImage encodedImage, Bitmap.Config bitmapConfig, @Nullable Rect regionToDecode, @Nullable final ColorSpace colorSpace) { BitmapFactory.Options options = getBitmapFactoryOptions( encodedImage.getSampleSize(), bitmapConfig); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { options.inPreferredColorSpace = colorSpace == null <START> ? ColorSpace.get(ColorSpace.Named.SRGB) : colorSpace; <END> } CloseableReference<PooledByteBuffer> bytesRef = encodedImage.getByteBufferRef(); Preconditions.checkNotNull(bytesRef); try { Bitmap bitmap = decodeByteArrayAsPurgeable(bytesRef, options); return pinBitmap(bitmap); } finally { CloseableReference.closeSafely(bytesRef); } }</code><technical_language>mentioned, this changes default behavior for images >= 26 force SRGB instead of leaving inPreferredColorSpace default null value. However, this change means this API set inPreferredColorSpace=null. if want this behavior if want this, set default ColorSpace in ImageDecodeOptions SRGB developers override null, enable inPreferredColorSpace=null mode. Existing calls currently pass in null / false support color spaces changed pass in SRGB consistent. I of a good example this needed though, this version fine well. do think</technical_language>

Target:
public CloseableReference<Bitmap> decodeFromEncodedImageWithColorSpace( final EncodedImage encodedImage, Bitmap.Config bitmapConfig, @Nullable Rect regionToDecode, @Nullable final ColorSpace colorSpace) { BitmapFactory.Options options = getBitmapFactoryOptions( encodedImage.getSampleSize(), bitmapConfig); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { OreoUtils.setColorSpace(options, colorSpace); } CloseableReference<PooledByteBuffer> bytesRef = encodedImage.getByteBufferRef(); Preconditions.checkNotNull(bytesRef); try { Bitmap bitmap = decodeByteArrayAsPurgeable(bytesRef, options); return pinBitmap(bitmap); } finally { CloseableReference.closeSafely(bytesRef); } }
Source:
<code>public static String getDatanodeIdFilePath(Configuration conf) { String dataNodeIDDirPath = conf.get(ScmConfigKeys.OZONE_SCM_DATANODE_ID); if (dataNodeIDDirPath == null) { File metaDirPath = ServerUtils.getOzoneMetaDirPath(conf); if (metaDirPath == null) { throw new IllegalArgumentException("Unable to locate meta data" + "directory when getting datanode id path"); } dataNodeIDDirPath = metaDirPath.toString(); } return new File(dataNodeIDDirPath, <START> ScmConfigKeys.OZONE_SCM_DATANODE_ID_PATH_DEFAULT).toString(); <END> }</code><technical_language>OZONE_SCM_DATANODE_ID_PATH_DEFAULT is a constant is configurable. move OzoneConsts</technical_language>

Target:
public static String getDatanodeIdFilePath(Configuration conf) { String dataNodeIDDirPath = conf.get(ScmConfigKeys.OZONE_SCM_DATANODE_ID_DIR); if (dataNodeIDDirPath == null) { File metaDirPath = ServerUtils.getOzoneMetaDirPath(conf); if (metaDirPath == null) { throw new IllegalArgumentException("Unable to locate meta data" + "directory when getting datanode id path"); } dataNodeIDDirPath = metaDirPath.toString(); } return new File(dataNodeIDDirPath, OzoneConsts.OZONE_SCM_DATANODE_ID_FILE_DEFAULT).toString(); }
Source:
<code>private void init() throws Exception { String originalAppId = propertiesBuilder.conf.get(ORIGINAL_APP_ID); if (originalAppId == null) { throw new AssertionError("Need original app id if launching without apa or appjar"); } Path appsBasePath = new Path(StramClientUtils.getDTDFSRootDir(fs, conf), StramClientUtils.SUBDIR_APPS); Path origAppPath = new Path(appsBasePath, originalAppId); StringWriter writer = new StringWriter(); try (FSDataInputStream in = fs.open(new Path(origAppPath, "meta.json"))) { IOUtils.copy(in, writer); } JSONObject metaJson = new JSONObject(writer.toString()); String originalLibJars = null; try { JSONObject attributes = metaJson.getJSONObject("attributes"); originalLibJars = attributes.getString(LogicalPlan.LIBRARY_JARS.getSimpleName()); recoveryAppName = attributes.getString(Context.DAGContext.APPLICATION_NAME.getSimpleName()); } catch (JSONException ex) { } <START> LinkedHashSet<URL> clUrls = new LinkedHashSet<>(); <END> String libjars = propertiesBuilder.conf.get(LIBJARS_CONF_KEY_NAME); if (StringUtils.isBlank(libjars)) { libjars = originalLibJars; } else if (StringUtils.isNotBlank(originalLibJars)){ libjars = libjars + "," + originalLibJars; } propertiesBuilder.conf.set(LIBJARS_CONF_KEY_NAME, libjars); processLibJars(libjars, clUrls); for (URL baseURL : clUrls) { LOG.debug("Dependency: {}", baseURL); } this.launchDependencies = clUrls; }</code><technical_language>happening here? dependencies copied HDFS</technical_language>

Target:
private void init() throws Exception { String originalAppId = propertiesBuilder.conf.get(ORIGINAL_APP_ID); if (originalAppId == null) { throw new AssertionError("Need original app id if launching without apa or appjar"); } Path appsBasePath = new Path(StramClientUtils.getDTDFSRootDir(fs, conf), StramClientUtils.SUBDIR_APPS); Path origAppPath = new Path(appsBasePath, originalAppId); StringWriter writer = new StringWriter(); try (FSDataInputStream in = fs.open(new Path(origAppPath, "meta.json"))) { IOUtils.copy(in, writer); } JSONObject metaJson = new JSONObject(writer.toString()); String originalLibJars = null; try { JSONObject attributes = metaJson.getJSONObject("attributes"); originalLibJars = attributes.getString(LogicalPlan.LIBRARY_JARS.getSimpleName()); recoveryAppName = attributes.getString(Context.DAGContext.APPLICATION_NAME.getSimpleName()); } catch (JSONException ex) { recoveryAppName = "Recovery App From " + originalAppId; } LinkedHashSet<URL> clUrls = new LinkedHashSet<>(); String libjars = propertiesBuilder.conf.get(LIBJARS_CONF_KEY_NAME); if (StringUtils.isBlank(libjars)) { libjars = originalLibJars; } else if (StringUtils.isNotBlank(originalLibJars)) { libjars = libjars + "," + originalLibJars; } propertiesBuilder.conf.set(LIBJARS_CONF_KEY_NAME, libjars); processLibJars(libjars, clUrls); for (URL baseURL : clUrls) { LOG.debug("Dependency: {}", baseURL); } this.launchDependencies = clUrls; }
Source:
<code>public void overlapTests() { HashSet<String> generatedIds = new HashSet<>(); for (int i = 0; i < 100; ++i) { for (int j = 0; j < 100; ++j) { for (int k = 0; k < 100; ++k) { String iPart = CompressingIdGenerator.generateCompressedIdString(i, GROWTH_LIMITED, LEAD_LIMITED, BODY_LIMITED, 1); String jPart = CompressingIdGenerator.generateCompressedIdString(j, GROWTH_LIMITED, LEAD_LIMITED, BODY_LIMITED, 1); <START> String kPart = CompressingIdGenerator.generateCompressedIdString(k, GROWTH_LIMITED, LEAD_LIMITED, BODY_LIMITED, 1); <END> String joined = iPart + jPart + kPart; if (generatedIds.contains(joined)) { Assert.fail(String.format("Duplicate ID [%s]@[%d,%d,%d]", joined, i, j, k)); } generatedIds.add(joined); } } } }</code><technical_language>able move iPart jPart in respective loops avoid a bunch of extra calls</technical_language>

Target:
public void overlapTests() { HashSet<String> generatedIds = new HashSet<>(); for (int i = 0; i < 100; ++i) { String iPart = CompressingIdGenerator.generateCompressedIdString(i, GROWTH_LIMITED, LEAD_LIMITED, BODY_LIMITED, 1); for (int j = 0; j < 100; ++j) { String jPart = CompressingIdGenerator.generateCompressedIdString(j, GROWTH_LIMITED, LEAD_LIMITED, BODY_LIMITED, 1); for (int k = 0; k < 100; ++k) { String kPart = CompressingIdGenerator.generateCompressedIdString(k, GROWTH_LIMITED, LEAD_LIMITED, BODY_LIMITED, 1); String joined = iPart + jPart + kPart; if (generatedIds.contains(joined)) { Assert.fail(String.format("Duplicate ID [%s]@[%d,%d,%d]", joined, i, j, k)); } generatedIds.add(joined); } } } }
Source:
<code>private boolean updateDataSource(VXQueryCollectionDataSource ds, Mutable<ILogicalExpression> expression) { boolean added = false; List<Mutable<ILogicalExpression>> finds = new ArrayList<Mutable<ILogicalExpression>>(); ExpressionToolbox.findAllFunctionExpressions(expression, BuiltinOperators.CHILD.getFunctionIdentifier(), finds); for (int i = finds.size(); i > 0; --i) { int typeId = ExpressionToolbox.getTypeExpressionTypeArgument(finds.get(i - 1)); <START> SequenceType sType = null; <END> if (typeId > 0) { sType = dCtx.lookupSequenceType(typeId); if (sType.getItemType().equals(ElementType.ANYELEMENT) && typeId > 0) { ds.addChildSeq(typeId); added = true; } } } return added; }</code><technical_language>I need declare variable here. move a class variable move if statement</technical_language>

Target:
private boolean updateDataSource(VXQueryCollectionDataSource ds, Mutable<ILogicalExpression> expression) { boolean added = false; List<Mutable<ILogicalExpression>> finds = new ArrayList<Mutable<ILogicalExpression>>(); ExpressionToolbox.findAllFunctionExpressions(expression, BuiltinOperators.CHILD.getFunctionIdentifier(), finds); for (int i = finds.size(); i > 0; --i) { int typeId = ExpressionToolbox.getTypeExpressionTypeArgument(finds.get(i - 1)); if (typeId > 0) { SequenceType sType = dCtx.lookupSequenceType(typeId); if (sType.getItemType().equals(ElementType.ANYELEMENT) && typeId > 0) { ds.addChildSeq(typeId); added = true; } } } return added; }
Source:
<code>public String format(String value) { ShortDOIService shortDOIService = new ShortDOIService(); DOI doi = null; try { <START> doi = new DOI(value); <END> value = shortDOIService.getShortDOI(doi).getDOI(); } catch (IllegalArgumentException | ShortDOIServiceException e) { LOGGER.error(e.getMessage(), e); } return value; }</code><technical_language>is preferable DOI.parse(value) adds a bit of cleanup need catch IlegalArgumentException. <LINK_0></technical_language>

Target:
public String format(String value) { Objects.requireNonNull(value); ShortDOIService shortDOIService = new ShortDOIService(); Optional<DOI> doi = Optional.empty(); try { doi = DOI.parse(value); if (doi.isPresent()) { return shortDOIService.getShortDOI(doi.get()).getDOI(); } } catch (ShortDOIServiceException e) { LOGGER.error(e.getMessage(), e); } return value; }
Source:
<code>public void setFileList(ArrayList<IFile> files, Map<Repository, IndexDiff> indexDiffs) { items.clear(); for (IFile file : files) { RepositoryMapping repositoryMapping = RepositoryMapping .getMapping(file.getProject()); Repository repo = repositoryMapping.getRepository(); String path = repositoryMapping.getRepoRelativePath(file); CommitItem item = new CommitItem(); item.status = getFileStatus(path, indexDiffs.get(repo)); item.file = file; items.add(item); <START> Collections.sort(items, new Comparator<CommitItem>() { <END> public int compare(CommitItem o1, CommitItem o2) { int diff = o1.status.ordinal() - o2.status.ordinal(); if (diff != 0) return diff; diff = o1.file.getProject().getName().compareTo( o2.file.getProject().getName()); if (diff != 0) return diff; return o1.file .getProjectRelativePath() .toString() .compareTo( o2.file.getProjectRelativePath().toString()); } }); } }</code><technical_language>I sort loop do</technical_language>

Target:
public void setFileList(ArrayList<IFile> files, Map<Repository, IndexDiff> indexDiffs) { items.clear(); for (IFile file : files) { RepositoryMapping repositoryMapping = RepositoryMapping .getMapping(file.getProject()); Repository repo = repositoryMapping.getRepository(); String path = repositoryMapping.getRepoRelativePath(file); CommitItem item = new CommitItem(); item.status = getFileStatus(path, indexDiffs.get(repo)); item.file = file; items.add(item); } Collections.sort(items, new Comparator<CommitItem>() { public int compare(CommitItem o1, CommitItem o2) { int diff = o1.status.ordinal() - o2.status.ordinal(); if (diff != 0) return diff; diff = o1.file.getProject().getName().compareTo( o2.file.getProject().getName()); if (diff != 0) return diff; return o1.file .getProjectRelativePath() .toString() .compareTo( o2.file.getProjectRelativePath().toString()); } }); }
Source:
<code>private boolean translateBinary2(String op, RexNode left, RexNode right) { switch (right.getKind()) { case LITERAL: break; default: return false; } final RexLiteral rightLiteral = (RexLiteral) right; switch (left.getKind()) { case INPUT_REF: final RexInputRef left1 = (RexInputRef) left; String name = fieldNames.get(left1.getIndex()); translateOp2(op, name, rightLiteral); return true; case CAST: return translateBinary2(op, ((RexCall) left).operands.get(0), right); <START> case OTHER_FUNCTION: <END> case ITEM: String itemName = MongoRules.isItem((RexCall) left); if (itemName != null) { translateOp2(op, itemName, rightLiteral); return true; } default: return false; } }</code><technical_language>remove this line-218 ? MongoRules.isItem works for ITEM</technical_language>

Target:
private boolean translateBinary2(String op, RexNode left, RexNode right) { switch (right.getKind()) { case LITERAL: break; default: return false; } final RexLiteral rightLiteral = (RexLiteral) right; switch (left.getKind()) { case INPUT_REF: final RexInputRef left1 = (RexInputRef) left; String name = fieldNames.get(left1.getIndex()); translateOp2(op, name, rightLiteral); return true; case CAST: return translateBinary2(op, ((RexCall) left).operands.get(0), right); case ITEM: String itemName = MongoRules.isItem((RexCall) left); if (itemName != null) { translateOp2(op, itemName, rightLiteral); return true; } default: return false; } }
Source:
<code>private void enableLocation() { <START> AlertDialog.Builder dialog = new AlertDialog.Builder(this, <END> R.style.MaterialAlertDialogStyle); dialog.setTitle(getResources().getString(R.string.gps_network_not_enabled)); dialog.setMessage(getResources().getString(R.string.enable_location)); dialog.setPositiveButton(getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface paramDialogInterface, int paramInt) { Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(myIntent); } }); dialog.setNegativeButton(getString(R.string.Cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface paramDialogInterface, int paramInt) { paramDialogInterface.dismiss(); } }); dialog.show(); }</code><technical_language>recommended builder pattern for sake of readability. i.e. new AlertDialog.Builder(...) .setTitle(...) .setMessage(...) ... ;</technical_language>

Target:
private void enableLocation() { AlertDialog alertDialog = new AlertDialog.Builder(this, R.style.MaterialAlertDialogStyle) .setTitle(getResources().getString(R.string.gps_network_not_enabled)) .setMessage(getResources().getString(R.string.enable_location)) .setPositiveButton(getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface paramDialogInterface, int paramInt) { Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(myIntent); } }) .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface paramDialogInterface, int paramInt) { paramDialogInterface.dismiss(); } }) .create(); alertDialog.show(); }
Source:
<code>public static void add(NetworkResponse response, ImageRequest request) { if (request.getRequestTime() == -1) { return; } mImageTimings.add(Pair.create(response.data.length, request.getRequestTime())); log("NETMON", "Added image request : " + response.data.length + " bytes with time " + request.getRequestTime()); int byteSum = 0; int timeSum = 0; for (Pair<Integer, Long> entry : mImageTimings.getElements()) { log("NETMON", "Queue entry:: bytes:" + entry.first + " time(ms):" + entry.second); byteSum += entry.first; timeSum += entry.second; } if (mImageTimings.isFull()) { int bandwidthKBPS = (byteSum / timeSum); log("NETMON", "Derived bandwidth: " + bandwidthKBPS + "kB/s"); if (bandwidthKBPS < BANDWIDTH_HYSTERETIC_LOWER) { lowBandwidth = true; log("NETMON", "Low-Bandwidth flag On"); <START> } else if (bandwidthKBPS > BANDWIDTH_HYSTERETIC_UPPER && (!mIsRoaming || !mForceLowBandwidthIfRoaming)) { <END> lowBandwidth = false; log("NETMON", "Low-Bandwidth flag Off"); } } }</code><technical_language>Do !mIsRoaming && !mForceLowBandwidthIfRoaming instead? mForceLowBandwidthIfRoaming start out false, right</technical_language>

Target:
public static void add(NetworkResponse response, ImageRequest request) { if (request.getRequestTime() == -1) { return; } mImageTimings.add(Pair.create(response.data.length, request.getRequestTime())); log("NETMON", "Added image request : " + response.data.length + " bytes with time " + request.getRequestTime()); int byteSum = 0; int timeSum = 0; for (Pair<Integer, Long> entry : mImageTimings.getElements()) { log("NETMON", "Queue entry:: bytes:" + entry.first + " time(ms):" + entry.second); byteSum += entry.first; timeSum += entry.second; } if (mImageTimings.isFull()) { int bandwidthKBPS = (byteSum / timeSum); log("NETMON", "Derived bandwidth: " + bandwidthKBPS + "kB/s"); if (bandwidthKBPS < BANDWIDTH_HYSTERETIC_LOWER) { lowBandwidth = true; log("NETMON", "Low-Bandwidth flag On"); } else if (bandwidthKBPS > BANDWIDTH_HYSTERETIC_UPPER) { lowBandwidth = false; log("NETMON", "Low-Bandwidth flag Off"); } } }
Source:
<code>public boolean checkExists(Long transactorId) { <START> if (timeoutCache.getIfPresent(transactorId) != null) <END> return false; return cache.getCurrentData(TransactorID.getNodePath(config, transactorId)) != null; }</code><technical_language>sense modify usage of this cache. Transactors timed out "not exist" for transactions startTime of timeout. For newer transactions, timeout needs occur timeout cache is updated a newer time. This prevent rollbacks continuing occur transactors slow started function correctly again</technical_language>

Target:
public boolean checkExists(Long transactorId) { return cache.getCurrentData(TransactorID.getNodePath(config, transactorId)) != null; }
Source:
<code><START> protected void hookOnNext(ServiceBusReceivedMessageContext message) { <END> boolean delivered = false; if (currentWork == null) { currentWork = getNextWorkAndRequest(); logger.verbose("No current work, Picked up next receive request."); } if (currentWork != null) { currentWork.next(message); delivered = true; remaining.decrementAndGet(); if (currentWork.isTerminal()) { currentWork.complete(); if (timeoutOperation != null && !timeoutOperation.isDisposed()) { timeoutOperation.dispose(); } currentWork = getNextWorkAndRequest(); logger.verbose("Current work is terminal, Picked up next receive request."); } } if (currentWork == null) { if (wip.decrementAndGet() != 0) { logger.warning("There is another worker in drainLoop. But there should only be 1 worker."); } if (!delivered) { bufferMessages.add(message); } } }</code><technical_language>a lot of logic in this method hard debug in future... work? management of currentWork, emitting next work in a single place, drainQueue method. java @Override protected void hookOnNext(ServiceBusReceivedMessageContext message) { bufferMessages.add(message); drain(); }</technical_language>

Target:
protected void hookOnNext(ServiceBusReceivedMessageContext message) { bufferMessages.add(message); drain(); }
Source:
<code>private void checkCallContext() { if(this.callContext == null) <START> throw new InternalError("Can only call methods with single callcontext."); <END> }</code><technical_language>error easier understand if "Can call set get methods for call state a single CallContext" present, sounds methods limits</technical_language>

Target:
private void checkCallContext() { if(this.callContext == null) throw new InternalError("Can only call set and get methods for call state when using a single CallContext."); }
Source:
<code>public ItemUseHandler getItemHandler() { return e -> { Player p = e.getPlayer(); if (p.getFoodLevel() >= 2) { if (p.getInventory().getItemInMainHand().getType() != Material.SHEARS && p.getGameMode() != GameMode.CREATIVE) { FoodLevelChangeEvent event = new FoodLevelChangeEvent(p, p.getFoodLevel() - 2); Bukkit.getPluginManager().callEvent(event); <START> if (event.isCancelled()) { SlimefunPlugin.getLocalization().sendMessage(p, "messages.wind-staff-fail", true); return; } <END> p.setFoodLevel(event.getFoodLevel()); } p.setVelocity(p.getEyeLocation().getDirection().multiply(4)); p.getWorld().playSound(p.getLocation(), Sound.ENTITY_TNT_PRIMED, 1, 1); p.getWorld().playEffect(p.getLocation(), Effect.SMOKE, 1); p.setFallDistance(0F); } else { SlimefunPlugin.getLocalization().sendMessage(p, "messages.hungry", true); } }; }</code><technical_language>I send a message here, if FoodLevelChangeEvent cancelled, simply consume hunger points. wind staff fail, if event cancelled, this is server hunger system..</technical_language>

Target:
public ItemUseHandler getItemHandler() { return e -> { Player p = e.getPlayer(); if (p.getFoodLevel() >= 2) { if (p.getInventory().getItemInMainHand().getType() != Material.SHEARS && p.getGameMode() != GameMode.CREATIVE) { FoodLevelChangeEvent event = new FoodLevelChangeEvent(p, p.getFoodLevel() - 2); Bukkit.getPluginManager().callEvent(event); if (!event.isCancelled()) { p.setFoodLevel(event.getFoodLevel()); } } p.setVelocity(p.getEyeLocation().getDirection().multiply(4)); p.getWorld().playSound(p.getLocation(), Sound.ENTITY_TNT_PRIMED, 1, 1); p.getWorld().playEffect(p.getLocation(), Effect.SMOKE, 1); p.setFallDistance(0F); } else { SlimefunPlugin.getLocalization().sendMessage(p, "messages.hungry", true); } }; }
Source:
<code><START> public final String getUsername() { <END> return username; }</code><technical_language>Oops, I meant accessors in abstract chat message class overridden. undo of for in abstract class</technical_language>

Target:
public String getUsername() { return username; }
Source:
<code>public void testConnection() { <START> } <END></code><technical_language>do a bit here</technical_language>

Target:
public void testConnection() { try { getClient().execute(new OpenStackRequest<>(getClient(), HttpMethod.GET, "", null, null)); } catch (RuntimeException e) { throw new VdcBLLException(VdcBllErrors.PROVIDER_FAILURE, e); } }
Source:
<code>public void onEvent(ActivitiEvent event) { <START> if (event.getType().equals(ActivitiEventType.JOB_RETRIES_DECREMENTED)) { <END> if (event instanceof ActivitiEntityEvent && DeadLetterJobEntity.class.isAssignableFrom(((ActivitiEntityEvent) event).getEntity().getClass()) && ((DeadLetterJobEntityImpl)((ActivitiEntityEvent) event).getEntity()).getJobType().equals("timer")) { converter.from((ActivitiEntityEvent) event) .ifPresent(convertedEvent -> { for (BPMNElementEventListener<BPMNTimerRetriesDecrementedEvent> listener : processRuntimeEventListeners) { listener.onEvent(convertedEvent); } }); } } }</code><technical_language>necessary</technical_language>

Target:
public void onEvent(ActivitiEvent event) { converter.from(event) .ifPresent(convertedEvent -> { for (BPMNElementEventListener<BPMNTimerRetriesDecrementedEvent> listener : processRuntimeEventListeners) { listener.onEvent(convertedEvent); } }); }
Source:
<code><START> protected String generateSlug(Id id) { <END> return "app-" + idCodec.encode(id.toBigInteger()); }</code><technical_language>If store Application a slug this abstract implementation control rely implementation calling this method</technical_language>

Target:
private String generateSlug(Id id) { return "app-" + idCodec.encode(id.toBigInteger()); }
Source:
<code>public void testMonitor() throws Exception { MonitorScheduler monitorScheduler = EasyMock.createNiceMock(MonitorScheduler.class); Capture<? extends Monitor> monitorCapture = Capture.newInstance(); monitorScheduler.addMonitor(EasyMock.capture(monitorCapture)); EasyMock.expectLastCall().once(); EasyMock.replay(monitorScheduler); MemcachedCache cache = MemcachedCache.create(memcachedCacheConfig, monitorScheduler); EasyMock.verify(monitorScheduler); Assert.assertTrue(monitorCapture.hasCaptured()); final Monitor monitor = monitorCapture.getValue(); monitor.start(); Assert.assertNotNull(monitor); Emitter emitter = EasyMock.createNiceMock(Emitter.class); final Collection<Event> events = new ArrayList<>(); final ServiceEmitter serviceEmitter = new ServiceEmitter("service", "host", emitter) { @Override public void emit(Event event) { events.add(event); } }; while (events.isEmpty()) { Thread.sleep(memcachedCacheConfig.getTimeout()); Assert.assertTrue(monitor.monitor(serviceEmitter)); } Assert.assertFalse(events.isEmpty()); ObjectMapper mapper = new DefaultObjectMapper(); for (Event event : events) { <START> log.info("Found event `%s`", mapper.writeValueAsString(event.toMap())); <END> } }</code><technical_language>do need logging in tests if check values</technical_language>

Target:
public void testMonitor() throws Exception { MonitorScheduler monitorScheduler = EasyMock.createNiceMock(MonitorScheduler.class); Capture<? extends Monitor> monitorCapture = Capture.newInstance(); monitorScheduler.addMonitor(EasyMock.capture(monitorCapture)); EasyMock.expectLastCall().once(); EasyMock.replay(monitorScheduler); MemcachedCache cache = MemcachedCache.create(memcachedCacheConfig, monitorScheduler); EasyMock.verify(monitorScheduler); Assert.assertTrue(monitorCapture.hasCaptured()); final Monitor monitor = monitorCapture.getValue(); monitor.start(); Assert.assertNotNull(monitor); Emitter emitter = EasyMock.createNiceMock(Emitter.class); final Collection<Event> events = new ArrayList<>(); final ServiceEmitter serviceEmitter = new ServiceEmitter("service", "host", emitter) { @Override public void emit(Event event) { events.add(event); } }; while (events.isEmpty()) { Thread.sleep(memcachedCacheConfig.getTimeout()); Assert.assertTrue(monitor.monitor(serviceEmitter)); } Assert.assertFalse(events.isEmpty()); ObjectMapper mapper = new DefaultObjectMapper(); for (Event event : events) { log.debug("Found event `%s`", mapper.writeValueAsString(event.toMap())); } }
Source:
<code>protected String getSpanName() { <START> String spanName = this.name != null ? this.name : SpanNameRetrievalUtil.getSpanName(this.delegate); <END> if (isDefaultToString(spanName)) { return "async"; } return spanName; }</code><technical_language>collapse this logic span namer.. ex. java if (this.name != null) return this.name; return spanNamer.name(this.delegate, "async"); // param is fallback default;</technical_language>

Target:
protected String getSpanName() { if (this.name != null) { return this.name; } return this.spanNamer.name(this.delegate, "async"); }
Source:
<code>public void testSingleDynamicFormSelectForm() throws Exception { if (!endToEndTestEnabled()) { return; } try { createNewNote(); setTextOfParagraph(1, "%spark println(\"Howdy \"+z.select(\"names\", Seq((\"1\",\"Alice\"), " + "(\"2\",\"Bob\"),(\"3\",\"stranger\"))))"); runParagraph(1); waitForParagraph(1, "FINISHED"); collector.checkThat("Output text should not display any of the options in select form", driver.findElement(By.xpath(getParagraphXPath(1) + " CoreMatchers.equalTo("Howdy ")); Select dropDownMenu = new Select(driver.findElement(By.xpath((getParagraphXPath(1) + " dropDownMenu.selectByVisibleText("Alice"); collector.checkThat("After selection in drop down menu, output should not display any of the options", driver.findElement(By.xpath(getParagraphXPath(1) + " CoreMatchers.equalTo("Howdy ")); runParagraph(1); waitForParagraph(1, "FINISHED"); <START> collector.checkThat("Only after paragraph run we should see the new output including the selected option", <END> driver.findElement(By.xpath(getParagraphXPath(1) + " CoreMatchers.equalTo("Howdy 1")); deleteTestNotebook(driver); } catch (Exception e) { handleException("Exception in ParagraphActionsIT while testSingleDynamicFormTextInput ", e); } }</code><technical_language>"Only paragraph run ~" -> "Only running paragraph, new output ~"</technical_language>

Target:
public void testSingleDynamicFormSelectForm() throws Exception { if (!endToEndTestEnabled()) { return; } try { createNewNote(); setTextOfParagraph(1, "%spark println(\"Howdy \"+z.select(\"names\", Seq((\"1\",\"Alice\"), " + "(\"2\",\"Bob\"),(\"3\",\"stranger\"))))"); runParagraph(1); waitForParagraph(1, "FINISHED"); collector.checkThat("Output text should not display any of the options in select form", driver.findElement(By.xpath(getParagraphXPath(1) + " CoreMatchers.equalTo("Howdy ")); Select dropDownMenu = new Select(driver.findElement(By.xpath("(" + (getParagraphXPath(1) + " dropDownMenu.selectByVisibleText("Alice"); collector.checkThat("After selection in drop down menu, output should display the newly selected option", driver.findElement(By.xpath(getParagraphXPath(1) + " CoreMatchers.equalTo("Howdy 1")); driver.findElement(By.xpath(getParagraphXPath(1) + " clickAndWait(By.xpath(getParagraphXPath(1) + " Select sameDropDownMenu = new Select(driver.findElement(By.xpath("(" + (getParagraphXPath(1) + " sameDropDownMenu.selectByVisibleText("Bob"); collector.checkThat("After 'Run on selection change' checkbox is unchecked, the paragraph should not run if selecting a different option", driver.findElement(By.xpath(getParagraphXPath(1) + " CoreMatchers.equalTo("Howdy 1")); deleteTestNotebook(driver); } catch (Exception e) { handleException("Exception in ParagraphActionsIT while testSingleDynamicFormSelectForm ", e); } }
Source:
<code>private Action getCumulativeAction() { Action action = new <START> Action("Cumulative Counters Action", IAction.AS_CHECK_BOX) <END> { @Override public void run() { TmfXYChartViewer chart = getChartViewer(); if (chart instanceof CounterChartViewer) { ((CounterChartViewer) chart).toggleCumulative(); } } }; action.setToolTipText("Activate cumulative counters"); action.setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin("org.eclipse.tracecompass.tmf.ui", "icons/elcl16/sigma.gif")); return action; }</code><technical_language>externalize string</technical_language>

Target:
private Action getCumulativeAction() { Action action = new Action(Messages.CounterView_CumulativeAction_Text, IAction.AS_CHECK_BOX) { private boolean isCumulative = false; @Override public void run() { isCumulative ^= true; setToolTipText(isCumulative ? Messages.CounterView_CumulativeAction_DifferentialTooltipText : Messages.CounterView_CumulativeAction_CumulativeTooltipText); TmfXYChartViewer chart = getChartViewer(); if (chart instanceof CounterChartViewer) { ((CounterChartViewer) chart).toggleCumulative(); } } }; action.setToolTipText(Messages.CounterView_CumulativeAction_CumulativeTooltipText); action.setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin("org.eclipse.tracecompass.tmf.ui", "icons/elcl16/sigma.gif")); return action; }
Source:
<code>private static List<String> checkNonNullUniqueNames(final List<String> input, final String roleName) { if (input == null) { return null; } <START> Utils.validateArg(input.stream().noneMatch(Objects::isNull), () -> <END> String.format("the input %s list must not contain nulls", roleName)); Utils.validateArg(input.stream().sorted().distinct().count() == input.size(), () -> String.format("the input %s list must not contain repeats", roleName)); return Collections.unmodifiableList(new ArrayList<>(input)); }</code><technical_language>I slightly clearer Utils.containsNoNull</technical_language>

Target:
private static List<String> checkNonNullUniqueNames(final List<String> input, final String roleName) { if (input == null) { return null; } Utils.containsNoNull(input, String.format("the input %s list must not contain nulls", roleName)); Utils.validateArg(input.stream().sorted().distinct().count() == input.size(), () -> String.format("the input %s list must not contain repeats", roleName)); return Collections.unmodifiableList(new ArrayList<>(input)); }
Source:
<code>public static UserTrades adaptTradeHistoryV2( List<org.knowm.xchange.bitfinex.v2.dto.trade.Trade> trades) { List<UserTrade> pastTrades = new ArrayList<>(trades.size()); for (org.knowm.xchange.bitfinex.v2.dto.trade.Trade trade : trades) { OrderType orderType = trade.getExecAmount().signum() <= 0 ? OrderType.BID : OrderType.ASK; BigDecimal amount = trade.getExecAmount().signum() == -1 ? trade.getExecAmount().negate() : trade.getExecAmount(); Date timestamp = DateUtils.fromMillisUtc(trade.getTimestamp()); final BigDecimal fee = trade.getFee() != null ? trade.getFee().negate() : null; pastTrades.add( <START> new UserTrade( <END> orderType, amount, adaptCurrencyPair(trade.getSymbol()), trade.getExecPrice(), timestamp, trade.getId(), trade.getOrderId(), fee, Currency.getInstance(trade.getFeeCurrency()))); } return new UserTrades(pastTrades, TradeSortType.SortByTimestamp); }</code><technical_language>please UserTrade.Builder</technical_language>

Target:
public static UserTrades adaptTradeHistoryV2( List<org.knowm.xchange.bitfinex.v2.dto.trade.Trade> trades) { List<UserTrade> pastTrades = new ArrayList<>(trades.size()); for (org.knowm.xchange.bitfinex.v2.dto.trade.Trade trade : trades) { OrderType orderType = trade.getExecAmount().signum() >= 0 ? OrderType.BID : OrderType.ASK; BigDecimal amount = trade.getExecAmount().signum() == -1 ? trade.getExecAmount().negate() : trade.getExecAmount(); final BigDecimal fee = trade.getFee() != null ? trade.getFee().negate() : null; pastTrades.add( new UserTrade.Builder() .type(orderType) .originalAmount(amount) .currencyPair(adaptCurrencyPair(trade.getSymbol())) .price(trade.getExecPrice()) .timestamp(trade.getTimestamp()) .id(trade.getId()) .orderId(trade.getOrderId()) .feeAmount(fee) .feeCurrency(Currency.getInstance(trade.getFeeCurrency())) .build()); } return new UserTrades(pastTrades, TradeSortType.SortByTimestamp); }
Source:
<code>public <KeyType> String chooseNode(Set<String> nodeIds, byte[] key) { if (nodeIds.isEmpty()) { return null; } Long2ObjectRBTreeMap<String> weights = new Long2ObjectRBTreeMap<>(); weights.defaultReturnValue(null); for (String nodeId : nodeIds) { <START> HashCode keyHash = HASH_FN.hashBytes(key); <END> HashCode nodeHash = HASH_FN.hashString(nodeId, Charsets.UTF_8); List<HashCode> hashes = Lists.newArrayList(nodeHash, keyHash); HashCode combinedHash = Hashing.combineOrdered(hashes); weights.put(combinedHash.asLong(), nodeId); } return weights.get(weights.lastLongKey()); }</code><technical_language>this computed of for loop once</technical_language>

Target:
public <KeyType> String chooseNode(Set<String> nodeIds, byte[] key) { if (nodeIds.isEmpty()) { return null; } final HashCode keyHash = HASH_FN.hashBytes(key); long maxHash = Long.MIN_VALUE; String maxNode = null; for (String nodeId : nodeIds) { HashCode nodeHash = HASH_FN.hashString(nodeId, Charsets.UTF_8); List<HashCode> hashes = Lists.newArrayList(nodeHash, keyHash); long combinedHash = Hashing.combineOrdered(hashes).asLong(); if (maxNode == null) { maxHash = combinedHash; maxNode = nodeId; } else if (combinedHash > maxHash) { maxHash = combinedHash; maxNode = nodeId; } } return maxNode; }
Source:
<code>public void testAddBucketAcl() throws Exception { OzoneBucket ozoneBucket = setupBucket(); String remoteUserName = "remoteUser"; OzoneAcl defaultUserAcl = new OzoneAcl(USER, remoteUserName, READ, DEFAULT); OzoneObj ozoneObj = OzoneObjInfo.Builder.newBuilder() .setResType(OzoneObj.ResourceType.BUCKET) .setStoreType(OzoneObj.StoreType.OZONE) .setVolumeName(ozoneBucket.getVolumeName()) .setBucketName(ozoneBucket.getName()).build(); boolean addAcl = objectStore.addAcl(ozoneObj, defaultUserAcl); Assert.assertTrue(addAcl); <START> ozoneBucket.addAcls(Collections.singletonList(defaultUserAcl)); <END> List<OzoneAcl> acls = objectStore.getAcl(ozoneObj); Assert.assertTrue(containsAcl(defaultUserAcl, acls)); addAcl = objectStore.addAcl(ozoneObj, defaultUserAcl); Assert.assertFalse(addAcl); defaultUserAcl = new OzoneAcl(USER, remoteUserName, WRITE, DEFAULT); addAcl = objectStore.addAcl(ozoneObj, defaultUserAcl); Assert.assertTrue(addAcl); }</code><technical_language>need remove OzoneBucket#addAcls API is legacy impl based BucketManager#SetProperty. switch setAcls(), existing acls preserved correctly. rename this API setAcls remove it</technical_language>

Target:
public void testAddBucketAcl() throws Exception { OzoneBucket ozoneBucket = setupBucket(); String remoteUserName = "remoteUser"; OzoneAcl defaultUserAcl = new OzoneAcl(USER, remoteUserName, READ, DEFAULT); OzoneObj ozoneObj = OzoneObjInfo.Builder.newBuilder() .setResType(OzoneObj.ResourceType.BUCKET) .setStoreType(OzoneObj.StoreType.OZONE) .setVolumeName(ozoneBucket.getVolumeName()) .setBucketName(ozoneBucket.getName()).build(); boolean addAcl = objectStore.addAcl(ozoneObj, defaultUserAcl); Assert.assertTrue(addAcl); List<OzoneAcl> acls = objectStore.getAcl(ozoneObj); Assert.assertTrue(containsAcl(defaultUserAcl, acls)); addAcl = objectStore.addAcl(ozoneObj, defaultUserAcl); Assert.assertFalse(addAcl); defaultUserAcl = new OzoneAcl(USER, remoteUserName, WRITE, DEFAULT); addAcl = objectStore.addAcl(ozoneObj, defaultUserAcl); Assert.assertTrue(addAcl); }
Source:
<code>protected Pair<OAuth20AccessToken, OAuth20RefreshToken> generateAccessTokenOAuthGrantTypes(final AccessTokenRequestDataHolder holder) { LOGGER.debug("Creating access token for [{}]", holder.getService()); val clientId = holder.getRegisteredService().getClientId(); val authn = DefaultAuthenticationBuilder .newInstance(holder.getAuthentication()) .addAttribute(OAuth20Constants.GRANT_TYPE, holder.getGrantType().toString()) .addAttribute(OAuth20Constants.SCOPE, holder.getScopes()) .addAttribute(OAuth20Constants.CLIENT_ID, clientId) .addAttribute(OAuth20Constants.CLAIMS, holder.getClaims()) .build(); LOGGER.debug("Creating access token for [{}]", holder); val ticketGrantingTicket = holder.getTicketGrantingTicket(); val accessToken = this.accessTokenFactory.create(holder.getService(), authn, ticketGrantingTicket, holder.getScopes(), clientId, holder.getClaims()); LOGGER.debug("Created access token [{}]", accessToken); addTicketToRegistry(accessToken, ticketGrantingTicket); LOGGER.debug("Added access token to registry", accessToken); updateOAuthCode(holder, accessToken.getId()); val refreshToken = FunctionUtils.doIf(holder.isGenerateRefreshToken(), <START> () -> generateRefreshToken(holder, accessToken.getId()), <END> () -> { LOGGER.debug("Service is not able/allowed to receive refresh tokens", holder.getService()); return null; }).get(); return Pair.of(accessToken, refreshToken); }</code><technical_language>Pass access token, id in callee</technical_language>

Target:
protected Pair<OAuth20AccessToken, OAuth20RefreshToken> generateAccessTokenOAuthGrantTypes(final AccessTokenRequestDataHolder holder) { LOGGER.debug("Creating access token for [{}]", holder.getService()); val clientId = holder.getRegisteredService().getClientId(); val authn = DefaultAuthenticationBuilder .newInstance(holder.getAuthentication()) .addAttribute(OAuth20Constants.GRANT_TYPE, holder.getGrantType().toString()) .addAttribute(OAuth20Constants.SCOPE, holder.getScopes()) .addAttribute(OAuth20Constants.CLIENT_ID, clientId) .addAttribute(OAuth20Constants.CLAIMS, holder.getClaims()) .build(); LOGGER.debug("Creating access token for [{}]", holder); val ticketGrantingTicket = holder.getTicketGrantingTicket(); val accessToken = this.accessTokenFactory.create(holder.getService(), authn, ticketGrantingTicket, holder.getScopes(), clientId, holder.getClaims()); LOGGER.debug("Created access token [{}]", accessToken); addTicketToRegistry(accessToken, ticketGrantingTicket); LOGGER.debug("Added access token to registry", accessToken); updateOAuthCode(holder, accessToken); val refreshToken = FunctionUtils.doIf(holder.isGenerateRefreshToken(), () -> generateRefreshToken(holder, accessToken), () -> { LOGGER.debug("Service is not able/allowed to receive refresh tokens", holder.getService()); return null; }).get(); return Pair.of(accessToken, refreshToken); }
Source:
<code>public final void testConsumerNotTransitionsToProcessingWhenInitializationFails() { ExecutorService failingService = spy(executorService); ShardConsumer consumer = new ShardConsumer(recordsPublisher, failingService, shardInfo, logWarningForTaskAfterMillis, shardConsumerArgument, blockedOnParentsState, t -> t, 1, taskExecutionListener, 0); mockSuccessfulUnblockOnParents(); mockSuccessfulInitializeWithFailureTransition(); mockSuccessfulProcessing(null); <START> doCallRealMethod() <END> .doThrow(new RejectedExecutionException()) .when(failingService).execute(any()); int arbitraryExecutionCount = 5; do { try { consumer.executeLifecycle(); Thread.sleep(100); } catch (Exception e) { } } while (--arbitraryExecutionCount > 0); assertEquals(ShardConsumerState.INITIALIZING.consumerState().state(), consumer.currentState().state()); }</code><technical_language>this test supposed test behavior of ShardConsumer failures executorservice is able handle submissions of runnables? Testing multithreaded behavior in unit tests is generally recommended. mocking executorservice work in this scenario</technical_language>

Target:
public final void testConsumerNotTransitionsToProcessingWhenInitializationFails() { ExecutorService failingService = spy(executorService); ShardConsumer consumer = new ShardConsumer(recordsPublisher, failingService, shardInfo, logWarningForTaskAfterMillis, shardConsumerArgument, blockedOnParentsState, t -> t, 1, taskExecutionListener, 0); mockSuccessfulUnblockOnParents(); mockSuccessfulInitializeWithFailureTransition(); mockSuccessfulProcessing(null); doAnswer(invocation -> directlyExecuteRunnable(invocation)) .doThrow(new RejectedExecutionException()) .when(failingService).execute(any()); int arbitraryExecutionCount = 5; do { try { consumer.executeLifecycle(); } catch (Exception e) { fail("Unexpected exception while executing consumer lifecycle"); } } while (--arbitraryExecutionCount > 0); assertEquals(ShardConsumerState.INITIALIZING.consumerState().state(), consumer.currentState().state()); verify(failingService, times(5)).execute(any()); }