Use JSON.stringify() or any other method to serialize without removing Whitespaces -Javascript

I have a Json let obj = {"a": "1", "b" : "2"} which contain whitespaces. I want to serialize the obj without removing the whitspaces, So that when i deserialize (EX: using JSON.parse()), i should be able to get the obj in same format.

let obj = {"a":   "1",  "b" :    "2"};
let serialized_obj = JSON.stringify(obj);
//then we get  serialized_obj  = "{"a":"1","b":"2"}" , this shouldn't happen.

What is Expected?

let obj = {"a":   "1",  "b" :    "2"};
let serialized_obj = serializationMethod(obj);
// expected to get serialized_obj  = "{"a":   "1",  "b" :    "2"}"
let deserialized_obj = deserializationMethod(serialized_obj);
//expected to get serialized_obj  = {"a":   "1",  "b" :    "2"}

Require the methods serializationMethod() and deserializationMethod()

More Details
For security reasons i get the JSON object and the digital signature of the serialized object. i have to verify the both. I can get these from any of the technology user. But the problem i faced is, in python serialization the json is beautified with whitespaces. So when i get them, i am not able to keep the format i got and verificaton fails.

Angular JS – Error: $http:badreq Bad Request Configuration

I am learning Angular JS. I am trying to create a mock portal that displays Daily Messages. I have stored my daily messages in a database table.

create table DailyMsg(Sno int primary key, msg varchar(max));

Then I created a service using factory in AngularJS.

 public class DailyMsgsController : Controller
    {
        private amenEntities1 db = new amenEntities1();

        // GET: DailyMsgs
        public ActionResult Index()
        {
            return Json(db.DailyMsgs.ToList(),JsonRequestBehavior.AllowGet);
        }
}

        

I tested the URL and it works fine, it returns the expected data in the JSON format

https://localhost:44329/DailyMsgs

Now, I wanted to display this data on my HomePage. But it doesn’t work. On inspecting the page it shows me the error

Error: $http:badreq
Bad Request Configuration
Http request configuration url must be a string or a $sce trusted object.  Received: undefined

My Controller

var myApp = angular.module('myApp', []);

//Daily Messages Service Function
myApp.factory('DailyMsgService', function ($http) {
    DailyMsgObj = {};
    DailyMsgObj.DisplayDailyMsg = function () {

        var Msg;

        Msg = $http({method: 'GET', URL: '/DailyMsgs/Index'}).
            then(function (response){
            return response.data;
        });

        return Msg;
    }

    return DailyMsgObj;
});



myApp.controller('HomePageController', function ($scope, DailyMsgService) {
    DailyMsgService.DisplayDailyMsg().then(function (result) {

        $scope.DailyMsg = result;

    });
});

My HomePage

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <meta charset="utf-8" />
    <title></title>

</head>
<body>
    <div ng-controller="HomePageController">
        {{DailyMsg}}
    </div>

</body>
</html>
<script src="../Scripts/angular.min.js"></script>
<script src="../Scripts/bootstrap.min.js"></script>
<link href="../Content/bootstrap.min.css" rel="stylesheet" />
<script src="../AngularControllers/HomePageController.js"></script>

How to manually upload a file with cypress?

I know that there is a plugin for doing this in cypress already. However using it with jar files just corrupts the file and therefore it is useless in my usecase. This is really weird because i tried it with every combination of encoding and it still does not work. Works perfectly fine with other filetypes however.

This is the code i am using (works except with jar files).

cy.get('[data-cy="dropzone"]')
  .attachFile('test.jar', { subjectType: 'drag-n-drop' });

I know that you can perform post requests in cypress. Is it possible to perfom the file upload with it after clicking the dropzone element?

React Function filter does not work (no errors in the console)

In my list, when I click on row, the background of the changes color and the id of my row is added to the array of my state. It works, but when I do the reverse my array doesn’t get empty when I use the filter function (line 15).

import React, {useState} from 'react';
import './Liste.css';
import Button from '../Button/Button';

function Liste(props) {

    const [nbLine, setNbLine] = useState([]);

    const clickLine = (e) =>
    {
        if (e.target.parentNode.className.length > 0)
        {
            console.log(e.target.parentNode.id);
            e.target.parentNode.classList.remove("lineClicked");
            nbLine.filter(line => line != e.target.parentNode.id);
            console.log(nbLine);         
        }
        else
        {
            e.target.parentNode.classList.add("lineClicked");
            nbLine.push(e.target.parentNode.id);
            console.log(nbLine);
        } 
    }

    const doubleClickLine = () =>
    {
        console.log("doubleClickLine"); 
    }

    return (
        <>
            <table className='tableList'>
                <thead>
                    <tr>
                        {props.headers.map((header, h) =>
                            <th key={h}>{header}</th>                   
                        )}
                    </tr>
                </thead>
                <tbody>
                    {props.records.map((record, r) =>
                        <tr key={r} id={props.table+"_"+record[0]} onClick={clickLine} onDoubleClick={doubleClickLine}>
                            {props.columns.map((column, c) =>
                                <td key={c}>{record[column]}</td>      
                            )} 
                        </tr>                
                    )}
                </tbody>
                <tfoot>
                    <tr>
                        <th colSpan={7}>
                            {props.buttons.map((button, b) =>
                                <Button key={b} id={button[0]} type={button[1]} value={button[2]} click={button[3]}/>              
                            )}
                        </th>
                    </tr>
                </tfoot>
            </table>
        </>
    )
}

export default Liste;

Here is the screen when I click (the elements are in the table).
Note: the data is fictitious.

And here is the screen when I click again (the elements resent in the array).

And here is the screen when I click again (the elements resent in the array).

Why is the filter function not working?

How to filter array of dates using javascript

I’ve got an array of dates (strings) in sorted order, going from oldest to latest days, like so:

const allDates = [
  '2020-11-21',
  '2020-11-22',
  '2020-11-23',
  '2020-12-21',
  '2020-12-22',
  '2020-12-23',
  '2021-01-21',
  '2021-01-22',
  '2021-01-23',
  '2021-02-21',
  '2021-02-22',
  '2021-02-23'
];

What I want to create is a new array with the oldest date from the oldest month, any dates from the middle months (could be the first date of each month) and the last date of the latest month, so the new array looks like this:

const filteredDates = ['2020-11-21', '2020-12-21', '2021-01-21', '2021-02-23']

The important thing is that I don’t want to use any JS library

Moving on from ExpressJS [closed]

So I am currently using Express as my defacto library for backend. But, I want to change. I have come across a lot of options like Fastify, Adonis, Koa & more. But, Express is a low-scope framework & I like its approach. But, while choosing a new framework, I am not sure if I should go for a full-fledged system like Adoni.

Function works but won’t return HTML?

I have a component that returns the following code:

  <Popup
    toggled={moveFolderPopup}
    width="50%"
    close={() => setMoveFolderPopup(false)}
  >
    <div className="popup-title">
      {t('view.assets.moveFolderPopup.title')}
    </div>
    <div className="filebrowser-moveFolderPopup-hierarchy">
      {renderFolderStructure(indexFolder.id)}
    </div>
  </Popup>

The part that’s failing is renderFolderStructure(indexFolder.id)
The function looks as follows:

const renderFolderStructure = (parentId: string) => {
if (assetFolders !== []) {
  assetFolders.map((folder, i) => {
    if(folder.parentId === parentId) {
      console.log('why wont this work?');
      return <div>{folder.name}</div>;
    }
  });
} else {
  return <div>Error</div>;
}
};

Running this code the console prints out “Why wont this work?” 6 times for 6 folders that have matching parentIds. So everything works except that the function won’t return <div>{folder.name}</div>. I feel like I have done something like this a million times. What’s wrong here?

How to send information between two html using json and POST?

In ‘cart.html’ I have a form of id=”order-selection-cart” which is for selecting user’s order, which the user wants to make payment for.

<select id="order-selection-cart" onchange="order_cart()" class="form-control">
          {% for order in orders_for_user %}
              <option>{{order.id_zamowienie}}</option>
          {% endfor %}
</select>

In the same html page, I also display the selected order value ({{order.id_zamowienie}} in a form of id=”order-selection-cart”:

<div class="row cart-box" style="background-color:rgb(226, 226, 226);">
            <h10>Szczegóły zamówienia </h10>
            <h4 type="value" id="order-details"></h4>
</div>

Now, I want to go to ‘checkout.html’ by clicking a button of name ‘Zamawiam’ and I have done it like this:

<div class="row cart-box" style="background-color:rgb(226, 226, 226);">
            <h4>Suma zamówienia</h4>
            <h10>Suma: {{cart_total|floatformat:2}} zł</h10>
            <br>
            <a class="btn btn-primary" href="{% url 'checkout' %}" role="button">Zamawiam</a>
</div>

This code works, but I have a problem with remembering selected user’s order which he wants to make payment for. Let’s say I selected option 2, I want to remember it and when clicked ‘Zamawiam’ I want to go to ‘checkout.html’ where this value (2) can be accessed and not changed when it is again changed (if user changes it in cart.html in other window for example). At first I have had js code which was changing value of selected option in ‘cart.html’:

// ordernumber update in cart.html
function order_cart() {
    let user = '{{request.user}}'
    let select = document.getElementById('order-selection-cart');
    let select1 = document.getElementById('order-details');

    let value = select.options[select.selectedIndex].value;
    select1.innerHTML = value;
}

Then I thought of adding a POST method, but it would be run every time user changes his order in cart.html. I want to run a POST method each time a user clicks ‘Zamawiam’ with content of current order option which was selected by user. I also would like to ask how to then access ‘order_number’ in a checkout.html code.

// ordernumber update in cart.html
function order_cart() {
    let user = '{{request.user}}'
    let select = document.getElementById('order-selection-cart');
    let select1 = document.getElementById('order-details');

    let value = select.options[select.selectedIndex].value;
    select1.innerHTML = value;

    // send information about selected option to 
    alert('USER:', user)
    if(user === 'AnonymousUser'){
        console.log('Not logged in')

        // TODO: delete it once login is done 
        update_order_number(value);
    }else{
        update_order_number(value);
    }

}

function update_order_number(order_number){
    console.log('User is logged in, sending data...')

    let url = '/checkout/'

    // whenever we are sending POST data to the backend in Django, is we need to send CSRF token
    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            'order_number': product_id// body data type must match "Content-Type" header
        })
    })


    .then((response) => {
                return response.json()
            })

            .then((data) => {
                console.log('data: ', data)
            })
} 

Vue JS lodash findKey nested object with dot notation returns undefined

I’m trying to pull out a value for a nested object key from some eligibility array that I’ve got, but I’m getting an undefined value for some reason and need to know what I’m missing.

Given the following array:

const eligibilityCriteria = [
  { field: 'loan.amount', operator: '>=', value: 1000 },
  { field: 'loan.term', operator: '>=', value: 1 },
  { field: 'applicant.birthday', operator: '>=', value: 40 },
  { field: 'applicant.isHomeowner', operator: '==', value: false }
]

I need to find loan.amount from a nested object and pull out it’s value:

My big nested object is (coming from the store)

application: {
  meta: {
    brand: '',
    version: '',
    affiliate: '',
    affiliate_full: '',
    campaign: '',
    client_hostname: '',
    client_href: '',
    client_origin: '',
    client_useragent: '',
    client_ip: '127.0.0.1',
    icicle_hash: ''
  },
  loan: {
    amount: 500,
    term: null,
    purpose: null
  }
}

My function right now is:

checkEligibility () {
  const eligibilityCriteria = [
    { field: 'loan.amount', operator: '>=', value: 1000 },
    { field: 'loan.term', operator: '>=', value: 1 },
    { field: 'applicant.birthday', operator: '>=', value: 40 },
    { field: 'applicant.isHomeowner', operator: '==', value: false }
  ]

  for (const [index, offer] of this.datasets.offers.entries()) {
    const eligibility = eligibilityCriteria

    if (eligibility) {
      for (const [ci, criteria] of eligibility.entries()) {

        // TODO: this fails to pull the value, returns undefined
        const field = _.findKey(this.$store.state.application.application, criteria.field)
      }
    }
  }
}

What am I missing?

Use variable in ejs script tag

I want to use variable (or variables) in ejs file in the script tag ,I also want to pass the rendered file to a function for taking screenshot from ejs file.

But now I have 2 problems :

1.I don’t know how to pass the variable in server file to the ejs file and render and use it without app.get… (in express) because it’s server side and I want to use html file.

2.I don’t know how to use variable in ejs file in the script tag

these are my files :

index.ejs


<div id="tvchart"><% symbol %></div>

<script>
//some codes 
 var symbolD =<%= symbol %>;
fetch(`http://127.0.0.1:9665/fetchAPI?endpoint=https://api.binance.com/api/v3/klines?symbol=${symbolD}&interval=1m&limit=1000`)
</script>

server.js

// set the view engine to ejs
app.set("view engine", "ejs");
const symbol = "EGLDUSDT"

const file = ejs.render("./index.ejs" , symbol);
console.log(file)

So Why my ejs and server file doesn’t work?

firebase initialize with vuejs 2022

i wish to initialize my vuejs project with firebase.

But because of the new update i can’t.

i must use import { initializeApp } from "firebase/app"; AND const app = initializeApp(firebaseConfig);

but i have 2 problems with this:

1)

This dependency was not found: To install it, you can run: npm install –save firebase

it didn’t found my module. In my package.json it’s present.

2)

to initialize my instance vuejs i need to write :

new Vue({ router,render: h => h(App)}).$mount('#app')

but i have “app” from firebase missing.

thanks for your help 🙂

react native local push notifications IOS – (react-native-push-notification)

I’m using the (react-native-push-notification) package for my alarm ios app but there is an issue when the app is in the background notification banner appears for a short time but does not receive any callback in the background because I need a callback, where I ring a sound continuously.
When the app is in the background notification banner appears with sound only for 6 seconds but I need to play a sound continuously when a notification appears in the background.

How do I understand my addEventListener error code? [duplicate]

I’m attempting to build a simple ‘To-Do List’. I’m trying to add a new P element to my existing div. Does anyone have any ideas regarding the following error code?

Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')

I feel like my HTML button (submitButton) click isn’t being received, although I could be wrong.

var toDoList = document.getElementById("toDoList"); // div with p elements within
var submitButton = document.getElementById("submitButton"); // HTML button
var textInput = document.getElementById("textInput"); // HTML text input

function addFunction(){
    var newItem = toDoList.createElement("p");
    newItem.innerText = textInput.value;
    document.toDoList.appendChild(newItem);
}

submitButton.addEventListener('click', addFunction);