Markdown rendering error when typing: “Hello

I am using react markdown library. Here is my code:

import Markdown from 'react-markdown';
import PreClass from './PreClass';

type MarkdownFormatTextProps = {
    markdown: string;
    tagName?: string;
};

const MarkdownFormatText = ({ markdown, tagName }: MarkdownFormatTextProps) => {
    return (
        <article className=" prose prose-pre:w-[600px] prose-sm prose-ul:leading-[6px] prose-code:text-[15px] prose-blockquote:leading-[6px] prose-ol:leading-[6px] prose-p:leading-[20px] prose-li:relative prose-li:bottom-[-5px]">
            {tagName && (
                <span style={{ color: '#3297ff' }} className="cursor-pointer">
                    {tagName}
                </span>
            )}
            <Markdown unwrapDisallowed children={markdown} skipHtml components={{ pre: PreClass }} />
        </article>
    );
};

export default MarkdownFormatText;

When I type in: “`hello

Then an error will be displayed.

enter image description here

Issue with EJS Templating Syntax Highlighting and Rendering in Visual Studio Code

I’m currently working on a JavaScript project using EJS (Embedded JavaScript Templates) in Visual Studio Code and encountering a couple of issues that I need help with.

Environment:

  • ubuntu Studio
  • Visual Studio Code
  • Node.js (v21.5.0)
  • Express.js
  • EJS

Problem:

  • Syntax Highlighting: The EJS syntax, specifically <%= %> tags, is not being recognized by Visual Studio Code. The tags are highlighted in red as if there’s a syntax error.

  • Rendering Issue: When attempting to view my EJS templates in the browser, nothing is displayed. It seems like the server isn’t properly rendering the EJS templates.

Questions:

  • Are there specific settings or configurations within Visual Studio Code that I need to adjust to enable proper rendering and display of EJS templates in the browser?
  • Could there be any some misconfigurations in my server setup that might prevent EJS templates from rendering correctly?

Any insights, advice, or resources you could provide would be greatly appreciated. Thank you in advance for your help!

  • I’ve checked my server setup to ensure it’s configured to use EJS as the view engine, with app.set(‘view engine’, ‘ejs’);.
  • I’ve attempted to look for EJS extensions in Visual Studio Code’s marketplace but am unsure which one would best resolve the syntax highlighting issue.

electron Render process gone: { reason: ‘crashed’, exitCode: 133 }

electron version: v15.4.1
operating system: Kylin Linux
arch: arm

The software created using Electron crashed after running on a Linux system for 5 days, with error message: { reason: ‘crashed’, exitCode: 133 }

Rxjs was used in the project, and it has caused crashes before. This time, I made some changes to its listening events, but the problem still exists

Fetch not returning data

Javascript:

fetch("https://localhost/data.php", {
  method: "POST",
  body: JSON.stringify({
    data1: data1,
    data2: data2
  })
})
.then(res => res.json())
.then(json => function (json) {
  console.log("Successful fetch.");
  console.log(json);
})
.catch((error) => function (error) {
  console.log("Failed to fetch. " + error);
});

data.php:

<?php
echo '{
    "reply": true
}';
?>

I am trying to use a post request with fetch, but I cannot get a reply back from my PHP file, but I can access it from my browser.

Appscript google docs error script function not found: createArticle

The actual function is create article, but the execution log says createAricle()???
Here’s the code:

function createArticle() {
  var num` = 0;`
  var body = DocumentApp.getActiveDocument().getBody();
  var article = body.getText().match(/TestTheTool|Article#|Article #|Article #/gim);
  
  if (article !== null) {
    for (var t of article) {
      num += 1;
    }
    
    var par1 = body.appendParagraph("Story #" + num + " ) None");
    var par2 = body.appendParagraph('By Pusheen');
    
    par1.setHeading(DocumentApp.ParagraphHeading.HEADING1);
    par1.setAlignment(DocumentApp.HorizontalAlignment.CENTER);
    par2.setAlignment(DocumentApp.HorizontalAlignment.CENTER);
  }
}

I even asked AI, and it didn’t work. This function is supposed to guess which “article” number it is, but instead, it just shows some random error for no reason! Please try to help me. I can’t seem to get the hang of this. I’m still a beginner appscripter.

setting up a database

hi everyone i really need help i have a project that has to be done by 2 tomorrow I’m running on 5 hours sleep and have been up since 5:30am (its currently 2:20am) and I really don’t understand how to set up a table booking system for my project I know I need a database but I don’t know how to please help

Flask: Template file cannot fetch from locally stored .json file in another directory

I’m trying to create a chatroom application using Flask and update the chat via AJAX calls. I’m storing all of my chat messages in a JSON file in the root directory (‘root/chat_data.json’) that looks like this:

{
    "id": 0,
    "room": "user1room",
    "owner": "user1",
    "messages":
    [
        {
            "sender": "admin",
            "text": "this should pop up first in user1room!",
            "date": "[2024-01-01 12:00:01]"
        },
        {
            "sender": "admin",
            "text": "this should pop up second in user1room!",
            "date": "[2024-01-01 12:30:01]"
        }
    ]
}

I’m able to retrieve and display the list of pre-existing chats for a given chatroom in Flask just fine, but I’m having trouble actually posting messages by writing to the .JSON file. My current implementation in root/templates/chat.html uses this form

<form action="javascript:sendMessage()" method="post">
    <dl>
        <dt>Message
        <dd><input type="text" id="msgContent" name="newMessage">   
        <dd><input type="submit" id="sendMsg" value="Send Message">
    </dl>
</form>

To call this function in a script tag that will eventually append the input to the JSON file

<script>
    async function sendMessage()
    {
        const response = await fetch('../chat_data.json', {
        dataType: 'json',
        headers: {
            'Accept': 'Application/json',
            "Content-Type" : "Application/json",
        }}).then(response => response.json())
        .then(function(chat_data) {
            console.log(chat_data);
        });
    };
</script>

As you can see, I’m just trying to receive and print out the chat data as of right now, but I keep getting a 404 error when I try fetching ‘../chat_data.json’. I’ve also tried ‘./chat_data.json’, ‘/chat_data.json’, and any other permutations of relative file path access. Where is chat_data.json stored when I run my application and how can I properly access it?

Additionally, I’m also getting another error that states “

Uncaught (in promise) SyntaxError: Unexpected token ‘<‘, “<!doctype “… is not valid JSON”.

I know this means that fetch is returning HTML, but how can I get it to properly return JSON once I’m able to access chat_data.json?

As I said, chat_data.json is in the root directory and the html file (chat.html) is at templates/chat.html. Thanks!

How are reference to objects handled in javascript when returning object and modifying them in their original functions

I am trying to create a function that returns an object and a function that reset this object to its initial state. Something like:

const create = () => ({
    a: "something"
});

const setup = () => {
    let obj = create();

    const reset = () => {
        obj = create();
    }

    return {
        obj,
        reset
    }
}

const { reset, obj: myObj } = setup();

myObj.b = 2;
reset();
console.log("expected to be undefined", myObj.b);

But when I call the function and uses the reset function, it doesn’t reset the object. myObj.2 still contains 2. I expected the reference to myObj to stay the same, so when we call reset obj becomes a new object and myObj’s reference points to that new object.

After some fiddling around I realized that my function works if I do this instead:

const create = () => ({
    a: "something"
});

const setupWithGet = () => {
    let obj = create();

    const getObj = () => obj;

    const reset = () => {
        obj = create();
    }

    return {
        getObj,
        reset
    }
}

const { reset, getObj } = setupWithGet();

getObj().b = 2;
reset();
console.log("expected to be undefined", getObj().b);

Why do I need to use a new function here?

Como mudar o src de uma imagem por responsividade [closed]

Estou tentando fazer uma troca de imagens quando a tela do navegador tiver abaixo de um mínimo de
pixels

tenho duas imagens e preciso que elas alternem se a tela tiver menos de 600 pixels de comprimento

eu tentei usar js para mudar mas não deu certo

a tag em questão está assim

<img class="logo" id="logo" src="../img/logoCadjoV.png">

e o script está assim

<script>
    if (window.matchMedia('(max-width: 600px)').matches) {
        var logoImg = document.getElementById('logo');
        if (logoImg) {
            logoImg.src = '../img/logoCadjoH.png'; 
        }
    }
</script>

não sei dizer o que está errado, ou se existe um caminho mais fácil

usage of multinomial assign javascript?

It is possible to assign multinomial variable in javascript like

let a = 10;
let b = a = 2; // like this
console.log(`a - ${a}, b - ${b}`); // prints "a - 2, b -2"

However, I could not find which case this expression is useful.
Is there any good reference of this usage?
(If this expression does not have particular strengths, should I block this in lint?)

Typescript error: “./src/models/MenuModel”).SortOrder’ is not assignable to parameter of type ‘number’.ts(2345) (property) MenuModel.order: SortOrder

error on line:

98
/src/models/MenuModel").SortOrder' is not assignable to parameter of type 'number'.ts(2345)
this: this
120
Type 'number | SortState[]' is not assignable to type 'SortState[]'.
  Type 'number' is not assignable to type 'SortState[]'.ts(2322)
(property) MenuModel.solution: SortState[]

Tried adding a binary search algorithm to my sortingAlgorithm class for visualization but getting error messages.

res.render not rendering all the data

/lego/sets renders all the data successfully but the /lego/sets/?theme=technic does not renders it just creates a single empty row of a table without any data
server.js

app.get("/lego/sets", (req, res) => {
  if(req.query.theme){
    legoData
    .getSetsByTheme(req.query.theme)
    .then((data) => {
      if (data.length > 0) {
        res.render("sets", {sets:data});
        console.log(data);
    }
      //res.send(data);
    })
    .catch((err) => {
      res.status(404).render("404");//sendFile(path.join(__dirname, "/views/404.html"));


    });
  }
  else{
    legoData
    .getAllSets()
    .then((data) => {
     res.render("sets", {sets:data});
    })
    .catch((err) => {
      console.log('err')
      res.status(404).render("404");//sendFile(path.join(__dirname, "/views/404.html"));

    });
     
  }
  
});

sets.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=
    , initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="/css/main.css">
</head>
<body>
  <%- include('partials/navbar', {page: '/lego/sets'}) %>

    <div class="hero min-h-24 p-6 bg-base-200 md:container md:mx-auto">
        
          <div class="max-w-md">
            <h1 class="text-5xl font-bold">Collection</h1>
            <!-- <p class="py-6 text-5xl ">Error 404 you messed up</p> -->
          </div>
        
    </div>
<table class="flex justify-center">
       
        <tbody>
    
            <% sets.forEach((set)=>{ %>
                <tr>
                  
                        <td class="w-24 rounded">
                            <img class="w-24 p-2" src="<%= set.img_url %>">
                        </td>
                        
                        <td ><%= set.name %> </td>
                        <td ><a href="/lego/sets?theme=<%= set.theme %>" class="btn"><%= set.theme %></td>
                        <td ><%= set.year %></td>
                        <td class="pl-6 pr-6"><%= set.num_parts %></td>
                        
                        <td><a href="/lego/sets/<%= set.set_num %>" class="btn">Details</a></td>
                   
                </tr>
                <% }) %>
        </tbody>
    </table>
  
</body>
</html>

all the routes are configured properly i also tried console logging from both sets.ejs and server.js and it does console logs the correct data

all the routes are configured properly i also tried console logging from both sets.ejs and server.js and it does console logs the correct data

Generics and arrays: why do I end up with `Generic` instead of `Generic[]`?

I have a simple function that can accept a single object of type T or an array of objects of type T[]. It will then do its thing and return a result matching the type passed in (i.e. if an array is passed an array of results are returned, and if a single item is passed, a single result is returned).

The transpiled JS functions exactly as expected, but the type system keeps insisting on nesting the array inside the generic instead and I’m not sure why or how to ensure it resolves to what I want.

Example Function

type OneOrMany<T> = T | T[]
type Item = Record<string, any>
type CapitalizedProps<T extends Item> = {
  [K in keyof T as Capitalize<K & string>]: T[K]
}

function toCapitalizedProps<T extends Item>(item: T): CapitalizedProps<T>
function toCapitalizedProps<T extends Item>(items: T[]): CapitalizedProps<T>[]
function toCapitalizedProps<T extends Item>(
  itemOrItems: OneOrMany<T>,
): OneOrMany<CapitalizedProps<T>> {
  if (Array.isArray(itemOrItems)) {
    return itemOrItems.map((item) =>
      toCapitalizedProps(item),
    ) as CapitalizedProps<T>[]
  }

  const result = { ...itemOrItems }

  for (const key in result) {
    result[(key[0].toUpperCase() + key.slice(1)) as keyof T] = result[key]
    delete result[key]
  }

  return result as unknown as CapitalizedProps<T>
}