div not showing react-router-dom

I’m new to JS and react, and I’m currently programming a Firebase project by watching a tutorial on youtube

I have a problem with the display of this div :

export const Main = () => {
  return <div> Home page </div>;
};

Here is the App.tsx

import React from 'react';
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom';
import "./App.css";
import { Main } from "./pages/main";

function App() {
  return (
    <div className="App">
      <Router>

        <Routes>
          <Route path="/" element={<Main />}/>
        </Routes>

      </Router>
    </div>
  );
}

export default App;

There is no error, just a blank page.

Thank you for your help !

It should display a div Home page at the main page

jSpreadsheet CE custom tooltip on hover

I am trying to set up custom tooltips for column headers. While the pro vers. site describes how to do this, I could not find the information on the CE site. I tried the following, but the column title appears in the tooltip.

jspreadsheet(document.getElementById('spreadsheet'), {
    workshets: [{
        columns: [
            {
                type: 'text',
                title: 'MyTitle',
                tooltip: 'This is a custom tooltip',
                width: 160
            }
        ]
    }]
});

Getting ‘Array’ as decoded json response from a post api call PHP

I’m trying to send a post request to my php endpoint from vue.js. This is the code :

$router->post('/add', function () {
    $json = file_get_contents('php://input');
    echo $json;
});

If I echo the json , I get an object as a response :

{
    "method": "POST",
    "headers": {
        "Content-Type": "application/json"
    },
    "body": "{"SKU":"ABC123","name":"Product Name","price":19.99,"type":1,"size":2,"weight":1.5,"height":10,"width":5,"length":15}"
}

However, when I try to decode it like this :

$router->post('/add', function () {
    $json = file_get_contents('php://input');
    $data = json_decode($json,true);
    echo $data;
});

I get this response : Array.
I can’t figure out why I’m not getting a decoded jsos, I’d appreciate any help, this is the post request from vue :

axios.post('http://127.0.0.1:8000/add', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      SKU: 'ABC123',
      name: 'Product Name',
      price: 19.99,
      type: 1,
      size: 2,
      weight: 1.5,
      height: 10,
      width: 5,
      length: 15
    })
  })
    .then(res => console.log(res))

    .catch(error => {
      console.error('Error:', error);
    });

Do we use weglot in react native? [closed]

https://www.weglot.com/

Form the above link i can’t find any steps orinstruction to achive that.. so anyone know means please share

Weglot is a platform that offers website translation services. It allows website owners to easily translate their websites into multiple languages without having to manually translate each page. With Weglot, you can integrate translation seamlessly into your website and manage all your translations from one dashboard.

Integrating Weglot for Multi-Language Support in React Native

I have find some steps in gemini but its not working

While Weglot doesn’t have a dedicated React Native integration, you can achieve multi-language functionality using their JavaScript integration for Single Page Applications (SPAs). Here’s a detailed step-by-step guide:

  1. Weglot Setup:

a. Account and Project:

  • Head to Weglot: weglot.com and create an account.
  • Once logged in, create a new project and define the languages you want to support (e.g., English, French, Spanish).

b. Weglot JavaScript Integration:

  • In your Weglot project dashboard, navigate to the “Installation” section.
  • Choose the “JavaScript” integration option. Weglot will provide a code snippet that needs to be integrated into your React Native app.
  1. React Native App Integration:

a. Installation (Optional):

  • Consider using a library like react-native-async-storage to store the user’s preferred language locally. This can improve the user experience by remembering the chosen language across app launches.

b. Weglot Script Integration:

  • Open your app’s main entry point (usually App.js or index.js).
  • Paste the Weglot JavaScript code snippet you obtained in step 1.b within the componentDidMount lifecycle method of your main component. This ensures the script runs after the app loads.

Example Code (Replace YOUR_API_KEY with your actual key

import React, { useEffect } from 'react';
const App = () => {
  useEffect(() => {
    window.Weglot = {
      key: YOUR_API_KEY, // Replace with your Weglot API key
    };
    const script = document.createElement("script");
    script.setAttribute("src", 'https://cdn.weglot.com/weglot.min.js');
    document.body.appendChild(script);
     return () => {
      // Cleanup function (optional)
    };
  }, []);

  // ... rest of your app code
};
export default App;
  1. Handling Dynamic Content:

    Weglot might not automatically detect all translatable content in React Native apps due to their dynamic nature.
    To ensure proper translation, you need to mark dynamic content using the data-wg-id attribute.

Example:
<Text data-wg-id="welcome_message">Welcome to our app!</Text>

I need to achieve the weglot in react native

How to fade between a series of sticky divs with scroll? [closed]

I have a series of full screen divs (for example 5) stacked on top of each other in a grid. I want to be able fade them in and out in sequence as I scroll up and down on the page. I want to make it with vanilla js, no jquery and the like.

I have the five divs stacked inside a grid but I cant figure out how to make them fade in and out based on scroll. Is intersection observer the way to go?

I figured I could put my five divs inside a container that is 500vh high and calculate the opacity for each div based on some scroll position inside that, but how to code that calculation escapes me?

Extension to create a hyperlink after select a text in web page and open new browser tab

I am lookin for a solution to create a Chrome extension or if somebody know ready solution for the following.

After select a text in web page and right click to have the option to open new tab with the following logic.

I select text “Gradina” and right click to open click and open the following link in new tab

https://praktiker.bg/en/**Gradina**/c/P1305

Some example of similar extension

enter image description here

I tried similar extension but dont fit to my issue.

Json.stringify() is ignoring a object property after xlsx.sheet_to_json

so im using the SheetJs Library to read an excel file.

 const data = XLSX.utils.sheet_to_json(workbook.Sheets[sheet])

Wich returns Objects like this.

enter image description here

Ignoring the other properties.

The property rowNum is created by the sheet_to_json function and returns the Excel row Number of the Object.

I then use JSON.stringifyto create the JSON string of a single excel sheet. Wich i string concetate to a previous sheet.

this.convertedJson= this.convertedJson +JSON.stringify(data,undefined, 4);

Now the problem im encountering. After using .stringify() i get returned every single property the different rows have, except rowNum.

This is the part of the output String for the Object above.

{
        "WebShop": "AR_APPD-72642_RDS_RetailerUI_User",
        "__EMPTY": "",
        "__EMPTY_2": "AR RDS Retailer UI User (Prod)",
        "__EMPTY_3": "AR RDS Retailer UI User (Prod) ",
        "__EMPTY_4": "RtailerUI",
        "__EMPTY_5": "RtailerAI"
    }

I’ve found an older changelog of SheetJs, where ive noticed that the rowNum property was changed from enumerable to non-enumerable. Following up on that lead, apparently you cant serialize non-enumerable properties with .stringify(). Does anyone know a simple solution how i can still use .stringify() with non-enumerable properties. Or how i can change all rowNum properties of every object to enumerable?

How does the JIT compiler Maglev in chrome v8 perform?

I write some js codes in a function named f , and call the f 4 times. That’s all I did, quite simple.

After I run it with ./d8 –trace-opt, I find the f is compiled 4 times by Maglev, 2 times by Turbofan, and then 2 times by Maglev.

In the turbofan period, it shows that “Found optimize code for f….”, which means that when it try to compile f with Turbofan again, it will directly return the code compiled at the first time, just as many blogs say.

But what about the Maglev? It compiles everytime and many times, and when I try to look at the result of it with option ‘–print-maglev-code’, it prints codes which are different with each other. Some are long, some are short.

Dose it have something to do with deoptmization becasue I see 6 times deopt from Maglev code and 3 times deopt from Turbofan code with option –trace-deopt? I am quite confused, and need some help.

What I need for help:

I’d like to know, in the source code files or any blog link, where is the reason for a function to get Magleved?

Will the deoptimization from maglev code influence the later call of f , which makes it compile again and render the different compiled codes?

Why maglev doesn’t get the code it compiled before just like Turbofan? Does it have something to do with FeedbackVector?

I am a beginner in v8 and I am very willing to refer to the source code. But I can’t find the exact code and don’t know if the code I find is the right place. Thanks.

Image sorting by category

I am trying to make an image gallery that lets the user sort options by category (land, sea, animal, and more). I wrote a small example.

My goal: is that once the user selects (clicks) the category he wishes to sort by, the website will present only pictures from that specific category, while the other “unwanted” pictures will slowly disappear and move downward. Once the user changes selection, the “missing” pictures will reappear from below and go up until they reach their destination.

I did manage to make the in and out animations as well as keep the image hidden after the animation ends, but only after all relevant pictures disappear, the sorted pictures “jump” to their place instead of smoothly sliding toward their expected place.

Now I think my current problem is missing animation, but maybe I wrote something wrong in my css or my JS.

const filterContainer = document.querySelector('.data-filters');
const photoItems = document.querySelectorAll('.photo-item');

filterContainer.addEventListener('click', (event) => {
    
  filterContainer.querySelector('.active-filter').classList.remove('active-filter');
  event.target.classList.add('active-filter');
    
  const filter = event.target.getAttribute('data-filter');
  
  photoItems.forEach((item) => {
  if(item.getAttribute('data-filter') == filter || filter == 'all'){
    item.classList.remove('photo-out')
    item.classList.add('photo-in')
  } else {
    item.classList.remove('photo-in')
    item.classList.add('photo-out')
  }
  })

})
.line-list li {
  display: inline-block;
  margin: 10px;
  cursor:pointer;
}

.active-filter {
  color:blue;
}

@keyframes go-out {
  0%   {top:0px;opacity:1.0}
  100% {top:600px;opacity:0;display:none}
}

@keyframes go-in {
  100%   {top:0px;opacity:1.0}
  0% {top:600px;opacity:0;display:block}
}

.photo-out {
  animation: go-out 1.2s forwards;
}

.photo-in {
  animation: go-in 1.2s forwards;
}
<html>
  <head>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  </head>
  <body>
  <section id='photo_wall'>
    <div class='container'>
      <div class='row'>
        <div class='col-md-12 data-filters'>
          <ul class='line-list'>
            <li class='active-filter' data-filter='all'> All photos </li>
            <li data-filter='land'> Land </li> 
            <li data-filter='sea'> Sea </li> 
            <li data-filter='animals'> Animals </li> 
          </ul>
        </div>
      </div>
      <div class='row'>
        <div class='col-md-3 photo-item p-4 photo-in' data-filter='land'>
          <img src='https://fastly.picsum.photos/id/807/200/200.jpg?hmac=Y8gayvNItiQYxP_Pd-2un9GH09XuyJdIZOQPw6K9QsI'>
        </div>
        <div class='col-md-3 col-sm-6 photo-item p-4 photo-in' data-filter='animals'>
          <img src='https://fastly.picsum.photos/id/659/200/200.jpg?hmac=kFpdD3XTBGwPUAH1tD-AiWigstjIX8WGIcyySuVQIvE' class='animals'>
        </div>
         <div class='col-md-3 col-sm-6 photo-item p-4 photo-in' data-filter='land'>
          <img src='https://fastly.picsum.photos/id/165/200/200.jpg?hmac=tQGrY9pm5ze9soSsZ5CNBt87zqnHfFwdPv_khau12Sw' class='land'>
        </div>
        <div class='col-md-3 photo-item p-4 photo-in' data-filter='sea'>
            <img src='https://fastly.picsum.photos/id/883/200/200.jpg?hmac=evNCTcW3jHI_xOnAn7LKuFH_YkA8r6WdQovmsyoM1IY' class='sea'>
           </div>
          <div class='col-md-3 photo-item p-4 photo-in' data-filter='animals'>
            <img src='https://fastly.picsum.photos/id/237/200/200.jpg?hmac=zHUGikXUDyLCCmvyww1izLK3R3k8oRYBRiTizZEdyfI' class='animals'>
            </div>
          <div class='col-md-3 photo-item p-4 photo-in' data-filter='sea'>
            <img src='https://fastly.picsum.photos/id/653/200/200.jpg?hmac=tZtho3csFdJ2rLHTTlT7WhXtDwbXgJNIIUvOQQb2dIo' class='sea'>
            </div>
      </div>
    </div>
  </section>
  </body>
</html>

Showing icon on results after selection

Am having a script below which is working and outputting results very well.

but my problem is that i wanted to change and output results with icon

i changed from

$("#results").text(firstname + " " + lastname);

to

$("#results").html("<i class='fa fa-user-circle-o'></i>" firstname + " " + lastname);

but its not working

<!DOCTYPE html>
<html>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<body>



  <select id="fname">
   <option value="">Select Firstname</option>
    <option value="jone">jone</option>
  </select>
  
    <select id="lname">
    <option value="">Select Lastname</option>
    <option value="micheal">micheal</option>
  </select>

 <br>
 <br>
 <p>My fullname is:</p>
 <div id="results"></div>
<script>
            $("select").on("change", function (e) {
                var firstname = $("#fname").children("option:selected").val();
                var lastname = $("#lname").children("option:selected").val();
                $("#results").text(firstname + " " + lastname);
            });
            
            </script>

</body>
</html>

R : Re-binding the SelectInput of a DataTable after being updated

So I am currently trying to create a Shiny App that would allow the user to chose the category associated with an entry, change it, and this change being directly written into the corresponding database. For that I used both RMySQL and DT libraries to configure Select Inputs displayed on each row with all the categories to chose from, as well as an “Update Data” button to confirm the changes and execute the SQL queries to write them into the database.

However, the app seems to work only the first time that the “Update Data” button is used after launching the app. From what I noticed, it seems to be related to the Select Input ids : they are first defined when the DataTable is initialized (with “single_input6” being associated with the row “ID : 6” for exemple), and are then recreated the same way when the DataTable is updated after the “Update Data” button has been clicked. However, the value associated with those inputs stay the same as the ones that were selected when the “Update Data” button was clicked the first time.

It could be that the ids are still binded to their initial values, or that the initial DataTable wasn’t replaced by the new one and so still exist. I don’t know however what exactly causes the issue or how to fix it.

Below are the images showing how the App works (1., 2.), where it doesn’t (3.) and what makes me think the ids are not correctly binded (4.) :

1. The App the first time it is launch
1. The App the first time it is launch](https://i.stack.imgur.com/I3DoH.png)

2. The App after selecting "Egyptien" for the row ID : 6 and cliking on "Update Data"
2. The App after selecting “Egyptien” for the row ID : 6 and cliking on “Update Data”

3. The App after then selecting "Grec" for the row ID : 6 and cliking on "Update Data" (nothing has changed)
3. The App after then selecting “Grec” for the row ID : 6 and cliking on “Update Data” (nothing has changed)

4. The console prints used for debug. The first "Egyptien" was displayed during the 2. image update, the second "Egyptien" was displayed during the 3. image update

4. The console prints used for debug. The first “Egyptien” was displayed during the 2. image update, the second “Egyptien” was displayed during the 3. image update


Here is the SQL queries to create the MySQL dummy database used as an exemple :

### Initialize the two MySQL Databases used in the code
# The Databases are not important in themselves but are handy to test and tinker what I need

CREATE TABLE Z_TEST (ID INT PRIMARY KEY NOT NULL, Divinite VARCHAR(20), ID_pantheon INT);
CREATE TABLE Z_TEST2 (id_pantheon INT PRIMARY KEY NOT NULL, nom_pantheon VARCHAR(20));

INSERT INTO Z_TEST VALUES 
(1, "Quetzalcoatl", 5), 
(2, "Odin", 3), 
(3, "Ra", 2),
(4, "Zeus", 1),
(5, "Tiamat", 4),
(6, "Isis", 0),
(7, "Hades", 0),
(8, "Thot", 0),
(9, "Thor", 0),
(10, "Persephone", 0),
(11, "Amatsu", 0);

INSERT INTO Z_TEST2 VALUES 
(1, "Grec"), 
(2, "Egyptien"), 
(3, "Nordique"),
(4, "Sumerien"),
(5, "Azteque"),
(6, "Japonais");


### Display each Database and their join

SELECT * FROM Z_TEST;
SELECT * FROM Z_TEST2;

SELECT ID, Divinite, Z_TEST.ID_pantheon, nom_pantheon FROM Z_TEST LEFT JOIN Z_TEST2 ON Z_TEST.ID_pantheon = Z_TEST2.id_pantheon;

Here is the R code used for the Shiny App :

### Libraries

{
  library(shiny)            # used to create the Shiny App
  library(bslib)            # used to create the Shiny App
  
  library(RMySQL)           # used to access the Database
  library(lares)            # used to import logins for the Database
  
  library(tidyverse)        # used for many things (mainly data manipulation)
  library(DT)               # used for creating interactive DataTable
  # library(DTedit)           # used for better editing of DataTable (judged not enought intuitive for the user)
}


### JS Module for keyboard shortcut (Not Important)
# Allows the use of arrow keys to move from cell to celle and the Enter key to confirm an edit

js <- c(
  "table.on('key', function(e, datatable, key, cell, originalEvent){",
  "  var targetName = originalEvent.target.localName;",
  "  if(key == 13 && targetName == 'body'){",
  "    $(cell.node()).trigger('dblclick.dt');",
  "  }",
  "});",
  "table.on('keydown', function(e){",
  "  var keys = [9,13,37,38,39,40];",
  "  if(e.target.localName == 'input' && keys.indexOf(e.keyCode) > -1){",
  "    $(e.target).trigger('blur');",
  "  }",
  "});",
  "table.on('key-focus', function(e, datatable, cell, originalEvent){",
  "  var targetName = originalEvent.target.localName;",
  "  var type = originalEvent.type;",
  "  if(type == 'keydown' && targetName == 'input'){",
  "    if([9,37,38,39,40].indexOf(originalEvent.keyCode) > -1){",
  "      $(cell.node()).trigger('dblclick.dt');",
  "    }",
  "  }",
  "});"
)


### Queries (Not Important)

QDisplay <- "
  SELECT ID, Divinite, Z_TEST.ID_pantheon, nom_pantheon 
  FROM Z_TEST LEFT JOIN Z_TEST2 ON Z_TEST.ID_pantheon = Z_TEST2.id_pantheon
"

QEdit <- "
  UPDATE Z_TEST
  SET %s = '%s'
  WHERE ID = %d
"

QRef <- "
  SELECT nom_pantheon FROM Z_TEST2
"

### --- YOU MUST EDIT THE FOLLOWING PART BEFORE RUNNING THE CODE --- ###

### Database Connection (Important)

# Connect to a MySQL Database using appropriate credentials, then close the connection
# IMPORTANT : Requires a config.yml file to be setup with corresponding credentials if you want to use the get_creds function as is
# Otherwise, you can simply replace the get_creds("cirrina_as")$[...] by putting the plain-text credentials in their place

mydbGetQuery <- function(Query) {
  
  DB <- dbConnect (
    MySQL(),
    dbname = get_creds("dummy_db")$dbname,
    host = get_creds("dummy_db")$host,
    user = get_creds("dummy_db")$user,
    password = get_creds("dummy_db")$password
  )
  data <- dbGetQuery(DB, Query)
  dbDisconnect(DB)
  
  return(data)
}


### Automatic generation of row Select Input (somewhat Important)

# Create levels to choose from in the Select Input
factorOptions <- function(select_factors) {
  a <- ""
  for (i in select_factors) {
    a <- paste0(a, '<option value="', i, '">', i, '</option>n')}
  
  return(a)
}

# Create the Select Input with ID and corresponding entry from the joined table
mySelectInput <- function(selected_factor, select_factors) {
  b <- c()
  
  for (j in 1:length(selected_factor)) {
    b <- c(b, paste0('<select id="single_select', j, '"style="width: 100%;">n', 
                     sprintf('<option value="%s" selected>%s</option>n', selected_factor[j], selected_factor[j]), 
                     factorOptions(select_factors), '</select>'))
  }
  return(b)
}

# Get the reference levels for the Select Input 
panth_level <- mydbGetQuery(QRef) %>% as_tibble() %>% pull(nom_pantheon)


### Shiny App (Important)

shinyApp(
  ui = fluidPage(
    DTOutput('interactiveTable'),
    actionButton("updateButton", "Update Data")
  ),
  
  server = function(input, output, session) {
    
    # Fetch the underlying data
    panth_data <- reactiveVal()
    observe(panth_data(mydbGetQuery(QDisplay) %>% as_tibble()))
    
    # Initialize the DataTable
    output$interactiveTable <- renderDT({
      datatable(data = bind_cols(panth_data(), tibble(Test = mySelectInput(panth_data()$nom_pantheon, panth_level))), 
                selection = 'none', escape = FALSE, rownames = FALSE, editable = list(target = 'cell', disable = list(columns = c(0, 2))),
                callback = JS(js), extensions = "KeyTable", 
                options = list(
                  keys = TRUE,
                  preDrawCallback = JS('function(){Shiny.unbindAll(this.api().table().node());}'),
                  drawCallback = JS('function(){Shiny.bindAll(this.api().table().node());}')
                )
      )
    })
    
    # If the button is clicked, apply the changes made with the Select Input directly to the database
    # Note : for now, only the sixth row (ID : 6, Divinite : Isis) is made responsive to any change done with selectors
    # Changing the "6" of "single_select6" and "sprintf(QEdit, "ID_pantheon", i, 6)" for another number will make another entry
    # responsive instead
    
    observeEvent(input$updateButton, {
      # for debug
      print(input$single_select6)
      
      # Fetch the corresponding ID of the selected pantheon and update the database
      i <- mydbGetQuery(sprintf("SELECT id_pantheon FROM Z_TEST2 WHERE nom_pantheon = '%s'", as.character(input$single_select6)))$id_pantheon
      mydbGetQuery(sprintf(QEdit, "ID_pantheon", i, 6))
      
      # Update the Datable
      output$interactiveTable <- renderDT({
        updated_data <- mydbGetQuery(QDisplay) %>% as_tibble()
        datatable(data = bind_cols(updated_data, tibble(Test = mySelectInput(updated_data$nom_pantheon, panth_level))),
                  selection = 'none', escape = FALSE, rownames = FALSE, editable = list(target = 'cell', disable = list(columns = c(0, 2))),
                  callback = JS(js), extensions = "KeyTable", options = list(
                    keys = TRUE,
                    preDrawCallback = JS('function(){Shiny.unbindAll(this.api().table().node());}'),
                    drawCallback = JS('function(){Shiny.bindAll(this.api().table().node());}'))
        )
      })
    })
    
    
    ### Attempt to edit the Data everytime the input is modified rather than waiting for a Button input
    
    # observeEvent(input$single_select6, {
    #   print(input$single_select6)
    #   
    #   i <- mydbGetQuery(sprintf("SELECT id_pantheon FROM Z_TEST2 WHERE nom_pantheon = '%s'", as.character(input$single_select6)))$id_pantheon
    #   mydbGetQuery(sprintf(QEdit, "ID_pantheon", i,
    #                        # d6()[input$x6_cell_edit$row,]$ID
    #                        6
    #   ))
    #   
    #   output$x6 <- renderDT({
    #     updated_data <- mydbGetQuery(QDisplay) %>% as_tibble()
    #     datatable(data = bind_cols(updated_data, tibble(Test = test2(updated_data$nom_pantheon, d))),
    #               selection = 'none', escape = FALSE, rownames = FALSE, editable = list(target = 'cell', disable = list(columns = c(0, 2))),
    #               callback = JS(js), extensions = "KeyTable", options = list(keys = TRUE))
    #   })
    #   
    #   reset("single_select6")
    # })
  }
)

Important Notes :

  • The SQL dummy database must first be created for the code to work properly as is
  • You must edit the “mydbGetQuery” function by replacing the credentials inside with either the one associated with your MySQL database in your config.yml file (if you intend to use lares) or directly with the plain-text credentials (simplest option)
  • Only the row ID : 6, Divinite : Isis can be updated by changing the Select Input Value and then clicking on “Update Data”. This is by design as to debug a single row first.
  • Closing and launching the App again will make the first new update work, before returning the same result again

Web-scraping: GET request returns a string – how can I read/process it in R?

I’m sending a GET request to an governmental page in India with the following URL:
https://pmfby.gov.in/landingPage/districtState?stateID=2F3DE245-46E6-4C4D-9297-C0B23C803B15&sssyID=02012223

What this basically does on their webpage (https://pmfby.gov.in/ -> “Insurance Premium Calculator”) is returning all districts for a specific state selected (with JavaScript).

I used the following R code to reproduce this:

content(httr::GET("https://pmfby.gov.in/landingPage/districtState?stateID=2F3DE245-46E6-4C4D-9297-C0B23C803B15&sssyID=02012223"))

I somehow expected to get a HTML or JSON structured return with a list of those districts. What I actually get back however is a string that starts with “09f2ba53495a95c8d6189182d996252553a088b548d4f3c7caf1e195ff….”.

I don’t even know what format this is and I’m unable to convert/process this is R.
Is there any solution to my problem?

javascript having problem in handling codes from html [closed]

There’s this code that can be applicable to html since it is from server side.

but in script, it cannot.

this is the code at html where the code works:

<span id="lang">#(main.language.toUpperCase())</span>

and this is the code in script that doesn’t work:

$('#lang').html(`<span>${main.language.toUpperCase}</span>`);

What do you think is the issue in js code?

Optional capturing in any order for values only

I have the following group of text:

name:   something
type:   another value
color:  red

I need to capture only the values to the right, in any order. Keeping in mind that any of the values above may be missing in other instances, or in a different order, such as:

color:  red
type:   value

On top of that, it being able to ignore quotation marks " and ' in case the values are wrapped in them, and ignoring the spaces between the proper and value. Which means that it would be able to still pull the values from the below example:

color:  "red"
type:   'value'
name:             'something'

Here is the JavaScript regex I’ve tried to pull together:

(?=[^`]*?name:? +(?<name>[^`n]*))(?=[^`]*?value:? +(?<value>[^`n]*))(?=[^`]*?color:? +(?<color>[^`n]*))(?=[^`]*?file:? +(?<file>[^`n]*))(?=[^`]*?type:? +(?<type>[^`n]*))

Regex101

The issue at the moment is:

  1. All values are required, if I remove any from the list, none of them capture. I’ve attempted adding optional ? syntax, but I can’t seem to place it in the right spot.
  2. The quotations are being captured with the value.

I have looked at examples online which mention using a ? between each group, but that results in the regex101 error: ? The preceding token is not quantifiable

Django-React not staying logged in

I have a React JS – Django site and I implemented the login functionality. But I have seen that the user does not stay logged in even though it authenticates and moves to the home page after log in. I tried displaying the username once it navigates to the home page and it returns empty.

Views.py

class Login(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')

        # Authenticate user
        user = authenticate(request, username=username, password=password)

        if user is not None:
            # If authentication succeeds, log in the user
            login(request, user)
            return JsonResponse({"message": "Login successful"})
        else:
            # If authentication fails, return error response
            return JsonResponse({"error": "Invalid username or password"}, status=status.HTTP_400_BAD_REQUEST)

Login.js

const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      const response = await fetch("http://localhost:8000/login/", {
        method: 'POST',
        withCredentials: true,
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
      });
      
      const data = await response.json();

      if (response.ok && data.message === "Login successful") {
        // Redirect to the home page upon successful login
        navigate('/');
      } else {
        // Set error state with the error message
        setError(data.error);
      }
    } catch (error) {
      // Handle network or server errors
      setError("An error occurred during login. Please try again later.");
    }

I have the necessary session middleware in my settings.py as well.

I tried adding middleware to settings.py and session cookie age but it didnt work either