Update data in Barchart from API in Vue

Calling an Api to get the values and putting them in the List but the list in data function is not being updated.

created(){

  // API CALL FOR BARCHAR
var getStandardBarchart = async() => {
  //var currentarray =[]

   // API CALL TO KEIKAI for BARCGARTS
   var myHeaders = new Headers();
   myHeaders.append("Content-Type", "application/json");
   //var raw = JSON.stringify({"input_values": input_values, "output_values": output_values});
   var raw = JSON.stringify({"input_values": {},"output_values": [ "barchart1","barchart2","barchart3","barchart4","barchart5","barchart6","barchart7","barchart8"  ]});

   var requestOptions = {
     method: 'POST',
     headers: myHeaders,
     body: raw,
     redirect: 'follow'
   };


   await fetch("/api", requestOptions)
     .then(response => response.json())
     .then(result => {
        var barChart = [];

        //var value
        Object.keys(result).forEach(function(key) {
        let specificValue = parseInt(result[key])
          barChart.push(specificValue) 
        })
        console.log(barChart)
        console.log(this.Agricultural_production_Animal_production_Cattle[1].imagecontent.barchart1.values[0][2])
       // this.Agricultural_production_Animal_production_Cattle[1].imagecontent.barchart1.values[0][1]=15

        // this.Agricultural_production_Animal_production_Cattle[1].imagecontent.barchart1.values[0] = barChart.splice(0, 4);
        // this.Agricultural_production_Animal_production_Cattle[1].imagecontent.barchart1.values[1] = barChart.splice(0, 4);


      })
     .catch(error => console.log('error', error));



 }

getStandardBarchart()







},

What I want is that the values in the data function should be updated by the barchart[] list. But if I push something in list before api or give some default value to the list it is not undefined
in Values:[barchart[0]] gives undefined

data:function(){
{imagecontent:

   {barchart1:{barid: "bar_Agricultural_production_Animal_production_Cattle",names:["sdjhfb", "derfgas", "Pdft", "dfdfs", "dfsdfat"],
   values:[[barchart[0], 10, 5, 150],[87, 80, 25, 35]],
   textxaxis:["future", "present"] }}
   }]
}

}

Understand why an else command is in a different position

I’m studing Javascript with FreeCodeCamp, till now everything is clear but I’ve a stupid question that I’ven’t understood:

function lookUpProfile(name, prop) {
  for (let x = 0; x < contacts.length; x++) {
    if (contacts[x].firstName === name) {
      if (contacts[x].hasOwnProperty(prop)) {
        return contacts[x][prop];
      } else {
        return "No such property";
      }
    }
  }
  return "No such contact";
}

Why return "No such contact"; is after the for cycle and not the if that control the contact name?!

Vue Metamask Login App Can’t Interact with Metamask Because The Store Components Won’t Interact with The Frontend

I followed this tutorial to try to create a Metamask login app with Vue https://duartefdias.medium.com/authenticating-users-to-your-web-app-using-metamask-and-nodejs-e920e45e358. The code is described in individual files but there isn’t a defined project structure. I made my own github repo to try to organize the structure in terms of where each file should go in the project https://github.com/ChristianOConnor/metamask-vue-for-debug. The app compiles but the button to connect/install Metamask doesn’t do anything.

This is the actual code that displays the connect to Metamask functionality:

<template>
  <div>
    <button
      color="primary"
      large
      :disabled="buttonDisabled"
      v-on:click="performAction"
    >
      <img src="../assets/metamaskloginbutton.png" class="metamask-logo" />
      <span v-if="isMetaMaskInstalled()">Login with Metamask</span>
      <span v-if="!isMetaMaskInstalled()">{{ buttonInstallText }}</span>
    </button>
  </div>
</template>

This is the function that’s supposed to determine whether Metamask is installed:

isMetaMaskInstalled() {
      //Have to check the ethereum binding on the window object to see if it's installed
      if (process.client) {
        return Boolean(
          this.$store.getters["metamask/ethereum"] &&
            this.$store.getters["metamask/ethereum"].isMetaMask
        );
      }
      return false;
    },

This function always returns false even though Metamask IS installed in the browser through which I am accessing the site.

I spoke with the author of the code and he said that my problem is that I’m not accounting for the vue store and I need to add the code ethereum: state => { if(process.client) { return window.ethereum } } but he never specified where. I read up on the vue store with articles like this one https://www.digitalocean.com/community/tutorials/how-to-manage-state-in-a-vue-js-application-with-vuex. This article didn’t help though. I tried to get the store to work by altering the store/index.js file like this

store/index.js

import { createStore } from "vuex";

export default createStore({
  state: {},
  getters: {
    ethereum: () => {
      if (process.client) {
        return window.ethereum;
      }
    },
  },
  mutations: {},
  actions: {},
  modules: {},
});

Btw I had to remove state from ethereum: state => { if(process.client) { return window.ethereum } } because prettier wouldn’t allow the code to compile with an unused parameter.

Why does isMetaMaskInstalled() always return false even when I add ethereum: state => { if(process.client) { return window.ethereum } } to the store/index.js file?

I’m assuming this code is failing because I’m putting ethereum: state => { if(process.client) { return window.ethereum } } in the wrong spot. Where am I supposed to put this code?

why this javascript code only works once? [duplicate]

Can someone tell me what’s wrong with this js code? it only works once, i want it to work every time i hit the document.querySelector(“.icon-right”);

const background = document.querySelector(".mainimage");
const right = document.querySelector(".icon-right");
right.addEventListener("click", () => {
  if (background.style.backgroundImage = "url(../img/1.jpg)") {
    background.style.backgroundImage = "url(../img/2.jpg)";
  } else if (background.style.backgroundImage = "url(../img/2.jpg)") {
    background.style.backgroundImage = "url(../img/3.jpg)";
  } else {
    background.style.backgroundImage = "url(../img/1.jpg)";
  }
});

How to add properties to a JSON in TypeScript?

I have the following code:

type DailySummaryEntrry = {date: string, summary: ParsedSummary};

function parseDailySummaries (summaries: DailyRawSummaries): DailySummaryEntrry[] {
  const entries: DailySummaryEntrry[] = [];

  for (const date in summaries) {
    const rawSummary = summaries[date];
    if (!rawSummary) continue;
    entries.date = date ;
    entries.summary= parseRawSummary(rawSummary);
  }
  return entries.sort().reverse(); // sort by newest date first
}

I don’t know why do I get

Property 'date' does not exist on type 'DailySummaryEntrry[]'.deno-ts(2339)

at this line
entries.date = date ;

and:

Property 'summary' does not exist on type 'DailySummaryEntrry[]'.deno-ts(2339)

At this line

entries.summary= parseRawSummary(rawSummary);

How to get browser certificate to digitally sign a payload using Chrome Extension

I am working on a chrome extension to get access to the list of certificates on my browser (Including the class 3 certificate I purchased).

This is the manifest.json

 {
"manifest_version": 2,
"name": "Coding Train Extension 2",
"version": "0.001",
"permissions": ["storage", "activeTab", "scripting"],
"content_scripts": [
    {
        "matches":["<all_urls>"],
        "js": ["content.js"]
    }
],
 "background":{
   "scripts": ["background.js"]
 },
 "browser_action":{
   "default_icon": "logo.png"

 }
} 

This is the background.js

 console.log("This is inside background...");
 chrome.browserAction.onClicked.addListener(collectAvailableCertificates);

 function collectAvailableCertificates() {
   // Return all certificates that this Extension can currently provide.
   // For example:
   return [{
     certificateChain: [new Uint8Array()],
     supportedAlgorithms: ['RSASSA_PKCS1_v1_5_SHA256']
    }];
   }

In this test, the content.js is not being used much. I have an icon of the extension on browser and on its click I am triggering the background.js.
I am trying to emulate the APIs provided in the Chrome API documentation https://developer.chrome.com/docs/extensions/reference/certificateProvider/

How to call the methods like collectAvailableCertificates(), handleSignatureRequest(request) as seen in the document is what I am pursuing. My aim is to use this purchased certificate to digitally sign an xml payload.

Issue with sending FormData from backend

I have a component which processes and uploads images. Currently I process the image on my backend and then send it to my frontend and then upload it from there. I would like to do everything on my backend. The only issue is that the upload endpoint requires FormData() object. I found an npm package form-data which I’m using on my backend now, but I’m still getting error.

This is how my frontend does it:

const data = await uploadImage(img) // I would like to move logic bellow to this backend function.
const file = new File([Buffer.from(data)], `img-${i}.webp`, {
  type: "image/webp",
});
const formData = new FormData();
formData.append("path", "images");
formData.append("files", file, file.name);
await axios
  .post("http://localhost:1338/api/upload", formData, {
    headers: { authorization: `Bearer ${jwtToken}` },
  })
  .then(({ data }) => {
    console.log(data);
  })
  .catch(console.log);

This is what im trying to do on my backend:

const data = await processImage(img.url)
const formData = new FormData();
formData.append("path", "images");
formData.append("files", data, "file.name");
await axios
  .post("http://localhost:1338/api/upload", formData, {
    headers: { authorization: `Bearer ${process.env.JWT_TOKEN}` },
  })
  .then(({ data }) => {
    console.log(data);
  })
  .catch(console.log);
// I get error: 413 Payload Too Large

I’m trying to do it with the same image which works with the frontend method. Perhaps I need to create a new File(), but I couldn’t find any npm packages which worked for that. What should I do to get this working?

i want to recreate this python function in JS so i can use it in an HTML file. i am not familiar with JS

def printit():
  threading.Timer(1.0, printit).start()
  session = HTTP("https://api-testnet.bybit.com/",api_key="", api_secret="")

  positionBuy = session.my_position(symbol="BTCUSDT")['result'][0]['unrealised_pnl']
  positionSell = session.my_position(symbol="BTCUSDT")['result'][1]['unrealised_pnl']
  print (positionBuy)
  print (positionSell)

printit()

The idea is to fetch data every second but if i do it in python i will hit rate limit if many users are using this , so if i do it in JS then it will reduce rate limit since it will load on the frontend with users ip(so i’ve heard)

is this possible?

How to change color of a specific feature (building) with setFeatureState Mapbox GL

My use case : Fill the color on building/address based on user’s searched building/address in Mapbox GL.

What I have achieved till now : I am able to get the searched building’s details by using GeoCoder event “result” and I am getting feature ID in response along with coordinates of the searched address. And I am changing it’s color by using setFeatureState method but it’s filling the color on whole state/country. Please checkout my JS code.


const bounds = [
        [-97.846976993, 30.167105159], // Southwest coordinates
        [-97.751211018, 30.242129961], // Northeast coordinates
      ];

      const map = new mapboxgl.Map({
        container: "map",
        style: "mapbox://styles/smallcrowd/cl07a4926001b15pnu5we767g",
        center: [-79.4512, 43.6568],
        zoom: 13,
        maxBounds: bounds,
      });

      // Add the control to the map.
      const geocoder = new MapboxGeocoder({
        accessToken: mapboxgl.accessToken,
        mapboxgl: mapboxgl,
      });

      geocoder.on("result", (e) => {
        map.addSource("states", {
          type: "geojson",
          data: "https://docs.mapbox.com/mapbox-gl-js/assets/us_states.geojson",
        });
        map.addLayer({
          id: "state-fills",
          type: "fill",
          source: "states",
          layout: {},
          paint: {
            "fill-color": "#FFA500",
          },
        });
        console.log(e);
        map.setFeatureState({
          id: e.result.id, //feature id
          source: "states",
        });
      });

      document.getElementById("geocoder").appendChild(geocoder.onAdd(map));

This is geocoder result response:


result: {
center: (2) [-97.791161, 30.229803]
context: (6) [{…}, {…}, {…}, {…}, {…}, {…}]
geometry: {coordinates: Array(2), type: 'Point'}
id: "poi.412316930875"
place_name: "Texas Tool Traders, 2101 W Ben White Blvd, Austin, Texas 78704, United States"
place_name_en-US: "Texas Tool Traders, 2101 W Ben White Blvd, Austin, Texas 78704, United States"
place_type: ['poi']
properties: {foursquare: '53d16d13498ea4ebec82bc78', landmark: true, address: '2101 W Ben White Blvd', category: 'hardware, shop'}
relevance: 1
text: "Texas Tool Traders"
text_en-US: "Texas Tool Traders"
type: "Feature"
}

Promise doesn’t execute asynchronously

I have been testing promises on node.js in the following program:

const areallylongprocesspromise = new Promise((resolve, reject) => {
    let buff = 0;
    for (let i = 0; i < 1000000000; i++)
    {
        if ((i % 73829) === 0) buff++;
    }
    if (buff > 10) resolve(buff);
    else reject(buff);
});




areallylongprocesspromise.then((resolved) => 
{
    console.log("Resolved: ", resolved);
})
.catch((rejected) => {
    console.log("Rejected: ", rejected);
});

console.log("Waiting for execution to finish up");

The expected output is:

Waiting for execution to finish up
Resolved:  13545

However, the first statement, “waiting… up” doesn’t get logged until the promise finishes execution, at which point both the statements get logged simultaneously.
I’m new to the concept of promises, so I don’t know what is going on here. Why is the promise holding up the execution of the rest of the code? Any help would be appreciated.

Find DOM element that rendered React prop

I’m trying to build a tool that takes in any React element, renders it on the screen, and allows you to edit any string-type props that end up rendered on the screen by just clicking on them (WYSIWYG style).

To do this, I want to render the component with some default values for each string prop and when the user clicks on the DOM, if they clicked on an element that is mapped to a prop value then we replace the DOM element with a contentEditable equivalent and update the props for the rendered component based on the user’s input.

For example with the following component

const HelloWorld = props => (
    Hello, <div>{props.name}</div>
)

I’d like to render the HelloWorld component with a default value for name such as Bob. When the user clicks on Bob on their screen, the tool would replace the div with content editable and update the prop value for name based on the user’s input.

My question is, how can I find the child most DOM element that eventually rendered a given prop?

In the example above, props.name would be mapped to the <div> element.

How can I iterate HTML elements using javascript?

I have the following HTML page.

page

I want to read values from the “Note” column and display something in the “Appréciation” column, how would I do it using a javascript function?
I have tried the following:

const allNotes = document.querySelectorAll('.note');
for(var i = 0; i < allNotes.length; i++){
    console.log('Note: ', allNotes[i])
}

And:

const allNotes = document.querySelectorAll('.note');
for(var notee of allNotes.values()){
    console.log('Note: ', notee)
}

But none of them work, how would I manage to do it? Thank you in advance.

How to Parse a JSON Object with JSON parse error

this is the main service imports and export class main service were we defined the property of the badgeColorsSet to a string

import { Injectable } from '@angular/core';
import { Observable, Subject, throwError } from 'rxjs';
import { map, mergeMap, repeatWhen } from 'rxjs/operators';
// import { environment } from '../../../environments/environment.prod';
import { HttpClient, HttpErrorResponse, HttpHeaders, } from '@angular/common/http';
import { GetPermissionsRequestPayload } from '../../dtos/get-permissions-request-payload';
import { ServiceResponse } from '../../dtos/Response';
import { Store } from '@ngrx/store';
import { AppState } from 'app/redux-store/reducers';
import { SetMenu, SetRoutes } from 'app/redux-store/actions/menu.actions';
import { Router } from '@angular/router';
// import { AddRecordComponent, DynamicProgramComponent, UpdateRecordComponent } from 'fuse-libs';
import { SetFormats } from 'app/redux-store/actions/auth.actions';
import { GetMenuResponsePayload } from 'app/dtos/response-payloads/get-menu-response-payload';
import { GlobalParametersService } from '../gloabal-parameters.service';
import { environment } from 'assets/environments/environment';
import { AppInitService } from '../app-init-service/app-init.service';
import { GetProgramPendingCountRequestPayload } from 'app/dtos/request-payloads/getProgramPendingCount-request-payload';
import { GetModulePendingCountRequestPayload } from 'app/dtos/request-payloads/getModulePendingCount-request-payload';

this is the main service imports and export class main service were we defined the property of the badgeColorsSet to a string
const httpOptions = {
headers: new HttpHeaders({
‘Content-Type’: ‘application/json’,
Authorization: ‘id_token’
})
};

@Injectable({
providedIn: ‘root’
}) //export class

    primaryColor;
    url ;
    myRoutes: any[]  = [];
    count: number;
    triggererModule = new Subject<any>();
    triggererProgram = new Subject<any>(); 
    badgesColorSet:string;
    

     constructor(private globalParamsService: GlobalParametersService,
        private http: HttpClient, private store: Store<AppState>,
        private router: Router , private appInitService: AppInitService) {
            
            this.url = this.appInitService.config.urlPath
            this.primaryColor = this.appInitService.config.primaryColor
            this.badgesColorSet = this.appInitService.config.badgesColorSet

**here is where we define the badgescolorset so it appears in the body**
    }

public getModulePendingCount(moduleCode: string): Observable<any> {
        const myCurrentPermission = JSON.parse(localStorage.getItem('currentPermission'));
        
        let className = "GetModulePendingCountRequestPayload"
        let programPendingCountPayload = new GetModulePendingCountRequestPayload(className, moduleCode )
        let obj =  {currentPermissions: {...myCurrentPermission  } , payload: programPendingCountPayload}
        return this.http.post<any>(this.url + '/getModulePendingCount',obj, httpOptions).pipe(map(resp => {

            return resp ;
        
            },
            error => {
                this.errorHandler(error);
            }
            
        ));
    }
     modifyData(data, currentPermission): any[] {

        return data.map(module => {
            let moduleBadge =    this.getModulePendingCount(module.code).pipe(map(data => {
                // console.log("module badge observable fired")
                return data.payload.count               
            }),repeatWhen(() => this.triggererModule))
            return {
                id: module.code,
                title: module.dsc,
                type: 'collapsable',
                icon: 'apps',
                classes:['module'],
                badge: {bg: this.getRandomColor() , fg: 'white' , title: moduleBadge},
                children: module.menus.map(menu => {
                    return {
                        id: menu.code,
                        title: menu.dsc,
                        type: 'collapsable',
                        // icon: 'dashboard',
                        classes: ['menu'],
                        children:
                            menu.programs.map(program => {
                                let myBadge = new Observable
                                // if(module.code == 'MX'){
                                
                             myBadge =   this.getProgramPendingCount(module.code , menu.code , program.code).pipe(map(data => {
                                    return data.payload.count
                                    
                                }),repeatWhen(() => this.triggererProgram)) **i already parsed the function but it's still doesn't show on my website**
                            // }
                                let url = [''];
                                let lang = localStorage.getItem['Language'];
                                const queryParams = {lang:lang, moduleCode: module.code, menuCode: menu.code, programCode: program.code, ...currentPermission, programLabel: program.dsc , programType: program.formType , routePath: program.routePath };
                                if (program.formType === 'StaticForm') {

                                    url = ['main/' + module.code.toLowerCase() + '/'
                                        + menu.code.toLowerCase() + '/' + program.code.toLowerCase()];
                                }

                                else {
                                    url = ['main/' + module.code.toLowerCase() + '/'
                                        + menu.code.toLowerCase() + '/' + program.code.toLowerCase()];
                                }
                                return {
                                    id: program.code,
                                    title: program.dsc,
                                    type: 'item',

                                    url: url,
                                    classes: ['program'],
                                    queryParams: queryParams,
                                    badge :{title: myBadge , bg: this.getRandomColor()  , fg: '#FFF'},
                                    completeId: {
                                        module: module.code,
                                        menu: menu.code,
                                        program: program.code
                                    }
                                };
                            })
                    };
                })
            };
        }); **I'm trying to send some data into a JSON object, and then into a cookie. But I'm getting this error when im trying to parse it: "SyntaxError: JSON Parse error: Unable to parse JSON string".**
    }```

getRandomColor(){ this is my function that needs to parsed im trying to get a material badge to change its color randomly whenever i refresh the page and this function is in main.service.ts
console.log(‘colors’)
// let colors = [‘#33FFFD’, ‘#FFD133′,’#FF7733′,’#3386FF’]; // to add my color codes
console.log(this.badgesColorSet)
let badgesColorSet = JSON.parse(this.badgesColorSet.get(‘getRandomColor’));

return this.badgesColorSet[Math.floor(Math.random() * this.badgesColorSet.length)];
 

}

php $_POST ist empty or not defined after send value from javascript ajax

I send a value with js/ajax to the same page
the console.log show the correct value but $_POST is empty or not defined after load page
this is my code what did i miss?

<script>
var xmlHttpObject = false;
if (typeof XMLHttpRequest != 'undefined') {
    xmlHttpObject = new XMLHttpRequest();
}
if (!xmlHttpObject) {
    try { xmlHttpObject = new ActiveXObject("Msxml2.XMLHTTP"); }
    catch(e) {
        try { xmlHttpObject = new ActiveXObject("Microsoft.XMLHTTP");}
        catch(e) { xmlHttpObject = null; }
    }
}

function load_data(){
    if (xmlHttpObject.readyState == 4){
        var GetXON = xmlHttpObject.GetXIN;
        document.getElementById(GetXON).innerHTML = xmlHttpObject.responseText;
    }
}
function get_data(N){
  var N   = N;
  var DATA ='data='+N;
  console.log(DATA);
  xmlHttpObject.open('post','',true);
  xmlHttpObject.GetXIN = 'book';
  xmlHttpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlHttpObject.onreadystatechange = load_data;
}
</script>

<button onclick="get_data('1')">Send Value</button> 

<div id="book">
<?php echo $_POST['data']; ?>
</div>