Can’t get other values to show using react

I can’t figure out how to get more values to show in my table using REACT. The only thing that I am able to show is the cost. I can’t show Manufacturer and Item. So When I choose Iphone12 – Manufacturer will be “Apple” and Item will be “iPhone 12” & Galaxy S21 will be “Android” and “Galaxy 21”,from the data structure in index.
This is my Index.js :

```import React from 'react';
import ReactDOM from 'react-dom';
import './Home.css';
import 'bootstrap/dist/css/bootstrap.min.css'
import MTWork  from "./MTWork";
let inventory = [
    { 'id': 0, 'manufact': 'None', 'item': 'None', 'descr': 'None', 'avail': 0, 'price': 0},
    { 'id': 100, 'manufact': 'Samsung', 'item': 'Galaxy S22', 'descr': 'The Lastest Phone', 'avail': 22, 'price': 1399.99 },
    { 'id': 101, 'manufact': 'Samsung', 'item': 'Galaxy S21', 'descr' : 'Recently refurbished like new', 'avail': 5, 'price': 699.99 },
    { 'id': 102, 'manufact': 'Samsung', 'item': 'Galaxy S20', 'descr' : 'Great phone works well', 'avail': 3, 'price': 399.99 },
    { 'id': 103, 'manufact': 'Apple', 'item': 'iPhone 13', 'descr' : 'New and Shiny, Nothing better', 'avail': 13, 'price': 1299.99 },
    { 'id': 104, 'manufact': 'Apple', 'item': 'iPhone 12', 'descr' : 'Refurbished but perfect', 'avail': 13, 'price': 899.99 },
    { 'id': 105, 'manufact': 'Apple', 'item': 'iPhone 11', 'descr' : 'Works great!', 'avail': 12, 'price': 599.99 }
];
let warranty = [
    { 'id': 0, 'plan' : 'None', 'cost' : 0  },
    { 'id': 1, 'plan' : 'Extended', 'cost' : .15  },
    { 'id': 2, 'plan' : 'Normal', 'cost' : .1  },
    { 'id': 3, 'plan' : 'Base', 'cost' : .05  }
];
let title = "Teds Technology Treasures"
ReactDOM.render(
    <React.StrictMode>
        <MTWork  title ={title} phones ={inventory} wrnty = {warranty} />
    </React.StrictMode>,
    document.getElementById('root')
);``` 

THIS IS MY MTWork.js -----------------------------------


```import {useState} from "react";


function MTWork(props){
    const {phones, title, wrnty} = props;


    const[name, setName] = useState("Kels");
    const[itm, setAndroid] = useState();
    const[Atem, setApple] = useState();
    const[Warrant, setWarranty] = useState(0);
    const[total, setTotal] = useState( 0);


    function updateName(n) {
        setName(n.target.value);
    }
    function updateAndroid(a){
        setAndroid(a.target.value);
    }
function updateApple(ap){
        setApple(ap.target.value);
    }
    function updateWarranty(w) {
        setWarranty(w.target.value);
    }

    function doOrder() {
        let total=0;
        let total2 = parseFloat(itm) + parseFloat(Atem);
       let wTotal = (total2)*(parseFloat(Warrant));
        total += total2+wTotal;
        return setTotal(total);

    }

    return(
        <div>
            <div className="container-fluid">
                <div className="row">
                    <div className="col">
                        <h1>  <span className='title'> {title}</span></h1>
                    </div>
                </div>
                <div className="row">
                    <div className="col-4">
                        Name: <input type='text' value={name}
                                     onChange = {updateName}/> <br/>
                       Android Phone: <select onChange={updateAndroid} value={itm} >
                        {phones.map( ( phn ) => (
                            <option key={phn.id} value={phn.price}> {phn.item} </option>
                        ))}
                    </select> <br/>
                        Apple Phone: <select onChange={updateApple} value={Atem} >
                        {phones.map( ( Apn ) => (
                            <option key={Apn.id} value={Apn.price} > {Apn.item} </option>
                        ))}
                    </select><br/>
                        Warranty: <select onChange={updateWarranty} value={Warrant} >
                        {wrnty.map( ( wrn ) => (
                            <option key={wrn.id} value={wrn.cost}> {wrn.plan} </option>
                        ))}

                    </select><br/>
                        <button className='btn btn-dark' onClick={ () => doOrder()}> Order</button>
                        <h2 style={{color:"blue"}}>Results For Name: {name}</h2>

                        <table className="table" >
                            <tbody className="color">
                            <tr><th>Manufacturer:</th><th>Item: </th><th>Cost: </th></tr>
                            <tr>
                                <td scope="row">{phones.maunfact}</td>
                                <td scope="row">{phones.price}</td>
                                <td scope="row">{itm}</td>
                            </tr>
                            <tr>
                                <td scope="row">{phones.manufact}</td>
                                <td scope="row">{phones.price}</td>
                                <td scope="row">{Atem}</td>
                            </tr>
                            <tr>
                                <td> Warranty</td>
                                <td scope="row">{props.plan}</td>
                                <td scope="row">{Warrant}%</td>
                            </tr>
                            <tr>
                                <td scope="row">Total </td>
                                <td scope="row"> </td>
                                <td scope="row">{total} </td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    )

}export default MTWork;```

[This is how the final product should look like in the end.)[1]
[1]: https://i.stack.imgur.com/mxBOK.png

search suggestion based on any letter of string

i am trying to write some java script code the auto suggest based on pretrial strings so to speak

here an example of what i mean:

if we have array of strings =>
[ ‘text’ , ‘apple’ , ‘texas’ , ‘time’ , ‘java’ , ‘java script’ , ‘pen’ ]

what i want to achieve is this :
when the user type ==> “te” the function should return this ==> ‘text’ and ‘texas’

BUT

if user type ==> “t*e” OR “t e” with space between the function should return this
==> ‘text’ , ‘texas’ , AND ‘time’ since it contains the tow letters no matter the oreder

the same if user type ==> “p*e” OR “p e” the result should be ==> ‘apple’ and ‘pen’
since booth contain the letters ‘p’ and ‘e’

here what i have done so far

const nameInput = document.getElementById('name')

const names = [ 'text' , 'apple' , 'texas' , 'time' , 'java' , 'java script' , 'pen' ]

nameInput.addEventListener('keyup', ()=> {
  // console.log(nameInput.value)
const text = nameInput.value.trim().replace(/s/g, '')
// console.log(text)
const a = names.filter(name => name.includes(text))
console.log(a)
})
<input type="text" placeholder="search"  id="name">

“Cannot read” error when trying to access Object’s properties

I have this JS Object that contains 3 “thread” objects each with different values.
I am trying to get the values from each of the threads. I am able to print the entire json object, but I can’t print individual values from them?

My code:
console.log(threadArray)
returns this in console: (which is perfect)
enter image description here

but when I try to replace "threadArray" with "threadArray[0].threads[0]["_id" to get the first thread’s ID, it says it Cannot read unknown value.

Does anybody know why?

fabric canvas pointer is misaligned when using css.zoom property

when I use fabric canvas and use css zoom property.
drawing in the cancas draws with some offset.
How can I correct the cursor position?

<div style="zoom: 50%">
 <div id="fabric_canvas"></div>
</div>

the reason why I put zoom property in wrapper div is that the canvas is supposed to be rendered image, and manually edited by drawing mode and to be exported as image. I’d like to keep the good resolution.

Github rest api do not return correct list of data

I am trying to get the top 10 repositories based on the star, So here is the API I am using.

However, The result I get is incorrect and it seems like it changes the order of the top 3 repositories.
For example:
The first time I call the below API, here is the top 3 repository based on the star.

  1. freeCodeCamp/freeCodeCamp 342K
  2. EbookFoundation/free-programming-books 225K
  3. vuejs/vue 194K

After 1 minute, i call the api one more time and got totally different result:

  1. freeCodeCamp/freeCodeCamp 342K
  2. 996icu/996.ICU 261K
  3. jwasham/coding-interview-university 212K

So basically, the result is not correct. Is there anything wrong with my API endpoint?

https://api.github.com/search/repositories?q=stars:>0&sort=stars&per_page=3

Speech to text wit.ai telegram bot

I’m making a telegram bot. Using node js (node-telegram-bot-api), axios, wit.ai. Voice to text not working. What i doing wrong?

require('dotenv').config()
const TelegramApi = require('node-telegram-bot-api')
const bot = new TelegramApi(process.env.TOKEN, { polling: true })
const axios = require('axios')

bot.on('voice', async (msg) => {
  const stream = bot.getFileStream(msg.voice.file_id)

  let chunks = []

  stream.on('data', (chunk) => chunks.push(chunk))
  stream.on('end', () => {
    const axiosConfig = {
      method: 'POST',
      url: 'https://api.wit.ai/speech',
      headers: {
        Authorization: 'Bearer ' + WIT_API_KEY,
        'Content-Type': 'audio/ogg',
      },
      data: Buffer.concat(chunks),
    }
    axios(axiosConfig)
      .then((response) => {
        console.log('answer', response.data)
      })
      .catch((err) => {
        console.log('error', err)
      })
  })
})

enter image description here

How Can I Make a conditional with return in a .map without get out of main function?

My objetive is create this object:

{
  name: string.
  birthday: date;
}

by this array:

const dataArray = [
 {
  "id": "name",
  "type": "string";
 },
 {
  "id": "birthday",
  "type": "date";
 }

]

So, I create a .map of the array, like this:

const inputsValues = {};

dataArray.map(item => {
  if(item.type === "date"){
    inputsValues[item.id] = new Date(item.value);
    return; // this line is the problem
  }

  inputsValues[item.id] = item.value;
});

Is there a option to make a return in this function without use else?

Web Scraping Journal “El Peruano” – Python/Scrapy

im trying to scrap some info from “El Peruano” journal, but i cannot at first sight it look have to:

El Peruano Website

  1. Put a Date in a Formbox.
  2. Do a click in SearchBox.
  3. Get all links for get all: “Title”,”Resolution#”, “Body”

This is my code:

import scrapy

class SpiderPeruano(scrapy.Spider):
    name = "peruano"
    start_urls = [
        "https://diariooficial.elperuano.pe/Normas"
    ]

    custom_settings= {
        "FEED_URI": "peruano.json",
        "FEED_FORMAT": "json",
        "FEED_EXPORT_ENCODING": "utf-8"
    }

    def parse_click(self, response):
        
        #i put here a condition but i think is not necessary
        #button = response.xpath("//div[@id='busqueda']/form[@action]/button[@id='btnBuscar']").get()
        #if buttom:
        yield scrapy.FormRequest.from_response(
            response,
            formxpath= "//form[@id='space_PortalNormasLegalesN']",
            formdata={"cddesde": "08/03/2022", "cdhasta:": "08/03/2022"},
            dont_click=True,
            dont_filter=True,
            callback=self.parse
            )
 
            
    def parse(self, response):
    
        links = response.xpath("//div[@class='ediciones_texto']/h5/a/@href").getall()
        for link in links:
            yield response.follow(link, callback=self.parse_link)


    def parse_link(self, response):
        title = response.xpath("//div[@class='story']/h1[@class='sumilla']/text()").get()
        num = response.xpath("//div[@class='story']/h2[@class='resoluci-n']/text()").getall()
        body = response.xpath("//div[@class='story']/p/text()").getall()

        yield {
            "title": title,
            "num": num,
            "body": body
        }

#call
#scrapy crawl peruano

#url = "https://diariooficial.elperuano.pe/normas"

#Form_BOX: "//form[@action]"
#Box_desde = "//form[@action]/input[@id='cddesde']"
#Box_hasta = "//form[@action]/input[@id='cdhasta']"
#Button= "//div[@id='busqueda']/form[@action]/button[@id='btnBuscar']"

#links = "//div[@class='ediciones_texto']/h5/a/@href"
#titles= "//div[@class='story']/h1[@class='sumilla']/text()"
#resolutionNum= "//div[@class='story']/h2[@class='resoluci-n']/text()"
#body= "//div[@class='story']/p/text()"

So, i need some help for know what i’m doing wrong on my code cuz this run well but dont get the data.

Thx a lot for your time and help!

In Node.js, How can I access exported module in Index.js?

I have searched in stackoverflow and it seems there isn’t any use case like mine.
I have a structure folders like this in functions directory:

functions/index.js

I added some codes to be used by other functions like this in index.js:

require("dotenv");
const admin = require("firebase-admin");
const config = JSON.parse(process.env.FIREBASE_CONFIG);
admin.initializeApp(config);

const highLevel = {
  timeoutSeconds: 300,
  memory: "2GB",
};

const secretLevel = {
  timeoutSeconds: 120,
  memory: "1GB",
  secret: [process.env.SERVER_BACKEND],
};

const lowLevel = {
  timeoutSeconds: 120,
  memory: "512MB",
};

module.exports = lowLevel, highLevel, secretLevel;

I created a file in a folder structure like this:

functions/admin/features/music/publisher.js

How can I access the variable of lowLevel from publisher.js as I tried using this:

const lowLevel = require("../index");

and I can’t get any of reference to index.js. Is there a way to access file index.js from the root folder? Thank you very much for any tips and trick.

React State Changing Without Explicitly Telling it to Change [duplicate]

My react state is changing without me calling my setState function from useState hook.

After some quick research, i’ve narrowed it down to the fact an array is a reference type so data and tempData share the same reference and change with each other. A solution I found was to stringify then parse the data: JSON.parse(JSON.stringify(data)) but this could have some pretty bad performance hits if it’s a large object right? Is there a better solution here? Redux? Or is that unnecessary? This is a pretty common case isn’t it?

I’ve attached an example below which can be easily created from create-react-app.

App.js

import Child from './Child';
import { useState } from 'react';

const defaultData = [
  {id:0, foo:1, bar:2},
  {id:1, foo:3, bar:4},
  {id:2, foo:4, bar:6},
]

function App() {
  const [data, setData] = useState(defaultData)

  const handleData = (id) => {
    const tempData = data
    for (const idx in tempData) {
      const item = tempData[idx]
      if (item.id === id) {
        tempData[idx].id += 10
      }
    }
  }

  return (
    <div>
      <Child data={data} handleData={handleData} />
    </div>
  );
}

export default App;

Child.js

export default function Child(props) {
  const {data, handleData} = props
  
  return (
    <div>
      
      <ul>
      {data.map((i) => (
        <li key={i.id}>
          <button onClick={() => handleData(i.id)}>
            {i.foo} {i.bar}
          </button>
        </li>
      ))}
      </ul>
    </div>
  )
}

Element implicitly has an ‘any’ type because expression of type ‘”status”‘ can’t be used to index type ‘Object’

Unable to index “res” with a string. I’ve tried other fixes i found but the context that it is used here in my code it does not recognise the object being defined earlier.

full error : “Element implicitly has an ‘any’ type because expression of type ‘”status”‘ can’t be used to index type ‘Object’. Property ‘status’ does not exist on type ‘Object’.ts(7053)”

error here:

if(res['status'] === 'success')

full function:

export class LoginComponent implements OnInit {
    public user : User;
    
    
    constructor(private loginService: LoginService, private router: Router) {
        this.user = new User();
    }
    
    validateLogin() {
        if(this.user.username && this.user.password) {
            this.loginService.validateLogin(this.user).subscribe(res => {
                console.log('result is ', res);
                if(res['status'] === 'success') {
                    this.router.navigate(['/home']);
                } else {
                    alert('Wrong username password');
                }
            }, error => {
                console.log('error is ', error);
            });
        } else {
            alert('enter user name and password');
        }
    }
    
    ngOnInit(): void {
    }
    
}

js get index from array

I have this code that I believe dynamically

<select name="list[]"></select>
<input name="field[]">

<select name="list[]"></select>
<input name="field[]">


<select name="list[]"></select>
<input name="field[]">

I would like the onchange of a select to be returned to me the index to dynamically fill the relative input

How to alert user before leaving webpage and run ajax function if user presses “ok”?

I have this function that is supposed to ask the user if they are sure that they want to leave or refresh the website and if they say yes and leave the ajax function is executed. My problem is if the ajax function is alone the user is given no warning but if anything else is in the code the ajax function doesn’t work.

<script type="text/javascript">
            window.onbeforeunload = function () {
                return "";
                $.ajax({url: "checkout.php", type : 'post', data : { page_left: 1}});
            }
       </script>

GoJS: Prevent specific region from being occupied by nodes in a ForceDirectedLayout

I’d like to prevent a specific coordinate area reserved for a legend in my GoJS diagram which is using a ForceDirectedLayout for node layouts. However, the legend shape doesn’t affect the layout of nodes when applied as a Part, and using a placeholder Node unfortunately doesn’t allow placement based on document coordinates.

How can you create a region in a ForceDirectedLayout which affects nodes as they’re being calculated but in turn either isn’t a node or is a fixed node position without any links?

Ideally it’d be possible to define a specific Rect in the diagram which isn’t accessible for nodes, but the closest I could find is the total bounding box via boundsComputation which would just narrow the area and not allow for cutting a specific region out.

Here’s a specific illustration of the challenge, where the legend will generally overlapping with node content without some force to repel the nodes:

enter image description here