Disadvantage of using insertAdjacentHTML to make HTML Component

Assuming system has following codes in each index.html and module.js,

index.html
...
<body>
    <div id="background">
    </div>
</body>

<script src="./module.js">
    builder("background", "title" , "Hello");
    builder("title", "text", "World");
</script>


module.js
function builder(ItemID, ChildID, Content) {
    var Object = document.getElementById(ItemID);
    Object.insertAdjacentHTML("beforeend", `
        <div id="` + ChildID + `">
            ` + Content + `
        </div>
    `);
}

it will return

<div id="background">
   <div id="title">
      Hello
      <div id="text">
         World
      </div>
   </div>
</div>

Hereby, I am curious that is there any disadvantages of using only insertAdjacentHTML without any help of frameworks to build a page.

(Looks like insertAdjacentHTML is much faster then innerHTML or innerText thus I think there shouldn’t be any problem, but questioning just because of curiousity)

What to do when npm install fails to find one dependency, but you can download it normally?

So I am trying to run a javascript file that comes with a package.json file. When I run npm install in the folder, it fails because it doesn’t find one of the dependencies.

I can then remove this dependency from the package.json file, and download it manually from the location provided and put it in a different folder. The npm install will then complete.

I can also run “npm install” on the downloaded dependency folders to have all of its dependencies.

Problem is, now I end up with 2 folders, with many different scripts in each folder, and two package.json files.

What is the proper way to handle this scenario?

Can I somehow point the original package.json my local hardrive, or where I found the file on the internet?

Compress the table

I have two tables, but here only half of the table is visible which is overlapped by another table
So, I want to compress the table to make both table visible.

I’ve tried css,html,js to compress, doesn’t work out.

Can anyone suggest on this
Thanks in advance.

Output
Expected Output

how to use firebase authentication with multiple login methods and role based authentication?

i’m creating a react.js app as nodejs as backend, i want to use these authentication methods login with email/password, login with google and login with phone, now i want to keep users unique as when a user signs up with any of them, i will take the other details also, like when user signs up with email/password, then i will also take user phone number and i dont want user to create another account with that phone number by using login with phone method.

and the second issue is my app has 3 user roles, user, sales and admin. each user has different sign up forms, and when a user with email sign up as sales and i also want to enable that user to sign up as user with same email, now as i use firebase sdk in react app, it throws error as user already exists.

what can be the resolution for this issue with firebase authentication and i want users to be unique and also i want to enable role based authentication.
i’m using firestore as my database

Element is not shifting up

[my output]2I had put a text beside image. I want to shift that text up but not able to do it. Padding bottom is not working on it. Tried everything but still facing this issue.

HTML Code:
<section>
        <ul class="left-section">
        <li><img class="prog" src="images/programming.png" alt=""></li>
         <li class="pp">DGcom</li>
        </ul>

        <ul class="right-section">
         <li class="sp1">
            <figure>
            <img src="images/clk.png" alt="">
            </figure>
        </li>
        <li class="pp1">Opening Hour</li>
         </ul>
        </section>
CSS Code:
section{
    margin-top: 0px;
    width: 100%;
    overflow: hidden;
    background-color: #ffffff;
    height: auto;
}
section ul li{
    display:inline-block;
}
.left-section{
    float:left;
    width: 40%;
}
.right-section{
    float:right;
    width: 58%;
    margin-top: -70px;
    text-align: right;
    height: auto;
}
.pp{
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    font-weight: 700;
    color: #3b6cff;
    font-size: 38px;
    padding: 15px;
    margin-bottom: 11px;
}
figure{
    display: inline-block;
    width: 50px;
    height: 50px;
    border-radius: 50px;
    font-size: 12px;
    text-align: center;
    margin-right: 10px;
    background: #fff;
    line-height: 1.7em;
    border: 1px solid #ccc;
}
figure img{
    display:inline-block;
    width: 22px;
    height: auto;
    margin-bottom: -22px;
 }
 .sp1{
   /* margin-left: 323px;*/
    padding-right: 100%;
   
 }
 .pp1{
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    padding-right: 80%;
 }

Pls Refer above code and let me know how to fixed it.

I’m creating section with logo and some details like opening hours, call us, etc. You can see the screenshot.

Floating Menu Is Not Working Within IFrame

I was using floating-1.12.js library to make a left Menu float when scrolling up or down, and this is working as expected, however a requirement changed by the client to make that page hosted within an iframe on other website that he owns, so both sites are on same domain but the one having the floating menu will be loaded inside an iframe on the other site.

So I noticed that the floating menu functionality is not working anymore and an error in the browser console appears as the following:

enter image description here

So I checked the official site of that library and I notice that if I put their demo inside an iframe I got same error:

    <html>
<head>
</head>

<body>
<iframe width="100%" height="1000px" src="http://www.jtricks.com/javascript/navigation/floating/confined_demo.html" />

</body>
</html>

So in the above code if you take the link and paste it in the browser you will see the demo working as expected, but putting it inside an iframe will be blocked.

How can I deal with this problem?
Please Advise.

Incoming TLS 1.3 sessions in Node 16/18 always generate different session ids

I have set up newSession and resumeSession listeners on the httpsServer instance, and whenever I want to compare the incoming IDs to the ones I already have stored on my backend (by literally following the official API: https://nodejs.org/api/tls.html#event-resumesession), I never get a match.

My ultimate goal is to have the client re-select a certificate by “invalidating” their session(s), similar to what a simple tlsSocket.renegotiate({}) used to do in TLS <= 1.2.

Here’s the code:

const app = express()

app.use(cors(), json())

const httpsServer = createServer(HTTPS_OPTIONS, app)

httpsServer.on(
  'newSession',
  (
    sessionId: Buffer,
    sessionData: Buffer,
    cb: (err: Error | null, resp: Buffer | null) => void
  ) => {
    const sId = sessionId.toString('hex')

    console.log('newSession', sId)

    certificationStore.setSessionData(sId, sessionData)
    cb(null, sessionData)
  }
)

httpsServer.on(
  'resumeSession',
  (
    sessionId?: Buffer,
    cb?: (err: Error | null, sessionData?: Buffer | null) => void
  ) => {
    if (!sessionId) return

    const sId = sessionId.toString('hex')
    const existingSession = certificationStore.getBySessionId(sId)

    // always returns false
    if (existingSession) {
      certificationStore.removeSession(sId)
      cb?.(null, existingSession)
    } else {
      cb?.(null)
    }
  }
)

And the HTTPS_OPTIONS object looks like this:

{
  key: fs.readFileSync(SSL_KEY_PATH),
  cert: fs.readFileSync(SSL_CERT_PATH),
  ca: [fs.readFileSync(SSL_CA_PATH)],
  requestCert: true,
  rejectUnauthorized: true,
}

I unfortunately need to stick with TLS 1.3, and I’m appalled at how little documentation there is on what to do instead of the old renegotiate() method.

What is the more correct way to approach all this?

Can not fetch php json with ReactJs

I am trying to fetch php object (as json string) with React. (I am very very new to php)

server.php

<?php
  header('Access-Control-Allow-Origin: http://localhost:3000');
........

$product = new Furniture();
$product->set_name('prod1');
$product->set_price('$4');
$product->set_Dimensions('2X2X2');
$myJSON = json_encode($product);


echo $myJSON;
?>

myJSON returns following

{"name":"prod1","price":"$4","Dimensions":"2X2X2"}

React code

import logo from './logo.svg';
import './App.css';
import { useState, useEffect } from 'react'
function App() {
  const [data, setData] = useState("");
  console.log(data)
  useEffect(() => {
    fetchAPI()
  },
    [data == ""])
  async function fetchAPI() {
    try {
      const response = await fetch('http://localhost:8000/server.php')
      if (response.ok) {
        let result = await response.json();
        console.log(result)
        setData(result);
      }
      else { return console.log('falied') }
    } catch (error) {
    }
  }
  return (
    <div className="App">
      {data.name}
    </div>
  );
}

export default App;

data on console is empty. Also there are no errors in network tab. (for example cors policy) Help would be greatly appreciated!

React Context is unavailable in Server Components when using useSession

Unhandled Runtime Error
Error: React Context is unavailable in Server Components

Source:

import { useSession, signIn, signOut } from "next-auth/react"

export default function Component() {
  const { data: session } = useSession()
  if(session) {
    return <>
      Signed in as {session.user.email} <br/>
      <button onClick={() => signOut()}>Sign out</button>
    </>
  }
  return <>
    Not signed in <br/>
    <button onClick={() => signIn()}>Sign in</button>
  </>
}

Access component scope reactive variable from parent in Svelte not updating

I have a TableRow.svelte component with a on click event that toggles a collapse class and changes the calling element text. The callback property works but the text never changes.

<script>
    export let rowData = {};
    export let labels = {};
    export let id = -1
    export let toggleCollapsible = function(){}
    let isCollapsed = true;
    $: isCollapsed
</script>
<tr>
    <td>{rowData.season}</td>
    <td>{rowData.farm}</td>
    <td>{rowData.block}</td>
    <td>{rowData.date}</td>
    <td>{rowData.totals}</td>
</tr>
<tr>
    <td colspan="3">
        <span data-row="{id}" role="button" on:click={toggleCollapsible}>{labels.realised} [{#if isCollapsed}<i class="fa fa-plus"></i>{:else}<i class="fa fa-minus"></i>{/if}]</span>
    </td>
    <td>{rowData.realised_date ?? "--"}</td>
    <td>{rowData.realised_total ?? "--"}</td>
</tr>

In the App.svelte component the TableRow component is initialised as follows:

<script>
    import FormRow from './FormRow.svelte';
    import TableRow from './TableRow.svelte';
    
    let table = [
        {id:1,block:"X",farm"xY",season:2023,total:3400, date:"2023-01-23"}
     ];
    let isCollapsed;
    let loading = true;
    let colspan = 4;
    let labels = {
        block: "Block",
        date: "Date",
        season: "Season",
        realised: "Realised",
        no_data: "No data",
        farm: "Farm"
    }
    $: loading;
    const loaded = () => {
        loading = false;
        return "";
    };

    function toggleCollapsible(e) {
        const id = e.target.dataset.row;
        if(id>0) {
            const tr = document.getElementById("row_form_"+id);
            tr.classList.toggle("show");
            isCollapsed = !tr.classList.contains("show");  // this does not update component scope reactive value
        }
    }

    function onSubmit(e) {
        // do submit things
    }
</script>
<style>
    :global(.opaque) {
        pointer-events: none!important;
        opacity: 0.6!important;
        transition: opacity 0.5s ease-in-out!important;
    }
</style>
    <FormRow onSubmit={onSubmit}/>

    <div class="container-full p-2">
        <div class="row justify-content-center">
            <div class="col-lg-12 w-100">
                <table class="mobile-table mobile-table-bordered text-center w-100">
                    <thead>
                        <tr style="background-color: #81d5c0; color: rgb(63, 63, 63);">
                            <th>{labels.season}</th>
                            <th>{labels.farm}</th>
                            <th>{labels.block}</th>
                            <th>{labels.date}</th>
                            <th>{labels.total}</th>
                        </tr>
                    </thead>
                    <tbody>
                        {#if table!==null && table!==undefined && table.length>0}
                        {loaded()}
                            {#each table as t, idx (t.id)}
                                <TableRow id={t.id} labels={labels} toggleCollapsible={toggleCollapsible} rowData={t}/>
                                <tr id="row_form_{t.id}" class="collapse" aria-expanded="false">
                                    <td colspan="{colspan}">
                                        <FormRow onSubmit={onSubmit}/>
                                    </td>
                                </tr>
                            {/each}
                        {:else}
                        {loaded()}
                            <tr>
                                <td colspan="{colspan}">{labels.no_data}</td>
                            </tr>
                        {/if}
                    </tbody>
                </table>
            </div>
        </div>
    </div>

How do I make the component variable reactive from parent scope function?

Getting error on firebox while using websocket php and javascript

I want to show realtime data on browser. I am using Rachet library for websocket. It is working on localhost in all browsers. After uploading on the linux shared hosting, it works fine on all browser except only mozilla. On the mozilla it gives error.

index.html is:

`<!DOCTYPE html>
<html>
<head>
  <title>WebSocket Chat</title>
</head>
<body>
  <h1>WebSocket Chat</h1>
  <div id="chatBox"></div>
  <input type="text" id="messageInput" placeholder="Type your message..." />
  <button id="sendButton">Send</button>

  <script>
    const socket = new WebSocket('wss://mydomain.com/websocket1:8081');

    // Function to save message on the server
        function saveMessage(message) {
          const xhr = new XMLHttpRequest();
          xhr.open('POST', 'save-message.php');
          xhr.setRequestHeader('Content-Type', 'application/json');
          xhr.send(JSON.stringify({ message: message }));
        }

    // Function to fetch messages from the server
    function fetchMessages() {
     const xhr = new XMLHttpRequest();
      xhr.open('GET', 'fetch-messages.php');
      xhr.onreadystatechange = function() {
            if (xhr.readyState === XMLHttpRequest.DONE) {
              if (xhr.status === 200) {
                const messages = JSON.parse(xhr.responseText);
                const chatBox = document.getElementById('chatBox');
                messages.forEach(function(message) {
              const messageElement = document.createElement('div');
              messageElement.textContent = message.fname;
              chatBox.appendChild(messageElement);
            });
          } else {
            console.log('Error fetching messages:', xhr.status);
          }
        }
      };
      xhr.send();
    }

    // Event listener for receiving messages from the server
    socket.addEventListener('message', function(event) {
      const message = event.data;
      const chatBox = document.getElementById('chatBox');
      const messageElement = document.createElement('div');
      messageElement.textContent = message;
      chatBox.appendChild(messageElement);
    });

    const sendButton = document.getElementById('sendButton');
    sendButton.addEventListener('click', function() {
      const messageInput = document.getElementById('messageInput');
      const message = messageInput.value;
      socket.send(message);
      messageInput.value = '';

      // Save the sent message on the server
      saveMessage(message);
    });

    // Fetch messages when the page loads
    fetchMessages();
  </script>
</body>
</html>

`

My server.php is:

`<?php
require 'vendor/autoload.php';

use RatchetMessageComponentInterface;
use RatchetConnectionInterface;
use RatchetServerIoServer;
use RatchetHttpHttpServer;
use RatchetWebSocketWsServer;
use SymfonyComponentHttpFoundationRequest;

class Chat implements MessageComponentInterface {
  protected $clients;

  public function __construct() {
   $this->clients = new SplObjectStorage;
  }

public function onOpen(ConnectionInterface $conn) {
$request = $conn->httpRequest;

// Handle the WebSocket handshake here
// You can perform any necessary checks or validation before accepting the connection

// Example: Check if the WebSocket upgrade header is present
if (!$request->hasHeader('Upgrade') || strtolower($request->getHeader('Upgrade')[0]) !== 'websocket') {
    // Close the connection if the Upgrade header is missing or incorrect
    $conn->close();
    return;
}

// Example: Check if the request contains the expected WebSocket version
if (!$request->hasHeader('Sec-WebSocket-Version') || $request->getHeader('Sec-WebSocket-Version')[0] !== '13') {
    // Close the connection if the WebSocket version is not supported
    $conn->close();
    return;
}

// Example: Check other necessary conditions

// Store the connection
$this->clients->attach($conn);
}


  public function onMessage(ConnectionInterface $from, $msg) {
    $message = htmlspecialchars($msg);

    foreach ($this->clients as $client) {
      $client->send($message);
    }
  }

  public function onClose(ConnectionInterface $conn) {
    $this->clients->detach($conn);
  }

  public function onError(ConnectionInterface $conn, Exception $e) {
    echo "An error has occurred: {$e->getMessage()}n";
    $conn->close();
  }
}

$chat = new Chat;
$server = IoServer::factory(
  new HttpServer(
    new WsServer($chat)
  ),
  8081
);

$server->run();

Error on firefox browser is:
enter image description here

Please ask if you need anything else from my side.

In the server Apache web socket module is installed and the port is opened.

What is wrong with this method for updating multiple rows dynamically?

exports.createTaskDataForNewDay = async function(values){
try {
    console.log("values" , JSON.stringify(values))
    let pool = await CreatePool()  //[timestamp , requiredTimes , reward , difficulty ,taskId , uid , csn]
    let query = "update userTaskData set timestamp = ?,requiredTimes=?,timesCompleted=0,reward=?,difficulty=?,state=1,taskId=?,replacedF=0,replacedC=0 where uid =? and suitCase = ?"
    let resp = await pool.query(query,[values])
    if(resp.changedRows >0 ){
        return resp
    }else  return {code:400 , mesage:"Could not insert data ! please try again or check syntax"}
    
} catch (error) {
    console.error(error)
    return {code:500 , message:error.message}
}
}

the ‘values’ being passed to the function is an array of arrays . each element holding the place holder data for different rows that i want to update .
but i getan error that is parsing error – something wrong with syntax and the query that is logged is –
sql: `update userTaskData set timestamp = (1686124176992, 1, ‘{“t”:”c”,”v”:1000}’, 1, ‘t1′, ’21GGZzSudOdUjKXcbVQHtFtTK772’, 1), (1686124176992, 3, ‘{“t”:”g”,”v”:10}’, 1, ‘t9′, ’21GGZzSudOdUjKXcbVQHtFtTK772’, 1), (1686124176992, 5, ‘{“t”:”c”,”v”:4000}’, 2, ‘t17′, ’21GGZzSudOdUjKXcbVQHtFtTK772’, 1), (1686124176992, 3, ‘{“t”:”c”,”v”:1000}’, 3, ‘t21′, ’21GGZzSudOdUjKXcbVQHtFtTK772’, 1),requiredTimes=?,timesCompleted=0,reward=?,difficulty=?,state=1,taskId=?,replacedF=0,replacedC=0 where uid =? and suitCase = ?

It is placing all the elements in the first place holder. Where as it is working fine for the insert queries .
please tell me what i’m doing wrong.

B13 – webprogramming excercise, i need some adv [closed]

`List<nevjegyadatokcs> lista = new List<nevjegyadatokcs>();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillGrid();
            FillDDL();
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        FillGrid();
    }
    protected void FillOszaly()
    {
        string sor;
        StreamReader reader = new StreamReader(Server.MapPath("~/nevjegyzek.txt"));
        while ((sor=reader.ReadLine()) != null)
        {
            nevjegyadatokcs item = new nevjegyadatokcs();
            string[] line = sor.ToString().Split("|");
            if (line.Length < 2)
            {
                break;
            }
            item.Id = line[0].Trim();
            item.Nev = line[1].Trim();
            item.Vezeteknev = line[2].Trim();
            item.Cim = line[3].Trim();
            item.Telefonszam = line[5].Trim();
            item.Email = line[6].Trim();
            item.Helyseg = line[4].Trim();
            lista.Add(item);
        }
        reader.Close();
    }

    protected void FillDDL()
    {
        FillOszaly();
        DropDownList1.Items.Add(" ");
        DropDownList1.Items.AddRange(lista.Select(i => new ListItem(i.Helyseg)).Distinct().ToArray());
    }

    protected void FillGrid()
    {
        FillOszaly();
        List<nevjegyadatokcs> eredmeny = lista;
        if (TextBox1.Text != "")
        {
            eredmeny = eredmeny.FindAll(i => i.Nev.Contains(TextBox1.Text));
        }
        if (TextBox2.Text != "")
        {
            eredmeny = eredmeny.FindAll(i => i.Vezeteknev.Contains(TextBox2.Text));
        }
        if (TextBox3.Text != "")
        {
            eredmeny = eredmeny.FindAll(i => i.Cim.Contains(TextBox3.Text));
        }
        if (TextBox4.Text != "")
        {
            eredmeny = eredmeny.FindAll(i => i.Telefonszam.Contains(TextBox4.Text));
        }
        if (TextBox5.Text != "")
        {
            eredmeny = eredmeny.FindAll(i => i.Email.Contains(TextBox5.Text));
        }
        if (DropDownList1.SelectedIndex > 0)
        {
            eredmeny = eredmeny.FindAll(i => i.Helyseg.Contains(DropDownList1.SelectedValue));
        }
        GridView1.DataSource = eredmeny;
        GridView1.DataBind();
    }
}

<asp:GridView ID=”GridView1″ runat=”server” Width=”520px” AutoGenerateColumns=”false”>
<Columns>
<asp:BoundField DataField=”Id” HeaderText=”Sorszám” />
<asp:BoundField DataField=”Nev” HeaderText=”Név” />
<asp:BoundField DataField=”Vezeteknev” HeaderText=”Vezetéknév” />
<asp:BoundField DataField=”Cim” HeaderText=”Cím” />
<asp:BoundField DataField=”Telefonszam” HeaderText=”Telefonszám” />
<asp:BoundField DataField=”Email” HeaderText=”E-mail” />
<asp:BoundField DataField=”Helyseg” HeaderText=”Helység” />
</Columns>
<EmptyDataTemplate>
Nincs találat !
</EmptyDataTemplate>
</asp:GridView>
}

this is the problem i have