Meteor Calls and Methods – Sent and received objects differ

I’m using Meteor and Typescript and would like to send a TypeScript object using Calls and Methods. I’ve noticed the object that is received when using Meteor.call() is different to the object that is sent.

I’m expecting the uniqueColumns field to be an array when received in the Meteor.call().

Class to send

export class Template {
  _id: string;
  userId: string;
  uniqueColumns: string[] = [];
}

Meteor Method – uniqueColumns is an array when printed

Meteor.methods({
  getTemplates(): Array<Template> {
    return TemplateCollectionManager.getInstance().getAll();
  }
});

Meteor Call – uniqueColumns is an Object

Meteor.call('getTemplates', null, (err: any, res: Array<Template>) => {
  if (err) {
    console.error(err);
  } else {
    console.log(res);
    callback(res);
  }
});

What is the correct method of sending/receiving a TypeScript object with Meteor Calls and Methods?

How do i make my bot delete embeds and not my messages before them?

I’m beginner in js and I’m trying to make my music bot delete embeds made by embedbuilder function. Example: I’m using play command and bot has to send 2 embeds first one saying it’s searching and then second showing results. It deletes my command and then…crash

throw new DiscordAPIError(data, res.status, request);

DiscordAPIError: Unknown Message

I’m new to Dc js v13 btw
Here’s embed builder function code

function embedbuilder(client, message, color, title, description, thumbnail) {
    try{   let embed = new Discord.MessageEmbed()
        .setColor(color)
        .setFooter(client.user.username, client.user.displayAvatarURL());
    if (title) embed.setTitle(title);
    if (description) embed.setDescription(description);
    if (thumbnail) embed.setThumbnail(thumbnail)
    return message.channel.send({ embeds:  }).then(setTimeout(() => message.delete(), 5000));
}catch (error){
    console.error(embed)
 }
}

This code is result of me trying to find solution.Now “play” command code

else if (command === "play" || command === "p") {
        embedbuilder(client, message, "#fffff0", "Searching!", args.join(" ")).catch(console.error)
        return distube.play(message, args.join(" "));

And code making bot show results

.on("searchResult", (message, result) => {
        try{    let i = 0;
        return embedbuilder(client, message, "#fffff0", "", `**Choose**n${result.map(song => `**${++i}**. [${song.name}](${song.url}) - `${song.formattedDuration}``).join("n")}n*I will wait*`).catch(console.error)
    }catch (error){
        console.error
     }
    })

I wonder if making separate timeouts would be better, but I already tried to and I gave up.
discord.js: 13.3.1 (v12 before for long time, new to v13)
distube: 3.0.4
By the way how do i fix that?

if (message.content.includes(client.user.id)) {
       return message.reply(new Discord.MessageEmbed().setColor("#fffff0").setAuthor(`${message.author.username}, My prefix is ${prefix}, please type ${prefix}help to see my commands`, message.author.displayAvatarURL({ dynamic: true })));
    }

When i try to ping my bot it says
throw new DiscordAPIError(data, res.status, request);
^

DiscordAPIError: Cannot send an empty message

ReactJS. I try to make dynamic input field together using react-calendar package

I want to build a dynamic form using react-calendar and input field input (type: time). Whenever a user wants to insert their times in a specific date, the input field will be reset to the first index and will need to enter their times.

I have managed to make the input field dynamic but I cannot get all the arrays with the same ISO DateTime value.

Here is the link to my sandbox for the case
https://codesandbox.io/s/staging-rgb-m8g9j?file=/src/App.js

How to check if image loads and set it as background-image of a cloned template

I have the following HTML template:

<template id="type1">
  <div class='type1'>
    <a>
      <div class='poster'></div>
      <div class='content'>
        <div class='title'></div>
        <div class='description'></div>
      </div>
    </a>
  </div>
</template>

I’m calling for some API and receive a list of objects with this structure:

[{
  id: 'someid',
  poster: 'some_image_url',
  url: 'some_link_url',
  title: 'Title',
  description: 'description'
}, {...}]

I run in loop on all objects and for each create a clone of the template:

const sonstruct = data => {
  const template = document.querySelector('#type1')
  const clone = template.content.cloneNode(true)
  clone.querySelector('a').setAttribute('href', data.url)
  clone.querySelector('.poster').setAttribute('style', `background-image: url("${data.poster}")`)
  clone.querySelector('.title').textContent = data.title
  clone.querySelector('.description').textContent = data.description
  return clone
}

So far everything works just fine. The problem begins when I decide to check if the image in the poster link is loaded, and if not – set some default image. First I tried to do the following (instead of clone.querySelector('.poster')):

const img = new Image
img.onload = function() {
  clone.querySelector('.poster').setAttribute('style', `background-image: url("${data.poster}")`)
}
img.onerror = function() {
  clone.querySelector('.poster').setAttribute('style', 'background-image: url("./assets/default.png")')
}
img.src = data.poster

And I received the following error: clone.querySelector(...) is null

I tried to use closures:

img.onload = (function (clone) {
  return function () {
    clone.querySelector('.poster').setAttribute('style', `background-image: url("${data.poster}")`)
  }
})(clone)
img.onerror = (function (clone) {
  return function () {
    clone.querySelector('.poster').setAttribute('style', 'background-image: url("./assets/default.png")')
  }
})(clone)

Alas, same result, same error.

I also tried to use .apply(clone) on the methods above, however in that case all the images were set to default image in the onerror method, even though the URL in data.poster did return an image.

Why is this happening and how to make it work?

How can I publish a website using my own computer? [closed]

assuming I have HTML, CSS and JavaScript files and now want to upload them to a web server so that anyone can access them via a domain or IP.

  • How do I proceed?
  • Do I need a domain (in form of: www.[name].de) or
    does an IP address work?
  • How do I publish the code
  • How do I make
    sure that the visitors of the website can interact with each other,
    e.g. through a chat?

Thanks in advance

How to make directories and files appear on the server, node.js

I have a code, it shows folders, I can navigate through them and files too, but this only works in the console:

`

const fs = require('fs/promises');
const fsToRead = require('fs')
const path = require('path');
const inquirer = require('inquirer');
const yargs = require('yargs');
const { lstatSync, readdirSync } = require('fs');
const http = require('http');
const url = require('url');
const options = yargs
    .options('p', {
        describe: 'Pattern',
        default: ''
    })
    .options('d', {
        describe: 'Path to directory', 
        default: process.cwd()
    }).argv;

console.log(options);

class itemsList {
    constructor(path, fileName) {
        this.path = path;
        this.fileName = fileName;
    }
    get folders() {
        return lstatSync(this.path).isDirectory();
    }
}

let executionDir = process.cwd();

const start = async () => {
    const list = await fs.readdir(executionDir);
    const items = list.map(fileName =>
        new itemsList(path.join(executionDir, fileName), fileName));
    const item = await inquirer.prompt([
        {
            name: 'fileName',
            type: 'list',
            message: `Choose: ${executionDir}`,
            choices: items.map(item => ({name: item.fileName, value: item})),
        }
    ]).then(answer => answer.fileName);
    
    if (item.folders) {
        executionDir = item.path;
        return await start();
    } else {
        const data = await fs.readFile(item.path, 'utf-8');

        if (!options.p) {
            console.log(data)
        }
        else {
            const regExp = new RegExp(options.p, 'igm');
            console.log(data.match(regExp));
        }
    }
}

start();

`

HOW TO IMPLEMENT THAT SHE SHOWS ON THE PAGE OF THE BROWSER, THAT IN THE WEB VERSION I COULD GO TO THE FOLDERS, IF THIS IS A FILE SHE WOULD SHOW ITS CODE, I WOULD NOT HAPPEN IT!

Why don’t HTML suggestions work in my Javascript file which has HTML elements in it?

I am creating and HTML web component in JavaScript. However, when i start writing the HTML in it the suggestions and completions don’t work. Below is the code:

class CardComponent extends LitElement {

    render() {
        return html`
        
        <div class="card">
            <h2>Title</h2>
            <p>11.12.2021</p>
            <p>Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla</p>
        </div>

        <style>
            .card {
                width:400px;
                bordr:2px solid red;
                padding:10px;
            }
        </style>

        `
    }
}

I had to type the entire HTML manually myself except for the curly braces which close on their own. Also, the tags in this part were not color coded in the IDE.

How do I enable the suggestions and auto completion?

How can check string value that contain in main string value in array by javascript

I want to check user.uid that contain or not in combined user ids.
here is combined ids in arrays

getid Array [
  "E8R52y6dD8XI3shXhnhS9pVzUpe26Lf5bHwzCSbI2bmoMv7KuduMGwe2",
  "KgRwTDgenjYpODPxRaldDQy9nnH36Lf5bHwzCSbI2bmoMv7KuduMGwe2",
  "pNv0iKlZ6xVOl0fFOZSoXJoPuVx2E8R52y6dD8XI3shXhnhS9pVzUpe2",
]

here is user.uid

pNv0iKlZ6xVOl0fFOZSoXJoPuVx2

I want to get result is my user.uid is in or not in this combined Id arrays.

const uid = user.uid in getId ? yes : no 

(or ) how can check this condition .I not know.
I not want to remove my user.uid from combined id , I just want to check my user.uid is in or not in this combined Id.
can someone help me?

quill-html-edit-button Super expression must either be null or a function, not undefined

I have nuxt project where i use “Quill editor”, and I’m trying to add quill-html-edit-button like in example https://github.com/benwinding/quill-html-edit-button, but after rebuilding my app i’ve got “Super expression must either be null or a function, not undefined”. Can someone help me, please?
My code:

“quillEditor.js” imported like plugin in “nuxt.config”

import Vue from 'vue';
import VueQuillEditor from 'vue-quill-editor';
import Quill from 'quill'
import ImageResize from 'quill-image-resize-vue'
import VideoResize from 'quill-video-resize-module';
import {ImageUpload} from 'quill-image-upload';

import htmlEditButton from "quill-html-edit-button";

Quill.register('modules/ImageResize', ImageResize);
Quill.register('modules/VideoResize', VideoResize);
Quill.register('modules/imageUpload', ImageUpload);
Quill.register('modules/htmlEditButton', htmlEditButton);

Vue.use(VueQuillEditor);

component

<quill-editor
                    ref="editor"
                    :content="formInitialData.content"
                    :options="editorOption"
                  />

editorOption: {
      theme: 'snow',
      modules: {
        toolbar: [
          ['bold', 'italic', 'underline', 'strike'],
          ['blockquote', 'code-block'],
          [{ 'header': 1 }, { 'header': 2 }],
          [{ 'list': 'ordered' }, { 'list': 'bullet' }],
          [{ 'script': 'sub' }, { 'script': 'super' }],
          [{ 'indent': '-1' }, { 'indent': '+1' }],
          [{ 'direction': 'rtl' }],
          [{ 'size': ['small', false, 'large', 'huge'] }],
          [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
          [{ 'color': [] }, { 'background': [] }],
          [{ 'font': [] }],
          [{ 'align': [] }],
          ['clean'],
          ['link', 'image', 'video']
        ],
        ImageResize: {},
        VideoResize: {},
        htmlEditButton: {
          debug: true,
          msg: "Edit the content in HTML format",
          okText: "Ok",
          cancelText: "Cancel",
          buttonHTML: "HTML",
          buttonTitle: "Show HTML source",
          syntax: false,
          prependSelector: 'div#myelement',
          editorModules: {}
        },
        imageUpload: {
          url: process.env.apiUrl + '/push-s3',
          method: 'POST',
          name: 'file',
          withCredentials: false,
          headers: {},
          csrf: { token: 'token', hash: '' },
          callbackOK: (serverResponse, next) => {
            if(serverResponse.success){
              next(serverResponse.data);
            }
          },
          callbackKO: serverError => {
            console.log(serverError);
          },
          checkBeforeSend: (file, next) => {
            console.log(this.apiUrl);
            next(file);
          }
        },
      },
      placeholder: 'Insert text here ...',
    },

packege.json

 "quill-html-edit-button": "^2.2.7",

My firebase isnt working with my canvas, please can someone help me

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Chat with ur friends!</title>

        <!-- Boostrap links-->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

        <!-- font-family: 'Montserrat', sans-serif; basic -->
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="https://fonts.googleapis.com/css2?family=Montserrat&display=swap" rel="stylesheet">

        <!-- font-family: 'Open Sans', sans-serif; header -->
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="https://fonts.googleapis.com/css2?family=Open+Sans&display=swap" rel="stylesheet">

        <!-- Font awesome -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
            
        <!-- Firebase links -->
        <script src="https://www.gstatic.com/firebasejs/7.6.2/firebase-app.js"></script>
        <script src="https://www.gstatic.com/firebasejs/7.6.2/firebase-firestore.js"></script>
        <script src="https://www.gstatic.com/firebasejs/live/3.1/firebase.js"></script>

    <link rel = "stylesheet" href = "chat.css">
    </head>
    <body>
        <h2 id = "title-name"></h2>
        <canvas id = "myCanvas"></canvas>
        <br>
        <br>
        <br>
        <div style = "display: flex;" id = "th">
            <h2 id = "design">design</h2>

            <br>
            <br>
            <br>

            <label>Width:</label>
            <input type = "number" id = "width" placeholder="Type in the width" class = "form-control">
            <div id = "color">
                <button id = "red" class = "square" onclick = "red()"></button>
                <button id = "blue" class = "square" onclick = "blue()"></button>
                <button id = "green" class = "square" onclick = "green()"></button>
                <button id = "black" class = "square" onclick = "black()"></button>
                <button id = "pink" class = "square" onclick = "pink()"></button>
                <button id = "orange" class = "square" onclick = "orange()"></button>
                <button id = "yellow" class = "square" onclick = "yellow()"></button>
                <button id = "purple" class = "square" onclick = "purple()"></button>
            </div>
            
        </div>

        <script src = "chat.js"></script>
    </body>
</html>

@import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&display=swap');

body {
    --bg-secondary:#262626;
    --bg-primary: #d4cc3b;
    background-color: var(--bg-secondary);
    color: white;
    display: flex;
    flex-direction: column;
    align-items: center;
}

body::-webkit-scrollbar {
    width: 1.5rem;
}

body::-webkit-scrollbar-track {
    background-color: var(--bg-primary);
}

body::-webkit-scrollbar-thumb {
    background-color: var(--bg-secondary);
    border-top-left-radius: 100px;
    border-top-right-radius: 100px;
    border-bottom-left-radius: 100px;
    border-bottom-right-radius: 100px;
}

#myCanvas {
    width: 1000px;
    height: 700px;
    border: var(--bg-primary) 10px ridge;
    background-color: white;
    border-radius: 10px;
}

#th {
    margin-bottom: 20px;
    background-color: var(--bg-primary);
    width: 1000px;
    height: 150px;
    align-items: center;
    border-radius: 10px;
}

#width {
    width: 300px;
    margin-left: 10px;
}

label {
    margin-left: 20px;
}

#color {
    margin-left: 200px;
}

#design {
    font-family: 'Bebas Neue', cursive;
    margin-bottom: 100px;
    margin-left: 425px;
    position: absolute;
    color: var(--bg-secondary) !important;
}

.square {
    width: 50px;
    height: 50px;
    border: none;
    border-radius: 10px;
}

#red {
    background-color: red;
}

#blue {
    background-color: blue;
}

#green {
    background-color: green;
}

#black {
    background-color: black;
}

#pink {
    background-color: pink;
}

#orange {
    background-color: orange;
}

#yellow {
    background-color: yellow;
}

#purple {
    background-color: purple;
}

var firebaseConfig = {
    apiKey: "AIzaSyCzlBjFMT4KtLmsRr3r8Q9a0I-L6Mpf0BQ",
    authDomain: "teamwork-bd9a7.firebaseapp.com",
    databaseURL: "https://teamwork-bd9a7-default-rtdb.firebaseio.com",
    projectId: "teamwork-bd9a7",
    storageBucket: "teamwork-bd9a7.appspot.com",
    messagingSenderId: "53158557502",
    appId: "1:53158557502:web:131aa36b2266e1c65f9e6f"
};
  
// Initialize Firebase
firebase.initializeApp(firebaseConfig)



canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");

color = "black";
line_width = 1;

function getData() {
    firebase.database().ref("/").on('value', function(snapshot) {
        snapshot.forEach(function(childSnapshot) {
            childKey  = childSnapshot.key;
            Room_names = childKey;

            var mouseEvent = "";
            var lastPositionX;
            var lastPositionY;

            canvas.addEventListener("mousdown", my_mouse_down);
            function my_mouse_down(e) {
                line_width = document.getElementById("width").value;

                console.log("down");
                mouseEvent = "mouseDown";
            }

            canvas.addEventListener("mousemove", my_mouse_move);
            function my_mouse_move(e) {
                currentPosX = e.clientX - canvas.offsetLeft;
                currentPosY = e.clientY - canvas.offsetTop;

                if(mouseEvent == "mouseDown") {
                    ctx.beginPath();
                    ctx.strokeStyle = color;
                    ctx.lineWidth = line_width;

                    console.log("Last position of x and y:");
                    console.log("x- " + lastPositionX + " y- " + lastPositionY);

                    ctx.moveTo(lastPositionX, lastPositionY);

                    console.log("Current position of x and y:");
                    console.log("x- " + currentPosX + " y- " + currentPosY);

                    ctx.lineTo(currentPosX, currentPosY);
                    ctx.stroke();
                }

                lastPositionX = currentPosX;
                lastPositionY = currentPosY;
            }

            canvas.addEventListener("mouseleave", my_mouse_leave);
            function my_mouse_leave(e) {
                mouseEvent = "mouseLeave";
                console.log("leave");
            }

            canvas.addEventListener("mouseup", my_mouse_up);
            function my_mouse_up(e) {
                mouseEvent = "mouseUp";
                console.log("up");
            }
        });
    })
}
getData();

roomName = localStorage.getItem("roomName");
document.getElementById("title-name").innerHTML = roomName;

function red() {
    color = "red";
}

function blue() {
    color = "blue";
}

function green() {
    color = "green";
}

function black() {
    color = "black";
}

function pink() {
    color = "pink";
}

function orange() {
    color = "orange";
}

function yellow() {
    color = "yellow";
}

function purple() {
    color = "purple";
}

Hi everyone, I wanted to make a small project on a chatting/teamwork website. I have included firebase and I wanted to make a drawing board so I used canvas. I have used realtime DB to make this successful but it isn’t working. If you could, can you please help me or fix this issue. The output should be you drawing on the canvas and other users could see it. If you want more details please tell me in the comments.

Bootstrap Modal can’t be hidden (Asp.net core, C#)

I have created a .NET Core project and used a Bootstrap Modal and ajax to Edit and delete data.
But somehow my modal can’t be hidden.

here is my index file

 <a href="javascript:void(0)" class="delete" onclick="ConfirmDelete(@item.Id)">
                            <i class="material-icons" data-toggle="tooltip" title="Delete">&#xE872;</i>
                        </a>
                        <!-- Delete Modal HTML -->
                        <div id="deleteCategoryModel" class="modal fade">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h4 class="modal-title">Delete Category</h4>
                                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                                    </div>
                                    <div class="modal-body">
                                        <h6 class="#modal_body"></h6>
                                        <p>Are you sure you want to delete this Category?</p>
                                        <p class="text-warning"><small>This action cannot be undone.</small></p>
                                    </div>
                                    <div class="modal-footer">
                                        <input type="button" class="btn btn-default" value="Cancel" onclick="closeDeleteModal()">
                                        <input type="button" class="btn btn-danger" value="Delete" onclick="DeleteCategory()">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <input type="hidden" id="hiddenCategoryId" />

and my code jQuery:

var ConfirmDelete = function (Id) {

$("#hiddenCategoryId").val(Id);
$("#deleteCategoryModel").modal('show');

}

var DeleteCategory = function () {

var Id = $("#hiddenCategoryId").val();

$.ajax({

    type: "POST",
    url: "/Category/Delete",
    data: { id: Id },
    success: function (result) {
        $("#deleteCategoryModel").modal("hide");
        $("#row_" + Id).remove();
    }
});

}

var closeDeleteModal = function () {
$('#deleteCategoryModel').modal('hide');

}

Why is it getting undefined after return in recursive function?

I m trying to solve the Recursive Digit sum of Hackerrank. I think I am done but getting undefined at the end of return of recursive function

function superDigit(n, k) {
  // Write your code here
  let str = "";
  for (let i = 0; i < k; i++) {
    str = str + n;
  }
  if (Math.floor(parseInt(str) / 10) === 0) {
    return n;
  } else {
    
      let t=calculateSum(str.split(''));
     console.log('done:',t)
     return t
     
  }
  function calculateSum(value) {
    let arr = value;
    let sum = 0;
    console.log(arr);
    for (let i = 0; i < arr.length; i++) {
        sum = sum + parseInt(arr[i]);
    }
    
    if (Math.floor(sum / 10) === 0) {
      console.log(sum);
      return sum;
    } else {
      calculateSum(sum.toString().split(''));
    }
  }
}

console.log("tttt:"+superDigit(9, 3));

Avoid adding duplicate values to array

I have an array with below values.

const array1 = [
      { id: "1111" },
      { id: "2222" },
      { id: "3333"},
      { id: "4444"},
      { id: "5555"}
    ];

Suppose I want to add {“id” : “1111”} once again or any other duplicate {key:value} pair, then how to prevent it from adding in the array ?

Please help on this.