Is there a way to have 2 separate sprites in canvas, one mirrored, one not?

So I’m making a game in javascript canvas. I’m using the context.scale(-1, 1) function, called within a method of my Sprite class that updates the image every frame to draw the mirrored image. I’m setting the scale back to (1,1) when I draw the non-flipped sprite. The problem is, the spirite that’s supposed to be flipped is not getting mirrored and it’s constantly flashing, any ideas?

I tried using save() and restore() methods of the context object. Not succesful, same result.

Button have different URL based on condition

I’m beginner in Code. I want to create button that have different url based on condition that user choose.

So for example the button called “Book Now”
I have to package using span: Standard and Premium

My plan is, if user choose “standard” the button will be have “html://blablabla.com/standard
and if user choose “premium” the url will be “html://blablabla.com/premium

I was wondering how it can be possible in html and javascript?

Vue 2 and Vuelidate 2 – Validating a child component from a custom npm component library

I’ve been searching the vuelidate-next (and vuelidate 0.x) documentation, github vuelidate repo (issues), and stackoverflow, but haven’t really found a solution for this issue that I currently have.

Main issue:

  • Vuelidate is not collecting all validation $errors and $silentErrors when used with a child component from a custom npm component library.

Context behind this issue:

  • I am currently building a Vue 2 component library (using the Options API), and using it in another Vue 2 (Options API) project (Parent Vue Project).
  • When the component library is being tested in Jest and or StoryBook, the v$ setup object appears in the Vue inspector tool, and supplies all the usual information as normal (examples posted below).
  • However, when the components are packaged for release via npm, then imported into another vue 2 project; the v$ setup object only returns information for vue 2 project instance, and completely ignores the validation for the library components.
  • All the library components have $autoDirty: true (code example below).
  • The components from the npm library render and function correctly within the Parent Vue Project, except for the validations through Vuelidate.
  • The component library has functioning validation as far as I have tested (Validation works perfectly with both Jest and StoryBook).
  • The components must have the validation rules within the custom npm library, and be validated in a parent wrapper within another project (client has specified this as a requirement, the examples posted below are a simplified representation of the actual code).

The Parent Vue Project code (not component library) looks like this:

<template>
    <div>
        <custom-input-component v-model="textValue"/>
            <span v-if="v$.value.$error" class="field validation-error">
              This field is required
            </span>
    </div>
</template>

<script>
    import { useVuelidate } from '@vuelidate/core';
    import { CustomInputComponent } from '@custom-components-library';
    
    export default{
        props:{...},
        data(){...},
        
          setup () {
            return {
              v$: useVuelidate()
            }
          },
        
        computed:{...}
        methods:{...}
    }
</script>

The npm component library package code looks like this:

<template>
    <div>
        <label for="name">Name: </label>
        <input type="text" :value="value">
    </div>
</template>

<script>
    import { useVuelidate } from '@vuelidate/core';
    import { required } from '@vuelidate/validators';

    export default{
        props:{
            value: {
                type: String,
                default: '',
            }
        },
        setup() {
            return {
              v$: useVuelidate({ $autoDirty: true }),
            };
        },
    
        validations() {
            return {
              value: {required},
            };
        }
  ...
  }
  </script>

v$ validation object in component library ( using Storybook with Vue 2)

v$:Object (Computed)
    $anyDirty:true
    $clearExternalResults:function $clearExternalResults()
    $commit:function $commit()
    $dirty:true
    $error:false
    $errors:Array[0]
    ...
    value:
        $anyDirty:true
        $commit:function $commit()
        $dirty:true
        $error:true
        $errors:Array[1]
        $externalResults:Array[0]
        $invalid:true
        ...
        required:Object

v$ validation object in Parent Vue Project (using Vue 2)

v$:Object (Computed)
    $anyDirty:true
    $clearExternalResults:function
    $clearExternalResults()
    $commit:function $commit()
    $dirty:true
    $error:false
    $errors:Array[0]
    ...

Web browser console errors:

[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading '$error')" 

Component library build config:

{
    "compilerOptions": {
    "target": "es5",
    "module": "esnext"
  }
}

Questions:

  • How can I get the child component to validate in the Parent Vue Project?
  • My suspicion is that there are potentially two vuelidate instances, and the parent vuelidate object doesn’t know about the v$ validation rules in child components?
  • Is there any way to overcome this, and be able to set validation rules within the npm library based components, and validate them within a parent wrapper within another project?

How can I re-declare the same var six times at JavaScript DOM? [closed]

I am trying to select six divs from my HTML and render a chart from https://apexcharts.com/javascript-chart-demos/radialbar-charts/basic/ which uses javascript

let options = {
  series: [70],
  chart: {
    height: 350,
    type: "radialBar",
  },
  plotOptions: {
    radialBar: {
      hollow: {
        size: "70%"
      }
    }
  },
  labels: ["Cricket"]
};

let charts = document.querySelectorAll(".chart");
charts.forEach((chart) => {
  let chartInstance = new ApexCharts(chart, options);
  chartInstance.render();
});
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<div class="chart"></div>
<div class="chart"></div>
<div class="chart"></div>
<div class="chart"></div>
<div class="chart"></div>
<div class="chart"></div>

However, only my first div receives this chart, the other five do not receive and I get it in my console:

Uncaught SyntaxError: Identifier ‘options’ has already been declared (at (index):641:36)

While I hide my password in react-native password freezes to the beginning

const [password, setPassword] = useState('')
const [passwordVisibility, setPasswordVisibility] = useState(false);
<View style={styles.inputContainer}>
          <TextInput
            name="password"
            style={styles.inputField}
            autoCapitalize='none'
            value={password}
            autoCorrect={false}
            textContentType="newPassword"
            onChangeText={onChangeText}
            placeholder="Password"
            enablesReturnKeyAutomatically
            secureTextEntry={passwordVisibility}
          />
          <Pressable onPress={()=>{setPasswordVisibility(!passwordVisibility) , console.log(password)}}>
          <Icon name={passwordVisibility == true ? 'eye' : 'eye-off' } size={23} color='purple' />
          </Pressable>
          
        </View>

Here is my code .While I hide my password in react-native password freezes to the beginning . How can I fix this

Why req.params answers 2 id?

it’s my first Express and MongoDb project and i encountered an issue today.
When i ask req.params it answers 2 id so i can’t search data in mongo db
idk if i made myself clear but here is the code

articleController.js

exports.articlepage = async(req, res) => {
    try {
        let artId = req.params
        console.log(artId)

        res.render('page', { title: `p` } );
    } catch (error) {
        console.log(error)
    }
}

articleRoutes.js

router.get('/article/:id', articleController.articlepage);

and the console answers
{ id: ‘638d07c63bec27224511c7af’ }
{ id: ‘jquery-2.1.1.min.js’ }

hope someone can help, thank you in advance and if you need more of my code you can ask me

I’ve searched about this but wasn’t able to find something truly helpful

TypeError: Cannot read properties of undefined (reading ‘input’), Vue

I’m trying to access a using my API, which works when I try using Postman, from VUE, but for some reason I’m getting the error “TypeError: Cannot read properties of undefined (reading ‘input’)”.

The body when sending the post would be something like this:

POST: http://localhost:8080/api/vendedor/login

{
  "correo": "[email protected]",
  "password": "123456"
}

And the answer from the POST would be a JSON with:

{
  "idvendedor": 5,
  "nombre": "Leonardo",
  "apellido": "Andrade",
  "correo": "[email protected]",
  "password": "123456",
  "lugartrabajo": "Casino Los Notros"
}

The HTML from the login would be like this:

<form class="w-96 mx-auto rounded-md">
            <div class="input">
                <label for="email" class="text-xl font-medium text- flex justify-left py-1">Correo</label>
                <input type="text" name="email" v-model="input.email" placeholder="[email protected]" class="border-2 p-1 w-96 border-violet-700 rounded-full">
            </div>
            <div class="input">
                <label for="password" class="text-xl font-medium text- flex justify-left py-1">Contraseña</label>
                <input type="password" name="password" v-model="input.password" placeholder="***************************" class="border-2 p-1 w-96 border-violet-700 rounded-full">
            </div>
            <div class="pb-5"></div>
            <button type="submit" id="botonlogin" v-on:click.prevent="login()" class="ml-28 h-8 w-36 mx-auto bg-gradient-to-r from-indigo-500 to-indigo-700 rounded-full hover:from-indigo-400 hover:to-indigo-600">
                <span class="text-center text-white font-medium">Iniciar Sesión</span>
            </button>
        </form>

And this is the script in the login:

<script>
import axios from 'axios';

  export default {
    name: 'Login',
    data() {
      return {
        input: {
          email: "",
          password: ""
        },
        vendedor: {
          idvendedor: "",
          nombre: "",
          apellido: "",
          correo: "",
          password: "",
          lugartrabajo: ""
        },
      }
    },
    methods: {
      async login() {
        try{
          let res = await axios.post('http://localhost:8080/api/vendedor/login', this.data.input);
          console.log(res);
          if(this.input.email == this.vendedor.correo && this.input.password == this.vendedor.password){
            this.$router.push('/vendedor/homeVender');
          }
        }catch (e){
          console.log(e)
        }
        
          
      }
    }
  }
</script>

I expected to get the JSON from axios, so that i could make an “if” for the login, but I’m getting the error “TypeError: Cannot read properties of undefined (reading ‘input’)”

Add SuperScript only if fragment id is present in GraphQL query

I am working on a AEM component to dynamically add superscripts based on a graphQL query and I need some help.

Currently the component will add a superscript to any element that has the data-id attribute.

The future state that I am looking to achieve is having the component only add the superscript if the fragment id is present in the graphQL query.

Below is the full code of the component:


document.addEventListener("DOMContentLoaded", function(){
    var myHeaders = new Headers();
        myHeaders.append("Content-Type", "application/json");
        myHeaders.append("Authorization", "Basic YWRtaW46YWRtaW4=");
        myHeaders.append("Cookie", "cq-authoring-mode=TOUCH");

    var requestOptions = {
        method: 'GET',
        headers: myHeaders,
        redirect: 'follow'
    };

    var query = {
        protocol: document.location.protocol,
        host: document.location.host,
        path: "graphql/execute.json/dot-pnc-aem-caas",
        name: "disclosure-by-id",
        paramName: "fragmentId"
    };

    let disclosureDiv = document.getElementById('disclosureComponent'),
        disclosureElement = document.querySelectorAll('span[data-id]'),
        orderedList = document.createElement("ol"),
        disclosureArray = [],
        queryValue,
        footnoteNumber = 1,
        footnoteObject = {},
        supNum,
        url = query.protocol +"//"+ query.host +"/"+ query.path +"/"+ query.name +"%3B"+ query.paramName +"%3D{"_logOp"%3A"OR"%2C"_expressions"%3A[";

    function createDisclosureArray(){    
        for (let i = 0, max=disclosureElement.length; i < max; i++) {
            let fragmentId = disclosureElement[i].dataset.id;
            if(!footnoteObject.hasOwnProperty(fragmentId)){
                footnoteObject[fragmentId] = footnoteNumber;
            }
            supNum = footnoteObject[fragmentId];
            disclosureArray.push({
                fragmentId: fragmentId,
                anchorId: fragmentId,
                superScript: supNum
            });
            anchorTag = document.createElement('a');
            anchorTag.setAttribute('href', '#'+disclosureArray[i].anchorId);
            anchorTag.setAttribute('class', 'disclosureAnchor');
            sup = document.createElement('sup');
            const fragment = document.createDocumentFragment();
            const superScript = fragment
                .appendChild(anchorTag)
                .appendChild(sup);
            superScript.textContent = '['+disclosureArray[i].superScript+']';
            disclosureElement[i].append(fragment);
            footnoteNumber++;
        }
        queryValue = disclosureArray.map(({fragmentId}) => '{"value"%3A"'+fragmentId+'"}').join('%2C');
        url += queryValue + "]}";
        return disclosureArray;
    }

    async function getDisclosures(){
        try{
            let result = await fetch(url, requestOptions);
            if (!result.ok) {
                const message = `An error has occured: ${result.status} - ${result.statusText}`;
                throw new Error(message);
            }
            return await result.json();
        } catch (error){
            console.log(error.message);
            disclosureDiv.append('No disclosures were found.');
        }
    }

    async function updateLegalAccordion(){
        let disclosure = await getDisclosures();
        let disclosureNum = disclosure.data.disclosureList.items;
        for (let i = 0, max = disclosureNum.length; i < max; i++ ){
            let listItem = document.createElement('li');
            listItem.innerHTML = `${disclosureNum[i].copy.html}`;
            listItem.setAttribute('id', disclosureArray[i].anchorId);
            orderedList.appendChild(listItem);
            disclosureDiv.appendChild(orderedList);
        }
    }

    createDisclosureArray();
    updateLegalAccordion();


});  

I have tried creating a new graphQL query in Postman to check if the fragmentId exists so I could base the superscript off that query but I was getting errors in Postman

Turning JSON file into HTML radio quiz

I need to fetch JSON file, sort it’s Question,Possible aswers and then display correct answer but I cant fetch and sort it properly

    <script>
            fetch("quiz.json").then(function (response) {

                response.json()

            }).then(function(quiz){
                for(let i = 0; 1 <quiz.length; i++){
                    document.body.innerHTML += '<h2>' +quiz[i].question + '</h2>';
                    document.body.innerHTML += '<imput type="radio">' +quiz[i].options ;
                    document.body.innerHTML += '<p>' +quiz[i].answer + '</p>';
                }
            })
    </script>

When I try it it says “

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'length')
    at (index):30:40
```"

JSON file : 

{
“quiz”: {
“q1”: {
“question”: “Which one is correct team name in NBA?”,
“options”: [
“New York Bulls”,
“Los Angeles Kings”,
“Golden State Warriros”,
“Huston Rocket”
],
“answer”: “Huston Rocket”
},
“q2”: {
“question”: “‘Namaste’ is a traditional greeting in which Asian language?”,
“options”: [
“Hindi”,
“Mandarin”,
“Nepalese”,
“Thai”
],
“answer”: “Hindi”
},
“q3”: {
“question”: “The Spree river flows through which major European capital city?”,
“options”: [
“Berlin”,
“Paris”,
“Rome”,
“London”
],
“answer”: “Berlin”
},
“q4”: {
“question”: “Which famous artist had both a ‘Rose Period’ and a ‘Blue Period’?”,
“options”: [
“Pablo Picasso”,
“Vincent van Gogh”,
“Salvador Dalí”,
“Edgar Degas”
],
“answer”: “Pablo Picasso”
}
}
}


Also Im using XAMPP and only vanilla js

I want open videos, audios, or images from ZIP js

I have searched in other forums and can’t find any good results.

I tried to load the path of the ZIP file in js, but it doesn’t work for me.

here the code:

function open_file_from_ZIP(path, zip_path, type){

   var zip_path = path+'://'+zip_path;
   var loader = new ZipLoader(path);

   switch (type) {
    case "folder" : 
        $("#folder-manager-table tr").remove(); 
        break;
    case "image" : 
        window.top. open_responsive(); 
        window.top. $("#image-viewer-panel").attr("src", loader.load(zip_path) ); 
        break;
    case "audio" : 
        window.top. $('#audio-player-tag').attr('src', loader.load(zip_path)); 
        window.top. document.getElementById("audio-player-tag").play(); 
        break;
    case "video" : 
        window.top. open_video(); 
        window.top. $('#popup-video-viewer').attr('src', loader.load(zip_path)); 
        window.top. document.getElementById("popup-video-viewer").play(); 
        break;
    }
}

Polygon Generator

I’m trying to generate a polygon with circles inside (JS canvas). Here’s a sample expected output:enter image description here

It’s basically a 4-sided polygon (square) with circles next to the vertices. Here is what I tried:

However, I don’t get the expected outcome.
Note: I want this to work for any sized polygon and not just a square. Also, stopping the draw() function to execute gives me a proper square. I believe there’s a problem in the draw() function. Any help is appreciated 🙂

function draw(x, y, ctx){
    ctx.arc(x, y, 4, 0, Math.PI * 2);
    ctx.fillStyle = "#283149";
    ctx.fill(); // create circle
}
function createPolygon(n){
    const canvas = document.getElementById("canvas");
    const ctx = canvas.getContext('2d');
    ctx.reset();
    var size = 60, Xcenter = 80, Ycenter = 80;
    ctx.beginPath();
    ctx.moveTo (Xcenter +  size * Math.cos(0), Ycenter +  size *  Math.sin(0));          
    
    for (var i = 1; i <= n; i++) {
        ctx.lineTo (Xcenter + size * Math.cos(i * 2 * Math.PI / n), Ycenter + size * Math.sin(i * 2 * Math.PI / n));
        draw(Xcenter + Math.cos(i * 2 * Math.PI / n), Ycenter +  Math.sin(i * 2 * Math.PI / n), ctx);
    }
    ctx.fillStyle = "#00818A"
    ctx.fill();
}
<button onclick="createPolygon(4)">Create 4</button>
<canvas id="canvas"></canvas>

How to show content () as per selection options ()?

I want to show content based on user’s selection from

Like, when user selects the option “Option A” then only show the div containing “Orange”.

HTML:
`

 <div id="main-container">
        <select name="" id="user-selector" class="selector-dropdown">
            <option selected="true" style='display: none'>Select</option>
            <option value="Option A">Fruit</option>
            <option value="Option B">Animal</option>
            <option value="Option C">Language</option>
            <option value="Option C">Stationary</option>
        </select>

        <div class="output">Orange</div>
        <div class="output">Lion</div>
        <div class="output">English</div>
        <div class="output">Pen</div>

    </div>

`

Can you please help me with the JS code?

Thanks in advance.

I have searched in codepens, stackoverflow, and most were using jQuery which i could’nt understand. It really helps if you can help me the JS code.

Variance in Array vs TypedArray performance test

I am comparing the operation of reverse in Typed vs Standard Arrays i.e:

const a = new Array(1e6).fill(0).map( () => Math.random())
a.reverse()
const b = new Float64Array(1e6).map( () => Math.random())
b.reverse()

Certainly we expect Typed to be faster and maybe also to be narrow in variation from the mean time.

However, the standard arrays are slower (expected) but the variation around the mean is very large in comparison. In my computer this shows 3% in TypedArrays, 30% in Arrays.

Conceptually, what is the cause of this ?

See Test

How to limit the search scope without lookbehinds?

Given a regular expression, I can easily decide where to start looking for a match from in a string using lastIndex.
Now, I want to make sure that the match I get doesn’t go past a certain point in the string.

I would happily enclose the regular expression in a non-capturing group and append, for instance, (?<=^.{0,8}).

But how can I achieve the same goal without lookbehinds, that still aren’t globally supported?

Note:

  • While it might be the only reasonable fallback, slicing the string is not a good option as it results in a loss of context for the search.

Example

https://regex101.com/r/7bWtSW/1

with the base regular expression that:

  • matches the letter ‘a’, at least once and as many times as possible
  • as long as an ‘X’ comes later

We can see that we can achieve our goal with a lookbehind: we still get a match, shorter.
However, if we sliced the string, we would lose the match (because the lookahead in the base regular expression would fail).