How do I update the repository of a Heroku app?

I am trying to update a repo on Heroku due to finding an error in my index.js file. After using heroku logs --tail, I noticed that:
Heroku Screenshot

I misspelled “config”, so I fixed the file. I tried to wipe the old repo using heroku git:remote -a <appname>, followed by git add ., git commit --am, and git commit push master to create a new one. However, opening the app begets the same error. How am I to update the repo so that the update to index.js is read?

I also followed the instructions of this Stackoverflow question, but nothing seemed to change. Thanks to any help in advance.

Don’t show contents of HTML page until firebase auth status is known

I am building a small site using plain HTML and javascript, and I am using Firebase for authentication. When users go to a certain page, I would like to redirect them to another page if they are signed in. This is the code I am using to achieve that (all scripts are placed in the <head>):

   <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script>
   <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-auth.js"></script>

   <script>
      const firebaseConfig = {
         // ...
      };

      firebase.initializeApp(firebaseConfig);

      firebase.auth().onAuthStateChanged((user) => {
         window.location.href = "/feed";
      });
   </script>

This redirects the user properly, but the user briefly sees the page meant for non-authenticated users during the time it takes for Firebase to fetch the auth state and for the onAuthStateChanged callback to be fired. Is there a way I can prevent rendering of the HTML page until onAuthStateChanged is called?

javascript fetch declares that response.json() is not a function [duplicate]

I have a simple function that sends json to a server in order to follow a user. Let me know if there’s an easier way, but this is the best way I’ve found that allows me to use a csrf token. Everytime the function runs it says “Uncaught TypeError: response.json is not a function”. I have no idea why…

Here is my function below:

function follow_user(user_id) {
    const fields = {
        csrf_token: {
            input: document.getElementById('csrf_token'),
            error: document.getElementById('csrf_token-error')
        }
    };
    const response = fetch('/_follow_user/'+user_id, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            csrf_token: fields.csrf_token.input.value
        })
    });
    console.log(response.json())
    if (response.ok) {
        if (response.text=="followed") {
            document.getElementById('follow_button').innerHTML="Unfollow";
        } else if (response.text=="unfollowed") {
            document.getElementById('follow_button').innerHTML="Follow";
        }
    } else {
        //This is the part that it declares is not a function. console.log shows response as going through, but response.ok also fails...
        const errors = response.json();
        Object.keys(errors).forEach((key) => {
           fields[key].input.classList.add('is-invalid');
           fields[key].error.innerHTML = errors[key][0];
        });
        jFlash('Follow Failed');
    }
}

SyntaxError: await is only valid in async function (in DiscordJS) [duplicate]

So, I am super new to this, and I’ve been trying to connect my Discord bot to a MySQL Database. I will need to do so in the future. So, because I’m still learning, I downloaded a pre-made bot off of GitHub (Link). And when I tried to execute the code, I got:

/home/zodiac/Documents/DiscordJS-MySQL-master/app.js:47
    if (message.guild && !message.member) await message.guild.fetch.members(message.author);
                                          ^^^^^


SyntaxError: await is only valid in async function

The part of the code it is referring to (Line number 6):

let prefix = row[0].value;
    let args = message.content.slice(prefix.length).trim().split(/ +/g);
    let command = args.shift().toLowerCase();

    if (!message.content.startsWith(prefix)) return;
    if (message.guild && !message.member) await message.guild.fetch.members(message.author);

    let member = message.guild.member(message.mentions.users.first() || args[0]);

I know this isn’t my code, but I would really like to see it working.

Awaiting a reply

How do I resolve this object promise? [duplicate]

I’m initializing a LeagueAPI object that returns a dictionary when a function is called on it. However, when I try to write the returned data to my HTML file, it displays an [object Promise] instead of the data. Here is the code:

LeagueAPI = new LeagueAPI('********', Region.NA);

LeagueAPI.initialize()
    .then().catch(console.error)


document.write(LeagueAPI.getFeaturedGames())

I’ve tried a few implementations of this, but I often run into a CORS error policy. What would be the correct implementation to write the returned data to the HTML file?

How to write JavaScript constructors without strong typing [duplicate]

In strongly typed languages, like C# or Java, I can distinguish constructor signatures by argument types.

class Cars {

    Cars(string x, string y) {};
    Cars(string x, int y) {};

}

But without strong typing in JavaScript, I can only do this, which obviously will not work:

class Cars {

    Cars(x, y) {};
    Cars(x, y) {};

}

Am I limited to only the number of constructor arguments to distinguish them? Is there some way to create JS constructors that have the same number of args, but of different “types”?

How do I make constructors that know that it should be looking for an string y in the first constructor, but int y in the second?

Fixed background and content attachment

Hey guys I have a fixed background attachment for scrolling uptill two pages of the content after that i want the second page to be fixed and make the third page with a different background to come up covering the second page. How can I make the content of the second page fixed when it comes at the top? So that scroll effect can be appliedm

Promise.all is not resolving if second promise is added to promise array

Given that promise1 and promise2 are correctly resolved with the below code:

export const getExistingPayments = async (payments: Payment[]) => {

  const promise1 = await getPayment(payments[0].paymentId)
  const promise2 = await getPayment(payments[1].paymentId)

  const results = [promise1, promise2]
  return results
}

Can anybody help explain why the below code would just hang, the promises are never resolved or rejected:

export const getExistingPayments = async (payments: Payment[]) => {

  const promise1 = getPayment(payments[0].paymentId)
  const promise2 = getPayment(payments[1].paymentId)

  const results = await Promise.all([promise1, promise2])
  return results
}

It might also be worth mentioning that when only one promise is passed to the Promise.all the promise is resolved as expected, the below code also works fine:

export const getExistingPayments = async (payments: Payment[]) => {

  const promise1 = getPayment(payments[0].paymentId)

  const results = await Promise.all([promise1)
  return results
}

is a good idea set props like my code in HOC Component?

I did this code to try to build a HOC Component

import { useState } from 'react';

function withCountState(Wrapped) {
  return function (props) {
    const [count, setCount] = useState(0);
    return <Wrapped count={count} setCount={setCount} {...props} />;
  };
}

const Wrapped = props => {
  const { count, setCount } = props;
  return (
    <div>
      <h1>Counter Functional Component</h1>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Increment count</button>
      <button onClick={() => setCount(count + 3)}>Increment count</button>
      <button onClick={() => setCount(count + 5)}>Increment count</button>
    </div>
  );
};

const EnhancedWrapped = withCountState(Wrapped);
export default EnhancedWrapped;

Complete code

Is a good idea set props like count={count} setCount={setCount} {...props} in ‘withCountState’ component, Why pass {…props} is not enough to detect my props?

How to use sqlite to store the cooldown of a command?

I want to try to store my command cooldown in any sort of storage, I think sqlite will be good, but I don’t know how to implement it for a cooldown.. I was checking one guide here https://anidiots.guide/coding-guides/sqlite-based-points-system/#you-get-points-and-you-get-points-and-everybody-gets-points, it’s for storage points and levels.. Unfortunately I’m not able edit this example into my needs, to store the cooldown for each user.

'use strict';

const SQLite = require("better-sqlite3");
const sql = new SQLite("./cooldowns.sqlite");

const humanizeDuration = require('humanize-duration');

// Require the necessary discord.js classes
const { Client, Intents, Collection } = require('discord.js');
const config = require("./config.json");
const { MessageEmbed } = require('discord.js');
const cooldowns = new Map();
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });

client.on('ready', () => {
  const table = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'scores';").get();
  if (!table['count(*)']) {
    // If the table isn't there, create it and setup the database correctly.
    sql.prepare("CREATE TABLE scores (id TEXT PRIMARY KEY, user TEXT, guild TEXT, points INTEGER, level INTEGER);").run();
    // Ensure that the "id" row is always unique and indexed.
    sql.prepare("CREATE UNIQUE INDEX idx_scores_id ON scores (id);").run();
    sql.pragma("synchronous = 1");
    sql.pragma("journal_mode = wal");
  }
  // And then we have two prepared statements to get and set the score data.
  client.getCooldown = sql.prepare("SELECT * FROM scores WHERE user = ? AND guild = ?");
  client.setCooldown = sql.prepare("INSERT OR REPLACE INTO scores (id, user, guild, points, level) VALUES (@id, @user, @guild, @points, @level);");
  
  client.user.setActivity("thinking...", { type: 'PLAYING' });
  console.log('Bot is online!')
});

client.on("messageCreate", message => {
    if (message.author.bot) return;
    // This is where we'll put our code.
    if (message.content.indexOf(config.prefix) !== 0) return;
  
    const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
    const command = args.shift().toLowerCase();
  
    if(command === 'mycommand') {
    const cooldown = cooldowns.getCooldown(message.author.id);
    if (!cooldown) {
        cooldowns = {
          id: `${message.author.id}`,
          user: message.author.id,
          cooldown: 0
        }
      }
    if (cooldown) {
        const remaining = humanizeDuration(cooldown - Date.now(), { round: true }, { units: ["d","h","m","s"] });
    
        message.reply(`Your cooldown is. ${remaining}`)
        return;
    }  
      async function main() {
      const messages = await message.channel.messages.fetch({ limit: 1 });
      const lastMessage = messages.last();
      const isValidDate = (dateString) => new Date(dateString).toString() !== 'Invalid Date'
      if(isValidDate(lastMessage.content) == false && lastMessage.content !== 'mycommand')
      message.reply("I need your date of birth!.")
      if(lastMessage.content === 'mycommand')
      message.reply("Please provide me your date of birth.")
      if(isValidDate(lastMessage.content) == true && lastMessage.content !== 'mycommand') {
      cooldowns.set(message.author.id, Date.now() + 604800000);
      message.reply("Check your DMs.")
      message.react("emoji"); //react with emoji to the issued command
      const predictions = ["Prediction 1", "Prediction 2", "Prediction 3", "Prediction 4", "Prediction 5", "Prediction 6", "Prediction 7"]
      const randomprediction = predictions[Math.floor(Math.random() * predictions.length)];
        const prediction1 = new MessageEmbed()
          .setColor('#ff7518')
        .setAuthor(client.user.username, client.user.displayAvatarURL())
          .setTitle(`Weekly message` + lastMessage.author.username + `#` + lastMessage.author.discriminator) 
        .setDescription(randomprediction);
        message.author.send({ embeds: [prediction1] });
        var random = Math.random()
        if (random < 0.9) {
        message.author.send("Congrats! You received this message " + '<@' + message.author.id + '>!')
        message.channel.send('Congrats again! ' + '<@' + message.author.id + '>'); 
        }
        setTimeout(() => cooldowns.delete(message.author.id), 604800000);
        client.setCooldown.run(cooldowns);
      }
  }
}

The problem is I don’t know how to edit the sql params, I never used sqlite/anything else before and have 0 experience with it. All I want is to store command in some sort of storage, but I don’t know where to start. Any help will be much appreciated!

jonthornton timepicker : How to get hours and minues

I’m using the jonthornton/jquery-timepicker and could not find the hours and minutes selected.
All I could find was a string output of the form ’10:30pm’.
Can the hours and minutes be accessed directly from the control?
I imagined you would be able to do this but could not find it.
The best I’ve been able to do is what follows, anyone got anything better?

$('#StartTime').on('change', function (timeControl) {
var hoursString;
if (timeControl.target.value.indexOf("am") >= 0) {
    hoursString = timeControl.target.value.replace("am", ":00 AM");
}
else {
    hoursString = timeControl.target.value.replace("pm", ":00 PM");
}
var oneDate = new Date(Date.parse("2000-01-01 " + hoursString));
var minutes = oneDate.getMinutes();
var hours = oneDate.getHours();

console.log("Hours : " + hours + " | Minutes : " + minutes);

});

TypeORM Timestamp Date equality not working

I’m using TypeORM with an Entity that looks something like this:

@Entity('users')
export class UserEntity extends BaseEntity {
  @PrimaryColumn()
  id: string;

  @CreateDateColumn({ type: 'timestamp' })
  createdAt: Date;

  @UpdateDateColumn({ type: 'timestamp' })
  updatedAt: Date;
}

However, when I try to do any sort of timestamp equality related SQL query using the TypeORM Entity’s repository it does not work properly. For example the query:

const id = 'dbe9e81d-aefa-459d-8460-707ade0fa156';
const userEntity = userRepository.findOne(id); // UserEntity(...)
const sameUserEntity = userRepository.findOne({ where: { createdAt: userEntity.createdAt } }); // undefined

Returns the correct entity for userEntity and undefined for sameUserEntity. I looked at the logs constructed by TypeORM for this query and it looks like this:

SELECT "UserEntity"."id" AS "UserEntity_id", 
    "UserEntity"."created_at" AS "UserEntity_created_at",
    "UserEntity"."updated_at" AS "UserEntity_updated_at" 
FROM "users" "UserEntity"
WHERE "UserEntity"."created_at" = $1 LIMIT 1 -- PARAMETERS: ["2022-02-19T22:10:13.564Z"]

It seems like TypeORM is not converting the JavaScript Date object to the correct PostgreSQL timestamp format. The timestamp in the database looks like 2022-02-19 22:10:13.564432, which is a completely different format and is a higher precision.

Is there a specific way I should be doing timestamp related searches when using TypeORM?

Note: I’ve tried too look for people having this same issue but I do not see any clear solution. I’m trying to implement cursor based pagination around the created at date, however the greater than and less than operators are not work properly as well.

How to add HTML Div onClick eventListener() [duplicate]

I am learning to create a calculator using Javascript. I have added my HTML elements and CSS style but I am struggling to make the eventListener work.

I have the following code (just a sample), and I have styled HTML with using grid:

HTML:

<div id="frame">
        <div class="btn">1</div>
        <div class="btn">2</div>
        <div class="btn">3</div>
</div>

JavaScript:

document.querySelectorAll(".btn").addEventListener("click", btnClick);

function btnClick(){
    alert("hi");
}

Desired outcome: Alert “Hi” whenever I click on any of the div

From everything I have learned, I thought this code should give me the desired outcome but I thought wrong. I would really appreciate if someone could point out the fault.

Many Thanks in Advance!!

How to force the require() function to call each time the screen shows?

I have a situation where on one screen (AScreen), I load JSON data from a .json file, I also have a Settings screen where the user can set ‘settingA’ as true or false.

AScreen (basically if settingA is set to true, load two JSON files, if settingA is false, load only one data file):

import React, { useContext } from 'react';
import { SettingsContext } from '../context/settingsContext';

const AScreen = () => {
  const { settingA } = useContext(SettingsContext);

  const loadedData = (() => {
    if (settingA === true) {
      return Object.assign(
        console.log('True');
        require('../assets/data/jsonFileA.json'),
        require('../assets/data/jsonFileB.json')
      )
    }
    console.log('False');
    return require('../assets/data/jsonFileA.json')
  })();

  console.log(settingA):
  console.log(loadedData);

  return (
    ...
  );
};

The issue here is that if I load the app and head to AScreen, I get the correct data loaded into loadedData. However, if I then head to the settings page and change the setting then go back to AScreen, the console.log(settingA) shows the updated setting and the correct ‘True’ or ‘False’ is printed but the loadedData still contains the data from the first time I visited AScreen.

This tells me that the require() function doesn’t actually get called until the screen is fully re-rendered.

Is there a better way to load JSON data than require()? Or how can I make sure require() is called every time the screen is displayed even if the screen isn’t re-rendered.

I know one option would be to load all the JSON data then simply filter it based on the user’s settings but in the actual app there are a lot more data files so it seems that would be a waste of resources to load all the files at once.