javascript – sinon.js : how to check for a variable value in a method

typescript / javascript
an app based on express.js
sinon.js

I need to get a general syntax for an expression that checks a value of a variable in a method.

I have a file controller.js (a controller, but should not matter) that has method in which a variable is assigned but not returned. I have to run a test that checks that the var got the value.

module.exports = (historyHandler) => ({
  getHistory: async (req, res, next) => {

    const myvar = 'abc';
    const myRes = await historyHandler.handle(req.logger)(myvar);
  res.status(200).json({ items: myRes });
......
});

and a test which should check if setting of myvar worked. The line I am trying to test is :

const myvar = 'abc';

I am trying to do this and the syntax is wrong. What should be the right syntax please?

const request = require("supertest");
const sinon = require("sinon");

test("mytest", async () => {
    const historyHandler  = require("../pathtocontroller/controller");
const historyHandlerSpy = sinon.spy(historyHandler);    
sinon.assert.calledWith(historyHandlerSpy(logger)(myvar), sinon.match({ myvar: "abc" }));

The error I am getting is :

error TS2349: This expression is not callable.
Type ‘{ myHistory: (req: any, res: any, next: any) => Promise; }’ has no call signatures.

//also tried: 
sinon.assert.calledWith(historyHandlerSpy.handle(logger)(myvar), sinon.match({ myvar: "abc" }));
//and got: 

error TS2339: Property ‘handle’ does not exist on type
‘(historyHandler: any) => { getHistory: (req: any, res: any,
next: any) => Promise; }’.

//and several other variants with various errors (e.g. something about "never").

Unfortunately I am new to this stack and can not find the exact way to do this test that references all the entities involved correctly in the docs.

Thanks

mathematical programming – How to write code to calculate partial derivative of several variable function in C++?

I already wrote the code to calculate the derivative of a single variable function at a point by making a class called “Der”. In class Der, I defined two private variables double f and double df and a print() function to print the values of f and df. Inside the class, I overloaded the operators +, -, *, /, ^ to calculate the derivative of the sum, difference, multiplication etc of functions. I can’t show the whole code because it’s very long but I will show some snippets to give an idea.

class Der{
private:
    double f;  // function value at x
    double df; // derivative of function at x
public:
    Der();
    Der(double);
    Der operator+(Der); // f + g
    Der operator-(Der); // f - g
    Der operator*(Der); // f * g
    Der operator/(Der); // f / g
       
    friend Der operator+(double, Der); //c+f
    friend Der operator-(double, Der); //c-f
    friend Der operator*(double, Der); //c*f
    friend Der operator/(double, Der); //c/f
    Der operator^(double); // f^c,  Where c is constant
   
    friend Der sin(Der);
    friend Der cos(Der);
    friend Der tan(Der);
    friend Der log(Der);
    friend Der exp(Der);
    
    void print();
};

Der :: Der(){}

Der :: Der(double x){
    this->f = x;
    this->df = 1;
}

Der Der :: operator+(Der g){
    Der h;
    h.f = this->f + g.f;
    h.df = this->df + g.df;
    return h;
}

Der sin(Der g){
    Der h;
    h.f = sin(g.f);
    h.df = cos(g.f)*g.df;
    return h;
}
void Der :: print(){
    cout<<"Derivative of function at a point : "<<df<<endl;
}

int main()
    {
        Der x(10), f;
        f = x^2+x^3;
        f.print();
    }

Now I want to use this derivative calculator to calculate the partial derivative of a several variable function and ultimately to calculate the gradient of that function. I have some vague ideas but I am not able to implement it in code. I am a beginner in C++ programming, so it would be helpful if you don’t use too many advanced topics.

Any kind of help would be highly appreciated. Thanks!

Edit: The program should take inputs of independent variables like x(2), y(4), z(5) and function like f(x,y,z)=x^2*y*z+log(x*y*z). Then, it will give the partial derivative of f w.r.t x, y, z at point (2, 4, 5) in the form of an array. I just need some idea on how to code the partial derivative calculator.

unity – How can I access a variable on a script in another scene that I made it dontdestroyonload?

I need to get access to the variable flag loading from some script in another scene.
The variable loading in my main menu scene and I need to access it in scripts in my game scene.

I’m not sure if using dontdestroyonload in this case is the right way and I don’t want to make the loading variable public static either :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEditor;
using Cinemachine;
using UnityStandardAssets.Characters.ThirdPerson;

public class MenuController : MonoBehaviour
{
    #region Default Values
    (Header("Default Menu Values"))
    (SerializeField) private float defaultVolume;
    (SerializeField) private int defaultSen;
    (SerializeField) private bool defaultInvertY;

    (Header("Levels To Load"))
    public string _newGameButtonLevel;
    private string levelToLoad;

    public SceneFader sceneFader;
    public GameObject player;

    private int menuNumber;
    #endregion

    #region Menu Dialogs
    (Header("Main Menu Components"))
    (SerializeField) private GameObject menuDefaultCanvas;
    (SerializeField) private GameObject GeneralSettingsCanvas;
    (SerializeField) private GameObject graphicsMenu;
    (SerializeField) private GameObject soundMenu;
    (SerializeField) private GameObject controlsMenu;
    (SerializeField) private GameObject confirmationMenu;
    (Space(10))
    (Header("Menu Popout Dialogs"))
    (SerializeField) private GameObject noSaveDialog;
    (SerializeField) private GameObject newGameDialog;
    (SerializeField) private GameObject loadGameDialog;
    #endregion

    #region Slider Linking
    (Header("Menu Sliders"))
    (SerializeField) private Text controllerSenText;
    (SerializeField) private Slider controllerSenSlider;
    public float controlSenFloat = 2f;
    (Space(10))
    (SerializeField) private Text volumeText;
    (SerializeField) private Slider volumeSlider;
    (Space(10))
    (SerializeField) private Toggle invertYToggle;
    #endregion

    public bool loading = false;

    #region Initialisation - Button Selection & Menu Order
    private void Start()
    {
        DontDestroyOnLoad(this);
        menuNumber = 1;
    }
    #endregion

    //MAIN SECTION
    public IEnumerator ConfirmationBox()
    {
        confirmationMenu.SetActive(true);
        yield return new WaitForSeconds(2);
        confirmationMenu.SetActive(false);
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            if (menuNumber == 2 || menuNumber == 7 || menuNumber == 8)
            {
                GoBackToMainMenu();
                ClickSound();
            }

            else if (menuNumber == 3 || menuNumber == 4 || menuNumber == 5)
            {
                GoBackToOptionsMenu();
                ClickSound();
            }

            else if (menuNumber == 6) //CONTROLS MENU
            {
                ClickSound();
            }
        }
    }

    private void ClickSound()
    {
        GetComponent<AudioSource>().Play();
    }

    #region Menu Mouse Clicks
    public void MouseClick(string buttonType)
    {
        if (buttonType == "Controls")
        {
            controlsMenu.SetActive(true);
            menuNumber = 6;
        }

        if (buttonType == "Graphics")
        {
            GeneralSettingsCanvas.SetActive(false);
            graphicsMenu.SetActive(true);
            menuNumber = 3;
        }

        if (buttonType == "Sound")
        {
            GeneralSettingsCanvas.SetActive(false);
            soundMenu.SetActive(true);
            menuNumber = 4;
        }

        if (buttonType == "Exit")
        {
            Debug.Log("YES QUIT!");
            Application.Quit();
        }

        if (buttonType == "Options")
        {
            menuDefaultCanvas.SetActive(false);
            GeneralSettingsCanvas.SetActive(true);
            menuNumber = 2;
        }

        if (buttonType == "LoadGame")
        {
            menuDefaultCanvas.SetActive(false);
            loadGameDialog.SetActive(true);
            menuNumber = 8;
        }

        if (buttonType == "NewGame")
        {
            menuDefaultCanvas.SetActive(false);
            newGameDialog.SetActive(true);
            menuNumber = 7;
        }
    }
    #endregion

    public void VolumeSlider(float volume)
    {
        AudioListener.volume = volume;
        volumeText.text = volume.ToString("0.0");
    }

    public void VolumeApply()
    {
        PlayerPrefs.SetFloat("masterVolume", AudioListener.volume);
        Debug.Log(PlayerPrefs.GetFloat("masterVolume"));
        StartCoroutine(ConfirmationBox());
    }

    public void ControllerSen()
    {
        controllerSenText.text = controllerSenSlider.value.ToString("0");
        controlSenFloat = controllerSenSlider.value;
    }

    #region ResetButton
    public void ResetButton(string GraphicsMenu)
    {
        if (GraphicsMenu == "Audio")
        {
            AudioListener.volume = defaultVolume;
            volumeSlider.value = defaultVolume;
            volumeText.text = defaultVolume.ToString("0.0");
            VolumeApply();
        }

        if (GraphicsMenu == "Graphics")
        {
            controllerSenText.text = defaultSen.ToString("0");
            controllerSenSlider.value = defaultSen;
            controlSenFloat = defaultSen;

            invertYToggle.isOn = false;
        }
    }
    #endregion

    #region Dialog Options - This is where we load what has been saved in player prefs!
    public void ClickNewGameDialog(string ButtonType)
    {
        if (ButtonType == "Yes")
        {
            // Here to use a script to load the start game scene slowly smooth fade to black
            // Then fade back to transparent when loading/loaded the scene game !!!!!
            //SceneManager.LoadScene(_newGameButtonLevel);

            // When making new game to reset everything state scene everythig.
            // Including the uiSceneText for example.
            // To check how to reset everything to default !
            loading = false;
            newGameDialog.SetActive(false);
            StartCoroutine(sceneFader.FadeAndLoadScene(SceneFader.FadeDirection.In, _newGameButtonLevel));
        }

        if (ButtonType == "No")
        {
            GoBackToMainMenu();
        }
    }

    public void ClickLoadGameDialog(string ButtonType)
    {
        if (ButtonType == "Yes")
        {
            //if (PlayerPrefs.HasKey("SavedLevel"))
            //{
            //Debug.Log("I WANT TO LOAD THE SAVED GAME");
            //LOAD LAST SAVED SCENE
            //levelToLoad = PlayerPrefs.GetString("SavedLevel");
            //SceneManager.LoadScene(levelToLoad);
            loading = true;
            newGameDialog.SetActive(false);
            StartCoroutine(sceneFader.FadeAndLoadScene(SceneFader.FadeDirection.In, _newGameButtonLevel));

            //}

            /*else
            {
                Debug.Log("Load Game Dialog");
                menuDefaultCanvas.SetActive(false);
                loadGameDialog.SetActive(false);
                noSaveDialog.SetActive(true);
            }*/
        }

        if (ButtonType == "No")
        {
            GoBackToMainMenu();
        }
    }
    #endregion

    #region Back to Menus
    public void GoBackToOptionsMenu()
    {
        GeneralSettingsCanvas.SetActive(true);
        graphicsMenu.SetActive(false);
        soundMenu.SetActive(false);

        VolumeApply();

        menuNumber = 2;
    }

    public void GoBackToMainMenu()
    {
        menuDefaultCanvas.SetActive(true);
        newGameDialog.SetActive(false);
        loadGameDialog.SetActive(false);
        noSaveDialog.SetActive(false);
        GeneralSettingsCanvas.SetActive(false);
        graphicsMenu.SetActive(false);
        soundMenu.SetActive(false);
        menuNumber = 1;
    }

    public void ClickQuitOptions()
    {
        GoBackToMainMenu();
    }

    public void ClickNoSaveDialog()
    {
        GoBackToMainMenu();
    }
    #endregion
}

At the top line 56 :

public bool loading = false;

Inside Start at line 61 :

DontDestroyOnLoad(this);

Then inside the method for starting a new game in line 207 :

loading = false;

And in the method that loading a saved game in line 228 :

loading = true;

Now that I know when it’s starting a new game and when it’s loading a game I want to use this loading variable in some scripts in my game scene.

For example this script :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class SceneFader : MonoBehaviour
{
    #region FIELDS
    public GameObject fadeOutUIGameobjectImage;
    public float fadeSpeed = 0.8f;

    private MenuController menuController;
    private Image fadeOutUIImage;

    private void Start()
    {
        
    }

    public enum FadeDirection
    {
        In, //Alpha = 1
        Out // Alpha = 0
    }
    #endregion

    #region FADE
    public IEnumerator Fade(FadeDirection fadeDirection)
    {
        fadeOutUIGameobjectImage.SetActive(true);

        float alpha = (fadeDirection == FadeDirection.Out) ? 1 : 0;
        float fadeEndValue = (fadeDirection == FadeDirection.Out) ? 0 : 1;
        if (fadeDirection == FadeDirection.Out)
        {
            while (alpha >= fadeEndValue)
            {
                SetColorImage(ref alpha, fadeDirection);
                yield return null;
            }
            fadeOutUIGameobjectImage.SetActive(false);
        }
        else
        {
            fadeOutUIGameobjectImage.SetActive(true);
            while (alpha <= fadeEndValue)
            {
                SetColorImage(ref alpha, fadeDirection);
                yield return null;
            }
        }
    }
    #endregion

    #region HELPERS
    public IEnumerator FadeAndLoadScene(FadeDirection fadeDirection, string sceneToLoad)
    {
        yield return Fade(fadeDirection);
        SceneManager.LoadScene(sceneToLoad);

        SceneManager.sceneLoaded += SceneManager_sceneLoaded;
    }

    private void SceneManager_sceneLoaded(Scene arg0, LoadSceneMode arg1)
    {
        if (menuController.loading == true)
        {
            var saveLoad = GameObject.Find("Save System").GetComponent<SaveLoad>();
            saveLoad.Load();
        }
    }

    private void SetColorImage(ref float alpha, FadeDirection fadeDirection)
    {
        if(fadeOutUIImage == null)
        {
            fadeOutUIImage = fadeOutUIGameobjectImage.GetComponent<Image>();
        }

        fadeOutUIImage.color = new Color(fadeOutUIImage.color.r, fadeOutUIImage.color.g, fadeOutUIImage.color.b, alpha);
        alpha += Time.deltaTime * (1.0f / fadeSpeed) * ((fadeDirection == FadeDirection.Out) ? -1 : 1);
    }
    #endregion
}

At the top I did :

private MenuController menuController;

Then inside the event SceneManager_sceneLoaded I did at line 67 :

if (menuController.loading == true)

but I didn’t make any reference to the MenuController script even if it’s not destroyed.
so loading will be null here I guess.

The idea is to use global in my project with the loading bool flag variable to find if the game is loading or if a new game started.

probability – PMF for the Quadruple of a random variable.

I had a homework problem with a question and solution as below.
Question: Let X be geometrically distributed with parameter p, let Y = $X^4$. Find the probability mass functions of Y.
My solution: $P(X=k) = (1-p)^{k-1} * p. P(Y = k) = P(X^4 = k) = P(X = k^{1/4}) = (1-p)^{x^{1/4} – 1} * p $.

The solution is: By definition, the probability mass function of X is given by
$P(X=k) = (1-p)^{k-1} * p$ ∀ k = 1, 2, 3, . . .
Therefore the only values that Y takes with non-zero probability are 4th powers of positive integers, and $P(Y = k^4) = (1 − p)^{k−1}p$ ∀ k = 1, 2, 3, . . .

I’m confused by why my solution isn’t the correct approach and why Y could be directly perceived as such. It seems that I have a lack of understanding of how PMFs work.

Thanks!

php – Por que no pasa mi variable a la vista blade?

Por que no pasa la variable usuario a la vista del componente?

este es mi componente:

<?php

namespace AppHttpLivewire;

use LivewireComponent;
use IlluminateSupportFacadesDB;
use IlluminateSupportFacadesAuth;
use AppUser;


class PerfilComponent extends Component
{
    public $id, $nombre, $correo, $password;

    public function mount(){
      $id = Auth::id();
    }

    public function render()
    {
        $usuario = User::where('id','=',$id)->get();
        return view('livewire.Perfiles.perfil-component',compact('usuario'));
    }


}

Coloque esto en el route/web

Route::view('/perfil', 'livewire/Perfiles/perfil-component');

y esta es la vista de mi componente:

@extends('layouts.app')
@section('content')
<div>
  @foreach($usuario as $usu)
    {{$usu->name}}
  @endforeach
</div>
@endsection

cuando me voy a localhot:8000/perfil me aparece el siguiente error:

ErrorException
Undefined variable: usuario (View: /../resources/views/livewire/Perfiles/perfil-component.blade.php)

he revisado proyectos anteriores con livewire y no me pasaba esto. qué podrá ser?

analysis – de-meaned data of dependent variable

A book on financial econometrics states:

we could subtract the mean from the data and write factor models in terms of de-meaned data x on y

= −µ µ where is the mean of y.
In this case, the constant terms a i are all equal to zero.

This does not appear evident. y is a dependent variable. If we substract its mean, we should get residuals, not x. Could ye please advise, on what logick foundation does the de-meaned data rest? Thank ye.

theming – How to use a Twig variable as View name in drupal_view() Twig Tweaks function?

This works:

{{ drupal_view('nursing_resource_blog_teasers', 'block_1') }

But this doesn’t:

{% set view_name = "nursing_resource_blog_teasers" %}
{{ drupal_view(view_name , 'block_1') }

It appears that drupal_view() isn’t allowing a variable as the View name. Is there a way to make this work?

troubleshooting – use of ND Variable filter

I am an amateur photographer and I tested a ND 2-400 variable filter-at its maximum 8 2/3 stops-for a low light landscape scenery.My Nikon d610 suggested data were aperture 4.0 ,shutter speed 0.4s,iso 100 without the filter and the exposure calculator app on my mobile gave me a time of shooting of 205 s.However photo was black and remained black even when I exceeded the time of shooting up to 5 minutes and more.
Something went wrong and I need some advice on this.

Session variable and cache drupal

I’ve created a small helper where I can set and access my session variable (thanks to the drupal 8 session).

Can’t figure out why, my session is working well with my dev (no cache) but on my prod my session is not persisted, need to refresh drupal cache to see my session variable…

  public static function getSessionIRA()
  {
    return self::getModuleStore()->get('session_ira');
  }

  public static function setSessionIRA($session_ira)
  {
    return self::getModuleStore()->set('session_ira', $session_ira);
  }

  /**
   * @return mixed
   */
  private static function getModuleStore()
  {
    return Drupal::request()->getSession();

    return self::$module_store = Drupal::service('user.private_tempstore')->get('mymodule_services');
  }

What could be a better naming for the variable ‘completeConfig’?

I have a feature in which the user can directly provide the entire nginx config inside the completeConfig variable in the config yaml.

Like this:

nginxConfig:
  completeConfig: >
   ....
   ....

But completeConfig variable seems a little weird. Can someone suggest something better?