Why is my images not showing under Swiper Slide tag?

So I am using the SwiperSlide for the first time and after reading the docs and following, I got to the part where i needed it to work and display my images but for some reasons not known to me, my images aren’t displaying. Here is my code;

      import React from 'react'
      import './residencies.css'
      // core version + navigation, pagination modules:
      import {Swiper, SwiperSlide } from 'swiper/react';
      // import Swiper and modules styles
      import 'swiper/css';
      import 'swiper/css/navigation';
      import 'swiper/css/pagination';
       import data from '../../utils/slider.json'



         function Residencies() {
         return (
         <div className='r-wrapper'>
         <div className='r-container paddings innerWidth'>
         <div className='r-head flexColStart'>
            <span className='orangeText'>Best Choices</span>
            <span className='primaryText'>Popular Residencies</span>

          </div>

           <Swiper>

            {
                data.map ((card, i) => (
                    <SwiperSlide key={i}>
                        <div className='r-card'>
                            <img src={card.image}alt="" />
                            <span className='secondaryText r-price'>
                                <span>$</span>
                                <span>{card.price}</span>

                            </span>

                        </div>

                    </SwiperSlide>

                )

                )}
            

           </Swiper>
       

            </div>

            </div>
           )
           }

         export default Residencies

And here is my data files;

       [
       {
       "name": "Aliva Priva Jardin",
       "price": "47,043",
       "detail": "Jakarta Garden City Street, Cakung. Pulo Gadung, Jakarta Timur, DKI Jakarta",
       "image": "/assets/r1.png"
      },
     {
       "name": "Asatti Garden City",
       "price": "66,353",
       "detail": "Pahlawan Street XVII No.215, Cinangka, Sawangan, Depok, Jawa Barat",
       "image": "/assets/r2.png"
     },
     {
      "name": "Citralan Puri Serang",
      "price": "35,853",
      "detail": "Ruko Puri Indah Residence Block A7, Lingkar Street, Ciracas, Serang, Banten",
      "image": "/assets/r3.png"
     },
     {
     "name": "Aliva Priva Jardin",
      "price": "47,043",
      "detail": "Jakarta Garden City Street, Cakung. Pulo Gadung, Jakarta Timur, DKI Jakarta",
      "image": "/assets/r1.png"
     },
     {
      "name": "Asatti Garden City",
      "price": "66,353",
      "detail": "Pahlawan Street XVII No.215, Cinangka, Sawangan, Depok, Jawa Barat",
      "image": "/assets/r2.png"
      },
     {
      "name": "Citralan Puri Serang",
     "price": "35,853",
      "detail": "Ruko Puri Indah Residence Block A7, Lingkar Street, Ciracas, Serang, Banten",
      "image": "/assets/r3.png"
    }
    ]

I have tried every possible ways to make sure my image path is correct, I even had to change the image path to traditional way but it wont display still but if i type it outside the SwiperSlide tag It will display. What could be the reasons why it’s not showing??

Just the thumbnail is showing, the actual image wont show

React Textarea Input – overflow-y is not showing scrollbar (on Chrome or Edge)

I can’t seem to figure out how to show/add scrollbar to a React Textarea. I have referenced this old post here Preventing scroll bars from being hidden for MacOS trackpad users in WebKit/Blink and few others but have not been successful.

I have tested it in both Chrome (Version 113.0.5672.129) and Edge (Version 114.0.1823.37)

Here is what I have:

const myComponet = () => {

 return (
    <input type= "textarea" className={styles.largeTextBox} id="someTextBox"/>
   )
}

//Stylesheet
.largeTextBox{
  width: 200px;
  height : 50px;
  overflow-x:hidden;
  overflow-y:scroll;
}

.frame::-webkit-scrollbar:vertical{
  width:11px;
}

.frame-webkit-scrollbar-track{
  background-color: #fff;
  border-radius: 8px;
}

Really appreciate some help here.

How can I toggle the hidden class on an inner div by clicking a button inside a card using jQuery?

How to create functionality in jQuery that will toggle hidden class on inner div by clicking on a button inside a card?

I tried to create a container div that have some cards in it.the problem is when i click the button
it only opens the panel but doesn’t close the panel if i click it again.
however it being closed if i open a new panel(that is somthing i want to happen)

another thing is that hideAllPanels and showMoreInfo works when only one is active.

function handleMoreInfo() {
  // 1) Find the coin-card element 
  $(".coin-card").on("click",async function(e) {
    // a) stop bubbling
    e.stopImmediatePropagation();

    // b) Find coin id
    const coinID = ($(this).find('.coin-name').text()).toLowerCase();
    
    // c) Get more info about the coin
    const data = await fetchMoreInfo(coinID);

    // d) Optional: hide all panels
    // if(nodeList) hideAllPanels();

    // e) display the chosen more info panel
    if (data) showMoreInfo(data,$(this));
  });
}

const showMoreInfo = (data,thatCoin) => {
  // 1) Find all classes on more-info-panel and then find out if class hidden exists

  // 2) Toggle more-info-panel between displayed and hidden

  nodeList[0].forEach(div => {
    const coinNameFromArr = $(div).find('.coin-name').text();

    if (coinNameFromArr.toLowerCase() === data.id ) {
      console.log('Match');
      const panel = $(div).find('.more-info-panel').attr("class");
      const panelClassesArr = panel.split(' ');


      if(panelClassesArr.length === 1) $(div).find('.more-info-panel').addClass("hidden");
      if(panelClassesArr.length === 2) $(div).find('.more-info-panel').removeClass("hidden");
    }
  })

  // 3) Set new data inside panel
  thatCoin.find('.more-info-image').prop("src",data?.image?.large);
  thatCoin.find('.usd').text(`USD: $${data?.market_data?.current_price?.usd}`);
  thatCoin.find('.eur').text(`EUR: €${data?.market_data?.current_price?.eur}`);
  thatCoin.find('.ils').text(`ILS: ₪${data?.market_data?.current_price?.ils}`);
}

const hideAllPanels = () => {
  // 1) Loop over node list of the body-container to see if some panels are open
  console.log(nodeList);
  nodeList[0].forEach(div => {
    const panel = $(div).find('.more-info-panel').attr("class");
    const panelClassesArr = panel.split(' ');

    // 2) If element have only one class it means that panel is displayed add we need to hide it
    if(panelClassesArr.length === 1) $(div).find('.more-info-panel').addClass("hidden");
  });  
}

this is the html of a card example

  <div class="coin-card">
    <div class="headInfo">
      <p class="coin-symbol">btc</p>
      <div class="form-check form-switch"><input class="form-check-input" num1="0" type="checkbox"             role="switch"
          onclick="addCoinsToArray()"><label class="form-check-label" for="flexSwitchCheckChecked"></label></div>
    </div>
    <p class="coin-name">Bitcoin</p><button class="btn btn-info mybtn" onclick="handleMoreInfo()" data-toggle="collapse"
      data-target="info" num="0">More Info</button>
    <div class="more-info-panel hidden" symbol="bitcoin"><img class="more-info-image"
        src="./src/img/bitcoin-g80ff29158_640.jpg">
      <p class="info-title">Coin Prices:</p>
      <p class="usd">USD: $30</p>
      <p class="eur">EUR: €30</p>
      <p class="ils">ILS: ₪30</p>
    </div>
  </div>

Object getting updated inside “response.on”, but updating is not getting reflected outside [duplicate]

The object result does not get updated when I send it back to the front end.
At the front-end, it just shows that an empty object has been sent.

url is defined. The API call works correctly. The result when console logged inside response.on shows the correct behaviour. However, outside the https request it shows an empty object and the key value pairs are not added.

app.post("/getWeather",(req,res,next)=>{

    console.log(req.body.cities);

    const cities=req.body.cities;

    const result={};

    cities.map((city)=>{

        https.get(url,(response)=>{

            response.on("data",(data)=>{
                const wdata=JSON.parse(data);
                const temperature=wdata.main.temp;
                result[city]=temperature;
            });


        }).on("error",(err)=>{
            console.log(err);

            result[city]="NA";
        });
    });

    return res.json(result);

});

Result output at front-end = {}

Save the most recent object in localstorage

Hey Im building a flipbook type application using html canvas in react the thing is that when i save an object(drawin) form the canvas into local storage it will save not only the next project but also the previous one that has been passed from handleCreateNewCanvas function that it is going to pass the object form the previous canvas to the new a new empty canvas as a reference form previous drawing

  saveCanvas = () => {
    if (this.canvasRef.current) {
      const saveData = this.canvasRef.current.getSaveData();
      const loadedSaveData = localStorage.getItem('canvasSaveData');
      const parsedData = JSON.parse(saveData);
      const loadedData = JSON.parse(loadedSaveData);
  
      // Check if the loaded data exists and has a newer version
      if (loadedData && parsedData.version > loadedData.version) {
        localStorage.setItem('canvasSaveData', saveData);
      } else if (!loadedData) {
        localStorage.setItem('canvasSaveData', saveData);
      }
    }
  };
  handleCreateNewCanvas = () => {
    // Make the drawing content transparent
    const saveData = localStorage.getItem('canvasSaveData');
    if (saveData) {
      const parsedData = JSON.parse(saveData);
      let brushColor = parsedData.lines[0].brushColor;
      if (brushColor === "#444") {
        parsedData.lines[0].brushColor = "grey";
      }
      const modifiedSaveData = JSON.stringify(parsedData);
      console.log(modifiedSaveData)
      localStorage.setItem("canvasSaveData", modifiedSaveData);
      this.canvasRef.current.loadSaveData(modifiedSaveData, true);
    }
  };

is there any change a should make to the saveCanvas function in order to make it save only what is being drawn in the the canvas and ignore the content of the object passed form the handleCreateNewCanvas function?

Discord.js TypeError: interaction.options is not a function – how to solve it?

const { SlashCommandBuilder } = require('@discordjs/builders');
const { MessageAttachment } = require('discord.js');
const { formatDate } = require('../../events/utils/functions');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('profil')
    .setDescription('Etiketlenen kişinin veya komutu birini etiketlemeden kullanan kişinin profilini gösterir.')
    .addUserOption(option => option.setName('kullanıcı').setDescription('Profilini görmek istediğiniz kullanıcıyı etiketleyin.')),
  async run(interaction) {
    const user = interaction.options.getUser('kullanıcı') || interaction.user;
    const member = interaction.guild.members.cache.get(user.id);
    const roles = member.roles.cache
      .filter((r) => r.id !== interaction.guild.id)
      .map((r) => `<@&${r.id}>`);
    const joinedDate = formatDate(member.joinedAt);
    const accountCreatedDate = formatDate(user.createdAt);
    const nitroSince = member.premiumSince
      ? formatDate(member.premiumSince)
      : 'Nitro abonesi değil.';
    const boostCount = member.premiumSubscriptionCount;
    const boostTime = member.premiumSince
      ? `Sunucuya takviye vermeye başladığı tarih: ${formatDate(member.premiumSince)}`
      : 'Sunucuya takviye yapmıyor.';

    await user.fetch();

    let bannerURL = user.bannerURL({ size: 2048, format: 'png' });
    if (!bannerURL) {
      const attachment = new MessageAttachment(
        './icons/TFDMYS_Afis_Yok.png',
        'TFDMYS_Afis_Yok.png'
      );
      bannerURL = 'attachment://TFDMYS_Afis_Yok.png';
      interaction.reply({ files: [attachment] });
      return;
    }

    const badgesArray = user.flags.toArray();
    let badges = '';

    if (badgesArray.length > 0) {
      badges = badgesArray.map((badge) => getBadgeName(badge)).join(', ');
    } else {
      badges =
        'Bu TF Sakininin herhangi bir Discord rozeti veya unvanı bulunmuyor.';
    }

    function getBadgeName(badge) {
      switch (badge) {
        case 'HOUSE_BALANCE':
          return '<:TF_Rozet_HypeSquad_Denge:1108870588954591312> HypeSquad Denge Rozeti';
        case 'HOUSE_BRAVERY':
          return '<:TF_Rozet_HypeSquad_Cesaret:1108872353255006238> HypeSquad Cesaret Rozeti';
        case 'HOUSE_BRILLIANCE':
          return '<:TF_Rozet_HypeSquad_Gorkem:1108872425103429692> HypeSquad Görkem Rozeti';
        case 'EARLY_SUPPORTER':
          return '<:TF_Rozet_Erken_Destekci:1108872344379871293> Erken Dönem Destekçisi';
        case 'EARLY_VERIFIED_DEVELOPER':
          return '<a:TF_Rozet_E_Dogrulanmis_G_Hareket:1108872845011980309> Erken Doğrulanmış Geliştirici';
        case 'BUGHUNTER_LEVEL_1':
          return '<a:TF_Rozet_DC_Hata_Avcisi_Hareket:1108872887328321648> Hata Avcısı Seviye 1';
        case 'BUGHUNTER_LEVEL_2':
          return '<a:TF_Rozet_DC_Altin_Hata_Avcisi_H:1108872881812807781> Hata Avcısı Seviye 2';
        case 'VERIFIED_DEVELOPER':
          return '<a:TF_Ikon_Onay_Hareketli:1108872805421961306> Doğrulanmış Geliştirici';
        case 'DISCORD_EMPLOYEE':
          return '<a:TF_Rozet_Discord_Ekibi_Hareketli:1108872838796034198> Discord Personeli';
        case 'DISCORD_PARTNER':
          return '<:TF_Rozet_Discord_Ortagi_Sunucu_S:1108872870714671135> Discord Ortağı';
        case 'DISCORD_CERTIFIED_MODERATOR':
          return '<a:TF_Rozet_Mod_Akademisi_Mezunu_H:1108872821800710255> Discord Onaylı Moderatör';
        case 'ACTIVE_DEVELOPER':
          return '<a:TF_Rozet_Aktif_Gelistirici_H:1108872851542523965> Aktif Geliştirici';
        case 'VERIFIED_BOT':
          return '<a:TF_Ikon_Onay_Hareketli:1108872805421961306> Doğrulanmış Bot';
        case 'PARTNERED_SERVER_OWNER':
          return '<:TF_Rozet_Discord_Ortagi_Sunucu_S:1108872870714671135> Discord Ortağı Sunucu Sahibi';
        case 'EARLY_VERIFIED_BOT_DEVELOPER':
          return '<a:TF_Rozet_E_Dogrulanmis_G_Hareket:1108872845011980309> Erken Doğrulanmış Bot Geliştiricisi';
        case 'EARLY_VERIFIED_BOT':
          return '<a:TF_Ikon_Onay_Hareketli:1108872805421961306> Erken Doğrulanmış Bot';
        default:
          return badge;
      }
    }

    const embed = {
      color: '#500000',
      author: {
        name: `${user.username}#${user.discriminator}`,
        icon_url: user.displayAvatarURL({ dynamic: true }),
      },
      thumbnail: {
        url: user.displayAvatarURL({ dynamic: true }),
      },
      image: {
        url: bannerURL,
      },
      fields: [
        {
          name: 'Nitro Bilgisi',
          value: `${nitroSince} ${member.premiumSince ? '(Abonelik başlamasından bu yana)' : ''}`,
          inline: true,
        },
        {
          name: 'Sunucuya Yapılan Takviye Sayısı',
          value: boostTime,
          inline: true,
        },
        {
          name: 'Roller',
          value:
            roles.length > 0
              ? roles.join(' ')
              : 'Bu kullanıcının herhangi bir rolü yok.',
        },
        {
          name: 'Sunucuya Katılım Tarihi',
          value: joinedDate,
          inline: true,
        },
        {
          name: 'Hesap Oluşturulma Tarihi',
          value: accountCreatedDate,
          inline: true,
        },
        {
          name: 'Rozetler',
          value: badges,
        },
      ],
      footer: {
        text: `${user.username}#${user.discriminator} | Profil Bilgisi`,
        icon_url: user.displayAvatarURL({ dynamic: true }),
      },
    };

    await interaction.reply({ embeds:  });
  },
};

Hi, I’m pretty new to this stuff and I’m getting an error I can’t solve. This is the slash command code that will reflect some of the user’s profile information to the embed message of my bot running with Discord.js version 13.15.1. The error I get is TypeError: interaction.options is not a function and I’ve been stuck on this error for a while. Thanks for your help!

I’ve tried everything I can to make sure the code doesn’t error, checked my discord.js version, still can’t seem to fix the problem.

What I expected to happen was that the code could properly respond to slash command requests without errors.

Breakdance plugin issue: Unable to add third tab to the media library dialog while using WordPress page builder

Breakdance plugin issue – it doesn’t show up 3rd tabs in media library dialog

Currently I’m building a platform with a new page builder called Breakdance. It’s at https://breakdance.com. And you can download a free version of the open-source plugin and upload to your admin panel to see how it works.

The problem is, when I open up the media library dialog you may have noticed that there are 2 horizontal tabs by default(Upload Image & Media Library) and currently I need to add a new one but still unable.

This problem raises only when I edit my page with breakdance. And of course, I am able to add the tab by extending wp.media.view.MediaFrame.Select when I edit my page on the default editor. Just like the below JavaScript code:

var old_media_frame_select = wp.media.view.MediaFrame.Select;
    var types = [];

wp.media.view.MediaFrame.Select = old_media_frame_select.extend({

// Tab / Router
// https://atimmer.github.io/wordpress-jsdoc/media_views_frame_select.js.html#sunlight-1-line-113
   browseRouter: function browseRouter(routerView) {
      old_media_frame_select.prototype.browseRouter.apply(this, arguments);

        // Bit dirty, but elementor dont set the types allowed in the popup
        if (document.querySelector('.elementor-control-image')) {
            types = ['image'];
        } else {
            types = this.options.library.type;
        }

        routerView.set({
            newTab: {
                text: 'ThirdTab',
                   priority: 45
            }
        });
    },

    // Handlers
    bindHandlers: function bindHandlers() {
        old_media_frame_select.prototype.bindHandlers.apply( this, arguments );
        this.on( 'content:create:newTab', this.frameContent, this );
    },

    /**
     * Render callback for the content region in the `browse` mode.
     *
     * @param {wp.media.controller.Region} contentRegion
     */
    frameContent: function frameContent(contentRegion) {
        var state = this.state();
        setTimeout(function() {
          newMediaTab(state);
        }, 200)
    },

    getFrame: function getFrame(id) {
        return this.states.findWhere({ id: id });
    }
});

I was planning to make an addon plugin to make it work but as it didn’t work correctly so I even tried modifying wpuiforbuilder/media.js and extending the old media frame just like the above but the error still persists.

If you are a wordpress plugin developer, do you mind giving me some helpful advices?
Thank you!
Olex

How can I fix the ‘TypeError: Cannot read property ‘origin’ of undefined’ error in AWS Lambda function?

I trying to test an lambda function in AWS where an answer is inserted in a table. I have attached the security policy. I have made sure that the questionID in the UpsertAnswer lambda matches the questionID of the UpsertQuestion lambda. But I keep getting an error that says:

"errorType": "TypeError",
  "errorMessage": "Cannot read property 'origin' of undefined",
  "trace": [
    "TypeError: Cannot read property 'origin' of undefined",
    "    at responseHeaders (/var/task/index.js:32:26)",
    "    at /var/task/index.js:124:22",
    "    at processTicksAndRejections (internal/process/task_queues.js:95:5)"
  ]

What could be causing this error?

Here is the code:

/**********************************************************************
 *  Upsert Answer item into table
 **********************************************************************/

/* POST test
  {
    "resource": "/",
    "path": "/",
    "httpMethod": "POST",
    "body": "{"answer":"This is my super important answer","questionSlug":"this-is-my-super-important-answer"}"
  }

  PUT test - make sure to change the ID to one in your database before running or this method will create a new record
  {
    "resource": "/",
    "path": "/",
    "httpMethod": "PUT",
    "body": "{"answer":"This is my super important answer","negativeVotes":0,"positiveVotes":1,"id":"5ec9957e3f64b70004e7599e"}"
  }
*/

// we need access to the AWS SDK
var AWS = require("aws-sdk");

// we need uuid to generate unique ids
const { v4: uuidv4 } = require("uuid");

//  we need access to DynamoDB and choose the DocumentClient model
var docClient = new AWS.DynamoDB.DocumentClient();

const responseHeaders = (headers) => {
  const origin = headers.origin || headers.Origin;

  return {
    // HTTP headers to pass back to the client
    "Content-Type": "application/json",
    // the next headers support CORS
    "X-Requested-With": "*",
    "Access-Control-Allow-Headers":
      "Content-Type,X-Amz-Date,Authorization,X-Api-Key,x-requested-with",
    "Access-Control-Allow-Origin": origin,
    "Access-Control-Allow-Methods": "OPTIONS,*",
    Vary: "Origin", // for proxies
    // the "has-cors" library used by the Angular application wants this set
    "Access-Control-Allow-Credentials": "true",
  };
};

exports.handler = async (event) => {
  // get the HTTP Method used
  var httpMethod = event.httpMethod;
  // get the HTTP body sent
  var payload = JSON.parse(event.body);

  // time to prepare the upsert
  const paramQuery = async () => {
    // define our query
    let params = {
      TableName: "Answer",
      Key: { id: "" },
      UpdateExpression: "set #qi = :qi, #a = :a, #nv = :nv, #pv = :pv",
      ExpressionAttributeNames: {
        // define the attributes used in the update expression
        "#qi": "questionId",
        "#a": "answer",
        "#nv": "negativeVotes",
        "#pv": "positiveVotes",
      },
      ExpressionAttributeValues: {
        // set default values
        ":qi": "",
        ":a": "",
        ":nv": 0,
        ":pv": 0,
      },
      // this tells DynamoDB to return the new records with all fields, not just the changed ones
      // see https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html for
      // information on the possible values
      ReturnValues: "ALL_NEW",
    };

    // these three fields can be set during create or update
    //  set the answer if there is one
    if (payload.answer && payload.answer.trim())
      params.ExpressionAttributeValues[":a"] = payload.answer;

    //  set the category slug if there is one
    if (payload.questionId && payload.questionId.trim())
      params.ExpressionAttributeValues[":qi"] = payload.questionId;

    if (httpMethod == "PUT") {
      // PUTs are updates but the ID is passed as a path paremeter
      // lets get the path parameters
      let pathParameters = event.pathParameters;

      //  set the unique key of the item to be modified
      params.Key.id = pathParameters.id;

      // these two values are only changed - they are always defaulted during create
      //  set the negativeVotes
      params.ExpressionAttributeValues[":nv"] = payload.negativeVotes;

      //  set the positiveVotes
      params.ExpressionAttributeValues[":pv"] = payload.positiveVotes;
    } else {
      // POSTs are inserts
      // create and set the unique key. its a uuid without the '-'
      var id = uuidv4().replace(/-/g, "");
      params.Key.id = id;
    }

    // uncomment the next line to see the parameters as sent to DynamoDB
    //console.log(JSON.stringify(params));

    // we create a promise to wrap the async DynamoDB execution
    return new Promise((resolve, reject) => {
      var queryParams = docClient.update(params).promise();
      queryParams
        .then(function (data) {
          resolve({
            statusCode: 200,
            body: JSON.stringify(data),
            // HTTP headers to pass back to the client
            headers: responseHeaders(event.headers),
          });
        })
        .catch(function (err) {
          reject(err);
        });
    });
  };
  // we await our promise here and return the result (see the resolve above)
  return await paramQuery();
};

I tried adding quotes around origin in the properties section, and was expecting data returned. But I still got the same error.

Formating API data returns “undefined” in console

So what im trying to do is format the data since API gives A LOT of stuff i have no use for, but in console its always returning as “undefined” or “null” in this case

enter image description here

export async function getCurrentData() {
    try {
        const apiData = await requestAPI("current", { city: "london,UK", })
        .then(data => currentDataFormat(data))
        return apiData
    }catch(err){
        console.error(err)
        return null
    }
}


function currentDataFormat(data) {
    const {
        weather: { icon, description },
        city_name, country_code, datetime, lat, lon, sunrise, sunset, temp, wind_spd
    } = data.current.data[0]

    return {icon, description, city_name, country_code, datetime, lat, lon, sunrise, sunset, temp, wind_spd}
}

function requestAPI(infoType, searchParams) {
    const url = new URL(API_URL + infoType)
    url.search = new URLSearchParams({ ...searchParams, key: API_KEY })

    return fetch(url)

        .then(res => res.json())
        .then(data => data)
        .catch(err => err)
}

Handlebars page not showing data from Mysql

Handlebars not showing data from Mysql

I’m using express, sequelize and data from Mysql to show a list of flights in a handlebars page.
In my console the data is being displayed but in the handlebars page, nothing appears.

I just started learning handlebars and express usage in node so I’m a little bit clueless on how to solve this.

Here is what I’ve tried in app.js:

//importações de módulos
const express = require("express");
const app = express();
const handlebars = require("express-handlebars");
const path = require("path");
const Sequelize = require("sequelize");

//conectando com o banco
const sequelize = new Sequelize("db", "user", "password", {
    host: "host",
    dialect: "mysql"
})

sequelize.authenticate().then(function(){
    console.log("deu certo!");
}).catch(function(){
    console.log("aAaAaAaAaAaAai")
})

const Voo = sequelize.define("Voo", {
    ID_VOO: {
        type: Sequelize.INTEGER(100), 
        primaryKey: true,
        autoIncrement: true,
    },
    ORIGEM: {
        type: Sequelize.STRING,
        allowNull: false,
    },
    DESTINO: {
        type: Sequelize.STRING,
        allowNull: false,
    },
    DT_PARTIDA: {
        type: Sequelize.DATE,
        allowNull: false,
    },
    DT_CHEGADA: {
        type: Sequelize.DATE,
        allowNull: false,
    },
    HR_SAIDA: {
        type: Sequelize.TIME,
        allowNull: false,
    },
    HR_CHEGADA: {
        type: Sequelize.TIME,
        allowNull: false,
    },
    VO_AERONAVE: {
        type: Sequelize.INTEGER,
        allowNull: false,
    }

}, {tableName: "voo", 
    timestamps: false,
})

//sincronizando model com banco de dados
Voo.sync().then(() => {
    console.log('Tabela sincronizada com sucesso');
  })
  .catch((error) => {
    console.error('Erro ao sincronizar tabela:', error);
  });

//buscando registros no banco
Voo.findAll().then((voos) => {
    app.post("/passagensAereas", function(req, res){
        res.render("passagensAereas", {voos: voos});
        //res.send("testando" + req.body.Origem + "n" + req.body.Destino + "n" + req.body.dataSaida);
    })
}).catch((error) => {
    console.error('Erro ao consultar tabela:', error);
  });
  
//=========================================================================================


//config
    //template engine
    app.engine('handlebars', handlebars.engine({defaultLayout: 'main'}));
    app.set('view engine', 'handlebars');

app.use(express.urlencoded({extended: false}));
app.use(express.json());
app.use(express.static('public'));

//rotas
app.get("/", function(req, res){
    res.render("index");
})


app.listen(8083, function(){
    console.log("aAaAaAaAai está funcionando mesmo")
})

And here is my handlebars page:

<body>
    <header>
        <img src="img/Logo-SKYIFSP.png">
    </header>
    <section>
        <div id="passagensAereas">
            <h2>Passagens aéreas</h2>
            <div id="box">
                <h1>Lista de voos</h1>
                <ul> 
                    {{#each voos}}
                    <li>{{this.origem}}</li>
                    {{/each}}
                </ul>
            </div>
        </div>
    </section>
    <footer>
        <h5 id="copyright">© 2022 - 2023 Symcode soluções de software - Todos os direitos reservados.</h5>
    </footer>
</body>

Cypress – removeAttr with .find not working

The cypress code below is working, but “.find(‘.link-btn.A0057#A0057’).invoke (‘removeAttr’, ‘target’).click()” is still opening a new tab and not is the same window

///

describe(‘Login’, () => {
it(‘ login with’, () => {

  cy.visit('http://localhost:8080')
  cy.get('#code').should('exist')
  cy.get('#username').type('[email protected]')
  cy.get('#password').type('forTest@123')
  cy.get('#login').click()
  cy.get('user-menu')
  .shadow()
.find('.link-btn.A0057#A0057').invoke ('removeAttr', 'target').click()


})

})

But

When Im doing .get(‘.link-btn.A0057#A0057’).invoke (‘removeAttr’, ‘target’).click()
getting error “expected ‘<div#A0057.link-btn.A0057.hover-A0057>’ to have attribute ‘target'”

Why does my local storage reset to empty whenever I refresh in React with Redux?

why does my localstorage resets to empty whenever i refresh?

i want to save the data on localstorage which is also passed to my redux state but i cant

const getLocalStorage = () => {
    const oldExpenses = JSON.parse(window.localStorage.getItem("ADDED_EXPENSES"));
    if (oldExpenses) {
        return oldExpenses;
    } else {
        return [];
    }
};
const loadedExpenses = getLocalStorage();
const Expense = () => {
    const dispatch = useDispatch();
    console.log(getLocalStorage());
    useEffect(() => {
        dispatch(loadExpenses(loadedExpenses));
    }, [dispatch]);
    const isnew = useSelector(isNew);

    const nonFormattedItems = useSelector(expenses);
    console.log(nonFormattedItems);

    const formattedItems = nonFormattedItems.map((expense) => {
        const dt = expense.date;
        const stDate = new Date(dt);
        const newExpense = { ...expense, date: stDate };
        return newExpense;
    });


    const updateLocalStorage = () => {
        window.localStorage.setItem(
            "ADDED_ITEMS",
            JSON.stringify(nonFormattedItems)
        );
    };

    useEffect(() => {
        updateLocalStorage();
    }, [nonFormattedItems]); // nonFormattedItems is used as a dependency here
    console.log(nonFormattedItems);
    const newExpenseHandler = (expense) => {
        if (isnew) {
            dispatch(addExpense(expense));
        }
    };

i tried to call this directly instead of using useEffect:

dispatch(loadExpenses(loadedExpenses));

but this gave me infinite loop.

How to correctly configure boostrap-select to add images to a select dropdown list

I am using custom Google Translate Element on my page and I need to insert flags inside select dropdown list. I’ve seen a suggestion on use ‘bootstrap-select’ but I can’t figure out how to make it work, and even looking on their example “Custom Content“, it’s not clear. Does anyone can give me a light on how to implement it?

This is the main select function

        function trocarIdioma(sigla) {
            sessionStorage.setItem('lang', sigla);
            var myPopup = document.querySelector("select#languages");

            if (comboGoogleTradutor) {
                comboGoogleTradutor.value = sigla;
                changeEvent(comboGoogleTradutor);//Dispara a troca
            }

            if (!visited) {
                sessionStorage.setItem('visited', true);
                
                for (var i = 0; i < myPopup.options.length; i++) {
                    if (myPopup.options[i].value == sigla) {
                        myPopup.options[i].selected = true;
                    }
                }

                comboGoogleTradutor.value = sigla;
                changeEvent(comboGoogleTradutor);//Dispara a troca
            } else {
                for (var i = 0; i < myPopup.options.length; i++) {
                    if (myPopup.options[i].value == sigla) {
                        var flag = myPopup.options[i].dataset.content;
                        console.log(flag);
                        //myPopup.options[i].innerHTML = flag;
                        myPopup.options[i].selected = true;
                    }
                }
            }
        }

Here is the complete fiddle:

https://jsfiddle.net/mjn10uLd/

Why my downloaded video file size is 0 byte by using fetch method

I am attempting to fetch a video from a website using its URL. To accomplish this, I have written some JavaScript code. However, when I run the code, the downloaded file size is 0 bytes.

I am confident that the URL is correct because I have entered the same URL in Chrome. I was able to see the video and download it successfully.

In that website: the html is below

<video controls autoplay name="media">
  
  <source src="https://rexample" type="video/mp4">

</video>

Below is my code:

async function downloadVideo(link) {
      try {
      
        const response = await fetch(link,{
          mode: 'no-cors',
          method: 'GET',
          headers: {
            'Content-Type': 'video/mp4',
        }});

      
        const blob = await response.blob();
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'video.mp4';
        a.click();
        URL.revokeObjectURL(url);
      } catch (error) {
        console.error(error);
      }
    }