Triggering submit event after change when uploading image on Yii2 framework

I am trying to save an image type file by using jquery to trigger the submit. I encountered an issue where it triggers even when the change event is not done.

View create.php:

<?php yiibootstrap4ActiveForm::begin([
    'options' => [
        'enctype' => 'multipart/form-data',
        'id' => 'dynamic-form'
    ]
]) ?>

<button class="btn btn-primary btn-file">
    Select Thumbnail
    <input type="file" id="recipeThumbnail" name="recipe">
</button>

<?php yiibootstrap4ActiveForm::end() ?>

In this view, i specify the id to call it in the javascipt file.

Js app.js:

$(function () {
    'use strict';
    $('#recipeThumbnail').change(ev => {
        $(ev.target).closest('form').trigger('submit');
    })
});

From my understanding here, the trigger(‘submit’) should only run when there is a change which in this case an image file is selected. However, i suspect the event is triggered and it caused an error of Attempt to read property “name” on null from the model below on the line $this->name = $this->recipe->name;. My other suspicion would be error in the model but i cant wrap my head around where or how it could be.

Model recipe.php:

public function save($runValidaiton = true, $attributeNames = null)
{
    $isInsert = $this->isNewRecord;
    if ($isInsert) {
        $this->recipe_id = Yii::$app->security->generateRandomString(16);
        $this->name = $this->recipe->name;
    }
    $saved = parent::save($runValidaiton, $attributeNames);
    if (!$saved) {
        return false;
    }
    if ($isInsert) {
        $recipePath = Yii::getAlias('@frontend/web/storage/thumbnail/' . $this->recipe_id . '.jpg');
        if (!is_dir(dirname($recipePath))) {
            FileHelper::createDirectory(dirname($recipePath));
        }
        $this->recipe->saveAs($recipePath);
    }

    return true;
}

Controller RecipeController.php:

public function actionCreate()
{
    $model = new Recipe();

    $model->recipe = UploadedFile::getInstanceByName('recipe');
    
    if ($this->request->isPost) {
        if (Yii::$app->request->isPost && $model->save()) {
            return $this->redirect(['view', 'recipe_id' => $model->recipe_id]);
        }

    } else {
        $model->loadDefaultValues();
    }

    return $this->render('create', [
        'model' => $model,
    ]);
}

I hope i explained this well. Is this error actually caused by the js or something else and any insight on this issue is much appreciated:D

How can I apply css to the child tag from component

<ButtonAtom></ButtonAtom>

this is the button components that I made.

<template>
 <div>
  <button class="px-2 py-1" :class="[borderRadius, backgroundColor]">
    <slot />
  </button>
 <div>
</template>

and this is the html tag inside the components.

If I add css to the <ButtonAtom> like <ButtonAtom color="white">

color connects to the root tag which is <div>

the point is if I try to connect the css to <button>.

Is there any ways to connect to <button> without deleting the root html <div>

P.S this is vue3.

set maxlength value dynamically in html

I have input field, with maxlength = 6 and ng-pattern="/^[0-9]{1,6}$/" accepting only numeric values.
On on-blur event I’m formatting the 6 digit code (“123456”) to “12-34-56” and browser remembers the formatted value i.e. 12-34-56

next time when I try to auto fill the field using remembered data by browser,
enter image description here
it only fill 4 digits.
How can I fill all the 6 digits. I tried to set the maxlength = 8 when text contains -, but it didn’t help.

Why fadeIn effect doesn’t work on my interactive town map?

I have “town map”, where I have (of course) houses and idea is that, when you hover over the house there is a gradient silhouette appears. I’m trying to build hitbox system, because origin image’s hitbox don’t fit properly my background.

I made the hitbox system in native JS, there it is:

blocks.forEach((block, BlockIndex) => {
    block.addEventListener('mouseover', (event) => {
        if(event.target.classList.contains('hitbox')){
            images.forEach((image, ImageIndex) => {
                if(BlockIndex == ImageIndex) {
                image.classList.add('hovered')
                }
            })
        }
    })
    block.addEventListener('mouseout', () => {
        images.forEach((image, ImageIndex) => {
            if(BlockIndex == ImageIndex) {
                image.classList.remove('hovered')
            }
        })
    })
})

But this code is too long and reverse animation doesn’t have transition. I mean, when you get your mouse off the house, silhouette disappears too quickly, without any animation. But in CSS I have “transition: .3s”

So, I wanted to use Jquery, because of “.fadeIn()” and “.fadeOut()”.
I wrote a code, and it’s not working. There it is:

$(blocks).each((block, BlockIndex) => {
    $(block).hover((event) => {
        if(event.target.hasClass('hitbox')) {
            $(images).each((image, ImageIndex) => {
                if(BlockIndex == ImageIndex) {
                    $(image).fadeIn('slow')
                }
            })
        }
    })
})

Sorry for stupid question, but I’m newbie in Jquery. Of course I can make reverse animation through native JS, but the code will be too long. Could you help me? What I did wrong and what I have to read to fix it? Can I use part of jquery inside my native JS? Like:

blocks.forEach((block, BlockIndex) => {
    block.addEventListener('mouseover', (event) => {
        if(event.target.classList.contains('hitbox')){
            images.forEach((image, ImageIndex) => {
                if(BlockIndex == ImageIndex) {
                $(image).fadeIn('slow')
                }
            })
        }
    })

Typescript – reference same class

class MyClass{

  someMethod(): MyClass{
     return new MyClass();
  }

}

How to reference current class, without explicitly passing the name?

Something like this:

class MyClass{

  someMethod(): self{
     return new self();
  }

}

obviously that doesn’t work, but you get the idea:)

Jest – Can’t get calls of Express Response.send()

i’m currently trying to implement some tests for my express controller, but I can’t get jest to recognize my calls of res.send() or anything else. I’m not sure if it’s caused by my asynchronous code and Promises but the documentation didn’t help my as good as I hoped it does. Maybe some of you geniuses can see my issue here.

That’s my code:

tab.controller.js

exports.createTab = (req, res) => {
  if (isValidTabConfig(req.body)) {
    var tab = saveNewTabToDb(req.body)
      .then((tab) => {
        addAndUpdateTabData(tab);
        res.send(tab);
      })
      .catch((err) => {
        res.status(500).send({ message: err });
      });
  } else res.status(422).send({ message: "Invalid tab config" });
};

tabController.test.js

describe("creation test", () => {
  const dbman = new DBManager();

  afterAll(() => dbman.stop());
  beforeAll(() => dbman.start());
  afterEach(() => dbman.cleanup());

  it("creates a new tab", async () => {
    const tabRequest = {
      body: getTabData(),
    };

    const res = mockResponse();

    expect(
      async () => await tabController.createTab(tabRequest, res)
    ).not.toThrow();
    expect(res.send).toHaveBeenCalledTimes(1);
  });
});

function mockResponse() {
  return {
    status: jest.fn().mockReturnThis(),
    send: jest.fn().mockReturnThis(),
  };
}

Much thanks in advance!

Why I am not able to change the state of my react component the second time and got no error

enter image description here

THe Github repo https://github.com/sarangkkl/gaurav_test

I have a currency dropdown menu when click appear and when click outside it disappears also when click on the same place it should disappears but when i am clicking on that button that function runs but the state does not change which is hiding that

//CurrencyDropwon.js

import React, { Component } from "react";
import { SelectWrapper,NavbarItem,CurrencyBtn } from "./CurrencyDropdownStyle";
import { getCurrency } from "../../../utls/MakeQuery";
import { connect } from 'react-redux'
import { SelectInput } from '../../';
import { toggleCurrency } from '../../../store/reducers/currencyReducers'

export class CurrencyDropdown extends Component {
  constructor() {
    super();
    this.state = {
      currency: [],
      isComponentVisible: true,
      isActiveCurrency:false,
      ref: React.createRef(null),
    };
  }

  handleHideDropdown = (event) => {
    if (event.key === 'Escape') {
      this.setState({ isComponentVisible: false });
    }
  }

  handleClickOutside = (event) => {
    if (this.state.ref.current && !this.state.ref.current.contains(event.target)) {
      this.setState({
        isActiveCurrency:!this.state.isActiveCurrency
      })
      
    }
  }

  componentDidMount() {
    getCurrency()
      .then((res) => {
        this.setState({
          currency: res.data.currencies,
        });
        this.props.toggleCurrency("USD+$");
      })
      .catch((err) => {
        console.log(err);
      });

      document.addEventListener('keydown', this.handleHideDropdown, true);
      document.addEventListener('click', this.handleClickOutside, true);
  }
  componentWillUnmount(){
    document.removeEventListener('keydown', this.handleHideDropdown, true);
    document.removeEventListener('click', this.handleClickOutside, true);
  }
  // Function That will handle the change of the currency in the state(●'◡'●)
  // Function that will show the currency selector
  
  
  render() {
    const handleCurrencyActive = () =>{
      console.log("handleCurrencyActive CLICKED");
      this.setState({
        isActiveCurrency:!this.state.isActiveCurrency
      })
    }
    
    return <>
          <NavbarItem>
              <CurrencyBtn onClick={()=>{handleCurrencyActive()}}>
                 {this.props.currencySymbol}    {this.state.isActiveCurrency ? "⮝":"⮟"}
              </CurrencyBtn>
                  {this.state.isActiveCurrency && <SelectWrapper ref={this.state.ref}>
                {this.state.currency ? this.state.currency.map((item,index)=>(
                        <SelectInput key={index} value={`${item.label}+${item.symbol}`} label={`${item.symbol} ${item.label}`}/>
                    )):""}
              </SelectWrapper> }
          </NavbarItem>

    </>;
  }
}
const  mapStateToProps = (state) =>{
  return {
      currencyState:state.currency.currencyState,
      currencySymbol:state.currency.currencySymbol,
      cart:state.cart.cart.cartItems
  }
}
export default connect(mapStateToProps,{toggleCurrency}) (CurrencyDropdown);

My Questions?
Why I am facing this error the task is straight forward that the state should change and that dropwdown should hide

how to Connect ember with java servlet

I’m new to ember js and trying to connect ember js and java servlet to retrieve data from the database via SQL. I don’t know how to make requests via network and receive data. can anyone explain how to establish a connection between java-servlet and ember js

Uncaught TypeError: Cannot read properties of null (reading ‘getElementsByClassName’) at hamburgerMenu [duplicate]

i have changed the jquery from 1.10 to 3.6 and i face this error on console :
Uncaught TypeError: Cannot read properties of null (reading ‘getElementsByClassName’) at hamburgerMenu.
i don’t know what im doing wrong 🙁

 <script>            
                                
                             function hamburgerMenu() {
                                var parents=document.getElementsByClassName('menu-item-has-children').length;
                                let t=0;
                                
                                while(t<parents){
                                    let butonat =document.getElementById("butoni");
                                   document.getElementsByClassName("menu-item-has-children")[t].insertBefore(butonat.cloneNode(true),document.getElementsByClassName("menu-item-has-children")[t].firstElementChild.nextSibling );
                                   t++;
                                      }
                                    
                                    var li_elem=document.getElementById('menu-top-left').getElementsByClassName('menu-item').length; 
                                    document.getElementById('menu-top-left').classList.add("primary-menu");
                                    document.getElementById('menu-top-left').setAttribute('id', 'menu-primary-extended-navigation');
                                    var cnt = $(".custom-menu-class").contents();
                                    $(".custom-menu-class").replaceWith(cnt);
                                    var i=0;
                                            while(i<parents){
                                             document.getElementsByClassName("menu-item-has-children")[i].classList.add("top-level-menu-item"); 
                                             document.getElementsByClassName("dropdown-content")[i].classList.add("sub-menu");      
                                             i++;
                                            }
                                       
                                    $('.primary-menu').children('li').addClass('children');
                                    var $children = $('.children');
                                    for(var i = 0, l = $children.length; i < l; i += 3) {
                                        $children.slice(i, i+3).wrapAll('<ul class="menu primary-menu" ></ul>');
                                           }          
                                }
                        </script>

Get Babel to transpile config files to CommonJS

I have a Nuxt app that I want to test with Jest and I can’t get it to work.
I have a setupFilesAfterEnv property set with a setupTests.ts that imports a translation file. This translations files uses ES6 import/export module syntax but it seems like my current configuration doesn’t work to transpile it.

Isn’t babel-jest supposed to transpile the .js files thanks to the transform property?

setupTests.ts

import { config } from '@vue/test-utils';
import flat from 'flat';
import '@testing-library/jest-dom/extend-expect';
import 'jest-axe/extend-expect';
import frenchTranslations from '~/config/translations/fr-FR';
...

babel.config.json

{
  "presets": ["@babel/preset-env", { "targets": { "node": "current" } }]
}

jest.config.js

module.exports = {
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/$1',
    '^~/(.*)$': '<rootDir>/$1',
    '^vue$': 'vue/dist/vue.common.js',
  },
  moduleFileExtensions: ['ts', 'js', 'vue', 'json'],
  resolver: '<rootDir>/test/integration/resolver.js',
  transform: {
    '^.+\.ts$': 'ts-jest',
    '^.+\.js$': 'babel-jest',
    '^.+\.vue$': '@vue/vue2-jest',
  },
  collectCoverage: true,
  collectCoverageFrom: [
    '<rootDir>/components/**/*.vue',
    '<rootDir>/pages/**/*.vue',
  ],
  testEnvironment: 'jsdom',
  passWithNoTests: true,
  setupFilesAfterEnv: ['<rootDir>/test/integration/setupTests.ts'],
};

/config/translations/fr-FR.js

export default {
 ...
}

Jest output

FAIL  test/integration/components/ui/RegistrationForm.test.ts
  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /my-project/config/translations/fr-FR.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export default {
                                                                                      ^^^^^^

    SyntaxError: Unexpected token 'export'

      1 | import { config } from '@vue/test-utils';
      2 | import flat from 'flat';
      3 | import '@testing-library/jest-dom/extend-expect';
      4 | import 'jest-axe/extend-expect';
    > 5 | import frenchTranslations from '~/config/translations/fr-FR';

      at Runtime.createScriptFromCode (node_modules/.pnpm/[email protected]/node_modules/jest-runtime/build/index.js:1796:14)
      at Object.<anonymous> (test/integration/setupTests.ts:3:1)
      at TestScheduler.scheduleTests (node_modules/.pnpm/@[email protected]/node_modules/@jest/core/build/TestScheduler.js:317:13)

----------------------|---------|----------|---------|---------|-------------------
File                  | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------------------|---------|----------|---------|---------|-------------------
All files             |       0 |        0 |       0 |       0 |
 RegistrationForm.vue |       0 |        0 |       0 |       0 | 1-113
----------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.35 s
Ran all test suites related to changed files.

how to replace string with all possible ways – removing unit productions in context free grammar [closed]

I have a context free grammar like this:

<S> -> a<A><S>c<A><A>b
<A> -> ab | c<A> | <T>
...

so in order to remove A -> T I have to replace A in the right hand side with every possible way like the example below:

"a<A><S>c<A><A>b"

and I want to replace < A > with < T > in a way which results in these strings:

"a<A><S>c<A><A>b",
"a<T><S>c<A><A>b",
"a<A><S>c<T><A>b",
"a<A><S>c<A><T>b",
"a<T><S>c<T><A>b",
"a<T><S>c<A><T>b",
"a<A><S>c<T><T>b",
"a<T><S>c<T><T>b"

PLEASE HELP!

I want the code for simplifying context free grammar in removing unit productions

How to pass data from view file to the controller?

I am using codeigniter-3 framework for developing web application, i have one update form when ever i click on any particular record it’s taking an ID of that particular record and passing to the URL this part is working fine,now i want instead of taking id i want to take all the record data and passed to the controller instead of the url parameters can you give me some idea how to do this one ..?

like this i am taking the id of particular tank but now i want entire object or array of that particular record and passing to the controller instead of the URL parameters.

    <a class="dropdown-item" href="<?php echo base_url(); ?>book/edit_book?book_id=<?php echo $book['book_id']; ?>">Update</a>

controller.php

    $book_id = $this->input->get('book_id',TRUE);
        $url = 'http://local.com/books?book_id='.$book_id;
//rest of my logic based on the URL

module.export not changing variable for other file?

I have two arrays of objects that I am exporting at the end of server.js with module.exports which will be used in another file to display scores, scores.js. My problem occurs when I try and reset these arrays when a new games begins and for some reason some data seems to not update in scores.js whilst others do.

I have been researching and think it has something to do with the way javascript saves objects and I have been trying different ways of deep/shallow cloning however nothing seems to work.

More specifically, there is a property in one of the arrays of objects called playersChoosing which is also an array and is the one that seems not to change even if I completely set the array of objects to an empty one in the server.js file.

Note: This is my first time properly using node.js so could definitely be missing something very basic. Any help is appreciated!

These are examples of the two objects:

Current player definitions [
  { definition: 'maiming; mutilation', playersChoosing: [ 'player4' ] },
  {
    definition: 'blah blah',
    id: 'vIe_bxsTjg4OzFdJAAAB',
    playersChoosing: [],
    choseCorrect: false
  },
  {
    definition: 'whatever',
    id: 'b7lJloolPhLGdrrnAAAD',
    playersChoosing: [ 'player1', 'player2', 'player3' ],
    choseCorrect: true
  },
  {
    definition: 'foo',
    id: 'o7rTbhVp8WllpLTwAAAF',
    playersChoosing: [],
    choseCorrect: false
  },
  {
    definition: 'bar',
    id: 'lMnqOsIzdfQMBWPVAAAH',
    playersChoosing: [],
    choseCorrect: false
  }
]
Game connections [
  {
    id: 'vIe_bxsTjg4OzFdJAAAB',
    nickname: 'player1',
    ready: true,
    score: 2
  },
  {
    id: 'b7lJloolPhLGdrrnAAAD',
    nickname: 'player2',
    ready: true,
    score: 4
  },
  {
    id: 'o7rTbhVp8WllpLTwAAAF',
    nickname: 'player3',
    ready: true,
    score: 1
  },
  {
    id: 'lMnqOsIzdfQMBWPVAAAH',
    nickname: 'player4',
    ready: true,
    score: 1
  }
]

js returning a function from a function call

let [count, setState] = React.useState(0);

  let ChangeState = (isIncrease) => {
    return () => (isIncrease ? setState(count + 1) : setState(count - 1));
  };

  return (
    <div className="container">
      <h1>{count}</h1>
      <button onClick={ChangeState(true)}>+</button>
      <button onClick={ChangeState(false)}>-</button>
    </div>
  );
}

I have this code and I don’t understand why my ChangeState function isn’t run when I call ChangeState(true) or false on the button onclicks I discovered this when finding a way to have a function be callable without running it on init