instruction
stringlengths
0
30k
I'm trying to reach a Rest WebService that should send me a JSON response, for which I need to expose a certificate in a KeyStore that lets me authenticate, meanwhile I need the same certificate to be in the TrustStore of my App so that my client recognizes the WebService. I succesfully put the keys in the SSLContext, but I didn't have the same luck with the TrustStore, since it keeps giving me `PKIX Path Building Failed`. This is the method that defines the Context: ``` public SSLContext defineTrustManager() { TrustManagerFactory trustManagerFactory; try { trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); X509TrustManager defaultX509CertificateTrustManager = null; for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) { if (trustManager instanceof X509TrustManager ) { defaultX509CertificateTrustManager = (X509TrustManager) trustManager; break; } } FileInputStream myKeys = new FileInputStream("./certificatiAddizionali"); KeyStore myTrustStore = KeyStore.getInstance(KeyStore.getDefaultType()); myTrustStore.load(myKeys, "".toCharArray()); trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(myTrustStore); X509TrustManager myTrustManager = null; for (TrustManager tm : trustManagerFactory.getTrustManagers()) { if (tm instanceof X509TrustManager ) { myTrustManager = (X509TrustManager) tm; break; } } X509TrustManager finalDefaultTm = defaultX509CertificateTrustManager; X509TrustManager finalMyTm = myTrustManager; X509TrustManager wrapper = new X509TrustManager() { private X509Certificate[] mergeCertificates() { ArrayList<X509Certificate> resultingCerts = new ArrayList<>(); resultingCerts.addAll(Arrays.asList(finalDefaultTm.getAcceptedIssuers())); resultingCerts.addAll(Arrays.asList(finalMyTm.getAcceptedIssuers())); return resultingCerts.toArray(new X509Certificate[resultingCerts.size()]); } @Override public X509Certificate[] getAcceptedIssuers() { return mergeCertificates(); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { try { finalMyTm.checkServerTrusted(chain, authType); } catch (CertificateException e) { finalDefaultTm.checkServerTrusted(chain, authType); } } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { finalDefaultTm.checkClientTrusted(mergeCertificates(), authType); } }; String keyPassphrase = ""; KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream("./certificatiKeystore"), keyPassphrase.toCharArray()); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, keyPassphrase.toCharArray()); SSLContext context = SSLContext.getInstance("TLS"); context.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { wrapper }, null); SSLContext.setDefault(context); return context; } catch (Exception e) { e.printStackTrace(); } return null; } ``` This is the test method I'm using to reach WS and check the response: ``` @RequestMapping(value = "/getSomething", method = RequestMethod.GET) public void test(HttpServletRequest request) { HttpResponse response = null; try { SSLContext sslContext = defineTrustManager(); HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build(); response =httpClient.execute(new HttpGet("mytesturl.com")); System.out.println(response); } catch(Exception e) { e.printStackTrace(); } } ``` In debug I can clearly see that the certificates are present and read by the TrustManagerFactory, so then why it keeps giving me the PKIX error? Ps. both the keystore and truststore have no password.
PKIX failed when using custom SSLcontext with custom keyStore and trustStore
|java|web-services|ssl|keystore|pkix|
So I have been tasked to create a program that compares the data on our Filemaker database with that of a website that contains the same set of data and identify discrepancies between the two. Any ideas on how I would go about this? Any help would be appreciated. Thank you so much :) I have been looking at some approaches that potentially utilise some of Filemaker's APIs, SQL queries as well as web scraping but was wondering if anybody had a better and clearer approach.
Data comparison between records on Filemaker database and website
|database|filemaker|data-comparison|
null
You can use `expected::transform`: static auto create(int val) noexcept -> std::expected<Foo, std::error_code> { if (val == 42) return std::unexpected<std::error_code>(std::in_place, EINVAL, std::generic_category() ); return std::expected<int, std::error_code>{val}.transform( [](int i) { return Foo{i}; } ); } [Demo](https://godbolt.org/z/Ejahrhxob)
```.size()``` returns the number of elements, whereas ```.sizeof()``` returns the number of bytes. For a character array, each element is one byte, which explains why the number is the same
Based on the provided code snippet, it seems you're using Bootstrap v5.3.3 and attempting to create a dropdown menu within a navbar. The code you've provided looks correct at first glance. However, if the dropdowns are not working as expected, there could be a few reasons: 1. **JavaScript Dependencies**: Bootstrap's dropdowns require both Bootstrap's JavaScript and Popper.js for proper functionality. 2. **Order of Script Imports**: Ensure that you're importing the Bootstrap JavaScript and Popper.js in the correct order, usually before the closing `</body>` tag. Let's adjust your code to include these dependencies in the correct order: ```html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bootstrap demo</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-expand-lg bg-body-tertiary"> <div class="container-fluid"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavDropdown"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Features</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Pricing</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Dropdown link </a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </li> </ul> </div> </div> </nav> <!-- jQuery and Bootstrap Bundle (includes Popper.js) --> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha384-KyZXEAg3QhqLMpG8r+Knujsl5/8h9YlT/Z4IxCX6JZ4n4zIz4+nRm4lE3hFfN4CV" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-Rr1eZ+5V4gFDRM/7QLoAj7th5f/+7x6zv1NwlXN+K35hrVNlt1Jjx4KaXgJsqQ4V" crossorigin="anonymous"></script> </body> </html> ``` Make sure to include jQuery before Bootstrap's JavaScript, and Bootstrap's bundle includes Popper.js, which is required for dropdowns to work properly. With these changes, your dropdowns should function as expected. If they still don't work, there might be other issues with your environment or code setup that need to be addressed.
How to get user's data file after decompiling an APK?
|kotlin|user-defined-functions|user-permissions|user-management|
null
The GUID is not even mandatory, so in my opinion it is not safe to consider it unique. I'd suggest you read [this blog post about rss feed duplicate detection][1]. ([archived copy][2]) [1]: http://www.xn--8ws00zhy3a.com/blog/2006/08/rss-dup-detection [2]: http://web.archive.org/web/20120201002535/http://www.xn--8ws00zhy3a.com/blog/2006/08/rss-dup-detection
null
Simple script: ``` import json import paramiko from rich import print, pretty, inspect from settings import domain pretty.install() convert_dom = json.dumps(domain) set_domain = json.loads(convert_dom) ip = "250" ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect(set_domain[ip]['host'], port=22, username='root', password=set_domain[ip]['pass']) except Exception as e: print('Ошибка подключения:', e) exit() stdin, stdout, stderr = ssh.exec_command('service mailerq restart') exit_status = stdout.channel.recv_exit_status() if exit_status == 0: stdout_output = stdout.read().decode("utf-8") print(f'STDOUD: {stdout_output}') stdout.close() else: stderr_output = stderr.read().decode("utf-8") print(f'STDERR: {stderr_output}') stderr.close() stdin.close() ssh.close() ``` I'm running it locally. The problem is that after execution the script does not end, but continues to be “executed”. Has anyone encountered this problem? Help me decide.
how to solve the problem of the script freezing after restarting the service in paramiko python
|python|ssh|paramiko|systemctl|
If your user account has the **Owner** role in an Azure subscription: - When you manually create a service principal in an AAD (Microsoft Entra ID), the service principal would not inherit the full permissions form your account. On same resources within the subscription, it might just have the **Contributor** role. - When you create an ARM service connection ([Azure Resource Manager service connection][1]) with the '**`automatic`**' option, it will automatically create a service principal for your user account. This service principal would just have the **Contributor** role on most resources by default, and also might not have access on some resources (such as Azure Key Vault) by default. [![enter image description here][2]][2] Only the **Owner** role has the permissions to do role assignment. So, you need to check and ensure the service principal has the **Owner** role within the subscription. Similarly, if you want to use the service principal to do role assignment on AAD (Microsoft Entra ID) level, it needs the **Privileged Role Administrator** or **Global Administrator** role in the AAD. --- [1]: https://learn.microsoft.com/en-us/azure/devops/pipelines/library/service-endpoints?view=azure-devops&tabs=yaml#azure-resource-manager-service-connection [2]: https://i.stack.imgur.com/Ow0Tp.jpg
uart in vhdl send a string
|vhdl|fpga|uart|
I've been working on a Springboot API, using MySQL as database. For deployment I'm using a docker-compose ```yaml version: "3.7" services: backend: build: ./backend networks: - shared-net environment: - spring.datasource.url=jdbc:mysql://application-db:3306/db?allowPublicKeyRetrieval=true ports: - 82:8080 depends_on: - application-db application-db: image: "mysql:latest" restart: always ports: - 3306:3306 networks: - shared-net environment: MYSQL_ROOT_PASSWORD: '' MYSQL_ALLOW_EMPTY_PASSWORD: "yes" MYSQL_DATABASE: db volumes: - ./db:/var/lib/mysql networks: shared-net: ``` On startup, I get the following error in logs: https://pastebin.com/zNq6JKs3 I've been debugging this & looking around for days & didn't find a fix. What I'm suspecting is an inheritance issue in these classes: ```java import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; @Data @Builder @NoArgsConstructor @AllArgsConstructor @Entity public class Etape { @Id @GeneratedValue private long id; @OneToMany(mappedBy = "etape", cascade = CascadeType.REMOVE) private List<Remarque> remarques; @ManyToOne() @JoinColumn(name = "idProjet") private Project project; @Column() private int termine; } ``` ```java package com.application.model.etapes.Etape1; import com.application.model.etapes.Etape; import jakarta.persistence.*; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.List; @EqualsAndHashCode(callSuper = true) @Data @Entity public class Etape1 extends Etape { @Column(columnDefinition = "TEXT") private String attr1; @Column() private String attr2; @Column() private boolean attr3; @OneToMany(mappedBy = "etape1", cascade = CascadeType.REMOVE) private List<Beneficiare> beneficiares; @OneToMany(mappedBy = "etape1", cascade = CascadeType.REMOVE) private List<Objectif> objectifs; @OneToMany(mappedBy = "etape1", cascade = CascadeType.REMOVE) private List<VeilleGlobal> veilleGlobals; @OneToOne(mappedBy ="etape1" , cascade = CascadeType.REMOVE) private Mission mission; } ``` Any help in debuging/fixing this issue is much appreciated and needed. NOTE: In the logs, there are 2 interesting errors: - `java.lang.ClassCastException: class org.hibernate.mapping.Bag cannot be cast to class org.hibernate.mapping.SimpleValue` - `PostInitCallbackEntry - Entity(com.model.etapes.Etape) `sqmMultiTableInsertStrategy` interpretation` The second one made me think of the inheritance issue, the first probably a relation issue? (ManyToOne/OneToMany) I tried using `@Inheritance(strategy = InheritanceType.SINGLE_TABLE)` but I kept getting the same error so, I'm a bit lost now
springboot class org.hibernate.mapping.Bag cannot be cast to class org.hibernate.mapping.SimpleValue
|java|spring|spring-boot|hibernate|spring-mvc|
When running the command: "pip3 install pyaudio" i get this error: "Collecting pyaudio Using cached PyAudio-0.2.14.tar.gz (47 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: pyaudio Building wheel for pyaudio (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for pyaudio (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [18 lines of output] running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.9-x86_64-cpython-38 creating build/lib.macosx-10.9-x86_64-cpython-38/pyaudio copying src/pyaudio/__init__.py -> build/lib.macosx-10.9-x86_64-cpython-38/pyaudio running build_ext building 'pyaudio._portaudio' extension creating build/temp.macosx-10.9-x86_64-cpython-38 creating build/temp.macosx-10.9-x86_64-cpython-38/src creating build/temp.macosx-10.9-x86_64-cpython-38/src/pyaudio gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -DMACOS=1 -I/usr/local/include -I/usr/include -I/opt/homebrew/include "-I<PATH FROM STEP 3>/include/" -I/Library/Frameworks/Python.framework/Versions/3.8/include/python3.8 -c src/pyaudio/device_api.c -o build/temp.macosx-10.9-x86_64-cpython-38/src/pyaudio/device_api.o src/pyaudio/device_api.c:9:10: fatal error: 'portaudio.h' file not found #include "portaudio.h" ^~~~~~~~~~~~~ 1 error generated. error: command '/usr/bin/gcc' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for pyaudio Failed to build pyaudio ERROR: Could not build wheels for pyaudio, which is required to install pyproject.toml-based projects" I am running MacOS 14.3.1. Any suggestions?
I wrote this time displaying FLUTTER app, How can I improve it?
|android|flutter|dart|datetime|
null
Change the react-native-screens version to: "react-native-screens": "3.29.0" There seems to be a issue with the current version of screens: The Fix: https: //github.com/software-mansion/react-native-screens/issues/2082 Other reports: https://github.com/software-mansion/react-native-screens/issues/2059
Assuming sorted range indexes, [`reset_index`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.reset_index.html) before [`merge`](https://pandas.pydata.org/docs/reference/api/pandas.merge.html), then [`sort_values`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.sort_values.html): ``` df3 = (pd.merge(df1.reset_index(), df2.reset_index(), how='outer', on='name', sort=False) .sort_values(by=['index_x', 'index_y'], ignore_index=True) .drop(columns=['index_x', 'index_y']) .rename({'value_x': 'v1','value_y':'y2'}, axis=1) ) ``` For a more generic case: ``` df3 = (pd.merge(df1.assign(index=np.arange(len(df1))), df2.assign(index=np.arange(len(df1))), how='outer', on='name', sort=False) .sort_values(by=['index_x', 'index_y'], ignore_index=True) .drop(columns=['index_x', 'index_y']) .rename({'value_x': 'v1','value_y':'y2'}, axis=1) ) ``` Alternatively, use the union of `df1['name']`/`df2['name']` to [`reindex`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html): ``` idx = pd.concat([df1['name'], df2['name']]).drop_duplicates() df3 = (pd.merge(df1, df2, how='outer', on='name', sort=False) .set_index('name').reindex(idx).reset_index() .rename({'value_x': 'v1','value_y':'y2'}, axis=1) ) ``` Output: ``` name v1 y2 0 4A 1.0 3.0 1 3B 2.0 NaN 2 2C 3.0 9.0 3 1D 4.0 NaN 4 6F NaN 2.0 5 5G NaN 1.0 ```
What are the pros and cons of a directive based programming model? Taking for instance a programming model like OpenMP, what are the disadvantages and advantages you get when using a directive based programming framework like this over one like SYCL which is explicit.
What are the pros and cons of a directive based programming model?
|c++|openmp|pragma|sycl|
I am trying to study the dynamics of a charged particle inside potential fields. I tried defining a dummy potential like this ``` x = np.linspace(-20, 20, 10) y = np.linspace(-20, 20, 10) z = np.linspace(0, 10, 10) X, Y, Z = np.meshgrid(x, y, z) V = X**2 + Y**2 + Z**2 ``` and I used gradient function to get Electric field at each point. ``` Ex, Ey, Ez = np.gradient(V) ``` This gives me a (10,10,10) 3d array. Now the problem arises when I am studying the motion of a particle with some mass in this vector field. for example, my force is defined like this ``` f_e[i][0] = -Q * Ex_at_r #Ex but at that r_x value particle is currently f_e[i][1] = -Q * Ey_at_r f_e[i][2] = -Q * Ez_at_r ``` when it comes to forces like gravity you don't need to worry about all this I can just have a 1-D array like this `f_g = np.array([0,0,-g])` and call it day, but my f_e is changing as the particle moves. I already tried defining f_e like this, `f_e_x = -Q*r[i][0] # X_component of position vector for `ith` iteration`, and this sort of works but this still isn't same as having a vector field and a charge thrown in it. Is there a standard way to go about this?
How can i install pyaudio on MacOS
|pyaudio|
the only other code used in this from anywhere else is Player::getPosition(), which is just returning playerSprite.getPosition() and Game::update which passes Player::getPosition() to this function `sf::Vector2f enemyLocation{0.f, 0.f};` starting value of enemyLocation for debugging ``` ///<summary> /// gets the amount enemy should move /// called from Game.update() ///</summary> /// <param name="t_playerPos"> player window position </param> /// <returns> enemy move amount per frame (normalised) </returns> sf::Vector2f Enemy::attemptMove(sf::Vector2f t_playerPos) { sf::Vector2f movement = { 0.f, 0.f }; // movement towards player each frame sf::Vector2f direction = t_playerPos - enemyLocation; // delta playerPos and enemyPos float angle = atan2f(direction.y, direction.x); // angle to player (rad) angle = angle * 180.f / M_PI; // convert angle to degrees float hyp = 1.f; // length of line to player (used for normalisation of vector) // check if enemy is horizontally in line with player if (direction.x == 0.f) { if (direction.y > 0.f) { movement.y = hyp; } // move straight down else { movement = -hyp; } // move straight up } // check if enemy is vertically in line with player else if (direction.y == 0.f) { if (direction.x > 0.f) { movement.x = hyp; } // move right else { movement.x = -hyp; } // move left } // if enemy is not in line with player else { // ratio of sides y:x = opp:adj movement.y = sinf(angle); movement.x = cosf(angle); // normalising the vector hyp = sqrtf(abs(movement.x * movement.x) + abs(movement.y * movement.y)); hyp = abs(1.f / hyp); // inverse of pythagoras theorem hypothenuse movement.x = hyp * movement.x; movement.y = hyp * movement.y; // sqrt(x^2 + y^2) should equal 1 move(movement); } return movement; // return to Game::update() (not currently assigned to anything there) } ///<summary> /// moves the enemy by the amount it should each frame /// in final code will be called from Game.update() /// for now only called from Enemy::attemptMove() ///</summary> ///<param name="t_movement"> amount to move each frame towards player </param> void Enemy::move(sf::Vector2f t_movement) { enemyLocation += t_movement; // update enemy location enemySprite.setPosition(enemyLocation); // set enemy position to updated location } ``` my includes are ``` #include <SFML/Graphics.hpp> #include <iostream> #define _USE_MATH_DEFINES #include <math.h> ``` I expect the enemy to move in a straight line to the player, which does happen if the player is stationary If the player moves diagonally away from the enemy, this also works, but if the player moves any other direction, the enemy spins in a circle (sometimes spiral) until the player stops moving or starts moving diagonally away from the enemy, or sometimes moves in a straight line in a completely wrong direction. I have tried: - assigning attemptMove() to a variable in Game::update and passing that to Enemy::move() - including an alpha and beta angle and calculating the ratios of the angle by Sine rule - including breakpoints to verify the angle is correct (it always seems to be) - removing the checks for "in line" with player and always running the calculation - changing if (movement.x/y == 0.f) to if (abs(movement.x/y) < 0.01f) and < epsilon - changing where the functions are called from and what args are passed to them - a few other changes, none of which seemed to have any promise - rewriting large sections of the code outside of the block shown, which naturally had no effect - cleaning up my code, (this is actually even cleaner than the one in my actual project, though I did run it to make sure it definitely didn't work before posting it) nothing seems to have any effect, and a lot of things make the problem worse or more severe, I really don't know what else there is to do ``` void Enemy::attemptMove(sf::Vector2f t_playerPos) { sf::Vector2f direction = t_playerPos - enemyLocation; // playerPos-enemyPos (direction to player) float hyp; // normalising the vector hyp = sqrtf(abs(direction.x * direction.x) + abs(direction.y * direction.y)); hyp = abs(1.f / hyp); // inverse of pythagoras theorem hypothenuse direction.x = hyp * direction.x; direction.y = hyp * direction.y; // sqrt(x^2 + y^2) should equal 1 move(direction); } void Enemy::move(sf::Vector2f t_movement) { enemyLocation += t_movement; // update enemy location enemySprite.setPosition(enemyLocation); // set enemy position to updated location } ```
For the approach you want in your app you need to use protected routes you can learn more in this blog : [https://blog.logrocket.com/authentication-react-router-v6/][1] Create normal routes import { createBrowserRouter } from 'react-router-dom'; //import all the page components here export const router = createBrowserRouter([ { path: '/', element: <Layout />, children: [ { index: true, element: <Login />, }, { path: 'signup', element: <SignUp />, }, { path: 'dashboard', element: ( <ProtectedRoute allowedRoles={roles.vendor}> <VendorDashboard /> </ProtectedRoute> ), }, { path: 'items', element:( <ProtectedRoute allowedRoles={roles.vendor}> <Items /> </ProtectedRoute> ), }, { path: 'buyer-dashboard', element:( <ProtectedRoute allowedRoles={roles.buyer}> <Dashboard /> </ProtectedRoute> ), }, { path: 'other', element:( <ProtectedRoute allowedRoles={roles.buyer}> <Other /> </ProtectedRoute> ), }, ],},]); const roles = { buyer: ['buyer-dashboard', 'other'], vendor: ['dashboard', 'items'], }; Make a function to retrieve to roles of the user on login const getUserRole = () => { return 'superAdmin'; }; now make a component for protected route import { Navigate } from 'react-router-dom'; const ProtectedRoute = ({ children, allowedRoles }) => { const userRole = getUserRole(); const isAuthenticated = true; if (!isAuthenticated) { return <Navigate to="/login" replace />; } if (!allowedRoles.includes(userRole)) { return <Navigate to="/unauthorized" replace />; } return children // <Outlet />; tyou can use Outlet here to }; export default ProtectedRoute; [1]: https://blog.logrocket.com/authentication-react-router-v6/
Why does the first test pass and the second one fail? ```java import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; import com.github.tomakehurst.wiremock.junit5.WireMockTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import org.springframework.http.HttpStatus; import org.springframework.web.reactive.function.client.ClientResponse; import org.springframework.web.reactive.function.client.WebClient; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; @WireMockTest public class GenericTest { int port; String responseBody; @BeforeEach void setUp(WireMockRuntimeInfo info) { port = info.getHttpPort(); responseBody = "response-body"; ResponseDefinitionBuilder response = aResponse() .withStatus(HttpStatus.OK.value()) .withBody(responseBody); stubFor(get("/test").willReturn(response)); } @Test void test1() { Mono<String> bodyMono = WebClient.builder() .baseUrl("http://localhost:%d".formatted(port)) .build() .get() .uri("/test") .retrieve() .bodyToMono(String.class); StepVerifier.create(bodyMono) .expectNext(responseBody) .verifyComplete(); } @Test void test2() { Mono<ClientResponse> responseMono = WebClient.builder() .baseUrl("http://localhost:%d".formatted(port)) .build() .get() .uri("/test") .exchangeToMono(Mono::just); StepVerifier.create(responseMono.flatMap(r -> r.bodyToMono(String.class))) .expectNext(responseBody) .verifyComplete(); } } ``` ```lang-none java.lang.AssertionError: expectation "expectNext(response-body)" failed (expected: onNext(response-body); actual: onComplete()) ``` I need to assert on a `ClientResponse` specifically. It has expected status and headers, but the body is always empty (even though it shouldn't). I tried calling `releaseBody()` first, but it doesn't help ```java // passes StepVerifier.create(responseMono.flatMap(ClientResponse::releaseBody)) .verifyComplete(); // still fails StepVerifier.create(responseMono.flatMap(r -> r.bodyToMono(String.class))) .expectNext(responseBody) .verifyComplete(); ```
SMTP error 421 denotes a problem with your outgoing server connection. This can often occur as a result of too many connections or a high volume of messages being sent within a short timeframe. https://www.ongage.com/glossary/smtp-error-421/
I am trying to align a tree structure I made with ggtree to an alluvial plot I made with ggalluvial. Here is a simple example data and the code I used: library(ggtreeExtra) library(ggtree) library(ggalluvial) data <- data.frame(v1 = c("t1","t2","t3","t1","t1","t2"), v2 = c("v1","v2","v3","v2","v3","v3"), n = c(1,1,1,2,3,1)) tr <- rtree(3) p_tree <- ggtree(tr)+geom_tiplab(align=TRUE) p_tree + geom_fruit(data = data, geom = geom_alluvium, mapping = aes(y = n, axis1 = v1, axis2 = v2, fill = v1)) But I get the following error: "Error in `$<-.data.frame`(`*tmp*`, "xtmp", value = 0) : replacement has 1 row, data has 0" Any idea what is going wrong? I tried to have the same order in the tree and the ggalluvial data, but it's still not working.
Aligning a tree structure with an alluvial plot using ggtreeExtra
|ggtree|ggalluvial|
null
How about: #define SV(str) _Generic(&("" str "") \ , char(*)[sizeof(str)]: sizeof(str) - 1 \ , const char(*)[sizeof(str)]: sizeof(str) - 1 \ ) #include <stddef.h> #include <stdio.h> int main() { printf("%zu\n", SV("test")); printf("%zu\n", SV("test" "test")); static const char *const s = "hello"; char word[] = "hello"; double a = 0.0f; double *d = &a; printf("%zu\n", SV(NULL)); printf("%zu\n", SV(word)); printf("%zu\n", SV(d)); printf("%zu\n", SV(s)); printf("%zu\n", SV()); printf("%zu\n", SV(/*comment*/)); printf("%zu\n", SV(-)); printf("%zu\n", SV("abc" - "def")); }
I have a current project of put sentences embeddings into clusters. I already have my embeddings and some clusters associated to a part of my sentences dataset. My goal is to use sentence similarity to my embeddings in order to apply a cluster to each of my sentence. I have in mind to use K nearest neighbours algorithm to label each of my sentence with a cluster. But I am not sure if it would work efficiently. Do you have any other idea that would perform great in this kind of situation ?
Project ideas about clustering and sentences similarity
|python|machine-learning|cluster-analysis|sentence-similarity|
I'm currently confused about windows and states. Suppose I have a program that counts user access data every minute and needs to do sum statistics in each window. Assume that at this time, I configure checkpoint for the fault tolerance of the program. The checkpoint configuration is to trigger every 30 seconds. Then when the time is 01:00, the program hangs. In theory, it can only be restored to the state data at 00:30, but there is no trigger window at 00:30. After calculation, we get the kafka offset data at 00:30 and the window data at 00:00. Is there any problem with my understanding? here is my program: [flink graph][1] build stream: //config is config.getDelayMaxDuration() = 60000 SingleOutputStreamOperator<BaseResult> wordCountSampleStream = subStream.assignTimestampsAndWatermarks( WatermarkStrategy.<MetricEvent>forBoundedOutOfOrderness(config.getDelayMaxDuration()) .withTimestampAssigner(new MetricEventTimestampAssigner()) .withIdleness(config.getWindowIdlenessTime()) ).setParallelism(CommonJobConfig.getParallelismOfSubJob("WORD_COUNT_SAMPLE_TEST")) .flatMap(new WordCountToResultFlatMapFunction(config)).setParallelism(CommonJobConfig.getParallelismOfSubJob("WORD_COUNT_SAMPLE_TEST")) .keyBy(new BaseResultKeySelector()) .window(TumblingEventTimeWindows.of(Time.milliseconds(config.getAggregateWindowMillisecond()))) .apply(new WordCountWindowFunction(config)).setParallelism(CommonJobConfig.getParallelismOfSubJob("WORD_COUNT_SAMPLE_TEST")); wordCountSampleStream.addSink(sink).setParallelism(CommonJobConfig.getParallelismOfSubJob("WORD_COUNT_SAMPLE_TEST")); window apply function: public class WordCountWindowFunction extends RichWindowFunction<BaseResult, BaseResult, String, TimeWindow> { private StreamingConfig config; private Logger logger = LoggerFactory.getLogger(WordCountWindowFunction.class); public WordCountWindowFunction(StreamingConfig config) { this.config = config; } @Override public void close() throws Exception { super.close(); } @Override public void apply(String s, TimeWindow window, Iterable<BaseResult> input, Collector<BaseResult> out) throws Exception { WordCountEventPortrait result = new WordCountEventPortrait(); long curWindowTimestamp = window.getStart() / config.getAggregateWindowMillisecond() * config.getAggregateWindowMillisecond(); result.setDatasource("word_count_test"); result.setTimeSlot(curWindowTimestamp); for (BaseResult sub : input) { logger.info("in window cur sub is {} ", sub); WordCountEventPortrait curInvoke = (WordCountEventPortrait) sub; result.setTotalCount(result.getTotalCount() + curInvoke.getTotalCount()); result.setWord(curInvoke.getWord()); } logger.info("out window result is {} ", result); out.collect(result); } } sink function: public class ClickHouseRichSinkFunction extends RichSinkFunction<BaseResult> implements CheckpointedFunction { private ConcurrentHashMap<String, SinkBatchInsertHelper<BaseResult>> tempResult = new ConcurrentHashMap<>(); private ClickHouseDataSource dataSource; private Logger logger = LoggerFactory.getLogger(ClickHouseRichSinkFunction.class); @Override public void snapshotState(FunctionSnapshotContext context) throws Exception { logger.info("start insert all temp data with snapshot"); long count =0; for (Map.Entry<String, SinkBatchInsertHelper<BaseResult>> helper : tempResult.entrySet()) { count = count + helper.getValue().insertAllTempData(); } logger.info("insert all temp data with snapshot end,insert count is {}",count); } @Override public void initializeState(FunctionInitializationContext context) throws Exception { } @Override public void open(Configuration parameters) throws Exception { Properties properties = new Properties(); properties.setProperty("user", CommonJobConfig.CLICKHOUSE_USER); properties.setProperty("password", CommonJobConfig.CLICKHOUSE_PASSWORD); dataSource = new ClickHouseDataSource(CommonJobConfig.CLICKHOUSE_JDBC_URL, properties); } @Override public void close() { log.info("准备处理未插入至Clickhouse的数据"); AtomicInteger totalCount = new AtomicInteger(); tempResult.values().forEach(it -> { totalCount.addAndGet(it.getTempList().size()); batchSaveBaseResult(it.getTempList()); it.getTempList().clear(); }); log.info("处理完毕,共插入{}条数据", totalCount.get()); } @Override public void invoke(BaseResult value, Context context) { tempResult.compute(value.getDatasource(), (datasource, baseResults) -> { if (baseResults == null) { baseResults = new SinkBatchInsertHelper<>(CommonJobConfig.COMMON_BATCH_INSERT_COUNT, needToInsert -> batchSaveBaseResult(needToInsert), CommonJobConfig.BATCH_INSERT_INTERVAL_MS); } baseResults.tempInsertSingle(value); return baseResults; }); } private void batchSaveBaseResult(List<BaseResult> list) { if (list.isEmpty()) { return; } String sql = list.get(0).getPreparedSQL(); try { try (PreparedStatement ps = dataSource.getConnection().prepareStatement(sql)) { for (BaseResult curResult : list) { curResult.addParamsToPreparedStatement(ps); ps.addBatch(); } ps.executeBatch(); } } catch (SQLException error) { log.error("has exception during batch insert,datasource is {} ", list.get(0).getDatasource(), error); } } } batch insert helper: public class SinkBatchInsertHelper<T> { private List<T> waitToInsert; private ReentrantLock lock; private int bulkActions; private AtomicInteger tempActions; private Consumer<List<T>> consumer; private AtomicLong lastSendTimestamp; private long sendInterval; private Logger logger = LoggerFactory.getLogger(SinkBatchInsertHelper.class); public SinkBatchInsertHelper(int bulkActions, Consumer<List<T>> consumer, long sendInterval) { this.waitToInsert = new ArrayList<>(); this.lock = new ReentrantLock(); this.bulkActions = bulkActions; this.tempActions = new AtomicInteger(0); this.consumer = consumer; this.sendInterval = sendInterval; this.lastSendTimestamp = new AtomicLong(0); } public void tempInsertSingle(T data) { lock.lock(); try { waitToInsert.add(data); if (tempActions.incrementAndGet() >= bulkActions || ((System.currentTimeMillis() - lastSendTimestamp.get()) >= sendInterval)) { //批量插入 batchInsert(); } } finally { lastSendTimestamp.set(System.currentTimeMillis()); lock.unlock(); } } public long insertAllTempData() { lock.lock(); try { long result = tempActions.get(); if (tempActions.get() > 0) { batchInsert(); } return result; } finally { lock.unlock(); } } private void batchInsert() { for(T t: waitToInsert){ logger.info("batch insert data:{}", t); } consumer.accept(waitToInsert); waitToInsert.clear(); tempActions.set(0); } public int getTempActions() { return tempActions.get(); } public List<T> getTempList() { lock.lock(); try { return waitToInsert; } finally { lock.unlock(); } } } The resulting phenomenon is: Suppose I cancel the task at 00:31:30, then when I restart the task, the statistics at 00:31:00 will be less than expected. I found out by printing records that it was because when the sink wrote the data at 00:30:00, the kafka consumer had actually consumed the data after 00:31:00, but this part of the data was not written to ck. , it was not replayed in the window when restarting, so this part of the data was lost. The statistics will not return to normal until 00:32:00. [1]: https://i.stack.imgur.com/03630.png
It's possible that the additional index you're seeing is automatically created by Neo4j for internal use. Neo4j may create additional indexes to optimize its internal operations, and these indexes might not be directly created by users. In your case, the "Lookup" index that is showing null properties could be one of these internal indexes. To confirm whether this index is indeed an internal index created by Neo4j, you can try querying the system catalogs directly. For example, you can use the following query to list all indexes in the database: CALL db.indexes() YIELD description RETURN description
PrivateGPT : Previous correct answer instead of creating a new one
|privategpt|
{"OriginalQuestionIds":[19597473],"Voters":[{"Id":11082165,"DisplayName":"Brian61354270"},{"Id":-1,"DisplayName":"Community","BindingReason":{"DuplicateApprovedByAsker":""}}]}
To load the Json with the data first get the cookies from the main page: ```py import pandas as pd import requests headers = { "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0" } url = "https://www.nseindia.com/api/corporate-announcements?index=equities" with requests.session() as s: s.headers.update(headers) s.get("https://www.nseindia.com/companies-listing/corporate-filings-announcements") data = s.get(url).json() df = pd.DataFrame(data) print(df) ``` Prints: ```none symbol desc dt attchmntFile sm_name sm_isin an_dt sort_date seq_id smIndustry orgid attchmntText bflag old_new csvName exchdisstime difference 0 SASKEN Change in Management 31032024234101 https://nsearchives.nseindia.com/corporate/SASKEN_31032024234101_Ltr_to_SE_Retirement_B_Ramkumar_SMP_31_Mar_2024.pdf Sasken Technologies Limited INE231F01020 31-Mar-2024 23:41:01 2024-03-31 23:41:01 105801547 Computers - Software None Sasken Technologies Limited has informed the Exchange about change in Management None None None 31-Mar-2024 23:41:06 00:00:05 1 CEREBRAINT Trading Window-XBRL 31032024234041 https://nsearchives.nseindia.com/corporate/xbrl/CEREBRAINT_31032024234042_CLOSURE_TRADING_WINDOW_1078060_31032024114041_WEB.xml Cerebra Integrated Technologies Limited INE345B01019 31-Mar-2024 23:40:41 2024-03-31 23:40:41 105801546 None None CEREBRA INTEGRATED TECHNOLOGIES LIMITED has informed the Exchange about Closure of Trading Window None None None 31-Mar-2024 23:40:46 00:00:05 2 UNIVASTU Updates 31032024233728 https://nsearchives.nseindia.com/corporate/UNIVASTU_31032024233728_Disposalofshare.pdf Univastu India Limited INE562X01013 31-Mar-2024 23:37:28 2024-03-31 23:37:28 105801545 None None Univastu India Limited has informed the Exchange regarding 'Disposal of shares'. None None None 31-Mar-2024 23:37:32 00:00:04 3 CEREBRAINT Trading Window 31032024233603 https://nsearchives.nseindia.com/corporate/CEREBRAINT_31032024233603_SEINTIMATION.pdf Cerebra Integrated Technologies Limited INE345B01019 31-Mar-2024 23:36:03 2024-03-31 23:36:03 105801544 None None Cerebra Integrated Technologies Limited has informed the Exchange regarding the Trading Window closure pursuant to SEBI (Prohibition of Insider Trading) Regulations, 2015 None None None 31-Mar-2024 23:36:07 00:00:04 4 CAREERP Change in Directors/ Key Managerial Personnel/ Auditor/ Compliance Officer/ Share Transfer Agent 31032024232247 https://nsearchives.nseindia.com/corporate/xbrl/CAREERP_31032024232247_CIM_21314_1078057_31032024112246_WEB.xml Career Point Limited INE521J01018 31-Mar-2024 23:22:47 2024-03-31 23:22:47 105801542 Computers - Software None CAREER POINT LIMITED has informed the Exchange about Change in Directors/ Key Managerial Personnel/ Auditor/ Compliance Officer/ Share Transfer Agent None None None 31-Mar-2024 23:22:53 00:00:06 5 WELCORP Trading Window-XBRL 31032024232101 https://nsearchives.nseindia.com/corporate/xbrl/WELCORP_31032024232101_CLOSURE_TRADING_WINDOW_1078055_31032024112101_WEB.xml Welspun Corp Limited INE191B01025 31-Mar-2024 23:21:01 2024-03-31 23:21:01 105801541 Steel And Steel Products None Welspun Corp Limited has informed the Exchange about Closure of Trading Window None None None 31-Mar-2024 23:21:10 00:00:09 6 PRESTIGE Acquisition 31032024232058 https://nsearchives.nseindia.com/corporate/PRESTIGE_31032024232058_Intimation.pdf Prestige Estates Projects Limited INE811K01011 31-Mar-2024 23:20:58 2024-03-31 23:20:58 105801540 Construction None Prestige Estates Projects Limited has informed the Exchange about Acquisition of 50% partnership interest in Prestige Realty Ventures None None None 31-Mar-2024 23:21:02 00:00:04 7 APTECHT Updates 31032024231519 https://nsearchives.nseindia.com/corporate/APTECHT_31032024231519_ReconsitutionofCommitees.pdf Aptech Limited INE266F01018 31-Mar-2024 23:15:19 2024-03-31 23:15:19 105801537 Computers - Software None Reconstitution of Audit Committee, Nomination and Remuneration Committee andStakeholders Relationship Committee None None None 31-Mar-2024 23:15:25 00:00:06 8 RAMCOCEM Change in Directors/ Key Managerial Personnel/ Auditor/ Compliance Officer/ Share Transfer Agent 31032024231041 https://nsearchives.nseindia.com/corporate/xbrl/RAMCOCEM_31032024231041_CIM_21312_1078048_31032024111040_WEB.xml The Ramco Cements Limited INE331A01037 31-Mar-2024 23:10:41 2024-03-31 23:10:41 105801535 None None THE RAMCO CEMENTS LIMITED has informed the Exchange about Change in Directors/ Key Managerial Personnel/ Auditor/ Compliance Officer/ Share Transfer Agent None None None 31-Mar-2024 23:10:51 00:00:10 9 INDIAGLYCO Updates 31032024231038 https://nsearchives.nseindia.com/corporate/INDIAGLYCO_31032024231038_Reg30GraincapacityandNSUAugustMarch24.pdf India Glycols Limited INE560A01015 31-Mar-2024 23:10:38 2024-03-31 23:10:38 105801534 Chemicals - Organic None India Glycols Limited has informed the Exchange regarding 'Update on enhancement of capacity of Grain Based Distillery and facilities/project for New Specialty Chemicals.'. None None None 31-Mar-2024 23:10:44 00:00:06 10 CAREERP Change in Director(s) 31032024230809 https://nsearchives.nseindia.com/corporate/CAREERP_31032024230809_CPL_Change_In_Directorate.pdf Career Point Limited INE521J01018 31-Mar-2024 23:08:09 2024-03-31 23:08:09 105801533 Computers - Software None Career Point Limited has informed the Exchange regarding Change in Director(s) of the company. None None None 31-Mar-2024 23:08:16 00:00:07 11 JUSTDIAL Change in Directors/ Key Managerial Personnel/ Auditor/ Compliance Officer/ Share Transfer Agent 31032024230216 https://nsearchives.nseindia.com/corporate/xbrl/JUSTDIAL_31032024230216_CIM_21311_1078045_31032024110215_WEB.xml Just Dial Limited INE599M01018 31-Mar-2024 23:02:16 2024-03-31 23:02:16 105801532 None None JUST DIAL LIMITED has informed the Exchange about Change in Directors/ Key Managerial Personnel/ Auditor/ Compliance Officer/ Share Transfer Agent None None None 31-Mar-2024 23:02:22 00:00:06 12 JUSTDIAL Appointment 31032024225920 https://nsearchives.nseindia.com/corporate/JUSTDIAL_31032024225920_regulation30.pdf Just Dial Limited INE599M01018 31-Mar-2024 22:59:20 2024-03-31 22:59:20 105801531 None None Completion of term of Ms. Bhavna Thakur, Independent Director of the Company and appointment of Ms. Bhama Krishnamurthy as an additional director designated as an Independent Director. None None None 31-Mar-2024 22:59:27 00:00:07 13 ADL Trading Window-XBRL 31032024225502 https://nsearchives.nseindia.com/corporate/xbrl/ADL_31032024225502_CLOSURE_TRADING_WINDOW_1078043_31032024105501_WEB.xml Archidply Decor Limited INE0CHO01012 31-Mar-2024 22:55:02 2024-03-31 22:55:02 105801530 None None ARCHIDPLY DECOR LIMITED has informed the Exchange about Closure of Trading Window None None None 31-Mar-2024 22:55:07 00:00:05 14 TITAGARH Cessation 31032024225203 https://nsearchives.nseindia.com/corporate/TITAGARH_31032024225204_IDCESSATIONSEDISCLOSURE31032024.pdf TITAGARH RAIL SYSTEMS LIMITED INE615H01020 31-Mar-2024 22:52:03 2024-03-31 22:52:03 105801529 None None TITAGARH RAIL SYSTEMS LIMITED has informed the Exchange regarding Cessation of Mr Sunirmal Talukdar (DIN: 00920608) as Non- Executive Independent Director of the company w.e.f. March 31, 2024. None None None 31-Mar-2024 22:52:17 00:00:14 15 TITAGARH Cessation 31032024225203 https://nsearchives.nseindia.com/corporate/TITAGARH_31032024225203_IDCESSATIONSEDISCLOSURE31032024.pdf TITAGARH RAIL SYSTEMS LIMITED INE615H01020 31-Mar-2024 22:52:03 2024-03-31 22:52:03 105801528 None None TITAGARH RAIL SYSTEMS LIMITED has informed the Exchange regarding Cessation of Mr Manoj Mohanka as Non- Executive Independent Director of the company w.e.f. March 31, 2024. None None None 31-Mar-2024 22:52:10 00:00:07 16 ADL Trading Window 31032024224744 https://nsearchives.nseindia.com/corporate/ADL_31032024224744_tradingwindowsigned.pdf Archidply Decor Limited INE0CHO01012 31-Mar-2024 22:47:44 2024-03-31 22:47:44 105801527 None None Archidply Decor Limited has informed the Exchange regarding the Trading Window closure pursuant to SEBI (Prohibition of Insider Trading) Regulations, 2015 None None None 31-Mar-2024 22:47:50 00:00:06 17 MASTEK Updates 31032024224617 https://nsearchives.nseindia.com/corporate/MASTEK_31032024224617_DubaiEntitiesPenalty31032024signed.pdf Mastek Limited INE759A01021 31-Mar-2024 22:46:17 2024-03-31 22:46:17 105801526 Computers - Software None Mastek Limited has informed the Exchange regarding ' Intimation of payment of penalty by UAE based group Subsidiary entities'. None None None 31-Mar-2024 22:46:24 00:00:07 18 RAMCOCEM Change in Director(s) 31032024224455 https://nsearchives.nseindia.com/corporate/RAMCOCEM_31032024224455_DIRSCESSSIGNED.pdf The Ramco Cements Limited INE331A01037 31-Mar-2024 22:44:55 2024-03-31 22:44:55 105801525 None None The Ramco Cements Limited has informed the Exchange regarding Change in Director(s) of the company. None None None 31-Mar-2024 22:45:01 00:00:06 19 ASIANPAINT Change in Directors/ Key Managerial Personnel/ Auditor/ Compliance Officer/ Share Transfer Agent 31032024223609 https://nsearchives.nseindia.com/corporate/xbrl/ASIANPAINT_31032024223609_CIM_21310_1078039_31032024103608_WEB.xml Asian Paints Limited INE021A01018 31-Mar-2024 22:36:09 2024-03-31 22:36:09 105801523 Paints None ASIAN PAINTS LIMITED has informed the Exchange about Change in Directors/ Key Managerial Personnel/ Auditor/ Compliance Officer/ Share Transfer Agent None None None 31-Mar-2024 22:36:15 00:00:06 ```
even after many years writing typescript you somtimes you get unexpected results: assume generic type function `WithComponentOverride` which its purpose is accepting component props and another generic parameter which tells which ComponentType the component is: ```typscript export type WithComponentOverride<P, T extends React.ElementType> = P & { component: T; } & InferProps<T>; export type InferProps<T extends React.ElementType> = T extends React.ComponentType<infer P> ? P : {}; ``` and usage: ```tsx interface MyComponentProps { someProp: number; // ... other props } const MyComponent = <T extends React.ElementType>( props: WithComponentOverride<MyComponentProps, T>, ) => { const Component = props.component; return <Component {...props} />; }; ``` now other componets can use `MyComponent` and decide which Host element the root of the component would be in typesafe way: ```tsx import { Box } from "@mui/material"; const UsingMyComponent = () => { return ( <MyComponent component={Box} someProp={5} sx={{ height: 10 }} // <-- perfectly typed! /> ); }; ``` works perfectly. now let's try to apply this generic type on much complicated type, taken from the <Link/> component from [`@tanstack/react-router`](https://tanstack.com/router/latest) ```tsx import { Link as TanstackLink } from "@tanstack/react-router"; type TanstackLinkProps = Parameters<typeof TanstackLink>[0]; const Link = <T extends React.ElementType>( props: WithComponentOverride<TanstackLinkProps, T>, ) => { const component = props.component; // TS2339: Property component does not exist on type <...blabla...> // ... }; ``` we get `TS2339` error even we shouldn't get one. we can even see `{ component: T; }` right there in the type: ``` Property 'component' does not exist on type '{ ...HUGE_OBJECT_TRIMMED... } & { component: T; } & InferProps<T>'. ``` WHAT'S GOING ON? im genuialy thinks that is a typescript bug here, but i cant tell for sure. --- for the curious, here the full typescript error: ``` Property 'component' does not exist on type '{ cite?: string | undefined; data?: string | undefined; form?: string | undefined; label?: string | undefined; search?: any; slot?: string | undefined; span?: number | undefined; style?: CSSProperties | undefined; summary?: string | undefined; title?: string | undefined; mask?: ToMaskOptions<AnyRoute, any, string> | undefined; pattern?: string | undefined; to?: any; params?: true | ParamsReducer<any, MakeDifferenceOptional<any, any>> | undefined; hash?: true | Updater<string> | undefined; state?: true | NonNullableUpdater<HistoryState> | undefined; from?: any; replace?: boolean | undefined; resetScroll?: boolean | undefined; startTransition?: boolean | undefined; target?: string | undefined; activeOptions?: ActiveOptions | undefined; preload?: false | "intent" | undefined; preloadDelay?: number | undefined; disabled?: boolean | undefined; activeProps?: AnchorHTMLAttributes<HTMLAnchorElement> | (() => AnchorHTMLAttributes<HTMLAnchorElement>) | undefined; inactiveProps?: AnchorHTMLAttributes<HTMLAnchorElement> | (() => AnchorHTMLAttributes<HTMLAnchorElement>) | undefined; children?: ReactNode | ((state: { isActive: boolean; }) => ReactNode); accept?: string | undefined; acceptCharset?: string | undefined; action?: string | undefined; allowFullScreen?: boolean | undefined; allowTransparency?: boolean | undefined; alt?: string | undefined; as?: string | undefined; async?: boolean | undefined; autoComplete?: string | undefined; autoPlay?: boolean | undefined; capture?: boolean | "user" | "environment" | undefined; cellPadding?: string | number | undefined; cellSpacing?: string | number | undefined; charSet?: string | undefined; challenge?: string | undefined; checked?: boolean | undefined; classID?: string | undefined; cols?: number | undefined; colSpan?: number | undefined; controls?: boolean | undefined; coords?: string | undefined; crossOrigin?: CrossOrigin; dateTime?: string | undefined; default?: boolean | undefined; defer?: boolean | undefined; download?: any; encType?: string | undefined; formAction?: string | undefined; formEncType?: string | undefined; formMethod?: string | undefined; formNoValidate?: boolean | undefined; formTarget?: string | undefined; frameBorder?: string | number | undefined; headers?: string | undefined; height?: string | number | undefined; high?: number | undefined; href?: string | undefined; hrefLang?: string | undefined; htmlFor?: string | undefined; httpEquiv?: string | undefined; integrity?: string | undefined; keyParams?: string | undefined; keyType?: string | undefined; kind?: string | undefined; list?: string | undefined; loop?: boolean | undefined; low?: number | undefined; manifest?: string | undefined; marginHeight?: number | undefined; marginWidth?: number | undefined; max?: string | number | undefined; maxLength?: number | undefined; media?: string | undefined; mediaGroup?: string | undefined; method?: string | undefined; min?: string | number | undefined; minLength?: number | undefined; multiple?: boolean | undefined; muted?: boolean | undefined; name?: string | undefined; noValidate?: boolean | undefined; open?: boolean | undefined; optimum?: number | undefined; placeholder?: string | undefined; playsInline?: boolean | undefined; poster?: string | undefined; readOnly?: boolean | undefined; required?: boolean | undefined; reversed?: boolean | undefined; rows?: number | undefined; rowSpan?: number | undefined; sandbox?: string | undefined; scope?: string | undefined; scoped?: boolean | undefined; scrolling?: string | undefined; seamless?: boolean | undefined; selected?: boolean | undefined; shape?: string | undefined; size?: number | undefined; sizes?: string | undefined; src?: string | undefined; srcDoc?: string | undefined; srcLang?: string | undefined; srcSet?: string | undefined; start?: number | undefined; step?: string | number | undefined; type?: string | undefined; useMap?: string | undefined; value?: string | number | readonly string[] | undefined; width?: string | number | undefined; wmode?: string | undefined; wrap?: string | undefined; defaultChecked?: boolean | undefined; defaultValue?: string | number | readonly string[] | undefined; suppressContentEditableWarning?: boolean | undefined; suppressHydrationWarning?: boolean | undefined; accessKey?: string | undefined; autoFocus?: boolean | undefined; className?: string | undefined; contentEditable?: Booleanish | "inherit" | "plaintext-only" | undefined; contextMenu?: string | undefined; dir?: string | undefined; draggable?: Booleanish | undefined; hidden?: boolean | undefined; id?: string | undefined; lang?: string | undefined; nonce?: string | undefined; spellCheck?: Booleanish | undefined; tabIndex?: number | undefined; translate?: "yes" | "no" | undefined; radioGroup?: string | undefined; role?: AriaRole | undefined; about?: string | undefined; content?: string | undefined; datatype?: string | undefined; inlist?: any; prefix?: string | undefined; property?: string | undefined; rel?: string | undefined; resource?: string | undefined; rev?: string | undefined; typeof?: string | undefined; vocab?: string | undefined; autoCapitalize?: string | undefined; autoCorrect?: string | undefined; autoSave?: string | undefined; color?: string | undefined; itemProp?: string | undefined; itemScope?: boolean | undefined; itemType?: string | undefined; itemID?: string | undefined; itemRef?: string | undefined; results?: number | undefined; security?: string | undefined; unselectable?: "on" | "off" | undefined; inputMode?: "search" | "text" | "none" | "tel" | "url" | "email" | "numeric" | "decimal" | undefined; is?: string | undefined; "aria-activedescendant"?: string | undefined; "aria-atomic"?: Booleanish | undefined; "aria-autocomplete"?: "list" | "none" | "inline" | "both" | undefined; "aria-braillelabel"?: string | undefined; "aria-brailleroledescription"?: string | undefined; "aria-busy"?: Booleanish | undefined; "aria-checked"?: boolean | "true" | "false" | "mixed" | undefined; "aria-colcount"?: number | undefined; "aria-colindex"?: number | undefined; "aria-colindextext"?: string | undefined; "aria-colspan"?: number | undefined; "aria-controls"?: string | undefined; "aria-current"?: boolean | "time" | "step" | "true" | "false" | "page" | "location" | "date" | undefined; "aria-describedby"?: string | undefined; "aria-description"?: string | undefined; "aria-details"?: string | undefined; "aria-disabled"?: Booleanish | undefined; "aria-dropeffect"?: "link" | "none" | "copy" | "execute" | "move" | "popup" | undefined; "aria-errormessage"?: string | undefined; "aria-expanded"?: Booleanish | undefined; "aria-flowto"?: string | undefined; "aria-grabbed"?: Booleanish | undefined; "aria-haspopup"?: boolean | "dialog" | "menu" | "true" | "false" | "grid" | "listbox" | "tree" | undefined; "aria-hidden"?: Booleanish | undefined; "aria-invalid"?: boolean | "true" | "false" | "grammar" | "spelling" | undefined; "aria-keyshortcuts"?: string | undefined; "aria-label"?: string | undefined; "aria-labelledby"?: string | undefined; "aria-level"?: number | undefined; "aria-live"?: "off" | "assertive" | "polite" | undefined; "aria-modal"?: Booleanish | undefined; "aria-multiline"?: Booleanish | undefined; "aria-multiselectable"?: Booleanish | undefined; "aria-orientation"?: "horizontal" | "vertical" | undefined; "aria-owns"?: string | undefined; "aria-placeholder"?: string | undefined; "aria-posinset"?: number | undefined; "aria-pressed"?: boolean | "true" | "false" | "mixed" | undefined; "aria-readonly"?: Booleanish | undefined; "aria-relevant"?: "text" | "additions" | "additions removals" | "additions text" | "all" | "removals" | "removals additions" | "removals text" | "text additions" | "text removals" | undefined; "aria-required"?: Booleanish | undefined; "aria-roledescription"?: string | undefined; "aria-rowcount"?: number | undefined; "aria-rowindex"?: number | undefined; "aria-rowindextext"?: string | undefined; "aria-rowspan"?: number | undefined; "aria-selected"?: Booleanish | undefined; "aria-setsize"?: number | undefined; "aria-sort"?: "none" | "ascending" | "descending" | "other" | undefined; "aria-valuemax"?: number | undefined; "aria-valuemin"?: number | undefined; "aria-valuenow"?: number | undefined; "aria-valuetext"?: string | undefined; dangerouslySetInnerHTML?: { __html: string | TrustedHTML; } | undefined; onCopy?: ClipboardEventHandler<"a"> | undefined; onCopyCapture?: ClipboardEventHandler<"a"> | undefined; onCut?: ClipboardEventHandler<"a"> | undefined; onCutCapture?: ClipboardEventHandler<"a"> | undefined; onPaste?: ClipboardEventHandler<"a"> | undefined; onPasteCapture?: ClipboardEventHandler<"a"> | undefined; onCompositionEnd?: CompositionEventHandler<"a"> | undefined; onCompositionEndCapture?: CompositionEventHandler<"a"> | undefined; onCompositionStart?: CompositionEventHandler<"a"> | undefined; onCompositionStartCapture?: CompositionEventHandler<"a"> | undefined; onCompositionUpdate?: CompositionEventHandler<"a"> | undefined; onCompositionUpdateCapture?: CompositionEventHandler<"a"> | undefined; onFocus?: FocusEventHandler<"a"> | undefined; onFocusCapture?: FocusEventHandler<"a"> | undefined; onBlur?: FocusEventHandler<"a"> | undefined; onBlurCapture?: FocusEventHandler<"a"> | undefined; onChange?: FormEventHandler<"a"> | undefined; onChangeCapture?: FormEventHandler<"a"> | undefined; onBeforeInput?: FormEventHandler<"a"> | undefined; onBeforeInputCapture?: FormEventHandler<"a"> | undefined; onInput?: FormEventHandler<"a"> | undefined; onInputCapture?: FormEventHandler<"a"> | undefined; onReset?: FormEventHandler<"a"> | undefined; onResetCapture?: FormEventHandler<"a"> | undefined; onSubmit?: FormEventHandler<"a"> | undefined; onSubmitCapture?: FormEventHandler<"a"> | undefined; onInvalid?: FormEventHandler<"a"> | undefined; onInvalidCapture?: FormEventHandler<"a"> | undefined; onLoad?: ReactEventHandler<"a"> | undefined; onLoadCapture?: ReactEventHandler<"a"> | undefined; onError?: ReactEventHandler<"a"> | undefined; onErrorCapture?: ReactEventHandler<"a"> | undefined; onKeyDown?: KeyboardEventHandler<"a"> | undefined; onKeyDownCapture?: KeyboardEventHandler<"a"> | undefined; onKeyPress?: KeyboardEventHandler<"a"> | undefined; onKeyPressCapture?: KeyboardEventHandler<"a"> | undefined; onKeyUp?: KeyboardEventHandler<"a"> | undefined; onKeyUpCapture?: KeyboardEventHandler<"a"> | undefined; onAbort?: ReactEventHandler<"a"> | undefined; onAbortCapture?: ReactEventHandler<"a"> | undefined; onCanPlay?: ReactEventHandler<"a"> | undefined; onCanPlayCapture?: ReactEventHandler<"a"> | undefined; onCanPlayThrough?: ReactEventHandler<"a"> | undefined; onCanPlayThroughCapture?: ReactEventHandler<"a"> | undefined; onDurationChange?: ReactEventHandler<"a"> | undefined; onDurationChangeCapture?: ReactEventHandler<"a"> | undefined; onEmptied?: ReactEventHandler<"a"> | undefined; onEmptiedCapture?: ReactEventHandler<"a"> | undefined; onEncrypted?: ReactEventHandler<"a"> | undefined; onEncryptedCapture?: ReactEventHandler<"a"> | undefined; onEnded?: ReactEventHandler<"a"> | undefined; onEndedCapture?: ReactEventHandler<"a"> | undefined; onLoadedData?: ReactEventHandler<"a"> | undefined; onLoadedDataCapture?: ReactEventHandler<"a"> | undefined; onLoadedMetadata?: ReactEventHandler<"a"> | undefined; onLoadedMetadataCapture?: ReactEventHandler<"a"> | undefined; onLoadStart?: ReactEventHandler<"a"> | undefined; onLoadStartCapture?: ReactEventHandler<"a"> | undefined; onPause?: ReactEventHandler<"a"> | undefined; onPauseCapture?: ReactEventHandler<"a"> | undefined; onPlay?: ReactEventHandler<"a"> | undefined; onPlayCapture?: ReactEventHandler<"a"> | undefined; onPlaying?: ReactEventHandler<"a"> | undefined; onPlayingCapture?: ReactEventHandler<"a"> | undefined; onProgress?: ReactEventHandler<"a"> | undefined; onProgressCapture?: ReactEventHandler<"a"> | undefined; onRateChange?: ReactEventHandler<"a"> | undefined; onRateChangeCapture?: ReactEventHandler<"a"> | undefined; onResize?: ReactEventHandler<"a"> | undefined; onResizeCapture?: ReactEventHandler<"a"> | undefined; onSeeked?: ReactEventHandler<"a"> | undefined; onSeekedCapture?: ReactEventHandler<"a"> | undefined; onSeeking?: ReactEventHandler<"a"> | undefined; onSeekingCapture?: ReactEventHandler<"a"> | undefined; onStalled?: ReactEventHandler<"a"> | undefined; onStalledCapture?: ReactEventHandler<"a"> | undefined; onSuspend?: ReactEventHandler<"a"> | undefined; onSuspendCapture?: ReactEventHandler<"a"> | undefined; onTimeUpdate?: ReactEventHandler<"a"> | undefined; onTimeUpdateCapture?: ReactEventHandler<"a"> | undefined; onVolumeChange?: ReactEventHandler<"a"> | undefined; onVolumeChangeCapture?: ReactEventHandler<"a"> | undefined; onWaiting?: ReactEventHandler<"a"> | undefined; onWaitingCapture?: ReactEventHandler<"a"> | undefined; onAuxClick?: MouseEventHandler<"a"> | undefined; onAuxClickCapture?: MouseEventHandler<"a"> | undefined; onClick?: MouseEventHandler<"a"> | undefined; onClickCapture?: MouseEventHandler<"a"> | undefined; onContextMenu?: MouseEventHandler<"a"> | undefined; onContextMenuCapture?: MouseEventHandler<"a"> | undefined; onDoubleClick?: MouseEventHandler<"a"> | undefined; onDoubleClickCapture?: MouseEventHandler<"a"> | undefined; onDrag?: DragEventHandler<"a"> | undefined; onDragCapture?: DragEventHandler<"a"> | undefined; onDragEnd?: DragEventHandler<"a"> | undefined; onDragEndCapture?: DragEventHandler<"a"> | undefined; onDragEnter?: DragEventHandler<"a"> | undefined; onDragEnterCapture?: DragEventHandler<"a"> | undefined; onDragExit?: DragEventHandler<"a"> | undefined; onDragExitCapture?: DragEventHandler<"a"> | undefined; onDragLeave?: DragEventHandler<"a"> | undefined; onDragLeaveCapture?: DragEventHandler<"a"> | undefined; onDragOver?: DragEventHandler<"a"> | undefined; onDragOverCapture?: DragEventHandler<"a"> | undefined; onDragStart?: DragEventHandler<"a"> | undefined; onDragStartCapture?: DragEventHandler<"a"> | undefined; onDrop?: DragEventHandler<"a"> | undefined; onDropCapture?: DragEventHandler<"a"> | undefined; onMouseDown?: MouseEventHandler<"a"> | undefined; onMouseDownCapture?: MouseEventHandler<"a"> | undefined; onMouseEnter?: MouseEventHandler<"a"> | undefined; onMouseLeave?: MouseEventHandler<"a"> | undefined; onMouseMove?: MouseEventHandler<"a"> | undefined; onMouseMoveCapture?: MouseEventHandler<"a"> | undefined; onMouseOut?: MouseEventHandler<"a"> | undefined; onMouseOutCapture?: MouseEventHandler<"a"> | undefined; onMouseOver?: MouseEventHandler<"a"> | undefined; onMouseOverCapture?: MouseEventHandler<"a"> | undefined; onMouseUp?: MouseEventHandler<"a"> | undefined; onMouseUpCapture?: MouseEventHandler<"a"> | undefined; onSelect?: ReactEventHandler<"a"> | undefined; onSelectCapture?: ReactEventHandler<"a"> | undefined; onTouchCancel?: TouchEventHandler<"a"> | undefined; onTouchCancelCapture?: TouchEventHandler<"a"> | undefined; onTouchEnd?: TouchEventHandler<"a"> | undefined; onTouchEndCapture?: TouchEventHandler<"a"> | undefined; onTouchMove?: TouchEventHandler<"a"> | undefined; onTouchMoveCapture?: TouchEventHandler<"a"> | undefined; onTouchStart?: TouchEventHandler<"a"> | undefined; onTouchStartCapture?: TouchEventHandler<"a"> | undefined; onPointerDown?: PointerEventHandler<"a"> | undefined; onPointerDownCapture?: PointerEventHandler<"a"> | undefined; onPointerMove?: PointerEventHandler<"a"> | undefined; onPointerMoveCapture?: PointerEventHandler<"a"> | undefined; onPointerUp?: PointerEventHandler<"a"> | undefined; onPointerUpCapture?: PointerEventHandler<"a"> | undefined; onPointerCancel?: PointerEventHandler<"a"> | undefined; onPointerCancelCapture?: PointerEventHandler<"a"> | undefined; onPointerEnter?: PointerEventHandler<"a"> | undefined; onPointerLeave?: PointerEventHandler<"a"> | undefined; onPointerOver?: PointerEventHandler<"a"> | undefined; onPointerOverCapture?: PointerEventHandler<"a"> | undefined; onPointerOut?: PointerEventHandler<"a"> | undefined; onPointerOutCapture?: PointerEventHandler<"a"> | undefined; onGotPointerCapture?: PointerEventHandler<"a"> | undefined; onGotPointerCaptureCapture?: PointerEventHandler<"a"> | undefined; onLostPointerCapture?: PointerEventHandler<"a"> | undefined; onLostPointerCaptureCapture?: PointerEventHandler<"a"> | undefined; onScroll?: UIEventHandler<"a"> | undefined; onScrollCapture?: UIEventHandler<"a"> | undefined; onWheel?: WheelEventHandler<"a"> | undefined; onWheelCapture?: WheelEventHandler<"a"> | undefined; onAnimationStart?: AnimationEventHandler<"a"> | undefined; onAnimationStartCapture?: AnimationEventHandler<"a"> | undefined; onAnimationEnd?: AnimationEventHandler<"a"> | undefined; onAnimationEndCapture?: AnimationEventHandler<"a"> | undefined; onAnimationIteration?: AnimationEventHandler<"a"> | undefined; onAnimationIterationCapture?: AnimationEventHandler<"a"> | undefined; onTransitionEnd?: TransitionEventHandler<"a"> | undefined; onTransitionEndCapture?: TransitionEventHandler<"a"> | undefined; key?: Key | null | undefined; ref?: LegacyRef<HTMLAnchorElement> | undefined; } & { component: T; } & InferProps<T>'. ``` the only difference between `TanstackLinkProps` and `MyComponentProps` is the size of the type. `WithComponentOverride` should act the same on both of them. Dont belive me? [**heres a demo**](https://stackblitz.com/edit/vitejs-vite-mcran5?file=src%2FLink.tsx)
TypeScript Property 'component' does not exist on type on complicated nested type
|reactjs|typescript|typescript-typings|typescript-generics|
null
I have a page(server component) that fetches some data from a route handler(`/api/v1/bookings/get`) in my app. Running my site with <kbd>next dev --turbo</kbd> works fine and does not give any errors but when deploying to vercel, I get the error `Application error: a server-side exception has occurred (see the server logs for more information)` Looking at my logs, I see a warning that says that the route `/api/v1/bookings/get` was not found, which is weird because it seems to have been build when deploying the project as per the deployment summary on vercel. [![Deployment summary][1]][1] After the `404` I see a error that tells my front end was unable to parse the response returned(which should be in JSON but is probably in **HTML** since the API route was not found) [![errors list][2]][2] [![error closeup][3]][3] --- For my route handler, it is a simple file that gets all the 'rides' for a specific user(determined by their email). It's code is: ```typescript import { auth, currentUser } from "@clerk/nextjs/server"; import { PrismaClient } from "@prisma/client"; const prisma = new PrismaClient(); export async function GET() { const user = await currentUser(); auth().protect(); try { const bookings = await prisma.ride.findMany({ where: { rider: { email: user?.primaryEmailAddress?.emailAddress, } } }); return new Response(JSON.stringify({bookings}), { status: 200, }); } catch (error) { console.log(error); return new Response(JSON.stringify(error), { status: 500, }); } } ``` The front end has a simple fetch request that looks like: ```typescript const response: { response: { bookings: booking[] } = await fetch(process.env.BASE_URL + "/api/v1/bookings/get") ``` I manually set the base URL variable in my `.env` file. --- Searching for a fix on Google, I saw a few people suggesting purging the cache(on Vercel's side), which I tried but didn't work, I also redeployed afterwards. Any idea how I can fix this? [1]: https://i.stack.imgur.com/oJh4v.png [2]: https://i.stack.imgur.com/tveSm.png [3]: https://i.stack.imgur.com/kG6Q7.png
NextJS 14 site working in development but not in vercel
|next.js|vercel|
the problem for me is just because in action file i had another exported object .... !
|javascript|reactjs|react-redux|razorpay|
How to throw a chrgaed particel in a electric vector field?
|python|matplotlib|math|physics|meshgrid|
null
Deep linking is not working. This is how the `info.plist` on iOS is configured for Google sign-in. ``` ... <key>GIDClientID</key> <string>[secret].apps.googleusercontent.com</string> <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>com.googleusercontent.apps.[secret]</string> </array> </dict> </array> </dict> </plist> ``` When I remove this part, deep linking works fine, why is that? Am I doing something wrong?
Expo Deep linking on iOS is not working (because of Google sign-in?)
|ios|expo|google-signin|
In gRPC, we can use an async client to send multiple calls at the same time. For example, with a service that has a RPC method `Foo()`, we need to call, in this order: 1. First `auto reader = stub.AsyncFoo(&client_context, request, &completion_queue)` 2. Then `reader->Finish(&response, &status, call_data)` 3. Finally `completion_queue.Next()` to get the status of the RPC. My questions about thread safety are the following: 1. Is it thread safe to call `Next()` and `AsyncFoo()` at the same time in different threads? 2. Is it thread safe to call `Next()` and `Finish()` at the same time in different threads? 3. Is it thread safe to call multiple `AsyncFoo()` for different call data at the same time in different thread? 4. Is it thread safe to call multiple `Finish()` for different call data at the same time in different thread? 5. For all the cases, if it is thread-safe: Is it thread-safe *only* when different threads are working with different stub or does it work also for the same stub?
gRPC: Asynchronous client thread safety clarification
|c++|grpc|
With a Flutter web app running on Windows 10, the default option for enacting scrolling is via the mouse wheel. Is it possible to set up additional options for scrolling, like a mouse drag down action for vertical scrolling, or mouse drag across action for horizontal scrolling?
Flutter web app on Windows -how to support mouse drag for horizontal and vertical scrolling as well as using mouse wheel
|flutter|
Im currently try to make Canny edge detection using stb_imahe and c++ without 3rfparty library My code: ``` // Generate gaussian kernel int size = 5, center = (size-1) / 2; float sigma = 1.4f; std::vector<std::vector<double>> kernel(size, std::vector<double>(size)); double sum = 0.0; for(int i = 0; i < size; i++) { for(int j = 0; j < size; j++) { int x=j-(center+1),y=i-(center+1); kernel[i][j]=(1.0/(2*M_PI*sigma*sigma))*exp(-(x*x+y*y)/(2*sigma*sigma)); sum+=kernel[i][j]; } }debug(kernel); // Normalize gausian kernel for(int i = 0; i < size; i++) { for(int j = 0; j < size; j++) { kernel[i][j]/=sum; } } debug(kernel); // Apply gaussian filter to image std::vector<unsigned char> temp(size*channels); for(int y = 0; y < height; y++) { for(int x = 0; x < width; x++) { for(int c = 0; c < 3; c++) { double sum = 0; for(int i = 0; i < size; i++) { for(int j = 0; j < size; j++) { int neighbor_x = x + j - center; int neighbor_y = y + i - center; int clamped_x = std::min(std::max(neighbor_x, 0), width - 1); int clamped_y = std::min(std::max(neighbor_y, 0), height - 1); sum += kernel[i][j] * data[(clamped_y*width+clamped_x)*channels+c]; } } temp[(y*width+x)*channels+c]=static_cast<unsigned char>(sum); } } } std::copy(temp.data(), temp.data()+size*channels, data); temp.clear(); stbi_write_png("gaussian.png", width, height, channels, data, width*channels); ``` the picture i use from wikipedia rgb format from Canny edge detection (in my code i copy to here is removing the grayscale conversion) when i run in grayscale is normal but the gaussian is have problem it show the top part is likely true (apply blur) but the remaining is still normal and i swap some part for checking it wasnt apply blur Please help me
How do you retrieve body from org.springframework.web.reactive.function.client.ClientResponse?
|java|spring-webflux|
Only dagger version 2.48 or above is supported by ksp according to the dagger doc https://dagger.dev/dev-guide/ksp.
Application migrated from Spring 5 to String 6 and JDK 1.8 to 17. The application is running in STS using the embedded Tomcat 10.1.15. But when I deploy the application to a Tomcat server 10.1.20 we are getting the following error. `org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Unsatisfied dependency expressed through method 'setFilterChains' parameter 0: Error creating bean with name 'securityFilterChain' defined in class path resource [com/xx/app1/security/SecurityConfiguration.class]: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'securityFilterChain' threw exception with message: This method cannot decide whether these patterns are Spring MVC patterns or not. If this endpoint is a Spring MVC endpoint, please use requestMatchers(MvcRequestMatcher); otherwise, please use requestMatchers(AntPathRequestMatcher). This is because there is more than one mappable servlet in your servlet context: {org.apache.jasper.servlet.JspServlet=[*.jspx, *.jsp], org.springframework.web.servlet.DispatcherServlet=[/]}. For each MvcRequestMatcher, call MvcRequestMatcher#setServletPath to indicate the servlet path. at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.resolveMethodArguments(AutowiredAnnotationBeanPostProcessor.java:875) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:828) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:145) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:492) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1416) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:597) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:520) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:325) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:323) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:973) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:950) ~[spring-context-6.0.13.jar:6.0.13] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:616) ~[spring-context-6.0.13.jar:6.0.13] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) ~[spring-boot-3.1.5.jar:3.1.5] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:738) ~[spring-boot-3.1.5.jar:3.1.5] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:440) ~[spring-boot-3.1.5.jar:3.1.5] at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) ~[spring-boot-3.1.5.jar:3.1.5] at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:174) ~[spring-boot-3.1.5.jar:3.1.5] at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:154) ~[spring-boot-3.1.5.jar:3.1.5] at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:96) ~[spring-boot-3.1.5.jar:3.1.5] at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:171) ~[spring-web-6.0.13.jar:6.0.13] at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:4880) ~[catalina.jar:10.1.20] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:171) ~[catalina.jar:10.1.20] at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:683) ~[catalina.jar:10.1.20] at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:658) ~[catalina.jar:10.1.20] at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:712) ~[catalina.jar:10.1.20] at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:969) ~[catalina.jar:10.1.20] at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1911) ~[catalina.jar:10.1.20] at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:539) ~[na:na] at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na] at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) ~[tomcat-util.jar:10.1.20] at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:123) ~[na:na] at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:771) ~[catalina.jar:10.1.20] at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:423) ~[catalina.jar:10.1.20] at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1629) ~[catalina.jar:10.1.20] at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:303) ~[catalina.jar:10.1.20] at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:114) ~[catalina.jar:10.1.20] at org.apache.catalina.util.LifecycleBase.setStateInternal(LifecycleBase.java:402) ~[catalina.jar:10.1.20] at org.apache.catalina.util.LifecycleBase.setState(LifecycleBase.java:345) ~[catalina.jar:10.1.20] at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:893) ~[catalina.jar:10.1.20] at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:845) ~[catalina.jar:10.1.20] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:171) ~[catalina.jar:10.1.20] at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1332) ~[catalina.jar:10.1.20] at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1322) ~[catalina.jar:10.1.20] at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na] at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) ~[tomcat-util.jar:10.1.20] at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:145) ~[na:na] at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:866) ~[catalina.jar:10.1.20] at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:240) ~[catalina.jar:10.1.20] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:171) ~[catalina.jar:10.1.20] at org.apache.catalina.core.StandardService.startInternal(StandardService.java:433) ~[catalina.jar:10.1.20] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:171) ~[catalina.jar:10.1.20] at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:921) ~[catalina.jar:10.1.20] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:171) ~[catalina.jar:10.1.20] at org.apache.catalina.startup.Catalina.start(Catalina.java:757) ~[catalina.jar:10.1.20] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na] at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:345) ~[bootstrap.jar:10.1.20] at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:473) ~[bootstrap.jar:10.1.20] Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityFilterChain' defined in class path resource [com/xx/app1/security/SecurityConfiguration.class]: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'securityFilterChain' threw exception with message: This method cannot decide whether these patterns are Spring MVC patterns or not. If this endpoint is a Spring MVC endpoint, please use requestMatchers(MvcRequestMatcher); otherwise, please use requestMatchers(AntPathRequestMatcher). This is because there is more than one mappable servlet in your servlet context: {org.apache.jasper.servlet.JspServlet=[*.jspx, *.jsp], org.springframework.web.servlet.DispatcherServlet=[/]}. For each MvcRequestMatcher, call MvcRequestMatcher#setServletPath to indicate the servlet path. at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:654) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:642) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1332) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1162) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:560) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:520) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:325) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:323) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:254) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.DefaultListableBeanFactory.addCandidateEntry(DefaultListableBeanFactory.java:1633) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1597) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveMultipleBeans(DefaultListableBeanFactory.java:1488) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1375) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1337) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.resolveMethodArguments(AutowiredAnnotationBeanPostProcessor.java:867) ~[spring-beans-6.0.13.jar:6.0.13] ... 61 common frames omitted Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'securityFilterChain' threw exception with message: This method cannot decide whether these patterns are Spring MVC patterns or not. If this endpoint is a Spring MVC endpoint, please use requestMatchers(MvcRequestMatcher); otherwise, please use requestMatchers(AntPathRequestMatcher). This is because there is more than one mappable servlet in your servlet context: {org.apache.jasper.servlet.JspServlet=[*.jspx, *.jsp], org.springframework.web.servlet.DispatcherServlet=[/]}. For each MvcRequestMatcher, call MvcRequestMatcher#setServletPath to indicate the servlet path. at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:171) ~[spring-beans-6.0.13.jar:6.0.13] at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:650) ~[spring-beans-6.0.13.jar:6.0.13] ... 77 common frames omitted Caused by: java.lang.IllegalArgumentException: This method cannot decide whether these patterns are Spring MVC patterns or not. If this endpoint is a Spring MVC endpoint, please use requestMatchers(MvcRequestMatcher); otherwise, please use requestMatchers(AntPathRequestMatcher). This is because there is more than one mappable servlet in your servlet context: {org.apache.jasper.servlet.JspServlet=[*.jspx, *.jsp], org.springframework.web.servlet.DispatcherServlet=[/]}. For each MvcRequestMatcher, call MvcRequestMatcher#setServletPath to indicate the servlet path. at org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry.requestMatchers(AbstractRequestMatcherRegistry.java:208) ~[spring-security-config-6.1.5.jar:6.1.5] at org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry.requestMatchers(AbstractRequestMatcherRegistry.java:276) ~[spring-security-config-6.1.5.jar:6.1.5] at com.xx.app1.security.SecurityConfiguration.lambda$securityFilterChain$0(SecurityConfiguration.java:40) ~[classes/:1.0.0-SNAPSHOT] at org.springframework.security.config.annotation.web.builders.HttpSecurity.authorizeHttpRequests(HttpSecurity.java:1466) ~[spring-security-config-6.1.5.jar:6.1.5] at com.xx.app1.security.SecurityConfiguration.securityFilterChain(SecurityConfiguration.java:39) ~[classes/:1.0.0-SNAPSHOT] at com.xx.app1.security.SecurityConfiguration$$SpringCGLIB$$0.CGLIB$securityFilterChain$1(<generated>) ~[classes/:1.0.0-SNAPSHOT] at com.xx.app1.security.SecurityConfiguration$$SpringCGLIB$$FastClass$$1.invoke(<generated>) ~[classes/:1.0.0-SNAPSHOT] at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:258) ~[spring-core-6.0.13.jar:6.0.13] at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331) ~[spring-context-6.0.13.jar:6.0.13] at com.xx.app1.security.SecurityConfiguration$$SpringCGLIB$$0.securityFilterChain(<generated>) ~[classes/:1.0.0-SNAPSHOT] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na] at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:139) ~[spring-beans-6.0.13.jar:6.0.13] ... 78 common frames omitted 31-Mar-2024 19:33:43.436 SEVERE [main] org.apache.catalina.startup.HostConfig.deployWAR Error deploying web application archive [C:\Projects\Softwares\apache-tomcat-10.1.20\webapps\app1-back.war] java.lang.IllegalStateException: Error starting child at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:686) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:658) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:712) at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:969) at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1911) at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:539) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:123) at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:771) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:423) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1629) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:303) at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:114) at org.apache.catalina.util.LifecycleBase.setStateInternal(LifecycleBase.java:402) at org.apache.catalina.util.LifecycleBase.setState(LifecycleBase.java:345) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:893) at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:845) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:171) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1332) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1322) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:145) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:866) at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:240) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:171) at org.apache.catalina.core.StandardService.startInternal(StandardService.java:433) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:171) at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:921) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:171) at org.apache.catalina.startup.Catalina.start(Catalina.java:757) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:345) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:473) Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/app1-back]] at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:419) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:186) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:683) ... 37 more Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Unsatisfied dependency expressed through method 'setFilterChains' parameter 0: Error creating bean with name 'securityFilterChain' defined in class path resource [com/xx/app1/security/SecurityConfiguration.class]: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'securityFilterChain' threw exception with message: This method cannot decide whether these patterns are Spring MVC patterns or not. If this endpoint is a Spring MVC endpoint, please use requestMatchers(MvcRequestMatcher); otherwise, please use requestMatchers(AntPathRequestMatcher). This is because there is more than one mappable servlet in your servlet context: {org.apache.jasper.servlet.JspServlet=[*.jspx, *.jsp], org.springframework.web.servlet.DispatcherServlet=[/]}. For each MvcRequestMatcher, call MvcRequestMatcher#setServletPath to indicate the servlet path. at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.resolveMethodArguments(AutowiredAnnotationBeanPostProcessor.java:875) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:828) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:145) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:492) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1416) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:597) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:520) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:325) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:323) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:973) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:950) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:616) at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:738) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:440) at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:174) at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:154) at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:96) at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:171) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:4880) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:171) ... 38 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityFilterChain' defined in class path resource [com/xx/app1/security/SecurityConfiguration.class]: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'securityFilterChain' threw exception with message: This method cannot decide whether these patterns are Spring MVC patterns or not. If this endpoint is a Spring MVC endpoint, please use requestMatchers(MvcRequestMatcher); otherwise, please use requestMatchers(AntPathRequestMatcher). ` ``` @Configuration @EnableWebSecurity @RequiredArgsConstructor public class SecurityConfiguration { private final JwtAuthenticationFilter jwtAuthenticationFilter; private final UserService userService; @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests( request -> request.requestMatchers("/**").permitAll().anyRequest().authenticated()) .sessionManagement(manager -> manager.sessionCreationPolicy(STATELESS)) .authenticationProvider(authenticationProvider()) .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); http.cors(); return http.build(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public AuthenticationProvider authenticationProvider() { DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); authProvider.setUserDetailsService(userService.userDetailsService()); authProvider.setPasswordEncoder(passwordEncoder()); return authProvider; } @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception { return config.getAuthenticationManager(); } } ``` Any help will be appeciated.
Issue while deploying Java Spring 6 application in Tomcat 10.1
For the approach you want in your app you need to use protected routes you can learn more in this blog : [https://blog.logrocket.com/authentication-react-router-v6/][1] Create routes using **createBrowserRouter** import { createBrowserRouter } from 'react-router-dom'; //import all the page components here export const router = createBrowserRouter([ { path: '/', element: <Layout />, children: [ { index: true, element: <Login />, }, { path: 'signup', element: <SignUp />, }, { path: 'dashboard', element: ( <ProtectedRoute allowedRoles={roles.vendor}> <VendorDashboard /> </ProtectedRoute> ), }, { path: 'items', element:( <ProtectedRoute allowedRoles={roles.vendor}> <Items /> </ProtectedRoute> ), }, { path: 'buyer-dashboard', element:( <ProtectedRoute allowedRoles={roles.buyer}> <Dashboard /> </ProtectedRoute> ), }, { path: 'other', element:( <ProtectedRoute allowedRoles={roles.buyer}> <Other /> </ProtectedRoute> ), }, ],},]); const roles = { buyer: ['buyer-dashboard', 'other'], vendor: ['dashboard', 'items'], }; Make a function to retrieve to roles of the user on login const getUserRole = () => { return 'superAdmin'; }; now make a component for protected route import { Navigate } from 'react-router-dom'; const ProtectedRoute = ({ children, allowedRoles }) => { const userRole = getUserRole(); const isAuthenticated = true; if (!isAuthenticated) { return <Navigate to="/login" replace />; } if (!allowedRoles.includes(userRole)) { return <Navigate to="/unauthorized" replace />; } return children // <Outlet />; tyou can use Outlet here to }; export default ProtectedRoute; [1]: https://blog.logrocket.com/authentication-react-router-v6/
Issue while deploying Java Spring 6 application in Tomcat 10.1.20
I have stuck with a pretty simple problem - I can't communicate with process' stdout. The process is a simple stopwatch, so I'd be able to start it, stop and get current time. The code of stopwatch is: ```python import argparse import time def main() -> None: parser = argparse.ArgumentParser() parser.add_argument('start', type=int, default=0) start = parser.parse_args().start while True: print(start) start += 1 time.sleep(1) if __name__ == "__main__": main() ``` And its manager is: ```python import asyncio class RobotManager: def __init__(self): self.cmd = ["python", "stopwatch.py", "10"] self.robot = None async def start(self): self.robot = await asyncio.create_subprocess_exec( *self.cmd, stdout=asyncio.subprocess.PIPE, ) async def stop(self): if self.robot: self.robot.kill() stdout = await self.robot.stdout.readline() print(stdout) await self.robot.wait() self.robot = None async def main(): robot = RobotManager() await robot.start() await asyncio.sleep(3) await robot.stop() await robot.start() await asyncio.sleep(3) await robot.stop() asyncio.run(main()) ``` But `stdout.readline` returns an empty byte string every time. When changing `stdout = await self.robot.stdout.readline()` to `stdout, _ = await self.robot.communicate()`, the result is still an empty byte string. When adding `await self.robot.stdout.readline()` to the end of the `RobotManager.start` method, it hangs forever. However, when removing `stdout=asyncio.subprocess.PIPE` and all `readline` calls, the subprocess prints to the terminal as expected. How do I read from the subprocess stdout correctly?
I'm trying to implement an accessible grid table and I'm having a problem understanding the indexing columns that span multiple columns. Lemme give you an example. Consider the following table: ```html <table role="grid"> <thead> <tr> <td colspan="2" rowspan="2" /> <th scope="colgroup" colspan="3">Clothes</th> <th scope="colgroup" colspan="2">Accessories</th> </tr> <tr> <th scope="col">Trousers</th> <th scope="col">Skirts</th> <th scope="col">Dresses</th> <th scope="col">Bracelets</th> <th scope="col">Rings</th> </tr> </thead> <tbody> <tr> <th scope="rowgroup" rowspan="3">Belgium</th> <th scope="row">Antwerp</th> <td>d1</td> <td>d2</td> <td>d3</td> <td>d4</td> <td>d5</td> </tr> <tr> <th scope="row">Gent</th> <td>d1</td> <td>d2</td> <td>d3</td> <td>d4</td> <td>d5</td> </tr> <tr> <th scope="row">Brussels</th> <td>d1</td> <td>d2</td> <td>d3</td> <td>d4</td> <td>d5</td> </tr> </tbody> </table> ``` How would you index the columns using `aria-colindex`? This is a direct quote from the docs: > If a `cell` or `gridcell` spans multiple columns, set `aria-colspan` to the number of columns it spans if not using `<td>` and `<th>` HTML elements, and set `aria-colindex` to the value of the start of the span; the value it would have had if it was only one column wide spanning only the first of its columns. I don't quite get this part: > set `aria-colindex` to the value of the start of the span Does it mean: ```html <td colspan="2" rowspan="2" aria-colindex="1" /> <th scope="colgroup" colspan="3" aria-colindex="3">Clothes</th> <th scope="colgroup" colspan="2" aria-colindex="6">Accessories</th> ``` Or: ```html <td colspan="2" rowspan="2" aria-colindex="1" /> <th scope="colgroup" colspan="3" aria-colindex="2">Clothes</th> <th scope="colgroup" colspan="2" aria-colindex="3">Accessories</th> ``` And also how to index the cells in the body? Is it this? ```html <tr> <th scope="rowgroup" rowspan="3" aria-colindex="1">Belgium</th> <th scope="row" aria-colindex="2">Antwerp</th> <td aria-colindex="3">d1</td> <td aria-colindex="4">d2</td> <td aria-colindex="5">d3</td> <td aria-colindex="6">d4</td> <td aria-colindex="7">d5</td> </tr> ```
HTML Tables A11y: column index in conjuction with column spanning
|html|html-table|accessibility|wai-aria|
null
`i am using material date picker in my andorid priject in fragment on specific click i want to show user the date dialog but on click nothing is showing .` 'here is my code' [enter image description here](https://i.stack[enter image description here](https://i.stack.imgur.com/CyZRZ.png).imgur.com/5saGg.png) `i am expecting that user select two date range and i get those date`
Material date picker not showing
|android|date|fragment|android-datepicker|
null
|nullpointerexception|tostring|
I am uploading a geotiff file from my streamlit app using st.file_uploader. How to store this file to snowflake DB. Is it possible to do so? fo rnow its geotiff but file type can be shape file also. Please guide. I have connected my streamlit app to snowflake using snowflake-connector. I have tried uploading csv and binary files from streamlit app. and it works. But i am stuck at other file types(tiff,shp) like mentioned.
I am working on a scraping project where I am trying to scrape NSE announcements page - https://www.nseindia.com/companies-listing/corporate-filings-announcements. Now the table is static but the JSON content get loads dynamically. I am able to hit the API endpoint of the website but after few times it says - “Resource not found”. I am not able to find workaround for it. How can I extract the news from announcements page? I tried using the headers in the code but even that is not helping.
How to scrape website which loads json content dynamically?
Currently I am working on a project where VueJS + Nuxt and TailwindCSS is used. Within this project there is a Sidebar Component defined as follows: ``` <template> <div > <!-- Static sidebar for desktop --> <div class="hidden lg:fixed lg:inset-y-0 lg:z-50 lg:flex lg:w-72 lg:flex-col"> <!-- Sidebar component, swap this element with another sidebar if you like --> <div class="flex grow flex-col gap-y-5 overflow-y-auto border-r border-gray-200 bg-white px-6"> <div class="flex h-16 shrink-0 items-center"> <NuxtLink class="flex items-center" to="/"> <img class="h-8 w-auto" src="../../assets/logo.svg" style="height: 40px; width: 40px" alt="Company" /> <p class="font-nunito text-2xl"> {{ $t('App.LogoTitle') }}</p> </NuxtLink> </div> <nav class="flex flex-1 flex-col"> <ul role="list" class="flex flex-1 flex-col gap-y-7"> <li> <ul role="list" class="-mx-2 space-y-1"> <li v-for="item in navigation" :key="item.name"> <a v-if="!item.children" :href="item.href" :class="[item.current ? 'bg-gray-50' : 'hover:bg-gray-50', 'group flex gap-x-3 rounded-md p-2 text-sm leading-6 font-semibold text-gray-700']"> <component :is="item.icon" class="h-6 w-6 shrink-0 text-gray-400" aria-hidden="true" /> {{ item.name }} </a> <Disclosure as="div" v-else v-slot="{ open }"> <DisclosureButton :class="[item.current ? 'bg-gray-50' : 'hover:bg-gray-50', 'flex items-center w-full text-left rounded-md p-2 gap-x-3 text-sm leading-6 font-semibold text-gray-700']"> <component :is="item.icon" class="h-6 w-6 shrink-0 text-gray-400" aria-hidden="true" /> {{ item.name }} <ChevronRightIcon :class="[open ? 'rotate-90 text-gray-500' : 'text-gray-400', 'ml-auto h-5 w-5 shrink-0']" aria-hidden="true" /> </DisclosureButton> <DisclosurePanel as="ul" class="mt-1 px-2"> <li v-for="subItem in item.children" :key="subItem.name"> <!-- 44px --> <DisclosureButton as="a" :href="subItem.href" :class="[subItem.current ? 'bg-gray-50' : 'hover:bg-gray-50', 'block rounded-md py-2 pr-2 pl-9 text-sm leading-6 text-gray-700']">{{ subItem.name }}</DisclosureButton> </li> </DisclosurePanel> </Disclosure> </li> </ul> </li> <li class="-mx-6 mt-auto"> <a href="#" class="flex items-center gap-x-4 px-6 py-3 text-sm font-semibold leading-6 text-gray-900 hover:bg-gray-50"> <img class="h-8 w-8 rounded-full bg-gray-50" src="https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80" alt="" /> <span class="sr-only">Your profile</span> <span aria-hidden="true">Tom Cook</span> </a> </li> </ul> </nav> </div> </div> <div class=" top-0 z-40 flex items-center gap-x-6 bg-white px-4 py-4 shadow-sm sm:px-6 lg:hidden"> <button type="button" class="-m-2.5 p-2.5 text-gray-700 lg:hidden" @click="sidebarOpen = true"> <span class="sr-only">Open sidebar</span> <Bars3Icon class="h-6 w-6" aria-hidden="true" /> </button> <div class="flex-1 text-sm font-semibold leading-6 text-gray-900">Dashboard</div> <a href="#"> <span class="sr-only">Your profile</span> <img class="h-8 w-8 rounded-full bg-gray-50" src="https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80" alt="" /> </a> </div> </div> </template> <script setup lang="ts"> import {ref} from 'vue' import {Disclosure, DisclosureButton, DisclosurePanel} from '@headlessui/vue' import {AcademicCapIcon, Bars3Icon, ChartPieIcon, ChevronRightIcon} from '@heroicons/vue/24/outline' const { t } = useI18n(); const navigation = [ { name: t('Components.SidebarComponent.Primary.Dashboard'), href: '#', icon: ChartPieIcon, current: true }, { name: t('Components.SidebarComponent.Primary.Knowledge'), icon: AcademicCapIcon, current: false }, ] const sidebarOpen = ref(false) </script> ``` The corresponding layout for it looks as follows: ``` <template> <SidebarComponent /> <slot /> </template> <style></style> <script setup lang="ts"> </script> ``` When I now use this layout for a page and "slot" is replaced with another Component the content of it is displayed behind the Sidebar. Is there a way that all content which is not defined inside the Sidebar Component is displayed on the right side of it?
Vue/TailwindCSS - Content is behind Sidebar
|typescript|vue.js|nuxt.js|tailwind-css|
I have an `Admin` area in my ASP.NET Core MVC app and when I try to reach to `/Admin/Category/Add` it says **No webpage was found** for the web address: `https://localhost:7002/Category/Add?area=Admin`. My routing in `program.cs`: ``` c# app.MapDefaultControllerRoute(); app.MapAreaControllerRoute( name: "Admin", areaName: "Admin", pattern: "Admin/{controller=Home}/{action=Index}/{id?}" ); ``` My view: ``` @model List<Category> @{ ViewData["Title"] = "Index"; Layout = "~/Areas/Admin/Views/Shared/_AdminLayout.cshtml"; } <div class="row"> <div class="col-lg-12"> <div class="card"> <div class="card-body"> <a asp-area="Admin" asp-controller="Category" asp-action="Update" class="btn mb-1 btn-primary">Add Category</a> <div class="card-title"> <h4>Table Basic</h4> </div> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>Name</th> <th>Created By</th> <th>Status</th> <th>Actions</th> </tr> </thead> <tbody> @foreach (var item in Model) { <tr> <td>@item.Name</td> <td>@item.CreatedBy</td> <td>@item.IsDeleted</td> <td> <a asp-area="Admin" asp-controller="Category" asp-action="Update" asp-route-id="@item.Id"> <button type="button" class="btn mb-1 btn-warning">Update</button> </a> <a asp-area="Admin" asp-controller="Category" asp-action="Delete" asp-route-id="@item.Id"> <button type="button" class="btn mb-1 btn-danger">Delete</button> </a> </td> </tr> } </tbody> </table> </div> </div> </div> </div> </div> ``` My controller: ``` c# namespace AnimeUI.Areas.Admin.Controllers { [Area("Admin")] public class CategoryController : Controller { private readonly ICategoryService categoryService; private readonly IValidator<Category> validator; private readonly IMapper mapper; public CategoryController(ICategoryService categoryService, IValidator<Category> validator, IMapper mapper) { this.categoryService = categoryService; this.validator = validator; this.mapper = mapper; } public async Task<IActionResult> Index() { var categories = await categoryService.GetAllCategoriesNonDeletedAsync(); return View(categories); } [HttpGet] public IActionResult Add() { return View(); } [HttpPost] public async Task<IActionResult> Add(AddCategoryDto addCategoryDto) { var category = mapper.Map<Category>(addCategoryDto); var result = validator.Validate(category); var exists = await categoryService.Exists(category); if (exists) result.Errors.Add(new ValidationFailure("Name", "This category name already exists")); if (result.IsValid) { await categoryService.CreateCategoryAsync(addCategoryDto); return RedirectToAction("Index", "Category", new { Area = "Admin" }); } result.AddToModelState(this.ModelState); return View(addCategoryDto); } } } ``` I have been searching for whole day, yet couldn't find a valid solve to this annoying problem. For some reason my URL is being generated like this: https://localhost:7002/Category/Add?area=Admin instead of https://localhost:7002/Admin/Category/Add I tried to change my port, add different routing syntax. I am currently using Visual Studio 2022 and my project is .NET 8.0 PS: My problem only occurs when I need to go to the pages of `Admin`.