How to reorder an array list by comparing the Id and the reference_id in the same array in react

This is the array what I am getting

[
  { id: 1, name: 'hello world', reference_id: null },
  { id: 2, name: 'hello world', reference_id: null },
  { id: 3, name: 'hello world', reference_id: 1 },
  { id: 4, name: 'hello world', reference_id: null },
  { id: 5, name: 'hello world', reference_id: 1 },
  { id: 6, name: 'hello world', reference_id: 2 },
]

I need to reorder this array into something similar to this.

[
  { id: 1, name: 'hello world', reference_id: null },
  { id: 3, name: 'hello world', reference_id: 1 },
  { id: 5, name: 'hello world', reference_id: 1 },
  { id: 2, name: 'hello world', reference_id: null },
  { id: 6, name: 'hello world', reference_id: 2 },
  { id: 4, name: 'hello world', reference_id: null },
]

This is the code which I tried

const parentIndex = skus?.findIndex(item => item.id === item.reference_id);
    console.log(parentIndex)

    if (parentIndex !== -1) {
      const parentId = skus[parentIndex].id;

      const parentItem = skus.splice(parentIndex, 1)[0];
      const referencedItem = skus.find(item => item.id === parentId);

      if (referencedItem) {
        const referencedIndex = skus.indexOf(referencedItem);
        skus.splice(referencedIndex + 1, 0, parentItem);
      } else {
        skus.push(parentItem);
      }
    }

When I run this code I am getting some weird unexpected results and most of the time it’s not running after the first line.

Can someone help me to resolve this issue I am struggling to find a solution.

TicTacToe MinMax logic problem, why does the method return the wrong move?

MinMax algo returns a completely illogical move (does not counter player) >.<

Hey,

I have some logic error in the getBestMove method of MinMax class implementation. I think everything looks ok.

I do a test in GameRunner and it takes the correct board, but returns a completely illogical move (does not counter player).

public class MinMax3x3 {

    public int[] getBestMove(char[][] board) {
        char computerSymbol = Symbol.X;
        int bestScore = Integer.MIN_VALUE;
        int row = -1;
        int col = -1;

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (board[i][j] == Symbol.EMPTY_FIELD) {
                    board[i][j] = computerSymbol;
                    int score = minimax(board, 0, false);
                    board[i][j] = Symbol.EMPTY_FIELD;
                    if (score > bestScore) {
                        bestScore = score;
                        row = i;
                        col = j;
                    }
                }
            }
        }
        int[] bestMove = {row, col};
        return bestMove;
    }

    public int minimax(char[][] board, int depth, boolean isMaximizing) {
        char playerSymbol = Symbol.O;
        char computerSymbol = Symbol.X;
        int result = analyze3x3(board, playerSymbol, computerSymbol);

        if (result != 0) {
            return result;
        }

        if (isMaximizing) {
            int bestScore = Integer.MIN_VALUE;
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 3; j++) {
                    if (board[i][j] == Symbol.EMPTY_FIELD) {
                        board[i][j] = computerSymbol;
                        int score = minimax(board, depth + 1, false);
                        board[i][j] = Symbol.EMPTY_FIELD;
                        bestScore = Math.max(score, bestScore);
                    }
                }
            }
            return bestScore;
        } else {
            int bestScore = Integer.MAX_VALUE;
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 3; j++) {
                    if (board[i][j] == Symbol.EMPTY_FIELD) {
                        board[i][j] = playerSymbol;
                        int score = minimax(board, depth + 1, true);
                        board[i][j] = Symbol.EMPTY_FIELD;
                        bestScore = Math.min(score, bestScore);
                    }
                }
            }
            return bestScore;
        }
    }

    private int analyze3x3(char[][] board, char playerSymbol, char computerSymbol) {
        // Check rows
        for (int row = 0; row < 3; row++) {
            if (board[row][0] == playerSymbol && board[row][1] == playerSymbol && board[row][2] == playerSymbol) {
                return 1; // Player wins
            } else if (board[row][0] == computerSymbol && board[row][1] == computerSymbol && board[row][2] == computerSymbol) {
                return -1; // Computer wins
            }
        }

        // Check columns
        for (int column = 0; column < 3; column++) {
            if (board[0][column] == playerSymbol && board[1][column] == playerSymbol && board[2][column] == playerSymbol) {
                return 1; // Player wins
            } else if (board[0][column] == computerSymbol && board[1][column] == computerSymbol && board[2][column] == computerSymbol) {
                return -1; // Computer wins
            }
        }

        // Check diagonals
        if ((board[0][0] == playerSymbol && board[1][1] == playerSymbol && board[2][2] == playerSymbol) ||
                (board[0][2] == playerSymbol && board[1][1] == playerSymbol && board[2][0] == playerSymbol)) {
            return 1; // Player wins
        } else if ((board[0][0] == computerSymbol && board[1][1] == computerSymbol && board[2][2] == computerSymbol) ||
                (board[0][2] == computerSymbol && board[1][1] == computerSymbol && board[2][0] == computerSymbol)) {
            return -1; // Computer wins
        }

        // It's a draw
        return 0;
    }

}


public class GameRunner {
    public static void main(String[] args) {

        char board[][] = {{'x', 'o', ' '},
                          {' ', 'o', ' '},
                          {' ', ' ', ' '}};

        MinMax3x3 bestMove = new MinMax3x3();
        int[] lol = bestMove.getBestMove(board);
        System.out.printf(lol[0] + ", " + lol[1]);

Result lol: [0,2] / should be lol: [2,1].
Something is wrong, I check in debugger, the board is passed correctly.

Discord.js Musik Bot disconnected ungewollt

I have written a Discord.js bot that currently runs in Discord.js version 14.11.0.
It should be able to play music by command, which actually works.
However… After about 40 seconds the bot stops playing and leaves the channel about 20 seconds later.
It seems to clear the queue and does not throw an error.
The problem is not caused by old versions like discord.js or @discordjs/voice.
The bot is supposed to run on my local PC, which is why I suspected connection errors, but I haven’t figured out the best way to catch them.

play.js: (Slash Command)

const { SlashCommandBuilder } = require("@discordjs/builders")
const { EmbedBuilder } = require('discord.js');
const { QueryType } = require("discord-player")

module.exports = {
    data: new SlashCommandBuilder()
        .setName("play")
        .setDescription("loads songs from youtube")
        .addSubcommand((subcommand) =>
            subcommand
                .setName("song")
                .setDescription("Loads a single song from a url")
                .addStringOption((option) => option.setName("url").setDescription("the song's url").setRequired(true))
        )
        .addSubcommand((subcommand) =>
            subcommand
                .setName("playlist")
                .setDescription("Loads a playlist of songs from a url")
                .addStringOption((option) => option.setName("url").setDescription("the playlist's url").setRequired(true))
        )
        .addSubcommand((subcommand) =>
            subcommand
                .setName("search")
                .setDescription("Searches for sogn based on provided keywords")
                .addStringOption((option) =>
                    option.setName("searchterms").setDescription("the search keywords").setRequired(true)
                )
        ),
    run: async ({ client, interaction }) => {
        if (!interaction.member.voice.channel) return interaction.editReply("You need to be in a VC to use this command")

        const queue = await client.player.createQueue(interaction.guild)
        if (!queue.connection) await queue.connect(interaction.member.voice.channel)

        let embed = new EmbedBuilder()

        if (interaction.options.getSubcommand() === "song") {
            let url = interaction.options.getString("url")
            const result = await client.player.search(url, {
                requestedBy: interaction.user,
                searchEngine: QueryType.YOUTUBE_VIDEO
            })
            if (result.tracks.length === 0)
                return interaction.editReply("No results")
            
            const song = result.tracks[0]
            await queue.addTrack(song)
            embed
                .setDescription(`**[${song.title}](${song.url})** has been added to the Queue`)
                .setThumbnail(song.thumbnail)
                .setFooter({ text: `Duration: ${song.duration}`})
                .setColor(`#970b0b`)

        } else if (interaction.options.getSubcommand() === "playlist") {
            let url = interaction.options.getString("url")
            const result = await client.player.search(url, {
                requestedBy: interaction.user,
                searchEngine: QueryType.YOUTUBE_PLAYLIST
            })

            if (result.tracks.length === 0)
                return interaction.editReply("No results")
            
            const playlist = result.playlist
            await queue.addTracks(result.tracks)
            embed
                .setDescription(`**${result.tracks.length} songs from [${playlist.title}](${playlist.url})** have been added to the Queue`)
                .setThumbnail(playlist.thumbnail)
                .setColor(`#970b0b`)
        } else if (interaction.options.getSubcommand() === "search") {
            let url = interaction.options.getString("searchterms")
            const result = await client.player.search(url, {
                requestedBy: interaction.user,
                searchEngine: QueryType.AUTO
            })

            if (result.tracks.length === 0)
                return interaction.editReply("No results")
            
            const song = result.tracks[0]
            await queue.addTrack(song)
            embed
                .setDescription(`**[${song.title}](${song.url})** has been added to the Queue`)
                .setThumbnail(song.thumbnail)
                .setFooter({ text: `Duration: ${song.duration}`})
                .setColor(`#970b0b`)
        }
        if (!queue.playing) await queue.play()
        await interaction.editReply({
            embeds: 
        })
    } 
}

And here are the relevant parts from the index.js:

// Requirements aka dependencies.
require("dotenv").config()   // Required for .env files.
const fs = require("fs")  // This package is for reading files and getting their inputs.
const yaml = require("js-yaml");   // For the config.
const { Player } = require("discord-player")   // For music commands.
const { Client, Collection, Partials, EmbedBuilder } = require("discord.js")                   // Intents, MessageEmbed, GatewayIntentBits

// Create a new Client
const client = new Client({
    partials: [Partials.Channel, Partials.user, Partials.Message, Partials.Reaction, Partials.GuildMember],
    intents: [3243773],
    messageCacheLifetime: 60,
    fetchAllMembers: false,
    messageCacheMaxSize: 20,
    restTimeOffset: 0,
    restWsBridgetimeout: 100,
    disableEveryone: true
})

// Collections
client.commands = new Collection();
client.cooldowns = new Collection(); // cooldowns for users

// Load the config
try {
    client.conf = yaml.load(fs.readFileSync('./src/config.yaml', 'utf8'));
} catch (error) {
    console.log(error);
    process.exit();
}

// YTDL option for the /play command
client.player = new Player(client, {
    ytdlOptions: {
        quality: "highestaudio",
        highWaterMark: 1 << 25
    }
})

// Rules for assigning files
const commandfiles = fs.readdirSync("./src/commands").filter(file => file.endsWith(".js"))
const eventFiles = fs.readdirSync("./src/events").filter(file => file.endsWith(".js"))

// Assign files for commands etc
commandfiles.forEach(commandfile => {
    const command = require(`./commands/${commandfile}`)
    client.commands.set(command.data.name, command)
})
eventFiles.forEach(eventFile => {
    const event = require(`./events/${eventFile}`)
    client.on(event.name, (...args) => event.execute(client, ...args))
})

// Confirmation of successful bot launch and status setting
client.once("ready", () => {
    console.log(`Ready! Logged in as ${client.user.tag}! Im on ${client.guilds.cache.size} guild(s)!`)
})


// Error Catcher
client.on("interactionCreate", (interaction) => {
   async function handleCommand() {
       if (!interaction.isCommand()) return

       const slashcmd = client.commands.get(interaction.commandName)
       if (!slashcmd) interaction.reply(client.conf.Invalid)

       await interaction.deferReply()
       await slashcmd.run({ client, interaction })
   }
   handleCommand()
})

// Bot login Line (DO NOT CHANGE!)
client.login(client.conf.token)

Of course, the bot should play the queue in full length and then leave the channel as usual.
However, it breaks off after the first 40 seconds and leaves the voice channel shortly afterwards because the queue seems to be empty.

Some more information is given above.

How to Stay in same link in iframe after refresh?

i’m using iframe for visit my website some page. What i’m facing now if i visit 2 pages inside of iframe, after refresh the whole page iframe coming to 1st page.

i want to stay in same page when page will reload.

<iframe src="https://my-domain.com/pagelink" name="iframe_a" style="width:100%; height:200px;" title="Iframe" id="frame"></iframe>

graphql – Is there a way to avoid re-fetching data that already exists on the client, without having to explicitly re-stitch data on the client

I have some simple associations in my database, which I fetch using the below graphql queries.

// MakerOrders query, performed first

maker {
  id
  orders {
    id
    customer {
      id
    }
  }
}

// MakerProducts query, performed after MakerOrders

maker {
  products {
    id
    order {
      id
      customer {
        id
      }
    }
  }
}

The associations are:

  • Orders to Customers, One to One

  • Products to Orders, One to One (can be null)

I first fetch my orders with the MakerOrders query.

Later in the application, I fetch my products with the MakerProducts query.

  • Note, if a product has an order, then this order must already exist in the cache from MakerOrders.

I am wondering if there is a simple way to avoid unnecessarily re-fetching order fields from the server (in this case, customer), whilst still being able to associate the products to their orders, and not having to re-stitch the state together on the client.

If we naively do something like this

// using @apollo/client

const { data } = useQuery(MakerProducts)

Then the server will always do a complete re-fetch of customer (as it doesn’t know that we already have them).

One solution is to remove customer from MakerProducts, and instead fetch it later on the client (the re-stitching approach):

const client = useApolloClient()

const { data } = useQuery(MakerProducts)

const products = data.maker.products.map(p => {
  const order = client.readFragment({
    id: `Order:${p.order.id}`,
    fragment: fragments.OrderFields
  })
  return { ...p, order }
})

I am wondering if there are any other solutions to this problem, such as getters on the client (like product.getOrder), as opposed to having to explicitly access fields as above. I understand graphql is just a specification so there may be nothing noted inside of that, but am open to suggestions in @apollo/client.

How to setup a proxy middleware in production

I have been working on a React app for a considerable amount of time. Recently, I noticed a particular issue. While I’m aware that it’s possible to set up a proxy middleware in the development server, I’m unsure if the same can be done for production. The problem is that I can see all the API endpoints, along with the payload and response, in the network console of the browser. I want to conceal the actual API endpoints and the associated payload. I’ve searched the internet for solutions and found some tools and resources that allow setting up a proxy middleware on development servers or local machines. Now, I want to implement a proxy middleware for production.

On local machines, I successfully set up a proxy for the React app, but I’m unsure about how to send requests to API endpoints and retrieve the responses. I would greatly appreciate any assistance in this matter. If there are any available resources, they would be extremely helpful.

For your reference, I have included the configuration file below. I used the ‘http-proxy-middleware’ package to set up the proxy in the React app.

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function (app) {
    app.use('/api1', createProxyMiddleware(
        {
            target: 'https://book.com/retrive-details/',
            changeOrigin: true,
            pathRewrite: {
                '^/api1': ''
            }
        })
    );

    app.use('/api2', createProxyMiddleware(
        {
            target: 'https://book.com/send-details/',
            changeOrigin: true,
            pathRewrite: {
                '^/api2': ''
            }
        })
    );
};

The provided code only covers the frontend configuration. I’m uncertain about how to pass data to the backend using a proxy in a production environment. My backend stack utilizes Laravel and Apache.

Problem passing headers value to a token variable in NodeJS (type error says undefined object)

I am getting an error trying to pass the headers value from Postman to a NodeJS service.

I created a method to handle the request object called ‘data.headers.token’ that is supposed to pass the Postman headers value to a variable I created called ‘token’.

var token = typeof(data.headers.token) == 'string' ? data.headers.token : false;

What I am trying to do is to get the information of a user using a token ID that must match the user’s phone number. The required request must have the token ID in the headers sent from Postman, which must match what is stored in JSON on the Node server.

It does not appear that the ‘data.headers.token’ object is recognized. The error is detected in the method I created called ‘handlers._users.get’.

Here is the code from the source (created as a file I called handlers.js):


/*

These are the request handlers

*/

//Dependencies
var _data = require('./data');
var helpers = require('./helpers');
var config = require('./config');

//Define handlers
var handlers = {};

/*// ping handler
handlers.ping = function(data,callback) {
    callback(200);
}; */

//users handler
handlers.users = function(data,callback) {
    var acceptableMethods = ['post','get','put','delete'];
    if(acceptableMethods.indexOf(data.method) > -1) {
        handlers._users[data.method](data,callback);
    } else {
        callback(405);
    }
};

//Container for the users submethods
handlers._users = {};

//Users post
//required data:firstName, lastName, phone, password, tosAgreement
//optional data: None
handlers._users.post = function(data,callback){
    //check all required fields are filled out
    var firstName = typeof(data.payload.firstName) == 'string' && data.payload.firstName.trim().length > 0 ? data.payload.firstName.trim() : false;
    var lastName = typeof(data.payload.lastName) == 'string' && data.payload.lastName.trim().length > 0 ? data.payload.lastName.trim() : false;
    var phone = typeof(data.payload.phone) == 'string' && data.payload.phone.trim().length == 10 ? data.payload.phone.trim() : false;
    var password = typeof(data.payload.password) == 'string' && data.payload.password.trim().length > 0 ? data.payload.password.trim() : false;
    var tosAgreement = typeof(data.payload.tosAgreement) == 'boolean' && data.payload.tosAgreement == true ? true : false;

    if(firstName && lastName && phone && password && tosAgreement) {
        //make sure that the user does not already exist
        _data.read('users',phone,function(err,data){
            if(err) {
                //hash the password
                var hashedPassword = helpers.hash(password);
                //create the user object
                if(hashedPassword) {
                    var userObject = {
                        'firstName' : firstName,
                        'lastName' : lastName,
                        'phone' : phone,
                        'hashedPassword' : hashedPassword,
                        'tosAgreement' : true
                    };
                    //store the user 
                    _data.create('users',phone,userObject,function(err){
                        if(!err) {
                            callback(200);
                        } else {
                            console.log(err);
                            callback(500,{'Error' : 'Could not create the new user'});
                        }
                    });
                } else {
                    callback(500,{'Error' : 'Could not hash the user's password'});
                }
                
            } else {
                //user already exists
                callback(400,{'Error' : 'A user with that phone number already exists'});
            }
        });
    } else {
        callback(400,{'Error':'Missing required fields'});
    }
};

//Users get
//Required data: phone
//Optional data: none
//only let an authenticated user access their object. Do not let them access other people's data.
handlers._users.get = function(data,callback){
    
    //check that the phone number provided is valid
    var phone = typeof(data.queryStringObject.phone) == 'string' && data.queryStringObject.phone.trim().length == 10 ? data.queryStringObject.phone.trim() : false;
    
    if(phone){
        
        //get the token from the headers
        var token = typeof(data.headers.token) == 'string' ? data.headers.token : false;
        //var token = (data && data.headers && typeof data.headers.token == 'string') ? data.headers.token : false;
       
        //verify that the given token is valid for the phone number
        handlers._tokens.verifyToken(token,phone,function(tokenIsValid){
            if(tokenIsValid) {
                //lookup the user
                _data.read('users',phone,function(err,data){
                    if(!err && data) {
                        //remove the hashed password from the user object before returning it to the requestor
                        delete data.hashedPassword;
                        callback(200,data);
                    } else {
                        callback(404);
                    }
                });
            } else {
                callback(403,{'Error':'Missing required token in header or token is invalid'});       
            }
        });    
    } else {
        callback(400,{'Error' : 'Missing Required Field'});
    }
};

//Users put
//Required data: phone
//Optional data: firstName, lastName, password (at least one must be specified)
//only let an authenticated user update their own object. Do not let them update anyone elses.
handlers._users.put = function(data,callback){
    //check for the required field
    var phone = typeof(data.payload.phone) == 'string' && data.payload.phone.trim().length == 10 ? data.payload.phone.trim() : false;

    //check for the optional fields
    var firstName = typeof(data.payload.firstName) == 'string' && data.payload.firstName.trim().length > 0 ? data.payload.firstName.trim() : false;
    var lastName = typeof(data.payload.lastName) == 'string' && data.payload.lastName.trim().length > 0 ? data.payload.lastName.trim() : false;
    var password = typeof(data.payload.password) == 'string' && data.payload.password.trim().length > 0 ? data.payload.password.trim() : false;

    //error if the phone is invalid
    if(phone) {
        //error if nothing is sent to update
        if(firstName || lastName || password) {
            //get the token from the headers
            var token = typeof(data.headers.token) == 'string' ? data.headers.token : false;
            //verify that the given token is valid for the phone number
            handlers._tokens.verifyToken(token,phone,function(tokenIsValid){
                if(tokenIsValid) {
                    //lookup user
                    _data.read('users',phone,function(err,userData){
                        if(!err && userData) {
                            //update the fields necessary
                            if(firstName){
                                userData.firstName = firstName;
                            }
                            if(lastName){
                                userData.lastName = lastName;
                            }
                            if(password){
                                userData.hashedPassword = helpers.hash(password);
                            }
                            //store the new updates
                            _data.update('users',phone,userData,function(err){
                                if(!err){
                                    callback(200);
                                } else {
                                    console.log(err);
                                    callback(500,{'Error' : 'Could not update the user'});
                                }
                            });
                        } else {
                            callback(400,{'Error' : 'The specified user does not exist'});
                        }
                    });
                } else {
                    callback(403,{'Error':'Missing required token in header or token is invalid'});
                }
            });
        } else {
            callback(400,{'Error' : 'Missing fields to update'});
        }
    } else {
        callback(400,{'Error' : 'Missing required field'});
    }

};

//Users delete
//Required field: phone
//only require an authenticated user delete their object. Do not let anyone else.
//delete or clean up any other data files associated with this user
handlers._users.delete = function(data,callback){
    //check the phone number is valid
    var phone = typeof(data.queryStringObject.phone) == 'string' && data.queryStringObject.phone.trim().length == 10 ? data.queryStringObject.phone.trim() : false;
    if(phone){
         //get the token from the headers
         var token = typeof(data.headers.token) == 'string' ? data.headers.token : false;
         //verify that the given token is valid for the phone number
         handlers._tokens.verifyToken(token,phone,function(tokenIsValid){
             if(tokenIsValid) {
                //lookup the user
                _data.read('users',phone,function(err,data){
                    if(!err && data) {
                        _data.delete('users',phone,function(err,data){
                            if(!err) {
                                callback(200);
                            } else {
                                callback(500,{'Error':'Could not delete the specified user'});
                            }
                        });
                    } else {
                        callback(400,{'Error':'Could not find the specified user'});
                    }
                });
             } else {
                callback(403,{'Error':'Missing required token in header or token is invalid'});
             }
         });
    } else {
        callback(400,{'Error' : 'Missing Required Field'});
    }
};

//Tokens handler
handlers.tokens = function(data,callback) {
    var acceptableMethods = ['post','get','put','delete'];
    if(acceptableMethods.indexOf(data.method) > -1) {
        handlers._tokens[data.method](data,callback);
    } else {
        callback(405);
    }
};

//Container for all the tokens
handlers._tokens = {};

//Tokens - post
//Required data: phone,password 
//Optional: none
handlers._tokens.post = function(data,callback){ 
    var phone = typeof(data.payload.phone) == 'string' && data.payload.phone.trim().length == 10 ? data.payload.phone.trim() : false;
    var password = typeof(data.payload.password) == 'string' && data.payload.password.trim().length > 0 ? data.payload.password.trim() : false;    
    if(phone && password) {
        //lookup the user that matches that phone number
        _data.read('users',phone,function(err,userData){
            if(!err && userData) {
                //hash the sent password and compare it to the password stored in user object
                var hashedPassword = helpers.hash(password);
                if(hashedPassword == userData.hashedPassword) {
                    //if valid, create a new token with a random name. Set expiration date 1 hour in the future
                    var tokenId = helpers.createRandomString(20); //20 character token string
                    var expires = Date.now() + 1000 * 60 * 60;
                    var tokenObject = {
                        'phone' : phone,
                        'id' : tokenId,
                        'expires' : expires
                    };
                    //store the token
                    _data.create('tokens',tokenId,tokenObject,function(err){
                        if(!err){
                            callback(200,tokenObject);
                        } else {
                            callback(500,{'Error':'Could not create the new token'});
                        }
                    });
                } else {
                    callback(400,{'Error':'Password did not match the stored password'});
                }
            } else {
                callback(400,{'Error':'Could not find the specified user'});
            }
        });
    } else {
        callback(400,{'Error':'Missing required fields'});
    }
};

//Tokens - get
//Required data: id
//Optional data: none
handlers._tokens.get = function(data,callback){
    //check id sent is valid
    var id = typeof(data.queryStringObject.id) == 'string' && data.queryStringObject.id.trim().length == 20 ? data.queryStringObject.id.trim() : false;
    if(id){
        //lookup the user
        _data.read('tokens',id,function(err,tokenData){
            if(!err && data) {
                callback(200,tokenData);
            } else {
                callback(404);
            }
        });
    } else {
        callback(400,{'Error' : 'Missing Required Field'});
    }
};

//Tokens - put
//Required: id, extend
//Optional data: none
handlers._tokens.put = function(data,callback){
    var id = typeof(data.payload.id) == 'string' && data.payload.id.trim().length == 20 ? data.payload.id.trim() : false;
    var extend = typeof(data.payload.extend) == 'boolean' && data.payload.extend == true ? true : false;
    if(id && extend) {
        //lookup the token
        _data.read('tokens',id,function(err,tokenData){
            if(!err && tokenData) {
                //check to make sure token is not expired
                if(tokenData.expires>Date.now()){
                    //set expiration an hour from now
                    tokenData.expires = Date.now() + 1000 * 60 * 60;
                    //store the new updates
                    _data.update('tokens',id,tokenData,function(err){
                        if(!err){
                            callback(200);
                        } else {
                            callback(500,{'Error':'Could not update the token's expiration'});
                        }
                    });
                } else {
                    callback(400,{'Error':'Token has already expired and cannot be extended'});
                }
            } else {
                callback(400,{'Error':'Specified token does not exist'});
            }
        });
    } else {
        callback(400,{'Error':'Missing required field(s) are invalid'});
    }

};

//Tokens - delete
//Required data: id
//Optional data: none
handlers._tokens.delete = function(data,callback){
    //check that the id is valid
    var id = typeof(data.queryStringObject.id) == 'string' && data.queryStringObject.id.trim().length == 20 ? data.queryStringObject.id.trim() : false;
    if(id){
        //lookup the token
        _data.read('tokens',id,function(err,data){
            if(!err && data) {
                _data.delete('tokens',id,function(err,data){
                    if(!err) {
                        callback(200);
                    } else {
                        callback(500,{'Error':'Could not delete the specified token'});
                    }
                });
            } else {
                callback(400,{'Error':'Could not find the specified token'});
            }
        });
    } else {
        callback(400,{'Error' : 'Missing Required Field'});
    }
};

//Verify if a given token id is currently valid for a given user
handlers._tokens.verifyToken = function(id,phone,callback){
    //lookup the token
    _data.read('tokens',id,function(err,tokenData){
        if(!err && tokenData){
            //check that the token is for the given user and has not expired
            if(tokenData.phone == phone && tokenData.expires > Date.now()){
                callback(true);
            } else {
                callback(false);
            }
        } else {
            callback(false);
        }
    });
};


//Not found handler
handlers.notfound = function(data,callback) {
    callback(404);
};

//Export the module
module.exports = handlers;

Here is a snippet of the error message I get from the server console:

D:appServiceTokensServicelibhandlers.js:96
        var token = typeof(data.headers.token) == 'string' ? data.headers.token : false;
                                        ^

TypeError: Cannot read properties of undefined (reading 'token')

Consolidate js code in an php loop. Avoid code repeating

I generate a list from a DB with php. There are js functions embedded in each line. As you can see in the code, I have to interact the functions and variables to make them work per line.

<table id="mySEARCH" class="shoppinglist-content">
<!-- ************************************************************************ shopping list beginn-->
<!-- script test start -->
<?php
if(isset($_COOKIE['shoppinglist'])){
  $list = $_COOKIE['shoppinglist'];
  $stmt = $pdo->prepare("SELECT * FROM `$list`");
  $stmt->execute();
  $x = 0;
  foreach($stmt as $item)
  { $x++;?>
    <tr id="line<?php echo $x;?>" style="opacity: 1.0;">
    <td><button id="activ<?php echo $x;?>" class="btn-hide-row" name='activ' onclick="hiddenLine<?php    echo $x;?>();" value="true"><img class="list-icon" id="visibility<?php echo $x;?>" src="images/icon-invisible.png" /></button></td>
     <form action='calculate.php' method='post'>
     <td class="pcs-unit-list"><?php echo $item['pieces']." ".$item['unit']?></td>
     <td name='item' class="shop-list-item" id="item"><?php echo $item['item']?></td>
     <td class="brand-list"><input type='text' id="brand<?php echo $x;?>" class="brand-list" name='brand' value="<?php echo $item['brand']?>" onkeyup="editSave<?php echo $x;?>(), success()"></td>
     <td class="kind-list"><select class="shoppinglist-kind" name='item-kind' id="item-kind<?php echo $x;?>" onchange="editSave<?php echo $x;?>(), success()">
       <option value=""></option>
       <option value="Gemüse" <?php if($item['kind'] == "Gemüse") echo "selected"?>>Gemüse</option>
       <option value="Obst" <?php if($item['kind'] == "Obst") echo "selected"?>>Obst</option>
       <option value="Fleisch" <?php if($item['kind'] == "Fleisch") echo "selected"?>>Fleisch</option>
       <option value="Fisch" <?php if($item['kind'] == "Fisch") echo "selected"?>>Fisch</option>
       <option value="Getreideprod." <?php if($item['kind'] == "Getreideprod.") echo "selected"?>>Getreideprod.</option>
       <option value="Milchprod." <?php if($item['kind'] == "Milchprod.") echo "selected"?>>Milchprod.</option>
       <option value="Gewürze" <?php if($item['kind'] == "Gewürze") echo "selected"?>>Gewürze</option>
       <option value="Knabbern" <?php if($item['kind'] == "Knabbern") echo "selected"?>>Knabbern</option>
       <option value="Getränke" <?php if($item['kind'] == "Getränke") echo "selected"?>>Getränke</option>
       <option value="Kräuter" <?php if($item['kind'] == "Kräuter") echo "selected"?>>Kräuter</option>
       <option value='Hygiene' <?php if($item['kind'] == "Hygiene") echo "selected"?>>Hygiene</option>
       <option value='Putzen' <?php if($item['kind'] == "Putzen") echo "selected"?>>Putzen</option>
       <option value='Haustier' <?php if($item['kind'] == "Haustier") echo "selected"?>>Haustiere</option>
       <option value='Sonstiges' <?php if($item['kind'] == "Sonstiges") echo "selected"?>>Sonstiges</option>
      </select></td>
      <td class="list-button"><button class='btn-list' name='delete' id="btn-locked-<?php echo $x;?>" value="<?php echo $item['id']?>"><img src='images/trashbox.png'></button></td></form></tr>
      <script>
       function editSave<?php echo $x;?>(){
         var id = <?php echo $item['id']?>;
         var brand = $("#brand<?php echo $x;?>").val();
         var itemKind = $("#item-kind<?php echo $x;?>").val();
         $.post("calculate.php", { save: id, brand: brand, itemkind: itemKind },
         function(data) {
           $('#edit-confirm').html(data);
         });
         }
                                function hiddenLine<?php echo $x;?>() {
                                    var line = document.getElementById("line<?php echo $x;?>");
                                    var activ = document.getElementById("activ<?php echo $x;?>");
                                    var brand = document.getElementById("brand<?php echo $x;?>");
                                    var itemKind = document.getElementById("item-kind<?php echo $x;?>");
                                    var btnLocked = document.getElementById("btn-locked-<?php echo $x;?>");
                                    var btnImage = document.getElementById("visibility<?php echo $x;?>");
                                    if(activ.value == "true"){
                                        activ.value = "false";
                                    }else{
                                        activ.value = "true";
                                    }
                                    if(activ.value == "false"){
                                        line.style.opacity = "0.1";
                                        brand.setAttribute("readonly", "");
                                        itemKind.setAttribute("disabled", "");
                                        btnLocked.setAttribute("disabled", "");
                                        btnImage.setAttribute("src", "images/icon-visible.png");
                                        //createCookie('hide-line-<?php echo $x;?>','false');
                                    }
                                    if(activ.value == "true") {
                                        line.style.opacity = "1.0";
                                        brand.removeAttribute("readonly", "");
                                        itemKind.removeAttribute("disabled", "");
                                        btnLocked.removeAttribute("disabled", "");
                                        btnImage.setAttribute("src", "images/icon-invisible.png");
                                        //createCookie('hide-line-<?php echo $x;?>','true');
                                    }
                                }
                            </script>
                        <?php
                        }
                    }else {
                                                /******************************************************************************** shopping list end****/
                        ?><tr><td></td><td></td><td>Keine Items vorhanden</td><td></td><td></td><td></td><td></td></tr><?php
                    }
                ?>
            <!-- script test end -->
            </table>

It all works, but is there a way to make it prettier? That I list the functions only 1x under the loop and it still works per line with the right variable values?

Can I reduce the size of this list of countries in Javascript or fetch them online so I don’t have to keep it hard coded?

I need a list like the one below to find the country code from the country name, so I constructed this array of objects in Javascript, but I was wondering if there was a more efficient way to do this than storing this long list?

Is there any way to either reduce the size of this list in storage/memory size or fetch this list from a free online service like Google?

One idea I thought would help with the size of the web app would be to download the list from the server, when needed, by the user, but wanted to see if anyone had a different idea.

Here is the array I created to store the list of countries with their codes.

export class Countries {
  countryCode = [
    {
      name: 'Afghanistan',
      code: 'AF'
    },
    {
      name: 'land Islands',
      code: 'AX'
    },
    {
      name: 'Albania',
      code: 'AL'
    },
    {
      name: 'Algeria',
      code: 'DZ'
    },
    {
      name: 'American Samoa',
      code: 'AS'
    },
    {
      name: 'AndorrA',
      code: 'AD'
    },
    {
      name: 'Angola',
      code: 'AO'
    },
    {
      name: 'Anguilla',
      code: 'AI'
    },
    {
      name: 'Antarctica',
      code: 'AQ'
    },
    {
      name: 'Antigua and Barbuda',
      code: 'AG'
    },
    {
      name: 'Argentina',
      code: 'AR'
    },
    {
      name: 'Armenia',
      code: 'AM'
    },
    ...
  ]
  CountryCode() {
    return this.countryCode;
  }
}

Troubleshooting Next.js Auth0 integration: API call without response and TypeError ‘secret’ is required

I am trying to add Auth0 to my nextjs app and Ive followed along with the quickstart guide here. I’ve added the login anchor and did not use Link as the guide suggested and when you click on it, it just loads infinitly and never reaches the login page. I get the error API resolved without sending a response for /api/auth/login, this may result in stalled requests. whenever you hit the login button and TypeError: "secret" is required . I have triple checked to make sure the .env.local file is correctly set up. Here is the link to the whole project front end. Ive been struggling with this for a while now and seen many examples with no clear resolution. Any help would be appreciated!

.env.local file is set up as such:

AUTH0_SECRET='very long string of random numbers and letters'

AUTH0_BASE_URL='http://localhost:3001/' (we hate 3000 out here)

AUTH0_ISSUER_BASE_URL='https://blahblahblah.us.auth0.com/'
AUTH0_CLIENT_ID='xxxxxx'

AUTH0_CLIENT_SECRET='xxxxxxx

The […auth0].js file looks like this:

import { handleAuth } from '@auth0/nextjs-auth0';

console.log('the AUTH0_SECRET env var is set: ', !!process.env.AUTH0_SECRET);

export default handleAuth();

and index.js looks like this:

import Head from 'next/head'
import { Inter } from 'next/font/google'
import styles from '@/styles/Home.module.css'
import Link from 'next/link';

const inter = Inter({ subsets: ['latin'] })

export default function Home() {


  return (
    <>
 
      <Head>
        <title>Workout Tracker</title>
        <meta name="description" content="Generated by create next app" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
       
      </Head>
      <main className={styles.main}>
        <Link href="/calendar">
          Calendar
        </Link>
        <Link href="/DailyDiary">
          Daily Diary
        </Link>
        <a href="/api/auth/login">
          Login
        </a>

      </main>
    </>
  )
}



I’m facing issue to detect browser refresh in ubuntu

Currently i’m using this code to check browser refreshes. But this is not working in ubuntu. can any one help me, to fix it

// If refreshed - handle the on-hold conversations
window.onunload = () => {
if (performance.getEntriesByType("navigation")[0].type === "reload") {
  localStorage.setItem(
    "onHoldConversations",
    JSON.stringify(state.conversations.liveConversations)
   );
 }
};

I need to store “onHoldConversations” in local storage while browser refreshes

Return a specific record from mysql database and display it to TinyMCE text area editor so the user can edit the note

I need to retrieve a record from mysql database and set it into a TinyMCE text editor area.

I created this template so it can act as my guide:

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);

$conn=mysqli_connect("localhost", "root", "", "tnstudentregistrationdb");

$selectNote = "SELECT notes FROM studentNotes WHERE noteid = 61";

$result = mysqli_query($conn, $selectNote);
$row = mysqli_fetch_assoc($result);


?>

<!DOCTYPE html>
<html>
    <head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <!--JQuery-->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    
    
        <title>TinyMCE - Set Data</title>
        
        <script src="./TinyMCE/tinymce/js/tinymce/tinymce.min.js"></script>
    </head>
    <body>

            <textarea class="tinymce" id="texteditor"></textarea>
            <textarea class="tinymce2" id="texteditor2"></textarea>
            <button class="set-data-btn-class" id="set-data-btn-id" >Set Data</button>
            
            <button class="update-data-btn-class" id="update-data-btn-id" >Update Data</button>
        <!-- javascript -->
        <script>
        
        $(document).ready(function() {
        $("#set-data-btn-id").on("click", function(e) {
        
        var content = `<?php echo $content = $row["notes"]; ?>`;                 //remember to only use single quote marks around <?php ?> tag
        console.log(content);
        tinymce.get("texteditor").setContent(content);

    });
        
        
        $("#update-data-btn-id").on("click", function(e) {
            
            
        });
        
        });
        
        tinymce.init({
            selector: '#texteditor, #texteditor2',
            width: '100%', 
  
        });
        
        
        </script>
        
    </body>
</html>

It does the desired functionality. $selectNote is the php mysql query to select a specific note, $result uses mysqli_query() to execute the sql query, and $row fetches the first row of results from the query.

$("#set-data-btn-id").on("click", function(e) {
        
        var content = `<?php echo $content = $row["notes"]; ?>`; //remember to only use single quote marks around <?php ?> tag
        console.log(content);
        tinymce.get("texteditor").setContent(content);

    });

This sets the content of #texteditor TinyMCE based on JS my JS content variable’s value which is the first results of my PHP $row variable.

I tried to mimic this implementation to my main system:

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);

$conn=mysqli_connect("localhost", "root", "", "tnstudentregistrationdb");

if (isset($_POST["note_id"])) {
    $output = '';

    $connect = mysqli_connect("localhost", "root", "", "tnstudentregistrationdb");  
    $query = "SELECT * FROM studentNotes WHERE noteid = '".$_POST["note_id"]."'";  
    $result = mysqli_query($connect, $query);  

    $querySpecific = "SELECT notes FROM studentNotes WHERE noteid = 61";
    $result2 = mysqli_query($connect, $querySpecific);
    $row1 = mysqli_fetch_assoc($result2);

    $output .= '  
    <!DOCTYPE html>
    <html>
    <head>
    
    <!--<link rel="stylesheet" href="selectNoteStyle.css"/>-->
    <!--There seems to be a problem with my external CSS, for now we will just use inline CSS-->

    <style>
    #deleteAndEditContainerID{
      text-align: left;
      
    }
  
  
  #noteTitleSelected {
      text-align: center;
      
  }
  
  #accessibilityOptionsID {
      float: right;
      
  }
  
  #noteContentID {
      width: 90%; 
      display: inline-block;
  }

  table, th, td, tr {
    /*We can also use ID and class to better specify which element to style, but since we only have one table
    in this component, we can also just call the entire table*/

    border: none;
  }
    </style>

    <script>
      
$(document).ready(
  function mode(){
  $("#darkMode").click(function(){
       document.getElementById("noteContentID").style.backgroundColor = "#ffcc66";
       document.getElementById("noteContentRow").style.backgroundColor = "#ffcc66";
       document.getElementById("noteContentID").style.color = "white";
      });
  
      $("#lightMode").click(function(){
       document.getElementById("noteContentID").style.backgroundColor = "white";
       document.getElementById("noteContentRow").style.backgroundColor = "white";
       document.getElementById("noteContentID").style.color = "black";
      });


      $(".deleteButton").click(function(){
       //Basically, .attr() gets the attribute value from $(this).attr("id"). so this could be $(".className").attr("id"), the id of the .className is selected.
       event.preventDefault(); // prevent page reload
       
       var title_note = $("#noteTitleSelected").text();
       var title_id_note = $("#noteIDSelected").text();

       $("#titleDeletingNoteID").text(title_note);
       $("#titleID").text(title_id_note);

       $("#myModal").modal("hide");
 
       
     }); //End of line for $(".deleteButton").click(function()){};

     
     $(".editButton").click(function(){
       //Basically, .attr() gets the attribute value from $(this).attr("id"). so this could be $(".className").attr("id"), the id of the .className is selected.
       event.preventDefault(); // prevent page reload
       
       $("#myModal").modal("hide");

       var content = "<?php echo $content = $row1["notes"]";
       //Try to use an external JavaScript file, using quotes in this js code is causing problem. https://stackoverflow.com/questions/3352576/how-do-i-embed-php-code-in-javascript
       console.log(content);
       tinymce.get("editNoteArea").setContent(content);
       
     }); //End of line for $(".editButton").click(function()){};
   
    
 });
    </script>
    </head>
    <body>
    <div>  
         <table >';  
    while($row = mysqli_fetch_array($result))  
    {  
         $output .= '  
              
                 <h2 id="noteTitleSelected">'.$row["noteTitle"].'</h2>
                 <h4 id="noteIDSelected">'.$row["noteid"].'</h4> <!--Make Delete and Edit functional-->
                 <div id="menuAbove">
                 <label><i>Timestamp: '.$row["note_timestamp"].'</i></label>
                 
                 <div class="dropdown">
                 <button class="btn btn-default dropdown-toggle" type="button" id="accessibilityOptionsID" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                 Accessibility options
                 <span class="caret"></span>
               </button>
               <ul class="dropdown-menu dropdown-menu-right" aria-labelledby="accessibilityOptionsID">
                 <li><a id="darkMode" href="#">Dim Mode</a></li>
                 <li><a id="lightMode" href="#">Light Mode</a></li>
                 <li><a href="#">Something else here</a></li>
                 <li role="separator" class="divider"></li>
                 <li><a href="#">Separated link</a></li>
               </ul>
                 </div>
                
                 </div>
              
              <tr>
                   <form id="currentNoteEdit">
                   <!--Use <textarea> tag for multiline support-->
                   <td width="70%" id="noteContentRow"><p id="noteContentID" placeholder="" >'.$row["notes"].'</p><br></br></td>
                   </form>
              </tr>

        <td id="deleteAndEditContainerID">
        <button type="button" class="btn deleteButton '.$row["noteTitle"].'" id="" data-dismiss="modal" data-toggle="modal" data-target="#deleteSelectedNoteModal">Delete</button>
        <button type="button" class="btn editButton '.$row["noteTitle"].'" id="" data-dismiss="modal" data-toggle="modal" data-target="#editSelectedNoteModal">Edit</button>
        </td>

              ';  

              
    }  

    
    $output .= '</table>
    
    </div>

    <!--REMEMBER TO USE A JAVASCRIPT TEXT EDITOR FOR THESE LINES OF CODES BECAUSE IT IS DIFFICULT TO SPOT ERRORS WITHOUT PROPER SYNTAX CHECKING!!!!!-->
    <script>
    
    </script>

    
    </body>
    </html>';  
    echo $output;  
  }
  
  
?>

When user clicks .editButton, it will open another modal from another file, and that modal should be able to display the selected record so it can be edited in TiyMCE text editor, this is that modal:

<!--Start of modal for editing selected note-->
<div class="modal fade" id="editSelectedNoteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
        <h5 class="modal-title" id="exampleModalLabelTitle">
          <!--If we want to change the modal title dynamically, maybe we shall just initialize a hidden table where we can fetch the current id of the selected note-->
</h5>
        
      </div>
      <div class="modal-body modalBodyOfEditingNote">
        Edit
        <textarea id="editNoteArea"> </textarea>
      </div>
      <div class="modal-footer">
        <button type="button" id="cancelEditNote" class="btn btn-secondary pull-left">Cancel</button>
        <button type="button" id="saveEditNote" class="btn btn-secondary pull-right">Save changes</button>
        <!--<button type="button" class="btn btn-primary">Save changes</button>-->
      </div>
    </div>
  </div>
</div>
<!--End of modal for editing selected note-->

However, console.log(content); from my script only returns this:
the file with problem

It doesn’t really return the result of my sql query, rather it returns the whole string of var content, so nothing is displayed or returned in my TinyMCE text editor. I already tried changing it to single quotes but I get a syntax error.

Compared that from my template guide which returns the proper result:
proper result returned

  • Already tried changing double quotes to single quotes, single quotes to double quotes, single/double quotes to backtick character
  • Already tried directly importing an external jquery directly to my javascript file
  • Already tried some solutions from this SO link: How do I embed PHP code in JavaScript?

What am I expecting:

  • return the specific record from mysql database to TinyMCE text area editor when user clicks ‘Edit’ button, this button shall allow user to edit their selected note.

Javascript – Is it possible to convert a varying-length if-else statement into for loop?

I have the following code which includes an if-else statement with a varying number (nk) of if-else conditions.

var x, n; // defined before
var nk = 4;

if ((x < n / nk) { ... }
else if (x < 2 * n / nk) { ... }
else if (x < 3 * n / nk) { ... }
else if (x < 4 * n) { ... }

nk is variable (2,4,10 etc.). Is it possible to turn this into a for loop (or anything else) so that it can work nicely with varying nk?

I tried the following, which obviously does not work:

for (let i = 0; i < nk; i++) {
    if (x < (i + 1) * n / ((i < nk) ? nk : 1)) { ... }
}

How can I make my react native map appear unmarked?

Hello I am using react native maps but I would like that no markers appear but I have searched and I can’t find how to do it, I don’t know if you can help me.

My versions
I’m doing it with the version:
“react-native-maps”: “1.7.1”,
“react-native-maps-directions”: “1.9.0”,

My Code

import MapView, { Marker, PROVIDER_OSM } from 'react-native-maps'
import MapViewDirections from 'react-native-maps-directions'

export default function Ruta({ origin }) {
   if (origin .latitude === undefined) {
      latitude: origin.latitude,
      longitude: origin.longitude,
   }

   const llave = 'My_APi_Key'

   useEffect(() => {
      obtLocations();
   }, [ruta])

   const obtLocations = async () => {
      let { status } = await requestForegroundPermissionsAsync()
      if (status !== 'granted') {
         alert("Permission denied");
         return
      }

      let location = await getCurrentPositionAsync({})
      const current = {
         latitude: location.coords.latitude,
         longitude: location.coords.longitude
      }
      setOrigin(current)
   }

   const [origin, setOrigin] = useState({
      latitude: origin.latitude,
      longitude: origin.longitude,
   })

   const destino = {
      latitude: ruta.latitude,
      longitude: ruta.longitude,
   }
   

   return (
      <Animated.View style={[StyleRuta.container, posRuta]}>
         <MapView
            style={StyleRuta.mapa}
            provider={PROVIDER_OSM}
            region={{
               latitude: origin.latitude,
               longitude: origin.longitude,
               latitudeDelta: 0.01,
               longitudeDelta: 0.01,
            }}
         >
            <Marker image={icons.walk} coordinate={origin} />
            <Marker coordinate={destino} />
            <MapViewDirections
               origin={origin}
               destination={destino}
               apikey={llave}
               strokeWidth={3}
               strokeColor="#0f0"
               strokeOpacity={0.8}
            />
         </MapView>
      </Animated.View>
   )
}