Getting the Index of the elements from an array that when substracted to the elements with same index from another array is negatif

As indicated in the question (maybe not properly formulated) I am trying to get the index of an array for which the difference between each of its element and the index-corresponding element of the second array is < 0. Maybe the code below will explain more what I am trying to obtain. I succeded to get the desired indexes using flatMap() function but could get it using the filter() filter which I think is more appropriate in this case (always getting here the element but not the index)

let array1 = ['524', '587', '034', '816', '65', '7']
let array2 = ['3', '0', '33', '4', '193', '13']



function getSumOfArrays(array1, array2){
    let sumArray = array1.map((elem,idx)=>parseFloat(elem) - parseFloat(array2[idx]))
    return sumArray
}

function getIdxNegativeDiff1(array1, array2){   //this function works   
    let negatifIdx1 = array1.flatMap((elem,idx)=>{return parseFloat(elem)-parseFloat(array2[idx]) < 0 ? idx : [] })
    return negatifIdx1
}

function getIdxNegativeDiff2(array1, array2){          
    let negatifIdx2 = array1.filter((elem,idx)=>{ return (parseFloat(elem)-parseFloat(array2[idx]) < 0 ? idx : '')})
    return negatifIdx2
}



console.log(array1)
console.log(array2)
console.log(getSumOfArrays(array1, array2))
console.log(getIdxNegativeDiff1(array1, array2))
console.log(getIdxNegativeDiff2(array1, array2))

Tried many possibilities but could not reach the solution with filter. Could someone with the solution

Replacing accountNumber with a new API field

API development was already completed to accept the new token when called.

Currently, we only have methods that show account numbers and mask them.

When someone has a protection field enabled though, I want to replace the account number/mask with the new Token from the API.

….how do I go about implementing this? JavaScript/React.

export interface TokenProps {
accNbr?: string;
tokenForExample?: string;
}

export const Token: React.FC<TokenProps> = ({
accNbr,
tokenForExample
})
// If tokenForExample == true {
// Do something()
}

How do you use JavaScript file system API to read and write to a file?

I want to edit a text file on my website, but I don’t have a PHP server. I want to use the file path instead of a file selector to read and write to the text file. The text file is on the website, not on the client’s computer.

I tried using the website here: https://developer.mozilla.org/en-US/docs/Web/API/File_System_API#concepts_and_usage, but it doesn’t allow me to just use a file path instead of a file selector.

Select2 throws too many events when clearing the selection

I am using Select2 for a multi select. This select is used to filter a list.

Selecting one item rebuilds the list with that filter(s). Removing one item, again rebuild the list without that specific item. You can select more than one items.

I have attached a behaviour on the “on change” event of the select. This is going well. The list is properly rebuild when individual items are selected/deselected.

My problem is when I click on the “clear handle”, I get too many events. For example, when I have two items selected in the selector, if I click the clear button, I get 3 change events and the list is rebuild 3 times! I would like to have only one event that I can rely on when clearing the selection.

I could use the clearing or clear event, but would I need a way to rebuild the list when individual items are selected or unselected. The problem is I cannot use both… a select2:unselect/change event is triggered for every individual items that is removed from the list whether you remove individual item manually or use the clear button that removes all items automatically…

Using the clear button should trigger the change event only once!

The select2:unselect could be triggered once per item removed though…

const $field = $("[name=color]");
$field.select2({
    allowClear: true
});

$field.on("change", function(e) {
  console.log("pulldown change");
  // Use $this.val() to rebuild the list with the new filters
});
$field.on("change.select2", function(e) {
  console.log("change.select2");
});
$field.on("select2:select", function(e) {
  console.log("select2:select");
});
$field.on("select2:unselect", function(e) {
  console.log("select2:unselect");
});
$field.on("select2:clearing", function(e) {
  console.log("select2:clearing");
});
$field.on("select2:clear", function(e) {
  console.log("select2:clear");
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<select class="form-control" style="width: 100%" name="color" multiple>
  <option value="blue">blue</option>
  <option value="red">red</option>
  <option value="yellow">yellow</option>
</select>

Browser console after clicking the clear button. (The X on the input that replaces the select box)

select2:clearing
select2:clear
pulldown change
change.select2
select2:unselect
pulldown change
change.select2
select2:unselect
pulldown change
change.select2

In short, clicking on the clear button will trigger the clearing and the clear events, it will then trigger a change, change.select2 and a select2:unselect event for each items that was selected. It then triggers a change and a change.select2 event once more.

How do I convert an id that defaults to comma-separated string to an array of strings?

I am trying to pass data from Formidable Forms to Brevo with an API. Here is my code so far:

{ "updateEnabled": true,
"email": "[376]",
"emailBlacklisted": false, 
"smsBlacklisted": false,
"attributes": {
    "FIRSTNAME": "[374]",  
    "LASTNAME": "[375]",   
    "GENRE": ["[385]"]
     
},
"listIds": [2]   

}

It works perfectly until I add in genres. The id 385 is the answers for a multiple-selection question in Formidable Forms and has the same answers as the GENRE attribute in Brevo. Formidable Forms defaults to a comma separated format but Brevo requires an array of strings. Currently, it will pass the data only if the first option in the form is selected. If anything else is selected, the other data transfers but the genre is left blank. Any ideas on how I can get it to pass all of the genre data in an array?

I tried the code listed above and I also tried the below (adding .split to help make it an array).

let selectedGenres = formData[385]; 
let genreArray = selectedGenres.split(',').map(item => item.trim());

let apiRequest = {
  "updateEnabled": true,
  "email": "[376]",
  "emailBlacklisted": false,
  "smsBlacklisted": false,
  "attributes": {
    "FIRSTNAME": "[374]",
    "LASTNAME": "[375]",
    "GENRE": genreArray 
  },
  "listIds": [2]
};

ScrollSpy active class not working in Bootstrap 5.3.3

I’m creating an app with React, and it has a sidebar where I want to use Bootstrap 5.3.3 ScrollSpy to highlight the items as I scroll down. I followed the documentation (it’s actually not the first time I use it) and I think my code is ok, but I can’t get the items in the sidebar highlighted as I scroll, because the “active” class is never applied to any of them.

Funny thing, though, is that besides it, I also straight copied a code snippet from the documentation in a test component, and it works. But my sidebar doesn’t.

This is my body element, which is supossed to be the scrollable / “spied” element:

<body data-bs-spy="scroll" data-bs-target="#sidebar" data-bs-offset="0" data-bs-smooth-scroll="true" class="scrollspy-example" tabindex="0"> 

This is my sidebar component, where the a anchors should be highlighted as I scroll down the body:

<div id="sidebar" className="grammar-class-list list-group">
     {meanings.map((meaning, index) => (
         <a href={`#grammar-class-${index + 1}`} className="grammar-class list-group-item list-group-item-action">{meaning.partOfSpeech}</a> 
     ))}
</div>

When it compiles, the DOM looks ok to me. The links in the sidebar are clickable and lead to their anchors in the body. But they don’t get highlighted, because the active class is never applied.

As I mentioned, I also used this other code from the BS docs as a dummy test, and it works, by “spying” the content where the anchors are, and highlighting them as I scroll.

 <div class="col-4">
   <div id="list-example" className="list-group">
    <a className="list-group-item list-group-item-action" href="#list-item-1">Item 1</a>
    <a className="list-group-item list-group-item-action" href="#list-item-2">Item 2</a>
    <a className="list-group-item list-group-item-action" href="#list-item-3">Item 3</a>
    <a className="list-group-item list-group-item-action" href="#list-item-4">Item 4</a>
  </div>
</div>
<div class="col-8">
  <div>
   <h4 id="list-item-1">Item 1</h4>
   <p>Some content</p>
   <h4 id="list-item-2">Item 2</h4>
   <p>Some more content</p>
   <h4 id="list-item-3">Item 3</h4>
   <p>Some more content</p>
   <h4 id="list-item-4">Item 4</h4>
   <p>Some more content</p>
 </div>
</div>

As you can see, I’m using Scrollspy via data atributtes. I’ve done it before and it worked, but I don’t what’s wrong with my sidebar.

I’m using Bootstrap via npm and including it in the body like this:

<script src="js/bootstrap.bundle.min.js"></script>

It’s working, because as mentioned the dummy example from the docs works in the same app.

You can see a live example here by searching for any word

Anybody has any idea what am I doing wrong? Please feel free to ask for more details if you need them.

Thanks in advance.

When does the popstate fire? What is it dependent on?

I found that popstate fires when the user presses back or forward button. But that does it mean it is the default behaviour of the browser. Suppose a website doesn’t use SPA, clicking on a link loads an entire webpage from the server. So the URL gets changed and a page gets loaded, pushstate or replacestate is functions only performed by user. So this click doesn’t performs any of this. Now if we click on the back button of the window this does not triggers popstate. Am I correct or both the thing are different? I mean we do not use pushstate/replace state but while pressing back or forward buttons do get fired?

I have been going through this link and I cannot these explanations mentioned in this website:

Example 1 :

Suppose we are on example.com/home, and from here we navigate to example.com/home#s1.
->When we navigate to example.com/home#s1, the webpage isn’t reloaded. The document of this new entry is the same document belonging to example.com/home.

Since the document of both these locations is the same, and we made a navigation, popstate gets fired. The answer is a clear cut yes.

Also, Example 2 :
Suppose we are on example.com/home#s1, and from here we navigate to example.com/home.
->When we navigate to example.com/home, a browser reload is done. This means that the document of the new entry example.com/home doesn’t remain the same as that of the initial entry example.com/home#s1; likewise popstate won’t fire.

The answer is a clear-cut no.

Example 3 :
Suppose you execute the code below on example.com and then navigate to example.com/#about. After this, you go back to the initial entry using the Back button on the browser.

var o = {x: 1}
history.replaceState(o, '');

window.onpopstate = function(e) {
    console.log(e.state === o);
}

What will the console print?

Can you explain these 3 examples this might clear my confusion a lot.

Error:You may need an appropriate loader to handle this file type -> when trying to add css styling

added a few npm packages to my package.json:

simple-line-icons.css

vendor.bundle.base.css

react-bootstrap-table2.min.css

materialdesignicons.css

rc-slider/assets/index.css

and then running npm install gives this error for each of those:

ERROR in ../node_modules/rc-slider/assets/index.css 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> .rc-slider {
|   position: relative;
|   height: 14px;
 @ ./src/App.tsx 19:0-36
 @ ./src/index.tsx 3:0-24 8:30-33

ERROR in ../node_modules/react-bootstrap-table-next/dist/react-bootstrap-table2.min.css 1:0
Module parse failed: Unexpected token (1:0)

And this is my webpack config:

module.exports = {
  entry: './src/index.tsx',
  mode: 'development',
  output: {
    filename: 'bundle.[fullhash].js',
    path: path.resolve(__dirname, 'dist'),
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
    }),
  ],
  resolve: {
    modules: [__dirname, 'src', 'node_modules'],
    extensions: ['*', '.js', '.jsx', '.tsx', '.ts'],
  },
  module: {
    rules: [
      {
        test: /.(js|ts)x?$/,
        exclude: /node_modules/,
        use: ['babel-loader'],
      },
      {
        test: /.css$/,
        exclude: /node_modules/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /.(png|svg|jpg|gif)$/,
        exclude: /node_modules/,
        use: ['file-loader'],
      },
    ],
  },
};

Port a JavaScript hashing function to Python [closed]

I want to convert the below function to Python but I guess the hashlib/Crypto library works differently to crypto-js:

class captha {
    constructor() {
        this.RECAPTCHA_ENCRYPT_SECRET = CryptoJS.MD5("token"); // Chave secreta como WordArray
        console.log(this.RECAPTCHA_ENCRYPT_SECRET)
    }
    encryptToken(z) {
        return CryptoJS.TripleDES.encrypt(z, this.RECAPTCHA_ENCRYPT_SECRET, {
            mode: CryptoJS.mode.ECB
        }).toString();
    }

}

I tried

from Crypto.Hash import MD5

hash_obj = MD5.new(data=b"token")
hash_bytes = hash_obj.digest()


words = [int.from_bytes(hash_bytes[i:i+4], byteorder='little', signed=True) for i in range(0, len(hash_bytes), 4)]
sigBytes = len(hash_bytes)


print("Words:", words)
print("SigBytes:", sigBytes)

but it didn’t work.

Unable to mock a typescript module in jest correctly

I have a test I’m trying to run and I want to mock a module using jest.mock. However, I can’t seem to get this one to work, in the example below, the original serializeProduct method is always invoked. I’ve tried spies, I’ve tried mocking the module. When I log out the variables that are the mocks/spies they are indeed mock functions at least so the mocking is happening. It’s just that something is causing it to invoke that original method instead of the mock.

product.serializer.ts

import { ProductDto } from './product.dto';

export function serializeProducts(value: any[]): ProductDto[] {
    return value.map(serializeProduct);
}

export function serializeProduct(value: any) {
    return value;
}

product.serializer.spect.ts in the same folder as the above.

import { expect } from '@jest/globals';
import * as productsSerializer from './products.serializer';

describe('serializer', () => {
    afterEach(() => {
        jest.clearAllMocks();
        jest.restoreAllMocks();
    });

    describe('serializeProducts method', () => {
        it('should foo', () => {
            const packages = [1,2,3,];

            const spy = jest.spyOn(productsSerializer, 'serializeProduct').mockImplementation(() => undefined);

            productsSerializer.serializeProducts(packages);

            expect(spy).toHaveBeenCalledTimes(3);
        });
    });
});

I have also tried module mocking originally like so

jest.mock('./products.serializer', () => ({
  ...jest.requireActual('./products.serializer'),
  serializeProduct: jest.fn()
});

import { expect } from '@jest/globals';
import * as productsSerializer from './products.serializer';

describe('serializer', () => {
    afterEach(() => {
        jest.clearAllMocks();
        jest.restoreAllMocks();
    });

    describe('serializeProducts method', () => {
        it('should foo', () => {
            const packages = [1,2,3,];

            (productsSerializer.serializeProduct as jest.Mock).mockImplementation(() => undefined);

            productsSerializer.serializeProducts(packages);

            expect(productsSerializer.serializeProduct).toHaveBeenCalledTimes(3);
        });
    });
});

I’ve also individually imported the methods in the above example instead of importing * as to no avail.

I’ve got examples of this working in the very same project I’m working on and yet this one doesn’t.

Use of the package.json main property when publishing Typescript libraries to NPM

When publishing web components to NPM it’s convenient to use the main property of package.json to publish the bundled module like so.

"main": "build/index.bundle.js",
"module": "build/index.js",
"type": "module",
"types": "build/index.d.ts",

This also makes the bundled API available via the UNPKG CDN.

However I just want to make sure that applications that install the package don’t somehow reference code from the bundle, causing it to be included in the build, instead of from the types / objects / etc that the API exports via index.ts, which has the corresponding javascript version set in the module field.

So is it OK to set the fields like this with respect to using the package in downstream typescript builds?

JavaScript Class related query

In one of my JavaScript basic tasks i am to make a couple of classes and second class will be the first property of first class as an array, how can I manage it correctly?i.e what technique should i use to write this programm?

I can make a simple class but do no know how to add a class as an array to my first class kind of nested class.

Is it possible for someone to track my phone activity using a JavaScript file? [closed]

I found a file named “jquery-2.1.3.min.js” on my Android phone’s internal storage and I think someone I know put it there to track my phone’s browsing history and app browsing history. Is this possible? I’ve since deleted the file and don’t have the code it contained.

After deleting it, it hasn’t come back. It was in the Internal Storage folder on my phone.

How to Create a Horizontally Scrollable Element with Hover Overlay Effect in HTML/CSS?

I’m working on a webpage where I need to create an element with the following properties:

  • Horizontally Scrollable: The element contains multiple dance cards, each representing a dance. It should automatically scroll to the left or right when the mouse is near the left or right edges of the element.
  • Hover Effect: When the mouse hovers over a dance card, the card should increase in size and overlay other elements above it, without changing the layout or spacing of the other elements.

Here’s my current HTML structure:

<div class="horizontal-scroll-videos">
    {% for dance in dances %}
        <a href="/sample/{{ dance.id }}" class="dance-card">
            <div class="dance-card-image-description">
                <img src="{{ dance.image_url }}" class="dance-card-image" alt="{{ dance.name }}">
                <video class="dance-card-video" dance-video-path="{{ dance.video }}" muted></video>
                <p class="dance-card-description body-text">{{ dance.description }}</p>
            </div>
            <div class="dance-card-body">
                <h5 class="dance-card-title">{{ dance.name }}</h5>
                <div class="dance-card-tags">
                    <span class="badge bg-primary">{{ dance.difficulty }}</span>
                    <span class="badge bg-secondary">{{ dance.genre }}</span> 
                    {% if dance.has_instructions %}
                    <span class="badge bg-warning">Tutorial</span> <!-
                    {% endif %}
                </div>
            </div>
        </a>
    {% endfor %}
</div>

I have managed to implement each of these features individually; but problem is that I cannot find a way to have both behaviours functioning at the same time.

I’ve found out that the problem is around the definition of the horizontal-scroll-videos element, particularly about the overflow-x.

.horizontal-scroll-videos {
  display: flex;
  align-items: flex-start;
  gap: var(--inter-video-gap);
  align-self: stretch;
  overflow-x: auto;
  overflow-y: visible;
  scroll-behavior: smooth;
  white-space: nowrap;
  scrollbar-width: none;
}

When overflow-x: auto is enabled: The horizontal scrolling works perfectly. However, the hover effect is cut off, and the dance cards are not able to overlay other elements as desired.

Srolling working but hover not working

When overflow-x: visible is enabled: The hover effect works correctly, and the dance cards overlay other elements as desired. However, the horizontal scrolling functionality is lost.

Hover working but scrolling not working

I have tried to dynamically toggle overflow-x behavior based on user interaction, but the problem is that the scroll loses its position. When switching back to overflow-x: visible, the scroll position resets, and the new content displayed during the scroll is lost.

Code for the hover effect and the scrolling effect is:

function addHoverEffectDanceCards(){
    const danceCards = document.querySelectorAll(".dance-card");
    danceCards.forEach(danceCard => {
        // Get the video and image elements within the dance card
        const video = danceCard.querySelector(".dance-card-video");
        const image = danceCard.querySelector(".dance-card-image");

        // Get the children (the elements within) the dance card
        const children = danceCard.children;
        const childrenArray = Array.from(children);

        childrenArray.forEach(child => {
            // If any element in a dance card gets moused over, add the hover class to every element in the dance card
            child.addEventListener("mouseover", function() {
                const container = danceCard.closest(".horizontal-scroll-videos");
                const containerRect = container.getBoundingClientRect();
                const danceCardRect = danceCard.getBoundingClientRect();
                // Check if the dance card is fully visible within the container; don't show preview if it is not
                if (danceCardRect.left >= containerRect.left && 
                    danceCardRect.right <= containerRect.right) {
                    childrenArray.forEach(child => {
                        classes = child.classList;
                        classes.add("hover");

                        // Add the hover to the children within the dance-card-image-description div
                        if (classes.contains("dance-card-image-description")) {
                            const imgDesChildren = child.children;
                            const imgDesChildrenArray = Array.from(imgDesChildren);

                            imgDesChildrenArray.forEach(imgDesChild => {
                                imgDesChild.classList.add("hover");
                            });
                        };
                    });

                    // Add the hover class to the dance card itself
                    danceCard.classList.add("hover");

                    // Check if the video src for preview is loaded
                    if (!video.src) {
                        // Get the video if it is not defined
                        fetch('/generate_video_url', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({video_path: video.getAttribute('dance-video-path')})
                        })
                        .then(response => response.json())
                        .then(data => {
                            video.src = data.video_url; // Asign the video
                        })
                        .catch(error => console.error('Error fetching video presigned URL:', error));
                    } 
                    
                    // Start playing the preview
                    video.currentTime = 0;
                    video.play();
                    video.style.display = "block";
                    image.style.display = "none";
                }
            });

            // Remove the hover when no longer mousing over
            child.addEventListener("mouseout", function() {
                childrenArray.forEach(child => {
                    classes = child.classList;
                    classes.remove("hover");

                    // Remove the hover effect from the children inside the dance-card-image-description div
                    if (classes.contains("dance-card-image-description")) {
                        const imgDesChildren = child.children;
                        const imgDesChildrenArray = Array.from(imgDesChildren);
        
                        imgDesChildrenArray.forEach(imgDesChild => {
                            imgDesChild.classList.remove("hover");
                        });
                    };
                });

                // Remove the hover class from the dance card itself
                danceCard.classList.remove("hover");

                // Pause the video and show the image
                video.pause();
                video.style.display = "none";
                image.style.display = "block";
            });
        });
    });

const horizontalScrollContainers = document.querySelectorAll(".horizontal-scroll-videos");

horizontalScrollContainers.forEach(container => {
    let scrollInterval;

    container.addEventListener('mouseover', (e) => {
        const screenWidth = window.innerWidth;
        const scrollThreshold = 200;
        // Check if mouse is within the scrollThreshold from the right edge
        const checkLeftScroll = (e) => {
            const mouseX = e.clientX;
            return mouseX > screenWidth - scrollThreshold;
        };
        const checkRightScroll = (e) => {
            const mouseX = e.clientX;
            return mouseX < scrollThreshold;
        }
        if (checkLeftScroll(e)) {
            scrollInterval = setInterval(() => {container.scrollLeft += 180;}, 30);
        } else if (checkRightScroll(e)) {
            scrollInterval = setInterval(() => {container.scrollLeft -= 180;}, 30);
        }
    });

    container.addEventListener('mouseout', () => {
        clearInterval(scrollInterval);
        scrollInterval = null;
    });
});

I am a beginner in this field, and any help or suggestions on how to achieve this would be greatly appreciated!