Enter key in android keyboard also in android-webview not working for input in JavaScript

I have input type text in my html inside form tag. Key down event of JavaScript is not executing when I press enter key of mobile devices. In computer keyboard it’s working fine. When I put this input not inside form tag it’s working fine in mobile devices.
I tried keypress, key down, key up events.

$("body").on("keydown", "input, select, textarea, button", function(e) {
    var self = $(this),
        form = self.parents("form:eq(0)"),
        focusable,
        next,
        id;
    id = $(this).closest("tr").parent().parent().attr("id");


    if (
        e.keyCode == 13 ||
        e.keyCode == 9 ||
        e.key == "Next" ||
        e.key == "Go"
    ) {

        focusable = form
            .find('input[type!="checkbox"],a,select,button,textarea')
            .filter(":visible:not([readonly]):enabled");



        if (
            (this.type == "text" ||
                this.type == "tel" ||
                this.type == "email" ||
                this.type == "time" ||
                this.type == "select-one" ||
                this.type == "number" ||
                this.type == "date") &&
            $(this).attr("tabindex") < 700
        ) {

            previous_elem = $(this);
            valid_func_agets(this, e);
            return false;
        }
    }
})

Note:this inputs is under one div and am rewriting entire html when some events executes.

Issues with prompt and function

I have a page where a user is to input their email and password. Upon entering the information correctly, the user will click on the Submit button then see a prompt that asks if they are sure with proceeding, if the user types in “Yes”, the data in the email/password fields will be cleared. If they answer “No” then the information will still be there. I can’t seem to figure this out even though it seems very simple. Keep in mine please I am still a novice to HTML/Javascript.

Code for “Submit” button:

<button onclick="Submit()">Submit</button>

Code for function that decides whether the information is to be cleared or not:
function Submit() {

var ques = window.prompt("Are you sure?");
      if ((ques = "Yes")) {
        form.style.display = "none";
      } else {
      }
    }

How to add multiple values to an object ID later in mongodb

I am trying to add values inside the object id. Object id is created before but I want to add more values in the future inside the object ID.

This is my MongoDB database:

[{
        label: 'colors',
        options: [
            { label: 'Black', value: 1 },
            { label: 'Green', value: 2 },
        ]
    }]

My expectation is when I will send a new object it will insert a new object inside the options property. suppose my new object is {label: ‘blue’, value: 3} it will be like this:

[{
        label: 'colors',
        object: [
            { label: 'Black', value: 1 },
            { label: 'Green', value: 2 },
            {label: 'blue', value: 3} 
        ]
    },

I am trying this way, I am storing the previous data value, inserting a new value, and sending it to the backend. but it’s not working. is there any different way I can fix it?

  const addAttributeValues = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault()

        if (label === '') {
            return
        }

        const slug = label?.split(' ').join('-')
        const options: any = [] // previous value storing 
        let update; // inserting previous and new value

        if (attr.options) {    // checking if the previous data has options property or not
            options.push(attr.options)
            const length: any = options.length
            update = { options: { ...options, [length]: { label, slug } }, id: attr._id }
        }

        else {     // if option property doesn't exist it means no new value added before 
            update = { options: { label, slug }, id: attr._id }
        }


        fetch('http://localhost:5000/dashboard/attributes', {
            method: 'PUT',
            headers: { 'content-type': 'application/json' },
            body: JSON.stringify(update)
        })
            .then(res => res.json())
            .then(data => {
                setLabel('')
                setIfShouldUpdate(true)
            })

    }

Backend API, I use put method, I don’t know is there any other method for inserting new values in the future.

 // ADD ATTRIBUTES VALUE
        app.put('/dashboard/attributes/', async (req, res) => {
            const { options, id } = req.body
        
            const filter = { _id: objectId(id) }
    
            const updateDoc = {
                $set: {
                    options: options
                },
            };

            const result = await unityMartAttributes.updateOne(filter, updateDoc);
            res.json(result)
            console.log(result);
        })

How to access a data member or class in an included javascript in odoo?

I’m new to odoo, currently I’m trying to adding a data filter in account_report module, and it made me to modify the js file in odoo (which is I’m not well versed). I’ve tried to modify the source code js and it worked, but I didn’t allowed to modify the source code, so I had to inherit or override the js from a custom module. But I kept having trouble to access the data member or the class (I’m not really sure what it is) because part of my code need to declare that class/data member from the parent/included class, can u guys guide me how to access or get the class/data member? thanks in advance

here is my Code:

odoo.define('nrs_de_financial_report_currency.account_report', function (require) {
'use strict';
    var account_report = require('account_reports.account_report');
    var core = require('web.core');
    var datepicker = require('web.datepicker');
    var QWeb = core.qweb;
    var _t = core._t;

    account_report.include({
        unfold: function(line) {
            var self = this;            
            var parent_result = this._super.apply(this, arguments);
            var line_id = line.data('id');
            .
            .
            .
        render_searchview_buttons: function() {
            var self = this;
            // bind searchview buttons/filter to the correct actions
            var $datetimepickers = this.$searchview_buttons.find('.js_account_reports_datetimepicker');
            .
            .
            .
                   

                if (!_.isEmpty(fields)) {
                        //this is the trouble part, when I must declare the new M2MFilters
                        this.M2MFilters = new M2MFilters(this, fields);
                        this.M2MFilters.appendTo(this.$searchview_buttons.find('.js_account_partner_m2m'));
                    }
                } else {
                    this.$searchview_buttons.find('.js_account_partner_m2m').append(this.M2MFilters.$el);
                }

svelte-codejar “ctx[1] is not a constructor”

I am using svelte and svelte-codejar with prismjs and I am getting this error Uncaught TypeError: ctx[1] is not a constructor Here’s my code

<script context="module">
    import Prism from "prismjs"
      const highlight = (code, syntax) => Prism.highlight(code, Prism.languages[syntax], syntax);
    </script>
    
    <script>
      import "prismjs/themes/prism-tomorrow.css";
      import {getContext} from "svelte";
      import {DEFAULT_CODE_SAMPLE, DEFAULT_CODE_SYNTAX} from "./_sample";
      const store = getContext("CodeJar");
      const options = getContext("options");
      const CodeJar = $store;
      
    </script> 

any help would be great I also get Uncaught TypeError: $options is undefined if this line is added $: ({withLineNumbers = false} = $options);

Fake path after uploading file in next js – mysql

I am trying to upload file and store in Mysql DB

i can upload but when its stored in DB the link will be like this:

C:fakepathblank.pdf

am i doing something wrong?

here is my code:
Pages folder:

export default function AddShopForm() {



const [product, setProduct] = useState({
file: "",
});

const router = useRouter();
const handleChange = ({ target: { name, value } }) => {
setProduct({ ...product, [name]: value });
};

const handleSubmit = async (e) => {
e.preventDefault();
if (router.query.id) {
  await axios.put(`/api/shops/${router.query.id}`, product);
  router.push("/dashboard/shop");
} else {
  await axios.post("/api/shops", product);
  router.push("/dashboard/shop");
  swal("The shop has been added successfully");
}
};

useEffect(() => {
const getProductById = async () => {
  const { data } = await axios.get(`/api/shops/${router.query.id}`);
  setProduct(data);
};

if (router.query.id) {
  getProductById(router.query.id);
  console.log("pepeID");
}
}, [router.query.id]);
return (
<>

<div className="w-full max-w-xs">
  <form
    onSubmit={handleSubmit}
    className="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4"
    enctype="multipart/form-data"
  >
    

<label htmlFor="file">file</label>
<input
      type="file"
      name="file"
      onChange={handleChange}
      className="shadow border rounded py-2 px-3 text-gray-700"
      value={product.file}
    />

    <button className="bg-blue-500 hover:bg-blue-700 py-2 px-4 rounded focus:outline-none focus:shadow-outline font-bold text-white">
      Save file
    </button>
  </form>
</div>

);
}

API index:

import { pool } from "../../../config/db";
export default async function handler(req, res) {
const { method } = req;

switch (method) {
case "GET":
  return await getProdcuts(req, res);
case "POST":
  return await saveProduct(req, res);

default:
  break;
}
}

const saveProduct = async (req, res) => {
const { file } = req.body;
const [result] = await pool.query("INSERT INTO product SET ?", {
file 
});
console.log(result);
return res
.status(200)
.json({ file,
    id: result.insertId });
};

const getProdcuts = async (req, res) => {
const [result] = await pool.query("SELECT * FROM product;");
return res.status(200).json(result);
};

[id]:

import { pool } from "../../../config/db";

export default async function handler(req, res) {
switch (req.method) {
case "GET":
  return await getProdcutById(req, res);
case "DELETE":
  return await deleteProduct(req, res);
case "PUT":
  return await updateProduct(req, res);
default:
  break;
}
}

const getProdcutById = async (req, res) => {
const { id } = req.query;
const [result] = await pool.query("SELECT * FROM product WHERE id = ?", [id]);

return res.status(200).json(result[0]);
};

const deleteProduct = async (req, res) => {
const { id } = req.query;
const result = await pool.query("DELETE  FROM product WHERE id = ?", [id]);

return res.status(204).json();
};

const updateProduct = async (req, res) => {
const { id } = req.query;
const { file } = req.body;

//*Para Actualizar tengo que enviar dos cosas, el id y el body
try {
await pool.query(
  "UPDATE product SET business_type= ?, shop_name = ?,company_register_name = ? WHERE id = ?",
  [file , id]
);
return res.status(204).json();
} catch (error) {
console.log(error.message);
}
};

i was able to store other kind of data in db without any problem but whenever i upload a file i will get Fakepath

i am new to nextjs and still learning, i searched online but still wasn’t able to find an answer

Can’t access data from miragejs and redux

It’s the first time i use miragejs and maybe i did something wrong,but in console i get my data which i need to be in a sort of time line dynamically. I created the redux slice,async thunk,and when i try to access the state i get get this erro in console TypeError: Cannot read properties of undefined (reading ‘educationList’) And the app doesnt work. If i put the data as a prop from component,it works,but with redux thunk it doesnt.. Could you tell me what i’m doing wrong please?
Here is my mirage server:

import { createServer,Model } from "miragejs"

export const makeServer =({ environment = 'test' } = {})  => {
    let server = createServer({
      environment,
        models: {
          educations: Model,
         skills:Model
        },

        seeds(server) {
            server.create("education", { date: 2001, title: "Title 0", text: "Elit voluptate ad nostrud laboris. Elit incididunt mollit enim enim id id laboris dolore et et mollit. Mollit adipisicing ullamco exercitation ullamco proident aute enim nisi. Dolore eu fugiat consectetur nulla sunt Lorem ex ad. Anim eiusmod do tempor fugiat minim do aliqua amet ex dolore velit.rn" });
            server.create("education", { date: 2000, title: "Title 1", text: "Et irure culpa ad proident labore excepteur elit dolore. Quis commodo elit culpa eiusmod dolor proident non commodo excepteur aute duis duis eu fugiat. Eu duis occaecat nulla eiusmod non esse cillum est aute elit amet cillum commodo.rn" });
            server.create("education", { date: 2012, title: "Title 2", text: "Labore esse tempor nisi non mollit enim elit ullamco veniam elit duis nostrud. Enim pariatur ullamco dolor eu sunt ad velit aute eiusmod aliquip voluptate. Velit magna labore eiusmod eiusmod labore amet eiusmod. In duis eiusmod commodo duis. Exercitation Lorem sint do aliquip veniam duis elit quis culpa irure quis nulla. Reprehenderit fugiat amet sint commodo ex.rn" });
          },
    
        routes() {
            //this.namespace = 'api/educations';
            this.get('api/educations', (schema, request) => {
              return schema.educations.all();
            });

            // this.namespace = 'api/skills';
            this.get('api/skills', (schema, request) => {
              return schema.skills.all();
            });
    

          this.post('api/skills', (schema, request) => {
            let attrs = JSON.parse(request.requestBody);
            return schema.skills.create(attrs);
          });
        },
      })
      return server;
    }  

redux store:

import { createStore, combineReducers, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension'
import { persistStore, persistReducer } from 'redux-persist'
import { toggleButtonReducer } from './reducers/toggleButtonReducer'
import storage from 'redux-persist/lib/storage'
import thunk from 'redux-thunk'
import { postSlice } from '../features/education/educationSlice';

const rootReducer = combineReducers({
    visibilityState: toggleButtonReducer,
    educationState: postSlice,
})

const persistConfig = {
    key: 'root',
    storage,
}

const persistedReducer = persistReducer(persistConfig, rootReducer)

export const store = createStore(persistedReducer, composeWithDevTools(applyMiddleware(thunk)))

export const persistor = persistStore(store)

educationSlice :

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'

const initialState = {
    educationList: []
}


export const getEducation = createAsyncThunk(
    'educations/getEducations',
    async (_, { rejectWithValue, dispatch }) => {
        const res = await axios.get('api/educations')
        dispatch(setEducations(res.data))
        console.log(res.data)
    })


export const postSlice = createSlice({
    name: 'educations',
    initialState,
    reducers: {
        setEducations: (state, action) => {
            state.educationList = action.payload
        },
    },
    extraReducers:{
        [getEducation.fulfilled]:()=> console.log('fullfiled'),
        [getEducation.pending]:()=>console.log('fullfiled'),
        [getEducation.rejected]:() =>console.log('rejected'),
    },
})

export const {setEducations} = postSlice.actions
export default postSlice.reducer;

And the component were i need data:

import '../../assets/styles/css/TimeLine/base.css'
import { useDispatch } from 'react-redux'
import { getEducation } from '../../features/education/educationSlice'
import { store } from '../../store'
import { useSelector } from 'react-redux'

const TimeLine = () => {

const dispatch = useDispatch()
dispatch(getEducation())
const data = useSelector(state => state.educationState.educationList)

    return (
        <>
            <section id='timeLine'>
                <h1 className='educationSection'>Education</h1>
                <div id="timeline" className='timelineWrapper'>
                    {data.map((info) => (
                        <div className="timeline-item" key={info.id}>
                            <span className="timeline-icon">
                                <span>&nbsp;&nbsp;</span>
                                <span className="year">{info.date}</span>
                            </span>
                            <div className='timeline-content'>
                                <h2>{info.title}</h2>
                                <p>{info.text}</p>
                            </div>
                        </div>
                    ))}
                </div>
            </section>
        </>
    )
}

export default TimeLine  

This is what i have in console:
enter image description here

but can’t acces the data.. please help,i’m stuck.. thanks in advance!

If JavaScript is disabled in developer tools, I want to run noscript on the screen immediately

If JavaScript is disabled in developer tools, I want to run noscript on the screen immediately.

<noscript> this page is wrong </noscript>

If you disable JavaScript in developer tools and go to another page, noscript is applied.
I want the noscript content to be applied immediately when JavaScript is disabled, but is there any way?

Or is there anything else I can do to disable javascript mode?

Jest mock jsonwebtoken sign : NestJs

I’m trying to write unit test for my authenticateUser method.In side that method i’m generating private key signed jwt token and return to the user.But my signToken method seem not mocked properly.it return Promise {}.

userService.ts

  async authenticateUser(authDto: AuthDTO): Promise<AuthResponse> {
  
  const formatedMobile = this.commonHelper.formatMobile(
        decodedIdToken.Mobile,
      );
      
    const userData = await this.userRepository.findOne({
        msisdn: formatedMobile,
      });
  if (!userData) {
        //save user info
        const user = new UserEntity();
        user.firstName = decodedIdToken['first_name'];
        user.lastName = decodedIdToken['last_name'];
        user.msisdn = formatedMobile;
        await this.userRepository.save(user);
      }
    const jwtPayload={createdTime: moment(),msisdn: formatedMobile}
    
    const jwtToken = this.commonHelper.signToken(jwtPayload);
    
     return new AuthResponse(
        HttpStatus.OK,
        STRING.SUCCESS,
        `${STRING.USER} ${STRING.AUTHENTICATE} ${STRING.SUCCESS}`,
        {jwtToken},
      );
  }

userService.specs.ts

  it('authenticateUser should return success response (User Exist)', async () => {
    const mockJWTToken = {
    jwtToken:"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NDgyNjIzMDYsImRhdGEiOnsiY3JlY"
    }
    const mockAuthBody = { authCode: 'c79da50f-4eb1',platform:'MOBILE' };
    const mockSuccessResponse = new AuthResponse(
      HttpStatus.OK,
      STRING.SUCCESS,
      `${STRING.USER} ${STRING.AUTHENTICATE} ${STRING.SUCCESS}`,
      mockJWTToken,
    );

    jest.spyOn(commonHelper, 'formatMobile');
    jest.spyOn(userRepository, 'findOne').mockResolvedValueOnce(userEntity);
    jest.spyOn(commonHelper, 'signToken').mockResolvedValueOnce(mockJWTToken);

    expect(await userService.authenticateUser(mockAuthBody)).toEqual(
      mockSuccessResponse,
    );
  });

enter image description here

GraphQL error adding chinese charactor in Gatsbyjs

I’m new Gatsbyjs.
I use this template

https://www.gatsbyjs.com/starters/netlify-templates/gatsby-starter-netlify-cms

I have question about changing gatsby-node.js file and srcpagesindex.md file.

Actually I asked before and Mr.Ferran Buireu helped me. so I could success to change some text and photos.

“gatsby develop” can’t run After adjusting image data

Currently I’m adjusting around LINE 16 of srcpagesindex.md file
text: > I would like to change this sentence.

intro:
  blurbs:
    - image: /img/coffee.png
      text: >
        日本語を入力したい I would like to change this sentence.
        

I use Japanese sentence and Chinese characters. When I save the file then run gatsby develop Many error show up such as below.

There was an error in your GraphQL query:
Field “image” must not have a selection since type “String” has no
subfields.

but I can see http://localhost:8000/ but with this error message.
And sentence are not changing.
enter image description here

I know there are problem but I tried to deploy at Netlify the sentence are changed.

I searched solution and tried that gatsby-node.js file non changing save(type space save and delete it and save again).

And restart gatsby develop but it doesn’t work.

Could someone teach me solution please?

Someone at the company I work for clicked on a phishing email attachment. This opens up a link in the browser [closed]

Someone at the company I work for clicked on a phishing email attachment. We here in the IT department are extremely concerned about what this may have done to our systems. I will be including source code from the website here in hopes someone may be able to provide a good understanding of what it might have done. Here’s the source code
https://drive.google.com/file/d/1eXcVp_pw9ZFC-BcK3yrnWQ0iRDpUqPhv/view

Cannot Read properties of undefined React. Log only works on object

I’m currently trying to create a weather website using weatherapi, but I’m running into a problem. If I log the object of location there’s no error, but if I try to log anything deeper than that object, like the name of the city it cannot read properties of undefined. If I comment out the log when it’s using the name of the city, then uncomment it again and don’t reload the page, then it will log the name of the city without error.

import React from 'react';
import './index.css';
import Navbar from "./components/Navbar"
import {useState} from "react"
import Weather from './components/Weather';


function App() {
  const [inputData, setInputData] = useState({})
  const [currentWeather, setCurrentWeather] = useState([])
  const [loc, setLoc] = useState({loc:"Arlington"})
  let apiKey = "7ab98e97faa64c4d8b4104902222202"
  // console.log("Location: "+ loc.loc)

  React.useEffect(() =>{///Finds weather data of certain location
    console.log(loc.loc)
    fetch(`https://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${loc.loc}&aqi=no`)
    .then(res => {
      if(res.ok){
        return res.json()
      }
    })

    .then(data => {
      if(data !=null){//Only change currentWeather when there is data for it
        setCurrentWeather(data)
      }else{
        alert(`${loc.loc} was not found`)
      }
    })
  }, [loc])

  React.useEffect(() =>{///Finds locations with search bar
    fetch(`https://api.weatherapi.com/v1/search.json?key=${apiKey}&q=${loc.loc}&aqi=no`)
    .then(res => res.json())
    .then(data => {
      if(data.loc == null){
      }else{
        setLoc(data)
      }
    })
  }, [])

  
  //console.log(currentWeather.location.name)
  

  return (
    <div className="App">
      <Navbar inputData={inputData} setLoc={setLoc} setInputData={setInputData}/>
      <Weather currentWeather={currentWeather}/>
    </div>
  );
}

export default App;


Any way to execute javascript to modify the dom of website using python

Any way to execute javascript to modify the dom of website(that you do manually by using inspect element) and fill in forms etc using python. Only one I saw was selenium webdriver execute script but I don’t want to use it because it is very slow. Any alternatives I would prefer directly in browser opposed to using apps like chromedriver as a medium.

 Windows 7 Python 3.8.8