auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void checkElement(ProblemsHolder holder, String type, GoNamedElement namedElement, int index) { if (index < 1) { return; } if (!StringUtil.isCapitalized(namedElement.getName())) { return; } String errorText = "Exported " + type + " '" + namedElement.getName() + "' should have its own declaration"; holder.registerProblem(namedElement, errorText, ProblemHighlightType.WEAK_WARNING); }

Target:
public static void checkElement(ProblemsHolder holder, String type, GoNamedElement namedElement, int index) { if (index < 1 || !namedElement.isPublic()) { return; } String errorText = "Exported " + type + " '" + namedElement.getName() + "' should have its own declaration"; holder.registerProblem(namedElement, errorText, ProblemHighlightType.WEAK_WARNING, new MyLocalQuickFixBase(index)); }
Source:
public MavenWorkspaceRepository() { super(); collect(); list = Memoize.supplier(() -> list0()); }

Target:
public MavenWorkspaceRepository() { super(); collect(); list = memoize(this::list0); }
Source:
public SystemViewAdapter(String name, String desc, Class<R> rowCls, SystemViewRowAttributeWalker<R> walker, Supplier<Collection<D>> dataSupplier, Function<D, R> rowFunc) { A.notNull(rowCls, "rowCls"); A.notNull(walker, "walker"); this.name = name; this.desc = desc; this.rowCls = rowCls; this.walker = walker; this.data = null; this.dataSupplier = dataSupplier; this.rowFunc = rowFunc; }

Target:
public SystemViewAdapter(String name, String desc, Class<R> rowCls, SystemViewRowAttributeWalker<R> walker, Supplier<Collection<D>> dataSupplier, Function<D, R> rowFunc) { super(name, desc, rowCls, walker); A.notNull(dataSupplier, "dataSupplier"); A.notNull(rowCls, "rowCls"); this.dataSupplier = dataSupplier; this.rowFunc = rowFunc; }
Source:
public JGroupsTopologyAwareAddress doReadObject(ObjectInput unmarshaller) throws IOException, ClassNotFoundException { try { ExtendedUUID jgroupsAddress = (ExtendedUUID) org.jgroups.util.Util.readAddress(unmarshaller); return (JGroupsTopologyAwareAddress) JGroupsAddressCache.fromJGroupsAddressUnchecked(jgroupsAddress); } catch (Exception e) { throw new IOException(e); } }

Target:
public JGroupsTopologyAwareAddress doReadObject(ObjectInput unmarshaller) throws IOException, ClassNotFoundException { try { org.jgroups.Address jgroupsAddress = (org.jgroups.Address) org.jgroups.util.Util.readAddress(unmarshaller); return (JGroupsTopologyAwareAddress) JGroupsAddressCache.fromJGroupsAddress(jgroupsAddress); } catch (Exception e) { throw new IOException(e); } }
Source:
public void actionPerformed(ActionEvent e) { File file = FileChooserService.getSelectedFile("pdf", "PDF files", DialogType.PDF, false); int reply = JOptionPane.NO_OPTION; if (file != null) { if (file.toString().endsWith(".pdf")) { file = new File(file.toString().substring(0, file.toString().length() - 4)); } File v_overwriting = new File(file.toString() + ".pdf"); while (v_overwriting.exists() && reply == JOptionPane.NO_OPTION) { reply = JOptionPane.showConfirmDialog(null, "The selected file already exists. Do you want to overwrite it?", "File already exists.", JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.NO_OPTION) { file = FileChooserService.getSelectedFile("pdf", "PDF files", DialogType.PDF, false); if (file != null) { if (file.toString().endsWith(".pdf")) { file = new File(file.toString().substring(0, file.toString().length() - 4)); } v_overwriting = new File(file.toString() + ".pdf"); } else return; } } } if (file == null) return; String filename = file.getName(); LOGGER.log("Invoking pdflatex"); CommandLineExecutor.executeGeneratePDF(new CommandLineBuilder() .withPathToSource(ApplicationUtils.getTempSourceFile()) .withOutputDirectory(file.getParentFile().getAbsolutePath()) .withJobname(filename) .withWorkingFile(etc.getCurrentFile()) .withLatexPath(etc.getLatexPath()) .withLogger(new ApplicationLogger("pdflatex"))); }

Target:
public void actionPerformed(ActionEvent e) { File file = FileChooserService.getSelectedFile("pdf", "PDF files", DialogType.PDF, false); int reply = JOptionPane.NO_OPTION; if (file != null) { if (file.toString().endsWith(".pdf")) { file = new File(file.toString().substring(0, file.toString().length() - 4)); } File v_overwriting = new File(file.toString() + ".pdf"); while (v_overwriting.exists() && reply == JOptionPane.NO_OPTION) { reply = JOptionPane.showConfirmDialog(null, v_overwriting.toString() + " already exists. Do you want to overwrite it?", "File already exists.", JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.NO_OPTION) { file = FileChooserService.getSelectedFile("pdf", "PDF files", DialogType.PDF, false); if (file != null) { if (file.toString().endsWith(".pdf")) { file = new File(file.toString().substring(0, file.toString().length() - 4)); } v_overwriting = new File(file.toString() + ".pdf"); } else return; } } } if (file == null) return; String filename = file.getName(); LOGGER.log("Invoking pdflatex"); CommandLineExecutor.executeGeneratePDF(new CommandLineBuilder() .withPathToSource(ApplicationUtils.getTempSourceFile()) .withOutputDirectory(file.getParentFile().getAbsolutePath()) .withJobname(filename) .withWorkingFile(etc.getCurrentFile()) .withLatexPath(etc.getLatexPath()) .withLogger(new ApplicationLogger("pdflatex"))); }
Source:
public void saveFields() { String[] lines = fieldsText.get().split("\n"); int i = 0; for (; i < lines.length; i++) { String[] parts = lines[i].split(":"); if (parts.length != 2) { String field = Localization.lang("field"); String title = Localization.lang("Error"); String content = Localization.lang("Each line must be of the following form") + " '" + Localization.lang("Tabname") + ':' + field + "1;" + field + "2;...;" + field + "N'"; dialogService.showInformationDialogAndWait(title, content); return; } String testString = BibtexKeyGenerator.cleanKey(parts[1], Globals.prefs.get(JabRefPreferences.DEFAULT_UNWANTED_BIBTEX_KEY_CHARACTERS)); if (!testString.equals(parts[1]) || (parts[1].indexOf('&') >= 0)) { String title = Localization.lang("Error"); String content = Localization.lang("Field names are not allowed to contain white space or the following " + "characters") + "{ } ( ) , = \\ \" # % ~ '"; dialogService.showInformationDialogAndWait(title, content); return; } preferences.setCustomTabsNameAndFields(parts[0], parts[1], i); } preferences.purgeSeries(JabRefPreferences.CUSTOM_TAB_NAME, i); preferences.purgeSeries(JabRefPreferences.CUSTOM_TAB_FIELDS, i); preferences.updateEntryEditorTabList(); }

Target:
public void saveFields() { Map<String, Set<Field>> customTabsMap = new LinkedHashMap<>(); String[] lines = fieldsText.get().split("\n"); for (String line : lines) { String[] parts = line.split(":"); if (parts.length != 2) { dialogService.showInformationDialogAndWait( Localization.lang("Error"), Localization.lang("Each line must be of the following form: 'tab:field1;field2;...;fieldN'.")); return; } String testString = BibtexKeyGenerator.cleanKey(parts[1], preferences.getUnwantedCharacters()); if (!testString.equals(parts[1]) || (parts[1].indexOf('&') >= 0)) { dialogService.showInformationDialogAndWait( Localization.lang("Error"), Localization.lang("Field names are not allowed to contain white spaces or certain characters (%0).", "# { } ( ) ~ , ^ & - \" ' ` ʹ \\")); return; } customTabsMap.put(parts[0], FieldFactory.parseFieldList(parts[1])); } preferences.storeEntryEditorTabList(customTabsMap); }
Source:
static boolean isCompanyPortalInstalled(final PackageManager pkgManager) { return isPackageInstalled(pkgManager, "com.microsoft.windowsintune.companyportal"); }

Target:
static boolean isCompanyPortalInstalled(final PackageManager pkgManager) { return isPackageInstalled(pkgManager, COMPANY_PORTAL_APP_PACKAGE_NAME); }
Source:
public void testOpenSessionEditorByDoubleClick3() { designerProject.convertToModelingProject(); SWTBotView modelExplorerView = bot.viewById(IModelExplorerView.ID); modelExplorerView.setFocus(); SWTBot packageExplorerViewBot = modelExplorerView.bot(); SWTBotTreeItem expandedNode = packageExplorerViewBot.tree().expandNode("DesignerTestProject", true); SWTBotTreeItem node = expandedNode.getNode("My.aird"); node.doubleClick(); bot.waitUntil(new DefaultCondition() { @Override public boolean test() throws Exception { return PlatformUI.getWorkbench().getWorkbenchWindows()[0].getActivePage().getActiveEditor() != null; } @Override public String getFailureMessage() { return "Wrong Active editor is : " + PlatformUI.getWorkbench().getWorkbenchWindows()[0].getActivePage().getActiveEditor().getEditorSite().getId(); } }); assertEquals("The session editor has not opened.", "org.eclipse.sirius.ui.editor.session", PlatformUI.getWorkbench().getWorkbenchWindows()[0].getActivePage().getActiveEditor().getEditorSite().getId()); }

Target:
public void testOpenSessionEditorByDoubleClick3() { designerProject.convertToModelingProject(); SWTBotView modelExplorerView = bot.viewById(IModelExplorerView.ID); modelExplorerView.setFocus(); SWTBot packageExplorerViewBot = modelExplorerView.bot(); assertSessionEditorOpened(packageExplorerViewBot); }
Source:
protected void onItemsFetched(BoxResponse response) { if (!response.isSuccess()) { checkConnectivity(); return; } ArrayList<String> removeIds = new ArrayList<String>(1); removeIds.add(BoxSearchAdapter.LOAD_MORE_ID); mAdapter.remove(removeIds); if (response.getResult() instanceof BoxIteratorItems) { if (((BoxRequestsSearch.Search) response.getRequest()).getOffset() == 0) { BoxIteratorItems items = (BoxIteratorItems) response.getResult(); updateTo(items.getEntries()); mOffset = 0; } else { BoxIteratorItems items = (BoxIteratorItems) response.getResult(); updateItems(items.getEntries()); mOffset += items.size(); if (items.fullSize() != null && mOffset < items.fullSize()) { mOffset = calculateBestOffset(mOffset, mLimit); BoxRequestsSearch.Search incrementalSearchTask = mRequest .setOffset(mOffset) .setLimit(mLimit); ((BoxSearchAdapter) mAdapter).addLoadMoreItem(incrementalSearchTask); } } } mSwipeRefresh.setRefreshing(false); }

Target:
protected void onItemsFetched(BoxResponse response) { if (!response.isSuccess()) { checkConnectivity(); return; } ArrayList<String> removeIds = new ArrayList<String>(1); removeIds.add(BoxSearchAdapter.LOAD_MORE_ID); mAdapter.remove(removeIds); if (response.getResult() instanceof BoxIteratorItems) { BoxIteratorItems items = (BoxIteratorItems) response.getResult(); if (((BoxRequestsSearch.Search) response.getRequest()).getOffset() == 0) { mOffset = 0; updateTo(items.getEntries()); } else { updateItems(items.getEntries()); } mOffset += items.size(); if (items.fullSize() != null && mOffset < items.fullSize()) { mOffset = calculateBestOffset(mOffset, mLimit); BoxRequestsSearch.Search incrementalSearchTask = mRequest .setOffset(mOffset) .setLimit(mLimit); ((BoxSearchAdapter) mAdapter).addLoadMoreItem(incrementalSearchTask); } } mSwipeRefresh.setRefreshing(false); }
Source:
public SortedMap<Long, List<List<Integer>>> getPalindromeProductsWithFactors(int minFactor, int maxFactor) { if(minFactor > maxFactor) throw new IllegalArgumentException("invalid input: min is " + minFactor + " and max is " + maxFactor); SortedMap<Long, List<List<Integer>>> palindromeSortedList = new TreeMap<>(); long num; List<List<Integer>> factors; for (int i = maxFactor; i >= minFactor; i--) { for (int j = maxFactor; j >= i; j--) { num = i * j; if (isPalindrome(num)) { factors = palindromeSortedList.get(num); if (factors == null) { factors = new ArrayList<>(); } factors.add(Arrays.asList(i, j)); palindromeSortedList.put(num, factors); } } } if(palindromeSortedList.size() == 0) throw new NoSuchElementException("no palindrome with factors in the range " + minFactor + " to " + maxFactor); return Collections.unmodifiableSortedMap(palindromeSortedList); }

Target:
public SortedMap<Long, List<List<Integer>>> getPalindromeProductsWithFactors(int minFactor, int maxFactor) { if(minFactor > maxFactor) { throw new IllegalArgumentException("invalid input: min is " + minFactor + " and max is " + maxFactor); } SortedMap<Long, List<List<Integer>>> palindromeSortedList = new TreeMap<>(); long num; List<List<Integer>> factors; for (int i = maxFactor; i >= minFactor; i--) { for (int j = maxFactor; j >= i; j--) { num = i * j; if (isPalindrome(num)) { factors = palindromeSortedList.get(num); if (factors == null) { factors = new ArrayList<>(); } factors.add(Arrays.asList(i, j)); palindromeSortedList.put(num, factors); } } } if(palindromeSortedList.size() == 0) { throw new NoSuchElementException("no palindrome with factors in the range " + minFactor + " to " + maxFactor); } return Collections.unmodifiableSortedMap(palindromeSortedList); }
Source:
protected void doGet(final CloudletTopic reqTopic, final KuraRequestPayload reqPayload, final KuraResponsePayload respPayload) { final String[] resources = reqTopic.getResources(); logger.info(message.cloudGETReqReceived()); if (resources.length != 1 || !ASSET_TOPIC_RESOURCE.equals(resources[0])) { respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_BAD_REQUEST); return; } this.findAssets(); JsonArray request; try { request = getRequestJsonArray(reqPayload); } catch (Exception e) { respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_BAD_REQUEST); return; } if (request == null || request.size() == 0) { getAssetMetadata(respPayload, this.assets.keySet().iterator()); return; } MetadataRequest parsedRequest; try { parsedRequest = new MetadataRequest(request); } catch (Exception e) { respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_BAD_REQUEST); return; } getAssetMetadata(respPayload, parsedRequest.getAssetNames().iterator()); }

Target:
protected void doGet(final CloudletTopic reqTopic, final KuraRequestPayload reqPayload, final KuraResponsePayload respPayload) { final String[] resources = reqTopic.getResources(); logger.info(message.cloudGETReqReceived()); if (resources.length != 1 || !ASSET_TOPIC_RESOURCE.equals(resources[0])) { respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_BAD_REQUEST); return; } this.findAssets(); JsonArray request; try { request = parseRequest(reqPayload); } catch (Exception e) { respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_BAD_REQUEST); return; } if (request == null || request.isEmpty()) { getAssetMetadata(respPayload, this.assets.keySet().iterator()); return; } MetadataRequest parsedRequest; try { parsedRequest = new MetadataRequest(request); } catch (Exception e) { respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_BAD_REQUEST); return; } getAssetMetadata(respPayload, parsedRequest.getAssetNames().iterator()); }
Source:
AwsS3Endpoints() { endpoints.put("ap-northeast-1", "s3-ap-northeast-1.amazonaws.com"); endpoints.put("ap-northeast-2", "s3-ap-northeast-2.amazonaws.com"); endpoints.put("ap-south-1", "s3-ap-south-1.amazonaws.com"); endpoints.put("ap-southeast-1", "s3-ap-southeast-1.amazonaws.com"); endpoints.put("ap-southeast-2", "s3-ap-southeast-2.amazonaws.com"); endpoints.put("eu-central-1", "s3-eu-central-1.amazonaws.com"); endpoints.put("eu-west-1", "s3-eu-west-1.amazonaws.com"); endpoints.put("eu-west-1", "s3-eu-west-1.amazonaws.com"); endpoints.put("sa-east-1", "s3-sa-east-1.amazonaws.com"); endpoints.put("us-west-1", "s3-us-west-1.amazonaws.com"); endpoints.put("us-west-2", "s3-us-west-2.amazonaws.com"); endpoints.put("us-east-1", "s3.amazonaws.com"); endpoints.put("us-east-2", "s3-us-east-2.amazonaws.com"); endpoints.put("ca-central-1", "s3.ca-central-1.amazonaws.com"); endpoints.put("cn-north-1", "s3.cn-north-1.amazonaws.com.cn"); }

Target:
AwsS3Endpoints() { endpoints.put("ap-northeast-1", "s3-ap-northeast-1.amazonaws.com"); endpoints.put("ap-northeast-2", "s3-ap-northeast-2.amazonaws.com"); endpoints.put("ap-south-1", "s3-ap-south-1.amazonaws.com"); endpoints.put("ap-southeast-1", "s3-ap-southeast-1.amazonaws.com"); endpoints.put("ap-southeast-2", "s3-ap-southeast-2.amazonaws.com"); endpoints.put("eu-central-1", "s3-eu-central-1.amazonaws.com"); endpoints.put("eu-west-1", "s3-eu-west-1.amazonaws.com"); endpoints.put("eu-west-2", "s3-eu-west-2.amazonaws.com"); endpoints.put("sa-east-1", "s3-sa-east-1.amazonaws.com"); endpoints.put("us-west-1", "s3-us-west-1.amazonaws.com"); endpoints.put("us-west-2", "s3-us-west-2.amazonaws.com"); endpoints.put("us-east-1", "s3.amazonaws.com"); endpoints.put("us-east-2", "s3-us-east-2.amazonaws.com"); endpoints.put("ca-central-1", "s3.ca-central-1.amazonaws.com"); endpoints.put("cn-north-1", "s3.cn-north-1.amazonaws.com.cn"); }
Source:
public Task<Void> delete(@NonNull Context context) { FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser(); if (currentUser == null) { return Tasks.forException(new FirebaseAuthInvalidUserException( String.valueOf(CommonStatusCodes.SIGN_IN_REQUIRED), "No currently signed in user.")); } Task<Void> deleteUserTask = currentUser.delete(); List<Credential> credentials = credentialsFromFirebaseUser(currentUser); CredentialsClient client; if (context instanceof Activity) { client = Credentials.getClient((Activity) context); } else { client = Credentials.getClient(context); } List<Task<?>> credentialTasks = new ArrayList<>(); for (Credential credential : credentials) { credentialTasks.add(client.delete(credential)); } final Task<Void> combinedCredentialTask = Tasks.whenAll(credentialTasks); return Tasks.whenAll(deleteUserTask, signOutIdps(context), combinedCredentialTask); }

Target:
public Task<Void> delete(@NonNull Context context) { final FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser(); if (currentUser == null) { return Tasks.forException(new FirebaseAuthInvalidUserException( String.valueOf(CommonStatusCodes.SIGN_IN_REQUIRED), "No currently signed in user.")); } final List<Credential> credentials = getCredentialsFromFirebaseUser(currentUser); final CredentialsClient client = GoogleApiUtils.getCredentialsClient(context); return signOutIdps(context).continueWithTask(new Continuation<Void, Task<Void>>() { @Override public Task<Void> then(@NonNull Task<Void> task) { task.getResult(); return currentUser.delete(); } }).continueWithTask(new Continuation<Void, Task<Void>>() { @Override public Task<Void> then(@NonNull Task<Void> task) { task.getResult(); List<Task<?>> credentialTasks = new ArrayList<>(); for (Credential credential : credentials) { credentialTasks.add(client.delete(credential)); } return Tasks.whenAll(credentialTasks) .continueWithTask(new Continuation<Void, Task<Void>>() { @Override public Task<Void> then(@NonNull Task<Void> task) { Exception e = task.getException(); Throwable t = e == null ? null : e.getCause(); if (!(t instanceof ApiException) || ((ApiException) t).getStatusCode() != CommonStatusCodes.CANCELED) { task.getResult(); } return Tasks.forResult(null); } }); } }); }
Source:
LuceneSearchResult<H> loadBlocking() { SearchProjectionTransformContext transformContext = extractContext.createProjectionTransformContext(); LoadingResult<?> loadingResult = extractContext.getProjectionHitMapper().loadBlocking( null ); int readIndex = 0; int writeIndex = 0; for ( ; readIndex < extractedData.size(); ++readIndex ) { transformContext.reset(); H transformed = transformUnsafe( rootProjection, loadingResult, extractedData.get( readIndex ), transformContext ); if ( transformContext.hasFailedLoad() ) { continue; } extractedData.set( writeIndex, transformed ); ++writeIndex; } if ( writeIndex < readIndex ) { extractedData.subList( writeIndex, readIndex ).clear(); } @SuppressWarnings("unchecked") List<H> loadedHits = Collections.unmodifiableList( (List<? extends H>) extractedData ); extractedData = null; return new LuceneSearchResultImpl<>( hitCount, loadedHits, extractedAggregations, took, timedOut ); }

Target:
LuceneSearchResult<H> loadBlocking() { SearchProjectionTransformContext transformContext = extractContext.createProjectionTransformContext(); LoadingResult<?> loadingResult = extractContext.getProjectionHitMapper().loadBlocking(); int readIndex = 0; int writeIndex = 0; for ( ; readIndex < extractedData.size(); ++readIndex ) { transformContext.reset(); H transformed = transformUnsafe( rootProjection, loadingResult, extractedData.get( readIndex ), transformContext ); if ( transformContext.hasFailedLoad() ) { continue; } extractedData.set( writeIndex, transformed ); ++writeIndex; } if ( writeIndex < readIndex ) { extractedData.subList( writeIndex, readIndex ).clear(); } @SuppressWarnings("unchecked") List<H> loadedHits = Collections.unmodifiableList( (List<? extends H>) extractedData ); extractedData = null; return new LuceneSearchResultImpl<>( hitCount, loadedHits, extractedAggregations, took, timedOut ); }
Source:
protected void preTick() { this.lock.lock(); try { this.condition.await(this.minimumTimeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { } catch (IllegalMonitorStateException e) { Sponge.getLogger().error("The scheduler internal state machine suffered a catastrophic error. Check #spongedev"); Sponge.getLogger().error(e.toString()); } }

Target:
protected void preTick() { this.lock.lock(); try { this.condition.await(this.minimumTimeout, TimeUnit.MILLISECONDS); } catch (InterruptedException ignored) { } catch (IllegalMonitorStateException e) { Sponge.getLogger().error("The scheduler internal state machine suffered a catastrophic error", e); } }
Source:
public void testPuts() { Mutation m = new Mutation(new Text("r1")); m.at().family(nt("cf1")).qualifier(nt("cq1")).set(nv("v1")); m.put(nt("cf2"), nt("cq2"), new ColumnVisibility("cv2"), nv("v2")); m.put(nt("cf3"), nt("cq3"), 3l, nv("v3")); m.put(nt("cf4"), nt("cq4"), new ColumnVisibility("cv4"), 4l, nv("v4")); m.putDelete(nt("cf5"), nt("cq5")); m.putDelete(nt("cf6"), nt("cq6"), new ColumnVisibility("cv6")); m.putDelete(nt("cf7"), nt("cq7"), 7l); m.putDelete(nt("cf8"), nt("cq8"), new ColumnVisibility("cv8"), 8l); assertEquals(8, m.size()); List<ColumnUpdate> updates = m.getUpdates(); assertEquals(8, m.size()); assertEquals(8, updates.size()); verifyColumnUpdate(updates.get(0), "cf1", "cq1", "", 0l, false, false, "v1"); verifyColumnUpdate(updates.get(1), "cf2", "cq2", "cv2", 0l, false, false, "v2"); verifyColumnUpdate(updates.get(2), "cf3", "cq3", "", 3l, true, false, "v3"); verifyColumnUpdate(updates.get(3), "cf4", "cq4", "cv4", 4l, true, false, "v4"); verifyColumnUpdate(updates.get(4), "cf5", "cq5", "", 0l, false, true, ""); verifyColumnUpdate(updates.get(5), "cf6", "cq6", "cv6", 0l, false, true, ""); verifyColumnUpdate(updates.get(6), "cf7", "cq7", "", 7l, true, true, ""); verifyColumnUpdate(updates.get(7), "cf8", "cq8", "cv8", 8l, true, true, ""); }

Target:
public void testPuts() { Mutation m = new Mutation(new Text("r1")); m.put(nt("cf1"), nt("cq1"), nv("v1")); m.put(nt("cf2"), nt("cq2"), new ColumnVisibility("cv2"), nv("v2")); m.put(nt("cf3"), nt("cq3"), 3l, nv("v3")); m.put(nt("cf4"), nt("cq4"), new ColumnVisibility("cv4"), 4l, nv("v4")); m.putDelete(nt("cf5"), nt("cq5")); m.putDelete(nt("cf6"), nt("cq6"), new ColumnVisibility("cv6")); m.putDelete(nt("cf7"), nt("cq7"), 7l); m.putDelete(nt("cf8"), nt("cq8"), new ColumnVisibility("cv8"), 8l); assertEquals(8, m.size()); List<ColumnUpdate> updates = m.getUpdates(); assertEquals(8, m.size()); assertEquals(8, updates.size()); verifyColumnUpdate(updates.get(0), "cf1", "cq1", "", 0l, false, false, "v1"); verifyColumnUpdate(updates.get(1), "cf2", "cq2", "cv2", 0l, false, false, "v2"); verifyColumnUpdate(updates.get(2), "cf3", "cq3", "", 3l, true, false, "v3"); verifyColumnUpdate(updates.get(3), "cf4", "cq4", "cv4", 4l, true, false, "v4"); verifyColumnUpdate(updates.get(4), "cf5", "cq5", "", 0l, false, true, ""); verifyColumnUpdate(updates.get(5), "cf6", "cq6", "cv6", 0l, false, true, ""); verifyColumnUpdate(updates.get(6), "cf7", "cq7", "", 7l, true, true, ""); verifyColumnUpdate(updates.get(7), "cf8", "cq8", "cv8", 8l, true, true, ""); }
Source:
public Expr apply(final List<Expr> args) { if (args.size() < 2 || args.size() > 3) { throw new IAE("Function[%s] must have 2 arguments", name()); } final Expr arg = args.get(0); final Expr patternExpr = args.get(1); if (!patternExpr.isLiteral() || !(patternExpr.getLiteralValue() == null || patternExpr.getLiteralValue() instanceof String)) { throw new IAE("Function[%s] pattern must be a string literal", name()); } final Pattern pattern = Pattern.compile( StringUtils.nullToEmptyNonDruidDataString((String) patternExpr.getLiteralValue()) ); class RegexpLikeExpr extends ExprMacroTable.BaseScalarUnivariateMacroFunctionExpr { private RegexpLikeExpr(Expr arg) { super(FN_NAME, arg); } @Nonnull @Override public ExprEval eval(final ObjectBinding bindings) { final String s = arg.eval(bindings).asString(); final Matcher matcher = pattern.matcher(NullHandling.nullToEmptyIfNeeded(s)); return ExprEval.of(matcher.find(), ExprType.LONG); } @Override public Expr visit(Shuttle shuttle) { Expr newArg = arg.visit(shuttle); return shuttle.visit(new RegexpLikeExpr(newArg)); } @Override public String stringify() { return StringUtils.format("%s(%s, %s)", FN_NAME, arg.stringify(), patternExpr.stringify()); } } return new RegexpLikeExpr(arg); }

Target:
public Expr apply(final List<Expr> args) { if (args.size() != 2) { throw new IAE("Function[%s] must have 2 arguments", name()); } final Expr arg = args.get(0); final Expr patternExpr = args.get(1); if (!ExprUtils.isStringLiteral(patternExpr)) { throw new IAE("Function[%s] pattern must be a string literal", name()); } final Pattern pattern = Pattern.compile( StringUtils.nullToEmptyNonDruidDataString((String) patternExpr.getLiteralValue()) ); class RegexpLikeExpr extends ExprMacroTable.BaseScalarUnivariateMacroFunctionExpr { private RegexpLikeExpr(Expr arg) { super(FN_NAME, arg); } @Nonnull @Override public ExprEval eval(final ObjectBinding bindings) { final String s = NullHandling.nullToEmptyIfNeeded(arg.eval(bindings).asString()); if (s == null) { return ExprEval.of(false, ExprType.LONG); } else { final Matcher matcher = pattern.matcher(s); return ExprEval.of(matcher.find(), ExprType.LONG); } } @Override public Expr visit(Shuttle shuttle) { Expr newArg = arg.visit(shuttle); return shuttle.visit(new RegexpLikeExpr(newArg)); } @Override public String stringify() { return StringUtils.format("%s(%s, %s)", FN_NAME, arg.stringify(), patternExpr.stringify()); } } return new RegexpLikeExpr(arg); }
Source:
public void testUpdateGlusterHook() { dao.updateGlusterHook(getGlusterHook()); GlusterHookEntity hook = dao.getById(FixturesTool.HOOK_ID); assertNotNull(hook); assertEquals(CHECKSUM, hook.getChecksum()); }

Target:
public void testUpdateGlusterHook() { GlusterHookEntity existingHook = getGlusterHook(); existingHook.setName(EXISTING_HOOK_NAME); dao.updateGlusterHook(getGlusterHook()); GlusterHookEntity hook = dao.getById(FixturesTool.HOOK_ID); assertNotNull(hook); assertEquals(existingHook, hook); }
Source:
public void readData(long n) { long curDataPoints = read.addAndGet(n); if (curDataPoints > 1_000_000) { long total = quotaWatchers.stream().map(QuotaWatcher::getReadData).reduce(0L, Long::sum); log.info("Total: {}; watchers: {}; Data points: {}; added: {}", total, quotaWatchers.size(), curDataPoints, n); } throwIfViolated(); dataInMemoryReporter.reportDataHasBeenRead(n); }

Target:
public void readData(long n) { long curDataPoints = read.addAndGet(n); if (curDataPoints > LOGLIMIT) { long total = quotaWatchers.stream().map(QuotaWatcher::getReadData) .reduce(0L, Long::sum); log.info("Data Points READ: Instance {}; This Query: {}; Delta: {}" + " (# Wathcers: {})", total, curDataPoints, n, quotaWatchers.size()); } throwIfViolated(); dataInMemoryReporter.reportDataHasBeenRead(n); }
Source:
public List<String> unapply(@Nullable final String value) { String valueToLookup = NullHandling.nullToEmptyIfNeeded(value); if (valueToLookup == null) { return Collections.EMPTY_LIST; } return Lists.newArrayList(Maps.filterKeys(map, key -> map.get(key).equals(valueToLookup)).keySet()); }

Target:
public List<String> unapply(@Nullable final String value) { String valueToLookup = NullHandling.nullToEmptyIfNeeded(value); if (valueToLookup == null) { return Collections.emptyList(); } return map.entrySet() .stream() .filter(entry -> entry.getValue().equals(valueToLookup)) .map(entry -> entry.getKey()) .collect(Collectors.toList()); }
Source:
private SSLContext buildSslContext() { SSLContext sslContext = null; try { SSLContextBuilder sslBuilder = sslContextBuilder; if (trustSelfSignCert) { if (sslBuilder != null) { throw new IllegalStateException("Cannot configure both SSLContextBuilder and TrustSelfSignCert"); } sslBuilder = SSLContexts.custom().loadTrustMaterial(TrustSelfSignedMultiChainStrategy.INSTANCE); } if (sslBuilder != null) { sslContext = sslBuilder.build(); } } catch (Exception e) { e.printStackTrace(); } return sslContext != null ? sslContext : SSLContexts.createDefault(); }

Target:
private SSLContext buildSslContext() { SSLContext sslContext = null; try { SSLContextBuilder sslBuilder = sslContextBuilder; if (trustSelfSignCert) { if (sslBuilder == null) { sslBuilder = SSLContexts.custom(); } sslBuilder.loadTrustMaterial(TrustSelfSignedMultiChainStrategy.INSTANCE); } if (sslBuilder != null) { sslContext = sslBuilder.build(); } } catch (Exception e) { e.printStackTrace(); } return sslContext != null ? sslContext : SSLContexts.createDefault(); }
Source:
private static void checkNotAdvertisedWants(UploadPack up, List<ObjectId> notAdvertisedWants, Set<ObjectId> reachableFrom) throws IOException { ObjectReader reader = up.getRevWalk().getObjectReader(); try (RevWalk walk = new RevWalk(reader)) { walk.setRetainBody(false); List<RevObject> wantsAsObjs = objectIdsToRevObjects(walk, notAdvertisedWants); List<RevCommit> wantsAsCommits = wantsAsObjs.stream() .filter(obj -> obj instanceof RevCommit) .map(obj -> (RevCommit) obj) .collect(Collectors.toList()); boolean allWantsAreCommits = wantsAsObjs.size() == wantsAsCommits .size(); boolean repoHasBitmaps = reader.getBitmapIndex() != null; if (!allWantsAreCommits) { if (!repoHasBitmaps) { RevObject nonCommit = wantsAsObjs .stream() .filter(obj -> !(obj instanceof RevCommit)) .limit(1) .collect(Collectors.toList()).get(0); throw new WantNotValidException(nonCommit); } checkNotAdvertisedWantsUsingBitmap(reader, reader.getBitmapIndex(), notAdvertisedWants, reachableFrom); return; } ReachabilityChecker reachabilityChecker = walk .getReachabilityChecker(); List<RevCommit> starters = objectIdsToRevCommits(walk, reachableFrom); Optional<RevCommit> unreachable = reachabilityChecker .areAllReachable(wantsAsCommits, starters); if (unreachable.isPresent()) { throw new WantNotValidException(unreachable.get()); } } catch (MissingObjectException notFound) { throw new WantNotValidException(notFound.getObjectId(), notFound); } }

Target:
private static void checkNotAdvertisedWants(UploadPack up, List<ObjectId> notAdvertisedWants, Set<ObjectId> reachableFrom) throws IOException { ObjectReader reader = up.getRevWalk().getObjectReader(); try (RevWalk walk = new RevWalk(reader)) { walk.setRetainBody(false); List<RevObject> wantsAsObjs = objectIdsToRevObjects(walk, notAdvertisedWants); List<RevCommit> wantsAsCommits = wantsAsObjs.stream() .filter(obj -> obj instanceof RevCommit) .map(obj -> (RevCommit) obj) .collect(Collectors.toList()); boolean allWantsAreCommits = wantsAsObjs.size() == wantsAsCommits .size(); boolean repoHasBitmaps = reader.getBitmapIndex() != null; if (!allWantsAreCommits) { if (!repoHasBitmaps) { RevObject nonCommit = wantsAsObjs .stream() .filter(obj -> !(obj instanceof RevCommit)) .limit(1) .collect(Collectors.toList()).get(0); throw new WantNotValidException(nonCommit); } checkNotAdvertisedWantsUsingBitmap(reader, reader.getBitmapIndex(), notAdvertisedWants, reachableFrom); return; } ReachabilityChecker reachabilityChecker = walk .createReachabilityChecker(); List<RevCommit> starters = objectIdsToRevCommits(walk, reachableFrom); Optional<RevCommit> unreachable = reachabilityChecker .areAllReachable(wantsAsCommits, starters); if (unreachable.isPresent()) { throw new WantNotValidException(unreachable.get()); } } catch (MissingObjectException notFound) { throw new WantNotValidException(notFound.getObjectId(), notFound); } }
Source:
public HTTPArgument(String name, String value, boolean alreadyEncoded, String contentEncoding) { setAlwaysEncoded(true); if (alreadyEncoded) { try { if(log.isDebugEnabled()) { log.debug("Decoding name, calling URLDecoder.decode with '"+name+"' and contentEncoding:"+EncoderCache.URL_ARGUMENT_ENCODING); } URLCodec urlCodec = new URLCodec(contentEncoding); name = urlCodec.decode(name, EncoderCache.URL_ARGUMENT_ENCODING); if(log.isDebugEnabled()) { log.debug("Decoding value, calling URLDecoder.decode with '"+value+"' and contentEncoding:"+contentEncoding); } value = urlCodec.decode(value, contentEncoding); } catch (UnsupportedEncodingException e) { log.error(contentEncoding + " encoding not supported!"); throw new Error(e.toString(), e); } catch (DecoderException e) { log.error(contentEncoding + " exception in decoder!"); throw new IllegalArgumentException(e.toString(), e); } } setName(name); setValue(value); setMetaData("="); }

Target:
public HTTPArgument(String name, String value, boolean alreadyEncoded, String contentEncoding) { setAlwaysEncoded(true); if (alreadyEncoded) { try { if(log.isDebugEnabled()) { log.debug("Decoding name, calling URLDecoder.decode with '{}' and contentEncoding: '{}'", name, EncoderCache.URL_ARGUMENT_ENCODING); } URLCodec urlCodec = new URLCodec(contentEncoding); name = urlCodec.decode(name, EncoderCache.URL_ARGUMENT_ENCODING); if(log.isDebugEnabled()) { log.debug("Decoding value, calling URLDecoder.decode with '{}' and contentEncoding: '{}'", value, contentEncoding); } value = urlCodec.decode(value, contentEncoding); } catch (UnsupportedEncodingException e) { log.error("{} encoding not supported!", contentEncoding); throw new Error(e.toString(), e); } catch (DecoderException e) { throw new IllegalArgumentException(e.toString(), e); } } setName(name); setValue(value); setMetaData("="); }
Source:
public void testMaximize() throws Exception { final SWTBotShell shell = bot.shell("shell4"); final int originalwidth = 400, originalheight = 400; UIThreadRunnable.syncExec(display, new VoidResult() { @Override public void run() { shell.widget.setSize(originalwidth, originalheight); } }); shell.maximize(true); assertThat(getWidth(shell), greaterThan(originalwidth)); assertThat(getHeight(shell), greaterThan(originalheight)); shell.maximize(false); assertThat(getWidth(shell), lessThanOrEqualTo(originalwidth)); assertThat(getHeight(shell), lessThanOrEqualTo(originalheight)); }

Target:
public void testMaximize() throws Exception { final SWTBotShell shell = bot.shell("shell4"); final int originalwidth = 400, originalheight = 400; UIThreadRunnable.syncExec(display, new VoidResult() { @Override public void run() { shell.widget.setSize(originalwidth, originalheight); } }); assertEquals("Initial width", originalwidth, getWidth(shell)); assertEquals("Initial height", originalheight, getHeight(shell)); shell.maximize(true); assertThat(getWidth(shell), greaterThan(originalwidth)); assertThat(getHeight(shell), greaterThan(originalheight)); shell.maximize(false); assertThat(getWidth(shell), lessThanOrEqualTo(originalwidth)); assertThat(getHeight(shell), lessThanOrEqualTo(originalheight)); }
Source:
synchronized RequestFuture<Map<String,ByteBuffer>> sendHeartbeatRequest() { log.debug("Sending Heartbeat request to coordinator {}", coordinator); HeartbeatRequest.Builder requestBuilder = new HeartbeatRequest.Builder(new HeartbeatRequestData() .setGroupId(rebalanceConfig.groupId) .setMemberId(this.generation.memberId) .setGroupInstanceId(this.rebalanceConfig.groupInstanceId.orElse(null)) .setGenerationId(this.generation.generationId) .setUserData(getHeartbeatData()) ); return client.send(coordinator, requestBuilder) .compose(new HeartbeatResponseHandler()); }

Target:
synchronized RequestFuture<Void> sendHeartbeatRequest() { log.debug("Sending Heartbeat request to coordinator {}", coordinator); HeartbeatRequest.Builder requestBuilder = new HeartbeatRequest.Builder(new HeartbeatRequestData() .setGroupId(rebalanceConfig.groupId) .setMemberId(this.generation.memberId) .setGroupInstanceId(this.rebalanceConfig.groupInstanceId.orElse(null)) .setGenerationId(this.generation.generationId) .setUserData(HeartbeatUserData.serializeOneUserData(getHeartbeatData())) ); return client.send(coordinator, requestBuilder) .compose(new HeartbeatResponseHandler()); }
Source:
public static <T extends Comparable<? super T>> T combineAnnotationValues(final List<T> values) { Utils.nonEmpty(values); final int size = values.size(); if ( size == 1 ) { return values.get(0); } else { final ArrayList<T> sorted = new ArrayList<>(values); Collections.sort(sorted); return sorted.get(size / 2); } }

Target:
private static <T extends Comparable<? super T>> T combineAnnotationValues(final List<T> values) { Utils.nonEmpty(values); final int size = values.size(); if ( size == 1 ) { return values.get(0); } else { final List<T> sorted = values.stream().sorted().collect(Collectors.toList()); return sorted.get(size / 2); } }
Source:
private AddIntegerTrainer(final ParameterWorker<Integer, Integer, Integer> parameterWorker, @Parameter(Parameters.Iterations.class) final int numIterations, @Parameter(Parameters.MiniBatchSize.class) final int miniBatchSize, @Parameter(ExampleParameters.DeltaValue.class) final int delta, @Parameter(ExampleParameters.NumKeys.class) final int numberOfKeys, @Parameter(ExampleParameters.NumWorkers.class) final int numberOfWorkers, @Parameter(ExampleParameters.ComputeTimeMs.class) final long computeTime, @Parameter(ExampleParameters.NumTrainingData.class) final int numTrainingData, final MetricsMsgSender<WorkerMetrics> metricsMsgSender) { this.parameterWorker = parameterWorker; this.delta = delta; this.numberOfKeys = numberOfKeys; this.computeTime = computeTime; final int numMiniBatches = (numTrainingData + miniBatchSize - 1) / miniBatchSize; this.expectedResult = delta * numberOfWorkers * numIterations * numMiniBatches; LOG.log(Level.INFO, "delta:{0}, numWorkers:{1}, numIterations:{2}, numTrainingData:{3}, numMiniBatches:{4}", new Object[]{delta, numberOfWorkers, numIterations, numTrainingData, numMiniBatches}); this.metricsMsgSender = metricsMsgSender; this.computeTracer = new Tracer(); }

Target:
private AddIntegerTrainer(final ParameterWorker<Integer, Integer, Integer> parameterWorker, @Parameter(Parameters.Iterations.class) final int numIterations, @Parameter(Parameters.MiniBatchSize.class) final int miniBatchSize, @Parameter(ExampleParameters.DeltaValue.class) final int delta, @Parameter(ExampleParameters.NumKeys.class) final int numberOfKeys, @Parameter(ExampleParameters.NumWorkers.class) final int numberOfWorkers, @Parameter(ExampleParameters.ComputeTimeMs.class) final long computeTime, @Parameter(ExampleParameters.NumTrainingData.class) final int numTrainingData, final MetricsMsgSender<WorkerMetrics> metricsMsgSender) { this.parameterWorker = parameterWorker; this.delta = delta; this.numberOfKeys = numberOfKeys; this.computeTime = computeTime; final int numMiniBatches = numTrainingData / miniBatchSize + (numTrainingData % miniBatchSize != 0 ? 1 : 0); this.expectedResult = delta * numberOfWorkers * numIterations * numMiniBatches; LOG.log(Level.INFO, "delta:{0}, numWorkers:{1}, numIterations:{2}, numTrainingData:{3}, numMiniBatches:{4}", new Object[]{delta, numberOfWorkers, numIterations, numTrainingData, numMiniBatches}); this.metricsMsgSender = metricsMsgSender; this.computeTracer = new Tracer(); }
Source:
private String printStats(Http.Request request) throws JsonProcessingException { Map<String, String[]> stringMap = request.body() .asFormUrlEncoded(); Map<String, Object> map = ImmutableMap.of( "Result", "ok", "GetParams", request.queryString(), "PostParams", stringMap == null ? "null" : stringMap, "Headers", request.getHeaders().toMap() ); return new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(map); }

Target:
private String printStats(Http.Request request) throws JsonProcessingException { Map<String, String[]> stringMap = request.body() .asFormUrlEncoded(); Map<String, Object> map = ImmutableMap.of( "Result", "ok", "GetParams", request.queryString(), "PostParams", stringMap == null ? Collections.emptyMap() : stringMap, "Headers", request.getHeaders().toMap() ); return new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(map); }
Source:
public void init(Map<String, Serializable> args) throws Exception { if (args.containsKey("ftpHostname")) { ftpHostname = args.get("ftpHostname").toString(); } if (args.containsKey("ftpPort")) { try { ftpPort = Integer.parseInt(args.get("ftpPort").toString()); } catch (NumberFormatException e) { } } if (args.containsKey("ftpExtractArchive")) { ftpExtractArchive = Boolean.parseBoolean(args.get("ftpExtractArchive").toString()); } if (args.containsKey("ftpLocalFilePath")) { ftpLocalFilePath = args.get("ftpLocalFilePath") == null ? "" : args.get("ftpLocalFilePath").toString(); } if (args.containsKey("ftpRemoteFilePath")) { ftpRemoteFilePath = args.get("ftpRemoteFilePath").toString(); } if (args.containsKey("ftpMode")) { ftpMode = args.get("ftpMode").toString(); } ftpUsername = getThirdPartyCredential("FTP_USERNAME"); ftpPassword = getThirdPartyCredential("FTP_PASSWORD"); if (ftpUsername == null || ftpPassword == null) { throw new Exception("You first need to add your ftp username and password (FTP_USERNAME, FTP_PASSWORD) to the third party credentials"); } }

Target:
public void init(Map<String, Serializable> args) throws Exception { if (args.containsKey("ftpHostname")) { ftpHostname = args.get("ftpHostname").toString(); } if (args.containsKey("ftpPort")) { try { ftpPort = Integer.parseInt(args.get("ftpPort").toString()); } catch (NumberFormatException e) { } } if (args.containsKey("ftpExtractArchive")) { ftpExtractArchive = Boolean.parseBoolean(args.get("ftpExtractArchive").toString()); } if (args.containsKey(FTP_LOCAL_FILE_PATH)) { ftpLocalFilePath = args.get(FTP_LOCAL_FILE_PATH) == null ? "" : args.get(FTP_LOCAL_FILE_PATH).toString(); } if (args.containsKey("ftpRemoteFilePath")) { ftpRemoteFilePath = args.get("ftpRemoteFilePath").toString(); } if (args.containsKey("ftpMode")) { ftpMode = args.get("ftpMode").toString(); } ftpUsername = getThirdPartyCredential("FTP_USERNAME"); ftpPassword = getThirdPartyCredential("FTP_PASSWORD"); if (ftpUsername == null || ftpPassword == null) { throw new IllegalArgumentException("You first need to add your ftp username and password (FTP_USERNAME, FTP_PASSWORD) to the third party credentials"); } }
Source:
public static ItemStack insert(Block node, Block target, ItemStack stack, int index) { if (!matchesFilter(node, stack, index)) return stack; DirtyChestMenu menu = getChestMenu(target); if (menu == null) { if (BlockUtils.hasInventory(target)) { BlockState state = target.getState(); if (state instanceof InventoryHolder) { return insertIntoVanillaInventory(stack, ((InventoryHolder) state).getInventory()); } } return stack; } ItemStackWrapper wrapper = new ItemStackWrapper(stack); for (int slot : menu.getPreset().getSlotsAccessedByItemTransport(menu, ItemTransportFlow.INSERT, stack)) { ItemStack itemInSlot = menu.getItemInSlot(slot); if (itemInSlot == null) { menu.replaceExistingItem(slot, stack); return null; } int inSlotMaxSize = itemInSlot.getType().getMaxStackSize(); int inSlotAmount = itemInSlot.getAmount(); if (SlimefunUtils.isItemSimilar(itemInSlot, wrapper, true, false) && inSlotAmount < inSlotMaxSize) { int amount = inSlotAmount + stack.getAmount(); itemInSlot.setAmount(Math.max(amount, inSlotMaxSize)); if (amount > inSlotMaxSize) { stack.setAmount(amount - inSlotMaxSize); } else { stack = null; } menu.replaceExistingItem(slot, itemInSlot); return stack; } } return stack; }

Target:
public static ItemStack insert(Block node, Block target, ItemStack stack, int index) { if (!matchesFilter(node, stack, index)) return stack; DirtyChestMenu menu = getChestMenu(target); if (menu == null) { if (BlockUtils.hasInventory(target)) { BlockState state = target.getState(); if (state instanceof InventoryHolder) { return insertIntoVanillaInventory(stack, ((InventoryHolder) state).getInventory()); } } return stack; } ItemStackWrapper wrapper = new ItemStackWrapper(stack); for (int slot : menu.getPreset().getSlotsAccessedByItemTransport(menu, ItemTransportFlow.INSERT, stack)) { ItemStack itemInSlot = menu.getItemInSlot(slot); if (itemInSlot == null) { menu.replaceExistingItem(slot, stack); return null; } int maxStackSize = itemInSlot.getType().getMaxStackSize(); int currentAmount = itemInSlot.getAmount(); if (SlimefunUtils.isItemSimilar(itemInSlot, wrapper, true, false) && currentAmount < maxStackSize) { int amount = currentAmount + stack.getAmount(); itemInSlot.setAmount(Math.min(amount, maxStackSize)); if (amount > maxStackSize) { stack.setAmount(amount - maxStackSize); } else { stack = null; } menu.replaceExistingItem(slot, itemInSlot); return stack; } } return stack; }
Source:
public void testGenotypePhenotypeSearchFeaturePagingAll() throws AvroRemoteException { SearchGenotypePhenotypeRequest request = SearchGenotypePhenotypeRequest.newBuilder().build(); request.setFeature("KIT *wild"); request.setPageSize(1); SearchGenotypePhenotypeResponse response = client.genotypePhenotype.searchGenotypePhenotype(request); assertThat(response).isNotNull(); assertThat(response.getAssociations()).isNotNull() ; assertThat(response.getAssociations().size()).isEqualTo(1); for(int i = 0 ; i < 3 ; i++) { String previous_id = response.getAssociations().get(0).getId() ; request = SearchGenotypePhenotypeRequest.newBuilder().build(); request.setFeature("KIT *wild"); request.setPageSize(1); request.setPageToken(response.getNextPageToken()); response = client.genotypePhenotype.searchGenotypePhenotype(request); assertThat(response.getAssociations().size()).isEqualTo(1); assertThat(previous_id).isNotEqualTo(response.getAssociations().get(0).getId()) ; assertThat(response.getNextPageToken()).isNotNull(); } }

Target:
public void testGenotypePhenotypeSearchFeaturePagingAll() throws AvroRemoteException { SearchGenotypePhenotypeRequest request = SearchGenotypePhenotypeRequest.newBuilder().build(); request.setFeature(TestData.FEATURE_NAME); request.setPageSize(1); SearchGenotypePhenotypeResponse response = client.genotypePhenotype.searchGenotypePhenotype(request); assertThat(response.getAssociations()).isNotNull() ; assertThat(response.getAssociations().size()).isEqualTo(1); while(response.getNextPageToken() != null) { System.err.println(response.getNextPageToken()) ; String previous_id = response.getAssociations().get(0).getId() ; request = SearchGenotypePhenotypeRequest.newBuilder().build(); request.setFeature(TestData.FEATURE_NAME); request.setPageSize(1); request.setPageToken(response.getNextPageToken()); response = client.genotypePhenotype.searchGenotypePhenotype(request); if (response.getNextPageToken() != null ) { assertThat(response.getAssociations()).isNotEmpty(); assertThat(previous_id).isNotEqualTo(response.getAssociations().get(0).getId()); } } }