javascript – Confused in understanding where the code is failing

I had recently written a code which gives the maximum XOR sum of the subsets of an array. While submitting the code, my code fails a few test cases and I’m unable to see what test cases it fails.
The code is below

    const readline = require('readline')
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    const int_bits = 32;
    let lalle = 0;
    rl.on('line',(line)=>{
        
    let nums = line.split(' ');
    if(lalle%2 === 0){
        arr_length = parseInt(nums(0))
        if(arr_length === 0){
            return 0;
        }
    }else{
        nums = nums.map((elem)=> parseInt(elem))
        console.log(maxXorSum2(nums,nums.length))
    }
    lalle++
})

function maxXorSum2 (set,n){
    let index = 0;  
    for (let i = int_bits - 1; i >= 0; i--)  
    { 
    let maxInd = index; 
    let maxEle = -2147483648; 
    for (let j = index; j < n; j++) { 
          
 
        if ((set(j) & (1 << i)) != 0 && set(j) > maxEle) 
        { 
        maxEle = set(j); 
        maxInd = j; 
        } 
    } 
  

    if (maxEle == -2147483648) 
        continue; 
  

    let temp = set(index); 
    set(index) = set(maxInd); 
    set(maxInd) = temp; 

    maxInd = index; 
  

    for (let j = 0; j < n; j++) { 
          
      
        if (j != maxInd && (set(j) & (1 << i)) != 0) 
        set(j) = set(j) ^ set(maxInd); 
    } 
  
 
    index++; 
    } 
  
  
    let res = 0; 
    for (let i = 0; i < n; i++) 
        res ^= set(i); 
    
    return res; 
} 

The input the file takes is as follows:

3

2 3 5

I’m unable to find out where it fails. Could you guys kindly help me?

javascript – Colocar uma condição em uma função exportada no node.js

Estou com uma dúvida pertinente, estou começando um projeto em electron onde tenho que fazer a conexão com dois bancos diferentes, um local e outro em nuvens, no meu código node js, tenho dois arquivos o index.js onde coloco os dados referentes ao electron e outro database.js onde vou chamar o banco de dados, daí vem a dúvida, quando utilizo o module.exports = function …, para exportar a função para o index.js, não consigo utilizar esta função esportada para fazer uma condição if onde dependendo da resposta do primeira sql devo executar a segunda em um outro banco, segue o código para entender melhor

database.js

var mysql = require('mysql');
module.exports = function execSQLbd(sqlQry){  
    var connection = mysql.createConnection({
      host     : 'localhost',
      port     : 3306,
      user     : 'teste',
      password : 'teste',
      database : 'teste'
  });
  connection.connect(function(err) {
      // in case of error
      if(err){
          console.log(err.code);
          console.log(err.fatal);
      }
  });
  connection.query(sqlQry, function(error, rows, fields){
      if(error){
          console.log("An error ocurred performing the query.");
          console.log(err);
          return;
      }
      
      nome = rows(0).nome;
      id = rows(0).id;
      connection.end();

      return id;
      //console.log(id);
  }); 
}

Quando mudo o return para console.log ele aparece o resultado do database, mas o problema é colocar este resultado no if, pois quando coloco a condição no index.js ele roda primeiro o if e depois a função do database;
Desde já agradeço a quem poder colaborar…

index.js

var execSQLbd = require('./models/db1');
banco1 = new execSQLbd("SELECT * FROM pagamentos WHERE id = '1'");

if (banco1 == 1)
 return true;


const {app, BrowserWindow} = require ('electron');


let mainWindow;

app.on('ready', () =>{
    mainWindow = new BrowserWindow ({

    });

    mainWindow.loadURL(`file://${__dirname}/teste.html`)
});

javascript – how can i make checkbox to not remove tick on page refresh when checked and have the checkbox update the complete field in my database table

I am creating a todo list app in flask python and mysql as my school assignment. problem is i have a “complete” field on my task form and in my db, when i click the checkbox on the form to check it as complete and refresh my web page it goes back to default unchecked and doesn`t update the db.

here is my checkbox:

<td>
        <div class="checkbox-container">
          <input id="chkDone" name="done" type="checkbox"> Mark as Done <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
        </div>
      </td>

and here is my inline Js:

<script>
function check() {
  document.getElementById("chkDone").checked = true;
}

function uncheck() {
  document.getElementById("chkDone").checked = false;
}
</script>

javascript – Bunch of errors coming from WP Includes folder

enter image description here

I do not know why, but I’ve got a bunch of errors in the backend, most of which coming from the wp-includes folder.

I tried to replicate the bug in a staging area, with no success. I’ve tried desactivating most plugins (but I’m stuck in production) and to no avail too.

Any ideas as to how I could clean up this bug?

javascript – Sharepoint list last modified date

I use this code to get the date of the last edit of a certain list.
Now I want to loop through the listitems and identify the item that was changed last, so i.e. that has the same date as the lastItemModifiedDate()

How you I do this?

Anyone?

ExecuteOrDelayUntilScriptLoaded(Initializeall, 'sp.js');
 function Initializeall()
{

 var ctx = SP.ClientContext.get_current();
 var web = ctx.get_web();
 var lists = web.get_lists();
 var list = lists.getByTitle("Sample");
ctx.load(list, "LastItemModifiedDate");
ctx.executeQueryAsync(
function() {
    var lastmodified = list.get_lastItemModifiedDate();
alert(lastmodified);
},
function() {}
);
}
</script>

performance – How to simplify and optimize bitwise get/set operations on a large bit buffer in JavaScript?

const a1 = uint8_get(0b10100000, 0, 1)
assertBits(a1, '1')

const a2 = uint8_get(0b10100000, 0, 2)
assertBits(a2, '10')

const a3 = uint8_get(0b10100000, 0, 3)
assertBits(a3, '101')

const a4 = uint8_get(0b10111001, 2, 4)
assertBits(a4, '1110')

const a5 = uint8_get(0b10111001, 0, 6)
assertBits(a5, '101110')

const b0 = uint8_set(0, 1, 1)
assertBits(b0, '1000000')

const b1 = uint8_set(0b10111001, 1, 0b10)
assertBits(b1, '11011001')

const b2 = uint8_set(0b10111001, 1, 0b1001)
assertBits(b2, '11001001')

const b3 = uint8_set(0b10111001, 3, 0b1001)
assertBits(b3, '10110011')

const b4 = uint8_set(0b10111001, 4, 0b1001)
assertBits(b4, '10111001')

const b5 = uint8_set(0b10111001, 5, 0b101)
assertBits(b5, '10111101')

const c1 = uint8_clear(0b10111001, 2, 3)
assertBits(c1, '10000001')

const c2 = uint8_clear(0b10111001, 0, 3)
assertBits(c2, '11001')

const d1 = uint8_set_with_leading_space(0b10111001, 2, 3, 2)
assertBits(d1, '10010001')

const e1 = new Uint8Array(16)
buf_set(e1, 0, 5)
assertBuffer(e1, 0, '10100000')
buf_set(e1, 6, 5)
assertBuffer(e1, 0, '10100010')
assertBuffer(e1, 1, '10000000')

const e2 = new Uint8Array(16)
buf_set(e2, 0, 5)
assertBuffer(e2, 0, '10100000')
buf_set(e2, 20, 5)
assertBuffer(e2, 0, '10100000')
assertBuffer(e2, 1, '0')
assertBuffer(e2, 2, '1010')
assertBuffer(e2, 3, '0')

const f1 = new Uint8Array(16)
f1(0) = 0b10111001
f1(1) = 0b10111001
f1(3) = 0b10111001
const f2 = new Uint8Array(16)
buf_get(f1, 0, 8, f2, 0)
assertBuffer(f2, 0, '10111001')

const f3 = new Uint8Array(16)
f3(0) = 0b10111001
f3(1) = 0b10111001
f3(3) = 0b10111001
const f4 = new Uint8Array(16)
buf_get(f3, 1, 8, f4, 0)
assertBuffer(f4, 0, '1110011')
assertBuffer(f4, 1, '0')

const f5 = new Uint8Array(16)
f5(0) = 0b10111001
f5(1) = 0b10111001
f5(3) = 0b10111001
const f6 = new Uint8Array(16)
buf_get(f5, 0, 16, f6, 0)
assertBuffer(f6, 0, '10111001')
assertBuffer(f6, 1, '10111001')

const f7 = new Uint8Array(16)
f7(0) = 0b10111001
const f8 = new Uint8Array(16)
buf_get(f7, 2, 2, f8, 0)
assertBuffer(f8, 0, '11')

const f9 = new Uint8Array(16)
f9(0) = 0b10111001
f9(1) = 0b10111001
f9(3) = 0b10111001
const f10 = new Uint8Array(16)
buf_get(f9, 0, 2, f10, 0)
assertBuffer(f10, 0, '10')

const f11 = new Uint8Array(16)
f11(0) = 0b10111001
f11(1) = 0b10111001
f11(3) = 0b10111001
const f12 = new Uint8Array(16)
buf_get(f11, 1, 16, f12, 0)
assertBuffer(f12, 0, '1110011')
assertBuffer(f12, 1, '1110010')

function buf_get(readUint8Buffer, readLeft, readSize, writeUint8Buffer, writeLeft) {
  buf_get_impl(readUint8Buffer, readLeft, readSize, writeLeft, function(l, s, b){
    buf_set_with_leading_space(writeUint8Buffer, l, s, b)
  })
}

function buf_get_with_leading_space(readUint8Buffer, readLeft, readSize) {
  let uint32 = 0
  buf_get_impl(readUint8Buffer, readLeft, readSize, 0, function(l, s, b){
    uint32 = uint8_set_with_leading_space(uint32, l, s, b)
  })
  return uint32
}

// since this was used in two places above I refactored it out.
function buf_get_impl(readUint8Buffer, readLeft, readSize, writeLeft, cb) {
  let i = 0
  while (readSize) {
    let readUint8Offset = readLeft >> 3
    let readBitOffset = readLeft % 8
    let readRightBitSize = Math.min(8, readSize + readBitOffset) - readBitOffset
    var strange = (readBitOffset + readRightBitSize) == 8
    let uint8 = readUint8Buffer(readUint8Offset)
    let bits = uint8_get(uint8, readBitOffset, readRightBitSize)
    cb(writeLeft, strange ? readRightBitSize : 8, bits)
    readSize -= readRightBitSize
    if (strange) {
      let uint8 = readUint8Buffer(readUint8Offset + 1)
      let bits = uint8_get(uint8, 0, 8 - readRightBitSize)
      cb(writeLeft, 8, bits)
      writeLeft += (8 - readRightBitSize)
      readLeft += (8 - readRightBitSize)
      // readSize -= (8 - readRightBitSize)
    }
    writeLeft += readRightBitSize
    readLeft += readRightBitSize
  }
}

function buf_set_with_leading_space(writeUint8Buffer, left, size, writeUint8) {
  buf_clear(writeUint8Buffer, left, size - left)
  let writeSize = uint8_get_size(writeUint8)
  let newLeft = left + size - writeSize
  buf_set(writeUint8Buffer, newLeft, writeUint8)
}

function buf_set(writeUint8Buffer, left, writeUint8) {
  let writeSize = uint8_get_size(writeUint8)
  let writeUpdated = writeUint8 << (8 - writeSize)
  let readUint8Left = left >> 3
  let readUint8a = writeUint8Buffer(readUint8Left)
  let readBitLeft = left % 8
  let readStartSize = 8 - readBitLeft
  let writeUint8Subseta = uint8_get(writeUpdated, 0, readStartSize)
  let outUint8a = uint8_set(readUint8a, readBitLeft, writeUint8Subseta)
  writeUint8Buffer(readUint8Left) = outUint8a
  let extent = readBitLeft + writeSize
  if (extent > 8) {
    let writeUint8SubsetbSize = extent - 8
    let writeUint8Subsetb = uint8_get(writeUpdated, readStartSize, writeUint8SubsetbSize)
    let readUint8b = writeUint8Buffer(readUint8Left + 1)
    let clearedUint8 = uint8_clear(readUint8b, 0, writeUint8SubsetbSize)
    let outUint8b = uint8_set_with_leading_space(clearedUint8, 0, writeUint8SubsetbSize, writeUint8Subsetb)
    writeUint8Buffer(readUint8Left + 1) = outUint8b
  }
}

function buf_clear(writeUint8Buffer, left, size) {
  // this currently allows local tests to pass
  // as long as you are just loading into a buffer
  // straight left to right.
  // i haven't gotten to clearing buffers yet, so
  // you can just ignore this for now to keep it simpler.
}

function uint8_get_size(n) {
  let i = 0
  while (n) {
    i++
    n >>= 1
  }
  return i
}

function uint8_get(n, l, s) {
  let r = 8 - l - s
  let p = 1 << 8
  let o = p - 1
  let ol = o << r
  let or = o >> l
  let om = or & ol
  let x = n & om
  return x >> r
}

function uint8_set(n, i, x) {
  let o = 0xff // 0b11111111
  let c = uint8_get_size(x)
  let j = 8 - i // right side start
  let k = j - c // right side remaining
  let h = c + i
  let a = x << k // set bits
  let b = a ^ o // set bits flip
  let d = o >> h // mask right
  let q = d ^ b //
  let m = o >> j // mask left
  let s = m << j
  let t = s ^ q // clear bits!
  let w = n | a // set the set bits
  let z = w & ~t // perform some magic https://stackoverflow.com/q/8965521/169992
  return z
}

function uint8_clear(n, i, c) {
  let s = i + c
  let r = 8 - s
  let p = 1 << 8
  let o = p - 1
  let j = o >> i
  let k = o << r
  let h = j & k
  let g = ~h
  let z = n & g
  return z
}

function uint8_set_with_leading_space(uint8, left, size, value) {
  uint8 = uint8_clear(uint8, left, size)
  let writeSize = uint8_get_size(value)
  let newLeft = left + size - writeSize
  return uint8_set(uint8, newLeft, value)
}

function assertBits(a, b) {
  assertEqual(a.toString(2), b)
}

function assertBuffer(buffer, index, value) {
  assertEqual(buffer(index).toString(2), value)
}

function assertEqual(a, b) {
  if (a != b) {
    throw new Error(`${a} != b`)
  }
  console.log('success')
}

javascript – How can I implement a Boardgame.io project using Webpack?

boardgame.io and webpack
This tutorial is derived from the official Boardgame.io Tutorial. It uses Webpack as an alternative to using React or Parcel.

This tutorial walks through implementing a simple game of Tic-Tac-Toe.

Setup

We’re going to use node.js modules with our web client, so we’ll need to use some kind of build system to compile our code for the browser. In this version of the tutorial, we will use Webpack to package the javascript code our web client needs into a single file dist/main.js

Let’s create a new Node project from the command line:

mkdir bgio-tutorial
cd bgio-tutorial
npm init -yes

We’re going to add boardgame.io and Webpack modules to help us build our app:

npm install boardgame.io
npm install --save-dev webpack webpack-cli

Now, let’s create a basic HTML page that will load our app:

index.html:

<!DOCTYPE html>
<html>
  <head>
    <title>boardgame.io Tutorial</title>
    <meta charset="utf-8" />
  </head>
  <body>
    <div id="app"></div>
    <script src="https://gamedev.stackexchange.com/./dist/main.js"></script>
  </body>
</html>

Next, create a basic http-server to share our html and javascript files:

server.js:

const PORT = 3004;                                       

const fs = require('fs');                                
    http = require('http');                              

http.createServer(function (req, res)
{
  console.log(`Request for url:${req.url}`);             

  if (req.url == '/')                                    
    req.url = '/index.html';                             

  fs.readFile(__dirname + req.url, function (err,data) { 
    if (err) {                                           
      res.writeHead(404);                                
      res.end(JSON.stringify(err));                      
      return;                                            
    }                                                    
    res.setHeader('Cache-Control', 'no-store');          

    if (req.url.endsWith('.js'))                         
      res.setHeader('Content-Type', 'text/javascript');  

    res.writeHead(200);                                  
    res.end(data);                                       
  });                                                    
}).listen(PORT);                                         

console.log(`Server started on port ${PORT}`);   

Create a src folder to hold our game files:

mkdir src

Our completed project directory will look like this:

bgio-tutorial/
├── dist
│   └── main.js
├── index.html
├── node_modules/
├── package-lock.json
├── package.json
├── server.js
└── src/
    ├── App.js
    └── Game.js

Defining a Game

We define a game by creating an object whose contents tell boardgame.io how your game works. More or less everything is optional, so we can start simple and gradually add complexity. To start, we’ll add a setup function, which will set the initial value of the game state G, and a moves object containing the moves that make up the game.

A move function receives the game state G and updates it to the desired new state. It also receives ctx, an object managed by boardgame.io that contains metadata like turn and currentPlayer. After G and ctx, moves can receive arbitrary arguments that you pass in when making the move.

In Tic-Tac-Toe, we only have one type of move and we will name it clickCell. It will take the ID of the cell that was clicked and update that cell with the ID of the player who clicked it.

Let’s put this together in src/Game.js to start defining our game:

src/Game.js:

export const TicTacToe = {
  setup: () => ({ cells: Array(9).fill(null) }),

  moves: {
    clickCell: (G, ctx, id) => {
      G.cells(id) = ctx.currentPlayer;
    },
  },
};

NOTE: The setup function will receive ctx as its first argument. This is useful if you need to customize the initial state based on some field in ctx — the number of players, for example — but we don’t need that for Tic-Tac-Toe.

Creating a Client

We’ll start by creating a class to manage our web app’s logic in src/App.js.

In the class’s constructor we’ll create a boardgame.io client and call its start method to run it.
src/App.js:

import { Client } from 'boardgame.io/client';
import { TicTacToe } from './Game';

class TicTacToeClient {
  constructor() {
    this.client = Client({ game: TicTacToe });
    this.client.start();
  }
}

const app = new TicTacToeClient();

Let’s also add two scripts to package.json to make serving the web app simpler:

package.json:

{
  "scripts": {
    "webpack": "webpack-cli --mode=development src/App.js",
    "start": "node server.js"
  }
}

Pack our classes and packages for distribution to client browsers:

npm run webpack

Open port 3004 on your firewall if necessary. On my CentOS 8 server I run:

sudo firewall-cmd --zone dmz --add-port 3004/tcp
sudo firewall-cmd --zone dmz --add-port 3004/tcp --permanent

You can now serve the app from the command line by running:

npm start

You should now be able to view the site in your browser. If you started the server on the same machine, just browse: http://localhost:3004

Although we haven’t built any UI yet, boardgame.io renders a Debug Panel. This panel means we can already play our Tic-Tac-Toe game!

You can make a move by clicking on clickCell on the Debug Panel, entering a number between 0 and 8, and pressing Enter. The current player will make a move on the chosen cell. The number you enter is the id passed to the clickCell function as the first argument after G and ctx. Notice how the cells array on the Debug Panel updates as you make moves. You can end the turn by clicking endTurn and pressing Enter. The next call to clickCell will result in a “1” in the chosen cell instead of a “0”.

enter image description here

Note: You can turn off the Debug Panel by passing debug: false in the Client config.

This is the end of the WebPack-specific content of the tutorial. You can now complete the “Plain JS” version of the official tutorial continuing from the Game Improvements section.

javascript – How Do I Display My React Application on the LocalHost after making revisions?

Good evening,

I have been learning Front End Web Development with React through Coursera.org. While I have part of one foot inside the door with the knowledge of web design I acquired previously through Coursera.org, React is all new to me.

Somehow through a lot of trial and error and watching over and over again the videos of the lectures on how to install the react app, I managed to display the react app at the beginning. But the webpage was blank it did not have any design or text in it. Once I started to add the code that the professor was providing us in the videos, everytime I saved the changes and checked the localhost, it kept displaying an error page. When I completed the first assignment, of course the my React app was not displaying, but I passed the assignment.

Now I am on my second assignment and I need to see if what my professor wants me to display on the React app through the instructions given displays. I need to see whether the code that I research and the revisions that will make as a result of the research is correct. Right now I feel I am blinded because i cannot see if whatever code I try works.

What I am planning to do for this Assignment 2 is go over the lectures prior to Assignment 1 so that I can try to reinstall the app and also pin point what is wrong with the code I submitted in Assignment 1. But also I can only assume that I must have made a lot of mistakes copying the code the professor gave me in the videos from the first week of lessons.

Right now, I do not have a working React App.

Any suggestions are greatly appreciated.

Millie

javascript – Como contar el tiempo en que la pestaña del cronometro está cerrada

estoy tratando de hacer que este cronómetro guarde el tiempo que lleva recorrido y lo logré con localstorage, es decir con el código que tengo el cronometro guarda el tiempo cada vez que refresco la pestaña, el problema empieza cuando cierro la pestaña y la dejo cerrada por un tiempo, el cronometro a pesar de haber guardado el tiempo que llevaba en lugar de sumar todo el tiempo que estuvo cerrada la pantalla reanuda el conteo desde donde se habia quedado, es decir que no tendría que cerrar la pestaña si quisiera que la cuenta sea correcta, intenté hacerlo con otro if en la function .onload, pero lo logro hacer que funcione, no me gustaria cambiar mucho la estructura del código, quiza solo ponerle una condición que haga que si el cronometro estaba corriendo cuando se cerro la pantalla reconozca la ultima vez que precioné el boton para reanudarlo o iniciarlo y que trabaje con ese tiempo,

muchas gracias.

 <!DOCTYPE html>
      <html lang="es">
      <head>
      <meta charset="utf-8">

      <script>
         var islog = localStorage.getItem("islog"); 
         var acumularlog = localStorage.getItem("acumularlog");
         var control1; 
         var logInicial = localStorage.getItem("logInicial");
         var logResume;
         var acumullogResume;
         window.onload = function (){

         pantalla1 = document.getElementById("crono");
          if ((islog == null)||(islog == "Log Out")) {
            acumularlog2 = new Date();
            acumularlog2.setTime(acumularlog); 
            cc1 = Math.round(acumularlog2.getMilliseconds()/10);
            ss1 = acumularlog2.getSeconds();
            mm1 = acumularlog2.getMinutes();
            hh1 = acumularlog2.getHours()-18;
            if (cc1 < 10) {cc1 = "0"+cc1;}
            if (ss1 < 10) {ss1 = "0"+ss1;}
            if (mm1 < 10) {mm1 = "0"+mm1;}
            if (hh1 < 10) {hh1 = "0"+hh1;}
            pantalla1.innerHTML = hh1+" : "+mm1+" : "+ss1;}
          else { 
            start1 ()
          }}

    function start1 () {
    pantalla1 = document.getElementById("crono");
    if (islog == null) { 
      logInicial = new Date();
      localStorage.setItem("logInicial", logInicial.getTime());
      control1 = setInterval(cronometro1,10);
      islog = true;
      localStorage.setItem("islog", islog);
      document.getElementById("button1").value = "Log Out";}   
    else if (islog == true) {
      clearInterval(control1);
      islog = "Log Out";
      localStorage.setItem("islog", islog);
      document.getElementById("button1").value = "Log In";}
   else if (islog = "Log Out"){
    logActual2 = new Date() ;
    logActual2 = logActual2.getTime(); 
    localStorage.setItem("logActual2", logActual2);
      acumullogResume = logActual2 - localStorage.getItem("acumularlog");
      logResume = acumullogResume;
      logInicial = new Date();
      logInicial.setTime(logResume);
      control1 = setInterval(cronometro1,10);
      islog = true;
      localStorage.setItem("islog", islog);
      document.getElementById("button1").value = "Log Out";}
      }

  function cronometro1 () {
    logActual = new Date();
    acumularlog = logActual - logInicial;
    localStorage.setItem("acumularlog", acumularlog);
    acumularlog2 = new Date();
    acumularlog2.setTime(acumularlog); 
    cc1 = Math.round(acumularlog2.getMilliseconds()/10);
    ss1 = acumularlog2.getSeconds();
    mm1 = acumularlog2.getMinutes();
    hh1 = acumularlog2.getHours()-18;
    if (cc1 < 10) {cc1 = "0"+cc1;}
    if (ss1 < 10) {ss1 = "0"+ss1;} 
    if (mm1 < 10) {mm1 = "0"+mm1;}
    if (hh1 < 10) {hh1 = "0"+hh1;}
    pantalla1.innerHTML = hh1+" : "+mm1+" : "+ss1;}

 </script>

   <style>
    .crono_wrapper {text-align:center;width:200px;}
   </style>
  </head>

  <body>

    <div class="crono_wrapper">
       <h2 id='crono'>00 : 00 : 00</h2>
       <input type="button" value="Empezar" id="button1" onclick="start1() ">
    </div>

  </body>
  </html>

javascript – How do document databases (like mongodb) store data behind the scenes?

For a couple of reason which need not be mentioned here, because they are rather complex, I need to program my own NoSQL document database in node.js. However, I am quite confused as to what is the best way to store this data.

I’ve searched around on google, but most information is on how to use a database, not how to program one. The following questions were a blank on google:

  1. To me, the name “document database”, and the fact that the smallest unit of data is a “document”, implies that each one would be stored in an own file. Is this correct?

  2. Also, how are collections grouped together? Is each collection a folder of documents? Or a manifestation file pointing to different documents in a collection?

  3. How should relations between documents be implemented? Is it compliant to the term “NoSQL database” to even have a concept of relations?

  4. Should a NoSQL database contain a way to create schemas for documents, or should NoSQL databases be free-form and schema-less?

I would greatly appreciate it if anyone can answer these questions!👍