Why does jquery DataTables turn my zero’s into floats with values?

I am trying to display some JSON data in a jquery datatable with a precision of two decimal places. It seems to work, sometimes. In the pic below, Chrome’s dev toolbar renders the value as 2000.0000000 but the datatable displays $2.000020000200002e+58. I used the following number renderer, as per the docs (https://datatables.net/manual/data/renderers#Built-in-helpers):

 columnDefs: [
        {
            orderable: false,
            render: $.fn.dataTable.render.number(null, null, 2, '$'),
            targets: [4],
        }
    ], 

enter image description here

Batch downloading files from webpage using python

i’ve got like 2000files i need to download from a certain link (some external link that sends files to investment partners in the company; something like that)
Below is my code:

from bs4 import BeautifulSoup as bs
import requests

login_req = s.post(url+LOGIN, headers = HEADERS, data = login_payload, verify = False)

page = requests.get(url +'reviewdocument.aspx', verify = False)

soup = BeautifulSoup(page.text, 'html.parser')

for link in soup.find_all('a'):
    url = link.get('href')
    with open(url, 'wb') as file:
        response = get(url)
        file.write(response.content)

However, its returning an error, InvalidSchema: No connection adapters were found for ‘JavaScript:ShowTrace()’

Saw online that it might have been the missing https, so i tried that. Instead, a new error is produced: OSError: [Errno 22] Invalid argument: ‘https://JavaScript:ShowTrace()’

im not a coder but perhaps its because i did not specify a working directory to download the files into..? but im not really sure on how to input that and if thats the correct explanation for the error, hope someone would point out how to fix this, thank you!

edit: tried print(url) and im just getting https://JavaScript:ShowTrace(). can anyone please enlighten me what this is supposed to be and how to fix it? thank you

when expire date entered, automatic slash

There is a credit card component. It asks the user to enter credit card information. However, I want to automatically put a slash between the day and month when the user enters the credit card expiration date. I searched the expiration date entry as “auto slash when 2 digits are entered” but I haven’t been successful yet.

i can write; 0614

The format i want; 06/14

How can I solve it?

js

const [expDateValidationState, setExpDateValidationState] = useState({
  error: false,
  helperText: '',
});

const expDateOnChange = (event) => {
  if (expDateValidator(event.target.value)) {
    setExpDateValidationState({ error: false, helperText: '' });
    setPaymentInfo({
      ...paymentInfo,
      expDate: event.target.value === '' ? null : event.target.value,
    });
  } else {
    setExpDateValidationState({
      error: true,
      helperText: 'Please enter your expire date.',
    });
    setPaymentInfo({
      ...paymentInfo,
      expDate: null,
    });
  }

const handleExpDateChange = (event) => {
  expDateOnChange(event);
  handleInputChange(event);
};

validator

export const expDateValidator = (expDate) => {
  const expDateRegex = /^(0[1-9]|1[0-2])/?([0-9]{4}|[0-9]{2})$/;

  return expDateRegex.test(expDate);
};

html

<AS.TextField
  placeholder="aa/YY"
  inputProps={{ maxLength: 5 }}
  onChange={handleExpDateChange}
  error={expDateValidationState.error}
  helperText={expDateValidationState.helperText}
  name="expDate"
  value={paymentInfo.expDate}
/>

Build a digital display in css html javascript [closed]

For a personal project I want to make a display of a number like the prices of fuel in gas stations. A digital display.

Like this image:

Gas station price display

I’m not good at front end so I don’t know where to start.

I’ve searched on the internet, but I can’t find exactly what I want to do.
I would like to make almost the same thing as the picture above.

Thanks you for your help 🙂

How to fix component position start on bottom then move to normal in react js when the page is refreshed

I have a component that has a sidebar and content as shown below.

strong text

When the page is refreshed, the first time the component content is loaded below as shown below and in an instant, the components are back to normal.

enter image description here

I use module.css in every component. With a structure like this:

component
|___Sidebar
|   |___index.tsx
|   |___index.module.css
|___Content
    |___index.tsx
    |___index.module.css

Can anyone explain what happened? Is this happening because I’m using css folder structure like that which causes styles to be late to read?
How do you think this problem can be solved?

How to get Google Maps api content to link to fancybox iframe

I have a google maps api with pins. When I click the pins is shows content above with a link. When I click the link within the content I want it to open a fancybox iframe.

Is this even possible with google maps api?

Usually I’d just add the fancybox js and css to the page and then do the following:

<a href="job.php?id='+ data.images + '" data-fancybox data-type="iframe">More info</a>

but that’s not possible as the maps api is in an iframe itself.

Here’s my function to display the markers with their respective content boxes, you can see I’ve already added the data-fancybox and data-type to the link, but it’s currently not working:

function addMarkerWithTimeout(position, timeout, data, infoWindow) {
var image = {
  url:"/images/map-marker.png",
  size: new google.maps.Size(32,50),
  anchor: new google.maps.Point(16,50),
};

window.setTimeout(() => {
  var marker = new google.maps.Marker({
    position: position,
    map,
    icon:image,
    animation: google.maps.Animation.DROP,
    optimized:true,
    title: data.title
  });

  (function(marker, data) {
    
    google.maps.event.addListener(marker, "click", function() {  
      var purchase = (data.availableToPurchase == null) ? 'No longer available to purchase' : 'This job is available to purchase';
      content = '<div class="infoWindow"><h5 class="truncate">' + data.name + '</h5><div class="blockinfo"><p class="right-align"><i class="tiny material-icons">place</i> ' + data.location + '</p><p class="right-align"><i class="tiny material-icons">calendar_month</i> ' + data.posted + '</p><p class="right-align">' + purchase + '</p></div><p class="truncate description">' + data.jobDescription + '</p><p class="right-align"><a class="btn-small blue waves-effect waves-light full-width" href="job.php?id='+ data.images + '" data-fancybox data-type="iframe">More info</a></p></div>';
      infoWindow.setContent(content);
      infoWindow.open(map, marker);
    });
      })(marker, data);
    }, timeout);
  }

Can anyone help me to get this working please?

Firebase Error(only dev): ReferenceError: IDBIndex is not defined

When I build my app for production everything works fine but in development I’m getting this error when I’m trying to import collection and addDoc from firestore. I’ve read that the problem is related to vite grabbing Firebase’s browser (esm) bundle and not the Node bundle. I’ve tried to fix this by adding a vite.config.js file with the following content but nothing changed:

import { defineConfig } from 'vite';
import path from 'path';

// vite.config.js
export default defineConfig({
  // config options
  resolve: {  
    alias: {
        ['firebase/firestore']: path.resolve(__dirname, 'node_modules/firebase/firestore/dist/firestore/index.d.ts')
  },extensions: ['.ts', '.js'] },
})

Canvas JS GAME, Can’t make the character jump only once after touching the ground

this is my code for a canvas game, my character is able to go left right and jump. The problem is that i want to make the character jump only once, then touch the ground again and now, to be able to jump again. In my code if i press w multiple times will jump forever.

……………………………………………………………………………….


const canvas = document.querySelector("canvas");
const c = canvas.getContext('2d')

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;


const gravity = 0.5;
let isGrounded;


class Player {
    constructor() {
        this.position = {
            x: 100,
            y: 100
        }
        this.width = 100
        this.height = 100
        this.velocity = {
            x: 0,
            y: 1
        }
    }
    draw() {
        c.fillStyle = 'black'
        c.fillRect(this.position.x, this.position.y,
        this.width,this.height)
    }

    update() {
        this.draw();
        this.position.x += this.velocity.x;
        this.position.y += this.velocity.y;
        // console.log('vel de y',this.velocity.y)

        if(this.position.y + this.height + this.velocity.y >= canvas.height)
            this.velocity.y = 0
        else this.velocity.y += gravity;



    }
}


class Platform {
    constructor({x,y}) {
        this.position = {
            x: x,
            y: y
        }
        this.width = 400
        this.height = 20
    }

    draw() {
        c.fillStyle = 'black'
        c.fillRect(this.position.x, this.position.y,
        this.width,this.height)
    }
}





const player = new Player()
const platforms = [
    new Platform({
        x: 150,
        y: 800,
    }),
    new Platform({
        x: 700, y: 900
    }),
];


const keys = {
    right: {
        pressed: false
    },
    left: {
        pressed: false
    },
    up: {
        pressed: false
    }
    
    
}

let scrollOffset = 0

function animate() {
    const JUMP_SPEED = 5
    requestAnimationFrame(animate)
    c.clearRect(0,0,canvas.width,canvas.height)
    player.update();
    platforms.forEach(platform => {
        platform.draw()
    })



    if (keys.right.pressed && player.position.x < 400) {
        player.velocity.x = 5
    } else if (keys.left.pressed && player.position.x > 100) {
        player.velocity.x = -5
    } else {
        player.velocity.x = 0

        if (keys.right.pressed) {
            scrollOffset += 5;
            platforms.forEach((platform) => {
                platform.position.x -= 5;
                

                });
        } else if (keys.left.pressed) {
            scrollOffset -=5
            platforms.forEach((platform) => {
                    
                    platform.position.x += 5;

                });
            
        }
    }
    //platform collision detection
    platforms.forEach(platform => {
        if (player.position.y + player.height <= platform.position.y
            && player.position.y + player.height + player.velocity.y >= platform.position.y
            && player.position.x + player.width >= platform.position.x
            && player.position.x <= platform.position.x + platform.width) {
            player.velocity.y = 0
        }
    })
    if (scrollOffset > 300) {
        console.log('u win')
    }
    }


animate()

window.addEventListener('keydown', ({ keyCode }) => {
    console.log(keyCode);
    switch (keyCode) {
        case 65:
            console.log("left");
            keys.left.pressed = true;

            break;
        case 83:
            console.log("down");
            break;
        case 68:
            console.log("right");
            keys.right.pressed = true;
            break;
        case 87:
            console.log("up");
            keys.up.pressed = true;
            player.velocity.y = -10
            break;
        console.log(keys.right.pressed)
    }
})


window.addEventListener("keyup", ({ keyCode }) => {
    console.log(keyCode);
    switch (keyCode) {
        case 65:
            console.log("left");
            keys.left.pressed = false;

            break;
        case 83:
            console.log("down");
            break;
        case 68:
            console.log("right");
            keys.right.pressed = false;

            break;
        case 87:
            console.log("up");
            keys.up.pressed = false;
            // player.velocity.y -= 20;
            break;
    }
});

Evaluate basic math expressions without using eval()

I need to evaluate simple math (+ - * / ^) for a Discord counting bot. I can’t use eval() for obvious security reasons, and I’ve taken a look at Math.js and JavaScript Expression Evaluator, but both support more advanced math (such as sin(), tan(), imaginary numbers, etc.), which I want to not implement for simplicity reasons.

Is there another library which allows for simple math evaluation without advanced math? If not, how can I use the mentioned libraries to not support this?

MongoDB won’t create a messageCount value

so I’m making a message count command with discord.js and MongoDB but the “messageCount” value just never gets created. I searched it up and looked at docs but I couldn’t find what was wrong.

Codes:

message-counter.js file:

const mongo = require("mongoose")
const schema = require("./schemas/rank/message-count-schema")

module.exports = client => {
    
    client.on('messageCreate', async (message) => {    
        const { author } = message
        const { id } = author
        mongo.connect(
            process.env.MONGO_URI,
            { keepAlive: true }
        )

        const dataQuery = await schema.findOne({ _id: id })
        
        if (!dataQuery) {
            const newSchem = schema(
                {
                    _id: id
                },
                {
                    $setOnInsert: { messageCount: 1 }
                },
                {
                    $inc: { messageCount: 1 }
                },
                {
                    upsert: true
                }
            )
        
            await newSchem.save()
        }
        else {
            dataQuery.updateOne(
                {
                    $inc: { messageCount: 1 }
                },
                {
                    upsert: true
                }
            )
        }
    })
}

message-count-schema.js file:

const mongoose = require('mongoose');

const messageCountSchema = new mongoose.Schema({
    _id: {
        type: String,
        required: true
    },

    messageCount: {
        type: Number,
        required: true
    }
})

module.exports = mongoose.model('message-count', messageCountSchema);

Can someone tell me what’s wrong and how to fix it? I’m not asking to be spoon fed, just what’s wrong.

enter image description here

Automatically run console commands on web based apps

I was wondering if you can run console commands in webbased applications automatically on their startup. As an example I mean apps such as discord or websites like YouTube where you can access the “Inspect Element” or the “Developer options” menu in the Console tab. If you have any answers they would be appericiated! Specificaly I mean javascript commands

Store canvas screenshot to local filesystem with Filesystem API

I am developing a small web-application with a threejs Renderer where I want to be able to store some screenshots to my local filesystem at a specific location. Rendering the images and creating the snapshots works, only the storage/download part gives me headache.

I create the snapshot this way:

    let imageData = renderer.domElement.toDataURL('image/png');
    console.log(imageData); // data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABFAAAANBC...

Now to download this, there are several methods: window.location.href = imageData;does trigger a download (and several alert messages from the browser). But the downloaded image is stored as a file called download inside the Download-Folder. If added the File-Extension .png it can be opened. This is not a useful solution, several downloads in a row will hardly be assigned.

So another working method is to build a download-link and trigger its click-method:

    let a_element = document.createElement('a');
    a_element.setAttribute('href', imageData.replace('image/png', 'image/octet-stream');
    a_element.setAttribute('download', 'screenshot.png');
    a_element.style.display = 'none';
    document.body.appendChild(a_element);
    a_element.click();
    document.body.removeChild(a_element);

This does download the screenshot with a custom-name to the Download folder, it’s almost what I want, but i’d like to have them stored in a custom folder as well. That’s where the Filesystem-API comes in. The drawback is, that every download has to be confirmed, but not having to move the files manually from the download folder would pay off for that.

    const options = {
        types: [
            {
            description: 'Images',
            accept: {
                'image/png': ['.png'],
            },
            },
        ],
        suggestedName: 'Screenshot.png',
        };
    imgFileHandle = await window.showSaveFilePicker(options);
    console.log("Save File chosen");
    const writable = await imgFileHandle.createWritable();
    await writable.write(imageData);
    await writable.close();

This seems to work, but the file that is stored is not a valid image. It contains only Text (same as the output of the console). How should I treat the imageData to download it as an image ?

Jules JavaScript heap out of memory

I am getting following error in Jules pipeline.

FATAL ERROR: Ineffective near heap limit Allocation failed - JavaScript heap out of memory

While running locally works fine.

I tried following script.

"build:prod": "npm test && webpack --max-old-space-size=8192 --mode=production "--output-path=...
"build:local": "webpack --max-old-space-size=8192 --mode=production "--output-path=...
"start": "webpack-dev-server --max-old-space-size=8192 --mode=development --progress --display-error-details --hot"

But, doesn’t solve.

FYI: locally I set env variable in my windows as NODE_OPTIONS --max-old-space-size=8192

I checked memory leak and fixed all but, still getting the error.

Not sure what else I can do. Any help would be greatly appreciated.

Note: I am using node version 12. Can’t upgrade now.