How to convert scaling from SVG units to pixels using scale formula?

Previously, I asked how to obtain the real coordinates (d) of a path when a transformation is applied, finally I decided to investigate the transformation formulas, I have already seen the translation, and now I am seeing the scaling (scale), I managed to do a scaling Basically the formula is:

x’ = x * sx

y’ = y * sy

Where:

x is equal to the x coordinate.

y is equal to the y coordinate.

sx or/and sy is equal to the scale factor.

x’ or/and y' is equal to the new size or coordinate.

But I can’t get the scale factor to increase or move the coordinates based on pixels, that is, assuming I have the following svg:

<svg width="300" height="300" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
     <rect x="0" y="0" width="100" height="100" fill="red" />
     <path id="element" d="M5, 5 L50, 5 L50, 45 L5, 45 Z" fill="none" stroke="white" /> 
</svg>

The d attribute (command) of <path id="my-path" d="M5, 5 L50, 5 L50, 45 L5, 45 Z" fill="none" stroke="white" />, If I wanted to scale this path using a scale factor of 2, it would be:

M = 5 * 2, 5 * 2
M = 10, 10

L = 50 * 2, 5 * 2
L = 100, 10

L = 50 * 2, 45 * 2
L = 100, 90

L = 5 * 2, 45 * 2
L = 10, 90

// result

M10, 10 L100, 10 L100, 90 L10, 90

But, going back to the beginning, how do I make it scale based on pixels? Playing around, I managed to guess that if the scale factor is:

1.1 = 15px -> therefore, the total width and height of the path will grow every 15px.

1.01 = 0.5px -> therefore, the total width and height of the path will grow every 0.5px.

But, as I mentioned, I guess it… Is there a formula to do this conversion? I want it to scale to 1px, 2px, 2.5px, etc, etc, for now I only need 1px.

I hope you have understood what I want to do, I hope you can help me.

Note: the svg is being added directly to the HTML.

Output image depending on selection vue.js

I am relatively new to vue.js and I am having a bit of difficulty. I want to show the images of NBA players depending on the selection using vue.js. For example: If the Dunk contest champion is selected: the image of only Kobe and Jordan should show up. To know if it should output the image of the player, it has to check the data in an object with key-values called properties, which contain conditions and every NBA player.

I created a variable called checksate initially set to false. I want it to turn true when the condition is met. I created an onChange method for that purpose. I am able to show the images and fill up the selection element by taking the data from the key-value objects. However, I cannot make the selection element and the images work together.

Any ideas?

<head>
    <style>
     a.incognito{
    display: none;
        }
        </style>
</head>
<body>
        <h2>NBA players</h2>
        <p>A selection of the best NBA players</p>

        <div id="app">
            <select  @change="onChange()" v-model="selected">
                <option value="none">Select filter</option>
                <option v-for="property in properties" :value="property.filter"> {{property.filter}}</option>
            </select>

            <div class="portfolio">
                <a v-for="player in players" :href="player.href" 
                    :class="{incognito: checkstate}" :playername="player.name">
                    <img :src="player.src" alt="" >
                </a>
            </div>
        </div>
  
    <script src="https://unpkg.com/vue@3"></script>


    <script>
        let app = Vue.createApp({
            data() {
                return {
                    players: [{ name: "Mike", href: "https://en.wikipedia.org/wiki/Michael_Jordan", src: "/Test/Michael_Jordan_in_2014.jpg" },
                    { name: "Kobe", href: "https://en.wikipedia.org/wiki/Kobe_Bryant", src: "/Test/Kobe_Bryant_2014.jpg" },
                    { name: "Lebron", href: "https://en.wikipedia.org/wiki/LeBron_James", src: "/Test/LeBron_James_-_51959723161_(cropped).jpg" },
                    { name: "Kd",  href: "https://en.wikipedia.org/wiki/Kevin_Durant", src: "/Test/Kevin_Durant_(Wizards_v._Warriors,_1-24-2019)_(cropped).jpg" },
                    ],

                    properties: [{filter: "Guard position",Mike:true,Kobe:true,Kd:false,LeBron:false},
                    { filter: "Foward position",Mike:false,Kobe:false,Kd:true,LeBron:true},
                    { filter: "Multiple Championships",Mike:true,Kobe:true,Kd:true,LeBron:true},
                    { filter: "Multiple MVP's",Mike:true,Kobe:false,Kd:false,LeBron:true},
                    { filter: "Over 6'8",Mike:false,Kobe:false,Kd:true,LeBron:true},
                    { filter: "Dunk contest champion",Mike:true,Kobe:true,Kd:false,LeBron:false}],
                    
                    selected: 'none',                  
                    checkstate:false,
                }
            }, methods: {
                onChange() {
                    const attr = this.properties.find((item) => item.filter === this.selected)

                        checkstate=this.properties[this.playername] 
                },
            },
                props:['playername']
            , 
        })
        app.mount('#app')
        
    </script>

</body>

disable elements when value = 1, enable them when value > 1

Using javascript only I am trying to say if cycn = 1, disable input element with id="prevdl"

if cycn > 1, then do not disable element with id="prevdl", and in both cases
preview the value of cycn in the <p> with id="transit"

but condition after if (cycn = 1) is executed no matter what. And the one after else is not seen at all

HTML

<label for="cyclecount">Cycle Count:</label>
<input type="number" id="cyccnt" name="cyclecount" placeholder="Today's cycle number" min="1" max="6" autocomplete="off" value=""><br><br>

<p id="transit"></p>

<label for="previousdoseLevel">Previous Dose Level:</label>
<input type="number" id="prevdl" name="previousdoseLevel" placeholder="Insert Previous Dose Level" autocomplete="off" value=""><br><br>

Javascript

var cyc = document.getElementById("cyccnt");
var cycn = Number(cyc.value);
document.getElementById("cyccnt").oninput = function (e) { 
    if (cycn = 1) {
        document.getElementById("prevdl").disabled = true;
        document.getElementById("transit").innerHTML = cycn;   
    } else if (cycn >1) {
        document.getElementById("prevdl").disabled = false; 
        document.getElementById("transit").innerHTML = cycn;    
    }
    e.preventDefault(e);
}

please help and thanks in advance.

Angular Promise returns undefined in another component

this is my carComponent.ts it has following method:

async Download() {
    try {
      const settings = {
        kit: true,
        tyres: true,
        serviced: false,
      };
      const [kits, tyres] = await Promise.all([
        this.checkKits(
          conf,
          "A",
         100,
          false,
          "My kit"
        ),
        this.checktyres(100, 50, false, 'My tyres'),
      ]);
    
    const checkSvg= [...kits.slice(0, 4), ...tyres, ...kits.slice(4)];
   checkSvg.forEach(({ side, svg }) => {
     console.log(svg); // here it returns all the SVG data; works 100%
   return svg;
    });
  }
  catch(e) {
    console.error(e);
  }
   
}

this is viewCarsComponent.ts which is calling above method. But here promise returns undefined so can anyone help please to resolve my issue? I am not sure what am I doing wrong or what I need to do here to resolve.

async DisplaySVG() {
 await this.carComponent.Download().then(data =>{
  console.log(data);
  // here it is undefined... 
 }).catch(error =>{
   console.log(error)
 });

  }

Thank you

Module not found: Error: Can’t resolve ‘core-js/modules/es.error.cause.js’

I am using Vuexy Dashboard in my project, Vuexy comes in with Vue 2, so I am trying to upgrade it to Vue 3, after fixing some errors, I’m stuck on this one, any help is much appreciated.
Thank you.
This is my package.json file :

 {
  "name": "vuexy-vuejs-react-html-laravel-admin-dashboard-template",
  "version": "6.4.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve --skip-plugins @vue/cli-plugin-eslint",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "@casl/ability": "4.1.6",
    "@casl/vue": "1.1.1",
    "@vue/cli-plugin-eslint": "^5.0.4",
    "@vue/compat": "^3.1.0-0",
    "@vue/composition-api": "^1.6.1",
    "@vueuse/core": "4.0.0",
    "animate.css": "4.1.1",
    "apexcharts": "^3.35.2",
    "assert": "^2.0.0",
    "axios": "^0.27.2",
    "axios-mock-adapter": "1.19.0",
    "bootstrap": "4.6.0",
    "bootstrap-vue": "2.21.1",
    "buffer": "^6.0.3",
    "chart.js": "2.9.4",
    "core-js": "3.8.1",
    "echarts": "4.8.0",
    "jsonwebtoken": "8.5.1",
    "leaflet": "1.6.0",
    "portal-vue": "2.1.7",
    "postcss-rtl": "1.7.3",
    "prismjs": "^1.28.0",
    "stream": "0.0.2",
    "swiper": "5.4.5",
    "uuid": "8.3.2",
    "vue-perfect-scrollbar": "0.2.1",
    "vue-prism-component": "1.1.1",
    "vue-quill-editor": "3.0.6",
    "vue-ripple-directive": "2.0.1",
    "vue-router": "3.4.9",
    "vue-select": "3.11.2",
    "vue-slider-component": "3.2.11",
    "vue-sweetalert2": "4.1.1",
    "vue-toastification": "1.7.8",
    "vue-tour": "1.5.0",
    "vue-tree-halower": "1.8.3",
    "vue2-leaflet": "2.5.2",
    "vuedraggable": "2.24.3",
    "vuex": "3.6.0"
  },
  "devDependencies": {
    "@babel/core": "^7.12.16",
    "@babel/eslint-parser": "^7.12.16",
    "@vue/cli-plugin-babel": "^5.0.4",
    "@vue/cli-plugin-router": "^5.0.4",
    "@vue/cli-plugin-vuex": "^5.0.4",
    "@vue/cli-service": "^5.0.4",
    "@vue/compiler-sfc": "^3.1.0-0",
    "@vue/eslint-config-airbnb": "^6.0.0",
    "@vuepress/plugin-medium-zoom": "^1.7.1",
    "eslint": "^7.32.0",
    "eslint-plugin-import": "^2.25.3",
    "eslint-plugin-vue": "^8.0.3",
    "eslint-plugin-vuejs-accessibility": "^1.1.1",
    "sass": "1.32.*",
    "sass-loader": "^10.1.0"
  }
}

And these are the errors I’m getting while running npm run serve :

    ERROR in ./node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js 1:0-43
Module not found: Error: Can't resolve 'core-js/modules/es.error.cause.js' in 'Desktopconsigliere-vue-laravele-commercefrontendnode_modules@babelruntimehelpersesm'

Passing an image from php to poastman (API)

Im tying to get my php to post an image, when I call it to postman but it keep sending a small white box. When I use the link that I got from an public API I get the image in postman.enter image description here

<?php
header("Accept-Ranges: bytes ");
header("Content-Type: image/jpeg");

include_once '../config/database.php';
include_once '../class/employees.php';

$get_data = callAPI('GET', 'https://awsbucketmemeapi.s3.ap-south-1.amazonaws.com/meme_api_prod/memes/173.jp
g?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIA2NSQQQNQTUD3QVEW%2F20220522%2Fap-south-1%2Fs3%2Faws4_request&X-
Amz-Date=20220522T205808Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=6d58ecb3f33729c3f7
7642d21b94b5cb8e81afdfa9e868dfcf411c8642cda7dd', false);
echo $get_data;

In ViewModel binds value with another

I’m using Kendo JQuery with MVVM.

I would like to automatically change the value of the a variable (“label”) when another variable changes (“optionId”).

This is my VieModel:

  var vm = kendo.observable({
    optionId: '',
    label: ( this.optionId == 'Spaghetti' ? "Pasta selected" : "Animal selected" ),

    setOption: function( event ) {

      var value = event.currentTarget.value;

      this.set("optionId", value );
      //this.set("label", this.optionId == 'Spaghetti' ? "Pasta selected" : "Animal" );

    }
  });

If I remove the commented line, it works. But that’s not what I want because I would have to add that line in every method.

I thought I could write:

label: ( this.get("optionId") == etc... )

but I can’t. I believe this would work.

Here is an example on Kendo Dojo.

https://dojo.telerik.com/agewIWAk

Many thanks.

checking array if has same value

Learning by coding, here i have an array of objects (data), and nodeId which is number , i want to check if that arrays ‘target’ has same value as nodeId then ‘return’, should i use map(), find(), filter(), how should i know which to use ?
english is not my mother language so could be mistakes

data:

  const Test = '7'
const nodeId = parseInt(Test);

  
  const data = [
    { target: 4, name: "usa" },
    { target: 7, name: "England" },
    { target: 3, name: "Japan" }
  ];
  
  
   if (check if data and nodeId both have same value then) {
    return;
  }

error Undefined variable: mysqli on line 10 Trying to get property ‘error’ of non-object in online10

<?php
include("../conexao/conexao.php");
date_default_timezone_set('America/Sao_Paulo');
$data = date('d/m/Y');
$documento = '9999' . $data;
$consulta = "SELECT produto.descricao, estoque.entrada,estoque.saida FROM
estoque,produto WHERE estoque.documento='$documento' and
estoque.id_produto=produto.id";

<!-- problema bem aqui

$con = @mysqli_query($conexao, $consulta) or die($mysqli->error);

function listarProdutos($conexao)
{
 $listadeprodutos = array();
 $resultado = mysqli_query($conexao, "select * from produto order by 
descricao");
 while ($produto = mysqli_fetch_assoc($resultado)) {
 array_push($listadeprodutos, $produto);
 }
 return $listadeprodutos;
}
$listadeproduto = listarProdutos($conexao);
?>

<!DOCTYPE html>
<html>
<head>
 <title>Estoque</title>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <link href="css/bootstrap.css" rel="stylesheet" type="text/css" />
</head>
<body>
 <h2>
 <p align="center"> Acerto de Estoque
 </h2>
 <br>
 <form method="post" action="..negociocad_itens_estoque.php">
 <div class="form-row">
 <div class="form-group col-md-6">
 Código<input class="form-control" type="text"
name="txtcod" value="<?php echo $documento ?>" readonly>
</div>
<div class=" form-group col-md-6">
 Descriçao <input class="form-control" type="text"
name="txtdesc" value="Acerto de Estoque" readonly>
 </div>
 <div class="form-group col-md-3">
 Produto<select class="form-control" name="txtprod">
 <?php foreach ($listadeproduto as $produ) { ?>
 <option value="<?php echo $produ['id'] ?>"><?php echo
utf8_encode($produ['descricao']) ?></option>
 <?php } ?>
 </select>
 </div>
 <div class="form-group col-md-3">
 Quantidade de Entrada <input class="form-control"
type="text" name="txtent" value="0">
 </div>
 <div class="form-group col-md-3">
 Quantidade de Saída <input class="form-control"
type="text" name="txtsai" value="0">
 </div>
 <div class="form-group col-md-3">
 <br>
 <input type="submit" name="btncal" class="btn btn-primary 
btn-alterar" role="button"
 class="glyphicon glyphicon-pencil" value="Adicionar">
 </div>
 </div>
 <br>
 <br>
 <div class=" form-group col-md-4" style="text-align:center"> <a
class="form-control"
 style="background-color: cyan;">
 <b> Descrição do Produto </b></a>
 </div>
 <div class=" form-group col-md-4" style="text-align:center">
 <a class="form-control" style="background-color: cyan;">
 <b>Quantidade de Entrada</b> </a>
 </div>
 <div class=" form-group col-md-4" style="text-align:center">
 <a class="form-control" style="background-color: cyan;">
 <b>Quantidade de Saida</b> </a>
 </div> <?php while ($dado = $con->fetch_array()) { ?>
 <div class=" form-group col-md-4">
 <input class="form-control" readonly type="text"
name="txtdescri" value=<?php echo utf8_encode($dado['descricao']); ?>>
 </div>
 <div class="form-group col-md-4">
 <input class="form-control" readonly type="text"
name="txtentr" value=<?php echo $dado['entrada']; ?>>
 </div>
 <div class="form-group col-md-4">
 <input class="form-control" readonly type="text"
name="txtsaida" value=<?php echo $dado['saida']; ?>>
 </div>
 <?php } ?>
 <br>
 <br>
 <input type="button" value="Finalizar" class="btn btn-danger btnexcluir" role="button"
 class="glyphicon glyphicon-trash" onclick="javascript: 
location.href='index.php';" />
</div>
 </form>
</body>
</html>

React Native and Expo-Google authentication using the “expo-google-sign-in” library failing

I am working on an app that uses google authentication. On the login screen of the app(my first screen), there is a bold button labeled “Sign in With Google”. When I click the button, nothing was happening. So, I check the console in Chrome and it says the following error message: “Please provide the appropriate client ID. See the documentation for more details https://docs.expo.io/versions/latest/sdk/google/#loginasync”(P.S. this link is outdated)
This is my entire code in Github: https://github.com/hypercoder457/storytellingapp-broken

In order to reproduce the error you need to:

  1. Download the code from GitHub/unzip/extract it on your computer
  2. In terminal, go to that folder & run “npm install”
  3. Then run the command “expo start:web –https”(MAKE SURE TO INSTALL FIREFOX FOR THIS TO WORK)
  4. Navigate in browser to “https://localhost:19006
  5. As you will see very soon, if you click the “SIGN IN WITH GOOGLE” button on the main screen, then check the Chrome console/developer tools, it will say the error message mentioned above

Javascript elements.contains Uncaught TypeError: Failed to execute ‘contains’ on ‘Node’

I’m trying to add and remove classes to drop_container, but I can’t. I am getting the following error in the JsFiddle console: Uncaught TypeError: Failed to execute ‘contains’ on ‘Node’: parameter 1 is not of type ‘Node’.

This is my project: link https://jsfiddle.net/Snorlax93x/cd3rhx7y/

I don’t want to use element.classList.toggle because later I would like to be able to work on css animations with show and hide.

Alternatively, if it can also be done with toggle then it would be good for me. Can anyone help me figure out what I’m doing wrong?

var dropdownBtn = document.querySelectorAll('.menu-btn');
lastOpened = null; //Add this for toggling dropdown

dropdownBtn.forEach(btn => btn.addEventListener('click', function() {
 var menuContent = this.nextElementSibling;
 if (!menuContent.contains("show")) {
    menuContent.classList.add("show");
 }  else {
    menuContent.classList.add("hide");
    menuContent.classList.remove("show");
    }

 //Add this for toggling dropdown
 if (lastOpened && lastOpened !== menuContent) {
     lastOpened.classList.remove("show");
     lastOpened = menuContent;
 }    
}));

Alternatively my code works this way, but the show class is simply added or removed. While I am trying to show the hide class when show is removed.

var dropdownBtn = document.querySelectorAll('.menu-btn');
lastOpened = null; //Add this for toggling dropdown

dropdownBtn.forEach(btn => btn.addEventListener('click', function() {
  var menuContent = this.nextElementSibling;
  menuContent.classList.toggle("show");

  //Add this for toggling dropdown
  if (lastOpened && lastOpened !== menuContent) 
      lastOpened.classList.remove("show");
      lastOpened = menuContent;
}));

Gm Script to click a radio button only highlights it, doesnt click it

I have a questionnaire (Yes/No questions) on a webpage that I need to create a grease-monkey script for, which will auto-select all “Yes” options (radio buttons with value yes in the page). I created the below script, but when I click the button it only highlights the “yes” option but does not actually click/select it.

Below is the code, which I believe is pretty straightforward. What could be wrong here:

var input=document.createElement("input");
input.type="button";
input.value="GreaseMonkey Button";
input.onclick = showAlert;
document.body.appendChild(input);

function showAlert()
{
    var btns = document.querySelectorAll('input[type="radio"]')
        for(var i=0;i<btns.length;i++){
           if(btns[i].value=="Yes"){
            btns[i].checked=true;
        }
    }
}

Extracting numbers from a string not working in production

I am having an issue with extracting a number from a string in react. The solution I used works fine on the local machine but doesn’t work as required when push into production. I tried on netlify and heroku but getting same result.

I fetch the data from a text file which has a list of content and further detail for each of the heading. Link to the text file is here: Link to text file from where I am fetching the data

For example:

  1. Game Concepts 100. General 101. The Magic Golden Rules
  2. Parts of a Card 200. General 201. Name
  3. Card Types 300. General 301. Artifacts

So, I am separating the main headings i.e. 1. Game Concept, 2. Parts of a Card, 3. Card Types and subheadings i.e. 100. General, 101. The Magic Golden Rules, 200. General, 201. Name, 300. General, 301. Artifacts etc… from that text file.

As I mentioned earlier, the method I tried works fine on local machine but as soon as I push the code to production I get the list as it was earlier + the new list that is separated. I tried this as well:

parseFloat([heading]) + "." < 5 , parseFloat([heading]) < 5

…but didn’t get desired results.

I have no idea what to do, I shall be grateful for getting some help on this issue.

Below is App.js:

import { useState, useEffect } from "react";
import url from "./MagicRules.txt";
import "./App.css";

function App() {
  let tempdata = [];
  let dataSplit = [];
  let headings = [];

  const [newdata, setNewData] = useState([]);
  useEffect(() => {
    temp();
    // eslint-disable-next-line
  }, [0]);
  const temp = async () => {
    tempdata = await (await fetch(url, { mode: "no-cors" })).text();
    dataSplit = tempdata
      .split(/^s+|s+$/gm)
      .filter((element) => isNaN(element));
    dataSplit = dataSplit.slice(0, dataSplit.lastIndexOf("Glossary"));
    headings = dataSplit.filter((heading) => parseInt([heading]) + "." < 5);
    let newHeadings = [...new Set(headings)];
    setNewData(newHeadings);
  };
  return (
    <div className="App">
      {newdata.map((heading, index) => (
        <ul key={index}>{heading}</ul>
      ))}
    </div>
  );
}

export default App;

This is in production

This is what I get on local machine i.e. localhost:3000 and this is the result I want

Why does JavaScript render data from the useEffect() hook but fails to render the data when put in the function body?

I have a JSON file called teams.json that contains the basic structure (“name”, “age”, “country”, “role”, “team”, and “image”) in an object. I’m using React to use the function fetch() to retrieve the data from the local JSON file. When I call the useEffect (shown below) hook, the data is retrieved from the local JSON file and I’m able call a useState function to store the data in a state variable called data.

useEffect() function call

//file path
filePath = "/src/public/teams.json"
const getData = (file) => {
   fetch(file)
   .then(res => res.json())
   .then(data => setData(data))
   .catch(err => console.log("Error fetching data", err)
}
  
useEffect(() => {
   getData(filePath)
}, [filePath])

If I try to edit or access data within the useEffect() hook, the data is able to be retrieved without any problems, as such.

.then(data => console.log(data[0]))

This returns a json object that contains the necessary information.

{
  "name":"R",
  "image":"https://example.com",
  "team":"B",
  "role":"WB",
  "country":"American",
  "age":18
}

However, in the main body of my react App, if I try to obtain data from the data state, it gives me an error saying Cannot read properties of undefined, shown below.

Body of React App

return (
   <main>
      {data[0].country}
    </main>
  )

But I get this error:

Error Screenshot

I’ve tried solutions to previous forums from:

Stack Overflow Discussion Axios

Stack Overflow Discussion Error Axios

I’ve moved my project to the structure:

-src
--public
*some files*

and put the JSON file in the public folder. It reads it now but still doesn’t render. I’ve also tried using axios but to no avail.

If this is an easy fix, sorry about that! Thanks for your help!