auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void checkAttributeSyntax(PerunSessionImpl perunSession, String key, Attribute attribute) throws WrongAttributeValueException { if (attribute.getValue() == null) return; if (!(attribute.getValue() instanceof String)) { throw new WrongAttributeValueException(attribute, key, "value must be of type String"); } String value = attribute.valueAsString(); if (!value.contains("{link}")) { throw new WrongAttributeValueException(attribute, key, "value doesn't contain contain tag {link}"); } }

Target:
public void checkAttributeSyntax(PerunSessionImpl perunSession, String key, Attribute attribute) throws WrongAttributeValueException { if (attribute.getValue() == null) return; if (!attribute.valueAsString().contains("{link}")) { throw new WrongAttributeValueException(attribute, key, "value doesn't contain contain tag {link}"); } }
Source:
public void shouldAddTransactionIdToCard() throws Exception { DatabaseFixtures.TestCharge testCharge = addCharge(); Pair<Long, Long> ids = createPaymentRequest(testCharge); long cardId = nextId.getAndIncrement(); databaseTestHelper.addCard(cardId, testCharge.getChargeId(), null); worker.execute(1L); Map<String, Object> card = databaseTestHelper.getCard(cardId); assertThat(card.get("transaction_id"), is(ids.getRight())); }

Target:
public void shouldAddTransactionIdToCard() { DatabaseFixtures.TestCharge testCharge = addCharge(); Pair<Long, Long> ids = createPaymentRequest(testCharge); long cardId = nextId.getAndIncrement(); databaseTestHelper.addCard(cardId, testCharge.getChargeId(), null); worker.execute(1L); Map<String, Object> card = databaseTestHelper.getCard(cardId); assertThat(card.get("transaction_id"), is(ids.getRight())); }
Source:
public void invalidTokenShouldFail() { StandardSlackService service = new StandardSlackService("", "tinyspeck", false, "#general", false,"token"); service.publish("message"); }

Target:
public void invalidTokenShouldFail() { StandardSlackService service = new StandardSlackService( StandardSlackService.builder() .withBaseUrl("") .withTeamDomain("tinyspeck") .withBotUser(false) .withRoomId("#general") .withReplyBroadcast(false) .withPopulatedToken("token")); service.publish("message"); }
Source:
public synchronized void save() throws IOException { if(BulkChange.contains(this)) return; long start=0; if(logger.isLoggable(Level.FINE)) start = System.currentTimeMillis(); FingerprintStorage.get().save(this); if(logger.isLoggable(Level.FINE)) logger.fine("Saving fingerprint took "+(System.currentTimeMillis()-start)+"ms"); }

Target:
public synchronized void save() throws IOException { if(BulkChange.contains(this)) { return; } long start=0; if(logger.isLoggable(Level.FINE)) start = System.currentTimeMillis(); FingerprintStorage.get().save(this); if(logger.isLoggable(Level.FINE)) logger.fine("Saving fingerprint " + getHashString() + " took " + (System.currentTimeMillis() - start) + "ms"); }
Source:
private void createNode() { if ( !isActive() ) { return; } if ( debugCreateNodeLatch != null ) { try { debugCreateNodeLatch.await(); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); return; } } try { String existingPath = nodePath.get(); String createPath = existingPath == null || (useProtection && !isSequential(mode)) ? basePath : (useProtection ? basePath + existingPath.substring(existingPath.length()-10) : existingPath); CreateModable<ACLBackgroundPathAndBytesable<String>> localCreateMethod = createMethod.get(); if ( localCreateMethod == null ) { CreateBuilderMain createBuilder = SafeIsTtlMode.isTtl(mode) ? client.create().withTtl(ttl) : client.create(); CreateModable<ACLBackgroundPathAndBytesable<String>> tempCreateMethod = useProtection ? createBuilder.creatingParentContainersIfNeeded().withProtection() : createBuilder.creatingParentContainersIfNeeded(); createMethod.compareAndSet(null, tempCreateMethod); localCreateMethod = createMethod.get(); } localCreateMethod.withMode(getCreateMode(existingPath != null)).inBackground(backgroundCallback).forPath(createPath, data.get()); } catch ( Exception e ) { ThreadUtils.checkInterrupted(e); throw new RuntimeException("Creating node. BasePath: " + basePath, e); } }

Target:
private void createNode() { if ( !isActive() ) { return; } if ( debugCreateNodeLatch != null ) { try { debugCreateNodeLatch.await(); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); return; } } try { String existingPath = nodePath.get(), createPath; if ( existingPath != null && !useProtection ) { createPath = existingPath; } else if ( existingPath != null && mode.isSequential() ) { createPath = basePath + ZKPaths.extractSequentialSuffix(existingPath); } else { createPath = basePath; } CreateModable<ACLBackgroundPathAndBytesable<String>> localCreateMethod = createMethod.get(); if ( localCreateMethod == null ) { CreateBuilderMain createBuilder = SafeIsTtlMode.isTtl(mode) ? client.create().withTtl(ttl) : client.create(); CreateModable<ACLBackgroundPathAndBytesable<String>> tempCreateMethod = useProtection ? createBuilder.creatingParentContainersIfNeeded().withProtection() : createBuilder.creatingParentContainersIfNeeded(); createMethod.compareAndSet(null, tempCreateMethod); localCreateMethod = createMethod.get(); } localCreateMethod.withMode(getCreateMode(existingPath != null)).inBackground(backgroundCallback).forPath(createPath, data.get()); } catch ( Exception e ) { ThreadUtils.checkInterrupted(e); throw new RuntimeException("Creating node. BasePath: " + basePath, e); } }
Source:
public String init(Model model) { model.addAttribute("users", this.pluginUserManagerService.getAllUsers()); if (!model.containsAttribute(VIEW_STATE)) model.addAttribute(VIEW_STATE, "users"); return "view-usermanager"; }

Target:
public String init(Model model) { model.addAttribute("users", this.pluginUserManagerService.getAllUsers()); if (!model.containsAttribute(VIEW_STATE)) { model.addAttribute(VIEW_STATE, "users"); } return "view-usermanager"; }
Source:
public synchronized Optional<ConnectorOutputMetadata> finishCreateTable(ConnectorSession session, ConnectorOutputTableHandle tableHandle, Collection<Slice> fragments) { checkArgument(requireNonNull(tableHandle, "tableHandle is null") instanceof MemoryOutputTableHandle); MemoryOutputTableHandle memoryOutputHandle = (MemoryOutputTableHandle) tableHandle; updateRowsOnHosts(memoryOutputHandle.getTable(), fragments); return Optional.empty(); }

Target:
public synchronized Optional<ConnectorOutputMetadata> finishCreateTable(ConnectorSession session, ConnectorOutputTableHandle tableHandle, Collection<Slice> fragments) { requireNonNull(tableHandle, "tableHandle is null"); MemoryOutputTableHandle memoryOutputHandle = (MemoryOutputTableHandle) tableHandle; updateRowsOnHosts(memoryOutputHandle.getTable(), fragments); return Optional.empty(); }
Source:
private double calculateHaversineDistance(MapValue value1, MapValue value2) { double lat1Degrees = getLastLatitute(value1); double lon1Degrees = getLastLongitude(value1); double lat2Degrees = getFirstLatitude(value2); double lon2Degrees = getFirstLongitude(value2); return calculateHaversineDistanceFromDegrees(lat1Degrees, lon1Degrees, lat2Degrees, lon2Degrees, 0); }

Target:
private double calculateHaversineDistance(MapValue value1, MapValue value2) { double lat1Degrees = getLastLatitude(value1); double lon1Degrees = getLastLongitude(value1); double lat2Degrees = getFirstLatitude(value2); double lon2Degrees = getFirstLongitude(value2); return calculateHaversineDistanceFromDegrees(lat1Degrees, lon1Degrees, lat2Degrees, lon2Degrees, 0); }
Source:
public void serializableTransaction() throws Exception { db.setTransactionHandler(new SerializableTransactionRunner()); BiConsumer<Handle, Integer> insert = (h, i) -> h.execute("INSERT INTO ints(value) VALUES(?)", i); handle.execute("CREATE TABLE ints (value INTEGER)"); insert.accept(handle, 10); insert.accept(handle, 20); ExecutorService executor = Executors.newCachedThreadPool(); CountDownLatch latch = new CountDownLatch(2); Supplier<Callable<Integer>> sumAndInsert = () -> () -> db.inTransaction(TransactionIsolationLevel.SERIALIZABLE, h -> { int sum = h.select("SELECT sum(value) FROM ints").mapTo(int.class).findOnly(); latch.countDown(); latch.await(); insert.accept(h, sum); return sum; }); Future<Integer> result1 = executor.submit(sumAndInsert.get()); Future<Integer> result2 = executor.submit(sumAndInsert.get()); assertThat(result1.get() + result2.get()).isEqualTo(30 + 60); executor.shutdown(); }

Target:
public void serializableTransaction() throws Exception { db.setTransactionHandler(new SerializableTransactionRunner()); BiConsumer<Handle, Integer> insert = (h, i) -> h.execute("INSERT INTO ints(value) VALUES(?)", i); handle.execute("CREATE TABLE ints (value INTEGER)"); insert.accept(handle, 10); insert.accept(handle, 20); ExecutorService executor = Executors.newCachedThreadPool(); CountDownLatch latch = new CountDownLatch(2); Callable<Integer> sumAndInsert = () -> db.inTransaction(TransactionIsolationLevel.SERIALIZABLE, h -> { int sum = h.select("SELECT sum(value) FROM ints").mapTo(int.class).findOnly(); latch.countDown(); latch.await(); insert.accept(h, sum); return sum; }); Future<Integer> result1 = executor.submit(sumAndInsert); Future<Integer> result2 = executor.submit(sumAndInsert); assertThat(result1.get() + result2.get()).isEqualTo(30 + 60); executor.shutdown(); }
Source:
PersistentStoragePathSanitizer()

Target:
private PersistentStoragePathSanitizer()
Source:
public boolean performFinish() { try { Repository repository = repositorySearchWizardPage.getRepository(); String repoName = repository.toString(); URIish uri = new URIish("git://github.com/" + repoName + ".git"); boolean allSelected = true; Collection<Ref> selectedBranches = Collections.emptyList(); IPreferenceStore preferenceStore = org.eclipse.egit.ui.Activator .getDefault().getPreferenceStore(); int timeout = preferenceStore .getInt(UIPreferences.REMOTE_CONNECTION_TIMEOUT); String defaultRepoDir = preferenceStore .getString(UIPreferences.DEFAULT_REPO_DIR); final CloneOperation cloneOperation = new CloneOperation(uri, allSelected, selectedBranches, new File(defaultRepoDir + File.separator + repoName), "master", "origin", timeout); getContainer().run(false, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { cloneOperation.run(monitor); RepositoryUtil repositoryUtil = Activator.getDefault() .getRepositoryUtil(); repositoryUtil.addConfiguredRepository(cloneOperation .getGitDir()); } }); } catch (URISyntaxException uriSyntaxException) { GitHubUi.logError(uriSyntaxException); return false; } catch (InvocationTargetException invocationTargetException) { GitHubUi.logError(invocationTargetException); return false; } catch (InterruptedException interruptedException) { GitHubUi.logError(interruptedException); return false; } return true; }

Target:
public boolean performFinish() { try { Repository repository = repositorySearchWizardPage.getRepository(); String repoName = repository.toString(); URIish uri = new URIish("git://github.com/" + repoName + Constants.DOT_GIT); boolean allSelected = true; Collection<Ref> selectedBranches = Collections.emptyList(); IPreferenceStore preferenceStore = org.eclipse.egit.ui.Activator .getDefault().getPreferenceStore(); int timeout = preferenceStore .getInt(UIPreferences.REMOTE_CONNECTION_TIMEOUT); String defaultRepoDir = preferenceStore .getString(UIPreferences.DEFAULT_REPO_DIR); final CloneOperation cloneOperation = new CloneOperation(uri, allSelected, selectedBranches, new File(defaultRepoDir + File.separator + repoName), Constants.R_HEADS + Constants.MASTER, Constants.DEFAULT_REMOTE_NAME, timeout); getContainer().run(false, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { cloneOperation.run(monitor); RepositoryUtil repositoryUtil = Activator.getDefault() .getRepositoryUtil(); repositoryUtil.addConfiguredRepository(cloneOperation .getGitDir()); } }); } catch (URISyntaxException uriSyntaxException) { GitHubUi.logError(uriSyntaxException); return false; } catch (InvocationTargetException invocationTargetException) { GitHubUi.logError(invocationTargetException); return false; } catch (InterruptedException interruptedException) { GitHubUi.logError(interruptedException); return false; } return true; }
Source:
private DingtalkJobErrorHandler getDingtalkJobErrorHandler() { for (JobErrorHandler jobErrorHandler : ServiceLoader.load(JobErrorHandler.class)) { if (null != jobErrorHandler && jobErrorHandler instanceof DingtalkJobErrorHandler) { return (DingtalkJobErrorHandler) jobErrorHandler; } } return new DingtalkJobErrorHandler(); }

Target:
private DingtalkJobErrorHandler getDingtalkJobErrorHandler() { for (JobErrorHandler each : ServiceLoader.load(JobErrorHandler.class)) { if (null != each && each instanceof DingtalkJobErrorHandler) { return (DingtalkJobErrorHandler) each; } } return new DingtalkJobErrorHandler(); }
Source:
private void launch(final List<String> args) { if (args.isEmpty() || containsHelpRequest(args)) { launchHelp(); } else { if (args.contains("--local-entry")) { final String descriptor = optVal(args, "--descriptor", null); List<String> argsList = new ArrayList<>(); argsList.addAll(args); final String entry = reqVal(args, "--entry"); File temp = new File(entry); checkEntryFile(temp,argsList, descriptor); }else{ final String descriptor = optVal(args, "--descriptor", CWL_STRING); if (descriptor.equals(CWL_STRING)) { try { launchCwl(args); } catch (ApiException e) { exceptionMessage(e, "api error launching workflow", Client.API_ERROR); } catch (IOException e) { exceptionMessage(e, "io error launching workflow", IO_ERROR); } } else if (descriptor.equals(WDL_STRING)) { launchWdl(args); } } } }

Target:
private void launch(final List<String> args) { if (args.isEmpty() || containsHelpRequest(args)) { launchHelp(); } else { if (args.contains("--local-entry")) { final String descriptor = optVal(args, "--descriptor", null); final String entry = reqVal(args, "--entry"); checkEntryFile(entry,args, descriptor); }else{ final String descriptor = optVal(args, "--descriptor", CWL_STRING); if (descriptor.equals(CWL_STRING)) { try { launchCwl(args); } catch (ApiException e) { exceptionMessage(e, "api error launching workflow", Client.API_ERROR); } catch (IOException e) { exceptionMessage(e, "io error launching workflow", IO_ERROR); } } else if (descriptor.equals(WDL_STRING)) { launchWdl(args); } } } }
Source:
private void pageLoadFromNetwork(final ErrorCallback errorCallback) { if (model.getTitle() == null) { return; } fragment.updateBookmarkAndMenuOptions(); sectionTargetFromTitle = model.getTitle().getFragment(); networkErrorCallback = errorCallback; if (!fragment.isAdded()) { return; } loading = true; fragment.requireActivity().invalidateOptionsMenu(); if (fragment.callback() != null) { fragment.callback().onPageUpdateProgressBar(true, true, 0); } app.getSessionFunnel().leadSectionFetchStart(); disposables.add(Observable.zip(new PageClient().summary(model.getTitle().getWikiSite(), model.getTitle().getPrefixedText(), null), ServiceFactory.getRest(model.getTitle().getWikiSite()).getMediaList(model.getTitle().getConvertedText()), Pair::new) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(pair -> { createPage(pair.first.body(), pair.second); bridge.execute(JavaScriptActionHandler.setFooter(fragment.requireContext(), model)); if ((pair.first.raw().cacheResponse() != null && pair.first.raw().networkResponse() == null) || OfflineCacheInterceptor.SAVE_HEADER_SAVE.equals(pair.first.headers().get(OfflineCacheInterceptor.SAVE_HEADER))) { showPageOfflineMessage(Objects.requireNonNull(pair.first.raw().header("date", ""))); } }, throwable -> { L.e("Page details network response error: ", throwable); commonSectionFetchOnCatch(throwable); })); bridge.resetHtml(model.getTitle().getWikiSite().url(), model.getTitle().getConvertedText()); }

Target:
private void pageLoadFromNetwork(final ErrorCallback errorCallback) { if (model.getTitle() == null) { return; } fragment.updateBookmarkAndMenuOptions(); networkErrorCallback = errorCallback; if (!fragment.isAdded()) { return; } loading = true; fragment.requireActivity().invalidateOptionsMenu(); if (fragment.callback() != null) { fragment.callback().onPageUpdateProgressBar(true, true, 0); } app.getSessionFunnel().leadSectionFetchStart(); disposables.add(new PageClient().summary(model.getTitle().getWikiSite(), model.getTitle().getPrefixedText(), null) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(pageSummaryResponse -> { if (pageSummaryResponse.body() != null) { createPage(pageSummaryResponse.body()); } bridge.execute(JavaScriptActionHandler.setFooter(model)); if ((pageSummaryResponse.raw().cacheResponse() != null && pageSummaryResponse.raw().networkResponse() == null) || OfflineCacheInterceptor.SAVE_HEADER_SAVE.equals(pageSummaryResponse.headers().get(OfflineCacheInterceptor.SAVE_HEADER))) { showPageOfflineMessage(Objects.requireNonNull(pageSummaryResponse.raw().header("date", ""))); } }, throwable -> { L.e("Page details network response error: ", throwable); commonSectionFetchOnCatch(throwable); })); bridge.resetHtml(model.getTitle().getWikiSite().url(), model.getTitle()); }
Source:
public PageableResult search(RequestContext context) throws ResponseException { String uuid = context.getParameter("uuid"); ConceptReferenceTerm conceptReferenceTerm = conceptService.getConceptReferenceTermByUuid(uuid); if (conceptReferenceTerm == null) { return new EmptySearchResult(); } else { List<ConceptMap> conceptMaps = new ArrayList<ConceptMap>(); conceptMaps.addAll(restHelperService.getObjectsByFields(ConceptMap.class, new Field("conceptReferenceTerm", conceptReferenceTerm))); List<Concept> concepts = new ArrayList<Concept>(); for (ConceptMap conceptMap : conceptMaps) { if (!conceptMap.getConcept().isRetired() || context.getIncludeAll()) { concepts.add(conceptMap.getConcept()); } } return new NeedsPaging<Concept>(concepts, context); } }

Target:
public PageableResult search(RequestContext context) throws ResponseException { String uuid = context.getParameter("term"); ConceptReferenceTerm conceptReferenceTerm = conceptService.getConceptReferenceTermByUuid(uuid); if (conceptReferenceTerm == null) { return new EmptySearchResult(); } else { List<ConceptMap> conceptMaps = new ArrayList<ConceptMap>(); conceptMaps.addAll(restHelperService.getObjectsByFields(ConceptMap.class, new Field("conceptReferenceTerm", conceptReferenceTerm))); List<Concept> concepts = new ArrayList<Concept>(); for (ConceptMap conceptMap : conceptMaps) { if (!conceptMap.getConcept().isRetired() || context.getIncludeAll()) { concepts.add(conceptMap.getConcept()); } } return new NeedsPaging<Concept>(concepts, context); } }
Source:
public void global_variable() { Set<Symbol> moduleSymbols = fileInput.globalVariables(); List<String> topLevelFunctions = Arrays.asList("global_x", "global_var", "function_with_local", "function_with_free_variable", "function_with_rebound_variable", "ref_in_interpolated", "print_var", "function_with_global_var", "func_wrapping_class", "function_with_unused_import", "function_with_nonlocal_var", "symbols_in_comp", "scope_of_comprehension", "for_comp_with_no_name_var", "function_with_loops", "simple_parameter", "comprehension_reusing_name", "tuple_assignment", "function_with_comprehension", "binding_usages", "func_with_star_param", "multiple_assignment", "function_with_nested_nonlocal_var", "func_with_tuple_param", "function_with_lambdas", "var_with_usages_in_decorator", "fn_inside_comprehension_same_name", "with_instance", "exception_instance", "unpacking"); List<String> globalSymbols = new ArrayList<>(); globalSymbols.addAll(topLevelFunctions); globalSymbols.addAll(BuiltinSymbols.CONSTANTS); globalSymbols.addAll(BuiltinSymbols.FUNCTIONS); globalSymbols.addAll(BuiltinSymbols.FUNCTIONS_PYTHON2); globalSymbols.addAll(BuiltinSymbols.EXCEPTIONS); globalSymbols.addAll(BuiltinSymbols.EXCEPTIONS_PYTHON2); globalSymbols.addAll(BuiltinSymbols.MODULE_ATTRIBUTES); globalSymbols.add("a"); assertThat(moduleSymbols).extracting(Symbol::name).containsExactlyInAnyOrder(globalSymbols.toArray(new String[] {})); moduleSymbols.stream().filter(s -> s.name().equals("global_var")).findFirst().ifPresent(s -> { assertThat(s.usages()).hasSize(3); }); }

Target:
public void global_variable() { Set<Symbol> moduleSymbols = fileInput.globalVariables(); List<String> topLevelFunctions = Arrays.asList("global_x", "global_var", "function_with_local", "function_with_free_variable", "function_with_rebound_variable", "ref_in_interpolated", "print_var", "function_with_global_var", "func_wrapping_class", "function_with_unused_import", "function_with_nonlocal_var", "symbols_in_comp", "scope_of_comprehension", "for_comp_with_no_name_var", "function_with_loops", "simple_parameter", "comprehension_reusing_name", "tuple_assignment", "function_with_comprehension", "binding_usages", "func_with_star_param", "multiple_assignment", "function_with_nested_nonlocal_var", "func_with_tuple_param", "function_with_lambdas", "var_with_usages_in_decorator", "fn_inside_comprehension_same_name", "with_instance", "exception_instance", "unpacking", "using_builtin_symbol", "keyword_usage"); List<String> globalSymbols = new ArrayList<>(topLevelFunctions); globalSymbols.add("a"); assertThat(moduleSymbols).extracting(Symbol::name).containsExactlyInAnyOrder(globalSymbols.toArray(new String[] {})); moduleSymbols.stream().filter(s -> s.name().equals("global_var")).findFirst().ifPresent(s -> { assertThat(s.usages()).hasSize(3); }); }
Source:
private boolean isAdd(ReferenceChange diff, boolean rightToLeft) { return rightToLeft ? isLeftDeleteOrRightAdd(diff) : isLeftAddOrRightDelete(diff); }

Target:
private boolean isAdd(ReferenceChange diff, boolean rightToLeft) { if (rightToLeft) { return isLeftDeleteOrRightAdd(diff); } else { return isLeftAddOrRightDelete(diff); } }
Source:
public boolean accept(ASTVisitor visitor) { if (visitor.shouldVisitCaptures) { switch (visitor.visit((ICPPASTCapture) this)) { case ASTVisitor.PROCESS_ABORT: return false; case ASTVisitor.PROCESS_SKIP: return true; default: break; } } if (visitor.shouldVisitDeclarations) { switch (visitor.visit((IASTDeclaration) this)) { case ASTVisitor.PROCESS_ABORT: return false; case ASTVisitor.PROCESS_SKIP: return true; } } if (fDeclarator != null && !fDeclarator.accept(visitor)) { return false; } if (visitor.shouldVisitCaptures && visitor.leave((ICPPASTCapture) this) == ASTVisitor.PROCESS_ABORT) { return false; } if (visitor.shouldVisitDeclarations && visitor.leave((IASTDeclaration) this) == ASTVisitor.PROCESS_ABORT) { return false; } return true; }

Target:
public boolean accept(ASTVisitor visitor) { if (visitor.shouldVisitCaptures) { switch (visitor.visit((ICPPASTCapture) this)) { case ASTVisitor.PROCESS_ABORT: return false; case ASTVisitor.PROCESS_SKIP: return true; default: break; } } if (visitor.shouldVisitDeclarations) { switch (visitor.visit((IASTDeclaration) this)) { case ASTVisitor.PROCESS_ABORT: return false; case ASTVisitor.PROCESS_SKIP: return true; } } if (fDeclarator != null && !fDeclarator.accept(visitor)) { return false; } if (visitor.shouldVisitDeclarations && visitor.leave((IASTDeclaration) this) == ASTVisitor.PROCESS_ABORT) { return false; } if (visitor.shouldVisitCaptures && visitor.leave((ICPPASTCapture) this) == ASTVisitor.PROCESS_ABORT) { return false; } return true; }
Source:
protected void initialize(Ruby runtime) { try { parser = createParser(); } catch (SAXException se) { throw runtime.newRuntimeError(se.getMessage()); } }

Target:
protected void initialize(Ruby runtime) { try { parser = createParser(); } catch (SAXException se) { RaiseException ex = runtime.newRuntimeError(se.toString()); ex.initCause(se); throw ex; } }
Source:
protected JSONObject configureEntryQuery(long groupId, long classNameId) throws JSONException { JSONObject entryQueryParams = _customEntryQuery == null ? new JSONObject() : new JSONObject(_customEntryQuery); entryQueryParams.put("classNameIds", classNameId); entryQueryParams.put("groupIds", groupId); entryQueryParams.put("visible", "true"); return entryQueryParams; }

Target:
protected JSONObject configureEntryQuery(long groupId, long classNameId) throws JSONException { JSONObject entryQueryParams = _customEntryQuery == null ? new JSONObject() : new JSONObject(_customEntryQuery); if (!entryQueryParams.has("classNameIds")) { entryQueryParams.put("classNameIds", classNameId); } if (!entryQueryParams.has("groupIds")) { entryQueryParams.put("groupIds", groupId); } if (!entryQueryParams.has("visible")) { entryQueryParams.put("visible", "true"); } return entryQueryParams; }
Source:
public final Connection getConnection(final long hardTimeout) throws SQLException { suspendResumeLock.acquire(); final long startTime = clockSource.currentTime(); try { long timeout = hardTimeout; final MetricsContext metricsContext = (isRecordMetrics ? metricsTracker.recordConnectionRequest() : MetricsTracker.NO_CONTEXT); do { final PoolBagEntry bagEntry = connectionBag.borrow(timeout, TimeUnit.MILLISECONDS); if (bagEntry == null) { break; } final long now = clockSource.currentTime(); if (bagEntry.evicted || (clockSource.elapsedMillis(bagEntry.lastAccess, now) > ALIVE_BYPASS_WINDOW_MS && !poolElf.isConnectionAlive(bagEntry.connection, lastConnectionFailure))) { closeConnection(bagEntry, "(connection evicted or dead)"); timeout = hardTimeout - clockSource.elapsedMillis(startTime, now); } else { metricsContext.setConnectionLastOpen(bagEntry, now); metricsContext.stop(); return ProxyFactory.getProxyConnection(bagEntry, leakTask.start(bagEntry), now); } } while (timeout > 0L); } catch (InterruptedException e) { throw new SQLException(poolName + " - Interrupted during connection acquisition", e); } finally { suspendResumeLock.release(); } logPoolState("Timeout failure "); String sqlState = null; final Throwable originalException = lastConnectionFailure.getAndSet(null); if (originalException instanceof SQLException) { sqlState = ((SQLException) originalException).getSQLState(); } throw new SQLTimeoutException(poolName + " - Cannot acquire connection, Timeout after " + clockSource.elapsedMillis(startTime) + "ms.", sqlState, originalException); }

Target:
public final Connection getConnection(final long hardTimeout) throws SQLException { suspendResumeLock.acquire(); final long startTime = clockSource.currentTime(); try { long timeout = hardTimeout; final MetricsContext metricsContext = (isRecordMetrics ? metricsTracker.recordConnectionRequest() : MetricsTracker.NO_CONTEXT); do { final PoolBagEntry bagEntry = connectionBag.borrow(timeout, TimeUnit.MILLISECONDS); if (bagEntry == null) { break; } final long now = clockSource.currentTime(); if (bagEntry.evicted || (clockSource.elapsedMillis(bagEntry.lastAccess, now) > ALIVE_BYPASS_WINDOW_MS && !poolElf.isConnectionAlive(bagEntry.connection, lastConnectionFailure))) { closeConnection(bagEntry, "(connection evicted or dead)"); timeout = hardTimeout - clockSource.elapsedMillis(startTime, now); } else { metricsContext.setConnectionLastOpen(bagEntry, now); metricsContext.stop(); return ProxyFactory.getProxyConnection(bagEntry, leakTask.start(bagEntry), now); } } while (timeout > 0L); } catch (InterruptedException e) { throw new SQLException(poolName + " - Interrupted during connection acquisition", e); } finally { suspendResumeLock.release(); } logPoolState("Timeout failure "); String sqlState = null; final Throwable originalException = lastConnectionFailure.getAndSet(null); if (originalException instanceof SQLException) { sqlState = ((SQLException) originalException).getSQLState(); } throw new SQLTransientConnectionException(poolName + " - Connection is not available, request timed out after " + clockSource.elapsedMillis(startTime) + "ms.", sqlState, originalException); }
Source:
public ServiceResponse<Void> evaluateNotifications(Long schoolId) { ServiceResponse<List<Notification>> notificationResponse = getAllNotifications(); if(null != notificationResponse.getValue()) { NotificationTriggerEvaluator factory = new NotificationTriggerEvaluator(pm); List<Notification> notifications = notificationResponse.getValue(); for(Notification n: notifications) { List<TriggeredNotification> triggeredNotifications = factory.evaluate(n); if(null != triggeredNotifications) { for(TriggeredNotification tr : triggeredNotifications) { notificationPersistence.insertTriggeredNotification(n.getId(), n.getOwner().getId(), tr); } } } } else { return new ServiceResponse<>(notificationResponse.getCode()); } return new ServiceResponse<>((Void) null); }

Target:
public ServiceResponse<Void> evaluateNotifications(Long schoolId) { ServiceResponse<List<Notification>> notificationResponse = getAllNotifications(); if(null != notificationResponse.getValue()) { NotificationTriggerEvaluator factory = new NotificationTriggerEvaluator(pm); List<Notification> notifications = notificationResponse.getValue(); for(Notification n: notifications) { List<TriggeredNotification> triggeredNotifications = factory.evaluate(n); if(null != triggeredNotifications) { for(TriggeredNotification tr : triggeredNotifications) { try { notificationPersistence.insertTriggeredNotification(n.getId(), n.getOwner().getId(), tr); } catch(Exception e) { LOGGER.info("Triggered notification not inserted due to: " + e.getMessage()); } } } } } else { return new ServiceResponse<>(notificationResponse.getCode()); } return new ServiceResponse<>((Void) null); }
Source:
public void testGetFirstRowItemCount_ItemsOfMultiSpan() throws Throwable { int itemCount = SPAN_COUNT * 20; setUpPagedListView(itemCount); RecyclerView recyclerView = mPagedListView.getRecyclerView(); mActivityRule.runOnUiThread(() -> { ((GridLayoutManager) recyclerView.getLayoutManager()).setSpanSizeLookup( new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { return position % 2 + 1; } }); }); InstrumentationRegistry.getInstrumentation().waitForIdleSync(); int expected = (SPAN_COUNT / 3) * 2 + (SPAN_COUNT % 3 > 0 ? 1 : 0); assertEquals(expected, GridLayoutManagerUtils.getFirstRowItemCount(recyclerView)); }

Target:
public void testGetFirstRowItemCount_ItemsOfMultiSpan() throws Throwable { int itemCount = SPAN_COUNT * 20; setUpPagedListView(itemCount, new AlternateSpanSizeLookup()); RecyclerView recyclerView = mPagedListView.getRecyclerView(); InstrumentationRegistry.getInstrumentation().waitForIdleSync(); assertEquals(AlternateSpanSizeLookup.ITEMS_PER_ROW, GridLayoutManagerUtils.getFirstRowItemCount(recyclerView)); }
Source:
static public void selectBoard(TargetBoard targetBoard) { TargetPlatform targetPlatform = targetBoard.getContainerPlatform(); TargetPackage targetPackage = targetPlatform.getContainerPackage(); PreferencesData.set("target_package", targetPackage.getId()); PreferencesData.set("target_platform", targetPlatform.getId()); PreferencesData.set("board", targetBoard.getId()); File platformFolder = targetPlatform.getFolder(); PreferencesData.set("runtime.platform.path", platformFolder.getAbsolutePath()); PreferencesData.set("runtime.hardware.path", platformFolder.getParentFile().getAbsolutePath()); if (!recentlyUsedBoards.contains(targetBoard)) { recentlyUsedBoards.add(targetBoard); } if (recentlyUsedBoards.size() > 4) { recentlyUsedBoards.remove(); } }

Target:
static public void selectBoard(TargetBoard targetBoard) { TargetPlatform targetPlatform = targetBoard.getContainerPlatform(); TargetPackage targetPackage = targetPlatform.getContainerPackage(); PreferencesData.set("target_package", targetPackage.getId()); PreferencesData.set("target_platform", targetPlatform.getId()); PreferencesData.set("board", targetBoard.getId()); File platformFolder = targetPlatform.getFolder(); PreferencesData.set("runtime.platform.path", platformFolder.getAbsolutePath()); PreferencesData.set("runtime.hardware.path", platformFolder.getParentFile().getAbsolutePath()); if (!recentlyUsedBoards.contains(targetBoard)) { recentlyUsedBoards.add(targetBoard); } if (recentlyUsedBoards.size() > PreferencesData.getInteger("editor.recent_boards.size", 4)) { recentlyUsedBoards.remove(); } }
Source:
public String getOrCreateSessionId(final PlayWebContext context) { final Http.Session session = context.getJavaSession(); String sessionId = session.get(Pac4jConstants.SESSION_ID); logger.trace("retrieved sessionId: {}", sessionId); if (sessionId == null) { sessionId = java.util.UUID.randomUUID().toString(); logger.debug("generated sessionId: {}", sessionId); session.put(Pac4jConstants.SESSION_ID, sessionId); } return sessionId; }

Target:
public String getOrCreateSessionId(final PlayWebContext context) { return tokenName; }
Source:
public void onNextDiffClicked() { view.getEditableContent(content -> { if (isEdited(content)) { saveContent(content); } currentFileIndex++; showCompareForCurrentFile(); }); }

Target:
public void onNextDiffClicked() { if (currentFileIndex < alteredFiles.getFilesQuantity() - 1) { onSaveChangesClicked(); currentFileIndex++; showCompareForCurrentFile(); } }
Source:
public void testMutualAuthDiffCertsServerFailure() throws Exception { File serverKeyFile = ResourcesUtil.getFile(getClass(), "test_encrypted.pem"); File serverCrtFile = ResourcesUtil.getFile(getClass(), "test.crt"); String serverKeyPassword = "12345"; File clientKeyFile = ResourcesUtil.getFile(getClass(), "test2_encrypted.pem"); File clientCrtFile = ResourcesUtil.getFile(getClass(), "test2.crt"); String clientKeyPassword = "12345"; mySetupMutualAuth(serverCrtFile, serverKeyFile, serverCrtFile, serverKeyPassword, serverCrtFile, clientKeyFile, clientCrtFile, clientKeyPassword); assertTrue(serverLatch.await(200, TimeUnit.SECONDS)); assertTrue(serverException instanceof SSLHandshakeException); }

Target:
public void testMutualAuthDiffCertsServerFailure() throws Exception { File serverKeyFile = ResourcesUtil.getFile(getClass(), "test_encrypted.pem"); File serverCrtFile = ResourcesUtil.getFile(getClass(), "test.crt"); String serverKeyPassword = "12345"; File clientKeyFile = ResourcesUtil.getFile(getClass(), "test2_encrypted.pem"); File clientCrtFile = ResourcesUtil.getFile(getClass(), "test2.crt"); String clientKeyPassword = "12345"; mySetupMutualAuth(serverCrtFile, serverKeyFile, serverCrtFile, serverKeyPassword, serverCrtFile, clientKeyFile, clientCrtFile, clientKeyPassword); assertTrue(serverLatch.await(2, TimeUnit.SECONDS)); assertTrue(serverException instanceof SSLHandshakeException); }
Source:
public AffinityLabelModel flush() { return driver.flush(); }

Target:
public AffinityLabelModel flush() { addRemoveHostWidget.flush(); addRemoveVmWidget.flush(); return driver.flush(); }
Source:
public static boolean isNewEditorPromoRequired() { return getBoolean(UndeletablePrefKey.NEW_EDITOR_PROMO_REQUIRED, true); }

Target:
public static boolean isNewEditorPromoRequired() { return getBoolean(UndeletablePrefKey.AZTEC_EDITOR_PROMO_REQUIRED, true); }
Source:
public FilterDropdownListBox(FilterDropdownResources resources) { super(true); this.setStyleName(""); this.resources = resources; this.resources.filterDropdownStyle().ensureInjected(); mainPanel.setStyleName(this.resources.filterDropdownStyle().dropDown()); this.add(mainPanel); addInfoMessages(); mainPanel.getElement().getStyle().setProperty("maxHeight", "250px"); mainPanel.getElement().getStyle().setProperty("overflow", "auto"); }

Target:
public FilterDropdownListBox(FilterDropdownResources resources) { super(true); this.setStyleName(""); this.resources = resources; this.resources.filterDropdownStyle().ensureInjected(); mainPanel.setStyleName(this.resources.filterDropdownStyle().dropDown()); this.add(mainPanel); addInfoMessages(); mainPanel.getElement().getStyle().setProperty("overflow", "auto"); }
Source:
public Collection<Device> get( @QueryParam("all") boolean all, @QueryParam("userId") long userId, @QueryParam("id") List<Long> deviceIds) throws SQLException { if (deviceIds.isEmpty()) { if (all) { if (Context.getPermissionsManager().isAdmin(getUserId())) { return Context.getDeviceManager().getAllDevices(); } else { Context.getPermissionsManager().checkManager(getUserId()); return Context.getDeviceManager().getManagedDevices(getUserId()); } } else { if (userId == 0) { userId = getUserId(); } Context.getPermissionsManager().checkUser(getUserId(), userId); return Context.getDeviceManager().getDevices(userId); } } else { ArrayList<Device> devices = new ArrayList<>(); for (Long deviceId : deviceIds) { Device device = Context.getDeviceManager().getDeviceById(deviceId); Context.getPermissionsManager().checkDevice(getUserId(), device.getId()); devices.add(device); } return devices; } }

Target:
public Collection<Device> get( @QueryParam("all") boolean all, @QueryParam("userId") long userId, @QueryParam("id") List<Long> deviceIds) throws SQLException { if (deviceIds.isEmpty()) { if (all) { if (Context.getPermissionsManager().isAdmin(getUserId())) { return Context.getDeviceManager().getAllDevices(); } else { Context.getPermissionsManager().checkManager(getUserId()); return Context.getDeviceManager().getManagedDevices(getUserId()); } } else { if (userId == 0) { userId = getUserId(); } Context.getPermissionsManager().checkUser(getUserId(), userId); return Context.getDeviceManager().getDevices(userId); } } else { ArrayList<Device> devices = new ArrayList<>(); for (Long deviceId : deviceIds) { Context.getPermissionsManager().checkDevice(getUserId(), deviceId); devices.add(Context.getDeviceManager().getDeviceById(deviceId)); } return devices; } }
Source:
private void loadImage(final EffectData data) { exoPlayer.removeListener(listener); exoPlayerView.setVisibility(View.GONE); Url baseUrl = MediaManager.get().url().publicId(data.getPublicId()).transformation(data.getTransformation()); MediaManager.get().responsiveUrl(imageView, baseUrl, FIT, new ResponsiveUrl.Callback() { @Override public void onUrlReady(Url url) { currentUrl = url.generate(); } }); MediaManager.get().download(this) .load(data.getPublicId()) .transformation(data.getTransformation()) .responsive(FIT) .into(imageView); }

Target:
private void loadImage(final EffectData data) { exoPlayer.removeListener(listener); exoPlayerView.setVisibility(View.GONE); progressBar.setVisibility(View.VISIBLE); Url baseUrl = MediaManager.get().url().publicId(data.getPublicId()).transformation(data.getTransformation()); MediaManager.get().responsiveUrl(imageView, baseUrl, FIT, new ResponsiveUrl.Callback() { @Override public void onUrlReady(Url url) { currentUrl = url.generate(); } }); MediaManager.get().download(this) .load(data.getPublicId()) .transformation(data.getTransformation()) .responsive(FIT) .callback(new DownloadRequestCallback() { @Override public void onSuccess() { progressBar.setVisibility(View.GONE); } @Override public void onFailure(Throwable t) { progressBar.setVisibility(View.GONE); } }) .into(imageView); }
Source:
public SecurityGroup removeIpPermission(IpPermission ipPermission, SecurityGroup group) { String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation()); String name = group.getName(); String id = Iterables.get(client.getSecurityGroupApi().get().describeSecurityGroupsInRegion(region, name), 0).getId(); client.getSecurityGroupApi().get().revokeSecurityGroupIngressInRegion(region, id, ipPermission); return getSecurityGroupById(new RegionAndName(region, group.getName()).slashEncode()); }

Target:
public SecurityGroup removeIpPermission(IpPermission ipPermission, SecurityGroup group) { String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation()); String name = group.getName(); String id = groupNameToId.apply(new RegionAndName(region, name).slashEncode()); client.getSecurityGroupApi().get().revokeSecurityGroupIngressInRegion(region, id, ipPermission); return getSecurityGroupById(new RegionAndName(region, group.getName()).slashEncode()); }
Source:
public static Slice varcharToLongDecimal(Slice value, long precision, long scale, BigInteger tenToScale) { try { String stringValue = value.toString(UTF_8); BigDecimal decimal = new BigDecimal(stringValue).setScale(intScale(scale), HALF_UP); if (overflows(decimal, precision)) { throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast VARCHAR '%s' to DECIMAL(%s, %s)", stringValue, precision, scale)); } return encodeUnscaledValue(decimal.unscaledValue()); } catch (NumberFormatException e) { throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast VARCHAR '%s' to DECIMAL(%s, %s)", value.toString(UTF_8), precision, scale)); } }

Target:
public static Slice varcharToLongDecimal(Slice value, long precision, long scale, BigInteger tenToScale) { BigDecimal result; String stringValue = value.toString(UTF_8); try { result = new BigDecimal(stringValue).setScale(intScale(scale), HALF_UP); } catch (NumberFormatException e) { throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast VARCHAR '%s' to DECIMAL(%s, %s). Value is not a number.", stringValue, precision, scale)); } if (overflows(result, precision)) { throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast VARCHAR '%s' to DECIMAL(%s, %s). Value too large.", stringValue, precision, scale)); } return encodeUnscaledValue(result.unscaledValue()); }
Source:
protected boolean attachUserToSession() { if (!StringUtils.isEmpty(getParameters().getSessionId())) { SessionDataContainer.getInstance().setUser(getParameters().getSessionId(), getCurrentUser()); } else { if (!SessionDataContainer.getInstance().setUser(getCurrentUser())) { return failCanDoAction(VdcBllMessages.USER_CANNOT_LOGIN_SESSION_MISSING); } SessionDataContainer.getInstance().setSoftLimit(DateUtils.addMinutes(new Date(), 2 * Config.<Integer> getValue(ConfigValues.UserSessionTimeOutInterval))); int maxSessionInterval = Config.<Integer> getValue(ConfigValues.MaxSessionTimeoutInterval); Date validTo = DateUtils.addMinutes(new Date(), maxSessionInterval == 0 ? Integer.MAX_VALUE : maxSessionInterval); try { Date fromExtension = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ").parse(authRecord.<String> get(AuthRecord.VALID_TO)); validTo = validTo.compareTo(fromExtension) < 0 ? validTo : fromExtension; } catch (ParseException e) { log.warn("Error parsing AuthRecord.VALID_TO . Default VALID_TO value will be set on session"); } SessionDataContainer.getInstance().setHardLimit(validTo); } return true; }

Target:
protected boolean attachUserToSession() { if (!StringUtils.isEmpty(getParameters().getSessionId())) { SessionDataContainer.getInstance().setUser(getParameters().getSessionId(), getCurrentUser()); } else { if (!SessionDataContainer.getInstance().setUser(getCurrentUser())) { return failCanDoAction(VdcBllMessages.USER_CANNOT_LOGIN_SESSION_MISSING); } SessionDataContainer.getInstance().setSoftLimit(DateUtils.addMinutes(new Date(), 2 * Config.<Integer> getValue(ConfigValues.UserSessionTimeOutInterval))); int maxSessionInterval = Config.<Integer> getValue(ConfigValues.MaxSessionTimeoutInterval); Date validTo = maxSessionInterval != 0 ? DateUtils.addMinutes(new Date(), maxSessionInterval) : null; try { Date fromExtension = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ").parse(authRecord.<String> get(AuthRecord.VALID_TO)); if (validTo != null) { validTo = validTo.compareTo(fromExtension) < 0 ? validTo : fromExtension; } } catch (ParseException e) { log.warn("Error parsing AuthRecord.VALID_TO . Default VALID_TO value will be set on session"); } SessionDataContainer.getInstance().setHardLimit(validTo); } return true; }
Source:
private void createDataSourceModel(GraphRewrite event, EvaluationContext context, XmlFileModel xmlFileModel) { GraphContext graphContext = event.getGraphContext(); DataSourceService dataSourceService = new DataSourceService(graphContext); Set<ProjectModel> applications = ProjectTraversalCache.getApplicationsForProject(event.getGraphContext(), xmlFileModel.getProjectModel()); Document doc = new XmlFileService(graphContext).loadDocumentQuiet(event, context, xmlFileModel); for (String tagName : Arrays.asList(SINGLE_DATASOURCE_TAG, SINGLE_DATASOURCE_XA_TAG)) { for (Element element : $(doc).find(tagName).get()) { DataSourceModel dataSourceModel = dataSourceService.create(); boolean isXa = tagName.equals(SINGLE_DATASOURCE_XA_TAG); dataSourceModel.setName(element.getAttribute("jndi-name")); dataSourceModel.setApplications(applications); dataSourceModel.setXa(isXa); } } }

Target:
private void createDataSourceModel(GraphRewrite event, EvaluationContext context, XmlFileModel xmlFileModel) { GraphContext graphContext = event.getGraphContext(); DataSourceService dataSourceService = new DataSourceService(graphContext); Set<ProjectModel> applications = ProjectTraversalCache.getApplicationsForProject(event.getGraphContext(), xmlFileModel.getProjectModel()); Document doc = new XmlFileService(graphContext).loadDocumentQuiet(event, context, xmlFileModel); for (String tagName : Arrays.asList(SINGLE_DATASOURCE_TAG, SINGLE_DATASOURCE_XA_TAG)) { for (Element element : $(doc).find(tagName).get()) { DataSourceModel dataSourceModel = dataSourceService.create(); boolean isXa = tagName.equals(SINGLE_DATASOURCE_XA_TAG); dataSourceModel.setName(element.getAttribute("pool-name")); dataSourceModel.setJndiLocation(element.getAttribute("jndi-name")); dataSourceModel.setApplications(applications); dataSourceModel.setXa(isXa); } } }
Source:
private void enableStagingWidgets(boolean enabled) { unstagedViewer.getControl().setEnabled(enabled); stagedViewer.getControl().setEnabled(enabled); }

Target:
private void enableStagingWidgets(boolean enabled) { if (isDisposed()) return; unstagedViewer.getControl().setEnabled(enabled); stagedViewer.getControl().setEnabled(enabled); }
Source:
public Block mapFromEntries( @TypeParameter("map(K,V)") MapType mapType, ConnectorSession session, @SqlType("array(row(K,V))") Block block) { Type keyType = mapType.getKeyType(); Type valueType = mapType.getValueType(); RowType rowType = new RowType(ImmutableList.of(keyType, valueType), Optional.empty()); if (pageBuilder.isFull()) { pageBuilder.reset(); } int entryCount = block.getPositionCount(); BlockBuilder mapBlockBuilder = pageBuilder.getBlockBuilder(0); BlockBuilder resultBuilder = mapBlockBuilder.beginBlockEntry(); TypedSet uniqueKeys = new TypedSet(keyType, entryCount); for (int i = 0; i < entryCount; i++) { Block rowBlock = rowType.getObject(block, i); if (rowBlock.isNull(0)) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "map key cannot be null"); } if (uniqueKeys.contains(rowBlock, 0)) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Duplicate keys (%s) are not allowed", keyType.getObjectValue(session, rowBlock, 0))); } uniqueKeys.add(rowBlock, 0); keyType.appendTo(rowBlock, 0, resultBuilder); valueType.appendTo(rowBlock, 1, resultBuilder); } mapBlockBuilder.closeEntry(); pageBuilder.declarePosition(); return mapType.getObject(mapBlockBuilder, mapBlockBuilder.getPositionCount() - 1); }

Target:
public Block mapFromEntries( @TypeParameter("map(K,V)") MapType mapType, ConnectorSession session, @SqlType("array(row(K,V))") Block block) { Type keyType = mapType.getKeyType(); Type valueType = mapType.getValueType(); RowType rowType = new RowType(ImmutableList.of(keyType, valueType), Optional.empty()); if (pageBuilder.isFull()) { pageBuilder.reset(); } int entryCount = block.getPositionCount(); BlockBuilder mapBlockBuilder = pageBuilder.getBlockBuilder(0); BlockBuilder resultBuilder = mapBlockBuilder.beginBlockEntry(); TypedSet uniqueKeys = new TypedSet(keyType, entryCount); for (int i = 0; i < entryCount; i++) { Block rowBlock = rowType.getObject(block, i); if (rowBlock.isNull(0)) { mapBlockBuilder.closeEntry(); throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "map key cannot be null"); } if (uniqueKeys.contains(rowBlock, 0)) { mapBlockBuilder.closeEntry(); throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Duplicate keys (%s) are not allowed", keyType.getObjectValue(session, rowBlock, 0))); } uniqueKeys.add(rowBlock, 0); keyType.appendTo(rowBlock, 0, resultBuilder); valueType.appendTo(rowBlock, 1, resultBuilder); } mapBlockBuilder.closeEntry(); pageBuilder.declarePosition(); return mapType.getObject(mapBlockBuilder, mapBlockBuilder.getPositionCount() - 1); }