p5js clipping mask equivalent?

I have a super simple script that creates a circle with alternating “slice” colors

let slices = 12;


function setup() {
  createCanvas(400, 400);
  noStroke();
}

function draw() {
  background(220);
  translate(width/2, height/2);
  
  let inc = TWO_PI/slices;
  let c = 0
  for (let i = 0; i < TWO_PI+inc; i+=inc) {
    if (c % 2 == 0) {
      fill('white')
    } else {
      fill('black')
    }
    arc(0, 0, width/2, width/2, i, i+inc);
    c++
  } 
}

How can I do this same thing but with a square? That is, I want the alternating slice colors but encapsulated in a square rather than a circle. I am not sure how to do this since I used arc() to create the slices. Is there some way I can create a mask or something? Or is there an easy solution to my problem?

How to make mock api axios call in test?

Hello I am new to testing and I am following this client’s testing protocol where they make an axios.post request to a localhost end point (they start up a separate express server during test script)

describe("Arrived For Delivery", () => {
it("POST /courier/arrivedForDelivery should return success", async () => {
    const res = await axios.post(
        `http://localhost:8888/courier/arrivedForDelivery`,
        { order_id: "MOCK" },
        {
            params: {
                authentication: mockAuth,
            },
        }
    );
    // Assertion
    expect(res.data).to.be.equal("success");
});

it("POST /courier/arrivedForDelivery should return error data", async () => {
    // Arrange
    const stubProviderStorage = stub(ProviderStorage, "GetProviderByID");
    stubProviderStorage.throws({ message: "test" });

    try {
        // Act
        await axios.post(
            `http://localhost:8888/courier/arrivedForDelivery`,
            { order_id: "MOCK" },
            {
                params: {
                    authentication: mockAuth,
                },
            }
        );

        // Assert
        expect.fail();
    } catch (error) {
        expect((error as AxiosError).response?.data).to.be.eqls({
            code: 400,
            message: "arrivedForDelivery Error test",
        });
    }
    stubProviderStorage.restore();
});

});

is it possible to use sinon to make a mock api call and define what the response should be? because my senior dev from another company is telling me that i shouldnt be making real axios requests in an unit test nor i should make requests outside the code base.
any suggestions?

Object with nested array to filter, want to return entire object with new filtered array

I’m attempting to remove an object out of an array nested within my movie object and then copy it to a new variable. So my original object looks like this:

{
    "id": 1,
    "title": "Avatar",
    "movieLength": 162,
    "releaseDate": "2009-12-18",
    "trailerUrl": "https://www.youtube.com/watch?v=5PSNL1qE6VY",
    "genre": {
        "id": 1,
        "genre": "Action"
    },
    "rating": {
        "id": 3,
        "rating": "PG-13"
    },
    "director": {
        "id": 1,
        "lastName": "Cameron",
        "firstName": "James"
    },
    "actors": [
        {
            "id": 2,
            "lastName": "Worthington",
            "firstName": "Sam"
        },
        {
            "id": 3,
            "lastName": "Weaver",
            "firstName": "Sigourney"
        },
        {
            "id": 4,
            "lastName": "Saldana",
            "firstName": "Zoe"
        }
    ],
    "comments": []
}

and what I’m doing right now is

const updatedMovie = const updatedMovie = movie.actors.filter((actor) => actor.id !== id);

but as you know that only returns the array of actors I filtered. I want to copy the entire object with the newly filtered actors so the object will come out like this (removing actor id 3):

{
    "id": 1,
    "title": "Avatar",
    "movieLength": 162,
    "releaseDate": "2009-12-18",
    "trailerUrl": "https://www.youtube.com/watch?v=5PSNL1qE6VY",
    "genre": {
        "id": 1,
        "genre": "Action"
    },
    "rating": {
        "id": 3,
        "rating": "PG-13"
    },
    "director": {
        "id": 1,
        "lastName": "Cameron",
        "firstName": "James"
    },
    "actors": [
        {
            "id": 2,
            "lastName": "Worthington",
            "firstName": "Sam"
        },
        {
            "id": 4,
            "lastName": "Saldana",
            "firstName": "Zoe"
        }
    ],
    "comments": []
}

I’ve tried reading around but I’m not having any luck getting any solutions to work with me, so if anyone can help or point me in the right direction that would be great!

How can I make a regular expresion that verify if a opening parenthesis has its closing parenthesis?

I’ve got a question. I have this regular expresion:

const r = /((B[(])*(w)+(b[)])*(s)*)+/g;

But lets suppose that we have the string :

ball (doll) (bicycle

So we wanna verify if every opening parenthesis has its closing parenthesis, then I wanna that this string returns me a false value, because the substring “(bicycle” hasn’t its closing parenthesis.

What can I do to create a pattern with regexp that verifies this? THANKS!! 😀

element onclick in class never called

I have a simple class.

The problem im having is that my onClick function is never called when clicking on the div element.

class card {
  constructor(parent, element) {
    this.parent = parent;
    this.element = element;

    this.element.on({
      'click': $.proxy(this.onClick, this)
    });
  }

  onClick() {
    console.log("onclick");
  }

}

class cards {
  constructor() {
    this.element = $(".cards");
    this.cards = [];

    this.element.children(".card").each((obj) => {
      this.cards.push(new card(this, $(obj)));
    });

  }
}

var my_a = new cards();

how to convert Array object to table javascript?

I have the following array of objects, and I need to display it in a table as shown in the screenshot:

This is the object:

[
    {
        "dayText": "Viernes",
        "monthText": "Diciembre",
        "date": "2021-12-10T15:26:55.273Z",
        "start": "08:00",
        "end": "08:30",
        "scheduled": true
    },
    {
        "dayText": "Viernes",
        "monthText": "Diciembre",
        "date": "2021-12-10T15:26:55.273Z",
        "start": "09:00",
        "end": "09:30",
        "scheduled": false
    },
    {
        "dayText": "Sábado",
        "monthText": "Diciembre",
        "date": "2021-12-11T15:26:55.273Z",
        "start": "08:00",
        "end": "08:15",
        "scheduled": false
    },
    {
        "dayText": "Sábado",
        "monthText": "Diciembre",
        "date": "2021-12-11T15:26:55.273Z",
        "start": "08:15",
        "end": "08:30",
        "scheduled": false
    },
    {
        "dayText": "Sábado",
        "monthText": "Diciembre",
        "date": "2021-12-11T15:26:55.273Z",
        "start": "08:30",
        "end": "08:45",
        "scheduled": false
    },

    {
        "dayText": "Domingo",
        "monthText": "Diciembre",
        "date": "2021-12-12T15:26:55.273Z",
        "start": "08:00",
        "end": "08:30",
        "scheduled": false
    },
    {
        "dayText": "Domingo",
        "monthText": "Diciembre",
        "date": "2021-12-12T15:26:55.273Z",
        "start": "09:00",
        "end": "09:30",
        "scheduled": true
    },
    {
        "dayText": "Domingo",
        "monthText": "Diciembre",
        "date": "2021-12-12T15:26:55.273Z",
        "start": "10:30",
        "end": "11:00",
        "scheduled": true
    },
    {
        "dayText": "Domingo",
        "monthText": "Diciembre",
        "date": "2021-12-12T15:26:55.273Z",
        "start": "11:00",
        "end": "11:30",
        "scheduled": false
    },
    {
        "dayText": "Domingo",
        "monthText": "Diciembre",
        "date": "2021-12-12T15:26:55.273Z",
        "start": "11:30",
        "end": "12:00",
        "scheduled": false
    },

    {
        "dayText": "Lunes",
        "monthText": "Diciembre",
        "date": "2021-12-13T15:26:55.273Z",
        "start": "10:30",
        "end": "11:00",
        "scheduled": false
    },
    {
        "dayText": "Lunes",
        "monthText": "Diciembre",
        "date": "2021-12-13T15:26:55.273Z",
        "start": "11:00",
        "end": "11:30",
        "scheduled": false
    },
    {
        "dayText": "Lunes",
        "monthText": "Diciembre",
        "date": "2021-12-13T15:26:55.273Z",
        "start": "11:30",
        "end": "12:00",
        "scheduled": false
    }
]

This is how it should look like:
enter image description here

I am getting: ReferenceError: jsonObject is not defined in my console when using fetch to test POST submission form data to a test API endpoint

I am just beginning to learn javascript and am hung up on getting my code to POST submission data to a test api endpoint. My console is telling me ReferenceError: jsonObject is not defined. Please help, thanks

<form id="jobData" method="post">
    <fieldset>
        <label for="machineField">Heavy Equipment Machine Type</label>
        <input name="Machine" type="text"" id="machineField">
        </input>
        <label for="workField">Work To Be Performed</label>
        <input type="text"  name="work" id="workField">
        <label for="detailsField">Other Important Details</label>
        <textarea name="details" id="detialsField" cols="30" rows="10"></textarea>
        <button type="submit" name="submit">SEND</button>
    </fieldset>
</form>
<script>
    const url = "https://6fp4lq4r8d.api.quickmocker.com";
    const formEl = document.querySelector("form");
    formEl.addEventListener("submit", async (e) => {
      e.preventDefault();
      const formData = new FormData(formEl);
      const formDataSerialized = Object.fromEntries(formData);
      console.log(formDataSerialized, "formDataSerialized");
      try {
          const response = await fetch(url, {
              method: 'POST',
              body: JSON.stringify(jsonObject),
              headers: {
                  'Content-Type': 'application/jason'
              }
          });
          const json = await response.json();
          console.log(json);
      } catch(e){
          console.error(e);
          alert("An Error Occured");
      }
    });
</script>

Webpack on the backend: missing exports

I’m trying to use webpack on the backend to transpile this code (called sub.js):

export const foo1 = () => {
  console.log("I'm foo1");
};

console.log('loaded');

I can compile it and then import it fine. On import (require) I see the ‘loaded’, but the imported object is empty and in particular has no function foo1.

This is my webpack.config.js:

const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry: `./sub.js`,
  module: {
    rules: [{
      test: /.(js|jsx)$/,
      exclude: /node_modules/,
      loader: 'babel-loader',
      options: {
        plugins: [
          '@babel/plugin-proposal-class-properties'
        ]
      },
    }],
  },
  resolve: {
    extensions: ['*', '.js', '.jsx'],
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'backend.js'
  },
  mode: 'production',
};

My package.json:

{
  "name": "sub",
  "version": "1.0.0",
  "description": "",
  "main": "dist/backend.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.13.8",
    "@babel/plugin-proposal-class-properties": "^7.13.0",
    "@babel/preset-env": "^7.13.9",
    "@babel/preset-react": "^7.12.10",
    "babel-loader": "^8.2.2",
    "webpack": "^5.65.0",
    "webpack-cli": "^4.9.1"
  }
}

I test using:

> npx webpack && node --eval "r = require('./dist/backend.js'); console.log(r);"
asset backend.js 45 bytes [emitted] [minimized] (name: main)
runtime modules 396 bytes 2 modules
./sub.js 204 bytes [built] [code generated]
webpack 5.65.0 compiled successfully in 250 ms
loaded
{}

I was expecting to see:

loaded
{foo1: [Function]}

or similar.

RegEx Character set with conditional

I’m trying to do the next:

/b[abcd(e|f)]{5}b/g

Then, should be equivalente to:

/b([abcde]{5}|[abcdf]{5})b/g

But, actually, considering the parenthesis part of the set.

My input is letters with no order:

abedg cbade cfead acbdf

Should return: cbade acbdf, but it also return cfead. But cannot be e and f at the same time

Why does one function cause component to rerender but the other does not Nextjs?

In my Nextjs web application, one of my pages has two functions that allow for emails to be added or removed from an array using nextjs’s useState().

const [invites, setInvites] = useState([])
// other code
const lmao = () => {
    console.log(invites)
}
const addEmail = async (email) => {
    if(!invites.includes(email)) {
        setInvites([...invites, email])

    }
    lmao()
}
const removeEmail = async (email) => {
    let tempArray = invites
    const index = tempArray.indexOf(email)
    if(index > -1) {
        tempArray.splice(index, 1)
    }
    setInvites(tempArray)
    lmao()
}

The function addEmail successfully results in a component rerender, and when ran, will visibly update the page with the added email. However, the function removeEmail fails to rerender the page. I used the function lmao() to see that invites was indeed being changed as needed, the page just was not rerendering to display the change.

I have also looked at Why does setState([…arr]) cause a rerender but setState(arr) does not?, and it does not answer my question because in my case, the item passed into the mutator is not === to its previous value, unless I am missing something. Does anyone know why this is?

What is the unit of x and y in canvasrendering2d.moveTo() in canvas of html5?

everyone. I made a different sizes canvas and drew a line with the same values for moveTo() and lineTo() but I get different sized lines.

This is the code.

    function testCanvas(height, width){
    canvas = document.createElement("canvas");
    ctx = canvas.getContext('2d');

    canvas.style.display = "inline-block";
    canvas.style.border = "1px solid black";

    canvas.height = height;
    canvas.width = width;

    document.getElementById("chartContainer").appendChild(canvas);
    }

    function drawLine(x1, y1, x2, y2){
    ctx.beginPath();
    ctx.moveTo(x1,y1);
    ctx.lineTo(x2,y2);
    
    ctx.stroke();
    }
  1. When i go to inspect element > console and call:

     testCanvas(300,300);
     drawLine(10,50,110,50);
    

and

    testCanvas(150,150);
    drawLine(10,50,110,50);

The length of lines is not equal.
Now, if the input for moveTo and lineTo were in pixel unit, these lines would have same length isnt is? What is the default unit here?

How do you make an alert from API become text on a webpage?

I have it set up so you have a list of countries and when you click on it it gives a pop-up with the sub region and then shows the country flag next to the country. How can I change it so that the sub region shows up with the flags using my API?

var xhttp = new XMLHttpRequest();
var respJSON = [];
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    resp = this.responseText;
    respJSON = JSON.parse(resp);

    html = document.getElementById("list");
    html.innerHTML = "";

    for (var i = 0; i < respJSON.length; i++) {
      html.innerHTML += "<li id=" + i + " onClick='clickMe(" + i + ")'>" + respJSON[i].name + "</li>"
    }
  }
}
//connect our api
xhttp.open("GET", "https://restcountries.com/v2/all", true);
xhttp.send();

function clickMe(index) {
  li = document.getElementById(index);
  img = document.createElement("img")
  img.src = respJSON[index].flag;
  li.append(img); 
  {
    //create subregion text on website
    //unsure how to make it show as text and not as a pop-up
    alert(respJSON[index].subregion);
  }
}

cant create a new Database in Firebase

Hey Guys I really need your help its my first software project and Im a bloody beginner.

My Problem is that I cant create a new Database in Firebase I created a Database called User to store Profildata which works but now I need another to store something else heres my Code I cant find the mistake.

Everything is working but it dont creates the database on backend.
And I nearly used the same code which I used for the first Database.

function Waffen(){

  const [open, setOpen] = React.useState(false);
  const handleClose = () => setOpen(false);
  const handleOpen = () => setOpen(true);

  const [Hersteller, setHersteller] = useState(['Baretta', 
  'Walther']);
  const [Modell, setModell] = useState();
  const [Kaliber, setKaliber] = useState();
  const history = useHistory("");
  const [data] = useState({loading: false,});
  const { loading } = data;
  
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    await setDoc(doc(db, 'Waffen' ,auth.currentUser.uid),  
    
    { Hersteller: Hersteller, Modell: Modell, Kaliber: Kaliber 
    });
  
      setOpen(false)
      history.replace("/Profil");
    }; 
  




 return (
    <div >
      <Button onClick={handleOpen}>Meine Waffen</Button>
        <Modal 
          open={open}
          onClose={handleClose}>
          <Box sx={style} >
            <form  >

        <Grid
         container
         justifyContent="center"
         alignItems="center"
         spacing={2}
        >     
         
         <Autocomplete
            disablePortal
            id="combo-box-demo"
            options={Hersteller}
            sx={{ width: 300 }}
            renderInput={(params) =>  

      <TextField {...params}  label='Hersteller'
          value={Hersteller}  onChange={event => 
          setHersteller(event.target.value)}
      />}
      />
          

          <Grid item>
             <TextField sx={{ width: 300}} variant="outlined" 
               color="secondary" label="Modell" type="text"
               name="Modell" value={Modell} onChange={event => 
               setModell(event.target.value)}>
             </TextField>
          </Grid>

          <Grid item >
              <TextField sx={{ width: 300}} variant="outlined" 
               color="secondary" label="Kaliber" type="text"
               name="Kaliber" value={Kaliber} onChange={event => 
               setKaliber(event.target.value)}>
              </TextField>
          </Grid>
          
           <Grid item>
              <button onSubmit={handleSubmit} 
                  className="AnmeldenButton" >
                  {loading ? "Bearbeitet ..." : "Speichern"}
              </button>
          </Grid>

        </Grid>

           </form>
         </Box>
      </Modal>
    </div>

  ) ;
  }

  export default Waffen;

Vue warn unhandled error during execution of render function, of scheduler flush, and violation scroll-blocking

I’ve tried to figure out what is happening with this one particular page I have as I get a list of warnings and an error every time I load it

[Vue warn]: Unhandled error during execution of render function 
  at <MovieDetails id="5" onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > > 
  at <RouterView> 
  at <App>


[Vue warn]: Unhandled error during execution of scheduler flush. This is likely a Vue internals bug. Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue-next 
  at <MovieDetails id="5" onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > > 
  at <RouterView> 
  at <App>

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'rating')
    at Proxy.render (MovieDetails.vue?e6ee:14)
    at renderComponentRoot (runtime-core.esm-bundler.js?5c40:444)
    at ReactiveEffect.componentUpdateFn [as fn] (runtime-core.esm-bundler.js?5c40:4211)
    at ReactiveEffect.run (reactivity.esm-bundler.js?a1e9:160)
    at setupRenderEffect (runtime-core.esm-bundler.js?5c40:4337)
    at mountComponent (runtime-core.esm-bundler.js?5c40:4120)
    at processComponent (runtime-core.esm-bundler.js?5c40:4078)
    at patch (runtime-core.esm-bundler.js?5c40:3673)
    at ReactiveEffect.componentUpdateFn [as fn] (runtime-core.esm-bundler.js?5c40:4288)
    at ReactiveEffect.run (reactivity.esm-bundler.js?a1e9:160)

5[Violation] Added non-passive event listener to a scroll-blocking <some> event. Consider marking event handler as 'passive' to make the page more responsive. See <URL>

[Violation] 'setTimeout' handler took 96ms www-embed-player.js:575 

They all really make no sense to me other than the uncaught (in promise) and even that I’m very unsure about because when the page loads (the rating it says it can’t read displays as it should). Can anyone tell me what the warning mean and if there is a way to fix them? This is the only page of my project that has this issue. I’ll also leave my view here too and if someone might be able to tell my why the rating is throwing the error despite it displaying properly, that would be great!

<template>
  <div class="movie-details">
    <div class="route">
      <h3>
        <router-link to="/movies">
          <span>Movies</span>
        </router-link>
        &emsp;/&emsp;{{ movie.title }}
      </h3>
    </div>

    <div class="flex row">
      <h1>{{ movie.title }} <span class="subtitle">({{ moment(movie.releaseDate).format("YYYY") }})</span></h1>
      <Button title="Edit" @btn-click="editMovie(this.id)" />
    </div>

    <div class="flex flex-info info">
      <span class="details">{{ movie.rating.rating }}</span> |
      <span class="details">{{ movie.movieLength }}</span> |
      <span class="details">{{ movie.genre.genre }}</span> |
      <span class="details">{{ moment(movie.releaseDate).format("D MMMM YYYY") }}</span>
    </div>
    
    <div class="youtube">
      <iframe width="640" height="360" :src="videoEmbed" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
    </div>

    <div class="cast-crew grid">
      <div class="director">
        <h2>Directed By:</h2>
        
        <router-link :to="{name: 'DirectorDetails', params: {id: movie.director.id }}">
          <ListItem>
            {{ movie.director.firstName }} {{ movie.director.lastName }}
          </ListItem>
        </router-link>
      </div>
      <aside class="cast">
        <h2>Actors:</h2>
        <div class="actors grid">
          <div :key="actor.id" class="actor" v-for="actor in movie.actors">
            <router-link :to="{name: 'ActorDetails', params: {id: actor.id}}">
              <ListItem>
                {{ actor.firstName }} {{ actor.lastName }}
              </ListItem>
            </router-link>
          </div>
        </div>
      </aside>
    </div>
  </div>
</template>

<script>
  import moment from "moment";
  import Button from "@/components/Button.vue";
  import ListItem from "@/components/ListItem.vue";

  export default {
    components: {
      Button,
      ListItem,
    },
    props: [
      "id"
    ],
    data() {
      return {
        movie: {},
        moment,
        videoEmbed: "https://www.youtube.com/embed/"
      };
    },
    methods: {
      editMovie(id) {
        this.$router.push({name: "EditMovie", params: { id: id }});
      },
      async fetchMovie(id) {
        const res = await fetch(`api/movies/${id}`);
        const data = await res.json();

        return data;
      }
    },
    async created() {
      this.movie = await this.fetchMovie(this.id);
      
      //eslint-disable-next-line
      const reg = new RegExp('.*?=s*(.*)');
      const split = reg.exec(this.movie.trailerUrl);
      this.videoEmbed += split[1];
    }
  }
</script>

<style scoped>
  h1 {
    font-weight: bold;
  }

  .subtitle {
    font-weight: 400;
    font-size: 1rem;
  }

  .info {
    font-weight: 300;
    letter-spacing: 1px;
  }

  .details {
    margin: 0 0.8rem;
  }

  .details:first-child {
    margin-left: 0;
  }

  .details:last-child {
    margin-right: 0;
  }

  .youtube {
    margin: 1.5rem 0;
    display: flex;
  }

  .youtube iframe {
    justify-self: flex-start;
    border-radius: 8px;
  }

  .cast-crew {
    height: 110%;
  }

  .cast-crew.grid {
    grid-template-columns: auto 75%;
  }

  .cast-crew a {
    font-weight: bold;
    font-size: 1.125rem;
  }

  .director {
    align-self: flex-start;
    text-align: left;
  }

  .cast {
    padding-left: 1.5rem;
    text-align: left;
    border-left: 2px solid #000;
    align-self: flex-start;
  }

  .actors.grid {
    grid-template-rows: repeat(4, 1fr);
    grid-template-columns: auto;
    gap: 0.75rem;
    grid-auto-flow: column;
    justify-content: flex-start;
  }
</style>

Cartesian product of an unknown amount of arrays/objects WITH label identifiers

Alright, I know that there are a few posts about getting the product of an unknown amount arrays with unknown amount of elements –

JavaScript – Generating combinations from n arrays with m elements

Cartesian array based on array of objects in Javascript

To name a few – However, I have a need for a slight twist –

What I would like is a function that can output an Array of serialized objects instead of an Array of Arrays..

for example, if the input of the function were –

scenarioBuilder({ENV: ["QA","UAT"], HOST: ["APP1", "APP2", "APP3"], API: ["Example1", "Example2"]})

The output would be an array of serialized objects like this –

[{ENV: "QA", HOST: "APP1", API: "Example1"}, 
{ENV: "UAT", HOST: "APP1", API: "Example1"},
{ENV: "QA", HOST: "APP2", API: "Example1"},
{ENV: "UAT", HOST: "APP2", API: "Example1"},
{ENV: "QA", HOST: "APP3", API: "Example1"},
{ENV: "UAT", HOST: "APP3", API: "Example1"}]

etc. etc. etc.

Essentially taking the Array of ENV, HOSTS, AND API’s – and making a serialized scenario builder.

I’ve tried a few cracks at adapting a few of the methods from the above links, but I have had no luck.

Can anyone take a shot at it?

Thank you as always.