React/Jest: Testing React Context methods (Result: TypeError: setScore is not a function)

I’m using React Context API to create a game.

In one of my components (GameStatus) I pull in some methods from the provider:

const context = React.useContext(MyContext);
const { setGameStart, setGameEnd, setScore } = context;

And in the component I invoke these three methods onClick of the start game button, which in turn sets the state back in the provider.

GameStatus Component

import React from 'react';
import { MyContext } from './Provider';

const GameStatus = ({ gameStart, gameEnd, score, total, getPlayers }: { gameStart: boolean, gameEnd: boolean, getPlayers: () => void, score: number, total: number }) => {
    const context = React.useContext(MyContext);
    const { setGameStart, setGameEnd, setScore } = context;
    return (
        <>
            {!gameStart && (
                <button onClick={() => {
                    getPlayers();
                    setScore(0);
                    setGameStart(true);
                    setGameEnd(false);
                }}>
                    Start game
                </button>
            )}
            {gameEnd && (
                <p>Game end - You scored {score} out {total}</p>
            )}
        </>
    )
}

export default GameStatus;

Then in my test file below I want to test that when the start game button is clicked the game is started (check the DOM has removed the button and is now showing the game).

But I’m not sure how to pull in the methods in to the test file as I get:

Result: TypeError: setScore is not a function

I tried just copying:

const context = React.useContext(MyContext);
const { setGameStart, setGameEnd, setScore } = context;

But then I get an invalid hook call as I can’t use React hooks inside the test.

Any ideas? Or a better approach to testing this? Thanks

GameStatus Test

import React from 'react';
import { shallow } from 'enzyme';
import { MyContext } from '../components/Provider';
import GameStatus from '../components/GameStatus';

test('should start the game', () => {
    const getPlayers = jest.fn();

    const uut = shallow(
        <MyContext.Provider>
            <GameStatus
                getPlayers={getPlayers}
            />
        </MyContext.Provider>
    ).dive().find('button');

    uut.simulate('click');

    console.log(uut.debug());
});

Next Js + Amplify @sls-next/-component error on deployment

I’ve deployed my app on amplify, the backend deployment is all good to go.

I’ve connected the frontend to my gitlab repo, and after debugging it is finally compiled successfully. Immediately after the compiling, I get this error.

Starting SSR Build...
[ERROR]: Error: Command failed: npm install @sls-next/[email protected] --prefix /root/./

I have tried to override the env with the following commands (I’ve tried previous versions of both next and node, however it doesnt pass the compiling phase unless I use the following)

Amplify CLI - latest
Next.js version - latest
Node.js version - 17

This is my amplify.yml

version: 1
frontend:
  phases:
    preBuild:
      commands:
        - npm ci
    build:
      commands:
        - npm run build
  artifacts:
    baseDirectory: .next
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*

My node_module versions on the project are

 "next": "^12.1.7-canary.16",
 "react": "^18.0.0",
 "react-dom": "^18.0.0",
 "aws-amplify": "^4.3.23"

my node version is 17.0.9 and my local amplify cli is 8.2.0

I should note my build passes locally

What am I missing? I dont have serverless installed anywhere on my project, it appears to be something amplify is trying to install. Perhaps I should be exporting after the build? But this is an ssr app, not static. I have a feeling this is a problem with conflicting versions.

,

AG-Grid Side Bar click functionality

So I have a side bar built using ag-grid and was wondering if it was possible to click on a side bar option without having the tool panel open and have a pop up component instead?

const gridOptions = {
    sideBar: {
        toolPanels: [
            {
                id: 'columns',
                labelDefault: 'Columns',
                labelKey: 'columns',
                iconKey: 'columns',
                toolPanel: 'agColumnsToolPanel',
                minWidth: 225,
                maxWidth: 225,
                width: 225
            },
            {
                id: 'filters',
                labelDefault: 'Filters',
                labelKey: 'filters',
                iconKey: 'filter',
                toolPanel: 'agFiltersToolPanel',
                minWidth: 180,
                maxWidth: 400,
                width: 250
            },
            {
                id: 'myComponent',
                labelDefault: 'MyComponent',
                labelKey: 'myComponent',
                iconKey: 'myComponent',
                toolPanel: () => {<MyComponent/>},
                minWidth: 180,
                maxWidth: 400,
                width: 250
            }
        ]
    },
}

For example, in the above code, I pass a component (e.g. <MyComponent/>) in place of the tool panel, but it doesn’t actually open that component when I click on it since it renders on the sideBar loading up.

Can I pass some onClick function into that particular sideBar option to allow me to click on it and open the component?

Send upload file and a few parameters from javascript AJAX to MVC method

struggling my head trying to pass a file and parameters from javascript using AJAX to mvc method.
I already successfully send and catch the file, but I dont know have to send and receive the strings parameters.

Javascript:

$('#importButton').on("change", function () {
            var fileUpload = $("#importButton").get(0);
            var files = fileUpload.files;
            
            var systemName = "param1";
            var clientName = "param2";
            
            // Create FormData object  
            var fileData = new FormData();

            // Looping over all files and add it to FormData object  
            for (var i = 0; i < files.length; i++) {
                fileData.append(files[i].name, files[i]);
            }
            
            $.ajax({
            url: ImportClick,
            type: 'POST',
            //here is the thing, how send the parameters and the file
            data: fileData,
            cache: false,
            processData: false,
            contentType: false,
            success: function (response) {
                alert(response);
            },
            error: function (err) {
                alert(err.statusText);
            }
        });

MVC:

[HttpPost]
    public ActionResult ImportClick()
    {
        
        //how take the two parameters??
        
        //Here take the file
        HttpFileCollectionBase files = Request.Files;
        
        byte[] fileData = null;
        
        using (var binaryReader = new BinaryReader(files[0].InputStream))
        {
            fileData = binaryReader.ReadBytes(files[0].ContentLength);
        }
        
        service.ImportAllClientConfigurationData(param1, param2, fileData);
        
    }

Add style according to the value of x-text/html value

I want to center my td element when the text is equals to “-“. If the text is equals to something else, I want it align at the left.

How can I do that?

<td x-bind:style="$el.textContent == '-' ? { 'text-align': 'left' } : { 'text-align': 'center' }" x-text="format(variable)"></td>

Yes, I could simple replace the $el.textContent by format(variable), but I would like to not call format(variable) twice.

Google Apps Script: TypeError: Cannot read property ‘values’ of undefined (line 3, file “Code”)

First, shoutout to NEWAZA for writing this amazing code!

Secondly, please refer to the StackOverflow link/question.

Google Apps Script to automatically duplicate a row the number of times a comma appears in a column keeping basic info?

Finally, I am getting an error in the code. Also, if I wanted to add new columns or questions to the Google form would that be as simple as just add the header’s text with the other constants in the script?

Adding a Loader in React while a three.js model is rendering

I am trying to add my loader component onto the page while my three.js GLTF model is either being downloaded or is trying to render onto the page.

In some cases this can take anywehre between 0.5s to 30s depending on what device you are on.

So I am wondering if there is a way to get the value of wether the 3D model is loaded or not. Or any other solution to this.

Capturing stdout/stderr of Node-API module running in Electron

I’m developing a Node-API module together with an Electron application. The N-API module is running in the render process of Electron, since it has a pretty complex API, that would be hard to get through a context bridge, and I’m only planning on running local resources anyway. However, none of the printing to stdout done by the N-API module is visible anywhere.

I’ve tried listening to the process.stdout, which fails because “The _read() method is not implemented”:

process.stdout.on("data", (data) => console.log(data));

Piping also doesn’t work, because “Cannot pipe, not readable”:

const duplexStream = new Stream.Duplex();
duplexStream.on("data", (data) => console.log(data));
process.stdout.pipe(duplexStream);

I even tried overriding the stdout.write() method, which actually worked for calls from within JavaScript, but still didn’t show anything from the native module:

process.stdout.write = (data) => {
    console.log(data);
    return true;
};

So is there any way to view the stdout/stderr of a Node-API module from within the script?

Adding event listners to a string and then converting it to an html/react element

I have a function that splits and checks for a word that matches the regex.. and if word found it add it in a span tag and style it then parse it using react parser..

const checkContent = (content) => {
    content = content.split(' ')
    let tag = '<p>'
    content.map(word => {
      if(word.match(regex))
        tag += ` <span className="taggedUser">${word}</span> `
      else
        tag += ' ' + word
    })
    tag += '</p>'
    return ( parse(`<div>${tag}</div>`))
  }

However i’m having difficulty trying to add an event listner to it like OnClick().
The only solution I’ve come up with is adding the listners by js via addEventListner().
My question is there any other way other than the above mentioned. Adding the listner directly to the span tag like this ${word} and then returning it?? Any Idea??

Im trying to visualize Audiofiles with the WebaudioAPI but getByteFrequencyData always is always 0

function playSound(){
let noise = context.createBufferSource()
noise.buffer = generateWhiteNoise()

const analyzer = context.createAnalyser()
analyzer.fftSize = 2048

let test = new Uint8Array(analyzer.frequencyBinCount)

noise.connect(analyzer)

analyzer.getByteFrequencyData(test)
console.log(test)

}

Currently im just trying to get the Analyzer node to work properly by testing it out with some whitenoise. The problem is that the test array is always 0 for every index. I cant figure out why.

function generateWhiteNoise() {
let bufferSize = context.sampleRate;
let buffer = context.createBuffer(1, bufferSize, context.sampleRate);
let output = buffer.getChannelData(0);

for (let i = 0; i < bufferSize; i++) {
    output[i] = Math.random() * 2 - 1;
}

return buffer;

}

Here is my generateWhiteNoise() Function.

Javascript – Google auth post request fails

I’m working an application where Google login (Oauth) callback fails. When I start the app, it redirects me to the Google Oauth’s login page. Below is the code:

passport.use(new GoogleStrategy({
  clientID: GOOGLE_CLIENT_ID,
  clientSecret: GOOGLE_CLIENT_SECRET,
  callbackURL: "http://localhost:8080/auth/google/callback"
},
function(accessToken, refreshToken, profile, done) {
    userProfile=profile;
    return done(null, userProfile);
}
));

app.get('/auth/google', 
  passport.authenticate('google', { scope : ['profile', 'email'] }));
 
app.get('/auth/google/callback', 
  
  // passport.authenticate('google', { failureRedirect: '/error' }),
  passport.authenticate('google'),
  function(req, res) {
    // Successful authentication, redirect success.
    var request = require("request");

    var options = {
      method: "POST",
      url: "http://localhost:8082/web/google-callback",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(userProfile),
    };
    request(options, function (error, response) {
      if (error) {
        console.log(error);
        return;
      }
      if (response.body != undefined){
        res.redirect('/select?t=' + JSON.parse(response.body)['token']);
      }
      else{
        res.redirect('/404');
      }    
    });    
});

After providing credential, callback fails and the response.body contains the following:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /web/google-callback</pre>
</body>
</html>

As stated in the response body there is an error in body. The response.redirect implementation is:

res.redirect('/select?t=' + JSON.parse(response.body)['token']);

An leads in this direction will be of great help.
Thanks in advance.

ReferenceError: Cannot access ‘Configuration’ before initialization

ok so I have literally no clue what is wrong here, I might just be an idiot but can someone help me out here

    const Configuration = require("openai");
    const OpenAIApi = require("openai")
    
    async function callAI() {
    const configuration = new Configuration({
      apiKey: "redacted",
    });
    const openai = new OpenAIApi(configuration);
    
    try {
        const completion = await openai.createCompletion("text-davinci-001", {
          prompt: document.getElementById("sus").value
        });
        document.getElementById(aiResponce).value = completion.data.choices[0].text;
      } catch (error) {
        if (error.response) {
          console.log(error.response.status);
          console.log(error.response.data);
        } else {
          console.log(error.message);
        }
      }
    }

heres the error that appears.

callAI.js:5:21 Uncaught (in promise) ReferenceError: Cannot access 'Configuration' before initialization
at callAI (callAI.js:5:21)

error ajax laravel 405 method not allowed

I try to insert data in database with Ajax, but it doesn’t work
Error:
POST http://127.0.0.1:8000/%7B%7Broute(‘achats.store’)%7D%7D 405 (Method Not Allowed)
Controller:

$achat = new achat();
    $achat->libellé=$request->input('libll');
    $achat->date_achat=$request->input('achatDate');
    $achat->montant_total=$request->input('montant');
    $achat->Agent=Auth::user()->id;
    $achat->fournisseur=$request->get('frn');
    if($request->file('bon')){
        $bon=$request->file('bon');
        $achat->bon=$bon->getClientOriginalName();
        $bon->move('bon',$bon->getClientOriginalName());
    }
    $achat->save();
       
           return response()->json([
               'status'=>true,
               'msg'=>'Sauvegardé avec succès'
           ]);
        
    
            return response()->json([
                'status'=>false,
                'msg'=>'Le sauvegarde a échoué veuillez réessayer'
            ]);

Code js:

   $("#btn_submit").click(function(e){
   e.preventDefault();
   $.ajax({
     type:'POST',
     url:"{{route('achats.store')}}",
     data:$("#frm_add").serialize(),
     success: function(date){

     },error : function(reject){

     }
   })

})

solve this destructuring method [closed]

const places = ['delhi', 'gurgaon', 'jaipur', 'pune']
const morePlaces = ['kochi', 'hyderabad', 'Shimla', 'Srinagar']

IMPORTANT: solve all problems using using destructuring and rest syntax

   

  1. remove first element from places array and print the remaining array

  2. insert that element at the start of the morePlaces array and print the new array
    take out last three element from the morePlacesArray and take out first three elements from the places array
    and print the combined array

result =  ['hyderabad', 'Shimla', 'Srinagar', 'delhi', 'gurgaon', 'jaipur',]

Why counter increases and fn is called? How it works?

I solved kata on codewars. Acctually I did this by accident and I don’t understand why this code works. May you explain it?

Kata:

Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.

39 –> 3 (because 39 = 27, 27 = 14, 1*4 = 4 and 4 has only one digit)

My solution:

function persistence(num) {
  let count = 0;
  const arr = [...num.toString()];
  const sumArr = arr.reduce((res, val) => (res *= val));

  if (arr.length > 1) {
    **// Why? How this line works?
    // Why it doesn't crashes?
    // Why it returns correct counter value and calls the function?**
    count += 1 + persistence(sumArr)
  }
  return count;
}

persistence(39); //3

Why if I do like this, the counter do not save the result:

  if (arr.length > 1) {
    count += 1
    persistence(sumArr)   }