How to have circular button for login with the Facebook?

Below is a code snippet where I am implementation login with the Facebook.

<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v16.0&appId=app_id_here&autoLogAppEvents=1"
    nonce="nonce_here"></script>
    

<div class="fb-login-button" data-width="" data-size="large" data-button-type="continue_with" data-layout="" data-auto-logout-link="false" data-use-continue-as="false"></div>

Login with FB

How can I make the button circular and set its width and height so it just displays the icon?

QtWebEngineWidgets: how to refresh the page after runJavaScript

Currently, I want to set value for html using runJavaScript.

The following code works:

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *


class Widget(QWidget):

    def __init__(self):
        super().__init__()

        lay = QVBoxLayout()
        self.btn = QPushButton('change html value')
        self.browser = QWebEngineView()
        lay.addWidget(self.btn)
        lay.addWidget(self.browser)

        self.setLayout(lay)

        self.browser.setHtml(
            '''
            <html>
                <head>
                    <title>My Page</title>
                </head>
                <body>
                    <h1 id="welcome">Welcome to my page!</h1>
                    <h1 id="value"> 0 </h1>
                </body>
            </html>
            '''
        )

        self.btn.clicked.connect(self.btnClickSlot)

    def btnClickSlot(self, check=False):
        self.browser.page().runJavaScript('document.getElementById("value").innerHTML = "1"')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = Widget()
    win.show()
    app.exec_()

The value changes from 0 to 1 after click the change html value button.

But, I don’t want to trigger the operation by click. I want to directly change the value.

And the modified code is:

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *


class Widget(QWidget):

    def __init__(self):
        super().__init__()

        lay = QVBoxLayout()
        self.btn = QPushButton('change html value')
        self.browser = QWebEngineView()
        lay.addWidget(self.btn)
        lay.addWidget(self.browser)

        self.setLayout(lay)

        self.browser.setHtml(
            '''
            <html>
                <head>
                    <title>My Page</title>
                </head>
                <body>
                    <h1 id="welcome">Welcome to my page!</h1>
                    <h1 id="value"> 0 </h1>
                </body>
            </html>
            '''
        )

        self.browser.page().runJavaScript('document.getElementById("value").innerHTML = "1"')
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = Widget()
    win.show()
    app.exec_()

The value don’t change as I expect.

How can I directly change the value? Any suggestion is appreciated~~~

Reduce an array of arrays (Javascript)

I have an array of arrays i.e:
const arrayDaddy = [[x, 1], [x, 1], [y, 2], [y, 2], [y, 2], [z, 3]]

my end goal is to take the above arrayDaddy and mutate it by adding the number in arrayDaddy[i][1] if the two items have the same value arrayDaddy[i][0]. Additionally, I want to throw out nested arrays with repeated arrayDaddy[i][0] values after they have been added. The desired result of this process on arrayDaddy would be as follows:

arrayDaddy = [[x, 2], [y, 6], [z, 3]]

I am wondering if there is a way to use Array.prototype.reduce(); to achieve this. If not, what is a simple way to achieve this goal?

NOTE: not sure if this is important, but all items with the same value in index 0 will share an index 1 value. for example consider [z, 3]. any addition [z, ] items will also have a 3 in index 1.

I did try reduce(); but did not have success. my code looked something like this:

const arrayDaddy = [[x, 1], [x, 1], [y, 2], [y, 2], [y, 2], [z, 3]] ;

arrayDaddy.reduce((arr1, arr2) => {
  if(arr1[0] === arr2[0]){
    arr1[1] += arr2[1]
    // do something here to delete arr2... but I can't use delete on a local variable?
  } else {
    //do nothing, continue to the next arr in arrayDaddy
  }
});

I also considered map, but want to avoid creating a new array. I want to mutate the arrayDaddy

Chartjs datalabels is not showing the labels on the bar chart

I have a vertical bar chart built via chartjs. I’m using the datalabels plugin, I expect the data to be plotted on each bar but it’s not visible

const data = [
    {
        "date": "2023-02-23",
        "subscribers": 1208123
    },
    {
        "date": "2023-02-22",
        "subscribers": 1045338
    },
    {
        "date": "2023-02-21",
        "subscribers": 1043130
    },
    {
        "date": "2023-02-20",
        "subscribers": 1248035
    },
    {
        "date": "2023-02-19",
        "subscribers": 1243734
    },
    {
        "date": "2023-02-18",
        "subscribers": 1240317
    },
    {
        "date": "2023-02-17",
        "subscribers": 1033439
    },
    {
        "date": "2023-02-16",
        "subscribers": 974864
    }
];
  const chart_label = "Number of subscribers";

 const chart_canvas = document
      .getElementById("number_of_messages_delivered")
      .getContext("2d");
    Chart.defaults.set("plugins.datalabels", {
      color: "#FE777B",
    });
    push_messages_chart = new Chart(chart_canvas, {
      type: "bar",
      options: {
        animation: true,
        plugins: {
          // Change options for ALL labels of THIS CHART
          datalabels: {
            color: "#FFCE56",
            display: true, // Set to true to display the labels
          },
        },
      },
      data: {
        labels: data.map((row) => row.date),
        datasets: [
          {
            label: chart_label,
            data: data.map((row) => row.subscribers),
          },
        ],
      },
    });
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.2.0/chartjs-plugin-datalabels.min.js"></script>
<canvas id="number_of_messages_delivered"></canvas>

I tried different iterations since last week of this code, but nothing is working. This is just a random sample of what I’ve tried

when local storage is saved it wont display in a HTML text box

I am working on text boxes with an add entry button in HTML. I had got it working through javascript code that when I press the add entry button, I am able to input a text entry then when the page is refreshed the entry remains on the page.

I went on to work on another part of the code and now the data in local storage does not display. I have checked the dev tools and it is definitely being saved but not displayed. My code is below, any help would be greatly appreciated.

function addTextEntry(key, initialText, isNewEntry) {
    var textareaElement = document.createElement("textarea");
    textareaElement.rows = 5;
    textareaElement.placeholder = "(new entry)";

    textareaElement.value = initialText;

    addSection(key, textareaElement);

    if (isNewEntry) {
        textareaElement.focus();
    }

    function saveEntry() {
        console.log("saveEntry called with variables in scope:", {
            key,
            initialText,
            isNewEntry,
            textareaElement,
        });
        
        var text = textareaElement.value;
        var item = makeItem("text", text);
        
    localStorage.setItem(key, item);
        
    }

  textareaElement.addEventListener('change', saveEntry);
    
}

From ‘var text’ downwards is where I have edited the code and this was working before

How prevent scrolling to the top of a page on mobile when call is make with react-infinite-scroll-component?

I have an issue with react-infinite-scroll-component…
When i’m at the to bottom of the infinite div, another call is make and the datas is added.
It’s work very well on desktop. But on mobile, the div scroll to the top of page at each render

See my code below:

import { useEffect, useState, useRef } from "react";
import { useSelector, useDispatch } from "react-redux";
import { setBanner } from "../../redux/filters";

import WindowDimensions from "../utils/WindowDimensions";
import Button from "../utils/Button";
import CarCard from "../utils/Card/CarCard";
import StoperCard from './StoperCard';
import DropDown from "../utils/DropDown";


import { stopers } from "./Stopers";

import Link from "next/link";

import InfiniteScroll from 'react-infinite-scroll-component';
import useApi from "../../api/useApi";

import { useRouter } from "next/router";

import CarNotFound from "../../public/images/catalogue/carnotfound.svg"



function Cars({ sortCars, countCars, query, setQuery, getCars, moreCars, setMoreCars, filtersChanged, removeFilters }) {
    const ref = useRef(null);

    const windowDimension = WindowDimensions();
    
    // Pagination 
    const pageCars = () => {

        if (sortCars.length < countCars) {
            if (window.location.pathname !== undefined && window.location.pathname === '/catalogue') {
                // SET NEW QUERY
                const getQuery = { ...query };
                getQuery.page += 1;
                setQuery(getQuery)
                
    
                // GET CARS
                getCars(getQuery, "infinite-scroll")
            }
        } else {
            setMoreCars(false)
        }
    }


    return (
        <>

                <div className="sm:ml-auto flex flex-col sm:flex-row sm:items-center sm:mt-4 lg:mt-auto">
                    <p className="mr-4 w-fit h-fit mb-4 sm:mb-0 sm:w-max uppercase bg-slate-200 px-4 py-1 min-w-fit rounded-full text-center text-black text-sm">
                        <span className="font-[Gibson-SemiBold] text-xl mr-1">{countCars}</span> résultats
                    </p>
                    <div className="flex flex-wrap sm:flex-nowrap items-center">
                        <p className="w-max uppercase font-[Gibson-SemiBold] mr-4">Tri :</p>
                        <DropDown getList={list_sort} sort={sort} />
                    </div>
                </div>

            </div> 
            <div ref={ref} className="mb-8 px-3 md:pr-8 md:pl-8 mt-6 lg:mt-24 lg:pl-0 lg:pr-12" id='test-zone'>
            {/* <div className="mb-8 md:pr-8 lg:pr-0 md:pl-8 mt-24 lg:pl-0"> */}

                <div id="cars">

                    {/* <div className="border border-primary rounded-lg py-4 px-4 flex items-center bg-gradient">
                        <div className="mr-4"><Exclamation /></div>
                        <p className="uppercase text-sm font-[Gibson-SemiBold] mr-4">Une mise à jour des prix est en cours</p>
                        <div className="-mt-2"><LittleCar /></div>
                    </div> */}
                </div>



                <InfiniteScroll
                    id="car-catalogue"
                    pageStart={0}
                    dataLength={listCars.length} //This is important field to render the next data
                    next={pageCars}
                    hasMore={moreCars}
                    loader={<svg role="status" className="mx-auto mr-2 w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-blue-600" viewBox="0 0 100 101" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" fill="currentColor" />
                        <path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" fill="currentFill" />
                    </svg>}
                    endMessage={listCars.length === 0 &&
                        <div className="col-span-full pt-4">
                            <div className="w-4/12 mx-auto fill-primary">
                                <CarNotFound />
                            </div>
                            <p className="text-center text-xl mt-4">Aucune voiture ne correspond à votre recherche.</p>
                        </div>
                    }
                    initialScrollY={145}
                    className="relative car-catalogue pb-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-3 gap-x-5 gap-y-10 auto-cols-fr overflow-hidden h-fit md:pr-8 md:pl-8 lg:pl-0 lg:pr-12"
                    scrollThreshold={0.7}
                >
                    {listCars && listCars.length > 0 && listCars.map((e, i) => (
                        e.type === undefined ?
                        <Link href={`/product/${e.slug}`} key={e._id}>
                                <a>
                                    <div className="h-full">
                                        <CarCard e={e} bgImage={e.bgImage} />
                                    </div>
                                </a>
                            </Link>
                            :
                            <StoperCard element={e} key={i} />
                    )
                    )}

                </InfiniteScroll>

            </div>
        </>
    )

}

export default Cars;


I tried to set the srcollTop position manually but it dont works…

How to sort a list using vue on-click and add an arrow in column using v-bind?

I want the data is sorted in ascending/descending order when I click the corresponding column. Also, I need an arrow after the column to represent the order. I’m stuck in using vue on-click build a function to sort a list and using v-bind to add an arrow. What should I do with my vue/css/html??
Here is my html

    <div id="app">
      <table>
        <thead>
          <tr></tr>
            <th v-for="(header, key) in column" :key="key" v-on:click="sort(header)" v-bind:class="[sortBy === header ? sortDirection : '']">{{ header }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="row in rows" :key="row.id">
            <td>{{ row.id }}</td>
            <td>{{ row.name }}</td>
            <td>{{ row.phone }}</td>
          </tr>
        </tbody>
      </table>
    </div>

and my js

var app = new Vue({
  sortBy: "ID",
  sortDirection: "asc",
  el: "#app",
  data: {
    arrow: {
      active: true,
      "text-danger": false,
    },
    column: {
      id: "ID",
      name: "Full Name",
      phone: "Phone",
    },
    rows: [],
  },
  methods: {
    async fetchData() {
      const response = await fetch(
        "https://jsonplaceholder.typicode.com/users"
      );
      const finalRes = await response.json();
      this.rows = finalRes;
    },
    sort(s) {
      if (this.s == this.sortBy) {
        this.sortDirection = this.sortDirection === "asc" ? "desc" : "asc";
      }
      this.sortBy = s;
    },
  },
  computed: {
    sortedProductions: function () {
      return this.products.sort((p1, p2) => {
        let modifier = 1;
        if (this.sortDirection === "desc") modifier = -1;
        if (p1[this.sortBy] < p2[this.sortBy]) return -1 * modifier;
        if (p1[this.sortBy] > p2[this.sortBy]) return 1 * modifier;
        return 0;
      });
    },
  },
  mounted() {
    this.fetchData();
    this.sort();
    this.sortedProductions();
  },
});

My expected outcome:
enter image description here

Its basically a mongoose code problem if anyone of u can help then pls

enter image description here

Error i am getting- DeprecationWarning: Mongoose: the strictQuery option will be switched back to false by default in Mongoose 7. Use mongoose.set('strictQuery', false); if you want to prepare for this change. Or use mongoose.set('strictQuery', true); to suppress this warning.

actually in the useNewUrlParser:true in the 8th line i was trying to figure out the changes that can be made but was unable to solve it.

Getting Undefined using Props with Map function, how can it be resolved?

I’m trying to integrate Mapbox to a tutorial page I’m working on using following code ang calling API:https://www.jsonkeeper.com/b/5NPS, however instead of getting Object values I’m getting “undefined “

AirBnbMap.js (component)

import { useState } from "react";
import Map from "react-map-gl";
import { getCenter } from "geolib";

function AirBnbMap({ searchResults }) {
  //Transform the search results objects in to
  //{ latitude: 52.516272, longitude: 13.377722 },
  //object

  const coordinates = searchResults.map((result) => ({
    longitude: result.long,
    latitude: result.lat,
  }));

  console.log(coordinates);

  //The latitude and longitude of the center of locations coordinates

  const center = getCenter(coordinates);

  const [viewState, setViewState] = useState({
    longitude: center.longitude,
    latitude: center.latitude,
    zoom: 3.5,
  });

  return (
    <Map
      {...viewState}
      onMove={(evt) => setViewState(evt.viewState)}
      style={{ width: "100%", height: "100%" }}
      mapStyle="mapbox://styles/mapbox/streets-v9"
      mapboxAccessToken={process.env.mapbox_key}
    />
  );
}
export default AirBnbMap;

search.js (page)

import { useRouter } from "next/router";
import { format } from "date-fns";
import Header from "../components/Header";
import Footer from "../components/Footer";
import InfoCard from "../components/InfoCard";
import AirBnbMap from "../components/AirBnbMap";

function Search({ searchResults }) {
  const router = useRouter();

  //ES6 Destrucuring
  const { location, startDate, endDate, noOfGuests } = router.query;

  const formattedStartDate = format(new Date(startDate), "dd MMMM yy");
  const formattedEndDate = format(new Date(endDate), "dd MMMM yy");
  const range = `${formattedStartDate} - ${formattedEndDate}`;

  return (
    <div>
      <Header placeholder={`${location} | ${range} | ${noOfGuests} guests`} />
      <main className="flex ">
        <section className="flex-grow pt-14 px-6">
          <p className="text-xs">
            300+ Stays - {range} - for {noOfGuests} guests
          </p>
          <h1 className="text-3xl font-semibold mt-2 mb-6">
            Stays in {location}
          </h1>

          <div className="hidden lg:inline-flex mb-5 space-x-3 text-gray-800 whitespace-nowrap">
            <p className="button">Cancellation Flexibility</p>
            <p className="button">Type of Place</p>
            <p className="button">Price</p>
            <p className="button">Rooms and Beds</p>
            <p className="button">More filters</p>
          </div>

          <div className="flex flex-col">
            {searchResults?.map(
              ({ img, location, title, description, star, price, total }) => (
                <InfoCard
                  key={img}
                  img={img}
                  location={location}
                  title={title}
                  description={description}
                  star={star}
                  price={price}
                  total={total}
                />
              )
            )}
          </div>
        </section>

        <section className="hidden xl:inline-flex xl:min-w-[40%] sticky top-[76px] h-[calc(100vh-76px)]">
          <AirBnbMap />
        </section>
      </main>

      <Footer />
    </div>
  );
}

export default Search;

export async function getServerSideProps() {
  const searchResults = await fetch("https://www.jsonkeeper.com/b/5NPS").then(
    (res) => res.json()
  );

  return {
    props: {
      searchResults,
    },
  };
}

Getting error:
Server Error
TypeError: Cannot read properties of undefined (reading ‘map’)

enter image description here

However expecting Object value:
enter image description here

Html2Canvas save file to the server

I’m using html2canvas to create an image and put it into “#output’ element and that works as intended, but I would also like to save that image on my server but that I can’t get to work.

Here is how I’m trying to do that:

// HTML2Canvas script
function convert() {
  $("#output").empty();
  const original = document.querySelector('#input')
  const canvasContainer = document.querySelector('#output')

  html2canvas(original, {
    scale: 2,
    useCORS: true,
    onrendered: function(canvas) {        
      var imgData = canvas.toDataURL('image/jpeg');   


      var url = '/files/export.php';

      $.ajax({ 
        type: "POST", 
        url: url,
        dataType: 'text',
        data: {
          base64data : imgData
        }
      });     
    }
  }).then(canvas => {
    canvasContainer.appendChild(canvas)
  })
}

And here is my export.php

<?php

    $data = $_REQUEST['base64data']; 
    //echo $data;

    $image = explode('base64,',$data); 


    file_put_contents('here.png', base64_decode($image[1]));

?>

Any clues on what I’m missing here?

Parsing Childnode values in javascript

I have an XML

<root><example><examplevalue>exampletext</examplevalue><examplevalue>exampletext2</examplevalue</example></root>

and I have the following javscript code

            if (window.DOMParser){ // Standard browsers
                var parser = new DOMParser();
                xmlDoc = parser.parseFromString(xmlString, "text/xml");
            }
            else { // Internet Explorer
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = false;
                xmlDoc.loadXML(xmlString); 
            }
            var coll=xmlDoc.getElementsByTagName("example");
            console.log(coll[0].childNodes[0].nodeValue);

The console output is

null

I would expect it to be

exampletext

Why are the childnodes not parsed correctly?
childNodes seems to be a method of class node. But the getElementByName return a HTMLCollection object. How does that work?
Thanks for any hints.

webpack devServer Hot reload / HMR reloading but not compiling VueJS components

Using webpack dev server on a vuejs project, when I edit a file the web page is reloaded but not updated.

When sniffing the websocket communication between the client and webpack server I can see this after editing LoginComponent.vue:

enter image description here

The “type”: “static-changed” makes me believe that webpack doesn’t know that it has to compile .vue files on change, and I have no idea how to fix that.

Here is my vue.config.js:

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  configureWebpack: {
    optimization: {
      runtimeChunk: 'single',
    },
  },
  devServer: {
    client: {
      progress: true,
    },
    static: {
      directory:'/dontmanagestaticfiles'
    },
    port: 80,
    allowedHosts: 'all',
    headers: {
      'Access-Control-Allow-Origin': '*'
    },
    
    // hot: true,
    liveReload: true,

    watchFiles: {
      paths: ['src/**'],
      options: {
        // ignored: ['nodes_modules'],
        usePolling: true,
        aggregateTimeout: 300,
        interval: 500,
      }
    },
  },
  chainWebpack: config => {
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap(options => {
        options.compilerOptions = {
          isCustomElement: tag => tag.startsWith('ion-')
        };
        return options;
      });
  }
})

How to start deployed Angular application locally

I have deployed Angular frontend, on server it working fine, there are 3 script

/runtime.0fad6a04e0afb2fa.js    
/polyfills.24f3ec2108a8e0ab.js    
/main.a9b28b9970fe807a.js    

I want to start this application in Firefox, without IIS or Apache – by simple click to Html-page. Is it possible?

But Firefox said me

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///runtime.0fad6a04e0afb2fa.js. (Reason: CORS request not http). 

Is it possible to remove this restriction? Or Firefox never allow me loading and working this scripts?