overwrite js file with another js file without webserver

Explanation:
I am working on a local web application which should use a local javascript file as database. Why? Because I dont want to use any database for this project as I want to avoid using a webserver, mainly to find out “what is possible“. So far so good, I am able to display the provided data in a html table.

Question:
How could I overwrite the existing data.js with this approach?

data = [
    {"firstname" : "Dagobert", "lastname": "Duck"},
    {"firstname" : "Daisy", "lastname": "Duck"},
    {"firstname" : "Mickey", "lastname": "Mouse"},
    {"firstname" : "Minnie", "lastname": "Mouse"}
  ];
  
<!DOCTYPE html>
<html lang="de">

<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <!-- title -->
    <title>Example</title>

    <!-- jQuery -->
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

    <!-- Import JS-->
    <script type="text/javascript" src="data.js"></script>
</head>

<body>
    <table id="table">
        <tbody>
            <th>Firstname</th>
            <th>Lastname</th>
            <!-- filled by script -->
        </tbody>
    </table>
    <button id="overwrite">overwrite</button>
    
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            let table = document.getElementById("table")
           
            data.forEach(item => {
                var row = `<tr>
                            <td class="name">${item.firstname}</td>
                            <td class="name">${item.lastname}</td>
                            </tr>`

                $("#table tbody").append(row)
            });
        })

        document.getElementById("overwrite").addEventListener("click", function() {
            console.log("change existing data.js")
            
            update = [
            {"firstname" : "Dagobert", "lastname": "Duck"},
            {"firstname" : "Daisy", "lastname": "Duck"},
            {"firstname" : "Mickey", "lastname": "Mouse"},
            {"firstname" : "Minnie", "lastname": "Mouse"},
            {"firstname" : "Cat", "lastname": "Karlo"},
            {"firstname" : "Gus", "lastname": "Goose"}
        ];

        })

    </script>
</body>

</html>

How can i use the same design with different data different pages in reactjs

I have a component called home pages where navbar i using i like use this same navber with my another component called shop.js with different data

This is the home component

const Home = () => {
    return (
        <React.Fragment>
            <Header/>
        </React.Fragment>
    );
};

This is the header component

const Header = () => {
    return (
        <header>
            <TopModal/>
            <Navbar/>
            <HeroSlider/>
        </header>
    );
};

This is the Shop.js components

export default function Shop() {
    return (
        <React.Fragment>
            {/*this component coming from home component*/}
            <Header/>
        </React.Fragment>
    )
}

I want to change the navbar value in shop.js?

Nextjs app with proxy – headers not included in response

I’m proxying requests to an external backend from a Nextjs app and trying to extract an
Authorization header from the response using the native fetch library. However the headers in the fetch response are empty even though they are present in the actual response from the server.

Here’s the setup in the next.config.js file:

module.exports = {
  async headers() {
    return [
      {
        source: '/api/:path*',
        headers: [
          {
            key: 'Access-Control-Expose-Headers',
            value: '*, authorization',
          },
        ],
      },
    ]
  },
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: `${process.env.NEXT_PUBLIC_BASE_URL}/api/:path*`,
      },
    ]
  },
}

With my limited knowledge of proxies I’m assuming that it’s a reverse proxy and the headers are lost in the response back somewhere inside it.
I’ve also tried adding a middleware to try to localize where the headers are being lost without any luck.

Does anyone know where I can configure the headers to be included back from the proxy?

Thanks in advance! 🙂

how to reduce to one object by same key value in javascript

I’m looking for reduce elements of array to one object by same key (id).
I try to use Array.reduce, but cannot reduce same id elements.
Actually I don’t really full understand Array.reduce‘s mechanism… 🙁
Can anybody help me?

const arr = [{id: 1, value: 1, key: 'email'}, {id: 1, value: 1, key: 'status'}, {id: 2, value: 2, key: 'email'}, {id: 2, value: 2, key: 'status'}];

// EXPECTED
const arr = [{id: 1, data: {'email': 1, 'status': 1}}, {id: 2, data: {'email': 2, 'status': 2}}];

// WHAT I DO
const result = arr.reduce((acc, cur)=>{
  const {id, key, value} = cur;
  acc.forEach(el => {
    if (el.id === id) {
      el.data[key] = value;
    }
  })
  acc = [...acc, {'id': id, 'data': { [key]: value }}];
  
  return acc
}, [])

// WHAT I GET
[
  { id: 1, data: { email: 1, status: 1 } },
  { id: 1, data: { status: 1 } },
  { id: 2, data: { email: 2, status: 2 } },
  { id: 2, data: { status: 2 } }
]

Only accepting values > 100000 into an array, those below 100000 will count as 1

I’m a beginner to Java and trying to code a program that will take in the number of views for each episode of a netflix series and eventually give me back the average number of views. However, I have been told to only count view numbers above 50000, anything below will count as 1 view. How would I implement this?

public class assignmentnetflix {
       public static void main(String[] args)
     
       {
             Scanner input = new Scanner(System.in);

             int[] NetflixShow;
             NetlixShow = new int[10];   
             
             for( int i = 0; i < 10; i++) { 
              System.out.println("Enter the number of views of Season 4 Episode " + (i+1));
              NetflixShow[i] = input.nextInt(); }

             input.close();
}

Data attributes and HASH [closed]

I have two tab buttons with data attributes ( data-tab ). When I click any of them they attached hash to the url. I need logic in which when data attribute of the button is equl to the current hash in the url to add active class to that button.

<div class="switcher-container fade-el">
  <a href="#tab1" class="tab" data-tab="tab1">Tab1</a>
  <a href="#tab2" class="tab" data-tab="tab2">Tab2</a>
</div>

While testing in javascript, Variables defined in ‘before’ block is showing undefined while using in ‘It’ block

This is a sample test where I am testing that testNum should be 0,

code:

describe("Test Contract", () => {
    
    before(async () => {
        const testNum = 0;
    })
    
    it("should be zero", function () {
        expect(testNum).to.equal(0);
    })
  }

But I am getting an error saying testNum is undefined.

Error:

1) Test Contract
       should be zero:
     ReferenceError: testNum is not defined

What I am doing wrong?

Open Printer window programmatically with predefined Destination by JS or PHP

I’m developing Laravel and React application. Here need to print document to different printer in our network.
Now need to select printer Destination when execute window.print() by clicking print button.
Already fetch all connected printer list by php.
Now need to open printer preview window with pre-defined Destinationo of printer
programmatically by JS or PHP.

Here how to fetch all connected printer.

// Get printer property by key
function getPrinterProperty($key){
    $str = shell_exec('wmic printer get '.$key.' /value');

    $keyname = "$key=";
    $validValues = [];
    $fragments = explode(PHP_EOL,$str);
    foreach($fragments as $fragment){
        if($fragment == ""){
            continue;
        }
        if (preg_match('/('.$keyname.')/i', $fragment)) {
            array_push($validValues,str_replace($keyname,"",$fragment));
        }
    }
    return $validValues;
}

$Name = getPrinterProperty("Name");
$Description =  getPrinterProperty("Description");
$Network = getPrinterProperty("Network");
$Local = getPrinterProperty("Local");
$PortName = getPrinterProperty("PortName");
$Default = getPrinterProperty("Default");
$Comment = getPrinterProperty("Comment");

$Printers = [];
foreach($Name as $i => $n){
    $Printers[$i] = (object)[
        "name" => $n,
        "description" => $Description[$i],
        "Portname" => $PortName[$i],
        "isDefault" =>($Default[$i] == "TRUE")? true : false,
        "isNetwork" => ($Network[$i] == "TRUE")? true : false,
        "isLocal" =>($Local[$i] == "TRUE")? true : false,
        "Comment" => $Comment[$i],
    ];
}

//var_dump($Printers);
echo json_encode($Printers);

Here is the result:

[
  {
    "name": "OneNote (Desktop)",
    "description": "",
    "Portname": "nul:",
    "isDefault": false,
    "isNetwork": false,
    "isLocal": true,
    "Comment": ""
  },
  {
    "name": "Microsoft XPS Document Writer",
    "description": "",
    "Portname": "PORTPROMPT:",
    "isDefault": false,
    "isNetwork": false,
    "isLocal": true,
    "Comment": ""
  },
  {
    "name": "Microsoft Print to PDF",
    "description": "",
    "Portname": "PORTPROMPT:",
    "isDefault": true,
    "isNetwork": false,
    "isLocal": true,
    "Comment": ""
  },
  {
    "name": "Fax",
    "description": "",
    "Portname": "SHRFAX:",
    "isDefault": false,
    "isNetwork": false,
    "isLocal": true,
    "Comment": ""
  },
  {
    "name": "EPSONED54D8 (L4160 Series)",
    "description": "",
    "Portname": "WSD-45eaf325-9cd7-4461-9a57-a3a14dd9ef18",
    "isDefault": false,
    "isNetwork": false,
    "isLocal": true,
    "Comment": ""
  }
]

JS: Now want to open printer window.print() by Portname or name.
PHP: shell_exec('Get-Printer -Name "Microsoft Print to PDF"');

Not working, Is it possible?
Open Printer window programmatically with predefined Destination by JS or PHP.

map.getView().fit() and image problems in openlayers

I want to make an “Add Area” function. After clicking on the map the popup for entering the Area name will be showing and after confirming the name, the map should be automatically zooming to the area with padding {100,100,100,100} and the image marker will be showing.
But my image marker(.png and .svg) is not showing, then it zooms too deep. It seems my padding didn’t work well.

AddArea.js

import 'ol/ol.css';
import Draw from 'ol/interaction/Draw';
import Map from 'ol/Map';
import View from 'ol/View';
import {toLonLat} from 'ol/proj';
import {toStringXY} from 'ol/coordinate';
import {OSM, Vector as VectorSource} from 'ol/source';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import {fromLonLat} from 'ol/proj';
import Swal from 'sweetalert2/dist/sweetalert2.js'
import 'sweetalert2/src/sweetalert2.scss'

const map=$('#map').data('map');

const vectorSource = new VectorSource();
const vector = new VectorLayer({
  source: vectorSource,
  style: new Style({
     image: new Icon({
         anchor: [0.5, 1],
         anchorXUnits: "fraction",
         anchorYUnits: "fraction",
         src: "pin.png"
     })
 })
});

var vectorLayer = new VectorLayer({
  source: new VectorSource(),
});
map.addLayer(vectorLayer);

let draw;
function addInteraction() {
    map.addLayer(vector);
    draw = new Draw({
    source: vectorSource,
    type: "Point",
  });
map.addInteraction(draw);
}


$('#add-area-btn').click(function(){
   addInteraction();

map.on('singleclick', function (evt) {

Swal.fire({
  position: 'top',
  title: 'Input area name',
  input: 'text',
  inputPlaceholder: 'Enter area name',
  showCancelButton: true,
  allowOutsideClick: false,
  inputValidator: (value) => {
     
    if (!value) {
      return 'You need to write something!'
    }
    else {

      map.getView().fit(vectorSource.getExtent(),  
      {
        size: map.getSize,
        padding:[100,100,100,100]
      });
      vector.getSource().clear(true);
      map.removeLayer(vector);
      map.getInteractions().pop();

      //Enable click function
      map.un('click', callback);
    }
  }
}).then((result) => {
  //Cancel button clicked
  
  if (result.dismiss == Swal.DismissReason.cancel) {
    Swal.fire({
      position: 'top',
      icon: 'info',
      title: 'Area Canceled'
    });
    vector.getSource().clear(true);
    map.removeLayer(vector);
    map.getInteractions().pop();

    //Enable click function
    map.un('click', callback);
   }
  })
 });
})

That’s my code and hope someone can help me…
Thank you…

Using Array.fill() with Array.splice() togerther doesn’t work

while solving this, I had to use something like the following lines of code where the line right after for loop didn’t work!

function staircase(n) {
    for(let i = 1; i <= n; i++){
       const e = Array(n).fill(' ').splice(n - i, i, ...Array(i).fill('#'));
       console.log(e.join(''))
    }
}

But, the following did!

function staircase(n) {
    for(let i = 1; i <= n; i++){
       const e = Array(n).fill(' ');
       e.splice(n - i, i, ...Array(i).fill('#'));
       console.log(e.join(''))
    }
}

I wonder, why using splice() with fill() in one line didn’t work!

Continue to receive server sent event after leaving and returning to a page

I have an EventSource that does nothing initially:

var source = new EventSource('{{do_nothing}}');

Then I trigger something in my flask backend and it changes my ‘do_nothing’ to a server sent event:

var source = new EventSource('/my_event');

and this server sent event will start sending (yielding) data where my source will pick it up and do stuff:

source.onmessage = function(event) { get(event.data) do stuff }

however if I leave the webpage; and return to the web page again, or open up the web page in another browser the event is no longer occurring on the newly opened page.

How do I make it so if I return to the same page that I will continue to get the output of the server sent event until the server sent event completes itself?

CSS – How to transform image to scale (HammerJS)

I am currently using Vue 3 Composition API, TypeScript and HammerJS package to implement a simple pinch zoom.

I having issues scaling my image. I have went through some other pages in StackOverflow on Merging CSS transforms but I still could not scale my image.

As you can see below image, the image is supposed to dynamically scale based on the 3 values. But it is not scaling at the moment
Image is here.

I am wondering if there is anything wrong with my css syntax. If anyone could help me with this, appreciate it.

I have included my code in Stackblitz: https://stackblitz.com/edit/vue-vc5rdt

Here is my code below:

<template>
<div class="outer">
  <div class="container">
    <p>{{ currentScale }}</p>
    <p>{{ currentDeltaX }}</p>
    <p>{{ currentDeltaY }}</p>
    <div>
      <div class="border">
        <img id="stage"
          v-pinch
          ref="stage"
          src="https://source.unsplash.com/random"
          class="image"
          :style="{ 'transform': 'translate(' + `${currentDeltaX}` + 'px,' + `${currentDeltaY}` + 'px) scale(' + `${currentScale}`  + 's)' }"
          >
      </div>
    </div>
  </div>
</div>
</template>

<script setup lang="ts">
import Hammer from "hammerjs";
import { ref, defineProps } from "vue";

  const adjustDeltaX = ref<number>(0);
  const adjustDeltaY = ref<number>(0);
  const adjustScale = ref<number>(1);
  
  const currentDeltaX = ref<number>(0);
  const currentDeltaY = ref<number>(0);
  const currentScale = ref<number>(0);

const props = defineProps({
  enableTouchControl: {
    type: Boolean,
    required: false,
    default: true
  }
})
const stage = ref<HTMLImageElement|null>(null);

const vPinch = {
  created(el: any, binding: any) {
    const mc = new Hammer(el);
    mc.get("pinch").set({ enable: true });
    mc.on("pinch panmove pinchmove", function(e: any) {
      console.log('pinchmove')
      currentScale.value = adjustScale.value * e.scale;
      currentDeltaX.value = adjustDeltaX.value + (e.deltaX / currentScale.value);
      currentDeltaY.value = adjustDeltaY.value + (e.deltaY / currentScale.value);
      console.log(currentScale.value, currentDeltaX.value, currentDeltaY.value)
    });
  },
};
</script>

<style>
.outer {
  margin: 1em;
  display: flex;
  justify-content: center;
  height: 100vh;
}
.container {
  background: #222;
  border: 2px solid #ccc;
  border-radius: 5px;
  height: 85%;
  width: 85%;
  padding: 1em;
  overflow: hidden;
  font-family: "Trebuchet Ms", helvetica, sans-serif;
}
img {
  width: 400px;
}
</style>

Javascript function not returning dictionary which it should be

I currently have two javascript functions which both produce the desired result alone, however when together do not.

The first function is process results. All this does is log the result of calling another function, textToTime. The text to time function accepts a dictionary and returns another dictionary, with a string time converted to an integer time.

For example,

textToTime({A: "32 min", B: "1 hour 10 min" C: "2 hours 1 min"})

should return

{A: 32, B: 70, C: 121}

Here are the following functions:

async function processResults(options) {
    var bestOption = "";
    var display = false;
    options = await textToTime(options);
    console.log(options);
}
function textToTime(options) {
    for (var key in options) {
        let total = 0;
        let current = options[key];
        if (current == "n/a") {
            total = -1;
        }
        else {
            var num = "";
            for (let i = 0; i < current.length; i++) {
                if (isNumeric(current.charAt(i))) {
                    num += current.charAt(i);
                }
                else {
                    if (current.charAt(i) == "h") {
                        total += 60 * parseInt(num);
                        num = "";
                    } 
                    if (current.charAt(i) == "m") {
                        total += parseInt(num);
                        num = "";
                    }
                }
            }
        }
        options[key] = total;
    }
    return options;
}

When I run textToTime alone, it always produces the correct output, however when I call it from inside processResults, it tends to return only part of the dictionary with integers and the rest still in the string format like: {A: 32, B: "1 hour 10 min", C: "2 hours 1 min"}

Any knowledge or support is greatly appreciated!

Reactjs App cannot build due to some dependency issue

After I delete node_modules and reinstall everything of my reactjs project, I can still run yarn start no problem, but when yarn build:

yarn run v1.22.4
warning ../../../package.json: No license field
$ craco build
craco:  *** Cannot find ESLint loader (eslint-loader). ***
Creating an optimized production build...
(node:54555) [DEP_WEBPACK_COMPILATION_NORMAL_MODULE_LOADER_HOOK] DeprecationWarning: Compilation.hooks.normalModuleLoader was moved to NormalModule.getCompilationHooks(compilation).loader
(Use `node --trace-deprecation ...` to show where the warning was created)
/Users/example_app/node_modules/react-scripts/scripts/build.js:19
  throw err;
  ^

TypeError: dependency.getCondition is not a function
    at ModuleGraph.setResolvedModule (/Users/example_app/node_modules/react-scripts/node_modules/webpack/lib/ModuleGraph.js:196:15)
    at /Users/example_app/node_modules/react-scripts/node_modules/webpack/lib/Compilation.js:1850:20
    at /Users/example_app/node_modules/react-scripts/node_modules/webpack/lib/util/AsyncQueue.js:352:5
    at Hook.eval [as callAsync] (eval at create (/Users/example_app/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:6:1)
    at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (/Users/example_app/node_modules/tapable/lib/Hook.js:18:14)
    at AsyncQueue._handleResult (/Users/example_app/node_modules/react-scripts/node_modules/webpack/lib/util/AsyncQueue.js:322:21)
    at /Users/example_app/node_modules/react-scripts/node_modules/webpack/lib/util/AsyncQueue.js:305:11
    at /Users/example_app/node_modules/react-scripts/node_modules/webpack/lib/Compilation.js:1303:4
    at /Users/example_app/node_modules/react-scripts/node_modules/webpack/lib/Cache.js:85:6
    at /Users/example_app/node_modules/react-scripts/node_modules/webpack/lib/Cache.js:39:11
error Command failed with exit code 1.

I am not sure what happened. Can’t really figure out how to resolve this by reading the error.