Object, swiperjs, destructure, array, map, filter, forEach

I have two question about my project.

  1. Today I put swiperJS in my project and when you try to click Book in some items my slider move and don’t open the modal. When you try to click on Fiesta Hotel, after loading the web, it doesn’t open the modal. This is my first time with SwiperJS and maybe someone has the same problem and can tell me what’s wrong.

  2. I make modal and do foreach on every book button, now i create the array of object, and wanna connect ModalBtns.id with cities.id how i can do?? I try map, filter and everything but still dont know how to connect this item because i wanna add info to modal dynamically. Like price for ticket and everything. I know in the future react it will be simply to use for operation like that, but i try do in JS

https://margsoftbf.github.io/trip-rest-website/

https://github.com/margsoftbf/trip-rest-website

Search accordion content for ID and open

I am using a basic accordion plugin where each item is added as a separate Gutenberg Block. The plugin does not allow me to add an ID to each block, only a class. When I try to add an ID within the Gutenberg code it returns the error ‘this block contains invalid content’- it’s also impractical for the clent.

While I don’t have control over the plugins ability to facilitate ID’s, the content in each panel is made up of ACF blocks where I can add ID’s.

I need to link to each panel from anchor links but this does not currently work as the ID’s reside within the collapsed accordion and so nothing happens.

Is there a way to search hidden content for a ID’s and then open its parent accordion panel?

This is how the accordion is structured by the plugin with an ACF map section as the content as an example

<div class=".aab__accordion_container">
   <div class=".aab__accordion_head">
      <div class=".aab__accordion_heading .aab_right_icon">
        <h4>the heading</h4>
      </div>
   </div>
   <div class=".aab__accordion_body">
      <section id="map-section">
         Content
      </section>
    </div>
</div>

An active accordion gets the class

.aab__accordion_body--show

added to

.aab__accordion_body

This switches between aria exanded: true or false on the accordion body and the CSS is:

.wp-block-aab-accordion-block .aab__accordion_body {
    display: block !important;
    position: absolute !important;
    top: -9999px !important;
    left: -9999px !important;
}

.wp-block-aab-accordion-block .aab__accordion_body.aab__accordion_body--show {
    position: relative !important;
    top: 0 !important;
    left: 0 !important;
}

I switched it to this css from the original ‘display none/block’ for screen readers and in hopes it would make the task easier but the page still just re-loads at the top with no effect.

To complicate things even more, these accordion panels also reside inside a Gutenberg group

The URL is here

http://staging.caledoniaworldwide.com/package/package-template-1

Thanks in advance

Google Map How to clear poligon and marker

I can not speak English well. Google Map How to clear poligon and marker? Help me please. I want poligon and market to be deleted when I click the button. I tried but I couldn’t.
Myscript :

function initMap() {

....
    function attachPolygonInfoWindow(polygon) {
        .....
    }
    google.maps.event.addListener(drawingManager, "overlaycomplete", function(e) {
        $(".clear").removeClass("d-none");
        if (e.type == "polygon") {
            drawingManager.setOptions({
                drawingControl: false,
            });
            allOverlays.push(e);
            if (e.type != google.maps.drawing.OverlayType.MARKER) {
                drawingManager.setDrawingMode(null);
                var newShape = e.overlay;
                newShape.type = e.type;
                google.maps.event.addListener(newShape, "click", function() {
                    setSelection(newShape);
                });
                    var path = newShape.getPath();
                    google.maps.event.addListener(path, "insert_at", function() {
                        attachPolygonInfoWindow(newShape);
                    });
                    google.maps.event.addListener(path, "set_at", function() {
                        attachPolygonInfoWindow(newShape);
                        var data = "";
                        $.each(e.overlay.getPath().getArray(), function(key, latlng) {
                            var lat = latlng.lat();
                            var lon = latlng.lng();
                            data += lat + " - " + lon + "<br>";
                        });
                        $(".map_coordinat").html(map.getCenter().lat() + " - " + map.getCenter().lng());
                        $(".poligon_coordinat").html(data);
                    });
                    attachPolygonInfoWindow(newShape);
                }
                setSelection(newShape);
            }
        
    });
}

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

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.

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!

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 {
    }
    
}