Swiper Slider – Display next/prev slide thumb with navigation

I am using Swiper Slider – 9.0.5

As in below screenshot, I am using swiper as homepage hero. With it’s previous/next slide navigation, I also want to display small thumbnail of next/prev slide. I don’t have any idea. Can anyone please help me out?

Navigation is working correctly. I just need help with displaying next/prev thumb image.

Thanks in advance!

enter image description here

My React Project Shows Weird Behavior-Components load only sometimes

My React project is acting weirdly, i.e, a component is rendered only sometimes. At other times, it doesn’t render completely even though elements like buttons are rendered. Also sometimes the css on other pages changes automatically. I can’t seem to figure out what is happening.

import React, { Component } from "react";
import "./Homes.css";
import { Link } from "react-router-dom";

class Home extends Component {
  state = { value: "" };
  handleInp = (e) => {
    this.setState({ value: e.target.value });
  };

  handleSub = () => {
    this.state.value === ""
      ? alert("Enter a String!")
      : console.log(this.state.value);
  };
  render() {
    return (
      <div className="whole">
        <div className="container">
          <h1 className="headi ">Enter the String</h1>
          <input
            className="in"
            type="text"
            value={this.state.value}
            onChange={(evt) => this.handleInp(evt)}
            placeholder="Enter the string"
          />
          <Link to={"/edit/" + this.state.value}>
            <button
              className="btn btn-primary but m-3 btn-sm"
              id="but"
              onClick={this.handleSub}
            >
              Submit
            </button>
          </Link>
        </div>
      </div>
    );
  }
}

export default Home;

Above is the Home component, which is showing this behavior.

This thing was working perfectly until a point of time. I did not change anything in the code. But then, the Home component stopped working in the right way(without showing any error)

Nuxt3 Attach algolia client to nuxtApp

I want to use the Algolia client accross my app to perform full text search on some data, so my first thought was to create a plugin, something like that :

import algoliasearch from 'algoliasearch/lite';

export default defineNuxtPlugin(async (NuxtApp) => {
    const config = useRuntimeConfig();

    client = algoliasearch(config.public.ALGOLIA_APP_ID, config.public.ALGOLIA_SEARCH_KEY);
     
    NuxtApp.vueApp.provide('algolia', client);
    NuxtApp.provide('algolia', client);
});

this is working fine, I can use my algolia client like that :

const { $algolia  } =  useNuxtApp();
 ... perform search

The problem is that I want to add security on top of that, using firebase auth to login and then use algolia to generate a secured key once signed in.
I successfully retrieve my algoliaSecuredKey but then I’m stuck with the algolia client (attached to NuxtApp)

... login
... retrieve of securedKey
const client = algoliasearch(config.public.ALGOLIA_APP_ID, algoliaSecuredKey);

I would love to instanciate the NuxtApp.$algolia to null at first and then attach the client with the secured key at login.

Any idea how to perform that ?

date.getMonth() is two months off

let date = new Date('2020-04');
let month = date.getMonth() + 1;

This is giving me March not April, it is 1 month off, why is that?

If I use:

let date = new Date('2020-04');
month = date.getUTCMonth() + 1;

Then I get the correct answer. I’m in California. I need the answer to be correct wherever the user is in the world. i.e. I need April as the correct answer.

Header error on my login api function using nodejs

Here is my login function, in my NodeJs API. “user_router” is an express.Router() object that my main express app uses.

users_router.post("/login", (req, res, next) => {

    var data = {
        email: req.body.email,
        password : req.body.password ? md5(req.body.password) : null
    }

    var sql_retrieve = "SELECT * from user WHERE email = ?, password = ?"
    var params = [data.email, data.password]

    db_mariposa.get(sql_retrieve, params, (err, rows) => {

        // from this point on, my user  exists
        if (err) {
            return res.status(400).json({"error":err.message});
        }

        // creates token
        const token = jwt.sign(
            { user_email: data.email },
            "secret",
            {
                expiresIn: "2h",
            }
        );

        var sql_update = "UPDATE user SET token = ? WHERE email = ?, password = ?"

        db_mariposa.run(sql_update, [token, data.email , md5(data.password)])
        
        return res.status(200).json({"my_token":token, "name": data.name, "email": data.email});

    });

});

I’m getting this error:

{
    "error": "SQLITE_ERROR: near ",": syntax error"
}

And before that I was getting an error on the “if (err)” line inside my first SQLite query regarding my header data:

Error: Can't render headers after they are sent to the client.

What am I doing wrong?

Here is my authentication:

const verifyToken = (req, res, next) => {

    const token = req.headers["my_token"];

    console.log(token)

    if (!token) {
        return res.status(403).send("A token is required for authentication");
    }

    try {

        console.log("try/catch")

        const decoded = jwt.verify(token, 'secret');

        req.user_email = decoded;

        console.log("Valid token!")

    } catch (err) {

        return res.status(401).send("Invalid Token");
    
    }

    return next();

};

How to find and collect all anagrams of 500k words and somewhat efficiently store the data in JSON (JavaScript)?

I have this code for generating anagrams, which seems to work as expected. It takes an input word and finds all subwords that can be generated from its letters, down to 3 letter words. However, it is painfully slow (10k words processed in 5 minutes, which is about 4 hours of runtime), and it results in extremely large JSON files.

const terms = require('../configurations/terms.json')
const fs = require('fs')
const _ = require('lodash')

function* getCombinations(array, k, taken=[]) {
    if (k == 0) return yield taken;
    if (array.length < k) return;
    yield* getCombinations(array.slice(1), k - 1, taken.concat(array[0]));
    yield* getCombinations(array.slice(1), k, taken);
}

const output = {}

let i = 0

let trie = {}

terms.forEach(input => {
  // frequencies[input.slug] ??= getFrequencies(input.slug)

  const letters = [...input.slug].sort()

  let node = { children: trie }

  letters.forEach(letter => {
    node = node.children[letter] = node.children[letter] ?? { word: {}, children: {} }
  })

  node.word[input.slug] = true

  i++

  // if (i % 1000 == 0) {
  //   console.log(i)
  // }
})

terms.forEach((input, xi) => {
  const letters = [...input.slug]

  if (xi % 10 === 0) {
    console.log(xi)
    fs.writeFileSync('configurations/term.anagram.en.json', JSON.stringify(output, null, 2))
  }

  const combinations = {}

  let i = letters.length
  while (i >= 3) {
    const array = [...getCombinations(letters, i)]
    array.forEach(item => combinations[item.sort().join('')] = true)
    i--
  }

  const matches = {}

  output[input.slug] = []

  for (const combination in combinations) {
    const match = findMatch([...combination])
    if (match) {
      output[input.slug].push(combination)
    }
  }
})

function findMatch(letters) {
  let node = { children: trie }
  let i = 0
  while (node && i < letters.length) {
    node = node.children[letters[i++]]
  }
  return Boolean(node?.word)
}

// terms.forEach((input, xi) => {
//   const letters = [...input.slug]

//   if (xi % 10 === 0) {
//     console.log(xi)
//     fs.writeFileSync('configurations/term.anagram.en.json', JSON.stringify(output, null, 2))
//   }

//   const combinations = []

//   let i = letters.length
//   while (i >= 3) {
//     const array = [...getCombinations(letters, i)]
//     array.forEach(item => combinations.push(item))
//     i--
//   }

//   const matchers = combinations.map(x => x.sort())

//   const matches = {}

//   matchers.forEach(matcher => {
//     const match = findMatch(matcher)
//     output[matcher] = match
//     matches[matcher] = true
//   })

//   output[input.slug] = Object.keys(matches)
// })

The terms can be simulated with this ~500k word list.

So for example, if the input word is:

interesting

The “subwords” are:

rest
set
sing
tint
get
resting
nesting
getter
...

Etc.. I only care about finding all words down to 3 letter words, so in, while it is a match, wouldn’t be included in the output.

The problem starts to be when it finds all things like say “yee, eye, eey” are all words (combinations of the letters), the 500k word pile has all kinds of junk words leading to an explosion of short words with different combinations of letters. I tried to cut that out in my example, so to “hydrate” all the possibilities you would first fetch the “initial list” given a word as a key, then for each word in the sublist, recursively use that as a key and find the subwords for that, etc.. I can’t see in my mind yet if this would work properly, but it seems close.

Is there any way you can think of to optimize this, both in terms of runtime speed and disk JSON size? Pretty printed JSON was over 5 million lines at 10k words processed, so that’s a lot IMO. How can this be optimized and stored so it doesn’t take up over let’s say 50MB of space? If speed can be brought down below the current ~4 hour mark, can it be brought down to less than a minute? Or even a half an hour?

How to get the community guild default primary language

I created a function to confirm if a guild has community mode enabled when the bot is added, if true I’d like to check if there’s a server primary language set on the community settings.

But I’m not getting or finding the community settings info on the guild object of the GuildCreate event.

Is this possible? thanks.

SelectizeJs: duplicate select menus are being creacted when dynamically generating select menus

I’m trying to create multiple selectize select menu’s dynamically, by pressing the plus icon.

Please test the code below, the problem is that if I comment out this line

selectize_init(select_class, options, results);

from addOrRemoveSelectContainer function, everything will be cloned correctly but selectize will stop working. You won’t be able to select anything

If I leave this line

selectize_init(select_class, options, results);

Then duplicate select menus will be created and only one of them works.

enter image description here

I have tried using

  $(className).selectize({...})

instead of

  $(className).last().selectize({...})

But the problem wasn’t fixed. And I don’t want to use maxItems: null and enable multi-select because each select menu has other options related to that specific selection.

var audiences_value = []
let audiences = [
{id: 1, title: 'foo'}, 
{id: 2, title: 'bar'},
{id: 3, title: 'foobar'},
{id: 4, title: 'baz'}
];

function addOrRemoveSelectContainer(
  btn,
  action,
  container,
  select_class,
  options,
  results
) {
  var $selectContainer = $(btn).parent(container);

  if (action == "add") {
    var $clone = $selectContainer.last().clone();

    $selectContainer.last().after($clone);
   // NOTE: if you comment out the line below
   // selectize_init(select_class, options,results);
   // The select field will be cloned correctly
   // but you cannot select anything
   
   selectize_init(select_class, options, results);
  } else if (action == "remove") {
    if ($(container).length > 1) {
      $selectContainer.remove();
    }
  }
}

function selectize_init(className, options, results) {
  $(className)
    .last()
    .selectize({
      maxItems: 1,
      valueField: "title",
      labelField: "title",
      searchField: "title",
      options: options,
      create: true,
      onChange: function (tenant) {
        results.push(tenant);
      },
    });

  return results;
}

audiences_value = selectize_init(".audiences", audiences, audiences_value)
.select-label,
.select {
    display: inline-block;

}

.select {
    width: 20rem;
}

.selectize-control {
    margin: 2em;
}

.select-container {
    display: block;
}

.add-row,
.remove-row {
    border: 0;
    margin-left: 3px;
}
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css" integrity="sha512-SzlrxWUlpfuzQ+pcUCosxcglQRNAq/DZjVsC0lE40xsADsfeQoEypE+enwcOiGjk/bSuGGKHEyjSoQ1zVisanQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.1/js/bootstrap.min.js"> </script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.15.2/js/selectize.min.js" integrity="sha512-IOebNkvA/HZjMM7MxL0NYeLYEalloZ8ckak+NDtOViP7oiYzG5vn6WVXyrJDiJPhl4yRdmNAG49iuLmhkUdVsQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.15.2/css/selectize.default.min.css" integrity="sha512-pTaEn+6gF1IeWv3W1+7X7eM60TFu/agjgoHmYhAfLEU8Phuf6JKiiE8YmsNC0aCgQv4192s4Vai8YZ6VNM6vyQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    
<div class="select-container audiences-container">
 <select class="select audiences" required></select>
  <button type="button" class="add-row bg-success text-white" onclick="addOrRemoveSelectContainer(this, 'add', '.audiences-container', '.audiences', audiences, audiences_value)"><i class="fas fa-plus"></i></button>
<button type="button" class="remove-row bg-danger text-white" onclick="addOrRemoveSelectContainer(this ,'remove', '.audiences-container')"><i class="fas fa-minus"></i></button>
 </div>

How do I add max-width to my slider swiper wrapper in react?

I have a slider swiper library in my react project. I am trying to add the max-width parameter to the swiper-wrapper. I have 3 slides inside my slider and each one is a flex container, which contains a content block and image. The issue is that my image and content have bad behaviour on big devices like monitors, and the max-width property there isn’t working. I think the error is connected to the image because content behaviour is good, but the image is moving from one side to another side on adaptive. How to fix it? Photo of that behaviour and CSS styles of my swiper wrapper below the question. If you need more code just ask, and I will add it to this question.

swiper wrapper CSS styles:

.main-slider .swiper-wrapper {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

swiper slide CSS styles:


.section-slide {
  display: flex;
  align-items: center;
  position: relative;
}

Image CSS styles:

.slide-image img {
    max-width: 100%;
    max-height: 400px;
    height: 100%;
}

The image

Foundation Sites — Adding accordion component with jQuery

Currently using Foundation Sites 6.4.1 in conjunction with jQuery, and specifically the accordion component. Right now, I’m trying to dynamically add an accordion component using jQuery. Currently it will add the component with all correct css classes, but the actual functionality of the accordion doesn’t work. None of the panels expand, which isn’t correct behavior. Here is the jQuery I’m adding on a button click:

 <ul class='accordion' data-accordion id='faq-accordion' data-allow-all-closed='true'>
          <li class='accordion-item is-active' data-accordion-item='' id='faq-first-question'>
            <a href='#' class='accordion-title'>Question</a>
            <div class='accordion-content' data-tab-content=''>
              <label for='data[faq][name][]'>Question Name</label>
              <input type='text' name='data[faq][name][]'/>
              <label for='data[faq][answer]'>Question Answer</label>
              <input type='text' name='data[faq][answer][]'/>
            </div>
          </li>
        </ul>

which creates the accordion — but doesn’t expand/contract.

This looks to be right — however, when I just add an accordion on the page that is static (not using jQuery) – I notice that the data-accordion property has been given an id of sorts:

<ul class="accordion" data-accordion="vxlufp-accordion" data-allow-all-closed="true" role="tablist">

and this works as expected. I feel like I’m missing something very small — or this just isn’t possible what I’m trying to do.

Thanks!

How do I make my sorting algorithm code work?

programming newbie over here trying to make it through college. I am working on this JSFiddle and I am trying to make a program that will implement a sorting algorithms. Here are a basic rundown of the instructions:

You should automatically populate Your List with 20 elements (random strings).

Once you have completed this – you will add the insertion sort as a function.

The interface should have buttons to (1) Repopulate the list with Random strings, (2) Sort list with selected algorithm 1 (3) Insert a user entered value into the sorted list. After each operation, it should display the new list.

Option 4 here will insert the new string entered by the user (you will need a textbox to enter the string) in the correct sorted position, and you should print the new list with the new element on the screen.

For a nice clean interface, you may want to create a table with three columns and put the insert button on columns 2 and 3 and the results of sorting the list (printed in column 1) in columns 2 and 3 below the button. This is not required, but it does give you an opportunity to look at various methods of creating an interface to present results (you will do a lot of this in COP4813).

When you insert the “String” ensure that it inserts into the correct location in one of the sorted lists. You can demonstrate the insertion into any of the sorted lists.

Note: Your insertion function should NOT SORT the entire List after the insert. You should insert the element into the correct location in your List without having to resort the entire List. This will give it a complexity of O(n).


Having said all that, I have managed to get the list to generate 20 random strings. I managed to get the sorting algorithm sort of working but definitely not flawlessly. The insertion function is very buggy. I have included the JSFiddle below, please let me know how I can fix my code because I really just cant get it to work. Thank you!

Here some code so I can add the jsfiddle link:

function insertionSort() {
        // Create a new double-linked list to hold the sorted 
        id = 0;
        var sortedList = new DblLink();

        // Iterate through the nodes in the unsorted list
        var node = dbleList.head;
        while (node != null) {
          // Find the correct position to insert the node in the sorted list
          var sortedNode = sortedList.last;
          while (sortedNode != null && sortedNode.item > node.item) {
            sortedNode = sortedNode.prev;
          }

          // Insert the node in the sorted list
          if (sortedNode == null) {
            sortedList.add(node.item);
          } else {
            var newNode = new Node(node.item);
            newNode.prev = sortedNode;
            newNode.next = sortedNode.next;
            if (sortedNode.next != null) {
              sortedNode.next.prev = newNode;
            } else {
              sortedList.last = newNode;
            }
            sortedNode.next = newNode;
            sortedList.length++;
          }

          // Move to the next node in the unsorted list
          node = node.next;
        }

https://jsfiddle.net/adrianpetria/d74tnugs/12/

Webpack/WordPress not loading all SCSS files of my React components

I’m using WordPress 6.1.1 with Gutenberg 15.3.1 and default webpack.config.js.

I don’t know why, but when I import more than one React component at the same level, their CSS doesn’t get loaded.

edit.js

export default function Edit() {
    const blockProps = useBlockProps();

    return (
        <div {...blockProps}>
            <CentreWrapper data={centres}/>
            <CentreInformation data={centres}/>
        </div>
    );
}

save.js:

export default function Save() {
    const blockProps = useBlockProps.save();

    return (
        <div {...blockProps}>
            <div id="centre-wrapper"></div>
            <div id="centre-information-wrapper"></div>
        </div>
    );
}

Then, this code goes into a client.js file that is attached on the frontend using viewScript in block.json.

window.addEventListener("DOMContentLoaded", (event) => {
    const centresWrapper = document.getElementById("centre-wrapper");
    const testWrapper = document.getElementById("centre-information-wrapper");

    if (centresWrapper) {
        render(<CentreWrapper data={centres} />, centresWrapper);
    }

    if (testWrapper) {
        render(<CentreInformation data={centres} />, testWrapper);
    }
});

Then, in my components I just import the SCSS files like this

import "./CentreInformation.scss";
const CentreInformation = ({ data }) => { }

It’s even weirder because in the editor, the first component has its CSS loaded, but the second one doesn’t. On the frontend, neither one of them has CSS.

In the Sources tab, the contents of the .scss files got changed to this:

// extracted by mini-css-extract-plugin
export {};

meaning that MiniCSSExtractPlugin has extracted the CSS but I don’t know where it is.

When memory is filled with big variables, canvas becomes very slow

In my drawing app i want to keep several steps of user, to give him ability to undo.

My idea was to save imageData to array (toDataUrl give some artifacts with canvas shadows). But then i’ve seen that storing it this way makes drawing really slow. Especially when use canvas filters like blur. It’s obvious that they slow down drawing, but difference between having variables in memory, or not, is huge, and also bigger when I use those canvas things like blur. Also, effect when i add for example 100 steps to array doesn’t seem to be much different from 2 steps

Is it because those canvas things like filters and blur require a lot of memory?

I’ve created demo in codesandbox: https://codesandbox.io/s/black-voice-v5oxhw?file=/src/index.js.