Update Local Data.json from firebase database

I am working on Packages App, Question is How can Update(all data) Data.json (file in Local Storage) with data fetched from Firebase Realtime Database. here is my code

private void UpdateJSONDB()
    {
        JSONObject JSONobj = null;

        try {
            loadJSONFromFiles();
            //get JSONObject from JSON file
            JSONobj = new JSONObject(loadJSONFromFiles());
            JSONObject Jazz_SimLagaoOffer = JSONobj.getJSONObject("packages").getJSONObject("jazz_packages").getJSONObject("call_packages").getJSONObject("sim_lagao_offer");
            
            Jazz_SimLagaoOffer.put("onnet", Jazz_SimLagaoOffer_OnNet.toString());

           String file = getFilesDir().toString() +"/" + "Data.json";
            Toast.makeText(MainActivity.this, file, Toast.LENGTH_SHORT).show();


            try {
                FileOutputStream fos = new FileOutputStream(file);

                if (JSONStringFromFirebase != null) {
                    fos.write(JSONStringFromFirebase.getBytes());
                }
                fos.close();
            }
            catch (FileNotFoundException fileNotFound)
            {
                Toast.makeText(MainActivity.this, "File not Found", Toast.LENGTH_SHORT).show();

            }
            catch (IOException ioException)
            {
                Toast.makeText(MainActivity.this, "IO Exception Occured", Toast.LENGTH_SHORT).show();

            }


        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

How can I successively filter the choices in a list on a letter by letter basis?

My apologies if this has been answered elsewhere; if so, I was unable to query the database in a way that returned the result I need. Here’s my question:

Let’s say I have an unordered list of state names.

etc.,
Louisiana, Maine, Massachusetts, Michigan, Mississippi, Missouri, Montana, New Hampshire, etc.

And I want to display a search box that filters the list to a single choice as successive unique letters are typed in. In other words, by just typing in an “M”, you eliminate “Louisiana” and “New Hampshire” from the list. By adding an “o” to the “M” you eliminate everything but “Montana.” But typing in an “a” after the “M” the list still offers two choices. In order to reduce the list to a single choice you have to type a third letter. I’ve found a script that will filter by upper case letter, but nothing more. If a second letter is typed in to further reduce the number of choices, the list disappears entirely.

Here (from w3schools with some modification) are the elements:

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

<ul id="myUL">
  <li><a href="#">Louisiana</a></li>
  <li><a href="#">Maine</a></li>
  <li><a href="#">Massachusetts</a></li>
  <li><a href="#">Michigan</a></li>
  <li><a href="#">Mississippi</a></li>
  <li><a href="#">Missouri</a></li>
  <li><a href="#">Montana</a></li>
  <li><a href="#">New Hampshire</a></li>
</ul>
* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}
function myFunction() {
    var input, filter, ul, li, a, i, txtValue;
    input = document.getElementById("myInput");
    filter = input.value.toUpperCase();
    ul = document.getElementById("myUL");
    li = ul.getElementsByTagName("li");
    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("a")[0];
        txtValue = a.textContent || a.innerText;
        if (txtValue.indexOf(filter) > -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}

Their script does offer the option of sorting by any letter in the name instead of just the uppercase (presumably first) letter. But this returns all names wherein the typed letter appears at all. Thus, typing an “i” (in a list of all state names) would display all states with that letter anywhere in the name. However, this method eventually does reduce the list to a single choice as more letters are typed in. I would like both of these methods to work together i.e., I want the first typed letter to filter the list to states with only that first letter, the second typed letter to reduce it to only those states with the same first two letters, etc. I hope that makes sense.

Thanks in advance for any help.

How to group by element in nested array of objects

I want to group the element present inside nested array of objects.

Input

data=[{
    "name":"abc",
    "age":12,
    "details":[{
        "place":"abc",
        "hobbies":"playing"
    }],
    "school":"abcd"
},
{
    "name":"bcd",
    "age":11,
    "details":[{
        "place":"zyx",
        "hobbies":"watching"
    }],
    "school":"bcda"
},
{
    "name":"cde",
    "age":13,
    "details":[{
        "place":"abc",
        "hobbies":"playing"
    }],
    "school":"cdba"
},
{
    "name":abcd",
    "age":15,
    "details":[{
        "place":"zyx",
        "hobbies":"playing"
    }],
    "school":"qwer"
}
]

From the above input I want to group the data by place present inside nested array.

Expected Output

{
    'abc': [
        {
            "name":"abc",
            "age":12,
            "details":[{
                "place":"abc",
                "hobbies":"playing"
            }],
            "school":"abcd"
        },
        {
            "name":"cde",
            "age":13,
            "details":[{
                "place":"abc",
                "hobbies":"playing"
            }],
            "school":"cdba"
        }
    ],
    'zyx': [
        {
            "name":abcd",
            "age":15,
            "details":[{
                "place":"zyx",
                "hobbies":"playing"
            }],
            "school":"qwer"
        },
        {
            "name":"bcd",
            "age":11,
            "details":[{
                "place":"zyx",
                "hobbies":"watching"
            }],
            "school":"bcda"
        },
    ]
  } 



I am able to group elements present inside array of objects and also array of nested objects but unable to group elements in nested array of objects.

I’m not able to use the url of the instagram image that comes in the json

I’m developing an api to get data from a specific hashtag.

This json it returns the image in different resolutions, but it’s a url that gives an error, I can’t use this image and I don’t know how to solve the problem.

URL: https://www.instagram.com/explore/tags/jeep/?__a=1

Error: GET https://scontent-gru1-1.cdninstagram.com/v/t51.2885-15/284660975_5107249636061398_8185965897577183599_n.jpg?stp=dst-jpg_e35_p640x640_sh0.08&_nc_ht=scontent-gru1-1.cdninstagram.com&_nc_cat=110&_nc_ohc=DOEOKz-tf2UAX98qbHQ&edm=AABBvjUBAAAA&ccb=7-5&oh=00_AT-Im7KGjYftnZu6Am-_FV7RKW7CVDcYmyzhU1zB0vKCvg&oe=629F3ED8&_nc_sid=83d603 net::ERR_BLOCKED_BY_RESPONSE.NotSameOrigin 200

Index.js

const express = require("express");
const morgan = require("morgan");
const bodyParser = require("body-parser");

// Routes
const routeLogin = require('./routes/login');
const routeRegister = require('./routes/register');
const routeHashtags = require('./routes/hashtag');

const app = express();
const cors = require("cors");



// Use
app.use(cors())

// Morgan
app.use(morgan("dev"));

// Body parser
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());



// Routes
app.use('/login', routeLogin);
app.use('/register', routeRegister);
app.use('/hashtag', routeHashtags);

// Error
app.use((req, res, next) => {
  const error = new Error("Erro! Não encontrado!");
  error.status = 404;
  next(error);
})

app.use((error, req, res, next) => {
  res.status(error.status || 500);
  return res.send({
    error: {
      message: error.message
    }
  })
})



module.exports = app;

How am I getting the data

async function dashboard(){
  async function pendingPosts(){
    let divPendImages = document.getElementById("pendingPosts_images");
    let ctaNo = document.getElementById("pendingPosts_cta_no")
    let ctaYes = document.getElementById("pendingPosts_cta_yes")

    // Get data
    const res = await fetch("http://localhost:3120/hashtag/")
                      .then((res) => res.json())
                      .then((data) => {return data.response})

    // Show data
    function showData(){
      console.log(res.length)

      res.forEach((element, index) => {
        // Img
        let img = document.createElement("img")
        let src = element.node.thumbnail_src;
        img.src = src;

        ctaNo.parentNode.querySelector("input").value = src;
        ctaYes.parentNode.querySelector("input").value = src;

        // CTA
        if(index == 0){
          ctaNo.parentNode.action = `http://localhost:3120/hashtag/notadd/${element.node.id}`;
          ctaYes.parentNode.action = `http://localhost:3120/hashtag/create/${element.node.id}`;
        }

        // Append img
        divPendImages.appendChild(img);
      });
    }
    showData()
  }
  pendingPosts()
}
dashboard()

ReferenceError: ko is not defined when running unit test in Jest

I am new to Jest and Stackoverflow posting.
I have been trying to add unit test cases for knockoutJS application but getting ReferenceError: ko is not defined error when running the test. Any help would be appreciated.

below is the package.json file.

    {
  "name": "jstesting",
  "version": "1.0.0",
  "description": "",
  "main": "eVIPs.js",
  "type": "module",
  "scripts": {
    "test": "jest"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/preset-react": "^7.17.12",
    "jest": "^28.1.0",
    "jest-html-reporters": "^3.0.8",
    "typescript": "^2.9.2"
  },
  
  "dependencies": {
    "@babel/preset-env": "^7.18.2",
    "@babel/preset-typescript": "^7.17.12",
    "babel-jest": "^28.1.0",
    "jquery": "^3.6.0",
    "knockout": "^3.5.1"
  },
  "jest": {
    "reporters": [
      "default",
      [
        "jest-html-reporters",
        {
          "publicPath": "./html-report",
          "filename": "report.html",
          "openReport": false
        }
      ]
    ],
    "collectCoverage": true
  }
}

and this is the test file.

    import testLogin from '../loginPage';
import homeJS, { HomeViewModel } from '../Home';

Categorized selection

I have a option tag inside of my html page and the choices there is categorized, and I want users to view and select Main categories before the sub categories.

But the real question is can I make 5 categories selection for example:
Main-categ,
sub-categ,
sub-sub-categ,
sub-sub-sub-categ,
and sub-sub-sub-sub-categ.

I can only do 3 categories and I cannot find a way to make it 5

I tried doing 4 categories like this, but it didn’t work:


var placeObject = {
 "Main A Category": {
   "Sub A-1 Category":{ 
       "sub-sub A1-1 Category": ["choice #1 of A1-1 sub-category", "choice #2 of A1-1 sub-category", "choice #3 of A1-1 sub-category"],
       "sub-sub A1-2 Category": ["choice #1 of A1-1 sub-category", "choice #2 of A1-1 sub-category", "choice #3 of A1-1 sub-category"]},
   "Sub A-2 Category":{ 
     "sub-sub A2-1 Category": ["choice #1 of A2-1 sub-category", "choice #2 of A2-1 sub-category", "choice #3 of A2-1 sub-category"],
     "sub-sub A2-2 Category": ["choice #1 of A2-1 sub-category", "choice #2 of A2-1 sub-category", "choice #3 of A2-1 sub-category"]}}

here is my finished JavaScript that has 3 categories.

var placeObject = {
  "Main A Category": {
  "Sub A-1 Category": ["choice #1 of A-1 sub-category", "choice #2 of A-1 sub-category", "choice #3 of A-1 sub-category"],
  "Sub A-2 Category": ["choice #1 of A-2 sub-category", "choice #2 of A-2 sub-category", "choice #3 of A-2 sub-category"]},
  "Main B Category": {
  "Sub B-1 Category": ["choice #1 of B-1 sub-category", "choice #2 of B-1 sub-category", "choice #3 B-1 of sub-category"],
  "Sub B-2 Category": ["choice #1 of B-2 sub-category", "choice #2 of B-2 sub-category", "choice #3 B-2 of sub-category"]}
}
window.onload = function() {
  var mainSel = document.getElementById("main");
  var subSel = document.getElementById("sub");
  var subsubSel = document.getElementById("sub-sub");
  
  for (var x in placeObject) {
    mainSel.options[mainSel.options.length] = new Option(x, x);
  }
  mainSel.onchange = function() {
    //empty promos- and hotels- dropdowns
    subSel.length = 1;
    subsubSel.length = 1;
    //display correct values
    for (var y in placeObject[this.value]) {
      subSel.options[subSel.options.length] = new Option(y, y);
    }
  }
  subSel.onchange = function() {
    //empty promos dropdown
    subsubSel.length = 1;
    //display correct values
    var z = placeObject[mainSel.value][this.value];
    for (var i = 0; i < z.length; i++) {
      subsubSel.options[subsubSel.options.length] = new Option(z[i], z[i]);
    }
  }
}

Please be nice, I’m a freshmen IT Student and making my simple project.
Thank you in advance.

how to remove lodash from this line

I need to remove lodash from an old project I never used lodash before so I couldn’t understand and couldn’t find an example for this one.
how to change this :
_.find(x, ['y', z])
is that equal to:

x.find( (e) => (e.y === y && e.z === z))

I want to create a website where you can rate tracks

I’m working on a beginner project, using html css JS and php.

It’s similar to Spotify and the concept is very simple we can rate our tracks, on 10.
I want to create many card, with all the information like the name, the picture of the album, and the rating, in a database using MySQL and then I’m printing it with a loop.

My question is, is there a solution for have all the database of Spotify, like all the singer, all their album etc.. then I could use it for build the card , with the name, the picture of it etc..

I don’t know if I’m clear, I need some advices to finish this project I’m enjoying doing it !

Create an instance of a composable

I created a little composable, which is supposed to help me handling modals and slideovers.

This is the composable:

export function useSlideover() {

    const isOpen = ref(false);

    function toggle(){
        isOpen.value = !isOpen.value;
    }

    function open(){
        isOpen.value = true;
    }

    function close(){
        isOpen.value = false;
    }

    return { isOpen,  toggle, open, close}
}

export function useModal() {

    const isOpen = ref(false);

    function toggle(){
        isOpen.value = !isOpen.value;
    }

    function open(){
        isOpen.value = true;
    }

    function close(){
        isOpen.value = false;
    }

    return { isOpen,  toggle, open, close}
}

If I use it in a component like this:

const {isOpen, open, close, toggle} = useSlideover();

...

open();

everything works nice.

But from time to time, there are two components using this composable at the very same time – e.g. there is a modal that opens a smaller modal.

What happens here is that if I use the close() function on the smaller modal, the parent-modal closes too, as isOpen changes to false for this component, too.

My question is: How can I handle the state of each modal individually?

React.js 16.8.0 to 18.0.1 Transformation

const rootElement = document.getElementById("root");
ReactDOM.render(
  <React.StrictMode>
    <CubeProvider cubejsApi={cubejsApi}>
      <App />
    </CubeProvider>
  </React.StrictMode>,
  rootElement

How to transform this into react 18.1.0. It’s written on 16.8.0 now

How does this code work? Why do not I understand this code?

I am learning JavaScript and I came across this code today but I could not understand how this code works. Can anyone explain this code to me?

function showPrimes(n) {

  for (let i = 2; i < n; i++) {
    if (!isPrime(i)) continue;

    alert(i);  // a prime
  }
}

function isPrime(n) {
  for (let i = 2; i < n; i++) {
    if ( n % i == 0) return false;
  }
  return true;
}

showPrimes(10);

Using a method from a ‘this’ object in an express post function

I have a class with two methods:

var express = require('express');

class TestClass{
    constructor() {}

    first() {
        var app = express();
        var path = require('path');
        app.use( express.urlencoded({ extended: true }) )
        app.use( express.json() );
    
        app.post('/centroid', function(req, res) {
            this.second(req.body);
        });

        app.listen(4444);
    }
    second(data) { console.log(data) }
}


module.exports = TestClass;

When I try to reference the second method while using this, I get an error that this is undefined.

I have looked into .bind() method, but it seems that I can’t use that with passing the req.body argument. Because it would require to bind it in the callback of the .post function.

How can i resolve this and use second() method in a callback of a post function?

How to pass value to a checkbox on ajax success

I am trying to display the value in checkbox value field that I got on ajax success.
Here is my ajax

$(".allowClick").on("click",function(e){
    var requested_id = $(this).attr("data-id");
    $.ajax({
      url: "myurl",
      data: {
        "data" : $(this).attr("data-id")
      },
      method: "GET",
      success: function (response) {
            $("#requested_ins_checkbox").val(requested_id);# The value that I got here want to display in checkbox  value field
      }
    });
  }

Here is my checkbox html

<input type='checkbox' name='remove_ins' value="requested_ins_checkbox" id="requested_ins" /> Remove

Kindly help. I don’t know where I made mistake.

Why do my javascript integration in a django template does not work?

I am really new to django and i am trying to build a small page where a chart with chart.js is shown. I want to load the javascript file static. I created a basic html-file called data_table.html and added a folder static where three files are in:
data_table.js, styles.css and a picture bild.jpg.
The html file is:

{% load static %}
<!DOCTYPE html>
<head>
    <link rel="stylesheet" href="{% static 'styles.css' %}" type="text/css">
    <script type="text/javascript" src="{% static 'data_table.js' %}"></script>
    <title>Data viewer</title>
    
</head>
<body>
    <canvas id="myChart" width="200" height="200"></canvas>
    <script>
    </script>
    <p class="text">Picture:</p>
    <br>
    <img class="img" src="{% static 'bild.jpg' %}" alt="My image">
</body>
</html>

The css file and the picture are loaded. The picture is displayed and with the css file i can resize the picture. So that works i guess? The javascripts file looks as follows:

const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: [{% for d in data%}'{{d.label}}',{%endfor%}],
        datasets: [{
            label: '# of Votes',
            data: [{% for d in data%}{{d.data}},{%endfor%}],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});    

The javascript file seems not to be loaded and no chart is displayed. Surprisingly if i am putting the javascript code in between the empty script tags in the body, the chart is displayed fine.
I also tried to put the
<script type="text/javascript" src="{% static 'data_table.js' %}"></script>
line at the sameplace where the empty script tag is right now. It also does not work.
No error is thrown. So what am i doing wrong?

Thank you in forward for your answers. In special if i am just doing a very stupid error.