Typescript error while array filtered on type

I have an array of number | undefineds and I want the max of this array, if any of them is a number. In order to do so I want to filter on the element being of type number, so that I can pass a numbers-only array to Math.max(...array)

(I know I shouldn’t Math.max on an desctructured empty array, so I’ll only do a math.max if there are 1 or more numeric values in the array)

const numbersArray: number[] = [a,b].filter((v) => typeof v === "number");

That works fine in runtime, but I get a typescript error saying that I cant assert numbersArray to be of type number[].

Type 'undefined[]' is not assignable to type 'number[]'.
  Type 'undefined' is not assignable to type 'number'.ts(2322)

What am I doing wrong here?

How to implement field-level complexity in graphql code-first approach?

I ran into such a problem when dealing with query complexity in GraphQL. The package I used is graphql-query-complexity.

App.js:

app.use(
  '/graphql',
  graphqlHTTP((req) => ({
    schema: schema,
    graphiql: true,
    validationRules: [
      createComplexityRule({
        estimators: [
          simpleEstimator({ defaultComplexity: 1 }),
        ],
        maximumComplexity: 20,
        },
      }),
    ]
  }))
);

It works well, but when I looked at other examples on the internet, I saw that they use Field-level complexity there. That is, they can set a different complexity for each field. But can’t understand it because they use TypeGraphQL server, I use express-graphql

Example were:

@Field({ complexity: 3 })
title: string;

But my express-graphql code-first approach code:

const PostTypes: { comment: GraphQLObjectType } = {
  post: new GraphQLObjectType({
    name: 'Post',
    fields: () => ({
      title: { type: graphql.GraphQLString },
    }),
  }),
};

export default PostTypes;

So, how can I implement this for my structure?

How to show div/form when select function executes in javascript?

I need some help on when my FullCalendar Select:function{} exectues I want to my div (form) to show. right now I implemented a alert/prompt to show. But I need help or guide me on what am I doing wrong in my code below. All I need is to show my div when I double click on the calendar, basically replace the prompt to the form. thank you for the help. here is my code.

Javascript snippet:

  select: function(info ) {
        let title = prompt("Event Content:");
        if (title) {
            calendar.addEvent({
                title: title,
                start: info.startStr,
                end: info.endStr
            })
        }
        calendar.unselect();
    },

HTML:

    <div class="modal fade" id="schedule-edit">
    <div class="modal-dialog">
        <div class="modal-content">
            <!-- Modal Header -->
            <div class="modal-header">
                <h4 class="modal-title">Add Task</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <!-- Modal body -->
            <div class="modal-body">
               <form id="event-form">
                    <div class="form-group">
                        <label>Title:</label>
                        <input type="text"  name = "title" id="title" class="form-control">
                    </div>
                        <div class="form-group">
                        <label>Project:</label>
                        <input type="text" id="project" class="form-control">
                    </div>
                        <div class="form-group">
                        <label>Est. Time (hours)</label>
                        <input type="text" id="time" class="form-control" placeholder="(Examples: 3,12.5,5.75")>
                    </div>
                        <div class="form-group">
                        <label>Time Spent (hours)</label>
                        <input type="text" id ="timeSpent" class="form-control" placeholder="(Examples: 3,12.5,5.75")>
                    </div>
                       <div class="form-group">
                        <label>Description</label>
                       <!--Add rich text editor here -->
                               <div class="sample-toolbar" id="description">
        <a href="javascript:void(0)" onclick="format('bold')"><span class="fa fa-bold fa-fw"></span></a>
        <a href="javascript:void(0)" onclick="format('italic')"><span class="fa fa-italic fa-fw"></span></a>
        <a href="javascript:void(0)" onclick="format('insertunorderedlist')"><span class="fa fa-list fa-fw"></span></a>
        <a href="javascript:void(0)" onclick="setUrl()"><span class="fa fa-link fa-fw"></span></a>


</div>
   <div class="editor" id="sampleeditor"></div>
                             <div class="form-group">
                        <label>Priority</label>
 
                      <select class="form-control"  id='firstList' name='firstList' onclick="getFoodItem()">
    </select>
                    </div>
                           <div class="form-group">
                           <label>Start Date</label>
                               <br>
                    <input  type="date" id="myDate" placeholder="yyyy-MM-dd" />
                           </div>
                                <div class="form-group">
                           <label>Due Date</label>
                               <br>
                    <input type="date" id="myDue" placeholder="yyyy-MM-dd" />
                           </div>
                    </div>
                </form>


            </div> 


 

Discord.js v13 why is my tempmute command not working?

I’ve made a tempmute command for my discord bot and it almost works. It has quite a few foolproofing measures like preventing the bot from muting themselves, not working if the time isn’t specified and such. I am using the npm ms package to deal with the mute duration (https://www.npmjs.com/package/ms). when instead of specifying an amount of time I type in gibberish it works as intended and replies with the correct message. The problem is that when I type in a 100% correct command it responds asthough I didn’t specify the time correctly instead of muting the user for that amount of time. here’s how it looks. Any ideas as to why that is?
My code is here:

const ms = require('ms');
const { Permissions, MessageActionRow, UserFlags } = require('discord.js');

module.exports = {
    name: 'tempmute',
    description: "Temporarily mutes a user",
    execute(message, args)
    {
        const target = message.mentions.members.first();
        let muteRole = message.guild.roles.cache.find(role => role.name === "muted");
        if(message.member.permissions.has(Permissions.FLAGS.MODERATE_MEMBERS))
        {
            if(target)
            {
                let memberTarget = message.guild.members.cache.get(target.id);
                if(target.id == 'myBotsID')
                {
                    message.reply("I can't mute myself.")
                }
                else if(message.member == target)
                {
                    message.reply("You can't mute yourself!")
                }
                else if(memberTarget.permissions.has(Permissions.FLAGS.MODERATE_MEMBERS))
                {
                    message.channel.send(`<@${memberTarget.user.id}> has been muted for ${ms(ms(args[1]))}`);                
                }
                else 
                {
                    if(!args[1]) 
                    {
                        return message.reply("Time not specified.")
                    }
                    else
                    {
                        let time = ms(args[1])
                        memberTarget.roles.add(muteRole.id); 
                        try {
                            message.reply("<@" + memberTarget.user.id + ">" + "has been muted for " + ms(ms(args[1])).catch(console.error))
                            setTimeout(function () {
                                memberTarget.roles.remove(muteRole.id);
                            }, time);
                        } catch (err) {
                            message.reply("Can't transform that into milliseconds `"+args[1]+"`")
                            return
                        }
                    }
                }
            }
            else
            {
                message.reply("You have to mention a valid member of this server.")
            }
        }
        else
        {
            message.reply("You can't use that.")
        }
    }
}

React keys for an array of strings

I have a question. How can I generate key for array of string? It is not object, in object I could put id and it would solve the problem. So what should I do in just array? Indexes as key is not a good practice so I am stuck.

const ingredients = ['rice', 'curry', 'chicken]



    {props.ingredients.map((ingredient) => (
                <Box>{ingredient}</Box>
          ))}

How to allow user to change column name’s in AG-GRID?

I am looking to allow my users to change the column header names to whatever they would like in ag-grid. I am using the javascript implementation.

I could not find an example of anyone doing this on stack overflow or the documentation, my initial idea is to create a new header component and add my own code to handle it that way via the ag grid api.

I found this page
https://www.ag-grid.com/javascript-data-grid/component-header/

It does not appear to have the default header component as an example. And I would like to use that to start off with… So my question is either:

  1. Does anyone know of an example or better method which achieves what I am trying to do?
    Or
  2. Would anyone please be able to point me to where I could find the code of the default ag grid header component, which I can use to start off with, and alter using the example given in the documentation linked above.

How can I render the values ​of an array in sessionStorage?

I will try to be as specific as possible in my question.
I am allocating some values ​​(key-text) in the sessionStorage.
I am using a dynamic method to get the keys for each session.
Unfortunately, reading on various websites and asking for support from people more experienced than me, I still couldn’t solve my problem …
Anyone know how to get all sessionStorage values ​​obtained with a dynamic key ??

let  unique_id = Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
        
const [value,setValue] = useState({
            id:unique_id,
            payload: ' ',
        })
sessionStorage.setItem(value)

Forestry + Gatsby Image – reference image from JSON files

I’m looking into using Forestry with Gatsby (and use gatsby-plugin-image to optimize the images), but I’m stuck on how to get it working and not sure if it’s even possible.

  1. The first approach I tried (not working with Gatsby Image) is:

The image path is set in JSON files (to make all page content editable) and the images are uploaded to the static/uploads folder because Forestry requires an absolute path for the images:

content/pages/home.json:

{
  "title": "Home",
  "hero_image": "../../uploads/hero_image.png",
  "hero_image_alt": "An image",
  ...
}

–> This approach will not make it queryable in GraphQL by Gatsby so I can only use it in a normal img tag:

pages/index.js:

import { useStaticQuery, graphql } from "gatsby"
...
const { allPagesJson } = useStaticQuery(
    graphql`
      {
        allPagesJson {
          nodes {
            hero_image_alt
            hero_image
          }
        }
      }
    `

const data = allPagesJson.nodes[0]
<img src={data.hero_image} alt={data.hero_image_alt} />
  1. Second approach I tried (queryable but still not working) is:

The images are uploaded to content/images and then a relative path is added in the JSON files:

content/pages/home.json:

{
  "title": "Home",
  "hero_image": "../images/hero_image.png",
  "hero_image_alt": "A picture"
}

–> This approach makes it queryable, so I’d think I can use it in the GatsbyImage component, but it always returns a 404 error:

pages/index.js:

import { useStaticQuery, graphql } from "gatsby"
import { GatsbyImage, getImage } from "gatsby-plugin-image"
...
const { allPagesJson } = useStaticQuery(
    graphql`
      {
        allPagesJson{
          nodes {
            hero_image_alt
            hero_image {
              childImageSharp {
                gatsbyImageData
              }
            }
          }
        }
      }
    `
  )
...
const data = allPagesJson.nodes[0]
const hero_image = getImage(data.hero_image)
...
<GatsbyImage image={hero_image} alt={data.hero_image_alt} />

This returns the error:
GET http://localhost:8000/static/130e6fa61e2ebe523785c187e562a5f8/61d51/hero_image.webp 404 (Not Found)

I’ve been struggling with this all afternoon and not sure what else I can try to get it working with Forestry.

My basic requirements are that I need to be able to make all page content editable (text/images) for users instead of only being able to create posts + optimize the images with GatsbyImage so if there’s a better way in general to make that happen I’m also all ears.

Type error: Subsequent variable declarations must have the same type. Variable ‘e’ must be of type ‘any’, but here has type ‘Event’

I am trying to build the project and would like to deploy it to vercel but getting some type errors.

The site runs fine in development (using yarn dev).

These are the two functions am using to close a modal without event propagation.

    //Closes the modal
    const exitModal = (e) => {
    closeModal(false)

    //this part stops the click from propagating
    if (!e) var e = window.event
    e.cancelBubble = true
    if (e.stopPropagation) e.stopPropagation()
   }

  const exitAndRefresh = (e) => {
    exitModal(e)
    window.location.reload()
  }

The JSX below with the onClick function:

              <button
                className="absolute z-10 top-0 right-0 mt-1 mr-2 p-2 rounded-lg text-white bg-red-500 hover:bg-red-700"
                onClick={exitModal}
              >
                Cancel
              </button>

Build Error: (using yarn build)

Type error: Subsequent variable declarations must have the same type.  Variable 'e' must be of type 'any', but here has type 'Event'.

  91 |
  92 |     //this part stops the click from propagating
> 93 |     if (!e) var e = window.event
     |                 ^
  94 |     e.cancelBubble = true
  95 |     if (e.stopPropagation) e.stopPropagation()
  96 |   }

I tried doing this –

//Closes the modal
  const exitModal = (e: Event) => {
    closeModal(false)

    //this part stops the click from propagating
    if (!e) var e = window.event
    e.cancelBubble = true
    if (e.stopPropagation) e.stopPropagation()
  }

  const exitAndRefresh = (e: Event) => {
    exitModal(e)
    window.location.reload()
  }

But got this error instead:

Type error: Type '(e: Event) => void' is not assignable to type 'MouseEventHandler<HTMLButtonElement>'.
  Types of parameters 'e' and 'event' are incompatible.
    Type 'MouseEvent<HTMLButtonElement, MouseEvent>' is missing the following properties from type 'Event': cancelBubble, composed, returnValue, srcElement, and 7 more.

  158 |               <button
  159 |                 className="absolute z-10 top-0 right-0 mt-1 mr-2 p-2 rounded-lg text-white bg-red-500 hover:bg-red-700"
> 160 |                 onClick={exitModal}
      |                 ^
  161 |               >
  162 |                 Cancel
  163 |               </button>
error Command failed with exit code 1.

Webcam Access for Custom Filters:vTypeError: URL.createObjectURL: Argument 1 is not valid for any of the 1-argument overloads

I am currently trying to improve my JS skills by going through WesBos’s 30 Days of JavaScript. (It is really fun if!) I’m currently on Day 19, which is about using JS to access the WebCam, and then add affects using CSS.

I was successfully able to set up a local server, and here is my code so far:

 function getVideo() {
        navigator.mediaDevices.getUserMedia({video: true, audio: false})
        .then(localMediaStream => {
            console.log(localMediaStream);
            video.src = window.URL.createObjectURL(localMediaStream);
            video.play();
        })
        .catch(err => {
            console.error(`Web camera access is not enabled. To resolve, reload the page and allow 
    access.`, err);
        });
    }
    
    getVideo();

However, I am getting this error:

    TypeError: URL.createObjectURL: Argument 1 is not valid for any of the 1-argument overloads.
    getVideo http://localhost/19-webcam-fun/scripts.js:12
    promise callback*getVideo http://localhost/19-webcam-fun/scripts.js:10
    <anonymous> http://localhost/19-webcam-fun/scripts.js:27

Idk if this helps, but the console.log(localMediaStream) results in the following:


    MediaStream { id: "{97c3d27e-404e-4d14-b1d2-2a9ebbf09137}", active: true, onaddtrack: null, 
    onremovetrack: null }
    ​
    active: true
    ​
    id: "{97c3d27e-404e-4d14-b1d2-2a9ebbf09137}"
    ​
    onaddtrack: null
    ​
    onremovetrack: null
    ​
    <prototype>: MediaStreamPrototype { getAudioTracks: getAudioTracks(), getVideoTracks: 
    getVideoTracks(), getTracks: getTracks(), … }

I would really appreciate it if someone could help me understand this a little better! Thanks!

Why I get this error when trying to simplify an 3D model using SimplifyModifier of Three.js?

I’m trying to simplify an 3D Model (.STL file) that is loaded using STLLoader and the Three.js function SimplifyModifier to reduce vertices and simplify the model.

I have a function called loadMesh that loads the file and return an Three.js mesh that renders on a Scene:

     /**
     * Method to load the mesh model from .stl or .3mf file and return Mesh ThreeJS object
     * @param {*} part Part or model of a part, on form of a .stl or .3mf file
     * @param {*} color Color of the mesh material. Default = #0096d6
     * @returns Mesh from ThreeJS
     */
    static loadMesh(part, color = '#0096d6') {
        if (!FileUtil.existsPath(part.path)) return null;

        const loader = (Loader, encoding) => new Loader().parse(FileUtil.readFile(part.path, encoding));

        let mesh = null;
        const material = new THREE.MeshStandardMaterial({ color, flatShading: true });

        const ext = FileUtil.getExtName(part.path, true).toLowerCase();
        if (ext == 'stl') {
            const geometry = loader(STLLoader, 'binary');

            // Make an instance of SimplifyModifier
            const modifier = new SimplifyModifier();

            // Create Mesh wit geometry and material already defined
            mesh = new THREE.Mesh(geometry, material);

            // Number of vertices to remove from part
            const count = Math.floor( mesh.geometry.attributes.position.count * 0.1 );

            console.log(count);

            // Now modify the geometry of our mesh to optimize number of polygons
            mesh.geometry = modifier.modify( mesh.geometry, count );


        } else if (ext == '3mf') {
            mesh = loader(ThreeMFLoader, 'buffer');

            for (const [index, buildItem] of Object.entries(mesh.children)) {
                (function updateMaterial(children) {
                    for (const child of children) {
                        if (child.children?.length > 0) {
                            updateMaterial(child.children);
                        } else {
                            child.index = String(index);
                            child.material = material.clone();
                        }
                    }
                })(buildItem.children);
            }

            if (part.buildItemIndex != 'all') {
                mesh = mesh.children[+part.buildItemIndex];
                mesh.position.set(0, 0, 0);
            }
        }

        mesh.part = part;
        MeshUtil.resetOrigin(mesh);

        return mesh;
    }

Currently the app supports two 3d files extensions: .STL and .3MF, that’s why you can use that the function checks the extension and its executes based on that. But for the moment im trying to simplify an STL model, so the important thing here is happening inside the STL if condition:

            const geometry = loader(STLLoader, 'binary');

            // Make an instance of SimplifyModifier
            const modifier = new SimplifyModifier();

            // Create Mesh wit geometry and material already defined
            mesh = new THREE.Mesh(geometry, material);

            // Number of vertices to remove from part
            const count = Math.floor( mesh.geometry.attributes.position.count * 0.1 );
//
            console.log(count);

            // Now modify the geometry of our mesh to optimize number of polygons
            mesh.geometry = modifier.modify( mesh.geometry, count );

When I try to render the model on another component using

// mesh is the returned mesh from the above function
scene.add(mesh);

I get the next error on console:

Error of undefined on console

Notes

Already tried to change count of vertices to remove and there is no difference.

For better reference, there are the properties of the geometry object that im trying to simplify:
geomtry object properties

The purpose of this is because in some cases the app can receive large files and it crashes when trying to render on Scene.

Also, don’t know if there is any problem that is BufferGeometry, and if its the case, how can I solved that?

3 buttons have different inputs but showing the same output as the first button

I have 3 modal buttons. All three buttons have different inputs. But when I press the first button, everything is showing completely fine but when I press the 2nd and 3rd button, it shows the same results as the first button. Please have a look, I am attaching my code below.

Extra: It would be very helpful for me if you can suggest me, how I can put multiple photos stacked in the modal body without losing the shape of the modal. It will show a single photo in the modal body but if someone swap over the picture then the next picture will arrive. Thank you so much.

// Modal
// Get DOM Elements
const modal = document.querySelector('#my-modal');
const modalBtn = document.querySelectorAll('.button');
const closeBtn = document.querySelector('.close');

// Events
modalBtn.forEach(btn => btn.addEventListener('click', openModal));
closeBtn.addEventListener('click', closeModal);
window.addEventListener('click', outsideClick);

// Open
function openModal() {
  modal.style.display = 'block';
}

// Close
function closeModal() {
  modal.style.display = 'none';
}

// Close If Outside Click
function outsideClick(e) {
  if (e.target == modal) {
    modal.style.display = 'none';
  }
}
/* Modal section styling */

:root {
    --modal-duration: 1s;
    --modal-color: crimson;
  }
  
  .button {
    font-family: 'poppins', sans-serif;
    display: inline-block;
    background: crimson;
    color: #fff;
    font-size: 18px;
    font-weight: 500;
    padding: 8px 16px;
    margin-top: 20px;
    border-radius: 6px;
    border: 2px solid crimson;
    transition: all 0.3s ease;
  }
  
  .button:hover {
    color: crimson;
    background: none;
  }
  
  .modal {
    display: none;
    position: fixed;
    z-index: 99999;
    left: 0;
    top: 0;
    height: 100%;
    width: 100%;
    overflow: auto;
    background-color: rgba(0, 0, 0, 0.5);
  }
  
  .modal-content {
    margin: 50px auto;
    width: 60%;
    box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.17);
    animation-name: modalopen;
    animation-duration: var(--modal-duration);
  }
  
  .modal-header h2,
  .modal-footer h3 {
    margin: 0;
  }
  
  .modal-header {
    background: var(--modal-color);
    text-align: center;
    padding: 10px;
    color: #fff;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
  }
  
  .modal-body {
    padding: 10px 5px 1px 5px;
    background: #fff;
  }
  
  .modal-footer {
    background: var(--modal-color);
    padding: 10px;
    font-size: 15px;
    font-weight: lighter;
    color: #fff;
    text-align: center;
    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;
  }
  
  .close {
    color: #ccc;
    float: right;
    font-size: 30px;
    color: #fff;
  }
  
  .close:hover,
  .close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
  }
  .responsive {
    width: 100%;
    height: auto;
  }
  @keyframes modalopen {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }
<!-- Modal Button 1 start -->
<button id="modal-btn" class="button">Parkit</button>
<div id="my-modal" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">&times;</span>
      <h3>Vehicle Parking Application</h3>
    </div>
    <div class="modal-body">
      <img src="https://thefinancialexpress.com.bd/uploads/1575560371.jpg" alt="Vehicle Parking Application" class="responsive">
    </div>
    <div class="modal-footer">
      <p>
      Footer
      </p>
    </div>
  </div>
</div>
<!-- Modal Button 1 end -->

<!-- Modal Button 2 start -->
<button id="modal-btn2" class="button">IPDC IMS</button>
<div id="my-modal2" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">&times;</span>
      <h3>Asset Management System</h3>
    </div>
    <div class="modal-body">
      <img src="#" alt="Asset Management System" class="responsive">
    </div>
    <div class="modal-footer">
      ...
    </div>
  </div>
</div>
<!-- Modal Button 2 end -->

<!-- Modal Button 3 start -->
<button id="modal-btn3" class="button">Gaming Website</button>
<div id="my-modal3" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">&times;</span>
      <h3>Gaming Website</h3>
    </div>
    <div class="modal-body">
      ...
    </div>
    <div class="modal-footer">

    </div>
  </div>
</div>
<!-- Modal Button 3 end -->

ARjs: Camera Video not centered / wrong image ratio

This problem arises using aframe v1.2.0 and ARjs master branch

Hey everyone:

Is there a way to center the camera image in ARjs?
I am currently using the version from the master branch, but the video is shifted, when using aframe version 1.2.0.
I know that the newest version of aframe is 1.3.0 but there are known incompatibilities with ARjs master branch. When using the dev branch the errors are resolved, but the video is still not centered.

Image from Android Studio:
Video not centered – Android Studio

The desired video should look like this:
Video centered – Android Studio

Script imports:

src=”https://aframe.io/releases/1.3.0/aframe.min.js”

src=”https://unpkg.com/[email protected]/dist/aframe-look-at-component.min.js”

src=”https://raw.githack.com/AR-js-org/AR.js/dev/aframe/build/aframe-ar-nft.js”

Kind regards