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);
        
    }

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?

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.

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){

     }
   })

})

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)

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)   }

Failed to execute ‘texImage2D’ on ‘WebGLRenderingContext’: using phaser

I’m using a phaser, I keep getting the following error:

Failed to execute ‘texImage2D’ on ‘WebGLRenderingContext’: The image
element contains cross-origin data, and may not be loaded.

The images are on my computer, same as the game.js file

<html>
  <head>
    <meta charset="UTF-8">
    <title>Jumper - written with Phaser 2</title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/phaser/2.0.7/phaser.min.js"></script>
    <link rel="stylesheet" href="./src/game.css" />
  </head>
  <body><script type="text/javascript" src="./src/game.js"></script></body>
</html>

JS

// Linted with standardJS - https://standardjs.com/

// Initialize the Phaser Game object and set default game window size
const game = new Phaser.Game(800, 600, Phaser.AUTO, '', {
  preload: preload,
  create: create,
  update: update
})

// Declare shared variables at the top so all methods can access them
let score = 0
let scoreText
let platforms
let diamonds
let cursors
let player

function preload () {
  // Load & Define our game assets
  game.load.image('sky', './assets/sky.png')
  game.load.image('ground', './assets/platform.png')
  game.load.image('diamond', './assets/diamond.png')
  game.load.spritesheet('woof', './assets/woof.png', 32, 32)
}

function create () {
  //  We're going to be using physics, so enable the Arcade Physics system
  game.physics.startSystem(Phaser.Physics.ARCADE)

  //  A simple background for our game
  game.add.sprite(0, 0, 'sky')

  //  The platforms group contains the ground and the 2 ledges we can jump on
  platforms = game.add.group()

  //  We will enable physics for any object that is created in this group
  platforms.enableBody = true

  // Here we create the ground.
  const ground = platforms.create(0, game.world.height - 64, 'ground')

  //  Scale it to fit the width of the game (the original sprite is 400x32 in size)
  ground.scale.setTo(2, 2)

  //  This stops it from falling away when you jump on it
  ground.body.immovable = true

  //  Now let's create two ledges
  let ledge = platforms.create(400, 450, 'ground')
  ledge.body.immovable = true

  ledge = platforms.create(-75, 350, 'ground')
  ledge.body.immovable = true

  // The player and its settings
  player = game.add.sprite(32, game.world.height - 150, 'woof')

  //  We need to enable physics on the player
  game.physics.arcade.enable(player)

  //  Player physics properties. Give the little guy a slight bounce.
  player.body.bounce.y = 0.2
  player.body.gravity.y = 800
  player.body.collideWorldBounds = true

  //  Our two animations, walking left and right.
  player.animations.add('left', [0, 1], 10, true)
  player.animations.add('right', [2, 3], 10, true)

  //  Finally some diamonds to collect
  diamonds = game.add.group()

  //  Enable physics for any object that is created in this group
  diamonds.enableBody = true

  //  Create 12 diamonds evenly spaced apart
  for (var i = 0; i < 12; i++) {
    const diamond = diamonds.create(i * 70, 0, 'diamond')

    //  Drop em from the sky and bounce a bit
    diamond.body.gravity.y = 1000
    diamond.body.bounce.y = 0.3 + Math.random() * 0.2
  }

  //  Create the score text
  scoreText = game.add.text(16, 16, '', { fontSize: '32px', fill: '#000' })

  //  And bootstrap our controls
  cursors = game.input.keyboard.createCursorKeys()
}

function update () {
  //  We want the player to stop when not moving
  player.body.velocity.x = 0

  //  Setup collisions for the player, diamonds, and our platforms
  game.physics.arcade.collide(player, platforms)
  game.physics.arcade.collide(diamonds, platforms)

  //  Call callectionDiamond() if player overlaps with a diamond
  game.physics.arcade.overlap(player, diamonds, collectDiamond, null, this)

  // Configure the controls!
  if (cursors.left.isDown) {
    player.body.velocity.x = -150
    player.animations.play('left')
  } else if (cursors.right.isDown) {
    player.body.velocity.x = 150
    player.animations.play('right')
  } else {
    // If no movement keys are pressed, stop the player
    player.animations.stop()
  }

  //  This allows the player to jump!
  if (cursors.up.isDown && player.body.touching.down) {
    player.body.velocity.y = -400
  }
  // Show an alert modal when score reaches 120
  if (score === 120) {
    alert('You win!')
    score = 0
  }
}

function collectDiamond (player, diamond) {
  // Removes the diamond from the screen
  diamond.kill()

  //  And update the score
  score += 10
  scoreText.text = 'Score: ' + score
}

Must supply a value for form control with name: ‘nom’

I am currently trying to update data stored with MongoDB via my form (Angular).
However, I have an error in my browser console:

ERROR Error: NG01002: Must supply a value for form control with name:
‘name’

HTML :

<div class="row justify-content-center mt-5">
  <div class="col-md-4">
    <h1>Modification de vos informations.</h1>
    <form [formGroup]="updateForm" (ngSubmit)="onUpdate()">
      <div class="form-group">
        <label>Nom</label>
        <input class="form-control" type="text" formControlName="nom" required>
      </div>

      <div class="form-group">
        <label>Prénom</label>
        <input class="form-control" type="text" formControlName="prenom" required>
      </div>

      <div class="form-group">
        <label>Email</label>
        <input class="form-control" type="text" formControlName="email" required>
      </div>

      <div class="form-group">
        <label>Mot de passe</label>
        <input class="form-control" type="text" formControlName="password" required>
      </div>

      <div class="form-group">
        <label>Statut</label>
        <input class="form-control" type="text" formControlName="statut" required>
      </div>

      <div class="form-group">
        <label>NombreUC</label>
        <input class="form-control" type="text" formControlName="nombreUC" required>
      </div>

      <div class="form-group">
        <button class="btn btn-primary btn-block" type="submit">Update</button>
      </div>
    </form>
  </div>
</div>

TS :

import { Component, OnInit, NgZone } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { CrudService } from './../../../service/crud.service';
import { FormGroup, FormBuilder } from "@angular/forms";


@Component({
  selector: 'app-edit-user',
  templateUrl: './edit-user.component.html',
  styleUrls: ['./edit-user.component.css']
})
export class EditUserComponent implements OnInit {

  getId: any;
  updateForm: FormGroup;

  constructor(
    public formBuilder: FormBuilder,
    private router: Router,
    private ngZone: NgZone,
    private activatedRoute: ActivatedRoute,
    private crudService: CrudService
  ) {
    this.getId = this.activatedRoute.snapshot.paramMap.get('id');

    this.crudService.GetUser(this.getId).subscribe(res => {
      this.updateForm.setValue({
        nom: res['nom'],
        prenom: res['prenom'],
        email: res['email'],
        password: res['password'],
        statut: res['statut'],
        nombreUC: res['nombreUC']
      });
    });

    this.updateForm = this.formBuilder.group({
      nom: [''],
      prenom: [''],
      email: [''],
      password: [''],
      statut: [''],
      nombreUC: ['']
    })
  }

  ngOnInit() { }

  onUpdate(): any {
    this.crudService.updateUser(this.getId, this.updateForm.value)
    .subscribe(() => {
        console.log('Updated!')
        this.ngZone.run(() => this.router.navigateByUrl('/admin/list-users'))
      }, (err) => {
        console.log(err);
    });
  }
}

I’m new to this so I’m sorry if I’m not clear enough.. but I haven’t found a solution yet.