How can I create a list of days between 2 dates?

  var today = moment().format("MMM D, YYYY");
  var lastDate = moment(today).add(10, 'days').format("MMM D, YYYY");

I want to list all the days between these 2 dates.

Just like this
Feb 20, 2022
Feb 21, 2022
Feb 22, 2022
Feb 23, 2022
Feb 24, 2022
Feb 25, 2022
Feb 26, 2022
Feb 27, 2022
Feb 28, 2022
Feb 29, 2022

how to add setInterval for this function

how to make autoslide for this function with setinterval please help me with this question

$(document).ready(function() {
    const next = document.querySelector(".next"),
    back = document.querySelector(".back"),
    slideshow = document.querySelector(".slideshow__images");
  let angle = 0;

  next.addEventListener("click", () => {
    angle -= 45;
    slideshow.style.transform = `translateZ(-25rem) rotateY(${angle}deg)`;
  });

  back.addEventListener("click", () => {
    angle += 45;
    slideshow.style.transform = `translateZ(-25rem) rotateY(${angle}deg)`;
  });
});

Formdata in expo app is being recieved in _parts

I am sending form to backend by using FormData and using multer on backend to recieve the data, it works fine on my web app but on doing the same axios call to submit data in react-native shows that data fields are being received on backend in following form

{ _parts: [ [ 'firstname', 'fahad' ], [ 'firstname', 'RAO' ] ] }

i am doing following call in my web app (which works there) and in my expo app

const testFOrmData = ()=>{
        
        var data = new FormData()
        data.append("firstname","fahad")
        data.append("firstnae","RAO")
        const adata  = {
            firsn:"rew"
        }
axios.post("http://192.168.10.8:3309/api/testform",data)
.then((res)=>{
    console.log(res)
})
alert("SANS")
    }

How to receive it in object form such that i dont have to make changes in my existing code in backend as i have so many forms and i have submitted them using form data in my web app and have to do same in mobile app but i dont want to submit without FormData(by sending object in axios)

my backend

router.post("/testform",upload.none(),(req,res)=>{
    console.log(req.body)
    res.json({resp:req.body})
})

How to check for unique values in chrome.storage array

I am really struggling with this:
What I am trying to do is create an array that is stored in chrome.sync with the url of unique pages a user visits. Adding the url to the array works fine – what I am struggling with is how to check if that url already exists in the array. This is what I have currently:

function getURL(array) {
    chrome.tabs.query({active: true, lastFocusedWindow: true, currentWindow: true}, tabs => {
        let tabUrl = tabs[0].url;
        addArr(tabUrl, array);
    });
}
function addArr(tabUrl, array) {
    array.map((x) => {
        let urlCheck = x.url;
        console.log(urlCheck);
        if(urlCheck != tabUrl) {
           array.push(tabUrl);
           chrome.storage.sync.set({data: array}, function() {
               console.log("added")
           });
        }
    })
}

The annoying thing I can’t work out is that it works when I remove anything to do with the the map and only keep the:

           array.push(tabUrl);
           chrome.storage.sync.set({data: array}, function() {
               console.log("added")
           });

This makes even less sense because when I inspect the array by inspecting the popup and then looking at console, there is no error only an empty data array. The error that it gives me, however, when I inspect the popup (actually right click on extension) is

Error handling response: TypeError: Cannot read properties of
undefined (reading ‘url’) at
chrome-extension://jkhpfndgmiimdbmjbajgdnmgembbkmgf/getURL.js:31:30

That getURL.js line 31? That is part of the code that gets the active tab. i.e

let tabUrl = tabs[0].url;

which isn’t even in the same function.

Any ideas? I am totally stumped.

Adding characters to the end of a line

Based on the following code and description here:

Add Bullets to Each New Line within a textarea

const bullet = "u002a";
const bulletWithSpace = `${bullet} `;
const enter = 13;


const handleInput = (event) => {
    const { keyCode, target } = event;
    const { selectionStart, value } = target;

    if (keyCode === enter) {
        //console.log('debug');
        target.value = [...value]
            .map((c, i) => i === selectionStart - 1
                ? `n${bulletWithSpace}`
                : c
            )
            .join('');
        //console.log(target.value);

        target.selectionStart = selectionStart+bulletWithSpace.length;
        target.selectionEnd = selectionStart+bulletWithSpace.length;
    }

    if (value[0] !== bullet) {
        target.value = `${bulletWithSpace}${value}`;
    }
}

How can this be modified to work in the opposite way?

Instead of adding the target to the first position of each new line. Change the target position to the end.

Note: I replaced the bullet unicode to * for testing

Original code does this:

* text
* new line

Changing the code to do instead:

text *  
new line *  

* = bullet in my example code

Error [ERR_MODULE_NOT_FOUND]: Cannot find package ‘@babel/plugin-preset-react’ imported from

when I run the command to build the react project:

yarn build

show error:

➜  react-admin git:(master) ✗ yarn build
yarn run v1.22.17
$ webpack --mode production --config config/webpack.build.config.js
assets by status 1.48 KiB [cached] 1 asset
./src/index.js 39 bytes [built] [code generated] [1 error]

ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@babel/plugin-preset-react' imported from /Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/babel-virtual-resolve-base.js
    at new NodeError (/Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/@babel/core/lib/vendor/import-meta-resolve.js:2552:5)
    at packageResolve (/Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/@babel/core/lib/vendor/import-meta-resolve.js:3208:9)
    at moduleResolve (/Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/@babel/core/lib/vendor/import-meta-resolve.js:3242:18)
    at defaultResolve (/Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/@babel/core/lib/vendor/import-meta-resolve.js:3281:13)
    at /Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/@babel/core/lib/vendor/import-meta-resolve.js:3304:14
    at Generator.next (<anonymous>)
    at asyncGeneratorStep (/Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/@babel/core/lib/vendor/import-meta-resolve.js:63:103)
    at _next (/Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/@babel/core/lib/vendor/import-meta-resolve.js:65:194)
    at /Users/xiaoqiangjiang/source/reddwarf/frontend/react-admin/node_modules/@babel/core/lib/vendor/import-meta-resolve.js:65:364
    at new Promise (<anonymous>)

I have tried to delete the node_modules folder and reinstall but did not work. this is the package.json about babel:

    "@babel/core": "^7.17.5",
    "@babel/preset-react": "^7.16.7",
    "@fingerprintjs/fingerprintjs": "^3.3.2",
    "@svgr/webpack": "4.3.3",
    "@typescript-eslint/eslint-plugin": "^2.10.0",
    "@typescript-eslint/parser": "^2.10.0",
    "animate.css": "^3.7.2",
    "antd": "^4.17.4",
    "axios": "^0.19.0",
    "babel-eslint": "10.1.0",
    "babel-jest": "^24.9.0",
    "babel-loader": "^8.2.3",
    "babel-plugin-named-asset-import": "^0.3.6",
    "babel-preset-react-app": "^9.1.2",

why did this error happen? what should I do to fix this problem?

Downloading File Object from C# API Controller to Client using Javascript

I am trying to return a file for a user to download when they click a download button on the page. The trick is I am downloading the file from an internal URL service. I have it set up as follows

The Download controller a function I call to return the File()

    public class DownloadController : ControllerBase
    {
        public FileResult DownloadFile(string url)
        {
            WebClient internalDownload = new WebClient();
            byte[] bytes = internalDownload.DownloadData(url);

            return File(bytes, "application/octet-stream", "test" + ".txt");
        }
    }

The API Controller this is what the JS calls

    public class TickController : ApiController
    {
        [Route("api/Tick/Download")]
        [HttpPost]
        public async Task<IActionResult> Download([FromBody] string ID)
        {

            string url = await GetFile("D00023974");
            DownloadController downloader = new DownloadController();

            return downloader.DownloadFile(url);

            

        }
    }

The Javascript I have for testing purposes at the moment

The API Manager Javascript which sends the request to the above Controller:

export class ApiCall {
    static post(controller: string, action: string, data: any, qString?: string) {
        var url = '/api/' + controller;
        if (action != null)
            url += '/' + action;
        if (querystring != null)
            url += "?" + qString;
        return $.ajax({
            url: url,
            data:JSON.stringify(data),
            method: 'POST',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
        });
    }
}

And the current test call and checking if its returning anything

async downloadAttach(ID: any) {
        window.open(await WebApiManager.post('Incident', 'Download', ID));
}

The above returns an object as follows:

[[Prototype]]     Object
ContentType       application/octet-stream
FileContents      //Filled with Base64
FileDownloadName  test.txt
_proto_           Object

However I’m not sure how to initiate the download on the client side of the returned file. Any help would be greatly appreciated.

Cascading dropdown using Vuejs

I am trying to create a cascading dropdown using Vuejs.
I want to set the data on the second dropdown based on the Item chosen from the first dropdown.
I don’t know how filter the data based on the chosen item
I’ve tried to use computed but didn’t succeed.
I need some help please.
Thanks in advanced.

<template>
  <b-container class="my-2">
    <b-row>
      <b-col col="12" md="6" lg="3">
        <b-form-group id="fieldset" :label="$t('tradingCalculators.fields.currencyPair')" label-for="currency-first" label-size="lg">
              <v-select
                id="assetPair"
                @click="changeAssetClass(assetPair)"
                v-model="assetPair"
                :searchable="true"
                :options="assetSymbols"
              />
            </b-form-group>
          </b-col>
          <b-col cols="12" md="6" lg="3">
            <b-form-group id="fieldset-1"               :label="$t('tradingCalculators.fields.currencyPair')" label-for="currency-pair" label-size="lg">
              <v-select id="symbolsPair" v-model="symbolsPair" :searchable="true" :options="currencyArray" />
            </b-form-group>
      </b-col>
    </b-row>
  </b-container>
</template>

export default {
data() {
assetPair: ‘Forex’,
symbolsPair: ”,
currencyArray: [],
assetsSymbols: [{
text: ‘Forex’,
id: 1
},
{
text: ‘Metal’,
id: 2
},
{
text: ‘Indices’,
id: 3
},
],
symbolsPair: {
1: [{
text: ‘AUDCAD’,
id: 1,
},
{
text: ‘AUDCHF’,
id: 2,
},
{
text: ‘AUDJPY’,
id: 3,
},
],
2: [{
text: ‘XAUUSD’,
id: 1,
},
{
text: ‘XAGUSD’,
id: 2,
},
],
3: [{
text: ‘GER30Cash’,
id: 1,
},
{
text: ‘US30Cash’,
id: 2,
},
{
text: ‘EU50Cash’,
id: 3,
},
],
}
},
computed() {
changeAssetClass(e) {
return this.currencyArray.push(this.symbolsPair[e])
}
}
}

Retained Size in Chrome devTools memory tab

I have attached three different variables to window Object. But why devTools show same retained size for them?

  let a = 23;

  let b = {
    'a': 1,
    'b': 2,
    'c': 3
  };

  let c = () => {
    console.log('I am a simple function')
  };
  
  Window.myNnum = a;
  Window.myObj = b;
  Window.myFunc = c;

Result: They all have 20 Bytes in Retained-Size and Shallow-Size, as below picture:

enter image description here

Hello, I need to implement a Button in ReactJS Table, to sort the items from the table

so this is my Code :

import products from "../products_json/products.json";
import "./style.module.css";
import { useState } from "react";

const Table = () => {
  const ProductsDisplay = products.map((info) => {
    return (
      <tr>
        <td>{info.id}</td>
        <td>{info.itemName}</td>
        <td>{info.category}</td>
        <td>{info.price}</td>
        <td>{info.manufacturer}</td>
        <td>{info.productionDate}</td>
      </tr>
    );
  });


  return (
    <div>
      <table class="table">
        <thead>
          <tr>
            <th>ID</th>
            <th>Item Name</th>
            <th>Category</th>
            <th>Price</th>
            <th>Manufacturer</th>
            <th>Production Date</th>
          </tr>
        </thead>
        <tbody>{ProductsDisplay}</tbody>
      </table>

      <div className="wrapper">
        <button>Sort by Price</button>
        <button>Sort By manufacturer</button>
        <button>Reset</button>
      </div>
    </div>
  );
};

export default Table;

I would like to do a sorting by Manufacturer, Price & reset button (which bring back the default table).
Since Im a complete beginner yet, im not quite sure how to implement that by useState hook, or just by simply creating a function.
I have the basic ideda of how to do it – for example some kind of

function () => {
 ProductsDisplay.info.price.sort((a,b) => a-b);
}

and then add an onClick in the button, but as I said im not very familiar with the syntax and practices yet, so a hint would be of huge help.
Thanks in advance !

How to design a complex function for scalability?

I have an app that needs to process various types of user uploaded files. The most common is images.

However not all images are handled in the same way. How they are processed depends on what they’ll be used for e.g. a product image needs to be much bigger size than a profile picture.

I have made a single function called processImage() which takes in arguments about the image that needs processing and creates different size images etc.

Its layout is like this:

mediahandler.js

processImage({ area, usage, uploadto, filepath, mimetype, etc, etc });
{
  // This could be a number of places like S3, Google Drive

  if (area === "Shop") {
    // What area will this image be used in? Determines properties and metadata of images

    if (usage === "Hero") {
      // What is the purpose of the image?
      // Hero images will be large and high quality

      if (uploadto === "SSD") {
        // Now write to serveer hard drive using file system
      } else if (uploadto === "S3") {
        // Now upload to S3 using a buffer
      }
    } else if (usage === "Thumbnail") {
      // Thumbnails will be small and low quality
      if (uploadto === "SSD") {
        // Now write to serveer hard drive using file system
      } else if (uploadto === "S3") {
        // Now upload to S3 using a buffer
      }
    }
  }
}
// Other functions
 processVideo(){ }

As you can see the number of if/else or even switch statements grows quickly. I fear this will be end up becoming a huge convoluted do-it-all function which may not scale well (I really don’t know if this is even a legitimate concern).

If I was to break this function apart and create several functions e.g. processStoreImage() and processPofileImage() then I will end up repeating a lot of code between them and violate the DRY (Don’t Repeat Yourself) principle.

Is there a ‘better’ way of going about this?

React context not shared between components

I use a react context between 2 components, however when I set the value this context in the child filtersBar component, it does not update or useffect in the second child map component.

contextprovider

const SearchContext = createContext();

const SearchContextProvider = ({children}) => {
const [contextValue, setContextValue] = useState(null);            
    return (
    <SearchContext.Provider value={[contextValue, setContextValue]}>
        {children}
    </SearchContext.Provider>
);

index.js

 <SearchContextProvider>
    <FiltersBar/>
      <Map/>
    </SearchContextProvider>

Filtersbar.js

const FiltersBar = () => {
        const [searchContext,setSearchContext] = useContext(SearchContext);
        const [searchLocationResult, setsearchLocationResult] = useState(null);
        const [inputSearchLocation, setinputSearchLocation] = useState("");
  
 useEffect(() => {
       /// stuff
              setSearchContext(searchContext)

        }, [searchLocationResult, inputSearchLocation]);

Map.js

const Map = () => {
  
    const [searchContext, setSearchContext] = useContext(SearchContext);


    useEffect(() => {
      console.log("use effect map"+JSON.stringify(searchContext))
    }, [searchContext]);

I never see this use effect map console log message. What am I missing?

CryptoJS: Can’t decrypt string sent from Browser in NodeJS sometimes

I have a web browser client that uses CryptoJS in JavaScript. It encrypts a string and sends it to a NodeJS server.

When I try to decrypt the string on my NodeJS server, sometimes it works, sometimes it doesn’t. It either gives a “Malformed UTF-8” data error or a “Unexpected end of JSON input” error.

Browser JavaScript code (encryption):

// Using CryptoJS via: https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js

var ENCRYPTION_KEY = "6268890F-9B58-484C-8CDC-34F9C6A9";
var ENCRYPTION_IV = "6268890F-9B58-48";

var data = {"hey": "hello"};
var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), ENCRYPTION_KEY, {iv: ENCRYPTION_IV}).toString();
console.log("ciphertext:", ciphertext);

$.ajax({

        url: "http://127.0.0.1/testEndpoint/"
        type: "GET",
        timeout:2000,
        data: ciphertext,
        statusCode: {
            200: function (response) {
                console.log("Success!");
            },
        }
        
 });

NodeJS Express Server code (decryption):

const WEB_PORT = 1234;

var CryptoJS = require("crypto-js");
var AES = require("crypto-js/aes");

var ENCRYPTION_KEY = "6268890F-9B58-484C-8CDC-34F9C6A9";
var ENCRYPTION_IV = "6268890F-9B58-48";

const express = require('express')
const app = express();

app.listen(WEB_PORT, () => {
    console.log("Listening...");
});

app.get('/testEndpoint/', (req, res) => {
    let ciphertext = Object.keys(req.query)[0];
    console.log("ciphertext from browser:", ciphertext);

    var bytes = CryptoJS.AES.decrypt(ciphertext, ENCRYPTION_KEY, {iv: ENCRYPTION_IV});
    var decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
    console.log("decryptedData:", decryptedData);       
});

Browser output (one time when it didn’t work [1]):

ciphertext: U2FsdGVkX19Epx6VAqYM48Q63NOVzrA+5A4zswQTv08=

NodeJS output (one time when it didn’t work [1]):

ciphertext from browser: U2FsdGVkX19Epx6VAqYM48Q63NOVzrA 5A4zswQTv08
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)

Browser output (another time when it worked [2]):

ciphertext: U2FsdGVkX19NRRozkZiJV/564MGE2keF4HHwqsEtkmw=

NodeJS output (another time when it worked [2]):

ciphertext from browser: U2FsdGVkX19NRRozkZiJV/564MGE2keF4HHwqsEtkmw
decryptedData: { hey: 'hello' }

Why does it only work sometimes, and other times it either gives an “Unexpected end of JSON input” or “Malformed UTF-8” error?

How to hide private key in Javascript Web3

I want to send signTransaction using web3, the problem is that for doing that, I need to use the privateKey of my Metamask account. Anyone could see the “privatekey” from explorer.

So how can I hide this variable in javascript for using it safety?
The line of code in javascript in frontend is the following:

web3.eth.accounts.signTransaction(rawTransaction, privateKey)

I would like to store the privatekey in backend and make a call to backend to obtain it, how should I do it in a safety way?

Thanks in advance.