Next.js TypeError: destroy is not a function when navigating to different page

So basically every time a navigate to a different page in this case from home page to /blog using next-link I get Unhandled Runtime Error
TypeError: destroy is not a function
but when I refresh the page the page loads correctly or if I type in the URL manually in the browser for instance localhost:3000/blog
here is a screenshot of the error

screenshot

and here is the code for the blog page


///blog page
export default function Blog(props) {

  const { posts, tags } = props;

  function switchMode() {
    props.setMode(props.mode === 'light' ? 'dark' : 'light');
  }
  return (
    <>
      <Head>

        <title>Blog</title>
        <link rel="icon" href="/favicon.ico" />
        <meta name="description" content="Yushae Raza's personal blog" />
      </Head>



      <main style={{ paddingTop: "5em" }}>
        <Container>
          <Typography variant="h1" align="center" >
            Blog
          </Typography>
          <Divider />
          <br></br>
          <Grid container spacing={2}>



            <Grid item xs={12} md={8}>

              {posts.map((post, idx) => (<>



                <Post
                  title={post.title}
                  publishedAt={post.published_at}
                  author={post.authors[0].name}

                  imageUrl={post.feature_image}
                  description={post.excerpt}
                  category={post.tags[0].name}
                  slug={post.slug} /><br></br>

              </>)
              )}
            </Grid>
            <Grid item xs={12} md={4}>
              <Sidebar tags={tags} />
            </Grid>



          </Grid>
        </Container>
      </main>

    </>

  )
}
export async function getStaticProps() {
  // get posts from our api
  const { posts } = await api.getPosts(0);
  const { tags } = await api.getTags();
  //  console.log(posts)




  return {
    props: { posts, tags },
    revalidate: 10
  };
}

//navbar
const pages = [
    { name: 'Blog', link: '/blog' },

  ]

              {pages.map((page, idx) => (
                <MenuItem key={idx} onClick={handleCloseNavMenu}
                  sx={{ flexGrow: 1 }}>
                  <Link href={page.link}>

                    {page.name}

                  </Link>
                </MenuItem>
              ))}

How to import and use bpmn file in vue component with aid of raw-loader

I’m new to bpmn-js and try to import and use a .bpmn file in a vue.js component (BPMNViewer.vue). My research only brought up to use the raw-loader. So I’m kind of at a loss here.

<script>
import demo from './examples/demo.bpmn'
...

export default {
  data() {
    return {
      xmlData: demo,
    };
  }
}

This results in the following Error:

error in ./src/views/BPMNViewer.vue?vue&type=script&lang=js&

Module not found: Error: Can't resolve './examples/demo.bpmn' in '/bpmn-test/src/views'

ERROR in ./src/views/BPMNViewer.vue?vue&type=script&lang=js& (./node_modules/@vue/vue-loader-v15/lib/index.js??vue-loader-options!./src/views/BPMNViewer.vue?vue&type=script&lang=js&) 12:0-39

Module not found: Error: Can't resolve './examples/demo.bpmn' in '/bpmn-test/src/views'
 @ ./src/views/BPMNViewer.vue?vue&type=script&lang=js& 1:0-134 1:150-153 1:155-286 1:155-286
 @ ./src/views/BPMNViewer.vue 2:0-62 3:0-57 3:0-57 10:2-8
 @ ./src/router/index.js 3:0-48 12:15-25
 @ ./src/main.js 3:0-29 9:2-8
webpack compiled with 1 error

I try to integrate the raw-loader in my vue.config.js:

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
    transpileDependencies: true,

    chainWebpack: config => {
        config.module
            .rule("bpmn")
            .test(/.bpmn$/)
            .use("raw-loader")
            .loader("raw-loader")
            .end();
    }
})

My package.json:

{
  "name": "bpmn-test",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "test:unit": "vue-cli-service test:unit",
    "test:e2e": "vue-cli-service test:e2e",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "bpmn-js": "^7.3.1",
    "bpmn-js-cli": "^2.0.0",
    "bpmn-js-properties-panel": "^0.37.2",
    "camunda-bpmn-moddle": "^4.4.0",
    "diagram-js-minimap": "^2.0.3",
    "inherits": "^2.0.4",
    "core-js": "^3.8.3",
    "vue": "^2.6.14",
    "vue-router": "^3.5.1",
    "vuex": "^3.6.2"
  },
  "devDependencies": {
    "@babel/core": "^7.12.16",
    "@babel/eslint-parser": "^7.12.16",
    "@vue/cli-plugin-babel": "~5.0.0",
    "@vue/cli-plugin-e2e-cypress": "~5.0.0",
    "@vue/cli-plugin-eslint": "~5.0.0",
    "@vue/cli-plugin-router": "~5.0.0",
    "@vue/cli-plugin-unit-jest": "~5.0.0",
    "@vue/cli-plugin-vuex": "~5.0.0",
    "@vue/cli-service": "~5.0.0",
    "@vue/test-utils": "^1.1.3",
    "@vue/vue2-jest": "^27.0.0-alpha.2",
    "babel-jest": "^27.0.6",
    "cypress": "^8.3.0",
    "eslint": "^7.32.0",
    "eslint-plugin-vue": "^8.0.3",
    "jest": "^27.0.5",
    "less": "^3.0.4",
    "less-loader": "^5.0.0",
    "raw-loader": "^3.1.0",
    "vue-template-compiler": "^2.6.14"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "@babel/eslint-parser"
    },
    "rules": {},
    "overrides": [
      {
        "files": [
          "**/__tests__/*.{j,t}s?(x)",
          "**/tests/unit/**/*.spec.{j,t}s?(x)"
        ],
        "env": {
          "jest": true
        }
      }
    ]
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead"
  ],
  "jest": {
    "preset": "@vue/cli-plugin-unit-jest"
  }
}

Seems like I miss something here. Please let me know if I need to provide more information.

show and hide element in jquery with ajax

I create survey poll in wordpress plugin to display questions i use ajax to display it

this is my html code

        <div id="my_poll">
            <button class="start" id="start"><b><?php _e('Start poll questions'); ?></b></button>
            <div id="poll" class="container mt-sm-5 my-1">
                <form>
                    <?php
                    if ($ques->have_posts()) {
                        while ($ques->have_posts()) {
                            $ques->the_post();
                            global $post;
                            $ID = $post->ID;
                            $option = get_post_meta($ID, "op1", true);
                            $nonce = wp_create_nonce("my_user_vote_nonce");
                            $link = admin_url('admin-ajax.php?action=my_user_vote&post_id=' . $ID . '&nonce=' . $nonce);
                            $ques_id = 'Q-' . $ID;
                    ?>
                            <div id="<?php echo $ques_id ?>" class="questions">
                                <div class="question ml-sm-5 pl-sm-5 pt-2">
                                    <h3><b><?php _e('Poll Survey'); ?></b></h3>

                                    <div class="py-2 h5"><b class="msg"><?php the_title() ?></b></div>
                                    <div class="ml-md-3 ml-sm-3 pl-md-5 pt-sm-0 pt-3" id="options">
                                        <label class="options"><?php _e($option['op1']['op1']); ?> <input type="radio" name="framework" value="<?php esc_attr_e($option['op1']['op1']) ?>"> <span class="checkmark"></span> </label>
                                        <label class="options"><?php _e($option['op2']['op2']); ?> <input type="radio" name="framework" value="<?php esc_attr_e($option['op2']['op2']) ?>"> <span class="checkmark"></span> </label>
                                        <label class="options"><?php _e($option['op3']['op3']); ?> <input type="radio" name="framework" value="<?php esc_attr_e($option['op3']['op3']) ?>"> <span class="checkmark"></span> </label>
                                    </div>

                                    <div class="d-flex align-items-center pt-3">
                                        <div class="ml-auto mr-sm-5">
                                            <button class="btn btn-success">
                                                <?php
                                                echo '<a class="user_vote" data-nonce="' . $nonce . '" data-post_id="' . $ID . '" href="' . $link . '">submit</a>';
                                                ?>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                    <?php
                        }
                    }
                    ?>
                </form>
            </div>
        </div>

and this is my ajax to show and hide elements

jQuery(document).ready(function() {
    jQuery("#poll").hide();
    var count = 0;

    jQuery(".start").click(function(e) {
        jQuery("#poll").show();
        jQuery(".start").hide();
    });

    jQuery(".user_vote").click(function(e) {
        e.preventDefault();
        option = jQuery('input[name="framework"]:checked').val();
        post_id = jQuery(this).attr("data-post_id");
        nonce = jQuery(this).attr("data-nonce");

        var idArr = [];
        jQuery(".questions").each(function() {
            idArr.push(jQuery(this).attr("id"));
        });

        jQuery.ajax({
            type: "post",
            dataType: "json",
            url: myAjax.ajaxurl,
            data: {
                action: "my_user_vote",
                post_id: post_id,
                nonce: nonce,
                option: option,
            },
            success: function(response) {
                if (response.type == "success") {
                    count++;
                    if (count < idArr.length) {
                        jQuery(".questions").hide();
                        jQuery("#" + idArr[count]).show();
                    } else {
                        jQuery("#my_poll").hide();
                        alert('Thank you for your time.')
                    }
                } else {
                    alert("Your vote could not be added");
                }
            },
        });
    });
});

in this jquery ajax whene i click start button i display all questoins divs.

but i want display the first question div.

Does anyone have any solutions?

Remove from array if parent property matches

I am currently trying to remove from an array of objects if the parent gets removed.

My array looks like this:

const items = [
  {
    id: '1'
    generatedFrom: undefined
  },
  {
    id: '2',
    generatedFrom: '1',
  },
  {
    id: '3',
    generatedFrom: '2'
  },
  {
    id: '4',
    generatedFrom: '1'
  }
]

I have a method which filters the objects out based on the id which I am passing into the method:

const removeFromArray = (id: string) => {
   const filtered = items.filter(item => item.id !== id); 
}

This gives me the correct results which I was hoping for in terms of removing the parent object. However, the problem that I am getting is this should have a knock on effect for the remainder of the objects within the array.

If you take the example above:

  • If I remove id 2 then it should delete items[1]
  • As items[2] is generated from id 2 this one should also be removed.
  • items[3] should stay existing as the parent is still there.

This could be a array which has many items within and I am unsure how to approach it

Products Update using Redux When click on ” Category” name one Mega Menu, MegaMenu And Product both are different components

Please See the Image >>

I want to update Products by click on Category Name the MegaMenu, But it does not change. I use redux for state management. Please help me !!

This is MegaMenu Component

import MenuIcon from '@mui/icons-material/Menu';
import './MegaMenu.css';
import { NavLink } from 'react-router-dom';
import ArrowRightIcon from '@mui/icons-material/ArrowRight';

const categories = [
  "Sunglass",
  "Footwear",
  "Men Watch",
  "Women Watch",
  "Computer",
  "SmartPhones",
  "Camera",
];

const MegaMenu = () => {

  return (
    <div className='mega_menu_component'>
      <div className='mega_menu_Items'>
        <div className='mega_menus'>
          <MenuIcon className='mega_menu_icon' style={{ fontSize: '40px', color: '#fff', cursor: 'pointer' }} />
          <div class="menu_link_content">
            <NavLink className="menu_name" to="/">Home</NavLink>
            <NavLink className="menu_name" to="/products">Shop <ArrowRightIcon style={{ fontSize: 'medium' }} />

              <ul className="categoryMenu">
                {categories.map((categoryName) => (
                  <li className="categoryMenu-link" > <NavLink style={{ textDecoration: 'none', color: '#000' }} key={categoryName} to={`/products/${categoryName}`}>{categoryName}</NavLink></li>
                ))}
              </ul>
            </NavLink>
            <NavLink className="menu_name" to="/contact">Contact</NavLink>
            <NavLink className="menu_name" to="/about">About</NavLink>
          </div>
        </div>
      </div>
    </div>
  );
};

export default MegaMenu;

This is Products component

 import React, { Fragment, useEffect, useState } from "react";
import "./Products.css";
import { useSelector, useDispatch } from "react-redux";
import { clearErrors, getProduct } from "../../actions/productAction";
import Loader from "../layout/Loader/Loader";
import ProductCard from "../Home/ProductCard";
import Pagination from "react-js-pagination";
import Slider from "@material-ui/core/Slider";
import { useAlert } from "react-alert";
import Typography from "@material-ui/core/Typography";
import MetaData from "../layout/MetaData";
import { useParams } from "react-router";
import { NavLink, useLocation } from "react-router-dom"
const categories = [
  "Sunglass",
  "Footwear",
  "Men Watch",
  "Women Watch",
  "Computer",
  "SmartPhones",
  "Camera",
];

const Products = ({ match }) => {
  const dispatch = useDispatch();


  const urlLocation = useLocation();
  const categoryName = urlLocation.pathname.split('/')[2];
  const alert = useAlert();

  const [currentPage, setCurrentPage] = useState(1);
  const [price, setPrice] = useState([0, 25000]);

    // const [category, setCategory] = useState(categoryName);


    const [category, setCategory] = useState('');
 

  const [ratings, setRatings] = useState(0);


  const {
    products,
    loading,
    error,
    productsCount,
    resultPerPage,
    filteredProductsCount,
  } = useSelector((state) => state.products);

  const keyword = match.params.keyword;

  const setCurrentPageNo = (e) => {
    setCurrentPage(e);
  };

  const priceHandler = (event, newPrice) => {
    setPrice(newPrice);
  };
  let count = filteredProductsCount;


  useEffect(() => {
    if (error) {
      alert.error(error);
      dispatch(clearErrors());
    }
    dispatch(getProduct(keyword, currentPage, price, category, ratings));
  }, [dispatch, keyword, currentPage, price, category, ratings, alert, error]);

  return (
    <Fragment>
      {loading ? (
        <Loader />
      ) : (
        <Fragment>
          <MetaData title="PRODUCTS -- ECOMMERCE" />
          <h2 className="productsHeading">Products</h2>

          <div className="products">
            {products &&
              products.map((product) => (
                <ProductCard key={product._id} product={product} />
              ))}
          </div>

          <div className="filterBox">
            <Typography>Price</Typography>
            <Slider
              value={price}
              onChange={priceHandler}
              valueLabelDisplay="auto"
              aria-labelledby="range-slider"
              min={0}
              max={25000}
            />

            <Typography>Categories</Typography>
            <ul className="categoryBox">
              {categories.map((category) => (
                <li className="category-link" >
                  <NavLink style={{ textDecoration: 'none', color: 'black' }} key={category} onClick={() => setCategory(category)} to={`/products`}>{category}</NavLink>
                </li>
              ))}
            </ul>
            <fieldset>
              <Typography component="legend">Ratings Above</Typography>
              <Slider
                value={ratings}
                onChange={(e, newRating) => {
                  setRatings(newRating);
                }}
                aria-labelledby="continuous-slider"
                valueLabelDisplay="auto"
                min={0}
                max={5}
              />
            </fieldset>
          </div>


          {resultPerPage < count && (
            <div className="paginationBox">
              <Pagination
                activePage={currentPage}
                itemsCountPerPage={resultPerPage}
                totalItemsCount={productsCount}
                onChange={setCurrentPageNo}
                nextPageText="Next"
                prevPageText="Prev"
                firstPageText="1st"
                lastPageText="Last"
                itemClass="page-item"
                linkClass="page-link"
                activeClass="pageItemActive"
                activeLinkClass="pageLinkActive"
              />
            </div>
          )}
        </Fragment>
      )}
    </Fragment>
  );
};

export default Products;

** When I want to click on the mega menu “Shop>>Category” name the URL would be like http://localhost:3000/products/Sunglass Here sunglass is the category name **

** Now I want to data update in the Product component (ProductCard Update) using the URL category part. But it does not work. **

Scraping by selecting icons and extracting hyperlink text (Kaggle)

I am new to web scraping and am trying to extract the usernames and scores of students on Kaggle. This is otherwise a lot of manual work, and we would like to automate the process. I am able to see the username at the end of the url of their icon. However, when I inspect the webpage, I’m not sure how to access each icon and each icon url.

Here is an example competition:

https://www.kaggle.com/competitions/digit-recognizer/leaderboard

If you hover over the icon of the third user, Andrej Marinchenko, you will see his username (andrej0marinchenko). It is also at the end of the hyperlink of the icon:

https://www.kaggle.com/andrej0marinchenko

In this example, the icon I describe is pointed to with a red arrow, and the score is pointed to with a blue arrow.
enter image description here

How do I scrape the webpage to get all the usernames and scores for all users? I apologize if I do not have the right tags and appreciate you letting me know.

Fading Canvas from Opacity 1 to 0 on Edges

I am creating a Canvas with an image inside using

context.drawImage(image, (cWidth - iRatio)/2, 0, iRatio, cHeight);

And behind the canvas there is a Blue Wallpaper inside a Div.

Canvas

As you can see on the image (done on Photoshop), the Canvas (Image with the Sun) is fading from opacity 1 to 0.

How can I do it in Canvas with JS or CSS ? I want the Canvas edges(All, so Left, Right, Top and botoom) to have an opacity 0 and fading to center with opacity 1.

I don’t know why this code doesn’t work for me in javascript

Does anyone know why the javascript methods that are in the script don’t work? Separately the first one works but together don’t.

My goal is to be able to open the dropdowns of the tree and also to be able to use the button (input) of the last for using the paradas function.

<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="~/css/StyleSheet.css" rel="stylesheet" />
</head>
<body>
    <h1>@ViewData["Title"]</h1>
    <form action="LDButtonClick" method="post">
        <button class="button-1" type="submit">Request</button>
    </form>

    <ul id="myUL"> 

        @foreach (var entry in Model)
        {
            <li>
                <span class="caret">@entry.Key</span>
                <ul class="nested">
                    @foreach (var entryT in @entry.Value)
                    {
                        <li>
                            <span class="caret">@entryT.Key</span>
                            <ul class="nested">
                                @foreach (String parada in @entryT.Value)
                                {
                                    <li>
                                        <input id="paradaId" class="caret-down::before" type="button" onclick="paradas" value="@parada"/>
                                    </li>
                                }
                            </ul>
                        </li>
                    }
                </ul>
            </li>
        }
    </ul>
    

    <script type="text/javascript">
        var toggler = document.getElementsByClassName("caret");
        var i;
        for (i = 0; i < toggler.length; i++) {
            toggler[i].addEventListener("click", function () {
                this.parentElement.querySelector(".nested").classList.toggle("active");
                this.classList.toggle("caret-down");
            });
        }

        function paradas() {
            var idParada = document.getElementById("paradaId").innerText;
            var [] words = idParada.Split(' ');
            paradasAnadidas = HttpContext.Session.GetComplexData < List < string >> ("paradasAnadidas");
        }

    </script>

</body>
</html>```


How can I configure a Javascript Webapp to enable it to use the Web Browser to view files in Google cloud storage

My Javascript Webapp uploads pdf files into the Google Cloud and stores them in a Cloud Storage bucket. I’d like to enable the Webapp to use the Browser to view these files.

An HTML button firing an onClick function for a window.open call hard-coded with an HREF referencing the full cloud storage URL for the file together with an access token will do the trick, but I’m at a loss to find a way of configuring this arrangement dynamically.

The URL part doesn’t appear to represent a problem, but I would appreciate advice on how I might enable the Webapp to obtain an access token

Is it possible to “initialize” a React component?

So basically I’m trying to implement a restart function for my game, and I would like to be able to somehow “reload” my GameView component. Here’s the lifecycle: 1. React renders/mounts my component 2. user interacts with the component and it changes 3. now, I want to call a function to basically wipe off all those changes and bring the component (and all of its child) back to its state in step 1. Here are 2 possible solutions I’ve thought of:

  • keep the same component and set all the state variables back to their initialized values
  • make a new component and replace the old one

The first is not very practical since it gets very complicated when child components gets involved and the second doesn’t work because apparently React still views the new component as being identical the old one since they have the same props? I’m not sure why but I couldn’t get it to work.

I would greatly appreciate some help!

Leaflet Shapefile marker

I have a problem with loading the leaflet shapefile on my page.
The shapefile is loaded correctly but the markers do not have the colors as in the shape file and the name of the shapefile does not appear in the list of layers but only the word shapefile. It appears to read the shapefile but not all information.
Questo è il codice che uso:


var watercolor = L.tileLayer('http://mt0.google.com/vt/lyrs=s&hl=en&x={x}&y={y}&z={z}', {});
var geo = L.geoJson({features: []}, {
        onEachFeature: function popUp(feature, layer) {
            var out = [];
            if (feature.properties) {
                for (var key in feature.properties) {
                    out.push(key + ": " + feature.properties[key]);
                }
                layer.bindPopup(out.join("<br />"));
            }
        }
    });


    var myMap = L.map('divMapID', {
        center: L.latLng(39.15097955985934, 9.019421210403138),//Valori prec: [39, 9],
        zoom: 10,
        minZoom: 3,

        layers: [watercolor, geo]

    });


    //data è un oggetto geoJson
    var base = 'testo.zip';
    shp(base).then(function (data) {
        geo.addData(data);
    });

    var baseMaps = {
        "BaseLayer": watercolor
    };
    var overlays = {
        "shapefile": geo
    };
    L.control.layers(baseMaps, overlays).addTo(myMap);

In the following image there is an example of what the shapefile with its properties should look like:

enter image description here

While in the following image it is how I visualize it:

enter image description here

How to make a static variable in JavaScript like we do in c ? ( to avoid re-initialization of the variable)

I watched this video on https://www.youtube.com/watch?v=cjIswDCKgu0&t=429s YouTube;

I just wanted to make a simple debounce function. but this code does not work on my device as intended. Please help.


let debounceTimes = 0;

// this code does not work as intended
let timeout; // if I make it global it works just fine
// but I don't want to do that for obvious reasons
function debounce(cb, delay = 100) {
  //  let timeout; // this is being reinitialized

  // only if I could do something like this
  // static timeout;
  // to avoid re-initializing the variable
  // return (...args) => {
  clearTimeout(timeout);
  timeout = setTimeout(() => {
    cb();
  }, delay);
  // }
}

window.addEventListener("mousemove", () => {
 // console.log("hello");
 // document.getElementById("debounce").innerText++;
  debounce(
    () => {
      debounceTimes++;
      document.getElementById("debounce").innerText = String(debounceTimes);
  }, 100);
});