Scroll prompt to appear only once on a page and max 3 times across the site

I have a scroll prompt that I show after 2s of page load for 5s using CSS+jQuery on every page:

$(document).ready(function(){
    $('.icon-scroll').delay(2000).fadeIn('slow', function(){    
      $('.icon-scroll').delay(5000).fadeOut('slow');
    });
});
body {margin:0;}
div {height:100vh;}

.icon-scroll {display: none; position: absolute; top: calc(50%); right: 30px; width: 30px; height: 45px; margin-left: -20px; bottom: 7%; margin-top: -35px; box-shadow: inset 0 0 0 3px; border-radius: 25px; z-index: 2;}

.icon-scroll:before {position: absolute; left: 50%; content: ''; width: 8px; height: 8px; background-color: inherit; box-shadow: inset 0 0 0 5px; margin-left: -4px; top: 7px; border-radius: 4px; -webkit-animation-duration: .800s; animation-duration: .800s; -webkit-animation-iteration-count: infinite; animation-iteration-count: infinite; -webkit-animation-name: scroll; animation-name: scroll;} @-webkit-keyframes scroll {0% {opacity: 1;} 100% {opacity: 0; transform: translateY(25px);}} @keyframes scroll {0% {opacity: 1;} 100% {opacity: 0; transform: translateY(25px);}}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>

  <span class="icon-scroll"></span>
  
</div>

The basic purpose of this is to make people scroll a page where a fullscreen image/design is used. But, I do not want this prompt to reappear on a page every time it is refreshed (page refreshes on resize) or revisit – basically once on a page, and max 3 times across the site in a visit for every user.

I think this can’t be done through CSS so any help in this regard is much appreciated.

Failed to get access token from Instagram in jQuery

Here is postman request and response

I’m trying to get code first from this url:

https://api.instagram.com/oauth/authorize?client_id=”My ClientID”&redirect_uri=’my redirctUri’/&scope=user_profile,user_media&response_type=code&grant_type=authorization_code

Then I got code like that : https://myredirctCode?code=MyCode#_

Copy that code and paste on postman collection and getting error

also I’m following How do I recive instagram log in token using ajax answer to change response type to token

And I’m getting this : this is response

I’m using Instagram page for displaying.

if any one have idea please let me know

Thanks in advance!

Jquery find changed attribute value after changing it with jquery

I do not know if what I am doing is the right aproach to do it. But what I am trying to do is the folowing.

I have a menu that a user can open and close buy clicking on the menuhead button. What I want is to save the status open or closed into my database so that when the user refreshes the page or when he logs in again the menu status is open or close as they intended.

The html button below has a attribute data-menustatus="<?php echo $showam; ?>" which stores the status value of the menu item from the database. 1 for open and 0 for closed.

<button class="btn-toggle hass-menuhead align-items-center collapsed MenuStatus" type="button" data-menuitem="accounts" data-menustatus="<?php echo $showam; ?>" data-bs-toggle="collapse" data-bs-target="#Accounts-collapse" data-bs-display="static" aria-expanded="true">
          Accounts Menu
        </button></div>

When the user clicks on the button I get that value and write it to the database and make it check for 1 or 0 and depending on the outcome I store 1 or 0. I use Jquery to change the data-menustatus="<?php echo $showam; ?>" to 1 or 0 depending on the original number. When I inspect the console I see it change to 1 when the original data is 0, as intended.

Now the problem. When I click on that same button again it now should read 1 as that is the value that jquery changed and is showing in the console. But instead Jquery is still finding the original 0 instead of the new 1 value.

I am not a expert in jqeury and I tried this in below script. What am I doing wrong? I this not posible? All help is welcome !

$(document).on("click", ".MenuStatus", function () {
var MenuStatus = $(this).data("menustatus");
var MenuItem = $(this).data("menuitem");

if(MenuStatus==1){
$(this).attr('data-menustatus','0');
}else{$(this).attr('data-menustatus','1');}
console.log(MenuStatus);
$.ajax({
type: "POST",
url: "../menu/SetMenuFilters.php",
data: {MenuStatus: MenuStatus,MenuItem: MenuItem},
success: function(data) {
},

error: function(xhr, status, error) {
 if(xhr.status&&xhr.status==401){
p.error('Session is broken, login again.'); 
setTimeout(window.location.reload.bind(window.location), 4000);
}else{
alert("Something went wrong, try again later."); 
       } }
});
});

Populate selectbox after div show with columns from a pandas dataframe

So, I have a html form which, after submit, populates some selectboxes with rows values form a pandas dataframe.
I have added a jquery script in order to hide the selectboxes before submit and show after submit , but the selectboxes are not being populated anymore as before. For sure something is missing but unfortunately I am pretty new to js and jquery.

This is my script:

$(document).ready(function(){
    $("#myform").submit(function(e) {
            
            e.preventDefault();
            $("#second").show();
                  
    });

This is my html:

<form method = "POST" action ="dashboard" id="myform">
            {% csrf_token %}
            <select name="line"> 
                <option value=" 1" selected="selected"> 1</option>
                <option value=" 2">2</option>
                <option value=" 3">3</option>
                <option value="All">ALL</option>

                
            </select> Line
            <select name="data"> 
                <option value="weekly" selected="selected">weekly</option>
                <option value="monthly">monthly</option>
                
                
            </select> Data
            <input type="submit" value="Select">
            </form>
                
    </div>
    <div id = "second" style="display:none">
   

        <br><br><br>
        <select class="position">
            
            {% for pos in posnr %}
            <option value="{{ pos }}">{{ pos }}</option>
            {% endfor %}
        </select>
            <select class="x">
            
                {% for pos in posnr %}
                <option value="{{ pos }}">{{ pos }}</option>
                {% endfor %}
            </select>
            <select class="y">
            
                {% for pos in posnr %}
                <option value="{{ pos }}">{{ pos }}</option>
                {% endfor %}
            </select>
        
        </div> 

This is part of a django project , the view part is working well

stripe webhhok with firebase showing error

it is showing Unexpected value for STRIPE_SIGNING_SECRET error even after checking it many times in the env file

the terminal shows everything created but it does not reach firebase database I am thinking there is a error in the code

the stripe dashboard also says connected

I am using the forward to local host line in git terminal

webhook code

import { buffer } from "micro";
import * as admin from 'firebase-admin'

//secure a connection to Firebase from backend
const serviceAccount = require('../../../permissions.json');
const app = !admin.apps.length ? admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
}) 
  : admin.app();

// establish connection to stripe
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

const endpointSecret = process.env.STRIPE_SIGNNING_SECRET;
if (typeof endpointSecret !== "string") {
    console.error("Unexpected value for STRIPE_SIGNING_SECRET");
    // potentially throw an error here
  }

const fulfillOrder = async (session) => {
    console.log('Fulfilling order', session)

    return app
    .firestore()
    .collection("user")
    .doc(session.metadata.email)
    .collection("orders")
    .doc(session.id)
    .set({
        amount: session.amount_total / 100,
        amount_shipping: session.amount_total_details.amount_shipping / 100,
        images: JSON.parse(session.metadata.images),
        timestamp: admin.firestore.FieldValue.serverTimestamp(),
    })
    .then(() => {
        console.log(`success: order ${session.id} had been added to db`);
    });
};

export default async (req, res) =>{
    if(req.method === 'post'){
        const requestBuffer = await buffer(req);
        const payload = requestBuffer.toString();
        const sig = req.headers["stripe-signatur"];

        let event;

        // verify that the event posted came from stripe 
        try{
            event = stripe.webhooks.constructEvent(
                 payload,
                 sig,
                 endpointSecret);
        } catch (err) {
            console.log('ERROR', err.message)
            return res.status(400).send(`Webhook error: ${err.message}`)
        }

        //handle the checkout event 
        if (event.type === 'checkout.session.completed') {
            const session = event .data.object;

            //fulfill the order...
            return fulfillOrder(session)
            .then(() => res.status(200))
            .catch((err) => res.status(400).send(`Webhook error: ${err.message}`));
        }
    }
};

export const config = {
    api: {
        bodyParser: false,
        externalResolver: true,
    },
};

firebase rules

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow write: if false;
      allow read: if true;
    }
  }
}

file folder

Axios get call in useEffect is not passing info on second time an option is selected

I am writing a axios get call useEffect that is called whenever a user selects an option from a dropdown menu. It works on getting info on the first time I select each option, but whenever I go back to a previously selected option, it is only cancelling the source and not getting the info again. am I doing this right?

useEffect(() =>{
        const CancelToken = axios.CancelToken;
        const source = CancelToken.source();
        getGames(source);

        return () =>{
            source.cancel();
        };
    }, [selectedOpt]);
const getGames = (source) => {
        const opt = getOpt();


        axios.get(`${URL}${opt}`, {
            cancelToken: source.token
        })
        .then(function (response){
            setSelectedResults(response.data.data);
        })
        .catch((err) =>{
            if(axios.isCancel(err)){
                console.log('successfully aborted');
            }
            else{
                alert(error.message)
                console.log('getGameTest', error);
            }
        });
       
    };

Once i get the info, I pass it to a child component to display it, which is where the data is ‘undefined’ the second time.

Array not mapping in NextJS

I am trying to build a blog application by following the tutorial of JSMastery using NextJS and GraphCMS. I am trying to make it using TS whereas he is using JS. I have been pulling my hair over a bug for the last 10 hours. In the video, he queries an array of recent posts and renders them in a component. Only when I do it the array is not being displayed. this issue is persisting for the next categories component also.

I tried to hardcode the response and map the array but I am getting the same issue.
I don’t know what I am doing wrong and any help will be appreciated. Please check out my repo and try debugging the Categories.TSX which has the hardcoded values.

Cytoscape.js : fixedNodeConstraint when collapsing or expanding compound nodes

I’m looking for a way to apply constraints for fixed nodes when collapsing or expanding compound nodes with Fcose layout (last version of cytoscape on May 2022).
I applied it the following:

api.expand(cy.$id(selection), options)

with

option ={
name:'fcose',
quality:"default",
animate:true,
animationDuration:1000,
animationEasing;'ease-out',
fit:'true',
step:"all",
fixedNodeConstraint:[{"nodeId":"id1, "position":{"x":10, "y":50}},... ]
}

The constraint on fixed node seems then not to apply, but it could not be the appropriate way for such constraints applying.

Any experience and ideas on the way to proceed?

Get possible paths from right top to bottom of a 2d array

Can someone help me solve this problem?
A javascript array represents a traversable path and obstacles

The route given is always sucess and does not contain an intersection.
A motorcycle will always start from point 0 and must always reach the point of the last line and last column of the table and we cant go left
A letter corresponds to each movement:
R for: right,
L for left,
T for top:
B for Bottom.
Write down the path the car must travel to reach its goal.

I tried with this code but something is wrong

var traverse = [
    ['_','_','X','_','_','_'],
    ['X','_','X','_','X','_'],
    ['X','_','_','_','X','_'],
    ['X','X','X','X','X','_'],
];
// Prints "0: a, 1: b, 2: c"
var current, next, last, itinerary, column ;
traverse.forEach(function callback(value, index) {
 // console.log(`${index}: ${value}`);
   console.log(value);
       current = value[index];
       next = value[index];
      if (index > 0) {
         last = current[index - 1];
    }
    addDirection(current, column, 'D', itinerary);
    addDirection(next, column, 'B', itinerary);
    addDirection(last, column, 'H', itinerary);
    column++;
  
});

function addDirection(line, column, direction, itinerary)
{
    line.forEach(function callback(value, index) {
        if(index == column){
            if (line[column] == '_') {
                itinerary.push(direction);
            }
        }
  });
}
console.log(itinerary);

In this exemple the itinerary must contain R/B/B/R/R/T/T/R/R/B/B/B

JS FireFox WebExtensions tabs.query(queryObj): can queryObj have an “or”?

https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/query

var urls = ["url_pattern_1", "url_pattern_2"];
var titles = "title_pattern_1", "title_pattern_2"];
for (let url of urls) {
  for (let title of titles) {
    browser.tabs.query({"title": title, "url": url}).then((matched_tabs) => {
      // code to run on matched_tab
      }
    });
  }
}

If the urls and/or titles lists are long, this will cause browser.tabs.query() to be called many times. I’m curious (but not optimistic) if it’s possible to have the query logical-OR all of the elements from the arrays so that I can get rid of the for loops.

Thanks!

Javascript Mocking functions that return Readable

I have a simple function that calls my s3 service which will return a Promise

  downloadFile(fileName: string): Promise<Readable> {
    console.log(
      "Downloading an object with key - ",
      fileName
    );

    return this.s3service.getObject(fileName);
  }

I would like to mock the return of the object and assert it in the test like this:

it("should return readable if file present", async () => {
  const readable = new Readable();
  readable.push("test");

  jest
    .spyOn(s3service, "getObject")
    .mockImplementation(() => Promise.resolve(readable));

  const file = await someService.downloadFile(
    TestConstants.reportName
  );

  expect(file).toBe(readable);
});

When i run the test, I face this error:

Error [ERR_METHOD_NOT_IMPLEMENTED]: The _read() method is not
implemented
at Readable.read (internal/streams/readable.js:642:9)
at Readable.read (internal/streams/readable.js:481:10)
at maybeReadMore
(internal/streams/readable.js:629:12)
at processTicksAndRejections (internal/process/task_queues.js:82:21) { code:
‘ERR_METHOD_NOT_IMPLEMENTED’

Would like some help on how I can properly mock a readable for example in this example

How can I manipulate nested object in es6

I have option with 3 stages nested options how can I manipulate them depends on option that a user clicked on the UI

CODES

[{
    future: false,
    NumberOfDay: 0,
    HourOption: ""
  },
 {
    within_date: false,
    start_date: "",
    end_date: ""
  },
 {
    indefinitely: false
}]

Expected output

in case user select option one future and numberOfDay would be changed and output might look like the following on index one of this array

[{
    future: true,
    NumberOfDay: Entered_Number_From_User,
    HourOption: ""
  },
 {
    within_date: false,
    start_date: "",
    end_date: ""
  },
 {
    indefinitely: false
}]