Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Overload variadic function for a single specific type using C++17
I want to overload (or specialize) a variadic function, such that the overload (or specialization) takes only arguments of a specific type. In C++20 I would write: #include <type_traits> #include <iostream> // original version void foo(auto const&...) { std::cout << "default\n"; } // oveload/specialization takes only Bar instances struct Bar {}; void foo(std::same_as<Bar> auto const&...){ std::cout << "Bar\n"; } The code works as expected. The second version is chosen, if the arguments are all Bar, the first otherwise. How would I create the second overload with C++17? Ideally, I wouldn't have to modify the more general version. Here is a first failed attempt using std::enable_if: https://godbolt.org/z/9vn39jTd4 -
how to make timer_create and timer_delete multi-thread proof
I am stuck in a peculiar situation where I call timer_create from one thread and call the timer_delete from another thread. But I cant seem to get it work as it ends up in a deadlock: I cannot figure out how to make it thread safe, should I use mutexes? or should I use some other way to avoid deadlocks? my code is as follows: #include <iostream> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <signal.h> #include <time.h> #include "pthread.h" typedef struct { struct sigevent tmrSigEvt; timer_t tmr; }TMR_DATA_T; int a = 10; int b = 20; int c = 0; TMR_DATA_T tmrDataArray[5] = { 0 }; void TimerCallback( union sigval timer_data ) { std::cout<<"am i here\n"; c = a + b; } int32_t CreateTimer( int32_t timerId, const uint32_t msPeriod ) { int32_t ret = -1; uint8_t slot = timerId; timer_t *tmrPtr = &tmrDataArray[slot].tmr; struct itimerspec period; uint32_t tmpPeriod; tmrDataArray[slot].tmrSigEvt.sigev_notify = SIGEV_THREAD; tmrDataArray[slot].tmrSigEvt.sigev_notify_function = TimerCallback; tmrDataArray[slot].tmrSigEvt.sigev_signo = timerId; tmrDataArray[slot].tmrSigEvt.sigev_value.sival_ptr = ( void* )&tmrDataArray[slot]; tmrDataArray[slot].tmrSigEvt.sigev_notify_attributes = NULL; ret = timer_create( /*CLOCK_REALTIME*/ CLOCK_MONOTONIC, &tmrDataArray[slot].tmrSigEvt, tmrPtr ); std::cout<<"----------------DO I COME HERE AFTER CREATING THE TIMER---------\n"; tmpPeriod = msPeriod % 1000; // remainder or period less than 1sec period.it_value.tv_nsec = ( … -
django-oauth-toolkit error: Unable to parse query string
I'm trying to access the /o/authorize/ domain with the following parameters: I'm redirected to login at an admin portal and once I successfully login, I get this: "Error: invalid_request. Unable to parse query string" This is the code I'm using to generate the code_challenge: import random import string import base64 import hashlib code_verifier = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(random.randint(43, 128))) code_verifier = base64.urlsafe_b64encode(code_verifier.encode('utf-8')) code_challenge = hashlib.sha256(code_verifier).digest() code_challenge = base64.urlsafe_b64encode(code_challenge).decode('utf-8').replace('=', '') print(fr'code verifier: {code_verifier}') print(fr'code challenger: {code_challenge}') -
Django and Okta Login
I have been following the guide on "https://pypi.org/project/django-okta-auth/" to integrate and app on to okta, but for some reason on the login screen after I enter the credentials , it takes me back to login screen again rather than the actual home page. Please help and verify my if I'm doing it correctly. urls.py urlpatterns = [ path('accounts/', include(("okta_oauth2.urls", "okta_oauth2"), namespace="okta_oauth2")), path('admin/', admin.site.urls), path('classroom/',include('classroom.urls')), path('',HomeView.as_view(),name='home') ] Okta_Auth "SCOPES": "openid profile email", # this is the default and can be omitted "REDIRECT_URI": "http://localhost:8000/oauth2/callback", "LOGIN_REDIRECT_URL": "/", # default INSTALLED_APPS = [ 'okta_oauth2.apps.OktaOauth2Config', 'classroom.apps.ClassroomConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Login.html <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script src="https://global.oktacdn.com/okta-signin-widget/5.0.1/js/okta-sign-in.min.js" type="text/javascript" ></script> <link href="https://global.oktacdn.com/okta-signin-widget/5.0.1/css/okta-sign-in.min.css" type="text/css" rel="stylesheet" /> </head> <body> <div id="okta-login-container"></div> <script type="text/javascript"> var oktaSignIn = new OktaSignIn({ baseUrl: '{{config.url}}', clientId: '{{config.clientId}}', redirectUri: '{{config.redirectUri}}', authParams: { issuer: '{{config.issuer}}', responseType: ['code'], scopes: "{{config.scope}}".split(" "), pkce: false, }, }); console.log(oktaSignIn) oktaSignIn.renderEl( {el: '#okta-login-container'}, /* function (res) {[![enter image description here][1]][1] console.log(res); }*/ ) </script> </body> </html> [ -
ckeditor in django has chenged to TextField
I was using postgresql and then I had to change my db to mysql . after changing all RichTextUploadingFields changed to TextFields in django admin ! How can I fix this ? also I try this code in settings.py but It does not working : STATIC_ROOT = '/home/yeganexu/public_html/static' STATIC_URL = '/static/' MEDIA_ROOT = '/home/yeganexu/public_html/media' MEDIA_URL = '/media/' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js' CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'width': 'auto', 'extraPlugins': ','.join([ 'codesnippet', ]), }, }` -
How can I use the ffi package to use c++ in my flutter app?
Right now I am trying to implement the mediapipe c++ library into my flutter app. At the beginning I wrote a simple function with a printf() function in it in c++ to try to to run it in flutter. I compiled as follows: g++ -shared -o produce_landmarks.so -fPIC produce_landmarks.cpp I put the compiled shared .so file into each following structur folder: android/app/src/main/jniLibs /arm64-v8a /armeabi-v7a /x86 /x86_64 Unfortunately I got an bad ELF error. Probably because I didn't compiled it for the correct processor architecture. "data/app/.../lib/arm64/produce_landmarks.so" has bad ELF magic: 4d5a9000" //on phone "/data/app/.../lib/x86_64/produce_landmarks.so" has bad ELF magic: 4d5a9000 // on emulator But do I really need to compile the c++ code, which is right now a simple function with a printf() function into different architectures? If that's the case then how can I do it? I would like to know what the exact steps are to run a simple c++ function the mediapipe c++ library in flutter. I am asking because I am just confused of the many ways that the ffi package was being used in youtube. Do I need to use ffigen? I saw many people create plugins? But I don't think that I need that because I … -
how to increase css file speed on django website.?
I have build website in Django it's working good but when trying to website speed test tell me css file loading I have already minify the file but show the same error. -
How to execute bash script with sudo password needed via libssh
I need to execute script on remote computer with libssh. Trying to follow this tutorial, but can't understand how to send sudo password That's my code, sudo password is hard coded for now, but I'll change that when I figure out how to pass the password. When executing the code, nothing happens int shell_session(ssh_session session) { std::string cmd1 = {"sudo -S bash ./tmp/update_project"}; std::string sudo_password = {"87654321"}; ssh_channel channel; int rc; channel = ssh_channel_new(session); if (channel == NULL) return SSH_ERROR; rc = ssh_channel_open_session(channel); if (rc != SSH_OK) { ssh_channel_free(channel); return rc; } rc = ssh_channel_request_shell(channel); if (rc != SSH_OK) return rc; rc = ssh_channel_request_exec(channel, cmd1.c_str()); if (!(rc > 0)) return SSH_ERROR; rc = ssh_channel_request_exec(channel, sudo_password.c_str()); if (!(rc > 0)) return SSH_ERROR; ssh_channel_close(channel); ssh_channel_send_eof(channel); ssh_channel_free(channel); return SSH_OK; } -
Jetson nano i2c + dma
I use Ubuntu 18.04.5 LTS (GNU/Linux 4.9.253-tegra aarch64). What should I do if I want to work with i2c with dma? I need to transmit ~1MB of data every 1sec. For non - dma transmitting I used smbus.h file from userspace. -
Is there any workaround for a virtual function template in this particular case?
If you have a concept and a class member function template like so: template<typename T> concept SomeConcept = ... // Some requirement struct foo { void func(SomeConcept auto&) { ... } }; Is there any way, through some workaround, to have func be a purely virtual function? So: struct foo { virtual void func(SomeConcept auto&) = 0; }; Obviously the above won't work since virtual function templates are not allowed. I searched around a bit, and found an SO answer suggesting the Base Visitor pattern, but I struggle to see how I apply it here. Is there any way to achieve what I want, or is it just not possible? -
while trying to implement a Django chat app using channels after implement daphne and channels and set up ASGI the server dindt running in ASGI
[asgi.py file[installed apps[after tring to fect the url it showing not fount ](https://i.stack.imgur.com/Z01ia.png)](https://i.stack.imgur.com/VwIlL.png)](https://i.stack.imgur.com/HdXwJ.png) [after run the server it did run in the asgi while teing to get websocket url it showing not fount](https://i.stack.imgur.com/KIC2C.[enter image description here](https://i.stack.imgur.com/Rtr6N.png)png) -
How can I combine two fields into one in django by using serializers
Is it possible to combine two fields, for example, age_from and age_to to key named age and dictionary value. Like this: age : { from: 18, to: null } My models: # models.py class Banner(models.Model): text = models.CharField(max_length=255) description = models.TextField() image = WEBPField( verbose_name='Image', upload_to=banner_folder, ) link = models.URLField() view_count = models.PositiveIntegerField(default=0) age_from = models.PositiveSmallIntegerField() age_to = models.PositiveSmallIntegerField() def __str__(self): return f"{self.id}. {self.text}" def count_increase(self): self.view_count += 1 self.save() My serializers: # serializers.py class BannerSerializer(ModelSerializer): image = Base64ImageField() class Meta: model = Banner fields = ["id", "text", "description", "image", "link"] -
Convert C++ PPL task<t> into .NET TPL Task<T>, using C++/CLI
I have a .NET interface which returns asynchronous Task objects. public interface MyInterface { public Task<void> DoTheThing(); } For Special Reasons, suppose I wanted to implement this interface using native code, compiled in C++/CLI. It's my understanding that Visual Studio 17.6 recently introduced support for C++20 with coroutines, in CLI-enabled compilation units. Our native code uses PPL task<T> templates with co_awaitc to achieve the same asynchronous approach that C#'s async/await keywords do with Task<T> objects. What options are available, for 'converting' (or wrapping) a native function which returns a PPL task<T>, into a managed Task<T>? -
How did |= change its behavior? [duplicate]
I just tracked down a bug in some C++ code, and it came down to a behavioral change in a C++ operation. I am just curious what caused the behavior change, was it a C++ standards change, or a hardware platform change? Also roasting me that I should have known better because of this reason or that etc are welcome. :-P This code: long sam = 0; sam |= ((char)-1); std::cout << "sam became " << sam << std::endl; On my Raspberry PI with gcc 8.3.0 that outputs 255. On my AMD Ryzen Threadripper with gcc 9.4.0 that outputs -1. -
Template compilation should fail but as long as offending function is not used, compilation succeeds
I would expect the code below to fail to compile because of the member function f of Exclamator<B> as B does not provide required name member. In reality it compiles fine when f is not used, even with optimizations turned off. How is this possible? #include <string> #include <iostream> class A { public: std::string name() { return "A"; } }; class B {} ; template <typename T> class Exclamator { public: Exclamator(T a): x{a} {} void f() { std::cout << x.name() << std::endl; } private: T x; }; int main() { A a; Exclamator xa {a}; xa.f(); B b; Exclamator xb {b}; // xb.f(); return 0; } $ g++ -std=c++17 -O0 main.cpp $ ./a.out A -
python django - How to make my projrct work on vercel.com
I log in to my vercel account and use github(project site https://github.com/TomTomThomas780/learning-log) and make it on vercel. But it is always a 404 and I don't know why. Website: learning-log-tau.vercel.app. The project works on localhost. My packages version is in requirements.txt -
Write access violation allocating memory for nested data structure on GPU using CUDA C/C++
I have the following data structure: typedef struct { float var1; signed short var2; float var3[4]; float var4[3]; float var5[3]; float var6; } B; typedef struct { signed long num_objects; signed long max_objects; B* objects; } A; I would like to allocate memory for data structure A and its element B* objects. I am doing it in the following way: A* deviceOutputData = nullptr; B* deviceOutputDataObject = nullptr; cudaDeviceSynchronize(); cudaError_t cudaStatus = cudaMalloc(&deviceOutputData, sizeof(A)); cudaDeviceSynchronize(); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMalloc for deviceOutputData failed: %s\n", cudaGetErrorString(cudaStatus)); } cudaDeviceSynchronize(); cudaStatus = cudaMalloc(&deviceOutputDataObject, sizeof(B) * max_objectsA); cudaDeviceSynchronize(); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMalloc for deviceOutputDataObject failed: %s\n", cudaGetErrorString(cudaStatus)); cudaFree(deviceOutputData); } else { cudaDeviceSynchronize(); deviceOutputData->objects = deviceOutputDataObject; } But I am getting write access violation when I do deviceOutputData->objects = deviceOutputDataObject; Can anyone help me solve this issue? I have tried the above code and I am expecting to successfully allocate memory for both A and B and link B address with A address of the data structure. -
Get class name which has an attribute in gdb
In gdb is it possible to know the name of the class that has a certain attribute? Here is an example: class A { public: int my_val; }; class B: public A { public: int my_other_val; }; class C: public B { public: int my_other_other_val; }; int main(int argc, char* argv[]) { C obj1; obj1.my_val = 10; } From obj1 can I know the name of the class with has the attribute my_val? -
unable to compile opengl program inside docker container
I want to compile and run an opengl program inside docker container. For this I used this https://github.com/atinfinity/cudagl Creating docker image and run works fine. glxgears shows the gears in a window. I also installed libglew-dev inside docker container with sudo apt-get install libglew-dev But when I want to compile my program I get this error: square.cpp:(.text+0xe): undefined reference to `glMatrixMode' /usr/bin/ld: square.cpp:(.text+0x13): undefined reference to `glLoadIdentity' /usr/bin/ld: square.cpp:(.text+0x32): undefined reference to `glClearColor' /usr/bin/ld: /tmp/ccSFc4Tx.o: in function `Update(GLFWwindow*)': square.cpp:(.text+0x60): undefined reference to `glfwSetWindowShouldClose' /usr/bin/ld: /tmp/ccSFc4Tx.o: in function `RenderScene(GLFWwindow*)': square.cpp:(.text+0xd1): undefined reference to `glClear' /usr/bin/ld: square.cpp:(.text+0xf0): undefined reference to `glColor3f' /usr/bin/ld: square.cpp:(.text+0x119): undefined reference to `glScalef' /usr/bin/ld: square.cpp:(.text+0x176): undefined reference to `glBegin' /usr/bin/ld: square.cpp:(.text+0x1a3): undefined reference to `glVertex2f' /usr/bin/ld: square.cpp:(.text+0x1c8): undefined reference to `glVertex2f' /usr/bin/ld: square.cpp:(.text+0x1f5): undefined reference to `glVertex2f' /usr/bin/ld: square.cpp:(.text+0x1fa): undefined reference to `glEnd' /usr/bin/ld: square.cpp:(.text+0x1ff): undefined reference to `glFlush' /usr/bin/ld: /tmp/ccSFc4Tx.o: in function `main': square.cpp:(.text+0x250): undefined reference to `glfwInit' /usr/bin/ld: square.cpp:(.text+0x275): undefined reference to `glfwCreateWindow' /usr/bin/ld: square.cpp:(.text+0x285): undefined reference to `glfwMakeContextCurrent' /usr/bin/ld: square.cpp:(.text+0x294): undefined reference to `glfwWindowHint' /usr/bin/ld: square.cpp:(.text+0x2af): undefined reference to `glfwSetKeyCallback' /usr/bin/ld: square.cpp:(.text+0x2da): undefined reference to `glfwSetTime' /usr/bin/ld: square.cpp:(.text+0x2e6): undefined reference to `glfwSwapBuffers' /usr/bin/ld: square.cpp:(.text+0x2eb): undefined reference to `glfwPollEvents' /usr/bin/ld: square.cpp:(.text+0x2f7): undefined reference to `glfwWindowShouldClose' /usr/bin/ld: … -
suppress warning "left operand of comma operator has no effect" [duplicate]
In the following code, a array with repeated elements is created using a fold expression: #include <array> #include <utility> template <std::size_t N> class A { int m_x; public: static constexpr std::size_t size = N; A(int x) : m_x{x} { } int f() const noexcept { return m_x; } int g() const noexcept { return m_x * m_x; } }; template <typename U, std::size_t... I> auto get_array_impl(const U& m, std::index_sequence<I...>) { return std::array<int, m.size + 1>{ m.g(), (I, m.f())... }; } template <typename U, std::size_t... I> auto get_array(const U& m) { return get_array_impl(m, std::make_index_sequence<m.size>{}); } int main() { A<3> x{8}; auto a = get_array(x); return 0; } Check it live on Coliru. Compiling the code gives a warning: main.cpp:18:50: warning: left operand of comma operator has no effect [-Wunused-value] 18 | return std::array<int, m.size + 1>{ m.g(), (I, m.f())... }; While it's clear why the warning is created (I is practically discarded), it is also clear that this is not an issue, since the code does not really need the I-values, but rather uses the variadic expansion to repeat m.f(). How can I suppress the warning while still compiling with -Wall? Is there some variation of the syntax that gives the … -
Incredibuild add-in fails to build C++ solution in Visual Studio
I upgraded my older Incredibuild installation with the latest version 10.5 to fix an invalid license error on Windows and I also upgraded my Visual Studio 2022 add-in respectively since I'm working in Visual Studio on C++ projects. When I initiate a build with Incredibuild, I'm getting a failure the following output: --------------------Build System Warning--------------------------------------- Checking MSBuild version: Cannot load version info from: �l�R�ct Visual Studio Solution File, Format VersionMSBuild\Current\Bin\amd64\, Error: 123 ------------------------------------------------------------------------------- --------------------Build System Warning--------------------------------------- Visual Studio does not include an English language pack: This version of Visual Studio does not include a built-in English language pack. For the best Incredibuild experience, it is highly recommended to install a Visual Studio English language pack. ------------------------------------------------------------------------------- Build ID: {184494E3-2125-4767-B661-F6D0037AE45A} Active code page: 437 The filename, directory name, or volume label syntax is incorrect. 2 build system warning(s): - Checking MSBuild version - Visual Studio does not include an English language pack I verified my Visual Studio Installer language packs and I have English installed, my Visual Studio is in English after all so the warning seems bogus: Overall I don't understand why Incredibuild is failing, maybe it calls a bad command in the Visual Studio 2022 development tools which implies … -
Check return stament of c++ code in vscode [duplicate]
Is it possible to check the result in a return statement in vscode running gdb? Here is an example: bool foo(int i) { return i>10; } int main(int argc, char* argv[]) { foo(11); } When using vscode with gdb to debug this code, once I step over the line with return i>10; I will end up in the line with }. Can I extract what was evaluated in the return statement without leaving the function? -
Django server not accessible when run through docker-compose: connection reset by peer
I have a docker image which runs django. Docker-compose is like this: services: www: image: my-www-image ports: - "80:80" If I docker exec -ti bash into this container and curl localhost, I get Django-related output, and the docker-compose log notes the GET request. If I go to the host machine and curl localhost, I get curl: (56) Recv failure: Connection reset by peer (note this is not a Connection refused, which I would get if I use a random wrong port number) Adding EXPOSE 80 to the Dockerfile made no difference. Why can't the host machine connect to the otherwise-working service inside the container? -
Ajax form not passing Product Id and Product Title to cart
I'm following Zander from Very Academy Ecommerce tutorial series and reached the part where we use Ajax to submit form data of the product to the cart. I've managed to pass the quantity and the price but not the title. Its not rendering(displaying) in the cart page. Everything else works fine. I messaged Zander asking for help and its been a month and still no response from him. Here is the Ajax from the tutorial: <script> $(document).on('click', '#add_button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "inventory:single_product_add_to_cart" %}', data: { productid: $('#add_button').val(), productqty: $('#select option:selected').text(), csrfmiddlewaretoken: "{{csrf_token}}", action: 'post' }, success: function (json) { }, error: function (xhr, errmsg, err) {} }); }) </script> This is my product model: class Product(models.Model): product_metas_set = models.ForeignKey(ProductMetas, on_delete=models.CASCADE, related_name='product_metas') PRODUCT_TYPE = ( ('single_product','Single product'), ('variable_product','Variable product'), ('groupped_product','Groupped product'), ) PRODUCT_STATUS = ( ('is_inactive','Inactive'), ('is_active','Active'), ('published','Published'), ) product_status = models.CharField(choices=PRODUCT_STATUS, max_length=100) product_is_featured = models.BooleanField(default=False) product_is_bestseller = models.BooleanField(default=False) product_is_on_sale = models.BooleanField(default=False) high_sell_through = models.BooleanField(default=False) price_regular = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) price_sale = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) product_UPC = models.CharField(max_length=300, blank=True, null=True) product_SKU = models.CharField(max_length=300, blank=True, null=True) product_MODEL_ID = models.CharField(max_length=300, blank=True, null=True) product_stock_management = models.ForeignKey(ProductStockManagement, on_delete=models.CASCADE, related_name='product_stock_management') product_attributes_set = models.ForeignKey(ProductAttributesSets, on_delete=models.CASCADE, related_name='product_attributes_set') product_specifications_set = … -
Add offset to a time
I have a string that I convert to time based on certain format const std::string format = "%Y-%m-%dT%H:%M:%S"; std::istringstream dateStream(date); std::tm tm = {}; dateStream >> std::get_time(&tm, format.c_str()); Then I want to add an offset to it and print the result as a string: tm.tm_min += offset; std::mktime(&tm); std::ostringstream resultStream; resultStream << std::put_time(&tm, format.c_str()); It seems to work here https://godbolt.org/z/q7svh51Y7 But when I run it on my local system I receive 2023-09-26T18:18:23 instead of 2023-09-26T17:18:23 Could you help with a solution for this ?