Custom filename for BLOB URL

I am implementing this functionality in ReactJS, Application generated blob url but I want to replace it with my custom file name. I tried but unfortunately was not able to achieve my goal could someone please help me thanks.

  const blob = new Blob([res.data], { type: 'application/pdf' })
    const blobUrl = URL.createObjectURL(blob)
    var fileLink = document.createElement('a')
    fileLink.href = fileLink

    // it forces the name of the downloaded file
    fileLink.download = 'pdf_name.pdf'

    // triggers the click event
    fileLink.click()

I implemented this code but when it get downloaded it showing Failed - no file

Scroll two DIVs different height with a parallax-like effect

I’ve been scanning the web for a simple solution possibly without using a 3rd party library.

I have a Section with two DIVs that are placed side-by-side that have different heights. WhatI want to achieve is as I scroll down the web page, when I reach this Section the DIV on the left remains fixed until the right-hand-side DIV reaches the bottom and then the whole page continues scrolling down similar to some Parallax effects.

I like the Section’s height to be limited to 100vh and the solution should work on different devices except Cellphone.

I found ScrollMagic but it looks like you should know the heights before hand and in my case the DIV on the right has content that can change over time.

Any help is greatly appreciated.

Changing state on redux-saga causes infinite loop inside component

I am trying to redirect user after successful login but changing state in saga is causing an infinite loop.

In my component I am using useSelector to listen to changes in isValidSession from store. If isValidSession changes to true, I want to redirect user to another page. However, when isValidSession is changed, my component keeps re-rendering in an infinite loop.

component

import { Link, useLocation } from 'react-router-dom'
import { Redirect } from 'react-router'

import MainLayout from '../../../layouts/MainLayout'
import { Typography, Alert, Row, Col, Divider } from 'antd'
import LoginForm from './LoginForm'

import { useDispatch, useSelector } from 'react-redux'
import * as loginActions from './Login.action'

const { Title } = Typography

export default function Login() {

    const dispatch = useDispatch()

    const { isValidSession, error } = useSelector((state) => state.login)

    const location = useLocation()

    let { from } = location.state || { from: { pathname: '/templates' } }

    const handleLogin = ({ email, password }) =>
        {
            dispatch(loginActions.authenticate({ email, password }))
        }

    const getAPIError = (error) =>
        error.status == 401
            ? 'Invalid username or password'
            : 'Something went wrong'

    if (isValidSession) return <Redirect push to={from.pathname} />

    return (
        <MainLayout>
            <Row align='stretch' className='vh-100'>
                <Col xs={24} md={12} lg={10} xl={8} xxl={6} className='bg--white'>
                    <div className='d-flex align-items-center h-100 p-5'>
                        <div id='login' className='w-100'>
                        
                            <Title level={3}>Welcome Back!</Title>

                            {/* ERROR MESSAGE */}
                            {error ? (
                                <Alert
                                    message={getAPIError(error)}
                                    showIcon
                                    type='error'
                                    className='mb-2'
                                />
                            ) : (
                                ''
                            )}

                            {/* FORM */}
                            <LoginForm onFinish={handleLogin} />

                            <Divider />

                            {/* ADDITIONAL LINKS */}
                            <div className='text-center'>
                                <p>
                                    Don't have an account yet?{' '}
                                    <Link
                                        to={{ pathname: '/register', state: { from: location } }}
                                    >
                                        Sign up
                                    </Link>
                                </p>
                                <Link
                                    to={{
                                        pathname: '/auth/recover-password',
                                        state: { from: location },
                                    }}
                                >
                                    Forgot your password?
                                </Link>
                            </div>
                        </div>
                    </div>
                </Col>
            </Row>
        </MainLayout>
    )
}

In my reducer, for action types.LOGIN_SUCCESS, I am making isValidSession to true.

reducer

const loginReducer = (state = initialState, action) => {
    switch (action.type) {
        case types.LOGIN_REQUESTING: {
            return {
                ...state,
                submitted: false,
            }
        }
        case types.LOGIN_SUCCESS: {
            return {
                ...state,
                submitted: true,
                successful: true,
                isValidSession: true,
            }
        }
        case types.LOGIN_ERROR: {
            const { error } = action
            return {
                ...state,
                error,
                submitted: false,
                successful: false,
                isValidSession: false,
            }
        }
        case types.UPDATE_LOGIN_CREDENTIAL: {
            const { login } = action
            return {
                ...state,
                login: {
                    ...state.login,
                    ...login,
                },
            }
        }
        case types.IS_LOGGINGIN: {
            const { isLoggingIn } = action
            return {
                ...state,
                isLoggingIn,
            }
        }
        default:
            return {
                ...state,
            }
    }
}

In my saga code, you can see that I am doing yield put({ type: types.LOGIN_SUCCESS }) to change isValidSession to true. 

saga

function* authenticateSage(payload) {
    try {
        alert('authenticateSage')

        const response = yield call(authService.login, payload.login)
        const { profile, account } = response

        yield put({ type: types.LOGIN_SUCCESS })
    } catch (error) {
        yield put({
            type: types.LOGIN_ERROR,
            error: { status: error.status, message: error.data?.message },
        })
    }
}

export default function* watchAuthentication() {
    yield takeLatest(types.LOGIN_REQUESTING, authenticateSage)
}

Bootstrap 3.3.7 dropdown menu not working on mobile

We populating our dropdowns from a JSON file, but for some reason, it’s not working on mobile. Except for the li anchors, I’m following the guidelines from the Bootstrap 3.3.7 documentation: https://getbootstrap.com/docs/3.3/components/#dropdowns.

I also added this, but the issue persists on mobile devices:

$('.dropdown-backdrop').css({display: 'none'});

What could be causing this? Here’s my dropdown code.

<div class="dropdown w-100 open" id="attrib">
  <button data-device="Umbra 501" class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
    Economy
    <span class="glyphicon glyphicon-menu-down"></span>
  </button>
  <ul class="dropdown-menu dropdown-menu-right">
    <li><a data-filter-dropdown="Small">Small</a></li>
    <li><a data-filter-dropdown="Medium">Medium</a></li>
    <li><a data-filter-dropdown="Large">Large</a></li>
    <li><a data-filter-dropdown="Xlarge">Xlarge</a></li>
  </ul>
</div>

Using Javascript functions with a button in Handlebars

I have a handlebars project with the following structure:

Project
 |
 +-- server.js
 +-- package.json
 +-- package-lock.json
 |    
 +-- public
 |  |  
 |  |-- css
 |      |
 |      + -- style.css
 |
 +-- views
 |  |  
 |  |-- layouts
 |  |   |
 |  |   + -- main.handlebars
 |  +-- index.handlebars

In my server.js file, I created the app to run on localhost:3000, as well as serve the index.handlebars at /. I understand how to grab information from an api, so just to learn how to navigate displaying data from an API in a handlebars application, I created a GetInsult(); function to retrieve a random insult from an API I found online (purely for learning purposes). I grab the data with the function, and then pass the data to the res.render() function. You can see how this works in my server.js file:

//import modules
import dotenv from 'dotenv';
dotenv.config();

import http from 'http';
import path from 'path';
import { dirname } from 'path';
import express from 'express';
import { engine } from 'express-handlebars';
import axios from 'axios';


//other variables
const port = process.env.PORT;
const hostname = process.env.HOSTNAME;
const __dirname = path.resolve();

//store data in variable
var insult = await GetInsult();


const app = express();

//Create http server to run and listen on localhost:3000
var server = http.createServer(app).listen(port, hostname, () => {
    console.log(`Server is running at http://${hostname}:${port}`);
})

app.engine('handlebars', engine());
app.set('view engine', 'handlebars')
app.set('views', './views')

//Use Static Files
app.use('/public', express.static(__dirname + '/public'));
app.use('/css', express.static(path.join(__dirname, 'node_modules/bootstrap/dist/css')));
app.use('/js', express.static(path.join(__dirname, 'node_modules/bootstrap/dist/js')));
app.use('/js', express.static(path.join(__dirname, 'node_modules/jquery')));

app.get('/', (req, res) => {
    res.render('index' , {insult})
});



export async function GetInsult() {
    var response = await axios('https://insult.mattbas.org/api/insult')
    var data = response.data
    return data
}

console.log(insult)

Then in my index.handlebars file, I can successfully display the insult like so:

<main>
    <div style="text-align: center;">
        <h1 id="insult">{{insult}}</h1>
        <button id="insult-button" class="btn btn-dark">Get New Insult</button>
    </div>
</main>

I’m having trouble figuring out how to add the GetInsult(); functionality to the button I have underneath the <h1>{{insult}}</h1> tags. I’ve tried numerous ways and feel like I’m missing something simple. I would like the button to execute the GetInsult(); function and display the new insult that is retrieved from the API. I’m not sure if I need to house the function elsewhere and call it from another file, or if it’s even possible with an asynchronous function. Any guidance would be appreciated. Thank you!

Phaser 3 Tweens with changing variable value

I’m building an HTML5 game with Phaser 3. I have a counter tween that I add to the scene upon a certain if condition being met on click of a game object. (It is a text value that flashes red if the card’s maximum stat value is lower than the player’s value of that stat.)

First, I set the variable based on which card was clicked:

if (this == action1_card) {
                action = action1
                energy_cost = action1_energy_cost
                max_suspicion = action1_suspicion_threshold
                selected_card = action1_card_selected
} else if (this == action2_card) {
                action = action2
                energy_cost = action2_energy_cost
                max_suspicion = action2_suspicion_threshold
                selected_card = action2_card_selected
}

Once I have the values I want (max suspicion is the relevant variable in this case), I then apply the flashing color animation to it if the condition is met.

if (action.suspicion_threshold < game_data.player.stats.suspicion) {
    t.tweens.addCounter({
        from: 0,
        to: 100,
        duration: 250,
        repeat: 1,
        yoyo: true,
        ease: Phaser.Math.Easing.Sine.InOut,
        onUpdate: function(tween) {
            const value = Math.floor(tween.getValue());
            const colorObject = Phaser.Display.Color.Interpolate.ColorWithColor(
                                Phaser.Display.Color.ValueToColor('#000000'),
                                Phaser.Display.Color.ValueToColor('#FF0000'),
                                100,
                                value
                            )
            const color = Phaser.Display.Color.RGBToString(colorObject.r, colorObject.g, colorObject.b)
            max_suspicion.setColor(color);
    }
});

The issue is that, if I was to click on card 1 and then card 2 before the animation was finished on card 1, the animation from card 1’s text would resume on card 2. This makes sense, as the variable “max_suspicion” was reassigned to the text object on card 2, and the tween’s onUpdate function is continuing as it should.

How do I either:

1) prevent this from being reassigned (e.g. setting max_suspicion to permanently represent card 1’s text object for the scope of the tween)

or

2) reset card 1’s value to it’s original color and end the tween prematurely so it doesn’t carry over to card 2?

I will gladly clarify anything as needed. Thank you so much for any help on this!

p5js clipping mask equivalent?

I have a super simple script that creates a circle with alternating “slice” colors

let slices = 12;


function setup() {
  createCanvas(400, 400);
  noStroke();
}

function draw() {
  background(220);
  translate(width/2, height/2);
  
  let inc = TWO_PI/slices;
  let c = 0
  for (let i = 0; i < TWO_PI+inc; i+=inc) {
    if (c % 2 == 0) {
      fill('white')
    } else {
      fill('black')
    }
    arc(0, 0, width/2, width/2, i, i+inc);
    c++
  } 
}

How can I do this same thing but with a square? That is, I want the alternating slice colors but encapsulated in a square rather than a circle. I am not sure how to do this since I used arc() to create the slices. Is there some way I can create a mask or something? Or is there an easy solution to my problem?

I’m having trouble displaying an html button with javascript

I have two buttons on an HTML page, and I’m trying to show them once a button is pressed, but only one actually displays.

This is the HTML

<button onclick="testLeft()" class="item-description" id= "left-item-description">.</button>
<button onclick="testRight()" class="item-description" id= "right-image-description">.</button>

This is the CSS

.item-description {
    display: none;
    box-sizing: border-box;
    position: fixed;
    z-index: 4;
    font-size: 35px;
    font-weight: 600;
    height: auto;
    top: 30%;
    padding: 10px 10px;
    color:white;
    background-color: transparent;
    border-radius: 4px;
    border: 3px solid black;
    transition: all 0.2s ease;
}


#left-item-description {
    margin-left: 10%;
    margin-right: 60%;
}

#right-image-description {
    margin-right: 10%;
    margin-left: 60%;
}

And this is the javascript

function newGame(){
    score = -1;
    increaseScore();
    correct = true;

    for (let i = 0; i < used.length; i++){
        used[i] = false;
    }

    indexLeft = shuffleIndex();
    indexRight = shuffleIndex();
    var left = document.getElementById("left-item-description");
    var righ = document.getElementById("right-item-description");
    
    left.style.display = "block";
    left.innerText = items[indexLeft];
    document.getElementById("left-item-image").src=images[indexLeft];
    
    righ.style.display = "block";
    righ.innerText = items[indexRight];
    document.getElementById("right-item-image").src=images[indexRight];

}

The left button works perfectly how I want it to, but for some reason, the right button doesn’t display

How can javascript extract specified key value from json blob with many nested values?

I have an https query which returns a json blob in the following format:

{
"metric_data": {
    "from": "2021-12-09T01:25:32+00:00",
    "to": "2021-12-09T01:55:32+00:00",
    "metrics_not_found": [],
    "metrics_found": [
        "Mobile/Crash/All"
    ],
    "metrics": [
        {
            "name": "Mobile/Crash/All",
            "timeslices": [
                {
                    "from": "2021-12-09T01:24:00+00:00",
                    "to": "2021-12-09T01:54:00+00:00",
                    "values": {
                        "call_count": 5
                    }
                }
            ]
        }
    ]
}

}

I want to find and extract the value for call_count. What is the best way to do that with Javascript? The following code will actually print out all the json values, including the call_count but all my efforts to just grab the value for call_count are failing.

var json = `{
"metric_data": {
    "from": "2021-12-09T01:25:32+00:00",
    "to": "2021-12-09T01:55:32+00:00",
    "metrics_not_found": [],
    "metrics_found": [
        "Mobile/Crash/All"
    ],
    "metrics": [
        {
            "name": "Mobile/Crash/All",
            "timeslices": [
                {
                    "from": "2021-12-09T01:24:00+00:00",
                    "to": "2021-12-09T01:54:00+00:00",
                    "values": {
                        "call_count": 5
                    }
                }
            ]
        }
    ]
}
}`;
    
    // Convert a JSON object to a Javascript object
var obj = JSON.parse(json);

// This function prints nested values
function printValues(obj) {
    for(var k in obj) {
        if(obj[k] instanceof Object) {
            printValues(obj[k]);
        } else {
            document.write(obj[k] + "<br>");
        };
    }
};

// Printing all the values from the resulting object
printValues(obj);

document.write("<hr>");
    
    // This is where I fail as I try to print a single value.
    document.write(obj["metrics"]["call_count"] + "<br>");

Any feedback would be much appreciated!

How to make mock api axios call in test?

Hello I am new to testing and I am following this client’s testing protocol where they make an axios.post request to a localhost end point (they start up a separate express server during test script)

describe("Arrived For Delivery", () => {
it("POST /courier/arrivedForDelivery should return success", async () => {
    const res = await axios.post(
        `http://localhost:8888/courier/arrivedForDelivery`,
        { order_id: "MOCK" },
        {
            params: {
                authentication: mockAuth,
            },
        }
    );
    // Assertion
    expect(res.data).to.be.equal("success");
});

it("POST /courier/arrivedForDelivery should return error data", async () => {
    // Arrange
    const stubProviderStorage = stub(ProviderStorage, "GetProviderByID");
    stubProviderStorage.throws({ message: "test" });

    try {
        // Act
        await axios.post(
            `http://localhost:8888/courier/arrivedForDelivery`,
            { order_id: "MOCK" },
            {
                params: {
                    authentication: mockAuth,
                },
            }
        );

        // Assert
        expect.fail();
    } catch (error) {
        expect((error as AxiosError).response?.data).to.be.eqls({
            code: 400,
            message: "arrivedForDelivery Error test",
        });
    }
    stubProviderStorage.restore();
});

});

is it possible to use sinon to make a mock api call and define what the response should be? because my senior dev from another company is telling me that i shouldnt be making real axios requests in an unit test nor i should make requests outside the code base.
any suggestions?

Object with nested array to filter, want to return entire object with new filtered array

I’m attempting to remove an object out of an array nested within my movie object and then copy it to a new variable. So my original object looks like this:

{
    "id": 1,
    "title": "Avatar",
    "movieLength": 162,
    "releaseDate": "2009-12-18",
    "trailerUrl": "https://www.youtube.com/watch?v=5PSNL1qE6VY",
    "genre": {
        "id": 1,
        "genre": "Action"
    },
    "rating": {
        "id": 3,
        "rating": "PG-13"
    },
    "director": {
        "id": 1,
        "lastName": "Cameron",
        "firstName": "James"
    },
    "actors": [
        {
            "id": 2,
            "lastName": "Worthington",
            "firstName": "Sam"
        },
        {
            "id": 3,
            "lastName": "Weaver",
            "firstName": "Sigourney"
        },
        {
            "id": 4,
            "lastName": "Saldana",
            "firstName": "Zoe"
        }
    ],
    "comments": []
}

and what I’m doing right now is

const updatedMovie = const updatedMovie = movie.actors.filter((actor) => actor.id !== id);

but as you know that only returns the array of actors I filtered. I want to copy the entire object with the newly filtered actors so the object will come out like this (removing actor id 3):

{
    "id": 1,
    "title": "Avatar",
    "movieLength": 162,
    "releaseDate": "2009-12-18",
    "trailerUrl": "https://www.youtube.com/watch?v=5PSNL1qE6VY",
    "genre": {
        "id": 1,
        "genre": "Action"
    },
    "rating": {
        "id": 3,
        "rating": "PG-13"
    },
    "director": {
        "id": 1,
        "lastName": "Cameron",
        "firstName": "James"
    },
    "actors": [
        {
            "id": 2,
            "lastName": "Worthington",
            "firstName": "Sam"
        },
        {
            "id": 4,
            "lastName": "Saldana",
            "firstName": "Zoe"
        }
    ],
    "comments": []
}

I’ve tried reading around but I’m not having any luck getting any solutions to work with me, so if anyone can help or point me in the right direction that would be great!

How can I make a regular expresion that verify if a opening parenthesis has its closing parenthesis?

I’ve got a question. I have this regular expresion:

const r = /((B[(])*(w)+(b[)])*(s)*)+/g;

But lets suppose that we have the string :

ball (doll) (bicycle

So we wanna verify if every opening parenthesis has its closing parenthesis, then I wanna that this string returns me a false value, because the substring “(bicycle” hasn’t its closing parenthesis.

What can I do to create a pattern with regexp that verifies this? THANKS!! 😀

element onclick in class never called

I have a simple class.

The problem im having is that my onClick function is never called when clicking on the div element.

class card {
  constructor(parent, element) {
    this.parent = parent;
    this.element = element;

    this.element.on({
      'click': $.proxy(this.onClick, this)
    });
  }

  onClick() {
    console.log("onclick");
  }

}

class cards {
  constructor() {
    this.element = $(".cards");
    this.cards = [];

    this.element.children(".card").each((obj) => {
      this.cards.push(new card(this, $(obj)));
    });

  }
}

var my_a = new cards();

how to convert Array object to table javascript?

I have the following array of objects, and I need to display it in a table as shown in the screenshot:

This is the object:

[
    {
        "dayText": "Viernes",
        "monthText": "Diciembre",
        "date": "2021-12-10T15:26:55.273Z",
        "start": "08:00",
        "end": "08:30",
        "scheduled": true
    },
    {
        "dayText": "Viernes",
        "monthText": "Diciembre",
        "date": "2021-12-10T15:26:55.273Z",
        "start": "09:00",
        "end": "09:30",
        "scheduled": false
    },
    {
        "dayText": "Sábado",
        "monthText": "Diciembre",
        "date": "2021-12-11T15:26:55.273Z",
        "start": "08:00",
        "end": "08:15",
        "scheduled": false
    },
    {
        "dayText": "Sábado",
        "monthText": "Diciembre",
        "date": "2021-12-11T15:26:55.273Z",
        "start": "08:15",
        "end": "08:30",
        "scheduled": false
    },
    {
        "dayText": "Sábado",
        "monthText": "Diciembre",
        "date": "2021-12-11T15:26:55.273Z",
        "start": "08:30",
        "end": "08:45",
        "scheduled": false
    },

    {
        "dayText": "Domingo",
        "monthText": "Diciembre",
        "date": "2021-12-12T15:26:55.273Z",
        "start": "08:00",
        "end": "08:30",
        "scheduled": false
    },
    {
        "dayText": "Domingo",
        "monthText": "Diciembre",
        "date": "2021-12-12T15:26:55.273Z",
        "start": "09:00",
        "end": "09:30",
        "scheduled": true
    },
    {
        "dayText": "Domingo",
        "monthText": "Diciembre",
        "date": "2021-12-12T15:26:55.273Z",
        "start": "10:30",
        "end": "11:00",
        "scheduled": true
    },
    {
        "dayText": "Domingo",
        "monthText": "Diciembre",
        "date": "2021-12-12T15:26:55.273Z",
        "start": "11:00",
        "end": "11:30",
        "scheduled": false
    },
    {
        "dayText": "Domingo",
        "monthText": "Diciembre",
        "date": "2021-12-12T15:26:55.273Z",
        "start": "11:30",
        "end": "12:00",
        "scheduled": false
    },

    {
        "dayText": "Lunes",
        "monthText": "Diciembre",
        "date": "2021-12-13T15:26:55.273Z",
        "start": "10:30",
        "end": "11:00",
        "scheduled": false
    },
    {
        "dayText": "Lunes",
        "monthText": "Diciembre",
        "date": "2021-12-13T15:26:55.273Z",
        "start": "11:00",
        "end": "11:30",
        "scheduled": false
    },
    {
        "dayText": "Lunes",
        "monthText": "Diciembre",
        "date": "2021-12-13T15:26:55.273Z",
        "start": "11:30",
        "end": "12:00",
        "scheduled": false
    }
]

This is how it should look like:
enter image description here