Tornado websocket connection working with python client but fails with javascript client code

In my project I have following websocket handler using tornado websockets:

class EchoWebSocket(tornado.websocket.WebSocketHandler):
def open(self):
    print("WebSocket opened")

def on_message(self, message):
    self.write_message(u"You said: " + message)
    # self.stream_logs()

def on_close(self):
    print("WebSocket closed")

I could connect to this websocket from an python client side code given here:

    import asyncio
    import websockets

    async def connect_to_websocket(uri):
        async with websockets.connect(uri) as websocket:
            await websocket.send("kdkdkd")
            while True:
                # Receive message from the WebSocket server
                message = await websocket.recv()
                print(f"Received message: {message}")
    
             
    
    async def main():
        uri = "ws://localhost:8889/myextension/echows"  # WebSocket server URI
        await connect_to_websocket(uri)

    if __name__ == "__main__":
        asyncio.create_task(main())

but when I try to connect it using javascript based client code it throws error VM449:3 WebSocket connection to ‘ws://localhost:8889/myextension/echows/’ failed javscript client code goes as:

async function connectToWebSocket(uri) {
      try {
        const connection = await new WebSocket(uri);

connection.onmessage = (event) => {
  console.log(`Received message: ${event.data}`);
};

connection.onerror = (error) => {
  console.error('WebSocket error:', error);
};

await connection.send("kdkdkd");

while (connection.readyState === WebSocket.OPEN) {
  // Receive messages and handle them appropriately (e.g., print or process)
  const message = await connection.receive();
  console.log(`Received message: ${message}`);
}
      } catch (error) {
console.error('Connection error:', error);
      }
    }

    const uri = "ws://localhost:8889/myextension/echows/"; 

    connectToWebSocket(uri);

I cannot figure out what am I doing wrong in js code although everything working while connecting using python.

Data Not Saving in Mongodb (PopUp Image)

I am currently facing one issue as you see in the below code there are 4 img options but one image comes under the popup(img2) so all three images are saved successfully in the MongoDB except the img2(which comes from the popup)

 <div className="mt-10 grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6">
            <div className="sm:col-span-3">
              <label
                htmlFor="img1"
                className="block text-sm font-medium leading-6 text-gray-900 font-bold"
              >
                Image1* (Thumbnail)
              </label>
              <div className="mt-2">
                <div className="flex rounded-md shadow-sm ring-1 ring-inset ring-gray-300 focus-within:ring-2 focus-within:ring-inset focus-within:ring-orange-600 ">
                  <input
                    type="file"
                    {...register("img1", {
                      required: "name is required",
                    })}
                    id="img1"
                    className="block flex-1 border-0 bg-transparent p-2 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
                    accept="image/*"
                    onChange={(e) => handleImageChange(e, 1)}
                  />
                </div>
              </div>
            </div>
            <div className="relative">
      <button
        className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
        onClick={openPopup}
      >
        Open Popup
      </button>

      {isPopupOpen && (
        
        <div className="fixed inset-0 z-50 flex items-center justify-center overflow-auto bg-gray-800 bg-opacity-75">
          <div className="bg-white rounded-lg p-8">
          <label
                htmlFor="img2"
                className="block text-sm font-medium leading-6 text-gray-900 font-bold"
              >
                Image2*
              </label>
            <h2 className="text-xl font-semibold mb-4">Upload Image</h2>
            <input
              type="file"
              {...register('img2', {
                required: 'name is required',
              })}
              id="img2"
              className="block w-full border-gray-400 p-2 rounded"
              accept="image/*"
              onChange={(e) => handleImageChange(e, 2)}
              // value={setImages}
            />
            <button
              className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
              onClick={closePopup}
            >
              Close
            </button>
          </div>
        </div>
      )}
    </div>
            {/* <div className="sm:col-span-3">
              <label
                htmlFor="img2"
                className="block text-sm font-medium leading-6 text-gray-900 font-bold"
              >
                Image2*
              </label>
              <div className="mt-2">
                <div className="flex rounded-md shadow-sm ring-1 ring-inset ring-gray-300 focus-within:ring-2 focus-within:ring-inset focus-within:ring-orange-600 ">
                  <input
                    type="file"
                    {...register('img2', {
                      required: 'name is required',
                    })}
                    id="img2"
                    className="block flex-1 border-0 bg-transparent p-2 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
                    accept="image/*"
                    onChange={(e) => handleImageChange(e, 2)}
                  />
                // </div>
              </div>
            </div> */}
          </div>
          <div className="mt-10 grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6">
            <div className="sm:col-span-3">
              <label
                htmlFor="img3"
                className="block text-sm font-medium leading-6 text-gray-900 font-bold"
              >
                Image3*
              </label>
              <div className="mt-2">
                <div className="flex rounded-md shadow-sm ring-1 ring-inset ring-gray-300 focus-within:ring-2 focus-within:ring-inset focus-within:ring-orange-600 ">
                  <input
                    type="file"
                    {...register("img3", {
                      required: "name is required",
                    })}
                    id="img3"
                    className="block flex-1 border-0 bg-transparent p-2 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
                    accept="image/*"
                    onChange={(e) => handleImageChange(e, 3)}
                  />
                </div>
              </div>
            </div>
            <div className="sm:col-span-3">
              <label
                htmlFor="img4"
                className="block text-sm font-medium leading-6 text-gray-900 font-bold"
              >
                Image4*
              </label>
              <div className="mt-2">
                <div className="flex rounded-md shadow-sm ring-1 ring-inset ring-gray-300 focus-within:ring-2 focus-within:ring-inset focus-within:ring-orange-600 ">
                  <input
                    type="file"
                    {...register("img4", {
                      required: "name is required",
                    })}
                    id="img4"
                    className="block flex-1 border-0 bg-transparent p-2 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6"
                    accept="image/*"
                    onChange={(e) => handleImageChange(e, 4)}
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
const handleImageChange = (e, index) => {
  const file = e.target.files[0];
  console.log(file);
  if (file) {
    const imageUrl = URL.createObjectURL(file);
    console.log("imageUrl", imageUrl);
    setImages(`img${index}`, imageUrl);
  }
};

const openPopup = () => {
  setIsPopupOpen(true);
};

const closePopup = () => {
  setIsPopupOpen(false);
};


   // Add images to FormData
        for (let i = 1; i <= 4; i++) {
        
          const fileInput = document.getElementById(`img${i}`);
          const file = fileInput?.files[0];
          if (file) {
            formData.append(`image`, file);
          }
        }

payload after submit the from in this only 3 images is going to save but there is 4 images option

    image: (binary)
title: mssanxasndj
patternNumber: asnjasndjsand
room: Living Room
designStyle: sasd
category: Flooring
demandtype: Best Seller
subCategory: Carpet Tiles
collection: asdasdsad
color: Oak Brown,Cherry Blossom,Teak
units: 10
unitType: sqft
totalPricePerUnit: 12
discountedprice: 8
perUnitType: sqft
specialprice: 
perUnitPrice: 9
dimensions[length][value]: 12
dimensions[length][unit]: mm
dimensions[width][value]: 1
dimensions[width][unit]: mm
dimensions[thickness][value]: 1
dimensions[thickness][unit]: mm
image: (binary)
image: (binary)
image: (binary)
purchaseMode: Only Online,In-store request Only
otherRoom: 
productDescription: asd
coreValues[0][heading]: 
coreValues[0][text]: 
features[0][feature]: 
maintainanceDetails: asdasd

there is one add product add page in which i have to choose 4 images which going to save at MongoDB so as of now 3 images successfully saved at MongoDB but when i comes to img2 (popup) that image is not getting saved in mongo db

how can i resolve this issue ?

NextJS – How to set cookie in route handler, such that the cookie can be sent to a separate server

My Post yesterday: NextJS – How to Set Cookie in route handler when having a separate backend

I solved it by adding

  cookies().set("accessToken", loginRes.data.accessToken, {
    httpOnly: true,
    maxAge: 24 * 60 * 60,
  });

/app/api/auth/google-login

...

export async function POST(request: NextRequest) {
  const { token } = await request.json();
  const loginRes: AxiosResponse<User> = await axios.post(
    "http://backend:3001/auth/google-login",
    {
      token: token,
    }
  );

  cookies().set("accessToken", loginRes.data.accessToken, {
    httpOnly: true,
    maxAge: 24 * 60 * 60,
  });
  
  return NextResponse.json(loginRes.data, { status: 201 });
}

Problem
Now I am trying to create a route handler for logout.
/app/api/auth/logout

...
export async function POST(request: NextRequest) {
  const cookieStore = cookies();
  // send a logout request to my NestJS server, which is gonna invalidate related stuff
  await axios.post(
    "http://backend:3001/auth/logout",
    {},
    {
      withCredentials: true,
    }
  );
  // Delete the cookie from the browser
  cookies().delete("accessToken");

  return NextResponse.json({ status: 201 });
}

The problem is, my NestJS backend validate users by checking the cookie accessToken from incoming request. Right now there is no cookie sent from the route handler to NestJS backend.
My question is, how to set cookie is this route handler before sending the logout request to my NestJS backend?

Javascript: Input value on fields and show value on popup

I have a registration form. After filling up the forms, the reference number will display in popup. A reminder for the user to use for logging in the system.

register.html

<div>Reference No.<input type="text" name="refno" value="{{ refno }}" readonly></div>
<div>Name<input type="text" name="name"></div>
...
<button type="submit" id="getInputValue()" class="btn">Submit</button>

this is my script

function getInputValue() {
  let textElement = document.getElementById('refno').value;
  alert(textElement);

views.py

if request.method == 'GET':
    random_chars = ''.join(random.choices(string.ascii_uppercase + string.digits, k=8))
    refno = f"{random_chars}"
    return render(request, 'registration_form.html', {"refno": refno})
if request.method == 'POST':
    refno = request.POST.get('refno')
    name = request.POST.get('name')
    ...
    Applicant.objects.create(refno=refno, name=name, ...)
    return redirect(/user_login/)

So after the button was clicked, the msg should display the reference number before it proceed to the login form. So I’m a bit confused on how to show the popup first before login. If I write return render(request, 'registration_form.html'), it will just return to the form. With this code I have, it doesn’t even show a pop up. Thank you in advance.

is there a way to render rtf string to html?

sorry for my poor english in advance.

what i wanna do is, to retrieve a raw text data of rich text that has sjis data in it from the DB, then somehow render the rich text in website i created.

what i mean by raw text data of rich text is String data of something like following:

{rtf1ansideff0nouicompat{fonttbl{f0fnilfcharset128 '82'6c'82'72 '96'be'92'a9;}}
{colortbl ;red255green0blue0;red255green255blue0;red0green77blue187;}
{*generator Riched20 10.0.19041}viewkind4uc1 
pardsa200sl276slmult1cf1bf0fs22lang1041'82'a0'82'a2'82'a4'82'a6'82'a8cf0b0par

pardsa200sl276slmult1qccf2i'82'a9'82'ab'82'ad'82'af'82'b1cf0i0par

pardsa200sl276slmult1qrcf3ul'82'b3'82'b5'82'b7'82'b9'82'bbcf0par

pardsa200sl276slmult1ulnonestrike'82'bd'82'bf'82'c2'82'c4'82'c6par
strike0lang17par
}

i tried apache TIKA. but what it can do is decode text data in readable string. that can’t reproduce font-color, style, family, alignment.

i tried converting rich text into html using JEditorPane. this can reproduce font color and style, but can’t reproduce alignment and resulting in garbled characters. containing text data is SJIS but decoded as UTF8. i can’t find the way to force JEditorPane to use specific character code.

i tried a jquery plugin that allows you to create rich text editor on your website. but it can’t use the raw text data of rich text as its input data.

is there any way to render rich text in website by using server side java or client side javascript?

Show selected item in search field

On my website (written in React) I create a search field (using HTML tag input).
At the moment I have:

  1. The user clicks on the field;
  2. Enter one character;
  3. Options that are in the database appear under the field

But at the moment the user cannot click on one of the proposed options. Therefore, what I would like to add:

  1. The user clicks on one of the proposed options

  2. The selected option is displayed in the input field, where the user entered the characters to search

    const mockData = [
    {
     id: 1,
     name: 'qwert',
    },
    {
     id: 2,
     name: 'ertyu',
    },
    ];
    

Component with field

export function Search() {
 const [query, setQuery] = useState('');
 return (

   <div>
     <SearchIcon />

     <Form.Label htmlFor="title">
       Event
       <Form.Input
         placeholder="Search"
         onChange={(event) => setQuery(event.target.value)}
         value={query}
       />
     </Form.Label>
     {mockData.length &&
       mockData
         .filter((title) => {
           if (query === '') {
             return '';
           }
           if (title.name.toLowerCase().includes(query.toLowerCase())) {
             return title;
           }
         })
         .map((title) => (
           <div className="card" key={title.id}>
             <h3>{title.name}</h3>
           </div>
         ))}
   </div>
)}

i want to preview whatapp flow preview url into my website like sidebar

i have created the whatsapp flow now when i click ‘preview’ button i need to call that meta preview url and show into my website like sidebar. i want to show only that widget it seems. But when i click it will show like new window. how can i achieve this. For reference i will share my url.

https://business.facebook.com/wa/manage/flows/307666118961640/preview/?token=e23e60d9-e89e-4250-af7d-46109d5ed8fd

Here only what inside widget i need to show in my website like sidebar

jQuery change() Function – Differences

Which is the difference between:

jQuery(selector).change(function(){
//something
}).change();   

And this:

jQuery(selector).change (function(){
//define your code here to execute once the change event is happened.
});

Thanks in advance!

I could not find an explanation about difference between those methods, that is why I ask here.

Speech synthesis availability

I created an announcer web app that announces the texts that are being read. It works well on my computer’s browser(Chrome and Firefox) and also on my phone’s browser. When I accessed it on our smart tv, it runs but it doesn’t make a sound when I click the button. The tv’s browser is chrome and I have a code that checks if the speechsynthesis is available to a browser, it displays that it is available but the sound is not playing. What should I do?

I tried it on different pc and mobile phones, it works, except for the smart tv

About ‘Failed to load resource: the server responded with a status of 404 ()’

I’m making board with spring framework and I have a issue.

I want to send Parameter ‘Id’ to Controller with Ajax but this errors is occurred

enter image description here

                var xhr = new XMLHttpRequest();
            var url = "${contextPath}/checkId?id=" + input_id.value;
            xhr.open("GET", url, true);
            xhr.onreadystatechange = function() {
              if (xhr.readyState == 4 && xhr.status == 200) {
                //var checkId = "${checkID}";
                
                var checkId = xhr.responseText;
                
                console.log("success");
                
                if(checkId === "" || checkId === undefined){
                    form_action.submit();
                    alert("Welcome!");
                    window.close();
                }
                else {
                    alert("ID exists");
                } 
                
                console.log(xhr.responseText);
              }
            };
            xhr.send();

And Controller is

    @Override
    @RequestMapping(value="/checkId", method = RequestMethod.GET)
    public String checkId(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String id = request.getParameter("id");
        
        String isIdExists = memberService.checkId(id); 
        //String isIdExistSts = String.valueOf(isIdExists); 
        System.out.println(isIdExists);
        request.setAttribute("checkID", isIdExists);
        //return "forward:/signUp";
        return "/signUp";
    }

What is problem? could you help?

Integer enum values is valid but not string enum value

I was learning Enums in typescript and came across this issue.
Let me know if anyone can help me understand it.

enum Type {
  UPPER = 1,
  LOWER,
  CAMEL = "camelcase",
}
let myType: Type;
myType = 1; --- this is valid
myType = "camelcase" --- this is not

Do you help me understand why this does not work?

I tried checking various resources and documentation but somehow I did not find the proper explanation to it. I even talked to AI assitent but it also did not helped.

Gauge JS remove margin

I am using gauge js in my code to show gauge graph on tv dashboards but the graph is showing extraspace in right and left side. Tried switching options but no use.
enter image description here
<div class="box-tile statitics m-w-324"> <canvas style="height: 200px;width: 400px;" id="efficiencyGauge"></canvas> <span class="label">EFF. <span class="value"><span id="efficiency" class="loading">...</span></span></span> </div>
var dhuGaugeOpts = { angle: -0.10, lineWidth: 0.2, radiusScale: 0.9, pointer: { length: 0.5, strokeWidth: 0.05, color: '#fff' }, staticLabels: { font: "10px sans-serif", color: '#fff', labels: [2, 5], fractionDigits: 0 }, staticZones: [ { strokeStyle: "#30B32D", min: 0, max: 2 }, { strokeStyle: "#FFDD00", min: 2, max: 5 }, { strokeStyle: "#F44336", min: 5, max: 10 }, ], limitMax: false, limitMin: false, highDpiSupport: true, plotBackgroundColor: null, plotBackgroundImage: null, plotBorderWidth: 0, plotShadow: false, margin: [0, 0, 0, 0], // Adjust margins to remove whitespace spacing: [0, 0, 0, 0] // Adjust spacing to remove whitespace }; dhuGauge = new Gauge(document.getElementById('dhuGauge')).setOptions(dhuGaugeOpts); dhuGauge.maxValue = 10; dhuGauge.setMinValue(0);

I tried different properties but no use. I am using library gauge.js
Is there any specific property for this. cause of using this on tv I can’t change the library since all tv browser doesn’t support new libraries

Svelte if-else connecting transitions

I have a page that has several stages, and I want to add transitions between them.

{#if state === 1}
 <div class="red" transition:fade/>
{:else if state === 2}
 <div class="blue" transition:fade/>
{:else if state === 3}
 <div class="green" transition:fade/>
{/if}

However, when switching from one state to the next, the next one appears at the same time as the previous one is still disappearing, so the two states would appear at the same time for the duration of the transition.

What is the best approach (the approach that requires adding the least amount of code) to make one state’s fade in connect with another state’s fade out?

Here is a code sandbox link: https://codesandbox.io/p/sandbox/priceless-pine-kgrh7w

How to extend div (smoothly) only when pressing specific button

First of all I’m a near-total beginner so please be kind TT

I’m tinkering around with developing a login/registration form for a project due kinda soon — basically just lacking more of the advanced functions (entry validation, etc. etc.), but I’ve been struggling with how to reduce and extend the div container of my form whenever the Log In and Register buttons are pressed, respectively. I have the reduction-extension concept down (thanks to another stackoverflow question, actually! You guys are helpful), but it activates whenever the div container itself — and not the buttons — is clicked. Can’t figure out how to rearrange things such that just clicking anywhere will NOT make it go off.

Attached is the code below in jsfiddle.

https://jsfiddle.net/Phiso/jes62m0d/

<div class="form-container" id="form-container">
.form-container {
    width: 380px;
    height: 305px;
    position: relative;
    margin: 6% auto;
    background: #fff;
    padding: 5px;
    overflow: hidden;
}

#form-container {
    transition: height 300ms;
}

#form-container.is-active {
    height: 370px;
}
window.onload=function(){
    document.getElementById("form-container").addEventListener("click", function() {
        this.classList.toggle("is-active");
    });
  }

Also, if extra code is needed (which it probably is), would prefer pure javascript if possible.

Thanks a bunch!

Specifically, I’ve tried moving around the ids and editing the toggle, but of course no dice – most I managed to get work were the buttons themselves extending.