javascript – use a variable from another function javascript – ‘today is not defined at Object’

I try to get todays date to use it in an URL (concatenation) with a function. But, each time I’ve tried to run it, i have the same error : today is not defined at Object

I tried to declare it with and without var/let/const but the error stays. Does someone have an idea (console.log()) is just to test)?

function GetTDDate() {
  today = new Date();
  var dd = String(today.getDate()).padStart(2, '0');
  var mm = String(today.getMonth() + 1).padStart(2, '0');
  var yyyy = today.getFullYear();

  today = yyyy + '-' + mm + '-' + dd;
  console.log(today);
}

const FetchURL = "https://static.data.gouv.fr/resources/donnees-relatives-aux-personnes-vaccinees-contre-la-covid-19-1/20211221-212503/vacsi-tot-fra-" + today + "-21h25.json"
console.log(FetchURL)

How do you convert an array of objects into an object of object

I am having trouble converting an array of objects into an object of objects for my job. The company API is expecting the data in this format. Any help would be appreciated. Here is an example

Original

const array = [
 {
  type: 'ITEM',
  info: {
   item_id: 'house'
  }
 },
{
  type: 'ITEM',
  info: {
   item_id: 'house'
  }
 }
]

Final

const array = {
 {
  type: 'ITEM',
  info: {
   item_id: 'house'
  }
 },
{
  type: 'ITEM',
  info: {
   item_id: 'house'
  }
 }
}

(1) table mytable has no column named number in “INSERT INTO mytable(number,name,email) VALUES (?,?,?)”

If I delete the line ” “number” + “text” “, the code works.

Error:

E/SQLiteLog: (1) table mytable has no column named number in “INSERT
INTO mytable(number,name,email) VALUES (?,?,?)”

E/SQLiteDatabase: Error inserting number=866454 name=TEST email=TEST

android.database.sqlite.SQLiteException: table mytable has no column
named number (code 1 SQLITE_ERROR): , while compiling: INSERT INTO
mytable(number,name,email) VALUES (?,?,?)

String name = text_name.getText().toString();
String email = text_email.getText().toString();
String number = text_phone.getText().toString();

SQLiteDatabase data_base = dbHelper.getWritableDatabase();

                    ContentValues container = new ContentValues();
                    container.put("name", name);
                    container.put("email", email);
                    container.put("number", number);
                    long rowID = data_base.insert("mytable", null, container);
                    Log.d("Log: ", "row inserted, ID = " + rowID);

AND

 @Override
        public void onCreate(@NonNull SQLiteDatabase db) {
            db.execSQL("create table mytable ("
                    + "id" + "integer primary key autoincrement,"
                    + "name" + "text,"
                    + "email" + "text,"
                    + "number" + "TEXT UNIQUE"
                    + ");");
        }

I am trying to add an active class to my nav bar items on my website when clicked

I want to add the active class to the navbar item that I click on, on my website. In my JS code, it tells the program what class to look under (“nav-item”). Then it tells my program to remove the active class from the current active class, and then add the active class to the class that was clicked. I’m assuming the logic is correct but I most likely missed syntax. I am new to HTML and JS so any help would be greatly appreciated.

HTML Code:

<ul class="navbar-nav">
                    <li class="nav-item"><a class="nav-link js-scroll-trigger active" href="#about">About</a></li>
                    <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#education">Education</a></li>
                    <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#experience">Experience</a></li>
                    <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#skills">Skills</a></li>
                </ul>

JS code:

$('.nav-item').on('click', '.nav-link js-scroll-trigger', function () {
        $('.nav-link js-scroll-trigger active').removeClass('active');
        $(this).addClass('active');
    });

how to detect file size / type while mid-download using axios or other requestor?

I have a scraper that looks for text on sites from a google search. However, occasionally the URLs for search are LARGE files without extension names (i.e. https://myfile.com/myfile/).

I do have a timeout mechanism in place, but by the time it times out, the file has already overloaded the memory. Is there any way to detect a file size or file type while it’s being downloaded?

Here is my request function:

const getHtml = async (url, { timeout = 10000, ...opts } = {}) => {
  const CancelToken = axios.CancelToken
  const source = CancelToken.source()
  try {
    const timeoutId = setTimeout(() => source.cancel('Request cancelled due to timeout'), timeout)
    let site = await axios.get(url, {
      headers: {
        'user-agent': userAgent().toString(),
        connection: 'keep-alive', // self note: Isn't this prohibited on http/2?
      },
      cancelToken: source.token,
      ...opts,
    })
    clearTimeout(timeoutId)
    return site.data
  } catch (err) {
    throw err
  }
}

PS: I’ve seen similar questions, but none had an answer that would apply.

User Auth with React Context API

I’m using React, Axios and Mongoose. Trying to store a user state but am having trouble with the stored state.user object.

When I manually enter values for state.user, the app works properly, however when I actually login from the site, the user object is stored in localStorage but is not being read properly by the app. I noticed I had to remove new ObjectId from the object and also convert the createdAt and lastUpdated dates into strings in order for my static values to work. How can I get around this? Thanks!

Screenshot of localStorage object

context.js

const INITIAL_STATE = {
    user: JSON.parse(localStorage.getItem("user")) || null,
    isFetching: false,
    error: false,
};

export const AuthContext = createContext(INITIAL_STATE);

export const AuthContextProvider = ({ children }) => {
    const [state, dispatch] = useReducer(AuthReducer, INITIAL_STATE);

    useEffect(() => {
        JSON.stringify(localStorage.setItem("user", state.user));
    }, [state.user]);

    return (
        <AuthContext.Provider
            value={{
                user: state.user,
                isFetching: state.isFetching,
                error: state.error,
                dispatch,
            }}
        >
            {children}
        </AuthContext.Provider>
    );
};

reducer.js

const AuthReducer = (state, action) => {
    switch (action.type) {
        case "LOGIN_START":
            return {
                user: null,
                isFetching: true,
                error: false,
            };
        case "LOGIN_SUCCESS":
            return {
                user: action.payload,
                isFetching: false,
                error: false,
            };
        case "LOGIN_FAILURE":
            return {
                user: null,
                isFetching: false,
                error: true,
            };
        case "FOLLOW":
            return {
                ...state,
                user: {
                    ...state.user,
                    following: [...state.user.following, action.payload],
                },
            };
        case "UNFOLLOW":
            return {
                ...state,
                user: {
                    ...state.user,
                    following: state.user.following.filter(
                        (following) => following !== action.payload
                    ),
                },
            };
        default:
            return state;
    }
};
export default AuthReducer;

actions.js

export const LoginStart = (userCredentials) => ({
    type: "LOGIN_START",
});

export const LoginSuccess = (user) => ({
    type: "LOGIN_SUCCESS",
    payload: user,
});

export const LoginFailure = (error) => ({
    type: "LOGIN_FAILURE",
    payload: error,
});

export const Follow = (userId) => ({
    type: "FOLLOW",
    payload: userId,
});
export const Unfollow = (userId) => ({
    type: "UNFOLLOW",
    payload: userId,
});

utils/api.js

import axios from "axios";

export const loginCall = async (userCredentials, dispatch) => {
    dispatch({ type: "LOGIN_START" });
    try {
        const response = await axios.post("/api/auth/login", userCredentials);
        dispatch({ type: "LOGIN_SUCCESS", payload: response.data });
    } catch (error) {
        dispatch({ type: "LOGIN_FAILURE", payload: error });
    }
};

How Scroll to Component Vuejs

I am working on a Single-Page-Website using the Vue-Cli and i have a Navigation with some Links in. I have registered All my Components from the links in the Navigation-Component and i want to Scroll to the component when the link is clicked. I tried to use the scrollIntoView() method but it didn’t work. Can someone help me please?

here is my template:

            <div><a href="#" @click="scrollToComponent(el)">Infrastrukturen</a></div>
            <div><a href="#" >Gartenbau</a></div>
            <div><a href="#" >Karriere</a></div>
            <div><a href="#" >Kontakt</a></div>
            <div><a href="#">Impressum</a></div>
        </div>

and here is my script:

import Kontakt from './kontakt.vue'
import Karriere from './karriere.vue'
import Gartenbau from './gartenbau.vue'
import Breitband from './breitband.vue'
import About from './about.vue'

export default {
  name: 'Navigation',
  components: {
      Kontakt,
      Karriere,
      Gartenbau,
      Breitband,
      About,

  },
    data:() => {
        return {
            defaultComp: 'About'

    }
  },
  methods:{
      scrollToComponent(el){
        const comp = el;
        if(comp){
            comp.scrollIntoView({
                behavior:"smooth"
            })
        }
    }
 }
}
</script>

how add global scss styles and mixins to preact app

clear project – from doc

npx create preact-cli default ...
npm i node-sass@10 sass

I tried import to index.js:

import "./style/global.scss";
import App from "./components/app";

export default App;

but cant use mixins and var in components styles

SassError: Undefined mixin.
     @include br;
     ^^^^^^^^^^^

but when Im importing scss file into component scss – all works fine

how can I import globally scss file?

How to access iframe within sandboxed iframe

Within a sandboxed iframe with sandbox="allow-scripts", if I dynamically create a new iframe using JS, I am not able to access it and receive the following error:
DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.

var iframe = document.createElement('iframe');
document.body.appendChild(iframe);

iframe.contentWindow.document.open();// throws error

Why is the newly generated iframe considered cross origin? And how can I create an iframe that I can access?
I cannot change the outer iframe sandbox properties.

hey guys could u plz help me in this code ? the description in inside the code [closed]

this is mu problem which i need to use arrays inside the function
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo

 * /*
 *   Array properites
 *   ----------------
 *   Complete the function to test if an array is empty (has no values in it)
 *
 * @format
 */

function isEmpty(arr) {
  return; // complete this statement
}

/* 
  DO NOT EDIT BELOW THIS LINE
  --------------------------- */
var numbers = [1, 2, 3];
var names = [];

console.log(isEmpty(numbers));
console.log(isEmpty(names));

/* 
  EXPECTED RESULT
  ---------------
  false
  true
*/

How to remove a event in Vue?

On my Vue instance i have this:

async mounted () {
  document.addEventListener('paste', this.onPasteEvent)
},
beforeDestroy () {
  document.removeEventListener('paste', this.onPasteEvent)
},
methods: {
  onPasteEvent () {
    return async (event) => {
      try {
        const items = event.clipboardData.items
        const files = await this.getBase64Files(items)

        this.transferedItems = files
        this.modal = true
      } catch (error) {
        this.$toast.error('Não foi possível detectar um arquivo na área de transferência.')
      }
    }
  },

I’m trying to destroy the “paste” event when the component is destroyed, but this just doesnt work, i know i need to pass the same reference to removeEventListener, but is this not the same reference?

The only way i found to make this work is placing the onPasteEvent method outside the Vue instance as a constant, but that way i don’t have access to this instance, which is important to me, also, i can’t pass anything as arguments, if i try to pass something, looks like my function create a new reference on memory, making unable to destroy it using removeEventListener.

Please, i just don’t understand how to remove a event in Javascript, can someone help me with that example? I already saw a lot of similar questions but no one explains:

  • How to keep the method reference even if it has parameters.
  • How to remove the event working with Vue instances.

Why might dragging SVG elements via TouchEvent on iPhone iOS be laggy?

I have created a web interface where the user can drag and drop SVG elements on screen. I am struggling with the performance of moving the SVGs via touch events on iPhone iOS using the webkit engine.

Everything is fine on desktop browsers and on Android phones that I could get hold of, but iOS on iPhones shows very bad performance (seems fine on iOS on one iPad that I could get hold of, but it sometimes leaves some traces of the SVG after moving).

There seems to be a delay before the touchstart event kicks in after touching the device and a delay before the touchend event is triggered after releasing the touch: An audio sample (already loaded) that is supposed to play after picking up or dropping the element plays with a delay of ~1.5 seconds. The touchmove event seems to be handled smoothly though – no delay with moving the SVG (after touchstart has ended).

I have already checked iOS Delay between touchstart and touchmove? – but the site that’s linked to doesn’t help me. I fail to get the scroll event on any element (window, document, svgElement) – and even if I did, I wouldn’t know how this could help me.

I assumed the the issue might be related to the size of the base64 encoded background image that the SVGs are using, but reduzing that size even dramatically didn’t help.

I read about some 300-350ms delay that iOS might have if there’s no “fast tap” mode set, but a) the delay between touching/releasing the screen and playing the audio is longer than 350ms (rather 1.5 seconds) and b) playing with the touch-action CSS property did not help. (Eliminate 300ms delay on click events in mobile Safari)

I am really not sure if I am doing anything wrong (very well possible!) or if the webkit engine on (iPhone) iOS is simply so bad (compared to e.g. Blink on Android that runs flawlessly) that it cannot handle to render/move SVGs? Testing this is particularly iffy, because Browserstack doesn’t issue TouchEvents properly and I never succeded to hook up the single physical iOS device that I have (a 2015 iPod Touch) to my Linux machine for remote debugging (while it’s very simple for Android on Chromium). I’d really be grateful for hints!

An SVG roughly follows the following pattern (some attributes like viewBox, stroke-width etc. omitted):

<svg>  
  <defs><pattern id="SOME_ID"><img href="data:SOME_BASE64_ENCODED_IMAGE" /></defs>  
  <path fill="url(#SOME_ID)" d="SOME_SIMPLE_PATH"></path>  
  <path d="SOME_OTHER_SIMPLE_PATH"></path>  
</svg>  

The SVGs can be moved by MouseEvent or TouchEvent using the following logic:

// this.svgElement is the DOM element within the class
this.svgElement.addEventListener('touchstart', this.handleMoveStarted, false);  
this.svgElement.addEventListener('mousedown', this.handleMoveStarted, false);  

// Keep track of start position and add move/end listeners
handleMoveStarted(event) {  
  event.preventDefault();  
  event.stopPropagation();  
  
  if (event.type === 'touchstart') {  
    this.moveInitialX = event.touches[0].clientX;  
    this.moveInitialY = event.touches[0].clientY;  
    this.svgElement.addEventListener('touchmove', this.handleMoved, false);
    this.svgElement.addEventListener('touchend', this.handleMoveEnded, false);
  }  
  else {
    // Same principle for event.clientX/Y and MouseEvent
  }
   
  // Callback to play audio here
}

// Compute delta position and update
handleMoved(event) {
  event.preventDefault();
  event.stopPropagation();

  let deltaX = 0;
  let deltaY = 0;

  if (event.type === 'touchmove') {
    deltaX = this.moveInitialX - event.touches[0].clientX;
    deltaY = this.moveInitialY - event.touches[0].clientY;
    this.moveInitialX = event.touches[0].clientX;
    this.moveInitialY = event.touches[0].clientY;
  }
  else {
    // Same principle for event.clientX/Y and MouseEvent
  }

  this.svgElement.style.left = `${parseFloat(this.svgElement.style.left) - deltaX}px`;
  this.svgElement.style.top = `${parseFloat(this.svgElement.style.top) - deltaY}px`;
}

// Used to remove listeners on tochenend/mouseup
handleMoveEnded(event) {
  event.preventDefault();
  event.stopPropagation();

  this.svgElement.removeEventListener('mousemove', this.handleMoved);
  this.svgElement.removeEventListener('touchmove', this.handleMoved);
  this.svgElement.removeEventListener('mouseup', this.handleMoveEnded);
  this.svgElement.removeEventListener('touchend', this.handleMoveEnded);

  // Callback to play audio here
}

Get page count from openXML word document in NodeJS

I am currently trying to get the page count of a Word document in openXML format and have been able to get to the point of where I have the XML structure of the document in a readable format, but I can’t seem to find where the page count property is. Any guidance would be appreciated.

const fs = require("fs");
const path = require("path");
const axios = require("axios");

let noRepeatDocs = ['somewebsite.com/somedocument.docx'];


const writeTheFile = async (data) => {
  fs.writeFileSync("read_word_doc", data);
};

const unzipTheFile = async (data) => {
  fs.createReadStream(data)
    .pipe(unzipper.Parse())
    .on("entry", function (entry) {
      const fileName = entry.path;
      const type = entry.type;
      const size = entry.vars.uncompressedSize;

        if (fileName === "word/document.xml") {
            entry.pipe(fs.createWriteStream("./output"));
      } else {
        entry.autodrain();
      }
    });
};

const getWordBuffer = async (arr) => {
  for (const wordDocLink of arr) {
    const response = await axios({
      url: wordDocLink,
      method: "GET",
      responseType: "arraybuffer",
    });
    const data = response.data;
    await writeTheFile(data);
    await unzipTheFile("./read_word_doc"); 
  }
};

getWordBuffer(noRepeatDocs);

xterm.js initial height and scroll bar problems

I am using xterm javascript control, and it is not sizing/resizing properly. I have the following HTML, creating two panes via div, left pane for xterm and right pane for a future side bar.

  <div id="panes" class="panes">
    <div id="terminal-pane" class="terminal-pane"></div>
    <div id="sidebar-pane" class="sidebar-pane"></div>
  </div>

With styles

    html, body {
      height: 100%;
      margin: 0;
    }

    div.panes {
      width: 100%;
      height: 100%;
      display: flex;
    }

    div.terminal-pane {
      width: 70%;
      height: 100%;
      overflow: hidden;
    }

    div.sidebar-pane {
      width: 30%;
      height: 100%;
    }

The xterm is created with

  <link rel="stylesheet" href="node_modules/xterm/css/xterm.css" />
  <script type="text/javascript" src="node_modules/xterm/lib/xterm.js"></script>
  <script type="text/javascript" src="node_modules/xterm-addon-fit/lib/xterm-addon-fit.js"></script>

  <script>
    var fitAddon = new FitAddon.FitAddon();
    var term = new Terminal();
    term.loadAddon(fitAddon);
    term.open(document.getElementById('terminal'));
    fitAddon.fit();
  </script>

At term.open, when I place a breakpoint, I see the initial width is sized to the table cell width, but the height of the terminal is 25 lines fixed. I expected the height to be sized to the table cell height.

Issue 1: can I do something to make term.open create the terminal initially full height?

Next, after fitAddon.fit, the terminal is resized to an integral of the character dimensions. The width might shrink a few pixels if it is not an even multiple of characters, and the height similarly stretches down all the way, minus any pixels that another row will not fit into.

Issue 2: can the term.open create the terminal on integrals of character width/height, or can I calculate and adjust the div before calling term.open?

Issue 3: the fitAddon.fit isn’t positioning the scroll bar properly. The terminal is on top of it and the left side of the scroll bar can get covered. Is there a way to fix this?

Finally, I add this:

  <script>
    function onSize() {
      if (fitAddon !== undefined) {
        fitAddon.fit();
      }
    }
    window.addEventListener('resize', onSize, false);
  </script>

I should see fitAddon.fit resize the terminal when the browser is resized.

Issue 4: If the width changes but the row count does not, the scroll bar does not move. When sizing bigger, the terminal will cover it, and when sizing smaller, the scroll bar will be clipped. When sizing to its initial position, part or all of the scroll bar shows up. However, if the terminal contains enough lines to scroll, the scroll bar will move with resize.

What should I be doing differently?

Jest – How To Test a Fetch() Call That Returns A Rejected Promise?

I have the following function that uses fetch() to make an API call:

export async function fetchCars(dealershipId) {
  return request('path/to/endpoint/' + dealershipId)
    .then((response) => {
      if (response.ok === false) {
        return Promise.reject();
      }
      return response.json();
    })
    .then((cars) => {
      return parseMyCars(cars);
    });
}

I want to test when the call fails (specifically when return Promise.reject() is returned). I have the following Jest test right now:

(fetch as jest.Mock).mockImplementation(() =>
    Promise.resolve({ ok: false })
);
const result = await fetchCars(1);
expect(request).toHaveBeenCalledWith('/path/to/endpoint/1');
expect(result).toEqual(Promise.reject());

but I get a Failed: undefined message when running the test. I’ve tried using:

(fetch as jest.Mock).mockRejectedValue(() =>
  Promise.resolve({ ok: false })
);

but get a similar Failed: [Function anonymous] message.

What’s the proper way to test for the rejected promise here?