Posts

Showing posts from May, 2023

Is it possible to modify input function to echo uppercase letters?

Let's say that I have an input("> ") , and if you try to input a lowercase "Hello, world!" it will look like this: > HELLO WORLD!

How to get the value type from a record in Typescript

I have a function which returns a record: ReturnType: Record<string, {...<SOME_BIG_TYPE>...}> , and another function that I would like to accept {...<SOME_BIG_TYPE>...} as an argument. How can I grab that type from the record? I would like something like the following where ExtractedValueOf grabs that value I mentioned earlier. const function = ({ bigObject }: { bigObject: ExtractedValueOf<ReturnType> }) => null; I was thinking something like ReturnType<keyof ReturnType> but this does not work. Edit: Added a basic example that illustrates my issue. I have here a function that returns Record<string, SomeType> , which is used to call my other function, which takes an argument of SomeType . This is all typesafe and how I would expect it to work: type SomeType = { field: string; another: string; }; function sample(): Record<string, SomeType> { return { object: { field: "Hello", another: "World",...

If I use a String as argument on a Provider the return of a Provider work But If I use a List

just like instagram my application has a feature that are the saved. One person can save post. For this I added a field in the users collection "save", this field is an array of "post id". This "post id" is used to fetch recipes (another collection) A user, if you want to see the posts you saved, click on a button and you are directed to this widget: ("getReceitaGuardadosProvider"-> this is the provider that I m talking about) receita=ref.read(getReceitaGuardadosProvider(user.guardados)); So if I give this provider a String as a argument It will return AsyncData(), but If I give a List as a argument It will return AsyncLoading() import 'package:chefapp/features/auth/controleer/auth_controller.dart'; import 'package:chefapp/features/receita/receitas_controller/receitas_controller.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:chefapp/co...

Wrap a paragraph around an image in bootstrap

Image
I want the paragraph to go around the image and wrap it so I don't waste space. My code: <div class="container"> <div class="row"> <div class="col-6"> <h1 class="display-4">Lorem ipsum</h1> <p class="lead">Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups.</p> <a href="#" class="btn btn-outline-dark rounded-pill">התחל לכתוב</a> </div> <div class="col-6"> <img src="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse2.mm.bing.net%2Fth%3Fid%3DOIP.YrOgCeeTMGooIg3gpMz8qgHaHa%26pid%3DApi&f=1&ipt=8172a3c985e7c4343b252d0ccaa06f7c36f146a5f6ce4f20fc7c801bf5ce2974&ipo=images" alt="Round Image" class="rounded-circle"> </div> </div> </div> I...

How do I implement timeOuts in TestNG? They don't appear to be working

@Test(dataProvider="TestDataSets", dataProviderClass = TestData.class, groups = { "SmokeTests", "Regression" }, timeOut = 120000) public void MyTestCase(String scenario, String formName) throws Exception { Am I implementing the timeOut incorrectly? This should timeout after 120 seconds, correct? Some of my test cases run too long and should be terminating at 120 seconds but they are never terminated by TestNG. I'm running Java 17 with TestNG 7.8.0 Upon further investigation TestNG did determine that my test case hit the timeOut: [ERROR] testCaseClassFile.methodName » ThreadTimeout Method tests.testCaseClassFile.methodName() didn't finish within the time-out 120000 Apparently it hit the timeOut and kept on going. The TestNG documentation made me think that it would stop execution: Section 5.11.2 of the TestNG documentation states, Additionally, a time-out of ten seconds guarantees that none of the threads will block on this thread forever. ...

mplfinance: 'secondary_y=True' not working. Not plot multiple lines/candles due to very wide Y-Axis data ranges

I want to compare price movement of two scrips with Stock Indices in one chart object (single panel) using mplfinance in python 3.11.3. Tried code from snippet: https://github.com/matplotlib/mplfinance/blob/master/examples/addplot.ipynb I have data in 3 excel csv files that are to be plotted (line or candle) in one chart: Indeces data Data of scrip1 Data of scrip2 Comparison of two tables is generating chart below: Chart comparing data in two tables I tried the mplfinance method given in Plot multiple mplfinance plots sharing x axis This method exits the console. Then, the following code has been tried: import mplfinance as mpf import pandas as pd idc = pd.read_csv(r'D:\NUVAMA_STOCK_DATA\CHARTING-BANKNIFTY-25 MAY 2023\Nifty Bank_03March2023-25 MAY 2023_CHART.csv') idc['Date'] = pd.to_datetime(idc['Date'], format = "mixed") idc.set_index('Date', inplace=True) intraday = idc intraday.index.name = 'Date' intraday.shape intrada...

Problem with using self-built GDAL in Docker

I am trying to prepare an Ubuntu 22.04 Docker image with GDAL 3.2.2. This GDAL installation needs to have ECW support, which means I cannot use the pre-built gdal-bin package that can be installed using apt. I can build and install GDAL with these specs in the Docker container. But when running a simple test command on a simple tiff file I get an error that I have no idea how to debug. $ gdalinfo --version GDAL 3.2.2, released 2021/03/05 $ gdalinfo test.tif Driver: GTiff/GeoTIFF Files: test.tif Size is 572, 577 Aborted (core dumped) The steps I took was starting with a regular Ubuntu 22.04 Docker image. Installing prerequisites (gcc and stuff). Downloading the ECW SDK. Install that. Download the source of gdal 3.2.2. Configure the build to include ECW. Use the make file to build and then install. If I do not use a self-built GDAL but rather install gdal-bin using apt directly, it works for the tiff file, but it would mean I have no ECW support. I have also successfully built and u...

Error while doing a POST call from Angular to Firebase Cloud Function

I've created a Firebase Cloud Function and it's working; export const deleteUser = functions.https.onRequest(async (request, response) => { const userEmail = request.body.userEmail; await admin.auth().getUserByEmail(userEmail) .then(function (userRecord:any) { const uid = userRecord.uid; admin.auth().deleteUser(uid) .then( () => { console.log('User deleted'); response.status(200).send('User deleted'); }) .catch(() => { console.log('Error deleting user'); response.status(500).send('Failed to delete user'); }); }) .catch(() => { console.log('Error fetching user'); response.status(500).send('Failed while fetching user'); }) }) I've checked with Postman and everythings is ok, it deletes the user from Firebase as expected. Screenshot of the call from Postman I call my service from my component, and work...

Auto-refetch a mutation by invalidating its tag from another mutation

Can I auto-refetch getEmployees mutation by invalidating its tag from another mutation called deleteEmployee in the code below? import { createApi } from '@reduxjs/toolkit/query/react' import customFetchBase from './customFetchBase.js' export const publicApi = createApi({ reducerPath: 'publicApi', baseQuery: customFetchBase, tagTypes: ['employees'], endpoints: builder => ({ getEmployees: builder.mutation({ query: ({ formData = "defaultHashedDataString", salt = "xyz", pageIndex = 1 }) => ({ url: '/Hafez/Employee/Data', method: 'POST', body: { RequestVerificationToken: salt, FormData: formData, currentPage: pageIndex + 1 } }), providesTags: ['employees'] }), deleteEmployee: builder.mutation({ query: ({ formData, salt }) => ({ url: '/Hafez/Employee/Delete...

How can I configure the log of grpc Java client to output all levels of grpc logs?

I have a server and a client using logback as log framework, client and server use grpc Java to communicate with each other. Now I want to output all level of grpc logs, I change the log level to trace on logback.xml, but there are not all grpc logs output to the log file. I add logging.properties and add - Djava.util.logging.config.file=logging.properties , It seems not work at all. # Create a file called logging.properties with the following contents. handlers=java.util.logging.ConsoleHandler io.grpc.level=FINE java.util.logging.ConsoleHandler.level=ALL java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter I want to output the logs of grpc re-connection attempts and all connect and re-connect actions. How to config the grpc logs? add JAVA_OPTS=-Djava.util.logging.config.file=logging.properties

What will be the time and space complexity for vertical order traversal of a binary tree?

I have written the following c++ function to traverse a binary tree in vertical order. For nodes on the same vertical level, I want to store them in the order they will appear in the level order traversal. Example: If we have the tree like this: 1 / \ 2 3 / \ / \ 4 5 6 7 I want to return a vector of vectors as: { {4} {2} {1 5 6} {3} {7} } void traversal(TreeNode* node, int x, int y, map<int,map<int,vector<int>>> &m){ if(node == NULL){ return; } if(m[x].find(y) == m[x].end()){ vector<int> temp; m[x][y] = temp; } m[x][y].push_back(node->val); traversal(node->left,x-1,y+1,m); traversal(node->right,x+1,y+1,m); return; } vector<vector<int>> verticalOrderTraversal(TreeNode* A) { map<int,map<int,vector<int>>> m; traversal(A,0,0,m); vector<vector<int>> ans; for(auto itr:m){ vector<int> temp; fo...

Laravel mysql order by with wherehas

I have 2 tables :- users - id,name,email, mobile user_info - id,user_id, store_name, startup_date User Model class EloquentUser extends Model { protected $table = 'users'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'mobile' ]; } User Info Model class UserInfo extends Model { use HasFactory, SoftDeletes; public $table = 'user_info'; } Below is relationship on above 2 tables :- public function info() { return $this->hasOne(UserInfo::class,'user_id','id'); } I want to order on base of startup_date but it is giving error column not found. Below is the query :- $reponse = EloquentUser::with('info')->has('info')->orderBy('info.startup_date')->get();

Training a BARTForSequenceClassification returns data with ununiform dimentsions

I am trying to fine-tune a BART-base model on a dataset that I have. The dataset looks like this: It has columns "id", "text", "label" and "dataset_id". The "text" column is what I want to use as inputs to the model, and it is plain text. "label" is a value of either 0 or 1. I've already written the code for Training, using transfomers==4.28.0. This is the code for the dataset class: class TextDataset(Dataset): def __init__(self, encodings): self.encodings = encodings def __getitem__(self, idx): return {key: torch.tensor(val[idx]) for key, val in self.encodings.items()} def __len__(self): return len(self.encodings['input_ids']) This is the code for loading and encoding of the data: def load_data(directory): files = os.listdir(directory) dfs = [] for file in files: if file.endswith('train.csv'): df = pd.read_csv(os.path.join(directory...

Can you use the activeElement property to see if an element with a specific class name has focus?

Im trying to get the Boolean true if elements with a certain class name are focused on. But it seems Document.activeElement only works with either ID or Tag name, which wont help since they're elements of the same type. Heres the situation: var test2 = document.getElementsByClassName('test2') var test3 = document.getElementsByClassName('test3') test3[1].focus() isFocused2 = (document.activeElement === test2) isFocused3 = (document.activeElement === test3) document.getElementById('test').innerHTML = isFocused3 <input type="text" class="test2"> <input type="text" class="test3"> <input type="text" class="test2"> <input type="text" class="test3"> <div id="test"></div> @Michael It works ONLY if the focus () is set to the input as you'll see below, but clicking on the input doesn't seem to make it active hence making the...

Inserting Overlay Content Into Header Of Jekyll Theme

Image
I want to add overlay content to the header, specifically to overlay on top of the Header Image. Details I have written the HTML/Liquid and SCSS and it all works when I test it outside of the site build, but I wanted to know how to add this overlay content into the header of all pages using the _masthead.html . The goal is to insert a widget of sorts with variable content. This is what the header currently looks like on the site image of website header This is what it is supposed to look like image of website header What it Looks Like Now After I implemented what Christian told me it looks like this now The Files The repository can be found here , and the components are: This is the _masthead.html <div id="masthead-no-image-header"> <div class="row"> <div class="small-12 columns"><!-- <a id="logo" href="/" title=" – "> <img src="/assets/img/" alt=" – ...

How to Update user data with patch and react native

I have a react native app and I try to update the user data. Like firstname, lastname, etc. And I am calling a api call. And I try to update a logged in user through passing arguments in the header of the api call. But apparently that doesn't work untill now. Only when I pass the arguments hardcoded then it works. So this is the service: export const AccountUpdateRequest = async ( first_name, last_name, email, username, password, password2 ) => { const token = await retrieveToken(); console.log("response"); try { if (token) { const response = await fetch("http://192.168.1.65:8000/api/user/me/", { method: "PATCH", headers: { Authorization: `Token ${token}`, "Content-Type": "application/json", }, body: JSON.stringify({ first_name: first_name, ...

Dynamic sub Select using Expression with FromSqlRaw in .Net Core (v7) with cast to Entity EF (Ex: The required column not present of 'FromSql')

This is simplified example of what is needed. Could this somehow be made to work? Entity: public class Entry { public int EntryId { get; set; } public string Name { get; set; } = null!; public string? Description { get; set; } } DbContext: public DbSet<Entry> Entries { get; set; } = null!; Code: public void RunTest(DbContext context) { // direct linq Select two column into Entity var list = context.Entries.Select(a => new Entry { EntryId = a.EntryId, Name = a.Name }).ToList(); // Generated Sql (seen in profiler): SELECT [e].[EntryId], [e].[Name] FROM [Entry] AS [e] var type = typeof(Entry); // dynamic Select with Expression (result should be same as direct above) // does NOT Work for subSelect // Exception: 'The required column 'Description' was not present in the results of a 'FromSql' operation.' var sqlQuery2 = "SELECT [EntryId], [Name] FROM [dbo].[Entry]"; var selectProps2 = new Lis...

Mocking data with nock in playwright test

I'm writing my first Playwright Screenshot-test for a node application. The application makes serverside api requests and I want to mock the api responses so that my test becomes stable, predictable and can be run offline. I will use nock to setup mocked data, because I've used nock in my old existing test suite (built on mocha + supertest) with great success. But in my new Playwright-test I can't get nock to apply to my node app, probably because the node app is started as a separate process. An old successful test file that uses supertest const supertest = require("supertest"); const app = setupMyEntireNodeExpressApp(); nock("https://my-api.com").get("/").reply(200, { fakeData:true }; supertest(app).get("/").expect(200).end((err, response) => { doSomething(); }) //let supertest start the node app and make a request The new playwright-test (myTest.spec.js) where the nock does not apply const { test, expect } = require(...

How can the cookie value not be the same in the dynamic route?

I implemented a program with next js , i want to use cookies on dynamic pages , the problem is that the cookie value is inherited in other pages , this happens while each page should have its own cookie. I want to have a button to set cookie and a Link for navigation between dynamic blog routes , when i set the cookie for example in this path /blog/2 and click the Link to go to next blog or previous blog , the cookie is inherited in other dynamic blog routes. In this example , the js-cookie module is used. Example : // /blog/[blogId] import Cookies from 'js-cookie'; import Link from 'next/link'; import { useRouter } from 'next/router'; import dynamic from 'next/dynamic'; function SingleBlog() { const router = useRouter(); const { blogId } = router.query; return ( <> <Link href={`/blog/${Number(blogId) + 1}`}> next blog </Link> <button onClick={() => Cookies.set('name...

Using spacebar to check a Check Box, perform a DCount(), with focus remaining on the check box?

I have a form with a datasheet subform, where one of the controls is a Check Box (Chk1). I want it to behave such that: If the check box is checked using mouse click, a DCount(...) on the same Check Box field is performed in the VBA straight away. I have this part working, by navigating away from the record in the Check Box AfterUpdate Sub: Public fromSpace As Boolean Private Sub Chk1_AfterUpdate() If Not fromSpace Then 'mouse click, so it's necessary to fire Form_AfterUpdate by navigating away Form_Main.cboSelector.SetFocus Else 'Spacebar used with SendKeys so navigating away is not necessary fromSpace = False 'reset for next time End If End Sub Then the AfterUpdate of the datasheet subform has the DCount(...) Private Sub Form_AfterUpdate() If DCount(...) = x Then 'This DCount looks at the yes/no (Check Box) field in question 'Do some stuff End If End Sub However, I also want it to behave such that: If the check...

Build a dictionary from an object's explicitly declared fields

My table definition: class AppProperties(base): __tablename__ = "app_properties" key = Column(String, primary_key=True, unique=True) value = Column(String) Code for updating an app property: session = Session() query = session.query(AppProperties).filter(AppProperties.key == "memory") new_setting = AppProperties(key="memory", value="1 GB") query.update(new_setting) The line query.update(new_setting) fails because the update method requires an iterable. If I use query.update(vars(new_setting)) , it includes some extra values, which are not there in the underlying table and hence fails. How can I build this dictionary: {"key": "memory", "value": "1 GB"} using the object new_setting , so that I can call the update method using this dictionary? For example: query.update({"key": "memory", "value": "1 GB"}) Because I already have everything in new_set...

beforeLoad suitescript netsuite

i create an script beforeLoad if status Pending Fulfillment or approval function beforeLoad(context) { var currRec = context.newRecord; var status = currRec.getValue('status') var mem = currRec.getValue('memo') var idSo = currRec.getValue('id') // log.debug('status', status) if (status === 'Pending Fulfillment') { record.submitFields({ type: record.Type.SALES_ORDER, id: idSo, values: { trandate: null }, }); } else if(status === 'Pending Approval'){ record.submitFields({ type: record.Type.SALES_ORDER, id: idSo, values: { trandate: null }, }); } } but when view an sales order that trandate not response. only when once r...

Learning Electron, trying to send data to renderer from main but appearing as undefined in renderer. Any help much appreciated

Am working with electron and encountering and issue that I cannot for the life of me fix despite it being so simple, where my received data is showing as undefined in renderer, yet shows correctly when console.log(the data) in main. All I am trying to do is have main read a .JSON file and send the contents of it to the renderer to be stored and used. Here is renderer code: let table_data ipcRenderer.send('request_data'); ipcRenderer.on('activity_data', (event, activityData) => { console.log('Data received'); console.log(activityData); //This returns undefined }); ipcRenderer.on('activity_data_error', (event, error) => { console.error('Error fetching activity data:', error); }); Here is main code: // Respond to ipc Renderer request activity_data ipcMain.on('request_data', (event, data) => { try { const rawData = fs.readFileSync('renderer/js/activity_data.json', 'utf8'); const activity...

flutter floor floor_generator There are no entities added to the database annotation

I have created the floor entities and DAOs but when i run flutter packages pub run build_runner build --delete-conflicting-outputs i got the following error There are no entities added to the database annotation. package:storeapp/database/myAppDatabase.dart:74:16 ╷ 74 │ abstract class MyAppDatabase extends FloorDatabase {} │ but i added the entities as following @Database(version: 1, entities: [ Account, AccountingClass, LocalizedProperty, PointOfSale, StoreCurrencyMapping, User, InventoryTransaction, JournalVoucher, JournalVoucherEntry, JournalVoucherEntryDetail, BaseObject, StoreCustomer, StoreEmployee, StoreVendor, Store, Warehouse, Category, Product, ProductCategory, StoreProductMapping, Order ])

Call a API synchronously inside For Each loop in android Kotlin Coroutines with Flow getting Error

Call a API synchronously inside For-each loop in android Kotlin Coroutines using Flow. Also i need to wait all the API calls need to complete without blocking the Main Thread. fun getLatesData(): Flow<Model> = flow { emit(getFirstList()) }.flatMapLatest { data -> flow { val responseList = mutableListOf<String>() data.items?.forEach { datalist -> val response = getCreatedDate(datalist.Id) response.collect{count-> responseList.add(count.check) } val countData = Model( datalist = data, responseListCount = responseList ) } emit(countData) } } private fun getCreatedDate(Id: String?)= flow { try { val response = repoApi.getCount(Id) emit(response) } catch (e: Exception) { ...

Hide button while model is running in Streamlit

Hide button while model is running in Streamlit. Hi, I am developing an application, which infer an stable diffusion model when RUN button is pressed. How can i disable/hide this RUN button while model is running, and enable/show it again when done. Thanks.

How do I use path the to my VS Code extension's directory in a contributed setting's default value?

I am developing a VS Code extension for Vale style linting. It includes a styles sub-directory with files for individual style rules. Inside the extension, I'm overriding a config option from another extension in its package.json file: "contributes": { "configurationDefaults": { "vale.valeCLI.config": ".vale.ini" } } The .vale.ini file is included in the root directory of the extension itself. Is there a variable that points to the root directory of the current extension? Or a way derive it from an extension ID? The above code does not work for me...

How to run a function in a singleton file only when electron main process is ready

I am using electron + vue, in my vue files, there is a file called globals.ts which is a file that exports global variables for all my vue files to use, it is a singleton file, I am trying to get it to communicate with electrons main process to fetch the user's machine IP address, however, there are errors occuring because apparently the main process is not finished loading before globals.ts function runs, meaning the ipcRenderer function is invoked before the main has the API available. How do i get it to wait for the main process to finish loading first so i can safely invoke a function and get a result? //electron/main/main.ts async function createWindow() {//...code to create window here} ipcMain.handle("getMachineIPv4", (e, arg) => { console.log("getting ipv4"); const interfaces = os.networkInterfaces(); for (const interfaceName in interfaces) { const interfaceInfo = interfaces[interfaceName]; for (const info of interfaceInfo) { ...

Calculating Fraction in power bi

I have a table with multiple columns which comes from different data sources. in which 2 columns are Actual Number and Expected Number(both measures). I have to create a new column in the table which just shows Actual Number/Expected Number. Few rows have blanks for both Actual and Expected, for which i have to show "N/A". I was able to acheive the first part where we just show actual/expected, But challenge is when changing the logic to show N/A for blank values of actual and expected columns. what i tried: Created a measure,This works perfectly for non-blanks IF([Actual] >0,[Actual]&"/"&[Expected]) I changed the measure to this to show N/A for blanks: IF(ISBLANK([Actual]) ||ISBLANK([Expected]),"N/A",IF([Actual] >0,[Actual]&"/"&[Expected])) when i try the above, the no of rows in the table drastically increases creating duplicates and i get many records with "N/A", where i only have 1 row which has blank ac...

Cannot create a Cloud Build trigger with Cloud Build repositories 2nd gen - permissions error

Image
I have been following the instructions at https://cloud.google.com/build/docs/automating-builds/github/connect-repo-github?generation=2nd-gen to create a Cloud Build Trigger from a GitHub repo connected to Cloud Build repositories 2nd gen. Whether I use gcloud as in the instructions, use the Google Cloud Console UI or even try programmatically via Terraform, I get the same error. I cannot work out if I need to set permissions somewhere or if it is just a misleading error and something is wrong with the GitHub permissions. My user account has the roles/cloudbuild.connectionAdmin role. I cannot see why the mentioned permission would not be there. connection of repository projects/my-project/locations/us-central1/connections/my-app-github-connection/repositories/MyApp cannot be fetched: generic::permission_denied: Permission 'cloudbuild.connections.get' denied on 'projects/my-project-number/locations/us-central1/connections/my-app-github-connection' Here is the roles...

How can I make environment variables available during Docker build for a Rails 7 app with MRSK?

I'm trying to build and deploy a rails 7 app with MRSK. The docker build process needs different environment variables for bundling gems, installing yarn packages, etc. My deploy.yml contains following information: env: secret: - GITLAB_TOKEN builder: secrets: - GITLAB_TOKEN args: RUBY_VERSION: 3.2.2 multiarch: false The .env-file: GITLAB_TOKEN='test' In my Dockerfile I've tried following: RUN echo "$GITLAB_TOKEN" RUN --mount=type=secret,id=GITLAB_TOKEN RUN cat /run/secrets/GITLAB_TOKEN But the environment is in both cases empty. I've found a workaround by using args instead of environments in the deploy.yml: builder: args: GITLAB_TOKEN: "<%= ENV['GITLAB_TOKEN'] %>" But args are not masked secret and using erb-text in a yml-file seems very ugly. This also may not work for non rails-applications.

why doesn't navigator.setAppBadge() in Safari on iOS work without a number argument?

According to the spec: ( https://www.w3.org/TR/badging/#example-showing-ready-status-on-the-app-icon ) navigator.setAppBadge() with no arg should alert the user with a badge containing no number, but it does not do so in Safari on iOS. You can try it yourself directly from the web inspector for the service worker (BTW, why can't I get a web inspector for the web app when it's installed on the home page?). EDIT: I can now get the developer tools to work with both the service worker and the web page; perhaps a Safari update? The windows will sometimes just disappear, however. Why is this not to spec? Is this by Apple's design, or a bug? If I put in a number: navigator.setAppBadge(23) ...it works fine. (BTW, numbers up to 999,999 seem to display on my iPhone 13 mini without being clipped.) This is all in the context of trying to use the Web Push API to display notifications and badges for my web app, with the sole purpose of telling the user it's xer turn in the game...

How can I implement basic authentication between Next.JS and DRF using JWT?

I am trying to recode the website for my student club and would need some assistance regarding authentication. I do have a Django Backend setup with all the necessary data (e.g. Member infos, etc.) and would like to display them on the frontend (name + position) and on the Backend (email, phone number, etc.). Now to achieve that I would need basic authentication where I can give out login credentials to the members and they can login (no sign up from the website). Now I am wondering how to do that; coming from Django I would generate a credential pair and the authentication would go via JWT, but I cant find a suitable example (everything is very old). Right now my setup looks like this: Django Backend with JWT Next.JS frontend (typescript, tailwind css) with seperate login page I was looking at next-auth which seems promising but I am afraid that login via Socials is not my usecase. Can anyone provide more information how to setup Django with Next.JS with authentication? Cheers I...

Splitting Text to Two Columns Using a Separator in R

I am trying to split the column using a separator "|" but unfortunately the suggestions in Stack Overflow which recommended using separator() is not working in my situation. Can someone help me out here. The data frame, I am using is given below: structure(list(UniqueID = c("12M-MA | X1", "12M-MA | X2", "12M-MA | X3", "12M-MA | X4", "12M-MA | X5" ), Cost = c(0.2, 0.3, 0.2, 0.2, 412.86), Actuals = c(0, 0, 0, 0, 32), Forecast = c(0, 0, 0, 0, 21), Value_Actuals = c(0, 0, 0, 0, 28341), Value_Forecast = c(0, 0, 0, 0, 652431 ), `Forecast Accuracy` = c(0, 0, 0, 0, 8.51), `Max (Act vs Cons)` = c(0, 0, 0, 0, 652431)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame")) The code which I have used and the one which is working is this: library(readxl) library(dplyr) library(writexl) library(stringr) Df<- read_excel("C:/X/X/X/X/YXZ-2023.xlsx"skip = 1) Df <- Df %>% ...

Python - Count all combinations of K numbers from 1-N whose sum is equal to N

How do i count all combinations of k numbers from 1-n whose sum is equal to n? Like for n = 10, k = 3, we have (1, 2, 7), (1, 3, 6), (1, 4, 5), (2, 3, 5) I've tried using itertools.combination but it grows really fast for big numbers

Elasticbeanstalk application deployed but not showing in AWS console

Image
I manage to run eb deploy successfully from the command prompt and get the following: 2023-05-21 21:27:31 INFO Environment update completed successfully. And when I run eb list I get as result the name of my environment * simply-dev . I can run eb status --verbose and see everything looks healthy/green. Environment details for: simply-dev Application name: simply Region: us-east-2 Deployed Version: app-230523_221320835290 Environment ID: e-rdyf63m2dr Platform: arn:aws:elasticbeanstalk:us-east-2::platform/Python 3.8 running on 64bit Amazon Linux 2/3.5.2 Tier: WebServer-Standard-1.0 CNAME: exit.us-east-2.elasticbeanstalk.com Updated: 2023-05-23 21:17:44.717000+00:00 Status: Ready Health: Green Running instances: 1 i-034a7471b6b368e1b: healthy However, when I run eb console , the console opened in the internet browser keeps loading endlessly and I cannot see any application or environment. I also checked I am in the same region and both show ...

How can i, in flutter scrap data from a random website on the internet and interact with it

How can i, in flutter (or other language) scrap data from a random website on the internet (like Youtube) and interact with it (Clicking on a video) and getting the content. For exemple, login on a website by inserting an email and a password and clicking on submit(All of this in the flutter app) and then getting the data of the profil and using it inside my flutter (or other) app

Find all numbers in a set of maxima that sum to a given number

I am struggling to think of an algorithm which matches my needs. I have a list of integers in a set, each integer represents a maximum value, the list can contain >= 1 entries. I would like to find all the combinations of integers within these maxima that sum to a given value. For example for a list of 4 maxima = [2, 3, 0, 5] and given value = 5, solutions are: [2, 3, 0, 0] [2, 2, 0, 1] [2, 1, 0, 2] [2, 0, 0, 3] [1, 3, 0, 1] [1, 2, 0, 2] [1, 1, 0, 3] [1, 0, 0, 4] [0, 3, 0, 2] [0, 2, 0, 3] [0, 1, 0, 4] [0, 0, 0, 5] I have found some great algorithms related to this but they only address the combinations of the integers in the list which sum to the given value (i.e. in above example, would generate [2, 3] and [5] but not all the other combinations that I am interested in. I have built a solution (in Swift) that solves this with blunt force (see below), but I am looking for something far more efficient. import UIKit let avail = [2, 3, 0, 5] let sol = [0, 0, 0, 0] var solList = [[...

Can I create separate a mouse cursor/keyboard for my Python bot to exclusively use? [closed]

I am using Python3, pynput and pyautogui to perform few mundane operations in an application on my second monitor by using mouse and keyboard. However, I would like my Python script to control a separate mouse/keyboard operating on my second monitor so it can perform its operations without interfering with my activity on the first monitor. Is this even possible to do? If so, are there any packages/libraries that do this?

.NET MAUI Blazor Desktop Application | How do I retrieve arguments passed into application

I have created a brand new .NET MAUI Blazor application using the standard template. There is a Program.cs file that has been created. As the title suggests, how do I retrieve arguments passed into application using C#?

Visual Studio 2022 Typescript Intellisense

I have a medium size React app hosted inside an ASP.NET Core WebApi project. I have about 100 ts/tsx, and a handful of js files created using the OOB React template. For 6 months, the development experience was great. Intellisense, reference navigation, and error resolution suggestion all near instant. Last week, I patched VS2022 Pro 2022 (64-bit) to V17.5.5. Initellicode 2.2, TypeScript Tools, 17.0.20105.2003. Now VS2022 is almost unusable. Apparently, a language service spins up a separate Node instance to handle JS/TS work. That Node process seems to be pegging the CPU, eating ~0.7GB of memory. Not while debugging but simply having the solution open. I created a new sandbox project from the same template. Added some ts files, nothing exotic, just simple type definitions and the npm packages I need. Same thing. It takes 13-15 seconds to hover over a type for Intellisense to recognize it. Compilation errors take at least that long. I get a progress bar when 'Go to Definition'....

"CMAKE" doesn't create "Debug" or "Release" output folders

My .vcxproj file had this segment, which includes x64/Debug and x64/Release for Configuration and Platform . I am working on Windows machine <ItemGroup Label="ProjectConfigurations"> <ProjectConfiguration Include="Debug|x64"> <Configuration>Debug</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|x64"> <Configuration>Release</Configuration> <Platform>x64</Platform> </ProjectConfiguration> .......... </ItemGroup> I now tried to create CMakeLists.txt cmake_minimum_required(VERSION 3.5) project(LogMsg) # Set the project source files set(SOURCES LogMsgMain.rc LogMsg.h ) # Add executable target add_executable(LogMsg ${SOURCES}) # Set the configuration-specific outputs set_target_properties(LogMsg PROPERTIES RUNTIME_OUTPUT_DIRECTORY_DEBUG "${CMAKE_CURRE...

What steps should I follow to enable PayPal Advanced Credit Card Payment integration in Spring Boot app for non-PayPal account holders?

I am trying to integrate paypal advanced credit card payment, for customers who do not have a paypal account to be able to pay using their card. And I'm facing issues doing that. I succesfuly integrated Paypal into my Spring Boot app, but only for customers with a paypal account (They are redirected and required to log into paypal before paying). The issue here is I want get a response from Paypal and beign able to process it alongside the user's session information, I followed tutorials leading to creating a PaymentSource instance and then setting into my orderRequest : Card card = new Card(); card.number(creditCard.getNumber()) .expiry("YYYY-MM") .securityCode("CVV"); PaymentSource paymentSource = new PaymentSource().card(card); But OrderRequest has no property as PaymetSource. I provide source code below, can you please help me fix this issue, or just provide me with a guide for the integration from scratch. Thank you...