Axios forward slash (/) url encoding issue

I am having a technical difficulties since I have to change date formats from ‘YYYYMMDD’ to ‘MM/DD/YYYY’.

I am using Axios; then Axios automatically encode my request uri.

For example, I made codes to create a request: STARTDATE=04/01/2021&ENDDATE=04/30/2021
but then when it sends through Axios it becomes: STARTDATE=04%2F01%2F2021&ENDDATE=04%2F30%2F2021; Because ‘/’ is encoded to ‘%2F’ automatically.

The requesting url I want to send is = 04/01/2021, != 04%2F01%2F2021
Any insights will be appreciated!

Website dark mode change triggers video source change

I have a custom button in my WordPress Elementor page that randomly changes the video playing on the website. The URLs are defined in the back end, and the PHP code is added in the footer. Not much to it, seems to work well:

<?php
$all_random_urls = array();
if( have_rows('videor_random_url') ):

    while( have_rows('videor_random_url') ) : the_row();

        $sub_value = get_sub_field('add_videor_random_url');
        $all_random_urls[] = $sub_value;
        
    endwhile;

else :
    // Do something...
endif;
?>
<script>
    jQuery(document).ready(function() {
        var all_datas = "";
        var new_video_url = "";
        setTimeout(function() {
            all_datas = <?php echo json_encode($all_random_urls); ?>;
            
            jQuery('#random_video_changer').on('click', function() {
                var present_video_url = all_datas[Math.floor(Math.random() * all_datas.length)];
                if(new_video_url != '' && new_video_url == present_video_url) {
                    present_video_url = all_datas[Math.floor(Math.random() * all_datas.length)];                    
                    new_video_url = present_video_url;
                    jQuery('.mdp-videor-video video.elementor-video').attr('src', new_video_url);
                } else {
                    new_video_url = present_video_url;
                    jQuery('.mdp-videor-video video.elementor-video').attr('src', new_video_url);   
                }
            });
        }, 2000);
        
    });
</script>

What I am trying to do now is use the dark mode toggle button from my Darklup plugin to change the video playing. I have managed to do it by changing the on-click from ‘#random_video_changer’ to whatever the div id/class of the button is. This works but in this way it is impossible to use different videos for dark and light theme since every button click toggles a video change. I have been trying to change the following plugin js to call for video change when theme is dark or light, but I am struggling to get any results.

    darkModeSwitchEvent: function() {

            let $that = this;

            $(this.switchTrigger).on( 'click', function(e) {

                let $this = $(this);

                $('html').toggleClass($that.darkEnabledClass);

                // Storage data
                if( $this.is(':checked') ) {
                    localStorage.setItem("darklupModeEnabled", $that.darkEnabledClass);
                    localStorage.setItem("triggerCheked", "checked");
                    $this.closest('.darkluplite-mode-switcher').addClass('darkluplite-dark-ignore');

                    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
                        localStorage.removeItem("lightOnOSDarkCheked");
                    }
                } else {
                    $this.closest('.darkluplite-mode-switcher').removeClass('darkluplite-dark-ignore');
                    localStorage.removeItem("darklupModeEnabled");
                    localStorage.removeItem("triggerCheked");

                    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
                        localStorage.setItem("lightOnOSDarkCheked", true);
                    }
                }

            } )

What would be the simplest way to achieve this – when light mode is active the video is played from video array 1, when dark mode is active, video is played from video array 2?

I am trying to learn how to do this on my own but have spent few hours on this now without any movement in the right direction, so any help is greatly appreciated.

How could I automatically read all of the directories and add all files that end in .js to discord collection

This is the code I currently have, how would adapt this to check each sub-directory:

const fs = require('fs')

module.exports = (client, Discord) =>{
    const command_files = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'))

    for(const file of command_files){
            const command = require(`../commands/${file}`);
            if(command.name) {
                client.commands.set(command.name, command);
            } else {
                continue
            }
         }
}

And this is the layout I have for the commands folder the folder layout

How to code “re-run custom function” button in Google Sheet custom function?

I’m having the problem lots are having where my Apps Script code on Gsheets doesn’t automatically update unless it registers a change in the parameters. The custom function I’m using counts the number of cells that are highlighted a specific color. Changing the color of a cell doesn’t re-run the script. I wanted to add a check box in a cell and every time I click it, it reruns the function.

function COUNTCOLOR(countRange,colorRef,recalc) {
  var activeRg = SpreadsheetApp.getActiveRange();
  var activeSht = SpreadsheetApp.getActiveSheet();
  var activeformula = activeRg.getFormula();
  var countRangeAddress = activeformula.match(/((.*),/).pop().trim();
  var backGrounds = activeSht.getRange(countRangeAddress).getBackgrounds();
  var colorRefAddress = activeformula.match(/,(.*))/).pop().trim();
  var BackGround = activeSht.getRange(colorRefAddress).getBackground();
  var countCells = 0;
  for (var i = 0; i < backGrounds.length; i++)
    for (var k = 0; k < backGrounds[i].length; k++)
      if ( backGrounds[i][k] == BackGround )
        countCells = countCells + 1;
  return countCells;
};

The function works, but only without the “recalc” variable, which is the variable I need to add a check box to re-run the code. I get an error: “Range not found (line 6)”. Any advice on getting this to work?

Thanks!

Need Help JavaScript Challenge

I can’t seem to pass the test for this challenge.

// Write a function that takes 6 values (a,b,c,d,e,f) as arguments
// Sum a and b
// Then substract by c
// Then multiply by d and divide by e
// Finally raise to the power of f and return the result
// Tipp: mind the order

function myFunction(a, b, c, d, e, f) {

    return 
}

Script dynamically inserted later on: how to make it run?

In my React app, I have scripts that are inserted dynamically later on. The scripts don’t load.

A field called content in my database for example contains data such as the following:

<p>Some text and html</p>
<div id="xxx_hype_container" style="width: 46px; height: 50px; overflow: hidden;">
<script type="text/javascript" charset="utf-8" src="https://example.com/uploads/hype_generated_script.js?499892"></script>
</div>
<div style="display: none;" aria-hidden="true"> 
<div>Some text.</div> 
Etc…

In my React app, I call on this db field to display that content:

import { thePost } from "../../../appRedux/actions/postAction";

class Post extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            post: "",
        };
    }

    componentDidMount() {
        // get post data from db
        this.props.thePost(this.props.match.params.postId);
    }

    render() {
        return (
            <div className="container">
                {post.content}
            </div>
        )
    }
}

It correctly loads the data from the database and displays the html from that data. But the data also contains a script, which does NOT get loaded. I think the script doesn’t work because it is dynamically inserted later on. How can I make this script work/run?

This post suggest a solution for dynamically inserted scripts, but I don’t think I can apply this solution because in my case the script/code is loaded from a database (so how to then use nodeScriptReplace on the code…?). Any suggestions how I might make my scripts work?

Symfony live search bar with ajax

I’m very new with ajax, I have a page which displays all formations on my Symfony online learning website, and I’m trying to make a search bar which would display the results without refreshing the page. If you don’t type anything, all formations show, if you type something you get matching results or an error message, without refreshing the page by using a submit button.

I’ve already looked into Ajax requests, I’m not sure I understand everything. I understand I need to get the string the user types in the bar by using onkey and getting the input and then make a query that selects formations in the database which titles match the input, and process it through the controller.

Here’s my twig view on which all formations are displayed:

{% extends 'base.html.twig' %}
{% block title %}Formations{% endblock %}
{% block content %}
    <div class="blockcontainer text-center">
        <h1>Nos formations</h1>
        <br>
            <input type="text" class="form-control" id="live_search" placeholder="Rechercher une formation">
        <br>
        <div class="row justify-content-md-center" id="search_results">
                {% for formation in formations %}
                    <div class="col-xl-2">
                        <div class="card">
                            <img class="card-img-top" src="{{ vich_uploader_asset(formation, 'imageFile') }}" alt="{{ formation.imageName }}">
                            <div class="card-body">
                                <h5 class="card-title">{{ formation.title }}</h5>
                                <p class="card-text">{{ formation.description }}</p>
                                <a class="small btn btn-success custom-btn rounded-pill px-3" href="{{path('app_formations_see', {'id' : formation.id })}}" role="button">voir</a>
                            </div>
                        </div>
                    </div>
                {% endfor %}
            </div>
    </div>
{% endblock %}

I also read you shouldn’t display results in a view that extends a template?
How do I go around this? thanks!

Does Google Apps Script (GAS) support proper tail calls or tail call optimization?

I’m wondering whether investing time into doing tail call optimization for a Google Apps Script is worth it.

So, I’ve understood that Google Apps Script uses the ES2015 (ES6) version of the JavaScript specification (ref1, ref2), running it on the V8 runtime implementation.

Supposedly, ES2015 supports (proper) tail call optimization from the spec. But there are some indications that V8 actually doesn’t implement it:

Furthermore, I’ve learned there is an important nuance here:

The terminology of proper tail calls (PTC) and tail call optimization (TCO) is often conflated. Here’s the difference between the two:

  • proper tail calls: functions called in the tail position reuse the current stack frame, preventing the creation of additional stack frames that cause space inefficiency.
  • tail call optimization: rewrites a recursive function into an iterative one, usually by calling goto.

PTC only deals with stack manipulation, while TCO rewrites a recursive
function as an iterative function.

So, given this…

Does Google Apps Script (GAS):

  • support proper tail calls? My guess from the above is “No.”, but it’d be nice to have an authoritative answer, as far as possible.
  • support tail call optimization to the point where it is worth doing it, for performance, in any way? My guess is “Yes, you can do it, but it doesn’t improve performance.” But it’d be nice if someone knew it definitively, or could point to a GAS performance comparison that demonstrates it.

How to make when bot ask a question, he waiting for an answer and ask another question

I wanted to create my bot for economics, but I ran into a problem. What do I want to do: after writing one question, the bot waits for an answer and then asks another question and so on. Can someone help me with my problem? Currently I have something like this:

const config = require('../../config.json');
const { MessageEmbed } = require('discord.js');
const shopEconomy = require('../../database/shopEconomy');

module.exports = {
    name: 'create-item',
    aliases: [],
    description: '',
    run: async(client, message, args) => {
        const items = require('../../items.json');
        const item = items[Math.floor(Math.random() * items.length)];
        const filter = response => {
            return response.content.toLowerCase();
        };
        const embed = new MessageEmbed()
        .setColor(`${config.correct}`)
        .setAuthor({ name: `Item` })
        .addFields(
            { name: `Name`, value: `---`}
        )

        return message.channel.send(item.question, { fetchReply: true, embeds:  })
        .then(() => {
            message.channel.awaitMessages({ filter, max: 1, time: 10000, errors: ['time'] })
            .then(async collected => {
                const embed = new MessageEmbed()
                .setColor(`${config.correct}`)
                .setAuthor({ name: `Item` })
                .addFields(
                    { name: `Name`, value: `${collected.first()}`}
                )
        
                    await shopEconomy.findOneAndUpdate(
                        {
                            guildID: message.guild.id,
                        },
                        {
                            name: `${collected.first()}`,
                        },
                        {
                            upsert: true,
                        }
                    );

                return message.channel.send({ embeds:  });
            })
            .catch(collected => {
                const embed = new MessageEmbed()
                .setColor(`${config.false}`)
                .setDescription(`Timeout.`)

                message.channel.send({ embeds:  });
            });
            
        });
    }
}

Image Optimization, long list data fetched from Rest API and rendering the top of the home page on a new user’s first visit

Can someone help me to answer these questions? I did it but I would like to have an expert opinion on these field. Here we is the case:

Please provide options of what someone can do to improve the performance of a website for each of the following topics. Imagine that an engineering manager has given you the freedom to improve the following items on a website for the next month. What would you tell the manager you would take a look at? Bonus: Please add any details to your list, if time allows, to showcase your knowledge.

displaying images
displaying long lists of data fetched from a REST API
rendering the top of the home page on a new user’s first visit as soon as possible

A React component’s function is not recognized as a function when passed in as a parameter

I’m trying to pass a function as a parameter for a component, however it does not see the function I pass in as a function.

Here’s the page (I’m only going to provide what’s imoprtant)

const Home = () => {
const nav = useNavigate()

const [userList, setUserList] = useState([]);
const [loggedInUser, setLoggedInUser] = useState({});
const [currentChat, setCurrentChat] = useState(undefined);
const [showMenu, setShowMenu] = useState(false);

let navMenu    


const handleChatChange = (chat) => {
    setCurrentChat(chat);
}



return (

        <div id='sidebar'>
            <div>
                <Userlist users={userList} switchChat={handleChatChange}/>
            </div>
        </div>
)

Here is the react component that provides the error

const Userlist = ( props, switchChat  ) => {

const switchCurrentchat = (user) => {
    switchChat(user);
}

return (
        <div>
            <div id='home-header'>
                <h1>DevsHelp</h1>
            </div>

            <div id='userlist'>

                {props.users.map((user) => {
                    return (
                        <div key={user._id} className='user' onClick={() => switchCurrentchat(user)} >
                            <h3>{user.username}</h3>
                        </div>
                    )
                })}
            </div>
        </div>
)}

Whenever switchChat is called upon, it returns an error stating “switchChat” is not a function.

If I do a console.log(user) instead of switchChat(user), it logs the user, so the function works, however it’s just not reading it as a function.

If anyone could help me, I would appreciate it a lot, thanks!

Proper class format in modern ES

Is the following an acceptable way to initialize a class?

class Person {
    name = undefined; // or just `name` ?
    age = undefined; // or just `age` ?
    constructor(name, age) {
        Object.assign(this, {name, age});
    }
}
let p = new Person('tom', 10);

By that I mean, more specifically,

  • Is Object.assign(this, {...variables}) a good way to do all the this assignments?
  • Is it considered good practice to stick the variables at the top, or should they be placed within the constructor?
  • Is it better to explicitly set a variable to undefined or not? That is, is name = undefined; or name; preferable?

Typescript can’t find module of a referenced Project

I am trying to share code between 2 seperate Typescript projects.
To demonstrate this easily reproducable problem I created a minimal repository here (Including instructions to reproduce):
https://github.com/realdegrees/ts-function-reference/tree/master/project

You can check out the repo or the following code snippets.
The issue is that I can import e.g. interfaces and enums just fine and they work (ran the code and had the enums logged) but as soon as it’s a function I’m trying to import it doesn’t work anymore.

Running tsc works fine and throws no errors. You can even see that typescript resolves the module in question perfectly fine.

❯ tsc --traceResolution | grep 'reference/lib'
======== Resolving module '../reference/lib' from '/home/fasc/projects/reference- 
test/project/index.ts'. ========
Loading module as file / folder, candidate module location 
'/home/fasc/projects/reference-test/reference/lib', target file type 'TypeScript'.
File '/home/fasc/projects/reference-test/reference/lib.ts' exist - use it as a name 
resolution result.
======== Module name '../reference/lib' was successfully resolved to 
'/home/fasc/projects/reference-test/reference/lib.ts'. ========
======== Module name './lib' was successfully resolved to 
'/home/fasc/projects/reference-test/reference/lib.ts'. ========

However as soon as I try to start the project it’s the ‘ole
Error: Cannot find module '../reference/lib'

I have tried importing the index.ts, lib.ts directly and paths in tsconfig.ts.
References are setup correctly and it obviously works with types but for some reason not functions.

The project looks like this: [Image][1]

Files:

////////////// project/index.ts
// None of these work
import { foo as regularDirectImport } from '../reference/lib';
import { foo as regularIndexImport } from '../reference/index';
import {foo as pathsImport} from '@reference';
pathsImport();
regularDirectImport();
regularIndexImport();

/////////// project/tsconfig.ts
{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "outDir": "dist", 
    "esModuleInterop": true, 
    "forceConsistentCasingInFileNames": true, 
    "strict": true, 
    "skipLibCheck": true,
    "baseUrl": ".",
    "paths": {
      "@reference": ["../reference/index"]
    }
  },
  "references": [
    {
      "path": "../reference"
    }
  ]
}

////////// reference/index.ts
export * from './lib';

////////// reference/lib.ts
export const foo = () => {
    console.log('bar');
}

////////// reference/tsconfig.ts
{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "outDir": "dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "baseUrl": "src",
    "declaration": true,
    "declarationMap": true,
    "composite": true
  }
}

I would die for some help, I have found several guides on how to import code from external typescript projects and they all mention that functions work as well but I just cannot get it work.
[1]: https://i.stack.imgur.com/KXOGc.png