Dynamically changing the variable name inside 2 for loops [duplicate]

So I’m working in babylon.js (but is more a js problem at this time) my problem is that I need to change a variable name dynamically but taking the index of both for that.

Here, let me show you the array in fact:

    for (let i = 0; i < torresIndex; i++) {
                for (let j = 0; j < repTorre[i]; j++) {
                    piso = BABYLON.MeshBuilder.ExtrudePolygon("piso"+i+j, {shape:torre[i], depth: 1, sideOrientation: -1 }, scene);
                    piso.position.y = factorTamano++;
                    factorTamano = factorTamano++;
                    piso.material  = materialforSolidPolygon;
                    piso.enableEdgesRendering(); 
                    piso.edgesWidth = 4.0;
                    piso.edgesColor = new BABYLON.Color4(0, 0, 0);
  }
}

“piso” is an array variable outside of the loop.

So the idea in question is that the name of the variable “piso” change dynamically according to the position of “i” and “j”

The expected result is this:

i=0 j=1
piso01
i=0 j=2
piso02
......... and so on.

The end result in general that I want is that I can call the shape in question and take their vertices to work it out individually in another for loop.

How to checkbox automatically checked all when select all after upload image

I want to make a method that when executed will check all inputs that have images and text, where this method will run on the input checkbox with the label Select All, which when select all is checked automatically all the input checkboxes on the uploaded image will be checked. Like the example I made on the imageChecked() method which worked successfully where when the input is checked, the checked image data will be entered/returned to the image array in crudData{‘image’:[]}, and the text input data will be entered/returned to the array name in crudData{‘name’:[]}. Does anyone understand the case I’m asking about? Thank you.

Here is the complete code https://jsfiddle.net/cd59bLxu/1/

export default {
  data() {
    return{
      crudData:{
        ‘id’: null,
        ‘name’: [],
        ‘image’: [],
        ‘arrImage’: [],
      },
    }
  },
  methods: {
    imageUpload(e, maxItem){
      …
    },
    uploadImage(e){
      …
    },
    removeImage(key){
      …
    },
    imageChecked() {
      let checkedImages =          this.crudData.arrImage.filter(img =>   img.checked)
      this.crudData.image =   checkedImages.map(img => img.image)
      this.crudData.name = checkedImages.map(img => img.name)
      console.log({imageFiles:    this.crudData.image, names:       this.crudData.name})
    }
  }}

Reset count when another button is pressed

I have a lots of articles that have 1, 2, 3 or 4 pictures. On mobile I created a carousel. All images all on the same line and I have a count that is 0. And when I press on the right button(for example) that count it will be -100 and all images will have a left: -100 and so on. The problem is that, let’s say, I press on the button from one article that count will be -100. but after I go to another article and if I press again the count is not -100 and is -200. How can I reset that count when I change the article. The code is something like:

<div class="article">
  <div class="minus">Minu</div>
  <div class="plus">Plus
  </div><div class="num">0</div>
</div>
<div class="article">
  <div class="minus">Minu2</div>
  <div class="plus">Plus2
  </div><div class="num">0</div>
</div>
<div class="article">
  <div class="minus">Minu3</div>
  <div class="plus">Plus3
  </div><div class="num">0</div>
</div>
<div class="article">
  <div class="minus">Minu4</div>
  <div class="plus">Plus4
  </div><div class="num">0</div>
</div>
<div class="article">
  <div class="minus">Minu5</div>
  <div class="plus">Plus5
  </div><div class="num">0</div>
</div>
 var c = 0;
$('.plus').on('click', function(){
    c += 100
    $(this).siblings('.num').text(c)
})```

unsuccesful login with react

Let there be a landing page that enables the login.
This landing page has:

  • Text field for user ID: LoginUserIDInput
  • Text field for password: LoginPasswordInput
  • Button to start the login process: LoginButton

If the login process is successful, I am redirected to a private page.
If the login process is not successful, I remain on the landing page.

Now the following error message appears in the console output:

`controlId` is ignored on `<FormControl>` when `id` is specified.

How can I successfully implement the login process ?

AuthenticationAction.js

export const SHOW_LOGIN_DIALOG ='SHOW_LOGIN_DIALOG';
export const HIDE_LOGIN_DIALOG ='HIDE_LOGIN_DIALOG';

export const AUTHENTICATION_PENDING = 'AUTHENTICATION_PENDING'
export const AUTHENTICATION_SUCCESS = 'AUTHENTICATION_SUCCESS'
export const AUTHENTICATION_ERROR = 'AUTHENTICATION_ERROR'

export function getShowLoginDialogAction(){

    return {
        type: SHOW_LOGIN_DIALOG
    }
}

export function getHideLoginDialogAction(){

    return{
        type: HIDE_LOGIN_DIALOG
    }
}

export function getAuthenticateUserPendingAction(){
    return{
        type: AUTHENTICATION_PENDING
    }
}

export function getAuthenticationSuccessAction(userSession) {
    return {
        type: AUTHENTICATION_SUCCESS,
        user: userSession.user,
        accessToken: userSession.accessToken
    }
}

export function getAuthenticationErrorAction(error){
    return {
        type: AUTHENTICATION_ERROR,
        error: error
    }
}

export function authenticateUser(userID, password){

    console.log("Authenticate")
    return dispatch => {
        dispatch(getAuthenticateUserPendingAction());
        login(userID,password).then(userSession => { const action= getAuthenticationSuccessAction(userSession);
        dispatch(action);}, error => {dispatch(getAuthenticationErrorAction(error));}).catch(error=> {dispatch(getAuthenticationErrorAction(error));})
    }
}

function login(userID,password){
    const requestOptions={
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({userID, password})
    };
    return fetch('http://localhost:8080/login',requestOptions).then(handleResponse).then(userSession => {return userSession});
};

function handleResponse(response){

    const authorizationHeader = response.headers.get('Authorization');
    return response.text().then(text => {
        console.log('Receive result: '+authorizationHeader)

        const data= text && JSON.parse(text);
        var token 
        if(authorizationHeader){
            token = authorizationHeader.split(" ")[1];
        }
        if(!response.ok){
            if(response.status ===401){
                logout();
            }
            const error =(data && data.message) || response.statusText;
            return Promise.reject(error);
        }
        else{
            let userSession = {
                user: data,
                accessToken: token
            }
            return userSession;
        }
    });
}

function logout(){
    console.error("Should logout user")
}

RootReducer.js

import * as authenticationActions from '../actions/AuthenticationAction'

const initialState = {
    user: null,
    loginPending: false,
    showLoginDialog: false
    };
    function rootReducer(state = initialState, action) {
        console.log("Bin im Reducer" + action.type)

        switch(action.type){

            case authenticationActions.SHOW_LOGIN_DIALOG:
                return {
                    ...state,
                    showLoginDialog: true,
                    error: null
                }
         
        case authenticationActions.HIDE_LOGIN_DIALOG:
                return {
                    ...state,
                    showLoginDialog: false,
                    error: null
                }
        

        case authenticationActions.AUTHENTICATION_SUCCESS:
            {
                return {
                    ...state,
                    showLoginDialog: false,
                    pending: false,
                    user: action.user,
                    accessToken: action.accessToken
                }
            }
        case authenticationActions.AUTHENTICATION_ERROR:
            {
                return {
                    ...state,
                    pending: false,
                    error: "Authentication failed"
                }
            }
        case authenticationActions.AUTHENTICATION_PENDING:
            {
                return {
                    ...state,
                    pending: true,
                    error: null
                }
            }
            default:
                return state;
        }
        
    };
    
    export default rootReducer;
    

UserSessionWidget.js

import React, {Component} from "react"
import {connect} from "react-redux";
import { bindActionCreators } from 'redux'
import Button from "react-bootstrap/Button"
import Modal from "react-bootstrap/Modal"
import Form from "react-bootstrap/Form"
import * as authenticationActions from '../actions/AuthenticationAction'

const mapStateToProps = state => {
    return state;
}



class UserSessionWidget extends Component {

    constructor(props){
        super(props)
        this.state={username: '', password: ''};
        this.handleShow=this.handleShow.bind(this);
        this.handleClose=this.handleClose.bind(this);
        this.handleChange=this.handleChange.bind(this);
        this.handleSubmit=this.handleSubmit.bind(this);
    }

    handleShow(e){
        e.preventDefault();
        /* this.setState({show: true}) */
        const {showLoginDialogAction} =this.props;
        showLoginDialogAction();


    }
    handleClose(e){
        e.preventDefault();
        this.setState({show: false})
        const {hideLoginDialogAction} =this.props;
        hideLoginDialogAction();

    }

    handleChange(e){

        const {name,value} = e.target;
        this.setState({[name]: value})

        console.log(JSON.stringify(this.state))

    }

    handleSubmit(e){
        e.preventDefault();
        const {username, password} =this.state;
        const {authenticateUserAction}=this.props;
        authenticateUserAction(username, password);
        console.log("Pushed submit")
    }

    render(){

        var showDialog=this.props.showLoginDialog;
        if(showDialog==undefined){
            showDialog=false;
        }
     

        return (
            
            <div>
                <Button variant="primary" onClick={this.handleShow}>Login</Button>
                <Modal show={showDialog} onHide={this.handleClose}>
                    
                    <Modal.Body>
                    <Form>
  <Form.Group className="mb-3" controlId="userID">
    <Form.Label>UserID</Form.Label>
    <Form.Control id="LoginUserIDInput" type="text" placeholder="User ID" name="userID"
onChange={this.handleChange} />
   
  </Form.Group>

  <Form.Group className="mb-3" controlId="formBasicPassword">
    <Form.Label>Password</Form.Label>
    <Form.Control id=" LoginPasswordInput" type="password" placeholder="Password" name="password" onChange={this.handleChange} />
  </Form.Group>
 
  <Button variant="primary" type="submit" onClick={this.handleSubmit}>
    Submit
  </Button>
</Form>
                    </Modal.Body>
                    <Modal.Footer>
                        <Button variant="primary" onClick={this.handleClose}>Close</Button>
                    </Modal.Footer>
                   
                </Modal>
            </div>
        )
    }
}

const mapDisaptchToProps = dispatch => bindActionCreators({showLoginDialogAction: authenticationActions.getShowLoginDialogAction,hideLoginDialogAction: authenticationActions.getHideLoginDialogAction, authenticateUserAction: authenticationActions.authenticateUser},dispatch)
const ConnectedUserSessionsWidget =connect(mapStateToProps,mapDisaptchToProps)(UserSessionWidget)

export default ConnectedUserSessionsWidget;

jquery.js and jquery.keyframes.js are not found when using NPM

I’m having trouble using jquery and jquery.keyframes. I use NPM and the js files are stored in the node_modules folder while the html files are stored in the public folder. For some reason the html file cannot find the js files when I use this code:

<script src="../node_modules/jquerykeyframes/dist/jquery.keyframes.js"></script>
<script src="../node_modules/jquery/dist/jquery.js"></script>

I’ve tried a few alternatives but nothing has worked. What am I doing wrong?

How to to save txt file on server in HTML/JS?

I’m making signup form stuff and I want to save data to server and I got this code :

function Signup()
   {
     var text = "hello world",
   blob = new Blob([text], { type: 'text/plain' }),
   anchor = document.createElement('a');

anchor.download = "hello.txt";
anchor
anchor.href = (window.webkitURL || window.URL).createObjectURL(blob);
anchor.dataset.downloadurl = ['text/plain', anchor.download, anchor.href].join(':');
anchor.click();
   }

But its download file and I’m wondering how to save/download it to server.

How to fetch data from the mongo dB by given an array

I need some help. I am building an Api for recipes according to the ingredient, calorie and meal which I get from the user. so according to given ingredient I have to fetch recipes from the database which include required ingredient. I have two collection first collection of recipes which have document of recipes and these recipes document have a field ingredient from which I am searching ingredient. but here problem arise that I have a Calories and meal queries also. I can explain this with an example so let say I get queries from user like

localhost:5000/getcalorie/salmon,Fish,Turkey,Pork,ham?calorie=1400&meal=3 

so here salmon fish are ingredient. but here I have to divide calorie into 3 meals like 20% 40% and 40% and fetch those recipes which have calorie less than 20% calorie, 40% and 40%
and also no recipes should repeat in any meal like if roasted salmon is in breakfast then it should not be in lunch or dinner. but they have different recipes or salmon like salmon patties in lunch and for dinner it something other.
So how can I do this

I will show you how I am doing

async function meals(array,meals){
                let selectedfood =  await Recipe.find({$and:[{ingredients:{$in:array}},{calorie:{$lte:meals}}]})
                let selectedfood1 = await Nutrition.find({$and:[{name:{$in:array}},{calorie:{$lte:meals}}]})
                
                let commonselectedfoodarray = selectedfood.concat(selectedfood1)
                return commonselectedfoodarray
            }

from above code I am fetching recipes from database but here I am just including required ingredient from URL and meals(meals change according to meal like for breakfast it is (20/100)*calorie same for lunch and dinner)

but this above code fetch me recipes which have required ingredient and calories less than a meal

but my problem is how can I handle not repetition of recipes in different meals

am trying to implement webpack dev server. so install the following package with npm express,webpack-cli. i had issue when running dev server on npm

server.get(“/”, (req, res) => {

10 | const initialMarkup = ReactDOMServer.hydrateToString();
| ^
11 |
12 | res.send(`
13 |
at Parser.pp$5.raise (C:UsersUSERAppDataRoamingnpmnode_modulesbabel-clinode_modulesbabylonlibindex.js:4454:13)
at Parser.pp.unexpected (C:UsersUSERAppDataRoamingnpmnode_modulesbabel-clinode_modulesbabylonlibindex.js:1761:8)
at Parser.pp$3.parseExprAtom (C:UsersUSERAppDataRoamingnpmnode_modulesbabel-clinode_modulesbabylonlibindex.js:3750:12)
at Parser.pp$3.parseExprSubscripts (C:UsersUSERAppDataRoamingnpmnode_modulesbabel-clinode_modulesbabylonlibindex.js:3494:19)
at Parser.pp$3.parseMaybeUnary (C:UsersUSERAppDataRoamingnpmnode_modulesbabel-clinode_modulesbabylonlibindex.js:3474:19)
at Parser.pp$3.parseExprOps (C:UsersUSERAppDataRoamingnpmnode_modulesbabel-clinode_modulesbabylonlibindex.js:3404:19)
at Parser.pp$3.parseMaybeConditional (C:UsersUSERAppDataRoamingnpmnode_modulesbabel-clinode_modulesbabylonlibindex.js:3381:19)
at Parser.pp$3.parseMaybeAssign (C:UsersUSERAppDataRoamingnpmnode_modulesbabel-clinode_modulesbabylonlibindex.js:3344:19)
at Parser.pp$3.parseExprListItem (C:UsersUSERAppDataRoamingnpmnode_modulesbabel-clinode_modulesbabylonlibindex.js:4312:16)
at Parser.pp$3.parseCallExpressionArguments (C:UsersUSERAppDataRoamingnpmnode_modulesbabel-clinode_modulesbabylonlibindex.js:3573:20) {
pos: 302,
loc: Position { line: 10, column: 55 },
_babel: true,
codeFrame: ‘x1B[0m x1B[90m 8 | x1B[39mn’ +
‘ x1B[90m 9 | x1B[39mserverx1B[33m.x1B[39mget(x1B[32m”/”x1B[39mx1B[33m,x1B[39m (reqx1B[33m,x1B[39m res) x1B[33m=>x1B[39m {n’ +

}
[nodemon] app crashed – waiting for file changes before starting…

Assert a script is present on the page using nightwatchjs

I’m using nightwatchjs and trying to test whether a javascript script is present on a page or not.

Below is the html;

enter image description here

and I need to test that this is present on a particular page.

I understand that I could use Xpath (for example) and simply assert the following;

browser.assert.elementPresent('/html/head/script[10]/text()')

However, this isn’t really practical as scripts are often inserted before this script in due course which would fail the test due to the xpath of this script changing.

So, is there a way that I can pick out a certain part of this inserted javascript script (highlighted in yellow in the image above) and assert against this, rather than the whole script? This would then make the test far less brittle.

Many thanks

How to display a preview value on mat-select

I am trying to create a compilation table where I have to select a value in from a mat-select.

enter image description here

In the third column I have a list of values ​​that I can choose

lunch:infoLunch[]=[{id_lunch: '',desc_lunch:''},
                     {id_lunch: 'TP1',desc_lunch:'Normale'},
                     {id_lunch: 'TP2',desc_lunch:'Senza carne'},
                     {id_lunch: 'TP3',desc_lunch:'Senza carne di maiale'},
                     {id_lunch: '14/1020',desc_lunch:'14/1020'}
  ];

And this is the html code of the column

<ng-container matColumnDef="pasto">
      <th mat-header-cell *matHeaderCellDef> Descrizione Pasto</th>
      <td mat-cell  *matCellDef="let studente">
        <mat-form-field>
          <mat-select [disabled]="studente.isAbsent || studente.isGuest" (selectionChange)="checkCheckPastovalue($event, studente)" panelClass="example-panel-dark-blue">
            <mat-option *ngFor="let cust of lunch"
                        [value]="cust"> {{studente.isAbsent || studente.isGuest ?  '': cust.desc_lunch}}
            </mat-option>
          </mat-select>
        </mat-form-field>
      </td>
    </ng-container>

I have an external json from db with set or empty values

    {
                      "idStudenti": 1,
                        "nome": "John",
                        "cognome": "Doe",
                        "isChecked": true,
                        "CodLunch": "TP1",
                        "DescLunch": "Normale",
                        "isGuest": false,
                        "hostSchool": "",
                        "isAbsent": false
                    },
                    {
                        "idStudenti": 2,
                        "nome": "Giada",
                        "cognome": "Doe",
                        "isChecked": false,
                        "CodLunch": "",
                        "DescLunch": "",
                        "isGuest": false,
                        "hostSchool": "",
                        "isAbsent": false
                    }

How can I display the current value of the json on the mat-select?

How does gql from graphql-tag works? [duplicate]

I am using graphql-tag package for graphql syntax. The syntax below I can’t understand if it is a valid javascript code.

How does it work? (Just surface level knowledge not the whole package’s working)

import gql from 'graphql-tag';

const query = gql`
  {
    user(id: 5) {
      firstName
      lastName
    }
  }

Below is the implementation of the gql from the package.

function gql(/* arguments */) {
  var args = Array.prototype.slice.call(arguments);

  var literals = args[0];

  // We always get literals[0] and then matching post literals for each arg given
  var result = literals[0];

  for (var i = 1; i < args.length; i++) {
    if (args[i] && args[i].kind && args[i].kind === 'Document') {
      result += args[i].loc.source.body;
    } else {
      result += args[i];
    }

    result += literals[i];
  }

  return parseDocument(result);
}

It seems it is a function. A function needs arguments that we pass inside parenthesis. But, gql doesn’t have any? How So?

TypeError: movieList.map is not a function, what is wrong?

import React, { useEffect, useState } from 'react';
import tmdb from './tmdb'; 
import MovieRow from './components/MovieRow';

export default () => {
  const [movieList, setMovieList] = useState([]);
  useEffect(() => {
    const loadAll = async() => {
      //Pegando a lista total
      let list = await tmdb.getHomeList();
      setMovieList(list);
    }
    loadAll();
  }, []);
  return(
    <div className="page">
      <section classname="lists">
        {movieList.map((item, key) => (
          <MovieRow/>
        ))}
      </section>
    </div>
  );
}

I’m building a clone of Netflix using React, but I’m getting this error midway into my project, can someone help me out?

Dynamic creation Table in postgresQL, node.js sequelize

I’m developing a web app which watches about crypto-coins currency. So now, i’m developing a server and DB, so:
I’ve got 2 main models:
Current Coins – the list of current currency of crypto coins
and CoinInfo – the table which has detailed coin currency for all period
So I use One to Many connection for models, but i want to have the next:
I refresh my Current currency every 5 minutes, so data in this Table always refresh, so i want that on each refresh, the data which will be updated store in other table (for each coin) But i don’t how to do it:

  const sequelize = require("../DB/db");
const DataTypes = require("sequelize");
const CoinDetalInfo = require("./CoinDetalnfo");

const CurrencyList = sequelize.define(
  "Coin",
  {
    id: {
      type: DataTypes.STRING,
      primaryKey: true,
      unique: true,
    },
    name: {
      type: DataTypes.STRING,
    },
    symbol: {
      type: DataTypes.STRING,
    },
    image: {
      type: DataTypes.STRING,
    },
    current_price: {
      type: DataTypes.FLOAT,
    },
    price_change_percentage_24h: {
      type: DataTypes.FLOAT,
    },
    mkt_cap: {
      type: DataTypes.FLOAT,
    },
    total_volume: {
      type: DataTypes.FLOAT,
    },
  },
  { timestamps: true }
);

CurrencyList.hasMany(CoinDetalInfo, {
  onDelete: "cascade",
});

module.exports = CurrencyList;

const sequelize = require("../DB/db");
const DataTypes = require("sequelize");

const CoinDetalInfo = sequelize.define("CoinInfo", {
  price: {
    type: DataTypes.FLOAT,
  },
  mkt_cap: {
    type: DataTypes.FLOAT,
  },
  total_volume: {
    type: DataTypes.FLOAT,
  },
});


module.exports = CoinDetalInfo

And code which fill my First table

const axios = require("axios");
const CurrencyList = require("../Models/CurrencyList");
const URLs = require("../Configs/URLs");

module.exports = {
  FillDataBaseWithCurrencyListInfo: async (req, res) => {
    const collectionCurrencies = await axios.get(
      URLs.CoinGeckoURL,
      (response) => {
        return response;
      }
    );
    const mappedCollectionCurrencies = collectionCurrencies.data.map(
      ({
        id,
        symbol,
        name,
        image,
        market_cap,
        current_price,
        price_change_percentage_24h,
        total_volume,
      }) => ({
        id,
        symbol,
        name,
        image,
        market_cap,
        current_price,
        price_change_percentage_24h,
        total_volume,
      })
    );

    mappedCollectionCurrencies.map(async (item, index) => {
      const found = await CurrencyList.findOne({
        where: { id: item.id },
      });

      if (!found) {
        await CurrencyList.create({
          id: item.id,
          name: item.name,
          symbol: item.symbol,
          image: item.image,
          mkt_cap: item.market_cap,
          current_price: item.current_price,
          price_change_percentage_24h: item.price_change_percentage_24h,
          total_volume: item.total_volume,
        });
      } else {
        await CurrencyList.update(
          {
            name: item.name,
            symbol: item.symbol,
            image: item.image,
            mkt_cap: item.market_cap,
            current_price: item.current_price,
            price_change_percentage_24h: item.price_change_percentage_24h,
            total_volume: item.total_volume,
          },
          {
            where: {
              id: item.id,
            },
          }
        );
      }
    });
    res.send(mappedCollectionCurrencies);
  },
  GetCurrencyListInfoFromDataBase: async (req, res) => {
    const CurrencyListCollection = await CurrencyList.findAll();
    res.json(CurrencyListCollection);
  },
};

Filter Datasource by multiple Values

I have a table with datasource(data) with columns 1-8 but i want to search a value only in columns 1,2,3,4 and return the filteredData. The following code doesn’t work and i cant seem to find why.

What i want to do is: when the user enters a keyword, it should search the table data source( array of objects) but only within 4 columns and return the filtered data.

const filterUserSearch = (data, searchState) => {
  const searchIndex = ["col1", "col2", "col3", "col4"];
  let filteredData = null;
  if (searchState) {
    const lowercasedFilter = searchState?.toLowerCase();
    filteredData = data.filter((item) => {
      return searchIndex.forEach((index) => {
        item[index].toLowerCase().includes(lowercasedFilter);
      });
    });
    console.log("filteredData", filteredData);
  } else {
    return data;
  }
  return filteredData;
};

Custom global components not applying style in Nuxt Js

I have built some components such as buttons and I want to use and reuse just about everywhere in my site.

I have already create plugins

Object.entries(components).forEach((([name, component]) => {
  Vue.component(name, component)
}))

and registered in nuxt.config

plugins [
'@/plugins/components'
]
<style lang="scss">
  .btn__container {
    border-radius: '5px';
    border: '1px solid red';
    background-color: 'red';
  }
</style>

but then when i call the component it doesnt apply the style

<v-button>button</v-button>

i am trying to inspect my custom button element and it got strikethrough i dunno why
enter image description here