Deenbandhu Chhotu Ram University Of Science And Technology (Dcrusm.Org.In)

The Deenbandhu Chhotu Ram University of Science & Technology is a renowned institution that is known for its excellence in the field of science and technology. With a strong emphasis on research and innovation, the university has been at the forefront of cutting-edge developments in various fields. Its state-of-the-art facilities and dedicated faculty provide students with a conducive environment for learning and growth. As a result, graduates from this institution have gone on to make significant contributions in their respective fields, both nationally and internationally.
Web Site:- www.dcrusm.org.in

The Deenbandhu Chhotu Ram University of Science & Technology is a renowned institution that is known for its excellence in the field of science and technology. With a strong emphasis on research and innovation, the university has been at the forefront of cutting-edge developments in various fields. Its state-of-the-art facilities and dedicated faculty provide students with a conducive environment for learning and growth. As a result, graduates from this institution have gone on to make significant contributions in their respective fields, both nationally and internationally.

How to build a Nuxt 3 app using Webpack builder with HtmlWebpackPlugin?

I’m having issues setting up HtmlWebpackPlugin in a Nuxt 3 app using Webpack 5 builder.

I’m getting an error while attempting this with a simple project. However, I was able to produce a successful build in another Vue project with similar steps (following this answer).

How can one build a successful bundle using HtmlWebpackPlugin in the context of a Nuxt project?

Please provide additional config if necessary for a successful build.

Scenario: Build a single standalone HTML bundle file with all assets inlined and embedded (JS, CSS, images, etc.) to be usable offline, locally and directly in a browser.

How to replicate

Create project and install dependencies:

npx nuxi init nuxt-webpack
cd nuxt-webpack
npm install @nuxt/webpack-builder html-webpack-plugin html-webpack-inline-source-plugin@beta -D
# prevent dependency error with memfs at the time of writing
npm install [email protected] -D

Set nuxt.config.ts as such:

// nuxt.config.ts

import HtmlWebpackPlugin from 'html-webpack-plugin';
import HtmlWebpackInlineSourcePlugin from 'html-webpack-inline-source-plugin';

// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
  debug: true,
  ssr: false, // try with and without
  builder: 'webpack',
  webpack: {
    plugins: [
      new HtmlWebpackPlugin({
        filename: 'output.html', // output file name that will be created
        template: 'output-template.html', // template file to use for insertion
        inlineSource: '.(js|css)$', // embed all javascript and css inline
        inject: 'body', // inject script at the end of document body
      }),
      new HtmlWebpackInlineSourcePlugin(HtmlWebpackPlugin),
    ]
  },
  hooks: {
    // may be needed for successful bundling
    "webpack:config"(configs) {
      // configs[0].module.rules.push(
      //   {
      //     test: /.vue$/,
      //     loader: 'vue-loader',
      //   },
      //   {
      //     test: /.html$/,
      //     loader: 'html-loader'
      //   },
      //   {
      //     test: /.tsx?$/,
      //     use: 'ts-loader',
      //     exclude: /node_modules/,
      //   },
      //   {
      //     test: /.css$/,
      //     use: ['style-loader', 'css-loader'],
      //   },
      //   {
      //     test: /.(png|jpg|gif|webp|svg)$/,
      //     loader: 'url-loader',
      //   },
      // );
    }
  },
});

Add file output-template.html:

<!-- output-template.html -->
<!DOCTYPE html>
<html lang=en>

<head>
    <meta charset=utf-8>
    <meta http-equiv=X-UA-Compatible content="IE=edge">
    <meta name=viewport content="width=device-width,initial-scale=1">
    <title>Nuxt App</title>
</head>

<body>
    <div id="__nuxt"></div>

    <!-- plugin will insert js here by default -->
</body>

</html>

Run build using npm run generate.

It results in the following error:

ERROR  Nuxt Build Error: Nuxt build error

  ModuleParseError: Module parse failed: Unexpected token (1:0)
  File was processed with these loaders:
  * ./node_modules/unplugin/dist/webpack/loaders/transform.js
  * ./node_modules/html-webpack-plugin/lib/loader.js
  * ./node_modules/unplugin/dist/webpack/loaders/transform.js
  * ./node_modules/unplugin/dist/webpack/loaders/transform.js
  You may need an additional loader to handle the result of these loaders.
  > <!-- output-template.html -->
  | <!DOCTYPE html>
  | <html lang=en>
  at handleParseError (node_modules/webpack/lib/NormalModule.js:982:19)
  at node_modules/webpack/lib/NormalModule.js:1101:5
  at processResult (node_modules/webpack/lib/NormalModule.js:806:11)
  at node_modules/webpack/lib/NormalModule.js:866:5
  at node_modules/loader-runner/lib/LoaderRunner.js:407:3
  at iterateNormalLoaders (node_modules/loader-runner/lib/LoaderRunner.js:233:10)
  at iterateNormalLoaders (node_modules/loader-runner/lib/LoaderRunner.js:240:10)
  at node_modules/loader-runner/lib/LoaderRunner.js:255:3
  at context.callback (node_modules/loader-runner/lib/LoaderRunner.js:124:13)
  at Object.transform (node_modules/unplugin/dist/webpack/loaders/transform.js:100:5)

How do I copy the values of a HTML table column to the clipboard using a Django template and JavaScript?

I need to copy the values of a HTML table column to the clipboard. I’m using Django templates.

Here is my HTML table:

<table>
                    <tr>
                        <th>Name</th>
                        <th>DOB</th>
                        <th>ID</th>
                        <th>Guardian</th>
                        <th>Email</th>
                        <th>Telephone</th>
                        <th>NIF</th>
                        <th>Notes</th>
                    </tr>
                    {% for a in sessao.first %}
                       <tr>
                          <td>{{ a.nome }}</td>
                          <td>{{ a.dtnasc }}</td>
                          <td>{{ a.alunoid }}</td>
                          <td>{{ a.educaid }}</td>
                          <td id="a.id">{{ a.educaid.email }}</td>
                          <td>{{ a.educaid.telefonea }}</td>
                          <td>{{ a.nif }}</td>
                          <td>{{ a.notas }}</td>
                          <td><button class="btn btn-outline-success btn-sm" onclick="CopyText({{ a.id }})" data-toggle="tooltip" data-placement="top" title="Copy">
                               copy
                           </button>
                          </td> 
                        </tr>
                    {% endfor %}
                </table>

I’m trying this script but I get an error message:

// Copy to ClipBoard
 function CopyText(el) {
 // Get the Selected Data By ID
  var copyText = document.getElementById(`${el}`)

  var str = copyText.innerHTML // Get All HTML Data and Copy to Clipboard

   function listener(e) {
    e.clipboardData.setData("text/plain", str);
    e.preventDefault();
  }
  document.addEventListener("copy", listener);
  document.execCommand("copy");
  document.removeEventListener("copy", listener);
};

The error message is:

Uncaught TypeError: Cannot read properties of null (reading 'innerHTML')
    at CopyText (lu.js:11:22)
    at HTMLButtonElement.onclick (2/:80:159)

Any help would be much appreciated. Thanks in advance.

Emscripten with cgal failed

First I clone this project:
https://github.com/yushi-bot/CGAL_triangulation_demo.

Background:
I am attempting to compile a C++ program that uses the CGAL library into WebAssembly (wasm) format using Emscripten technology to run it on a web page. The compilation is successful when using CMake alone. However, when I try to use the command emcmake make ../, the compilation process fails.

cmake ../        (at build folder which make by myself , it is success)
-- The C compiler identification is GNU 11.4.0
-- The CXX compiler identification is GNU 11.4.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
CMake Warning at /usr/lib/x86_64-linux-gnu/cmake/CGAL/CGALConfig.cmake:92 (message):
  CGAL_DATA_DIR cannot be deduced, set the variable CGAL_DATA_DIR to set the
  default value of CGAL::data_file_path()
Call Stack (most recent call first):
  CMakeLists.txt:4 (find_package)


-- Using header-only CGAL
-- Targetting Unix Makefiles
-- Using /usr/bin/c++ compiler.
-- Found GMP: /usr/lib/x86_64-linux-gnu/libgmp.so
-- Found MPFR: /usr/lib/x86_64-linux-gnu/libmpfr.so
-- Found Boost: /usr/lib/x86_64-linux-gnu/cmake/Boost-1.74.0/BoostConfig.cmake (found suitable version "1.74.0", minimum required is "1.48")
-- Boost include dirs: /usr/include
-- Boost libraries:
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD - Success
-- Found Threads: TRUE
-- Using gcc version 4 or later. Adding -frounding-math
-- Build type:
-- USING CXXFLAGS = ' '
-- USING EXEFLAGS = ' '
CMake Warning at /usr/lib/x86_64-linux-gnu/cmake/CGAL/CGAL_enable_end_of_configuration_hook.cmake:99 (message):
  =======================================================================

  CGAL performance notice:

  The variable CMAKE_BUILD_TYPE is set to "".  For performance reasons, you
  should set CMAKE_BUILD_TYPE to "Release".

  Set CGAL_DO_NOT_WARN_ABOUT_CMAKE_BUILD_TYPE to TRUE if you want to disable
  this warning.

  =======================================================================
Call Stack (most recent call first):
  CMakeLists.txt:9223372036854775807 (CGAL_run_at_the_end_of_configuration)


-- Configuring done
-- Generating done
-- Build files have been written to: /home/lyciih/github/CGAL_triangulation_demo/build

When I use this command.

emcmake cmake ../ 
configure: cmake ../ -DCMAKE_TOOLCHAIN_FILE=/usr/share/emscripten/cmake/Modules/Platform/Emscripten.cmake -DCMAKE_CROSSCOMPILING_EMULATOR=/usr/bin/node;--experimental-wasm-threads
CMake Error at CMakeLists.txt:4 (find_package):
  By not providing "FindCGAL.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "CGAL", but
  CMake did not find one.

  Could not find a package configuration file provided by "CGAL" with any of
  the following names:

    CGALConfig.cmake
    cgal-config.cmake

  Add the installation prefix of "CGAL" to CMAKE_PREFIX_PATH or set
  "CGAL_DIR" to a directory containing one of the above files.  If "CGAL"
  provides a separate development package or SDK, be sure it has been
  installed.


-- Configuring incomplete, errors occurred!
See also "/home/lyciih/github/CGAL_triangulation_demo/build/CMakeFiles/CMakeOutput.log".
emcmake: error: 'cmake ../ -DCMAKE_TOOLCHAIN_FILE=/usr/share/emscripten/cmake/Modules/Platform/Emscripten.cmake -DCMAKE_CROSSCOMPILING_EMULATOR=/usr/bin/node;--experimental-wasm-threads' failed (returned 1)

please tell me how to fix it.

Thanks for help

Custom tabBarButton: component navigation in React Navigation

I’m encountering an issue with a custom tab button component in my React Navigation application.

I have defined a custom tab button component called CustomTabBarButton and I want to use it as a button within the tab bar in a specific Tab.Screen. However, I’m facing a problem when I include it in the options of the Tab.Screen

import CustomTabBarButton from "../CustomTabBarButton/CustomTabBarButton";

///

<Tab.Screen
  name="AddButton"
  children={() => <HomeStackScreen user={user} />}
  options={{
    tabBarLabel: "",
    tabBarIcon: ({ focused }) => (
      <Image
        source={imageUrl}
        resizeMode="contain"
        style={{
          width: 70,
          height: 70,
          backgroundColor: "#373737",
          borderRadius: 100,
        }}
      />
    ),
    tabBarButton: () => (<CustomTabBarButton navigation={navigation} setScreen={setScreen} />)
  }}
/>

Im getting the following error in the console:
The action ‘NAVIGATE’ with payload {“name”:”TrackerSetttings”} was not handled by any navigator.

Do you have a screen named ‘TrackerSetttings’?

If you’re trying to navigate to a screen in a nested navigator, see https://reactnavigation.org/docs/nesting-navigators#navigating-to-a-screen-in-a-nested-navigator.

In the same file TrackerSetttings is defined in the following way:

function HomeStackScreen({ navigation, user, backgroundColor }) {
  return (
    <HomeStack.Navigator>
      <HomeStack.Screen
        name="Tracker Setttings"
        children={() => <TrackerSettings user={user} />}
        options={({ navigation }) => ({
          title: "Velg lokasjon",
        })}
      />

The issue is that it doesn’t work when I include tabBarButton in the options. However, when I remove it, as shown below, it works as expected.

<Tab.Screen
  name="AddButton"
  children={() => <HomeStackScreen user={user} />}
  options={{
    tabBarLabel: "",
    tabBarIcon: ({ focused }) => (
      <Image
        source={imageUrl}
        resizeMode="contain"
        style={{
          width: 70,
          height: 70,
          backgroundColor: "#373737",
          borderRadius: 100,
        }}
      />
    )
  }}
/>

I’m looking for insights into why the tabBarButton causes issues and how to resolve this problem so I can use my custom tab button component. Any help or guidance on the correct implementation would be greatly appreciated. Thank you.

Troubles with server.php

Maybe someone knows, I want to receive the data entered by the user and I use PCP as a server, but the code does not go through – ” request.send(formData) “, it says ” Failed to load resource: the server responded with a status of 405 (Method Not Allowed) “, what could be the reason for this behavior? I add the code:

const inputName = document.getElementById('name')
const inputTel = document.getElementById('tel')
const clickBtn = document.getElementById('submit')
const forms = document.querySelector('form')


addForm(forms)


function addForm (form){
form.addEventListener(('submit'), (e) =>{
    e.preventDefault();

    const statusMessage = document.createElement('div')
    statusMessage.innerHTML = '';
    statusMessage.innerHTML = 'Loading'
    forms.append(statusMessage)

    const request = new XMLHttpRequest();
    request.open('POST', 'server.php');
    // request.setRequestHeader('Content-type', 'multipart/form-data')
    const formData = new FormData(form)
    request.send(formData)

    request.addEventListener(('load'), () => {
        statusMessage.innerHTML = ''
        if (request.status === 200) {
            console.log(request.response)
            statusMessage.innerHTML = 'Loading success'
        } else{
            statusMessage.innerHTML = 'Something went wrong'
        }
    })
})
}
<?php
echo var_dump($_POST);

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>coffe-house</title>
    <style>
        body{
            background-color: rgb(88, 0, 88);
            display: flex;
            flex-direction: column;
            width: 100%;
            max-width: 100vw;
            min-height: 100vh;
            align-items: center;
            justify-content: center;
        }
        .forma{
            width: 100%;
            max-width: 400px;
            display: flex;
            flex-direction: column;
            align-items:center;
            padding: 60px 0;
            background-color: rgba(0, 255, 247, 0.5);
            border-radius: 10px;
        }
        form{
            display: flex;
            flex-direction: column;
            row-gap: 30px;
        }
        input{
            border-radius: 5px;
            outline: none;
            border: none;
            padding: 5px;
        }
        #submit{
            padding: 10px;
            cursor: pointer;
        }
    </style>
</head>
<body>

<div class="forma">
    <form>
            <input id="name" type="text" name="name">
            <input id="tel" type="tel" name="tel">
        <button id="submit">Click here</button>
    </form>
</div>
<script src="./index.js"></script>
    
</body>
</html>

Show a http code of a website in an html file [duplicate]

I want to generate a diagnosis html page that can show the connection status (200, 404, …) of a certain website in an html page. The problem is that now no matter which url I use in var url = 'https://google.com'; (I’ve tried my own website, Google, Apple, …), it never gives code 200.

The following is my code:

var url = 'https://google.com';
var statusDot = document.getElementById('status-dot');
var statusText = document.getElementById('status-text');

fetch(url)
  .then(response => {
    if (response.ok) {
      statusDot.style.backgroundColor = 'green';
      statusText.textContent = 'success';
    } else {
      statusDot.style.backgroundColor = 'red';
      statusText.textContent = 'fail';
    }
  })
  .catch(error => {
    statusDot.style.backgroundColor = 'red';
    statusText.textContent = 'fail';
  });
#status-container {
  display: flex;
  align-items: center;
}

#status-dot {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: inline-block;
}

#status-text {
  margin-left: 10px;
}
<p>Checking connection...</p>
<div id="status-container">
  <div id="status-dot"></div>
  <span id="status-text"></span>
</div>

Can anyone help me with this?

AES encryption in Perl similar to [email protected]

The following JavaScript code:

'use strict';
const CryptoJS = require('crypto-js');

const plaintext = 's3cret';
const password  = 'MyPassword';
//const iv   = CryptoJS.lib.WordArray.random(16);
//const salt = CryptoJS.lib.WordArray.random(16);
const iv   = CryptoJS.enc.Hex.parse("43c9ccba630fe1cd61fc2bdb90121c6f"); // For testing
const salt = CryptoJS.enc.Hex.parse("5c788a415851e909d9c7951717714204"); // For testing
const key = CryptoJS.PBKDF2(password, salt, {keySize: 128/32, iterations: 1000});
const b64ciphertext = CryptoJS.AES.encrypt(plaintext, key, {iv: iv}).ciphertext.toString(CryptoJS.enc.Base64);
console.log(b64ciphertext);
  1. Using [email protected], produces:
eiJkaAmCVjHFKbvY/CnkvQ==
  1. Using [email protected], produces:
qT1Vtod7ihS2wvtwmlnPow==

The Perl equivalent for the [email protected] output was provided by this answer:

use strict;
use warnings;
use feature qw( say );

use Crypt::CBC    qw( );
use Crypt::PBKDF2 qw( );
use Mojo::Util qw(b64_encode);

my $plaintext = 's3cret';
my $password  = 'MyPassword';
#my $iv   = Crypt::CBC->random_bytes( 16 );
#my $salt = Crypt::CBC->random_bytes( 16 );
my $iv   = pack( "H*", "43c9ccba630fe1cd61fc2bdb90121c6f" ); # For testing
my $salt = pack( "H*", "5c788a415851e909d9c7951717714204" ); # For testing

my $pbkdf2 = Crypt::PBKDF2->new(output_len=>128/8, iterations=>1000);
my $key = $pbkdf2->PBKDF2($salt,$password);
my $cipher = Crypt::CBC->new(
                 -cipher  => 'Cipher::AES',
                 -header  => 'none',
                 -pbkdf   => 'none',
                 -keysize => length($key),
                 -key     => $key,
                 -iv      => $iv
                );
my $ciphertext = $cipher->encrypt( $plaintext );
my $b64ciphertext = b64_encode($ciphertext,'');

say $b64ciphertext;

Using Perl, how can I get an output similar to [email protected]?

useState-value doesn’t change in function when updated (react native)

I have the following (simplified) react native code. Please read below the code for the explanation.

const [id, setId] = useState(null);

const functionOne = (id) => {
    setId(id);
};

const functionTwo = (newId) => {
    if (id === newId) {
        console.log('ids are the same');
    } else {
        console.log('ids are not the same');
    }
};

useEffect(() => {
    const socket = new WebSocket(url);

    socket.addEventListener('open', () => {
        console.log('socket connection opened');
    });

    socket.addEventListener('message', (msg) => {
        const data = JSON.parse(msg.data);

        if (data.eventType === 'one') {
            functionOne(data.id);
        }

        if (data.eventType === 'two') {
            functionTwo(data.id);
        }
    }) 

    socket.addEventListener('close', () => {
        console.log('socket connection closed');
    });
}, []);

I have a useState-hook for an ID. And I have two events which are sent from the server over websockets to the app: event “one” and event “two”.

In event “one”: I send a unique ID to the app, and I store this ID in the useState-id-hook. This works, because when I do a console.log in a useEffect-function to see if the state changes, it works.

After 1 minute, I receive another socket message with event type = “two” and the exact same ID I received a minute before. I want to compare this “new” ID with the previous received ID.

The problem is: when running functionTwo(), it seems that the useState-hook still is stuck in the original state, eg. “null”. It does get updated by this update is not reflected in functionTwo(), where the value of “id” is still “null”.

Wrapping functionTwo() in a useCallback(functionTwo, [id]) didn’t work.

What is wrong with my code?

Telegram Bot on Node.JS

I am attempting to launch the bot at https://github.com/ArbeitBot/ArbeitBot, but I am encountering difficulties. I have gone through the installation guide; however, it appears to be inadequate for my comprehension. Could someone provide me with a more comprehensive step-by-step guide on how to successfully launch the bot?

I tried to create .env file with next lines:
enter image description here

But when i run npm start command, I am faced with the following problem:

PS C:UsersflyxnDesktopTapsyrmaBetaarbeitbot> npm start

> [email protected] start
> node ./app.js

C:UsersflyxnDesktopTapsyrmaBetaarbeitbotnode_modulesnode-telegram-bot-apilibtelegram.js:170
        throw new Error('Telegram Bot Token not provided!');
        ^

Error: Telegram Bot Token not provided!
    at TelegramBot._request (C:UsersflyxnDesktopTapsyrmaBetaarbeitbotnode_modulesnode-telegram-bot-apilibtelegram.js:170:15)
    at TelegramBot.setWebHook (C:UsersflyxnDesktopTapsyrmaBetaarbeitbotnode_modulesnode-telegram-bot-apilibtelegram.js:255:19)
    at Object.<anonymous> (C:UsersflyxnDesktopTapsyrmaBetaarbeitbothelperstelegramBot.js:35:7)
    at Module._compile (node:internal/modules/cjs/loader:1256:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
    at Module.load (node:internal/modules/cjs/loader:1119:32)
    at Module._load (node:internal/modules/cjs/loader:960:12)
    at Module.require (node:internal/modules/cjs/loader:1143:19)
    at require (node:internal/modules/cjs/helpers:121:18)
    at Object.<anonymous> (C:UsersflyxnDesktopTapsyrmaBetaarbeitbothelperslogic.js:19:13)
    at Module._compile (node:internal/modules/cjs/loader:1256:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
    at Module.load (node:internal/modules/cjs/loader:1119:32)
    at Module._load (node:internal/modules/cjs/loader:960:12)
    at Module.require (node:internal/modules/cjs/loader:1143:19)
    at require (node:internal/modules/cjs/helpers:121:18)
    at Object.<anonymous> (C:UsersflyxnDesktopTapsyrmaBetaarbeitbotapp.js:24:1)
    at Module._compile (node:internal/modules/cjs/loader:1256:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
    at Module.load (node:internal/modules/cjs/loader:1119:32)
    at Module._load (node:internal/modules/cjs/loader:960:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)

Node.js v18.17.1

Change “locale” language JSON files

I have a Vue 3 project. It has 2 default languages but it can have more

Inside my src folder I have my “locales” folder, where I have the jsons with the translations

For example:

root-
    src-
       locales-
              - en.json
              - pt.json

I have one problem. Some clients want different names for the same thing. Imagine that I have:

en.json

{
    menu1: "This is a menu"
}

Client A wants the text as it is. But Client B wants to change that text to:

{
    menu1: "What an amazing menu"
}

Is there a way to give freedom to users and let them change the json files?
Like where they change the text inside a text field, they press “submit” and the json is updated with the new info?

Our problem is that if the client decides to change multiple times the text, we need to do it inside that json file manually. And I want something more pratical. If I give that “power” to the client it would be great

We are talking about two different applications. Each application as its own jsons translation files.

The only thing that I want is to give the freedom to the user to rename some of the texts and translations

<template>
    <v-container fluid class="mx-16 px-16 py-12" v-if="!loading">
        
        <v-card>
            <v-card-title>
                Configurar nomes de menus
            </v-card-title>
            <v-card-text>
                <v-row>
                    <v-col cols="12">
                        <v-text-field
                            v-model="fields[this.$route.params.lang].menu.home"
                            label="Homepage"
                            prepend-icon="$vuetify"
                            variant="underlined"
                        ></v-text-field>
                    </v-col>
                </v-row>
                <v-row no-gutters>
                    <v-col cols="12">
                        <v-btn color="success" @click="updateMenus">Atualizar</v-btn>
                    </v-col>
                </v-row>
            </v-card-text>
        </v-card>
    </v-container>
</template>
<script>

// This gives me the json objects
// pt: {}
// en: {} ... and other languages
import index from '@/locales/index.js'

export default{
    name: "EditMenus",
    data: () => ({
        loading: true,
        fields: null
    }),
    mounted(){
        this.fields = index
        this.loading = false
    },
    methods:{
        updateMenus(){

            console.log("UPDATE JSON")
        }
    }
}
</script>

Ways around the Vue 2 restriction on single-root templates

I’m trying to modify a Vue component that’s based on an HTML template tag. The trouble is that the parent page places this component inside an <li> tag:

<li>
    <my-custom-vue-component></my-custom-vue-component>
</li>

And the current component only contains an tag:

<template>
    <a class="my-button" @click="doTheThing()">Press Me</a>
</template>

What I need to do is add some conditional logic to this (which is straightforward with v-if) so that one of the renderings displays a modal. The problem is, I can’t get the modal tags into the component because of the restriction on a single root element.

I can’t wrap the whole thing inside a <div> or <span> because this is part of a list, and it destroys the formatting. I can’t put the <div> tags for the modal inside an <a></a> because that’s invalid HTML. And while I can use v-if to render two different links depending on the condition, I can’t put the <div> tags for the modal outside the template, otherwise nothing renders. I’ve considered creating a new component just for this but it’s still going to have the same fundamental problem – it’ll need a link in it and a modal, and I can’t see any way of getting them both inside the same <template>.

My understanding is that this restriction is removed with Vue 3 but we’re still on Vue 2, and there’s no way I can upgrade just to do this work.

Is there any tricksy way I can contain the tags I need to creat modal inside a template with a link given the restriction on a single root tag?

I need help making an animated full screen button for my website using CSS

I’m working on an animated button for my website that transforms an icon like this into one like this and back. The goal is for a spam-proof transition to smoothly take place between the two states in a style similar to this one I made earlier.

Here’s what I have so far:

function toggleState(target) {
  target.classList.toggle("animate");
}
:root {
  --btn-size: min(8vh, 8vw);
  --bar-dimen: calc(var(--btn-size) * 0.225);
  --bar-thick: calc(var(--bar-dimen) * 0.5);
  --animation: 0.50s;
  --anim-half: calc(var(--animation) / 2);
  --anim-func: ease-in-out;
  --btn-color: black;
}

body {
  margin: 1%;
}

#fullscreen-btn {
  height: var(--btn-size);
  aspect-ratio: 1;
  position: relative;
  cursor: pointer;
  transition: rotate var(--animation) var(--anim-func);
}

#fullscreen-btn::before,
#fullscreen-btn::after,
#fullscreen-btn span::before,
#fullscreen-btn span::after {
  height: var(--bar-dimen);
  aspect-ratio: 1;
  position: absolute;
  border: var(--bar-thick) none var(--btn-color);
  transition: rotate var(--animation) var(--anim-func);
}

#fullscreen-btn::before {
  content: "";
  border-style: solid none none solid;
  top: 0;
  left: 0;
}

#fullscreen-btn::after {
  content: "";
  border-style: solid solid none none;
  top: 0;
  right: 0;
}

#fullscreen-btn span::before {
  content: "";
  border-style: none none solid solid;
  left: 0px;
  bottom: 0px;
}

#fullscreen-btn span::after {
  content: "";
  border-style: none solid solid none;
  right: 0px;
  bottom: 0px;
}

#fullscreen-btn.animate {
  rotate: 360deg;
}

#fullscreen-btn.animate::before,
#fullscreen-btn.animate::after,
#fullscreen-btn.animate span::before,
#fullscreen-btn.animate span::after {
  transition: rotate var(--animation) var(--anim-func);
  rotate: 180deg;
}
<div id="fullscreen-btn" onclick="toggleState(this)">
  <span></span>
</div>

First, is there any way for me to remove the <span> from the <div>? Second, is there anything I can do to optimize my code, make it nicer, neater, etc.? And finally, does anyone have any ideas to make the animation nicer, more confined inside of the <div> while animating, and more on-par with the menu button?

How can I Preserve Clicked Country States in amCharts 5 Map on Page Reload?

I’m very new to HTML, and I’m currently working on a personal project with an interactive amCharts map. When a country is clicked, it changes colour, marking it “active.” I am struggling to keep the countries “active” between web reloads. (I am mainly using this code to make an interactive notion widget for my travel page)

I’ve tried using local storage to preserve these clicked states across page reloads for personal use, but I couldn’t get it to work.

I’ve used localstorage successfully on a button I coded before to keep its state if it’s clicked or not between web reloads.

I couldn’t find clear guidance in amCharts documentation on how to achieve this. Can anyone provide insights or code examples for storing and retrieving the active states of clicked countries using local storage or another method?

The code below:

<html>
<head>
    <meta charset="UTF-8">
    <title>Interactive Polygon Map</title>
    <!-- Styles -->
    <style>
        #chartdiv {
            width: 100%;
            height: 500px;
        }
    </style>

    <!-- Resources -->
    <script src="https://cdn.amcharts.com/lib/5/index.js"></script>
    <script src="https://cdn.amcharts.com/lib/5/map.js"></script>
    <script src="https://cdn.amcharts.com/lib/5/geodata/worldLow.js"></script>
    <script src="https://cdn.amcharts.com/lib/5/themes/Animated.js"></script>
</head>
<body>
    <div id="chartdiv"></div>
    <script>
    
        am5.ready(function () {
            var root = am5.Root.new("chartdiv");

            root.setThemes([am5themes_Animated.new(root)]);

            var chart = root.container.children.push(am5map.MapChart.new(root, {
                panX: "rotateX",
                panY: "translateY",
                projection: am5map.geoNaturalEarth1()
            }));

            var polygonSeries = chart.series.push(am5map.MapPolygonSeries.new(root, {
                geoJSON: am5geodata_worldLow,
                exclude: ["AQ"]
            }));

            chart.chartContainer.set("background", am5.Rectangle.new(root, {
                fill: am5.color(0x191919),
                fillOpacity: 1.0
            }));

            polygonSeries.mapPolygons.template.setAll({
                tooltipText: "{name}",
                toggleKey: "active",
                interactive: true,
                fill: am5.color("#FFD6E6"),
            });

            polygonSeries.mapPolygons.template.states.create("hover", {
                fill: am5.color("#DEB4C6")
            });

            polygonSeries.mapPolygons.template.states.create("active", {
                fill: am5.color("#B9CCB1")
            });

            // Function to handle when a country is clicked
            function handleCountryClick(event) {
                var polygon = event.target;
                var isActive = polygon.isActive;
                polygon.isActive = !isActive;
            }

            // Add a click event listener to handle country clicks
            polygonSeries.mapPolygons.events.on("hit", handleCountryClick);

            // Set clicking on "water" to zoom out
            chart.chartContainer.get("background").events.on("click", function () {
                chart.goHome();
            });

            // Add zoom control
            var zoomControl = chart.set("zoomControl", am5map.ZoomControl.new(root, {}));
            var homeButton = zoomControl.children.moveValue(am5.Button.new(root, {
                paddingTop: 10,
                paddingBottom: 10,
                icon: am5.Graphics.new(root, {
                    svgPath: "M16,8 L14,8 L14,16 L10,16 L10,10 L6,10 L6,16 L2,16 L2,8 L0,8 L8,0 L16,8 Z M16,8",
                    fill: am5.color(0xffffff)
                })
            }), 0);

            homeButton.events.on("click", function () {
                chart.goHome();
            });

            // Make stuff animate on load
            chart.appear(1000, 100)

        });
    </script>
</body>
</html>

I’m trying to add items to cart using php but something about alternating between script,html,and php seems wrong [closed]

My guess is that I’m not adding a li everytime the while loop runs. So the result shows contents for one item but blank for the rest. I tried adding but I’m not sure how to. Something about alternating between script, html, and php seems wrong.

To give a brief overview of my code:

  1. I’m first initializing variables in javascript that I will be using later to format html
  2. I’m connecting to my DB and getting data by row and traversing it with a while loop until there is no more data left.
  3. I get data from DB and save it into variables
  4. I’m adding script to modify php variable
  5. I edit the html by either using textContent or value. Modifications of script variable exist to fit imagename
  6. Then once edit is clicked, I send the quantity edited to php and put the new data into my DB

Here is my code:

?php session_start(); include "dbconn.php"; ?>
    <html>
        
        <head>
            <meta charset="utf-8">
            <link rel="stylesheet" href="css/reset.css">
            <script src="js/jquery-1.11.2.min.js">
            </script>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
            </script>
        </head>
        <script>
            var prename = "";
            var code = "";
            var price = 1;
            var quant = 1;
            var tot = 1;
            var newquant = 1;
            var name = "";
            var preimagename = "";
            var imagename = "";
            var $ul = $('.shoppinglist');
        </script>
        <div class="productscontent">
            <ul class="shoppinglist">
                <?php $sql="select * from cart" ; $result=m ysqli_query($connect,$sql);
                while($row=m ysqli_fetch_array($result)) { //mysqli_fetch array fetches
                a single result row for you // When you call it the first time, it returns
                the first one. When you call it the second time, it returns the second
                one - and so on. //while loop keep getting results until there are no more
                results; $item_code=$ row[ 'code']; $item_proname=$ row[ 'proname']; $item_price=$
                row[ 'price']; $item_quant=$ row[ 'quant']; $item_tot=$ row[ 'tot']; echo
                "<script>prename = '$item_proname';</script>"; ?>
                    <li class='list'>
                        <h3 class="name">
                        </h3>
                        <img class="imagename" src="" width="200px" height="200px" alt="img">
                        <p class="code">
                            <?php echo "<script>code = '$item_code'</script>";?>
                        </p>
                        <p class="price">
                            <?php echo "<script>price = $item_price</script>";?>
                                <p>
                                    <ul class="quantbox cf">
                                        <li>
                                            <form>
                                                <input type="number" name="quant" class="quant" required placeholder="1">
                                                <?php echo "<script>quant = '$item_quant'</script>";?>
                                            </form>
                                        </li>
                                        <li>
                                            <button class="edit">
                                                edit
                                            </button>
                                        </li>
                                    </ul>
                                    <div class="close">
                                        <a href="#">
                                            <img src="close.png" alt="icon" width="50px" height="50px">
                                        </a>
                                    </div>
                    </li>
                    <script>
                        name = prename.replace(/_/g, " ");
                        document.querySelector('.name').textContent = name;
                        preimagename = prename.replace(/_/g, "");
                        imagename = preimagename.toLowerCase();
                        document.querySelector('.imagename').src = imagename + ".png";
                        document.querySelector('.code').textContent = code;
                        document.querySelector('.price').textContent = "$" + price;
                        document.querySelector('.quant').value = quant;
                        window.alert(name + imagename + code + price + quant);
                    </script>
            </ul>
            <h2 class="total">
            </h2>
            <?php echo "<script>tot = '$item_tot'</script>";?>
                <script>
                    document.querySelector('.total').textContent = "Total Price is $" + tot;
                </script>
        </div>
        <script type="text/javascript">
            //if you make a change and click on edit
            document.querySelector(".edit").addEventListener("click",
            function() {
                //select quantity from user input and send it to php
                newquant = parseInt(document.querySelector('[name="quant"]').value);
                $.ajax({
                    url: "product.php",
                    method: "POST",
                    data: "newquant=" + newquant,
                    dataType: 'number'
                }) tot = newquant * price; < ?php
                //receive quantity in php
                $newquant = $_POST['newquant'];
                //calculate new total value
                $newtot = $newquant * $item_price;
                //send new total value to javascript so that you can print it in javascript
                //update db with new values
                $sql1 = "update cart set code='$item_code', proname='$item_proname', price='$item_price', quant='$newquant', tot='$newtot' where code='$item_code'";
                $result1 = mysqli_query($connect, $sql1);
                //close db
                mysqli_close($connect); ? >
                //display total price
                document.querySelector('.total').textContent = "Total Price is $" + tot;
                //inform user that quantitiy has been updated
                window.alert('Quantity has be updated');
            });
            $ul.append($('.list'));
        </script>
        </body>
        <?php }//end of while loop ?>
    
    </html>